@matheuskrumenauer/tanya 0.17.0 → 0.17.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{chunk-5PSV2Y3X.js → chunk-3NV2QP7J.js} +576 -249
- package/dist/chunk-3NV2QP7J.js.map +1 -0
- package/dist/cli.js +91 -5
- package/dist/cli.js.map +1 -1
- package/dist/{runInkChat-AZFI7553.js → runInkChat-SVBEQCQ4.js} +76 -9
- package/dist/runInkChat-SVBEQCQ4.js.map +1 -0
- package/package.json +2 -1
- package/dist/chunk-5PSV2Y3X.js.map +0 -1
- package/dist/runInkChat-AZFI7553.js.map +0 -1
package/dist/cli.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/cli.ts","../src/config/env.ts","../src/context/artifacts.ts","../src/events/jsonl.ts","../src/agent/reasoning.ts","../src/providers/schemaFlatten.ts","../src/providers/retry.ts","../src/providers/messageNormalize.ts","../src/providers/openAiCompatible.ts","../src/providers/factory.ts","../src/agent/dispatch.ts","../src/agent/postCheck.ts","../src/agent/planner.ts","../src/agent/reviewer.ts","../src/agent/phaseBudget.ts","../src/ui/liveStatus.ts","../src/ui/humanSink.ts","../src/tools/adRenderTools.ts","../src/golden/profiles.ts","../src/golden/run.ts","../src/golden/suite.ts","../src/init/projectInit.ts","../src/context/autoContext.ts","../src/safety/permissions/migrate.ts","../src/mcp/server.ts","../src/eval/suites/eco30.ts","../src/eval/suites/mvp.ts","../src/eval/suites/sweBenchLite.ts","../src/eval/suites/tanya-native.ts","../src/eval/suites/verifierSelfTest.ts","../src/eval/suites/integrations.ts","../src/eval/schemas/EvalSuite.ts","../src/eval/suites/registry.ts","../src/eval/runner.ts","../src/eval/mvpVerifier.ts","../src/eval/verifierExtensions.ts","../src/eval/report.ts","../src/eval/compare.ts"],"sourcesContent":["import { existsSync, readFileSync } from \"node:fs\";\nimport { join, resolve } from \"node:path\";\nimport { createInterface } from \"node:readline\";\nimport { Command, Option } from \"commander\";\nimport { loadConfig } from \"./config/env\";\nimport { envValue } from \"./config/envCompat\";\nimport { loadRunContextFile, type TanyaRunContext } from \"./context/runContext\";\nimport { materializeCliArtifacts } from \"./context/artifacts\";\nimport { createJsonlSink } from \"./events/jsonl\";\nimport { createProvider, createProviderForRoute } from \"./providers/factory\";\nimport type { EventSink } from \"./events/types\";\nimport { runAgent, type RunAgentOptions, type RunAgentResult, type TanyaFinalManifest } from \"./agent/runner\";\nimport { parseVerifyFailureJSONL, runPlanAndDispatch, type DispatchMode, type VerifyFailure } from \"./agent/dispatch\";\nimport { detectPostRunBlockers } from \"./agent/postCheck\";\nimport { buildExecutionPlan } from \"./agent/planner\";\nimport { reviewChanges } from \"./agent/reviewer\";\nimport { buildSystemPrompt, loadPromptSkillPacks } from \"./agent/systemPrompt\";\nimport { startInteractiveChat } from \"./agent/chat\";\nimport { phaseAwareMaxTurns } from \"./agent/phaseBudget\";\nimport { createHumanSink } from \"./ui/humanSink\";\nimport { generateVideoAsset, videoPresets } from \"./tools/videoTools\";\nimport { renderFullAd } from \"./tools/adRenderTools\";\nimport { runGoldenSuiteCommand } from \"./golden/suite\";\nimport { initTanyaProject } from \"./init/projectInit\";\nimport { buildExportMap } from \"./context/loader\";\nimport { buildRepoMap, readRepoMap, repoMapDiagnostics } from \"./context/repoMap\";\nimport { OpenAiCompatibleProvider } from \"./providers/openAiCompatible\";\nimport { buildAutoRunContext } from \"./context/autoContext\";\nimport { buildHistoryBlock, readRecentTaskHistory } from \"./memory/taskHistory\";\nimport { formatSkillPackSummary } from \"./skills\";\nimport { estimateRunCost, formatRunLogLine, readRunLogs } from \"./memory/runLogs\";\nimport { suggestPermissionsFromRuns } from \"./safety/permissions/migrate\";\nimport { serveTanyaMcpServer } from \"./mcp/server\";\nimport { loadRouteTable } from \"./router\";\nimport { dryRunEvalSuite, loadEvalSuite } from \"./eval/suites\";\nimport { parseTaskFilter, readEvalResult, runEvalSuite, writeEvalResult } from \"./eval/runner\";\nimport { formatEvalReport } from \"./eval/report\";\nimport { compareEvalResults, formatEvalComparison } from \"./eval/compare\";\nimport { runSessionsCommand } from \"./cli/sessionsCommand\";\n\ninterface ParsedArgs {\n command: string;\n positional: string[];\n flags: Map<string, string | string[] | boolean>;\n}\n\ntype CliOptionKind = \"array\" | \"boolean\" | \"negated\" | \"string\";\n\ntype CliOptionDefinition = {\n flags: string;\n key: string;\n kind: CliOptionKind;\n property: string;\n aliases?: string[];\n};\n\nconst knownCommands = new Set([\"chat\", \"ask\", \"run\", \"review\", \"init\", \"video\", \"golden\", \"benchmark\", \"eval\", \"providers\", \"permissions\", \"mcp\", \"doctor\", \"debug-prompt\", \"runs\", \"patterns\", \"sessions\", \"help\"]);\n\nconst cliOptionDefinitions: CliOptionDefinition[] = [\n { flags: \"--artifact <path>\", key: \"artifact\", kind: \"array\", property: \"artifact\" },\n { flags: \"--artifact-output-root <path>\", key: \"artifact-output-root\", kind: \"string\", property: \"artifactOutputRoot\" },\n { flags: \"--artifacts-root <path>\", key: \"artifacts-root\", kind: \"string\", property: \"artifactsRoot\" },\n { flags: \"--auto-fix-verify\", key: \"auto-fix-verify\", kind: \"boolean\", property: \"autoFixVerify\" },\n { flags: \"--auto-fix-warns\", key: \"auto-fix-warns\", kind: \"boolean\", property: \"autoFixWarns\" },\n { flags: \"--badge <text>\", key: \"badge\", kind: \"string\", property: \"badge\" },\n { flags: \"--basename <name>\", key: \"basename\", kind: \"string\", property: \"basename\" },\n { flags: \"--context-file <path>\", key: \"context-file\", kind: \"string\", property: \"contextFile\" },\n { flags: \"--context-path <path>\", key: \"context-path\", kind: \"array\", property: \"contextPath\" },\n { flags: \"--continue\", key: \"continue\", kind: \"boolean\", property: \"continue\" },\n { flags: \"--cwd <path>\", key: \"cwd\", kind: \"string\", property: \"cwd\" },\n { flags: \"--duration <seconds>\", key: \"duration\", kind: \"string\", property: \"duration\" },\n { flags: \"--dispatch-mode <mode>\", key: \"dispatch-mode\", kind: \"string\", property: \"dispatchMode\" },\n { flags: \"--ffmpeg-path <path>\", key: \"ffmpeg-path\", kind: \"string\", property: \"ffmpegPath\", aliases: [\"ffmpegPath\"] },\n { flags: \"--format <format>\", key: \"format\", kind: \"array\", property: \"format\" },\n { flags: \"--fps <number>\", key: \"fps\", kind: \"string\", property: \"fps\" },\n { flags: \"--global\", key: \"global\", kind: \"boolean\", property: \"global\" },\n { flags: \"--height <number>\", key: \"height\", kind: \"string\", property: \"height\" },\n { flags: \"--input <path>\", key: \"input\", kind: \"string\", property: \"input\" },\n { flags: \"--json\", key: \"json\", kind: \"boolean\", property: \"json\" },\n { flags: \"--keep-context\", key: \"keep-context\", kind: \"boolean\", property: \"keepContext\" },\n { flags: \"--line <text>\", key: \"line\", kind: \"array\", property: \"line\" },\n { flags: \"--limit <count>\", key: \"limit\", kind: \"string\", property: \"limit\" },\n { flags: \"--max-subtasks <count>\", key: \"max-subtasks\", kind: \"string\", property: \"maxSubtasks\" },\n { flags: \"--max-fix-iterations <count>\", key: \"max-fix-iterations\", kind: \"string\", property: \"maxFixIterations\" },\n { flags: \"--mode <mode>\", key: \"mode\", kind: \"string\", property: \"mode\" },\n { flags: \"--model <model>\", key: \"model\", kind: \"string\", property: \"model\" },\n { flags: \"--max-turns <count>\", key: \"max-turns\", kind: \"string\", property: \"maxTurns\" },\n { flags: \"--no-auto-brief\", key: \"no-auto-brief\", kind: \"negated\", property: \"autoBrief\" },\n { flags: \"--no-obsidian-context\", key: \"no-obsidian-context\", kind: \"negated\", property: \"obsidianContext\" },\n { flags: \"--no-post-check\", key: \"no-post-check\", kind: \"negated\", property: \"postCheck\" },\n { flags: \"--no-tui\", key: \"no-tui\", kind: \"negated\", property: \"tui\" },\n { flags: \"--no-retry-stash\", key: \"no-retry-stash\", kind: \"negated\", property: \"retryStash\" },\n { flags: \"--older-than <duration>\", key: \"older-than\", kind: \"string\", property: \"olderThan\" },\n { flags: \"--output-dir <path>\", key: \"output-dir\", kind: \"string\", property: \"outputDir\", aliases: [\"outputDir\"] },\n { flags: \"--plan\", key: \"plan\", kind: \"boolean\", property: \"plan\" },\n { flags: \"--plan-and-dispatch\", key: \"plan-and-dispatch\", kind: \"boolean\", property: \"planAndDispatch\" },\n { flags: \"--profile <id>\", key: \"profile\", kind: \"string\", property: \"profile\" },\n { flags: \"--provider <name>\", key: \"provider\", kind: \"string\", property: \"provider\" },\n { flags: \"--prompt-file <path>\", key: \"prompt-file\", kind: \"string\", property: \"promptFile\" },\n { flags: \"--repair-attempts <count>\", key: \"repair-attempts\", kind: \"string\", property: \"repairAttempts\" },\n { flags: \"--require-verification <command>\", key: \"require-verification\", kind: \"array\", property: \"requireVerification\" },\n { flags: \"--resume <run_id>\", key: \"resume\", kind: \"string\", property: \"resume\" },\n { flags: \"--retries <count>\", key: \"retries\", kind: \"string\", property: \"retries\" },\n { flags: \"--review\", key: \"review\", kind: \"boolean\", property: \"review\" },\n { flags: \"--section <name>\", key: \"section\", kind: \"array\", property: \"section\" },\n { flags: \"--secondary-tab <name>\", key: \"secondary-tab\", kind: \"string\", property: \"secondaryTab\", aliases: [\"secondaryTab\"] },\n { flags: \"--spec-generation\", key: \"spec-generation\", kind: \"boolean\", property: \"specGeneration\" },\n { flags: \"--tab <name>\", key: \"tab\", kind: \"string\", property: \"tab\" },\n { flags: \"-t, --tdd\", key: \"tdd\", kind: \"boolean\", property: \"tdd\" },\n { flags: \"--test-cmd <command>\", key: \"test-cmd\", kind: \"string\", property: \"testCmd\" },\n { flags: \"--title <text>\", key: \"title\", kind: \"string\", property: \"title\" },\n { flags: \"--suite <name>\", key: \"suite\", kind: \"string\", property: \"suite\" },\n { flags: \"--task <id>\", key: \"task\", kind: \"string\", property: \"task\" },\n { flags: \"--parallel <n>\", key: \"parallel\", kind: \"string\", property: \"parallel\" },\n { flags: \"--out <path>\", key: \"out\", kind: \"string\", property: \"out\" },\n { flags: \"--dry-run\", key: \"dry-run\", kind: \"boolean\", property: \"dryRun\" },\n { flags: \"--cost-regression-threshold <ratio>\", key: \"cost-regression-threshold\", kind: \"string\", property: \"costRegressionThreshold\" },\n { flags: \"--verbose-verifier\", key: \"verbose-verifier\", kind: \"boolean\", property: \"verboseVerifier\" },\n { flags: \"--verify <command>\", key: \"verify\", kind: \"array\", property: \"verify\" },\n { flags: \"--width <number>\", key: \"width\", kind: \"string\", property: \"width\" },\n { flags: \"--all\", key: \"all\", kind: \"boolean\", property: \"all\" },\n];\n\nfunction collectOptionValue(value: string, previous: string[] | undefined): string[] {\n return [...(previous ?? []), value];\n}\n\nfunction addCliOptions(command: Command): Command {\n for (const definition of cliOptionDefinitions) {\n const option = new Option(definition.flags);\n if (definition.kind === \"array\") {\n option.argParser(collectOptionValue).default([]);\n }\n command.addOption(option);\n }\n return command;\n}\n\nfunction normalizeCommanderArgv(argv: string[]): string[] {\n if (argv.length === 0) return [\"chat\"];\n if (argv[0] === \"--help\" || argv[0] === \"-h\") return argv;\n if (argv[0] && knownCommands.has(argv[0])) return normalizeOptionAliases(argv);\n const normalized = normalizeOptionAliases(argv);\n if (normalized.some((arg) => arg === \"--plan-and-dispatch\" || arg.startsWith(\"--plan-and-dispatch=\") || arg === \"--auto-fix-verify\" || arg.startsWith(\"--auto-fix-verify=\"))) {\n return [\"run\", ...normalized];\n }\n return [\"chat\", ...normalized];\n}\n\nfunction normalizeOptionAliases(argv: string[]): string[] {\n return argv.map((arg) => {\n if (arg === \"--ffmpegPath\") return \"--ffmpeg-path\";\n if (arg.startsWith(\"--ffmpegPath=\")) return `--ffmpeg-path=${arg.slice(\"--ffmpegPath=\".length)}`;\n if (arg === \"--outputDir\") return \"--output-dir\";\n if (arg.startsWith(\"--outputDir=\")) return `--output-dir=${arg.slice(\"--outputDir=\".length)}`;\n if (arg === \"--secondaryTab\") return \"--secondary-tab\";\n if (arg.startsWith(\"--secondaryTab=\")) return `--secondary-tab=${arg.slice(\"--secondaryTab=\".length)}`;\n if (arg === \"-pd\") return \"--plan-and-dispatch\";\n if (arg === \"-afv\") return \"--auto-fix-verify\";\n return arg;\n });\n}\n\nfunction optionSource(command: Command, property: string): string | undefined {\n return command.getOptionValueSource(property);\n}\n\nfunction parsedFromCommand(commandName: string, positional: string[], command: Command): ParsedArgs {\n const opts = command.opts<Record<string, unknown>>();\n const flags = new Map<string, string | string[] | boolean>();\n for (const definition of cliOptionDefinitions) {\n const source = optionSource(command, definition.property);\n const value = opts[definition.property];\n if (definition.kind === \"array\") {\n if (Array.isArray(value) && value.length > 0) {\n for (const item of value) appendFlagValue(flags, definition.key, String(item));\n for (const alias of definition.aliases ?? []) {\n for (const item of value) appendFlagValue(flags, alias, String(item));\n }\n }\n continue;\n }\n if (definition.kind === \"negated\") {\n if (source === \"cli\" && value === false) flags.set(definition.key, true);\n continue;\n }\n if (definition.kind === \"boolean\") {\n if (source === \"cli\" && value === true) flags.set(definition.key, true);\n continue;\n }\n if (source === \"cli\" && typeof value === \"string\") {\n flags.set(definition.key, value);\n for (const alias of definition.aliases ?? []) flags.set(alias, value);\n }\n }\n return { command: commandName, positional, flags };\n}\n\nfunction configureCliCommand(command: Command, commandName: string, onParsed: (args: ParsedArgs) => void): Command {\n addCliOptions(command)\n .argument(\"[args...]\", \"command arguments\")\n .allowExcessArguments(true)\n .action((positional: string[]) => {\n onParsed(parsedFromCommand(commandName, positional, command));\n });\n return command;\n}\n\nfunction buildCliProgram(onParsed: (args: ParsedArgs) => void): Command {\n const program = new Command();\n program\n .name(\"tanya\")\n .description(\"Tanya CLI\")\n .helpCommand(false)\n .showHelpAfterError()\n .allowExcessArguments(true);\n\n configureCliCommand(program.command(\"chat\").description(\"Start live chat\"), \"chat\", onParsed);\n configureCliCommand(program.command(\"ask\").description(\"Run one prompt without tools\"), \"ask\", onParsed);\n configureCliCommand(program.command(\"run\").description(\"Run an agent task with tools\"), \"run\", onParsed);\n configureCliCommand(program.command(\"review\").description(\"Review uncommitted changes against a task\"), \"review\", onParsed);\n configureCliCommand(program.command(\"init\").description(\"Create .tania/INSTRUCTIONS.md for this project\"), \"init\", onParsed);\n configureCliCommand(program.command(\"video\").description(\"Generate Tanya video assets\"), \"video\", onParsed);\n configureCliCommand(program.command(\"golden\").description(\"Manage local golden task memory\"), \"golden\", onParsed);\n configureCliCommand(program.command(\"benchmark\").description(\"Run executable regression benchmarks\"), \"benchmark\", onParsed);\n configureCliCommand(program.command(\"eval\").description(\"Run eval suites and reports\"), \"eval\", onParsed);\n configureCliCommand(program.command(\"providers\").description(\"Provider utilities\"), \"providers\", onParsed);\n configureCliCommand(program.command(\"mcp\").description(\"MCP server/client utilities\"), \"mcp\", onParsed);\n configureCliCommand(program.command(\"doctor\").description(\"Check local setup\"), \"doctor\", onParsed);\n configureCliCommand(program.command(\"debug-prompt\").description(\"Print system prompt without running agent\"), \"debug-prompt\", onParsed);\n configureCliCommand(program.command(\"runs\").description(\"Show recent run logs\"), \"runs\", onParsed);\n configureCliCommand(program.command(\"patterns\").description(\"Show forbidden-pattern fire metrics\"), \"patterns\", onParsed);\n configureCliCommand(program.command(\"sessions\").description(\"Manage chat sessions\"), \"sessions\", onParsed);\n return program;\n}\n\nfunction parseArgs(argv: string[]): ParsedArgs {\n if (argv[0] === \"help\") return { command: \"help\", positional: argv.slice(1), flags: new Map() };\n let parsed: ParsedArgs | undefined;\n const program = buildCliProgram((args) => {\n parsed = args;\n });\n program.parse(normalizeCommanderArgv(argv), { from: \"user\" });\n return parsed ?? { command: \"chat\", positional: [], flags: new Map() };\n}\n\nfunction appendFlagValue(flags: Map<string, string | string[] | boolean>, key: string, value: string) {\n const existing = flags.get(key);\n if (typeof existing === \"string\") {\n flags.set(key, [existing, value]);\n } else if (Array.isArray(existing)) {\n existing.push(value);\n } else {\n flags.set(key, value);\n }\n}\n\nfunction flagString(args: ParsedArgs, name: string): string | undefined {\n const value = args.flags.get(name);\n return typeof value === \"string\" ? value : undefined;\n}\n\nfunction flagStrings(args: ParsedArgs, name: string): string[] {\n const value = args.flags.get(name);\n if (typeof value === \"string\") return [value];\n if (Array.isArray(value)) return value;\n return [];\n}\n\nfunction hasFlag(args: ParsedArgs, name: string): boolean {\n const value = args.flags.get(name);\n return value === true || typeof value === \"string\" || Array.isArray(value);\n}\n\nfunction flagNumber(args: ParsedArgs, name: string): number | undefined {\n const value = flagString(args, name);\n if (!value) return undefined;\n const parsed = Number(value);\n return Number.isFinite(parsed) ? parsed : undefined;\n}\n\nasync function readVerifyFailuresFromStdin(): Promise<VerifyFailure[]> {\n if (process.stdin.isTTY) return [];\n const rl = createInterface({ input: process.stdin, crlfDelay: Infinity });\n const lines: string[] = [];\n for await (const line of rl) {\n lines.push(line);\n try {\n const event = JSON.parse(line) as { type?: string };\n if (event.type === \"verify_failure_eof\") break;\n } catch {\n continue;\n }\n }\n rl.close();\n return parseVerifyFailureJSONL(lines);\n}\n\nfunction applyCliProfileFlag(args: ParsedArgs): void {\n if (args.command !== \"run\" && args.command !== \"chat\") return;\n const profile = flagString(args, \"profile\");\n if (!profile) return;\n process.env.TANYA_PROFILE = profile;\n}\n\nfunction applyCliProviderFlag(args: ParsedArgs): void {\n const provider = flagString(args, \"provider\");\n if (!provider) return;\n process.env.TANYA_PROVIDER = provider;\n}\n\nfunction applyCliModeFlag(args: ParsedArgs): void {\n if (args.command !== \"run\" && args.command !== \"chat\") return;\n const mode = flagString(args, \"mode\");\n if (!mode) return;\n if (![\"ask\", \"bypass\", \"plan\", \"default\"].includes(mode)) {\n throw new Error(`Invalid permission mode: ${mode}. Expected ask, bypass, plan, or default.`);\n }\n process.env.TANYA_MODE = mode;\n}\n\nfunction buildRetryContext(manifest: TanyaFinalManifest, attempt: number, extraBlockers: string[] = []): string {\n const lines = [\n `RETRY CONTEXT (attempt ${attempt}): the previous run did not complete cleanly.`,\n \"Do not repeat the same approach that failed.\",\n ];\n const allBlockers = [...manifest.blockers, ...extraBlockers];\n if (allBlockers.length > 0) {\n lines.push(\"\", \"Previous run blockers:\");\n for (const blocker of allBlockers) lines.push(`- ${blocker}`);\n }\n if (manifest.changedFiles.length > 0) {\n lines.push(\"\", \"Files already changed in previous attempt (verify their current state before editing):\");\n for (const file of manifest.changedFiles) lines.push(`- ${file}`);\n }\n if (manifest.verification.length > 0) {\n lines.push(\"\", \"Verification results from previous attempt:\");\n for (const verification of manifest.verification) lines.push(`- ${verification}`);\n }\n lines.push(\"\", \"Fix the blockers above and complete the task.\");\n return lines.join(\"\\n\");\n}\n\nfunction usage(): string {\n return `Tanya CLI\n\nUsage:\n tanya Start live chat\n tanya chat [--profile reasoner] Start live chat\n tanya --continue Continue the latest chat session for this project\n tanya --resume <id> Resume a specific chat session\n tanya ask \"prompt\" Run one prompt without tools\n tanya init [--cwd path] Create .tania/INSTRUCTIONS.md for this project\n tanya run [--cwd path] [--profile reasoner] \"task\" Run an agent task with tools\n tanya run \"task\" Auto-detects ./artifacts if present\n tanya run --context-file /tmp/context.json --prompt-file /tmp/prompt.txt\n tanya run --artifacts-root <path> \"task\" Use a custom artifacts directory\n tanya run --artifacts-root /path/to/artifacts --artifact ios/FastlaneSetup.md \"task\"\n tanya run --context-path /path/to/brand/safety.md --artifact-output-root /path/to/artifacts \"task\"\n tanya run --mode spec-generation \"task\" Non-coding spec generation; no edits, verification, or final coding report\n tanya run --no-auto-brief \"task\" Skip automatic local task briefing\n tanya run --no-obsidian-context \"task\" Skip automatic Obsidian context retrieval\n tanya run --no-post-check \"task\" Skip independent TypeScript/test verification\n tanya run --repair-attempts 2 --context-file /tmp/context.json --prompt-file /tmp/prompt.txt\n tanya run --keep-context --artifacts-root /path/to/artifacts --artifact ios/FastlaneSetup.md \"task\"\n tanya run --verify \"npm run typecheck\" --verify \"npm run build\" \"task\"\n tanya run --verbose-verifier \"task\" Include advisory reasoning excerpts in verifier reports\n tanya run --retries 2 \"task\" Retry up to 2 times if the run has blockers\n tanya run --plan \"task\" Pre-plan with deepseek-reasoner before executing\n tanya run --plan-and-dispatch \"task\" Split a task into sequential sub-tasks\n tanya run --plan-and-dispatch --tdd \"task\" Split into sub-tasks with RED/GREEN TDD\n tanya run --plan-and-dispatch --auto-fix-verify \"task\" Read verify_failure JSONL batches on stdin and re-prompt fixes\n tanya --plan-and-dispatch \"task\" Shorthand for plan-and-dispatch run mode\n tanya run --resume <run_id> Resume a stopped dispatch run\n tanya run --plan --retries 2 \"task\"\n tanya run --review \"task\" Run task then auto-review the diff\n tanya run --plan --retries 2 --review \"task\" Full autonomous mode\n tanya run --json --prompt-file /tmp/prompt.txt\n tanya debug-prompt \"task\" Print system prompt without running agent\n tanya debug-prompt --cwd <path> \"task\" Print system prompt for a specific project\n tanya debug-prompt --section artifacts \"task\" Print only the artifact section\n tanya debug-prompt --section exports \"task\" Print only the export map section\n tanya runs [--cwd <path>] Show last 10 run logs with cost and status\n tanya sessions list [--all] [--cwd path] [--global]\n tanya sessions show <id>\n tanya sessions rm <id>\n tanya sessions prune --older-than 30d\n tanya review \"task description\" Review uncommitted changes against the task\n tanya review --cwd <path> \"task\" Review changes in a specific project\n tanya video presets\n tanya video one-terminal-simctl --output-dir assets/video\n tanya video render-ad --input spec.json --output-dir assets/video-ads --format mp4 --format poster\n tanya golden summary Summarize local golden task memory\n tanya golden profiles List built-in golden task profiles\n tanya golden run Run executable golden task fixtures\n tanya golden validate Fail if latest golden task signatures are failing\n tanya benchmark profiles List benchmark profiles\n tanya benchmark run --all Run executable regression benchmarks\n tanya benchmark validate Validate recent benchmark signatures\n tanya eval --suite tanya-native --dry-run\n tanya eval --suite eco-30 --provider deepseek --model deepseek-chat --out result.json\n tanya providers test --provider deepseek Test provider configuration (live only with TANYA_RUN_LIVE_PROVIDER_TESTS=1)\n tanya mcp serve Start Tanya's MCP server over stdio\n tanya doctor Check local setup\n tanya patterns Show forbidden-pattern fire metrics for this workspace\n\nInstall locally during development:\n npm install\n npm run link:local\n`;\n}\n\nfunction readPrompt(args: ParsedArgs): string {\n const promptFile = flagString(args, \"prompt-file\");\n if (promptFile) return readFileSync(resolve(promptFile), \"utf8\");\n return args.positional.join(\" \").trim();\n}\n\nasync function buildRunContextForCli(\n args: ParsedArgs,\n cwd: string,\n prompt: string,\n obsidianVault?: string,\n): Promise<TanyaRunContext | undefined> {\n const contextFile = flagString(args, \"context-file\");\n const baseRunContext = contextFile ? loadRunContextFile(contextFile) : undefined;\n const mode = flagString(args, \"mode\")?.trim();\n const specGenerationMode = mode === \"spec-generation\" || mode === \"spec\" || hasFlag(args, \"spec-generation\");\n if (specGenerationMode) {\n const baseSpecContext: TanyaRunContext = { ...(baseRunContext ?? {}) };\n delete baseSpecContext.expected_report;\n delete baseSpecContext.verification;\n const runContext: TanyaRunContext = {\n ...baseSpecContext,\n task: {\n ...(baseRunContext?.task ?? {}),\n kind: \"spec-generation\",\n title: baseRunContext?.task?.title ?? prompt.split(/\\r?\\n/).find((line) => line.trim().length > 0)?.trim().slice(0, 120) ?? \"Spec generation\",\n },\n instructions: [\n ...(baseRunContext?.instructions ?? []),\n \"You are running in spec-generation mode.\",\n \"Generate the requested specification only.\",\n \"Do not edit files, run shell commands, run verification, inspect git status, or create artifacts.\",\n \"Do not append coding-agent report sections such as Verification, Final Report, Modified files, Artifact reused, Artifact created, or Blockers.\",\n ],\n metadata: {\n ...(baseRunContext?.metadata ?? {}),\n mode: \"spec-generation\",\n autoContext: false,\n },\n };\n return buildAutoRunContext({\n cwd,\n prompt,\n runContext,\n obsidianVault,\n enableBrief: false,\n enableObsidian: false,\n keepContext: false,\n });\n }\n const explicitArtifactsRoot = flagString(args, \"artifacts-root\");\n const localArtifactsRoot = resolve(cwd, \"artifacts\");\n const artifactsRoot = explicitArtifactsRoot ?? (existsSync(localArtifactsRoot) ? localArtifactsRoot : undefined);\n let runContext = materializeCliArtifacts({\n cwd,\n root: artifactsRoot,\n artifacts: flagStrings(args, \"artifact\"),\n contextPaths: flagStrings(args, \"context-path\"),\n artifactOutputRoot: flagString(args, \"artifact-output-root\"),\n keepContext: hasFlag(args, \"keep-context\"),\n baseContext: baseRunContext,\n });\n if (!explicitArtifactsRoot && artifactsRoot) {\n const autoArtifactInstructions = [\n \"This workspace contains an artifacts/ directory with reusable patterns.\",\n \"The artifact index and rules have been injected into your system prompt.\",\n \"Before implementing anything, check the artifact index and read relevant artifacts.\",\n ];\n runContext = {\n ...(runContext ?? {}),\n instructions: [...(runContext?.instructions ?? []), ...autoArtifactInstructions],\n };\n }\n const extraVerify = flagStrings(args, \"verify\");\n if (extraVerify.length > 0) {\n const existing = runContext?.verification?.commands ?? [];\n const merged = [...new Set([...existing, ...extraVerify])];\n runContext = { ...(runContext ?? {}), task: { ...(runContext?.task ?? {}), kind: \"coding\" }, verification: { commands: merged } };\n }\n const requireVerify = flagStrings(args, \"require-verification\");\n if (requireVerify.length > 0) {\n // --require-verification REPLACES the auto-brief verification list with exactly\n // these commands. Use when the caller knows the canonical verification set\n // and the auto-generated recommendations would over-require.\n runContext = {\n ...(runContext ?? {}),\n task: { ...(runContext?.task ?? {}), kind: \"coding\" },\n verification: { commands: [...new Set(requireVerify)] },\n metadata: { ...(runContext?.metadata ?? {}), verificationOverridden: true },\n };\n }\n if (hasFlag(args, \"verbose-verifier\")) {\n runContext = {\n ...(runContext ?? {}),\n metadata: { ...(runContext?.metadata ?? {}), verboseVerifier: true },\n };\n }\n return buildAutoRunContext({\n cwd,\n prompt,\n ...(runContext ? { runContext } : {}),\n obsidianVault,\n enableBrief: !hasFlag(args, \"no-auto-brief\"),\n enableObsidian: !hasFlag(args, \"no-obsidian-context\"),\n keepContext: hasFlag(args, \"keep-context\"),\n });\n}\n\nfunction selectPromptSections(systemPrompt: string, sections: string[]): string {\n if (sections.length === 0) return systemPrompt;\n const sectionMap: Record<string, { starts: string[]; ends: string[] }> = {\n artifacts: {\n starts: [\"## Artifact Index\", \"## Project Artifacts\"],\n ends: [\"## Workspace Context\", \"## Project Instructions\", \"## Caller Context\"],\n },\n \"repo-map\": {\n starts: [\"## Repo Map (advisory)\"],\n ends: [\"## Artifact Index\", \"## Workspace Context\", \"## Project Instructions\", \"## Caller Context\"],\n },\n exports: {\n starts: [\"## Workspace export map\"],\n ends: [\"## Repo Map (advisory)\", \"## Artifact Index\", \"## Project Artifacts\", \"## Workspace Context\", \"## Project Instructions\", \"## Caller Context\"],\n },\n context: {\n starts: [\"## Workspace Context\"],\n ends: [\"## Project Instructions\", \"## Caller Context\"],\n },\n instructions: {\n starts: [\"## Project Instructions\"],\n ends: [\"## Caller Context\"],\n },\n };\n\n const findHeading = (heading: string, from = 0): number => {\n if (systemPrompt.startsWith(`${heading}\\n`)) return 0;\n return systemPrompt.indexOf(`\\n${heading}\\n`, from);\n };\n\n const extractSection = (starts: string[], ends: string[]): string | null => {\n const startCandidates = starts\n .map((heading) => findHeading(heading))\n .filter((index) => index >= 0);\n if (startCandidates.length === 0) return null;\n let start = Math.min(...startCandidates);\n if (systemPrompt[start] === \"\\n\") start += 1;\n\n const endCandidates = ends\n .map((heading) => findHeading(heading, start + 1))\n .filter((index) => index > start);\n const end = endCandidates.length > 0 ? Math.min(...endCandidates) : systemPrompt.length;\n return systemPrompt.slice(start, end).trim();\n };\n\n const matched: string[] = [];\n for (const section of sections) {\n const definition = sectionMap[section];\n if (!definition) {\n process.stderr.write(`[debug-prompt] Unknown section \"${section}\". Available: ${Object.keys(sectionMap).join(\", \")}\\n`);\n continue;\n }\n const match = extractSection(definition.starts, definition.ends);\n if (match) {\n matched.push(match);\n } else {\n process.stderr.write(`[debug-prompt] Section \"${section}\" not found in prompt.\\n`);\n }\n }\n return matched.join(\"\\n\\n---\\n\\n\");\n}\n\nasync function askOnce(provider: ReturnType<typeof createProvider>, prompt: string): Promise<string> {\n let text = \"\";\n for await (const delta of provider.streamChat({ messages: [{ role: \"user\", content: prompt }], tools: [] })) {\n if (delta.content) {\n process.stdout.write(delta.content);\n text += delta.content;\n }\n }\n process.stdout.write(\"\\n\");\n return text;\n}\n\nfunction buildRoutingOptions(config: ReturnType<typeof loadConfig>, cwd: string): RunAgentOptions[\"routing\"] | undefined {\n const loaded = loadRouteTable({\n cwd,\n defaults: { provider: config.provider, model: config.model },\n });\n for (const issue of loaded.issues) {\n process.stderr.write(`[tanya] Ignoring invalid route config ${issue.file} ${issue.path}: ${issue.message}\\n`);\n }\n const hasRouteFile = loaded.table.sources.some((source) => source !== \"built-in\");\n return {\n enabled: hasRouteFile,\n table: loaded.table,\n providerFactory: (target) => createProviderForRoute(config, target),\n };\n}\n\nfunction shouldUseInkChat(args: ParsedArgs, json: boolean): boolean {\n if (args.command !== \"chat\") return false;\n if (json) return false;\n if (hasFlag(args, \"no-tui\")) return false;\n if (envValue({}, \"TANYA_TUI\").trim().toLowerCase() === \"off\") return false;\n return Boolean(process.stdout.isTTY && process.stdin.isTTY);\n}\n\nasync function testProvider(args: ParsedArgs): Promise<void> {\n const requestedProvider = flagString(args, \"provider\") ?? \"configured\";\n if (envValue({}, \"TANYA_RUN_LIVE_PROVIDER_TESTS\") !== \"1\") {\n console.log(`skipped live provider test for ${requestedProvider}; set TANYA_RUN_LIVE_PROVIDER_TESTS=1 to run against the real endpoint.`);\n return;\n }\n const config = loadConfig();\n const provider = createProvider(config);\n const startedAt = Date.now();\n let text = \"\";\n for await (const delta of provider.streamChat({\n messages: [\n { role: \"system\", content: \"You are a provider conformance probe. Keep answers short.\" },\n { role: \"user\", content: \"Reply with exactly: pong\" },\n { role: \"user\", content: \"No tools are needed.\" },\n ],\n tools: [],\n maxTokens: 12,\n temperature: 0,\n })) {\n if (delta.content) text += delta.content;\n }\n console.log(`PASS adapter: ${provider.id}:${provider.model}`);\n console.log(`PASS streaming-chat: ${Date.now() - startedAt}ms ${text.trim()}`);\n console.log(\"PASS parser-surface: mock conformance covers malformed tool-call quirks in CI\");\n}\n\nasync function runEvalCommand(args: ParsedArgs): Promise<void> {\n const cwd = resolve(flagString(args, \"cwd\") ?? process.cwd());\n const action = args.positional[0];\n const format = flagStrings(args, \"format\").includes(\"markdown\") ? \"markdown\" : \"text\";\n if (action === \"report\") {\n const file = args.positional[1];\n if (!file) throw new Error(\"Usage: tanya eval report <result.json> [--format markdown]\");\n process.stdout.write(formatEvalReport(await readEvalResult(resolve(cwd, file)), format));\n return;\n }\n if (action === \"compare\") {\n const baseline = args.positional[1];\n const next = args.positional[2];\n if (!baseline || !next) throw new Error(\"Usage: tanya eval compare <baseline.json> <new.json> [--format markdown]\");\n const comparison = compareEvalResults(\n await readEvalResult(resolve(cwd, baseline)),\n await readEvalResult(resolve(cwd, next)),\n flagNumber(args, \"cost-regression-threshold\") ?? 0.20,\n );\n process.stdout.write(formatEvalComparison(comparison, format));\n if (comparison.regressions.length > 0) process.exitCode = 1;\n return;\n }\n const suiteName = flagString(args, \"suite\") ?? args.positional[0] ?? \"tanya-native\";\n const suite = loadEvalSuite(suiteName);\n const modelFlag = flagString(args, \"model\");\n const modelParts = modelFlag?.includes(\"/\") ? modelFlag.split(\"/\") : undefined;\n const providerName = modelParts?.[0] ?? flagString(args, \"provider\");\n const modelName = modelParts?.[1] ?? modelFlag;\n const config = hasFlag(args, \"dry-run\") && providerName && modelName\n ? undefined\n : loadConfig(cwd);\n const provider = providerName ?? config?.provider ?? \"deepseek\";\n const model = modelName ?? config?.model ?? \"deepseek-chat\";\n if (hasFlag(args, \"dry-run\")) {\n const dryRun = dryRunEvalSuite(suite, provider, model);\n if (hasFlag(args, \"json\")) {\n process.stdout.write(`${JSON.stringify(dryRun, null, 2)}\\n`);\n } else {\n process.stdout.write(`Eval dry-run: ${dryRun.suite}@${dryRun.suiteVersion}\\n`);\n process.stdout.write(`Tasks: ${dryRun.taskCount}\\n`);\n process.stdout.write(`Model: ${provider}/${model}\\n`);\n process.stdout.write(`Estimated cost: ${dryRun.estimatedCostUsd === null ? \"pricing unknown\" : `$${dryRun.estimatedCostUsd.toFixed(3)}`}\\n`);\n }\n return;\n }\n\n process.env.TANYA_PROVIDER = provider;\n process.env.TANYA_MODEL = model;\n const evalConfig = loadConfig(cwd);\n const taskIds = parseTaskFilter(flagString(args, \"task\"));\n const parallel = flagNumber(args, \"parallel\");\n const result = await runEvalSuite(suite, {\n cwd,\n provider,\n model,\n tanyaVersion: JSON.parse(readFileSync(resolve(\"package.json\"), \"utf8\")).version,\n ...(taskIds ? { taskIds } : {}),\n ...(parallel !== undefined ? { parallel } : {}),\n providerFactory: () => createProvider(evalConfig),\n });\n const out = flagString(args, \"out\");\n if (out) {\n await writeEvalResult(resolve(cwd, out), result);\n process.stdout.write(`Wrote eval result to ${resolve(cwd, out)}\\n`);\n } else {\n process.stdout.write(`${JSON.stringify(result, null, 2)}\\n`);\n }\n}\n\nasync function doctor(args?: ParsedArgs): Promise<void> {\n const cwd = resolve(args ? flagString(args, \"cwd\") ?? process.cwd() : process.cwd());\n const config = loadConfig(cwd);\n const checks: Array<{ name: string; status: \"ok\" | \"warn\" | \"fail\"; detail: string }> = [];\n const ok = (name: string, detail: string) => checks.push({ name, status: \"ok\", detail });\n const warn = (name: string, detail: string) => checks.push({ name, status: \"warn\", detail });\n const fail = (name: string, detail: string) => checks.push({ name, status: \"fail\", detail });\n\n // Node + runtime\n const major = Number(process.version.replace(/^v/, \"\").split(\".\")[0] ?? \"0\");\n if (major >= 20) ok(\"node\", `${process.version}`);\n else fail(\"node\", `${process.version} — tanya requires Node 20+`);\n\n // Provider config\n if (config.apiKey) ok(\"provider.apiKey\", \"present\");\n else fail(\"provider.apiKey\", \"missing — set TANYA_API_KEY or DEEPSEEK_API_KEY\");\n if (config.baseUrl) ok(\"provider.baseUrl\", config.baseUrl);\n else fail(\"provider.baseUrl\", \"missing — set TANYA_BASE_URL\");\n ok(\"provider.model\", `${config.provider}:${config.model} (profile=${config.profile})`);\n ok(\"provider.timeoutMs\", `${config.timeoutMs}ms`);\n\n // Workspace\n const cwdHasGit = existsSync(join(cwd, \".git\"));\n if (cwdHasGit) ok(\"workspace.git\", `${cwd}`);\n else warn(\"workspace.git\", `${cwd} is not a git repository — stash/retry recovery will be disabled`);\n const cwdHasArtifacts = existsSync(join(cwd, \"artifacts\"));\n if (cwdHasArtifacts) ok(\"workspace.artifacts\", `${join(cwd, \"artifacts\")} (auto-detected)`);\n else warn(\"workspace.artifacts\", \"no ./artifacts dir — pass --artifacts-root or run from a project that has one\");\n\n // Project-level forbidden patterns\n const fpPath = join(cwd, \".tania\", \"forbidden-patterns.json\");\n if (existsSync(fpPath)) {\n try {\n const raw = readFileSync(fpPath, \"utf8\");\n const parsed = JSON.parse(raw);\n const count = Array.isArray(parsed?.patterns) ? parsed.patterns.length : 0;\n ok(\"workspace.forbiddenPatterns\", `${count} project pattern(s) loaded from ${fpPath}`);\n } catch (err) {\n fail(\"workspace.forbiddenPatterns\", `${fpPath} exists but is invalid JSON: ${err instanceof Error ? err.message : String(err)}`);\n }\n } else {\n ok(\"workspace.forbiddenPatterns\", \"no project overrides (using defaults)\");\n }\n\n // Forbidden-pattern fire metrics (from accumulated runs)\n const fpMetricsPath = join(cwd, \".tania\", \"memory\", \"forbidden-patterns-metrics.json\");\n if (existsSync(fpMetricsPath)) {\n try {\n const raw = readFileSync(fpMetricsPath, \"utf8\");\n const parsed = JSON.parse(raw) as { totals?: Record<string, number>; totalScans?: number };\n const totals = parsed.totals ?? {};\n const top = Object.entries(totals).sort((a, b) => b[1] - a[1]).slice(0, 5);\n if (top.length > 0) {\n const summary = top.map(([id, n]) => `${id}=${n}`).join(\", \");\n ok(\"workspace.forbiddenPatterns.metrics\", `top fires across ${parsed.totalScans ?? 0} scans: ${summary}`);\n } else {\n ok(\"workspace.forbiddenPatterns.metrics\", `no patterns ever fired (${parsed.totalScans ?? 0} scans)`);\n }\n } catch {\n warn(\"workspace.forbiddenPatterns.metrics\", `${fpMetricsPath} exists but is unreadable`);\n }\n } else {\n ok(\"workspace.forbiddenPatterns.metrics\", \"no metrics yet (no scans recorded)\");\n }\n\n // Obsidian vault\n if (config.obsidianVault) {\n if (existsSync(config.obsidianVault)) ok(\"obsidian.vault\", config.obsidianVault);\n else warn(\"obsidian.vault\", `${config.obsidianVault} configured but path does not exist`);\n } else {\n ok(\"obsidian.vault\", \"not configured (optional)\");\n }\n\n // ffmpeg presence (informational; only required for tanya video)\n try {\n const { execFileSync } = await import(\"node:child_process\");\n execFileSync(\"ffmpeg\", [\"-version\"], { stdio: \"ignore\" });\n ok(\"ffmpeg\", \"available (tanya video commands enabled)\");\n } catch {\n warn(\"ffmpeg\", \"not found on PATH — tanya video commands will fail until installed\");\n }\n\n // Render\n console.log(`Tanya doctor — ${cwd}`);\n console.log(\"\");\n for (const check of checks) {\n const tag = check.status === \"ok\" ? \"[ok] \" : check.status === \"warn\" ? \"[warn]\" : \"[FAIL]\";\n console.log(`${tag} ${check.name.padEnd(28)} ${check.detail}`);\n }\n const failed = checks.filter((c) => c.status === \"fail\").length;\n const warned = checks.filter((c) => c.status === \"warn\").length;\n console.log(\"\");\n console.log(`Summary: ${checks.length - failed - warned} ok, ${warned} warn, ${failed} fail`);\n if (failed > 0) process.exitCode = 1;\n}\n\nasync function runVideoCommand(args: ParsedArgs): Promise<void> {\n const preset = args.positional[0] ?? \"one-terminal-simctl\";\n if (preset === \"presets\" || preset === \"list\") {\n console.log(\"Video presets:\");\n for (const item of videoPresets) {\n const aliases = item.aliases.length ? ` aliases: ${item.aliases.join(\", \")}` : \"\";\n console.log(`- ${item.name} (${item.width}x${item.height}, ${item.fps}fps, ${item.duration}s)${aliases}`);\n console.log(` ${item.description}`);\n }\n return;\n }\n if (preset === \"render-ad\") {\n const cwd = resolve(flagString(args, \"cwd\") ?? process.cwd());\n const input = flagString(args, \"input\");\n if (!input) {\n console.log(\"Usage: tanya video render-ad --input spec.json [--output-dir dir] [--basename name] [--format mp4] [--format poster]\");\n return;\n }\n const formats = flagStrings(args, \"format\");\n const renderOptions: Parameters<typeof renderFullAd>[0] = {\n input,\n formats: formats.length ? formats as Array<\"mp4\" | \"poster\"> : [\"mp4\", \"poster\"],\n };\n const outputDir = flagString(args, \"output-dir\") ?? flagString(args, \"outputDir\");\n const basename = flagString(args, \"basename\");\n const ffmpegPath = flagString(args, \"ffmpeg-path\") ?? flagString(args, \"ffmpegPath\");\n if (outputDir) renderOptions.outputDir = outputDir;\n if (basename) renderOptions.basename = basename;\n if (ffmpegPath) renderOptions.ffmpegPath = ffmpegPath;\n const result = await renderFullAd(renderOptions, cwd);\n console.log(JSON.stringify({\n mp4Path: result.mp4Path,\n posterPath: result.posterPath,\n durationMs: result.durationMs,\n frameCount: result.frameCount,\n width: result.width,\n height: result.height,\n warnings: result.warnings,\n }, null, 2));\n return;\n }\n if (preset !== \"one-terminal-simctl\" && preset !== \"terminal-simctl\") {\n console.log(\"Usage: tanya video one-terminal-simctl [--output-dir dir] [--basename name] [--width 980] [--height 1012] [--duration 3] [--fps 30] [--format webm] [--format mov] [--format poster] [--line text]\\n tanya video render-ad --input spec.json [--output-dir dir] [--format mp4] [--format poster]\");\n return;\n }\n const cwd = resolve(flagString(args, \"cwd\") ?? process.cwd());\n const formats = flagStrings(args, \"format\");\n const options: Parameters<typeof generateVideoAsset>[0] = { preset };\n const outputDir = flagString(args, \"output-dir\") ?? flagString(args, \"outputDir\");\n const basename = flagString(args, \"basename\");\n const width = flagNumber(args, \"width\");\n const height = flagNumber(args, \"height\");\n const fps = flagNumber(args, \"fps\");\n const duration = flagNumber(args, \"duration\");\n const title = flagString(args, \"title\");\n const tab = flagString(args, \"tab\");\n const secondaryTab = flagString(args, \"secondary-tab\") ?? flagString(args, \"secondaryTab\");\n const badge = flagString(args, \"badge\");\n const lines = flagStrings(args, \"line\");\n if (outputDir) options.outputDir = outputDir;\n if (basename) options.basename = basename;\n if (width !== undefined) options.width = width;\n if (height !== undefined) options.height = height;\n if (fps !== undefined) options.fps = fps;\n if (duration !== undefined) options.duration = duration;\n if (formats.length > 0) options.formats = formats as Array<\"webm\" | \"mov\" | \"poster\">;\n if (title) options.title = title;\n if (tab) options.tab = tab;\n if (secondaryTab) options.secondaryTab = secondaryTab;\n if (badge) options.badge = badge;\n if (lines.length > 0) options.lines = lines;\n const result = await generateVideoAsset(options, cwd);\n console.log(`Generated ${result.files.length} video asset file${result.files.length === 1 ? \"\" : \"s\"}:`);\n for (const file of result.files) console.log(`- ${file}`);\n}\n\nasync function main(): Promise<void> {\n const args = parseArgs(process.argv.slice(2));\n applyCliProviderFlag(args);\n applyCliModeFlag(args);\n if (args.command === \"help\" || args.command === \"--help\" || args.command === \"-h\") {\n console.log(usage());\n return;\n }\n\n if (args.command === \"doctor\") {\n await doctor(args);\n return;\n }\n\n if (args.command === \"patterns\") {\n const cwd = resolve(flagString(args, \"cwd\") ?? process.cwd());\n const metricsPath = join(cwd, \".tania\", \"memory\", \"forbidden-patterns-metrics.json\");\n if (!existsSync(metricsPath)) {\n console.log(`No metrics file at ${metricsPath}. Run a tanya task in this workspace first.`);\n return;\n }\n try {\n const parsed = JSON.parse(readFileSync(metricsPath, \"utf8\")) as {\n totals?: Record<string, number>;\n lastFiredAt?: Record<string, string>;\n totalScans?: number;\n };\n const totals = parsed.totals ?? {};\n const lastFiredAt = parsed.lastFiredAt ?? {};\n const entries = Object.entries(totals).sort((a, b) => b[1] - a[1]);\n console.log(`Forbidden-pattern fire metrics — ${cwd}`);\n console.log(`Total scans: ${parsed.totalScans ?? 0}`);\n console.log(\"\");\n if (entries.length === 0) {\n console.log(\"No patterns have fired in this workspace yet.\");\n return;\n }\n console.log(`${\"PATTERN\".padEnd(48)} ${\"FIRES\".padStart(7)} LAST FIRED`);\n for (const [id, count] of entries) {\n const last = lastFiredAt[id]?.slice(0, 16) ?? \"—\";\n console.log(`${id.padEnd(48)} ${String(count).padStart(7)} ${last}`);\n }\n } catch (err) {\n console.error(`Could not read metrics: ${err instanceof Error ? err.message : String(err)}`);\n process.exitCode = 1;\n }\n return;\n }\n\n if (args.command === \"sessions\") {\n const cwd = resolve(flagString(args, \"cwd\") ?? process.cwd());\n await runSessionsCommand({\n action: args.positional[0] ?? \"list\",\n args: args.positional.slice(1),\n cwd,\n global: hasFlag(args, \"global\"),\n all: hasFlag(args, \"all\"),\n limit: flagNumber(args, \"limit\"),\n olderThan: flagString(args, \"older-than\"),\n });\n return;\n }\n\n if (args.command === \"providers\") {\n if (args.positional[0] !== \"test\") {\n console.log(\"Usage: tanya providers test --provider <name>\");\n return;\n }\n await testProvider(args);\n return;\n }\n\n if (args.command === \"permissions\") {\n if (args.positional[0] !== \"migrate\") {\n console.log(\"Usage: tanya permissions migrate [--cwd path] [--limit 100]\");\n return;\n }\n const cwd = resolve(flagString(args, \"cwd\") ?? process.cwd());\n const limit = flagNumber(args, \"limit\") ?? 100;\n console.log(JSON.stringify(suggestPermissionsFromRuns(cwd, limit), null, 2));\n return;\n }\n\n if (args.command === \"mcp\") {\n if (args.positional[0] !== \"serve\") {\n console.log(\"Usage: tanya mcp serve\");\n return;\n }\n await serveTanyaMcpServer({ defaultCwd: resolve(flagString(args, \"cwd\") ?? process.cwd()) });\n return;\n }\n\n if (args.command === \"eval\") {\n await runEvalCommand(args);\n return;\n }\n\n if (args.command === \"init\") {\n const cwd = resolve(flagString(args, \"cwd\") ?? process.cwd());\n const path = await initTanyaProject(cwd);\n console.log(path);\n return;\n }\n\n if (args.command === \"video\") {\n await runVideoCommand(args);\n return;\n }\n\n if (args.command === \"golden\" || args.command === \"benchmark\") {\n const cwd = resolve(flagString(args, \"cwd\") ?? process.cwd());\n const action = args.positional[0] ?? \"summary\";\n if (![\"summary\", \"list\", \"profiles\", \"run\", \"validate\"].includes(action)) {\n console.log(`Usage: tanya ${args.command} summary|list|profiles|run|validate [--cwd path] [--json] [--profile id] [--all]`);\n return;\n }\n const profile = flagString(args, \"profile\");\n const exitCode = await runGoldenSuiteCommand(cwd, action, hasFlag(args, \"json\"), {\n ...(profile ? { profile } : {}),\n all: hasFlag(args, \"all\"),\n });\n process.exitCode = exitCode;\n return;\n }\n\n if (args.command === \"runs\") {\n const cwd = resolve(flagString(args, \"cwd\") ?? process.cwd());\n const logs = readRunLogs(cwd, 10);\n if (logs.length === 0) {\n process.stdout.write(\"No run logs found. Run tanya run first.\\n\");\n return;\n }\n for (const log of logs) process.stdout.write(`${formatRunLogLine(log)}\\n`);\n return;\n }\n\n applyCliProfileFlag(args);\n const config = loadConfig();\n\n if (args.command === \"debug-prompt\") {\n const cwd = resolve(flagString(args, \"cwd\") ?? process.cwd());\n const task = readPrompt(args);\n if (!task) throw new Error(\"Missing task. Usage: tanya debug-prompt --cwd <path> \\\"task description\\\"\");\n\n const runContext = await buildRunContextForCli(args, cwd, task, config.obsidianVault);\n const historyBlock = buildHistoryBlock(await readRecentTaskHistory(cwd));\n const lite = /^(1|true|yes|on)$/i.test(envValue(process.env, \"TANYA_LITE_PROMPT\").trim());\n if (lite) {\n try {\n await buildRepoMap(cwd, { writeCache: true });\n } catch {\n // Repo-map diagnostics are best-effort for debug-prompt.\n }\n }\n const systemPrompt = buildSystemPrompt(cwd, runContext, historyBlock, task, {\n lite,\n });\n const skillPacks = loadPromptSkillPacks(cwd, runContext, task);\n const sections = flagStrings(args, \"section\");\n const output = selectPromptSections(systemPrompt, sections);\n\n process.stdout.write(\"=== SYSTEM PROMPT ===\\n\\n\");\n process.stdout.write(output);\n process.stdout.write(\"\\n\\n=== END SYSTEM PROMPT ===\\n\");\n if (sections.length === 0) {\n process.stdout.write(`\\nLength: ${systemPrompt.length} chars (~${Math.ceil(systemPrompt.length / 4)} tokens)\\n`);\n process.stdout.write(`${formatSkillPackSummary(skillPacks)}\\n`);\n const map = readRepoMap(cwd);\n if (map) {\n const diagnostics = repoMapDiagnostics(map);\n process.stdout.write(`Repo map: ${diagnostics.fileCount} files, ${diagnostics.symbolCount} symbols, ${diagnostics.importCount} imports, ~${diagnostics.estimatedTokens} tokens, parsers tree-sitter=${diagnostics.parserCounts[\"tree-sitter\"]} ripgrep=${diagnostics.parserCounts.ripgrep} path=${diagnostics.parserCounts.path}\\n`);\n }\n }\n return;\n }\n\n const provider = createProvider(config);\n\n if (args.command === \"ask\") {\n const prompt = readPrompt(args);\n if (!prompt) throw new Error(\"Missing prompt.\");\n await askOnce(provider, prompt);\n return;\n }\n\n if (args.command === \"review\") {\n const cwd = resolve(flagString(args, \"cwd\") ?? process.cwd());\n const task = readPrompt(args);\n if (!task) throw new Error(\"Missing task description. Usage: tanya review --cwd <path> \\\"task description\\\"\");\n\n const { execFileSync } = await import(\"node:child_process\");\n let diff = \"\";\n try {\n diff = execFileSync(\"git\", [\"diff\", \"HEAD\"], { cwd, encoding: \"utf8\" });\n if (!diff.trim()) {\n diff = execFileSync(\"git\", [\"show\", \"--format=\", \"HEAD\"], { cwd, encoding: \"utf8\" });\n }\n } catch {\n throw new Error(\"tanya review requires a git repository with changes.\");\n }\n\n process.stdout.write(\"Reviewing changes...\\n\\n\");\n const review = await reviewChanges(provider, task, diff);\n process.stdout.write(`${review}\\n`);\n return;\n }\n\n const cwd = resolve(flagString(args, \"cwd\") ?? process.cwd());\n const routing = buildRoutingOptions(config, cwd);\n const json = hasFlag(args, \"json\");\n if (shouldUseInkChat(args, json)) {\n const { startInkChat } = await import(\"./ui/ink/runInkChat\");\n await startInkChat({\n provider,\n cwd,\n ...(routing ? { routing } : {}),\n resumeSessionId: flagString(args, \"resume\"),\n continueSession: hasFlag(args, \"continue\"),\n });\n return;\n }\n const sink = json ? createJsonlSink() : createHumanSink(process.stdout, { liveStatus: args.command === \"chat\" });\n let runPromptTokens = 0;\n let runCompletionTokens = 0;\n const trackingSink: EventSink = async (event) => {\n if (event.type === \"final\" && event.metrics) {\n runPromptTokens += event.metrics.promptTokens ?? 0;\n runCompletionTokens += event.metrics.completionTokens ?? 0;\n }\n return sink(event);\n };\n\n if (args.command === \"run\") {\n const prompt = readPrompt(args);\n const resumeRunID = flagString(args, \"resume\");\n if (!prompt && !resumeRunID) throw new Error(\"Missing prompt.\");\n const runContext = prompt\n ? await buildRunContextForCli(args, cwd, prompt, config.obsidianVault)\n : undefined;\n const maxTurns = phaseAwareMaxTurns(runContext, prompt, flagNumber(args, \"max-turns\"));\n const repairAttempts = flagNumber(args, \"repair-attempts\");\n const maxRetries = flagNumber(args, \"retries\") ?? 0;\n const skipPostCheck = hasFlag(args, \"no-post-check\");\n const usePlan = hasFlag(args, \"plan\");\n const planAndDispatch = hasFlag(args, \"plan-and-dispatch\") || Boolean(flagString(args, \"resume\"));\n const tdd = hasFlag(args, \"tdd\");\n const testCmd = flagString(args, \"test-cmd\");\n const autoFixVerify = hasFlag(args, \"auto-fix-verify\");\n const autoFixWarns = hasFlag(args, \"auto-fix-warns\");\n const maxFixIterations = flagNumber(args, \"max-fix-iterations\") ?? 5;\n\n if (planAndDispatch) {\n if (!prompt && !resumeRunID) throw new Error(\"Missing prompt.\");\n const maxSubtasks = flagNumber(args, \"max-subtasks\") ?? 12;\n const dispatchMode = (flagString(args, \"dispatch-mode\") ?? \"sequential\") as DispatchMode;\n const { expected_report: _expectedReport, ...runContextWithoutExpectedReport } = runContext ?? {};\n const subtaskRunContext: TanyaRunContext | undefined = runContext\n ? {\n ...runContextWithoutExpectedReport,\n task: { ...(runContext.task ?? {}), kind: \"dispatch-subtask\" },\n }\n : undefined;\n\n await runPlanAndDispatch({\n cwd,\n prompt,\n maxSubtasks,\n mode: dispatchMode,\n tdd,\n autoFixVerify,\n autoFixWarns,\n maxFixIterations,\n readVerifyFailures: readVerifyFailuresFromStdin,\n ...(testCmd ? { testCmd } : {}),\n ...(resumeRunID ? { resumeRunID } : {}),\n sink: trackingSink,\n runTurn: async (turnPrompt, meta) => {\n if (meta.phase === \"plan\") {\n let text = \"\";\n for await (const delta of provider.streamChat({ messages: [{ role: \"user\", content: turnPrompt }], tools: [], temperature: 0, topP: 0.2 })) {\n if (delta.usage) {\n runPromptTokens += delta.usage.promptTokens;\n runCompletionTokens += delta.usage.completionTokens;\n }\n if (delta.content) text += delta.content;\n }\n return text;\n }\n\n const result = await runAgent({\n provider,\n prompt: turnPrompt,\n cwd,\n sink: trackingSink,\n ...(meta.phase === \"complete\" && runContext ? { runContext } : {}),\n ...(meta.phase === \"subtask\" && subtaskRunContext ? { runContext: subtaskRunContext } : {}),\n ...(maxTurns ? { maxTurns } : {}),\n ...(repairAttempts !== undefined ? { repairAttempts } : {}),\n });\n\n if (meta.phase === \"complete\" && !skipPostCheck) {\n const postBlockers = await detectPostRunBlockers(cwd, result.manifest);\n if (postBlockers.length > 0) {\n await trackingSink({\n type: \"status\",\n message: `Post-run checks found ${postBlockers.length} issue(s): ${postBlockers.join(\"; \")}`,\n });\n }\n }\n return result.message;\n },\n });\n\n if (runPromptTokens > 0 || runCompletionTokens > 0) {\n const costStr = estimateRunCost({\n provider: config.provider,\n model: config.model,\n promptTokens: runPromptTokens,\n completionTokens: runCompletionTokens,\n });\n process.stderr.write(\n `[tanya] Tokens: ${runPromptTokens.toLocaleString()} in / ${runCompletionTokens.toLocaleString()} out ${costStr}\\n`,\n );\n }\n return;\n }\n\n let planBlock = \"\";\n\n if (usePlan) {\n process.stderr.write(\"[tanya] Building execution plan with reasoner...\\n\");\n const reasonerConfig = loadConfig(cwd);\n const reasonerProvider = new OpenAiCompatibleProvider({\n id: \"deepseek-reasoner\",\n apiKey: reasonerConfig.apiKey,\n baseUrl: reasonerConfig.baseUrl,\n model: \"deepseek-reasoner\",\n timeoutMs: 180_000,\n temperature: 0,\n topP: 0.2,\n });\n const exportMap = buildExportMap(cwd);\n try {\n const plan = await buildExecutionPlan(reasonerProvider, prompt, exportMap);\n if (plan) {\n planBlock = `## Execution plan (pre-approved, follow it)\\n${plan}`;\n process.stderr.write(\"[tanya] Plan ready.\\n\");\n }\n } catch {\n process.stderr.write(\"[tanya] Planner failed, continuing without plan.\\n\");\n }\n }\n\n let lastResult: RunAgentResult | null = null;\n let previousPostBlockers: string[] = [];\n let attempt = 0;\n let stashedAttemptResult: RunAgentResult | null = null;\n let stashedAttemptLabel: string | null = null;\n // --no-retry-stash: skip stash-and-clean between retries so the agent sees\n // its previous attempt's files and can fix them incrementally instead of\n // rewriting from scratch. Use for tasks where partial progress is valuable\n // (e.g. test-writing where the agent's repeated rewrites burn context). The\n // default (stash) is best for tasks where a wrong-direction first attempt\n // should be discarded.\n const noRetryStash = hasFlag(args, \"no-retry-stash\");\n\n while (attempt <= maxRetries) {\n if (!noRetryStash && attempt > 0 && lastResult && lastResult.manifest.changedFiles.length > 0) {\n try {\n const { execFileSync } = await import(\"node:child_process\");\n const label = `tanya-retry-${attempt}`;\n // Exclude `.tania/` from the stash: those are runner-internal artifacts\n // (history.json, runs/*, memory/*) regenerated each attempt, and\n // including them in the stash causes pop conflicts on retry-recovery.\n execFileSync(\n \"git\",\n [\"stash\", \"push\", \"--include-untracked\", \"-m\", label, \"--\", \":(exclude).tania\", \":!**/.tania/**\"],\n { cwd, stdio: \"ignore\" },\n );\n stashedAttemptResult = lastResult;\n stashedAttemptLabel = label;\n process.stderr.write(\"[tanya] Stashed previous attempt changes. Retrying from clean state.\\n\");\n } catch {\n // Not a git repo or stash failed; retry context still helps.\n }\n }\n const retryContext = attempt > 0 && lastResult\n ? buildRetryContext(lastResult.manifest, attempt, previousPostBlockers)\n : \"\";\n const attemptPrompt = [planBlock, retryContext, \"Original task:\", prompt]\n .filter(Boolean)\n .join(\"\\n\\n---\\n\");\n\n lastResult = await runAgent({\n provider,\n prompt: attemptPrompt,\n cwd,\n sink: trackingSink,\n ...(runContext ? { runContext } : {}),\n ...(maxTurns ? { maxTurns } : {}),\n ...(repairAttempts !== undefined ? { repairAttempts } : {}),\n retryAttempt: attempt,\n ...(routing ? { routing } : {}),\n });\n\n const postBlockers = skipPostCheck\n ? []\n : await detectPostRunBlockers(cwd, lastResult.manifest);\n if (postBlockers.length > 0) {\n process.stderr.write(\n `[tanya] Post-run checks found ${postBlockers.length} issue(s) not reported by model:\\n${postBlockers.map((blocker) => ` - ${blocker}`).join(\"\\n\")}\\n`,\n );\n }\n previousPostBlockers = postBlockers;\n\n const failed =\n lastResult.manifest.blockers.length > 0 ||\n postBlockers.length > 0 ||\n (lastResult.manifest.validation !== undefined && !lastResult.manifest.validation.passed);\n\n if (!failed || attempt >= maxRetries) break;\n\n attempt += 1;\n process.stderr.write(\n `\\n[tanya] Attempt ${attempt} had blockers. Starting attempt ${attempt + 1} of ${maxRetries + 1}...\\n`,\n );\n }\n\n if (\n stashedAttemptResult &&\n stashedAttemptLabel &&\n lastResult &&\n lastResult.manifest.changedFiles.length === 0 &&\n stashedAttemptResult.manifest.changedFiles.length > 0\n ) {\n const { execFileSync } = await import(\"node:child_process\");\n let stashList = \"\";\n try { stashList = execFileSync(\"git\", [\"stash\", \"list\"], { cwd, encoding: \"utf8\" }); } catch { stashList = \"\"; }\n if (!stashList.includes(stashedAttemptLabel)) {\n process.stderr.write(`[tanya] Stashed attempt (${stashedAttemptLabel}) was already consumed; nothing to recover.\\n`);\n } else {\n try {\n execFileSync(\"git\", [\"stash\", \"pop\"], { cwd, stdio: \"pipe\" });\n process.stderr.write(\n `[tanya] Final attempt produced 0 file changes; restoring stashed attempt (${stashedAttemptResult.manifest.changedFiles.length} files) so the work isn't lost.\\n`,\n );\n lastResult = stashedAttemptResult;\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n if (/conflict|merge|CONFLICT/i.test(msg)) {\n process.stderr.write(`[tanya] Stash pop conflicted with current tree; aborting pop and keeping current attempt. Conflict: ${msg.slice(0, 240)}\\n`);\n try { execFileSync(\"git\", [\"checkout\", \".\"], { cwd, stdio: \"ignore\" }); } catch {}\n } else {\n process.stderr.write(`[tanya] Could not pop stash to recover previous attempt's work: ${msg.slice(0, 240)}\\n`);\n }\n }\n }\n }\n\n if (runPromptTokens > 0 || runCompletionTokens > 0) {\n const costStr = estimateRunCost({\n provider: config.provider,\n model: config.model,\n promptTokens: runPromptTokens,\n completionTokens: runCompletionTokens,\n }).display;\n process.stderr.write(\n `[tanya] Tokens: ${runPromptTokens.toLocaleString()} in / ${runCompletionTokens.toLocaleString()} out ${costStr}\\n`,\n );\n }\n\n if (hasFlag(args, \"review\") && lastResult) {\n let diff = \"\";\n try {\n const { execFileSync } = await import(\"node:child_process\");\n diff = execFileSync(\"git\", [\"diff\", \"HEAD\"], { cwd, encoding: \"utf8\" });\n if (!diff.trim() && lastResult.manifest.git.head) {\n diff = execFileSync(\"git\", [\"show\", \"--format=\", \"HEAD\"], { cwd, encoding: \"utf8\" });\n }\n } catch {\n // No git repository or diff unavailable; skip optional auto-review.\n }\n\n if (diff.trim()) {\n process.stdout.write(\"\\n--- Auto-review ---\\n\");\n const review = await reviewChanges(provider, prompt, diff);\n process.stdout.write(`${review}\\n`);\n }\n }\n return;\n }\n\n await startInteractiveChat({\n provider,\n cwd,\n sink,\n ...(routing ? { routing } : {}),\n resumeSessionId: flagString(args, \"resume\"),\n continueSession: hasFlag(args, \"continue\"),\n });\n}\n\nmain().catch((err) => {\n const message = err instanceof Error ? err.message : String(err);\n console.error(`Tanya error: ${message}`);\n process.exitCode = 1;\n});\n","import { existsSync, readFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { parse } from \"dotenv\";\nimport { envValue, numberEnvValue } from \"./envCompat\";\nimport { resolveProviderAdapter } from \"../providers/adapters\";\n\nexport interface TanyaConfig {\n provider: string;\n profile: \"chat\" | \"reasoner\";\n apiKey: string;\n baseUrl: string;\n model: string;\n temperature: number;\n topP: number;\n timeoutMs: number;\n obsidianVault?: string;\n}\n\nfunction loadDotEnv(cwd: string): Record<string, string> {\n const envPath = join(cwd, \".env\");\n if (!existsSync(envPath)) return {};\n return parse(readFileSync(envPath, \"utf8\"));\n}\n\nexport function loadConfig(cwd = process.cwd()): TanyaConfig {\n const local = loadDotEnv(cwd);\n const profile = envValue(local, \"TANYA_PROFILE\") === \"reasoner\" ? \"reasoner\" : \"chat\";\n const requestedProvider = envValue(local, \"TANYA_PROVIDER\").trim();\n const requestedBaseUrl = envValue(local, \"TANYA_BASE_URL\").trim();\n const providerSeed = requestedProvider || (requestedBaseUrl ? \"\" : \"deepseek\");\n const adapter = resolveProviderAdapter({\n provider: providerSeed,\n baseUrl: requestedBaseUrl,\n });\n const provider = providerSeed || adapter.id;\n\n const apiKey =\n provider === \"deepseek\"\n ? envValue(local, \"DEEPSEEK_API_KEY\") || envValue(local, \"TANYA_API_KEY\")\n : envValue(local, \"TANYA_API_KEY\");\n\n const baseUrl =\n provider === \"deepseek\"\n ? envValue(local, \"DEEPSEEK_BASE_URL\") || envValue(local, \"TANYA_BASE_URL\") || adapter.defaultBaseUrl || \"https://api.deepseek.com\"\n : envValue(local, \"TANYA_BASE_URL\") || adapter.defaultBaseUrl || \"\";\n\n const profileModelDefault = profile === \"reasoner\" && adapter.id === \"deepseek\"\n ? \"deepseek-reasoner\"\n : adapter.defaultModel ?? \"deepseek-v4-pro\";\n const model = envValue(local, \"TANYA_MODEL\") || profileModelDefault;\n\n const profileTimeoutDefault = profile === \"reasoner\" ? 180_000 : 90_000;\n const timeoutMs = numberEnvValue(local, \"TANYA_TIMEOUT_MS\", profileTimeoutDefault);\n\n const config: TanyaConfig = {\n provider,\n profile,\n apiKey,\n baseUrl: baseUrl.replace(/\\/$/, \"\"),\n model,\n temperature: numberEnvValue(local, \"TANYA_TEMPERATURE\", 0),\n topP: numberEnvValue(local, \"TANYA_TOP_P\", 0.2),\n timeoutMs,\n ...(envValue(local, \"TANYA_OBSIDIAN_VAULT\") ? { obsidianVault: envValue(local, \"TANYA_OBSIDIAN_VAULT\") } : {}),\n };\n\n if (!config.apiKey.trim()) {\n throw new Error(\"TANYA_API_KEY is not set. Add it to your .env file or environment.\");\n }\n\n return config;\n}\n","import { copyFileSync, cpSync, existsSync, mkdirSync, statSync, writeFileSync } from \"node:fs\";\nimport { basename, dirname, isAbsolute, relative, resolve } from \"node:path\";\nimport type { TanyaRunContext } from \"./runContext\";\n\nexport type MaterializeCliArtifactsInput = {\n cwd: string;\n root?: string | undefined;\n artifacts: string[];\n contextPaths?: string[] | undefined;\n artifactOutputRoot?: string | undefined;\n keepContext?: boolean | undefined;\n baseContext?: TanyaRunContext | undefined;\n};\n\nfunction normalizePath(path: string): string {\n return path.trim().replace(/\\\\/g, \"/\").replace(/^\"|\"$/g, \"\");\n}\n\nfunction unique(values: string[]): string[] {\n return [...new Set(values.map(normalizePath).filter(Boolean))];\n}\n\nfunction sourceLabel(root: string | undefined, artifact: string): string {\n const clean = normalizePath(artifact);\n if (!root || isAbsolute(clean)) return clean;\n const rootBase = basename(resolve(root));\n return rootBase === \"artifacts\" ? `artifacts/${clean}` : clean;\n}\n\nfunction relativeMaterializedPath(root: string | undefined, artifact: string, source: string): string {\n const clean = normalizePath(artifact);\n if (root && !isAbsolute(clean)) return clean;\n if (root) {\n const rel = normalizePath(relative(resolve(root), source));\n if (rel && !rel.startsWith(\"../\") && rel !== \"..\") return rel;\n }\n return basename(source);\n}\n\nexport function materializeCliArtifacts(input: MaterializeCliArtifactsInput): TanyaRunContext | undefined {\n const artifactInputs = unique(input.artifacts);\n const contextInputs = unique(input.contextPaths ?? []);\n if (artifactInputs.length === 0 && contextInputs.length === 0 && !input.artifactOutputRoot) return input.baseContext;\n\n const cwd = resolve(input.cwd);\n const root = input.root ? resolve(input.root) : undefined;\n const targetRoot = resolve(cwd, \".tania\", \"artifacts\");\n const contextTargetRoot = resolve(cwd, \".tania\", \"context\");\n const materialized: NonNullable<TanyaRunContext[\"artifacts\"]> = [];\n const contextFiles: NonNullable<TanyaRunContext[\"contextFiles\"]> = [];\n\n for (const artifact of artifactInputs) {\n const source = isAbsolute(artifact)\n ? resolve(artifact)\n : resolve(root ?? cwd, artifact);\n const rel = relativeMaterializedPath(root, artifact, source);\n const target = resolve(targetRoot, rel);\n const localPath = `.tania/artifacts/${normalizePath(rel)}`;\n const label = sourceLabel(root, artifact);\n\n if (!target.startsWith(`${targetRoot}/`) || !existsSync(source)) {\n materialized.push({\n path: localPath,\n sourcePath: label,\n role: \"source-pattern\",\n status: \"missing\",\n reason: \"Artifact was requested by the caller but was not found.\",\n });\n continue;\n }\n\n const sourceStat = statSync(source);\n if (sourceStat.isDirectory()) {\n mkdirSync(target, { recursive: true });\n cpSync(source, target, { recursive: true, force: true });\n } else {\n mkdirSync(dirname(target), { recursive: true });\n copyFileSync(source, target);\n }\n materialized.push({\n path: localPath,\n sourcePath: label,\n role: \"source-pattern\",\n status: \"available\",\n reason: \"Materialized into this workspace from a caller-provided artifact input.\",\n });\n }\n\n if (materialized.some((artifact) => artifact.status === \"available\")) {\n mkdirSync(targetRoot, { recursive: true });\n writeFileSync(\n resolve(targetRoot, \"manifest.json\"),\n JSON.stringify({ generatedAt: new Date().toISOString(), artifacts: materialized }, null, 2),\n \"utf8\",\n );\n }\n\n for (const contextPath of contextInputs) {\n const source = resolve(contextPath);\n const rel = normalizePath(relative(dirname(source), source)) || basename(source);\n const parentLabel = basename(dirname(source));\n const targetRel = parentLabel ? `${parentLabel}/${basename(source)}` : rel;\n const target = resolve(contextTargetRoot, targetRel);\n const localPath = `.tania/context/${normalizePath(targetRel)}`;\n\n if (!target.startsWith(`${contextTargetRoot}/`) || !existsSync(source)) {\n contextFiles.push({\n path: localPath,\n sourcePath: contextPath,\n role: \"caller-context\",\n status: \"missing\",\n reason: \"Context file was requested by the caller but was not found.\",\n });\n continue;\n }\n\n mkdirSync(dirname(target), { recursive: true });\n copyFileSync(source, target);\n contextFiles.push({\n path: localPath,\n sourcePath: contextPath,\n role: \"caller-context\",\n status: \"available\",\n reason: \"Materialized into this workspace from a caller-provided context input.\",\n });\n }\n\n if (contextFiles.some((contextFile) => contextFile.status === \"available\")) {\n mkdirSync(contextTargetRoot, { recursive: true });\n writeFileSync(\n resolve(contextTargetRoot, \"manifest.json\"),\n JSON.stringify({ generatedAt: new Date().toISOString(), contextFiles }, null, 2),\n \"utf8\",\n );\n }\n\n const artifactOutputRoot = input.artifactOutputRoot ? resolve(input.artifactOutputRoot) : undefined;\n\n return {\n ...(input.baseContext ?? {}),\n artifacts: [...(input.baseContext?.artifacts ?? []), ...materialized],\n contextFiles: [...(input.baseContext?.contextFiles ?? []), ...contextFiles],\n instructions: [\n ...(input.baseContext?.instructions ?? []),\n ...(materialized.length > 0 ? [\n \"Caller artifacts were provided through Tanya's artifact input contract and materialized under .tania/artifacts.\",\n \"Read relevant materialized artifact paths before implementing related code.\",\n ] : []),\n ...(contextFiles.length > 0 ? [\n \"Caller context files were materialized under .tania/context.\",\n \"Read relevant materialized context paths before implementing safety, brand, architecture, or API contract requirements.\",\n ] : []),\n ...(artifactOutputRoot ? [\n \"If you create a reusable artifact, write it inside .tania/artifact-output using the intended artifact-relative path and mention it as Artifact created.\",\n ] : []),\n \"When reporting artifact reuse, use the artifact sourcePath label when available.\",\n ],\n expected_report: {\n ...(input.baseContext?.expected_report ?? {}),\n artifact_reuse: true,\n },\n metadata: {\n ...(input.baseContext?.metadata ?? {}),\n ...(artifactOutputRoot ? { artifactOutputRoot } : {}),\n tanyaMaterializedContext: true,\n keepMaterializedContext: input.keepContext === true,\n },\n };\n}\n","import type { EventSink, TanyaEvent } from \"./types\";\n\nconst knownEventTypes = new Set([\n \"status\",\n \"message_start\",\n \"message_delta\",\n \"message_end\",\n \"reasoning_chunk\",\n \"reasoning_truncated\",\n \"tool_call\",\n \"tool_progress\",\n \"tool_cancel_requested\",\n \"tool_cancelled\",\n \"permission_request\",\n \"permission_decision\",\n \"tool_result\",\n \"tool_call_parse_warning\",\n \"schema_flatten_warning\",\n \"provider_throttle\",\n \"model_routed\",\n \"escalation_event\",\n \"compact_event\",\n \"prompt_budget_exceeded\",\n \"subtask_started\",\n \"subtask_completed\",\n \"subtask_start\",\n \"subtask_done\",\n \"command_invoked\",\n \"final\",\n \"error\",\n]);\n\nfunction isKnownEvent(event: unknown): event is TanyaEvent {\n return Boolean(\n event &&\n typeof event === \"object\" &&\n typeof (event as { type?: unknown }).type === \"string\" &&\n knownEventTypes.has((event as { type: string }).type),\n );\n}\n\nexport function createJsonlSink(stream: NodeJS.WritableStream = process.stdout): EventSink {\n return (event: TanyaEvent) => {\n if (!isKnownEvent(event)) return;\n stream.write(`${JSON.stringify(event)}\\n`);\n };\n}\n","export type ReasoningSplit =\n | { type: \"content\"; text: string }\n | { type: \"reasoning\"; text: string };\n\nconst OPEN_TAG = \"<think>\";\nconst CLOSE_TAG = \"</think>\";\n\nexport class ThinkBlockSplitter {\n private mode: \"content\" | \"reasoning\" = \"content\";\n private buffer = \"\";\n\n push(text: string): ReasoningSplit[] {\n this.buffer += text;\n return this.drain(false);\n }\n\n flush(): ReasoningSplit[] {\n return this.drain(true);\n }\n\n private drain(flush: boolean): ReasoningSplit[] {\n const output: ReasoningSplit[] = [];\n while (this.buffer.length > 0) {\n if (this.mode === \"content\") {\n const open = this.buffer.indexOf(OPEN_TAG);\n if (open >= 0) {\n this.emit(output, \"content\", this.buffer.slice(0, open));\n this.buffer = this.buffer.slice(open + OPEN_TAG.length);\n this.mode = \"reasoning\";\n continue;\n }\n const keep = flush ? 0 : OPEN_TAG.length - 1;\n if (this.buffer.length <= keep) break;\n this.emit(output, \"content\", this.buffer.slice(0, this.buffer.length - keep));\n this.buffer = this.buffer.slice(this.buffer.length - keep);\n break;\n }\n\n const close = this.buffer.indexOf(CLOSE_TAG);\n if (close >= 0) {\n this.emit(output, \"reasoning\", this.buffer.slice(0, close));\n this.buffer = this.buffer.slice(close + CLOSE_TAG.length);\n this.mode = \"content\";\n continue;\n }\n const keep = flush ? 0 : CLOSE_TAG.length - 1;\n if (this.buffer.length <= keep) break;\n this.emit(output, \"reasoning\", this.buffer.slice(0, this.buffer.length - keep));\n this.buffer = this.buffer.slice(this.buffer.length - keep);\n break;\n }\n\n if (flush && this.buffer.length > 0) {\n this.emit(output, this.mode, this.buffer);\n this.buffer = \"\";\n }\n return output;\n }\n\n private emit(output: ReasoningSplit[], type: ReasoningSplit[\"type\"], text: string): void {\n if (text.length > 0) output.push({ type, text });\n }\n}\n\nexport function estimateReasoningTokens(text: string): number {\n return Math.ceil(text.length / 4);\n}\n","import type { ToolDefinition } from \"./types\";\n\nexport type SchemaFlattenWarning = {\n path: string;\n reason: string;\n tool?: string;\n};\n\nexport type SchemaFlattenResult<T> = {\n schema: T;\n warnings: SchemaFlattenWarning[];\n};\n\ntype JsonObject = Record<string, unknown>;\n\nexport function flattenJsonSchema<T>(schema: T): SchemaFlattenResult<T> {\n const warnings: SchemaFlattenWarning[] = [];\n const root = clone(schema);\n const flattened = flattenValue(root, root, \"#\", warnings, new Set()) as T;\n return { schema: flattened, warnings };\n}\n\nexport function flattenToolDefinition(tool: ToolDefinition): SchemaFlattenResult<ToolDefinition> {\n const result = flattenJsonSchema(tool.function.parameters);\n return {\n schema: {\n ...tool,\n function: {\n ...tool.function,\n parameters: result.schema,\n },\n },\n warnings: result.warnings.map((warning) => ({ ...warning, tool: tool.function.name })),\n };\n}\n\nexport function flattenToolDefinitions(tools: ToolDefinition[]): SchemaFlattenResult<ToolDefinition[]> {\n const flattened: ToolDefinition[] = [];\n const warnings: SchemaFlattenWarning[] = [];\n for (const tool of tools) {\n const result = flattenToolDefinition(tool);\n flattened.push(result.schema);\n warnings.push(...result.warnings);\n }\n return { schema: flattened, warnings };\n}\n\nfunction flattenValue(\n value: unknown,\n root: unknown,\n path: string,\n warnings: SchemaFlattenWarning[],\n seenRefs: Set<string>,\n): unknown {\n if (Array.isArray(value)) {\n return value.map((item, index) => flattenValue(item, root, `${path}/${index}`, warnings, seenRefs));\n }\n if (!isObject(value)) return value;\n\n const ref = typeof value.$ref === \"string\" ? value.$ref : null;\n if (ref) {\n const resolved = resolveLocalRef(root, ref);\n if (resolved === undefined) {\n warnings.push({ path, reason: `unresolved $ref ${ref}; leaving reference in place` });\n return value;\n }\n if (seenRefs.has(ref)) {\n warnings.push({ path, reason: `circular $ref ${ref}; leaving reference in place` });\n return value;\n }\n warnings.push({ path, reason: `inlined $ref ${ref}` });\n seenRefs.add(ref);\n const flattened = flattenValue(resolved, root, path, warnings, seenRefs);\n seenRefs.delete(ref);\n const { $ref: _ref, ...overrides } = value;\n return isObject(flattened)\n ? flattenObject({ ...flattened, ...overrides }, root, path, warnings, seenRefs)\n : flattened;\n }\n\n return flattenObject(value, root, path, warnings, seenRefs);\n}\n\nfunction flattenObject(\n object: JsonObject,\n root: unknown,\n path: string,\n warnings: SchemaFlattenWarning[],\n seenRefs: Set<string>,\n): JsonObject {\n const withoutDefs = stripDefinitions(object);\n if (Array.isArray(withoutDefs.oneOf)) {\n return flattenOneOf(withoutDefs, root, path, warnings, seenRefs);\n }\n\n const output: JsonObject = {};\n for (const [key, raw] of Object.entries(withoutDefs)) {\n output[key] = flattenValue(raw, root, `${path}/${escapePointer(key)}`, warnings, seenRefs);\n }\n return output;\n}\n\nfunction flattenOneOf(\n object: JsonObject,\n root: unknown,\n path: string,\n warnings: SchemaFlattenWarning[],\n seenRefs: Set<string>,\n): JsonObject {\n const variants = object.oneOf as unknown[];\n const flattenedVariants = variants\n .map((variant, index) => flattenValue(variant, root, `${path}/oneOf/${index}`, warnings, seenRefs))\n .filter(isObject);\n if (flattenedVariants.length === 0) {\n warnings.push({ path, reason: \"oneOf had no object variants; dropped oneOf\" });\n const { oneOf: _oneOf, ...rest } = object;\n return flattenObject(rest, root, path, warnings, seenRefs);\n }\n\n const commonType = commonScalar(flattenedVariants.map((variant) => variant.type));\n const commonProperties = commonObjectProperties(flattenedVariants);\n const commonRequired = commonRequiredFields(flattenedVariants);\n const { oneOf: _oneOf, ...rest } = object;\n warnings.push({ path, reason: `collapsed oneOf (${variants.length} variants) to common object shape` });\n\n return flattenObject({\n ...rest,\n ...(commonType ? { type: commonType } : {}),\n ...(Object.keys(commonProperties).length ? { properties: commonProperties } : {}),\n ...(commonRequired.length ? { required: commonRequired } : {}),\n }, root, path, warnings, seenRefs);\n}\n\nfunction commonObjectProperties(variants: JsonObject[]): JsonObject {\n const propertyMaps = variants\n .map((variant) => isObject(variant.properties) ? variant.properties : {});\n if (propertyMaps.length === 0) return {};\n const commonKeys = Object.keys(propertyMaps[0] ?? {})\n .filter((key) => propertyMaps.every((properties) => key in properties));\n const output: JsonObject = {};\n for (const key of commonKeys) output[key] = propertyMaps[0]?.[key];\n return output;\n}\n\nfunction commonRequiredFields(variants: JsonObject[]): string[] {\n const requiredLists = variants\n .map((variant) => Array.isArray(variant.required) ? variant.required.filter((item): item is string => typeof item === \"string\") : []);\n if (requiredLists.length === 0) return [];\n return requiredLists[0]?.filter((key) => requiredLists.every((list) => list.includes(key))) ?? [];\n}\n\nfunction commonScalar(values: unknown[]): string | null {\n const [first] = values;\n return typeof first === \"string\" && values.every((value) => value === first) ? first : null;\n}\n\nfunction resolveLocalRef(root: unknown, ref: string): unknown {\n if (!ref.startsWith(\"#/\")) return undefined;\n const parts = ref.slice(2).split(\"/\").map(unescapePointer);\n let current = root;\n for (const part of parts) {\n if (!isObject(current) && !Array.isArray(current)) return undefined;\n current = (current as Record<string, unknown>)[part];\n }\n return current;\n}\n\nfunction stripDefinitions(object: JsonObject): JsonObject {\n const { $defs: _defs, definitions: _definitions, ...rest } = object;\n return rest;\n}\n\nfunction clone<T>(value: T): T {\n return JSON.parse(JSON.stringify(value)) as T;\n}\n\nfunction isObject(value: unknown): value is JsonObject {\n return Boolean(value && typeof value === \"object\" && !Array.isArray(value));\n}\n\nfunction escapePointer(value: string): string {\n return value.replace(/~/g, \"~0\").replace(/\\//g, \"~1\");\n}\n\nfunction unescapePointer(value: string): string {\n return value.replace(/~1/g, \"/\").replace(/~0/g, \"~\");\n}\n","export type ProviderThrottleEvent = {\n provider: string;\n attempt: number;\n waitMs: number;\n};\n\nexport type ProviderRetryOptions = {\n provider: string;\n maxRetries?: number;\n maxWaitMs?: number;\n initialWaitMs?: number;\n concurrency?: number;\n sleep?: (ms: number) => Promise<void>;\n onThrottle?: (event: ProviderThrottleEvent) => void | Promise<void>;\n fetch: () => Promise<Response>;\n};\n\nconst DEFAULT_MAX_RETRIES = 3;\nconst DEFAULT_MAX_WAIT_MS = 30_000;\nconst DEFAULT_INITIAL_WAIT_MS = 500;\nconst DEFAULT_PROVIDER_CONCURRENCY = 4;\n\nconst semaphores = new Map<string, ProviderSemaphore>();\n\nexport function retryAfterMs(response: Response, now = Date.now()): number | null {\n const raw = response.headers.get(\"retry-after\");\n if (!raw) return null;\n const seconds = Number(raw);\n if (Number.isFinite(seconds) && seconds >= 0) return Math.max(0, seconds * 1000);\n const dateMs = Date.parse(raw);\n if (!Number.isNaN(dateMs)) return Math.max(dateMs - now, 0);\n return null;\n}\n\nexport function backoffMs(attempt: number, options: { initialWaitMs?: number; maxWaitMs?: number } = {}): number {\n const initial = options.initialWaitMs ?? DEFAULT_INITIAL_WAIT_MS;\n const max = options.maxWaitMs ?? DEFAULT_MAX_WAIT_MS;\n return Math.min(initial * 2 ** Math.max(0, attempt - 1), max);\n}\n\nexport function retryWaitMs(response: Response, attempt: number, options: { initialWaitMs?: number; maxWaitMs?: number } = {}): number | null {\n if (response.status === 429) {\n const retryAfter = retryAfterMs(response);\n if (retryAfter !== null) return Math.min(retryAfter, options.maxWaitMs ?? DEFAULT_MAX_WAIT_MS);\n }\n if ((response.status >= 500 && response.status <= 599) || response.status === 429) {\n return backoffMs(attempt, options);\n }\n return null;\n}\n\nexport async function fetchWithProviderRetry(options: ProviderRetryOptions): Promise<Response> {\n const semaphore = getProviderSemaphore(options.provider, options.concurrency ?? DEFAULT_PROVIDER_CONCURRENCY);\n return semaphore.run(() => fetchWithRetry(options));\n}\n\nexport function resetProviderRetryStateForTests(): void {\n semaphores.clear();\n}\n\nasync function fetchWithRetry(options: ProviderRetryOptions): Promise<Response> {\n const maxRetries = options.maxRetries ?? DEFAULT_MAX_RETRIES;\n const sleep = options.sleep ?? defaultSleep;\n let response: Response;\n\n for (let attempt = 0; attempt <= maxRetries; attempt += 1) {\n response = await options.fetch();\n const retryAttempt = attempt + 1;\n const waitOptions = {\n ...(options.initialWaitMs !== undefined ? { initialWaitMs: options.initialWaitMs } : {}),\n ...(options.maxWaitMs !== undefined ? { maxWaitMs: options.maxWaitMs } : {}),\n };\n const waitMs = attempt < maxRetries ? retryWaitMs(response, retryAttempt, waitOptions) : null;\n if (waitMs === null) return response;\n await options.onThrottle?.({ provider: options.provider, attempt: retryAttempt, waitMs });\n await sleep(waitMs);\n }\n\n return response!;\n}\n\nfunction getProviderSemaphore(provider: string, concurrency: number): ProviderSemaphore {\n const normalizedProvider = provider || \"unknown\";\n const existing = semaphores.get(normalizedProvider);\n if (existing && existing.limit === concurrency) return existing;\n const created = new ProviderSemaphore(Math.max(1, Math.floor(concurrency)));\n semaphores.set(normalizedProvider, created);\n return created;\n}\n\nfunction defaultSleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\nclass ProviderSemaphore {\n readonly limit: number;\n private active = 0;\n private readonly queue: Array<() => void> = [];\n\n constructor(limit: number) {\n this.limit = limit;\n }\n\n async run<T>(fn: () => Promise<T>): Promise<T> {\n await this.acquire();\n try {\n return await fn();\n } finally {\n this.release();\n }\n }\n\n private acquire(): Promise<void> {\n if (this.active < this.limit) {\n this.active += 1;\n return Promise.resolve();\n }\n return new Promise((resolve) => {\n this.queue.push(() => {\n this.active += 1;\n resolve();\n });\n });\n }\n\n private release(): void {\n this.active -= 1;\n const next = this.queue.shift();\n if (next) next();\n }\n}\n","import type { ChatMessage, ToolCall } from \"./types\";\n\nexport type NormalizationResult = {\n messages: ChatMessage[];\n warnings: string[];\n droppedOrphans: number;\n droppedDuplicates: number;\n filteredToolCalls: number;\n coercedNullContent: number;\n};\n\ntype ToolResultCandidate = {\n id: string;\n messageIndex: number;\n assistantIndex: number;\n};\n\nfunction toolCallId(call: ToolCall): string | null {\n return call.id.trim() ? call.id : null;\n}\n\nexport function normalizeMessages(messages: ChatMessage[]): NormalizationResult {\n const lastAssistantByToolCallId = new Map<string, number>();\n const toolResultCandidates: ToolResultCandidate[] = [];\n let droppedOrphans = 0;\n\n for (const [index, message] of messages.entries()) {\n if (message.role === \"assistant\") {\n for (const call of message.tool_calls ?? []) {\n const id = toolCallId(call);\n if (id) lastAssistantByToolCallId.set(id, index);\n }\n continue;\n }\n\n if (message.role !== \"tool\") continue;\n\n const id = message.tool_call_id?.trim();\n const assistantIndex = id ? lastAssistantByToolCallId.get(id) : undefined;\n if (!id || assistantIndex === undefined) {\n droppedOrphans += 1;\n continue;\n }\n\n toolResultCandidates.push({ id, messageIndex: index, assistantIndex });\n }\n\n const latestToolResultById = new Map<string, ToolResultCandidate>();\n for (const candidate of toolResultCandidates) {\n const existing = latestToolResultById.get(candidate.id);\n if (!existing || candidate.messageIndex > existing.messageIndex) {\n latestToolResultById.set(candidate.id, candidate);\n }\n }\n\n const keptToolMessageIndexes = new Set<number>();\n const answeredToolCalls = new Set<string>();\n for (const candidate of latestToolResultById.values()) {\n keptToolMessageIndexes.add(candidate.messageIndex);\n answeredToolCalls.add(`${candidate.assistantIndex}:${candidate.id}`);\n }\n\n const droppedDuplicates = toolResultCandidates.length - keptToolMessageIndexes.size;\n let filteredToolCalls = 0;\n let coercedNullContent = 0;\n const normalized: ChatMessage[] = [];\n\n for (const [index, message] of messages.entries()) {\n if (message.role === \"tool\") {\n if (keptToolMessageIndexes.has(index)) normalized.push(message);\n continue;\n }\n\n if (message.role !== \"assistant\" || !message.tool_calls?.length) {\n normalized.push(message);\n continue;\n }\n\n const toolCalls = message.tool_calls.filter((call) => {\n const id = toolCallId(call);\n return Boolean(id && answeredToolCalls.has(`${index}:${id}`));\n });\n filteredToolCalls += message.tool_calls.length - toolCalls.length;\n\n const content = message.content === null ? \"\" : message.content;\n if (message.content === null) coercedNullContent += 1;\n\n const normalizedMessage: ChatMessage = { ...message, content };\n if (toolCalls.length > 0) {\n normalizedMessage.tool_calls = toolCalls;\n } else {\n delete normalizedMessage.tool_calls;\n }\n normalized.push(normalizedMessage);\n }\n\n const warnings = [\n droppedOrphans > 0 ? `dropped orphan tool messages: ${droppedOrphans}` : null,\n droppedDuplicates > 0 ? `dropped duplicate tool results: ${droppedDuplicates}` : null,\n filteredToolCalls > 0 ? `filtered unanswered tool calls: ${filteredToolCalls}` : null,\n coercedNullContent > 0 ? `coerced null assistant content: ${coercedNullContent}` : null,\n ].filter((message): message is string => Boolean(message));\n\n return {\n messages: normalized,\n warnings,\n droppedOrphans,\n droppedDuplicates,\n filteredToolCalls,\n coercedNullContent,\n };\n}\n","import { ContextWindowExceededError, type ChatDelta, type ChatMessage, type ChatProvider, type ChatRequest, type ToolCall } from \"./types\";\nimport { envValue } from \"../config/envCompat\";\nimport { estimateReasoningTokens, ThinkBlockSplitter } from \"../agent/reasoning\";\nimport { resolveProviderAdapter, type ChatResponse, type ProviderAdapter, type ProviderRequest } from \"./adapters\";\nimport { flattenToolDefinitions, type SchemaFlattenWarning } from \"./schemaFlatten\";\nimport { fetchWithProviderRetry } from \"./retry\";\nimport { normalizeMessages } from \"./messageNormalize\";\n\nexport interface OpenAiCompatibleProviderOptions {\n id: string;\n apiKey: string;\n baseUrl: string;\n model: string;\n timeoutMs?: number;\n temperature?: number;\n topP?: number;\n}\n\ninterface StreamChoice {\n delta?: {\n content?: string | null;\n reasoning_content?: string | null;\n tool_calls?: Array<{\n index?: number;\n id?: string;\n type?: \"function\";\n function?: {\n name?: string;\n arguments?: string;\n };\n }>;\n };\n finish_reason?: string | null;\n}\n\ninterface StreamChunk {\n choices?: StreamChoice[];\n usage?: {\n prompt_tokens?: number;\n completion_tokens?: number;\n reasoning_tokens?: number;\n completion_tokens_details?: {\n reasoning_tokens?: number;\n };\n };\n}\n\nconst CONTEXT_WINDOW_ERROR_PATTERNS = [\n /context_length_exceeded/i,\n /maximum context length/i,\n /tokens?\\s+exceeds?/i,\n /too long/i,\n];\n\nconst deprecatedDeepSeekModels = new Set([\"deepseek-chat\", \"deepseek-reasoner\"]);\nconst warnedDeprecatedModels = new Set<string>();\n\nfunction isContextWindowExceededResponse(status: number, detail: string): boolean {\n if (status === 413) return true;\n if (status >= 500) return false;\n return CONTEXT_WINDOW_ERROR_PATTERNS.some((pattern) => pattern.test(detail));\n}\n\nfunction providerConcurrency(): number {\n const raw = Number(envValue({}, \"TANYA_PROVIDER_CONCURRENCY\"));\n return Number.isFinite(raw) && raw > 0 ? Math.floor(raw) : 4;\n}\n\nfunction warnDeprecatedDeepSeekModel(providerId: string, model: string): void {\n if (providerId !== \"deepseek\") return;\n if (!deprecatedDeepSeekModels.has(model)) return;\n if (warnedDeprecatedModels.has(model)) return;\n if (envValue({}, \"TANYA_SUPPRESS_DEPRECATION\") === \"1\") return;\n\n warnedDeprecatedModels.add(model);\n process.stderr.write([\n `[tanya] DeepSeek model \"${model}\" is a V4-Flash compatibility alias and is scheduled for deprecation by DeepSeek on 2026-07-24.`,\n \"Tanya will migrate to V4 thinking-mode config in a future release (tracked as M13).\",\n \"Until then, you can keep using the legacy name with no behavior change.\",\n \"See docs/providers.md#deepseek-v4-deprecation for the migration story.\",\n \"Suppress this warning with TANYA_SUPPRESS_DEPRECATION=1 (or legacy TANIA_SUPPRESS_DEPRECATION=1).\",\n \"\",\n ].join(\"\\n\"));\n}\n\nexport function messagesForAdapter(messages: ChatMessage[], roundTripReasoning: boolean): ChatMessage[] {\n return messages.map((message) => {\n const carryReasoning =\n roundTripReasoning &&\n message.role === \"assistant\" &&\n typeof message.reasoning_content === \"string\" &&\n message.reasoning_content.length > 0;\n\n const base = carryReasoning ? message : (() => {\n const { reasoning_content: _reasoningContent, ...rest } = message;\n return rest;\n })();\n\n // DeepSeek rejects assistant messages where content is null and tool_calls\n // is empty/missing, even when reasoning_content is present.\n if (\n roundTripReasoning &&\n base.role === \"assistant\" &&\n (base.content === null || base.content === undefined) &&\n (!base.tool_calls || base.tool_calls.length === 0)\n ) {\n return { ...base, content: \"\" };\n }\n\n return base;\n });\n}\n\nexport class OpenAiCompatibleProvider implements ChatProvider {\n readonly id: string;\n readonly model: string;\n readonly contextWindow: number;\n readonly reasoning: boolean;\n readonly roundTripReasoning: boolean;\n private readonly apiKey: string;\n private readonly baseUrl: string;\n private readonly timeoutMs: number;\n private readonly temperature: number;\n private readonly topP: number;\n private readonly adapter: ProviderAdapter;\n\n constructor(options: OpenAiCompatibleProviderOptions) {\n this.adapter = resolveProviderAdapter({ provider: options.id, baseUrl: options.baseUrl });\n this.id = options.id;\n this.apiKey = options.apiKey;\n this.baseUrl = (options.baseUrl || this.adapter.defaultBaseUrl || \"\").replace(/\\/$/, \"\");\n this.model = options.model || this.adapter.defaultModel || \"\";\n warnDeprecatedDeepSeekModel(this.adapter.id, this.model);\n this.contextWindow = this.adapter.capabilities.contextWindow;\n this.reasoning = reasoningEnabled(this.adapter, this.model);\n this.roundTripReasoning = this.adapter.capabilities.roundTripReasoning === true;\n const envTimeout = parseInt(envValue({}, \"TANYA_TIMEOUT_MS\"), 10);\n const envTimeoutMs = Number.isFinite(envTimeout) && envTimeout > 0 ? envTimeout : null;\n this.timeoutMs = envTimeoutMs ?? options.timeoutMs ?? 90_000;\n this.temperature = options.temperature ?? 0;\n this.topP = options.topP ?? 0.2;\n }\n\n async *streamChat(input: ChatRequest): AsyncGenerator<ChatDelta> {\n if (!this.apiKey) {\n throw new Error(`Missing API key for provider \"${this.id}\".`);\n }\n\n const controller = new AbortController();\n let timeout: ReturnType<typeof setTimeout> | null = null;\n const resetTimeout = () => {\n if (timeout) clearTimeout(timeout);\n timeout = setTimeout(() => controller.abort(), this.timeoutMs);\n };\n\n const normalizedMessages = normalizeMessages(input.messages);\n if (normalizedMessages.warnings.length > 0 && envValue({}, \"TANYA_DEBUG\")) {\n console.debug(`[tanya] Provider message normalization: ${normalizedMessages.warnings.join(\"; \")}`);\n }\n\n const request: ProviderRequest = {\n model: this.model,\n messages: messagesForAdapter(normalizedMessages.messages, this.roundTripReasoning),\n temperature: input.temperature ?? this.temperature,\n top_p: input.topP ?? this.topP,\n max_tokens: input.maxTokens ?? 8192,\n stream: true,\n };\n const schemaWarnings: SchemaFlattenWarning[] = [];\n if (input.tools?.length) {\n if (this.adapter.capabilities.flattenSchemas) {\n const flattened = flattenToolDefinitions(input.tools);\n request.tools = flattened.schema;\n schemaWarnings.push(...flattened.warnings);\n } else {\n request.tools = input.tools;\n }\n request.tool_choice = \"auto\";\n }\n const requestBody = JSON.stringify(this.adapter.preRequest ? this.adapter.preRequest(request) : request);\n\n resetTimeout();\n const retryOptions = {\n provider: this.adapter.id,\n concurrency: providerConcurrency(),\n fetch: () => {\n resetTimeout();\n return fetch(`${this.baseUrl}/chat/completions`, {\n method: \"POST\",\n signal: controller.signal,\n headers: {\n Authorization: `Bearer ${this.apiKey}`,\n \"Content-Type\": \"application/json\",\n },\n body: requestBody,\n }).catch((error) => {\n if (controller.signal.aborted) {\n throw new Error(`Provider ${this.id} timed out before streaming a response.`);\n }\n throw error;\n });\n },\n ...(input.onProviderThrottle ? { onThrottle: input.onProviderThrottle } : {}),\n };\n const response = await fetchWithProviderRetry(retryOptions);\n\n if (!response.ok || !response.body) {\n if (timeout) clearTimeout(timeout);\n const detail = await response.text().catch(() => \"\");\n if (isContextWindowExceededResponse(response.status, detail)) {\n throw new ContextWindowExceededError({\n provider: this.id,\n status: response.status,\n rawMessage: detail || response.statusText || \"context window exceeded\",\n });\n }\n throw new Error(`Provider ${this.id} returned HTTP ${response.status}: ${detail.slice(0, 500)}`);\n }\n\n const decoder = new TextDecoder();\n let buffer = \"\";\n const toolCallParts = new Map<number, ToolCall>();\n const thinkSplitter = new ThinkBlockSplitter();\n let thinkSplittingActive = this.reasoning;\n\n const flushThinkSplitter = function* (): Generator<ChatDelta> {\n if (!thinkSplittingActive) return;\n for (const split of thinkSplitter.flush()) {\n if (split.type === \"reasoning\") {\n yield { reasoningContent: split.text, usage: { promptTokens: 0, completionTokens: 0, reasoningTokens: estimateReasoningTokens(split.text) } };\n } else {\n yield { content: split.text };\n }\n }\n };\n\n try {\n if (schemaWarnings.length > 0) {\n yield { schemaWarnings };\n }\n for await (const chunk of response.body as unknown as AsyncIterable<Uint8Array>) {\n resetTimeout();\n buffer += decoder.decode(chunk, { stream: true });\n const lines = buffer.split(\"\\n\");\n buffer = lines.pop() ?? \"\";\n\n for (const rawLine of lines) {\n const line = rawLine.trim();\n if (!line || !line.startsWith(\"data:\")) continue;\n const data = line.slice(\"data:\".length).trim();\n if (data === \"[DONE]\") {\n yield* flushThinkSplitter();\n return;\n }\n\n let parsed: StreamChunk;\n try {\n const rawParsed = JSON.parse(data) as ChatResponse;\n parsed = (this.adapter.postResponse ? this.adapter.postResponse(rawParsed) : rawParsed) as StreamChunk;\n } catch (error) {\n if (envValue({}, \"TANYA_DEBUG\")) {\n const message = error instanceof Error ? error.message : String(error);\n console.debug(`[tanya] Skipping malformed SSE chunk: ${message}`);\n }\n continue;\n }\n if (parsed.usage?.prompt_tokens !== undefined) {\n const reasoningTokens = parsed.usage.reasoning_tokens ??\n parsed.usage.completion_tokens_details?.reasoning_tokens;\n yield {\n usage: {\n promptTokens: parsed.usage.prompt_tokens ?? 0,\n completionTokens: parsed.usage.completion_tokens ?? 0,\n ...(typeof reasoningTokens === \"number\" ? { reasoningTokens } : {}),\n },\n };\n }\n\n const choice = parsed.choices?.[0];\n if (!choice) continue;\n\n const reasoningContent = choice.delta?.reasoning_content ?? undefined;\n if (reasoningContent) {\n yield {\n reasoningContent,\n usage: { promptTokens: 0, completionTokens: 0, reasoningTokens: estimateReasoningTokens(reasoningContent) },\n };\n }\n\n const content = choice.delta?.content ?? undefined;\n if (content) {\n if (!thinkSplittingActive && !content.includes(\"<think>\")) {\n yield { content };\n } else {\n thinkSplittingActive = true;\n for (const split of thinkSplitter.push(content)) {\n if (split.type === \"reasoning\") {\n yield {\n reasoningContent: split.text,\n usage: { promptTokens: 0, completionTokens: 0, reasoningTokens: estimateReasoningTokens(split.text) },\n };\n } else {\n yield { content: split.text };\n }\n }\n }\n }\n\n const rawToolCalls = choice.delta?.tool_calls ?? [];\n for (const rawToolCall of rawToolCalls) {\n const index = rawToolCall.index ?? 0;\n const existing =\n toolCallParts.get(index) ??\n ({\n id: rawToolCall.id ?? `tool-${index}`,\n type: \"function\",\n function: { name: \"\", arguments: \"\" },\n } satisfies ToolCall);\n\n if (rawToolCall.id) existing.id = rawToolCall.id;\n if (rawToolCall.function?.name) existing.function.name += rawToolCall.function.name;\n if (rawToolCall.function?.arguments) existing.function.arguments += rawToolCall.function.arguments;\n toolCallParts.set(index, existing);\n }\n\n if (choice.finish_reason) {\n const toolCalls = [...toolCallParts.values()].filter((call) => call.function.name);\n yield toolCalls.length\n ? { finishReason: choice.finish_reason, toolCalls }\n : { finishReason: choice.finish_reason };\n }\n }\n }\n yield* flushThinkSplitter();\n } catch (error) {\n if (controller.signal.aborted) {\n throw new Error(`Provider ${this.id} timed out while streaming a response.`);\n }\n throw error;\n } finally {\n if (timeout) clearTimeout(timeout);\n }\n }\n}\n\nfunction reasoningEnabled(adapter: ProviderAdapter, model: string): boolean {\n const normalized = model.toLowerCase();\n if (adapter.id === \"deepseek\") return normalized.includes(\"reasoner\") || /\\br1\\b/.test(normalized);\n if (adapter.id === \"qwen\") return /qwen3.*thinking|thinking/.test(normalized);\n if (adapter.id === \"grok\") return /grok-3-reasoning|reasoning/.test(normalized);\n return false;\n}\n","import type { TanyaConfig } from \"../config/env\";\nimport { envValue } from \"../config/envCompat\";\nimport { resolveProviderAdapter } from \"./adapters\";\nimport { OpenAiCompatibleProvider } from \"./openAiCompatible\";\nimport type { ChatProvider } from \"./types\";\nimport type { RouteTarget } from \"../router/types\";\n\nexport function createProvider(config: TanyaConfig): ChatProvider {\n return new OpenAiCompatibleProvider({\n id: config.provider === \"deepseek\" && config.profile === \"reasoner\" ? \"deepseek-reasoner\" : config.provider,\n apiKey: config.apiKey,\n baseUrl: config.baseUrl,\n model: config.model,\n temperature: config.temperature,\n topP: config.topP,\n timeoutMs: config.timeoutMs,\n });\n}\n\nexport function createProviderForRoute(config: TanyaConfig, target: RouteTarget): ChatProvider {\n const adapter = resolveProviderAdapter({ provider: target.provider });\n const envPrefix = target.provider.toUpperCase().replace(/[^A-Z0-9]+/g, \"_\");\n const providerApiKey = process.env[`${envPrefix}_API_KEY`] ?? \"\";\n const providerBaseUrl = process.env[`${envPrefix}_BASE_URL`] ?? \"\";\n const apiKey = target.provider === \"deepseek\"\n ? envValue(process.env, \"DEEPSEEK_API_KEY\") || providerApiKey || config.apiKey\n : providerApiKey || config.apiKey;\n const baseUrl = target.provider === config.provider && config.baseUrl\n ? config.baseUrl\n : providerBaseUrl || adapter.defaultBaseUrl || config.baseUrl;\n\n return new OpenAiCompatibleProvider({\n id: target.provider === \"deepseek\" && target.model === \"deepseek-reasoner\" ? \"deepseek-reasoner\" : target.provider,\n apiKey,\n baseUrl: baseUrl.replace(/\\/$/, \"\"),\n model: target.model,\n temperature: config.temperature,\n topP: config.topP,\n timeoutMs: config.timeoutMs,\n });\n}\n","import { appendFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { exec } from \"node:child_process\";\nimport { join, resolve } from \"node:path\";\nimport { randomBytes } from \"node:crypto\";\nimport type { EventSink } from \"../events/types\";\n\nexport type DispatchMode = \"sequential\" | \"parallel\";\n\nexport type DispatchSubtask = {\n id: string;\n title: string;\n files: string[];\n depends_on: string[];\n tdd?: boolean;\n auto_fix?: boolean;\n};\n\nexport type DispatchPlan = {\n plan: string;\n subtasks: DispatchSubtask[];\n default_test_cmd?: string;\n};\n\nexport type DispatchSubtaskResult = {\n done: true;\n files_changed: string[];\n summary: string;\n unfixed_failures?: VerifyFailure[];\n};\n\nexport type DispatchRunTurn = (prompt: string, meta: { phase: \"plan\" | \"subtask\" | \"complete\"; subtask?: DispatchSubtask }) => Promise<string>;\n\nexport type DispatchCommandResult = {\n exitCode: number;\n stdout: string;\n stderr: string;\n};\n\nexport type DispatchRunCommand = (cmd: string, cwd: string) => Promise<DispatchCommandResult>;\n\nexport type RunPlanAndDispatchOptions = {\n cwd: string;\n prompt: string;\n maxSubtasks?: number;\n mode?: DispatchMode;\n resumeRunID?: string;\n tdd?: boolean;\n testCmd?: string;\n sink?: EventSink;\n runTurn: DispatchRunTurn;\n runCommand?: DispatchRunCommand;\n autoFixVerify?: boolean;\n autoFixWarns?: boolean;\n maxFixIterations?: number;\n readVerifyFailures?: () => Promise<VerifyFailure[]>;\n};\n\nexport type RunPlanAndDispatchResult = {\n runID: string;\n plan: DispatchPlan;\n completed: DispatchSubtaskResult[];\n};\n\nconst ULID_ALPHABET = \"0123456789ABCDEFGHJKMNPQRSTVWXYZ\";\n\nexport type VerifyFailure = {\n type?: \"verify_failure\";\n kind: string;\n severity?: \"error\" | \"warn\" | string;\n description?: string;\n path?: string;\n pattern?: string;\n task_id?: string;\n cmd?: string;\n exit_code?: number;\n output_excerpt?: string;\n matched_at?: string;\n};\n\nexport function generateRunID(now = Date.now()): string {\n let value = now;\n let time = \"\";\n for (let i = 0; i < 10; i += 1) {\n time = ULID_ALPHABET[value % 32] + time;\n value = Math.floor(value / 32);\n }\n const bytes = randomBytes(10);\n let random = \"\";\n for (const byte of bytes) random += ULID_ALPHABET[byte % 32];\n return `${time}${random}`;\n}\n\nexport function buildPlanningPrompt(prompt: string, maxSubtasks: number): string {\n return [\n \"Before writing code, output a JSON plan with this exact shape — nothing else in the response, just the fenced JSON block:\",\n \"```json\",\n \"{\",\n ' \"plan\": \"<one-paragraph summary of what we will build>\",',\n ' \"default_test_cmd\": \"<optional fallback test command for subtasks>\",',\n ' \"subtasks\": [',\n ' {\"id\": \"1\", \"title\": \"...\", \"files\": [\"path/to/a.go\"], \"depends_on\": [], \"tdd\": true, \"auto_fix\": true},',\n ' {\"id\": \"2\", \"title\": \"...\", \"files\": [\"path/to/b.go\"], \"depends_on\": [\"1\"], \"tdd\": false, \"auto_fix\": false}',\n \" ]\",\n \"}\",\n \"```\",\n `Constraints: each subtask should be 1-8 files. Total subtasks <= ${maxSubtasks}. depends_on is a list of subtask IDs that must complete first. auto_fix defaults to true when --auto-fix-verify is enabled.`,\n \"\",\n \"User prompt:\",\n prompt,\n ].join(\"\\n\");\n}\n\nexport function buildSubtaskPrompt(subtask: DispatchSubtask, ordered: DispatchSubtask[], completed: DispatchSubtaskResult[]): string {\n const index = ordered.findIndex((candidate) => candidate.id === subtask.id) + 1;\n const prior = completed.length === 0\n ? \"None.\"\n : completed.map((result, i) => {\n const files = result.files_changed.length > 0 ? ` Files changed: ${result.files_changed.join(\", \")}.` : \"\";\n return `- ${i + 1}. ${result.summary}${files}`;\n }).join(\"\\n\");\n return [\n `Subtask ${index}/${ordered.length}: ${subtask.title}`,\n \"\",\n `Files to touch: ${subtask.files.join(\", \")}`,\n \"\",\n \"Subtasks already complete:\",\n prior,\n \"\",\n \"Write the code. When done, output ONLY a fenced JSON block:\",\n \"```json\",\n '{\"done\": true, \"files_changed\": [\"path/to/file\"], \"summary\": \"...\"}',\n \"```\",\n ].join(\"\\n\");\n}\n\nexport function buildCompletionPrompt(plan: DispatchPlan, completed: DispatchSubtaskResult[]): string {\n return [\n \"All dispatch subtasks are complete. Run the existing verification discipline for this coding step, fix any issues you find, and then report the aggregate result.\",\n \"\",\n `Original plan: ${plan.plan}`,\n \"\",\n \"Completed subtasks:\",\n ...completed.map((result, i) => `- ${i + 1}. ${result.summary} (${result.files_changed.join(\", \") || \"no files reported\"})`),\n ].join(\"\\n\");\n}\n\nexport function parseFencedJSON<T>(text: string): T {\n const fence = /```(?:json)?\\s*([\\s\\S]*?)```/i.exec(text);\n const raw = fence?.[1] ?? text;\n return JSON.parse(raw.trim()) as T;\n}\n\nexport function normalizePlan(plan: DispatchPlan, maxSubtasks: number): DispatchPlan {\n if (!plan || typeof plan.plan !== \"string\" || !Array.isArray(plan.subtasks)) {\n throw new Error(\"dispatch plan must include plan and subtasks\");\n }\n if (plan.subtasks.length === 0) throw new Error(\"dispatch plan must include at least one subtask\");\n if (plan.subtasks.length > maxSubtasks) {\n throw new Error(`dispatch plan has ${plan.subtasks.length} subtasks, exceeding max ${maxSubtasks}`);\n }\n const ids = new Set<string>();\n const subtasks = plan.subtasks.map((task) => {\n if (!task || typeof task.id !== \"string\" || typeof task.title !== \"string\") {\n throw new Error(\"each dispatch subtask must include id and title\");\n }\n if (ids.has(task.id)) throw new Error(`duplicate dispatch subtask id: ${task.id}`);\n ids.add(task.id);\n const files = Array.isArray(task.files) ? task.files.map(String) : [];\n const dependsOn = Array.isArray(task.depends_on) ? task.depends_on.map(String) : [];\n // files is advisory: the planning prompt nudges toward small subtasks and runtime\n // outOfScopeFiles() warns on sprawl. No hard cap — a legit CRUD feature spans many\n // files and a pre-flight throw would abort the whole run.\n const tdd = typeof task.tdd === \"boolean\" ? task.tdd : undefined;\n const autoFix = typeof task.auto_fix === \"boolean\" ? task.auto_fix : undefined;\n return { id: task.id, title: task.title, files, depends_on: dependsOn, ...(tdd !== undefined ? { tdd } : {}), ...(autoFix !== undefined ? { auto_fix: autoFix } : {}) };\n });\n for (const task of subtasks) {\n for (const dep of task.depends_on) {\n if (!ids.has(dep)) throw new Error(`dispatch subtask ${task.id} depends on unknown subtask ${dep}`);\n }\n }\n return { plan: plan.plan, subtasks, ...(typeof plan.default_test_cmd === \"string\" && plan.default_test_cmd.trim() ? { default_test_cmd: plan.default_test_cmd.trim() } : {}) };\n}\n\nexport function topologicalSubtasks(plan: DispatchPlan): DispatchSubtask[] {\n const remaining = new Map(plan.subtasks.map((task) => [task.id, task]));\n const done = new Set<string>();\n const ordered: DispatchSubtask[] = [];\n while (remaining.size > 0) {\n const ready = [...remaining.values()].filter((task) => task.depends_on.every((dep) => done.has(dep)));\n if (ready.length === 0) throw new Error(\"dispatch plan contains a dependency cycle\");\n ready.sort((a, b) => a.id.localeCompare(b.id, undefined, { numeric: true }));\n for (const task of ready) {\n ordered.push(task);\n done.add(task.id);\n remaining.delete(task.id);\n }\n }\n return ordered;\n}\n\nfunction dispatchDir(cwd: string, runID: string): string {\n return resolve(cwd, \".tania\", \"dispatch\", runID);\n}\n\nfunction subtaskResultPath(dir: string, id: string): string {\n return join(dir, `subtask_${id}.json`);\n}\n\nfunction subtaskPhasePath(dir: string, id: string): string {\n return join(dir, `subtask_${id}_phases.jsonl`);\n}\n\nfunction subtaskFixPath(dir: string, id: string): string {\n return join(dir, `subtask_${id}_fixes.jsonl`);\n}\n\nfunction loadCompleted(dir: string, ordered: DispatchSubtask[]): DispatchSubtaskResult[] {\n const completed: DispatchSubtaskResult[] = [];\n for (const task of ordered) {\n const path = subtaskResultPath(dir, task.id);\n if (!existsSync(path)) break;\n completed.push(JSON.parse(readFileSync(path, \"utf8\")) as DispatchSubtaskResult);\n }\n return completed;\n}\n\nfunction recordFailure(dir: string, subtaskID: string, err: unknown): void {\n const message = err instanceof Error ? err.message : String(err);\n appendFileSync(join(dir, \"failures.log\"), `${new Date().toISOString()} subtask=${subtaskID} ${message}\\n`);\n}\n\nfunction appendPhase(dir: string, subtaskID: string, event: Record<string, unknown>): void {\n appendFileSync(subtaskPhasePath(dir, subtaskID), `${JSON.stringify({ at: new Date().toISOString(), ...event })}\\n`);\n}\n\nfunction appendFix(dir: string, subtaskID: string, event: Record<string, unknown>): void {\n appendFileSync(subtaskFixPath(dir, subtaskID), `${JSON.stringify({ at: new Date().toISOString(), ...event })}\\n`);\n}\n\nexport function parseVerifyFailureJSONL(lines: string[]): VerifyFailure[] {\n const failures: VerifyFailure[] = [];\n for (const line of lines) {\n const trimmed = line.trim();\n if (!trimmed) continue;\n let event: unknown;\n try {\n event = JSON.parse(trimmed);\n } catch {\n continue;\n }\n if (!event || typeof event !== \"object\") continue;\n const record = event as Record<string, unknown>;\n if (record.type === \"verify_failure_eof\") break;\n if (record.type !== \"verify_failure\") continue;\n const failure: VerifyFailure = { type: \"verify_failure\", kind: String(record.kind ?? \"\") };\n if (typeof record.severity === \"string\") failure.severity = record.severity;\n if (typeof record.description === \"string\") failure.description = record.description;\n if (typeof record.path === \"string\") failure.path = record.path;\n if (typeof record.pattern === \"string\") failure.pattern = record.pattern;\n if (typeof record.task_id === \"string\") failure.task_id = record.task_id;\n if (typeof record.cmd === \"string\") failure.cmd = record.cmd;\n if (typeof record.exit_code === \"number\") failure.exit_code = record.exit_code;\n if (typeof record.output_excerpt === \"string\") failure.output_excerpt = record.output_excerpt;\n if (typeof record.matched_at === \"string\") failure.matched_at = record.matched_at;\n failures.push(failure);\n }\n return failures.filter((failure) => failure.kind);\n}\n\nexport function buildAutoFixPrompt(failures: VerifyFailure[]): string {\n const lines = [\n `The verify suite ran on your sub-task output and ${failures.length} check(s) failed:`,\n \"\",\n ];\n failures.forEach((failure, index) => {\n lines.push(`Failure ${index + 1}/${failures.length}: ${failure.kind}${failure.path ? ` in ${failure.path}` : \"\"}`);\n if (failure.description) lines.push(` Description: ${failure.description}`);\n if (failure.pattern) lines.push(` Pattern: ${failure.pattern}`);\n if (failure.matched_at) lines.push(` Matched at: ${failure.matched_at}`);\n if (failure.cmd) lines.push(` Cmd: ${failure.cmd}`);\n if (typeof failure.exit_code === \"number\") lines.push(` Exit code: ${failure.exit_code}`);\n if (failure.output_excerpt) lines.push(` Cmd output: ${failure.output_excerpt.slice(0, 2048)}`);\n lines.push(\"\");\n });\n lines.push(\"Fix the implementation. Touch only the files that need to change. Do NOT modify test files unless the failure points at a test file directly.\");\n lines.push('When done, output ONLY a fenced JSON block: {\"done\": true, \"files_changed\": [\"...\"], \"summary\": \"fixed: ...\"}');\n return lines.join(\"\\n\");\n}\n\nfunction failureKey(failure: VerifyFailure): string {\n return [failure.kind, failure.path ?? \"\", failure.pattern ?? \"\", failure.cmd ?? \"\", failure.matched_at ?? \"\"].join(\"\\x1f\");\n}\n\nfunction sameFailureSet(a: VerifyFailure[], b: VerifyFailure[]): boolean {\n if (a.length !== b.length) return false;\n const left = a.map(failureKey).sort();\n const right = b.map(failureKey).sort();\n return left.every((key, i) => key === right[i]);\n}\n\nfunction outOfScopeFiles(subtask: DispatchSubtask, changed: string[]): string[] {\n const allowed = new Set(subtask.files);\n return changed.filter((file) => !allowed.has(file));\n}\n\nasync function runAutoFixLoop(\n options: RunPlanAndDispatchOptions,\n subtask: DispatchSubtask,\n result: DispatchSubtaskResult,\n dir: string,\n): Promise<DispatchSubtaskResult> {\n if (!options.autoFixVerify || subtask.auto_fix === false || !options.readVerifyFailures) return result;\n const max = options.maxFixIterations ?? 5;\n let previous: VerifyFailure[] | undefined;\n let current = (await options.readVerifyFailures()).filter((failure) => options.autoFixWarns || failure.severity !== \"warn\");\n if (current.length === 0) return result;\n for (let iteration = 1; iteration <= max; iteration += 1) {\n if (previous && sameFailureSet(previous, current)) {\n const gaveUp = { ...result, summary: `auto-fix entered a loop at iteration ${iteration}`, unfixed_failures: current };\n appendFix(dir, subtask.id, { iteration, failures_in: current, success: false, loop_detected: true });\n return gaveUp;\n }\n const response = await options.runTurn(buildAutoFixPrompt(current), { phase: \"subtask\", subtask });\n const fixed = parseFencedJSON<DispatchSubtaskResult>(response);\n fixed.files_changed = Array.isArray(fixed.files_changed) ? fixed.files_changed.map(String) : [];\n fixed.summary = typeof fixed.summary === \"string\" ? fixed.summary : \"\";\n appendFix(dir, subtask.id, { iteration, failures_in: current, files_changed_out: fixed.files_changed, success: true });\n previous = current;\n result = fixed;\n current = (await options.readVerifyFailures()).filter((failure) => options.autoFixWarns || failure.severity !== \"warn\");\n if (current.length === 0) {\n writeFileSync(subtaskResultPath(dir, subtask.id), JSON.stringify(result, null, 2));\n return result;\n }\n }\n const gaveUp = { ...result, summary: `auto-fix gave up after ${max} iterations`, unfixed_failures: current };\n appendFix(dir, subtask.id, { iteration: max, failures_in: current, success: false, giveup: true });\n writeFileSync(subtaskResultPath(dir, subtask.id), JSON.stringify(gaveUp, null, 2));\n return gaveUp;\n}\n\ntype RedWritten = {\n phase: \"red_written\";\n test_files?: string[];\n test_cmd?: string;\n};\n\ntype GreenWritten = {\n phase: \"green_written\";\n impl_files?: string[];\n};\n\nexport function buildRedPrompt(subtask: DispatchSubtask, plan: DispatchPlan, cwd: string, cliTestCmd?: string): string {\n const testHint = cliTestCmd || plan.default_test_cmd || inferTestCommand(cwd);\n return [\n `TDD phase 1 of 4 for subtask ${subtask.id}: ${subtask.title}`,\n \"\",\n \"Write or extend the test(s) for this subtask. Do NOT touch implementation files yet.\",\n \"The test must capture the intended behavior precisely.\",\n testHint ? `Use this test command unless the new test requires a narrower one: ${testHint}` : \"Declare the exact test command to run.\",\n \"\",\n \"When done, output ONLY a fenced JSON block:\",\n \"```json\",\n '{\"phase\": \"red_written\", \"test_files\": [\"path/to/test\"], \"test_cmd\": \"go test ./... -count=1\"}',\n \"```\",\n ].join(\"\\n\");\n}\n\nfunction buildRedViolationPrompt(output: DispatchCommandResult, attempt: number): string {\n return [\n \"TDD violation: your test passed before the implementation existed. This means the test isn't testing what you think.\",\n \"Options: (a) tighten the test to actually fail, (b) the implementation already exists and your test is redundant, or (c) the test command isn't running the new test.\",\n `RED attempt ${attempt}/3 passed unexpectedly.`,\n \"Update and output a new {\\\"phase\\\": \\\"red_written\\\", \\\"test_files\\\": [...], \\\"test_cmd\\\": \\\"...\\\"} block.\",\n \"If this is the 3rd failed RED attempt for this subtask, TDD will be abandoned for this subtask and regular dispatch will continue.\",\n \"\",\n trimCommandOutput(output),\n ].join(\"\\n\");\n}\n\nfunction buildGreenPrompt(subtask: DispatchSubtask, redOutput: DispatchCommandResult): string {\n return [\n `TDD phase 3 of 4 for subtask ${subtask.id}: ${subtask.title}`,\n \"\",\n \"The test failed correctly (RED). Now write the implementation.\",\n \"Touch only the files needed to make the test pass. Do NOT modify the test itself.\",\n \"\",\n \"RED output:\",\n trimCommandOutput(redOutput),\n \"\",\n \"When done, output ONLY a fenced JSON block:\",\n \"```json\",\n '{\"phase\": \"green_written\", \"impl_files\": [\"path/to/file\"]}',\n \"```\",\n ].join(\"\\n\");\n}\n\nfunction buildGreenRetryPrompt(output: DispatchCommandResult, attempt: number): string {\n return [\n `Test still failing after GREEN attempt ${attempt}/5.`,\n \"Output:\",\n trimCommandOutput(output),\n \"\",\n \"Diagnose and fix the IMPLEMENTATION (do not weaken the test).\",\n \"Output a new {\\\"phase\\\": \\\"green_written\\\", \\\"impl_files\\\": [...]} block.\",\n ].join(\"\\n\");\n}\n\nfunction trimCommandOutput(output: DispatchCommandResult, max = 6000): string {\n const text = [`exit_code=${output.exitCode}`, output.stdout, output.stderr].filter(Boolean).join(\"\\n\");\n if (text.length <= max) return text;\n return `${text.slice(0, max)}\\n...<trimmed>`;\n}\n\nexport function inferTestCommand(cwd: string): string | undefined {\n if (existsSync(join(cwd, \"go.mod\"))) return \"go test ./... -count=1\";\n if (existsSync(join(cwd, \"package.json\"))) return \"npm test\";\n if (existsSync(join(cwd, \"Cargo.toml\"))) return \"cargo test\";\n if (existsSync(join(cwd, \"requirements.txt\")) || existsSync(join(cwd, \"pyproject.toml\"))) return \"pytest\";\n return undefined;\n}\n\nasync function defaultRunCommand(cmd: string, cwd: string): Promise<DispatchCommandResult> {\n return new Promise((resolveCommand) => {\n exec(cmd, { cwd, maxBuffer: 10 * 1024 * 1024 }, (error, stdout, stderr) => {\n const maybeCode = typeof (error as { code?: unknown } | null)?.code === \"number\" ? (error as { code: number }).code : 0;\n resolveCommand({ exitCode: error ? maybeCode || 1 : 0, stdout, stderr });\n });\n });\n}\n\nfunction resolveTestCommand(options: RunPlanAndDispatchOptions, plan: DispatchPlan, red?: RedWritten): string {\n const declared = red?.test_cmd?.trim();\n if (options.testCmd?.trim()) return options.testCmd.trim();\n if (declared) return declared;\n if (plan.default_test_cmd?.trim()) return plan.default_test_cmd.trim();\n const inferred = inferTestCommand(options.cwd);\n if (inferred) return inferred;\n throw new Error(\"cannot infer test_cmd — declare one in the subtask's red_written JSON or the plan's default_test_cmd\");\n}\n\nasync function runRegularSubtask(\n options: RunPlanAndDispatchOptions,\n subtask: DispatchSubtask,\n ordered: DispatchSubtask[],\n completed: DispatchSubtaskResult[],\n dir: string,\n): Promise<DispatchSubtaskResult> {\n const response = await options.runTurn(buildSubtaskPrompt(subtask, ordered, completed), { phase: \"subtask\", subtask });\n const result = parseFencedJSON<DispatchSubtaskResult>(response);\n if (!result.done) throw new Error(`subtask ${subtask.id} did not report done=true`);\n result.files_changed = Array.isArray(result.files_changed) ? result.files_changed.map(String) : [];\n result.summary = typeof result.summary === \"string\" ? result.summary : \"\";\n writeFileSync(subtaskResultPath(dir, subtask.id), JSON.stringify(result, null, 2));\n return result;\n}\n\nasync function runTDDSubtask(\n options: RunPlanAndDispatchOptions,\n plan: DispatchPlan,\n subtask: DispatchSubtask,\n ordered: DispatchSubtask[],\n completed: DispatchSubtaskResult[],\n dir: string,\n): Promise<DispatchSubtaskResult> {\n const runCommand = options.runCommand ?? defaultRunCommand;\n let red: RedWritten | undefined;\n let redOutput: DispatchCommandResult | undefined;\n let redPrompt = buildRedPrompt(subtask, plan, options.cwd, options.testCmd);\n for (let attempt = 1; attempt <= 3; attempt += 1) {\n appendPhase(dir, subtask.id, { phase: \"red_write\", attempt });\n red = parseFencedJSON<RedWritten>(await options.runTurn(redPrompt, { phase: \"subtask\", subtask }));\n if (red.phase !== \"red_written\") throw new Error(`subtask ${subtask.id} did not report phase=red_written`);\n const testCmd = resolveTestCommand(options, plan, red);\n appendPhase(dir, subtask.id, { phase: \"red_verify\", attempt, test_cmd: testCmd });\n const output = await runCommand(testCmd, options.cwd);\n appendPhase(dir, subtask.id, { phase: \"red_verify_result\", attempt, ok: output.exitCode !== 0, exit_code: output.exitCode, stdout: output.stdout, stderr: output.stderr });\n if (output.exitCode !== 0) {\n redOutput = output;\n break;\n }\n redPrompt = buildRedViolationPrompt(output, attempt);\n }\n if (!redOutput || !red) {\n appendPhase(dir, subtask.id, { phase: \"red_abandoned\", reason: \"test passed before implementation after 3 attempts\" });\n return runRegularSubtask(options, subtask, ordered, completed, dir);\n }\n\n const testCmd = resolveTestCommand(options, plan, red);\n for (let attempt = 1; attempt <= 5; attempt += 1) {\n appendPhase(dir, subtask.id, { phase: \"green_write\", attempt });\n const prompt = attempt === 1 ? buildGreenPrompt(subtask, redOutput) : buildGreenRetryPrompt(redOutput, attempt - 1);\n const green = parseFencedJSON<GreenWritten>(await options.runTurn(prompt, { phase: \"subtask\", subtask }));\n if (green.phase !== \"green_written\") throw new Error(`subtask ${subtask.id} did not report phase=green_written`);\n appendPhase(dir, subtask.id, { phase: \"green_verify\", attempt, test_cmd: testCmd });\n const output = await runCommand(testCmd, options.cwd);\n appendPhase(dir, subtask.id, { phase: \"green_verify_result\", attempt, ok: output.exitCode === 0, exit_code: output.exitCode, stdout: output.stdout, stderr: output.stderr });\n if (output.exitCode === 0) {\n const result: DispatchSubtaskResult = {\n done: true,\n files_changed: Array.isArray(green.impl_files) ? green.impl_files.map(String) : [],\n summary: `TDD subtask ${subtask.id} passed ${testCmd}`,\n };\n writeFileSync(subtaskResultPath(dir, subtask.id), JSON.stringify(result, null, 2));\n return result;\n }\n redOutput = output;\n }\n throw new Error(`subtask ${subtask.id} failed TDD GREEN after 5 attempts`);\n}\n\nexport async function runPlanAndDispatch(options: RunPlanAndDispatchOptions): Promise<RunPlanAndDispatchResult> {\n const maxSubtasks = options.maxSubtasks ?? 12;\n const mode = options.mode ?? \"sequential\";\n if (mode === \"parallel\") throw new Error(\"--dispatch-mode parallel is not implemented yet; use sequential\");\n\n const runID = options.resumeRunID ?? generateRunID();\n const dir = dispatchDir(options.cwd, runID);\n mkdirSync(dir, { recursive: true });\n await options.sink?.({ type: \"status\", message: `Dispatch run: ${runID}` });\n\n let plan: DispatchPlan;\n if (options.resumeRunID) {\n const planPath = join(dir, \"plan.json\");\n if (!existsSync(planPath)) throw new Error(`dispatch run ${runID} has no plan.json`);\n plan = normalizePlan(JSON.parse(readFileSync(planPath, \"utf8\")) as DispatchPlan, maxSubtasks);\n } else {\n const planningResponse = await options.runTurn(buildPlanningPrompt(options.prompt, maxSubtasks), { phase: \"plan\" });\n plan = normalizePlan(parseFencedJSON<DispatchPlan>(planningResponse), maxSubtasks);\n writeFileSync(join(dir, \"plan.json\"), JSON.stringify(plan, null, 2));\n }\n\n const ordered = topologicalSubtasks(plan);\n const completed = loadCompleted(dir, ordered);\n\n for (const subtask of ordered.slice(completed.length)) {\n await options.sink?.({ type: \"subtask_start\", subtask_id: subtask.id, title: subtask.title, files: subtask.files });\n try {\n let result = options.tdd && subtask.tdd !== false\n ? await runTDDSubtask(options, plan, subtask, ordered, completed, dir)\n : await runRegularSubtask(options, subtask, ordered, completed, dir);\n result = await runAutoFixLoop(options, subtask, result, dir);\n const outOfScope = outOfScopeFiles(subtask, result.files_changed);\n if (outOfScope.length > 0) {\n await options.sink?.({\n type: \"status\",\n message: `Subtask ${subtask.id} changed files outside its declared scope: ${outOfScope.join(\", \")}`,\n });\n }\n completed.push(result);\n await options.sink?.({\n type: \"subtask_done\",\n subtask_id: subtask.id,\n files_changed: result.files_changed,\n summary: result.summary,\n ok: !result.unfixed_failures?.some((failure) => failure.severity !== \"warn\"),\n });\n } catch (err) {\n recordFailure(dir, subtask.id, err);\n await options.sink?.({ type: \"subtask_done\", subtask_id: subtask.id, files_changed: [], summary: err instanceof Error ? err.message : String(err), ok: false });\n throw err;\n }\n }\n\n await options.runTurn(buildCompletionPrompt(plan, completed), { phase: \"complete\" });\n return { runID, plan, completed };\n}\n","import { spawnSync } from \"node:child_process\";\nimport { existsSync, readFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport type { TanyaFinalManifest } from \"./runner\";\n\nconst POST_CHECK_TIMEOUT_MS = 25_000;\n\nfunction hasPassingVerification(manifest: TanyaFinalManifest, pattern: RegExp): boolean {\n return manifest.verification.some(\n (line) => /->\\s*passed\\b/i.test(line) && pattern.test(line),\n );\n}\n\nfunction readPackageScripts(cwd: string): Record<string, string> {\n try {\n const raw = readFileSync(join(cwd, \"package.json\"), \"utf8\");\n const parsed = JSON.parse(raw) as { scripts?: Record<string, string> };\n return parsed.scripts ?? {};\n } catch {\n return {};\n }\n}\n\nfunction readPackageManager(cwd: string): \"npm\" | \"pnpm\" | \"yarn\" | \"bun\" {\n try {\n const raw = readFileSync(join(cwd, \"package.json\"), \"utf8\");\n const parsed = JSON.parse(raw) as { packageManager?: string };\n const packageManager = parsed.packageManager?.split(\"@\")[0];\n if (packageManager === \"pnpm\" || packageManager === \"yarn\" || packageManager === \"bun\") return packageManager;\n } catch {\n // fall through to lockfile detection\n }\n if (existsSync(join(cwd, \"pnpm-lock.yaml\"))) return \"pnpm\";\n if (existsSync(join(cwd, \"yarn.lock\"))) return \"yarn\";\n if (existsSync(join(cwd, \"bun.lockb\")) || existsSync(join(cwd, \"bun.lock\"))) return \"bun\";\n return \"npm\";\n}\n\nfunction packageScriptCommand(\n packageManager: \"npm\" | \"pnpm\" | \"yarn\" | \"bun\",\n script: string,\n): { cmd: string; args: string[] } {\n if (packageManager === \"yarn\") return { cmd: \"yarn\", args: [script] };\n return { cmd: packageManager, args: [\"run\", script] };\n}\n\nfunction runCommand(\n cmd: string,\n args: string[],\n cwd: string,\n timeoutMs: number,\n): { exitCode: number; output: string } {\n const result = spawnSync(cmd, args, {\n cwd,\n encoding: \"utf8\",\n timeout: timeoutMs,\n shell: false,\n });\n const output = `${result.stdout ?? \"\"}${result.stderr ?? \"\"}`.trim();\n const exitCode = result.status ?? (result.error ? 1 : 0);\n return { exitCode, output };\n}\n\nfunction parseTypeScriptErrors(output: string): string[] {\n return output\n .split(/\\r?\\n/)\n .filter((line) => /\\.tsx?:\\d+:\\d+\\s*-?\\s*error\\s+TS\\d+:/i.test(line) || /error TS\\d+:/i.test(line))\n .slice(0, 5);\n}\n\nexport async function detectPostRunBlockers(\n cwd: string,\n manifest: TanyaFinalManifest,\n): Promise<string[]> {\n const blockers: string[] = [];\n const tsconfigExists =\n existsSync(join(cwd, \"tsconfig.json\")) || existsSync(join(cwd, \"tsconfig.base.json\"));\n const scripts = readPackageScripts(cwd);\n const packageManager = readPackageManager(cwd);\n\n if (tsconfigExists && !hasPassingVerification(manifest, /tsc|typecheck|type-check/i)) {\n const typecheckCommand = scripts.typecheck\n ? packageScriptCommand(packageManager, \"typecheck\")\n : { cmd: \"npx\", args: [\"tsc\", \"--noEmit\", \"--pretty\", \"false\"] };\n const { exitCode, output } = runCommand(typecheckCommand.cmd, typecheckCommand.args, cwd, POST_CHECK_TIMEOUT_MS);\n if (exitCode !== 0) {\n const errorLines = parseTypeScriptErrors(output);\n const summary = errorLines.length > 0\n ? `TypeScript errors after run:\\n${errorLines.map((line) => ` ${line}`).join(\"\\n\")}`\n : \"TypeScript compilation failed (post-run check)\";\n blockers.push(summary);\n }\n }\n\n if (scripts.test && !hasPassingVerification(manifest, /\\btest\\b/i)) {\n const testCommand = packageScriptCommand(packageManager, \"test\");\n const { exitCode } = runCommand(testCommand.cmd, testCommand.args, cwd, POST_CHECK_TIMEOUT_MS);\n if (exitCode !== 0) {\n blockers.push(\"Tests failed after run (post-run check)\");\n }\n }\n\n return blockers;\n}\n","import type { ChatProvider } from \"../providers/types\";\n\nconst PLAN_SYSTEM = [\n \"You are a senior engineer producing a concise execution plan for a coding agent.\",\n \"Given a task description and a workspace export map, output ONLY a structured plan.\",\n \"Format:\",\n \"Files to read first: <comma-separated list>\",\n \"Files to modify: <comma-separated list>\",\n \"Key steps:\",\n \"1. <step>\",\n \"2. <step>\",\n \"...\",\n \"Verification: <command to run>\",\n \"Do not write any code. Do not explain. Output the plan only.\",\n].join(\"\\n\");\n\nexport async function buildExecutionPlan(\n reasonerProvider: ChatProvider,\n task: string,\n exportMap: string,\n): Promise<string> {\n const userContent = exportMap\n ? `Workspace export map:\\n${exportMap}\\n\\nTask: ${task}`\n : `Task: ${task}`;\n\n let plan = \"\";\n for await (const delta of reasonerProvider.streamChat({\n messages: [\n { role: \"system\", content: PLAN_SYSTEM },\n { role: \"user\", content: userContent },\n ],\n tools: [],\n temperature: 0,\n maxTokens: 512,\n })) {\n if (delta.content) plan += delta.content;\n }\n return plan.trim();\n}\n","import type { ChatProvider } from \"../providers/types\";\n\nconst REVIEW_SYSTEM = [\n \"You are a senior code reviewer. You will be given a task description and the diff of changes made.\",\n \"Review only what was changed. Be concise. Flag only real issues.\",\n \"Output format:\",\n \"## Review\",\n \"**Verdict:** LGTM | NEEDS CHANGES\",\n \"\",\n \"**Issues:** (list only if verdict is NEEDS CHANGES)\",\n \"- <file>:<line> — <issue>\",\n \"\",\n \"**Suggestions:** (optional minor improvements, max 3)\",\n \"- <suggestion>\",\n \"\",\n \"Do not praise the code. Do not explain what the code does. Only flag problems.\",\n].join(\"\\n\");\n\nexport async function reviewChanges(\n provider: ChatProvider,\n task: string,\n diff: string,\n): Promise<string> {\n if (!diff.trim()) return \"## Review\\n**Verdict:** LGTM\\n\\nNo changes to review.\";\n\n let review = \"\";\n for await (const delta of provider.streamChat({\n messages: [\n { role: \"system\", content: REVIEW_SYSTEM },\n {\n role: \"user\",\n content: `Task: ${task}\\n\\nDiff:\\n\\`\\`\\`diff\\n${diff.slice(0, 8000)}\\n\\`\\`\\``,\n },\n ],\n tools: [],\n temperature: 0,\n maxTokens: 600,\n })) {\n if (delta.content) review += delta.content;\n }\n return review.trim();\n}\n","import type { TanyaRunContext } from \"../context/runContext\";\n\nfunction boundedTurnBudget(value: number): number {\n return Math.max(1, Math.min(300, Math.floor(value)));\n}\n\nexport function phaseAwareMaxTurns(runContext: TanyaRunContext | undefined, prompt: string, override?: number): number | undefined {\n if (override !== undefined) return boundedTurnBudget(override);\n const text = [\n runContext?.task?.title,\n runContext?.task?.summary,\n ...(runContext?.instructions ?? []),\n prompt,\n ].filter(Boolean).join(\"\\n\").toLowerCase();\n const isCoding = runContext?.task?.kind === \"coding\" ||\n /\\b(?:coding|go-backend-|initialize\\s+go\\s+backend|backend\\s+step|pre-seeded tasks)\\b/.test(text);\n if (!isCoding) return undefined;\n if (/\\b(?:foundation|go-backend-foundation)\\b/.test(text)) {\n return 300;\n }\n if (/\\b(?:setup|auth|initialize\\s+go\\s+backend|go-backend-(?:init|auth))\\b/.test(text)) {\n return 200;\n }\n if (/\\b(?:testing|verify|verification|go-backend-verify)\\b/.test(text)) {\n return 50;\n }\n if (/\\b(?:feature|addon|add-on|go-backend-(?:feature|addon))\\b/.test(text)) {\n return 100;\n }\n return 100;\n}\n","import type { TanyaEvent } from \"../events/types\";\nimport { envValue } from \"../config/envCompat\";\nimport { estimateRunCost } from \"../memory/runLogs\";\n\nexport type LiveRouteStep = \"planning\" | \"tool_call\" | \"synthesis\" | \"verification\" | \"reasoning\" | \"unknown\";\n\nexport type LiveStatus = {\n provider: string;\n model: string;\n routeStep?: LiveRouteStep;\n spend: {\n usd: number;\n inputTokens: number;\n outputTokens: number;\n reasoningTokens?: number;\n };\n contextPressure?: { used: number; cap: number };\n activeTools: Array<{ id: string; tool: string; startedAt: string }>;\n activeChildren: Array<{ subRunId: string; workspace: string; startedAt: string }>;\n pendingPermission?: { tool: string; matchedRule?: string };\n lastEscalation?: { from: string; to: string; reason: string; at: string };\n lastCompaction?: { type: string; removedTokens: number; at: string };\n promptBudgetWarning?: { droppedSections: string[]; at: string };\n};\n\nexport type LiveStatusController = {\n snapshot(): LiveStatus;\n consume(event: TanyaEvent): void;\n};\n\nexport type LiveStatusRenderer = {\n consume(event: TanyaEvent): void;\n render(): void;\n snapshot(): LiveStatus;\n enabled(): boolean;\n};\n\nexport function createLiveStatus(options: {\n now?: () => Date;\n estimateUsd?: (provider: string, model: string, inputTokens: number, outputTokens: number) => number;\n} = {}): LiveStatusController {\n const now = options.now ?? (() => new Date());\n const activeTools = new Map<string, { id: string; tool: string; startedAt: string }>();\n const activeChildren = new Map<string, { subRunId: string; workspace: string; startedAt: string }>();\n let provider = \"\";\n let model = \"\";\n let routeStep: LiveRouteStep | undefined;\n let spend: LiveStatus[\"spend\"] = { usd: 0, inputTokens: 0, outputTokens: 0 };\n let contextPressure: LiveStatus[\"contextPressure\"];\n let pendingPermission: LiveStatus[\"pendingPermission\"];\n let lastEscalation: LiveStatus[\"lastEscalation\"];\n let lastCompaction: LiveStatus[\"lastCompaction\"];\n let promptBudgetWarning: LiveStatus[\"promptBudgetWarning\"];\n\n function stamp(): string {\n return now().toISOString();\n }\n\n return {\n snapshot() {\n return {\n provider,\n model,\n ...(routeStep ? { routeStep } : {}),\n spend: { ...spend },\n ...(contextPressure ? { contextPressure: { ...contextPressure } } : {}),\n activeTools: [...activeTools.values()].sort((a, b) => a.startedAt.localeCompare(b.startedAt) || a.id.localeCompare(b.id)),\n activeChildren: [...activeChildren.values()].sort((a, b) => a.startedAt.localeCompare(b.startedAt) || a.subRunId.localeCompare(b.subRunId)),\n ...(pendingPermission ? { pendingPermission: { ...pendingPermission } } : {}),\n ...(lastEscalation ? { lastEscalation: { ...lastEscalation } } : {}),\n ...(lastCompaction ? { lastCompaction: { ...lastCompaction } } : {}),\n ...(promptBudgetWarning ? { promptBudgetWarning: { ...promptBudgetWarning, droppedSections: [...promptBudgetWarning.droppedSections] } } : {}),\n };\n },\n consume(event) {\n switch (event.type) {\n case \"model_routed\":\n provider = event.provider;\n model = event.model;\n routeStep = event.stepType;\n break;\n case \"tool_call\":\n activeTools.set(event.id, { id: event.id, tool: event.tool, startedAt: stamp() });\n break;\n case \"tool_result\":\n activeTools.delete(event.id);\n break;\n case \"subtask_started\":\n activeChildren.set(event.subRunId, {\n subRunId: event.subRunId,\n workspace: event.workspace,\n startedAt: stamp(),\n });\n break;\n case \"subtask_completed\":\n activeChildren.delete(event.subRunId);\n break;\n case \"permission_request\":\n pendingPermission = {\n tool: event.tool,\n ...(event.matchedRule ? { matchedRule: event.matchedRule } : {}),\n };\n break;\n case \"permission_decision\":\n pendingPermission = undefined;\n break;\n case \"escalation_event\":\n lastEscalation = {\n from: `${event.from.provider}:${event.from.model}`,\n to: `${event.to.provider}:${event.to.model}`,\n reason: event.reason,\n at: stamp(),\n };\n break;\n case \"compact_event\":\n lastCompaction = {\n type: event.compactType,\n removedTokens: event.removedTokens,\n at: stamp(),\n };\n break;\n case \"prompt_budget_exceeded\":\n contextPressure = { used: event.totalTokens, cap: event.cap };\n promptBudgetWarning = { droppedSections: [...event.droppedSections], at: stamp() };\n break;\n case \"message_start\":\n promptBudgetWarning = undefined;\n break;\n case \"final\": {\n const metrics = event.metrics;\n if (!metrics) break;\n const inputTokens = metrics.promptTokens ?? 0;\n const outputTokens = metrics.completionTokens ?? 0;\n const reasoningTokens = (metrics as { reasoningTokens?: number }).reasoningTokens ?? 0;\n spend = {\n usd: spend.usd + (options.estimateUsd?.(provider, model, inputTokens, outputTokens) ?? 0),\n inputTokens: spend.inputTokens + inputTokens,\n outputTokens: spend.outputTokens + outputTokens,\n ...(reasoningTokens > 0\n ? { reasoningTokens: (spend.reasoningTokens ?? 0) + reasoningTokens }\n : spend.reasoningTokens !== undefined\n ? { reasoningTokens: spend.reasoningTokens }\n : {}),\n };\n break;\n }\n default:\n break;\n }\n },\n };\n}\n\nexport function formatLiveStatus(status: LiveStatus, options: {\n now?: Date;\n columns?: number;\n fadeMs?: number;\n} = {}): string {\n const now = options.now ?? new Date();\n const fadeMs = options.fadeMs ?? 5_000;\n const promptBudget = status.promptBudgetWarning;\n const escalation = status.lastEscalation && withinWindow(status.lastEscalation.at, now, fadeMs)\n ? status.lastEscalation\n : undefined;\n const compaction = status.lastCompaction && withinWindow(status.lastCompaction.at, now, fadeMs)\n ? status.lastCompaction\n : undefined;\n\n if (status.pendingPermission) {\n return fitLine(`[awaiting permission: ${status.pendingPermission.tool}${status.pendingPermission.matchedRule ? ` (${status.pendingPermission.matchedRule})` : \"\"}]`, options.columns);\n }\n if (promptBudget) {\n return fitLine(`[prompt budget: dropped ${promptBudget.droppedSections.join(\", \")}]`, options.columns);\n }\n if (escalation) {\n return fitLine(`[escalated ${escalation.from}->${escalation.to}: ${escalation.reason}]`, options.columns);\n }\n if (compaction) {\n return fitLine(`[compacted ~${compactTokenCount(compaction.removedTokens)} tokens via ${compaction.type}]`, options.columns);\n }\n\n const route = status.provider && status.model ? `${status.provider}:${status.model}` : \"no route\";\n const step = status.routeStep ?? \"unknown\";\n const tools = `${status.activeTools.length} tool${status.activeTools.length === 1 ? \"\" : \"s\"}`;\n const children = `${status.activeChildren.length} child${status.activeChildren.length === 1 ? \"\" : \"ren\"}`;\n const context = status.contextPressure ? ` | ctx ${compactTokenCount(status.contextPressure.used)}/${compactTokenCount(status.contextPressure.cap)}` : \"\";\n return fitLine(`[${route} | ${step} | ${formatUsd(status.spend.usd)} | ${tools} | ${children}${context}]`, options.columns);\n}\n\nexport function createLiveStatusRenderer(options: {\n stream?: NodeJS.WritableStream;\n env?: Record<string, string | undefined>;\n now?: () => Date;\n columns?: number;\n} = {}): LiveStatusRenderer {\n const stream = options.stream ?? process.stdout;\n const now = options.now ?? (() => new Date());\n const status = createLiveStatus({\n now,\n estimateUsd: (provider, model, inputTokens, outputTokens) => estimateRunCost({\n provider,\n model,\n promptTokens: inputTokens,\n completionTokens: outputTokens,\n }).usd ?? 0,\n });\n\n function enabled(): boolean {\n return liveStatusEnabled({\n stream,\n ...(options.env ? { env: options.env } : {}),\n });\n }\n\n function render(): void {\n if (!enabled()) return;\n const columns = options.columns ?? terminalColumns(stream);\n const line = formatLiveStatus(status.snapshot(), { now: now(), columns });\n // Escape sequences are guarded by liveStatusEnabled(), which requires a TTY.\n stream.write(`\\x1b7\\r\\x1b[2K${line}\\x1b8`);\n }\n\n return {\n consume(event) {\n status.consume(event);\n if (shouldRenderLiveStatus(event)) render();\n },\n render,\n snapshot: status.snapshot,\n enabled,\n };\n}\n\nexport function liveStatusEnabled(options: {\n stream?: NodeJS.WritableStream;\n env?: Record<string, string | undefined>;\n} = {}): boolean {\n const stream = options.stream ?? process.stdout;\n if ((stream as { isTTY?: boolean }).isTTY !== true) return false;\n const raw = envValue(options.env ?? process.env, \"TANYA_LIVE_STATUS\").trim();\n return !/^(0|false|off|no)$/i.test(raw);\n}\n\nfunction shouldRenderLiveStatus(event: TanyaEvent): boolean {\n return ![\n \"message_start\",\n \"message_delta\",\n \"tool_progress\",\n \"command_invoked\",\n ].includes(event.type);\n}\n\nfunction withinWindow(iso: string, now: Date, windowMs: number): boolean {\n const ts = Date.parse(iso);\n return Number.isFinite(ts) && now.getTime() - ts <= windowMs;\n}\n\nfunction terminalColumns(stream: NodeJS.WritableStream): number {\n const columns = (stream as { columns?: number }).columns;\n return typeof columns === \"number\" && Number.isFinite(columns) && columns > 0 ? columns : 80;\n}\n\nfunction fitLine(line: string, columns = 80): string {\n const width = Math.max(20, columns);\n if (line.length <= width) return line;\n return `${line.slice(0, Math.max(0, width - 3))}...`;\n}\n\nfunction compactTokenCount(tokens: number): string {\n if (tokens >= 1_000_000) return `${Math.round(tokens / 100_000) / 10}m`;\n if (tokens >= 1_000) return `${Math.round(tokens / 100) / 10}k`;\n return `${Math.max(0, Math.round(tokens))}`;\n}\n\nfunction formatUsd(usd: number): string {\n if (usd > 0 && usd < 0.001) return \"<$0.001\";\n return `$${usd.toFixed(3)}`;\n}\n","import type { EventSink } from \"../events/types\";\nimport { runIdDepth } from \"../agent/subAgentContext\";\nimport { createLiveStatusRenderer, type LiveStatusRenderer } from \"./liveStatus\";\nimport { envValue } from \"../config/envCompat\";\nimport { formatClock, formatElapsed } from \"../utils/formatElapsed\";\n\nconst toolGlyph = \">\";\nconst ansiDimItalic = \"\\x1b[2m\\x1b[3m\";\nconst ansiReset = \"\\x1b[0m\";\nconst reasoningPreviewLimit = 600;\n\nfunction eventPrefix(event: { subRunId?: string }): string {\n if (!event.subRunId) return \"\";\n return `${\" \".repeat(Math.max(0, runIdDepth(event.subRunId) - 1))}↳ `;\n}\n\nexport function createHumanSink(stream: NodeJS.WritableStream = process.stdout, options: {\n liveStatus?: boolean;\n env?: Record<string, string | undefined>;\n now?: () => Date;\n columns?: number;\n} = {}): EventSink {\n let inMessage = false;\n let messageHasText = false;\n let reasoningStartedAt: number | null = null;\n let reasoningChars = 0;\n let reasoningCollapsed = false;\n const hideReasoning = /^(1|true|yes|on)$/i.test(envValue(options.env ?? process.env, \"TANYA_HIDE_REASONING\").trim());\n const liveStatus: LiveStatusRenderer | null = options.liveStatus\n ? createLiveStatusRenderer({\n stream,\n ...(options.env ? { env: options.env } : {}),\n ...(options.now ? { now: options.now } : {}),\n ...(options.columns !== undefined ? { columns: options.columns } : {}),\n })\n : null;\n\n function finishReasoning(prefix: string): void {\n if (reasoningStartedAt === null || hideReasoning) return;\n const seconds = (Date.now() - reasoningStartedAt) / 1000;\n stream.write(`\\n${prefix}${ansiDimItalic}thinking for ${seconds.toFixed(1)}s...${ansiReset}\\n`);\n reasoningStartedAt = null;\n reasoningChars = 0;\n reasoningCollapsed = false;\n }\n\n const sink: EventSink = (event) => {\n const prefix = eventPrefix(event);\n switch (event.type) {\n case \"status\":\n stream.write(`\\n${prefix}${event.message}\\n`);\n break;\n case \"message_start\":\n inMessage = true;\n messageHasText = false;\n reasoningStartedAt = null;\n reasoningChars = 0;\n reasoningCollapsed = false;\n stream.write(`\\n${prefix}${\n event.headingStartedAt !== undefined ? `[${formatClock(new Date(event.headingStartedAt))}] ` : \"\"\n }${event.elapsedMs !== undefined ? `Tanya · ${formatElapsed(event.elapsedMs)}:` : \"Tanya:\"} `);\n break;\n case \"message_delta\":\n if (reasoningStartedAt !== null) finishReasoning(prefix);\n messageHasText = true;\n stream.write(event.text);\n break;\n case \"message_end\":\n finishReasoning(prefix);\n if (inMessage) stream.write(\"\\n\");\n inMessage = false;\n messageHasText = false;\n break;\n case \"reasoning_chunk\":\n if (hideReasoning) break;\n stream.write(ansiDimItalic);\n if (reasoningStartedAt === null) {\n reasoningStartedAt = Date.now();\n if (inMessage && !messageHasText) {\n stream.write(\"thinking... \");\n } else {\n stream.write(`\\n${prefix}thinking... `);\n }\n }\n reasoningChars += event.content.length;\n if (reasoningChars <= reasoningPreviewLimit) {\n stream.write(event.content);\n } else if (!reasoningCollapsed) {\n stream.write(\" ...\");\n reasoningCollapsed = true;\n }\n stream.write(ansiReset);\n break;\n case \"reasoning_truncated\":\n if (inMessage) stream.write(\"\\n\");\n inMessage = false;\n stream.write(`${prefix}[reasoning truncated at ${event.capTokens} tokens; used ${event.usedTokens}]\\n`);\n break;\n case \"tool_call\":\n finishReasoning(prefix);\n if (inMessage) stream.write(\"\\n\");\n inMessage = false;\n stream.write(`\\n${prefix}${toolGlyph} ${event.tool}\\n`);\n stream.write(`${prefix} input: ${JSON.stringify(event.input)}\\n`);\n break;\n case \"tool_result\":\n stream.write(`${prefix} ${event.ok ? \"ok\" : \"error\"}: ${event.summary}\\n`);\n break;\n case \"tool_progress\":\n finishReasoning(prefix);\n if (inMessage) stream.write(\"\\n\");\n inMessage = false;\n stream.write(`${prefix} ${event.stream}: ${event.chunk}${event.chunk.endsWith(\"\\n\") ? \"\" : \"\\n\"}`);\n break;\n case \"tool_cancel_requested\":\n stream.write(`${prefix} cancelling: ${event.tool ?? event.toolCallId}\\n`);\n break;\n case \"tool_cancelled\":\n stream.write(`${prefix} cancelled: ${event.tool ?? event.toolCallId}\\n`);\n break;\n case \"permission_request\":\n stream.write(` permission requested: ${event.tool}${event.matchedRule ? ` (${event.matchedRule})` : \"\"}\\n`);\n break;\n case \"permission_decision\":\n stream.write(` permission ${event.decision}: ${event.matchedRule ?? event.source}\\n`);\n break;\n case \"command_invoked\":\n break;\n case \"tool_call_parse_warning\":\n stream.write(` warning: malformed tool call (${event.reason})\\n`);\n break;\n case \"schema_flatten_warning\":\n stream.write(` warning: flattened schema${event.tool ? ` for ${event.tool}` : \"\"} (${event.reason})\\n`);\n break;\n case \"provider_throttle\":\n stream.write(`\\nProvider ${event.provider} throttled; waiting ${Math.ceil(event.waitMs / 1000)}s before retry ${event.attempt}.\\n`);\n break;\n case \"model_routed\":\n stream.write(`${prefix} route: ${event.stepType} -> ${event.provider}/${event.model}${event.cacheImpact === \"miss\" ? \" (cache miss)\" : \"\"}\\n`);\n break;\n case \"escalation_event\":\n stream.write(`${prefix} escalation: ${event.from.provider}/${event.from.model} -> ${event.to.provider}/${event.to.model} (${event.reason})\\n`);\n break;\n case \"compact_event\":\n finishReasoning(prefix);\n if (inMessage) stream.write(\"\\n\");\n inMessage = false;\n stream.write(`[compaction: removed ~${Math.ceil(event.removedTokens / 1000)}k tokens via ${event.compactType}]\\n`);\n break;\n case \"prompt_budget_exceeded\":\n finishReasoning(prefix);\n if (inMessage) stream.write(\"\\n\");\n inMessage = false;\n stream.write(`${prefix}[prompt budget: dropped ${event.droppedSections.join(\", \")}; ${event.totalTokens} tokens > cap ${event.cap}]\\n`);\n break;\n case \"subtask_started\":\n finishReasoning(prefix);\n if (inMessage) stream.write(\"\\n\");\n inMessage = false;\n stream.write(`\\n${prefix}subtask started: ${event.subRunId} (${event.workspace})\\n`);\n break;\n case \"subtask_completed\":\n finishReasoning(prefix);\n if (inMessage) stream.write(\"\\n\");\n inMessage = false;\n stream.write(`${prefix}subtask ${event.verdict}: ${event.summary}\\n`);\n break;\n case \"subtask_start\":\n if (inMessage) stream.write(\"\\n\");\n inMessage = false;\n stream.write(`\\nSubtask ${event.subtask_id}: ${event.title}\\n`);\n if (event.files.length) stream.write(` files: ${event.files.join(\", \")}\\n`);\n break;\n case \"subtask_done\":\n stream.write(` ${event.ok ? \"done\" : \"failed\"}: ${event.summary}\\n`);\n break;\n case \"final\":\n if (!event.suppressHumanMessage) {\n stream.write(`\\n${event.message.trim()}\\n`);\n }\n if (event.files?.length) stream.write(`Files: ${event.files.join(\", \")}\\n`);\n break;\n case \"error\":\n stream.write(`\\nError: ${event.message}${event.detail ? `\\n${event.detail}` : \"\"}\\n`);\n break;\n default:\n break;\n }\n liveStatus?.consume(event);\n };\n (sink as EventSink & { tanyaSinkKind?: \"human\" }).tanyaSinkKind = \"human\";\n return sink;\n}\n","import { existsSync } from \"node:fs\";\nimport { mkdir, readFile, readdir, rm, writeFile } from \"node:fs/promises\";\nimport { dirname, isAbsolute, join, resolve } from \"node:path\";\nimport { spawn, spawnSync } from \"node:child_process\";\nimport sharp from \"sharp\";\nimport { envValue } from \"../config/envCompat\";\nimport { resolveInsideWorkspace } from \"../safety/workspace\";\n\ntype LayerAnimation = \"fade-up\" | \"type-in\" | \"scale-in\" | \"hold\" | \"fade-in\" | \"slide-up\" | \"subtle-parallax\";\ntype SceneTransition = \"cut\" | \"crossfade\" | \"slide-left\" | \"slide-up\" | \"push\";\n\nexport interface FullAdRenderSpec {\n version: 1;\n canvas: {\n width: number;\n height: number;\n fps: number;\n safeArea?: { x: number; y: number; width: number; height: number };\n };\n project?: { id: string; name: string; appName: string; platform: string };\n brand?: {\n primary: string;\n secondary: string;\n accent: string;\n background: string;\n iconAssetId?: string;\n };\n assets: Array<{\n id: string;\n type: \"image\" | \"gif\" | \"video\";\n mimeType: string;\n src: string;\n width?: number;\n height?: number;\n durationMs?: number | null;\n }>;\n scenes: FullAdSceneSpec[];\n}\n\nexport interface FullAdSceneSpec {\n id: string;\n order: number;\n durationMs: number;\n backgroundPreset: string;\n backgroundAssetId?: string;\n layoutPreset?: string;\n transition: SceneTransition;\n layers: FullAdLayerSpec[];\n}\n\nexport type FullAdLayerSpec = FullAdTextLayerSpec | FullAdMediaLayerSpec;\n\nexport interface FullAdBaseLayerSpec {\n id: string;\n x: number;\n y: number;\n width: number;\n height: number;\n zIndex: number;\n startTimeMs: number;\n endTimeMs: number | null;\n opacity: number;\n}\n\nexport interface FullAdTextLayerSpec extends FullAdBaseLayerSpec {\n type: \"text\";\n text: string;\n role: \"title\" | \"subtitle\" | \"caption\" | \"cta\" | \"badge\";\n color: string;\n fontSize: number;\n fontWeight: number;\n align: \"center\";\n animation: LayerAnimation;\n}\n\nexport interface FullAdMediaLayerSpec extends FullAdBaseLayerSpec {\n type: \"image\" | \"video\";\n assetId: string;\n fit: \"cover\" | \"contain\" | \"fill\";\n borderRadius: number;\n shadow: boolean;\n animation: LayerAnimation;\n}\n\nexport interface RenderAdOptions {\n input: string;\n outputDir?: string;\n basename?: string;\n formats?: Array<\"mp4\" | \"poster\">;\n ffmpegPath?: string;\n}\n\nexport interface RenderAdResult {\n mp4Path?: string;\n posterPath?: string;\n durationMs: number;\n frameCount: number;\n width: number;\n height: number;\n warnings: string[];\n renderSpec: FullAdRenderSpec;\n}\n\ninterface MediaFrames {\n frames: Buffer[];\n fps: number;\n}\n\nfunction findExecutable(name: string, explicit?: string): string {\n if (explicit) return explicit;\n const result = spawnSync(\"which\", [name], { encoding: \"utf8\" });\n return result.status === 0 && result.stdout.trim() ? result.stdout.trim() : name;\n}\n\nfunction run(command: string, args: string[], cwd: string): void {\n const result = spawnSync(command, args, { cwd, stdio: \"pipe\", encoding: \"utf8\" });\n if (result.status !== 0) {\n throw new Error(`${command} ${args.join(\" \")}\\n${result.stderr || result.stdout}`);\n }\n}\n\nfunction easeOut(t: number): number {\n const v = Math.max(0, Math.min(1, t));\n return 1 - Math.pow(1 - v, 3);\n}\n\nconst SCENE_TRANSITION_DURATION_MS = 560;\nconst SCENE_TRANSITION_TRAVEL_PX = 52;\n\nfunction escapeXml(value: string): string {\n return value.replaceAll(\"&\", \"&\").replaceAll(\"<\", \"<\").replaceAll(\">\", \">\").replaceAll('\"', \""\");\n}\n\nfunction backgroundColor(preset: string): string {\n if (preset === \"solid-light\") return \"#f5f5f7\";\n if (preset === \"gradient-brand\") return \"#101628\";\n if (preset === \"gradient-dark\") return \"#10111d\";\n if (preset === \"blur-asset\") return \"#0a0a0c\";\n return \"#0a0a0c\";\n}\n\nfunction renderBrand(spec: FullAdRenderSpec): Required<NonNullable<FullAdRenderSpec[\"brand\"]>> {\n return {\n primary: spec.brand?.primary ?? \"#8C4CEB\",\n secondary: spec.brand?.secondary ?? \"#6B33CC\",\n accent: spec.brand?.accent ?? \"#F59E0B\",\n background: spec.brand?.background ?? \"#080A12\",\n iconAssetId: spec.brand?.iconAssetId ?? \"\",\n };\n}\n\nfunction backgroundSvg(spec: FullAdRenderSpec, scene: FullAdSceneSpec): Buffer {\n const { width, height } = spec.canvas;\n const brand = renderBrand(spec);\n const base = scene.backgroundPreset === \"gradient-brand\" ? brand.background : backgroundColor(scene.backgroundPreset);\n const brandGlow = scene.backgroundPreset === \"gradient-brand\" ? brand.primary : \"#4f8eff\";\n const secondaryGlow = scene.backgroundPreset === \"gradient-brand\" ? brand.secondary : brandGlow;\n const warmGlow = scene.backgroundPreset === \"gradient-brand\" ? brand.accent : \"#f59e0b\";\n const svg = `<svg width=\"${width}\" height=\"${height}\" xmlns=\"http://www.w3.org/2000/svg\">\n <defs>\n <radialGradient id=\"g1\" cx=\"28%\" cy=\"12%\" r=\"64%\">\n <stop offset=\"0%\" stop-color=\"${brandGlow}\" stop-opacity=\"0.34\"/>\n <stop offset=\"54%\" stop-color=\"${brandGlow}\" stop-opacity=\"0.08\"/>\n <stop offset=\"100%\" stop-color=\"${base}\" stop-opacity=\"0\"/>\n </radialGradient>\n <radialGradient id=\"g2\" cx=\"88%\" cy=\"86%\" r=\"54%\">\n <stop offset=\"0%\" stop-color=\"${warmGlow}\" stop-opacity=\"0.18\"/>\n <stop offset=\"100%\" stop-color=\"${base}\" stop-opacity=\"0\"/>\n </radialGradient>\n <radialGradient id=\"g3\" cx=\"50%\" cy=\"42%\" r=\"58%\">\n <stop offset=\"0%\" stop-color=\"${secondaryGlow}\" stop-opacity=\"${scene.backgroundPreset === \"gradient-brand\" ? \"0.2\" : \"0.06\"}\"/>\n <stop offset=\"100%\" stop-color=\"${base}\" stop-opacity=\"0\"/>\n </radialGradient>\n <linearGradient id=\"v\" x1=\"0\" y1=\"0\" x2=\"0\" y2=\"1\">\n <stop offset=\"0%\" stop-color=\"#ffffff\" stop-opacity=\"0.04\"/>\n <stop offset=\"46%\" stop-color=\"#000000\" stop-opacity=\"0\"/>\n <stop offset=\"100%\" stop-color=\"#000000\" stop-opacity=\"0.28\"/>\n </linearGradient>\n </defs>\n <rect width=\"100%\" height=\"100%\" fill=\"${base}\"/>\n <rect width=\"100%\" height=\"100%\" fill=\"url(#g1)\"/>\n <rect width=\"100%\" height=\"100%\" fill=\"url(#g2)\"/>\n <rect width=\"100%\" height=\"100%\" fill=\"url(#g3)\"/>\n <rect width=\"100%\" height=\"100%\" fill=\"url(#v)\"/>\n </svg>`;\n return Buffer.from(svg);\n}\n\nfunction resolveAssetPath(src: string, workspace: string): string {\n if (src.startsWith(\"file://\")) return new URL(src).pathname;\n if (isAbsolute(src)) return src;\n return resolveInsideWorkspace(workspace, src);\n}\n\nasync function loadStaticFrame(src: string, workspace: string): Promise<Buffer> {\n if (src.startsWith(\"data:\")) {\n return Buffer.from(src.split(\",\")[1] ?? \"\", \"base64\");\n }\n if (src.startsWith(\"http://\") || src.startsWith(\"https://\")) {\n const response = await fetch(src);\n if (!response.ok) throw new Error(`Unable to fetch asset ${src}: ${response.status}`);\n return Buffer.from(await response.arrayBuffer());\n }\n return readFile(resolveAssetPath(src, workspace));\n}\n\nasync function extractVideoFrames(params: {\n src: string;\n workspace: string;\n outDir: string;\n fps: number;\n ffmpegPath: string;\n}): Promise<Buffer[]> {\n await mkdir(params.outDir, { recursive: true });\n const input = resolveAssetPath(params.src, params.workspace);\n run(params.ffmpegPath, [\n \"-y\",\n \"-i\",\n input,\n \"-vf\",\n `fps=${params.fps}`,\n join(params.outDir, \"frame-%05d.png\"),\n ], params.workspace);\n const files = (await readdir(params.outDir)).filter((file) => file.endsWith(\".png\")).sort();\n return Promise.all(files.map((file) => readFile(join(params.outDir, file))));\n}\n\nasync function buildMediaFrames(spec: FullAdRenderSpec, workspace: string, tmpDir: string, ffmpegPath: string, warnings: string[]): Promise<Map<string, MediaFrames>> {\n const media = new Map<string, MediaFrames>();\n for (const asset of spec.assets) {\n try {\n if (asset.type === \"video\" || asset.type === \"gif\") {\n const frames = await extractVideoFrames({\n src: asset.src,\n workspace,\n outDir: join(tmpDir, \"media\", asset.id),\n fps: spec.canvas.fps,\n ffmpegPath,\n });\n media.set(asset.id, { frames: frames.length ? frames : [await sharp(await loadStaticFrame(asset.src, workspace)).png().toBuffer()], fps: spec.canvas.fps });\n } else {\n media.set(asset.id, { frames: [await sharp(await loadStaticFrame(asset.src, workspace)).png().toBuffer()], fps: 1 });\n }\n } catch (error) {\n warnings.push(`Asset ${asset.id} could not be decoded: ${error instanceof Error ? error.message : String(error)}`);\n }\n }\n return media;\n}\n\nfunction wrapText(text: string, maxChars: number, maxLines = 4): string[] {\n const words = text.trim().split(/\\s+/).filter(Boolean);\n const lines: string[] = [];\n let current = \"\";\n for (const word of words) {\n const next = current ? `${current} ${word}` : word;\n if (next.length > maxChars && current) {\n lines.push(current);\n current = word;\n } else {\n current = next;\n }\n }\n if (current) lines.push(current);\n return lines.slice(0, maxLines);\n}\n\nfunction renderTextSvg(layer: FullAdTextLayerSpec, progress: number, brand?: FullAdRenderSpec[\"brand\"]): Buffer {\n const resolvedBrand = {\n primary: brand?.primary ?? \"#8C4CEB\",\n secondary: brand?.secondary ?? \"#6B33CC\",\n accent: brand?.accent ?? \"#F59E0B\",\n };\n const visibleChars = layer.animation === \"type-in\"\n ? Math.max(1, Math.ceil(layer.text.length * easeOut(progress)))\n : layer.text.length;\n const text = layer.text.slice(0, visibleChars);\n const maxChars = Math.max(8, Math.floor(layer.width / Math.max(12, layer.fontSize * 0.55)));\n const maxLines = layer.role === \"badge\" ? 6 : 4;\n const lines = wrapText(text, maxChars, maxLines);\n const fontSize = Math.max(24, Math.min(layer.fontSize, Math.floor(layer.height / Math.max(1.4, lines.length * 1.18))));\n const lineHeight = Math.round(fontSize * 1.16);\n const startY = Math.round((layer.height - lineHeight * lines.length) / 2 + fontSize * 0.88);\n const tspans = lines.map((line, index) =>\n `<tspan x=\"50%\" y=\"${startY + index * lineHeight}\">${escapeXml(line)}</tspan>`,\n ).join(\"\");\n const glowOpacity = layer.role === \"title\" || layer.role === \"cta\" ? 0.28 : 0.12;\n const chrome = layer.role === \"cta\"\n ? `<linearGradient id=\"ctaFill\" x1=\"0\" y1=\"0\" x2=\"1\" y2=\"1\">\n <stop offset=\"0%\" stop-color=\"${resolvedBrand.primary}\"/>\n <stop offset=\"100%\" stop-color=\"${resolvedBrand.secondary}\"/>\n </linearGradient>`\n : layer.role === \"badge\" || layer.role === \"caption\"\n ? `<linearGradient id=\"badgeFill\" x1=\"0\" y1=\"0\" x2=\"1\" y2=\"0\">\n <stop offset=\"0%\" stop-color=\"${resolvedBrand.accent}\" stop-opacity=\"0.2\"/>\n <stop offset=\"100%\" stop-color=\"${resolvedBrand.primary}\" stop-opacity=\"0.14\"/>\n </linearGradient>`\n : \"\";\n const rect = layer.role === \"cta\"\n ? `<rect x=\"2\" y=\"2\" width=\"${Math.round(layer.width) - 4}\" height=\"${Math.round(layer.height) - 4}\" rx=\"${Math.round(layer.height / 2)}\" fill=\"url(#ctaFill)\" stroke=\"rgba(255,255,255,0.22)\" stroke-width=\"2\"/>`\n : layer.role === \"badge\" || layer.role === \"caption\"\n ? `<rect x=\"2\" y=\"6\" width=\"${Math.round(layer.width) - 4}\" height=\"${Math.round(layer.height) - 12}\" rx=\"${Math.round((layer.height - 12) / 2)}\" fill=\"url(#badgeFill)\" stroke=\"${resolvedBrand.accent}\" stroke-opacity=\"0.34\" stroke-width=\"1.5\"/>`\n : \"\";\n const svg = `<svg width=\"${Math.round(layer.width)}\" height=\"${Math.round(layer.height)}\" xmlns=\"http://www.w3.org/2000/svg\">\n <defs>\n ${chrome}\n <filter id=\"softShadow\" x=\"-20%\" y=\"-20%\" width=\"140%\" height=\"160%\">\n <feDropShadow dx=\"0\" dy=\"10\" stdDeviation=\"10\" flood-color=\"#000000\" flood-opacity=\"${glowOpacity}\"/>\n </filter>\n </defs>\n ${rect}\n <text text-anchor=\"middle\" font-family=\"-apple-system, BlinkMacSystemFont, Inter, Helvetica, Arial, sans-serif\"\n font-size=\"${fontSize}\" font-weight=\"${layer.fontWeight}\" fill=\"${escapeXml(layer.color)}\" filter=\"url(#softShadow)\">${tspans}</text>\n </svg>`;\n return Buffer.from(svg);\n}\n\nasync function roundedMask(width: number, height: number, radius: number): Promise<Buffer> {\n const r = Math.max(0, Math.min(radius, Math.floor(Math.min(width, height) / 2)));\n return Buffer.from(`<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"${width}\" height=\"${height}\"><rect width=\"${width}\" height=\"${height}\" rx=\"${r}\" fill=\"#fff\"/></svg>`);\n}\n\nasync function renderMediaLayer(layer: FullAdMediaLayerSpec, frame: Buffer): Promise<Buffer> {\n const width = Math.max(1, Math.round(layer.width));\n const height = Math.max(1, Math.round(layer.height));\n const resized = sharp(frame)\n .resize(width, height, {\n fit: layer.fit === \"contain\" ? \"inside\" : layer.fit === \"fill\" ? \"fill\" : \"cover\",\n position: \"center\",\n background: { r: 0, g: 0, b: 0, alpha: 0 },\n })\n .ensureAlpha();\n const png = await resized.png().toBuffer();\n if (!layer.borderRadius) return png;\n return sharp(png).composite([{ input: await roundedMask(width, height, layer.borderRadius), blend: \"dest-in\" }]).png().toBuffer();\n}\n\nasync function shadowLayer(width: number, height: number, radius: number): Promise<Buffer> {\n const mask = await roundedMask(width, height, radius);\n return sharp({\n create: {\n width,\n height,\n channels: 4,\n background: { r: 0, g: 0, b: 0, alpha: 0.52 },\n },\n })\n .composite([{ input: mask, blend: \"dest-in\" }])\n .blur(18)\n .extend({ top: 24, bottom: 24, left: 24, right: 24, background: { r: 0, g: 0, b: 0, alpha: 0 } })\n .png()\n .toBuffer();\n}\n\nasync function scaleOverlay(input: Buffer, scale: number): Promise<{ input: Buffer; dx: number; dy: number }> {\n if (Math.abs(scale - 1) < 0.001) return { input, dx: 0, dy: 0 };\n const meta = await sharp(input).metadata();\n const width = Math.max(1, Math.round((meta.width ?? 1) * scale));\n const height = Math.max(1, Math.round((meta.height ?? 1) * scale));\n return {\n input: await sharp(input).resize(width, height).png().toBuffer(),\n dx: Math.round(((meta.width ?? width) - width) / 2),\n dy: Math.round(((meta.height ?? height) - height) / 2),\n };\n}\n\nfunction layerTransform(layer: FullAdLayerSpec, localMs: number): { opacity: number; dx: number; dy: number; scale: number } {\n const progress = easeOut((localMs - layer.startTimeMs) / 360);\n const baseOpacity = layer.opacity ?? 1;\n if (layer.animation === \"hold\") return { opacity: baseOpacity, dx: 0, dy: 0, scale: 1 };\n if (layer.animation === \"fade-up\" || layer.animation === \"slide-up\") {\n return { opacity: baseOpacity * progress, dx: 0, dy: (1 - progress) * 34, scale: 1 };\n }\n if (layer.animation === \"scale-in\") {\n return { opacity: baseOpacity * progress, dx: 0, dy: 0, scale: 0.965 + progress * 0.035 };\n }\n if (layer.animation === \"subtle-parallax\") {\n return { opacity: baseOpacity * progress, dx: 0, dy: Math.sin(localMs / 1000) * 8, scale: 1.02 };\n }\n return { opacity: baseOpacity * progress, dx: 0, dy: 0, scale: 1 };\n}\n\nfunction sceneTransform(scene: FullAdSceneSpec, localMs: number): { opacity: number; dx: number; dy: number; scale: number } {\n const progress = easeOut(localMs / SCENE_TRANSITION_DURATION_MS);\n if (scene.transition === \"cut\") return { opacity: 1, dx: 0, dy: 0, scale: 1 };\n if (scene.transition === \"slide-left\" || scene.transition === \"push\") return { opacity: 1, dx: (1 - progress) * SCENE_TRANSITION_TRAVEL_PX, dy: 0, scale: 1 };\n if (scene.transition === \"slide-up\") return { opacity: 1, dx: 0, dy: (1 - progress) * SCENE_TRANSITION_TRAVEL_PX, scale: 1 };\n return { opacity: progress, dx: 0, dy: 0, scale: 1 };\n}\n\nasync function renderFrame(spec: FullAdRenderSpec, scene: FullAdSceneSpec, mediaFrames: Map<string, MediaFrames>, frameInScene: number): Promise<Buffer> {\n const fps = spec.canvas.fps;\n const localMs = (frameInScene / fps) * 1000;\n const sceneFx = sceneTransform(scene, localMs);\n const overlays: sharp.OverlayOptions[] = [];\n const sorted = [...scene.layers].sort((a, b) => a.zIndex - b.zIndex);\n for (const layer of sorted) {\n const end = layer.endTimeMs ?? scene.durationMs;\n if (localMs < layer.startTimeMs || localMs >= end) continue;\n const fx = layerTransform(layer, localMs);\n const opacity = Math.max(0, Math.min(1, fx.opacity * sceneFx.opacity));\n if (opacity <= 0.001) continue;\n if (layer.type === \"text\") {\n let textPng = await sharp(renderTextSvg(layer, (localMs - layer.startTimeMs) / 520, spec.brand)).png().toBuffer();\n const scaled = await scaleOverlay(textPng, fx.scale * sceneFx.scale);\n textPng = scaled.input;\n if (opacity < 0.999) textPng = await sharp(textPng).linear(opacity, 0).png().toBuffer();\n overlays.push({\n input: textPng,\n left: Math.round(layer.x + fx.dx + sceneFx.dx + scaled.dx),\n top: Math.round(layer.y + fx.dy + sceneFx.dy + scaled.dy),\n });\n continue;\n }\n const frames = mediaFrames.get(layer.assetId);\n if (!frames?.frames.length) continue;\n const elapsed = Math.max(0, localMs - layer.startTimeMs);\n const sourceIndex = frames.frames.length === 1\n ? 0\n : Math.floor((elapsed / 1000) * frames.fps) % frames.frames.length;\n let mediaPng = await renderMediaLayer(layer, frames.frames[sourceIndex]!);\n const scaled = await scaleOverlay(mediaPng, fx.scale * sceneFx.scale);\n mediaPng = scaled.input;\n if (opacity < 0.999) mediaPng = await sharp(mediaPng).linear(opacity, 0).png().toBuffer();\n if (layer.shadow) {\n const shadow = await shadowLayer(Math.round(layer.width), Math.round(layer.height), layer.borderRadius);\n const scaledShadow = await scaleOverlay(shadow, fx.scale * sceneFx.scale);\n overlays.push({\n input: scaledShadow.input,\n left: Math.round(layer.x + fx.dx + sceneFx.dx + scaled.dx - 24 + scaledShadow.dx),\n top: Math.round(layer.y + fx.dy + sceneFx.dy + scaled.dy - 2 + scaledShadow.dy),\n });\n }\n overlays.push({\n input: mediaPng,\n left: Math.round(layer.x + fx.dx + sceneFx.dx + scaled.dx),\n top: Math.round(layer.y + fx.dy + sceneFx.dy + scaled.dy),\n });\n }\n\n const backgroundFrame = scene.backgroundAssetId ? mediaFrames.get(scene.backgroundAssetId)?.frames[0] : null;\n let image = backgroundFrame\n ? sharp(backgroundFrame).resize(spec.canvas.width, spec.canvas.height, { fit: \"cover\" })\n : sharp(backgroundSvg(spec, scene));\n if (overlays.length) image = image.composite(overlays);\n return image.png({ compressionLevel: 1 }).toBuffer();\n}\n\nfunction parseSpec(value: unknown): FullAdRenderSpec {\n const spec = value as FullAdRenderSpec;\n if (!spec || spec.version !== 1 || !spec.canvas || !Array.isArray(spec.scenes) || !Array.isArray(spec.assets)) {\n throw new Error(\"Invalid full-ad render spec.\");\n }\n if (spec.canvas.width !== 1080 || spec.canvas.height !== 1920) {\n throw new Error(\"Full-ad render spec must use a 1080x1920 canvas.\");\n }\n if (!Number.isFinite(spec.canvas.fps) || spec.canvas.fps < 1 || spec.canvas.fps > 60) {\n throw new Error(\"Full-ad render spec fps must be between 1 and 60.\");\n }\n return spec;\n}\n\nexport async function renderFullAd(options: RenderAdOptions, workspace: string): Promise<RenderAdResult> {\n const inputPath = isAbsolute(options.input) ? options.input : resolveInsideWorkspace(workspace, options.input);\n const spec = parseSpec(JSON.parse(await readFile(inputPath, \"utf8\")));\n const outputDir = resolveInsideWorkspace(workspace, options.outputDir ?? \"tanya-video-ads\");\n const basename = (options.basename ?? `full-ad-${Date.now()}`).replace(/[^a-zA-Z0-9._-]+/g, \"-\");\n const formats = options.formats?.length ? options.formats : [\"mp4\", \"poster\"];\n const ffmpegPath = findExecutable(\"ffmpeg\", options.ffmpegPath ?? envValue({}, \"TANYA_FFMPEG_PATH\"));\n const tmpRoot = resolveInsideWorkspace(workspace, \".tania/tmp\");\n const tmpDir = await fsMkdtemp(join(tmpRoot, \"tanya-render-ad-\"));\n const frameDir = join(tmpDir, \"frames\");\n const warnings: string[] = [];\n await mkdir(frameDir, { recursive: true });\n await mkdir(outputDir, { recursive: true });\n const mediaFrames = await buildMediaFrames(spec, workspace, tmpDir, ffmpegPath, warnings);\n\n let frameIndex = 0;\n const scenes = [...spec.scenes].sort((a, b) => a.order - b.order);\n for (const scene of scenes) {\n const frameCount = Math.max(1, Math.round((scene.durationMs / 1000) * spec.canvas.fps));\n for (let i = 0; i < frameCount; i += 1) {\n const frame = await renderFrame(spec, scene, mediaFrames, i);\n await writeFile(\n join(frameDir, `frame_${String(frameIndex).padStart(6, \"0\")}.jpg`),\n await sharp(frame).jpeg({ quality: 84, mozjpeg: true }).toBuffer(),\n );\n frameIndex += 1;\n }\n }\n\n const result: RenderAdResult = {\n durationMs: scenes.reduce((sum, scene) => sum + scene.durationMs, 0),\n frameCount: frameIndex,\n width: spec.canvas.width,\n height: spec.canvas.height,\n warnings,\n renderSpec: spec,\n };\n\n if (formats.includes(\"poster\")) {\n const posterPath = join(outputDir, `${basename}-poster.png`);\n await sharp(await readFile(join(frameDir, \"frame_000000.jpg\"))).png().toFile(posterPath);\n result.posterPath = posterPath;\n }\n\n if (formats.includes(\"mp4\")) {\n const mp4Path = join(outputDir, `${basename}.mp4`);\n run(ffmpegPath, [\n \"-y\",\n \"-framerate\",\n String(spec.canvas.fps),\n \"-i\",\n join(frameDir, \"frame_%06d.jpg\"),\n \"-c:v\",\n \"libx264\",\n \"-pix_fmt\",\n \"yuv420p\",\n \"-preset\",\n \"fast\",\n \"-crf\",\n \"23\",\n \"-movflags\",\n \"+faststart\",\n mp4Path,\n ], workspace);\n result.mp4Path = mp4Path;\n }\n\n await rm(tmpDir, { recursive: true, force: true }).catch(() => {});\n return result;\n}\n\nasync function fsMkdtemp(prefix: string): Promise<string> {\n const { mkdtemp } = await import(\"node:fs/promises\");\n await mkdir(dirname(prefix), { recursive: true });\n return mkdtemp(prefix);\n}\n","import { readFileSync } from \"node:fs\";\nimport { discoverIntegrationEntries } from \"../integrations/discovery\";\n\nexport type GoldenTaskProfile = {\n id: string;\n title: string;\n platform: \"ios\" | \"android\" | \"backend\" | \"cross-platform\";\n purpose: string;\n requiredCapabilities: string[];\n};\n\nexport type IntegrationGoldenProfilesFile =\n | GoldenTaskProfile\n | GoldenTaskProfile[]\n | { profiles: GoldenTaskProfile[] };\n\nconst profilePlatforms = new Set<GoldenTaskProfile[\"platform\"]>([\"ios\", \"android\", \"backend\", \"cross-platform\"]);\n\nfunction isStringArray(value: unknown): value is string[] {\n return Array.isArray(value) && value.every((item) => typeof item === \"string\");\n}\n\nfunction isGoldenTaskProfile(value: unknown): value is GoldenTaskProfile {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) return false;\n const profile = value as Record<string, unknown>;\n return typeof profile.id === \"string\" &&\n typeof profile.title === \"string\" &&\n typeof profile.platform === \"string\" &&\n profilePlatforms.has(profile.platform as GoldenTaskProfile[\"platform\"]) &&\n typeof profile.purpose === \"string\" &&\n isStringArray(profile.requiredCapabilities);\n}\n\nfunction readJson(path: string): unknown {\n try {\n return JSON.parse(readFileSync(path, \"utf8\"));\n } catch {\n return null;\n }\n}\n\nfunction parseIntegrationGoldenProfiles(path: string): GoldenTaskProfile[] {\n const parsed = readJson(path);\n const profiles = Array.isArray(parsed)\n ? parsed\n : parsed && typeof parsed === \"object\" && Array.isArray((parsed as { profiles?: unknown }).profiles)\n ? (parsed as { profiles: unknown[] }).profiles\n : [parsed];\n const valid = profiles.filter(isGoldenTaskProfile);\n if (valid.length !== profiles.length) {\n console.warn(`[golden] Skipping invalid integration profile data: ${path}`);\n }\n return valid;\n}\n\nexport const GENERIC_BENCHMARK_PROFILES: GoldenTaskProfile[] = [\n {\n id: \"tanya.low.search-replace\",\n title: \"Low - Targeted Search Replace\",\n platform: \"cross-platform\",\n purpose: \"Update one existing source file with a precise replacement and verify the marker.\",\n requiredCapabilities: [\"read before edit\", \"search_replace\", \"bounded verification\"],\n },\n {\n id: \"tanya.low.new-helper\",\n title: \"Low - New Helper File\",\n platform: \"cross-platform\",\n purpose: \"Create a small helper module and verify it exists with expected content.\",\n requiredCapabilities: [\"write_file\", \"final report\", \"bounded verification\"],\n },\n {\n id: \"tanya.low.config-update\",\n title: \"Low - Config Update\",\n platform: \"cross-platform\",\n purpose: \"Update a simple JSON-like config file without touching unrelated files.\",\n requiredCapabilities: [\"targeted edit\", \"changed-file reporting\", \"bounded verification\"],\n },\n {\n id: \"tanya.low.readme-update\",\n title: \"Low - README Update\",\n platform: \"cross-platform\",\n purpose: \"Append a concise documentation note and verify the note is present.\",\n requiredCapabilities: [\"documentation edit\", \"artifact reuse none\", \"bounded verification\"],\n },\n {\n id: \"tanya.low.package-script\",\n title: \"Low - Package Script\",\n platform: \"cross-platform\",\n purpose: \"Add a package script while preserving existing package metadata.\",\n requiredCapabilities: [\"JSON edit\", \"package script reporting\", \"bounded verification\"],\n },\n {\n id: \"tanya.medium.service-module\",\n title: \"Medium - Service Module\",\n platform: \"cross-platform\",\n purpose: \"Create a service module and matching index export in a small multi-file change.\",\n requiredCapabilities: [\"multi-file edit\", \"verification\", \"complete report\"],\n },\n {\n id: \"tanya.medium.test-harness\",\n title: \"Medium - Test Harness\",\n platform: \"cross-platform\",\n purpose: \"Add a tiny executable test harness and verify it runs.\",\n requiredCapabilities: [\"test file creation\", \"run_command\", \"complete report\"],\n },\n {\n id: \"tanya.medium.artifact-component\",\n title: \"Medium - Artifact Component\",\n platform: \"cross-platform\",\n purpose: \"Read a reusable UI artifact and adapt it into a project component.\",\n requiredCapabilities: [\"artifact read\", \"artifact provenance\", \"multi-file report\"],\n },\n {\n id: \"tanya.medium.artifact-service\",\n title: \"Medium - Artifact Service\",\n platform: \"backend\",\n purpose: \"Read a reusable service artifact and adapt it into a project helper.\",\n requiredCapabilities: [\"artifact read\", \"artifact provenance\", \"bounded verification\"],\n },\n {\n id: \"tanya.medium.dirty-worktree\",\n title: \"Medium - Dirty Worktree\",\n platform: \"cross-platform\",\n purpose: \"Complete a task in a repo that already has unrelated uncommitted changes.\",\n requiredCapabilities: [\"git snapshot\", \"unrelated dirty preservation\", \"final report\"],\n },\n {\n id: \"tanya.medium.report-repair\",\n title: \"Medium - Report Repair\",\n platform: \"cross-platform\",\n purpose: \"Recover when the model initially omits the required coding final report.\",\n requiredCapabilities: [\"final report reminder\", \"repair loop\", \"verification preservation\"],\n },\n {\n id: \"tanya.medium.multi-file\",\n title: \"Medium - Multi-File Feature\",\n platform: \"cross-platform\",\n purpose: \"Create coordinated source and docs changes and verify both outputs.\",\n requiredCapabilities: [\"multi-file edit\", \"changed-file reporting\", \"bounded verification\"],\n },\n {\n id: \"tanya.medium.package-manager\",\n title: \"Medium - Package Manager Script\",\n platform: \"cross-platform\",\n purpose: \"Use a workspace script path that also exercises post-check package-manager detection.\",\n requiredCapabilities: [\"package metadata\", \"script verification\", \"post-check readiness\"],\n },\n {\n id: \"tanya.medium.context-aware\",\n title: \"Medium - Context-Aware Edit\",\n platform: \"cross-platform\",\n purpose: \"Read caller context before editing and preserve that provenance in the run.\",\n requiredCapabilities: [\"context read\", \"context provenance\", \"complete report\"],\n },\n {\n id: \"tanya.medium.existing-tests\",\n title: \"Medium - Existing Tests\",\n platform: \"cross-platform\",\n purpose: \"Modify implementation while running an existing local verification script.\",\n requiredCapabilities: [\"existing test command\", \"verification reporting\", \"changed-file reporting\"],\n },\n {\n id: \"tanya.medium.dependency-install\",\n title: \"Medium - Dependency Install\",\n platform: \"cross-platform\",\n purpose: \"Update package metadata and lockfile-style state while verifying dependency intent without network access.\",\n requiredCapabilities: [\"package manifest update\", \"lockfile update\", \"bounded verification\"],\n },\n {\n id: \"tanya.medium.framework-migration\",\n title: \"Medium - Framework Migration\",\n platform: \"cross-platform\",\n purpose: \"Move a small legacy page into an app-router-style layout while preserving a compatibility entrypoint.\",\n requiredCapabilities: [\"framework convention\", \"multi-file migration\", \"changed-file reporting\"],\n },\n {\n id: \"tanya.medium.failing-test-repair\",\n title: \"Medium - Failing Test Repair\",\n platform: \"cross-platform\",\n purpose: \"Observe a failing verification, repair the implementation, and rerun the same check successfully.\",\n requiredCapabilities: [\"failed verification recovery\", \"targeted edit\", \"verification rerun\"],\n },\n {\n id: \"tanya.medium.frontend-smoke\",\n title: \"Medium - Frontend Smoke\",\n platform: \"cross-platform\",\n purpose: \"Create a minimal component, styles, and smoke check that verifies rendered content markers.\",\n requiredCapabilities: [\"frontend files\", \"visual smoke proxy\", \"bounded verification\"],\n },\n {\n id: \"tanya.medium.run-log-history\",\n title: \"Medium - Usage Metrics Run Log\",\n platform: \"cross-platform\",\n purpose: \"Complete a normal edit while emitting usage counts that should be persisted to .tania/runs.\",\n requiredCapabilities: [\"usage metrics\", \"run log persistence\", \"history visibility\"],\n },\n {\n id: \"tanya.medium.streaming-long-tool\",\n title: \"Medium - Streaming Long Tool\",\n platform: \"cross-platform\",\n purpose: \"Run a >10s shell verification that streams progress while preserving the final tool result contract.\",\n requiredCapabilities: [\"tool_progress\", \"long-running run_shell\", \"provider-history isolation\"],\n },\n {\n id: \"tanya.medium.compaction-boundary\",\n title: \"Medium - Compaction Boundary\",\n platform: \"cross-platform\",\n purpose: \"Recover from a synthetic context-window failure mid-run and preserve the final verifier verdict.\",\n requiredCapabilities: [\"ContextWindowExceededError\", \"auto-compact retry\", \"archive-backed verifier surface\"],\n },\n {\n id: \"tanya.medium.edit-block-fuzzy\",\n title: \"Medium - Fuzzy Edit Block\",\n platform: \"cross-platform\",\n purpose: \"Recover a cheap-provider-style near-match with permission-gated fuzzy edit blocks while preserving verifier verdicts.\",\n requiredCapabilities: [\"edit_block\", \"fuzzy recovery\", \"permission-gated edit\", \"verifier parity\"],\n },\n];\n\nexport const BUILT_IN_GOLDEN_TASK_PROFILES: GoldenTaskProfile[] = [\n ...GENERIC_BENCHMARK_PROFILES,\n];\n\nexport function loadIntegrationGoldenTaskProfiles(): GoldenTaskProfile[] {\n return discoverIntegrationEntries(\"golden\")\n .filter((entry) => entry.path.toLowerCase().endsWith(\".json\"))\n .flatMap((entry) => parseIntegrationGoldenProfiles(entry.path));\n}\n\nexport function loadGoldenTaskProfiles(): GoldenTaskProfile[] {\n const seen = new Set(BUILT_IN_GOLDEN_TASK_PROFILES.map((profile) => profile.id));\n const profiles = [...BUILT_IN_GOLDEN_TASK_PROFILES];\n for (const profile of loadIntegrationGoldenTaskProfiles()) {\n if (seen.has(profile.id)) continue;\n seen.add(profile.id);\n profiles.push(profile);\n }\n return profiles;\n}\n","import { execFile } from \"node:child_process\";\nimport { mkdtemp, mkdir, writeFile } from \"node:fs/promises\";\nimport { tmpdir } from \"node:os\";\nimport { join } from \"node:path\";\nimport { promisify } from \"node:util\";\nimport { runAgent } from \"../agent/runner\";\nimport type { TanyaRunContext } from \"../context/runContext\";\nimport type { TanyaEvent } from \"../events/types\";\nimport { ContextWindowExceededError, type ChatDelta, type ChatProvider, type ChatRequest, type ToolCall } from \"../providers/types\";\nimport { loadGoldenTaskProfiles, type GoldenTaskProfile } from \"./profiles\";\n\ntype GoldenTaskFixture = {\n workspace: string;\n prompt: string;\n runContext: TanyaRunContext;\n provider: ChatProvider;\n};\n\ntype GenericBenchmarkSpec = {\n id: string;\n targetFiles: Array<{ path: string; content: string }>;\n prompt: string;\n preFiles?: Array<{ path: string; content: string }>;\n useArtifact?: boolean;\n useContext?: boolean;\n useSearchReplace?: boolean;\n dirtyWorktree?: boolean;\n reportRepair?: boolean;\n preVerifyBeforeEdit?: boolean;\n usage?: { promptTokens: number; completionTokens: number };\n};\n\nexport type GoldenRunResult = {\n profile: GoldenTaskProfile;\n workspace: string;\n passed: boolean;\n finalText: string;\n problems: string[];\n turns: number;\n};\n\nfunction toolCall(id: string, name: string, args: unknown): ToolCall {\n return {\n id,\n type: \"function\",\n function: {\n name,\n arguments: JSON.stringify(args),\n },\n };\n}\n\nfunction scriptedProvider(id: string, turns: ChatDelta[]): ChatProvider & { requests: ChatRequest[] } {\n const requests: ChatRequest[] = [];\n return {\n id: `golden:${id}`,\n model: \"scripted\",\n requests,\n async *streamChat(input: ChatRequest) {\n requests.push({ ...input, messages: [...input.messages] });\n yield turns[Math.min(requests.length - 1, turns.length - 1)] ?? { content: \"\" };\n },\n };\n}\n\nconst execFileAsync = promisify(execFile);\n\nasync function createBaseWorkspace(profileId: string): Promise<string> {\n return mkdtemp(join(tmpdir(), `tanya-golden-${profileId.replace(/[^a-z0-9]+/gi, \"-\")}-`));\n}\n\nconst GENERIC_BENCHMARK_SPECS: Record<string, GenericBenchmarkSpec> = {\n \"tanya.low.search-replace\": {\n id: \"tanya.low.search-replace\",\n prompt: \"Replace the pending marker in an existing helper and verify it.\",\n useSearchReplace: true,\n targetFiles: [{ path: \"src/searchReplaceTarget.ts\", content: \"export const status = 'search-replace-ready';\\n\" }],\n },\n \"tanya.low.new-helper\": {\n id: \"tanya.low.new-helper\",\n prompt: \"Create a small helper file and verify it.\",\n targetFiles: [{ path: \"src/newHelper.ts\", content: \"export function newHelper() { return 'new-helper-ready'; }\\n\" }],\n },\n \"tanya.low.config-update\": {\n id: \"tanya.low.config-update\",\n prompt: \"Update a small config file with the requested marker.\",\n useSearchReplace: true,\n targetFiles: [{ path: \"config/settings.json\", content: \"{\\n \\\"mode\\\": \\\"config-update-ready\\\"\\n}\\n\" }],\n },\n \"tanya.low.readme-update\": {\n id: \"tanya.low.readme-update\",\n prompt: \"Append the benchmark readiness note to the README.\",\n useSearchReplace: true,\n targetFiles: [{ path: \"README.md\", content: \"# Demo\\n\\nBenchmark note: readme-update-ready\\n\" }],\n },\n \"tanya.low.package-script\": {\n id: \"tanya.low.package-script\",\n prompt: \"Add a benchmark package script while preserving package metadata.\",\n targetFiles: [{ path: \"package.json\", content: \"{\\n \\\"name\\\": \\\"benchmark-fixture\\\",\\n \\\"scripts\\\": {\\n \\\"benchmark:ok\\\": \\\"node scripts/check.js\\\"\\n },\\n \\\"marker\\\": \\\"package-script-ready\\\"\\n}\\n\" }],\n },\n \"tanya.medium.service-module\": {\n id: \"tanya.medium.service-module\",\n prompt: \"Create a service module and export it from the index.\",\n targetFiles: [\n { path: \"src/services/taskService.ts\", content: \"export function taskService() { return 'service-module-ready'; }\\n\" },\n { path: \"src/index.ts\", content: \"export { taskService } from './services/taskService';\\n\" },\n ],\n },\n \"tanya.medium.test-harness\": {\n id: \"tanya.medium.test-harness\",\n prompt: \"Add a tiny executable test harness and verify it runs.\",\n targetFiles: [\n { path: \"src/harness.js\", content: \"module.exports = () => 'test-harness-ready';\\n\" },\n { path: \"test/harness.test.js\", content: \"const run = require('../src/harness'); if (run() !== 'test-harness-ready') process.exit(1);\\n\" },\n ],\n },\n \"tanya.medium.artifact-component\": {\n id: \"tanya.medium.artifact-component\",\n prompt: \"Adapt the reusable component artifact into the project.\",\n useArtifact: true,\n targetFiles: [{ path: \"src/components/BenchmarkCard.tsx\", content: \"export function BenchmarkCard() { return 'artifact-component-ready'; }\\n\" }],\n },\n \"tanya.medium.artifact-service\": {\n id: \"tanya.medium.artifact-service\",\n prompt: \"Adapt the reusable service artifact into the project.\",\n useArtifact: true,\n targetFiles: [{ path: \"src/services/artifactService.ts\", content: \"export function artifactService() { return 'artifact-service-ready'; }\\n\" }],\n },\n \"tanya.medium.dirty-worktree\": {\n id: \"tanya.medium.dirty-worktree\",\n prompt: \"Complete the task while preserving an unrelated dirty file.\",\n dirtyWorktree: true,\n targetFiles: [{ path: \"src/dirtyTask.ts\", content: \"export const dirtyTask = 'dirty-worktree-ready';\\n\" }],\n },\n \"tanya.medium.report-repair\": {\n id: \"tanya.medium.report-repair\",\n prompt: \"Complete the task and recover if the first final response omits the required report.\",\n reportRepair: true,\n targetFiles: [{ path: \"src/reportRepair.ts\", content: \"export const reportRepair = 'report-repair-ready';\\n\" }],\n },\n \"tanya.medium.multi-file\": {\n id: \"tanya.medium.multi-file\",\n prompt: \"Create a coordinated source and documentation update.\",\n targetFiles: [\n { path: \"src/multiFile.ts\", content: \"export const multiFile = 'multi-file-ready';\\n\" },\n { path: \"docs/multi-file.md\", content: \"# Multi File\\n\\nmulti-file-ready\\n\" },\n ],\n },\n \"tanya.medium.package-manager\": {\n id: \"tanya.medium.package-manager\",\n prompt: \"Add package-manager metadata and a source marker.\",\n targetFiles: [\n { path: \"package.json\", content: \"{\\n \\\"name\\\": \\\"benchmark-fixture\\\",\\n \\\"packageManager\\\": \\\"npm@10.0.0\\\",\\n \\\"scripts\\\": {\\n \\\"typecheck\\\": \\\"node scripts/check.js\\\",\\n \\\"test\\\": \\\"node scripts/check.js\\\"\\n },\\n \\\"marker\\\": \\\"package-manager-ready\\\"\\n}\\n\" },\n { path: \"src/packageManager.ts\", content: \"export const packageManager = 'package-manager-ready';\\n\" },\n ],\n },\n \"tanya.medium.context-aware\": {\n id: \"tanya.medium.context-aware\",\n prompt: \"Read the provided context note before editing the implementation.\",\n useContext: true,\n targetFiles: [{ path: \"src/contextAware.ts\", content: \"export const contextAware = 'context-aware-ready';\\n\" }],\n },\n \"tanya.medium.existing-tests\": {\n id: \"tanya.medium.existing-tests\",\n prompt: \"Modify implementation while running the existing verification script.\",\n targetFiles: [\n { path: \"src/existingTests.js\", content: \"module.exports = 'existing-tests-ready';\\n\" },\n { path: \"test/existingTests.test.js\", content: \"if (require('../src/existingTests') !== 'existing-tests-ready') process.exit(1);\\n\" },\n ],\n },\n \"tanya.medium.dependency-install\": {\n id: \"tanya.medium.dependency-install\",\n prompt: \"Add the requested runtime dependency and lockfile state, then verify the manifest.\",\n targetFiles: [\n { path: \"package.json\", content: \"{\\n \\\"name\\\": \\\"benchmark-fixture\\\",\\n \\\"scripts\\\": {\\n \\\"check\\\": \\\"node scripts/check.js\\\"\\n },\\n \\\"dependencies\\\": {\\n \\\"zod\\\": \\\"^3.25.0\\\"\\n },\\n \\\"marker\\\": \\\"dependency-install-ready\\\"\\n}\\n\" },\n { path: \"package-lock.json\", content: \"{\\n \\\"name\\\": \\\"benchmark-fixture\\\",\\n \\\"lockfileVersion\\\": 3,\\n \\\"packages\\\": {\\n \\\"\\\": {\\n \\\"dependencies\\\": {\\n \\\"zod\\\": \\\"^3.25.0\\\"\\n },\\n \\\"marker\\\": \\\"dependency-install-ready\\\"\\n }\\n }\\n}\\n\" },\n ],\n },\n \"tanya.medium.framework-migration\": {\n id: \"tanya.medium.framework-migration\",\n prompt: \"Migrate the legacy page into an app-router-style page and preserve compatibility.\",\n preFiles: [\n { path: \"src/pages/index.tsx\", content: \"export default function LegacyHome() { return 'legacy'; }\\n\" },\n ],\n targetFiles: [\n { path: \"src/app/page.tsx\", content: \"export default function Page() { return 'framework-migration-ready'; }\\n\" },\n { path: \"src/app/layout.tsx\", content: \"export default function Layout({ children }: { children: unknown }) { return children; }\\n// framework-migration-ready\\n\" },\n { path: \"src/pages/index.tsx\", content: \"export { default } from '../app/page';\\n// framework-migration-ready\\n\" },\n ],\n },\n \"tanya.medium.failing-test-repair\": {\n id: \"tanya.medium.failing-test-repair\",\n prompt: \"Run the existing check, repair the failing implementation, and rerun verification.\",\n useSearchReplace: true,\n preVerifyBeforeEdit: true,\n targetFiles: [\n { path: \"src/math.js\", content: \"module.exports = function add(a, b) { return a + b; };\\n// failing-test-repair-ready\\n\" },\n { path: \"test/math.test.js\", content: \"const add = require('../src/math'); if (add(2, 2) !== 4) process.exit(1);\\n// failing-test-repair-ready\\n\" },\n ],\n },\n \"tanya.medium.frontend-smoke\": {\n id: \"tanya.medium.frontend-smoke\",\n prompt: \"Create a small frontend component and smoke check that proves the key UI marker is present.\",\n targetFiles: [\n { path: \"src/App.tsx\", content: \"export function App() { return <main className=\\\"dashboard\\\">frontend-smoke-ready</main>; }\\n\" },\n { path: \"src/App.css\", content: \".dashboard { display: grid; gap: 12px; }\\n/* frontend-smoke-ready */\\n\" },\n { path: \"test/render-smoke.js\", content: \"const fs = require('fs'); const text = fs.readFileSync('src/App.tsx', 'utf8'); if (!text.includes('frontend-smoke-ready')) process.exit(1);\\n// frontend-smoke-ready\\n\" },\n ],\n },\n \"tanya.medium.run-log-history\": {\n id: \"tanya.medium.run-log-history\",\n prompt: \"Complete a normal edit and make sure usage metrics are available for run history.\",\n usage: { promptTokens: 2_400, completionTokens: 620 },\n targetFiles: [{ path: \"src/runLogHistory.ts\", content: \"export const runLogHistory = 'run-log-history-ready';\\n\" }],\n },\n};\n\nasync function genericBenchmarkFixture(profile: GoldenTaskProfile): Promise<GoldenTaskFixture> {\n const spec = GENERIC_BENCHMARK_SPECS[profile.id];\n if (!spec) throw new Error(`No generic benchmark spec for ${profile.id}`);\n const workspace = await createBaseWorkspace(profile.id);\n const marker = `${profile.id.split(\".\").pop() ?? \"benchmark\"}-ready`;\n\n await mkdir(join(workspace, \"scripts\"), { recursive: true });\n await writeFile(join(workspace, \"scripts/check.js\"), [\n \"const fs = require('fs');\",\n `const targets = ${JSON.stringify(spec.targetFiles.map((file) => ({ path: file.path, marker })))};`,\n \"for (const target of targets) {\",\n \" const text = fs.readFileSync(target.path, 'utf8');\",\n \" if (!text.includes(target.marker)) {\",\n \" console.error(`missing ${target.marker} in ${target.path}`);\",\n \" process.exit(1);\",\n \" }\",\n \"}\",\n \"console.log('benchmark ok');\",\n \"\",\n ].join(\"\\n\"));\n\n if (spec.useSearchReplace) {\n for (const file of spec.targetFiles) {\n const dir = file.path.split(\"/\").slice(0, -1).join(\"/\");\n if (dir) await mkdir(join(workspace, dir), { recursive: true });\n await writeFile(join(workspace, file.path), file.content.replace(marker, \"PENDING_MARKER\"));\n }\n }\n for (const file of spec.preFiles ?? []) {\n const dir = file.path.split(\"/\").slice(0, -1).join(\"/\");\n if (dir) await mkdir(join(workspace, dir), { recursive: true });\n await writeFile(join(workspace, file.path), file.content);\n }\n if (spec.useArtifact) {\n await mkdir(join(workspace, \".tania/artifacts/generic\"), { recursive: true });\n await writeFile(join(workspace, \".tania/artifacts/generic/Pattern.md\"), `# Pattern\\n\\nUse ${marker} in the adapted output.\\n`);\n }\n if (spec.useContext) {\n await mkdir(join(workspace, \".tania/context\"), { recursive: true });\n await writeFile(join(workspace, \".tania/context/task.md\"), `# Task Context\\n\\nUse ${marker}.\\n`);\n }\n if (spec.dirtyWorktree) {\n await writeFile(join(workspace, \"unrelated.txt\"), \"baseline\\n\");\n await execFileAsync(\"git\", [\"init\"], { cwd: workspace });\n await execFileAsync(\"git\", [\"config\", \"user.email\", \"tanya@example.test\"], { cwd: workspace });\n await execFileAsync(\"git\", [\"config\", \"user.name\", \"Tanya Benchmark\"], { cwd: workspace });\n await execFileAsync(\"git\", [\"add\", \"unrelated.txt\"], { cwd: workspace });\n await execFileAsync(\"git\", [\"commit\", \"-m\", \"baseline\"], { cwd: workspace });\n await writeFile(join(workspace, \"unrelated.txt\"), \"pre-existing dirty change\\n\");\n }\n\n const toolCalls: ToolCall[] = [];\n if (spec.useArtifact) toolCalls.push(toolCall(\"read-artifact\", \"read_file\", { path: \".tania/artifacts/generic/Pattern.md\" }));\n if (spec.useContext) toolCalls.push(toolCall(\"read-context\", \"read_file\", { path: \".tania/context/task.md\" }));\n if (spec.preVerifyBeforeEdit) toolCalls.push(toolCall(\"verify-before\", \"run_command\", { command: \"node\", args: [\"scripts/check.js\"] }));\n if (spec.useSearchReplace) {\n for (const file of spec.targetFiles) {\n toolCalls.push(toolCall(`edit-${file.path}`, \"search_replace\", {\n path: file.path,\n old_string: file.content.replace(marker, \"PENDING_MARKER\"),\n new_string: file.content,\n }));\n }\n } else {\n for (const file of spec.targetFiles) toolCalls.push(toolCall(`write-${file.path}`, \"write_file\", file));\n }\n toolCalls.push(toolCall(\"verify\", \"run_command\", { command: \"node\", args: [\"scripts/check.js\"] }));\n\n const artifactLine = spec.useArtifact\n ? `Artifact reused: artifacts/generic/Pattern.md -> ${spec.targetFiles.map((file) => file.path).join(\", \")}`\n : \"Artifact reused: none\";\n const finalReport = [\n artifactLine,\n \"Artifact created: none\",\n ...spec.targetFiles.map((file) => `Modified: ${file.path}`),\n \"Verification: node scripts/check.js -> passed\",\n \"Blocked: none\",\n ].join(\"\\n\");\n\n return {\n workspace,\n prompt: spec.prompt,\n provider: scriptedProvider(profile.id, [\n { content: spec.prompt, toolCalls, ...(spec.usage ? { usage: spec.usage } : {}) },\n ...(spec.reportRepair ? [{ content: \"Done.\" }] : []),\n { content: finalReport },\n ]),\n runContext: {\n task: { kind: \"coding\", title: profile.title, summary: profile.purpose },\n artifacts: spec.useArtifact ? [{ path: \".tania/artifacts/generic/Pattern.md\", sourcePath: \"artifacts/generic/Pattern.md\", status: \"available\" }] : [],\n contextFiles: spec.useContext ? [{ path: \".tania/context/task.md\", sourcePath: \"context/task.md\", status: \"available\" }] : [],\n expected_report: { verification: true, artifact_reuse: true },\n metadata: { goldenTaskCandidate: true, caller: \"tanya-benchmark\" },\n },\n };\n}\n\nasync function streamingLongToolFixture(profile: GoldenTaskProfile): Promise<GoldenTaskFixture> {\n const workspace = await createBaseWorkspace(profile.id);\n const script = \"for i in 1 2 3 4 5 6; do printf \\\"stream-$i\\\\n\\\"; sleep 2; done; node scripts/check.js\";\n await mkdir(join(workspace, \"scripts\"), { recursive: true });\n await writeFile(join(workspace, \"scripts/check.js\"), [\n \"const fs = require('fs');\",\n \"const text = fs.readFileSync('src/streamingLongTool.ts', 'utf8');\",\n \"if (!text.includes('streaming-long-tool-ready')) process.exit(1);\",\n \"console.log('benchmark ok');\",\n \"\",\n ].join(\"\\n\"));\n\n const provider = scriptedProvider(profile.id, [\n {\n content: \"Create a marker file and verify it with a long-running streaming shell command.\",\n toolCalls: [\n toolCall(\"write-marker\", \"write_file\", {\n path: \"src/streamingLongTool.ts\",\n content: \"export const streamingLongTool = 'streaming-long-tool-ready';\\n\",\n }),\n toolCall(\"long-verify\", \"run_shell\", { script, timeoutMs: 20_000 }),\n ],\n },\n {\n content: [\n \"Artifact reused: none\",\n \"Artifact created: none\",\n \"Modified: src/streamingLongTool.ts\",\n `Verification: ${script} -> passed`,\n \"Blocked: none\",\n ].join(\"\\n\"),\n },\n ]);\n\n return {\n workspace,\n prompt: \"Create a marker file and verify it with a >10s shell command that streams output.\",\n provider,\n runContext: {\n task: { kind: \"coding\", title: profile.title, summary: profile.purpose },\n expected_report: { verification: true, artifact_reuse: true },\n metadata: { goldenTaskCandidate: true, caller: \"tanya-golden\" },\n },\n };\n}\n\nasync function compactionBoundaryFixture(profile: GoldenTaskProfile): Promise<GoldenTaskFixture> {\n const workspace = await createBaseWorkspace(profile.id);\n await mkdir(join(workspace, \"scripts\"), { recursive: true });\n await writeFile(join(workspace, \"scripts/check.js\"), [\n \"const fs = require('fs');\",\n \"const text = fs.readFileSync('src/compactionBoundary.ts', 'utf8');\",\n \"if (!text.includes('compaction-boundary-ready')) process.exit(1);\",\n \"console.log('benchmark ok');\",\n \"\",\n ].join(\"\\n\"));\n\n const requests: ChatRequest[] = [];\n let mainAttempts = 0;\n const provider: ChatProvider & { requests: ChatRequest[] } = {\n id: `golden:${profile.id}`,\n model: \"scripted\",\n requests,\n async *streamChat(input: ChatRequest) {\n requests.push({ ...input, messages: [...input.messages] });\n const prompt = input.messages[0]?.content ?? \"\";\n if (input.tools?.length === 0 && prompt.includes(\"Summarize these older Tanya conversation turns\")) {\n yield { content: \"The run wrote src/compactionBoundary.ts and verified it with node scripts/check.js.\" };\n return;\n }\n\n mainAttempts += 1;\n if (mainAttempts === 1) {\n yield {\n content: \"Create and verify the compaction boundary marker.\",\n toolCalls: [\n toolCall(\"write-marker\", \"write_file\", {\n path: \"src/compactionBoundary.ts\",\n content: \"export const compactionBoundary = 'compaction-boundary-ready';\\n\",\n }),\n toolCall(\"verify\", \"run_command\", { command: \"node\", args: [\"scripts/check.js\"] }),\n ],\n };\n return;\n }\n if (mainAttempts === 2) {\n throw new ContextWindowExceededError({\n provider: provider.id,\n status: 413,\n rawMessage: \"context_length_exceeded\",\n });\n }\n yield {\n content: [\n \"Artifact reused: none\",\n \"Artifact created: none\",\n \"Modified: src/compactionBoundary.ts\",\n \"Verification: node scripts/check.js -> passed\",\n \"Blocked: none\",\n ].join(\"\\n\"),\n };\n },\n };\n\n return {\n workspace,\n prompt: \"Create a marker file and finish correctly after a synthetic context compaction boundary.\",\n provider,\n runContext: {\n task: { kind: \"coding\", title: profile.title, summary: profile.purpose },\n expected_report: { verification: true, artifact_reuse: true },\n metadata: { goldenTaskCandidate: true, caller: \"tanya-golden\" },\n },\n };\n}\n\nasync function editBlockFuzzyFixture(profile: GoldenTaskProfile, mode: \"enabled\" | \"disabled\" = \"enabled\"): Promise<GoldenTaskFixture> {\n const workspace = await createBaseWorkspace(`${profile.id}-${mode}`);\n await mkdir(join(workspace, \"src\"), { recursive: true });\n await mkdir(join(workspace, \"scripts\"), { recursive: true });\n await writeFile(join(workspace, \"src/status.ts\"), [\n \"export function status() {\",\n \" const current = \\\"pending\\\";\",\n \" return current;\",\n \"}\",\n \"\",\n ].join(\"\\n\"));\n await writeFile(join(workspace, \"scripts/check.js\"), [\n \"const fs = require('fs');\",\n \"const text = fs.readFileSync('src/status.ts', 'utf8');\",\n \"if (!text.includes('complete')) {\",\n \" console.error('missing edit-block-fuzzy-ready');\",\n \" process.exit(1);\",\n \"}\",\n \"console.log('benchmark ok');\",\n \"\",\n ].join(\"\\n\"));\n if (mode === \"enabled\") {\n await mkdir(join(workspace, \".tania\"), { recursive: true });\n await writeFile(join(workspace, \".tania\", \"permissions.json\"), JSON.stringify({\n version: 1,\n mode: \"default\",\n alwaysAllow: [\"edit_block:.*\\\"matchPolicy\\\":\\\"fuzzy\\\".*\"],\n }));\n }\n\n const original = [\n \"export function status() {\",\n \" const current = \\\"pending\\\";\",\n \" return current;\",\n \"}\",\n ].join(\"\\n\");\n const nearMatch = [\n \"export function status() {\",\n \" const current = \\\"pendng\\\";\",\n \" return current;\",\n \"}\",\n ].join(\"\\n\");\n const replacement = [\n \"export function status() {\",\n \" const current = \\\"complete\\\";\",\n \" return current;\",\n \"}\",\n ].join(\"\\n\");\n const finalReport = [\n \"Artifact reused: none\",\n \"Artifact created: none\",\n \"Modified: src/status.ts\",\n \"Verification: node scripts/check.js -> passed\",\n \"Blocked: none\",\n ].join(\"\\n\");\n\n const turns = mode === \"enabled\"\n ? [\n {\n content: \"Use fuzzy edit_block to recover the near-match and verify it.\",\n toolCalls: [\n toolCall(\"fuzzy-edit\", \"edit_block\", {\n path: \"src/status.ts\",\n search: nearMatch,\n replace: replacement,\n matchPolicy: \"fuzzy\",\n }),\n toolCall(\"verify\", \"run_command\", { command: \"node\", args: [\"scripts/check.js\"] }),\n ],\n },\n { content: finalReport },\n ]\n : [\n {\n content: \"Try the near-match exactly first.\",\n toolCalls: [\n toolCall(\"bad-exact\", \"edit_block\", {\n path: \"src/status.ts\",\n search: nearMatch,\n replace: replacement,\n }),\n ],\n },\n {\n content: \"Read the file after the exact block failed.\",\n toolCalls: [toolCall(\"read-status\", \"read_file\", { path: \"src/status.ts\" })],\n },\n {\n content: \"Apply the closer exact block and verify.\",\n toolCalls: [\n toolCall(\"exact-edit\", \"edit_block\", {\n path: \"src/status.ts\",\n search: original,\n replace: replacement,\n }),\n toolCall(\"verify\", \"run_command\", { command: \"node\", args: [\"scripts/check.js\"] }),\n ],\n },\n { content: finalReport },\n ];\n\n return {\n workspace,\n prompt: \"Recover a cheap-provider-style near-match edit and verify the file.\",\n provider: scriptedProvider(`${profile.id}-${mode}`, turns),\n runContext: {\n task: { kind: \"coding\", title: profile.title, summary: profile.purpose },\n expected_report: { verification: true, artifact_reuse: true },\n metadata: { goldenTaskCandidate: true, caller: \"tanya-golden\" },\n },\n };\n}\n\nasync function androidSplashFixture(profile: GoldenTaskProfile): Promise<GoldenTaskFixture> {\n const workspace = await createBaseWorkspace(profile.id);\n await mkdir(join(workspace, \".tania/artifacts/android\"), { recursive: true });\n await mkdir(join(workspace, \"app/src/main/java/com/example/app/ui/splash\"), { recursive: true });\n await mkdir(join(workspace, \"app/src/main/res/values\"), { recursive: true });\n await mkdir(join(workspace, \"app/src/main/res/drawable\"), { recursive: true });\n await writeFile(join(workspace, \".tania/artifacts/android/SplashScreenPattern.kt\"), \"fun SplashPattern() {}\\n\");\n await writeFile(join(workspace, \"gradlew\"), \"#!/bin/sh\\ncase \\\"$*\\\" in\\n *ktlintCheck*) echo ktlint ok ;;\\n *) echo BUILD SUCCESSFUL ;;\\nesac\\n\");\n await writeFile(join(workspace, \"app/src/main/res/drawable/ic_splash_logo.png\"), \"png\\n\");\n\n const provider = scriptedProvider(profile.id, [\n {\n content: \"Create Android splash resources from the artifact.\",\n toolCalls: [\n toolCall(\"read-artifact\", \"read_file\", { path: \".tania/artifacts/android/SplashScreenPattern.kt\" }),\n toolCall(\"write-manifest\", \"write_file\", {\n path: \"app/src/main/AndroidManifest.xml\",\n content: \"<manifest xmlns:android=\\\"http://schemas.android.com/apk/res/android\\\"><application><activity android:name=\\\".MainActivity\\\" android:theme=\\\"@style/Theme.App.Splash\\\" /></application></manifest>\\n\",\n }),\n toolCall(\"write-theme\", \"write_file\", {\n path: \"app/src/main/res/values/splash_theme.xml\",\n content: \"<resources><style name=\\\"Theme.App.Splash\\\" parent=\\\"Theme.SplashScreen\\\"><item name=\\\"windowSplashScreenAnimatedIcon\\\">@drawable/ic_splash_logo</item><item name=\\\"postSplashScreenTheme\\\">@style/Theme.App</item></style></resources>\\n\",\n }),\n toolCall(\"write-icon\", \"write_file\", {\n path: \"app/src/main/res/drawable/ic_splash_logo.png\",\n content: \"png\\n\",\n }),\n toolCall(\"write-main\", \"write_file\", {\n path: \"app/src/main/java/com/example/app/MainActivity.kt\",\n content: \"package com.example.app\\nfun onCreate() { installSplashScreen() }\\n\",\n }),\n toolCall(\"write-splash\", \"write_file\", {\n path: \"app/src/main/java/com/example/app/ui/splash/SplashScreen.kt\",\n content: \"package com.example.app.ui.splash\\nfun CosaNostraSplashScreen() {}\\n\",\n }),\n toolCall(\"verify\", \"run_shell\", { script: \"chmod +x ./gradlew && ./gradlew assembleDebug --no-daemon\" }),\n ],\n },\n {\n content: [\n \"Artifact reused: artifacts/android/SplashScreenPattern.kt -> app/src/main/java/com/example/app/ui/splash/SplashScreen.kt\",\n \"Artifact created: none\",\n \"Modified: app/src/main/AndroidManifest.xml\",\n \"Modified: app/src/main/res/values/splash_theme.xml\",\n \"Modified: app/src/main/res/drawable/ic_splash_logo.png\",\n \"Modified: app/src/main/java/com/example/app/MainActivity.kt\",\n \"Modified: app/src/main/java/com/example/app/ui/splash/SplashScreen.kt\",\n \"Verification: ./gradlew assembleDebug --no-daemon -> passed\",\n \"Blocked: none\",\n ].join(\"\\n\"),\n },\n ]);\n\n return {\n workspace,\n prompt: \"Create Android splash screen using artifacts/android/SplashScreenPattern.kt.\",\n provider,\n runContext: {\n task: { kind: \"coding\", title: \"Splash Screen - Android\", summary: profile.purpose },\n artifacts: [{ path: \".tania/artifacts/android/SplashScreenPattern.kt\", sourcePath: \"artifacts/android/SplashScreenPattern.kt\", status: \"available\" }],\n expected_report: { verification: true, artifact_reuse: true },\n metadata: { goldenTaskCandidate: true, caller: \"tanya-golden\" },\n },\n };\n}\n\nasync function iosFoundationFixture(profile: GoldenTaskProfile): Promise<GoldenTaskFixture> {\n const workspace = await createBaseWorkspace(profile.id);\n await mkdir(join(workspace, \".tania/artifacts/ios\"), { recursive: true });\n await writeFile(join(workspace, \".tania/artifacts/ios/ThemeSystem.swift\"), \"import SwiftUI\\n\");\n await writeFile(join(workspace, \".tania/artifacts/ios/SwiftDataSetup.swift\"), \"import SwiftData\\n\");\n await writeFile(join(workspace, \".tania/artifacts/ios/NavigationSetup.swift\"), \"import SwiftUI\\n\");\n\n const provider = scriptedProvider(profile.id, [\n {\n content: \"Create iOS foundation from theme, SwiftData, and navigation artifacts.\",\n toolCalls: [\n toolCall(\"read-theme\", \"read_file\", { path: \".tania/artifacts/ios/ThemeSystem.swift\" }),\n toolCall(\"read-data\", \"read_file\", { path: \".tania/artifacts/ios/SwiftDataSetup.swift\" }),\n toolCall(\"read-nav\", \"read_file\", { path: \".tania/artifacts/ios/NavigationSetup.swift\" }),\n toolCall(\"mkdirs\", \"run_shell\", { script: \"mkdir -p CosaNostra/Theme CosaNostra/Models CosaNostra/Navigation\" }),\n toolCall(\"write-colors\", \"write_file\", {\n path: \"CosaNostra/Theme/Colors.swift\",\n content: \"import SwiftUI\\nextension Color { static let brandPrimary = Color(red: 26 / 255, green: 47 / 255, blue: 75 / 255); static let brandSecondary = Color(red: 200 / 255, green: 174 / 255, blue: 127 / 255); static let textPrimary = Color.primary }\\n\",\n }),\n toolCall(\"write-type\", \"write_file\", {\n path: \"CosaNostra/Theme/Typography.swift\",\n content: \"import SwiftUI\\nenum AppTypography { static let title = Font.system(size: 28, design: .serif); static let body = Font.system(size: 16, design: .default) /* Playfair Display / Roboto local fallback */ }\\n\",\n }),\n toolCall(\"write-mods\", \"write_file\", {\n path: \"CosaNostra/Theme/ViewModifiers.swift\",\n content: \"import SwiftUI\\nstruct CardStyle: ViewModifier { func body(content: Content) -> some View { content } }\\nstruct PrimaryButtonStyle: ButtonStyle { func makeBody(configuration: Configuration) -> some View { configuration.label } }\\nstruct EmptyStateView: View { var body: some View { Text(\\\"Empty\\\") } }\\nstruct LoadingView: View { var body: some View { ProgressView() } }\\nstruct ErrorView: View { var body: some View { Text(\\\"Error\\\") } }\\n\",\n }),\n toolCall(\"write-models\", \"write_file\", {\n path: \"CosaNostra/Models/SwiftDataSetup.swift\",\n content: \"import SwiftData\\n@Model final class UserProfile { var id: String = \\\"\\\" }\\nlet appSchema = Schema([UserProfile.self])\\n\",\n }),\n toolCall(\"write-nav\", \"write_file\", {\n path: \"CosaNostra/Navigation/NavigationSetup.swift\",\n content: \"import SwiftUI\\nstruct RootTabView: View { @AppStorage(\\\"isDarkMode\\\") private var isDarkMode = false; var body: some View { TabView { NavigationStack { Toggle(\\\"Dark Mode\\\", isOn: $isDarkMode); Text(\\\"Dashboard\\\") } } } }\\n\",\n }),\n toolCall(\"write-app\", \"write_file\", {\n path: \"CosaNostra/CosaNostraApp.swift\",\n content: \"import SwiftUI\\nimport SwiftData\\n@main struct CosaNostraApp: App { @AppStorage(\\\"isDarkMode\\\") private var isDarkMode = false; var body: some Scene { WindowGroup { RootTabView().preferredColorScheme(isDarkMode ? .dark : nil).modelContainer(for: [UserProfile.self]) } } }\\n\",\n }),\n toolCall(\"verify\", \"run_shell\", { script: \"grep -R \\\"TabView\\\" CosaNostra/Navigation && echo xcodebuild\" }),\n ],\n },\n {\n content: [\n \"Artifact reused: artifacts/ios/ThemeSystem.swift -> CosaNostra/Theme/Colors.swift, CosaNostra/Theme/Typography.swift, CosaNostra/Theme/ViewModifiers.swift\",\n \"Artifact reused: artifacts/ios/SwiftDataSetup.swift -> CosaNostra/Models/SwiftDataSetup.swift\",\n \"Artifact reused: artifacts/ios/NavigationSetup.swift -> CosaNostra/Navigation/NavigationSetup.swift\",\n \"Artifact created: none\",\n \"Modified: CosaNostra/Theme/Colors.swift\",\n \"Modified: CosaNostra/Theme/Typography.swift\",\n \"Modified: CosaNostra/Theme/ViewModifiers.swift\",\n \"Modified: CosaNostra/Models/SwiftDataSetup.swift\",\n \"Modified: CosaNostra/Navigation/NavigationSetup.swift\",\n \"Modified: CosaNostra/CosaNostraApp.swift\",\n \"Verification: grep -R \\\"TabView\\\" CosaNostra/Navigation && echo xcodebuild -> passed\",\n \"Blocked: none\",\n ].join(\"\\n\"),\n },\n ]);\n\n return {\n workspace,\n prompt: \"Create bounded iOS foundation from the provided artifacts. Ensure dark mode support and local typography fallback.\",\n provider,\n runContext: {\n task: { kind: \"coding\", title: \"Fundações - iOS\", summary: profile.purpose },\n artifacts: [\n { path: \".tania/artifacts/ios/ThemeSystem.swift\", sourcePath: \"artifacts/ios/ThemeSystem.swift\", status: \"available\" },\n { path: \".tania/artifacts/ios/SwiftDataSetup.swift\", sourcePath: \"artifacts/ios/SwiftDataSetup.swift\", status: \"available\" },\n { path: \".tania/artifacts/ios/NavigationSetup.swift\", sourcePath: \"artifacts/ios/NavigationSetup.swift\", status: \"available\" },\n ],\n expected_report: { verification: true, artifact_reuse: true },\n metadata: { goldenTaskCandidate: true, caller: \"tanya-golden\" },\n },\n };\n}\n\nasync function appleAppIconFixture(profile: GoldenTaskProfile): Promise<GoldenTaskFixture> {\n const workspace = await createBaseWorkspace(profile.id);\n await mkdir(join(workspace, \"CosaNostra/Assets.xcassets\"), { recursive: true });\n const provider = scriptedProvider(profile.id, [\n {\n content: \"Generate Apple app icon set with iOS and macOS slots.\",\n toolCalls: [\n toolCall(\"write-svg\", \"write_file\", {\n path: \"brand-icon.svg\",\n content: \"<svg xmlns=\\\"http://www.w3.org/2000/svg\\\" width=\\\"1024\\\" height=\\\"1024\\\"><rect width=\\\"1024\\\" height=\\\"1024\\\" fill=\\\"#1A2F4B\\\"/><circle cx=\\\"512\\\" cy=\\\"512\\\" r=\\\"280\\\" fill=\\\"#C8AE7F\\\"/></svg>\\n\",\n }),\n toolCall(\"create-icons\", \"create_apple_app_icon_set\", {\n source: \"brand-icon.svg\",\n outputDir: \"CosaNostra/Assets.xcassets/AppIcon.appiconset\",\n platforms: [\"ios\", \"macos\"],\n }),\n toolCall(\"parse-json\", \"run_shell\", { script: \"node -e \\\"const c=require('./CosaNostra/Assets.xcassets/AppIcon.appiconset/Contents.json'); const idioms=new Set(c.images.map(i=>i.idiom)); if(!idioms.has('iphone')||!idioms.has('ipad')||!idioms.has('ios-marketing')||!idioms.has('mac')) process.exit(1); console.log(c.images.length)\\\"\" }),\n toolCall(\"xcodebuild\", \"run_shell\", { script: \"printf '#!/bin/sh\\\\necho BUILD SUCCEEDED\\\\n' > xcodebuild && chmod +x xcodebuild && PATH=\\\"$PWD:$PATH\\\" xcodebuild build -scheme CosaNostra -destination 'generic/platform=iOS Simulator'\" }),\n ],\n },\n {\n content: [\n \"Artifact reused: none\",\n \"Artifact created: none\",\n \"Modified: brand-icon.svg\",\n \"Modified: CosaNostra/Assets.xcassets/AppIcon.appiconset/Contents.json\",\n \"Verification: node Contents.json idiom parse -> passed\",\n \"Verification: xcodebuild build -scheme CosaNostra -destination 'generic/platform=iOS Simulator' -> passed\",\n \"Blocked: none\",\n ].join(\"\\n\"),\n },\n ]);\n\n return {\n workspace,\n prompt: \"Generate Apple app icon assets for iOS, iPad, ios-marketing, and macOS.\",\n provider,\n runContext: {\n task: { kind: \"coding\", title: \"App Icon - Apple\", summary: profile.purpose },\n expected_report: { verification: true, artifact_reuse: true },\n metadata: { goldenTaskCandidate: true, caller: \"tanya-golden\" },\n },\n };\n}\n\nasync function androidFoundationFixture(profile: GoldenTaskProfile): Promise<GoldenTaskFixture> {\n const workspace = await createBaseWorkspace(profile.id);\n await mkdir(join(workspace, \".tania/artifacts/android\"), { recursive: true });\n await mkdir(join(workspace, \"app\"), { recursive: true });\n await writeFile(join(workspace, \".tania/artifacts/android/ThemeSystem.kt\"), \"package artifact\\n\");\n await writeFile(join(workspace, \".tania/artifacts/android/NavigationSetup.kt\"), \"package artifact\\n\");\n await writeFile(join(workspace, \".tania/artifacts/android/RoomSetup.kt\"), \"package artifact\\n\");\n await writeFile(join(workspace, \"gradlew\"), \"#!/bin/sh\\ncase \\\"$*\\\" in\\n *ktlintCheck*) echo ktlint ok ;;\\n *) echo BUILD SUCCESSFUL ;;\\nesac\\n\");\n await writeFile(join(workspace, \"build.gradle.kts\"), \"plugins {\\n id(\\\"com.android.application\\\") version \\\"8.7.2\\\" apply false\\n}\\n\");\n await writeFile(join(workspace, \"app/build.gradle.kts\"), [\n \"plugins {\",\n \" id(\\\"com.android.application\\\")\",\n \" id(\\\"org.jetbrains.kotlin.android\\\")\",\n \"}\",\n \"\",\n \"dependencies {\",\n \"}\",\n \"\",\n ].join(\"\\n\"));\n\n const provider = scriptedProvider(profile.id, [\n {\n content: \"Create Android foundation with the deterministic high-level tool.\",\n toolCalls: [\n toolCall(\"read-theme\", \"read_file\", { path: \".tania/artifacts/android/ThemeSystem.kt\" }),\n toolCall(\"read-nav\", \"read_file\", { path: \".tania/artifacts/android/NavigationSetup.kt\" }),\n toolCall(\"read-room\", \"read_file\", { path: \".tania/artifacts/android/RoomSetup.kt\" }),\n toolCall(\"create-foundation\", \"create_android_foundation\", {\n packageName: \"com.example.app\",\n appName: \"Golden\",\n brandPrimaryHex: \"#1A2F4B\",\n brandSecondaryHex: \"#C8AE7F\",\n }),\n toolCall(\"verify\", \"run_shell\", { script: \"chmod +x ./gradlew && ./gradlew assembleDebug --no-daemon\" }),\n ],\n },\n {\n content: [\n \"Artifact reused: artifacts/android/ThemeSystem.kt -> app/src/main/java/com/example/app/ui/theme/AppTheme.kt\",\n \"Artifact reused: artifacts/android/NavigationSetup.kt -> app/src/main/java/com/example/app/navigation/AppNavigation.kt\",\n \"Artifact reused: artifacts/android/RoomSetup.kt -> app/src/main/java/com/example/app/data/AppDatabase.kt\",\n \"Artifact created: none\",\n \"Modified: build.gradle.kts\",\n \"Modified: app/build.gradle.kts\",\n \"Modified: app/src/main/java/com/example/app/ui/theme/AppTheme.kt\",\n \"Modified: app/src/main/java/com/example/app/navigation/AppNavigation.kt\",\n \"Modified: app/src/main/java/com/example/app/data/AppDatabase.kt\",\n \"Modified: app/src/main/java/com/example/app/ui/components/FoundationStates.kt\",\n \"Verification: ./gradlew assembleDebug --no-daemon -> passed\",\n \"Blocked: none\",\n ].join(\"\\n\"),\n },\n ]);\n\n return {\n workspace,\n prompt: \"Create Android foundation using Room, Navigation Compose, Material 3 theme, and base composables.\",\n provider,\n runContext: {\n task: { kind: \"coding\", title: \"Fundações - Android\", summary: profile.purpose },\n artifacts: [\n { path: \".tania/artifacts/android/ThemeSystem.kt\", sourcePath: \"artifacts/android/ThemeSystem.kt\", status: \"available\" },\n { path: \".tania/artifacts/android/NavigationSetup.kt\", sourcePath: \"artifacts/android/NavigationSetup.kt\", status: \"available\" },\n { path: \".tania/artifacts/android/RoomSetup.kt\", sourcePath: \"artifacts/android/RoomSetup.kt\", status: \"available\" },\n ],\n expected_report: { verification: true, artifact_reuse: true },\n metadata: { goldenTaskCandidate: true, caller: \"tanya-golden\" },\n },\n };\n}\n\nasync function backendApiFoundationFixture(profile: GoldenTaskProfile): Promise<GoldenTaskFixture> {\n const workspace = await createBaseWorkspace(profile.id);\n await mkdir(join(workspace, \".tania/artifacts/backend\"), { recursive: true });\n await mkdir(join(workspace, \"app/api/health\"), { recursive: true });\n await mkdir(join(workspace, \"lib\"), { recursive: true });\n await mkdir(join(workspace, \"prisma\"), { recursive: true });\n await writeFile(join(workspace, \".tania/artifacts/backend/JwtAuthRoutes.ts\"), \"export function authRoutePattern() {}\\n\");\n await writeFile(join(workspace, \"package.json\"), JSON.stringify({ scripts: { typecheck: \"tsc --noEmit\", test: \"node --test\" }, dependencies: {} }, null, 2));\n\n const provider = scriptedProvider(profile.id, [\n {\n content: \"Create backend health/API foundation from the route artifact.\",\n toolCalls: [\n toolCall(\"read-artifact\", \"read_file\", { path: \".tania/artifacts/backend/JwtAuthRoutes.ts\" }),\n toolCall(\"write-health\", \"write_file\", {\n path: \"app/api/health/route.ts\",\n content: \"export async function GET() { return Response.json({ status: 'ok', health: true }); }\\n\",\n }),\n toolCall(\"write-openapi\", \"write_file\", {\n path: \"lib/openapi.ts\",\n content: \"export const openApiSpec = { paths: { '/api/health': { get: { summary: 'health' } } } };\\n\",\n }),\n toolCall(\"write-prisma\", \"write_file\", {\n path: \"prisma/schema.prisma\",\n content: \"datasource db { provider = \\\"postgresql\\\" url = env(\\\"DATABASE_URL\\\") }\\ngenerator client { provider = \\\"prisma-client-js\\\" }\\nmodel User { id String @id }\\n\",\n }),\n toolCall(\"write-env\", \"write_file\", {\n path: \".env.example\",\n content: [\n \"# Managed deploy provisions PostgreSQL.\",\n \"# Set DATABASE_URL and DIRECT_URL before seed:mock-data and seed:test-account actions.\",\n \"DATABASE_URL=\\\"replace-me-managed-postgresql-url\\\"\",\n \"DIRECT_URL=\\\"replace-me-managed-postgresql-direct-url\\\"\",\n \"\",\n ].join(\"\\n\"),\n }),\n toolCall(\"verify\", \"run_shell\", { script: \"node -e \\\"require('fs').accessSync('app/api/health/route.ts'); console.log('typecheck')\\\"\" }),\n ],\n },\n {\n content: [\n \"Artifact reused: artifacts/backend/JwtAuthRoutes.ts -> app/api/health/route.ts\",\n \"Artifact created: none\",\n \"Modified: app/api/health/route.ts\",\n \"Modified: lib/openapi.ts\",\n \"Modified: prisma/schema.prisma\",\n \"Modified: .env.example\",\n \"Verification: node -e route exists -> passed\",\n \"Blocked: none\",\n ].join(\"\\n\"),\n },\n ]);\n\n return {\n workspace,\n prompt: \"Implement backend API foundation with health endpoint, OpenAPI seed, Prisma schema, and env example.\",\n provider,\n runContext: {\n task: { kind: \"coding\", title: \"Backend API Foundation\", summary: profile.purpose },\n artifacts: [{ path: \".tania/artifacts/backend/JwtAuthRoutes.ts\", sourcePath: \"artifacts/backend/JwtAuthRoutes.ts\", status: \"available\" }],\n expected_report: { verification: true, artifact_reuse: true },\n metadata: { goldenTaskCandidate: true, caller: \"tanya-golden\" },\n },\n };\n}\n\nexport function goldenRunnableProfiles(): GoldenTaskProfile[] {\n const runnable = new Set([\n \"tanya.medium.streaming-long-tool\",\n \"tanya.medium.compaction-boundary\",\n \"tanya.medium.edit-block-fuzzy\",\n ...Object.keys(GENERIC_BENCHMARK_SPECS),\n ]);\n return loadGoldenTaskProfiles().filter((profile) => runnable.has(profile.id));\n}\n\nasync function createFixture(profile: GoldenTaskProfile): Promise<GoldenTaskFixture> {\n if (profile.id === \"tanya.medium.streaming-long-tool\") return streamingLongToolFixture(profile);\n if (profile.id === \"tanya.medium.compaction-boundary\") return compactionBoundaryFixture(profile);\n if (profile.id === \"tanya.medium.edit-block-fuzzy\") return editBlockFuzzyFixture(profile);\n if (profile.id in GENERIC_BENCHMARK_SPECS) return genericBenchmarkFixture(profile);\n throw new Error(`Golden profile is not executable yet: ${profile.id}`);\n}\n\nasync function runFixture(profile: GoldenTaskProfile, fixture: GoldenTaskFixture): Promise<GoldenRunResult> {\n const events: TanyaEvent[] = [];\n const { message: finalText } = await runAgent({\n provider: fixture.provider,\n prompt: fixture.prompt,\n cwd: fixture.workspace,\n sink: async (event) => { events.push(event); },\n runContext: fixture.runContext,\n });\n const problems = [\n ...finalText.matchAll(/\"severity\"\\s*:\\s*\"error\"[\\s\\S]{0,220}?\"id\"\\s*:\\s*\"([^\"]+)\"/g),\n ].map((match) => match[1] ?? \"validation-error\");\n if (profile.id === \"tanya.medium.streaming-long-tool\" && !events.some((event) => event.type === \"tool_progress\")) {\n problems.push(\"missing-tool-progress\");\n }\n if (profile.id === \"tanya.medium.compaction-boundary\" && !events.some((event) => event.type === \"compact_event\" && event.compactType === \"auto\")) {\n problems.push(\"missing-auto-compaction\");\n }\n const blocked = finalText\n .split(/\\r?\\n/)\n .some((line) => {\n const match = line.trim().match(/^Blocked:\\s*(.+)$/i);\n return !!match?.[1] && !/^none\\b/i.test(match[1].trim());\n });\n return {\n profile,\n workspace: fixture.workspace,\n passed: !blocked && problems.length === 0,\n finalText,\n problems,\n turns: (fixture.provider as ChatProvider & { requests?: ChatRequest[] }).requests?.length ?? events.filter((event) => event.type === \"message_start\").length,\n };\n}\n\nexport async function runGoldenTask(profileId: string): Promise<GoldenRunResult> {\n const profile = loadGoldenTaskProfiles().find((item) => item.id === profileId);\n if (!profile) throw new Error(`Unknown golden profile: ${profileId}`);\n const fixture = await createFixture(profile);\n return runFixture(profile, fixture);\n}\n\nexport async function runEditBlockFuzzyGoldenComparison(): Promise<{\n enabled: GoldenRunResult;\n disabled: GoldenRunResult;\n}> {\n const profile = loadGoldenTaskProfiles().find((item) => item.id === \"tanya.medium.edit-block-fuzzy\");\n if (!profile) throw new Error(\"Unknown golden profile: tanya.medium.edit-block-fuzzy\");\n const enabled = await runFixture(profile, await editBlockFuzzyFixture(profile, \"enabled\"));\n const disabled = await runFixture(profile, await editBlockFuzzyFixture(profile, \"disabled\"));\n return { enabled, disabled };\n}\n","import { buildGoldenTaskSummary, readGoldenTaskMemory, validateGoldenTaskSummary } from \"../memory/goldenTasks\";\nimport { BUILT_IN_GOLDEN_TASK_PROFILES, loadGoldenTaskProfiles } from \"./profiles\";\nimport { goldenRunnableProfiles, runGoldenTask } from \"./run\";\n\nexport async function runGoldenSuiteCommand(workspace: string, action: string, json = false, options: { profile?: string; all?: boolean } = {}): Promise<number> {\n const records = await readGoldenTaskMemory(workspace);\n const summary = buildGoldenTaskSummary(records);\n const problems = validateGoldenTaskSummary(summary);\n\n if (action === \"run\") {\n const profiles = options.all\n ? goldenRunnableProfiles()\n : [options.profile ?? \"tanya.low.search-replace\"]\n .map((profileId) => loadGoldenTaskProfiles().find((profile) => profile.id === profileId))\n .filter((profile): profile is NonNullable<typeof profile> => !!profile);\n if (profiles.length === 0) {\n const message = `No executable golden profile matched ${options.profile ?? \"(default)\"}.`;\n if (json) console.log(JSON.stringify({ results: [], problems: [message] }, null, 2));\n else console.log(message);\n return 1;\n }\n const results = [];\n for (const profile of profiles) results.push(await runGoldenTask(profile.id));\n if (json) {\n console.log(JSON.stringify({\n results: results.map((result) => ({\n profileId: result.profile.id,\n title: result.profile.title,\n workspace: result.workspace,\n passed: result.passed,\n problems: result.problems,\n })),\n }, null, 2));\n } else {\n for (const result of results) {\n console.log(`${result.passed ? \"PASS\" : \"FAIL\"} ${result.profile.id} ${result.profile.title}`);\n console.log(` workspace: ${result.workspace}`);\n if (result.problems.length > 0) console.log(` problems: ${result.problems.join(\", \")}`);\n }\n }\n return results.every((result) => result.passed) ? 0 : 1;\n }\n\n if (json) {\n const profiles = loadGoldenTaskProfiles();\n console.log(JSON.stringify({\n summary,\n problems,\n profiles: action === \"profiles\" ? profiles : undefined,\n executableProfiles: action === \"profiles\" ? goldenRunnableProfiles().map((profile) => profile.id) : undefined,\n }, null, 2));\n return action === \"validate\" && problems.length > 0 ? 1 : 0;\n }\n\n if (action === \"profiles\") {\n const profiles = loadGoldenTaskProfiles();\n if (profiles.length === BUILT_IN_GOLDEN_TASK_PROFILES.length) {\n console.log(`Built-in golden task profiles: ${BUILT_IN_GOLDEN_TASK_PROFILES.length}`);\n } else {\n console.log(`Golden task profiles: ${profiles.length} (${BUILT_IN_GOLDEN_TASK_PROFILES.length} built-in, ${profiles.length - BUILT_IN_GOLDEN_TASK_PROFILES.length} integration)`);\n }\n const runnable = goldenRunnableProfiles();\n for (const profile of profiles) {\n const executable = runnable.some((item) => item.id === profile.id) ? \" executable\" : \"\";\n console.log(`${profile.id} [${profile.platform}${executable}] ${profile.title}`);\n console.log(` ${profile.purpose}`);\n console.log(` capabilities: ${profile.requiredCapabilities.join(\", \")}`);\n }\n return 0;\n }\n\n if (action === \"list\") {\n if (summary.latestBySignature.length === 0) {\n console.log(\"No golden task records found.\");\n return 0;\n }\n for (const record of summary.latestBySignature) {\n const title = record.task?.title ?? record.signature;\n console.log(`${record.outcome.toUpperCase()} ${record.signature} ${title}`);\n }\n return 0;\n }\n\n console.log(`Golden tasks: ${summary.total} record(s), ${summary.signatures} signature(s), ${summary.passed} passed, ${summary.failed} failed.`);\n if (summary.failureReasons.length > 0) {\n console.log(\"Top failure reasons:\");\n for (const reason of summary.failureReasons.slice(0, 8)) console.log(`- ${reason.reason}: ${reason.count}`);\n }\n if (action === \"validate\") {\n if (problems.length === 0) {\n console.log(\"Golden suite validation passed.\");\n return 0;\n }\n console.log(\"Golden suite validation failed:\");\n for (const problem of problems) console.log(`- ${problem}`);\n return 1;\n }\n return 0;\n}\n","import { mkdir, readFile, readdir, stat, writeFile } from \"node:fs/promises\";\nimport { dirname, join, resolve } from \"node:path\";\n\ntype PackageJson = {\n scripts?: Record<string, unknown>;\n dependencies?: Record<string, unknown>;\n devDependencies?: Record<string, unknown>;\n};\n\ntype StackDetection = {\n projectTypes: string[];\n verificationCommands: string[];\n signals: string[];\n};\n\nasync function fileExists(path: string): Promise<boolean> {\n try {\n const entry = await stat(path);\n return entry.isFile() || entry.isDirectory();\n } catch {\n return false;\n }\n}\n\nasync function readPackageJson(workspace: string): Promise<PackageJson | null> {\n const packagePath = join(workspace, \"package.json\");\n try {\n return JSON.parse(await readFile(packagePath, \"utf8\")) as PackageJson;\n } catch {\n return null;\n }\n}\n\nfunction hasDependency(pkg: PackageJson | null, name: string): boolean {\n return !!pkg && (Object.hasOwn(pkg.dependencies ?? {}, name) || Object.hasOwn(pkg.devDependencies ?? {}, name));\n}\n\nfunction scriptCommand(pkg: PackageJson | null, scriptName: \"typecheck\" | \"build\" | \"test\"): string | null {\n const script = pkg?.scripts?.[scriptName];\n return typeof script === \"string\" && script.trim() ? `npm run ${scriptName}` : null;\n}\n\nasync function rootEntries(workspace: string): Promise<string[]> {\n try {\n return await readdir(workspace);\n } catch {\n return [];\n }\n}\n\nfunction unique(values: string[]): string[] {\n return [...new Set(values)];\n}\n\nasync function detectStack(workspace: string): Promise<StackDetection> {\n const pkg = await readPackageJson(workspace);\n const entries = await rootEntries(workspace);\n const hasPackageJson = pkg !== null;\n const hasPrisma = await fileExists(join(workspace, \"prisma\", \"schema.prisma\"));\n const hasNextConfig = entries.some((entry) => /^next\\.config\\.(?:js|mjs|cjs|ts)$/.test(entry));\n const hasTsconfig = await fileExists(join(workspace, \"tsconfig.json\"));\n const hasGradlew = await fileExists(join(workspace, \"gradlew\"));\n const xcodeProjects = entries.filter((entry) => entry.endsWith(\".xcodeproj\"));\n\n const projectTypes: string[] = [];\n if (hasNextConfig || hasDependency(pkg, \"next\")) projectTypes.push(\"Next.js\");\n if (hasGradlew) projectTypes.push(\"Android\");\n if (xcodeProjects.length > 0) projectTypes.push(\"iOS\");\n if (hasPackageJson && projectTypes.length === 0) projectTypes.push(\"Node\");\n if (projectTypes.length === 0) projectTypes.push(\"Unknown\");\n\n const verificationCommands = [\n scriptCommand(pkg, \"typecheck\") ?? (hasTsconfig ? \"npx tsc --noEmit\" : null),\n scriptCommand(pkg, \"build\"),\n scriptCommand(pkg, \"test\"),\n hasPrisma ? \"npx prisma generate\" : null,\n hasGradlew ? \"./gradlew assembleDebug --no-daemon\" : null,\n ...xcodeProjects.map((project) => `xcodebuild -list -project '${project}'`),\n ].filter((command): command is string => !!command);\n\n const signals = [\n hasPackageJson ? \"package.json\" : null,\n hasPrisma ? \"prisma/schema.prisma\" : null,\n hasNextConfig ? entries.find((entry) => /^next\\.config\\.(?:js|mjs|cjs|ts)$/.test(entry)) ?? \"next.config.*\" : null,\n hasTsconfig ? \"tsconfig.json\" : null,\n hasGradlew ? \"gradlew\" : null,\n ...xcodeProjects,\n ].filter((signal): signal is string => !!signal);\n\n return {\n projectTypes: unique(projectTypes),\n verificationCommands: unique(verificationCommands),\n signals: unique(signals),\n };\n}\n\nfunction buildInstructions(detection: StackDetection): string {\n const verificationLines = detection.verificationCommands.length > 0\n ? detection.verificationCommands.map((command) => `- \\`${command}\\``)\n : [\"- Add project-specific verification commands here.\"];\n const signalLines = detection.signals.length > 0\n ? detection.signals.map((signal) => `- ${signal}`)\n : [\"- No common stack markers detected.\"];\n\n return [\n \"# Tanya Project Instructions\",\n \"\",\n `Project type: ${detection.projectTypes.join(\" / \")}`,\n \"\",\n \"## Detected Stack Signals\",\n ...signalLines,\n \"\",\n \"## Verification Commands\",\n ...verificationLines,\n \"\",\n \"## Custom Instructions\",\n \"- Add project-specific rules, safety constraints, architecture notes, and preferred workflows here.\",\n \"\",\n ].join(\"\\n\");\n}\n\nexport async function initTanyaProject(cwd: string): Promise<string> {\n const workspace = resolve(cwd);\n const instructionsPath = join(workspace, \".tania\", \"INSTRUCTIONS.md\");\n const detection = await detectStack(workspace);\n await mkdir(dirname(instructionsPath), { recursive: true });\n try {\n await writeFile(instructionsPath, buildInstructions(detection), { encoding: \"utf8\", flag: \"wx\" });\n } catch (error) {\n const code = typeof error === \"object\" && error !== null && \"code\" in error ? String((error as { code?: unknown }).code) : \"\";\n if (code === \"EEXIST\") throw new Error(`${instructionsPath} already exists. Refusing to overwrite.`);\n throw error;\n }\n return instructionsPath;\n}\n","import type { TanyaRunContext } from \"./runContext\";\nimport { buildTaskBrief, type TanyaTaskBrief } from \"../tools/projectContextTools\";\nimport { materializeObsidianContext } from \"../obsidian/search\";\n\nexport type AutoRunContextOptions = {\n cwd: string;\n prompt: string;\n runContext?: TanyaRunContext;\n obsidianVault?: string | undefined;\n enableBrief?: boolean | undefined;\n enableObsidian?: boolean | undefined;\n keepContext?: boolean | undefined;\n};\n\nfunction unique(values: string[]): string[] {\n return [...new Set(values.filter((value) => value.trim().length > 0))];\n}\n\nfunction shouldTreatAsCodingTask(brief: TanyaTaskBrief, runContext?: TanyaRunContext): boolean {\n if (runContext?.task?.kind === \"coding\") return true;\n if (runContext?.expected_report && Object.keys(runContext.expected_report).length > 0) return true;\n if (runContext?.verification?.commands?.length) return true;\n if (runContext?.artifacts?.length || runContext?.contextFiles?.length) return true;\n return brief.signals.platforms.length > 0 || brief.signals.domains.length > 0;\n}\n\nexport async function buildAutoRunContext(options: AutoRunContextOptions): Promise<TanyaRunContext | undefined> {\n let runContext = options.runContext;\n let brief: TanyaTaskBrief | undefined;\n const instructions: string[] = [...(runContext?.instructions ?? [])];\n const contextFiles: NonNullable<TanyaRunContext[\"contextFiles\"]> = [...(runContext?.contextFiles ?? [])];\n const metadata: Record<string, unknown> = { ...(runContext?.metadata ?? {}) };\n const expectedReport: Record<string, unknown> = { ...(runContext?.expected_report ?? {}) };\n const verificationCommands = [...(runContext?.verification?.commands ?? [])];\n let didMaterializeContext = false;\n\n if (options.enableBrief !== false) {\n brief = await buildTaskBrief({\n workspace: options.cwd,\n task: options.prompt,\n });\n metadata.autoBrief = brief;\n metadata.autoBriefEnforceArtifacts = brief.artifacts.length > 0;\n instructions.push(\n \"Tanya generated an automatic task brief before the run. Use it to choose context files, artifacts, capability packs, tools, and verification.\",\n \"If the automatic task brief lists artifact candidates and you change code, read at least one relevant artifact or explicitly explain why none applies before the final report.\",\n );\n if (shouldTreatAsCodingTask(brief, runContext)) {\n expectedReport.verification = true;\n expectedReport.artifact_reuse = true;\n expectedReport.context_review = true;\n // Skip auto-recommended verification commands when the caller explicitly\n // overrode the list (e.g. via --require-verification). Preserves caller intent.\n if (!metadata.verificationOverridden) {\n for (const command of brief.verification) verificationCommands.push(command);\n }\n runContext = {\n ...(runContext ?? {}),\n task: {\n ...(runContext?.task ?? {}),\n kind: \"coding\",\n title: runContext?.task?.title ?? brief.task.slice(0, 120),\n },\n };\n }\n }\n\n if (options.enableObsidian !== false && options.obsidianVault?.trim()) {\n const materialized = await materializeObsidianContext({\n workspace: options.cwd,\n vaultPath: options.obsidianVault,\n query: options.prompt,\n maxResults: 5,\n ...(options.keepContext !== undefined ? { keepContext: options.keepContext } : {}),\n });\n if (materialized.contextFiles.length > 0) {\n didMaterializeContext = true;\n contextFiles.push(...materialized.contextFiles);\n metadata.obsidianContext = {\n vaultConfigured: true,\n noteCount: materialized.notes.length,\n notes: materialized.notes.map((note) => ({\n path: note.path,\n title: note.title,\n score: note.score,\n reason: note.reason,\n })),\n };\n instructions.push(\n \"Relevant Obsidian note excerpts were materialized under .tania/context/obsidian.\",\n \"Read relevant Obsidian context paths before implementing if the task depends on prior decisions, project memory, or historical fixes.\",\n );\n } else {\n metadata.obsidianContext = { vaultConfigured: true, noteCount: 0 };\n }\n }\n\n if (!brief && contextFiles.length === 0 && instructions.length === (runContext?.instructions?.length ?? 0)) {\n return runContext;\n }\n\n return {\n ...(runContext ?? {}),\n ...(runContext?.task ? { task: runContext.task } : {}),\n ...(contextFiles.length > 0 ? { contextFiles } : {}),\n ...(instructions.length > 0 ? { instructions: unique(instructions) } : {}),\n ...(verificationCommands.length > 0 ? { verification: { commands: unique(verificationCommands) } } : {}),\n ...(Object.keys(expectedReport).length > 0 ? { expected_report: expectedReport } : {}),\n metadata: {\n ...metadata,\n autoContext: true,\n tanyaMaterializedContext: didMaterializeContext,\n keepMaterializedContext: options.keepContext === true,\n ...(options.obsidianVault ? { obsidianVault: options.obsidianVault } : {}),\n },\n };\n}\n","import { readRunLogs } from \"../../memory/runLogs\";\nimport type { PermissionRulesConfig } from \"./schema\";\n\nexport const BUILT_IN_ALWAYS_ALLOW_SEED = [\n \"read_file:.*\",\n \"glob:.*\",\n \"list_files:.*\",\n \"run_shell:ls.*\",\n \"run_shell:git status.*\",\n \"run_shell:git diff.*\",\n];\n\nexport function suggestPermissionsFromRuns(workspace: string, limit = 100): PermissionRulesConfig {\n const counts = new Map<string, number>();\n for (const log of readRunLogs(workspace, limit)) {\n for (const file of log.changedFiles) {\n if (!file || file.startsWith(\".tania/\") || file.startsWith(\".tanya/\")) continue;\n const escaped = escapeRegex(JSON.stringify(file));\n counts.set(`write_file:.*${escaped}.*`, (counts.get(`write_file:.*${escaped}.*`) ?? 0) + 1);\n }\n if (log.blockers.length === 0) {\n counts.set(\"run_command:.*node.*\", (counts.get(\"run_command:.*node.*\") ?? 0) + 1);\n }\n }\n\n const frequent = [...counts.entries()]\n .sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))\n .slice(0, 25)\n .map(([pattern]) => pattern);\n\n return {\n version: 1,\n mode: \"ask\",\n alwaysAllow: unique([...BUILT_IN_ALWAYS_ALLOW_SEED, ...frequent]),\n alwaysDeny: [],\n alwaysAsk: [],\n pathRules: [],\n spendRules: [],\n };\n}\n\nfunction unique(values: string[]): string[] {\n return [...new Set(values)];\n}\n\nfunction escapeRegex(value: string): string {\n return value.replace(/[|\\\\{}()[\\]^$+?.]/g, \"\\\\$&\");\n}\n","import { resolve } from \"node:path\";\nimport { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { StdioServerTransport } from \"@modelcontextprotocol/sdk/server/stdio.js\";\nimport { z } from \"zod\";\nimport { captureGitSnapshot } from \"../agent/git\";\nimport { buildFinalManifest, ensureCodingReport } from \"../agent/report\";\nimport { runAgent, type RunAgentOptions } from \"../agent/runner\";\nimport { loadConfig } from \"../config/env\";\nimport type { TanyaEvent } from \"../events/types\";\nimport { createProvider } from \"../providers/factory\";\nimport type { ChatProvider } from \"../providers/types\";\nimport { readGoldenTaskMemory } from \"../memory/goldenTasks\";\nimport { loadPromptSkillPacks } from \"../agent/systemPrompt\";\n\nexport interface TanyaMcpServerOptions {\n defaultCwd?: string;\n providerFactory?: (cwd: string) => ChatProvider;\n runAgentFn?: (options: RunAgentOptions) => Promise<Awaited<ReturnType<typeof runAgent>>>;\n}\n\nexport function createTanyaMcpServer(options: TanyaMcpServerOptions = {}): McpServer {\n const server = new McpServer({ name: \"tanya\", version: \"0.10.0-beta.0\" });\n const defaultCwd = () => resolve(options.defaultCwd ?? process.cwd());\n\n server.registerTool(\"tanya.verify\", {\n description: \"Run Tanya's deterministic verifier for a workspace path.\",\n inputSchema: {\n path: z.string().optional(),\n },\n }, async (args) => {\n const workspace = resolve(args.path ?? defaultCwd());\n const beforeGitSnapshot = await captureGitSnapshot(workspace);\n const manifest = await buildFinalManifest({\n workspace,\n beforeGitSnapshot,\n changed: [],\n verificationLines: [],\n toolErrorCount: 0,\n readArtifactPaths: [],\n readContextPaths: [],\n createdArtifactPaths: [],\n blockers: [],\n prompt: \"MCP tanya.verify\",\n });\n const report = ensureCodingReport(\"\", manifest).trim();\n const validationErrors = manifest.validation?.issues.filter((issue) => issue.severity === \"error\") ?? [];\n const blockers = [...manifest.blockers, ...validationErrors.map((issue) => issue.message)];\n const verdict = blockers.length === 0 ? \"passed\" : \"failed\";\n return {\n structuredContent: { verdict, blockers, manifest },\n content: [{ type: \"text\" as const, text: report || \"No verifier evidence available for this workspace.\" }],\n };\n });\n\n server.registerTool(\"tanya.golden_task_search\", {\n description: \"Search Tanya golden task memory by substring across signature, title, outcome, and blockers.\",\n inputSchema: {\n query: z.string(),\n limit: z.number().optional(),\n },\n }, async (args) => {\n const query = args.query.toLowerCase();\n const limit = Math.max(1, Math.min(50, Math.floor(args.limit ?? 10)));\n const records = (await readGoldenTaskMemory(defaultCwd()))\n .filter((record) => JSON.stringify({\n signature: record.signature,\n title: record.task?.title,\n kind: record.task?.kind,\n outcome: record.outcome,\n blockers: record.blockers,\n }).toLowerCase().includes(query))\n .slice(-limit)\n .reverse();\n return {\n structuredContent: { records },\n content: [{ type: \"text\" as const, text: records.length ? JSON.stringify(records, null, 2) : \"No matching golden tasks.\" }],\n };\n });\n\n server.registerTool(\"tanya.run\", {\n description: \"Run a one-shot Tanya agent task.\",\n inputSchema: {\n prompt: z.string(),\n cwd: z.string().optional(),\n max_turns: z.number().optional(),\n },\n }, async (args, extra) => {\n const mcpDepth = typeof extra._meta?.[\"tanya/mcp-depth\"] === \"number\"\n ? extra._meta[\"tanya/mcp-depth\"]\n : 0;\n if (mcpDepth > 1) {\n return {\n isError: true,\n structuredContent: { ok: false, error: \"recursive MCP loop detected\", depth: mcpDepth },\n content: [{ type: \"text\" as const, text: \"recursive MCP loop detected: Tanya MCP depth > 1\" }],\n };\n }\n const cwd = resolve(args.cwd ?? defaultCwd());\n const provider = options.providerFactory ? options.providerFactory(cwd) : createProvider(loadConfig(cwd));\n const events: TanyaEvent[] = [];\n const run = options.runAgentFn ?? runAgent;\n const result = await run({\n provider,\n prompt: args.prompt,\n cwd,\n sink: async (event) => { events.push(event); },\n ...(args.max_turns !== undefined ? { maxTurns: Math.max(1, Math.floor(args.max_turns)) } : {}),\n signal: extra.signal,\n });\n const streamedEvents = events.filter((event) => event.type === \"subtask_started\" || event.type === \"subtask_completed\");\n return {\n structuredContent: {\n message: result.message,\n manifest: result.manifest,\n metrics: result.metrics,\n events: streamedEvents,\n },\n content: [{ type: \"text\" as const, text: result.message }],\n };\n });\n\n server.registerTool(\"tanya.skills_list\", {\n description: \"List Tanya skill packs loaded for a workspace.\",\n inputSchema: {\n cwd: z.string().optional(),\n },\n }, async (args) => {\n const cwd = resolve(args.cwd ?? defaultCwd());\n const skills = loadPromptSkillPacks(cwd).map((pack) => ({\n slug: pack.slug,\n title: pack.title,\n sourcePath: pack.sourcePath,\n tokens: pack.tokens,\n reason: pack.reason,\n }));\n return {\n structuredContent: { skills },\n content: [{ type: \"text\" as const, text: skills.length ? JSON.stringify(skills, null, 2) : \"No skill packs loaded.\" }],\n };\n });\n\n return server;\n}\n\nexport async function serveTanyaMcpServer(options: TanyaMcpServerOptions = {}): Promise<void> {\n const server = createTanyaMcpServer(options);\n await server.connect(new StdioServerTransport());\n}\n","import type { EvalSuite, EvalTask } from \"../schemas\";\n\nconst categories = [\n \"long-file-read-dedup\",\n \"large-tool-result-truncation\",\n \"reasoning-heavy-planning\",\n \"system-prompt-budget\",\n \"repo-map-targeting\",\n \"fuzzy-edit-recovery\",\n] as const;\n\nfunction ecoTask(index: number): EvalTask {\n const category = categories[index % categories.length] ?? \"long-file-read-dedup\";\n return {\n id: `eco-${String(index + 1).padStart(2, \"0\")}-${category}`,\n repo_setup: { type: \"local_fixture\", path: `builtin:eco-30/${category}` },\n prompt: ecoPrompt(category),\n expected_files: category === \"long-file-read-dedup\" ? [] : [`src/eco-${index + 1}.ts`],\n metadata: {\n category,\n providerTier: \"cheap\",\n measures: [\"input_tokens\", \"output_tokens\", \"reasoning_tokens\", \"system_prompt_tokens\", \"cost_usd\"],\n },\n };\n}\n\nexport function eco30Suite(): EvalSuite {\n return {\n name: \"eco-30\",\n version: \"2026-05\",\n tasks: Array.from({ length: 30 }, (_, index) => ecoTask(index)),\n };\n}\n\nfunction ecoPrompt(category: string): string {\n switch (category) {\n case \"long-file-read-dedup\":\n return \"Inspect a repeated long file read pattern and avoid resending unchanged content.\";\n case \"large-tool-result-truncation\":\n return \"Run a large-output verification command and use expand_result only for necessary ranges.\";\n case \"reasoning-heavy-planning\":\n return \"Plan a multi-file repair while staying within the reasoning token cap.\";\n case \"system-prompt-budget\":\n return \"Complete a small task under a tight system-prompt budget.\";\n case \"repo-map-targeting\":\n return \"Use structural context to identify the right file before reading broadly.\";\n case \"fuzzy-edit-recovery\":\n return \"Recover a near-match edit block without rewriting the entire file.\";\n default:\n return \"Complete the token-economy fixture.\";\n }\n}\n","import type { EvalSuite, EvalTask } from \"../schemas\";\n\ntype MvpTaskSpec = {\n id: string;\n title: string;\n prompt: string;\n expectedFiles: string[];\n capMinutes: number;\n capUsd: number;\n};\n\nconst tasks: MvpTaskSpec[] = [\n {\n id: \"mvp-01\",\n title: \"Python todo CLI\",\n prompt: [\n \"Build a one-file Python todo CLI with add, list, done, and delete commands.\",\n \"Persist tasks to a JSON file in the project directory.\",\n \"Include a short README with example commands.\",\n \"Verify it by running at least one add/list/done/delete flow.\",\n ].join(\" \"),\n expectedFiles: [\"todo.py\", \"README.md\"],\n capMinutes: 5,\n capUsd: 0.05,\n },\n {\n id: \"mvp-02\",\n title: \"Express notes REST API\",\n prompt: [\n \"Build a Node.js Express REST API for an in-memory notes resource.\",\n \"Implement GET /notes, POST /notes, PUT /notes/:id, and DELETE /notes/:id.\",\n \"Include package.json, server code, and README.md with curl examples.\",\n \"Use a conventional startup shape: export the Express app from src/server.js as module.exports/app/default, and only call app.listen when the file is run directly.\",\n \"Verify the app can start and the routes are wired.\",\n ].join(\" \"),\n expectedFiles: [\"package.json\", \"src/server.js\", \"README.md\"],\n capMinutes: 10,\n capUsd: 0.10,\n },\n {\n id: \"mvp-03\",\n title: \"Hacker News top stories scraper\",\n prompt: [\n \"Build a Python script that scrapes today's top 10 stories from news.ycombinator.com into stories.json.\",\n \"Use requests and beautifulsoup4.\",\n \"Include requirements.txt and README.md.\",\n \"If dependency install or live network access fails twice, pivot to a deterministic local mock fallback, still write stories.json, and document mock versus live behavior in README.md.\",\n \"Verify the script runs or document the exact network limitation if the live request is unavailable.\",\n ].join(\" \"),\n expectedFiles: [\"hn_top.py\", \"requirements.txt\", \"README.md\", \"stories.json\"],\n capMinutes: 5,\n capUsd: 0.05,\n },\n {\n id: \"mvp-04\",\n title: \"Static landing page\",\n prompt: [\n \"Build a static landing page using index.html and Tailwind via CDN.\",\n \"Include a hero, features section, pricing section, and footer.\",\n \"No build step. Keep it polished and readable.\",\n \"Verify the HTML is self-contained.\",\n ].join(\" \"),\n expectedFiles: [\"index.html\"],\n capMinutes: 10,\n capUsd: 0.10,\n },\n {\n id: \"mvp-05\",\n title: \"Python curses Snake game\",\n prompt: [\n \"Build a simple terminal Snake game in Python using curses.\",\n \"Include movement, food spawning, score display, collision handling, and graceful quit.\",\n \"Keep it in one file plus README.md.\",\n \"Verify syntax without requiring an interactive terminal.\",\n ].join(\" \"),\n expectedFiles: [\"snake.py\", \"README.md\"],\n capMinutes: 15,\n capUsd: 0.15,\n },\n {\n id: \"mvp-06\",\n title: \"JSON to CSV converter\",\n prompt: [\n \"Use the provided data/input.json fixture.\",\n \"Build a Python converter using pandas that writes output.csv with columns id,name,email,plan.\",\n \"Include requirements.txt and README.md.\",\n \"Verify the converter runs and output.csv has the expected header and row count.\",\n ].join(\" \"),\n expectedFiles: [\"convert.py\", \"requirements.txt\", \"README.md\", \"output.csv\"],\n capMinutes: 5,\n capUsd: 0.05,\n },\n {\n id: \"mvp-07\",\n title: \"Rust prime CLI\",\n prompt: [\n \"Build a Rust CLI that answers whether an integer is prime.\",\n \"Use cargo init or equivalent project structure.\",\n \"Support cargo run -- 17 and cargo run -- 18.\",\n \"Verify with cargo run and include README.md examples.\",\n ].join(\" \"),\n expectedFiles: [\"Cargo.toml\", \"src/main.rs\", \"README.md\"],\n capMinutes: 10,\n capUsd: 0.10,\n },\n {\n id: \"mvp-08\",\n title: \"Vitest fizzbuzz tests\",\n prompt: [\n \"The project already contains src/fizzbuzz.js.\",\n \"Write at least 5 Vitest unit tests covering fizz, buzz, fizzbuzz, normal numbers, and edge behavior.\",\n \"Add package.json if needed and verify npm test passes.\",\n \"Do not rewrite the implementation unless a test proves it is necessary.\",\n ].join(\" \"),\n expectedFiles: [\"src/fizzbuzz.js\", \"package.json\"],\n capMinutes: 5,\n capUsd: 0.05,\n },\n {\n id: \"mvp-09\",\n title: \"Fix Python stats bug\",\n prompt: [\n \"Fix the known bug in stats.py.\",\n \"The current script has an off-by-one error and does not handle None values.\",\n \"Make the smallest reasonable change, add or update tests if useful, and verify python stats.py runs successfully.\",\n ].join(\" \"),\n expectedFiles: [\"stats.py\"],\n capMinutes: 5,\n capUsd: 0.05,\n },\n {\n id: \"mvp-10\",\n title: \"Commander TypeScript CLI\",\n prompt: [\n \"Build a slash-command-style CLI tool in TypeScript using commander.\",\n \"Subcommands: init, add <item>, list, remove <id>.\",\n \"Persist data to a local JSON file.\",\n \"Use a conventional startup shape: export the Commander program from src/index.ts and call program.parse only when run as the CLI entry.\",\n \"Include package.json, tsconfig.json, source code, README.md, and verify the CLI commands run.\",\n ].join(\" \"),\n expectedFiles: [\"package.json\", \"tsconfig.json\", \"src/index.ts\", \"README.md\"],\n capMinutes: 15,\n capUsd: 0.15,\n },\n];\n\nexport function mvpSuite(): EvalSuite {\n return {\n name: \"mvp\",\n version: \"2026-05\",\n tasks: tasks.map(toEvalTask),\n };\n}\n\nfunction toEvalTask(task: MvpTaskSpec): EvalTask {\n return {\n id: task.id,\n repo_setup: { type: \"local_fixture\", path: `src/eval/suites/mvp-fixtures/${task.id}` },\n prompt: [\n task.prompt,\n \"\",\n \"First-time-user MVP validation criteria:\",\n `- Expected files: ${task.expectedFiles.join(\", \")}`,\n `- Soft cap: ${task.capMinutes} minutes / $${task.capUsd.toFixed(2)}.`,\n \"- Prefer simple, conventional code over clever abstractions.\",\n \"- Run the most relevant local verification command before finalizing.\",\n \"- Final report must state what was built, how it was verified, and any limitations.\",\n ].join(\"\\n\"),\n expected_files: task.expectedFiles,\n verifier_extension: `src/eval/suites/mvp-fixtures/${task.id}/verify.md`,\n metadata: {\n title: task.title,\n capMinutes: task.capMinutes,\n capUsd: task.capUsd,\n perspective: \"first-time-community-user\",\n },\n };\n}\n","import type { EvalSuite, EvalTask } from \"../schemas\";\n\nexport const SWE_BENCH_LITE_REPO = \"https://github.com/SWE-bench/SWE-bench.git\";\nexport const SWE_BENCH_LITE_COMMIT = \"f7bbbb2ccdf479001d6467c9e34af59e44a840f9\";\n\nexport function sweBenchLiteSuite(): EvalSuite {\n const tasks: EvalTask[] = Array.from({ length: 30 }, (_, index) => ({\n id: `swe-lite-${String(index + 1).padStart(2, \"0\")}`,\n repo_setup: {\n type: \"git_clone\",\n url: SWE_BENCH_LITE_REPO,\n commit: SWE_BENCH_LITE_COMMIT,\n path: `.tania/eval/datasets/swe-bench-lite/${String(index + 1).padStart(2, \"0\")}`,\n },\n prompt: `Run the pinned SWE-bench-Lite task ${index + 1} through Tanya's verifier-aware workflow.`,\n metadata: {\n dataset: \"SWE-bench-Lite\",\n pinnedCommit: SWE_BENCH_LITE_COMMIT,\n cacheDir: \".tania/eval/datasets/swe-bench-lite\",\n },\n }));\n return { name: \"swe-bench-lite\", version: `pinned-${SWE_BENCH_LITE_COMMIT.slice(0, 12)}`, tasks };\n}\n","import type { EvalSuite, EvalTask } from \"../schemas\";\n\nconst categories = [\n [\"long-bash\", \"Repair a long shell verification command and report the exact failing line.\"],\n [\"multi-file-edit\", \"Update two related TypeScript modules and keep their exports consistent.\"],\n [\"broken-patch\", \"Recover from a patch that does not apply cleanly by re-reading the file.\"],\n [\"dependency-install\", \"Add a tiny dependency and update the lockfile without unrelated churn.\"],\n [\"noop-confirmation\", \"Inspect the repo and confirm no code change is needed.\"],\n] as const;\n\nfunction nativeTask(index: number): EvalTask {\n const [category, prompt] = categories[index % categories.length] ?? categories[0];\n return {\n id: `native-${String(index + 1).padStart(2, \"0\")}-${category}`,\n repo_setup: { type: \"local_fixture\", path: `builtin:tanya-native/${category}` },\n prompt,\n expected_files: category === \"noop-confirmation\" ? [] : [`src/task-${index + 1}.ts`],\n metadata: { category, expectedVerdict: index % 7 === 0 ? \"failed\" : \"passed\" },\n };\n}\n\nexport function tanyaNativeSuite(): EvalSuite {\n return {\n name: \"tanya-native\",\n version: \"2026-05\",\n tasks: Array.from({ length: 25 }, (_, index) => nativeTask(index)),\n };\n}\n","import type { EvalSuite, EvalTask } from \"../schemas\";\n\nexport function verifierSelfTestSuite(): EvalSuite {\n const tasks: EvalTask[] = [\n verifierTask(\"verifier-self-01-correct-report\", \"passed\", \"Known-correct output includes changed files and passing verification.\"),\n verifierTask(\"verifier-self-02-missing-verification\", \"failed\", \"Known-incorrect output omits required verification evidence.\"),\n verifierTask(\"verifier-self-03-failed-test\", \"failed\", \"Known-incorrect output includes a failing test command.\"),\n verifierTask(\"verifier-self-04-noop-clean\", \"passed\", \"Known-correct no-op report has no changed files and no blockers.\"),\n ];\n return { name: \"verifier-self-test\", version: \"2026-05\", tasks };\n}\n\nfunction verifierTask(id: string, expectedVerdict: \"passed\" | \"failed\", prompt: string): EvalTask {\n return {\n id,\n repo_setup: { type: \"local_fixture\", path: `builtin:verifier-self-test/${id}` },\n prompt,\n metadata: {\n expectedVerifierVerdict: expectedVerdict,\n purpose: \"assert verifier classification, not model output\",\n },\n };\n}\n","import { readFileSync } from \"node:fs\";\nimport { discoverIntegrationEntries } from \"../../integrations/discovery\";\nimport type { EvalSuite, EvalTask } from \"../schemas\";\nimport { formatEvalSchemaIssues, validateEvalSuite } from \"../schemas\";\n\nexport type IntegrationSuiteFile = {\n name: string;\n version: string;\n tasks: EvalTask[];\n};\n\nfunction readJson(path: string): unknown {\n try {\n return JSON.parse(readFileSync(path, \"utf8\"));\n } catch {\n return null;\n }\n}\n\nfunction parseIntegrationSuite(path: string): EvalSuite | null {\n const parsed = readJson(path);\n const result = validateEvalSuite(parsed);\n if (result.ok) return result.data;\n console.warn(`[eval] Skipping integration suite ${path}: ${formatEvalSchemaIssues(result.issues)}`);\n return null;\n}\n\nexport function loadIntegrationEvalSuites(): EvalSuite[] {\n return discoverIntegrationEntries(\"suites\")\n .filter((entry) => entry.path.toLowerCase().endsWith(\".json\"))\n .map((entry) => parseIntegrationSuite(entry.path))\n .filter((suite): suite is EvalSuite => suite !== null);\n}\n","export type EvalRepoSetup =\n | { type: \"git_clone\"; url: string; commit: string; path?: string }\n | { type: \"local_fixture\"; path: string };\n\nexport type EvalTask = {\n id: string;\n repo_setup: EvalRepoSetup;\n prompt: string;\n expected_files?: string[];\n verifier_extension?: string;\n metadata?: Record<string, unknown>;\n};\n\nexport type EvalSuite = {\n name: string;\n version: string;\n tasks: EvalTask[];\n};\n\nexport type EvalSchemaIssue = {\n path: string;\n message: string;\n};\n\nexport type EvalValidationResult<T> =\n | { ok: true; data: T }\n | { ok: false; issues: EvalSchemaIssue[] };\n\nconst repoSetupTypes = new Set([\"git_clone\", \"local_fixture\"]);\n\nexport function validateEvalSuite(input: unknown): EvalValidationResult<EvalSuite> {\n const issues: EvalSchemaIssue[] = [];\n const root = asRecord(input);\n requireString(root, \"name\", \"/name\", issues);\n requireString(root, \"version\", \"/version\", issues);\n if (!Array.isArray(root?.tasks)) {\n issues.push({ path: \"/tasks\", message: \"tasks must be an array\" });\n } else {\n root.tasks.forEach((task, index) => validateTask(task, `/tasks/${index}`, issues));\n }\n return issues.length === 0 ? { ok: true, data: input as EvalSuite } : { ok: false, issues };\n}\n\nexport function assertEvalSuite(input: unknown): EvalSuite {\n const result = validateEvalSuite(input);\n if (result.ok) return result.data;\n throw new Error(formatEvalSchemaIssues(result.issues));\n}\n\nexport function formatEvalSchemaIssues(issues: EvalSchemaIssue[]): string {\n return issues.map((issue) => `${issue.path}: ${issue.message}`).join(\"\\n\");\n}\n\nfunction validateTask(input: unknown, path: string, issues: EvalSchemaIssue[]): void {\n const task = asRecord(input);\n requireString(task, \"id\", `${path}/id`, issues);\n requireString(task, \"prompt\", `${path}/prompt`, issues);\n validateRepoSetup(task?.repo_setup, `${path}/repo_setup`, issues);\n if (task?.expected_files !== undefined && !isStringArray(task.expected_files)) {\n issues.push({ path: `${path}/expected_files`, message: \"expected_files must be an array of strings\" });\n }\n if (task?.verifier_extension !== undefined && typeof task.verifier_extension !== \"string\") {\n issues.push({ path: `${path}/verifier_extension`, message: \"verifier_extension must be a string\" });\n }\n}\n\nfunction validateRepoSetup(input: unknown, path: string, issues: EvalSchemaIssue[]): void {\n const setup = asRecord(input);\n const type = typeof setup?.type === \"string\" ? setup.type : \"\";\n if (!repoSetupTypes.has(type)) {\n issues.push({ path: `${path}/type`, message: \"type must be git_clone or local_fixture\" });\n return;\n }\n if (type === \"git_clone\") {\n requireString(setup, \"url\", `${path}/url`, issues);\n requireString(setup, \"commit\", `${path}/commit`, issues);\n }\n if (type === \"local_fixture\") {\n requireString(setup, \"path\", `${path}/path`, issues);\n }\n}\n\nfunction asRecord(input: unknown): Record<string, unknown> | null {\n return input && typeof input === \"object\" && !Array.isArray(input)\n ? input as Record<string, unknown>\n : null;\n}\n\nfunction requireString(record: Record<string, unknown> | null, key: string, path: string, issues: EvalSchemaIssue[]): void {\n if (typeof record?.[key] !== \"string\" || !record[key]) {\n issues.push({ path, message: `${key} must be a non-empty string` });\n }\n}\n\nfunction isStringArray(value: unknown): value is string[] {\n return Array.isArray(value) && value.every((item) => typeof item === \"string\");\n}\n","import { estimateRunCost } from \"../../memory/runLogs\";\nimport type { EvalSuite } from \"../schemas\";\nimport { eco30Suite } from \"./eco30\";\nimport { mvpSuite } from \"./mvp\";\nimport { sweBenchLiteSuite } from \"./sweBenchLite\";\nimport { tanyaNativeSuite } from \"./tanya-native\";\nimport { verifierSelfTestSuite } from \"./verifierSelfTest\";\nimport { loadIntegrationEvalSuites } from \"./integrations\";\n\nexport type EvalSuiteName = \"swe-bench-lite\" | \"tanya-native\" | \"eco-30\" | \"mvp\" | \"verifier-self-test\";\n\nconst suiteLoaders: Record<EvalSuiteName, () => EvalSuite> = {\n \"swe-bench-lite\": sweBenchLiteSuite,\n \"tanya-native\": tanyaNativeSuite,\n \"eco-30\": eco30Suite,\n mvp: mvpSuite,\n \"verifier-self-test\": verifierSelfTestSuite,\n};\n\nexport type EvalDryRun = {\n suite: string;\n suiteVersion: string;\n taskCount: number;\n estimatedCostUsd: number | null;\n model: string;\n};\n\nfunction builtInSuiteNames(): EvalSuiteName[] {\n return Object.keys(suiteLoaders) as EvalSuiteName[];\n}\n\nexport function listEvalSuites(): string[] {\n const names = new Set<string>(builtInSuiteNames());\n for (const suite of loadIntegrationEvalSuites()) {\n if (!names.has(suite.name)) names.add(suite.name);\n }\n return [...names];\n}\n\nexport function loadEvalSuite(name: string): EvalSuite {\n const loader = suiteLoaders[name as EvalSuiteName];\n if (loader) return loader();\n\n const suite = loadIntegrationEvalSuites().find((candidate) => candidate.name === name);\n if (suite) return suite;\n\n throw new Error(`Unknown eval suite \"${name}\". Available: ${listEvalSuites().join(\", \")}`);\n}\n\nexport function dryRunEvalSuite(suite: EvalSuite, provider: string | undefined, model: string): EvalDryRun {\n const estimatedPromptTokens = suite.tasks.length * 14_000;\n const estimatedCompletionTokens = suite.tasks.length * 3_000;\n const estimate = estimateRunCost({\n ...(provider ? { provider } : {}),\n model,\n promptTokens: estimatedPromptTokens,\n completionTokens: estimatedCompletionTokens,\n });\n return {\n suite: suite.name,\n suiteVersion: suite.version,\n taskCount: suite.tasks.length,\n estimatedCostUsd: estimate.usd,\n model,\n };\n}\n","import { cp, mkdtemp, mkdir, readFile, rm, writeFile } from \"node:fs/promises\";\nimport { existsSync } from \"node:fs\";\nimport { tmpdir } from \"node:os\";\nimport { dirname, join, resolve } from \"node:path\";\nimport { execFileSync } from \"node:child_process\";\nimport { envValue, numberEnvValue } from \"../config/envCompat\";\nimport type { ChatProvider } from \"../providers/types\";\nimport { createJsonlSink } from \"../events/jsonl\";\nimport { runAgent } from \"../agent/runner\";\nimport { estimateRunCost } from \"../memory/runLogs\";\nimport type { EvalResult, EvalRunResult, EvalSuite, EvalTask, EvalTokensUsed } from \"./schemas\";\nimport { runVerifierExtension } from \"./verifierExtensions\";\n\nexport type EvalExecutionContext = {\n workspace: string;\n provider: string;\n model: string;\n timeoutMs: number;\n tokenCap: number;\n};\n\nexport type EvalExecutionOutcome = {\n verifierVerdict: \"passed\" | \"failed\";\n tokensUsed: EvalTokensUsed;\n costUsd: number;\n diff?: string;\n error?: string;\n};\n\nexport type EvalExecutor = (task: EvalTask, ctx: EvalExecutionContext) => Promise<EvalExecutionOutcome>;\n\nexport type RunEvalOptions = {\n cwd: string;\n provider: string;\n model: string;\n tanyaVersion: string;\n taskIds?: string[];\n parallel?: number;\n timeoutMs?: number;\n tokenCap?: number;\n executor?: EvalExecutor;\n providerFactory?: () => ChatProvider;\n keepWorkspaces?: boolean;\n};\n\nexport async function runEvalSuite(suite: EvalSuite, options: RunEvalOptions): Promise<EvalResult> {\n const timeoutMs = options.timeoutMs ?? numberEnvValue(process.env, \"TANYA_EVAL_TASK_TIMEOUT_MS\", 600_000);\n const tokenCap = options.tokenCap ?? numberEnvValue(process.env, \"TANYA_EVAL_TASK_TOKEN_CAP\", 500_000);\n const selected = options.taskIds?.length\n ? suite.tasks.filter((task) => options.taskIds?.includes(task.id))\n : suite.tasks;\n const missing = (options.taskIds ?? []).filter((id) => !suite.tasks.some((task) => task.id === id));\n if (missing.length > 0) throw new Error(`Unknown eval task id(s): ${missing.join(\", \")}`);\n\n const executor = options.executor ?? defaultExecutor(options);\n const runs: EvalRunResult[] = [];\n // Keep execution sequential for deterministic local logs. The CLI accepts\n // --parallel for forward compatibility; CI can raise it once provider and\n // fixture isolation have enough soak time.\n void (options.parallel ?? numberEnvValue(process.env, \"TANYA_EVAL_PARALLEL\", 4));\n for (const task of selected) {\n runs.push(await runOneTask(suite, task, options, executor, timeoutMs, tokenCap));\n }\n\n return {\n suite: suite.name,\n suiteVersion: suite.version,\n tanyaVersion: options.tanyaVersion,\n provider: options.provider,\n model: options.model,\n generatedAt: new Date().toISOString(),\n ...aggregateRuns(runs),\n runs,\n };\n}\n\nexport async function writeEvalResult(path: string, result: EvalResult): Promise<void> {\n await mkdir(dirname(path), { recursive: true });\n await writeFile(path, `${JSON.stringify(result, null, 2)}\\n`);\n}\n\nexport async function readEvalResult(path: string): Promise<EvalResult> {\n return JSON.parse(await readFile(path, \"utf8\")) as EvalResult;\n}\n\nasync function runOneTask(\n suite: EvalSuite,\n task: EvalTask,\n options: RunEvalOptions,\n executor: EvalExecutor,\n timeoutMs: number,\n tokenCap: number,\n): Promise<EvalRunResult> {\n const started = Date.now();\n let workspace = \"\";\n try {\n workspace = await setupEvalWorkspace(suite, task, options.cwd);\n const outcome = await withTimeout(\n executor(task, {\n workspace,\n provider: options.provider,\n model: options.model,\n timeoutMs,\n tokenCap,\n }),\n timeoutMs,\n );\n const status = outcome.verifierVerdict === \"passed\" ? \"passed\" : \"failed\";\n return {\n taskId: task.id,\n status,\n durationMs: Date.now() - started,\n tokensUsed: outcome.tokensUsed,\n costUsd: outcome.costUsd,\n verifierVerdict: outcome.verifierVerdict,\n ...(outcome.diff ? { diff: outcome.diff } : {}),\n ...(outcome.error ? { error: outcome.error } : {}),\n };\n } catch (err) {\n const timeout = err instanceof Error && err.message === \"eval task timeout\";\n return {\n taskId: task.id,\n status: timeout ? \"timeout\" : \"errored\",\n durationMs: Date.now() - started,\n tokensUsed: { input: 0, output: 0 },\n costUsd: 0,\n verifierVerdict: \"failed\",\n error: err instanceof Error ? err.message : String(err),\n };\n } finally {\n if (workspace && !options.keepWorkspaces) await rm(workspace, { recursive: true, force: true });\n }\n}\n\nasync function setupEvalWorkspace(suite: EvalSuite, task: EvalTask, cwd: string): Promise<string> {\n const workspace = await mkdtemp(join(tmpdir(), `tanya-eval-${suite.name}-${task.id}-`));\n if (task.repo_setup.type === \"local_fixture\" && !task.repo_setup.path.startsWith(\"builtin:\")) {\n const source = resolve(cwd, task.repo_setup.path);\n if (!existsSync(source)) throw new Error(`local fixture does not exist: ${source}`);\n await cp(source, workspace, { recursive: true });\n } else if (task.repo_setup.type === \"git_clone\") {\n execFileSync(\"git\", [\"clone\", \"--quiet\", task.repo_setup.url, workspace], { stdio: \"ignore\" });\n execFileSync(\"git\", [\"checkout\", \"--quiet\", task.repo_setup.commit], { cwd: workspace, stdio: \"ignore\" });\n } else {\n await writeFile(join(workspace, \"README.md\"), `# ${task.id}\\n\\n${task.prompt}\\n`);\n await mkdir(join(workspace, \"src\"), { recursive: true });\n await writeFile(join(workspace, \"src\", \"index.ts\"), \"export const status = 'pending';\\n\");\n }\n initializeGit(workspace);\n return workspace;\n}\n\nfunction initializeGit(workspace: string): void {\n try {\n execFileSync(\"git\", [\"init\"], { cwd: workspace, stdio: \"ignore\" });\n execFileSync(\"git\", [\"config\", \"user.email\", \"eval@tanya.local\"], { cwd: workspace, stdio: \"ignore\" });\n execFileSync(\"git\", [\"config\", \"user.name\", \"Tanya Eval\"], { cwd: workspace, stdio: \"ignore\" });\n execFileSync(\"git\", [\"add\", \".\"], { cwd: workspace, stdio: \"ignore\" });\n execFileSync(\"git\", [\"commit\", \"-m\", \"eval baseline\"], { cwd: workspace, stdio: \"ignore\" });\n } catch {\n // Git is useful for diffs but not required for accounting errored tasks.\n }\n}\n\nfunction defaultExecutor(options: RunEvalOptions): EvalExecutor {\n return async (task, ctx) => {\n if (!options.providerFactory) throw new Error(\"eval runner requires a providerFactory\");\n const provider = options.providerFactory();\n const outputChunks: string[] = [];\n const sink = createJsonlSink({\n write(chunk: string) {\n outputChunks.push(chunk);\n return true;\n },\n } as NodeJS.WritableStream);\n const result = await runAgent({\n provider,\n prompt: task.prompt,\n cwd: ctx.workspace,\n sink,\n maxTurns: 40,\n runContext: { task: { kind: \"coding\" } },\n });\n const diff = safeGitDiff(ctx.workspace);\n const tokensUsed: EvalTokensUsed = {\n input: result.metrics?.promptTokens ?? 0,\n output: result.metrics?.completionTokens ?? 0,\n reasoning: result.metrics?.reasoningTokens ?? 0,\n system_prompt: result.metrics?.systemPromptTokens ?? 0,\n repo_map: result.metrics?.repoMapTokens ?? 0,\n };\n const costUsd = estimateRunCost({\n provider: ctx.provider,\n model: ctx.model,\n promptTokens: tokensUsed.input,\n completionTokens: tokensUsed.output,\n ...(tokensUsed.reasoning !== undefined ? { reasoningTokens: tokensUsed.reasoning } : {}),\n }).usd ?? 0;\n const extension = await runVerifierExtension(task, ctx.workspace, options.cwd);\n const verifierVerdict = extension\n ? extension.ok ? \"passed\" : \"failed\"\n : result.manifest.blockers.length === 0 ? \"passed\" : \"failed\";\n const errors = extension\n ? extension.ok ? [] : extension.errors\n : result.manifest.blockers;\n return {\n verifierVerdict,\n tokensUsed,\n costUsd,\n ...(diff ? { diff } : {}),\n ...(errors.length > 0 ? { error: errors.join(\"\\n\") } : {}),\n };\n };\n}\n\nfunction safeGitDiff(workspace: string): string {\n try {\n return execFileSync(\"git\", [\"diff\", \"HEAD\"], { cwd: workspace, encoding: \"utf8\" });\n } catch {\n return \"\";\n }\n}\n\nasync function withTimeout<T>(promise: Promise<T>, timeoutMs: number): Promise<T> {\n let timer: ReturnType<typeof setTimeout> | undefined;\n const timeout = new Promise<never>((_, reject) => {\n timer = setTimeout(() => reject(new Error(\"eval task timeout\")), timeoutMs);\n timer.unref?.();\n });\n try {\n return await Promise.race([promise, timeout]);\n } finally {\n if (timer) clearTimeout(timer);\n }\n}\n\nexport function parseTaskFilter(raw: string | undefined): string[] | undefined {\n if (!raw?.trim()) return undefined;\n return raw.split(\",\").map((item) => item.trim()).filter(Boolean);\n}\n\nexport function aggregateRuns(runs: EvalRunResult[]): Pick<EvalResult, \"totalCostUsd\" | \"costPerPass\" | \"tokensPerPass\" | \"reasoningShare\"> {\n const totalCostUsd = runs.reduce((sum, run) => sum + run.costUsd, 0);\n const passed = runs.filter((run) => run.status === \"passed\").length;\n const totalInput = runs.reduce((sum, run) => sum + run.tokensUsed.input, 0);\n const totalOutput = runs.reduce((sum, run) => sum + run.tokensUsed.output, 0);\n const totalReasoning = runs.reduce((sum, run) => sum + (run.tokensUsed.reasoning ?? 0), 0);\n const totalTokens = totalInput + totalOutput + totalReasoning;\n return {\n totalCostUsd,\n costPerPass: passed > 0 ? totalCostUsd / passed : null,\n tokensPerPass: passed > 0 ? totalTokens / passed : null,\n reasoningShare: totalTokens > 0 ? totalReasoning / totalTokens : 0,\n };\n}\n","import { access, readFile, rm } from \"node:fs/promises\";\nimport { existsSync } from \"node:fs\";\nimport { execFile } from \"node:child_process\";\nimport { join, resolve } from \"node:path\";\nimport { promisify } from \"node:util\";\n\nconst execFileAsync = promisify(execFile);\n\nexport type MvpVerifierOutcome =\n | { ok: true; notes: string[] }\n | { ok: false; errors: string[] };\n\ntype CommandResult = {\n code: number;\n output: string;\n};\n\nexport async function runMvpVerifier(taskId: string, workspace: string, repoRoot: string): Promise<MvpVerifierOutcome | null> {\n if (taskId === \"mvp-02\") return verifyExpressNotesApi(workspace);\n if (taskId === \"mvp-03\") return verifyHnScraper(workspace);\n if (taskId === \"mvp-10\") return verifyCommanderCli(workspace, repoRoot);\n return null;\n}\n\nasync function verifyHnScraper(workspace: string): Promise<MvpVerifierOutcome> {\n const errors: string[] = [];\n for (const file of [\"hn_top.py\", \"requirements.txt\", \"README.md\", \"stories.json\"]) {\n if (!existsSync(join(workspace, file))) errors.push(`${file} is missing.`);\n }\n if (errors.length > 0) return { ok: false, errors };\n\n const requirements = await readFile(join(workspace, \"requirements.txt\"), \"utf8\");\n if (!/\\brequests\\b/i.test(requirements)) errors.push(\"requirements.txt must include requests.\");\n if (!/\\b(?:beautifulsoup4|bs4)\\b/i.test(requirements)) errors.push(\"requirements.txt must include beautifulsoup4.\");\n\n const readme = await readFile(join(workspace, \"README.md\"), \"utf8\");\n if (!/\\b(?:mock|fallback|sample|offline|network unavailable|network limitation)\\b/i.test(readme)) {\n errors.push(\"README.md must document mock/offline fallback behavior for unavailable live network access.\");\n }\n\n try {\n const parsed = JSON.parse(await readFile(join(workspace, \"stories.json\"), \"utf8\")) as unknown;\n const stories = Array.isArray(parsed)\n ? parsed\n : parsed && typeof parsed === \"object\" && Array.isArray((parsed as { stories?: unknown }).stories)\n ? (parsed as { stories: unknown[] }).stories\n : null;\n if (!stories) errors.push(\"stories.json must be an array or an object with a stories array.\");\n else {\n if (stories.length > 10) errors.push(\"stories.json must contain at most 10 stories.\");\n if (stories.length === 0) errors.push(\"stories.json should include deterministic sample stories when live network access is unavailable.\");\n if (!stories.every((story) => story && typeof story === \"object\" && typeof (story as { title?: unknown }).title === \"string\")) {\n errors.push(\"Each story must include a title.\");\n }\n }\n } catch (error) {\n errors.push(`stories.json is not valid JSON: ${error instanceof Error ? error.message : String(error)}`);\n }\n\n return errors.length > 0 ? { ok: false, errors } : { ok: true, notes: [\"HN scraper fallback artifact verified.\"] };\n}\n\nasync function verifyExpressNotesApi(workspace: string): Promise<MvpVerifierOutcome> {\n const candidates = [\"src/server.js\", \"src/index.js\", \"server.js\", \"app.js\"]\n .filter((file) => existsSync(join(workspace, file)));\n if (candidates.length === 0) {\n return { ok: false, errors: [\"No Express entry file found. Expected src/server.js, src/index.js, server.js, or app.js.\"] };\n }\n\n const script = String.raw`\nconst { existsSync } = require(\"node:fs\");\nconst http = require(\"node:http\");\nconst { pathToFileURL } = require(\"node:url\");\nconst { spawn } = require(\"node:child_process\");\n\nconst entries = ${JSON.stringify(candidates)};\n\nfunction request(port, method, path, body) {\n return new Promise((resolve, reject) => {\n const req = http.request({\n hostname: \"127.0.0.1\",\n port,\n path,\n method,\n headers: body ? { \"Content-Type\": \"application/json\" } : {},\n }, (res) => {\n let data = \"\";\n res.on(\"data\", (chunk) => { data += chunk; });\n res.on(\"end\", () => resolve({ status: res.statusCode || 0, body: data }));\n });\n req.on(\"error\", reject);\n if (body) req.write(JSON.stringify(body));\n req.end();\n });\n}\n\nfunction assertStatus(response, accepted, label) {\n if (!accepted.includes(response.status)) {\n throw new Error(label + \" returned HTTP \" + response.status + \" with body \" + response.body);\n }\n}\n\nasync function testRoutes(port) {\n assertStatus(await request(port, \"GET\", \"/notes\"), [200], \"GET /notes\");\n const created = await request(port, \"POST\", \"/notes\", { title: \"test\", content: \"hello\" });\n assertStatus(created, [200, 201], \"POST /notes\");\n let id = 1;\n try {\n const parsed = JSON.parse(created.body);\n id = parsed.id ?? parsed.note?.id ?? parsed.data?.id ?? 1;\n } catch {}\n assertStatus(await request(port, \"GET\", \"/notes\"), [200], \"GET /notes after create\");\n assertStatus(await request(port, \"PUT\", \"/notes/\" + encodeURIComponent(String(id)), { title: \"test\", content: \"world\" }), [200, 204], \"PUT /notes/:id\");\n assertStatus(await request(port, \"DELETE\", \"/notes/\" + encodeURIComponent(String(id))), [200, 202, 204], \"DELETE /notes/:id\");\n}\n\nasync function loadModule(entry) {\n try {\n return require(\"./\" + entry);\n } catch (err) {\n if (!/(ERR_REQUIRE_ESM|Cannot use import statement|Unexpected token 'export')/.test(String(err && (err.stack || err.message || err)))) throw err;\n return import(pathToFileURL(process.cwd() + \"/\" + entry).href);\n }\n}\n\nasync function verifyExportShape(entry) {\n const loaded = await loadModule(entry);\n const candidates = [\n loaded,\n loaded && loaded.default,\n loaded && loaded.app,\n loaded && loaded.server,\n loaded && typeof loaded.createApp === \"function\" ? loaded.createApp() : null,\n ].filter(Boolean);\n for (const app of candidates) {\n if (typeof app.listen !== \"function\") continue;\n const server = await new Promise((resolve, reject) => {\n const s = app.listen(0, \"127.0.0.1\", () => resolve(s));\n s.once(\"error\", reject);\n });\n try {\n const address = server.address();\n const port = typeof address === \"object\" && address ? address.port : 0;\n await testRoutes(port);\n return \"export:\" + entry;\n } finally {\n await new Promise((resolve) => server.close(resolve));\n }\n }\n throw new Error(\"No exported Express app with .listen() found in \" + entry);\n}\n\nasync function waitForServer(port, timeoutMs) {\n const started = Date.now();\n while (Date.now() - started < timeoutMs) {\n try {\n await request(port, \"GET\", \"/notes\");\n return;\n } catch {\n await new Promise((resolve) => setTimeout(resolve, 100));\n }\n }\n throw new Error(\"Timed out waiting for server on port \" + port);\n}\n\nasync function verifyScriptShape(entry) {\n const port = 3101;\n const child = spawn(process.execPath, [entry], {\n cwd: process.cwd(),\n env: { ...process.env, PORT: String(port), NODE_ENV: \"test\" },\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\n });\n let output = \"\";\n child.stdout.on(\"data\", (chunk) => { output += chunk.toString(); });\n child.stderr.on(\"data\", (chunk) => { output += chunk.toString(); });\n try {\n await waitForServer(port, 1500);\n await testRoutes(port);\n return \"script:\" + entry;\n } finally {\n child.kill(\"SIGTERM\");\n setTimeout(() => child.kill(\"SIGKILL\"), 500).unref();\n }\n}\n\n(async () => {\n const errors = [];\n for (const entry of entries) {\n try {\n const via = await verifyExportShape(entry);\n console.log(\"verified \" + via);\n return;\n } catch (err) {\n errors.push(entry + \" export shape: \" + (err && err.message ? err.message : String(err)));\n }\n }\n for (const entry of entries) {\n try {\n const via = await verifyScriptShape(entry);\n console.log(\"verified \" + via);\n return;\n } catch (err) {\n errors.push(entry + \" script shape: \" + (err && err.message ? err.message : String(err)));\n }\n }\n console.error(errors.join(\"\\n\"));\n process.exit(1);\n})().catch((err) => {\n console.error(err && err.stack ? err.stack : String(err));\n process.exit(1);\n});\n`;\n\n const result = await runNodeScript(workspace, script, 20_000);\n if (result.code === 0) return { ok: true, notes: [result.output.trim() || \"Express routes verified.\"] };\n return { ok: false, errors: [`Express route verification failed: ${result.output}`] };\n}\n\nasync function verifyCommanderCli(workspace: string, repoRoot: string): Promise<MvpVerifierOutcome> {\n const packageJsonPath = join(workspace, \"package.json\");\n if (!existsSync(packageJsonPath)) return { ok: false, errors: [\"package.json is missing.\"] };\n const packageJson = JSON.parse(await readFile(packageJsonPath, \"utf8\")) as {\n bin?: string | Record<string, string>;\n scripts?: Record<string, string>;\n dependencies?: Record<string, string>;\n devDependencies?: Record<string, string>;\n };\n const source = existsSync(join(workspace, \"src\", \"index.ts\"))\n ? await readFile(join(workspace, \"src\", \"index.ts\"), \"utf8\")\n : \"\";\n const hasCommander = Boolean(packageJson.dependencies?.commander || packageJson.devDependencies?.commander || /\\bfrom\\s+[\"']commander[\"']|\\brequire\\([\"']commander[\"']\\)/.test(source));\n if (!hasCommander) return { ok: false, errors: [\"Commander dependency/import was not found.\"] };\n\n if (packageJson.scripts?.build) {\n await runCommand(workspace, \"npm\", [\"run\", \"build\"], 90_000).catch(() => undefined);\n }\n\n const command = await resolveCliCommand(workspace, repoRoot, packageJson);\n if (!command) {\n return { ok: false, errors: [\"No runnable CLI entry found. Expected dist/index.js, src/index.ts, src/index.js, or package.json bin.\"] };\n }\n\n const nodePath = [join(repoRoot, \"node_modules\"), process.env.NODE_PATH].filter(Boolean).join(\":\");\n const env = nodePath ? { NODE_PATH: nodePath } : {};\n\n await rm(join(workspace, \".mvp10\"), { recursive: true, force: true }).catch(() => undefined);\n\n const errors: string[] = [];\n const init = await runCommand(workspace, command.cmd, [...command.args, \"init\"], 20_000, env);\n if (init.code !== 0) errors.push(`init failed: ${init.output}`);\n const add = await runCommand(workspace, command.cmd, [...command.args, \"add\", \"Buy milk\"], 20_000, env);\n if (add.code !== 0) errors.push(`add failed: ${add.output}`);\n const list = await runCommand(workspace, command.cmd, [...command.args, \"list\"], 20_000, env);\n if (list.code !== 0 || !/Buy milk/i.test(list.output)) errors.push(`list did not show persisted item: ${list.output}`);\n const itemId = itemIdFromListOutput(list.output, \"Buy milk\") ?? \"1\";\n const remove = await runCommand(workspace, command.cmd, [...command.args, \"remove\", itemId], 20_000, env);\n if (remove.code !== 0) errors.push(`remove existing item failed: ${remove.output}`);\n const missingRemove = await runCommand(workspace, command.cmd, [...command.args, \"remove\", \"99\"], 20_000, env);\n if (missingRemove.code !== 0 && !/\\b(not found|no item|missing|does not exist|unknown id|invalid id)\\b/i.test(missingRemove.output)) {\n errors.push(`remove missing id failed without a clear negative-path message: ${missingRemove.output}`);\n }\n\n if (errors.length > 0) return { ok: false, errors };\n return { ok: true, notes: [`Commander CLI verified via ${command.cmd} ${command.args.join(\" \")}`.trim()] };\n}\n\nfunction itemIdFromListOutput(output: string, itemLabel: string): string | null {\n const escapedLabel = itemLabel.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n for (const line of output.split(/\\r?\\n/)) {\n if (!new RegExp(escapedLabel, \"i\").test(line)) continue;\n const direct = line.match(/\\b(?:id|#)\\s*[:=]?\\s*([A-Za-z0-9_-]{1,36})\\b/i)?.[1];\n if (direct) return direct;\n const leading = line.match(/^\\s*(?:[-*]\\s*)?([A-Za-z0-9_-]{1,36})\\s*(?:[).:-]|\\s+-\\s+)/)?.[1];\n if (leading) return leading;\n }\n return null;\n}\n\nasync function resolveCliCommand(\n workspace: string,\n repoRoot: string,\n packageJson: { bin?: string | Record<string, string> },\n): Promise<{ cmd: string; args: string[] } | null> {\n const binValue = typeof packageJson.bin === \"string\"\n ? packageJson.bin\n : packageJson.bin ? Object.values(packageJson.bin)[0] : undefined;\n const candidates = [\n binValue,\n \"dist/index.js\",\n \"dist/cli.js\",\n \"src/index.js\",\n ].filter((entry): entry is string => Boolean(entry));\n for (const entry of candidates) {\n if (existsSync(join(workspace, entry))) return { cmd: process.execPath, args: [entry] };\n }\n const tsEntry = join(workspace, \"src\", \"index.ts\");\n if (existsSync(tsEntry)) {\n const tsxCli = join(repoRoot, \"node_modules\", \"tsx\", \"dist\", \"cli.mjs\");\n await access(tsxCli);\n return { cmd: process.execPath, args: [tsxCli, \"src/index.ts\"] };\n }\n return null;\n}\n\nasync function runNodeScript(cwd: string, script: string, timeoutMs: number): Promise<CommandResult> {\n return runCommand(cwd, process.execPath, [\"-e\", script], timeoutMs);\n}\n\nasync function runCommand(cwd: string, command: string, args: string[], timeoutMs: number, envOverrides: Record<string, string> = {}): Promise<CommandResult> {\n try {\n const { stdout, stderr } = await execFileAsync(command, args, {\n cwd,\n timeout: timeoutMs,\n maxBuffer: 4 * 1024 * 1024,\n env: { ...process.env, ...envOverrides },\n });\n return { code: 0, output: `${stdout}${stderr ? `\\n${stderr}` : \"\"}`.trim() };\n } catch (error) {\n const err = error as { code?: number; stdout?: string; stderr?: string; message?: string };\n const output = `${err.stdout ?? \"\"}${err.stderr ? `\\n${err.stderr}` : \"\"}`.trim() || err.message || \"command failed\";\n return { code: typeof err.code === \"number\" ? err.code : 1, output };\n }\n}\n","import type { EvalTask } from \"./schemas\";\nimport { runMvpVerifier, type MvpVerifierOutcome } from \"./mvpVerifier\";\n\nexport type VerifierExtensionOutcome = MvpVerifierOutcome;\n\nexport async function runVerifierExtension(task: EvalTask, workspace: string, repoRoot: string): Promise<VerifierExtensionOutcome | null> {\n if (!task.verifier_extension) return null;\n if (task.verifier_extension.includes(\"/mvp-fixtures/\")) {\n return runMvpVerifier(task.id, workspace, repoRoot);\n }\n return null;\n}\n","import type { EvalResult, EvalRunResult } from \"./schemas\";\n\nexport type EvalReportFormat = \"text\" | \"markdown\";\n\nexport function formatEvalReport(result: EvalResult, format: EvalReportFormat = \"text\"): string {\n const total = result.runs.length;\n const passed = result.runs.filter((run) => run.status === \"passed\").length;\n const failed = result.runs.filter((run) => run.status === \"failed\").length;\n const errored = result.runs.filter((run) => run.status === \"errored\").length;\n const timeout = result.runs.filter((run) => run.status === \"timeout\").length;\n const totalCost = result.runs.reduce((sum, run) => sum + run.costUsd, 0);\n const costPerTask = total > 0 ? totalCost / total : 0;\n const slowest = [...result.runs].sort((a, b) => b.durationMs - a.durationMs).slice(0, 3);\n const costliest = [...result.runs].sort((a, b) => b.costUsd - a.costUsd).slice(0, 3);\n\n if (format === \"markdown\") {\n return [\n `## Eval Report: ${result.suite}`,\n \"\",\n `- Version: ${result.suiteVersion}`,\n `- Model: ${result.provider ? `${result.provider}/` : \"\"}${result.model}`,\n `- Pass rate: ${percent(passed, total)} (${passed}/${total})`,\n `- Status: ${passed} passed, ${failed} failed, ${errored} errored, ${timeout} timeout`,\n `- Total cost: ${usd(totalCost)}`,\n `- Cost/task: ${usd(costPerTask)}`,\n `- Reasoning share: ${((result.reasoningShare ?? 0) * 100).toFixed(1)}%`,\n \"\",\n markdownRunTable(\"Slowest tasks\", slowest, \"duration\"),\n \"\",\n markdownRunTable(\"Costliest tasks\", costliest, \"cost\"),\n \"\",\n ].join(\"\\n\");\n }\n\n return [\n `Eval report: ${result.suite}@${result.suiteVersion}`,\n `Model: ${result.provider ? `${result.provider}/` : \"\"}${result.model}`,\n `Pass rate: ${percent(passed, total)} (${passed}/${total})`,\n `Status: ${passed} passed, ${failed} failed, ${errored} errored, ${timeout} timeout`,\n `Total cost: ${usd(totalCost)}`,\n `Cost/task: ${usd(costPerTask)}`,\n `Reasoning share: ${((result.reasoningShare ?? 0) * 100).toFixed(1)}%`,\n \"\",\n \"Slowest tasks:\",\n ...slowest.map((run) => `- ${run.taskId}: ${seconds(run.durationMs)} (${run.status})`),\n \"\",\n \"Costliest tasks:\",\n ...costliest.map((run) => `- ${run.taskId}: ${usd(run.costUsd)} (${run.status})`),\n \"\",\n ].join(\"\\n\");\n}\n\nfunction markdownRunTable(title: string, runs: EvalRunResult[], metric: \"duration\" | \"cost\"): string {\n const rows = [\n `### ${title}`,\n \"\",\n \"| Task | Status | Metric |\",\n \"| --- | --- | ---: |\",\n ];\n for (const run of runs) {\n rows.push(`| \\`${run.taskId}\\` | ${run.status} | ${metric === \"duration\" ? seconds(run.durationMs) : usd(run.costUsd)} |`);\n }\n return rows.join(\"\\n\");\n}\n\nfunction percent(numerator: number, denominator: number): string {\n if (denominator === 0) return \"0.0%\";\n return `${((numerator / denominator) * 100).toFixed(1)}%`;\n}\n\nfunction seconds(ms: number): string {\n return `${(ms / 1000).toFixed(1)}s`;\n}\n\nfunction usd(value: number): string {\n return `$${value.toFixed(4)}`;\n}\n","import type { EvalResult } from \"./schemas\";\n\nexport type EvalComparison = {\n baselineSuite: string;\n newSuite: string;\n costRegressionThreshold: number;\n regressions: Array<{ taskId: string; reason: string }>;\n improvements: Array<{ taskId: string; reason: string }>;\n};\n\nexport function compareEvalResults(baseline: EvalResult, next: EvalResult, costRegressionThreshold = 0.20): EvalComparison {\n const baselineByTask = new Map(baseline.runs.map((run) => [run.taskId, run]));\n const regressions: EvalComparison[\"regressions\"] = [];\n const improvements: EvalComparison[\"improvements\"] = [];\n for (const run of next.runs) {\n const previous = baselineByTask.get(run.taskId);\n if (!previous) continue;\n if (previous.verifierVerdict === \"passed\" && run.verifierVerdict === \"failed\") {\n regressions.push({ taskId: run.taskId, reason: \"verdict drift: passed -> failed\" });\n }\n if (previous.status !== \"errored\" && run.status === \"errored\") {\n regressions.push({ taskId: run.taskId, reason: \"new error\" });\n }\n if (previous.status !== \"timeout\" && run.status === \"timeout\") {\n regressions.push({ taskId: run.taskId, reason: \"new timeout\" });\n }\n if (previous.costUsd > 0 && run.costUsd >= previous.costUsd * (1 + costRegressionThreshold)) {\n regressions.push({\n taskId: run.taskId,\n reason: `cost regression: ${usd(previous.costUsd)} -> ${usd(run.costUsd)} (+${(((run.costUsd / previous.costUsd) - 1) * 100).toFixed(1)}%)`,\n });\n }\n if (previous.verifierVerdict === \"failed\" && run.verifierVerdict === \"passed\") {\n improvements.push({ taskId: run.taskId, reason: \"verdict improved: failed -> passed\" });\n }\n }\n if (baseline.totalCostUsd > 0 && next.totalCostUsd >= baseline.totalCostUsd * (1 + costRegressionThreshold)) {\n regressions.push({\n taskId: \"__suite__\",\n reason: `suite cost regression: ${usd(baseline.totalCostUsd)} -> ${usd(next.totalCostUsd)}`,\n });\n }\n return {\n baselineSuite: `${baseline.suite}@${baseline.suiteVersion}`,\n newSuite: `${next.suite}@${next.suiteVersion}`,\n costRegressionThreshold,\n regressions,\n improvements,\n };\n}\n\nexport function formatEvalComparison(comparison: EvalComparison, format: \"text\" | \"markdown\" = \"text\"): string {\n if (format === \"markdown\") {\n return [\n `## Eval Compare`,\n \"\",\n `- Baseline: ${comparison.baselineSuite}`,\n `- New: ${comparison.newSuite}`,\n `- Cost threshold: ${(comparison.costRegressionThreshold * 100).toFixed(0)}%`,\n `- Regressions: ${comparison.regressions.length}`,\n `- Improvements: ${comparison.improvements.length}`,\n \"\",\n markdownList(\"Regressions\", comparison.regressions),\n \"\",\n markdownList(\"Improvements\", comparison.improvements),\n \"\",\n ].join(\"\\n\");\n }\n return [\n `Eval compare: ${comparison.baselineSuite} -> ${comparison.newSuite}`,\n `Cost threshold: ${(comparison.costRegressionThreshold * 100).toFixed(0)}%`,\n `Regressions: ${comparison.regressions.length}`,\n ...comparison.regressions.map((item) => `- ${item.taskId}: ${item.reason}`),\n `Improvements: ${comparison.improvements.length}`,\n ...comparison.improvements.map((item) => `- ${item.taskId}: ${item.reason}`),\n \"\",\n ].join(\"\\n\");\n}\n\nfunction usd(value: number): string {\n return `$${value.toFixed(4)}`;\n}\n\nfunction markdownList(title: string, items: Array<{ taskId: string; reason: string }>): string {\n const lines = [`### ${title}`];\n if (items.length === 0) return [...lines, \"\", \"None.\"].join(\"\\n\");\n return [...lines, \"\", ...items.map((item) => `- \\`${item.taskId}\\`: ${item.reason}`)].join(\"\\n\");\n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,MAAM,gBAAgB,OAAO,EAAE;AACvC,UAAQ,WAAW;AACrB,CAAC;","names":["existsSync","readFileSync","join","resolve","existsSync","keep","_oneOf","rest","seconds","resolve","id","existsSync","mkdirSync","readFileSync","writeFileSync","join","resolve","gaveUp","runCommand","testCmd","existsSync","readFileSync","join","usd","seconds","dirname","isAbsolute","join","spawnSync","spawnSync","isAbsolute","join","scaled","basename","mkdtemp","dirname","readFileSync","readFileSync","mkdir","writeFile","join","join","mkdir","writeFile","mkdir","readFile","readdir","writeFile","dirname","join","resolve","unique","unique","unique","resolve","resolve","run","tasks","categories","tasks","readFileSync","isStringArray","readJson","readFileSync","mkdtemp","mkdir","readFile","rm","writeFile","existsSync","tmpdir","dirname","join","resolve","readFile","rm","existsSync","execFile","join","promisify","execFileAsync","runCommand","mkdir","dirname","writeFile","readFile","rm","mkdtemp","join","tmpdir","resolve","existsSync","run","run","run","usd","readFileSync","resolve","runContext","existsSync","join","execFileSync","cwd","formats","outputDir","basename","result"]}
|
|
1
|
+
{"version":3,"sources":["../src/cli.ts","../src/config/env.ts","../src/context/artifacts.ts","../src/events/jsonl.ts","../src/agent/reasoning.ts","../src/providers/schemaFlatten.ts","../src/providers/retry.ts","../src/providers/messageNormalize.ts","../src/providers/openAiCompatible.ts","../src/providers/factory.ts","../src/agent/dispatch.ts","../src/agent/postCheck.ts","../src/agent/planner.ts","../src/agent/reviewer.ts","../src/agent/phaseBudget.ts","../src/ui/liveStatus.ts","../src/ui/humanSink.ts","../src/tools/adRenderTools.ts","../src/golden/profiles.ts","../src/golden/run.ts","../src/golden/suite.ts","../src/init/projectInit.ts","../src/context/autoContext.ts","../src/safety/permissions/migrate.ts","../src/mcp/server.ts","../src/eval/suites/eco30.ts","../src/eval/suites/mvp.ts","../src/eval/suites/sweBenchLite.ts","../src/eval/suites/tanya-native.ts","../src/eval/suites/verifierSelfTest.ts","../src/eval/suites/integrations.ts","../src/eval/schemas/EvalSuite.ts","../src/eval/suites/registry.ts","../src/eval/runner.ts","../src/eval/mvpVerifier.ts","../src/eval/verifierExtensions.ts","../src/eval/report.ts","../src/eval/compare.ts","../src/integrations/cosmochatFinalize.ts"],"sourcesContent":["import { existsSync, readFileSync } from \"node:fs\";\nimport { join, resolve } from \"node:path\";\nimport { createInterface } from \"node:readline\";\nimport { Command, Option } from \"commander\";\nimport { loadConfig } from \"./config/env\";\nimport { envValue } from \"./config/envCompat\";\nimport { loadRunContextFile, type TanyaRunContext } from \"./context/runContext\";\nimport { materializeCliArtifacts } from \"./context/artifacts\";\nimport { createJsonlSink } from \"./events/jsonl\";\nimport { createProvider, createProviderForRoute } from \"./providers/factory\";\nimport type { EventSink } from \"./events/types\";\nimport { runAgent, type RunAgentOptions, type RunAgentResult, type TanyaFinalManifest } from \"./agent/runner\";\nimport { parseVerifyFailureJSONL, runPlanAndDispatch, type DispatchMode, type VerifyFailure } from \"./agent/dispatch\";\nimport { detectPostRunBlockers } from \"./agent/postCheck\";\nimport { buildExecutionPlan } from \"./agent/planner\";\nimport { reviewChanges } from \"./agent/reviewer\";\nimport { buildSystemPrompt, loadPromptSkillPacks } from \"./agent/systemPrompt\";\nimport { startInteractiveChat } from \"./agent/chat\";\nimport { phaseAwareMaxTurns } from \"./agent/phaseBudget\";\nimport { createHumanSink } from \"./ui/humanSink\";\nimport { generateVideoAsset, videoPresets } from \"./tools/videoTools\";\nimport { renderFullAd } from \"./tools/adRenderTools\";\nimport { runGoldenSuiteCommand } from \"./golden/suite\";\nimport { initTanyaProject } from \"./init/projectInit\";\nimport { buildExportMap } from \"./context/loader\";\nimport { buildRepoMap, readRepoMap, repoMapDiagnostics } from \"./context/repoMap\";\nimport { OpenAiCompatibleProvider } from \"./providers/openAiCompatible\";\nimport { buildAutoRunContext } from \"./context/autoContext\";\nimport { buildHistoryBlock, readRecentTaskHistory } from \"./memory/taskHistory\";\nimport { formatSkillPackSummary } from \"./skills\";\nimport { estimateRunCost, formatRunLogLine, readRunLogs } from \"./memory/runLogs\";\nimport { suggestPermissionsFromRuns } from \"./safety/permissions/migrate\";\nimport { serveTanyaMcpServer } from \"./mcp/server\";\nimport { loadRouteTable } from \"./router\";\nimport { dryRunEvalSuite, loadEvalSuite } from \"./eval/suites\";\nimport { parseTaskFilter, readEvalResult, runEvalSuite, writeEvalResult } from \"./eval/runner\";\nimport { formatEvalReport } from \"./eval/report\";\nimport { compareEvalResults, formatEvalComparison } from \"./eval/compare\";\nimport { runSessionsCommand } from \"./cli/sessionsCommand\";\nimport { createCosmoChatFinalizeSink } from \"./integrations/cosmochatFinalize\";\n\ninterface ParsedArgs {\n command: string;\n positional: string[];\n flags: Map<string, string | string[] | boolean>;\n}\n\ntype CliOptionKind = \"array\" | \"boolean\" | \"negated\" | \"string\";\n\ntype CliOptionDefinition = {\n flags: string;\n key: string;\n kind: CliOptionKind;\n property: string;\n aliases?: string[];\n};\n\nconst knownCommands = new Set([\"chat\", \"ask\", \"run\", \"review\", \"init\", \"video\", \"golden\", \"benchmark\", \"eval\", \"providers\", \"permissions\", \"mcp\", \"doctor\", \"debug-prompt\", \"runs\", \"patterns\", \"sessions\", \"help\"]);\n\nconst cliOptionDefinitions: CliOptionDefinition[] = [\n { flags: \"--artifact <path>\", key: \"artifact\", kind: \"array\", property: \"artifact\" },\n { flags: \"--artifact-output-root <path>\", key: \"artifact-output-root\", kind: \"string\", property: \"artifactOutputRoot\" },\n { flags: \"--artifacts-root <path>\", key: \"artifacts-root\", kind: \"string\", property: \"artifactsRoot\" },\n { flags: \"--auto-fix-verify\", key: \"auto-fix-verify\", kind: \"boolean\", property: \"autoFixVerify\" },\n { flags: \"--auto-fix-warns\", key: \"auto-fix-warns\", kind: \"boolean\", property: \"autoFixWarns\" },\n { flags: \"--badge <text>\", key: \"badge\", kind: \"string\", property: \"badge\" },\n { flags: \"--basename <name>\", key: \"basename\", kind: \"string\", property: \"basename\" },\n { flags: \"--context-file <path>\", key: \"context-file\", kind: \"string\", property: \"contextFile\" },\n { flags: \"--context-path <path>\", key: \"context-path\", kind: \"array\", property: \"contextPath\" },\n { flags: \"--continue\", key: \"continue\", kind: \"boolean\", property: \"continue\" },\n { flags: \"--cwd <path>\", key: \"cwd\", kind: \"string\", property: \"cwd\" },\n { flags: \"--duration <seconds>\", key: \"duration\", kind: \"string\", property: \"duration\" },\n { flags: \"--dispatch-mode <mode>\", key: \"dispatch-mode\", kind: \"string\", property: \"dispatchMode\" },\n { flags: \"--ffmpeg-path <path>\", key: \"ffmpeg-path\", kind: \"string\", property: \"ffmpegPath\", aliases: [\"ffmpegPath\"] },\n { flags: \"--format <format>\", key: \"format\", kind: \"array\", property: \"format\" },\n { flags: \"--fps <number>\", key: \"fps\", kind: \"string\", property: \"fps\" },\n { flags: \"--global\", key: \"global\", kind: \"boolean\", property: \"global\" },\n { flags: \"--height <number>\", key: \"height\", kind: \"string\", property: \"height\" },\n { flags: \"--input <path>\", key: \"input\", kind: \"string\", property: \"input\" },\n { flags: \"--json\", key: \"json\", kind: \"boolean\", property: \"json\" },\n { flags: \"--keep-context\", key: \"keep-context\", kind: \"boolean\", property: \"keepContext\" },\n { flags: \"--line <text>\", key: \"line\", kind: \"array\", property: \"line\" },\n { flags: \"--limit <count>\", key: \"limit\", kind: \"string\", property: \"limit\" },\n { flags: \"--max-subtasks <count>\", key: \"max-subtasks\", kind: \"string\", property: \"maxSubtasks\" },\n { flags: \"--max-fix-iterations <count>\", key: \"max-fix-iterations\", kind: \"string\", property: \"maxFixIterations\" },\n { flags: \"--mode <mode>\", key: \"mode\", kind: \"string\", property: \"mode\" },\n { flags: \"--model <model>\", key: \"model\", kind: \"string\", property: \"model\" },\n { flags: \"--max-turns <count>\", key: \"max-turns\", kind: \"string\", property: \"maxTurns\" },\n { flags: \"--no-auto-brief\", key: \"no-auto-brief\", kind: \"negated\", property: \"autoBrief\" },\n { flags: \"--no-obsidian-context\", key: \"no-obsidian-context\", kind: \"negated\", property: \"obsidianContext\" },\n { flags: \"--no-post-check\", key: \"no-post-check\", kind: \"negated\", property: \"postCheck\" },\n { flags: \"--no-tui\", key: \"no-tui\", kind: \"negated\", property: \"tui\" },\n { flags: \"--no-retry-stash\", key: \"no-retry-stash\", kind: \"negated\", property: \"retryStash\" },\n { flags: \"--older-than <duration>\", key: \"older-than\", kind: \"string\", property: \"olderThan\" },\n { flags: \"--output-dir <path>\", key: \"output-dir\", kind: \"string\", property: \"outputDir\", aliases: [\"outputDir\"] },\n { flags: \"--plan\", key: \"plan\", kind: \"boolean\", property: \"plan\" },\n { flags: \"--plan-and-dispatch\", key: \"plan-and-dispatch\", kind: \"boolean\", property: \"planAndDispatch\" },\n { flags: \"--profile <id>\", key: \"profile\", kind: \"string\", property: \"profile\" },\n { flags: \"--provider <name>\", key: \"provider\", kind: \"string\", property: \"provider\" },\n { flags: \"--prompt-file <path>\", key: \"prompt-file\", kind: \"string\", property: \"promptFile\" },\n { flags: \"--repair-attempts <count>\", key: \"repair-attempts\", kind: \"string\", property: \"repairAttempts\" },\n { flags: \"--require-verification <command>\", key: \"require-verification\", kind: \"array\", property: \"requireVerification\" },\n { flags: \"--resume <run_id>\", key: \"resume\", kind: \"string\", property: \"resume\" },\n { flags: \"--retries <count>\", key: \"retries\", kind: \"string\", property: \"retries\" },\n { flags: \"--review\", key: \"review\", kind: \"boolean\", property: \"review\" },\n { flags: \"--section <name>\", key: \"section\", kind: \"array\", property: \"section\" },\n { flags: \"--secondary-tab <name>\", key: \"secondary-tab\", kind: \"string\", property: \"secondaryTab\", aliases: [\"secondaryTab\"] },\n { flags: \"--spec-generation\", key: \"spec-generation\", kind: \"boolean\", property: \"specGeneration\" },\n { flags: \"--tab <name>\", key: \"tab\", kind: \"string\", property: \"tab\" },\n { flags: \"-t, --tdd\", key: \"tdd\", kind: \"boolean\", property: \"tdd\" },\n { flags: \"--test-cmd <command>\", key: \"test-cmd\", kind: \"string\", property: \"testCmd\" },\n { flags: \"--title <text>\", key: \"title\", kind: \"string\", property: \"title\" },\n { flags: \"--suite <name>\", key: \"suite\", kind: \"string\", property: \"suite\" },\n { flags: \"--task <id>\", key: \"task\", kind: \"string\", property: \"task\" },\n { flags: \"--parallel <n>\", key: \"parallel\", kind: \"string\", property: \"parallel\" },\n { flags: \"--out <path>\", key: \"out\", kind: \"string\", property: \"out\" },\n { flags: \"--dry-run\", key: \"dry-run\", kind: \"boolean\", property: \"dryRun\" },\n { flags: \"--cost-regression-threshold <ratio>\", key: \"cost-regression-threshold\", kind: \"string\", property: \"costRegressionThreshold\" },\n { flags: \"--verbose-verifier\", key: \"verbose-verifier\", kind: \"boolean\", property: \"verboseVerifier\" },\n { flags: \"--verify <command>\", key: \"verify\", kind: \"array\", property: \"verify\" },\n { flags: \"--width <number>\", key: \"width\", kind: \"string\", property: \"width\" },\n { flags: \"--all\", key: \"all\", kind: \"boolean\", property: \"all\" },\n];\n\nfunction collectOptionValue(value: string, previous: string[] | undefined): string[] {\n return [...(previous ?? []), value];\n}\n\nfunction addCliOptions(command: Command): Command {\n for (const definition of cliOptionDefinitions) {\n const option = new Option(definition.flags);\n if (definition.kind === \"array\") {\n option.argParser(collectOptionValue).default([]);\n }\n command.addOption(option);\n }\n return command;\n}\n\nfunction normalizeCommanderArgv(argv: string[]): string[] {\n if (argv.length === 0) return [\"chat\"];\n if (argv[0] === \"--help\" || argv[0] === \"-h\") return argv;\n if (argv[0] && knownCommands.has(argv[0])) return normalizeOptionAliases(argv);\n const normalized = normalizeOptionAliases(argv);\n if (normalized.some((arg) => arg === \"--plan-and-dispatch\" || arg.startsWith(\"--plan-and-dispatch=\") || arg === \"--auto-fix-verify\" || arg.startsWith(\"--auto-fix-verify=\"))) {\n return [\"run\", ...normalized];\n }\n return [\"chat\", ...normalized];\n}\n\nfunction normalizeOptionAliases(argv: string[]): string[] {\n return argv.map((arg) => {\n if (arg === \"--ffmpegPath\") return \"--ffmpeg-path\";\n if (arg.startsWith(\"--ffmpegPath=\")) return `--ffmpeg-path=${arg.slice(\"--ffmpegPath=\".length)}`;\n if (arg === \"--outputDir\") return \"--output-dir\";\n if (arg.startsWith(\"--outputDir=\")) return `--output-dir=${arg.slice(\"--outputDir=\".length)}`;\n if (arg === \"--secondaryTab\") return \"--secondary-tab\";\n if (arg.startsWith(\"--secondaryTab=\")) return `--secondary-tab=${arg.slice(\"--secondaryTab=\".length)}`;\n if (arg === \"-pd\") return \"--plan-and-dispatch\";\n if (arg === \"-afv\") return \"--auto-fix-verify\";\n return arg;\n });\n}\n\nfunction optionSource(command: Command, property: string): string | undefined {\n return command.getOptionValueSource(property);\n}\n\nfunction parsedFromCommand(commandName: string, positional: string[], command: Command): ParsedArgs {\n const opts = command.opts<Record<string, unknown>>();\n const flags = new Map<string, string | string[] | boolean>();\n for (const definition of cliOptionDefinitions) {\n const source = optionSource(command, definition.property);\n const value = opts[definition.property];\n if (definition.kind === \"array\") {\n if (Array.isArray(value) && value.length > 0) {\n for (const item of value) appendFlagValue(flags, definition.key, String(item));\n for (const alias of definition.aliases ?? []) {\n for (const item of value) appendFlagValue(flags, alias, String(item));\n }\n }\n continue;\n }\n if (definition.kind === \"negated\") {\n if (source === \"cli\" && value === false) flags.set(definition.key, true);\n continue;\n }\n if (definition.kind === \"boolean\") {\n if (source === \"cli\" && value === true) flags.set(definition.key, true);\n continue;\n }\n if (source === \"cli\" && typeof value === \"string\") {\n flags.set(definition.key, value);\n for (const alias of definition.aliases ?? []) flags.set(alias, value);\n }\n }\n return { command: commandName, positional, flags };\n}\n\nfunction configureCliCommand(command: Command, commandName: string, onParsed: (args: ParsedArgs) => void): Command {\n addCliOptions(command)\n .argument(\"[args...]\", \"command arguments\")\n .allowExcessArguments(true)\n .action((positional: string[]) => {\n onParsed(parsedFromCommand(commandName, positional, command));\n });\n return command;\n}\n\nfunction buildCliProgram(onParsed: (args: ParsedArgs) => void): Command {\n const program = new Command();\n program\n .name(\"tanya\")\n .description(\"Tanya CLI\")\n .helpCommand(false)\n .showHelpAfterError()\n .allowExcessArguments(true);\n\n configureCliCommand(program.command(\"chat\").description(\"Start live chat\"), \"chat\", onParsed);\n configureCliCommand(program.command(\"ask\").description(\"Run one prompt without tools\"), \"ask\", onParsed);\n configureCliCommand(program.command(\"run\").description(\"Run an agent task with tools\"), \"run\", onParsed);\n configureCliCommand(program.command(\"review\").description(\"Review uncommitted changes against a task\"), \"review\", onParsed);\n configureCliCommand(program.command(\"init\").description(\"Create .tania/INSTRUCTIONS.md for this project\"), \"init\", onParsed);\n configureCliCommand(program.command(\"video\").description(\"Generate Tanya video assets\"), \"video\", onParsed);\n configureCliCommand(program.command(\"golden\").description(\"Manage local golden task memory\"), \"golden\", onParsed);\n configureCliCommand(program.command(\"benchmark\").description(\"Run executable regression benchmarks\"), \"benchmark\", onParsed);\n configureCliCommand(program.command(\"eval\").description(\"Run eval suites and reports\"), \"eval\", onParsed);\n configureCliCommand(program.command(\"providers\").description(\"Provider utilities\"), \"providers\", onParsed);\n configureCliCommand(program.command(\"mcp\").description(\"MCP server/client utilities\"), \"mcp\", onParsed);\n configureCliCommand(program.command(\"doctor\").description(\"Check local setup\"), \"doctor\", onParsed);\n configureCliCommand(program.command(\"debug-prompt\").description(\"Print system prompt without running agent\"), \"debug-prompt\", onParsed);\n configureCliCommand(program.command(\"runs\").description(\"Show recent run logs\"), \"runs\", onParsed);\n configureCliCommand(program.command(\"patterns\").description(\"Show forbidden-pattern fire metrics\"), \"patterns\", onParsed);\n configureCliCommand(program.command(\"sessions\").description(\"Manage chat sessions\"), \"sessions\", onParsed);\n return program;\n}\n\nfunction parseArgs(argv: string[]): ParsedArgs {\n if (argv[0] === \"help\") return { command: \"help\", positional: argv.slice(1), flags: new Map() };\n let parsed: ParsedArgs | undefined;\n const program = buildCliProgram((args) => {\n parsed = args;\n });\n program.parse(normalizeCommanderArgv(argv), { from: \"user\" });\n return parsed ?? { command: \"chat\", positional: [], flags: new Map() };\n}\n\nfunction appendFlagValue(flags: Map<string, string | string[] | boolean>, key: string, value: string) {\n const existing = flags.get(key);\n if (typeof existing === \"string\") {\n flags.set(key, [existing, value]);\n } else if (Array.isArray(existing)) {\n existing.push(value);\n } else {\n flags.set(key, value);\n }\n}\n\nfunction flagString(args: ParsedArgs, name: string): string | undefined {\n const value = args.flags.get(name);\n return typeof value === \"string\" ? value : undefined;\n}\n\nfunction flagStrings(args: ParsedArgs, name: string): string[] {\n const value = args.flags.get(name);\n if (typeof value === \"string\") return [value];\n if (Array.isArray(value)) return value;\n return [];\n}\n\nfunction hasFlag(args: ParsedArgs, name: string): boolean {\n const value = args.flags.get(name);\n return value === true || typeof value === \"string\" || Array.isArray(value);\n}\n\nfunction flagNumber(args: ParsedArgs, name: string): number | undefined {\n const value = flagString(args, name);\n if (!value) return undefined;\n const parsed = Number(value);\n return Number.isFinite(parsed) ? parsed : undefined;\n}\n\nasync function readVerifyFailuresFromStdin(): Promise<VerifyFailure[]> {\n if (process.stdin.isTTY) return [];\n const rl = createInterface({ input: process.stdin, crlfDelay: Infinity });\n const lines: string[] = [];\n for await (const line of rl) {\n lines.push(line);\n try {\n const event = JSON.parse(line) as { type?: string };\n if (event.type === \"verify_failure_eof\") break;\n } catch {\n continue;\n }\n }\n rl.close();\n return parseVerifyFailureJSONL(lines);\n}\n\nfunction applyCliProfileFlag(args: ParsedArgs): void {\n if (args.command !== \"run\" && args.command !== \"chat\") return;\n const profile = flagString(args, \"profile\");\n if (!profile) return;\n process.env.TANYA_PROFILE = profile;\n}\n\nfunction applyCliProviderFlag(args: ParsedArgs): void {\n const provider = flagString(args, \"provider\");\n if (!provider) return;\n process.env.TANYA_PROVIDER = provider;\n}\n\nfunction applyCliModeFlag(args: ParsedArgs): void {\n if (args.command !== \"run\" && args.command !== \"chat\") return;\n const mode = flagString(args, \"mode\");\n if (!mode) return;\n if (![\"ask\", \"bypass\", \"plan\", \"default\"].includes(mode)) {\n throw new Error(`Invalid permission mode: ${mode}. Expected ask, bypass, plan, or default.`);\n }\n process.env.TANYA_MODE = mode;\n}\n\nfunction buildRetryContext(manifest: TanyaFinalManifest, attempt: number, extraBlockers: string[] = []): string {\n const lines = [\n `RETRY CONTEXT (attempt ${attempt}): the previous run did not complete cleanly.`,\n \"Do not repeat the same approach that failed.\",\n ];\n const allBlockers = [...manifest.blockers, ...extraBlockers];\n if (allBlockers.length > 0) {\n lines.push(\"\", \"Previous run blockers:\");\n for (const blocker of allBlockers) lines.push(`- ${blocker}`);\n }\n if (manifest.changedFiles.length > 0) {\n lines.push(\"\", \"Files already changed in previous attempt (verify their current state before editing):\");\n for (const file of manifest.changedFiles) lines.push(`- ${file}`);\n }\n if (manifest.verification.length > 0) {\n lines.push(\"\", \"Verification results from previous attempt:\");\n for (const verification of manifest.verification) lines.push(`- ${verification}`);\n }\n lines.push(\"\", \"Fix the blockers above and complete the task.\");\n return lines.join(\"\\n\");\n}\n\nfunction usage(): string {\n return `Tanya CLI\n\nUsage:\n tanya Start live chat\n tanya chat [--profile reasoner] Start live chat\n tanya --continue Continue the latest chat session for this project\n tanya --resume <id> Resume a specific chat session\n tanya ask \"prompt\" Run one prompt without tools\n tanya init [--cwd path] Create .tania/INSTRUCTIONS.md for this project\n tanya run [--cwd path] [--profile reasoner] \"task\" Run an agent task with tools\n tanya run \"task\" Auto-detects ./artifacts if present\n tanya run --context-file /tmp/context.json --prompt-file /tmp/prompt.txt\n tanya run --artifacts-root <path> \"task\" Use a custom artifacts directory\n tanya run --artifacts-root /path/to/artifacts --artifact ios/FastlaneSetup.md \"task\"\n tanya run --context-path /path/to/brand/safety.md --artifact-output-root /path/to/artifacts \"task\"\n tanya run --mode spec-generation \"task\" Non-coding spec generation; no edits, verification, or final coding report\n tanya run --no-auto-brief \"task\" Skip automatic local task briefing\n tanya run --no-obsidian-context \"task\" Skip automatic Obsidian context retrieval\n tanya run --no-post-check \"task\" Skip independent TypeScript/test verification\n tanya run --repair-attempts 2 --context-file /tmp/context.json --prompt-file /tmp/prompt.txt\n tanya run --keep-context --artifacts-root /path/to/artifacts --artifact ios/FastlaneSetup.md \"task\"\n tanya run --verify \"npm run typecheck\" --verify \"npm run build\" \"task\"\n tanya run --verbose-verifier \"task\" Include advisory reasoning excerpts in verifier reports\n tanya run --retries 2 \"task\" Retry up to 2 times if the run has blockers\n tanya run --plan \"task\" Pre-plan with deepseek-reasoner before executing\n tanya run --plan-and-dispatch \"task\" Split a task into sequential sub-tasks\n tanya run --plan-and-dispatch --tdd \"task\" Split into sub-tasks with RED/GREEN TDD\n tanya run --plan-and-dispatch --auto-fix-verify \"task\" Read verify_failure JSONL batches on stdin and re-prompt fixes\n tanya --plan-and-dispatch \"task\" Shorthand for plan-and-dispatch run mode\n tanya run --resume <run_id> Resume a stopped dispatch run\n tanya run --plan --retries 2 \"task\"\n tanya run --review \"task\" Run task then auto-review the diff\n tanya run --plan --retries 2 --review \"task\" Full autonomous mode\n tanya run --json --prompt-file /tmp/prompt.txt\n tanya debug-prompt \"task\" Print system prompt without running agent\n tanya debug-prompt --cwd <path> \"task\" Print system prompt for a specific project\n tanya debug-prompt --section artifacts \"task\" Print only the artifact section\n tanya debug-prompt --section exports \"task\" Print only the export map section\n tanya runs [--cwd <path>] Show last 10 run logs with cost and status\n tanya sessions list [--all] [--cwd path] [--global]\n tanya sessions show <id>\n tanya sessions rm <id>\n tanya sessions prune --older-than 30d\n tanya review \"task description\" Review uncommitted changes against the task\n tanya review --cwd <path> \"task\" Review changes in a specific project\n tanya video presets\n tanya video one-terminal-simctl --output-dir assets/video\n tanya video render-ad --input spec.json --output-dir assets/video-ads --format mp4 --format poster\n tanya golden summary Summarize local golden task memory\n tanya golden profiles List built-in golden task profiles\n tanya golden run Run executable golden task fixtures\n tanya golden validate Fail if latest golden task signatures are failing\n tanya benchmark profiles List benchmark profiles\n tanya benchmark run --all Run executable regression benchmarks\n tanya benchmark validate Validate recent benchmark signatures\n tanya eval --suite tanya-native --dry-run\n tanya eval --suite eco-30 --provider deepseek --model deepseek-chat --out result.json\n tanya providers test --provider deepseek Test provider configuration (live only with TANYA_RUN_LIVE_PROVIDER_TESTS=1)\n tanya mcp serve Start Tanya's MCP server over stdio\n tanya doctor Check local setup\n tanya patterns Show forbidden-pattern fire metrics for this workspace\n\nInstall locally during development:\n npm install\n npm run link:local\n`;\n}\n\nfunction readPrompt(args: ParsedArgs): string {\n const promptFile = flagString(args, \"prompt-file\");\n if (promptFile) return readFileSync(resolve(promptFile), \"utf8\");\n return args.positional.join(\" \").trim();\n}\n\nasync function buildRunContextForCli(\n args: ParsedArgs,\n cwd: string,\n prompt: string,\n obsidianVault?: string,\n): Promise<TanyaRunContext | undefined> {\n const contextFile = flagString(args, \"context-file\");\n const baseRunContext = contextFile ? loadRunContextFile(contextFile) : undefined;\n const mode = flagString(args, \"mode\")?.trim();\n const specGenerationMode = mode === \"spec-generation\" || mode === \"spec\" || hasFlag(args, \"spec-generation\");\n if (specGenerationMode) {\n const baseSpecContext: TanyaRunContext = { ...(baseRunContext ?? {}) };\n delete baseSpecContext.expected_report;\n delete baseSpecContext.verification;\n const runContext: TanyaRunContext = {\n ...baseSpecContext,\n task: {\n ...(baseRunContext?.task ?? {}),\n kind: \"spec-generation\",\n title: baseRunContext?.task?.title ?? prompt.split(/\\r?\\n/).find((line) => line.trim().length > 0)?.trim().slice(0, 120) ?? \"Spec generation\",\n },\n instructions: [\n ...(baseRunContext?.instructions ?? []),\n \"You are running in spec-generation mode.\",\n \"Generate the requested specification only.\",\n \"Do not edit files, run shell commands, run verification, inspect git status, or create artifacts.\",\n \"Do not append coding-agent report sections such as Verification, Final Report, Modified files, Artifact reused, Artifact created, or Blockers.\",\n ],\n metadata: {\n ...(baseRunContext?.metadata ?? {}),\n mode: \"spec-generation\",\n autoContext: false,\n },\n };\n return buildAutoRunContext({\n cwd,\n prompt,\n runContext,\n obsidianVault,\n enableBrief: false,\n enableObsidian: false,\n keepContext: false,\n });\n }\n const explicitArtifactsRoot = flagString(args, \"artifacts-root\");\n const localArtifactsRoot = resolve(cwd, \"artifacts\");\n const artifactsRoot = explicitArtifactsRoot ?? (existsSync(localArtifactsRoot) ? localArtifactsRoot : undefined);\n let runContext = materializeCliArtifacts({\n cwd,\n root: artifactsRoot,\n artifacts: flagStrings(args, \"artifact\"),\n contextPaths: flagStrings(args, \"context-path\"),\n artifactOutputRoot: flagString(args, \"artifact-output-root\"),\n keepContext: hasFlag(args, \"keep-context\"),\n baseContext: baseRunContext,\n });\n if (!explicitArtifactsRoot && artifactsRoot) {\n const autoArtifactInstructions = [\n \"This workspace contains an artifacts/ directory with reusable patterns.\",\n \"The artifact index and rules have been injected into your system prompt.\",\n \"Before implementing anything, check the artifact index and read relevant artifacts.\",\n ];\n runContext = {\n ...(runContext ?? {}),\n instructions: [...(runContext?.instructions ?? []), ...autoArtifactInstructions],\n };\n }\n const extraVerify = flagStrings(args, \"verify\");\n if (extraVerify.length > 0) {\n const existing = runContext?.verification?.commands ?? [];\n const merged = [...new Set([...existing, ...extraVerify])];\n runContext = { ...(runContext ?? {}), task: { ...(runContext?.task ?? {}), kind: \"coding\" }, verification: { commands: merged } };\n }\n const requireVerify = flagStrings(args, \"require-verification\");\n if (requireVerify.length > 0) {\n // --require-verification REPLACES the auto-brief verification list with exactly\n // these commands. Use when the caller knows the canonical verification set\n // and the auto-generated recommendations would over-require.\n runContext = {\n ...(runContext ?? {}),\n task: { ...(runContext?.task ?? {}), kind: \"coding\" },\n verification: { commands: [...new Set(requireVerify)] },\n metadata: { ...(runContext?.metadata ?? {}), verificationOverridden: true },\n };\n }\n if (hasFlag(args, \"verbose-verifier\")) {\n runContext = {\n ...(runContext ?? {}),\n metadata: { ...(runContext?.metadata ?? {}), verboseVerifier: true },\n };\n }\n return buildAutoRunContext({\n cwd,\n prompt,\n ...(runContext ? { runContext } : {}),\n obsidianVault,\n enableBrief: !hasFlag(args, \"no-auto-brief\"),\n enableObsidian: !hasFlag(args, \"no-obsidian-context\"),\n keepContext: hasFlag(args, \"keep-context\"),\n });\n}\n\nfunction selectPromptSections(systemPrompt: string, sections: string[]): string {\n if (sections.length === 0) return systemPrompt;\n const sectionMap: Record<string, { starts: string[]; ends: string[] }> = {\n artifacts: {\n starts: [\"## Artifact Index\", \"## Project Artifacts\"],\n ends: [\"## Workspace Context\", \"## Project Instructions\", \"## Caller Context\"],\n },\n \"repo-map\": {\n starts: [\"## Repo Map (advisory)\"],\n ends: [\"## Artifact Index\", \"## Workspace Context\", \"## Project Instructions\", \"## Caller Context\"],\n },\n exports: {\n starts: [\"## Workspace export map\"],\n ends: [\"## Repo Map (advisory)\", \"## Artifact Index\", \"## Project Artifacts\", \"## Workspace Context\", \"## Project Instructions\", \"## Caller Context\"],\n },\n context: {\n starts: [\"## Workspace Context\"],\n ends: [\"## Project Instructions\", \"## Caller Context\"],\n },\n instructions: {\n starts: [\"## Project Instructions\"],\n ends: [\"## Caller Context\"],\n },\n };\n\n const findHeading = (heading: string, from = 0): number => {\n if (systemPrompt.startsWith(`${heading}\\n`)) return 0;\n return systemPrompt.indexOf(`\\n${heading}\\n`, from);\n };\n\n const extractSection = (starts: string[], ends: string[]): string | null => {\n const startCandidates = starts\n .map((heading) => findHeading(heading))\n .filter((index) => index >= 0);\n if (startCandidates.length === 0) return null;\n let start = Math.min(...startCandidates);\n if (systemPrompt[start] === \"\\n\") start += 1;\n\n const endCandidates = ends\n .map((heading) => findHeading(heading, start + 1))\n .filter((index) => index > start);\n const end = endCandidates.length > 0 ? Math.min(...endCandidates) : systemPrompt.length;\n return systemPrompt.slice(start, end).trim();\n };\n\n const matched: string[] = [];\n for (const section of sections) {\n const definition = sectionMap[section];\n if (!definition) {\n process.stderr.write(`[debug-prompt] Unknown section \"${section}\". Available: ${Object.keys(sectionMap).join(\", \")}\\n`);\n continue;\n }\n const match = extractSection(definition.starts, definition.ends);\n if (match) {\n matched.push(match);\n } else {\n process.stderr.write(`[debug-prompt] Section \"${section}\" not found in prompt.\\n`);\n }\n }\n return matched.join(\"\\n\\n---\\n\\n\");\n}\n\nasync function askOnce(provider: ReturnType<typeof createProvider>, prompt: string): Promise<string> {\n let text = \"\";\n for await (const delta of provider.streamChat({ messages: [{ role: \"user\", content: prompt }], tools: [] })) {\n if (delta.content) {\n process.stdout.write(delta.content);\n text += delta.content;\n }\n }\n process.stdout.write(\"\\n\");\n return text;\n}\n\nfunction buildRoutingOptions(config: ReturnType<typeof loadConfig>, cwd: string): RunAgentOptions[\"routing\"] | undefined {\n const loaded = loadRouteTable({\n cwd,\n defaults: { provider: config.provider, model: config.model },\n });\n for (const issue of loaded.issues) {\n process.stderr.write(`[tanya] Ignoring invalid route config ${issue.file} ${issue.path}: ${issue.message}\\n`);\n }\n const hasRouteFile = loaded.table.sources.some((source) => source !== \"built-in\");\n return {\n enabled: hasRouteFile,\n table: loaded.table,\n providerFactory: (target) => createProviderForRoute(config, target),\n };\n}\n\nfunction shouldUseInkChat(args: ParsedArgs, json: boolean): boolean {\n if (args.command !== \"chat\") return false;\n if (json) return false;\n if (hasFlag(args, \"no-tui\")) return false;\n if (envValue({}, \"TANYA_TUI\").trim().toLowerCase() === \"off\") return false;\n return Boolean(process.stdout.isTTY && process.stdin.isTTY);\n}\n\nasync function testProvider(args: ParsedArgs): Promise<void> {\n const requestedProvider = flagString(args, \"provider\") ?? \"configured\";\n if (envValue({}, \"TANYA_RUN_LIVE_PROVIDER_TESTS\") !== \"1\") {\n console.log(`skipped live provider test for ${requestedProvider}; set TANYA_RUN_LIVE_PROVIDER_TESTS=1 to run against the real endpoint.`);\n return;\n }\n const config = loadConfig();\n const provider = createProvider(config);\n const startedAt = Date.now();\n let text = \"\";\n for await (const delta of provider.streamChat({\n messages: [\n { role: \"system\", content: \"You are a provider conformance probe. Keep answers short.\" },\n { role: \"user\", content: \"Reply with exactly: pong\" },\n { role: \"user\", content: \"No tools are needed.\" },\n ],\n tools: [],\n maxTokens: 12,\n temperature: 0,\n })) {\n if (delta.content) text += delta.content;\n }\n console.log(`PASS adapter: ${provider.id}:${provider.model}`);\n console.log(`PASS streaming-chat: ${Date.now() - startedAt}ms ${text.trim()}`);\n console.log(\"PASS parser-surface: mock conformance covers malformed tool-call quirks in CI\");\n}\n\nasync function runEvalCommand(args: ParsedArgs): Promise<void> {\n const cwd = resolve(flagString(args, \"cwd\") ?? process.cwd());\n const action = args.positional[0];\n const format = flagStrings(args, \"format\").includes(\"markdown\") ? \"markdown\" : \"text\";\n if (action === \"report\") {\n const file = args.positional[1];\n if (!file) throw new Error(\"Usage: tanya eval report <result.json> [--format markdown]\");\n process.stdout.write(formatEvalReport(await readEvalResult(resolve(cwd, file)), format));\n return;\n }\n if (action === \"compare\") {\n const baseline = args.positional[1];\n const next = args.positional[2];\n if (!baseline || !next) throw new Error(\"Usage: tanya eval compare <baseline.json> <new.json> [--format markdown]\");\n const comparison = compareEvalResults(\n await readEvalResult(resolve(cwd, baseline)),\n await readEvalResult(resolve(cwd, next)),\n flagNumber(args, \"cost-regression-threshold\") ?? 0.20,\n );\n process.stdout.write(formatEvalComparison(comparison, format));\n if (comparison.regressions.length > 0) process.exitCode = 1;\n return;\n }\n const suiteName = flagString(args, \"suite\") ?? args.positional[0] ?? \"tanya-native\";\n const suite = loadEvalSuite(suiteName);\n const modelFlag = flagString(args, \"model\");\n const modelParts = modelFlag?.includes(\"/\") ? modelFlag.split(\"/\") : undefined;\n const providerName = modelParts?.[0] ?? flagString(args, \"provider\");\n const modelName = modelParts?.[1] ?? modelFlag;\n const config = hasFlag(args, \"dry-run\") && providerName && modelName\n ? undefined\n : loadConfig(cwd);\n const provider = providerName ?? config?.provider ?? \"deepseek\";\n const model = modelName ?? config?.model ?? \"deepseek-chat\";\n if (hasFlag(args, \"dry-run\")) {\n const dryRun = dryRunEvalSuite(suite, provider, model);\n if (hasFlag(args, \"json\")) {\n process.stdout.write(`${JSON.stringify(dryRun, null, 2)}\\n`);\n } else {\n process.stdout.write(`Eval dry-run: ${dryRun.suite}@${dryRun.suiteVersion}\\n`);\n process.stdout.write(`Tasks: ${dryRun.taskCount}\\n`);\n process.stdout.write(`Model: ${provider}/${model}\\n`);\n process.stdout.write(`Estimated cost: ${dryRun.estimatedCostUsd === null ? \"pricing unknown\" : `$${dryRun.estimatedCostUsd.toFixed(3)}`}\\n`);\n }\n return;\n }\n\n process.env.TANYA_PROVIDER = provider;\n process.env.TANYA_MODEL = model;\n const evalConfig = loadConfig(cwd);\n const taskIds = parseTaskFilter(flagString(args, \"task\"));\n const parallel = flagNumber(args, \"parallel\");\n const result = await runEvalSuite(suite, {\n cwd,\n provider,\n model,\n tanyaVersion: JSON.parse(readFileSync(resolve(\"package.json\"), \"utf8\")).version,\n ...(taskIds ? { taskIds } : {}),\n ...(parallel !== undefined ? { parallel } : {}),\n providerFactory: () => createProvider(evalConfig),\n });\n const out = flagString(args, \"out\");\n if (out) {\n await writeEvalResult(resolve(cwd, out), result);\n process.stdout.write(`Wrote eval result to ${resolve(cwd, out)}\\n`);\n } else {\n process.stdout.write(`${JSON.stringify(result, null, 2)}\\n`);\n }\n}\n\nasync function doctor(args?: ParsedArgs): Promise<void> {\n const cwd = resolve(args ? flagString(args, \"cwd\") ?? process.cwd() : process.cwd());\n const config = loadConfig(cwd);\n const checks: Array<{ name: string; status: \"ok\" | \"warn\" | \"fail\"; detail: string }> = [];\n const ok = (name: string, detail: string) => checks.push({ name, status: \"ok\", detail });\n const warn = (name: string, detail: string) => checks.push({ name, status: \"warn\", detail });\n const fail = (name: string, detail: string) => checks.push({ name, status: \"fail\", detail });\n\n // Node + runtime\n const major = Number(process.version.replace(/^v/, \"\").split(\".\")[0] ?? \"0\");\n if (major >= 20) ok(\"node\", `${process.version}`);\n else fail(\"node\", `${process.version} — tanya requires Node 20+`);\n\n // Provider config\n if (config.apiKey) ok(\"provider.apiKey\", \"present\");\n else fail(\"provider.apiKey\", \"missing — set TANYA_API_KEY or DEEPSEEK_API_KEY\");\n if (config.baseUrl) ok(\"provider.baseUrl\", config.baseUrl);\n else fail(\"provider.baseUrl\", \"missing — set TANYA_BASE_URL\");\n ok(\"provider.model\", `${config.provider}:${config.model} (profile=${config.profile})`);\n ok(\"provider.timeoutMs\", `${config.timeoutMs}ms`);\n\n // Workspace\n const cwdHasGit = existsSync(join(cwd, \".git\"));\n if (cwdHasGit) ok(\"workspace.git\", `${cwd}`);\n else warn(\"workspace.git\", `${cwd} is not a git repository — stash/retry recovery will be disabled`);\n const cwdHasArtifacts = existsSync(join(cwd, \"artifacts\"));\n if (cwdHasArtifacts) ok(\"workspace.artifacts\", `${join(cwd, \"artifacts\")} (auto-detected)`);\n else warn(\"workspace.artifacts\", \"no ./artifacts dir — pass --artifacts-root or run from a project that has one\");\n\n // Project-level forbidden patterns\n const fpPath = join(cwd, \".tania\", \"forbidden-patterns.json\");\n if (existsSync(fpPath)) {\n try {\n const raw = readFileSync(fpPath, \"utf8\");\n const parsed = JSON.parse(raw);\n const count = Array.isArray(parsed?.patterns) ? parsed.patterns.length : 0;\n ok(\"workspace.forbiddenPatterns\", `${count} project pattern(s) loaded from ${fpPath}`);\n } catch (err) {\n fail(\"workspace.forbiddenPatterns\", `${fpPath} exists but is invalid JSON: ${err instanceof Error ? err.message : String(err)}`);\n }\n } else {\n ok(\"workspace.forbiddenPatterns\", \"no project overrides (using defaults)\");\n }\n\n // Forbidden-pattern fire metrics (from accumulated runs)\n const fpMetricsPath = join(cwd, \".tania\", \"memory\", \"forbidden-patterns-metrics.json\");\n if (existsSync(fpMetricsPath)) {\n try {\n const raw = readFileSync(fpMetricsPath, \"utf8\");\n const parsed = JSON.parse(raw) as { totals?: Record<string, number>; totalScans?: number };\n const totals = parsed.totals ?? {};\n const top = Object.entries(totals).sort((a, b) => b[1] - a[1]).slice(0, 5);\n if (top.length > 0) {\n const summary = top.map(([id, n]) => `${id}=${n}`).join(\", \");\n ok(\"workspace.forbiddenPatterns.metrics\", `top fires across ${parsed.totalScans ?? 0} scans: ${summary}`);\n } else {\n ok(\"workspace.forbiddenPatterns.metrics\", `no patterns ever fired (${parsed.totalScans ?? 0} scans)`);\n }\n } catch {\n warn(\"workspace.forbiddenPatterns.metrics\", `${fpMetricsPath} exists but is unreadable`);\n }\n } else {\n ok(\"workspace.forbiddenPatterns.metrics\", \"no metrics yet (no scans recorded)\");\n }\n\n // Obsidian vault\n if (config.obsidianVault) {\n if (existsSync(config.obsidianVault)) ok(\"obsidian.vault\", config.obsidianVault);\n else warn(\"obsidian.vault\", `${config.obsidianVault} configured but path does not exist`);\n } else {\n ok(\"obsidian.vault\", \"not configured (optional)\");\n }\n\n // ffmpeg presence (informational; only required for tanya video)\n try {\n const { execFileSync } = await import(\"node:child_process\");\n execFileSync(\"ffmpeg\", [\"-version\"], { stdio: \"ignore\" });\n ok(\"ffmpeg\", \"available (tanya video commands enabled)\");\n } catch {\n warn(\"ffmpeg\", \"not found on PATH — tanya video commands will fail until installed\");\n }\n\n // Render\n console.log(`Tanya doctor — ${cwd}`);\n console.log(\"\");\n for (const check of checks) {\n const tag = check.status === \"ok\" ? \"[ok] \" : check.status === \"warn\" ? \"[warn]\" : \"[FAIL]\";\n console.log(`${tag} ${check.name.padEnd(28)} ${check.detail}`);\n }\n const failed = checks.filter((c) => c.status === \"fail\").length;\n const warned = checks.filter((c) => c.status === \"warn\").length;\n console.log(\"\");\n console.log(`Summary: ${checks.length - failed - warned} ok, ${warned} warn, ${failed} fail`);\n if (failed > 0) process.exitCode = 1;\n}\n\nasync function runVideoCommand(args: ParsedArgs): Promise<void> {\n const preset = args.positional[0] ?? \"one-terminal-simctl\";\n if (preset === \"presets\" || preset === \"list\") {\n console.log(\"Video presets:\");\n for (const item of videoPresets) {\n const aliases = item.aliases.length ? ` aliases: ${item.aliases.join(\", \")}` : \"\";\n console.log(`- ${item.name} (${item.width}x${item.height}, ${item.fps}fps, ${item.duration}s)${aliases}`);\n console.log(` ${item.description}`);\n }\n return;\n }\n if (preset === \"render-ad\") {\n const cwd = resolve(flagString(args, \"cwd\") ?? process.cwd());\n const input = flagString(args, \"input\");\n if (!input) {\n console.log(\"Usage: tanya video render-ad --input spec.json [--output-dir dir] [--basename name] [--format mp4] [--format poster]\");\n return;\n }\n const formats = flagStrings(args, \"format\");\n const renderOptions: Parameters<typeof renderFullAd>[0] = {\n input,\n formats: formats.length ? formats as Array<\"mp4\" | \"poster\"> : [\"mp4\", \"poster\"],\n };\n const outputDir = flagString(args, \"output-dir\") ?? flagString(args, \"outputDir\");\n const basename = flagString(args, \"basename\");\n const ffmpegPath = flagString(args, \"ffmpeg-path\") ?? flagString(args, \"ffmpegPath\");\n if (outputDir) renderOptions.outputDir = outputDir;\n if (basename) renderOptions.basename = basename;\n if (ffmpegPath) renderOptions.ffmpegPath = ffmpegPath;\n const result = await renderFullAd(renderOptions, cwd);\n console.log(JSON.stringify({\n mp4Path: result.mp4Path,\n posterPath: result.posterPath,\n durationMs: result.durationMs,\n frameCount: result.frameCount,\n width: result.width,\n height: result.height,\n warnings: result.warnings,\n }, null, 2));\n return;\n }\n if (preset !== \"one-terminal-simctl\" && preset !== \"terminal-simctl\") {\n console.log(\"Usage: tanya video one-terminal-simctl [--output-dir dir] [--basename name] [--width 980] [--height 1012] [--duration 3] [--fps 30] [--format webm] [--format mov] [--format poster] [--line text]\\n tanya video render-ad --input spec.json [--output-dir dir] [--format mp4] [--format poster]\");\n return;\n }\n const cwd = resolve(flagString(args, \"cwd\") ?? process.cwd());\n const formats = flagStrings(args, \"format\");\n const options: Parameters<typeof generateVideoAsset>[0] = { preset };\n const outputDir = flagString(args, \"output-dir\") ?? flagString(args, \"outputDir\");\n const basename = flagString(args, \"basename\");\n const width = flagNumber(args, \"width\");\n const height = flagNumber(args, \"height\");\n const fps = flagNumber(args, \"fps\");\n const duration = flagNumber(args, \"duration\");\n const title = flagString(args, \"title\");\n const tab = flagString(args, \"tab\");\n const secondaryTab = flagString(args, \"secondary-tab\") ?? flagString(args, \"secondaryTab\");\n const badge = flagString(args, \"badge\");\n const lines = flagStrings(args, \"line\");\n if (outputDir) options.outputDir = outputDir;\n if (basename) options.basename = basename;\n if (width !== undefined) options.width = width;\n if (height !== undefined) options.height = height;\n if (fps !== undefined) options.fps = fps;\n if (duration !== undefined) options.duration = duration;\n if (formats.length > 0) options.formats = formats as Array<\"webm\" | \"mov\" | \"poster\">;\n if (title) options.title = title;\n if (tab) options.tab = tab;\n if (secondaryTab) options.secondaryTab = secondaryTab;\n if (badge) options.badge = badge;\n if (lines.length > 0) options.lines = lines;\n const result = await generateVideoAsset(options, cwd);\n console.log(`Generated ${result.files.length} video asset file${result.files.length === 1 ? \"\" : \"s\"}:`);\n for (const file of result.files) console.log(`- ${file}`);\n}\n\nasync function main(): Promise<void> {\n const args = parseArgs(process.argv.slice(2));\n applyCliProviderFlag(args);\n applyCliModeFlag(args);\n if (args.command === \"help\" || args.command === \"--help\" || args.command === \"-h\") {\n console.log(usage());\n return;\n }\n\n if (args.command === \"doctor\") {\n await doctor(args);\n return;\n }\n\n if (args.command === \"patterns\") {\n const cwd = resolve(flagString(args, \"cwd\") ?? process.cwd());\n const metricsPath = join(cwd, \".tania\", \"memory\", \"forbidden-patterns-metrics.json\");\n if (!existsSync(metricsPath)) {\n console.log(`No metrics file at ${metricsPath}. Run a tanya task in this workspace first.`);\n return;\n }\n try {\n const parsed = JSON.parse(readFileSync(metricsPath, \"utf8\")) as {\n totals?: Record<string, number>;\n lastFiredAt?: Record<string, string>;\n totalScans?: number;\n };\n const totals = parsed.totals ?? {};\n const lastFiredAt = parsed.lastFiredAt ?? {};\n const entries = Object.entries(totals).sort((a, b) => b[1] - a[1]);\n console.log(`Forbidden-pattern fire metrics — ${cwd}`);\n console.log(`Total scans: ${parsed.totalScans ?? 0}`);\n console.log(\"\");\n if (entries.length === 0) {\n console.log(\"No patterns have fired in this workspace yet.\");\n return;\n }\n console.log(`${\"PATTERN\".padEnd(48)} ${\"FIRES\".padStart(7)} LAST FIRED`);\n for (const [id, count] of entries) {\n const last = lastFiredAt[id]?.slice(0, 16) ?? \"—\";\n console.log(`${id.padEnd(48)} ${String(count).padStart(7)} ${last}`);\n }\n } catch (err) {\n console.error(`Could not read metrics: ${err instanceof Error ? err.message : String(err)}`);\n process.exitCode = 1;\n }\n return;\n }\n\n if (args.command === \"sessions\") {\n const cwd = resolve(flagString(args, \"cwd\") ?? process.cwd());\n await runSessionsCommand({\n action: args.positional[0] ?? \"list\",\n args: args.positional.slice(1),\n cwd,\n global: hasFlag(args, \"global\"),\n all: hasFlag(args, \"all\"),\n limit: flagNumber(args, \"limit\"),\n olderThan: flagString(args, \"older-than\"),\n });\n return;\n }\n\n if (args.command === \"providers\") {\n if (args.positional[0] !== \"test\") {\n console.log(\"Usage: tanya providers test --provider <name>\");\n return;\n }\n await testProvider(args);\n return;\n }\n\n if (args.command === \"permissions\") {\n if (args.positional[0] !== \"migrate\") {\n console.log(\"Usage: tanya permissions migrate [--cwd path] [--limit 100]\");\n return;\n }\n const cwd = resolve(flagString(args, \"cwd\") ?? process.cwd());\n const limit = flagNumber(args, \"limit\") ?? 100;\n console.log(JSON.stringify(suggestPermissionsFromRuns(cwd, limit), null, 2));\n return;\n }\n\n if (args.command === \"mcp\") {\n if (args.positional[0] !== \"serve\") {\n console.log(\"Usage: tanya mcp serve\");\n return;\n }\n await serveTanyaMcpServer({ defaultCwd: resolve(flagString(args, \"cwd\") ?? process.cwd()) });\n return;\n }\n\n if (args.command === \"eval\") {\n await runEvalCommand(args);\n return;\n }\n\n if (args.command === \"init\") {\n const cwd = resolve(flagString(args, \"cwd\") ?? process.cwd());\n const path = await initTanyaProject(cwd);\n console.log(path);\n return;\n }\n\n if (args.command === \"video\") {\n await runVideoCommand(args);\n return;\n }\n\n if (args.command === \"golden\" || args.command === \"benchmark\") {\n const cwd = resolve(flagString(args, \"cwd\") ?? process.cwd());\n const action = args.positional[0] ?? \"summary\";\n if (![\"summary\", \"list\", \"profiles\", \"run\", \"validate\"].includes(action)) {\n console.log(`Usage: tanya ${args.command} summary|list|profiles|run|validate [--cwd path] [--json] [--profile id] [--all]`);\n return;\n }\n const profile = flagString(args, \"profile\");\n const exitCode = await runGoldenSuiteCommand(cwd, action, hasFlag(args, \"json\"), {\n ...(profile ? { profile } : {}),\n all: hasFlag(args, \"all\"),\n });\n process.exitCode = exitCode;\n return;\n }\n\n if (args.command === \"runs\") {\n const cwd = resolve(flagString(args, \"cwd\") ?? process.cwd());\n const logs = readRunLogs(cwd, 10);\n if (logs.length === 0) {\n process.stdout.write(\"No run logs found. Run tanya run first.\\n\");\n return;\n }\n for (const log of logs) process.stdout.write(`${formatRunLogLine(log)}\\n`);\n return;\n }\n\n applyCliProfileFlag(args);\n const config = loadConfig();\n\n if (args.command === \"debug-prompt\") {\n const cwd = resolve(flagString(args, \"cwd\") ?? process.cwd());\n const task = readPrompt(args);\n if (!task) throw new Error(\"Missing task. Usage: tanya debug-prompt --cwd <path> \\\"task description\\\"\");\n\n const runContext = await buildRunContextForCli(args, cwd, task, config.obsidianVault);\n const historyBlock = buildHistoryBlock(await readRecentTaskHistory(cwd));\n const lite = /^(1|true|yes|on)$/i.test(envValue(process.env, \"TANYA_LITE_PROMPT\").trim());\n if (lite) {\n try {\n await buildRepoMap(cwd, { writeCache: true });\n } catch {\n // Repo-map diagnostics are best-effort for debug-prompt.\n }\n }\n const systemPrompt = buildSystemPrompt(cwd, runContext, historyBlock, task, {\n lite,\n });\n const skillPacks = loadPromptSkillPacks(cwd, runContext, task);\n const sections = flagStrings(args, \"section\");\n const output = selectPromptSections(systemPrompt, sections);\n\n process.stdout.write(\"=== SYSTEM PROMPT ===\\n\\n\");\n process.stdout.write(output);\n process.stdout.write(\"\\n\\n=== END SYSTEM PROMPT ===\\n\");\n if (sections.length === 0) {\n process.stdout.write(`\\nLength: ${systemPrompt.length} chars (~${Math.ceil(systemPrompt.length / 4)} tokens)\\n`);\n process.stdout.write(`${formatSkillPackSummary(skillPacks)}\\n`);\n const map = readRepoMap(cwd);\n if (map) {\n const diagnostics = repoMapDiagnostics(map);\n process.stdout.write(`Repo map: ${diagnostics.fileCount} files, ${diagnostics.symbolCount} symbols, ${diagnostics.importCount} imports, ~${diagnostics.estimatedTokens} tokens, parsers tree-sitter=${diagnostics.parserCounts[\"tree-sitter\"]} ripgrep=${diagnostics.parserCounts.ripgrep} path=${diagnostics.parserCounts.path}\\n`);\n }\n }\n return;\n }\n\n const provider = createProvider(config);\n\n if (args.command === \"ask\") {\n const prompt = readPrompt(args);\n if (!prompt) throw new Error(\"Missing prompt.\");\n await askOnce(provider, prompt);\n return;\n }\n\n if (args.command === \"review\") {\n const cwd = resolve(flagString(args, \"cwd\") ?? process.cwd());\n const task = readPrompt(args);\n if (!task) throw new Error(\"Missing task description. Usage: tanya review --cwd <path> \\\"task description\\\"\");\n\n const { execFileSync } = await import(\"node:child_process\");\n let diff = \"\";\n try {\n diff = execFileSync(\"git\", [\"diff\", \"HEAD\"], { cwd, encoding: \"utf8\" });\n if (!diff.trim()) {\n diff = execFileSync(\"git\", [\"show\", \"--format=\", \"HEAD\"], { cwd, encoding: \"utf8\" });\n }\n } catch {\n throw new Error(\"tanya review requires a git repository with changes.\");\n }\n\n process.stdout.write(\"Reviewing changes...\\n\\n\");\n const review = await reviewChanges(provider, task, diff);\n process.stdout.write(`${review}\\n`);\n return;\n }\n\n const cwd = resolve(flagString(args, \"cwd\") ?? process.cwd());\n const routing = buildRoutingOptions(config, cwd);\n const json = hasFlag(args, \"json\");\n if (shouldUseInkChat(args, json)) {\n const { startInkChat } = await import(\"./ui/ink/runInkChat\");\n await startInkChat({\n provider,\n cwd,\n ...(routing ? { routing } : {}),\n resumeSessionId: flagString(args, \"resume\"),\n continueSession: hasFlag(args, \"continue\"),\n });\n return;\n }\n const sink = createCosmoChatFinalizeSink(json ? createJsonlSink() : createHumanSink(process.stdout, { liveStatus: args.command === \"chat\" }));\n let runPromptTokens = 0;\n let runCompletionTokens = 0;\n const trackingSink: EventSink = async (event) => {\n if (event.type === \"final\" && event.metrics) {\n runPromptTokens += event.metrics.promptTokens ?? 0;\n runCompletionTokens += event.metrics.completionTokens ?? 0;\n }\n return sink(event);\n };\n\n if (args.command === \"run\") {\n const prompt = readPrompt(args);\n const resumeRunID = flagString(args, \"resume\");\n if (!prompt && !resumeRunID) throw new Error(\"Missing prompt.\");\n const runContext = prompt\n ? await buildRunContextForCli(args, cwd, prompt, config.obsidianVault)\n : undefined;\n const maxTurns = phaseAwareMaxTurns(runContext, prompt, flagNumber(args, \"max-turns\"));\n const repairAttempts = flagNumber(args, \"repair-attempts\");\n const maxRetries = flagNumber(args, \"retries\") ?? 0;\n const skipPostCheck = hasFlag(args, \"no-post-check\");\n const usePlan = hasFlag(args, \"plan\");\n const planAndDispatch = hasFlag(args, \"plan-and-dispatch\") || Boolean(flagString(args, \"resume\"));\n const tdd = hasFlag(args, \"tdd\");\n const testCmd = flagString(args, \"test-cmd\");\n const autoFixVerify = hasFlag(args, \"auto-fix-verify\");\n const autoFixWarns = hasFlag(args, \"auto-fix-warns\");\n const maxFixIterations = flagNumber(args, \"max-fix-iterations\") ?? 5;\n\n if (planAndDispatch) {\n if (!prompt && !resumeRunID) throw new Error(\"Missing prompt.\");\n const maxSubtasks = flagNumber(args, \"max-subtasks\") ?? 12;\n const dispatchMode = (flagString(args, \"dispatch-mode\") ?? \"sequential\") as DispatchMode;\n const { expected_report: _expectedReport, ...runContextWithoutExpectedReport } = runContext ?? {};\n const subtaskRunContext: TanyaRunContext | undefined = runContext\n ? {\n ...runContextWithoutExpectedReport,\n task: { ...(runContext.task ?? {}), kind: \"dispatch-subtask\" },\n }\n : undefined;\n\n await runPlanAndDispatch({\n cwd,\n prompt,\n maxSubtasks,\n mode: dispatchMode,\n tdd,\n autoFixVerify,\n autoFixWarns,\n maxFixIterations,\n readVerifyFailures: readVerifyFailuresFromStdin,\n ...(testCmd ? { testCmd } : {}),\n ...(resumeRunID ? { resumeRunID } : {}),\n sink: trackingSink,\n runTurn: async (turnPrompt, meta) => {\n if (meta.phase === \"plan\") {\n let text = \"\";\n for await (const delta of provider.streamChat({ messages: [{ role: \"user\", content: turnPrompt }], tools: [], temperature: 0, topP: 0.2 })) {\n if (delta.usage) {\n runPromptTokens += delta.usage.promptTokens;\n runCompletionTokens += delta.usage.completionTokens;\n }\n if (delta.content) text += delta.content;\n }\n return text;\n }\n\n const result = await runAgent({\n provider,\n prompt: turnPrompt,\n cwd,\n sink: trackingSink,\n ...(meta.phase === \"complete\" && runContext ? { runContext } : {}),\n ...(meta.phase === \"subtask\" && subtaskRunContext ? { runContext: subtaskRunContext } : {}),\n ...(maxTurns ? { maxTurns } : {}),\n ...(repairAttempts !== undefined ? { repairAttempts } : {}),\n });\n\n if (meta.phase === \"complete\" && !skipPostCheck) {\n const postBlockers = await detectPostRunBlockers(cwd, result.manifest);\n if (postBlockers.length > 0) {\n await trackingSink({\n type: \"status\",\n message: `Post-run checks found ${postBlockers.length} issue(s): ${postBlockers.join(\"; \")}`,\n });\n }\n }\n return result.message;\n },\n });\n\n if (runPromptTokens > 0 || runCompletionTokens > 0) {\n const costStr = estimateRunCost({\n provider: config.provider,\n model: config.model,\n promptTokens: runPromptTokens,\n completionTokens: runCompletionTokens,\n });\n process.stderr.write(\n `[tanya] Tokens: ${runPromptTokens.toLocaleString()} in / ${runCompletionTokens.toLocaleString()} out ${costStr}\\n`,\n );\n }\n return;\n }\n\n let planBlock = \"\";\n\n if (usePlan) {\n process.stderr.write(\"[tanya] Building execution plan with reasoner...\\n\");\n const reasonerConfig = loadConfig(cwd);\n const reasonerProvider = new OpenAiCompatibleProvider({\n id: \"deepseek-reasoner\",\n apiKey: reasonerConfig.apiKey,\n baseUrl: reasonerConfig.baseUrl,\n model: \"deepseek-reasoner\",\n timeoutMs: 180_000,\n temperature: 0,\n topP: 0.2,\n });\n const exportMap = buildExportMap(cwd);\n try {\n const plan = await buildExecutionPlan(reasonerProvider, prompt, exportMap);\n if (plan) {\n planBlock = `## Execution plan (pre-approved, follow it)\\n${plan}`;\n process.stderr.write(\"[tanya] Plan ready.\\n\");\n }\n } catch {\n process.stderr.write(\"[tanya] Planner failed, continuing without plan.\\n\");\n }\n }\n\n let lastResult: RunAgentResult | null = null;\n let previousPostBlockers: string[] = [];\n let attempt = 0;\n let stashedAttemptResult: RunAgentResult | null = null;\n let stashedAttemptLabel: string | null = null;\n // --no-retry-stash: skip stash-and-clean between retries so the agent sees\n // its previous attempt's files and can fix them incrementally instead of\n // rewriting from scratch. Use for tasks where partial progress is valuable\n // (e.g. test-writing where the agent's repeated rewrites burn context). The\n // default (stash) is best for tasks where a wrong-direction first attempt\n // should be discarded.\n const noRetryStash = hasFlag(args, \"no-retry-stash\");\n\n while (attempt <= maxRetries) {\n if (!noRetryStash && attempt > 0 && lastResult && lastResult.manifest.changedFiles.length > 0) {\n try {\n const { execFileSync } = await import(\"node:child_process\");\n const label = `tanya-retry-${attempt}`;\n // Exclude `.tania/` from the stash: those are runner-internal artifacts\n // (history.json, runs/*, memory/*) regenerated each attempt, and\n // including them in the stash causes pop conflicts on retry-recovery.\n execFileSync(\n \"git\",\n [\"stash\", \"push\", \"--include-untracked\", \"-m\", label, \"--\", \":(exclude).tania\", \":!**/.tania/**\"],\n { cwd, stdio: \"ignore\" },\n );\n stashedAttemptResult = lastResult;\n stashedAttemptLabel = label;\n process.stderr.write(\"[tanya] Stashed previous attempt changes. Retrying from clean state.\\n\");\n } catch {\n // Not a git repo or stash failed; retry context still helps.\n }\n }\n const retryContext = attempt > 0 && lastResult\n ? buildRetryContext(lastResult.manifest, attempt, previousPostBlockers)\n : \"\";\n const attemptPrompt = [planBlock, retryContext, \"Original task:\", prompt]\n .filter(Boolean)\n .join(\"\\n\\n---\\n\");\n\n lastResult = await runAgent({\n provider,\n prompt: attemptPrompt,\n cwd,\n sink: trackingSink,\n ...(runContext ? { runContext } : {}),\n ...(maxTurns ? { maxTurns } : {}),\n ...(repairAttempts !== undefined ? { repairAttempts } : {}),\n retryAttempt: attempt,\n ...(routing ? { routing } : {}),\n });\n\n const postBlockers = skipPostCheck\n ? []\n : await detectPostRunBlockers(cwd, lastResult.manifest);\n if (postBlockers.length > 0) {\n process.stderr.write(\n `[tanya] Post-run checks found ${postBlockers.length} issue(s) not reported by model:\\n${postBlockers.map((blocker) => ` - ${blocker}`).join(\"\\n\")}\\n`,\n );\n }\n previousPostBlockers = postBlockers;\n\n const failed =\n lastResult.manifest.blockers.length > 0 ||\n postBlockers.length > 0 ||\n (lastResult.manifest.validation !== undefined && !lastResult.manifest.validation.passed);\n\n if (!failed || attempt >= maxRetries) break;\n\n attempt += 1;\n process.stderr.write(\n `\\n[tanya] Attempt ${attempt} had blockers. Starting attempt ${attempt + 1} of ${maxRetries + 1}...\\n`,\n );\n }\n\n if (\n stashedAttemptResult &&\n stashedAttemptLabel &&\n lastResult &&\n lastResult.manifest.changedFiles.length === 0 &&\n stashedAttemptResult.manifest.changedFiles.length > 0\n ) {\n const { execFileSync } = await import(\"node:child_process\");\n let stashList = \"\";\n try { stashList = execFileSync(\"git\", [\"stash\", \"list\"], { cwd, encoding: \"utf8\" }); } catch { stashList = \"\"; }\n if (!stashList.includes(stashedAttemptLabel)) {\n process.stderr.write(`[tanya] Stashed attempt (${stashedAttemptLabel}) was already consumed; nothing to recover.\\n`);\n } else {\n try {\n execFileSync(\"git\", [\"stash\", \"pop\"], { cwd, stdio: \"pipe\" });\n process.stderr.write(\n `[tanya] Final attempt produced 0 file changes; restoring stashed attempt (${stashedAttemptResult.manifest.changedFiles.length} files) so the work isn't lost.\\n`,\n );\n lastResult = stashedAttemptResult;\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n if (/conflict|merge|CONFLICT/i.test(msg)) {\n process.stderr.write(`[tanya] Stash pop conflicted with current tree; aborting pop and keeping current attempt. Conflict: ${msg.slice(0, 240)}\\n`);\n try { execFileSync(\"git\", [\"checkout\", \".\"], { cwd, stdio: \"ignore\" }); } catch {}\n } else {\n process.stderr.write(`[tanya] Could not pop stash to recover previous attempt's work: ${msg.slice(0, 240)}\\n`);\n }\n }\n }\n }\n\n if (runPromptTokens > 0 || runCompletionTokens > 0) {\n const costStr = estimateRunCost({\n provider: config.provider,\n model: config.model,\n promptTokens: runPromptTokens,\n completionTokens: runCompletionTokens,\n }).display;\n process.stderr.write(\n `[tanya] Tokens: ${runPromptTokens.toLocaleString()} in / ${runCompletionTokens.toLocaleString()} out ${costStr}\\n`,\n );\n }\n\n if (hasFlag(args, \"review\") && lastResult) {\n let diff = \"\";\n try {\n const { execFileSync } = await import(\"node:child_process\");\n diff = execFileSync(\"git\", [\"diff\", \"HEAD\"], { cwd, encoding: \"utf8\" });\n if (!diff.trim() && lastResult.manifest.git.head) {\n diff = execFileSync(\"git\", [\"show\", \"--format=\", \"HEAD\"], { cwd, encoding: \"utf8\" });\n }\n } catch {\n // No git repository or diff unavailable; skip optional auto-review.\n }\n\n if (diff.trim()) {\n process.stdout.write(\"\\n--- Auto-review ---\\n\");\n const review = await reviewChanges(provider, prompt, diff);\n process.stdout.write(`${review}\\n`);\n }\n }\n return;\n }\n\n await startInteractiveChat({\n provider,\n cwd,\n sink,\n ...(routing ? { routing } : {}),\n resumeSessionId: flagString(args, \"resume\"),\n continueSession: hasFlag(args, \"continue\"),\n });\n}\n\nmain().catch((err) => {\n const message = err instanceof Error ? err.message : String(err);\n console.error(`Tanya error: ${message}`);\n process.exitCode = 1;\n});\n","import { existsSync, readFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { parse } from \"dotenv\";\nimport { envValue, numberEnvValue } from \"./envCompat\";\nimport { resolveProviderAdapter } from \"../providers/adapters\";\n\nexport interface TanyaConfig {\n provider: string;\n profile: \"chat\" | \"reasoner\";\n apiKey: string;\n baseUrl: string;\n model: string;\n temperature: number;\n topP: number;\n timeoutMs: number;\n obsidianVault?: string;\n}\n\nfunction loadDotEnv(cwd: string): Record<string, string> {\n const envPath = join(cwd, \".env\");\n if (!existsSync(envPath)) return {};\n return parse(readFileSync(envPath, \"utf8\"));\n}\n\nexport function loadConfig(cwd = process.cwd()): TanyaConfig {\n const local = loadDotEnv(cwd);\n const profile = envValue(local, \"TANYA_PROFILE\") === \"reasoner\" ? \"reasoner\" : \"chat\";\n const requestedProvider = envValue(local, \"TANYA_PROVIDER\").trim();\n const requestedBaseUrl = envValue(local, \"TANYA_BASE_URL\").trim();\n const providerSeed = requestedProvider || (requestedBaseUrl ? \"\" : \"deepseek\");\n const adapter = resolveProviderAdapter({\n provider: providerSeed,\n baseUrl: requestedBaseUrl,\n });\n const provider = providerSeed || adapter.id;\n\n const apiKey =\n provider === \"deepseek\"\n ? envValue(local, \"DEEPSEEK_API_KEY\") || envValue(local, \"TANYA_API_KEY\")\n : envValue(local, \"TANYA_API_KEY\");\n\n const baseUrl =\n provider === \"deepseek\"\n ? envValue(local, \"DEEPSEEK_BASE_URL\") || envValue(local, \"TANYA_BASE_URL\") || adapter.defaultBaseUrl || \"https://api.deepseek.com\"\n : envValue(local, \"TANYA_BASE_URL\") || adapter.defaultBaseUrl || \"\";\n\n const profileModelDefault = profile === \"reasoner\" && adapter.id === \"deepseek\"\n ? \"deepseek-reasoner\"\n : adapter.defaultModel ?? \"deepseek-v4-pro\";\n const model = envValue(local, \"TANYA_MODEL\") || profileModelDefault;\n\n const profileTimeoutDefault = profile === \"reasoner\" ? 180_000 : 90_000;\n const timeoutMs = numberEnvValue(local, \"TANYA_TIMEOUT_MS\", profileTimeoutDefault);\n\n const config: TanyaConfig = {\n provider,\n profile,\n apiKey,\n baseUrl: baseUrl.replace(/\\/$/, \"\"),\n model,\n temperature: numberEnvValue(local, \"TANYA_TEMPERATURE\", 0),\n topP: numberEnvValue(local, \"TANYA_TOP_P\", 0.2),\n timeoutMs,\n ...(envValue(local, \"TANYA_OBSIDIAN_VAULT\") ? { obsidianVault: envValue(local, \"TANYA_OBSIDIAN_VAULT\") } : {}),\n };\n\n if (!config.apiKey.trim()) {\n throw new Error(\"TANYA_API_KEY is not set. Add it to your .env file or environment.\");\n }\n\n return config;\n}\n","import { copyFileSync, cpSync, existsSync, mkdirSync, statSync, writeFileSync } from \"node:fs\";\nimport { basename, dirname, isAbsolute, relative, resolve } from \"node:path\";\nimport type { TanyaRunContext } from \"./runContext\";\n\nexport type MaterializeCliArtifactsInput = {\n cwd: string;\n root?: string | undefined;\n artifacts: string[];\n contextPaths?: string[] | undefined;\n artifactOutputRoot?: string | undefined;\n keepContext?: boolean | undefined;\n baseContext?: TanyaRunContext | undefined;\n};\n\nfunction normalizePath(path: string): string {\n return path.trim().replace(/\\\\/g, \"/\").replace(/^\"|\"$/g, \"\");\n}\n\nfunction unique(values: string[]): string[] {\n return [...new Set(values.map(normalizePath).filter(Boolean))];\n}\n\nfunction sourceLabel(root: string | undefined, artifact: string): string {\n const clean = normalizePath(artifact);\n if (!root || isAbsolute(clean)) return clean;\n const rootBase = basename(resolve(root));\n return rootBase === \"artifacts\" ? `artifacts/${clean}` : clean;\n}\n\nfunction relativeMaterializedPath(root: string | undefined, artifact: string, source: string): string {\n const clean = normalizePath(artifact);\n if (root && !isAbsolute(clean)) return clean;\n if (root) {\n const rel = normalizePath(relative(resolve(root), source));\n if (rel && !rel.startsWith(\"../\") && rel !== \"..\") return rel;\n }\n return basename(source);\n}\n\nexport function materializeCliArtifacts(input: MaterializeCliArtifactsInput): TanyaRunContext | undefined {\n const artifactInputs = unique(input.artifacts);\n const contextInputs = unique(input.contextPaths ?? []);\n if (artifactInputs.length === 0 && contextInputs.length === 0 && !input.artifactOutputRoot) return input.baseContext;\n\n const cwd = resolve(input.cwd);\n const root = input.root ? resolve(input.root) : undefined;\n const targetRoot = resolve(cwd, \".tania\", \"artifacts\");\n const contextTargetRoot = resolve(cwd, \".tania\", \"context\");\n const materialized: NonNullable<TanyaRunContext[\"artifacts\"]> = [];\n const contextFiles: NonNullable<TanyaRunContext[\"contextFiles\"]> = [];\n\n for (const artifact of artifactInputs) {\n const source = isAbsolute(artifact)\n ? resolve(artifact)\n : resolve(root ?? cwd, artifact);\n const rel = relativeMaterializedPath(root, artifact, source);\n const target = resolve(targetRoot, rel);\n const localPath = `.tania/artifacts/${normalizePath(rel)}`;\n const label = sourceLabel(root, artifact);\n\n if (!target.startsWith(`${targetRoot}/`) || !existsSync(source)) {\n materialized.push({\n path: localPath,\n sourcePath: label,\n role: \"source-pattern\",\n status: \"missing\",\n reason: \"Artifact was requested by the caller but was not found.\",\n });\n continue;\n }\n\n const sourceStat = statSync(source);\n if (sourceStat.isDirectory()) {\n mkdirSync(target, { recursive: true });\n cpSync(source, target, { recursive: true, force: true });\n } else {\n mkdirSync(dirname(target), { recursive: true });\n copyFileSync(source, target);\n }\n materialized.push({\n path: localPath,\n sourcePath: label,\n role: \"source-pattern\",\n status: \"available\",\n reason: \"Materialized into this workspace from a caller-provided artifact input.\",\n });\n }\n\n if (materialized.some((artifact) => artifact.status === \"available\")) {\n mkdirSync(targetRoot, { recursive: true });\n writeFileSync(\n resolve(targetRoot, \"manifest.json\"),\n JSON.stringify({ generatedAt: new Date().toISOString(), artifacts: materialized }, null, 2),\n \"utf8\",\n );\n }\n\n for (const contextPath of contextInputs) {\n const source = resolve(contextPath);\n const rel = normalizePath(relative(dirname(source), source)) || basename(source);\n const parentLabel = basename(dirname(source));\n const targetRel = parentLabel ? `${parentLabel}/${basename(source)}` : rel;\n const target = resolve(contextTargetRoot, targetRel);\n const localPath = `.tania/context/${normalizePath(targetRel)}`;\n\n if (!target.startsWith(`${contextTargetRoot}/`) || !existsSync(source)) {\n contextFiles.push({\n path: localPath,\n sourcePath: contextPath,\n role: \"caller-context\",\n status: \"missing\",\n reason: \"Context file was requested by the caller but was not found.\",\n });\n continue;\n }\n\n mkdirSync(dirname(target), { recursive: true });\n copyFileSync(source, target);\n contextFiles.push({\n path: localPath,\n sourcePath: contextPath,\n role: \"caller-context\",\n status: \"available\",\n reason: \"Materialized into this workspace from a caller-provided context input.\",\n });\n }\n\n if (contextFiles.some((contextFile) => contextFile.status === \"available\")) {\n mkdirSync(contextTargetRoot, { recursive: true });\n writeFileSync(\n resolve(contextTargetRoot, \"manifest.json\"),\n JSON.stringify({ generatedAt: new Date().toISOString(), contextFiles }, null, 2),\n \"utf8\",\n );\n }\n\n const artifactOutputRoot = input.artifactOutputRoot ? resolve(input.artifactOutputRoot) : undefined;\n\n return {\n ...(input.baseContext ?? {}),\n artifacts: [...(input.baseContext?.artifacts ?? []), ...materialized],\n contextFiles: [...(input.baseContext?.contextFiles ?? []), ...contextFiles],\n instructions: [\n ...(input.baseContext?.instructions ?? []),\n ...(materialized.length > 0 ? [\n \"Caller artifacts were provided through Tanya's artifact input contract and materialized under .tania/artifacts.\",\n \"Read relevant materialized artifact paths before implementing related code.\",\n ] : []),\n ...(contextFiles.length > 0 ? [\n \"Caller context files were materialized under .tania/context.\",\n \"Read relevant materialized context paths before implementing safety, brand, architecture, or API contract requirements.\",\n ] : []),\n ...(artifactOutputRoot ? [\n \"If you create a reusable artifact, write it inside .tania/artifact-output using the intended artifact-relative path and mention it as Artifact created.\",\n ] : []),\n \"When reporting artifact reuse, use the artifact sourcePath label when available.\",\n ],\n expected_report: {\n ...(input.baseContext?.expected_report ?? {}),\n artifact_reuse: true,\n },\n metadata: {\n ...(input.baseContext?.metadata ?? {}),\n ...(artifactOutputRoot ? { artifactOutputRoot } : {}),\n tanyaMaterializedContext: true,\n keepMaterializedContext: input.keepContext === true,\n },\n };\n}\n","import type { EventSink, TanyaEvent } from \"./types\";\n\nconst knownEventTypes = new Set([\n \"status\",\n \"message_start\",\n \"message_delta\",\n \"message_end\",\n \"reasoning_chunk\",\n \"reasoning_truncated\",\n \"tool_call\",\n \"tool_progress\",\n \"tool_cancel_requested\",\n \"tool_cancelled\",\n \"permission_request\",\n \"permission_decision\",\n \"tool_result\",\n \"tool_call_parse_warning\",\n \"schema_flatten_warning\",\n \"provider_throttle\",\n \"provider.raw\",\n \"model_routed\",\n \"escalation_event\",\n \"compact_event\",\n \"prompt_budget_exceeded\",\n \"subtask_started\",\n \"subtask_completed\",\n \"subtask_start\",\n \"subtask_done\",\n \"command_invoked\",\n \"final\",\n \"error\",\n]);\n\nfunction isKnownEvent(event: unknown): event is TanyaEvent {\n return Boolean(\n event &&\n typeof event === \"object\" &&\n typeof (event as { type?: unknown }).type === \"string\" &&\n knownEventTypes.has((event as { type: string }).type),\n );\n}\n\nexport function createJsonlSink(stream: NodeJS.WritableStream = process.stdout): EventSink {\n return (event: TanyaEvent) => {\n if (!isKnownEvent(event)) return;\n stream.write(`${JSON.stringify(event)}\\n`);\n };\n}\n","export type ReasoningSplit =\n | { type: \"content\"; text: string }\n | { type: \"reasoning\"; text: string };\n\nconst OPEN_TAG = \"<think>\";\nconst CLOSE_TAG = \"</think>\";\n\nexport class ThinkBlockSplitter {\n private mode: \"content\" | \"reasoning\" = \"content\";\n private buffer = \"\";\n\n push(text: string): ReasoningSplit[] {\n this.buffer += text;\n return this.drain(false);\n }\n\n flush(): ReasoningSplit[] {\n return this.drain(true);\n }\n\n private drain(flush: boolean): ReasoningSplit[] {\n const output: ReasoningSplit[] = [];\n while (this.buffer.length > 0) {\n if (this.mode === \"content\") {\n const open = this.buffer.indexOf(OPEN_TAG);\n if (open >= 0) {\n this.emit(output, \"content\", this.buffer.slice(0, open));\n this.buffer = this.buffer.slice(open + OPEN_TAG.length);\n this.mode = \"reasoning\";\n continue;\n }\n const keep = flush ? 0 : OPEN_TAG.length - 1;\n if (this.buffer.length <= keep) break;\n this.emit(output, \"content\", this.buffer.slice(0, this.buffer.length - keep));\n this.buffer = this.buffer.slice(this.buffer.length - keep);\n break;\n }\n\n const close = this.buffer.indexOf(CLOSE_TAG);\n if (close >= 0) {\n this.emit(output, \"reasoning\", this.buffer.slice(0, close));\n this.buffer = this.buffer.slice(close + CLOSE_TAG.length);\n this.mode = \"content\";\n continue;\n }\n const keep = flush ? 0 : CLOSE_TAG.length - 1;\n if (this.buffer.length <= keep) break;\n this.emit(output, \"reasoning\", this.buffer.slice(0, this.buffer.length - keep));\n this.buffer = this.buffer.slice(this.buffer.length - keep);\n break;\n }\n\n if (flush && this.buffer.length > 0) {\n this.emit(output, this.mode, this.buffer);\n this.buffer = \"\";\n }\n return output;\n }\n\n private emit(output: ReasoningSplit[], type: ReasoningSplit[\"type\"], text: string): void {\n if (text.length > 0) output.push({ type, text });\n }\n}\n\nexport function estimateReasoningTokens(text: string): number {\n return Math.ceil(text.length / 4);\n}\n","import type { ToolDefinition } from \"./types\";\n\nexport type SchemaFlattenWarning = {\n path: string;\n reason: string;\n tool?: string;\n};\n\nexport type SchemaFlattenResult<T> = {\n schema: T;\n warnings: SchemaFlattenWarning[];\n};\n\ntype JsonObject = Record<string, unknown>;\n\nexport function flattenJsonSchema<T>(schema: T): SchemaFlattenResult<T> {\n const warnings: SchemaFlattenWarning[] = [];\n const root = clone(schema);\n const flattened = flattenValue(root, root, \"#\", warnings, new Set()) as T;\n return { schema: flattened, warnings };\n}\n\nexport function flattenToolDefinition(tool: ToolDefinition): SchemaFlattenResult<ToolDefinition> {\n const result = flattenJsonSchema(tool.function.parameters);\n return {\n schema: {\n ...tool,\n function: {\n ...tool.function,\n parameters: result.schema,\n },\n },\n warnings: result.warnings.map((warning) => ({ ...warning, tool: tool.function.name })),\n };\n}\n\nexport function flattenToolDefinitions(tools: ToolDefinition[]): SchemaFlattenResult<ToolDefinition[]> {\n const flattened: ToolDefinition[] = [];\n const warnings: SchemaFlattenWarning[] = [];\n for (const tool of tools) {\n const result = flattenToolDefinition(tool);\n flattened.push(result.schema);\n warnings.push(...result.warnings);\n }\n return { schema: flattened, warnings };\n}\n\nfunction flattenValue(\n value: unknown,\n root: unknown,\n path: string,\n warnings: SchemaFlattenWarning[],\n seenRefs: Set<string>,\n): unknown {\n if (Array.isArray(value)) {\n return value.map((item, index) => flattenValue(item, root, `${path}/${index}`, warnings, seenRefs));\n }\n if (!isObject(value)) return value;\n\n const ref = typeof value.$ref === \"string\" ? value.$ref : null;\n if (ref) {\n const resolved = resolveLocalRef(root, ref);\n if (resolved === undefined) {\n warnings.push({ path, reason: `unresolved $ref ${ref}; leaving reference in place` });\n return value;\n }\n if (seenRefs.has(ref)) {\n warnings.push({ path, reason: `circular $ref ${ref}; leaving reference in place` });\n return value;\n }\n warnings.push({ path, reason: `inlined $ref ${ref}` });\n seenRefs.add(ref);\n const flattened = flattenValue(resolved, root, path, warnings, seenRefs);\n seenRefs.delete(ref);\n const { $ref: _ref, ...overrides } = value;\n return isObject(flattened)\n ? flattenObject({ ...flattened, ...overrides }, root, path, warnings, seenRefs)\n : flattened;\n }\n\n return flattenObject(value, root, path, warnings, seenRefs);\n}\n\nfunction flattenObject(\n object: JsonObject,\n root: unknown,\n path: string,\n warnings: SchemaFlattenWarning[],\n seenRefs: Set<string>,\n): JsonObject {\n const withoutDefs = stripDefinitions(object);\n if (Array.isArray(withoutDefs.oneOf)) {\n return flattenOneOf(withoutDefs, root, path, warnings, seenRefs);\n }\n\n const output: JsonObject = {};\n for (const [key, raw] of Object.entries(withoutDefs)) {\n output[key] = flattenValue(raw, root, `${path}/${escapePointer(key)}`, warnings, seenRefs);\n }\n return output;\n}\n\nfunction flattenOneOf(\n object: JsonObject,\n root: unknown,\n path: string,\n warnings: SchemaFlattenWarning[],\n seenRefs: Set<string>,\n): JsonObject {\n const variants = object.oneOf as unknown[];\n const flattenedVariants = variants\n .map((variant, index) => flattenValue(variant, root, `${path}/oneOf/${index}`, warnings, seenRefs))\n .filter(isObject);\n if (flattenedVariants.length === 0) {\n warnings.push({ path, reason: \"oneOf had no object variants; dropped oneOf\" });\n const { oneOf: _oneOf, ...rest } = object;\n return flattenObject(rest, root, path, warnings, seenRefs);\n }\n\n const commonType = commonScalar(flattenedVariants.map((variant) => variant.type));\n const commonProperties = commonObjectProperties(flattenedVariants);\n const commonRequired = commonRequiredFields(flattenedVariants);\n const { oneOf: _oneOf, ...rest } = object;\n warnings.push({ path, reason: `collapsed oneOf (${variants.length} variants) to common object shape` });\n\n return flattenObject({\n ...rest,\n ...(commonType ? { type: commonType } : {}),\n ...(Object.keys(commonProperties).length ? { properties: commonProperties } : {}),\n ...(commonRequired.length ? { required: commonRequired } : {}),\n }, root, path, warnings, seenRefs);\n}\n\nfunction commonObjectProperties(variants: JsonObject[]): JsonObject {\n const propertyMaps = variants\n .map((variant) => isObject(variant.properties) ? variant.properties : {});\n if (propertyMaps.length === 0) return {};\n const commonKeys = Object.keys(propertyMaps[0] ?? {})\n .filter((key) => propertyMaps.every((properties) => key in properties));\n const output: JsonObject = {};\n for (const key of commonKeys) output[key] = propertyMaps[0]?.[key];\n return output;\n}\n\nfunction commonRequiredFields(variants: JsonObject[]): string[] {\n const requiredLists = variants\n .map((variant) => Array.isArray(variant.required) ? variant.required.filter((item): item is string => typeof item === \"string\") : []);\n if (requiredLists.length === 0) return [];\n return requiredLists[0]?.filter((key) => requiredLists.every((list) => list.includes(key))) ?? [];\n}\n\nfunction commonScalar(values: unknown[]): string | null {\n const [first] = values;\n return typeof first === \"string\" && values.every((value) => value === first) ? first : null;\n}\n\nfunction resolveLocalRef(root: unknown, ref: string): unknown {\n if (!ref.startsWith(\"#/\")) return undefined;\n const parts = ref.slice(2).split(\"/\").map(unescapePointer);\n let current = root;\n for (const part of parts) {\n if (!isObject(current) && !Array.isArray(current)) return undefined;\n current = (current as Record<string, unknown>)[part];\n }\n return current;\n}\n\nfunction stripDefinitions(object: JsonObject): JsonObject {\n const { $defs: _defs, definitions: _definitions, ...rest } = object;\n return rest;\n}\n\nfunction clone<T>(value: T): T {\n return JSON.parse(JSON.stringify(value)) as T;\n}\n\nfunction isObject(value: unknown): value is JsonObject {\n return Boolean(value && typeof value === \"object\" && !Array.isArray(value));\n}\n\nfunction escapePointer(value: string): string {\n return value.replace(/~/g, \"~0\").replace(/\\//g, \"~1\");\n}\n\nfunction unescapePointer(value: string): string {\n return value.replace(/~1/g, \"/\").replace(/~0/g, \"~\");\n}\n","export type ProviderThrottleEvent = {\n provider: string;\n attempt: number;\n waitMs: number;\n};\n\nexport type ProviderRetryOptions = {\n provider: string;\n maxRetries?: number;\n maxWaitMs?: number;\n initialWaitMs?: number;\n concurrency?: number;\n sleep?: (ms: number) => Promise<void>;\n onThrottle?: (event: ProviderThrottleEvent) => void | Promise<void>;\n fetch: () => Promise<Response>;\n};\n\nconst DEFAULT_MAX_RETRIES = 3;\nconst DEFAULT_MAX_WAIT_MS = 30_000;\nconst DEFAULT_INITIAL_WAIT_MS = 500;\nconst DEFAULT_PROVIDER_CONCURRENCY = 4;\n\nconst semaphores = new Map<string, ProviderSemaphore>();\n\nexport function retryAfterMs(response: Response, now = Date.now()): number | null {\n const raw = response.headers.get(\"retry-after\");\n if (!raw) return null;\n const seconds = Number(raw);\n if (Number.isFinite(seconds) && seconds >= 0) return Math.max(0, seconds * 1000);\n const dateMs = Date.parse(raw);\n if (!Number.isNaN(dateMs)) return Math.max(dateMs - now, 0);\n return null;\n}\n\nexport function backoffMs(attempt: number, options: { initialWaitMs?: number; maxWaitMs?: number } = {}): number {\n const initial = options.initialWaitMs ?? DEFAULT_INITIAL_WAIT_MS;\n const max = options.maxWaitMs ?? DEFAULT_MAX_WAIT_MS;\n return Math.min(initial * 2 ** Math.max(0, attempt - 1), max);\n}\n\nexport function retryWaitMs(response: Response, attempt: number, options: { initialWaitMs?: number; maxWaitMs?: number } = {}): number | null {\n if (response.status === 429) {\n const retryAfter = retryAfterMs(response);\n if (retryAfter !== null) return Math.min(retryAfter, options.maxWaitMs ?? DEFAULT_MAX_WAIT_MS);\n }\n if ((response.status >= 500 && response.status <= 599) || response.status === 429) {\n return backoffMs(attempt, options);\n }\n return null;\n}\n\nexport async function fetchWithProviderRetry(options: ProviderRetryOptions): Promise<Response> {\n const semaphore = getProviderSemaphore(options.provider, options.concurrency ?? DEFAULT_PROVIDER_CONCURRENCY);\n return semaphore.run(() => fetchWithRetry(options));\n}\n\nexport function resetProviderRetryStateForTests(): void {\n semaphores.clear();\n}\n\nasync function fetchWithRetry(options: ProviderRetryOptions): Promise<Response> {\n const maxRetries = options.maxRetries ?? DEFAULT_MAX_RETRIES;\n const sleep = options.sleep ?? defaultSleep;\n let response: Response;\n\n for (let attempt = 0; attempt <= maxRetries; attempt += 1) {\n response = await options.fetch();\n const retryAttempt = attempt + 1;\n const waitOptions = {\n ...(options.initialWaitMs !== undefined ? { initialWaitMs: options.initialWaitMs } : {}),\n ...(options.maxWaitMs !== undefined ? { maxWaitMs: options.maxWaitMs } : {}),\n };\n const waitMs = attempt < maxRetries ? retryWaitMs(response, retryAttempt, waitOptions) : null;\n if (waitMs === null) return response;\n await options.onThrottle?.({ provider: options.provider, attempt: retryAttempt, waitMs });\n await sleep(waitMs);\n }\n\n return response!;\n}\n\nfunction getProviderSemaphore(provider: string, concurrency: number): ProviderSemaphore {\n const normalizedProvider = provider || \"unknown\";\n const existing = semaphores.get(normalizedProvider);\n if (existing && existing.limit === concurrency) return existing;\n const created = new ProviderSemaphore(Math.max(1, Math.floor(concurrency)));\n semaphores.set(normalizedProvider, created);\n return created;\n}\n\nfunction defaultSleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\nclass ProviderSemaphore {\n readonly limit: number;\n private active = 0;\n private readonly queue: Array<() => void> = [];\n\n constructor(limit: number) {\n this.limit = limit;\n }\n\n async run<T>(fn: () => Promise<T>): Promise<T> {\n await this.acquire();\n try {\n return await fn();\n } finally {\n this.release();\n }\n }\n\n private acquire(): Promise<void> {\n if (this.active < this.limit) {\n this.active += 1;\n return Promise.resolve();\n }\n return new Promise((resolve) => {\n this.queue.push(() => {\n this.active += 1;\n resolve();\n });\n });\n }\n\n private release(): void {\n this.active -= 1;\n const next = this.queue.shift();\n if (next) next();\n }\n}\n","import type { ChatMessage, ToolCall } from \"./types\";\n\nexport type NormalizationResult = {\n messages: ChatMessage[];\n warnings: string[];\n droppedOrphans: number;\n droppedDuplicates: number;\n filteredToolCalls: number;\n coercedNullContent: number;\n};\n\ntype ToolResultCandidate = {\n id: string;\n messageIndex: number;\n assistantIndex: number;\n};\n\nfunction toolCallId(call: ToolCall): string | null {\n return call.id.trim() ? call.id : null;\n}\n\nexport function normalizeMessages(messages: ChatMessage[]): NormalizationResult {\n const lastAssistantByToolCallId = new Map<string, number>();\n const toolResultCandidates: ToolResultCandidate[] = [];\n let droppedOrphans = 0;\n\n for (const [index, message] of messages.entries()) {\n if (message.role === \"assistant\") {\n for (const call of message.tool_calls ?? []) {\n const id = toolCallId(call);\n if (id) lastAssistantByToolCallId.set(id, index);\n }\n continue;\n }\n\n if (message.role !== \"tool\") continue;\n\n const id = message.tool_call_id?.trim();\n const assistantIndex = id ? lastAssistantByToolCallId.get(id) : undefined;\n if (!id || assistantIndex === undefined) {\n droppedOrphans += 1;\n continue;\n }\n\n toolResultCandidates.push({ id, messageIndex: index, assistantIndex });\n }\n\n const latestToolResultById = new Map<string, ToolResultCandidate>();\n for (const candidate of toolResultCandidates) {\n const existing = latestToolResultById.get(candidate.id);\n if (!existing || candidate.messageIndex > existing.messageIndex) {\n latestToolResultById.set(candidate.id, candidate);\n }\n }\n\n const keptToolMessageIndexes = new Set<number>();\n const answeredToolCalls = new Set<string>();\n for (const candidate of latestToolResultById.values()) {\n keptToolMessageIndexes.add(candidate.messageIndex);\n answeredToolCalls.add(`${candidate.assistantIndex}:${candidate.id}`);\n }\n\n const droppedDuplicates = toolResultCandidates.length - keptToolMessageIndexes.size;\n let filteredToolCalls = 0;\n let coercedNullContent = 0;\n const normalized: ChatMessage[] = [];\n\n for (const [index, message] of messages.entries()) {\n if (message.role === \"tool\") {\n if (keptToolMessageIndexes.has(index)) normalized.push(message);\n continue;\n }\n\n if (message.role !== \"assistant\" || !message.tool_calls?.length) {\n normalized.push(message);\n continue;\n }\n\n const toolCalls = message.tool_calls.filter((call) => {\n const id = toolCallId(call);\n return Boolean(id && answeredToolCalls.has(`${index}:${id}`));\n });\n filteredToolCalls += message.tool_calls.length - toolCalls.length;\n\n const content = message.content === null ? \"\" : message.content;\n if (message.content === null) coercedNullContent += 1;\n\n const normalizedMessage: ChatMessage = { ...message, content };\n if (toolCalls.length > 0) {\n normalizedMessage.tool_calls = toolCalls;\n } else {\n delete normalizedMessage.tool_calls;\n }\n normalized.push(normalizedMessage);\n }\n\n const warnings = [\n droppedOrphans > 0 ? `dropped orphan tool messages: ${droppedOrphans}` : null,\n droppedDuplicates > 0 ? `dropped duplicate tool results: ${droppedDuplicates}` : null,\n filteredToolCalls > 0 ? `filtered unanswered tool calls: ${filteredToolCalls}` : null,\n coercedNullContent > 0 ? `coerced null assistant content: ${coercedNullContent}` : null,\n ].filter((message): message is string => Boolean(message));\n\n return {\n messages: normalized,\n warnings,\n droppedOrphans,\n droppedDuplicates,\n filteredToolCalls,\n coercedNullContent,\n };\n}\n","import { ContextWindowExceededError, type ChatDelta, type ChatMessage, type ChatProvider, type ChatRequest, type ToolCall } from \"./types\";\nimport { envValue } from \"../config/envCompat\";\nimport { estimateReasoningTokens, ThinkBlockSplitter } from \"../agent/reasoning\";\nimport { resolveProviderAdapter, type ChatResponse, type ProviderAdapter, type ProviderRequest } from \"./adapters\";\nimport { flattenToolDefinitions, type SchemaFlattenWarning } from \"./schemaFlatten\";\nimport { fetchWithProviderRetry } from \"./retry\";\nimport { normalizeMessages } from \"./messageNormalize\";\n\nexport interface OpenAiCompatibleProviderOptions {\n id: string;\n apiKey: string;\n baseUrl: string;\n model: string;\n timeoutMs?: number;\n temperature?: number;\n topP?: number;\n contextWindow?: number;\n}\n\ninterface StreamChoice {\n delta?: {\n content?: string | null;\n reasoning_content?: string | null;\n tool_calls?: Array<{\n index?: number;\n id?: string;\n type?: \"function\";\n function?: {\n name?: string;\n arguments?: string;\n };\n }>;\n };\n finish_reason?: string | null;\n}\n\ninterface StreamChunk {\n choices?: StreamChoice[];\n usage?: {\n prompt_tokens?: number;\n completion_tokens?: number;\n reasoning_tokens?: number;\n completion_tokens_details?: {\n reasoning_tokens?: number;\n };\n };\n}\n\nconst CONTEXT_WINDOW_ERROR_PATTERNS = [\n /context_length_exceeded/i,\n /maximum context length/i,\n /tokens?\\s+exceeds?/i,\n /too long/i,\n];\n\nconst deprecatedDeepSeekModels = new Set([\"deepseek-chat\", \"deepseek-reasoner\"]);\nconst warnedDeprecatedModels = new Set<string>();\n\nfunction isContextWindowExceededResponse(status: number, detail: string): boolean {\n if (status === 413) return true;\n if (status >= 500) return false;\n return CONTEXT_WINDOW_ERROR_PATTERNS.some((pattern) => pattern.test(detail));\n}\n\nfunction providerConcurrency(): number {\n const raw = Number(envValue({}, \"TANYA_PROVIDER_CONCURRENCY\"));\n return Number.isFinite(raw) && raw > 0 ? Math.floor(raw) : 4;\n}\n\nfunction warnDeprecatedDeepSeekModel(providerId: string, model: string): void {\n if (providerId !== \"deepseek\") return;\n if (!deprecatedDeepSeekModels.has(model)) return;\n if (warnedDeprecatedModels.has(model)) return;\n if (envValue({}, \"TANYA_SUPPRESS_DEPRECATION\") === \"1\") return;\n\n warnedDeprecatedModels.add(model);\n process.stderr.write([\n `[tanya] DeepSeek model \"${model}\" is a V4-Flash compatibility alias and is scheduled for deprecation by DeepSeek on 2026-07-24.`,\n \"Tanya will migrate to V4 thinking-mode config in a future release (tracked as M13).\",\n \"Until then, you can keep using the legacy name with no behavior change.\",\n \"See docs/providers.md#deepseek-v4-deprecation for the migration story.\",\n \"Suppress this warning with TANYA_SUPPRESS_DEPRECATION=1 (or legacy TANIA_SUPPRESS_DEPRECATION=1).\",\n \"\",\n ].join(\"\\n\"));\n}\n\nexport function messagesForAdapter(messages: ChatMessage[], roundTripReasoning: boolean): ChatMessage[] {\n return messages.map((message) => {\n const carryReasoning =\n roundTripReasoning &&\n message.role === \"assistant\" &&\n typeof message.reasoning_content === \"string\" &&\n message.reasoning_content.length > 0;\n\n const base = carryReasoning ? message : (() => {\n const { reasoning_content: _reasoningContent, ...rest } = message;\n return rest;\n })();\n\n // DeepSeek rejects assistant messages where content is null and tool_calls\n // is empty/missing, even when reasoning_content is present.\n if (\n roundTripReasoning &&\n base.role === \"assistant\" &&\n (base.content === null || base.content === undefined) &&\n (!base.tool_calls || base.tool_calls.length === 0)\n ) {\n return { ...base, content: \"\" };\n }\n\n return base;\n });\n}\n\nexport class OpenAiCompatibleProvider implements ChatProvider {\n readonly id: string;\n readonly model: string;\n readonly contextWindow: number;\n readonly reasoning: boolean;\n readonly roundTripReasoning: boolean;\n private readonly apiKey: string;\n private readonly baseUrl: string;\n private readonly timeoutMs: number;\n private readonly temperature: number;\n private readonly topP: number;\n private readonly adapter: ProviderAdapter;\n\n constructor(options: OpenAiCompatibleProviderOptions) {\n this.adapter = resolveProviderAdapter({ provider: options.id, baseUrl: options.baseUrl });\n this.id = options.id;\n this.apiKey = options.apiKey;\n this.baseUrl = (options.baseUrl || this.adapter.defaultBaseUrl || \"\").replace(/\\/$/, \"\");\n this.model = options.model || this.adapter.defaultModel || \"\";\n warnDeprecatedDeepSeekModel(this.adapter.id, this.model);\n this.contextWindow = options.contextWindow ?? this.adapter.capabilities.contextWindow;\n this.reasoning = reasoningEnabled(this.adapter, this.model);\n this.roundTripReasoning = this.adapter.capabilities.roundTripReasoning === true;\n const envTimeout = parseInt(envValue({}, \"TANYA_TIMEOUT_MS\"), 10);\n const envTimeoutMs = Number.isFinite(envTimeout) && envTimeout > 0 ? envTimeout : null;\n this.timeoutMs = envTimeoutMs ?? options.timeoutMs ?? 90_000;\n this.temperature = options.temperature ?? 0;\n this.topP = options.topP ?? 0.2;\n }\n\n async *streamChat(input: ChatRequest): AsyncGenerator<ChatDelta> {\n if (!this.apiKey) {\n throw new Error(`Missing API key for provider \"${this.id}\".`);\n }\n\n const controller = new AbortController();\n let timeout: ReturnType<typeof setTimeout> | null = null;\n const resetTimeout = () => {\n if (timeout) clearTimeout(timeout);\n timeout = setTimeout(() => controller.abort(), this.timeoutMs);\n };\n\n const normalizedMessages = normalizeMessages(input.messages);\n if (normalizedMessages.warnings.length > 0 && envValue({}, \"TANYA_DEBUG\")) {\n console.debug(`[tanya] Provider message normalization: ${normalizedMessages.warnings.join(\"; \")}`);\n }\n\n const request: ProviderRequest = {\n model: this.model,\n messages: messagesForAdapter(normalizedMessages.messages, this.roundTripReasoning),\n temperature: input.temperature ?? this.temperature,\n top_p: input.topP ?? this.topP,\n max_tokens: input.maxTokens ?? 8192,\n stream: true,\n };\n const schemaWarnings: SchemaFlattenWarning[] = [];\n if (input.tools?.length) {\n if (this.adapter.capabilities.flattenSchemas) {\n const flattened = flattenToolDefinitions(input.tools);\n request.tools = flattened.schema;\n schemaWarnings.push(...flattened.warnings);\n } else {\n request.tools = input.tools;\n }\n request.tool_choice = \"auto\";\n }\n const requestBody = JSON.stringify(this.adapter.preRequest ? this.adapter.preRequest(request) : request);\n\n resetTimeout();\n const retryOptions = {\n provider: this.adapter.id,\n concurrency: providerConcurrency(),\n fetch: () => {\n resetTimeout();\n return fetch(`${this.baseUrl}/chat/completions`, {\n method: \"POST\",\n signal: controller.signal,\n headers: {\n Authorization: `Bearer ${this.apiKey}`,\n \"Content-Type\": \"application/json\",\n },\n body: requestBody,\n }).catch((error) => {\n if (controller.signal.aborted) {\n throw new Error(`Provider ${this.id} timed out before streaming a response.`);\n }\n throw error;\n });\n },\n ...(input.onProviderThrottle ? { onThrottle: input.onProviderThrottle } : {}),\n };\n const response = await fetchWithProviderRetry(retryOptions);\n\n if (!response.ok || !response.body) {\n if (timeout) clearTimeout(timeout);\n const detail = await response.text().catch(() => \"\");\n if (isContextWindowExceededResponse(response.status, detail)) {\n throw new ContextWindowExceededError({\n provider: this.id,\n status: response.status,\n rawMessage: detail || response.statusText || \"context window exceeded\",\n });\n }\n throw new Error(`Provider ${this.id} returned HTTP ${response.status}: ${detail.slice(0, 500)}`);\n }\n\n const decoder = new TextDecoder();\n let buffer = \"\";\n const toolCallParts = new Map<number, ToolCall>();\n const thinkSplitter = new ThinkBlockSplitter();\n let thinkSplittingActive = this.reasoning;\n\n const flushThinkSplitter = function* (): Generator<ChatDelta> {\n if (!thinkSplittingActive) return;\n for (const split of thinkSplitter.flush()) {\n if (split.type === \"reasoning\") {\n yield { reasoningContent: split.text, usage: { promptTokens: 0, completionTokens: 0, reasoningTokens: estimateReasoningTokens(split.text) } };\n } else {\n yield { content: split.text };\n }\n }\n };\n\n try {\n if (schemaWarnings.length > 0) {\n yield { schemaWarnings };\n }\n for await (const chunk of response.body as unknown as AsyncIterable<Uint8Array>) {\n resetTimeout();\n buffer += decoder.decode(chunk, { stream: true });\n const lines = buffer.split(\"\\n\");\n buffer = lines.pop() ?? \"\";\n\n for (const rawLine of lines) {\n const line = rawLine.trim();\n if (!line || !line.startsWith(\"data:\")) continue;\n const data = line.slice(\"data:\".length).trim();\n if (data === \"[DONE]\") {\n yield* flushThinkSplitter();\n return;\n }\n\n let parsed: StreamChunk;\n try {\n const rawParsed = JSON.parse(data) as ChatResponse;\n parsed = (this.adapter.postResponse ? this.adapter.postResponse(rawParsed) : rawParsed) as StreamChunk;\n } catch (error) {\n if (envValue({}, \"TANYA_DEBUG\")) {\n const message = error instanceof Error ? error.message : String(error);\n console.debug(`[tanya] Skipping malformed SSE chunk: ${message}`);\n }\n continue;\n }\n if (parsed.usage?.prompt_tokens !== undefined) {\n const reasoningTokens = parsed.usage.reasoning_tokens ??\n parsed.usage.completion_tokens_details?.reasoning_tokens;\n yield {\n usage: {\n promptTokens: parsed.usage.prompt_tokens ?? 0,\n completionTokens: parsed.usage.completion_tokens ?? 0,\n ...(typeof reasoningTokens === \"number\" ? { reasoningTokens } : {}),\n },\n };\n }\n\n const choice = parsed.choices?.[0];\n if (!choice) continue;\n\n const reasoningContent = choice.delta?.reasoning_content ?? undefined;\n if (reasoningContent) {\n yield {\n reasoningContent,\n usage: { promptTokens: 0, completionTokens: 0, reasoningTokens: estimateReasoningTokens(reasoningContent) },\n };\n }\n\n const content = choice.delta?.content ?? undefined;\n if (content) {\n if (!thinkSplittingActive && !content.includes(\"<think>\")) {\n yield { content };\n } else {\n thinkSplittingActive = true;\n for (const split of thinkSplitter.push(content)) {\n if (split.type === \"reasoning\") {\n yield {\n reasoningContent: split.text,\n usage: { promptTokens: 0, completionTokens: 0, reasoningTokens: estimateReasoningTokens(split.text) },\n };\n } else {\n yield { content: split.text };\n }\n }\n }\n }\n\n const rawToolCalls = choice.delta?.tool_calls ?? [];\n for (const rawToolCall of rawToolCalls) {\n const index = rawToolCall.index ?? 0;\n const existing =\n toolCallParts.get(index) ??\n ({\n id: rawToolCall.id ?? `tool-${index}`,\n type: \"function\",\n function: { name: \"\", arguments: \"\" },\n } satisfies ToolCall);\n\n if (rawToolCall.id) existing.id = rawToolCall.id;\n if (rawToolCall.function?.name) existing.function.name += rawToolCall.function.name;\n if (rawToolCall.function?.arguments) existing.function.arguments += rawToolCall.function.arguments;\n toolCallParts.set(index, existing);\n }\n\n if (choice.finish_reason) {\n const toolCalls = [...toolCallParts.values()].filter((call) => call.function.name);\n yield toolCalls.length\n ? { finishReason: choice.finish_reason, toolCalls }\n : { finishReason: choice.finish_reason };\n }\n }\n }\n yield* flushThinkSplitter();\n } catch (error) {\n if (controller.signal.aborted) {\n throw new Error(`Provider ${this.id} timed out while streaming a response.`);\n }\n throw error;\n } finally {\n if (timeout) clearTimeout(timeout);\n }\n }\n}\n\nfunction reasoningEnabled(adapter: ProviderAdapter, model: string): boolean {\n const normalized = model.toLowerCase();\n if (adapter.id === \"deepseek\") return normalized.includes(\"reasoner\") || /\\br1\\b/.test(normalized);\n if (adapter.id === \"qwen\") return /qwen3.*thinking|thinking/.test(normalized);\n if (adapter.id === \"grok\") return /grok-3-reasoning|reasoning/.test(normalized);\n return false;\n}\n","import type { TanyaConfig } from \"../config/env\";\nimport { envValue } from \"../config/envCompat\";\nimport { resolveProviderAdapter } from \"./adapters\";\nimport { OpenAiCompatibleProvider } from \"./openAiCompatible\";\nimport type { ChatProvider } from \"./types\";\nimport type { RouteTarget } from \"../router/types\";\n\nexport function createProvider(config: TanyaConfig): ChatProvider {\n return new OpenAiCompatibleProvider({\n id: config.provider === \"deepseek\" && config.profile === \"reasoner\" ? \"deepseek-reasoner\" : config.provider,\n apiKey: config.apiKey,\n baseUrl: config.baseUrl,\n model: config.model,\n temperature: config.temperature,\n topP: config.topP,\n timeoutMs: config.timeoutMs,\n });\n}\n\nexport function createProviderForRoute(config: TanyaConfig, target: RouteTarget): ChatProvider {\n const adapter = resolveProviderAdapter({ provider: target.provider });\n const envPrefix = target.provider.toUpperCase().replace(/[^A-Z0-9]+/g, \"_\");\n const providerApiKey = process.env[`${envPrefix}_API_KEY`] ?? \"\";\n const providerBaseUrl = process.env[`${envPrefix}_BASE_URL`] ?? \"\";\n const apiKey = target.provider === \"deepseek\"\n ? envValue(process.env, \"DEEPSEEK_API_KEY\") || providerApiKey || config.apiKey\n : providerApiKey || config.apiKey;\n const baseUrl = target.provider === config.provider && config.baseUrl\n ? config.baseUrl\n : providerBaseUrl || adapter.defaultBaseUrl || config.baseUrl;\n\n return new OpenAiCompatibleProvider({\n id: target.provider === \"deepseek\" && target.model === \"deepseek-reasoner\" ? \"deepseek-reasoner\" : target.provider,\n apiKey,\n baseUrl: baseUrl.replace(/\\/$/, \"\"),\n model: target.model,\n temperature: config.temperature,\n topP: config.topP,\n timeoutMs: config.timeoutMs,\n ...(target.maxInputTokens ? { contextWindow: target.maxInputTokens } : {}),\n });\n}\n","import { appendFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { exec } from \"node:child_process\";\nimport { join, resolve } from \"node:path\";\nimport { randomBytes } from \"node:crypto\";\nimport type { EventSink } from \"../events/types\";\n\nexport type DispatchMode = \"sequential\" | \"parallel\";\n\nexport type DispatchSubtask = {\n id: string;\n title: string;\n files: string[];\n depends_on: string[];\n tdd?: boolean;\n auto_fix?: boolean;\n};\n\nexport type DispatchPlan = {\n plan: string;\n subtasks: DispatchSubtask[];\n default_test_cmd?: string;\n};\n\nexport type DispatchSubtaskResult = {\n done: true;\n files_changed: string[];\n summary: string;\n unfixed_failures?: VerifyFailure[];\n};\n\nexport type DispatchRunTurn = (prompt: string, meta: { phase: \"plan\" | \"subtask\" | \"complete\"; subtask?: DispatchSubtask }) => Promise<string>;\n\nexport type DispatchCommandResult = {\n exitCode: number;\n stdout: string;\n stderr: string;\n};\n\nexport type DispatchRunCommand = (cmd: string, cwd: string) => Promise<DispatchCommandResult>;\n\nexport type RunPlanAndDispatchOptions = {\n cwd: string;\n prompt: string;\n maxSubtasks?: number;\n mode?: DispatchMode;\n resumeRunID?: string;\n tdd?: boolean;\n testCmd?: string;\n sink?: EventSink;\n runTurn: DispatchRunTurn;\n runCommand?: DispatchRunCommand;\n autoFixVerify?: boolean;\n autoFixWarns?: boolean;\n maxFixIterations?: number;\n readVerifyFailures?: () => Promise<VerifyFailure[]>;\n};\n\nexport type RunPlanAndDispatchResult = {\n runID: string;\n plan: DispatchPlan;\n completed: DispatchSubtaskResult[];\n};\n\nconst ULID_ALPHABET = \"0123456789ABCDEFGHJKMNPQRSTVWXYZ\";\n\nexport type VerifyFailure = {\n type?: \"verify_failure\";\n kind: string;\n severity?: \"error\" | \"warn\" | string;\n description?: string;\n path?: string;\n pattern?: string;\n task_id?: string;\n cmd?: string;\n exit_code?: number;\n output_excerpt?: string;\n matched_at?: string;\n};\n\nexport function generateRunID(now = Date.now()): string {\n let value = now;\n let time = \"\";\n for (let i = 0; i < 10; i += 1) {\n time = ULID_ALPHABET[value % 32] + time;\n value = Math.floor(value / 32);\n }\n const bytes = randomBytes(10);\n let random = \"\";\n for (const byte of bytes) random += ULID_ALPHABET[byte % 32];\n return `${time}${random}`;\n}\n\nexport function buildPlanningPrompt(prompt: string, maxSubtasks: number): string {\n return [\n \"Before writing code, output a JSON plan with this exact shape — nothing else in the response, just the fenced JSON block:\",\n \"```json\",\n \"{\",\n ' \"plan\": \"<one-paragraph summary of what we will build>\",',\n ' \"default_test_cmd\": \"<optional fallback test command for subtasks>\",',\n ' \"subtasks\": [',\n ' {\"id\": \"1\", \"title\": \"...\", \"files\": [\"path/to/a.go\"], \"depends_on\": [], \"tdd\": true, \"auto_fix\": true},',\n ' {\"id\": \"2\", \"title\": \"...\", \"files\": [\"path/to/b.go\"], \"depends_on\": [\"1\"], \"tdd\": false, \"auto_fix\": false}',\n \" ]\",\n \"}\",\n \"```\",\n `Constraints: each subtask should be 1-8 files. Total subtasks <= ${maxSubtasks}. depends_on is a list of subtask IDs that must complete first. auto_fix defaults to true when --auto-fix-verify is enabled.`,\n \"\",\n \"User prompt:\",\n prompt,\n ].join(\"\\n\");\n}\n\nexport function buildSubtaskPrompt(subtask: DispatchSubtask, ordered: DispatchSubtask[], completed: DispatchSubtaskResult[]): string {\n const index = ordered.findIndex((candidate) => candidate.id === subtask.id) + 1;\n const prior = completed.length === 0\n ? \"None.\"\n : completed.map((result, i) => {\n const files = result.files_changed.length > 0 ? ` Files changed: ${result.files_changed.join(\", \")}.` : \"\";\n return `- ${i + 1}. ${result.summary}${files}`;\n }).join(\"\\n\");\n return [\n `Subtask ${index}/${ordered.length}: ${subtask.title}`,\n \"\",\n `Files to touch: ${subtask.files.join(\", \")}`,\n \"\",\n \"Subtasks already complete:\",\n prior,\n \"\",\n \"Write the code. When done, output ONLY a fenced JSON block:\",\n \"```json\",\n '{\"done\": true, \"files_changed\": [\"path/to/file\"], \"summary\": \"...\"}',\n \"```\",\n ].join(\"\\n\");\n}\n\nexport function buildCompletionPrompt(plan: DispatchPlan, completed: DispatchSubtaskResult[]): string {\n return [\n \"All dispatch subtasks are complete. Run the existing verification discipline for this coding step, fix any issues you find, and then report the aggregate result.\",\n \"\",\n `Original plan: ${plan.plan}`,\n \"\",\n \"Completed subtasks:\",\n ...completed.map((result, i) => `- ${i + 1}. ${result.summary} (${result.files_changed.join(\", \") || \"no files reported\"})`),\n ].join(\"\\n\");\n}\n\nexport function parseFencedJSON<T>(text: string): T {\n const fence = /```(?:json)?\\s*([\\s\\S]*?)```/i.exec(text);\n const raw = fence?.[1] ?? text;\n return JSON.parse(raw.trim()) as T;\n}\n\nexport function normalizePlan(plan: DispatchPlan, maxSubtasks: number): DispatchPlan {\n if (!plan || typeof plan.plan !== \"string\" || !Array.isArray(plan.subtasks)) {\n throw new Error(\"dispatch plan must include plan and subtasks\");\n }\n if (plan.subtasks.length === 0) throw new Error(\"dispatch plan must include at least one subtask\");\n if (plan.subtasks.length > maxSubtasks) {\n throw new Error(`dispatch plan has ${plan.subtasks.length} subtasks, exceeding max ${maxSubtasks}`);\n }\n const ids = new Set<string>();\n const subtasks = plan.subtasks.map((task) => {\n if (!task || typeof task.id !== \"string\" || typeof task.title !== \"string\") {\n throw new Error(\"each dispatch subtask must include id and title\");\n }\n if (ids.has(task.id)) throw new Error(`duplicate dispatch subtask id: ${task.id}`);\n ids.add(task.id);\n const files = Array.isArray(task.files) ? task.files.map(String) : [];\n const dependsOn = Array.isArray(task.depends_on) ? task.depends_on.map(String) : [];\n // files is advisory: the planning prompt nudges toward small subtasks and runtime\n // outOfScopeFiles() warns on sprawl. No hard cap — a legit CRUD feature spans many\n // files and a pre-flight throw would abort the whole run.\n const tdd = typeof task.tdd === \"boolean\" ? task.tdd : undefined;\n const autoFix = typeof task.auto_fix === \"boolean\" ? task.auto_fix : undefined;\n return { id: task.id, title: task.title, files, depends_on: dependsOn, ...(tdd !== undefined ? { tdd } : {}), ...(autoFix !== undefined ? { auto_fix: autoFix } : {}) };\n });\n for (const task of subtasks) {\n for (const dep of task.depends_on) {\n if (!ids.has(dep)) throw new Error(`dispatch subtask ${task.id} depends on unknown subtask ${dep}`);\n }\n }\n return { plan: plan.plan, subtasks, ...(typeof plan.default_test_cmd === \"string\" && plan.default_test_cmd.trim() ? { default_test_cmd: plan.default_test_cmd.trim() } : {}) };\n}\n\nexport function topologicalSubtasks(plan: DispatchPlan): DispatchSubtask[] {\n const remaining = new Map(plan.subtasks.map((task) => [task.id, task]));\n const done = new Set<string>();\n const ordered: DispatchSubtask[] = [];\n while (remaining.size > 0) {\n const ready = [...remaining.values()].filter((task) => task.depends_on.every((dep) => done.has(dep)));\n if (ready.length === 0) throw new Error(\"dispatch plan contains a dependency cycle\");\n ready.sort((a, b) => a.id.localeCompare(b.id, undefined, { numeric: true }));\n for (const task of ready) {\n ordered.push(task);\n done.add(task.id);\n remaining.delete(task.id);\n }\n }\n return ordered;\n}\n\nfunction dispatchDir(cwd: string, runID: string): string {\n return resolve(cwd, \".tania\", \"dispatch\", runID);\n}\n\nfunction subtaskResultPath(dir: string, id: string): string {\n return join(dir, `subtask_${id}.json`);\n}\n\nfunction subtaskPhasePath(dir: string, id: string): string {\n return join(dir, `subtask_${id}_phases.jsonl`);\n}\n\nfunction subtaskFixPath(dir: string, id: string): string {\n return join(dir, `subtask_${id}_fixes.jsonl`);\n}\n\nfunction loadCompleted(dir: string, ordered: DispatchSubtask[]): DispatchSubtaskResult[] {\n const completed: DispatchSubtaskResult[] = [];\n for (const task of ordered) {\n const path = subtaskResultPath(dir, task.id);\n if (!existsSync(path)) break;\n completed.push(JSON.parse(readFileSync(path, \"utf8\")) as DispatchSubtaskResult);\n }\n return completed;\n}\n\nfunction recordFailure(dir: string, subtaskID: string, err: unknown): void {\n const message = err instanceof Error ? err.message : String(err);\n appendFileSync(join(dir, \"failures.log\"), `${new Date().toISOString()} subtask=${subtaskID} ${message}\\n`);\n}\n\nfunction appendPhase(dir: string, subtaskID: string, event: Record<string, unknown>): void {\n appendFileSync(subtaskPhasePath(dir, subtaskID), `${JSON.stringify({ at: new Date().toISOString(), ...event })}\\n`);\n}\n\nfunction appendFix(dir: string, subtaskID: string, event: Record<string, unknown>): void {\n appendFileSync(subtaskFixPath(dir, subtaskID), `${JSON.stringify({ at: new Date().toISOString(), ...event })}\\n`);\n}\n\nexport function parseVerifyFailureJSONL(lines: string[]): VerifyFailure[] {\n const failures: VerifyFailure[] = [];\n for (const line of lines) {\n const trimmed = line.trim();\n if (!trimmed) continue;\n let event: unknown;\n try {\n event = JSON.parse(trimmed);\n } catch {\n continue;\n }\n if (!event || typeof event !== \"object\") continue;\n const record = event as Record<string, unknown>;\n if (record.type === \"verify_failure_eof\") break;\n if (record.type !== \"verify_failure\") continue;\n const failure: VerifyFailure = { type: \"verify_failure\", kind: String(record.kind ?? \"\") };\n if (typeof record.severity === \"string\") failure.severity = record.severity;\n if (typeof record.description === \"string\") failure.description = record.description;\n if (typeof record.path === \"string\") failure.path = record.path;\n if (typeof record.pattern === \"string\") failure.pattern = record.pattern;\n if (typeof record.task_id === \"string\") failure.task_id = record.task_id;\n if (typeof record.cmd === \"string\") failure.cmd = record.cmd;\n if (typeof record.exit_code === \"number\") failure.exit_code = record.exit_code;\n if (typeof record.output_excerpt === \"string\") failure.output_excerpt = record.output_excerpt;\n if (typeof record.matched_at === \"string\") failure.matched_at = record.matched_at;\n failures.push(failure);\n }\n return failures.filter((failure) => failure.kind);\n}\n\nexport function buildAutoFixPrompt(failures: VerifyFailure[]): string {\n const lines = [\n `The verify suite ran on your sub-task output and ${failures.length} check(s) failed:`,\n \"\",\n ];\n failures.forEach((failure, index) => {\n lines.push(`Failure ${index + 1}/${failures.length}: ${failure.kind}${failure.path ? ` in ${failure.path}` : \"\"}`);\n if (failure.description) lines.push(` Description: ${failure.description}`);\n if (failure.pattern) lines.push(` Pattern: ${failure.pattern}`);\n if (failure.matched_at) lines.push(` Matched at: ${failure.matched_at}`);\n if (failure.cmd) lines.push(` Cmd: ${failure.cmd}`);\n if (typeof failure.exit_code === \"number\") lines.push(` Exit code: ${failure.exit_code}`);\n if (failure.output_excerpt) lines.push(` Cmd output: ${failure.output_excerpt.slice(0, 2048)}`);\n lines.push(\"\");\n });\n lines.push(\"Fix the implementation. Touch only the files that need to change. Do NOT modify test files unless the failure points at a test file directly.\");\n lines.push('When done, output ONLY a fenced JSON block: {\"done\": true, \"files_changed\": [\"...\"], \"summary\": \"fixed: ...\"}');\n return lines.join(\"\\n\");\n}\n\nfunction failureKey(failure: VerifyFailure): string {\n return [failure.kind, failure.path ?? \"\", failure.pattern ?? \"\", failure.cmd ?? \"\", failure.matched_at ?? \"\"].join(\"\\x1f\");\n}\n\nfunction sameFailureSet(a: VerifyFailure[], b: VerifyFailure[]): boolean {\n if (a.length !== b.length) return false;\n const left = a.map(failureKey).sort();\n const right = b.map(failureKey).sort();\n return left.every((key, i) => key === right[i]);\n}\n\nfunction outOfScopeFiles(subtask: DispatchSubtask, changed: string[]): string[] {\n const allowed = new Set(subtask.files);\n return changed.filter((file) => !allowed.has(file));\n}\n\nasync function runAutoFixLoop(\n options: RunPlanAndDispatchOptions,\n subtask: DispatchSubtask,\n result: DispatchSubtaskResult,\n dir: string,\n): Promise<DispatchSubtaskResult> {\n if (!options.autoFixVerify || subtask.auto_fix === false || !options.readVerifyFailures) return result;\n const max = options.maxFixIterations ?? 5;\n let previous: VerifyFailure[] | undefined;\n let current = (await options.readVerifyFailures()).filter((failure) => options.autoFixWarns || failure.severity !== \"warn\");\n if (current.length === 0) return result;\n for (let iteration = 1; iteration <= max; iteration += 1) {\n if (previous && sameFailureSet(previous, current)) {\n const gaveUp = { ...result, summary: `auto-fix entered a loop at iteration ${iteration}`, unfixed_failures: current };\n appendFix(dir, subtask.id, { iteration, failures_in: current, success: false, loop_detected: true });\n return gaveUp;\n }\n const response = await options.runTurn(buildAutoFixPrompt(current), { phase: \"subtask\", subtask });\n const fixed = parseFencedJSON<DispatchSubtaskResult>(response);\n fixed.files_changed = Array.isArray(fixed.files_changed) ? fixed.files_changed.map(String) : [];\n fixed.summary = typeof fixed.summary === \"string\" ? fixed.summary : \"\";\n appendFix(dir, subtask.id, { iteration, failures_in: current, files_changed_out: fixed.files_changed, success: true });\n previous = current;\n result = fixed;\n current = (await options.readVerifyFailures()).filter((failure) => options.autoFixWarns || failure.severity !== \"warn\");\n if (current.length === 0) {\n writeFileSync(subtaskResultPath(dir, subtask.id), JSON.stringify(result, null, 2));\n return result;\n }\n }\n const gaveUp = { ...result, summary: `auto-fix gave up after ${max} iterations`, unfixed_failures: current };\n appendFix(dir, subtask.id, { iteration: max, failures_in: current, success: false, giveup: true });\n writeFileSync(subtaskResultPath(dir, subtask.id), JSON.stringify(gaveUp, null, 2));\n return gaveUp;\n}\n\ntype RedWritten = {\n phase: \"red_written\";\n test_files?: string[];\n test_cmd?: string;\n};\n\ntype GreenWritten = {\n phase: \"green_written\";\n impl_files?: string[];\n};\n\nexport function buildRedPrompt(subtask: DispatchSubtask, plan: DispatchPlan, cwd: string, cliTestCmd?: string): string {\n const testHint = cliTestCmd || plan.default_test_cmd || inferTestCommand(cwd);\n return [\n `TDD phase 1 of 4 for subtask ${subtask.id}: ${subtask.title}`,\n \"\",\n \"Write or extend the test(s) for this subtask. Do NOT touch implementation files yet.\",\n \"The test must capture the intended behavior precisely.\",\n testHint ? `Use this test command unless the new test requires a narrower one: ${testHint}` : \"Declare the exact test command to run.\",\n \"\",\n \"When done, output ONLY a fenced JSON block:\",\n \"```json\",\n '{\"phase\": \"red_written\", \"test_files\": [\"path/to/test\"], \"test_cmd\": \"go test ./... -count=1\"}',\n \"```\",\n ].join(\"\\n\");\n}\n\nfunction buildRedViolationPrompt(output: DispatchCommandResult, attempt: number): string {\n return [\n \"TDD violation: your test passed before the implementation existed. This means the test isn't testing what you think.\",\n \"Options: (a) tighten the test to actually fail, (b) the implementation already exists and your test is redundant, or (c) the test command isn't running the new test.\",\n `RED attempt ${attempt}/3 passed unexpectedly.`,\n \"Update and output a new {\\\"phase\\\": \\\"red_written\\\", \\\"test_files\\\": [...], \\\"test_cmd\\\": \\\"...\\\"} block.\",\n \"If this is the 3rd failed RED attempt for this subtask, TDD will be abandoned for this subtask and regular dispatch will continue.\",\n \"\",\n trimCommandOutput(output),\n ].join(\"\\n\");\n}\n\nfunction buildGreenPrompt(subtask: DispatchSubtask, redOutput: DispatchCommandResult): string {\n return [\n `TDD phase 3 of 4 for subtask ${subtask.id}: ${subtask.title}`,\n \"\",\n \"The test failed correctly (RED). Now write the implementation.\",\n \"Touch only the files needed to make the test pass. Do NOT modify the test itself.\",\n \"\",\n \"RED output:\",\n trimCommandOutput(redOutput),\n \"\",\n \"When done, output ONLY a fenced JSON block:\",\n \"```json\",\n '{\"phase\": \"green_written\", \"impl_files\": [\"path/to/file\"]}',\n \"```\",\n ].join(\"\\n\");\n}\n\nfunction buildGreenRetryPrompt(output: DispatchCommandResult, attempt: number): string {\n return [\n `Test still failing after GREEN attempt ${attempt}/5.`,\n \"Output:\",\n trimCommandOutput(output),\n \"\",\n \"Diagnose and fix the IMPLEMENTATION (do not weaken the test).\",\n \"Output a new {\\\"phase\\\": \\\"green_written\\\", \\\"impl_files\\\": [...]} block.\",\n ].join(\"\\n\");\n}\n\nfunction trimCommandOutput(output: DispatchCommandResult, max = 6000): string {\n const text = [`exit_code=${output.exitCode}`, output.stdout, output.stderr].filter(Boolean).join(\"\\n\");\n if (text.length <= max) return text;\n return `${text.slice(0, max)}\\n...<trimmed>`;\n}\n\nexport function inferTestCommand(cwd: string): string | undefined {\n if (existsSync(join(cwd, \"go.mod\"))) return \"go test ./... -count=1\";\n if (existsSync(join(cwd, \"package.json\"))) return \"npm test\";\n if (existsSync(join(cwd, \"Cargo.toml\"))) return \"cargo test\";\n if (existsSync(join(cwd, \"requirements.txt\")) || existsSync(join(cwd, \"pyproject.toml\"))) return \"pytest\";\n return undefined;\n}\n\nasync function defaultRunCommand(cmd: string, cwd: string): Promise<DispatchCommandResult> {\n return new Promise((resolveCommand) => {\n exec(cmd, { cwd, maxBuffer: 10 * 1024 * 1024 }, (error, stdout, stderr) => {\n const maybeCode = typeof (error as { code?: unknown } | null)?.code === \"number\" ? (error as { code: number }).code : 0;\n resolveCommand({ exitCode: error ? maybeCode || 1 : 0, stdout, stderr });\n });\n });\n}\n\nfunction resolveTestCommand(options: RunPlanAndDispatchOptions, plan: DispatchPlan, red?: RedWritten): string {\n const declared = red?.test_cmd?.trim();\n if (options.testCmd?.trim()) return options.testCmd.trim();\n if (declared) return declared;\n if (plan.default_test_cmd?.trim()) return plan.default_test_cmd.trim();\n const inferred = inferTestCommand(options.cwd);\n if (inferred) return inferred;\n throw new Error(\"cannot infer test_cmd — declare one in the subtask's red_written JSON or the plan's default_test_cmd\");\n}\n\nasync function runRegularSubtask(\n options: RunPlanAndDispatchOptions,\n subtask: DispatchSubtask,\n ordered: DispatchSubtask[],\n completed: DispatchSubtaskResult[],\n dir: string,\n): Promise<DispatchSubtaskResult> {\n const response = await options.runTurn(buildSubtaskPrompt(subtask, ordered, completed), { phase: \"subtask\", subtask });\n const result = parseFencedJSON<DispatchSubtaskResult>(response);\n if (!result.done) throw new Error(`subtask ${subtask.id} did not report done=true`);\n result.files_changed = Array.isArray(result.files_changed) ? result.files_changed.map(String) : [];\n result.summary = typeof result.summary === \"string\" ? result.summary : \"\";\n writeFileSync(subtaskResultPath(dir, subtask.id), JSON.stringify(result, null, 2));\n return result;\n}\n\nasync function runTDDSubtask(\n options: RunPlanAndDispatchOptions,\n plan: DispatchPlan,\n subtask: DispatchSubtask,\n ordered: DispatchSubtask[],\n completed: DispatchSubtaskResult[],\n dir: string,\n): Promise<DispatchSubtaskResult> {\n const runCommand = options.runCommand ?? defaultRunCommand;\n let red: RedWritten | undefined;\n let redOutput: DispatchCommandResult | undefined;\n let redPrompt = buildRedPrompt(subtask, plan, options.cwd, options.testCmd);\n for (let attempt = 1; attempt <= 3; attempt += 1) {\n appendPhase(dir, subtask.id, { phase: \"red_write\", attempt });\n red = parseFencedJSON<RedWritten>(await options.runTurn(redPrompt, { phase: \"subtask\", subtask }));\n if (red.phase !== \"red_written\") throw new Error(`subtask ${subtask.id} did not report phase=red_written`);\n const testCmd = resolveTestCommand(options, plan, red);\n appendPhase(dir, subtask.id, { phase: \"red_verify\", attempt, test_cmd: testCmd });\n const output = await runCommand(testCmd, options.cwd);\n appendPhase(dir, subtask.id, { phase: \"red_verify_result\", attempt, ok: output.exitCode !== 0, exit_code: output.exitCode, stdout: output.stdout, stderr: output.stderr });\n if (output.exitCode !== 0) {\n redOutput = output;\n break;\n }\n redPrompt = buildRedViolationPrompt(output, attempt);\n }\n if (!redOutput || !red) {\n appendPhase(dir, subtask.id, { phase: \"red_abandoned\", reason: \"test passed before implementation after 3 attempts\" });\n return runRegularSubtask(options, subtask, ordered, completed, dir);\n }\n\n const testCmd = resolveTestCommand(options, plan, red);\n for (let attempt = 1; attempt <= 5; attempt += 1) {\n appendPhase(dir, subtask.id, { phase: \"green_write\", attempt });\n const prompt = attempt === 1 ? buildGreenPrompt(subtask, redOutput) : buildGreenRetryPrompt(redOutput, attempt - 1);\n const green = parseFencedJSON<GreenWritten>(await options.runTurn(prompt, { phase: \"subtask\", subtask }));\n if (green.phase !== \"green_written\") throw new Error(`subtask ${subtask.id} did not report phase=green_written`);\n appendPhase(dir, subtask.id, { phase: \"green_verify\", attempt, test_cmd: testCmd });\n const output = await runCommand(testCmd, options.cwd);\n appendPhase(dir, subtask.id, { phase: \"green_verify_result\", attempt, ok: output.exitCode === 0, exit_code: output.exitCode, stdout: output.stdout, stderr: output.stderr });\n if (output.exitCode === 0) {\n const result: DispatchSubtaskResult = {\n done: true,\n files_changed: Array.isArray(green.impl_files) ? green.impl_files.map(String) : [],\n summary: `TDD subtask ${subtask.id} passed ${testCmd}`,\n };\n writeFileSync(subtaskResultPath(dir, subtask.id), JSON.stringify(result, null, 2));\n return result;\n }\n redOutput = output;\n }\n throw new Error(`subtask ${subtask.id} failed TDD GREEN after 5 attempts`);\n}\n\nexport async function runPlanAndDispatch(options: RunPlanAndDispatchOptions): Promise<RunPlanAndDispatchResult> {\n const maxSubtasks = options.maxSubtasks ?? 12;\n const mode = options.mode ?? \"sequential\";\n if (mode === \"parallel\") throw new Error(\"--dispatch-mode parallel is not implemented yet; use sequential\");\n\n const runID = options.resumeRunID ?? generateRunID();\n const dir = dispatchDir(options.cwd, runID);\n mkdirSync(dir, { recursive: true });\n await options.sink?.({ type: \"status\", message: `Dispatch run: ${runID}` });\n\n let plan: DispatchPlan;\n if (options.resumeRunID) {\n const planPath = join(dir, \"plan.json\");\n if (!existsSync(planPath)) throw new Error(`dispatch run ${runID} has no plan.json`);\n plan = normalizePlan(JSON.parse(readFileSync(planPath, \"utf8\")) as DispatchPlan, maxSubtasks);\n } else {\n const planningResponse = await options.runTurn(buildPlanningPrompt(options.prompt, maxSubtasks), { phase: \"plan\" });\n plan = normalizePlan(parseFencedJSON<DispatchPlan>(planningResponse), maxSubtasks);\n writeFileSync(join(dir, \"plan.json\"), JSON.stringify(plan, null, 2));\n }\n\n const ordered = topologicalSubtasks(plan);\n const completed = loadCompleted(dir, ordered);\n\n for (const subtask of ordered.slice(completed.length)) {\n await options.sink?.({ type: \"subtask_start\", subtask_id: subtask.id, title: subtask.title, files: subtask.files });\n try {\n let result = options.tdd && subtask.tdd !== false\n ? await runTDDSubtask(options, plan, subtask, ordered, completed, dir)\n : await runRegularSubtask(options, subtask, ordered, completed, dir);\n result = await runAutoFixLoop(options, subtask, result, dir);\n const outOfScope = outOfScopeFiles(subtask, result.files_changed);\n if (outOfScope.length > 0) {\n await options.sink?.({\n type: \"status\",\n message: `Subtask ${subtask.id} changed files outside its declared scope: ${outOfScope.join(\", \")}`,\n });\n }\n completed.push(result);\n await options.sink?.({\n type: \"subtask_done\",\n subtask_id: subtask.id,\n files_changed: result.files_changed,\n summary: result.summary,\n ok: !result.unfixed_failures?.some((failure) => failure.severity !== \"warn\"),\n });\n } catch (err) {\n recordFailure(dir, subtask.id, err);\n await options.sink?.({ type: \"subtask_done\", subtask_id: subtask.id, files_changed: [], summary: err instanceof Error ? err.message : String(err), ok: false });\n throw err;\n }\n }\n\n await options.runTurn(buildCompletionPrompt(plan, completed), { phase: \"complete\" });\n return { runID, plan, completed };\n}\n","import { spawnSync } from \"node:child_process\";\nimport { existsSync, readFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport type { TanyaFinalManifest } from \"./runner\";\n\nconst POST_CHECK_TIMEOUT_MS = 25_000;\n\nfunction hasPassingVerification(manifest: TanyaFinalManifest, pattern: RegExp): boolean {\n return manifest.verification.some(\n (line) => /->\\s*passed\\b/i.test(line) && pattern.test(line),\n );\n}\n\nfunction readPackageScripts(cwd: string): Record<string, string> {\n try {\n const raw = readFileSync(join(cwd, \"package.json\"), \"utf8\");\n const parsed = JSON.parse(raw) as { scripts?: Record<string, string> };\n return parsed.scripts ?? {};\n } catch {\n return {};\n }\n}\n\nfunction readPackageManager(cwd: string): \"npm\" | \"pnpm\" | \"yarn\" | \"bun\" {\n try {\n const raw = readFileSync(join(cwd, \"package.json\"), \"utf8\");\n const parsed = JSON.parse(raw) as { packageManager?: string };\n const packageManager = parsed.packageManager?.split(\"@\")[0];\n if (packageManager === \"pnpm\" || packageManager === \"yarn\" || packageManager === \"bun\") return packageManager;\n } catch {\n // fall through to lockfile detection\n }\n if (existsSync(join(cwd, \"pnpm-lock.yaml\"))) return \"pnpm\";\n if (existsSync(join(cwd, \"yarn.lock\"))) return \"yarn\";\n if (existsSync(join(cwd, \"bun.lockb\")) || existsSync(join(cwd, \"bun.lock\"))) return \"bun\";\n return \"npm\";\n}\n\nfunction packageScriptCommand(\n packageManager: \"npm\" | \"pnpm\" | \"yarn\" | \"bun\",\n script: string,\n): { cmd: string; args: string[] } {\n if (packageManager === \"yarn\") return { cmd: \"yarn\", args: [script] };\n return { cmd: packageManager, args: [\"run\", script] };\n}\n\nfunction runCommand(\n cmd: string,\n args: string[],\n cwd: string,\n timeoutMs: number,\n): { exitCode: number; output: string } {\n const result = spawnSync(cmd, args, {\n cwd,\n encoding: \"utf8\",\n timeout: timeoutMs,\n shell: false,\n });\n const output = `${result.stdout ?? \"\"}${result.stderr ?? \"\"}`.trim();\n const exitCode = result.status ?? (result.error ? 1 : 0);\n return { exitCode, output };\n}\n\nfunction parseTypeScriptErrors(output: string): string[] {\n return output\n .split(/\\r?\\n/)\n .filter((line) => /\\.tsx?:\\d+:\\d+\\s*-?\\s*error\\s+TS\\d+:/i.test(line) || /error TS\\d+:/i.test(line))\n .slice(0, 5);\n}\n\nexport async function detectPostRunBlockers(\n cwd: string,\n manifest: TanyaFinalManifest,\n): Promise<string[]> {\n const blockers: string[] = [];\n const tsconfigExists =\n existsSync(join(cwd, \"tsconfig.json\")) || existsSync(join(cwd, \"tsconfig.base.json\"));\n const scripts = readPackageScripts(cwd);\n const packageManager = readPackageManager(cwd);\n\n if (tsconfigExists && !hasPassingVerification(manifest, /tsc|typecheck|type-check/i)) {\n const typecheckCommand = scripts.typecheck\n ? packageScriptCommand(packageManager, \"typecheck\")\n : { cmd: \"npx\", args: [\"tsc\", \"--noEmit\", \"--pretty\", \"false\"] };\n const { exitCode, output } = runCommand(typecheckCommand.cmd, typecheckCommand.args, cwd, POST_CHECK_TIMEOUT_MS);\n if (exitCode !== 0) {\n const errorLines = parseTypeScriptErrors(output);\n const summary = errorLines.length > 0\n ? `TypeScript errors after run:\\n${errorLines.map((line) => ` ${line}`).join(\"\\n\")}`\n : \"TypeScript compilation failed (post-run check)\";\n blockers.push(summary);\n }\n }\n\n if (scripts.test && !hasPassingVerification(manifest, /\\btest\\b/i)) {\n const testCommand = packageScriptCommand(packageManager, \"test\");\n const { exitCode } = runCommand(testCommand.cmd, testCommand.args, cwd, POST_CHECK_TIMEOUT_MS);\n if (exitCode !== 0) {\n blockers.push(\"Tests failed after run (post-run check)\");\n }\n }\n\n return blockers;\n}\n","import type { ChatProvider } from \"../providers/types\";\n\nconst PLAN_SYSTEM = [\n \"You are a senior engineer producing a concise execution plan for a coding agent.\",\n \"Given a task description and a workspace export map, output ONLY a structured plan.\",\n \"Format:\",\n \"Files to read first: <comma-separated list>\",\n \"Files to modify: <comma-separated list>\",\n \"Key steps:\",\n \"1. <step>\",\n \"2. <step>\",\n \"...\",\n \"Verification: <command to run>\",\n \"Do not write any code. Do not explain. Output the plan only.\",\n].join(\"\\n\");\n\nexport async function buildExecutionPlan(\n reasonerProvider: ChatProvider,\n task: string,\n exportMap: string,\n): Promise<string> {\n const userContent = exportMap\n ? `Workspace export map:\\n${exportMap}\\n\\nTask: ${task}`\n : `Task: ${task}`;\n\n let plan = \"\";\n for await (const delta of reasonerProvider.streamChat({\n messages: [\n { role: \"system\", content: PLAN_SYSTEM },\n { role: \"user\", content: userContent },\n ],\n tools: [],\n temperature: 0,\n maxTokens: 512,\n })) {\n if (delta.content) plan += delta.content;\n }\n return plan.trim();\n}\n","import type { ChatProvider } from \"../providers/types\";\n\nconst REVIEW_SYSTEM = [\n \"You are a senior code reviewer. You will be given a task description and the diff of changes made.\",\n \"Review only what was changed. Be concise. Flag only real issues.\",\n \"Output format:\",\n \"## Review\",\n \"**Verdict:** LGTM | NEEDS CHANGES\",\n \"\",\n \"**Issues:** (list only if verdict is NEEDS CHANGES)\",\n \"- <file>:<line> — <issue>\",\n \"\",\n \"**Suggestions:** (optional minor improvements, max 3)\",\n \"- <suggestion>\",\n \"\",\n \"Do not praise the code. Do not explain what the code does. Only flag problems.\",\n].join(\"\\n\");\n\nexport async function reviewChanges(\n provider: ChatProvider,\n task: string,\n diff: string,\n): Promise<string> {\n if (!diff.trim()) return \"## Review\\n**Verdict:** LGTM\\n\\nNo changes to review.\";\n\n let review = \"\";\n for await (const delta of provider.streamChat({\n messages: [\n { role: \"system\", content: REVIEW_SYSTEM },\n {\n role: \"user\",\n content: `Task: ${task}\\n\\nDiff:\\n\\`\\`\\`diff\\n${diff.slice(0, 8000)}\\n\\`\\`\\``,\n },\n ],\n tools: [],\n temperature: 0,\n maxTokens: 600,\n })) {\n if (delta.content) review += delta.content;\n }\n return review.trim();\n}\n","import type { TanyaRunContext } from \"../context/runContext\";\n\nfunction boundedTurnBudget(value: number): number {\n return Math.max(1, Math.min(300, Math.floor(value)));\n}\n\nexport function phaseAwareMaxTurns(runContext: TanyaRunContext | undefined, prompt: string, override?: number): number | undefined {\n if (override !== undefined) return boundedTurnBudget(override);\n const text = [\n runContext?.task?.title,\n runContext?.task?.summary,\n ...(runContext?.instructions ?? []),\n prompt,\n ].filter(Boolean).join(\"\\n\").toLowerCase();\n const isCoding = runContext?.task?.kind === \"coding\" ||\n /\\b(?:coding|go-backend-|initialize\\s+go\\s+backend|backend\\s+step|pre-seeded tasks)\\b/.test(text);\n if (!isCoding) return undefined;\n if (/\\b(?:foundation|go-backend-foundation)\\b/.test(text)) {\n return 300;\n }\n if (/\\b(?:setup|auth|initialize\\s+go\\s+backend|go-backend-(?:init|auth))\\b/.test(text)) {\n return 200;\n }\n if (/\\b(?:testing|verify|verification|go-backend-verify)\\b/.test(text)) {\n return 50;\n }\n if (/\\b(?:feature|addon|add-on|go-backend-(?:feature|addon))\\b/.test(text)) {\n return 100;\n }\n return 100;\n}\n","import type { TanyaEvent } from \"../events/types\";\nimport { envValue } from \"../config/envCompat\";\nimport { estimateRunCost } from \"../memory/runLogs\";\n\nexport type LiveRouteStep = \"planning\" | \"tool_call\" | \"synthesis\" | \"verification\" | \"reasoning\" | \"unknown\";\n\nexport type LiveStatus = {\n provider: string;\n model: string;\n routeStep?: LiveRouteStep;\n spend: {\n usd: number;\n inputTokens: number;\n outputTokens: number;\n reasoningTokens?: number;\n };\n contextPressure?: { used: number; cap: number };\n activeTools: Array<{ id: string; tool: string; startedAt: string }>;\n activeChildren: Array<{ subRunId: string; workspace: string; startedAt: string }>;\n pendingPermission?: { tool: string; matchedRule?: string };\n lastEscalation?: { from: string; to: string; reason: string; at: string };\n lastCompaction?: { type: string; removedTokens: number; at: string };\n promptBudgetWarning?: { droppedSections: string[]; at: string };\n};\n\nexport type LiveStatusController = {\n snapshot(): LiveStatus;\n consume(event: TanyaEvent): void;\n};\n\nexport type LiveStatusRenderer = {\n consume(event: TanyaEvent): void;\n render(): void;\n snapshot(): LiveStatus;\n enabled(): boolean;\n};\n\nexport function createLiveStatus(options: {\n now?: () => Date;\n estimateUsd?: (provider: string, model: string, inputTokens: number, outputTokens: number) => number;\n} = {}): LiveStatusController {\n const now = options.now ?? (() => new Date());\n const activeTools = new Map<string, { id: string; tool: string; startedAt: string }>();\n const activeChildren = new Map<string, { subRunId: string; workspace: string; startedAt: string }>();\n let provider = \"\";\n let model = \"\";\n let routeStep: LiveRouteStep | undefined;\n let spend: LiveStatus[\"spend\"] = { usd: 0, inputTokens: 0, outputTokens: 0 };\n let contextPressure: LiveStatus[\"contextPressure\"];\n let pendingPermission: LiveStatus[\"pendingPermission\"];\n let lastEscalation: LiveStatus[\"lastEscalation\"];\n let lastCompaction: LiveStatus[\"lastCompaction\"];\n let promptBudgetWarning: LiveStatus[\"promptBudgetWarning\"];\n\n function stamp(): string {\n return now().toISOString();\n }\n\n return {\n snapshot() {\n return {\n provider,\n model,\n ...(routeStep ? { routeStep } : {}),\n spend: { ...spend },\n ...(contextPressure ? { contextPressure: { ...contextPressure } } : {}),\n activeTools: [...activeTools.values()].sort((a, b) => a.startedAt.localeCompare(b.startedAt) || a.id.localeCompare(b.id)),\n activeChildren: [...activeChildren.values()].sort((a, b) => a.startedAt.localeCompare(b.startedAt) || a.subRunId.localeCompare(b.subRunId)),\n ...(pendingPermission ? { pendingPermission: { ...pendingPermission } } : {}),\n ...(lastEscalation ? { lastEscalation: { ...lastEscalation } } : {}),\n ...(lastCompaction ? { lastCompaction: { ...lastCompaction } } : {}),\n ...(promptBudgetWarning ? { promptBudgetWarning: { ...promptBudgetWarning, droppedSections: [...promptBudgetWarning.droppedSections] } } : {}),\n };\n },\n consume(event) {\n switch (event.type) {\n case \"model_routed\":\n provider = event.provider;\n model = event.model;\n routeStep = event.stepType;\n break;\n case \"tool_call\":\n activeTools.set(event.id, { id: event.id, tool: event.tool, startedAt: stamp() });\n break;\n case \"tool_result\":\n activeTools.delete(event.id);\n break;\n case \"subtask_started\":\n activeChildren.set(event.subRunId, {\n subRunId: event.subRunId,\n workspace: event.workspace,\n startedAt: stamp(),\n });\n break;\n case \"subtask_completed\":\n activeChildren.delete(event.subRunId);\n break;\n case \"permission_request\":\n pendingPermission = {\n tool: event.tool,\n ...(event.matchedRule ? { matchedRule: event.matchedRule } : {}),\n };\n break;\n case \"permission_decision\":\n pendingPermission = undefined;\n break;\n case \"escalation_event\":\n lastEscalation = {\n from: `${event.from.provider}:${event.from.model}`,\n to: `${event.to.provider}:${event.to.model}`,\n reason: event.reason,\n at: stamp(),\n };\n break;\n case \"compact_event\":\n lastCompaction = {\n type: event.compactType,\n removedTokens: event.removedTokens,\n at: stamp(),\n };\n break;\n case \"prompt_budget_exceeded\":\n contextPressure = { used: event.totalTokens, cap: event.cap };\n promptBudgetWarning = { droppedSections: [...event.droppedSections], at: stamp() };\n break;\n case \"message_start\":\n promptBudgetWarning = undefined;\n break;\n case \"final\": {\n const metrics = event.metrics;\n if (!metrics) break;\n const inputTokens = metrics.promptTokens ?? 0;\n const outputTokens = metrics.completionTokens ?? 0;\n const reasoningTokens = (metrics as { reasoningTokens?: number }).reasoningTokens ?? 0;\n spend = {\n usd: spend.usd + (options.estimateUsd?.(provider, model, inputTokens, outputTokens) ?? 0),\n inputTokens: spend.inputTokens + inputTokens,\n outputTokens: spend.outputTokens + outputTokens,\n ...(reasoningTokens > 0\n ? { reasoningTokens: (spend.reasoningTokens ?? 0) + reasoningTokens }\n : spend.reasoningTokens !== undefined\n ? { reasoningTokens: spend.reasoningTokens }\n : {}),\n };\n break;\n }\n default:\n break;\n }\n },\n };\n}\n\nexport function formatLiveStatus(status: LiveStatus, options: {\n now?: Date;\n columns?: number;\n fadeMs?: number;\n} = {}): string {\n const now = options.now ?? new Date();\n const fadeMs = options.fadeMs ?? 5_000;\n const promptBudget = status.promptBudgetWarning;\n const escalation = status.lastEscalation && withinWindow(status.lastEscalation.at, now, fadeMs)\n ? status.lastEscalation\n : undefined;\n const compaction = status.lastCompaction && withinWindow(status.lastCompaction.at, now, fadeMs)\n ? status.lastCompaction\n : undefined;\n\n if (status.pendingPermission) {\n return fitLine(`[awaiting permission: ${status.pendingPermission.tool}${status.pendingPermission.matchedRule ? ` (${status.pendingPermission.matchedRule})` : \"\"}]`, options.columns);\n }\n if (promptBudget) {\n return fitLine(`[prompt budget: dropped ${promptBudget.droppedSections.join(\", \")}]`, options.columns);\n }\n if (escalation) {\n return fitLine(`[escalated ${escalation.from}->${escalation.to}: ${escalation.reason}]`, options.columns);\n }\n if (compaction) {\n return fitLine(`[compacted ~${compactTokenCount(compaction.removedTokens)} tokens via ${compaction.type}]`, options.columns);\n }\n\n const route = status.provider && status.model ? `${status.provider}:${status.model}` : \"no route\";\n const step = status.routeStep ?? \"unknown\";\n const tools = `${status.activeTools.length} tool${status.activeTools.length === 1 ? \"\" : \"s\"}`;\n const children = `${status.activeChildren.length} child${status.activeChildren.length === 1 ? \"\" : \"ren\"}`;\n const context = status.contextPressure ? ` | ctx ${compactTokenCount(status.contextPressure.used)}/${compactTokenCount(status.contextPressure.cap)}` : \"\";\n return fitLine(`[${route} | ${step} | ${formatUsd(status.spend.usd)} | ${tools} | ${children}${context}]`, options.columns);\n}\n\nexport function createLiveStatusRenderer(options: {\n stream?: NodeJS.WritableStream;\n env?: Record<string, string | undefined>;\n now?: () => Date;\n columns?: number;\n} = {}): LiveStatusRenderer {\n const stream = options.stream ?? process.stdout;\n const now = options.now ?? (() => new Date());\n const status = createLiveStatus({\n now,\n estimateUsd: (provider, model, inputTokens, outputTokens) => estimateRunCost({\n provider,\n model,\n promptTokens: inputTokens,\n completionTokens: outputTokens,\n }).usd ?? 0,\n });\n\n function enabled(): boolean {\n return liveStatusEnabled({\n stream,\n ...(options.env ? { env: options.env } : {}),\n });\n }\n\n function render(): void {\n if (!enabled()) return;\n const columns = options.columns ?? terminalColumns(stream);\n const line = formatLiveStatus(status.snapshot(), { now: now(), columns });\n // Escape sequences are guarded by liveStatusEnabled(), which requires a TTY.\n stream.write(`\\x1b7\\r\\x1b[2K${line}\\x1b8`);\n }\n\n return {\n consume(event) {\n status.consume(event);\n if (shouldRenderLiveStatus(event)) render();\n },\n render,\n snapshot: status.snapshot,\n enabled,\n };\n}\n\nexport function liveStatusEnabled(options: {\n stream?: NodeJS.WritableStream;\n env?: Record<string, string | undefined>;\n} = {}): boolean {\n const stream = options.stream ?? process.stdout;\n if ((stream as { isTTY?: boolean }).isTTY !== true) return false;\n const raw = envValue(options.env ?? process.env, \"TANYA_LIVE_STATUS\").trim();\n return !/^(0|false|off|no)$/i.test(raw);\n}\n\nfunction shouldRenderLiveStatus(event: TanyaEvent): boolean {\n return ![\n \"message_start\",\n \"message_delta\",\n \"tool_progress\",\n \"command_invoked\",\n ].includes(event.type);\n}\n\nfunction withinWindow(iso: string, now: Date, windowMs: number): boolean {\n const ts = Date.parse(iso);\n return Number.isFinite(ts) && now.getTime() - ts <= windowMs;\n}\n\nfunction terminalColumns(stream: NodeJS.WritableStream): number {\n const columns = (stream as { columns?: number }).columns;\n return typeof columns === \"number\" && Number.isFinite(columns) && columns > 0 ? columns : 80;\n}\n\nfunction fitLine(line: string, columns = 80): string {\n const width = Math.max(20, columns);\n if (line.length <= width) return line;\n return `${line.slice(0, Math.max(0, width - 3))}...`;\n}\n\nfunction compactTokenCount(tokens: number): string {\n if (tokens >= 1_000_000) return `${Math.round(tokens / 100_000) / 10}m`;\n if (tokens >= 1_000) return `${Math.round(tokens / 100) / 10}k`;\n return `${Math.max(0, Math.round(tokens))}`;\n}\n\nfunction formatUsd(usd: number): string {\n if (usd > 0 && usd < 0.001) return \"<$0.001\";\n return `$${usd.toFixed(3)}`;\n}\n","import type { EventSink } from \"../events/types\";\nimport { runIdDepth } from \"../agent/subAgentContext\";\nimport { createLiveStatusRenderer, type LiveStatusRenderer } from \"./liveStatus\";\nimport { envValue } from \"../config/envCompat\";\nimport { formatClock, formatElapsed } from \"../utils/formatElapsed\";\n\nconst toolGlyph = \">\";\nconst ansiDimItalic = \"\\x1b[2m\\x1b[3m\";\nconst ansiReset = \"\\x1b[0m\";\nconst reasoningPreviewLimit = 600;\n\nfunction eventPrefix(event: { subRunId?: string }): string {\n if (!event.subRunId) return \"\";\n return `${\" \".repeat(Math.max(0, runIdDepth(event.subRunId) - 1))}↳ `;\n}\n\nexport function createHumanSink(stream: NodeJS.WritableStream = process.stdout, options: {\n liveStatus?: boolean;\n env?: Record<string, string | undefined>;\n now?: () => Date;\n columns?: number;\n} = {}): EventSink {\n let inMessage = false;\n let messageHasText = false;\n let reasoningStartedAt: number | null = null;\n let reasoningChars = 0;\n let reasoningCollapsed = false;\n const hideReasoning = /^(1|true|yes|on)$/i.test(envValue(options.env ?? process.env, \"TANYA_HIDE_REASONING\").trim());\n const liveStatus: LiveStatusRenderer | null = options.liveStatus\n ? createLiveStatusRenderer({\n stream,\n ...(options.env ? { env: options.env } : {}),\n ...(options.now ? { now: options.now } : {}),\n ...(options.columns !== undefined ? { columns: options.columns } : {}),\n })\n : null;\n\n function finishReasoning(prefix: string): void {\n if (reasoningStartedAt === null || hideReasoning) return;\n const seconds = (Date.now() - reasoningStartedAt) / 1000;\n stream.write(`\\n${prefix}${ansiDimItalic}thinking for ${seconds.toFixed(1)}s...${ansiReset}\\n`);\n reasoningStartedAt = null;\n reasoningChars = 0;\n reasoningCollapsed = false;\n }\n\n const sink: EventSink = (event) => {\n const prefix = eventPrefix(event);\n switch (event.type) {\n case \"status\":\n stream.write(`\\n${prefix}${event.message}\\n`);\n break;\n case \"message_start\":\n inMessage = true;\n messageHasText = false;\n reasoningStartedAt = null;\n reasoningChars = 0;\n reasoningCollapsed = false;\n stream.write(`\\n${prefix}${\n event.headingStartedAt !== undefined ? `[${formatClock(new Date(event.headingStartedAt))}] ` : \"\"\n }${event.elapsedMs !== undefined ? `Tanya · ${formatElapsed(event.elapsedMs)}:` : \"Tanya:\"} `);\n break;\n case \"message_delta\":\n if (reasoningStartedAt !== null) finishReasoning(prefix);\n messageHasText = true;\n stream.write(event.text);\n break;\n case \"message_end\":\n finishReasoning(prefix);\n if (inMessage) stream.write(\"\\n\");\n inMessage = false;\n messageHasText = false;\n break;\n case \"reasoning_chunk\":\n if (hideReasoning) break;\n stream.write(ansiDimItalic);\n if (reasoningStartedAt === null) {\n reasoningStartedAt = Date.now();\n if (inMessage && !messageHasText) {\n stream.write(\"thinking... \");\n } else {\n stream.write(`\\n${prefix}thinking... `);\n }\n }\n reasoningChars += event.content.length;\n if (reasoningChars <= reasoningPreviewLimit) {\n stream.write(event.content);\n } else if (!reasoningCollapsed) {\n stream.write(\" ...\");\n reasoningCollapsed = true;\n }\n stream.write(ansiReset);\n break;\n case \"reasoning_truncated\":\n if (inMessage) stream.write(\"\\n\");\n inMessage = false;\n stream.write(`${prefix}[reasoning truncated at ${event.capTokens} tokens; used ${event.usedTokens}]\\n`);\n break;\n case \"tool_call\":\n finishReasoning(prefix);\n if (inMessage) stream.write(\"\\n\");\n inMessage = false;\n stream.write(`\\n${prefix}${toolGlyph} ${event.tool}\\n`);\n stream.write(`${prefix} input: ${JSON.stringify(event.input)}\\n`);\n break;\n case \"tool_result\":\n stream.write(`${prefix} ${event.ok ? \"ok\" : \"error\"}: ${event.summary}\\n`);\n break;\n case \"tool_progress\":\n finishReasoning(prefix);\n if (inMessage) stream.write(\"\\n\");\n inMessage = false;\n stream.write(`${prefix} ${event.stream}: ${event.chunk}${event.chunk.endsWith(\"\\n\") ? \"\" : \"\\n\"}`);\n break;\n case \"tool_cancel_requested\":\n stream.write(`${prefix} cancelling: ${event.tool ?? event.toolCallId}\\n`);\n break;\n case \"tool_cancelled\":\n stream.write(`${prefix} cancelled: ${event.tool ?? event.toolCallId}\\n`);\n break;\n case \"permission_request\":\n stream.write(` permission requested: ${event.tool}${event.matchedRule ? ` (${event.matchedRule})` : \"\"}\\n`);\n break;\n case \"permission_decision\":\n stream.write(` permission ${event.decision}: ${event.matchedRule ?? event.source}\\n`);\n break;\n case \"command_invoked\":\n break;\n case \"tool_call_parse_warning\":\n stream.write(` warning: malformed tool call (${event.reason})\\n`);\n break;\n case \"schema_flatten_warning\":\n stream.write(` warning: flattened schema${event.tool ? ` for ${event.tool}` : \"\"} (${event.reason})\\n`);\n break;\n case \"provider_throttle\":\n stream.write(`\\nProvider ${event.provider} throttled; waiting ${Math.ceil(event.waitMs / 1000)}s before retry ${event.attempt}.\\n`);\n break;\n case \"model_routed\":\n stream.write(`${prefix} route: ${event.stepType} -> ${event.provider}/${event.model}${event.cacheImpact === \"miss\" ? \" (cache miss)\" : \"\"}\\n`);\n break;\n case \"escalation_event\":\n stream.write(`${prefix} escalation: ${event.from.provider}/${event.from.model} -> ${event.to.provider}/${event.to.model} (${event.reason})\\n`);\n break;\n case \"compact_event\":\n finishReasoning(prefix);\n if (inMessage) stream.write(\"\\n\");\n inMessage = false;\n stream.write(`[compaction: removed ~${Math.ceil(event.removedTokens / 1000)}k tokens via ${event.compactType}]\\n`);\n break;\n case \"prompt_budget_exceeded\":\n finishReasoning(prefix);\n if (inMessage) stream.write(\"\\n\");\n inMessage = false;\n stream.write(`${prefix}[prompt budget: dropped ${event.droppedSections.join(\", \")}; ${event.totalTokens} tokens > cap ${event.cap}]\\n`);\n break;\n case \"subtask_started\":\n finishReasoning(prefix);\n if (inMessage) stream.write(\"\\n\");\n inMessage = false;\n stream.write(`\\n${prefix}subtask started: ${event.subRunId} (${event.workspace})\\n`);\n break;\n case \"subtask_completed\":\n finishReasoning(prefix);\n if (inMessage) stream.write(\"\\n\");\n inMessage = false;\n stream.write(`${prefix}subtask ${event.verdict}: ${event.summary}\\n`);\n break;\n case \"subtask_start\":\n if (inMessage) stream.write(\"\\n\");\n inMessage = false;\n stream.write(`\\nSubtask ${event.subtask_id}: ${event.title}\\n`);\n if (event.files.length) stream.write(` files: ${event.files.join(\", \")}\\n`);\n break;\n case \"subtask_done\":\n stream.write(` ${event.ok ? \"done\" : \"failed\"}: ${event.summary}\\n`);\n break;\n case \"final\":\n if (!event.suppressHumanMessage) {\n stream.write(`\\n${event.message.trim()}\\n`);\n }\n if (event.files?.length) stream.write(`Files: ${event.files.join(\", \")}\\n`);\n break;\n case \"error\":\n stream.write(`\\nError: ${event.message}${event.detail ? `\\n${event.detail}` : \"\"}\\n`);\n break;\n default:\n break;\n }\n liveStatus?.consume(event);\n };\n (sink as EventSink & { tanyaSinkKind?: \"human\" }).tanyaSinkKind = \"human\";\n return sink;\n}\n","import { existsSync } from \"node:fs\";\nimport { mkdir, readFile, readdir, rm, writeFile } from \"node:fs/promises\";\nimport { dirname, isAbsolute, join, resolve } from \"node:path\";\nimport { spawn, spawnSync } from \"node:child_process\";\nimport sharp from \"sharp\";\nimport { envValue } from \"../config/envCompat\";\nimport { resolveInsideWorkspace } from \"../safety/workspace\";\n\ntype LayerAnimation = \"fade-up\" | \"type-in\" | \"scale-in\" | \"hold\" | \"fade-in\" | \"slide-up\" | \"subtle-parallax\";\ntype SceneTransition = \"cut\" | \"crossfade\" | \"slide-left\" | \"slide-up\" | \"push\";\n\nexport interface FullAdRenderSpec {\n version: 1;\n canvas: {\n width: number;\n height: number;\n fps: number;\n safeArea?: { x: number; y: number; width: number; height: number };\n };\n project?: { id: string; name: string; appName: string; platform: string };\n brand?: {\n primary: string;\n secondary: string;\n accent: string;\n background: string;\n iconAssetId?: string;\n };\n assets: Array<{\n id: string;\n type: \"image\" | \"gif\" | \"video\";\n mimeType: string;\n src: string;\n width?: number;\n height?: number;\n durationMs?: number | null;\n }>;\n scenes: FullAdSceneSpec[];\n}\n\nexport interface FullAdSceneSpec {\n id: string;\n order: number;\n durationMs: number;\n backgroundPreset: string;\n backgroundAssetId?: string;\n layoutPreset?: string;\n transition: SceneTransition;\n layers: FullAdLayerSpec[];\n}\n\nexport type FullAdLayerSpec = FullAdTextLayerSpec | FullAdMediaLayerSpec;\n\nexport interface FullAdBaseLayerSpec {\n id: string;\n x: number;\n y: number;\n width: number;\n height: number;\n zIndex: number;\n startTimeMs: number;\n endTimeMs: number | null;\n opacity: number;\n}\n\nexport interface FullAdTextLayerSpec extends FullAdBaseLayerSpec {\n type: \"text\";\n text: string;\n role: \"title\" | \"subtitle\" | \"caption\" | \"cta\" | \"badge\";\n color: string;\n fontSize: number;\n fontWeight: number;\n align: \"center\";\n animation: LayerAnimation;\n}\n\nexport interface FullAdMediaLayerSpec extends FullAdBaseLayerSpec {\n type: \"image\" | \"video\";\n assetId: string;\n fit: \"cover\" | \"contain\" | \"fill\";\n borderRadius: number;\n shadow: boolean;\n animation: LayerAnimation;\n}\n\nexport interface RenderAdOptions {\n input: string;\n outputDir?: string;\n basename?: string;\n formats?: Array<\"mp4\" | \"poster\">;\n ffmpegPath?: string;\n}\n\nexport interface RenderAdResult {\n mp4Path?: string;\n posterPath?: string;\n durationMs: number;\n frameCount: number;\n width: number;\n height: number;\n warnings: string[];\n renderSpec: FullAdRenderSpec;\n}\n\ninterface MediaFrames {\n frames: Buffer[];\n fps: number;\n}\n\nfunction findExecutable(name: string, explicit?: string): string {\n if (explicit) return explicit;\n const result = spawnSync(\"which\", [name], { encoding: \"utf8\" });\n return result.status === 0 && result.stdout.trim() ? result.stdout.trim() : name;\n}\n\nfunction run(command: string, args: string[], cwd: string): void {\n const result = spawnSync(command, args, { cwd, stdio: \"pipe\", encoding: \"utf8\" });\n if (result.status !== 0) {\n throw new Error(`${command} ${args.join(\" \")}\\n${result.stderr || result.stdout}`);\n }\n}\n\nfunction easeOut(t: number): number {\n const v = Math.max(0, Math.min(1, t));\n return 1 - Math.pow(1 - v, 3);\n}\n\nconst SCENE_TRANSITION_DURATION_MS = 560;\nconst SCENE_TRANSITION_TRAVEL_PX = 52;\n\nfunction escapeXml(value: string): string {\n return value.replaceAll(\"&\", \"&\").replaceAll(\"<\", \"<\").replaceAll(\">\", \">\").replaceAll('\"', \""\");\n}\n\nfunction backgroundColor(preset: string): string {\n if (preset === \"solid-light\") return \"#f5f5f7\";\n if (preset === \"gradient-brand\") return \"#101628\";\n if (preset === \"gradient-dark\") return \"#10111d\";\n if (preset === \"blur-asset\") return \"#0a0a0c\";\n return \"#0a0a0c\";\n}\n\nfunction renderBrand(spec: FullAdRenderSpec): Required<NonNullable<FullAdRenderSpec[\"brand\"]>> {\n return {\n primary: spec.brand?.primary ?? \"#8C4CEB\",\n secondary: spec.brand?.secondary ?? \"#6B33CC\",\n accent: spec.brand?.accent ?? \"#F59E0B\",\n background: spec.brand?.background ?? \"#080A12\",\n iconAssetId: spec.brand?.iconAssetId ?? \"\",\n };\n}\n\nfunction backgroundSvg(spec: FullAdRenderSpec, scene: FullAdSceneSpec): Buffer {\n const { width, height } = spec.canvas;\n const brand = renderBrand(spec);\n const base = scene.backgroundPreset === \"gradient-brand\" ? brand.background : backgroundColor(scene.backgroundPreset);\n const brandGlow = scene.backgroundPreset === \"gradient-brand\" ? brand.primary : \"#4f8eff\";\n const secondaryGlow = scene.backgroundPreset === \"gradient-brand\" ? brand.secondary : brandGlow;\n const warmGlow = scene.backgroundPreset === \"gradient-brand\" ? brand.accent : \"#f59e0b\";\n const svg = `<svg width=\"${width}\" height=\"${height}\" xmlns=\"http://www.w3.org/2000/svg\">\n <defs>\n <radialGradient id=\"g1\" cx=\"28%\" cy=\"12%\" r=\"64%\">\n <stop offset=\"0%\" stop-color=\"${brandGlow}\" stop-opacity=\"0.34\"/>\n <stop offset=\"54%\" stop-color=\"${brandGlow}\" stop-opacity=\"0.08\"/>\n <stop offset=\"100%\" stop-color=\"${base}\" stop-opacity=\"0\"/>\n </radialGradient>\n <radialGradient id=\"g2\" cx=\"88%\" cy=\"86%\" r=\"54%\">\n <stop offset=\"0%\" stop-color=\"${warmGlow}\" stop-opacity=\"0.18\"/>\n <stop offset=\"100%\" stop-color=\"${base}\" stop-opacity=\"0\"/>\n </radialGradient>\n <radialGradient id=\"g3\" cx=\"50%\" cy=\"42%\" r=\"58%\">\n <stop offset=\"0%\" stop-color=\"${secondaryGlow}\" stop-opacity=\"${scene.backgroundPreset === \"gradient-brand\" ? \"0.2\" : \"0.06\"}\"/>\n <stop offset=\"100%\" stop-color=\"${base}\" stop-opacity=\"0\"/>\n </radialGradient>\n <linearGradient id=\"v\" x1=\"0\" y1=\"0\" x2=\"0\" y2=\"1\">\n <stop offset=\"0%\" stop-color=\"#ffffff\" stop-opacity=\"0.04\"/>\n <stop offset=\"46%\" stop-color=\"#000000\" stop-opacity=\"0\"/>\n <stop offset=\"100%\" stop-color=\"#000000\" stop-opacity=\"0.28\"/>\n </linearGradient>\n </defs>\n <rect width=\"100%\" height=\"100%\" fill=\"${base}\"/>\n <rect width=\"100%\" height=\"100%\" fill=\"url(#g1)\"/>\n <rect width=\"100%\" height=\"100%\" fill=\"url(#g2)\"/>\n <rect width=\"100%\" height=\"100%\" fill=\"url(#g3)\"/>\n <rect width=\"100%\" height=\"100%\" fill=\"url(#v)\"/>\n </svg>`;\n return Buffer.from(svg);\n}\n\nfunction resolveAssetPath(src: string, workspace: string): string {\n if (src.startsWith(\"file://\")) return new URL(src).pathname;\n if (isAbsolute(src)) return src;\n return resolveInsideWorkspace(workspace, src);\n}\n\nasync function loadStaticFrame(src: string, workspace: string): Promise<Buffer> {\n if (src.startsWith(\"data:\")) {\n return Buffer.from(src.split(\",\")[1] ?? \"\", \"base64\");\n }\n if (src.startsWith(\"http://\") || src.startsWith(\"https://\")) {\n const response = await fetch(src);\n if (!response.ok) throw new Error(`Unable to fetch asset ${src}: ${response.status}`);\n return Buffer.from(await response.arrayBuffer());\n }\n return readFile(resolveAssetPath(src, workspace));\n}\n\nasync function extractVideoFrames(params: {\n src: string;\n workspace: string;\n outDir: string;\n fps: number;\n ffmpegPath: string;\n}): Promise<Buffer[]> {\n await mkdir(params.outDir, { recursive: true });\n const input = resolveAssetPath(params.src, params.workspace);\n run(params.ffmpegPath, [\n \"-y\",\n \"-i\",\n input,\n \"-vf\",\n `fps=${params.fps}`,\n join(params.outDir, \"frame-%05d.png\"),\n ], params.workspace);\n const files = (await readdir(params.outDir)).filter((file) => file.endsWith(\".png\")).sort();\n return Promise.all(files.map((file) => readFile(join(params.outDir, file))));\n}\n\nasync function buildMediaFrames(spec: FullAdRenderSpec, workspace: string, tmpDir: string, ffmpegPath: string, warnings: string[]): Promise<Map<string, MediaFrames>> {\n const media = new Map<string, MediaFrames>();\n for (const asset of spec.assets) {\n try {\n if (asset.type === \"video\" || asset.type === \"gif\") {\n const frames = await extractVideoFrames({\n src: asset.src,\n workspace,\n outDir: join(tmpDir, \"media\", asset.id),\n fps: spec.canvas.fps,\n ffmpegPath,\n });\n media.set(asset.id, { frames: frames.length ? frames : [await sharp(await loadStaticFrame(asset.src, workspace)).png().toBuffer()], fps: spec.canvas.fps });\n } else {\n media.set(asset.id, { frames: [await sharp(await loadStaticFrame(asset.src, workspace)).png().toBuffer()], fps: 1 });\n }\n } catch (error) {\n warnings.push(`Asset ${asset.id} could not be decoded: ${error instanceof Error ? error.message : String(error)}`);\n }\n }\n return media;\n}\n\nfunction wrapText(text: string, maxChars: number, maxLines = 4): string[] {\n const words = text.trim().split(/\\s+/).filter(Boolean);\n const lines: string[] = [];\n let current = \"\";\n for (const word of words) {\n const next = current ? `${current} ${word}` : word;\n if (next.length > maxChars && current) {\n lines.push(current);\n current = word;\n } else {\n current = next;\n }\n }\n if (current) lines.push(current);\n return lines.slice(0, maxLines);\n}\n\nfunction renderTextSvg(layer: FullAdTextLayerSpec, progress: number, brand?: FullAdRenderSpec[\"brand\"]): Buffer {\n const resolvedBrand = {\n primary: brand?.primary ?? \"#8C4CEB\",\n secondary: brand?.secondary ?? \"#6B33CC\",\n accent: brand?.accent ?? \"#F59E0B\",\n };\n const visibleChars = layer.animation === \"type-in\"\n ? Math.max(1, Math.ceil(layer.text.length * easeOut(progress)))\n : layer.text.length;\n const text = layer.text.slice(0, visibleChars);\n const maxChars = Math.max(8, Math.floor(layer.width / Math.max(12, layer.fontSize * 0.55)));\n const maxLines = layer.role === \"badge\" ? 6 : 4;\n const lines = wrapText(text, maxChars, maxLines);\n const fontSize = Math.max(24, Math.min(layer.fontSize, Math.floor(layer.height / Math.max(1.4, lines.length * 1.18))));\n const lineHeight = Math.round(fontSize * 1.16);\n const startY = Math.round((layer.height - lineHeight * lines.length) / 2 + fontSize * 0.88);\n const tspans = lines.map((line, index) =>\n `<tspan x=\"50%\" y=\"${startY + index * lineHeight}\">${escapeXml(line)}</tspan>`,\n ).join(\"\");\n const glowOpacity = layer.role === \"title\" || layer.role === \"cta\" ? 0.28 : 0.12;\n const chrome = layer.role === \"cta\"\n ? `<linearGradient id=\"ctaFill\" x1=\"0\" y1=\"0\" x2=\"1\" y2=\"1\">\n <stop offset=\"0%\" stop-color=\"${resolvedBrand.primary}\"/>\n <stop offset=\"100%\" stop-color=\"${resolvedBrand.secondary}\"/>\n </linearGradient>`\n : layer.role === \"badge\" || layer.role === \"caption\"\n ? `<linearGradient id=\"badgeFill\" x1=\"0\" y1=\"0\" x2=\"1\" y2=\"0\">\n <stop offset=\"0%\" stop-color=\"${resolvedBrand.accent}\" stop-opacity=\"0.2\"/>\n <stop offset=\"100%\" stop-color=\"${resolvedBrand.primary}\" stop-opacity=\"0.14\"/>\n </linearGradient>`\n : \"\";\n const rect = layer.role === \"cta\"\n ? `<rect x=\"2\" y=\"2\" width=\"${Math.round(layer.width) - 4}\" height=\"${Math.round(layer.height) - 4}\" rx=\"${Math.round(layer.height / 2)}\" fill=\"url(#ctaFill)\" stroke=\"rgba(255,255,255,0.22)\" stroke-width=\"2\"/>`\n : layer.role === \"badge\" || layer.role === \"caption\"\n ? `<rect x=\"2\" y=\"6\" width=\"${Math.round(layer.width) - 4}\" height=\"${Math.round(layer.height) - 12}\" rx=\"${Math.round((layer.height - 12) / 2)}\" fill=\"url(#badgeFill)\" stroke=\"${resolvedBrand.accent}\" stroke-opacity=\"0.34\" stroke-width=\"1.5\"/>`\n : \"\";\n const svg = `<svg width=\"${Math.round(layer.width)}\" height=\"${Math.round(layer.height)}\" xmlns=\"http://www.w3.org/2000/svg\">\n <defs>\n ${chrome}\n <filter id=\"softShadow\" x=\"-20%\" y=\"-20%\" width=\"140%\" height=\"160%\">\n <feDropShadow dx=\"0\" dy=\"10\" stdDeviation=\"10\" flood-color=\"#000000\" flood-opacity=\"${glowOpacity}\"/>\n </filter>\n </defs>\n ${rect}\n <text text-anchor=\"middle\" font-family=\"-apple-system, BlinkMacSystemFont, Inter, Helvetica, Arial, sans-serif\"\n font-size=\"${fontSize}\" font-weight=\"${layer.fontWeight}\" fill=\"${escapeXml(layer.color)}\" filter=\"url(#softShadow)\">${tspans}</text>\n </svg>`;\n return Buffer.from(svg);\n}\n\nasync function roundedMask(width: number, height: number, radius: number): Promise<Buffer> {\n const r = Math.max(0, Math.min(radius, Math.floor(Math.min(width, height) / 2)));\n return Buffer.from(`<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"${width}\" height=\"${height}\"><rect width=\"${width}\" height=\"${height}\" rx=\"${r}\" fill=\"#fff\"/></svg>`);\n}\n\nasync function renderMediaLayer(layer: FullAdMediaLayerSpec, frame: Buffer): Promise<Buffer> {\n const width = Math.max(1, Math.round(layer.width));\n const height = Math.max(1, Math.round(layer.height));\n const resized = sharp(frame)\n .resize(width, height, {\n fit: layer.fit === \"contain\" ? \"inside\" : layer.fit === \"fill\" ? \"fill\" : \"cover\",\n position: \"center\",\n background: { r: 0, g: 0, b: 0, alpha: 0 },\n })\n .ensureAlpha();\n const png = await resized.png().toBuffer();\n if (!layer.borderRadius) return png;\n return sharp(png).composite([{ input: await roundedMask(width, height, layer.borderRadius), blend: \"dest-in\" }]).png().toBuffer();\n}\n\nasync function shadowLayer(width: number, height: number, radius: number): Promise<Buffer> {\n const mask = await roundedMask(width, height, radius);\n return sharp({\n create: {\n width,\n height,\n channels: 4,\n background: { r: 0, g: 0, b: 0, alpha: 0.52 },\n },\n })\n .composite([{ input: mask, blend: \"dest-in\" }])\n .blur(18)\n .extend({ top: 24, bottom: 24, left: 24, right: 24, background: { r: 0, g: 0, b: 0, alpha: 0 } })\n .png()\n .toBuffer();\n}\n\nasync function scaleOverlay(input: Buffer, scale: number): Promise<{ input: Buffer; dx: number; dy: number }> {\n if (Math.abs(scale - 1) < 0.001) return { input, dx: 0, dy: 0 };\n const meta = await sharp(input).metadata();\n const width = Math.max(1, Math.round((meta.width ?? 1) * scale));\n const height = Math.max(1, Math.round((meta.height ?? 1) * scale));\n return {\n input: await sharp(input).resize(width, height).png().toBuffer(),\n dx: Math.round(((meta.width ?? width) - width) / 2),\n dy: Math.round(((meta.height ?? height) - height) / 2),\n };\n}\n\nfunction layerTransform(layer: FullAdLayerSpec, localMs: number): { opacity: number; dx: number; dy: number; scale: number } {\n const progress = easeOut((localMs - layer.startTimeMs) / 360);\n const baseOpacity = layer.opacity ?? 1;\n if (layer.animation === \"hold\") return { opacity: baseOpacity, dx: 0, dy: 0, scale: 1 };\n if (layer.animation === \"fade-up\" || layer.animation === \"slide-up\") {\n return { opacity: baseOpacity * progress, dx: 0, dy: (1 - progress) * 34, scale: 1 };\n }\n if (layer.animation === \"scale-in\") {\n return { opacity: baseOpacity * progress, dx: 0, dy: 0, scale: 0.965 + progress * 0.035 };\n }\n if (layer.animation === \"subtle-parallax\") {\n return { opacity: baseOpacity * progress, dx: 0, dy: Math.sin(localMs / 1000) * 8, scale: 1.02 };\n }\n return { opacity: baseOpacity * progress, dx: 0, dy: 0, scale: 1 };\n}\n\nfunction sceneTransform(scene: FullAdSceneSpec, localMs: number): { opacity: number; dx: number; dy: number; scale: number } {\n const progress = easeOut(localMs / SCENE_TRANSITION_DURATION_MS);\n if (scene.transition === \"cut\") return { opacity: 1, dx: 0, dy: 0, scale: 1 };\n if (scene.transition === \"slide-left\" || scene.transition === \"push\") return { opacity: 1, dx: (1 - progress) * SCENE_TRANSITION_TRAVEL_PX, dy: 0, scale: 1 };\n if (scene.transition === \"slide-up\") return { opacity: 1, dx: 0, dy: (1 - progress) * SCENE_TRANSITION_TRAVEL_PX, scale: 1 };\n return { opacity: progress, dx: 0, dy: 0, scale: 1 };\n}\n\nasync function renderFrame(spec: FullAdRenderSpec, scene: FullAdSceneSpec, mediaFrames: Map<string, MediaFrames>, frameInScene: number): Promise<Buffer> {\n const fps = spec.canvas.fps;\n const localMs = (frameInScene / fps) * 1000;\n const sceneFx = sceneTransform(scene, localMs);\n const overlays: sharp.OverlayOptions[] = [];\n const sorted = [...scene.layers].sort((a, b) => a.zIndex - b.zIndex);\n for (const layer of sorted) {\n const end = layer.endTimeMs ?? scene.durationMs;\n if (localMs < layer.startTimeMs || localMs >= end) continue;\n const fx = layerTransform(layer, localMs);\n const opacity = Math.max(0, Math.min(1, fx.opacity * sceneFx.opacity));\n if (opacity <= 0.001) continue;\n if (layer.type === \"text\") {\n let textPng = await sharp(renderTextSvg(layer, (localMs - layer.startTimeMs) / 520, spec.brand)).png().toBuffer();\n const scaled = await scaleOverlay(textPng, fx.scale * sceneFx.scale);\n textPng = scaled.input;\n if (opacity < 0.999) textPng = await sharp(textPng).linear(opacity, 0).png().toBuffer();\n overlays.push({\n input: textPng,\n left: Math.round(layer.x + fx.dx + sceneFx.dx + scaled.dx),\n top: Math.round(layer.y + fx.dy + sceneFx.dy + scaled.dy),\n });\n continue;\n }\n const frames = mediaFrames.get(layer.assetId);\n if (!frames?.frames.length) continue;\n const elapsed = Math.max(0, localMs - layer.startTimeMs);\n const sourceIndex = frames.frames.length === 1\n ? 0\n : Math.floor((elapsed / 1000) * frames.fps) % frames.frames.length;\n let mediaPng = await renderMediaLayer(layer, frames.frames[sourceIndex]!);\n const scaled = await scaleOverlay(mediaPng, fx.scale * sceneFx.scale);\n mediaPng = scaled.input;\n if (opacity < 0.999) mediaPng = await sharp(mediaPng).linear(opacity, 0).png().toBuffer();\n if (layer.shadow) {\n const shadow = await shadowLayer(Math.round(layer.width), Math.round(layer.height), layer.borderRadius);\n const scaledShadow = await scaleOverlay(shadow, fx.scale * sceneFx.scale);\n overlays.push({\n input: scaledShadow.input,\n left: Math.round(layer.x + fx.dx + sceneFx.dx + scaled.dx - 24 + scaledShadow.dx),\n top: Math.round(layer.y + fx.dy + sceneFx.dy + scaled.dy - 2 + scaledShadow.dy),\n });\n }\n overlays.push({\n input: mediaPng,\n left: Math.round(layer.x + fx.dx + sceneFx.dx + scaled.dx),\n top: Math.round(layer.y + fx.dy + sceneFx.dy + scaled.dy),\n });\n }\n\n const backgroundFrame = scene.backgroundAssetId ? mediaFrames.get(scene.backgroundAssetId)?.frames[0] : null;\n let image = backgroundFrame\n ? sharp(backgroundFrame).resize(spec.canvas.width, spec.canvas.height, { fit: \"cover\" })\n : sharp(backgroundSvg(spec, scene));\n if (overlays.length) image = image.composite(overlays);\n return image.png({ compressionLevel: 1 }).toBuffer();\n}\n\nfunction parseSpec(value: unknown): FullAdRenderSpec {\n const spec = value as FullAdRenderSpec;\n if (!spec || spec.version !== 1 || !spec.canvas || !Array.isArray(spec.scenes) || !Array.isArray(spec.assets)) {\n throw new Error(\"Invalid full-ad render spec.\");\n }\n if (spec.canvas.width !== 1080 || spec.canvas.height !== 1920) {\n throw new Error(\"Full-ad render spec must use a 1080x1920 canvas.\");\n }\n if (!Number.isFinite(spec.canvas.fps) || spec.canvas.fps < 1 || spec.canvas.fps > 60) {\n throw new Error(\"Full-ad render spec fps must be between 1 and 60.\");\n }\n return spec;\n}\n\nexport async function renderFullAd(options: RenderAdOptions, workspace: string): Promise<RenderAdResult> {\n const inputPath = isAbsolute(options.input) ? options.input : resolveInsideWorkspace(workspace, options.input);\n const spec = parseSpec(JSON.parse(await readFile(inputPath, \"utf8\")));\n const outputDir = resolveInsideWorkspace(workspace, options.outputDir ?? \"tanya-video-ads\");\n const basename = (options.basename ?? `full-ad-${Date.now()}`).replace(/[^a-zA-Z0-9._-]+/g, \"-\");\n const formats = options.formats?.length ? options.formats : [\"mp4\", \"poster\"];\n const ffmpegPath = findExecutable(\"ffmpeg\", options.ffmpegPath ?? envValue({}, \"TANYA_FFMPEG_PATH\"));\n const tmpRoot = resolveInsideWorkspace(workspace, \".tania/tmp\");\n const tmpDir = await fsMkdtemp(join(tmpRoot, \"tanya-render-ad-\"));\n const frameDir = join(tmpDir, \"frames\");\n const warnings: string[] = [];\n await mkdir(frameDir, { recursive: true });\n await mkdir(outputDir, { recursive: true });\n const mediaFrames = await buildMediaFrames(spec, workspace, tmpDir, ffmpegPath, warnings);\n\n let frameIndex = 0;\n const scenes = [...spec.scenes].sort((a, b) => a.order - b.order);\n for (const scene of scenes) {\n const frameCount = Math.max(1, Math.round((scene.durationMs / 1000) * spec.canvas.fps));\n for (let i = 0; i < frameCount; i += 1) {\n const frame = await renderFrame(spec, scene, mediaFrames, i);\n await writeFile(\n join(frameDir, `frame_${String(frameIndex).padStart(6, \"0\")}.jpg`),\n await sharp(frame).jpeg({ quality: 84, mozjpeg: true }).toBuffer(),\n );\n frameIndex += 1;\n }\n }\n\n const result: RenderAdResult = {\n durationMs: scenes.reduce((sum, scene) => sum + scene.durationMs, 0),\n frameCount: frameIndex,\n width: spec.canvas.width,\n height: spec.canvas.height,\n warnings,\n renderSpec: spec,\n };\n\n if (formats.includes(\"poster\")) {\n const posterPath = join(outputDir, `${basename}-poster.png`);\n await sharp(await readFile(join(frameDir, \"frame_000000.jpg\"))).png().toFile(posterPath);\n result.posterPath = posterPath;\n }\n\n if (formats.includes(\"mp4\")) {\n const mp4Path = join(outputDir, `${basename}.mp4`);\n run(ffmpegPath, [\n \"-y\",\n \"-framerate\",\n String(spec.canvas.fps),\n \"-i\",\n join(frameDir, \"frame_%06d.jpg\"),\n \"-c:v\",\n \"libx264\",\n \"-pix_fmt\",\n \"yuv420p\",\n \"-preset\",\n \"fast\",\n \"-crf\",\n \"23\",\n \"-movflags\",\n \"+faststart\",\n mp4Path,\n ], workspace);\n result.mp4Path = mp4Path;\n }\n\n await rm(tmpDir, { recursive: true, force: true }).catch(() => {});\n return result;\n}\n\nasync function fsMkdtemp(prefix: string): Promise<string> {\n const { mkdtemp } = await import(\"node:fs/promises\");\n await mkdir(dirname(prefix), { recursive: true });\n return mkdtemp(prefix);\n}\n","import { readFileSync } from \"node:fs\";\nimport { discoverIntegrationEntries } from \"../integrations/discovery\";\n\nexport type GoldenTaskProfile = {\n id: string;\n title: string;\n platform: \"ios\" | \"android\" | \"backend\" | \"cross-platform\";\n purpose: string;\n requiredCapabilities: string[];\n};\n\nexport type IntegrationGoldenProfilesFile =\n | GoldenTaskProfile\n | GoldenTaskProfile[]\n | { profiles: GoldenTaskProfile[] };\n\nconst profilePlatforms = new Set<GoldenTaskProfile[\"platform\"]>([\"ios\", \"android\", \"backend\", \"cross-platform\"]);\n\nfunction isStringArray(value: unknown): value is string[] {\n return Array.isArray(value) && value.every((item) => typeof item === \"string\");\n}\n\nfunction isGoldenTaskProfile(value: unknown): value is GoldenTaskProfile {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) return false;\n const profile = value as Record<string, unknown>;\n return typeof profile.id === \"string\" &&\n typeof profile.title === \"string\" &&\n typeof profile.platform === \"string\" &&\n profilePlatforms.has(profile.platform as GoldenTaskProfile[\"platform\"]) &&\n typeof profile.purpose === \"string\" &&\n isStringArray(profile.requiredCapabilities);\n}\n\nfunction readJson(path: string): unknown {\n try {\n return JSON.parse(readFileSync(path, \"utf8\"));\n } catch {\n return null;\n }\n}\n\nfunction parseIntegrationGoldenProfiles(path: string): GoldenTaskProfile[] {\n const parsed = readJson(path);\n const profiles = Array.isArray(parsed)\n ? parsed\n : parsed && typeof parsed === \"object\" && Array.isArray((parsed as { profiles?: unknown }).profiles)\n ? (parsed as { profiles: unknown[] }).profiles\n : [parsed];\n const valid = profiles.filter(isGoldenTaskProfile);\n if (valid.length !== profiles.length) {\n console.warn(`[golden] Skipping invalid integration profile data: ${path}`);\n }\n return valid;\n}\n\nexport const GENERIC_BENCHMARK_PROFILES: GoldenTaskProfile[] = [\n {\n id: \"tanya.low.search-replace\",\n title: \"Low - Targeted Search Replace\",\n platform: \"cross-platform\",\n purpose: \"Update one existing source file with a precise replacement and verify the marker.\",\n requiredCapabilities: [\"read before edit\", \"search_replace\", \"bounded verification\"],\n },\n {\n id: \"tanya.low.new-helper\",\n title: \"Low - New Helper File\",\n platform: \"cross-platform\",\n purpose: \"Create a small helper module and verify it exists with expected content.\",\n requiredCapabilities: [\"write_file\", \"final report\", \"bounded verification\"],\n },\n {\n id: \"tanya.low.config-update\",\n title: \"Low - Config Update\",\n platform: \"cross-platform\",\n purpose: \"Update a simple JSON-like config file without touching unrelated files.\",\n requiredCapabilities: [\"targeted edit\", \"changed-file reporting\", \"bounded verification\"],\n },\n {\n id: \"tanya.low.readme-update\",\n title: \"Low - README Update\",\n platform: \"cross-platform\",\n purpose: \"Append a concise documentation note and verify the note is present.\",\n requiredCapabilities: [\"documentation edit\", \"artifact reuse none\", \"bounded verification\"],\n },\n {\n id: \"tanya.low.package-script\",\n title: \"Low - Package Script\",\n platform: \"cross-platform\",\n purpose: \"Add a package script while preserving existing package metadata.\",\n requiredCapabilities: [\"JSON edit\", \"package script reporting\", \"bounded verification\"],\n },\n {\n id: \"tanya.medium.service-module\",\n title: \"Medium - Service Module\",\n platform: \"cross-platform\",\n purpose: \"Create a service module and matching index export in a small multi-file change.\",\n requiredCapabilities: [\"multi-file edit\", \"verification\", \"complete report\"],\n },\n {\n id: \"tanya.medium.test-harness\",\n title: \"Medium - Test Harness\",\n platform: \"cross-platform\",\n purpose: \"Add a tiny executable test harness and verify it runs.\",\n requiredCapabilities: [\"test file creation\", \"run_command\", \"complete report\"],\n },\n {\n id: \"tanya.medium.artifact-component\",\n title: \"Medium - Artifact Component\",\n platform: \"cross-platform\",\n purpose: \"Read a reusable UI artifact and adapt it into a project component.\",\n requiredCapabilities: [\"artifact read\", \"artifact provenance\", \"multi-file report\"],\n },\n {\n id: \"tanya.medium.artifact-service\",\n title: \"Medium - Artifact Service\",\n platform: \"backend\",\n purpose: \"Read a reusable service artifact and adapt it into a project helper.\",\n requiredCapabilities: [\"artifact read\", \"artifact provenance\", \"bounded verification\"],\n },\n {\n id: \"tanya.medium.dirty-worktree\",\n title: \"Medium - Dirty Worktree\",\n platform: \"cross-platform\",\n purpose: \"Complete a task in a repo that already has unrelated uncommitted changes.\",\n requiredCapabilities: [\"git snapshot\", \"unrelated dirty preservation\", \"final report\"],\n },\n {\n id: \"tanya.medium.report-repair\",\n title: \"Medium - Report Repair\",\n platform: \"cross-platform\",\n purpose: \"Recover when the model initially omits the required coding final report.\",\n requiredCapabilities: [\"final report reminder\", \"repair loop\", \"verification preservation\"],\n },\n {\n id: \"tanya.medium.multi-file\",\n title: \"Medium - Multi-File Feature\",\n platform: \"cross-platform\",\n purpose: \"Create coordinated source and docs changes and verify both outputs.\",\n requiredCapabilities: [\"multi-file edit\", \"changed-file reporting\", \"bounded verification\"],\n },\n {\n id: \"tanya.medium.package-manager\",\n title: \"Medium - Package Manager Script\",\n platform: \"cross-platform\",\n purpose: \"Use a workspace script path that also exercises post-check package-manager detection.\",\n requiredCapabilities: [\"package metadata\", \"script verification\", \"post-check readiness\"],\n },\n {\n id: \"tanya.medium.context-aware\",\n title: \"Medium - Context-Aware Edit\",\n platform: \"cross-platform\",\n purpose: \"Read caller context before editing and preserve that provenance in the run.\",\n requiredCapabilities: [\"context read\", \"context provenance\", \"complete report\"],\n },\n {\n id: \"tanya.medium.existing-tests\",\n title: \"Medium - Existing Tests\",\n platform: \"cross-platform\",\n purpose: \"Modify implementation while running an existing local verification script.\",\n requiredCapabilities: [\"existing test command\", \"verification reporting\", \"changed-file reporting\"],\n },\n {\n id: \"tanya.medium.dependency-install\",\n title: \"Medium - Dependency Install\",\n platform: \"cross-platform\",\n purpose: \"Update package metadata and lockfile-style state while verifying dependency intent without network access.\",\n requiredCapabilities: [\"package manifest update\", \"lockfile update\", \"bounded verification\"],\n },\n {\n id: \"tanya.medium.framework-migration\",\n title: \"Medium - Framework Migration\",\n platform: \"cross-platform\",\n purpose: \"Move a small legacy page into an app-router-style layout while preserving a compatibility entrypoint.\",\n requiredCapabilities: [\"framework convention\", \"multi-file migration\", \"changed-file reporting\"],\n },\n {\n id: \"tanya.medium.failing-test-repair\",\n title: \"Medium - Failing Test Repair\",\n platform: \"cross-platform\",\n purpose: \"Observe a failing verification, repair the implementation, and rerun the same check successfully.\",\n requiredCapabilities: [\"failed verification recovery\", \"targeted edit\", \"verification rerun\"],\n },\n {\n id: \"tanya.medium.frontend-smoke\",\n title: \"Medium - Frontend Smoke\",\n platform: \"cross-platform\",\n purpose: \"Create a minimal component, styles, and smoke check that verifies rendered content markers.\",\n requiredCapabilities: [\"frontend files\", \"visual smoke proxy\", \"bounded verification\"],\n },\n {\n id: \"tanya.medium.run-log-history\",\n title: \"Medium - Usage Metrics Run Log\",\n platform: \"cross-platform\",\n purpose: \"Complete a normal edit while emitting usage counts that should be persisted to .tania/runs.\",\n requiredCapabilities: [\"usage metrics\", \"run log persistence\", \"history visibility\"],\n },\n {\n id: \"tanya.medium.streaming-long-tool\",\n title: \"Medium - Streaming Long Tool\",\n platform: \"cross-platform\",\n purpose: \"Run a >10s shell verification that streams progress while preserving the final tool result contract.\",\n requiredCapabilities: [\"tool_progress\", \"long-running run_shell\", \"provider-history isolation\"],\n },\n {\n id: \"tanya.medium.compaction-boundary\",\n title: \"Medium - Compaction Boundary\",\n platform: \"cross-platform\",\n purpose: \"Recover from a synthetic context-window failure mid-run and preserve the final verifier verdict.\",\n requiredCapabilities: [\"ContextWindowExceededError\", \"auto-compact retry\", \"archive-backed verifier surface\"],\n },\n {\n id: \"tanya.medium.edit-block-fuzzy\",\n title: \"Medium - Fuzzy Edit Block\",\n platform: \"cross-platform\",\n purpose: \"Recover a cheap-provider-style near-match with permission-gated fuzzy edit blocks while preserving verifier verdicts.\",\n requiredCapabilities: [\"edit_block\", \"fuzzy recovery\", \"permission-gated edit\", \"verifier parity\"],\n },\n];\n\nexport const BUILT_IN_GOLDEN_TASK_PROFILES: GoldenTaskProfile[] = [\n ...GENERIC_BENCHMARK_PROFILES,\n];\n\nexport function loadIntegrationGoldenTaskProfiles(): GoldenTaskProfile[] {\n return discoverIntegrationEntries(\"golden\")\n .filter((entry) => entry.path.toLowerCase().endsWith(\".json\"))\n .flatMap((entry) => parseIntegrationGoldenProfiles(entry.path));\n}\n\nexport function loadGoldenTaskProfiles(): GoldenTaskProfile[] {\n const seen = new Set(BUILT_IN_GOLDEN_TASK_PROFILES.map((profile) => profile.id));\n const profiles = [...BUILT_IN_GOLDEN_TASK_PROFILES];\n for (const profile of loadIntegrationGoldenTaskProfiles()) {\n if (seen.has(profile.id)) continue;\n seen.add(profile.id);\n profiles.push(profile);\n }\n return profiles;\n}\n","import { execFile } from \"node:child_process\";\nimport { mkdtemp, mkdir, writeFile } from \"node:fs/promises\";\nimport { tmpdir } from \"node:os\";\nimport { join } from \"node:path\";\nimport { promisify } from \"node:util\";\nimport { runAgent } from \"../agent/runner\";\nimport type { TanyaRunContext } from \"../context/runContext\";\nimport type { TanyaEvent } from \"../events/types\";\nimport { ContextWindowExceededError, type ChatDelta, type ChatProvider, type ChatRequest, type ToolCall } from \"../providers/types\";\nimport { loadGoldenTaskProfiles, type GoldenTaskProfile } from \"./profiles\";\n\ntype GoldenTaskFixture = {\n workspace: string;\n prompt: string;\n runContext: TanyaRunContext;\n provider: ChatProvider;\n};\n\ntype GenericBenchmarkSpec = {\n id: string;\n targetFiles: Array<{ path: string; content: string }>;\n prompt: string;\n preFiles?: Array<{ path: string; content: string }>;\n useArtifact?: boolean;\n useContext?: boolean;\n useSearchReplace?: boolean;\n dirtyWorktree?: boolean;\n reportRepair?: boolean;\n preVerifyBeforeEdit?: boolean;\n usage?: { promptTokens: number; completionTokens: number };\n};\n\nexport type GoldenRunResult = {\n profile: GoldenTaskProfile;\n workspace: string;\n passed: boolean;\n finalText: string;\n problems: string[];\n turns: number;\n};\n\nfunction toolCall(id: string, name: string, args: unknown): ToolCall {\n return {\n id,\n type: \"function\",\n function: {\n name,\n arguments: JSON.stringify(args),\n },\n };\n}\n\nfunction scriptedProvider(id: string, turns: ChatDelta[]): ChatProvider & { requests: ChatRequest[] } {\n const requests: ChatRequest[] = [];\n return {\n id: `golden:${id}`,\n model: \"scripted\",\n requests,\n async *streamChat(input: ChatRequest) {\n requests.push({ ...input, messages: [...input.messages] });\n yield turns[Math.min(requests.length - 1, turns.length - 1)] ?? { content: \"\" };\n },\n };\n}\n\nconst execFileAsync = promisify(execFile);\n\nasync function createBaseWorkspace(profileId: string): Promise<string> {\n return mkdtemp(join(tmpdir(), `tanya-golden-${profileId.replace(/[^a-z0-9]+/gi, \"-\")}-`));\n}\n\nconst GENERIC_BENCHMARK_SPECS: Record<string, GenericBenchmarkSpec> = {\n \"tanya.low.search-replace\": {\n id: \"tanya.low.search-replace\",\n prompt: \"Replace the pending marker in an existing helper and verify it.\",\n useSearchReplace: true,\n targetFiles: [{ path: \"src/searchReplaceTarget.ts\", content: \"export const status = 'search-replace-ready';\\n\" }],\n },\n \"tanya.low.new-helper\": {\n id: \"tanya.low.new-helper\",\n prompt: \"Create a small helper file and verify it.\",\n targetFiles: [{ path: \"src/newHelper.ts\", content: \"export function newHelper() { return 'new-helper-ready'; }\\n\" }],\n },\n \"tanya.low.config-update\": {\n id: \"tanya.low.config-update\",\n prompt: \"Update a small config file with the requested marker.\",\n useSearchReplace: true,\n targetFiles: [{ path: \"config/settings.json\", content: \"{\\n \\\"mode\\\": \\\"config-update-ready\\\"\\n}\\n\" }],\n },\n \"tanya.low.readme-update\": {\n id: \"tanya.low.readme-update\",\n prompt: \"Append the benchmark readiness note to the README.\",\n useSearchReplace: true,\n targetFiles: [{ path: \"README.md\", content: \"# Demo\\n\\nBenchmark note: readme-update-ready\\n\" }],\n },\n \"tanya.low.package-script\": {\n id: \"tanya.low.package-script\",\n prompt: \"Add a benchmark package script while preserving package metadata.\",\n targetFiles: [{ path: \"package.json\", content: \"{\\n \\\"name\\\": \\\"benchmark-fixture\\\",\\n \\\"scripts\\\": {\\n \\\"benchmark:ok\\\": \\\"node scripts/check.js\\\"\\n },\\n \\\"marker\\\": \\\"package-script-ready\\\"\\n}\\n\" }],\n },\n \"tanya.medium.service-module\": {\n id: \"tanya.medium.service-module\",\n prompt: \"Create a service module and export it from the index.\",\n targetFiles: [\n { path: \"src/services/taskService.ts\", content: \"export function taskService() { return 'service-module-ready'; }\\n\" },\n { path: \"src/index.ts\", content: \"export { taskService } from './services/taskService';\\n\" },\n ],\n },\n \"tanya.medium.test-harness\": {\n id: \"tanya.medium.test-harness\",\n prompt: \"Add a tiny executable test harness and verify it runs.\",\n targetFiles: [\n { path: \"src/harness.js\", content: \"module.exports = () => 'test-harness-ready';\\n\" },\n { path: \"test/harness.test.js\", content: \"const run = require('../src/harness'); if (run() !== 'test-harness-ready') process.exit(1);\\n\" },\n ],\n },\n \"tanya.medium.artifact-component\": {\n id: \"tanya.medium.artifact-component\",\n prompt: \"Adapt the reusable component artifact into the project.\",\n useArtifact: true,\n targetFiles: [{ path: \"src/components/BenchmarkCard.tsx\", content: \"export function BenchmarkCard() { return 'artifact-component-ready'; }\\n\" }],\n },\n \"tanya.medium.artifact-service\": {\n id: \"tanya.medium.artifact-service\",\n prompt: \"Adapt the reusable service artifact into the project.\",\n useArtifact: true,\n targetFiles: [{ path: \"src/services/artifactService.ts\", content: \"export function artifactService() { return 'artifact-service-ready'; }\\n\" }],\n },\n \"tanya.medium.dirty-worktree\": {\n id: \"tanya.medium.dirty-worktree\",\n prompt: \"Complete the task while preserving an unrelated dirty file.\",\n dirtyWorktree: true,\n targetFiles: [{ path: \"src/dirtyTask.ts\", content: \"export const dirtyTask = 'dirty-worktree-ready';\\n\" }],\n },\n \"tanya.medium.report-repair\": {\n id: \"tanya.medium.report-repair\",\n prompt: \"Complete the task and recover if the first final response omits the required report.\",\n reportRepair: true,\n targetFiles: [{ path: \"src/reportRepair.ts\", content: \"export const reportRepair = 'report-repair-ready';\\n\" }],\n },\n \"tanya.medium.multi-file\": {\n id: \"tanya.medium.multi-file\",\n prompt: \"Create a coordinated source and documentation update.\",\n targetFiles: [\n { path: \"src/multiFile.ts\", content: \"export const multiFile = 'multi-file-ready';\\n\" },\n { path: \"docs/multi-file.md\", content: \"# Multi File\\n\\nmulti-file-ready\\n\" },\n ],\n },\n \"tanya.medium.package-manager\": {\n id: \"tanya.medium.package-manager\",\n prompt: \"Add package-manager metadata and a source marker.\",\n targetFiles: [\n { path: \"package.json\", content: \"{\\n \\\"name\\\": \\\"benchmark-fixture\\\",\\n \\\"packageManager\\\": \\\"npm@10.0.0\\\",\\n \\\"scripts\\\": {\\n \\\"typecheck\\\": \\\"node scripts/check.js\\\",\\n \\\"test\\\": \\\"node scripts/check.js\\\"\\n },\\n \\\"marker\\\": \\\"package-manager-ready\\\"\\n}\\n\" },\n { path: \"src/packageManager.ts\", content: \"export const packageManager = 'package-manager-ready';\\n\" },\n ],\n },\n \"tanya.medium.context-aware\": {\n id: \"tanya.medium.context-aware\",\n prompt: \"Read the provided context note before editing the implementation.\",\n useContext: true,\n targetFiles: [{ path: \"src/contextAware.ts\", content: \"export const contextAware = 'context-aware-ready';\\n\" }],\n },\n \"tanya.medium.existing-tests\": {\n id: \"tanya.medium.existing-tests\",\n prompt: \"Modify implementation while running the existing verification script.\",\n targetFiles: [\n { path: \"src/existingTests.js\", content: \"module.exports = 'existing-tests-ready';\\n\" },\n { path: \"test/existingTests.test.js\", content: \"if (require('../src/existingTests') !== 'existing-tests-ready') process.exit(1);\\n\" },\n ],\n },\n \"tanya.medium.dependency-install\": {\n id: \"tanya.medium.dependency-install\",\n prompt: \"Add the requested runtime dependency and lockfile state, then verify the manifest.\",\n targetFiles: [\n { path: \"package.json\", content: \"{\\n \\\"name\\\": \\\"benchmark-fixture\\\",\\n \\\"scripts\\\": {\\n \\\"check\\\": \\\"node scripts/check.js\\\"\\n },\\n \\\"dependencies\\\": {\\n \\\"zod\\\": \\\"^3.25.0\\\"\\n },\\n \\\"marker\\\": \\\"dependency-install-ready\\\"\\n}\\n\" },\n { path: \"package-lock.json\", content: \"{\\n \\\"name\\\": \\\"benchmark-fixture\\\",\\n \\\"lockfileVersion\\\": 3,\\n \\\"packages\\\": {\\n \\\"\\\": {\\n \\\"dependencies\\\": {\\n \\\"zod\\\": \\\"^3.25.0\\\"\\n },\\n \\\"marker\\\": \\\"dependency-install-ready\\\"\\n }\\n }\\n}\\n\" },\n ],\n },\n \"tanya.medium.framework-migration\": {\n id: \"tanya.medium.framework-migration\",\n prompt: \"Migrate the legacy page into an app-router-style page and preserve compatibility.\",\n preFiles: [\n { path: \"src/pages/index.tsx\", content: \"export default function LegacyHome() { return 'legacy'; }\\n\" },\n ],\n targetFiles: [\n { path: \"src/app/page.tsx\", content: \"export default function Page() { return 'framework-migration-ready'; }\\n\" },\n { path: \"src/app/layout.tsx\", content: \"export default function Layout({ children }: { children: unknown }) { return children; }\\n// framework-migration-ready\\n\" },\n { path: \"src/pages/index.tsx\", content: \"export { default } from '../app/page';\\n// framework-migration-ready\\n\" },\n ],\n },\n \"tanya.medium.failing-test-repair\": {\n id: \"tanya.medium.failing-test-repair\",\n prompt: \"Run the existing check, repair the failing implementation, and rerun verification.\",\n useSearchReplace: true,\n preVerifyBeforeEdit: true,\n targetFiles: [\n { path: \"src/math.js\", content: \"module.exports = function add(a, b) { return a + b; };\\n// failing-test-repair-ready\\n\" },\n { path: \"test/math.test.js\", content: \"const add = require('../src/math'); if (add(2, 2) !== 4) process.exit(1);\\n// failing-test-repair-ready\\n\" },\n ],\n },\n \"tanya.medium.frontend-smoke\": {\n id: \"tanya.medium.frontend-smoke\",\n prompt: \"Create a small frontend component and smoke check that proves the key UI marker is present.\",\n targetFiles: [\n { path: \"src/App.tsx\", content: \"export function App() { return <main className=\\\"dashboard\\\">frontend-smoke-ready</main>; }\\n\" },\n { path: \"src/App.css\", content: \".dashboard { display: grid; gap: 12px; }\\n/* frontend-smoke-ready */\\n\" },\n { path: \"test/render-smoke.js\", content: \"const fs = require('fs'); const text = fs.readFileSync('src/App.tsx', 'utf8'); if (!text.includes('frontend-smoke-ready')) process.exit(1);\\n// frontend-smoke-ready\\n\" },\n ],\n },\n \"tanya.medium.run-log-history\": {\n id: \"tanya.medium.run-log-history\",\n prompt: \"Complete a normal edit and make sure usage metrics are available for run history.\",\n usage: { promptTokens: 2_400, completionTokens: 620 },\n targetFiles: [{ path: \"src/runLogHistory.ts\", content: \"export const runLogHistory = 'run-log-history-ready';\\n\" }],\n },\n};\n\nasync function genericBenchmarkFixture(profile: GoldenTaskProfile): Promise<GoldenTaskFixture> {\n const spec = GENERIC_BENCHMARK_SPECS[profile.id];\n if (!spec) throw new Error(`No generic benchmark spec for ${profile.id}`);\n const workspace = await createBaseWorkspace(profile.id);\n const marker = `${profile.id.split(\".\").pop() ?? \"benchmark\"}-ready`;\n\n await mkdir(join(workspace, \"scripts\"), { recursive: true });\n await writeFile(join(workspace, \"scripts/check.js\"), [\n \"const fs = require('fs');\",\n `const targets = ${JSON.stringify(spec.targetFiles.map((file) => ({ path: file.path, marker })))};`,\n \"for (const target of targets) {\",\n \" const text = fs.readFileSync(target.path, 'utf8');\",\n \" if (!text.includes(target.marker)) {\",\n \" console.error(`missing ${target.marker} in ${target.path}`);\",\n \" process.exit(1);\",\n \" }\",\n \"}\",\n \"console.log('benchmark ok');\",\n \"\",\n ].join(\"\\n\"));\n\n if (spec.useSearchReplace) {\n for (const file of spec.targetFiles) {\n const dir = file.path.split(\"/\").slice(0, -1).join(\"/\");\n if (dir) await mkdir(join(workspace, dir), { recursive: true });\n await writeFile(join(workspace, file.path), file.content.replace(marker, \"PENDING_MARKER\"));\n }\n }\n for (const file of spec.preFiles ?? []) {\n const dir = file.path.split(\"/\").slice(0, -1).join(\"/\");\n if (dir) await mkdir(join(workspace, dir), { recursive: true });\n await writeFile(join(workspace, file.path), file.content);\n }\n if (spec.useArtifact) {\n await mkdir(join(workspace, \".tania/artifacts/generic\"), { recursive: true });\n await writeFile(join(workspace, \".tania/artifacts/generic/Pattern.md\"), `# Pattern\\n\\nUse ${marker} in the adapted output.\\n`);\n }\n if (spec.useContext) {\n await mkdir(join(workspace, \".tania/context\"), { recursive: true });\n await writeFile(join(workspace, \".tania/context/task.md\"), `# Task Context\\n\\nUse ${marker}.\\n`);\n }\n if (spec.dirtyWorktree) {\n await writeFile(join(workspace, \"unrelated.txt\"), \"baseline\\n\");\n await execFileAsync(\"git\", [\"init\"], { cwd: workspace });\n await execFileAsync(\"git\", [\"config\", \"user.email\", \"tanya@example.test\"], { cwd: workspace });\n await execFileAsync(\"git\", [\"config\", \"user.name\", \"Tanya Benchmark\"], { cwd: workspace });\n await execFileAsync(\"git\", [\"add\", \"unrelated.txt\"], { cwd: workspace });\n await execFileAsync(\"git\", [\"commit\", \"-m\", \"baseline\"], { cwd: workspace });\n await writeFile(join(workspace, \"unrelated.txt\"), \"pre-existing dirty change\\n\");\n }\n\n const toolCalls: ToolCall[] = [];\n if (spec.useArtifact) toolCalls.push(toolCall(\"read-artifact\", \"read_file\", { path: \".tania/artifacts/generic/Pattern.md\" }));\n if (spec.useContext) toolCalls.push(toolCall(\"read-context\", \"read_file\", { path: \".tania/context/task.md\" }));\n if (spec.preVerifyBeforeEdit) toolCalls.push(toolCall(\"verify-before\", \"run_command\", { command: \"node\", args: [\"scripts/check.js\"] }));\n if (spec.useSearchReplace) {\n for (const file of spec.targetFiles) {\n toolCalls.push(toolCall(`edit-${file.path}`, \"search_replace\", {\n path: file.path,\n old_string: file.content.replace(marker, \"PENDING_MARKER\"),\n new_string: file.content,\n }));\n }\n } else {\n for (const file of spec.targetFiles) toolCalls.push(toolCall(`write-${file.path}`, \"write_file\", file));\n }\n toolCalls.push(toolCall(\"verify\", \"run_command\", { command: \"node\", args: [\"scripts/check.js\"] }));\n\n const artifactLine = spec.useArtifact\n ? `Artifact reused: artifacts/generic/Pattern.md -> ${spec.targetFiles.map((file) => file.path).join(\", \")}`\n : \"Artifact reused: none\";\n const finalReport = [\n artifactLine,\n \"Artifact created: none\",\n ...spec.targetFiles.map((file) => `Modified: ${file.path}`),\n \"Verification: node scripts/check.js -> passed\",\n \"Blocked: none\",\n ].join(\"\\n\");\n\n return {\n workspace,\n prompt: spec.prompt,\n provider: scriptedProvider(profile.id, [\n { content: spec.prompt, toolCalls, ...(spec.usage ? { usage: spec.usage } : {}) },\n ...(spec.reportRepair ? [{ content: \"Done.\" }] : []),\n { content: finalReport },\n ]),\n runContext: {\n task: { kind: \"coding\", title: profile.title, summary: profile.purpose },\n artifacts: spec.useArtifact ? [{ path: \".tania/artifacts/generic/Pattern.md\", sourcePath: \"artifacts/generic/Pattern.md\", status: \"available\" }] : [],\n contextFiles: spec.useContext ? [{ path: \".tania/context/task.md\", sourcePath: \"context/task.md\", status: \"available\" }] : [],\n expected_report: { verification: true, artifact_reuse: true },\n metadata: { goldenTaskCandidate: true, caller: \"tanya-benchmark\" },\n },\n };\n}\n\nasync function streamingLongToolFixture(profile: GoldenTaskProfile): Promise<GoldenTaskFixture> {\n const workspace = await createBaseWorkspace(profile.id);\n const script = \"for i in 1 2 3 4 5 6; do printf \\\"stream-$i\\\\n\\\"; sleep 2; done; node scripts/check.js\";\n await mkdir(join(workspace, \"scripts\"), { recursive: true });\n await writeFile(join(workspace, \"scripts/check.js\"), [\n \"const fs = require('fs');\",\n \"const text = fs.readFileSync('src/streamingLongTool.ts', 'utf8');\",\n \"if (!text.includes('streaming-long-tool-ready')) process.exit(1);\",\n \"console.log('benchmark ok');\",\n \"\",\n ].join(\"\\n\"));\n\n const provider = scriptedProvider(profile.id, [\n {\n content: \"Create a marker file and verify it with a long-running streaming shell command.\",\n toolCalls: [\n toolCall(\"write-marker\", \"write_file\", {\n path: \"src/streamingLongTool.ts\",\n content: \"export const streamingLongTool = 'streaming-long-tool-ready';\\n\",\n }),\n toolCall(\"long-verify\", \"run_shell\", { script, timeoutMs: 20_000 }),\n ],\n },\n {\n content: [\n \"Artifact reused: none\",\n \"Artifact created: none\",\n \"Modified: src/streamingLongTool.ts\",\n `Verification: ${script} -> passed`,\n \"Blocked: none\",\n ].join(\"\\n\"),\n },\n ]);\n\n return {\n workspace,\n prompt: \"Create a marker file and verify it with a >10s shell command that streams output.\",\n provider,\n runContext: {\n task: { kind: \"coding\", title: profile.title, summary: profile.purpose },\n expected_report: { verification: true, artifact_reuse: true },\n metadata: { goldenTaskCandidate: true, caller: \"tanya-golden\" },\n },\n };\n}\n\nasync function compactionBoundaryFixture(profile: GoldenTaskProfile): Promise<GoldenTaskFixture> {\n const workspace = await createBaseWorkspace(profile.id);\n await mkdir(join(workspace, \"scripts\"), { recursive: true });\n await writeFile(join(workspace, \"scripts/check.js\"), [\n \"const fs = require('fs');\",\n \"const text = fs.readFileSync('src/compactionBoundary.ts', 'utf8');\",\n \"if (!text.includes('compaction-boundary-ready')) process.exit(1);\",\n \"console.log('benchmark ok');\",\n \"\",\n ].join(\"\\n\"));\n\n const requests: ChatRequest[] = [];\n let mainAttempts = 0;\n const provider: ChatProvider & { requests: ChatRequest[] } = {\n id: `golden:${profile.id}`,\n model: \"scripted\",\n requests,\n async *streamChat(input: ChatRequest) {\n requests.push({ ...input, messages: [...input.messages] });\n const prompt = input.messages[0]?.content ?? \"\";\n if (input.tools?.length === 0 && prompt.includes(\"Summarize these older Tanya conversation turns\")) {\n yield { content: \"The run wrote src/compactionBoundary.ts and verified it with node scripts/check.js.\" };\n return;\n }\n\n mainAttempts += 1;\n if (mainAttempts === 1) {\n yield {\n content: \"Create and verify the compaction boundary marker.\",\n toolCalls: [\n toolCall(\"write-marker\", \"write_file\", {\n path: \"src/compactionBoundary.ts\",\n content: \"export const compactionBoundary = 'compaction-boundary-ready';\\n\",\n }),\n toolCall(\"verify\", \"run_command\", { command: \"node\", args: [\"scripts/check.js\"] }),\n ],\n };\n return;\n }\n if (mainAttempts === 2) {\n throw new ContextWindowExceededError({\n provider: provider.id,\n status: 413,\n rawMessage: \"context_length_exceeded\",\n });\n }\n yield {\n content: [\n \"Artifact reused: none\",\n \"Artifact created: none\",\n \"Modified: src/compactionBoundary.ts\",\n \"Verification: node scripts/check.js -> passed\",\n \"Blocked: none\",\n ].join(\"\\n\"),\n };\n },\n };\n\n return {\n workspace,\n prompt: \"Create a marker file and finish correctly after a synthetic context compaction boundary.\",\n provider,\n runContext: {\n task: { kind: \"coding\", title: profile.title, summary: profile.purpose },\n expected_report: { verification: true, artifact_reuse: true },\n metadata: { goldenTaskCandidate: true, caller: \"tanya-golden\" },\n },\n };\n}\n\nasync function editBlockFuzzyFixture(profile: GoldenTaskProfile, mode: \"enabled\" | \"disabled\" = \"enabled\"): Promise<GoldenTaskFixture> {\n const workspace = await createBaseWorkspace(`${profile.id}-${mode}`);\n await mkdir(join(workspace, \"src\"), { recursive: true });\n await mkdir(join(workspace, \"scripts\"), { recursive: true });\n await writeFile(join(workspace, \"src/status.ts\"), [\n \"export function status() {\",\n \" const current = \\\"pending\\\";\",\n \" return current;\",\n \"}\",\n \"\",\n ].join(\"\\n\"));\n await writeFile(join(workspace, \"scripts/check.js\"), [\n \"const fs = require('fs');\",\n \"const text = fs.readFileSync('src/status.ts', 'utf8');\",\n \"if (!text.includes('complete')) {\",\n \" console.error('missing edit-block-fuzzy-ready');\",\n \" process.exit(1);\",\n \"}\",\n \"console.log('benchmark ok');\",\n \"\",\n ].join(\"\\n\"));\n if (mode === \"enabled\") {\n await mkdir(join(workspace, \".tania\"), { recursive: true });\n await writeFile(join(workspace, \".tania\", \"permissions.json\"), JSON.stringify({\n version: 1,\n mode: \"default\",\n alwaysAllow: [\"edit_block:.*\\\"matchPolicy\\\":\\\"fuzzy\\\".*\"],\n }));\n }\n\n const original = [\n \"export function status() {\",\n \" const current = \\\"pending\\\";\",\n \" return current;\",\n \"}\",\n ].join(\"\\n\");\n const nearMatch = [\n \"export function status() {\",\n \" const current = \\\"pendng\\\";\",\n \" return current;\",\n \"}\",\n ].join(\"\\n\");\n const replacement = [\n \"export function status() {\",\n \" const current = \\\"complete\\\";\",\n \" return current;\",\n \"}\",\n ].join(\"\\n\");\n const finalReport = [\n \"Artifact reused: none\",\n \"Artifact created: none\",\n \"Modified: src/status.ts\",\n \"Verification: node scripts/check.js -> passed\",\n \"Blocked: none\",\n ].join(\"\\n\");\n\n const turns = mode === \"enabled\"\n ? [\n {\n content: \"Use fuzzy edit_block to recover the near-match and verify it.\",\n toolCalls: [\n toolCall(\"fuzzy-edit\", \"edit_block\", {\n path: \"src/status.ts\",\n search: nearMatch,\n replace: replacement,\n matchPolicy: \"fuzzy\",\n }),\n toolCall(\"verify\", \"run_command\", { command: \"node\", args: [\"scripts/check.js\"] }),\n ],\n },\n { content: finalReport },\n ]\n : [\n {\n content: \"Try the near-match exactly first.\",\n toolCalls: [\n toolCall(\"bad-exact\", \"edit_block\", {\n path: \"src/status.ts\",\n search: nearMatch,\n replace: replacement,\n }),\n ],\n },\n {\n content: \"Read the file after the exact block failed.\",\n toolCalls: [toolCall(\"read-status\", \"read_file\", { path: \"src/status.ts\" })],\n },\n {\n content: \"Apply the closer exact block and verify.\",\n toolCalls: [\n toolCall(\"exact-edit\", \"edit_block\", {\n path: \"src/status.ts\",\n search: original,\n replace: replacement,\n }),\n toolCall(\"verify\", \"run_command\", { command: \"node\", args: [\"scripts/check.js\"] }),\n ],\n },\n { content: finalReport },\n ];\n\n return {\n workspace,\n prompt: \"Recover a cheap-provider-style near-match edit and verify the file.\",\n provider: scriptedProvider(`${profile.id}-${mode}`, turns),\n runContext: {\n task: { kind: \"coding\", title: profile.title, summary: profile.purpose },\n expected_report: { verification: true, artifact_reuse: true },\n metadata: { goldenTaskCandidate: true, caller: \"tanya-golden\" },\n },\n };\n}\n\nasync function androidSplashFixture(profile: GoldenTaskProfile): Promise<GoldenTaskFixture> {\n const workspace = await createBaseWorkspace(profile.id);\n await mkdir(join(workspace, \".tania/artifacts/android\"), { recursive: true });\n await mkdir(join(workspace, \"app/src/main/java/com/example/app/ui/splash\"), { recursive: true });\n await mkdir(join(workspace, \"app/src/main/res/values\"), { recursive: true });\n await mkdir(join(workspace, \"app/src/main/res/drawable\"), { recursive: true });\n await writeFile(join(workspace, \".tania/artifacts/android/SplashScreenPattern.kt\"), \"fun SplashPattern() {}\\n\");\n await writeFile(join(workspace, \"gradlew\"), \"#!/bin/sh\\ncase \\\"$*\\\" in\\n *ktlintCheck*) echo ktlint ok ;;\\n *) echo BUILD SUCCESSFUL ;;\\nesac\\n\");\n await writeFile(join(workspace, \"app/src/main/res/drawable/ic_splash_logo.png\"), \"png\\n\");\n\n const provider = scriptedProvider(profile.id, [\n {\n content: \"Create Android splash resources from the artifact.\",\n toolCalls: [\n toolCall(\"read-artifact\", \"read_file\", { path: \".tania/artifacts/android/SplashScreenPattern.kt\" }),\n toolCall(\"write-manifest\", \"write_file\", {\n path: \"app/src/main/AndroidManifest.xml\",\n content: \"<manifest xmlns:android=\\\"http://schemas.android.com/apk/res/android\\\"><application><activity android:name=\\\".MainActivity\\\" android:theme=\\\"@style/Theme.App.Splash\\\" /></application></manifest>\\n\",\n }),\n toolCall(\"write-theme\", \"write_file\", {\n path: \"app/src/main/res/values/splash_theme.xml\",\n content: \"<resources><style name=\\\"Theme.App.Splash\\\" parent=\\\"Theme.SplashScreen\\\"><item name=\\\"windowSplashScreenAnimatedIcon\\\">@drawable/ic_splash_logo</item><item name=\\\"postSplashScreenTheme\\\">@style/Theme.App</item></style></resources>\\n\",\n }),\n toolCall(\"write-icon\", \"write_file\", {\n path: \"app/src/main/res/drawable/ic_splash_logo.png\",\n content: \"png\\n\",\n }),\n toolCall(\"write-main\", \"write_file\", {\n path: \"app/src/main/java/com/example/app/MainActivity.kt\",\n content: \"package com.example.app\\nfun onCreate() { installSplashScreen() }\\n\",\n }),\n toolCall(\"write-splash\", \"write_file\", {\n path: \"app/src/main/java/com/example/app/ui/splash/SplashScreen.kt\",\n content: \"package com.example.app.ui.splash\\nfun CosaNostraSplashScreen() {}\\n\",\n }),\n toolCall(\"verify\", \"run_shell\", { script: \"chmod +x ./gradlew && ./gradlew assembleDebug --no-daemon\" }),\n ],\n },\n {\n content: [\n \"Artifact reused: artifacts/android/SplashScreenPattern.kt -> app/src/main/java/com/example/app/ui/splash/SplashScreen.kt\",\n \"Artifact created: none\",\n \"Modified: app/src/main/AndroidManifest.xml\",\n \"Modified: app/src/main/res/values/splash_theme.xml\",\n \"Modified: app/src/main/res/drawable/ic_splash_logo.png\",\n \"Modified: app/src/main/java/com/example/app/MainActivity.kt\",\n \"Modified: app/src/main/java/com/example/app/ui/splash/SplashScreen.kt\",\n \"Verification: ./gradlew assembleDebug --no-daemon -> passed\",\n \"Blocked: none\",\n ].join(\"\\n\"),\n },\n ]);\n\n return {\n workspace,\n prompt: \"Create Android splash screen using artifacts/android/SplashScreenPattern.kt.\",\n provider,\n runContext: {\n task: { kind: \"coding\", title: \"Splash Screen - Android\", summary: profile.purpose },\n artifacts: [{ path: \".tania/artifacts/android/SplashScreenPattern.kt\", sourcePath: \"artifacts/android/SplashScreenPattern.kt\", status: \"available\" }],\n expected_report: { verification: true, artifact_reuse: true },\n metadata: { goldenTaskCandidate: true, caller: \"tanya-golden\" },\n },\n };\n}\n\nasync function iosFoundationFixture(profile: GoldenTaskProfile): Promise<GoldenTaskFixture> {\n const workspace = await createBaseWorkspace(profile.id);\n await mkdir(join(workspace, \".tania/artifacts/ios\"), { recursive: true });\n await writeFile(join(workspace, \".tania/artifacts/ios/ThemeSystem.swift\"), \"import SwiftUI\\n\");\n await writeFile(join(workspace, \".tania/artifacts/ios/SwiftDataSetup.swift\"), \"import SwiftData\\n\");\n await writeFile(join(workspace, \".tania/artifacts/ios/NavigationSetup.swift\"), \"import SwiftUI\\n\");\n\n const provider = scriptedProvider(profile.id, [\n {\n content: \"Create iOS foundation from theme, SwiftData, and navigation artifacts.\",\n toolCalls: [\n toolCall(\"read-theme\", \"read_file\", { path: \".tania/artifacts/ios/ThemeSystem.swift\" }),\n toolCall(\"read-data\", \"read_file\", { path: \".tania/artifacts/ios/SwiftDataSetup.swift\" }),\n toolCall(\"read-nav\", \"read_file\", { path: \".tania/artifacts/ios/NavigationSetup.swift\" }),\n toolCall(\"mkdirs\", \"run_shell\", { script: \"mkdir -p CosaNostra/Theme CosaNostra/Models CosaNostra/Navigation\" }),\n toolCall(\"write-colors\", \"write_file\", {\n path: \"CosaNostra/Theme/Colors.swift\",\n content: \"import SwiftUI\\nextension Color { static let brandPrimary = Color(red: 26 / 255, green: 47 / 255, blue: 75 / 255); static let brandSecondary = Color(red: 200 / 255, green: 174 / 255, blue: 127 / 255); static let textPrimary = Color.primary }\\n\",\n }),\n toolCall(\"write-type\", \"write_file\", {\n path: \"CosaNostra/Theme/Typography.swift\",\n content: \"import SwiftUI\\nenum AppTypography { static let title = Font.system(size: 28, design: .serif); static let body = Font.system(size: 16, design: .default) /* Playfair Display / Roboto local fallback */ }\\n\",\n }),\n toolCall(\"write-mods\", \"write_file\", {\n path: \"CosaNostra/Theme/ViewModifiers.swift\",\n content: \"import SwiftUI\\nstruct CardStyle: ViewModifier { func body(content: Content) -> some View { content } }\\nstruct PrimaryButtonStyle: ButtonStyle { func makeBody(configuration: Configuration) -> some View { configuration.label } }\\nstruct EmptyStateView: View { var body: some View { Text(\\\"Empty\\\") } }\\nstruct LoadingView: View { var body: some View { ProgressView() } }\\nstruct ErrorView: View { var body: some View { Text(\\\"Error\\\") } }\\n\",\n }),\n toolCall(\"write-models\", \"write_file\", {\n path: \"CosaNostra/Models/SwiftDataSetup.swift\",\n content: \"import SwiftData\\n@Model final class UserProfile { var id: String = \\\"\\\" }\\nlet appSchema = Schema([UserProfile.self])\\n\",\n }),\n toolCall(\"write-nav\", \"write_file\", {\n path: \"CosaNostra/Navigation/NavigationSetup.swift\",\n content: \"import SwiftUI\\nstruct RootTabView: View { @AppStorage(\\\"isDarkMode\\\") private var isDarkMode = false; var body: some View { TabView { NavigationStack { Toggle(\\\"Dark Mode\\\", isOn: $isDarkMode); Text(\\\"Dashboard\\\") } } } }\\n\",\n }),\n toolCall(\"write-app\", \"write_file\", {\n path: \"CosaNostra/CosaNostraApp.swift\",\n content: \"import SwiftUI\\nimport SwiftData\\n@main struct CosaNostraApp: App { @AppStorage(\\\"isDarkMode\\\") private var isDarkMode = false; var body: some Scene { WindowGroup { RootTabView().preferredColorScheme(isDarkMode ? .dark : nil).modelContainer(for: [UserProfile.self]) } } }\\n\",\n }),\n toolCall(\"verify\", \"run_shell\", { script: \"grep -R \\\"TabView\\\" CosaNostra/Navigation && echo xcodebuild\" }),\n ],\n },\n {\n content: [\n \"Artifact reused: artifacts/ios/ThemeSystem.swift -> CosaNostra/Theme/Colors.swift, CosaNostra/Theme/Typography.swift, CosaNostra/Theme/ViewModifiers.swift\",\n \"Artifact reused: artifacts/ios/SwiftDataSetup.swift -> CosaNostra/Models/SwiftDataSetup.swift\",\n \"Artifact reused: artifacts/ios/NavigationSetup.swift -> CosaNostra/Navigation/NavigationSetup.swift\",\n \"Artifact created: none\",\n \"Modified: CosaNostra/Theme/Colors.swift\",\n \"Modified: CosaNostra/Theme/Typography.swift\",\n \"Modified: CosaNostra/Theme/ViewModifiers.swift\",\n \"Modified: CosaNostra/Models/SwiftDataSetup.swift\",\n \"Modified: CosaNostra/Navigation/NavigationSetup.swift\",\n \"Modified: CosaNostra/CosaNostraApp.swift\",\n \"Verification: grep -R \\\"TabView\\\" CosaNostra/Navigation && echo xcodebuild -> passed\",\n \"Blocked: none\",\n ].join(\"\\n\"),\n },\n ]);\n\n return {\n workspace,\n prompt: \"Create bounded iOS foundation from the provided artifacts. Ensure dark mode support and local typography fallback.\",\n provider,\n runContext: {\n task: { kind: \"coding\", title: \"Fundações - iOS\", summary: profile.purpose },\n artifacts: [\n { path: \".tania/artifacts/ios/ThemeSystem.swift\", sourcePath: \"artifacts/ios/ThemeSystem.swift\", status: \"available\" },\n { path: \".tania/artifacts/ios/SwiftDataSetup.swift\", sourcePath: \"artifacts/ios/SwiftDataSetup.swift\", status: \"available\" },\n { path: \".tania/artifacts/ios/NavigationSetup.swift\", sourcePath: \"artifacts/ios/NavigationSetup.swift\", status: \"available\" },\n ],\n expected_report: { verification: true, artifact_reuse: true },\n metadata: { goldenTaskCandidate: true, caller: \"tanya-golden\" },\n },\n };\n}\n\nasync function appleAppIconFixture(profile: GoldenTaskProfile): Promise<GoldenTaskFixture> {\n const workspace = await createBaseWorkspace(profile.id);\n await mkdir(join(workspace, \"CosaNostra/Assets.xcassets\"), { recursive: true });\n const provider = scriptedProvider(profile.id, [\n {\n content: \"Generate Apple app icon set with iOS and macOS slots.\",\n toolCalls: [\n toolCall(\"write-svg\", \"write_file\", {\n path: \"brand-icon.svg\",\n content: \"<svg xmlns=\\\"http://www.w3.org/2000/svg\\\" width=\\\"1024\\\" height=\\\"1024\\\"><rect width=\\\"1024\\\" height=\\\"1024\\\" fill=\\\"#1A2F4B\\\"/><circle cx=\\\"512\\\" cy=\\\"512\\\" r=\\\"280\\\" fill=\\\"#C8AE7F\\\"/></svg>\\n\",\n }),\n toolCall(\"create-icons\", \"create_apple_app_icon_set\", {\n source: \"brand-icon.svg\",\n outputDir: \"CosaNostra/Assets.xcassets/AppIcon.appiconset\",\n platforms: [\"ios\", \"macos\"],\n }),\n toolCall(\"parse-json\", \"run_shell\", { script: \"node -e \\\"const c=require('./CosaNostra/Assets.xcassets/AppIcon.appiconset/Contents.json'); const idioms=new Set(c.images.map(i=>i.idiom)); if(!idioms.has('iphone')||!idioms.has('ipad')||!idioms.has('ios-marketing')||!idioms.has('mac')) process.exit(1); console.log(c.images.length)\\\"\" }),\n toolCall(\"xcodebuild\", \"run_shell\", { script: \"printf '#!/bin/sh\\\\necho BUILD SUCCEEDED\\\\n' > xcodebuild && chmod +x xcodebuild && PATH=\\\"$PWD:$PATH\\\" xcodebuild build -scheme CosaNostra -destination 'generic/platform=iOS Simulator'\" }),\n ],\n },\n {\n content: [\n \"Artifact reused: none\",\n \"Artifact created: none\",\n \"Modified: brand-icon.svg\",\n \"Modified: CosaNostra/Assets.xcassets/AppIcon.appiconset/Contents.json\",\n \"Verification: node Contents.json idiom parse -> passed\",\n \"Verification: xcodebuild build -scheme CosaNostra -destination 'generic/platform=iOS Simulator' -> passed\",\n \"Blocked: none\",\n ].join(\"\\n\"),\n },\n ]);\n\n return {\n workspace,\n prompt: \"Generate Apple app icon assets for iOS, iPad, ios-marketing, and macOS.\",\n provider,\n runContext: {\n task: { kind: \"coding\", title: \"App Icon - Apple\", summary: profile.purpose },\n expected_report: { verification: true, artifact_reuse: true },\n metadata: { goldenTaskCandidate: true, caller: \"tanya-golden\" },\n },\n };\n}\n\nasync function androidFoundationFixture(profile: GoldenTaskProfile): Promise<GoldenTaskFixture> {\n const workspace = await createBaseWorkspace(profile.id);\n await mkdir(join(workspace, \".tania/artifacts/android\"), { recursive: true });\n await mkdir(join(workspace, \"app\"), { recursive: true });\n await writeFile(join(workspace, \".tania/artifacts/android/ThemeSystem.kt\"), \"package artifact\\n\");\n await writeFile(join(workspace, \".tania/artifacts/android/NavigationSetup.kt\"), \"package artifact\\n\");\n await writeFile(join(workspace, \".tania/artifacts/android/RoomSetup.kt\"), \"package artifact\\n\");\n await writeFile(join(workspace, \"gradlew\"), \"#!/bin/sh\\ncase \\\"$*\\\" in\\n *ktlintCheck*) echo ktlint ok ;;\\n *) echo BUILD SUCCESSFUL ;;\\nesac\\n\");\n await writeFile(join(workspace, \"build.gradle.kts\"), \"plugins {\\n id(\\\"com.android.application\\\") version \\\"8.7.2\\\" apply false\\n}\\n\");\n await writeFile(join(workspace, \"app/build.gradle.kts\"), [\n \"plugins {\",\n \" id(\\\"com.android.application\\\")\",\n \" id(\\\"org.jetbrains.kotlin.android\\\")\",\n \"}\",\n \"\",\n \"dependencies {\",\n \"}\",\n \"\",\n ].join(\"\\n\"));\n\n const provider = scriptedProvider(profile.id, [\n {\n content: \"Create Android foundation with the deterministic high-level tool.\",\n toolCalls: [\n toolCall(\"read-theme\", \"read_file\", { path: \".tania/artifacts/android/ThemeSystem.kt\" }),\n toolCall(\"read-nav\", \"read_file\", { path: \".tania/artifacts/android/NavigationSetup.kt\" }),\n toolCall(\"read-room\", \"read_file\", { path: \".tania/artifacts/android/RoomSetup.kt\" }),\n toolCall(\"create-foundation\", \"create_android_foundation\", {\n packageName: \"com.example.app\",\n appName: \"Golden\",\n brandPrimaryHex: \"#1A2F4B\",\n brandSecondaryHex: \"#C8AE7F\",\n }),\n toolCall(\"verify\", \"run_shell\", { script: \"chmod +x ./gradlew && ./gradlew assembleDebug --no-daemon\" }),\n ],\n },\n {\n content: [\n \"Artifact reused: artifacts/android/ThemeSystem.kt -> app/src/main/java/com/example/app/ui/theme/AppTheme.kt\",\n \"Artifact reused: artifacts/android/NavigationSetup.kt -> app/src/main/java/com/example/app/navigation/AppNavigation.kt\",\n \"Artifact reused: artifacts/android/RoomSetup.kt -> app/src/main/java/com/example/app/data/AppDatabase.kt\",\n \"Artifact created: none\",\n \"Modified: build.gradle.kts\",\n \"Modified: app/build.gradle.kts\",\n \"Modified: app/src/main/java/com/example/app/ui/theme/AppTheme.kt\",\n \"Modified: app/src/main/java/com/example/app/navigation/AppNavigation.kt\",\n \"Modified: app/src/main/java/com/example/app/data/AppDatabase.kt\",\n \"Modified: app/src/main/java/com/example/app/ui/components/FoundationStates.kt\",\n \"Verification: ./gradlew assembleDebug --no-daemon -> passed\",\n \"Blocked: none\",\n ].join(\"\\n\"),\n },\n ]);\n\n return {\n workspace,\n prompt: \"Create Android foundation using Room, Navigation Compose, Material 3 theme, and base composables.\",\n provider,\n runContext: {\n task: { kind: \"coding\", title: \"Fundações - Android\", summary: profile.purpose },\n artifacts: [\n { path: \".tania/artifacts/android/ThemeSystem.kt\", sourcePath: \"artifacts/android/ThemeSystem.kt\", status: \"available\" },\n { path: \".tania/artifacts/android/NavigationSetup.kt\", sourcePath: \"artifacts/android/NavigationSetup.kt\", status: \"available\" },\n { path: \".tania/artifacts/android/RoomSetup.kt\", sourcePath: \"artifacts/android/RoomSetup.kt\", status: \"available\" },\n ],\n expected_report: { verification: true, artifact_reuse: true },\n metadata: { goldenTaskCandidate: true, caller: \"tanya-golden\" },\n },\n };\n}\n\nasync function backendApiFoundationFixture(profile: GoldenTaskProfile): Promise<GoldenTaskFixture> {\n const workspace = await createBaseWorkspace(profile.id);\n await mkdir(join(workspace, \".tania/artifacts/backend\"), { recursive: true });\n await mkdir(join(workspace, \"app/api/health\"), { recursive: true });\n await mkdir(join(workspace, \"lib\"), { recursive: true });\n await mkdir(join(workspace, \"prisma\"), { recursive: true });\n await writeFile(join(workspace, \".tania/artifacts/backend/JwtAuthRoutes.ts\"), \"export function authRoutePattern() {}\\n\");\n await writeFile(join(workspace, \"package.json\"), JSON.stringify({ scripts: { typecheck: \"tsc --noEmit\", test: \"node --test\" }, dependencies: {} }, null, 2));\n\n const provider = scriptedProvider(profile.id, [\n {\n content: \"Create backend health/API foundation from the route artifact.\",\n toolCalls: [\n toolCall(\"read-artifact\", \"read_file\", { path: \".tania/artifacts/backend/JwtAuthRoutes.ts\" }),\n toolCall(\"write-health\", \"write_file\", {\n path: \"app/api/health/route.ts\",\n content: \"export async function GET() { return Response.json({ status: 'ok', health: true }); }\\n\",\n }),\n toolCall(\"write-openapi\", \"write_file\", {\n path: \"lib/openapi.ts\",\n content: \"export const openApiSpec = { paths: { '/api/health': { get: { summary: 'health' } } } };\\n\",\n }),\n toolCall(\"write-prisma\", \"write_file\", {\n path: \"prisma/schema.prisma\",\n content: \"datasource db { provider = \\\"postgresql\\\" url = env(\\\"DATABASE_URL\\\") }\\ngenerator client { provider = \\\"prisma-client-js\\\" }\\nmodel User { id String @id }\\n\",\n }),\n toolCall(\"write-env\", \"write_file\", {\n path: \".env.example\",\n content: [\n \"# Managed deploy provisions PostgreSQL.\",\n \"# Set DATABASE_URL and DIRECT_URL before seed:mock-data and seed:test-account actions.\",\n \"DATABASE_URL=\\\"replace-me-managed-postgresql-url\\\"\",\n \"DIRECT_URL=\\\"replace-me-managed-postgresql-direct-url\\\"\",\n \"\",\n ].join(\"\\n\"),\n }),\n toolCall(\"verify\", \"run_shell\", { script: \"node -e \\\"require('fs').accessSync('app/api/health/route.ts'); console.log('typecheck')\\\"\" }),\n ],\n },\n {\n content: [\n \"Artifact reused: artifacts/backend/JwtAuthRoutes.ts -> app/api/health/route.ts\",\n \"Artifact created: none\",\n \"Modified: app/api/health/route.ts\",\n \"Modified: lib/openapi.ts\",\n \"Modified: prisma/schema.prisma\",\n \"Modified: .env.example\",\n \"Verification: node -e route exists -> passed\",\n \"Blocked: none\",\n ].join(\"\\n\"),\n },\n ]);\n\n return {\n workspace,\n prompt: \"Implement backend API foundation with health endpoint, OpenAPI seed, Prisma schema, and env example.\",\n provider,\n runContext: {\n task: { kind: \"coding\", title: \"Backend API Foundation\", summary: profile.purpose },\n artifacts: [{ path: \".tania/artifacts/backend/JwtAuthRoutes.ts\", sourcePath: \"artifacts/backend/JwtAuthRoutes.ts\", status: \"available\" }],\n expected_report: { verification: true, artifact_reuse: true },\n metadata: { goldenTaskCandidate: true, caller: \"tanya-golden\" },\n },\n };\n}\n\nexport function goldenRunnableProfiles(): GoldenTaskProfile[] {\n const runnable = new Set([\n \"tanya.medium.streaming-long-tool\",\n \"tanya.medium.compaction-boundary\",\n \"tanya.medium.edit-block-fuzzy\",\n ...Object.keys(GENERIC_BENCHMARK_SPECS),\n ]);\n return loadGoldenTaskProfiles().filter((profile) => runnable.has(profile.id));\n}\n\nasync function createFixture(profile: GoldenTaskProfile): Promise<GoldenTaskFixture> {\n if (profile.id === \"tanya.medium.streaming-long-tool\") return streamingLongToolFixture(profile);\n if (profile.id === \"tanya.medium.compaction-boundary\") return compactionBoundaryFixture(profile);\n if (profile.id === \"tanya.medium.edit-block-fuzzy\") return editBlockFuzzyFixture(profile);\n if (profile.id in GENERIC_BENCHMARK_SPECS) return genericBenchmarkFixture(profile);\n throw new Error(`Golden profile is not executable yet: ${profile.id}`);\n}\n\nasync function runFixture(profile: GoldenTaskProfile, fixture: GoldenTaskFixture): Promise<GoldenRunResult> {\n const events: TanyaEvent[] = [];\n const { message: finalText } = await runAgent({\n provider: fixture.provider,\n prompt: fixture.prompt,\n cwd: fixture.workspace,\n sink: async (event) => { events.push(event); },\n runContext: fixture.runContext,\n });\n const problems = [\n ...finalText.matchAll(/\"severity\"\\s*:\\s*\"error\"[\\s\\S]{0,220}?\"id\"\\s*:\\s*\"([^\"]+)\"/g),\n ].map((match) => match[1] ?? \"validation-error\");\n if (profile.id === \"tanya.medium.streaming-long-tool\" && !events.some((event) => event.type === \"tool_progress\")) {\n problems.push(\"missing-tool-progress\");\n }\n if (profile.id === \"tanya.medium.compaction-boundary\" && !events.some((event) => event.type === \"compact_event\" && event.compactType === \"auto\")) {\n problems.push(\"missing-auto-compaction\");\n }\n const blocked = finalText\n .split(/\\r?\\n/)\n .some((line) => {\n const match = line.trim().match(/^Blocked:\\s*(.+)$/i);\n return !!match?.[1] && !/^none\\b/i.test(match[1].trim());\n });\n return {\n profile,\n workspace: fixture.workspace,\n passed: !blocked && problems.length === 0,\n finalText,\n problems,\n turns: (fixture.provider as ChatProvider & { requests?: ChatRequest[] }).requests?.length ?? events.filter((event) => event.type === \"message_start\").length,\n };\n}\n\nexport async function runGoldenTask(profileId: string): Promise<GoldenRunResult> {\n const profile = loadGoldenTaskProfiles().find((item) => item.id === profileId);\n if (!profile) throw new Error(`Unknown golden profile: ${profileId}`);\n const fixture = await createFixture(profile);\n return runFixture(profile, fixture);\n}\n\nexport async function runEditBlockFuzzyGoldenComparison(): Promise<{\n enabled: GoldenRunResult;\n disabled: GoldenRunResult;\n}> {\n const profile = loadGoldenTaskProfiles().find((item) => item.id === \"tanya.medium.edit-block-fuzzy\");\n if (!profile) throw new Error(\"Unknown golden profile: tanya.medium.edit-block-fuzzy\");\n const enabled = await runFixture(profile, await editBlockFuzzyFixture(profile, \"enabled\"));\n const disabled = await runFixture(profile, await editBlockFuzzyFixture(profile, \"disabled\"));\n return { enabled, disabled };\n}\n","import { buildGoldenTaskSummary, readGoldenTaskMemory, validateGoldenTaskSummary } from \"../memory/goldenTasks\";\nimport { BUILT_IN_GOLDEN_TASK_PROFILES, loadGoldenTaskProfiles } from \"./profiles\";\nimport { goldenRunnableProfiles, runGoldenTask } from \"./run\";\n\nexport async function runGoldenSuiteCommand(workspace: string, action: string, json = false, options: { profile?: string; all?: boolean } = {}): Promise<number> {\n const records = await readGoldenTaskMemory(workspace);\n const summary = buildGoldenTaskSummary(records);\n const problems = validateGoldenTaskSummary(summary);\n\n if (action === \"run\") {\n const profiles = options.all\n ? goldenRunnableProfiles()\n : [options.profile ?? \"tanya.low.search-replace\"]\n .map((profileId) => loadGoldenTaskProfiles().find((profile) => profile.id === profileId))\n .filter((profile): profile is NonNullable<typeof profile> => !!profile);\n if (profiles.length === 0) {\n const message = `No executable golden profile matched ${options.profile ?? \"(default)\"}.`;\n if (json) console.log(JSON.stringify({ results: [], problems: [message] }, null, 2));\n else console.log(message);\n return 1;\n }\n const results = [];\n for (const profile of profiles) results.push(await runGoldenTask(profile.id));\n if (json) {\n console.log(JSON.stringify({\n results: results.map((result) => ({\n profileId: result.profile.id,\n title: result.profile.title,\n workspace: result.workspace,\n passed: result.passed,\n problems: result.problems,\n })),\n }, null, 2));\n } else {\n for (const result of results) {\n console.log(`${result.passed ? \"PASS\" : \"FAIL\"} ${result.profile.id} ${result.profile.title}`);\n console.log(` workspace: ${result.workspace}`);\n if (result.problems.length > 0) console.log(` problems: ${result.problems.join(\", \")}`);\n }\n }\n return results.every((result) => result.passed) ? 0 : 1;\n }\n\n if (json) {\n const profiles = loadGoldenTaskProfiles();\n console.log(JSON.stringify({\n summary,\n problems,\n profiles: action === \"profiles\" ? profiles : undefined,\n executableProfiles: action === \"profiles\" ? goldenRunnableProfiles().map((profile) => profile.id) : undefined,\n }, null, 2));\n return action === \"validate\" && problems.length > 0 ? 1 : 0;\n }\n\n if (action === \"profiles\") {\n const profiles = loadGoldenTaskProfiles();\n if (profiles.length === BUILT_IN_GOLDEN_TASK_PROFILES.length) {\n console.log(`Built-in golden task profiles: ${BUILT_IN_GOLDEN_TASK_PROFILES.length}`);\n } else {\n console.log(`Golden task profiles: ${profiles.length} (${BUILT_IN_GOLDEN_TASK_PROFILES.length} built-in, ${profiles.length - BUILT_IN_GOLDEN_TASK_PROFILES.length} integration)`);\n }\n const runnable = goldenRunnableProfiles();\n for (const profile of profiles) {\n const executable = runnable.some((item) => item.id === profile.id) ? \" executable\" : \"\";\n console.log(`${profile.id} [${profile.platform}${executable}] ${profile.title}`);\n console.log(` ${profile.purpose}`);\n console.log(` capabilities: ${profile.requiredCapabilities.join(\", \")}`);\n }\n return 0;\n }\n\n if (action === \"list\") {\n if (summary.latestBySignature.length === 0) {\n console.log(\"No golden task records found.\");\n return 0;\n }\n for (const record of summary.latestBySignature) {\n const title = record.task?.title ?? record.signature;\n console.log(`${record.outcome.toUpperCase()} ${record.signature} ${title}`);\n }\n return 0;\n }\n\n console.log(`Golden tasks: ${summary.total} record(s), ${summary.signatures} signature(s), ${summary.passed} passed, ${summary.failed} failed.`);\n if (summary.failureReasons.length > 0) {\n console.log(\"Top failure reasons:\");\n for (const reason of summary.failureReasons.slice(0, 8)) console.log(`- ${reason.reason}: ${reason.count}`);\n }\n if (action === \"validate\") {\n if (problems.length === 0) {\n console.log(\"Golden suite validation passed.\");\n return 0;\n }\n console.log(\"Golden suite validation failed:\");\n for (const problem of problems) console.log(`- ${problem}`);\n return 1;\n }\n return 0;\n}\n","import { mkdir, readFile, readdir, stat, writeFile } from \"node:fs/promises\";\nimport { dirname, join, resolve } from \"node:path\";\n\ntype PackageJson = {\n scripts?: Record<string, unknown>;\n dependencies?: Record<string, unknown>;\n devDependencies?: Record<string, unknown>;\n};\n\ntype StackDetection = {\n projectTypes: string[];\n verificationCommands: string[];\n signals: string[];\n};\n\nasync function fileExists(path: string): Promise<boolean> {\n try {\n const entry = await stat(path);\n return entry.isFile() || entry.isDirectory();\n } catch {\n return false;\n }\n}\n\nasync function readPackageJson(workspace: string): Promise<PackageJson | null> {\n const packagePath = join(workspace, \"package.json\");\n try {\n return JSON.parse(await readFile(packagePath, \"utf8\")) as PackageJson;\n } catch {\n return null;\n }\n}\n\nfunction hasDependency(pkg: PackageJson | null, name: string): boolean {\n return !!pkg && (Object.hasOwn(pkg.dependencies ?? {}, name) || Object.hasOwn(pkg.devDependencies ?? {}, name));\n}\n\nfunction scriptCommand(pkg: PackageJson | null, scriptName: \"typecheck\" | \"build\" | \"test\"): string | null {\n const script = pkg?.scripts?.[scriptName];\n return typeof script === \"string\" && script.trim() ? `npm run ${scriptName}` : null;\n}\n\nasync function rootEntries(workspace: string): Promise<string[]> {\n try {\n return await readdir(workspace);\n } catch {\n return [];\n }\n}\n\nfunction unique(values: string[]): string[] {\n return [...new Set(values)];\n}\n\nasync function detectStack(workspace: string): Promise<StackDetection> {\n const pkg = await readPackageJson(workspace);\n const entries = await rootEntries(workspace);\n const hasPackageJson = pkg !== null;\n const hasPrisma = await fileExists(join(workspace, \"prisma\", \"schema.prisma\"));\n const hasNextConfig = entries.some((entry) => /^next\\.config\\.(?:js|mjs|cjs|ts)$/.test(entry));\n const hasTsconfig = await fileExists(join(workspace, \"tsconfig.json\"));\n const hasGradlew = await fileExists(join(workspace, \"gradlew\"));\n const xcodeProjects = entries.filter((entry) => entry.endsWith(\".xcodeproj\"));\n\n const projectTypes: string[] = [];\n if (hasNextConfig || hasDependency(pkg, \"next\")) projectTypes.push(\"Next.js\");\n if (hasGradlew) projectTypes.push(\"Android\");\n if (xcodeProjects.length > 0) projectTypes.push(\"iOS\");\n if (hasPackageJson && projectTypes.length === 0) projectTypes.push(\"Node\");\n if (projectTypes.length === 0) projectTypes.push(\"Unknown\");\n\n const verificationCommands = [\n scriptCommand(pkg, \"typecheck\") ?? (hasTsconfig ? \"npx tsc --noEmit\" : null),\n scriptCommand(pkg, \"build\"),\n scriptCommand(pkg, \"test\"),\n hasPrisma ? \"npx prisma generate\" : null,\n hasGradlew ? \"./gradlew assembleDebug --no-daemon\" : null,\n ...xcodeProjects.map((project) => `xcodebuild -list -project '${project}'`),\n ].filter((command): command is string => !!command);\n\n const signals = [\n hasPackageJson ? \"package.json\" : null,\n hasPrisma ? \"prisma/schema.prisma\" : null,\n hasNextConfig ? entries.find((entry) => /^next\\.config\\.(?:js|mjs|cjs|ts)$/.test(entry)) ?? \"next.config.*\" : null,\n hasTsconfig ? \"tsconfig.json\" : null,\n hasGradlew ? \"gradlew\" : null,\n ...xcodeProjects,\n ].filter((signal): signal is string => !!signal);\n\n return {\n projectTypes: unique(projectTypes),\n verificationCommands: unique(verificationCommands),\n signals: unique(signals),\n };\n}\n\nfunction buildInstructions(detection: StackDetection): string {\n const verificationLines = detection.verificationCommands.length > 0\n ? detection.verificationCommands.map((command) => `- \\`${command}\\``)\n : [\"- Add project-specific verification commands here.\"];\n const signalLines = detection.signals.length > 0\n ? detection.signals.map((signal) => `- ${signal}`)\n : [\"- No common stack markers detected.\"];\n\n return [\n \"# Tanya Project Instructions\",\n \"\",\n `Project type: ${detection.projectTypes.join(\" / \")}`,\n \"\",\n \"## Detected Stack Signals\",\n ...signalLines,\n \"\",\n \"## Verification Commands\",\n ...verificationLines,\n \"\",\n \"## Custom Instructions\",\n \"- Add project-specific rules, safety constraints, architecture notes, and preferred workflows here.\",\n \"\",\n ].join(\"\\n\");\n}\n\nexport async function initTanyaProject(cwd: string): Promise<string> {\n const workspace = resolve(cwd);\n const instructionsPath = join(workspace, \".tania\", \"INSTRUCTIONS.md\");\n const detection = await detectStack(workspace);\n await mkdir(dirname(instructionsPath), { recursive: true });\n try {\n await writeFile(instructionsPath, buildInstructions(detection), { encoding: \"utf8\", flag: \"wx\" });\n } catch (error) {\n const code = typeof error === \"object\" && error !== null && \"code\" in error ? String((error as { code?: unknown }).code) : \"\";\n if (code === \"EEXIST\") throw new Error(`${instructionsPath} already exists. Refusing to overwrite.`);\n throw error;\n }\n return instructionsPath;\n}\n","import type { TanyaRunContext } from \"./runContext\";\nimport { buildTaskBrief, type TanyaTaskBrief } from \"../tools/projectContextTools\";\nimport { materializeObsidianContext } from \"../obsidian/search\";\n\nexport type AutoRunContextOptions = {\n cwd: string;\n prompt: string;\n runContext?: TanyaRunContext;\n obsidianVault?: string | undefined;\n enableBrief?: boolean | undefined;\n enableObsidian?: boolean | undefined;\n keepContext?: boolean | undefined;\n};\n\nfunction unique(values: string[]): string[] {\n return [...new Set(values.filter((value) => value.trim().length > 0))];\n}\n\nfunction shouldTreatAsCodingTask(brief: TanyaTaskBrief, runContext?: TanyaRunContext): boolean {\n if (runContext?.task?.kind === \"coding\") return true;\n if (runContext?.expected_report && Object.keys(runContext.expected_report).length > 0) return true;\n if (runContext?.verification?.commands?.length) return true;\n if (runContext?.artifacts?.length || runContext?.contextFiles?.length) return true;\n return brief.signals.platforms.length > 0 || brief.signals.domains.length > 0;\n}\n\nexport async function buildAutoRunContext(options: AutoRunContextOptions): Promise<TanyaRunContext | undefined> {\n let runContext = options.runContext;\n let brief: TanyaTaskBrief | undefined;\n const instructions: string[] = [...(runContext?.instructions ?? [])];\n const contextFiles: NonNullable<TanyaRunContext[\"contextFiles\"]> = [...(runContext?.contextFiles ?? [])];\n const metadata: Record<string, unknown> = { ...(runContext?.metadata ?? {}) };\n const expectedReport: Record<string, unknown> = { ...(runContext?.expected_report ?? {}) };\n const verificationCommands = [...(runContext?.verification?.commands ?? [])];\n let didMaterializeContext = false;\n\n if (options.enableBrief !== false) {\n brief = await buildTaskBrief({\n workspace: options.cwd,\n task: options.prompt,\n });\n metadata.autoBrief = brief;\n metadata.autoBriefEnforceArtifacts = brief.artifacts.length > 0;\n instructions.push(\n \"Tanya generated an automatic task brief before the run. Use it to choose context files, artifacts, capability packs, tools, and verification.\",\n \"If the automatic task brief lists artifact candidates and you change code, read at least one relevant artifact or explicitly explain why none applies before the final report.\",\n );\n if (shouldTreatAsCodingTask(brief, runContext)) {\n expectedReport.verification = true;\n expectedReport.artifact_reuse = true;\n expectedReport.context_review = true;\n // Skip auto-recommended verification commands when the caller explicitly\n // overrode the list (e.g. via --require-verification). Preserves caller intent.\n if (!metadata.verificationOverridden) {\n for (const command of brief.verification) verificationCommands.push(command);\n }\n runContext = {\n ...(runContext ?? {}),\n task: {\n ...(runContext?.task ?? {}),\n kind: \"coding\",\n title: runContext?.task?.title ?? brief.task.slice(0, 120),\n },\n };\n }\n }\n\n if (options.enableObsidian !== false && options.obsidianVault?.trim()) {\n const materialized = await materializeObsidianContext({\n workspace: options.cwd,\n vaultPath: options.obsidianVault,\n query: options.prompt,\n maxResults: 5,\n ...(options.keepContext !== undefined ? { keepContext: options.keepContext } : {}),\n });\n if (materialized.contextFiles.length > 0) {\n didMaterializeContext = true;\n contextFiles.push(...materialized.contextFiles);\n metadata.obsidianContext = {\n vaultConfigured: true,\n noteCount: materialized.notes.length,\n notes: materialized.notes.map((note) => ({\n path: note.path,\n title: note.title,\n score: note.score,\n reason: note.reason,\n })),\n };\n instructions.push(\n \"Relevant Obsidian note excerpts were materialized under .tania/context/obsidian.\",\n \"Read relevant Obsidian context paths before implementing if the task depends on prior decisions, project memory, or historical fixes.\",\n );\n } else {\n metadata.obsidianContext = { vaultConfigured: true, noteCount: 0 };\n }\n }\n\n if (!brief && contextFiles.length === 0 && instructions.length === (runContext?.instructions?.length ?? 0)) {\n return runContext;\n }\n\n return {\n ...(runContext ?? {}),\n ...(runContext?.task ? { task: runContext.task } : {}),\n ...(contextFiles.length > 0 ? { contextFiles } : {}),\n ...(instructions.length > 0 ? { instructions: unique(instructions) } : {}),\n ...(verificationCommands.length > 0 ? { verification: { commands: unique(verificationCommands) } } : {}),\n ...(Object.keys(expectedReport).length > 0 ? { expected_report: expectedReport } : {}),\n metadata: {\n ...metadata,\n autoContext: true,\n tanyaMaterializedContext: didMaterializeContext,\n keepMaterializedContext: options.keepContext === true,\n ...(options.obsidianVault ? { obsidianVault: options.obsidianVault } : {}),\n },\n };\n}\n","import { readRunLogs } from \"../../memory/runLogs\";\nimport type { PermissionRulesConfig } from \"./schema\";\n\nexport const BUILT_IN_ALWAYS_ALLOW_SEED = [\n \"read_file:.*\",\n \"glob:.*\",\n \"list_files:.*\",\n \"run_shell:ls.*\",\n \"run_shell:git status.*\",\n \"run_shell:git diff.*\",\n];\n\nexport function suggestPermissionsFromRuns(workspace: string, limit = 100): PermissionRulesConfig {\n const counts = new Map<string, number>();\n for (const log of readRunLogs(workspace, limit)) {\n for (const file of log.changedFiles) {\n if (!file || file.startsWith(\".tania/\") || file.startsWith(\".tanya/\")) continue;\n const escaped = escapeRegex(JSON.stringify(file));\n counts.set(`write_file:.*${escaped}.*`, (counts.get(`write_file:.*${escaped}.*`) ?? 0) + 1);\n }\n if (log.blockers.length === 0) {\n counts.set(\"run_command:.*node.*\", (counts.get(\"run_command:.*node.*\") ?? 0) + 1);\n }\n }\n\n const frequent = [...counts.entries()]\n .sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))\n .slice(0, 25)\n .map(([pattern]) => pattern);\n\n return {\n version: 1,\n mode: \"ask\",\n alwaysAllow: unique([...BUILT_IN_ALWAYS_ALLOW_SEED, ...frequent]),\n alwaysDeny: [],\n alwaysAsk: [],\n pathRules: [],\n spendRules: [],\n };\n}\n\nfunction unique(values: string[]): string[] {\n return [...new Set(values)];\n}\n\nfunction escapeRegex(value: string): string {\n return value.replace(/[|\\\\{}()[\\]^$+?.]/g, \"\\\\$&\");\n}\n","import { resolve } from \"node:path\";\nimport { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { StdioServerTransport } from \"@modelcontextprotocol/sdk/server/stdio.js\";\nimport { z } from \"zod\";\nimport { captureGitSnapshot } from \"../agent/git\";\nimport { buildFinalManifest, ensureCodingReport } from \"../agent/report\";\nimport { runAgent, type RunAgentOptions } from \"../agent/runner\";\nimport { loadConfig } from \"../config/env\";\nimport type { TanyaEvent } from \"../events/types\";\nimport { createProvider } from \"../providers/factory\";\nimport type { ChatProvider } from \"../providers/types\";\nimport { readGoldenTaskMemory } from \"../memory/goldenTasks\";\nimport { loadPromptSkillPacks } from \"../agent/systemPrompt\";\n\nexport interface TanyaMcpServerOptions {\n defaultCwd?: string;\n providerFactory?: (cwd: string) => ChatProvider;\n runAgentFn?: (options: RunAgentOptions) => Promise<Awaited<ReturnType<typeof runAgent>>>;\n}\n\nexport function createTanyaMcpServer(options: TanyaMcpServerOptions = {}): McpServer {\n const server = new McpServer({ name: \"tanya\", version: \"0.10.0-beta.0\" });\n const defaultCwd = () => resolve(options.defaultCwd ?? process.cwd());\n\n server.registerTool(\"tanya.verify\", {\n description: \"Run Tanya's deterministic verifier for a workspace path.\",\n inputSchema: {\n path: z.string().optional(),\n },\n }, async (args) => {\n const workspace = resolve(args.path ?? defaultCwd());\n const beforeGitSnapshot = await captureGitSnapshot(workspace);\n const manifest = await buildFinalManifest({\n workspace,\n beforeGitSnapshot,\n changed: [],\n verificationLines: [],\n toolErrorCount: 0,\n readArtifactPaths: [],\n readContextPaths: [],\n createdArtifactPaths: [],\n blockers: [],\n prompt: \"MCP tanya.verify\",\n });\n const report = ensureCodingReport(\"\", manifest).trim();\n const validationErrors = manifest.validation?.issues.filter((issue) => issue.severity === \"error\") ?? [];\n const blockers = [...manifest.blockers, ...validationErrors.map((issue) => issue.message)];\n const verdict = blockers.length === 0 ? \"passed\" : \"failed\";\n return {\n structuredContent: { verdict, blockers, manifest },\n content: [{ type: \"text\" as const, text: report || \"No verifier evidence available for this workspace.\" }],\n };\n });\n\n server.registerTool(\"tanya.golden_task_search\", {\n description: \"Search Tanya golden task memory by substring across signature, title, outcome, and blockers.\",\n inputSchema: {\n query: z.string(),\n limit: z.number().optional(),\n },\n }, async (args) => {\n const query = args.query.toLowerCase();\n const limit = Math.max(1, Math.min(50, Math.floor(args.limit ?? 10)));\n const records = (await readGoldenTaskMemory(defaultCwd()))\n .filter((record) => JSON.stringify({\n signature: record.signature,\n title: record.task?.title,\n kind: record.task?.kind,\n outcome: record.outcome,\n blockers: record.blockers,\n }).toLowerCase().includes(query))\n .slice(-limit)\n .reverse();\n return {\n structuredContent: { records },\n content: [{ type: \"text\" as const, text: records.length ? JSON.stringify(records, null, 2) : \"No matching golden tasks.\" }],\n };\n });\n\n server.registerTool(\"tanya.run\", {\n description: \"Run a one-shot Tanya agent task.\",\n inputSchema: {\n prompt: z.string(),\n cwd: z.string().optional(),\n max_turns: z.number().optional(),\n },\n }, async (args, extra) => {\n const mcpDepth = typeof extra._meta?.[\"tanya/mcp-depth\"] === \"number\"\n ? extra._meta[\"tanya/mcp-depth\"]\n : 0;\n if (mcpDepth > 1) {\n return {\n isError: true,\n structuredContent: { ok: false, error: \"recursive MCP loop detected\", depth: mcpDepth },\n content: [{ type: \"text\" as const, text: \"recursive MCP loop detected: Tanya MCP depth > 1\" }],\n };\n }\n const cwd = resolve(args.cwd ?? defaultCwd());\n const provider = options.providerFactory ? options.providerFactory(cwd) : createProvider(loadConfig(cwd));\n const events: TanyaEvent[] = [];\n const run = options.runAgentFn ?? runAgent;\n const result = await run({\n provider,\n prompt: args.prompt,\n cwd,\n sink: async (event) => { events.push(event); },\n ...(args.max_turns !== undefined ? { maxTurns: Math.max(1, Math.floor(args.max_turns)) } : {}),\n signal: extra.signal,\n });\n const streamedEvents = events.filter((event) => event.type === \"subtask_started\" || event.type === \"subtask_completed\");\n return {\n structuredContent: {\n message: result.message,\n manifest: result.manifest,\n metrics: result.metrics,\n events: streamedEvents,\n },\n content: [{ type: \"text\" as const, text: result.message }],\n };\n });\n\n server.registerTool(\"tanya.skills_list\", {\n description: \"List Tanya skill packs loaded for a workspace.\",\n inputSchema: {\n cwd: z.string().optional(),\n },\n }, async (args) => {\n const cwd = resolve(args.cwd ?? defaultCwd());\n const skills = loadPromptSkillPacks(cwd).map((pack) => ({\n slug: pack.slug,\n title: pack.title,\n sourcePath: pack.sourcePath,\n tokens: pack.tokens,\n reason: pack.reason,\n }));\n return {\n structuredContent: { skills },\n content: [{ type: \"text\" as const, text: skills.length ? JSON.stringify(skills, null, 2) : \"No skill packs loaded.\" }],\n };\n });\n\n return server;\n}\n\nexport async function serveTanyaMcpServer(options: TanyaMcpServerOptions = {}): Promise<void> {\n const server = createTanyaMcpServer(options);\n await server.connect(new StdioServerTransport());\n}\n","import type { EvalSuite, EvalTask } from \"../schemas\";\n\nconst categories = [\n \"long-file-read-dedup\",\n \"large-tool-result-truncation\",\n \"reasoning-heavy-planning\",\n \"system-prompt-budget\",\n \"repo-map-targeting\",\n \"fuzzy-edit-recovery\",\n] as const;\n\nfunction ecoTask(index: number): EvalTask {\n const category = categories[index % categories.length] ?? \"long-file-read-dedup\";\n return {\n id: `eco-${String(index + 1).padStart(2, \"0\")}-${category}`,\n repo_setup: { type: \"local_fixture\", path: `builtin:eco-30/${category}` },\n prompt: ecoPrompt(category),\n expected_files: category === \"long-file-read-dedup\" ? [] : [`src/eco-${index + 1}.ts`],\n metadata: {\n category,\n providerTier: \"cheap\",\n measures: [\"input_tokens\", \"output_tokens\", \"reasoning_tokens\", \"system_prompt_tokens\", \"cost_usd\"],\n },\n };\n}\n\nexport function eco30Suite(): EvalSuite {\n return {\n name: \"eco-30\",\n version: \"2026-05\",\n tasks: Array.from({ length: 30 }, (_, index) => ecoTask(index)),\n };\n}\n\nfunction ecoPrompt(category: string): string {\n switch (category) {\n case \"long-file-read-dedup\":\n return \"Inspect a repeated long file read pattern and avoid resending unchanged content.\";\n case \"large-tool-result-truncation\":\n return \"Run a large-output verification command and use expand_result only for necessary ranges.\";\n case \"reasoning-heavy-planning\":\n return \"Plan a multi-file repair while staying within the reasoning token cap.\";\n case \"system-prompt-budget\":\n return \"Complete a small task under a tight system-prompt budget.\";\n case \"repo-map-targeting\":\n return \"Use structural context to identify the right file before reading broadly.\";\n case \"fuzzy-edit-recovery\":\n return \"Recover a near-match edit block without rewriting the entire file.\";\n default:\n return \"Complete the token-economy fixture.\";\n }\n}\n","import type { EvalSuite, EvalTask } from \"../schemas\";\n\ntype MvpTaskSpec = {\n id: string;\n title: string;\n prompt: string;\n expectedFiles: string[];\n capMinutes: number;\n capUsd: number;\n};\n\nconst tasks: MvpTaskSpec[] = [\n {\n id: \"mvp-01\",\n title: \"Python todo CLI\",\n prompt: [\n \"Build a one-file Python todo CLI with add, list, done, and delete commands.\",\n \"Persist tasks to a JSON file in the project directory.\",\n \"Include a short README with example commands.\",\n \"Verify it by running at least one add/list/done/delete flow.\",\n ].join(\" \"),\n expectedFiles: [\"todo.py\", \"README.md\"],\n capMinutes: 5,\n capUsd: 0.05,\n },\n {\n id: \"mvp-02\",\n title: \"Express notes REST API\",\n prompt: [\n \"Build a Node.js Express REST API for an in-memory notes resource.\",\n \"Implement GET /notes, POST /notes, PUT /notes/:id, and DELETE /notes/:id.\",\n \"Include package.json, server code, and README.md with curl examples.\",\n \"Use a conventional startup shape: export the Express app from src/server.js as module.exports/app/default, and only call app.listen when the file is run directly.\",\n \"Verify the app can start and the routes are wired.\",\n ].join(\" \"),\n expectedFiles: [\"package.json\", \"src/server.js\", \"README.md\"],\n capMinutes: 10,\n capUsd: 0.10,\n },\n {\n id: \"mvp-03\",\n title: \"Hacker News top stories scraper\",\n prompt: [\n \"Build a Python script that scrapes today's top 10 stories from news.ycombinator.com into stories.json.\",\n \"Use requests and beautifulsoup4.\",\n \"Include requirements.txt and README.md.\",\n \"If dependency install or live network access fails twice, pivot to a deterministic local mock fallback, still write stories.json, and document mock versus live behavior in README.md.\",\n \"Verify the script runs or document the exact network limitation if the live request is unavailable.\",\n ].join(\" \"),\n expectedFiles: [\"hn_top.py\", \"requirements.txt\", \"README.md\", \"stories.json\"],\n capMinutes: 5,\n capUsd: 0.05,\n },\n {\n id: \"mvp-04\",\n title: \"Static landing page\",\n prompt: [\n \"Build a static landing page using index.html and Tailwind via CDN.\",\n \"Include a hero, features section, pricing section, and footer.\",\n \"No build step. Keep it polished and readable.\",\n \"Verify the HTML is self-contained.\",\n ].join(\" \"),\n expectedFiles: [\"index.html\"],\n capMinutes: 10,\n capUsd: 0.10,\n },\n {\n id: \"mvp-05\",\n title: \"Python curses Snake game\",\n prompt: [\n \"Build a simple terminal Snake game in Python using curses.\",\n \"Include movement, food spawning, score display, collision handling, and graceful quit.\",\n \"Keep it in one file plus README.md.\",\n \"Verify syntax without requiring an interactive terminal.\",\n ].join(\" \"),\n expectedFiles: [\"snake.py\", \"README.md\"],\n capMinutes: 15,\n capUsd: 0.15,\n },\n {\n id: \"mvp-06\",\n title: \"JSON to CSV converter\",\n prompt: [\n \"Use the provided data/input.json fixture.\",\n \"Build a Python converter using pandas that writes output.csv with columns id,name,email,plan.\",\n \"Include requirements.txt and README.md.\",\n \"Verify the converter runs and output.csv has the expected header and row count.\",\n ].join(\" \"),\n expectedFiles: [\"convert.py\", \"requirements.txt\", \"README.md\", \"output.csv\"],\n capMinutes: 5,\n capUsd: 0.05,\n },\n {\n id: \"mvp-07\",\n title: \"Rust prime CLI\",\n prompt: [\n \"Build a Rust CLI that answers whether an integer is prime.\",\n \"Use cargo init or equivalent project structure.\",\n \"Support cargo run -- 17 and cargo run -- 18.\",\n \"Verify with cargo run and include README.md examples.\",\n ].join(\" \"),\n expectedFiles: [\"Cargo.toml\", \"src/main.rs\", \"README.md\"],\n capMinutes: 10,\n capUsd: 0.10,\n },\n {\n id: \"mvp-08\",\n title: \"Vitest fizzbuzz tests\",\n prompt: [\n \"The project already contains src/fizzbuzz.js.\",\n \"Write at least 5 Vitest unit tests covering fizz, buzz, fizzbuzz, normal numbers, and edge behavior.\",\n \"Add package.json if needed and verify npm test passes.\",\n \"Do not rewrite the implementation unless a test proves it is necessary.\",\n ].join(\" \"),\n expectedFiles: [\"src/fizzbuzz.js\", \"package.json\"],\n capMinutes: 5,\n capUsd: 0.05,\n },\n {\n id: \"mvp-09\",\n title: \"Fix Python stats bug\",\n prompt: [\n \"Fix the known bug in stats.py.\",\n \"The current script has an off-by-one error and does not handle None values.\",\n \"Make the smallest reasonable change, add or update tests if useful, and verify python stats.py runs successfully.\",\n ].join(\" \"),\n expectedFiles: [\"stats.py\"],\n capMinutes: 5,\n capUsd: 0.05,\n },\n {\n id: \"mvp-10\",\n title: \"Commander TypeScript CLI\",\n prompt: [\n \"Build a slash-command-style CLI tool in TypeScript using commander.\",\n \"Subcommands: init, add <item>, list, remove <id>.\",\n \"Persist data to a local JSON file.\",\n \"Use a conventional startup shape: export the Commander program from src/index.ts and call program.parse only when run as the CLI entry.\",\n \"Include package.json, tsconfig.json, source code, README.md, and verify the CLI commands run.\",\n ].join(\" \"),\n expectedFiles: [\"package.json\", \"tsconfig.json\", \"src/index.ts\", \"README.md\"],\n capMinutes: 15,\n capUsd: 0.15,\n },\n];\n\nexport function mvpSuite(): EvalSuite {\n return {\n name: \"mvp\",\n version: \"2026-05\",\n tasks: tasks.map(toEvalTask),\n };\n}\n\nfunction toEvalTask(task: MvpTaskSpec): EvalTask {\n return {\n id: task.id,\n repo_setup: { type: \"local_fixture\", path: `src/eval/suites/mvp-fixtures/${task.id}` },\n prompt: [\n task.prompt,\n \"\",\n \"First-time-user MVP validation criteria:\",\n `- Expected files: ${task.expectedFiles.join(\", \")}`,\n `- Soft cap: ${task.capMinutes} minutes / $${task.capUsd.toFixed(2)}.`,\n \"- Prefer simple, conventional code over clever abstractions.\",\n \"- Run the most relevant local verification command before finalizing.\",\n \"- Final report must state what was built, how it was verified, and any limitations.\",\n ].join(\"\\n\"),\n expected_files: task.expectedFiles,\n verifier_extension: `src/eval/suites/mvp-fixtures/${task.id}/verify.md`,\n metadata: {\n title: task.title,\n capMinutes: task.capMinutes,\n capUsd: task.capUsd,\n perspective: \"first-time-community-user\",\n },\n };\n}\n","import type { EvalSuite, EvalTask } from \"../schemas\";\n\nexport const SWE_BENCH_LITE_REPO = \"https://github.com/SWE-bench/SWE-bench.git\";\nexport const SWE_BENCH_LITE_COMMIT = \"f7bbbb2ccdf479001d6467c9e34af59e44a840f9\";\n\nexport function sweBenchLiteSuite(): EvalSuite {\n const tasks: EvalTask[] = Array.from({ length: 30 }, (_, index) => ({\n id: `swe-lite-${String(index + 1).padStart(2, \"0\")}`,\n repo_setup: {\n type: \"git_clone\",\n url: SWE_BENCH_LITE_REPO,\n commit: SWE_BENCH_LITE_COMMIT,\n path: `.tania/eval/datasets/swe-bench-lite/${String(index + 1).padStart(2, \"0\")}`,\n },\n prompt: `Run the pinned SWE-bench-Lite task ${index + 1} through Tanya's verifier-aware workflow.`,\n metadata: {\n dataset: \"SWE-bench-Lite\",\n pinnedCommit: SWE_BENCH_LITE_COMMIT,\n cacheDir: \".tania/eval/datasets/swe-bench-lite\",\n },\n }));\n return { name: \"swe-bench-lite\", version: `pinned-${SWE_BENCH_LITE_COMMIT.slice(0, 12)}`, tasks };\n}\n","import type { EvalSuite, EvalTask } from \"../schemas\";\n\nconst categories = [\n [\"long-bash\", \"Repair a long shell verification command and report the exact failing line.\"],\n [\"multi-file-edit\", \"Update two related TypeScript modules and keep their exports consistent.\"],\n [\"broken-patch\", \"Recover from a patch that does not apply cleanly by re-reading the file.\"],\n [\"dependency-install\", \"Add a tiny dependency and update the lockfile without unrelated churn.\"],\n [\"noop-confirmation\", \"Inspect the repo and confirm no code change is needed.\"],\n] as const;\n\nfunction nativeTask(index: number): EvalTask {\n const [category, prompt] = categories[index % categories.length] ?? categories[0];\n return {\n id: `native-${String(index + 1).padStart(2, \"0\")}-${category}`,\n repo_setup: { type: \"local_fixture\", path: `builtin:tanya-native/${category}` },\n prompt,\n expected_files: category === \"noop-confirmation\" ? [] : [`src/task-${index + 1}.ts`],\n metadata: { category, expectedVerdict: index % 7 === 0 ? \"failed\" : \"passed\" },\n };\n}\n\nexport function tanyaNativeSuite(): EvalSuite {\n return {\n name: \"tanya-native\",\n version: \"2026-05\",\n tasks: Array.from({ length: 25 }, (_, index) => nativeTask(index)),\n };\n}\n","import type { EvalSuite, EvalTask } from \"../schemas\";\n\nexport function verifierSelfTestSuite(): EvalSuite {\n const tasks: EvalTask[] = [\n verifierTask(\"verifier-self-01-correct-report\", \"passed\", \"Known-correct output includes changed files and passing verification.\"),\n verifierTask(\"verifier-self-02-missing-verification\", \"failed\", \"Known-incorrect output omits required verification evidence.\"),\n verifierTask(\"verifier-self-03-failed-test\", \"failed\", \"Known-incorrect output includes a failing test command.\"),\n verifierTask(\"verifier-self-04-noop-clean\", \"passed\", \"Known-correct no-op report has no changed files and no blockers.\"),\n ];\n return { name: \"verifier-self-test\", version: \"2026-05\", tasks };\n}\n\nfunction verifierTask(id: string, expectedVerdict: \"passed\" | \"failed\", prompt: string): EvalTask {\n return {\n id,\n repo_setup: { type: \"local_fixture\", path: `builtin:verifier-self-test/${id}` },\n prompt,\n metadata: {\n expectedVerifierVerdict: expectedVerdict,\n purpose: \"assert verifier classification, not model output\",\n },\n };\n}\n","import { readFileSync } from \"node:fs\";\nimport { discoverIntegrationEntries } from \"../../integrations/discovery\";\nimport type { EvalSuite, EvalTask } from \"../schemas\";\nimport { formatEvalSchemaIssues, validateEvalSuite } from \"../schemas\";\n\nexport type IntegrationSuiteFile = {\n name: string;\n version: string;\n tasks: EvalTask[];\n};\n\nfunction readJson(path: string): unknown {\n try {\n return JSON.parse(readFileSync(path, \"utf8\"));\n } catch {\n return null;\n }\n}\n\nfunction parseIntegrationSuite(path: string): EvalSuite | null {\n const parsed = readJson(path);\n const result = validateEvalSuite(parsed);\n if (result.ok) return result.data;\n console.warn(`[eval] Skipping integration suite ${path}: ${formatEvalSchemaIssues(result.issues)}`);\n return null;\n}\n\nexport function loadIntegrationEvalSuites(): EvalSuite[] {\n return discoverIntegrationEntries(\"suites\")\n .filter((entry) => entry.path.toLowerCase().endsWith(\".json\"))\n .map((entry) => parseIntegrationSuite(entry.path))\n .filter((suite): suite is EvalSuite => suite !== null);\n}\n","export type EvalRepoSetup =\n | { type: \"git_clone\"; url: string; commit: string; path?: string }\n | { type: \"local_fixture\"; path: string };\n\nexport type EvalTask = {\n id: string;\n repo_setup: EvalRepoSetup;\n prompt: string;\n expected_files?: string[];\n verifier_extension?: string;\n metadata?: Record<string, unknown>;\n};\n\nexport type EvalSuite = {\n name: string;\n version: string;\n tasks: EvalTask[];\n};\n\nexport type EvalSchemaIssue = {\n path: string;\n message: string;\n};\n\nexport type EvalValidationResult<T> =\n | { ok: true; data: T }\n | { ok: false; issues: EvalSchemaIssue[] };\n\nconst repoSetupTypes = new Set([\"git_clone\", \"local_fixture\"]);\n\nexport function validateEvalSuite(input: unknown): EvalValidationResult<EvalSuite> {\n const issues: EvalSchemaIssue[] = [];\n const root = asRecord(input);\n requireString(root, \"name\", \"/name\", issues);\n requireString(root, \"version\", \"/version\", issues);\n if (!Array.isArray(root?.tasks)) {\n issues.push({ path: \"/tasks\", message: \"tasks must be an array\" });\n } else {\n root.tasks.forEach((task, index) => validateTask(task, `/tasks/${index}`, issues));\n }\n return issues.length === 0 ? { ok: true, data: input as EvalSuite } : { ok: false, issues };\n}\n\nexport function assertEvalSuite(input: unknown): EvalSuite {\n const result = validateEvalSuite(input);\n if (result.ok) return result.data;\n throw new Error(formatEvalSchemaIssues(result.issues));\n}\n\nexport function formatEvalSchemaIssues(issues: EvalSchemaIssue[]): string {\n return issues.map((issue) => `${issue.path}: ${issue.message}`).join(\"\\n\");\n}\n\nfunction validateTask(input: unknown, path: string, issues: EvalSchemaIssue[]): void {\n const task = asRecord(input);\n requireString(task, \"id\", `${path}/id`, issues);\n requireString(task, \"prompt\", `${path}/prompt`, issues);\n validateRepoSetup(task?.repo_setup, `${path}/repo_setup`, issues);\n if (task?.expected_files !== undefined && !isStringArray(task.expected_files)) {\n issues.push({ path: `${path}/expected_files`, message: \"expected_files must be an array of strings\" });\n }\n if (task?.verifier_extension !== undefined && typeof task.verifier_extension !== \"string\") {\n issues.push({ path: `${path}/verifier_extension`, message: \"verifier_extension must be a string\" });\n }\n}\n\nfunction validateRepoSetup(input: unknown, path: string, issues: EvalSchemaIssue[]): void {\n const setup = asRecord(input);\n const type = typeof setup?.type === \"string\" ? setup.type : \"\";\n if (!repoSetupTypes.has(type)) {\n issues.push({ path: `${path}/type`, message: \"type must be git_clone or local_fixture\" });\n return;\n }\n if (type === \"git_clone\") {\n requireString(setup, \"url\", `${path}/url`, issues);\n requireString(setup, \"commit\", `${path}/commit`, issues);\n }\n if (type === \"local_fixture\") {\n requireString(setup, \"path\", `${path}/path`, issues);\n }\n}\n\nfunction asRecord(input: unknown): Record<string, unknown> | null {\n return input && typeof input === \"object\" && !Array.isArray(input)\n ? input as Record<string, unknown>\n : null;\n}\n\nfunction requireString(record: Record<string, unknown> | null, key: string, path: string, issues: EvalSchemaIssue[]): void {\n if (typeof record?.[key] !== \"string\" || !record[key]) {\n issues.push({ path, message: `${key} must be a non-empty string` });\n }\n}\n\nfunction isStringArray(value: unknown): value is string[] {\n return Array.isArray(value) && value.every((item) => typeof item === \"string\");\n}\n","import { estimateRunCost } from \"../../memory/runLogs\";\nimport type { EvalSuite } from \"../schemas\";\nimport { eco30Suite } from \"./eco30\";\nimport { mvpSuite } from \"./mvp\";\nimport { sweBenchLiteSuite } from \"./sweBenchLite\";\nimport { tanyaNativeSuite } from \"./tanya-native\";\nimport { verifierSelfTestSuite } from \"./verifierSelfTest\";\nimport { loadIntegrationEvalSuites } from \"./integrations\";\n\nexport type EvalSuiteName = \"swe-bench-lite\" | \"tanya-native\" | \"eco-30\" | \"mvp\" | \"verifier-self-test\";\n\nconst suiteLoaders: Record<EvalSuiteName, () => EvalSuite> = {\n \"swe-bench-lite\": sweBenchLiteSuite,\n \"tanya-native\": tanyaNativeSuite,\n \"eco-30\": eco30Suite,\n mvp: mvpSuite,\n \"verifier-self-test\": verifierSelfTestSuite,\n};\n\nexport type EvalDryRun = {\n suite: string;\n suiteVersion: string;\n taskCount: number;\n estimatedCostUsd: number | null;\n model: string;\n};\n\nfunction builtInSuiteNames(): EvalSuiteName[] {\n return Object.keys(suiteLoaders) as EvalSuiteName[];\n}\n\nexport function listEvalSuites(): string[] {\n const names = new Set<string>(builtInSuiteNames());\n for (const suite of loadIntegrationEvalSuites()) {\n if (!names.has(suite.name)) names.add(suite.name);\n }\n return [...names];\n}\n\nexport function loadEvalSuite(name: string): EvalSuite {\n const loader = suiteLoaders[name as EvalSuiteName];\n if (loader) return loader();\n\n const suite = loadIntegrationEvalSuites().find((candidate) => candidate.name === name);\n if (suite) return suite;\n\n throw new Error(`Unknown eval suite \"${name}\". Available: ${listEvalSuites().join(\", \")}`);\n}\n\nexport function dryRunEvalSuite(suite: EvalSuite, provider: string | undefined, model: string): EvalDryRun {\n const estimatedPromptTokens = suite.tasks.length * 14_000;\n const estimatedCompletionTokens = suite.tasks.length * 3_000;\n const estimate = estimateRunCost({\n ...(provider ? { provider } : {}),\n model,\n promptTokens: estimatedPromptTokens,\n completionTokens: estimatedCompletionTokens,\n });\n return {\n suite: suite.name,\n suiteVersion: suite.version,\n taskCount: suite.tasks.length,\n estimatedCostUsd: estimate.usd,\n model,\n };\n}\n","import { cp, mkdtemp, mkdir, readFile, rm, writeFile } from \"node:fs/promises\";\nimport { existsSync } from \"node:fs\";\nimport { tmpdir } from \"node:os\";\nimport { dirname, join, resolve } from \"node:path\";\nimport { execFileSync } from \"node:child_process\";\nimport { envValue, numberEnvValue } from \"../config/envCompat\";\nimport type { ChatProvider } from \"../providers/types\";\nimport { createJsonlSink } from \"../events/jsonl\";\nimport { runAgent } from \"../agent/runner\";\nimport { estimateRunCost } from \"../memory/runLogs\";\nimport type { EvalResult, EvalRunResult, EvalSuite, EvalTask, EvalTokensUsed } from \"./schemas\";\nimport { runVerifierExtension } from \"./verifierExtensions\";\n\nexport type EvalExecutionContext = {\n workspace: string;\n provider: string;\n model: string;\n timeoutMs: number;\n tokenCap: number;\n};\n\nexport type EvalExecutionOutcome = {\n verifierVerdict: \"passed\" | \"failed\";\n tokensUsed: EvalTokensUsed;\n costUsd: number;\n diff?: string;\n error?: string;\n};\n\nexport type EvalExecutor = (task: EvalTask, ctx: EvalExecutionContext) => Promise<EvalExecutionOutcome>;\n\nexport type RunEvalOptions = {\n cwd: string;\n provider: string;\n model: string;\n tanyaVersion: string;\n taskIds?: string[];\n parallel?: number;\n timeoutMs?: number;\n tokenCap?: number;\n executor?: EvalExecutor;\n providerFactory?: () => ChatProvider;\n keepWorkspaces?: boolean;\n};\n\nexport async function runEvalSuite(suite: EvalSuite, options: RunEvalOptions): Promise<EvalResult> {\n const timeoutMs = options.timeoutMs ?? numberEnvValue(process.env, \"TANYA_EVAL_TASK_TIMEOUT_MS\", 600_000);\n const tokenCap = options.tokenCap ?? numberEnvValue(process.env, \"TANYA_EVAL_TASK_TOKEN_CAP\", 500_000);\n const selected = options.taskIds?.length\n ? suite.tasks.filter((task) => options.taskIds?.includes(task.id))\n : suite.tasks;\n const missing = (options.taskIds ?? []).filter((id) => !suite.tasks.some((task) => task.id === id));\n if (missing.length > 0) throw new Error(`Unknown eval task id(s): ${missing.join(\", \")}`);\n\n const executor = options.executor ?? defaultExecutor(options);\n const runs: EvalRunResult[] = [];\n // Keep execution sequential for deterministic local logs. The CLI accepts\n // --parallel for forward compatibility; CI can raise it once provider and\n // fixture isolation have enough soak time.\n void (options.parallel ?? numberEnvValue(process.env, \"TANYA_EVAL_PARALLEL\", 4));\n for (const task of selected) {\n runs.push(await runOneTask(suite, task, options, executor, timeoutMs, tokenCap));\n }\n\n return {\n suite: suite.name,\n suiteVersion: suite.version,\n tanyaVersion: options.tanyaVersion,\n provider: options.provider,\n model: options.model,\n generatedAt: new Date().toISOString(),\n ...aggregateRuns(runs),\n runs,\n };\n}\n\nexport async function writeEvalResult(path: string, result: EvalResult): Promise<void> {\n await mkdir(dirname(path), { recursive: true });\n await writeFile(path, `${JSON.stringify(result, null, 2)}\\n`);\n}\n\nexport async function readEvalResult(path: string): Promise<EvalResult> {\n return JSON.parse(await readFile(path, \"utf8\")) as EvalResult;\n}\n\nasync function runOneTask(\n suite: EvalSuite,\n task: EvalTask,\n options: RunEvalOptions,\n executor: EvalExecutor,\n timeoutMs: number,\n tokenCap: number,\n): Promise<EvalRunResult> {\n const started = Date.now();\n let workspace = \"\";\n try {\n workspace = await setupEvalWorkspace(suite, task, options.cwd);\n const outcome = await withTimeout(\n executor(task, {\n workspace,\n provider: options.provider,\n model: options.model,\n timeoutMs,\n tokenCap,\n }),\n timeoutMs,\n );\n const status = outcome.verifierVerdict === \"passed\" ? \"passed\" : \"failed\";\n return {\n taskId: task.id,\n status,\n durationMs: Date.now() - started,\n tokensUsed: outcome.tokensUsed,\n costUsd: outcome.costUsd,\n verifierVerdict: outcome.verifierVerdict,\n ...(outcome.diff ? { diff: outcome.diff } : {}),\n ...(outcome.error ? { error: outcome.error } : {}),\n };\n } catch (err) {\n const timeout = err instanceof Error && err.message === \"eval task timeout\";\n return {\n taskId: task.id,\n status: timeout ? \"timeout\" : \"errored\",\n durationMs: Date.now() - started,\n tokensUsed: { input: 0, output: 0 },\n costUsd: 0,\n verifierVerdict: \"failed\",\n error: err instanceof Error ? err.message : String(err),\n };\n } finally {\n if (workspace && !options.keepWorkspaces) await rm(workspace, { recursive: true, force: true });\n }\n}\n\nasync function setupEvalWorkspace(suite: EvalSuite, task: EvalTask, cwd: string): Promise<string> {\n const workspace = await mkdtemp(join(tmpdir(), `tanya-eval-${suite.name}-${task.id}-`));\n if (task.repo_setup.type === \"local_fixture\" && !task.repo_setup.path.startsWith(\"builtin:\")) {\n const source = resolve(cwd, task.repo_setup.path);\n if (!existsSync(source)) throw new Error(`local fixture does not exist: ${source}`);\n await cp(source, workspace, { recursive: true });\n } else if (task.repo_setup.type === \"git_clone\") {\n execFileSync(\"git\", [\"clone\", \"--quiet\", task.repo_setup.url, workspace], { stdio: \"ignore\" });\n execFileSync(\"git\", [\"checkout\", \"--quiet\", task.repo_setup.commit], { cwd: workspace, stdio: \"ignore\" });\n } else {\n await writeFile(join(workspace, \"README.md\"), `# ${task.id}\\n\\n${task.prompt}\\n`);\n await mkdir(join(workspace, \"src\"), { recursive: true });\n await writeFile(join(workspace, \"src\", \"index.ts\"), \"export const status = 'pending';\\n\");\n }\n initializeGit(workspace);\n return workspace;\n}\n\nfunction initializeGit(workspace: string): void {\n try {\n execFileSync(\"git\", [\"init\"], { cwd: workspace, stdio: \"ignore\" });\n execFileSync(\"git\", [\"config\", \"user.email\", \"eval@tanya.local\"], { cwd: workspace, stdio: \"ignore\" });\n execFileSync(\"git\", [\"config\", \"user.name\", \"Tanya Eval\"], { cwd: workspace, stdio: \"ignore\" });\n execFileSync(\"git\", [\"add\", \".\"], { cwd: workspace, stdio: \"ignore\" });\n execFileSync(\"git\", [\"commit\", \"-m\", \"eval baseline\"], { cwd: workspace, stdio: \"ignore\" });\n } catch {\n // Git is useful for diffs but not required for accounting errored tasks.\n }\n}\n\nfunction defaultExecutor(options: RunEvalOptions): EvalExecutor {\n return async (task, ctx) => {\n if (!options.providerFactory) throw new Error(\"eval runner requires a providerFactory\");\n const provider = options.providerFactory();\n const outputChunks: string[] = [];\n const sink = createJsonlSink({\n write(chunk: string) {\n outputChunks.push(chunk);\n return true;\n },\n } as NodeJS.WritableStream);\n const result = await runAgent({\n provider,\n prompt: task.prompt,\n cwd: ctx.workspace,\n sink,\n maxTurns: 40,\n runContext: { task: { kind: \"coding\" } },\n });\n const diff = safeGitDiff(ctx.workspace);\n const tokensUsed: EvalTokensUsed = {\n input: result.metrics?.promptTokens ?? 0,\n output: result.metrics?.completionTokens ?? 0,\n reasoning: result.metrics?.reasoningTokens ?? 0,\n system_prompt: result.metrics?.systemPromptTokens ?? 0,\n repo_map: result.metrics?.repoMapTokens ?? 0,\n };\n const costUsd = estimateRunCost({\n provider: ctx.provider,\n model: ctx.model,\n promptTokens: tokensUsed.input,\n completionTokens: tokensUsed.output,\n ...(tokensUsed.reasoning !== undefined ? { reasoningTokens: tokensUsed.reasoning } : {}),\n }).usd ?? 0;\n const extension = await runVerifierExtension(task, ctx.workspace, options.cwd);\n const verifierVerdict = extension\n ? extension.ok ? \"passed\" : \"failed\"\n : result.manifest.blockers.length === 0 ? \"passed\" : \"failed\";\n const errors = extension\n ? extension.ok ? [] : extension.errors\n : result.manifest.blockers;\n return {\n verifierVerdict,\n tokensUsed,\n costUsd,\n ...(diff ? { diff } : {}),\n ...(errors.length > 0 ? { error: errors.join(\"\\n\") } : {}),\n };\n };\n}\n\nfunction safeGitDiff(workspace: string): string {\n try {\n return execFileSync(\"git\", [\"diff\", \"HEAD\"], { cwd: workspace, encoding: \"utf8\" });\n } catch {\n return \"\";\n }\n}\n\nasync function withTimeout<T>(promise: Promise<T>, timeoutMs: number): Promise<T> {\n let timer: ReturnType<typeof setTimeout> | undefined;\n const timeout = new Promise<never>((_, reject) => {\n timer = setTimeout(() => reject(new Error(\"eval task timeout\")), timeoutMs);\n timer.unref?.();\n });\n try {\n return await Promise.race([promise, timeout]);\n } finally {\n if (timer) clearTimeout(timer);\n }\n}\n\nexport function parseTaskFilter(raw: string | undefined): string[] | undefined {\n if (!raw?.trim()) return undefined;\n return raw.split(\",\").map((item) => item.trim()).filter(Boolean);\n}\n\nexport function aggregateRuns(runs: EvalRunResult[]): Pick<EvalResult, \"totalCostUsd\" | \"costPerPass\" | \"tokensPerPass\" | \"reasoningShare\"> {\n const totalCostUsd = runs.reduce((sum, run) => sum + run.costUsd, 0);\n const passed = runs.filter((run) => run.status === \"passed\").length;\n const totalInput = runs.reduce((sum, run) => sum + run.tokensUsed.input, 0);\n const totalOutput = runs.reduce((sum, run) => sum + run.tokensUsed.output, 0);\n const totalReasoning = runs.reduce((sum, run) => sum + (run.tokensUsed.reasoning ?? 0), 0);\n const totalTokens = totalInput + totalOutput + totalReasoning;\n return {\n totalCostUsd,\n costPerPass: passed > 0 ? totalCostUsd / passed : null,\n tokensPerPass: passed > 0 ? totalTokens / passed : null,\n reasoningShare: totalTokens > 0 ? totalReasoning / totalTokens : 0,\n };\n}\n","import { access, readFile, rm } from \"node:fs/promises\";\nimport { existsSync } from \"node:fs\";\nimport { execFile } from \"node:child_process\";\nimport { join, resolve } from \"node:path\";\nimport { promisify } from \"node:util\";\n\nconst execFileAsync = promisify(execFile);\n\nexport type MvpVerifierOutcome =\n | { ok: true; notes: string[] }\n | { ok: false; errors: string[] };\n\ntype CommandResult = {\n code: number;\n output: string;\n};\n\nexport async function runMvpVerifier(taskId: string, workspace: string, repoRoot: string): Promise<MvpVerifierOutcome | null> {\n if (taskId === \"mvp-02\") return verifyExpressNotesApi(workspace);\n if (taskId === \"mvp-03\") return verifyHnScraper(workspace);\n if (taskId === \"mvp-10\") return verifyCommanderCli(workspace, repoRoot);\n return null;\n}\n\nasync function verifyHnScraper(workspace: string): Promise<MvpVerifierOutcome> {\n const errors: string[] = [];\n for (const file of [\"hn_top.py\", \"requirements.txt\", \"README.md\", \"stories.json\"]) {\n if (!existsSync(join(workspace, file))) errors.push(`${file} is missing.`);\n }\n if (errors.length > 0) return { ok: false, errors };\n\n const requirements = await readFile(join(workspace, \"requirements.txt\"), \"utf8\");\n if (!/\\brequests\\b/i.test(requirements)) errors.push(\"requirements.txt must include requests.\");\n if (!/\\b(?:beautifulsoup4|bs4)\\b/i.test(requirements)) errors.push(\"requirements.txt must include beautifulsoup4.\");\n\n const readme = await readFile(join(workspace, \"README.md\"), \"utf8\");\n if (!/\\b(?:mock|fallback|sample|offline|network unavailable|network limitation)\\b/i.test(readme)) {\n errors.push(\"README.md must document mock/offline fallback behavior for unavailable live network access.\");\n }\n\n try {\n const parsed = JSON.parse(await readFile(join(workspace, \"stories.json\"), \"utf8\")) as unknown;\n const stories = Array.isArray(parsed)\n ? parsed\n : parsed && typeof parsed === \"object\" && Array.isArray((parsed as { stories?: unknown }).stories)\n ? (parsed as { stories: unknown[] }).stories\n : null;\n if (!stories) errors.push(\"stories.json must be an array or an object with a stories array.\");\n else {\n if (stories.length > 10) errors.push(\"stories.json must contain at most 10 stories.\");\n if (stories.length === 0) errors.push(\"stories.json should include deterministic sample stories when live network access is unavailable.\");\n if (!stories.every((story) => story && typeof story === \"object\" && typeof (story as { title?: unknown }).title === \"string\")) {\n errors.push(\"Each story must include a title.\");\n }\n }\n } catch (error) {\n errors.push(`stories.json is not valid JSON: ${error instanceof Error ? error.message : String(error)}`);\n }\n\n return errors.length > 0 ? { ok: false, errors } : { ok: true, notes: [\"HN scraper fallback artifact verified.\"] };\n}\n\nasync function verifyExpressNotesApi(workspace: string): Promise<MvpVerifierOutcome> {\n const candidates = [\"src/server.js\", \"src/index.js\", \"server.js\", \"app.js\"]\n .filter((file) => existsSync(join(workspace, file)));\n if (candidates.length === 0) {\n return { ok: false, errors: [\"No Express entry file found. Expected src/server.js, src/index.js, server.js, or app.js.\"] };\n }\n\n const script = String.raw`\nconst { existsSync } = require(\"node:fs\");\nconst http = require(\"node:http\");\nconst { pathToFileURL } = require(\"node:url\");\nconst { spawn } = require(\"node:child_process\");\n\nconst entries = ${JSON.stringify(candidates)};\n\nfunction request(port, method, path, body) {\n return new Promise((resolve, reject) => {\n const req = http.request({\n hostname: \"127.0.0.1\",\n port,\n path,\n method,\n headers: body ? { \"Content-Type\": \"application/json\" } : {},\n }, (res) => {\n let data = \"\";\n res.on(\"data\", (chunk) => { data += chunk; });\n res.on(\"end\", () => resolve({ status: res.statusCode || 0, body: data }));\n });\n req.on(\"error\", reject);\n if (body) req.write(JSON.stringify(body));\n req.end();\n });\n}\n\nfunction assertStatus(response, accepted, label) {\n if (!accepted.includes(response.status)) {\n throw new Error(label + \" returned HTTP \" + response.status + \" with body \" + response.body);\n }\n}\n\nasync function testRoutes(port) {\n assertStatus(await request(port, \"GET\", \"/notes\"), [200], \"GET /notes\");\n const created = await request(port, \"POST\", \"/notes\", { title: \"test\", content: \"hello\" });\n assertStatus(created, [200, 201], \"POST /notes\");\n let id = 1;\n try {\n const parsed = JSON.parse(created.body);\n id = parsed.id ?? parsed.note?.id ?? parsed.data?.id ?? 1;\n } catch {}\n assertStatus(await request(port, \"GET\", \"/notes\"), [200], \"GET /notes after create\");\n assertStatus(await request(port, \"PUT\", \"/notes/\" + encodeURIComponent(String(id)), { title: \"test\", content: \"world\" }), [200, 204], \"PUT /notes/:id\");\n assertStatus(await request(port, \"DELETE\", \"/notes/\" + encodeURIComponent(String(id))), [200, 202, 204], \"DELETE /notes/:id\");\n}\n\nasync function loadModule(entry) {\n try {\n return require(\"./\" + entry);\n } catch (err) {\n if (!/(ERR_REQUIRE_ESM|Cannot use import statement|Unexpected token 'export')/.test(String(err && (err.stack || err.message || err)))) throw err;\n return import(pathToFileURL(process.cwd() + \"/\" + entry).href);\n }\n}\n\nasync function verifyExportShape(entry) {\n const loaded = await loadModule(entry);\n const candidates = [\n loaded,\n loaded && loaded.default,\n loaded && loaded.app,\n loaded && loaded.server,\n loaded && typeof loaded.createApp === \"function\" ? loaded.createApp() : null,\n ].filter(Boolean);\n for (const app of candidates) {\n if (typeof app.listen !== \"function\") continue;\n const server = await new Promise((resolve, reject) => {\n const s = app.listen(0, \"127.0.0.1\", () => resolve(s));\n s.once(\"error\", reject);\n });\n try {\n const address = server.address();\n const port = typeof address === \"object\" && address ? address.port : 0;\n await testRoutes(port);\n return \"export:\" + entry;\n } finally {\n await new Promise((resolve) => server.close(resolve));\n }\n }\n throw new Error(\"No exported Express app with .listen() found in \" + entry);\n}\n\nasync function waitForServer(port, timeoutMs) {\n const started = Date.now();\n while (Date.now() - started < timeoutMs) {\n try {\n await request(port, \"GET\", \"/notes\");\n return;\n } catch {\n await new Promise((resolve) => setTimeout(resolve, 100));\n }\n }\n throw new Error(\"Timed out waiting for server on port \" + port);\n}\n\nasync function verifyScriptShape(entry) {\n const port = 3101;\n const child = spawn(process.execPath, [entry], {\n cwd: process.cwd(),\n env: { ...process.env, PORT: String(port), NODE_ENV: \"test\" },\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\n });\n let output = \"\";\n child.stdout.on(\"data\", (chunk) => { output += chunk.toString(); });\n child.stderr.on(\"data\", (chunk) => { output += chunk.toString(); });\n try {\n await waitForServer(port, 1500);\n await testRoutes(port);\n return \"script:\" + entry;\n } finally {\n child.kill(\"SIGTERM\");\n setTimeout(() => child.kill(\"SIGKILL\"), 500).unref();\n }\n}\n\n(async () => {\n const errors = [];\n for (const entry of entries) {\n try {\n const via = await verifyExportShape(entry);\n console.log(\"verified \" + via);\n return;\n } catch (err) {\n errors.push(entry + \" export shape: \" + (err && err.message ? err.message : String(err)));\n }\n }\n for (const entry of entries) {\n try {\n const via = await verifyScriptShape(entry);\n console.log(\"verified \" + via);\n return;\n } catch (err) {\n errors.push(entry + \" script shape: \" + (err && err.message ? err.message : String(err)));\n }\n }\n console.error(errors.join(\"\\n\"));\n process.exit(1);\n})().catch((err) => {\n console.error(err && err.stack ? err.stack : String(err));\n process.exit(1);\n});\n`;\n\n const result = await runNodeScript(workspace, script, 20_000);\n if (result.code === 0) return { ok: true, notes: [result.output.trim() || \"Express routes verified.\"] };\n return { ok: false, errors: [`Express route verification failed: ${result.output}`] };\n}\n\nasync function verifyCommanderCli(workspace: string, repoRoot: string): Promise<MvpVerifierOutcome> {\n const packageJsonPath = join(workspace, \"package.json\");\n if (!existsSync(packageJsonPath)) return { ok: false, errors: [\"package.json is missing.\"] };\n const packageJson = JSON.parse(await readFile(packageJsonPath, \"utf8\")) as {\n bin?: string | Record<string, string>;\n scripts?: Record<string, string>;\n dependencies?: Record<string, string>;\n devDependencies?: Record<string, string>;\n };\n const source = existsSync(join(workspace, \"src\", \"index.ts\"))\n ? await readFile(join(workspace, \"src\", \"index.ts\"), \"utf8\")\n : \"\";\n const hasCommander = Boolean(packageJson.dependencies?.commander || packageJson.devDependencies?.commander || /\\bfrom\\s+[\"']commander[\"']|\\brequire\\([\"']commander[\"']\\)/.test(source));\n if (!hasCommander) return { ok: false, errors: [\"Commander dependency/import was not found.\"] };\n\n if (packageJson.scripts?.build) {\n await runCommand(workspace, \"npm\", [\"run\", \"build\"], 90_000).catch(() => undefined);\n }\n\n const command = await resolveCliCommand(workspace, repoRoot, packageJson);\n if (!command) {\n return { ok: false, errors: [\"No runnable CLI entry found. Expected dist/index.js, src/index.ts, src/index.js, or package.json bin.\"] };\n }\n\n const nodePath = [join(repoRoot, \"node_modules\"), process.env.NODE_PATH].filter(Boolean).join(\":\");\n const env = nodePath ? { NODE_PATH: nodePath } : {};\n\n await rm(join(workspace, \".mvp10\"), { recursive: true, force: true }).catch(() => undefined);\n\n const errors: string[] = [];\n const init = await runCommand(workspace, command.cmd, [...command.args, \"init\"], 20_000, env);\n if (init.code !== 0) errors.push(`init failed: ${init.output}`);\n const add = await runCommand(workspace, command.cmd, [...command.args, \"add\", \"Buy milk\"], 20_000, env);\n if (add.code !== 0) errors.push(`add failed: ${add.output}`);\n const list = await runCommand(workspace, command.cmd, [...command.args, \"list\"], 20_000, env);\n if (list.code !== 0 || !/Buy milk/i.test(list.output)) errors.push(`list did not show persisted item: ${list.output}`);\n const itemId = itemIdFromListOutput(list.output, \"Buy milk\") ?? \"1\";\n const remove = await runCommand(workspace, command.cmd, [...command.args, \"remove\", itemId], 20_000, env);\n if (remove.code !== 0) errors.push(`remove existing item failed: ${remove.output}`);\n const missingRemove = await runCommand(workspace, command.cmd, [...command.args, \"remove\", \"99\"], 20_000, env);\n if (missingRemove.code !== 0 && !/\\b(not found|no item|missing|does not exist|unknown id|invalid id)\\b/i.test(missingRemove.output)) {\n errors.push(`remove missing id failed without a clear negative-path message: ${missingRemove.output}`);\n }\n\n if (errors.length > 0) return { ok: false, errors };\n return { ok: true, notes: [`Commander CLI verified via ${command.cmd} ${command.args.join(\" \")}`.trim()] };\n}\n\nfunction itemIdFromListOutput(output: string, itemLabel: string): string | null {\n const escapedLabel = itemLabel.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n for (const line of output.split(/\\r?\\n/)) {\n if (!new RegExp(escapedLabel, \"i\").test(line)) continue;\n const direct = line.match(/\\b(?:id|#)\\s*[:=]?\\s*([A-Za-z0-9_-]{1,36})\\b/i)?.[1];\n if (direct) return direct;\n const leading = line.match(/^\\s*(?:[-*]\\s*)?([A-Za-z0-9_-]{1,36})\\s*(?:[).:-]|\\s+-\\s+)/)?.[1];\n if (leading) return leading;\n }\n return null;\n}\n\nasync function resolveCliCommand(\n workspace: string,\n repoRoot: string,\n packageJson: { bin?: string | Record<string, string> },\n): Promise<{ cmd: string; args: string[] } | null> {\n const binValue = typeof packageJson.bin === \"string\"\n ? packageJson.bin\n : packageJson.bin ? Object.values(packageJson.bin)[0] : undefined;\n const candidates = [\n binValue,\n \"dist/index.js\",\n \"dist/cli.js\",\n \"src/index.js\",\n ].filter((entry): entry is string => Boolean(entry));\n for (const entry of candidates) {\n if (existsSync(join(workspace, entry))) return { cmd: process.execPath, args: [entry] };\n }\n const tsEntry = join(workspace, \"src\", \"index.ts\");\n if (existsSync(tsEntry)) {\n const tsxCli = join(repoRoot, \"node_modules\", \"tsx\", \"dist\", \"cli.mjs\");\n await access(tsxCli);\n return { cmd: process.execPath, args: [tsxCli, \"src/index.ts\"] };\n }\n return null;\n}\n\nasync function runNodeScript(cwd: string, script: string, timeoutMs: number): Promise<CommandResult> {\n return runCommand(cwd, process.execPath, [\"-e\", script], timeoutMs);\n}\n\nasync function runCommand(cwd: string, command: string, args: string[], timeoutMs: number, envOverrides: Record<string, string> = {}): Promise<CommandResult> {\n try {\n const { stdout, stderr } = await execFileAsync(command, args, {\n cwd,\n timeout: timeoutMs,\n maxBuffer: 4 * 1024 * 1024,\n env: { ...process.env, ...envOverrides },\n });\n return { code: 0, output: `${stdout}${stderr ? `\\n${stderr}` : \"\"}`.trim() };\n } catch (error) {\n const err = error as { code?: number; stdout?: string; stderr?: string; message?: string };\n const output = `${err.stdout ?? \"\"}${err.stderr ? `\\n${err.stderr}` : \"\"}`.trim() || err.message || \"command failed\";\n return { code: typeof err.code === \"number\" ? err.code : 1, output };\n }\n}\n","import type { EvalTask } from \"./schemas\";\nimport { runMvpVerifier, type MvpVerifierOutcome } from \"./mvpVerifier\";\n\nexport type VerifierExtensionOutcome = MvpVerifierOutcome;\n\nexport async function runVerifierExtension(task: EvalTask, workspace: string, repoRoot: string): Promise<VerifierExtensionOutcome | null> {\n if (!task.verifier_extension) return null;\n if (task.verifier_extension.includes(\"/mvp-fixtures/\")) {\n return runMvpVerifier(task.id, workspace, repoRoot);\n }\n return null;\n}\n","import type { EvalResult, EvalRunResult } from \"./schemas\";\n\nexport type EvalReportFormat = \"text\" | \"markdown\";\n\nexport function formatEvalReport(result: EvalResult, format: EvalReportFormat = \"text\"): string {\n const total = result.runs.length;\n const passed = result.runs.filter((run) => run.status === \"passed\").length;\n const failed = result.runs.filter((run) => run.status === \"failed\").length;\n const errored = result.runs.filter((run) => run.status === \"errored\").length;\n const timeout = result.runs.filter((run) => run.status === \"timeout\").length;\n const totalCost = result.runs.reduce((sum, run) => sum + run.costUsd, 0);\n const costPerTask = total > 0 ? totalCost / total : 0;\n const slowest = [...result.runs].sort((a, b) => b.durationMs - a.durationMs).slice(0, 3);\n const costliest = [...result.runs].sort((a, b) => b.costUsd - a.costUsd).slice(0, 3);\n\n if (format === \"markdown\") {\n return [\n `## Eval Report: ${result.suite}`,\n \"\",\n `- Version: ${result.suiteVersion}`,\n `- Model: ${result.provider ? `${result.provider}/` : \"\"}${result.model}`,\n `- Pass rate: ${percent(passed, total)} (${passed}/${total})`,\n `- Status: ${passed} passed, ${failed} failed, ${errored} errored, ${timeout} timeout`,\n `- Total cost: ${usd(totalCost)}`,\n `- Cost/task: ${usd(costPerTask)}`,\n `- Reasoning share: ${((result.reasoningShare ?? 0) * 100).toFixed(1)}%`,\n \"\",\n markdownRunTable(\"Slowest tasks\", slowest, \"duration\"),\n \"\",\n markdownRunTable(\"Costliest tasks\", costliest, \"cost\"),\n \"\",\n ].join(\"\\n\");\n }\n\n return [\n `Eval report: ${result.suite}@${result.suiteVersion}`,\n `Model: ${result.provider ? `${result.provider}/` : \"\"}${result.model}`,\n `Pass rate: ${percent(passed, total)} (${passed}/${total})`,\n `Status: ${passed} passed, ${failed} failed, ${errored} errored, ${timeout} timeout`,\n `Total cost: ${usd(totalCost)}`,\n `Cost/task: ${usd(costPerTask)}`,\n `Reasoning share: ${((result.reasoningShare ?? 0) * 100).toFixed(1)}%`,\n \"\",\n \"Slowest tasks:\",\n ...slowest.map((run) => `- ${run.taskId}: ${seconds(run.durationMs)} (${run.status})`),\n \"\",\n \"Costliest tasks:\",\n ...costliest.map((run) => `- ${run.taskId}: ${usd(run.costUsd)} (${run.status})`),\n \"\",\n ].join(\"\\n\");\n}\n\nfunction markdownRunTable(title: string, runs: EvalRunResult[], metric: \"duration\" | \"cost\"): string {\n const rows = [\n `### ${title}`,\n \"\",\n \"| Task | Status | Metric |\",\n \"| --- | --- | ---: |\",\n ];\n for (const run of runs) {\n rows.push(`| \\`${run.taskId}\\` | ${run.status} | ${metric === \"duration\" ? seconds(run.durationMs) : usd(run.costUsd)} |`);\n }\n return rows.join(\"\\n\");\n}\n\nfunction percent(numerator: number, denominator: number): string {\n if (denominator === 0) return \"0.0%\";\n return `${((numerator / denominator) * 100).toFixed(1)}%`;\n}\n\nfunction seconds(ms: number): string {\n return `${(ms / 1000).toFixed(1)}s`;\n}\n\nfunction usd(value: number): string {\n return `$${value.toFixed(4)}`;\n}\n","import type { EvalResult } from \"./schemas\";\n\nexport type EvalComparison = {\n baselineSuite: string;\n newSuite: string;\n costRegressionThreshold: number;\n regressions: Array<{ taskId: string; reason: string }>;\n improvements: Array<{ taskId: string; reason: string }>;\n};\n\nexport function compareEvalResults(baseline: EvalResult, next: EvalResult, costRegressionThreshold = 0.20): EvalComparison {\n const baselineByTask = new Map(baseline.runs.map((run) => [run.taskId, run]));\n const regressions: EvalComparison[\"regressions\"] = [];\n const improvements: EvalComparison[\"improvements\"] = [];\n for (const run of next.runs) {\n const previous = baselineByTask.get(run.taskId);\n if (!previous) continue;\n if (previous.verifierVerdict === \"passed\" && run.verifierVerdict === \"failed\") {\n regressions.push({ taskId: run.taskId, reason: \"verdict drift: passed -> failed\" });\n }\n if (previous.status !== \"errored\" && run.status === \"errored\") {\n regressions.push({ taskId: run.taskId, reason: \"new error\" });\n }\n if (previous.status !== \"timeout\" && run.status === \"timeout\") {\n regressions.push({ taskId: run.taskId, reason: \"new timeout\" });\n }\n if (previous.costUsd > 0 && run.costUsd >= previous.costUsd * (1 + costRegressionThreshold)) {\n regressions.push({\n taskId: run.taskId,\n reason: `cost regression: ${usd(previous.costUsd)} -> ${usd(run.costUsd)} (+${(((run.costUsd / previous.costUsd) - 1) * 100).toFixed(1)}%)`,\n });\n }\n if (previous.verifierVerdict === \"failed\" && run.verifierVerdict === \"passed\") {\n improvements.push({ taskId: run.taskId, reason: \"verdict improved: failed -> passed\" });\n }\n }\n if (baseline.totalCostUsd > 0 && next.totalCostUsd >= baseline.totalCostUsd * (1 + costRegressionThreshold)) {\n regressions.push({\n taskId: \"__suite__\",\n reason: `suite cost regression: ${usd(baseline.totalCostUsd)} -> ${usd(next.totalCostUsd)}`,\n });\n }\n return {\n baselineSuite: `${baseline.suite}@${baseline.suiteVersion}`,\n newSuite: `${next.suite}@${next.suiteVersion}`,\n costRegressionThreshold,\n regressions,\n improvements,\n };\n}\n\nexport function formatEvalComparison(comparison: EvalComparison, format: \"text\" | \"markdown\" = \"text\"): string {\n if (format === \"markdown\") {\n return [\n `## Eval Compare`,\n \"\",\n `- Baseline: ${comparison.baselineSuite}`,\n `- New: ${comparison.newSuite}`,\n `- Cost threshold: ${(comparison.costRegressionThreshold * 100).toFixed(0)}%`,\n `- Regressions: ${comparison.regressions.length}`,\n `- Improvements: ${comparison.improvements.length}`,\n \"\",\n markdownList(\"Regressions\", comparison.regressions),\n \"\",\n markdownList(\"Improvements\", comparison.improvements),\n \"\",\n ].join(\"\\n\");\n }\n return [\n `Eval compare: ${comparison.baselineSuite} -> ${comparison.newSuite}`,\n `Cost threshold: ${(comparison.costRegressionThreshold * 100).toFixed(0)}%`,\n `Regressions: ${comparison.regressions.length}`,\n ...comparison.regressions.map((item) => `- ${item.taskId}: ${item.reason}`),\n `Improvements: ${comparison.improvements.length}`,\n ...comparison.improvements.map((item) => `- ${item.taskId}: ${item.reason}`),\n \"\",\n ].join(\"\\n\");\n}\n\nfunction usd(value: number): string {\n return `$${value.toFixed(4)}`;\n}\n\nfunction markdownList(title: string, items: Array<{ taskId: string; reason: string }>): string {\n const lines = [`### ${title}`];\n if (items.length === 0) return [...lines, \"\", \"None.\"].join(\"\\n\");\n return [...lines, \"\", ...items.map((item) => `- \\`${item.taskId}\\`: ${item.reason}`)].join(\"\\n\");\n}\n","import type { EventSink, TanyaEvent } from \"../events/types\";\n\nexport interface CosmoChatFinalizeOptions {\n env?: NodeJS.ProcessEnv;\n fetchImpl?: typeof fetch;\n}\n\ntype RunStatus = \"succeeded\" | \"failed\";\n\ninterface FinalizeConfig {\n runId: string;\n endpoint: string;\n token?: string;\n graceMs: number;\n fetchImpl: typeof fetch;\n}\n\nexport function createCosmoChatFinalizeSink(sink: EventSink, options: CosmoChatFinalizeOptions = {}): EventSink {\n const config = resolveFinalizeConfig(options);\n if (!config) return sink;\n\n let finalized = false;\n let messageEndTimer: NodeJS.Timeout | undefined;\n\n const clearMessageEndTimer = () => {\n if (!messageEndTimer) return;\n clearTimeout(messageEndTimer);\n messageEndTimer = undefined;\n };\n\n const finalize = (status: RunStatus, error?: string) => {\n if (finalized) return;\n finalized = true;\n clearMessageEndTimer();\n void patchCosmoChatRun(config, status, error).catch(() => {});\n };\n\n return async (event: TanyaEvent) => {\n await sink(event);\n\n if (event.type === \"message_end\") {\n clearMessageEndTimer();\n messageEndTimer = setTimeout(() => {\n finalize(\"failed\", `timeout: message_end without follow-up event for ${config.graceMs}ms`);\n }, config.graceMs);\n return;\n }\n\n if (event.type === \"tool_call\" || event.type === \"tool_result\" || event.type === \"message_start\") {\n clearMessageEndTimer();\n return;\n }\n\n if (event.type === \"error\") {\n finalize(\"failed\", event.message);\n return;\n }\n\n if (event.type === \"final\") {\n finalize(finalEventStatus(event), finalEventError(event));\n }\n };\n}\n\nfunction resolveFinalizeConfig(options: CosmoChatFinalizeOptions): FinalizeConfig | null {\n const env = options.env ?? process.env;\n const runId = env.COSMOCHAT_RUN_ID || env.TANYA_COSMOCHAT_RUN_ID;\n const explicitURL = env.COSMOCHAT_RUN_FINALIZE_URL || env.TANYA_COSMOCHAT_RUN_FINALIZE_URL;\n const baseURL = env.COSMOCHAT_BASE_URL || env.TANYA_COSMOCHAT_BASE_URL;\n const endpoint = explicitURL || (runId && baseURL ? `${baseURL.replace(/\\/$/, \"\")}/v1/runs/${encodeURIComponent(runId)}` : \"\");\n if (!runId || !endpoint) return null;\n\n const fetchImpl = options.fetchImpl ?? globalThis.fetch;\n if (!fetchImpl) return null;\n const graceMs = Math.max(0, Number(env.TANYA_COSMOCHAT_MESSAGE_END_GRACE_MS ?? env.COSMOCHAT_MESSAGE_END_GRACE_MS ?? 30_000));\n const token = env.COSMOCHAT_SERVICE_TOKEN || env.TANYA_COSMOCHAT_SERVICE_TOKEN;\n return {\n runId,\n endpoint,\n ...(token ? { token } : {}),\n graceMs,\n fetchImpl,\n };\n}\n\nasync function patchCosmoChatRun(config: FinalizeConfig, status: RunStatus, error?: string): Promise<void> {\n const headers: Record<string, string> = { \"content-type\": \"application/json\" };\n if (config.token) headers.authorization = `Bearer ${config.token}`;\n await config.fetchImpl(config.endpoint, {\n method: \"PATCH\",\n headers,\n body: JSON.stringify({\n status,\n ...(error ? { error } : {}),\n }),\n });\n}\n\nfunction finalEventStatus(event: Extract<TanyaEvent, { type: \"final\" }>): RunStatus {\n const message = event.message || \"\";\n const blockers = Array.isArray(event.manifest?.blockers) ? event.manifest.blockers : [];\n if (/TANIA RESULT:\\s*FAIL/i.test(message) || blockers.length > 0) return \"failed\";\n return \"succeeded\";\n}\n\nfunction finalEventError(event: Extract<TanyaEvent, { type: \"final\" }>): string | undefined {\n if (finalEventStatus(event) !== \"failed\") return undefined;\n const blockers = Array.isArray(event.manifest?.blockers) ? event.manifest.blockers.filter((item): item is string => typeof item === \"string\") :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;AACH;AAEA,KAAK,EAAE,MAAM,CAAC,QAAQ;AACpB,QAAM,UAAU,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG;AAC/D,UAAQ,MAAM,gBAAgB,OAAO,EAAE;AACvC,UAAQ,WAAW;AACrB,CAAC;","names":["existsSync","readFileSync","join","resolve","existsSync","keep","_oneOf","rest","seconds","resolve","id","existsSync","mkdirSync","readFileSync","writeFileSync","join","resolve","gaveUp","runCommand","testCmd","existsSync","readFileSync","join","usd","seconds","dirname","isAbsolute","join","spawnSync","spawnSync","isAbsolute","join","scaled","basename","mkdtemp","dirname","readFileSync","readFileSync","mkdir","writeFile","join","join","mkdir","writeFile","mkdir","readFile","readdir","writeFile","dirname","join","resolve","unique","unique","unique","resolve","resolve","run","tasks","categories","tasks","readFileSync","isStringArray","readJson","readFileSync","mkdtemp","mkdir","readFile","rm","writeFile","existsSync","tmpdir","dirname","join","resolve","readFile","rm","existsSync","execFile","join","promisify","execFileAsync","runCommand","mkdir","dirname","writeFile","readFile","rm","mkdtemp","join","tmpdir","resolve","existsSync","run","run","run","usd","readFileSync","resolve","runContext","existsSync","join","execFileSync","cwd","formats","outputDir","basename","result"]}
|