@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
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/config/envCompat.ts","../src/context/runContext.ts","../src/tools/videoTools.ts","../src/safety/workspace.ts","../src/context/repoMap.ts","../src/context/repoMapSchema.ts","../src/memory/taskHistory.ts","../src/memory/runLogs.ts","../src/router/load.ts","../src/router/defaults.ts","../src/router/classify.ts","../src/providers/adapters/deepseek.ts","../src/providers/adapters/types.ts","../src/providers/adapters/grok.ts","../src/providers/adapters/groq.ts","../src/providers/adapters/ollama.ts","../src/providers/adapters/openai.ts","../src/providers/adapters/qwen.ts","../src/providers/adapters/together.ts","../src/providers/adapters/index.ts","../src/memory/runArchive.ts","../src/agent/compact.ts","../src/router/resolve.ts","../src/context/loader.ts","../src/skills/load.ts","../src/integrations/discovery.ts","../src/skills/summary.ts","../src/agent/systemPrompt.ts","../src/events/subAgentSink.ts","../src/providers/types.ts","../src/providers/parser.ts","../src/safety/permissions/modes.ts","../src/safety/permissions/engine.ts","../src/safety/permissions/rules.ts","../src/safety/permissions/schema.ts","../src/tools/fsTools.ts","../src/tools/imageTools.ts","../src/tools/projectContextTools.ts","../src/obsidian/search.ts","../src/tools/obsidianTools.ts","../src/memory/resultCache.ts","../src/tools/expandResult.ts","../src/agent/subAgentContext.ts","../src/tools/task.ts","../src/tools/editBlock.ts","../src/tools/repoMapTools.ts","../src/tools/metricsDashboardTools.ts","../src/tools/registry.ts","../src/memory/goldenTasks.ts","../src/memory/repairRuns.ts","../src/obsidian/vaultAppender.ts","../src/memory/auditLog.ts","../src/memory/fileReadDedup.ts","../src/memory/reasoningArchive.ts","../src/mcp/client.ts","../src/mcp/config.ts","../src/agent/verifier/index.ts","../src/agent/verifier/shell.ts","../src/agent/verifier/verifiers/goBackend.ts","../src/agent/verifier/types.ts","../src/agent/verifier/textHints.ts","../src/agent/verifier/verifiers/nodeBackend.ts","../src/agent/verifier/verifiers/frontend.ts","../src/agent/verifier/verifiers/mobile.ts","../src/agent/verifier/registry.ts","../src/agent/forbiddenPatterns.ts","../src/agent/validators/core.ts","../src/agent/validators/rules/load.ts","../src/agent/validators/rules/index.ts","../src/agent/validators/apple.ts","../src/agent/validators/android.ts","../src/agent/validators/go.ts","../src/agent/validators/prisma.ts","../src/agent/validators/security.ts","../src/agent/validators/index.ts","../src/agent/git.ts","../src/agent/report.ts","../src/agent/budgetLedger.ts","../src/agent/cycleDetect.ts","../src/agent/runner.ts","../src/cli/sessionsCommand.ts","../src/sessions/storage.ts","../src/sessions/repl.ts","../src/agent/chat.ts","../src/commands/registry.ts","../src/commands/builtin/audit.ts","../src/safety/permissions/config.ts","../src/commands/builtin/budget.ts","../src/commands/builtin/clear.ts","../src/commands/builtin/cost.ts","../src/commands/builtin/help.ts","../src/commands/builtin/memory.ts","../src/commands/builtin/mcp.ts","../src/commands/builtin/mode.ts","../src/commands/builtin/route.ts","../src/commands/builtin/skills.ts","../src/commands/builtin/verify.ts","../src/utils/formatElapsed.ts","../src/commands/sessions.ts","../src/commands/project.ts","../src/commands/index.ts","../src/safety/permissions/learning.ts","../src/ui/permissionPrompt.ts"],"sourcesContent":["const warnedLegacyKeys = new Set<string>();\n\nfunction readRaw(local: Record<string, string | undefined>, key: string): string | undefined {\n return process.env[key] ?? local[key];\n}\n\nfunction legacyKey(key: string): string | null {\n return key.startsWith(\"TANYA_\") ? `TANIA_${key.slice(\"TANYA_\".length)}` : null;\n}\n\nfunction warnLegacyEnv(legacy: string, current: string): void {\n if (warnedLegacyKeys.has(legacy)) return;\n warnedLegacyKeys.add(legacy);\n console.warn(`[tanya] ${legacy} is deprecated; use ${current}.`);\n}\n\nexport function envValue(local: Record<string, string | undefined> = {}, key: string): string {\n const current = readRaw(local, key);\n if (current !== undefined) return current;\n\n const legacy = legacyKey(key);\n if (!legacy) return \"\";\n\n const legacyValue = readRaw(local, legacy);\n if (legacyValue === undefined) return \"\";\n warnLegacyEnv(legacy, key);\n return legacyValue;\n}\n\nexport function numberEnvValue(local: Record<string, string | undefined>, key: string, fallback: number): number {\n const raw = envValue(local, key);\n if (!raw) return fallback;\n const parsed = Number(raw);\n return Number.isFinite(parsed) ? parsed : fallback;\n}\n","import { readFileSync } from \"node:fs\";\nimport { resolve } from \"node:path\";\n\nexport type TanyaRunContext = {\n task?: {\n kind?: string | undefined;\n title?: string | undefined;\n summary?: string | undefined;\n };\n artifacts?: Array<{\n path: string;\n sourcePath?: string | undefined;\n role?: string | undefined;\n status?: string | undefined;\n reason?: string | undefined;\n }>;\n contextFiles?: Array<{\n path: string;\n sourcePath?: string | undefined;\n role?: string | undefined;\n status?: string | undefined;\n reason?: string | undefined;\n }>;\n instructions?: string[];\n verification?: {\n commands?: string[];\n };\n languages?: string[];\n frameworks?: string[];\n stack?: string;\n expected_report?: Record<string, unknown>;\n metadata?: Record<string, unknown>;\n};\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === \"object\" && !Array.isArray(value);\n}\n\nfunction asString(value: unknown): string | undefined {\n return typeof value === \"string\" && value.trim() ? value.trim() : undefined;\n}\n\nfunction stringArray(value: unknown): string[] | undefined {\n if (!Array.isArray(value)) return undefined;\n const strings = value.filter((item): item is string => typeof item === \"string\" && item.trim().length > 0);\n return strings.length ? strings : undefined;\n}\n\nfunction recordArray(value: unknown): Record<string, unknown>[] {\n return Array.isArray(value) ? value.filter(isRecord) : [];\n}\n\nfunction briefListValue(value: unknown, key: string): string[] {\n if (!isRecord(value)) return [];\n return stringArray(value[key]) ?? [];\n}\n\nfunction buildAutoBriefBlock(metadata?: Record<string, unknown>): string[] {\n const brief = isRecord(metadata?.autoBrief) ? metadata.autoBrief : undefined;\n if (!brief) return [];\n const lines: string[] = [\"\", \"Auto task brief:\"];\n const signals = isRecord(brief.signals) ? brief.signals : {};\n const platforms = briefListValue({ platforms: signals.platforms }, \"platforms\");\n const domains = briefListValue({ domains: signals.domains }, \"domains\");\n lines.push(`- Platforms: ${platforms.length ? platforms.join(\", \") : \"none detected\"}`);\n lines.push(`- Domains: ${domains.length ? domains.join(\", \") : \"none detected\"}`);\n\n const contextFiles = recordArray(brief.contextFiles).slice(0, 12);\n if (contextFiles.length > 0) {\n lines.push(\"- Context files to consider:\");\n for (const file of contextFiles) {\n const path = asString(file.path) ?? \"unknown\";\n const role = asString(file.role);\n lines.push(` - ${path}${role ? ` (${role})` : \"\"}`);\n }\n }\n\n const artifacts = recordArray(brief.artifacts).slice(0, 12);\n if (artifacts.length > 0) {\n lines.push(\"- Artifact candidates:\");\n for (const artifact of artifacts) {\n const path = asString(artifact.path) ?? \"unknown\";\n const description = asString(artifact.description);\n lines.push(` - ${path}${description ? ` - ${description}` : \"\"}`);\n }\n }\n\n const packs = recordArray(brief.capabilityPacks).slice(0, 8);\n if (packs.length > 0) {\n lines.push(\"- Capability packs:\");\n for (const pack of packs) {\n const id = asString(pack.id) ?? \"unknown\";\n const reason = asString(pack.reason);\n lines.push(` - ${id}${reason ? `: ${reason}` : \"\"}`);\n }\n }\n\n const tools = briefListValue(brief, \"recommendedTools\").slice(0, 16);\n if (tools.length > 0) lines.push(`- Recommended tools: ${tools.join(\", \")}`);\n const verification = briefListValue(brief, \"verification\").slice(0, 12);\n if (verification.length > 0) {\n lines.push(\"- Recommended verification:\");\n for (const command of verification) lines.push(` - ${command}`);\n }\n const cautions = briefListValue(brief, \"cautions\").slice(0, 8);\n if (cautions.length > 0) {\n lines.push(\"- Cautions:\");\n for (const caution of cautions) lines.push(` - ${caution}`);\n }\n\n return lines;\n}\n\nexport function normalizeRunContext(input: unknown): TanyaRunContext {\n if (!isRecord(input)) throw new Error(\"Context file must contain a JSON object.\");\n\n const taskInput = isRecord(input.task) ? input.task : undefined;\n const artifactsInput = Array.isArray(input.artifacts) ? input.artifacts : undefined;\n const verificationInput = isRecord(input.verification) ? input.verification : undefined;\n const contextFilesInput = Array.isArray(input.contextFiles) ? input.contextFiles : undefined;\n\n const artifacts = artifactsInput\n ?.filter(isRecord)\n .map((artifact) => ({\n path: asString(artifact.path) ?? \"\",\n ...(asString(artifact.sourcePath) ? { sourcePath: asString(artifact.sourcePath) } : {}),\n ...(asString(artifact.role) ? { role: asString(artifact.role) } : {}),\n ...(asString(artifact.status) ? { status: asString(artifact.status) } : {}),\n ...(asString(artifact.reason) ? { reason: asString(artifact.reason) } : {}),\n }))\n .filter((artifact) => artifact.path.length > 0);\n const contextFiles = contextFilesInput\n ?.filter(isRecord)\n .map((contextFile) => ({\n path: asString(contextFile.path) ?? \"\",\n ...(asString(contextFile.sourcePath) ? { sourcePath: asString(contextFile.sourcePath) } : {}),\n ...(asString(contextFile.role) ? { role: asString(contextFile.role) } : {}),\n ...(asString(contextFile.status) ? { status: asString(contextFile.status) } : {}),\n ...(asString(contextFile.reason) ? { reason: asString(contextFile.reason) } : {}),\n }))\n .filter((contextFile) => contextFile.path.length > 0);\n\n const task = taskInput\n ? {\n ...(asString(taskInput.kind) ? { kind: asString(taskInput.kind) } : {}),\n ...(asString(taskInput.title) ? { title: asString(taskInput.title) } : {}),\n ...(asString(taskInput.summary) ? { summary: asString(taskInput.summary) } : {}),\n }\n : undefined;\n const verificationCommands = verificationInput ? stringArray(verificationInput.commands) : undefined;\n const instructions = stringArray(input.instructions);\n const languages = stringArray(input.languages);\n const frameworks = stringArray(input.frameworks);\n const stack = asString(input.stack);\n\n return {\n ...(task && Object.keys(task).length > 0 ? { task } : {}),\n ...(artifacts?.length ? { artifacts } : {}),\n ...(contextFiles?.length ? { contextFiles } : {}),\n ...(instructions ? { instructions } : {}),\n ...(verificationCommands ? { verification: { commands: verificationCommands } } : {}),\n ...(languages ? { languages } : {}),\n ...(frameworks ? { frameworks } : {}),\n ...(stack ? { stack } : {}),\n ...(isRecord(input.expected_report) ? { expected_report: input.expected_report } : {}),\n ...(isRecord(input.metadata) ? { metadata: input.metadata } : {}),\n };\n}\n\nexport function loadRunContextFile(path: string): TanyaRunContext {\n const content = readFileSync(resolve(path), \"utf8\");\n try {\n return normalizeRunContext(JSON.parse(content));\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n throw new Error(`Invalid context file: ${message}`);\n }\n}\n\nexport function buildRunContextBlock(context?: TanyaRunContext): string {\n if (!context) return \"\";\n const lines: string[] = [\"## Caller Context\"];\n\n if (context.task) {\n lines.push(`Task kind: ${context.task.kind ?? \"unspecified\"}`);\n if (context.task.title) lines.push(`Task title: ${context.task.title}`);\n if (context.task.summary) lines.push(`Task summary: ${context.task.summary}`);\n }\n\n if (context.artifacts?.length) {\n lines.push(\"\", \"Artifacts:\");\n for (const artifact of context.artifacts) {\n const suffix = [\n artifact.sourcePath ? `source=${artifact.sourcePath}` : null,\n artifact.role ? `role=${artifact.role}` : null,\n artifact.status ? `status=${artifact.status}` : null,\n artifact.reason ? `reason=${artifact.reason}` : null,\n ].filter(Boolean).join(\"; \");\n lines.push(`- ${artifact.path}${suffix ? ` (${suffix})` : \"\"}`);\n }\n }\n\n if (context.contextFiles?.length) {\n lines.push(\"\", \"Context files:\");\n for (const contextFile of context.contextFiles) {\n const suffix = [\n contextFile.sourcePath ? `source=${contextFile.sourcePath}` : null,\n contextFile.role ? `role=${contextFile.role}` : null,\n contextFile.status ? `status=${contextFile.status}` : null,\n contextFile.reason ? `reason=${contextFile.reason}` : null,\n ].filter(Boolean).join(\"; \");\n lines.push(`- ${contextFile.path}${suffix ? ` (${suffix})` : \"\"}`);\n }\n }\n\n if (context.instructions?.length) {\n lines.push(\"\", \"Caller instructions:\");\n for (const instruction of context.instructions) lines.push(`- ${instruction}`);\n }\n\n if (context.verification?.commands?.length) {\n lines.push(\"\", \"Verification commands requested by caller:\");\n for (const command of context.verification.commands) lines.push(`- ${command}`);\n }\n\n if (context.languages?.length || context.frameworks?.length || context.stack) {\n lines.push(\"\", \"Skill-pack hints:\");\n if (context.languages?.length) lines.push(`- Languages: ${context.languages.join(\", \")}`);\n if (context.frameworks?.length) lines.push(`- Frameworks: ${context.frameworks.join(\", \")}`);\n if (context.stack) lines.push(`- Stack: ${context.stack}`);\n }\n\n if (context.expected_report && Object.keys(context.expected_report).length > 0) {\n lines.push(\"\", `Expected report JSON keys: ${Object.keys(context.expected_report).join(\", \")}`);\n }\n\n lines.push(...buildAutoBriefBlock(context.metadata));\n\n lines.push(\n \"\",\n \"Treat caller metadata as opaque labels. Do not infer product-specific behavior from it.\",\n \"If artifacts are listed and relevant, read the listed local artifact paths before implementing related code and mention artifact usage in the final report.\",\n \"If context files are listed, read the listed local context paths when the task references safety, brand, architecture, API contracts, or product rules.\",\n \"Never use absolute sourcePath values with read_file. The sourcePath is provenance only; use the local artifact path shown before it.\",\n \"If an instruction mentions an absolute file outside the workspace and no local materialized copy is listed, do not repeatedly try to read it; report that it is outside the workspace.\",\n );\n\n return lines.join(\"\\n\");\n}\n","import { existsSync } from \"node:fs\";\nimport { mkdir, writeFile, copyFile } from \"node:fs/promises\";\nimport { dirname, join } from \"node:path\";\nimport { spawn, spawnSync } from \"node:child_process\";\nimport WebSocket from \"ws\";\nimport { envValue } from \"../config/envCompat\";\nimport type { TanyaTool, ToolContext } from \"./types\";\nimport { resolveInsideWorkspace } from \"../safety/workspace\";\n\ntype VideoFormat = \"webm\" | \"mov\" | \"poster\";\ntype VideoPreset = \"one-terminal-simctl\";\ntype TerminalLineKind = \"cmd\" | \"log\" | \"error\" | \"warn\";\ntype TerminalLine = [string, string, TerminalLineKind];\n\nexport interface GenerateVideoAssetOptions {\n preset?: VideoPreset | \"terminal-simctl\";\n outputDir?: string;\n basename?: string;\n width?: number;\n height?: number;\n fps?: number;\n duration?: number;\n formats?: VideoFormat[];\n title?: string;\n tab?: string;\n secondaryTab?: string;\n badge?: string;\n lines?: string[];\n chromePath?: string;\n ffmpegPath?: string;\n}\n\ninterface RenderConfig {\n workspace: string;\n preset: VideoPreset;\n outputDir: string;\n basename: string;\n width: number;\n height: number;\n fps: number;\n duration: number;\n formats: VideoFormat[];\n title: string;\n tab: string;\n secondaryTab: string;\n badge: string;\n lines: TerminalLine[];\n chromePath: string;\n ffmpegPath: string;\n}\n\nfunction asRecord(input: unknown): Record<string, unknown> {\n return input && typeof input === \"object\" ? (input as Record<string, unknown>) : {};\n}\n\nfunction asOptionalString(input: unknown, key: string): string | undefined {\n const value = asRecord(input)[key];\n return typeof value === \"string\" && value.trim() ? value.trim() : undefined;\n}\n\nfunction asOptionalNumber(input: unknown, key: string, fallback: number): number {\n const value = asRecord(input)[key];\n return typeof value === \"number\" && Number.isFinite(value) ? value : fallback;\n}\n\nfunction optionalStringArray(input: unknown, key: string, fallback: string[]): string[] {\n const value = asRecord(input)[key];\n if (!Array.isArray(value)) return fallback;\n return value.filter((item): item is string => typeof item === \"string\" && item.trim().length > 0);\n}\n\nfunction ensureRelativePath(path: string): string {\n if (path.startsWith(\"/\")) throw new Error(`Path must be relative to the workspace: ${path}`);\n return path;\n}\n\nfunction sanitizeName(value: string): string {\n return value.toLowerCase().replace(/[^a-z0-9._-]+/g, \"-\").replace(/^-+|-+$/g, \"\") || \"video-asset\";\n}\n\nfunction clamp(value: number, min: number, max: number): number {\n return Math.max(min, Math.min(max, value));\n}\n\nfunction escapeXml(value: string): string {\n return value\n .replaceAll(\"&\", \"&\")\n .replaceAll(\"<\", \"<\")\n .replaceAll(\">\", \">\")\n .replaceAll('\"', \""\");\n}\n\nfunction findChromePath(explicit?: string): string {\n const candidates = [\n explicit,\n envValue({}, \"TANYA_CHROME_PATH\"),\n \"/Applications/Google Chrome.app/Contents/MacOS/Google Chrome\",\n \"/Applications/Chromium.app/Contents/MacOS/Chromium\",\n \"/opt/homebrew/bin/chromium\",\n \"/usr/local/bin/chromium\",\n ].filter((path): path is string => !!path);\n const found = candidates.find((path) => existsSync(path));\n if (!found) throw new Error(\"Chrome/Chromium not found. Set TANYA_CHROME_PATH or install Google Chrome.\");\n return found;\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 text(x: number, y: number, content: string, opts: {\n size?: number;\n fill?: string;\n weight?: number;\n family?: string;\n opacity?: number;\n anchor?: \"start\" | \"middle\" | \"end\";\n} = {}): string {\n const size = opts.size ?? 23;\n const fill = opts.fill ?? \"#d7dee8\";\n const weight = opts.weight ?? 620;\n const family = opts.family ?? \"Menlo, SFMono-Regular, Consolas, monospace\";\n const opacity = opts.opacity ?? 1;\n const anchor = opts.anchor ?? \"start\";\n return `<text x=\"${x}\" y=\"${y}\" fill=\"${fill}\" font-size=\"${size}\" font-weight=\"${weight}\" font-family=\"${family}\" opacity=\"${opacity}\" text-anchor=\"${anchor}\">${escapeXml(content)}</text>`;\n}\n\nfunction rect(x: number, y: number, w: number, h: number, opts: {\n r?: number;\n fill?: string;\n stroke?: string;\n sw?: number;\n opacity?: number;\n filter?: string;\n} = {}): string {\n const r = opts.r ?? 0;\n const fill = opts.fill ?? \"none\";\n const stroke = opts.stroke ?? \"none\";\n const sw = opts.sw ?? 1;\n const opacity = opts.opacity ?? 1;\n const filter = opts.filter ? `filter=\"${opts.filter}\"` : \"\";\n return `<rect x=\"${x}\" y=\"${y}\" width=\"${w}\" height=\"${h}\" rx=\"${r}\" fill=\"${fill}\" stroke=\"${stroke}\" stroke-width=\"${sw}\" opacity=\"${opacity}\" ${filter}/>`;\n}\n\nfunction circle(cx: number, cy: number, r: number, fill: string, opacity = 1): string {\n return `<circle cx=\"${cx}\" cy=\"${cy}\" r=\"${r}\" fill=\"${fill}\" opacity=\"${opacity}\"/>`;\n}\n\nconst defaultTerminalLines: TerminalLine[] = [\n ['$ xcrun simctl boot \"iPhone 16 Pro\"', \"#d8e0ea\", \"cmd\"],\n [\"CoreSimulator: attempting boot...\", \"#8fa1b3\", \"log\"],\n [\"error: device failed to boot in 60.0s\", \"#ff5c6c\", \"error\"],\n [\"$ xcrun simctl install booted DemoApp.app\", \"#d8e0ea\", \"cmd\"],\n [\"error: unable to find a booted simulator\", \"#ff5c6c\", \"error\"],\n [\"$ xcrun simctl io booted screenshot out.png\", \"#d8e0ea\", \"cmd\"],\n [\"xcrun: error: selected device is not available\", \"#ff5c6c\", \"error\"],\n [\"$ xcrun simctl spawn booted log stream\", \"#d8e0ea\", \"cmd\"],\n [\"warning: stale runtime cache detected\", \"#ffd166\", \"warn\"],\n [\"$ xcrun simctl erase all\", \"#d8e0ea\", \"cmd\"],\n [\"error: operation timed out waiting for service\", \"#ff5c6c\", \"error\"],\n];\n\nexport const videoPresets = [\n {\n name: \"one-terminal-simctl\",\n aliases: [\"terminal-simctl\"],\n description: \"Exact native-size transparent terminal asset with failing iOS Simulator xcrun simctl commands.\",\n width: 980,\n height: 1012,\n fps: 30,\n duration: 3,\n },\n];\n\nfunction normalizePreset(preset: GenerateVideoAssetOptions[\"preset\"]): VideoPreset {\n if (!preset || preset === \"terminal-simctl\" || preset === \"one-terminal-simctl\") return \"one-terminal-simctl\";\n throw new Error(`Unsupported video preset: ${preset}`);\n}\n\nfunction inferLineKind(line: string): TerminalLineKind {\n if (/^\\s*\\$/.test(line)) return \"cmd\";\n if (/\\b(error|failed|unable|timed out|not found|unavailable)\\b/i.test(line)) return \"error\";\n if (/\\b(warning|warn|stale)\\b/i.test(line)) return \"warn\";\n return \"log\";\n}\n\nfunction lineColor(kind: TerminalLineKind): string {\n if (kind === \"cmd\") return \"#d8e0ea\";\n if (kind === \"error\") return \"#ff5c6c\";\n if (kind === \"warn\") return \"#ffd166\";\n return \"#8fa1b3\";\n}\n\nfunction normalizeLines(lines?: string[]): TerminalLine[] {\n const source = lines?.length ? lines : defaultTerminalLines.map(([line]) => line);\n return source.slice(0, 11).map((line) => {\n const kind = inferLineKind(line);\n return [line, lineColor(kind), kind];\n });\n}\n\nfunction ease(t: number): number {\n const bounded = clamp(t, 0, 1);\n return 1 - Math.pow(1 - bounded, 3);\n}\n\nfunction terminalSvg(config: RenderConfig, frame: number): string {\n const { width, height, fps } = config;\n const t = frame / fps;\n const enter = ease(t / 0.75);\n const marginX = Math.max(44, Math.round(width * 0.078));\n const marginY = Math.max(36, Math.round(height * 0.043));\n const w = width - marginX * 2;\n const h = height - marginY * 2 - 66;\n const x = marginX + (1 - enter) * -42;\n const y = marginY + (1 - enter) * 28 + Math.sin(t * Math.PI * 2) * 4;\n const visible = Math.min(config.lines.length, Math.floor((t - 0.14) / 0.17) + 1);\n const cursorOn = Math.floor(t * 4) % 2 === 0;\n let body = \"\";\n\n body += `<g opacity=\"${enter}\">`;\n body += rect(x, y, w, h, { r: 28, fill: \"#070b12\", stroke: \"#34485b\", sw: 1.6, filter: \"url(#terminalShadow)\" });\n body += rect(x, y, w, 66, { r: 28, fill: \"#111d28\" });\n body += rect(x, y + 38, w, 28, { fill: \"#111d28\" });\n body += circle(x + 34, y + 33, 8, \"#ff5f57\");\n body += circle(x + 60, y + 33, 8, \"#febc2e\");\n body += circle(x + 86, y + 33, 8, \"#28c840\");\n body += rect(x + 132, y + 17, 126, 32, { r: 10, fill: \"#223245\", stroke: \"#50657a\" });\n body += text(x + 167, y + 39, config.tab, { size: 15, fill: \"#dce6ef\", weight: 850 });\n body += rect(x + 270, y + 17, 150, 32, { r: 10, fill: \"#0b141d\", stroke: \"#27394b\" });\n body += text(x + 292, y + 39, config.secondaryTab, { size: 15, fill: \"#728495\", weight: 780 });\n body += text(x + 452, y + 39, config.badge, {\n size: 15,\n fill: \"#8ea0b2\",\n weight: 800,\n family: \"-apple-system, BlinkMacSystemFont, Helvetica, sans-serif\",\n });\n body += text(x + 36, y + 113, config.title, { size: 20, fill: \"#93a5b7\", weight: 850 });\n\n for (let i = 0; i < visible; i += 1) {\n const [line, color, kind] = config.lines[i]!;\n const yy = y + 164 + i * 54;\n const opacity = ease((t - 0.14 - i * 0.17) / 0.15);\n if (kind === \"error\") body += rect(x + 28, yy - 33, w - 56, 42, { r: 11, fill: \"#34131b\", opacity: 0.77 * opacity });\n if (kind === \"warn\") body += rect(x + 28, yy - 33, w - 56, 42, { r: 11, fill: \"#302711\", opacity: 0.7 * opacity });\n if (kind === \"log\") body += rect(x + 28, yy - 33, w - 56, 42, { r: 11, fill: \"#0f1822\", opacity: 0.58 * opacity });\n body += text(x + 44, yy, line, { size: 23, fill: color, opacity, weight: kind === \"cmd\" ? 650 : 760 });\n }\n\n const cursorY = y + 164 + Math.min(visible, config.lines.length - 1) * 54 + 54;\n if (cursorOn && t > 1.8) body += rect(x + 44, cursorY - 24, 13, 29, { fill: \"#7cf7d4\", opacity: 0.92 });\n body += \"</g>\";\n\n return `<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"${width}\" height=\"${height}\" viewBox=\"0 0 ${width} ${height}\">\n <defs>\n <filter id=\"terminalShadow\" x=\"-30%\" y=\"-30%\" width=\"160%\" height=\"170%\">\n <feDropShadow dx=\"0\" dy=\"34\" stdDeviation=\"34\" flood-color=\"#000000\" flood-opacity=\"0.42\"/>\n </filter>\n </defs>\n ${body}\n</svg>`;\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\nasync function waitForJson(url: string, timeout = 10_000): Promise<any> {\n const start = Date.now();\n while (Date.now() - start < timeout) {\n try {\n const res = await fetch(url);\n if (res.ok) return await res.json();\n } catch {\n // Chrome may still be starting.\n }\n await sleep(120);\n }\n throw new Error(`Timed out waiting for ${url}`);\n}\n\nfunction makeCdp(wsUrl: string) {\n let id = 0;\n const pending = new Map<number, { resolve: (value: any) => void; reject: (error: Error) => void }>();\n const ws = new WebSocket(wsUrl);\n ws.on(\"message\", (data) => {\n const msg = JSON.parse(data.toString());\n if (!msg.id || !pending.has(msg.id)) return;\n const handlers = pending.get(msg.id)!;\n pending.delete(msg.id);\n if (msg.error) handlers.reject(new Error(JSON.stringify(msg.error)));\n else handlers.resolve(msg.result);\n });\n return {\n ready: new Promise<void>((resolveReady, rejectReady) => {\n ws.once(\"open\", () => resolveReady());\n ws.once(\"error\", rejectReady);\n }),\n send(method: string, params: Record<string, unknown> = {}) {\n const msgId = ++id;\n ws.send(JSON.stringify({ id: msgId, method, params }));\n return new Promise<any>((resolveSend, rejectSend) => pending.set(msgId, { resolve: resolveSend, reject: rejectSend }));\n },\n close() {\n ws.close();\n },\n };\n}\n\nasync function captureFrames(config: RenderConfig, frameDir: string, svgDir: string, chromeProfile: string): Promise<void> {\n const port = 9230 + Math.floor(Math.random() * 400);\n const chrome = spawn(config.chromePath, [\n \"--headless=new\",\n \"--disable-gpu\",\n \"--hide-scrollbars\",\n \"--mute-audio\",\n `--remote-debugging-port=${port}`,\n `--user-data-dir=${chromeProfile}`,\n `--window-size=${config.width},${config.height}`,\n \"about:blank\",\n ], { stdio: \"ignore\" });\n\n try {\n const version = await waitForJson(`http://127.0.0.1:${port}/json/version`);\n const browser = makeCdp(version.webSocketDebuggerUrl);\n await browser.ready;\n const target = await browser.send(\"Target.createTarget\", { url: \"about:blank\" });\n const targets = await waitForJson(`http://127.0.0.1:${port}/json/list`);\n const pageInfo = targets.find((item: { id: string }) => item.id === target.targetId);\n if (!pageInfo) throw new Error(\"Unable to open Chrome render target.\");\n const page = makeCdp(pageInfo.webSocketDebuggerUrl);\n await page.ready;\n await page.send(\"Page.enable\");\n await page.send(\"Runtime.enable\");\n await page.send(\"Emulation.setDeviceMetricsOverride\", {\n width: config.width,\n height: config.height,\n deviceScaleFactor: 1,\n mobile: false,\n screenWidth: config.width,\n screenHeight: config.height,\n });\n await page.send(\"Emulation.setDefaultBackgroundColorOverride\", { color: { r: 0, g: 0, b: 0, a: 0 } });\n const html = `<!doctype html><html><head><meta charset=\"utf-8\"><style>html,body{margin:0;width:${config.width}px;height:${config.height}px;overflow:hidden;background:transparent;}svg{display:block;width:${config.width}px;height:${config.height}px;}</style></head><body></body></html>`;\n await page.send(\"Page.navigate\", { url: `data:text/html;charset=utf-8,${encodeURIComponent(html)}` });\n await sleep(250);\n\n const totalFrames = Math.round(config.fps * config.duration);\n for (let i = 0; i < totalFrames; i += 1) {\n const n = String(i + 1).padStart(4, \"0\");\n const svg = terminalSvg(config, i);\n await writeFile(join(svgDir, `frame-${n}.svg`), svg, \"utf8\");\n await page.send(\"Runtime.evaluate\", { expression: `document.body.innerHTML = ${JSON.stringify(svg)};`, awaitPromise: true });\n const shot = await page.send(\"Page.captureScreenshot\", {\n format: \"png\",\n fromSurface: true,\n captureBeyondViewport: false,\n omitBackground: true,\n });\n await writeFile(join(frameDir, `frame-${n}.png`), Buffer.from(shot.data, \"base64\"));\n }\n\n page.close();\n browser.close();\n } finally {\n chrome.kill(\"SIGTERM\");\n }\n}\n\nfunction normalizeOptions(options: GenerateVideoAssetOptions, workspace: string): RenderConfig {\n const preset = normalizePreset(options.preset);\n const width = Math.round(options.width ?? 980);\n const height = Math.round(options.height ?? 1012);\n const fps = Math.round(options.fps ?? 30);\n const duration = options.duration ?? 3;\n if (width < 640 || height < 640) throw new Error(\"Video width and height must be at least 640px.\");\n if (fps < 1 || fps > 60) throw new Error(\"fps must be between 1 and 60.\");\n if (duration <= 0 || duration > 10) throw new Error(\"duration must be greater than 0 and at most 10 seconds.\");\n const formats = options.formats?.length ? options.formats : [\"webm\", \"mov\", \"poster\"];\n for (const format of formats) {\n if (![\"webm\", \"mov\", \"poster\"].includes(format)) throw new Error(`Unsupported video format: ${format}`);\n }\n return {\n workspace,\n preset,\n outputDir: ensureRelativePath(options.outputDir ?? \"tanya-video-assets\"),\n basename: sanitizeName(options.basename ?? \"terminal-simctl\"),\n width,\n height,\n fps,\n duration,\n formats: [...new Set(formats)] as VideoFormat[],\n title: options.title?.trim() || \"zsh - iOS Simulator Control\",\n tab: options.tab?.trim() || \"simctl\",\n secondaryTab: options.secondaryTab?.trim() || \"boot logs\",\n badge: options.badge?.trim() || \"DemoApp Debug\",\n lines: normalizeLines(options.lines),\n chromePath: findChromePath(options.chromePath),\n ffmpegPath: findExecutable(\"ffmpeg\", options.ffmpegPath ?? envValue({}, \"TANYA_FFMPEG_PATH\")),\n };\n}\n\nexport async function generateVideoAsset(options: GenerateVideoAssetOptions, workspace: string): Promise<{\n files: string[];\n output: Record<string, unknown>;\n}> {\n const config = normalizeOptions(options, workspace);\n const outputAbs = resolveInsideWorkspace(workspace, config.outputDir);\n const tmpDir = resolveInsideWorkspace(workspace, `.tania/video-tmp/${config.basename}-${Date.now()}`);\n const frameDir = join(tmpDir, \"frames\");\n const svgDir = join(tmpDir, \"svg\");\n const chromeProfile = join(tmpDir, \"chrome-profile\");\n await mkdir(frameDir, { recursive: true });\n await mkdir(svgDir, { recursive: true });\n await mkdir(outputAbs, { recursive: true });\n\n await captureFrames(config, frameDir, svgDir, chromeProfile);\n\n const files: string[] = [];\n const inputFrames = join(frameDir, \"frame-%04d.png\");\n const fileBase = `${config.basename}-${config.width}x${config.height}-${config.duration}s-alpha`;\n\n if (config.formats.includes(\"webm\")) {\n const rel = `${config.outputDir}/${fileBase}.webm`;\n run(config.ffmpegPath, [\n \"-y\",\n \"-framerate\",\n String(config.fps),\n \"-i\",\n inputFrames,\n \"-c:v\",\n \"libvpx-vp9\",\n \"-pix_fmt\",\n \"yuva420p\",\n \"-auto-alt-ref\",\n \"0\",\n \"-b:v\",\n \"0\",\n \"-crf\",\n \"28\",\n resolveInsideWorkspace(workspace, rel),\n ], workspace);\n files.push(rel);\n }\n\n if (config.formats.includes(\"mov\")) {\n const rel = `${config.outputDir}/${fileBase}.mov`;\n run(config.ffmpegPath, [\n \"-y\",\n \"-framerate\",\n String(config.fps),\n \"-i\",\n inputFrames,\n \"-c:v\",\n \"prores_ks\",\n \"-profile:v\",\n \"4444\",\n \"-pix_fmt\",\n \"yuva444p10le\",\n resolveInsideWorkspace(workspace, rel),\n ], workspace);\n files.push(rel);\n }\n\n if (config.formats.includes(\"poster\")) {\n const rel = `${config.outputDir}/${config.basename}-poster-alpha.png`;\n const posterFrame = String(Math.max(1, Math.min(Math.round(config.fps * Math.min(2, config.duration)), Math.round(config.fps * config.duration)))).padStart(4, \"0\");\n await mkdir(dirname(resolveInsideWorkspace(workspace, rel)), { recursive: true });\n await copyFile(join(frameDir, `frame-${posterFrame}.png`), resolveInsideWorkspace(workspace, rel));\n files.push(rel);\n }\n\n return {\n files,\n output: {\n preset: config.preset,\n width: config.width,\n height: config.height,\n fps: config.fps,\n duration: config.duration,\n formats: config.formats,\n files,\n },\n };\n}\n\nexport const generateVideoAssetTool: TanyaTool = {\n name: \"generate_video_asset\",\n description: \"Generate a short transparent video asset inside the workspace. Currently supports a terminal-simctl preset for failing iOS Simulator commands.\",\n definition: {\n type: \"function\",\n function: {\n name: \"generate_video_asset\",\n description: \"Generate a short transparent WebM/MOV video asset. Use for compositable ad or app demo assets.\",\n parameters: {\n type: \"object\",\n properties: {\n preset: { type: \"string\", enum: [\"one-terminal-simctl\", \"terminal-simctl\"], description: \"Video preset. terminal-simctl is an alias. Default one-terminal-simctl.\" },\n outputDir: { type: \"string\", description: \"Output directory relative to workspace. Default tanya-video-assets.\" },\n basename: { type: \"string\", description: \"Output filename base. Default terminal-simctl.\" },\n width: { type: \"number\", description: \"Canvas width in pixels. Default 980.\" },\n height: { type: \"number\", description: \"Canvas height in pixels. Default 1012.\" },\n fps: { type: \"number\", description: \"Frames per second. Default 30.\" },\n duration: { type: \"number\", description: \"Duration in seconds. Default 3.\" },\n formats: {\n type: \"array\",\n items: { type: \"string\", enum: [\"webm\", \"mov\", \"poster\"] },\n description: \"Outputs to write. Default ['webm','mov','poster'].\",\n },\n title: { type: \"string\", description: \"Terminal title line. Default zsh - iOS Simulator Control.\" },\n tab: { type: \"string\", description: \"Active tab label. Default simctl.\" },\n secondaryTab: { type: \"string\", description: \"Inactive tab label. Default boot logs.\" },\n badge: { type: \"string\", description: \"Small header badge text. Default DemoApp Debug.\" },\n lines: {\n type: \"array\",\n items: { type: \"string\" },\n description: \"Optional terminal lines. Line colors are inferred from commands, warnings, and errors.\",\n },\n },\n additionalProperties: false,\n },\n },\n },\n async run(input, context: ToolContext) {\n const preset = asOptionalString(input, \"preset\") as GenerateVideoAssetOptions[\"preset\"];\n const outputDir = asOptionalString(input, \"outputDir\");\n const basename = asOptionalString(input, \"basename\");\n const options: GenerateVideoAssetOptions = {\n width: asOptionalNumber(input, \"width\", 980),\n height: asOptionalNumber(input, \"height\", 1012),\n fps: asOptionalNumber(input, \"fps\", 30),\n duration: asOptionalNumber(input, \"duration\", 3),\n formats: optionalStringArray(input, \"formats\", [\"webm\", \"mov\", \"poster\"]) as VideoFormat[],\n lines: optionalStringArray(input, \"lines\", []),\n };\n if (preset) options.preset = preset;\n if (outputDir) options.outputDir = outputDir;\n if (basename) options.basename = basename;\n const title = asOptionalString(input, \"title\");\n const tab = asOptionalString(input, \"tab\");\n const secondaryTab = asOptionalString(input, \"secondaryTab\");\n const badge = asOptionalString(input, \"badge\");\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 const result = await generateVideoAsset(options, context.workspace);\n return {\n ok: true,\n summary: `Generated ${options.preset ?? \"terminal-simctl\"} video asset (${result.files.length} file${result.files.length === 1 ? \"\" : \"s\"}).`,\n output: result.output,\n files: result.files,\n };\n },\n};\n","import { existsSync, lstatSync, realpathSync } from \"node:fs\";\nimport { dirname, resolve, relative } from \"node:path\";\n\nexport function resolveWorkspace(cwd: string): string {\n return realpathSync(resolve(cwd));\n}\n\nexport function pathIsInsideWorkspace(workspace: string, inputPath: string): boolean {\n const target = resolve(workspace, inputPath);\n const lexicalRel = relative(workspace, target);\n return !(lexicalRel.startsWith(\"..\") || lexicalRel === \"..\" || lexicalRel.includes(`..${\"/\"}`));\n}\n\nexport function resolveInsideWorkspace(workspace: string, inputPath: string): string {\n const target = resolve(workspace, inputPath);\n const lexicalRel = relative(workspace, target);\n if (lexicalRel.startsWith(\"..\") || lexicalRel === \"..\" || lexicalRel.includes(`..${\"/\"}`)) {\n throw new Error(`Path escapes workspace: ${inputPath}`);\n }\n\n if (!existsSync(workspace)) return target;\n const realWorkspace = realpathSync(workspace);\n let existingPath = target;\n while (!existsSync(existingPath)) {\n const parent = dirname(existingPath);\n if (parent === existingPath) break;\n existingPath = parent;\n }\n\n if (existsSync(existingPath)) {\n const realExisting = realpathSync(existingPath);\n const realRel = relative(realWorkspace, realExisting);\n if (realRel.startsWith(\"..\") || realRel === \"..\" || realRel.includes(`..${\"/\"}`)) {\n throw new Error(`Path escapes workspace via symlink: ${inputPath}`);\n }\n if (lstatSync(existingPath).isSymbolicLink()) {\n const symlinkRel = relative(realWorkspace, realExisting);\n if (symlinkRel.startsWith(\"..\") || symlinkRel === \"..\" || symlinkRel.includes(`..${\"/\"}`)) {\n throw new Error(`Path escapes workspace via symlink: ${inputPath}`);\n }\n }\n }\n return target;\n}\n","import { execFile } from \"node:child_process\";\nimport { existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from \"node:fs\";\nimport { readdir } from \"node:fs/promises\";\nimport { join, relative, resolve, sep } from \"node:path\";\nimport { promisify } from \"node:util\";\nimport { envValue } from \"../config/envCompat\";\nimport {\n REPO_MAP_SCHEMA_VERSION,\n REPO_MAP_VERSION,\n assertRepoMap,\n type RepoMap,\n type RepoMapFile,\n type RepoMapImport,\n type RepoMapLang,\n type RepoMapParser,\n type RepoMapSymbol,\n type RepoMapSymbolKind,\n} from \"./repoMapSchema\";\n\nconst execFileAsync = promisify(execFile);\n\nconst DEFAULT_MAX_FILE_BYTES = 500 * 1024;\nconst SOURCE_EXTENSIONS = new Map<string, RepoMapLang>([\n [\".ts\", \"ts\"],\n [\".tsx\", \"tsx\"],\n [\".js\", \"js\"],\n [\".jsx\", \"jsx\"],\n [\".py\", \"py\"],\n [\".go\", \"go\"],\n [\".swift\", \"swift\"],\n [\".kt\", \"kt\"],\n]);\n\nconst SKIP_SEGMENTS = new Set([\n \".git\",\n \".next\",\n \".tania\",\n \"build\",\n \"coverage\",\n \"dist\",\n \"node_modules\",\n \"out\",\n]);\n\nconst BINARY_EXTENSIONS = new Set([\n \".bin\", \".dll\", \".dylib\", \".exe\", \".gif\", \".ico\", \".jpg\", \".jpeg\", \".pdf\", \".png\", \".so\",\n \".ttf\", \".woff\", \".woff2\", \".zip\",\n]);\n\nexport type BuildRepoMapOptions = {\n maxFileBytes?: number;\n now?: Date;\n writeCache?: boolean;\n useCache?: boolean;\n headSha?: string | null;\n};\n\ntype RepoMapMeta = {\n headSha: string | null;\n schemaVersion: number;\n generatedAt: string;\n};\n\nexport type RepoMapDiagnostics = {\n fileCount: number;\n symbolCount: number;\n importCount: number;\n parserCounts: Record<RepoMapParser, number>;\n estimatedTokens: number;\n generatedAt?: string;\n};\n\nexport async function buildRepoMap(workspace: string, options: BuildRepoMapOptions = {}): Promise<RepoMap> {\n const root = resolve(workspace);\n const generatedAt = (options.now ?? new Date()).toISOString();\n const maxFileBytes = options.maxFileBytes ?? configuredMaxFileBytes();\n const headSha = options.headSha === undefined ? await currentHeadSha(root) : options.headSha;\n const cached = options.writeCache && options.useCache !== false ? readRepoMap(root) : null;\n const cachedMeta = options.writeCache && options.useCache !== false ? readRepoMapMeta(root) : null;\n const canReuseCache = Boolean(\n cached &&\n cachedMeta &&\n cached.schemaVersion === REPO_MAP_SCHEMA_VERSION &&\n cachedMeta.schemaVersion === REPO_MAP_SCHEMA_VERSION &&\n cachedMeta.headSha === headSha,\n );\n const cachedByPath = canReuseCache\n ? new Map(cached?.files.map((file) => [file.path, file]) ?? [])\n : new Map<string, RepoMapFile>();\n const files = await listIndexableFiles(root);\n const entries = files\n .map((path) => indexFile(root, path, maxFileBytes, generatedAt, cachedByPath.get(path)))\n .filter((entry): entry is RepoMapFile => entry !== null)\n .sort((a, b) => a.path.localeCompare(b.path));\n const map = assertRepoMap({\n version: REPO_MAP_VERSION,\n workspace: root,\n generatedAt,\n schemaVersion: REPO_MAP_SCHEMA_VERSION,\n files: entries,\n });\n if (options.writeCache) {\n writeRepoMap(root, map);\n writeRepoMapMeta(root, { headSha, schemaVersion: REPO_MAP_SCHEMA_VERSION, generatedAt });\n }\n return map;\n}\n\nexport function repoMapCachePath(workspace: string): string {\n return join(resolve(workspace), \".tania\", \"index\", \"repo-map.json\");\n}\n\nexport function repoMapMetaPath(workspace: string): string {\n return join(resolve(workspace), \".tania\", \"index\", \"repo-map-meta.json\");\n}\n\nexport function writeRepoMap(workspace: string, map: RepoMap): void {\n const path = repoMapCachePath(workspace);\n mkdirSync(resolve(path, \"..\"), { recursive: true });\n writeFileSync(path, `${JSON.stringify(map, null, 2)}\\n`, \"utf8\");\n}\n\nexport function readRepoMap(workspace: string): RepoMap | null {\n const path = repoMapCachePath(workspace);\n if (!existsSync(path)) return null;\n try {\n return assertRepoMap(JSON.parse(readFileSync(path, \"utf8\")));\n } catch {\n return null;\n }\n}\n\nfunction readRepoMapMeta(workspace: string): RepoMapMeta | null {\n const path = repoMapMetaPath(workspace);\n if (!existsSync(path)) return null;\n try {\n const parsed = JSON.parse(readFileSync(path, \"utf8\")) as Partial<RepoMapMeta>;\n return {\n headSha: typeof parsed.headSha === \"string\" ? parsed.headSha : null,\n schemaVersion: typeof parsed.schemaVersion === \"number\" ? parsed.schemaVersion : 0,\n generatedAt: typeof parsed.generatedAt === \"string\" ? parsed.generatedAt : \"\",\n };\n } catch {\n return null;\n }\n}\n\nfunction writeRepoMapMeta(workspace: string, meta: RepoMapMeta): void {\n const path = repoMapMetaPath(workspace);\n mkdirSync(resolve(path, \"..\"), { recursive: true });\n writeFileSync(path, `${JSON.stringify(meta, null, 2)}\\n`, \"utf8\");\n}\n\nexport function repoMapDiagnostics(map: RepoMap): RepoMapDiagnostics {\n const parserCounts: Record<RepoMapParser, number> = { \"tree-sitter\": 0, ripgrep: 0, path: 0 };\n let symbolCount = 0;\n let importCount = 0;\n for (const file of map.files) {\n parserCounts[file.parser] += 1;\n symbolCount += file.symbols.length;\n importCount += file.imports.length;\n }\n return {\n fileCount: map.files.length,\n symbolCount,\n importCount,\n parserCounts,\n estimatedTokens: estimateRepoMapTokens(map),\n generatedAt: map.generatedAt,\n };\n}\n\nexport function estimateRepoMapTokens(map: Pick<RepoMap, \"files\">): number {\n return Math.ceil(JSON.stringify(map.files).length / 4);\n}\n\nasync function listIndexableFiles(workspace: string): Promise<string[]> {\n const gitFiles = await listGitFiles(workspace);\n const files = gitFiles.length > 0 ? gitFiles : await listRecursiveFiles(workspace);\n return files\n .filter((path) => shouldConsiderPath(path))\n .sort((a, b) => a.localeCompare(b));\n}\n\nasync function listGitFiles(workspace: string): Promise<string[]> {\n try {\n const { stdout } = await execFileAsync(\"git\", [\"ls-files\", \"-co\", \"--exclude-standard\"], {\n cwd: workspace,\n timeout: 10_000,\n maxBuffer: 16 * 1024 * 1024,\n });\n return stdout.split(/\\r?\\n/).filter(Boolean);\n } catch {\n return [];\n }\n}\n\nasync function currentHeadSha(workspace: string): Promise<string | null> {\n try {\n const { stdout } = await execFileAsync(\"git\", [\"rev-parse\", \"HEAD\"], {\n cwd: workspace,\n timeout: 10_000,\n maxBuffer: 1024 * 1024,\n });\n const value = stdout.trim();\n return value || null;\n } catch {\n return null;\n }\n}\n\nasync function listRecursiveFiles(workspace: string, dir = workspace): Promise<string[]> {\n const entries = await readdir(dir, { withFileTypes: true });\n const files: string[] = [];\n for (const entry of entries) {\n const abs = join(dir, entry.name);\n const rel = relative(workspace, abs).split(sep).join(\"/\");\n if (entry.isDirectory()) {\n if (!shouldTraversePath(rel)) continue;\n files.push(...await listRecursiveFiles(workspace, abs));\n } else if (entry.isFile()) {\n if (!shouldConsiderPath(rel)) continue;\n files.push(rel);\n }\n }\n return files;\n}\n\nfunction shouldConsiderPath(path: string): boolean {\n const normalized = path.split(sep).join(\"/\");\n if (!shouldTraversePath(normalized)) return false;\n if (/(^|\\/)[^/]*\\.generated\\.[^/]+$/i.test(normalized)) return false;\n const ext = extension(normalized);\n if (BINARY_EXTENSIONS.has(ext)) return false;\n return SOURCE_EXTENSIONS.has(ext);\n}\n\nfunction shouldTraversePath(path: string): boolean {\n const normalized = path.split(sep).join(\"/\");\n return !normalized.split(\"/\").some((part) => SKIP_SEGMENTS.has(part));\n}\n\nfunction indexFile(workspace: string, relPath: string, maxFileBytes: number, generatedAt: string, cached?: RepoMapFile): RepoMapFile | null {\n const abs = resolve(workspace, relPath);\n let size = 0;\n let mtime = generatedAt;\n try {\n const stat = statSync(abs);\n size = stat.size;\n mtime = stat.mtime.toISOString();\n if (size > maxFileBytes) return null;\n if (cached && cached.lastIndexed === mtime && cached.size === size) return cached;\n } catch {\n return null;\n }\n const lang = langForPath(relPath);\n let content = \"\";\n try {\n content = readFileSync(abs, \"utf8\");\n } catch {\n return {\n path: relPath,\n lang,\n parser: \"path\",\n lastIndexed: mtime,\n size,\n symbols: [],\n imports: [],\n exports: [],\n };\n }\n const symbols = extractSymbols(content, lang);\n const imports = extractImports(content, lang);\n const exports = extractExports(content, lang, symbols);\n return {\n path: relPath,\n lang,\n parser: lang === \"unknown\" ? \"path\" : \"ripgrep\",\n lastIndexed: mtime,\n size,\n symbols,\n imports,\n exports,\n };\n}\n\nfunction extractSymbols(content: string, lang: RepoMapLang): RepoMapSymbol[] {\n const symbols: RepoMapSymbol[] = [];\n const lines = content.split(/\\r?\\n/);\n for (const [index, line] of lines.entries()) {\n const lineNo = index + 1;\n for (const symbol of symbolsForLine(line, lang, lineNo)) symbols.push(symbol);\n }\n return uniqueSymbols(symbols);\n}\n\nfunction symbolsForLine(line: string, lang: RepoMapLang, lineNo: number): RepoMapSymbol[] {\n const trimmed = line.trim();\n if (!trimmed || trimmed.startsWith(\"//\") || trimmed.startsWith(\"#\")) return [];\n switch (lang) {\n case \"ts\":\n case \"tsx\":\n case \"js\":\n case \"jsx\":\n return compactSymbols([\n matchSymbol(trimmed, /^(?:export\\s+)?(?:async\\s+)?function\\s+([A-Za-z_$][\\w$]*)\\b/, \"function\", lineNo),\n matchSymbol(trimmed, /^(?:export\\s+)?class\\s+([A-Za-z_$][\\w$]*)\\b/, \"class\", lineNo),\n matchSymbol(trimmed, /^(?:export\\s+)?(?:const|let|var)\\s+([A-Za-z_$][\\w$]*)\\b/, \"const\", lineNo),\n matchSymbol(trimmed, /^(?:export\\s+)?(?:type|interface)\\s+([A-Za-z_$][\\w$]*)\\b/, \"type\", lineNo),\n matchSymbol(trimmed, /^export\\s*\\{\\s*([A-Za-z_$][\\w$]*)\\b/, \"export\", lineNo),\n line.startsWith(\" \") || line.startsWith(\"\\t\")\n ? matchSymbol(trimmed, /^(?:async\\s+)?([A-Za-z_$][\\w$]*)\\s*\\([^)]*\\)\\s*\\{?$/, \"method\", lineNo)\n : null,\n ]);\n case \"py\":\n return compactSymbols([\n matchSymbol(trimmed, /^def\\s+([A-Za-z_]\\w*)\\b/, \"function\", lineNo),\n matchSymbol(trimmed, /^async\\s+def\\s+([A-Za-z_]\\w*)\\b/, \"function\", lineNo),\n matchSymbol(trimmed, /^class\\s+([A-Za-z_]\\w*)\\b/, \"class\", lineNo),\n ]);\n case \"go\":\n return compactSymbols([\n matchSymbol(trimmed, /^func\\s+(?:\\([^)]*\\)\\s*)?([A-Za-z_]\\w*)\\b/, \"function\", lineNo),\n matchSymbol(trimmed, /^type\\s+([A-Za-z_]\\w*)\\b/, \"type\", lineNo),\n matchSymbol(trimmed, /^(?:const|var)\\s+([A-Za-z_]\\w*)\\b/, \"const\", lineNo),\n ]);\n case \"swift\":\n return compactSymbols([\n matchSymbol(trimmed, /^(?:public\\s+|private\\s+|internal\\s+|open\\s+)?func\\s+([A-Za-z_]\\w*)\\b/, \"function\", lineNo),\n matchSymbol(trimmed, /^(?:public\\s+|private\\s+|internal\\s+|open\\s+)?(?:class|struct|enum|protocol)\\s+([A-Za-z_]\\w*)\\b/, \"class\", lineNo),\n matchSymbol(trimmed, /^(?:public\\s+|private\\s+|internal\\s+|open\\s+)?(?:let|var)\\s+([A-Za-z_]\\w*)\\b/, \"const\", lineNo),\n ]);\n case \"kt\":\n return compactSymbols([\n matchSymbol(trimmed, /^(?:public\\s+|private\\s+|internal\\s+)?fun\\s+([A-Za-z_]\\w*)\\b/, \"function\", lineNo),\n matchSymbol(trimmed, /^(?:public\\s+|private\\s+|internal\\s+)?(?:class|object|interface)\\s+([A-Za-z_]\\w*)\\b/, \"class\", lineNo),\n matchSymbol(trimmed, /^(?:public\\s+|private\\s+|internal\\s+)?(?:val|var)\\s+([A-Za-z_]\\w*)\\b/, \"const\", lineNo),\n matchSymbol(trimmed, /^typealias\\s+([A-Za-z_]\\w*)\\b/, \"type\", lineNo),\n ]);\n default:\n return [];\n }\n}\n\nfunction matchSymbol(line: string, pattern: RegExp, kind: RepoMapSymbolKind, lineNo: number): RepoMapSymbol | null {\n const match = line.match(pattern);\n const name = match?.[1];\n return name ? { name, kind, line: lineNo } : null;\n}\n\nfunction compactSymbols(symbols: Array<RepoMapSymbol | null>): RepoMapSymbol[] {\n return symbols.filter((symbol): symbol is RepoMapSymbol => Boolean(symbol));\n}\n\nfunction uniqueSymbols(symbols: RepoMapSymbol[]): RepoMapSymbol[] {\n const seen = new Set<string>();\n return symbols.filter((symbol) => {\n const key = `${symbol.name}:${symbol.kind}:${symbol.line}`;\n if (seen.has(key)) return false;\n seen.add(key);\n return true;\n });\n}\n\nfunction extractImports(content: string, lang: RepoMapLang): RepoMapImport[] {\n const imports: RepoMapImport[] = [];\n const lines = content.split(/\\r?\\n/);\n for (const line of lines) {\n const trimmed = line.trim();\n if (!trimmed) continue;\n if ([\"ts\", \"tsx\", \"js\", \"jsx\"].includes(lang)) {\n const from = trimmed.match(/^import\\s+(?:.+?\\s+from\\s+)?['\"]([^'\"]+)['\"]/);\n if (from?.[1]) imports.push({ from: from[1], ...namedImport(trimmed) });\n const req = trimmed.match(/require\\(['\"]([^'\"]+)['\"]\\)/);\n if (req?.[1]) imports.push({ from: req[1] });\n } else if (lang === \"py\") {\n const from = trimmed.match(/^from\\s+([A-Za-z0-9_./]+)\\s+import\\s+(.+)$/);\n if (from?.[1]) imports.push({ from: from[1], named: splitNames(from[2] ?? \"\") });\n const plain = trimmed.match(/^import\\s+(.+)$/);\n if (plain?.[1]) imports.push(...splitNames(plain[1]).map((name) => ({ from: name })));\n } else if (lang === \"go\") {\n const quoted = trimmed.match(/^\"([^\"]+)\"$/) ?? trimmed.match(/^import\\s+\"([^\"]+)\"/);\n if (quoted?.[1]) imports.push({ from: quoted[1] });\n } else if (lang === \"swift\") {\n const imported = trimmed.match(/^import\\s+([A-Za-z0-9_]+)/);\n if (imported?.[1]) imports.push({ from: imported[1] });\n } else if (lang === \"kt\") {\n const imported = trimmed.match(/^import\\s+([A-Za-z0-9_.]+)(?:\\.\\*)?/);\n if (imported?.[1]) imports.push({ from: imported[1] });\n }\n }\n return uniqueImports(imports);\n}\n\nfunction namedImport(line: string): { named?: string[] } {\n const named = line.match(/\\{\\s*([^}]+?)\\s*\\}/);\n const names = splitNames(named?.[1] ?? \"\");\n return names.length > 0 ? { named: names } : {};\n}\n\nfunction splitNames(value: string): string[] {\n return value\n .split(\",\")\n .map((item) => item.trim().replace(/\\s+as\\s+.+$/i, \"\").replace(/\\s+from\\s+.+$/i, \"\"))\n .filter(Boolean);\n}\n\nfunction uniqueImports(imports: RepoMapImport[]): RepoMapImport[] {\n const seen = new Set<string>();\n return imports.filter((entry) => {\n const key = `${entry.from}:${entry.named?.join(\",\") ?? \"\"}`;\n if (seen.has(key)) return false;\n seen.add(key);\n return true;\n });\n}\n\nfunction extractExports(content: string, lang: RepoMapLang, symbols: RepoMapSymbol[]): string[] {\n const exports = new Set<string>();\n for (const line of content.split(/\\r?\\n/)) {\n const trimmed = line.trim();\n const direct = trimmed.match(/^export\\s+(?:async\\s+)?(?:function|class|const|let|var|type|interface)\\s+([A-Za-z_$][\\w$]*)\\b/);\n if (direct?.[1]) exports.add(direct[1]);\n const list = trimmed.match(/^export\\s*\\{\\s*([^}]+)\\s*\\}/);\n if (list?.[1]) for (const name of splitNames(list[1])) exports.add(name);\n }\n if ([\"py\", \"go\", \"swift\", \"kt\"].includes(lang)) {\n for (const symbol of symbols) {\n if (!symbol.name.startsWith(\"_\")) exports.add(symbol.name);\n }\n }\n return [...exports].sort((a, b) => a.localeCompare(b));\n}\n\nfunction langForPath(path: string): RepoMapLang {\n return SOURCE_EXTENSIONS.get(extension(path)) ?? \"unknown\";\n}\n\nfunction extension(path: string): string {\n const match = path.match(/(\\.[^.\\/]+)$/);\n return match?.[1]?.toLowerCase() ?? \"\";\n}\n\nfunction configuredMaxFileBytes(): number {\n const raw = envValue(process.env, \"TANYA_REPO_MAP_MAX_FILE_BYTES\");\n const parsed = raw ? Number(raw) : NaN;\n return Number.isFinite(parsed) && parsed > 0 ? parsed : DEFAULT_MAX_FILE_BYTES;\n}\n","import { z } from \"zod\";\n\nexport const REPO_MAP_VERSION = 1;\nexport const REPO_MAP_SCHEMA_VERSION = 1;\n\nexport const RepoMapLangSchema = z.enum([\"ts\", \"tsx\", \"js\", \"jsx\", \"py\", \"go\", \"swift\", \"kt\", \"unknown\"]);\nexport const RepoMapParserSchema = z.enum([\"tree-sitter\", \"ripgrep\", \"path\"]);\nexport const RepoMapSymbolKindSchema = z.enum([\"function\", \"class\", \"method\", \"const\", \"type\", \"export\"]);\n\nexport const RepoMapSymbolSchema = z.object({\n name: z.string().min(1),\n kind: RepoMapSymbolKindSchema,\n line: z.number().int().positive(),\n}).strict();\n\nexport const RepoMapImportSchema = z.object({\n from: z.string().min(1),\n named: z.array(z.string().min(1)).optional(),\n}).strict();\n\nexport const RepoMapFileSchema = z.object({\n path: z.string().min(1),\n lang: RepoMapLangSchema,\n parser: RepoMapParserSchema,\n lastIndexed: z.string().datetime({ offset: true }),\n size: z.number().int().nonnegative(),\n symbols: z.array(RepoMapSymbolSchema),\n imports: z.array(RepoMapImportSchema),\n exports: z.array(z.string().min(1)),\n}).strict();\n\nexport const RepoMapSchema = z.object({\n version: z.literal(REPO_MAP_VERSION),\n workspace: z.string().min(1),\n generatedAt: z.string().datetime({ offset: true }),\n schemaVersion: z.number().int().positive(),\n files: z.array(RepoMapFileSchema),\n}).strict();\n\nexport type RepoMapLang = z.infer<typeof RepoMapLangSchema>;\nexport type RepoMapParser = z.infer<typeof RepoMapParserSchema>;\nexport type RepoMapSymbolKind = z.infer<typeof RepoMapSymbolKindSchema>;\nexport type RepoMapSymbol = z.infer<typeof RepoMapSymbolSchema>;\nexport type RepoMapImport = z.infer<typeof RepoMapImportSchema>;\nexport type RepoMapFile = z.infer<typeof RepoMapFileSchema>;\nexport type RepoMap = z.infer<typeof RepoMapSchema>;\n\nexport type RepoMapValidationIssue = {\n path: string;\n message: string;\n};\n\nexport type RepoMapValidationResult =\n | { ok: true; value: RepoMap; issues: [] }\n | { ok: false; issues: RepoMapValidationIssue[] };\n\nexport function validateRepoMap(input: unknown): RepoMapValidationResult {\n const parsed = RepoMapSchema.safeParse(input);\n if (parsed.success) return { ok: true, value: parsed.data, issues: [] };\n return {\n ok: false,\n issues: parsed.error.issues.map((issue) => ({\n path: jsonPointer(issue.path),\n message: issue.message,\n })),\n };\n}\n\nexport function assertRepoMap(input: unknown): RepoMap {\n const result = validateRepoMap(input);\n if (result.ok) return result.value;\n const details = result.issues.map((issue) => `${issue.path}: ${issue.message}`).join(\"; \");\n throw new Error(`Invalid repo-map: ${details}`);\n}\n\nfunction jsonPointer(path: Array<string | number | symbol>): string {\n if (path.length === 0) return \"/\";\n return `/${path.map((segment) => String(segment).replace(/~/g, \"~0\").replace(/\\//g, \"~1\")).join(\"/\")}`;\n}\n","import { readFile, writeFile, mkdir } from \"node:fs/promises\";\nimport { join, dirname } from \"node:path\";\nimport type { TanyaFinalManifest } from \"../agent/runner\";\nimport type { TanyaRunContext } from \"../context/runContext\";\n\nexport type TaskHistoryEntry = {\n timestamp: string;\n prompt: string;\n outcome: \"passed\" | \"blocked\";\n changedFiles: string[];\n gitHead: string | null;\n};\n\nexport async function appendTaskHistory(\n workspace: string,\n prompt: string,\n manifest: TanyaFinalManifest,\n _runContext?: TanyaRunContext,\n): Promise<void> {\n const historyPath = join(workspace, \".tania\", \"history.json\");\n await mkdir(dirname(historyPath), { recursive: true });\n let entries: TaskHistoryEntry[] = [];\n try {\n entries = JSON.parse(await readFile(historyPath, \"utf8\")) as TaskHistoryEntry[];\n if (!Array.isArray(entries)) entries = [];\n } catch {\n // First run or corrupt history; start fresh.\n }\n\n const validationErrors = manifest.validation?.issues.filter((issue) => issue.severity === \"error\") ?? [];\n const entry: TaskHistoryEntry = {\n timestamp: new Date().toISOString(),\n prompt: prompt.slice(0, 200),\n outcome: manifest.blockers.length === 0 && validationErrors.length === 0 ? \"passed\" : \"blocked\",\n changedFiles: manifest.changedFiles,\n gitHead: manifest.git.head,\n };\n\n entries = [...entries, entry].slice(-20);\n await writeFile(historyPath, JSON.stringify(entries, null, 2), \"utf8\");\n}\n\nexport async function readRecentTaskHistory(workspace: string, count = 3): Promise<TaskHistoryEntry[]> {\n try {\n const raw = await readFile(join(workspace, \".tania\", \"history.json\"), \"utf8\");\n const entries = JSON.parse(raw) as unknown;\n if (!Array.isArray(entries)) return [];\n return entries.slice(-count) as TaskHistoryEntry[];\n } catch {\n return [];\n }\n}\n\nexport function buildHistoryBlock(entries: TaskHistoryEntry[]): string {\n if (entries.length === 0) return \"\";\n const lines = [\"## Recent task history\"];\n for (const entry of entries) {\n const date = entry.timestamp.slice(0, 10);\n const files = entry.changedFiles.length > 0\n ? entry.changedFiles.join(\", \")\n : \"none\";\n lines.push(`- [${date}] ${entry.outcome.toUpperCase()}: \"${entry.prompt}\" → changed: ${files}`);\n }\n return lines.join(\"\\n\");\n}\n","import { existsSync, readdirSync, readFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\n\nexport interface RunLog {\n ts: string;\n prompt: string;\n provider?: string;\n model: string;\n durationMs: number;\n promptTokens: number;\n completionTokens: number;\n reasoningTokens?: number;\n systemPromptTokens?: number;\n repoMapTokens?: number;\n historyTokens?: number;\n toolResultTokens?: number;\n modelOutputTokens?: number;\n changedFiles: string[];\n blockers: string[];\n}\n\nexport interface RunCostEstimate {\n provider: string;\n usd: number | null;\n display: string;\n cacheModelKnown: boolean;\n}\n\ntype Pricing = {\n inputPerMillion: number;\n outputPerMillion: number;\n cacheModelKnown?: boolean;\n};\n\nexport const CACHE_MISS_ESTIMATE_TAG = \"[cache-miss estimate]\";\n\nconst deepSeekPricingByModel: Record<string, Pricing> = {\n \"deepseek-chat\": { inputPerMillion: 0.27, outputPerMillion: 1.10 },\n \"deepseek-reasoner\": { inputPerMillion: 0.55, outputPerMillion: 2.19 },\n};\n\nexport function readRunLogs(workspace: string, limit?: number): RunLog[] {\n const runsDir = join(workspace, \".tania\", \"runs\");\n if (!existsSync(runsDir)) return [];\n\n const files = readdirSync(runsDir)\n .filter((file) => file.endsWith(\".json\"))\n .sort()\n .reverse();\n const selected = limit === undefined ? files : files.slice(0, limit);\n\n return selected.flatMap((file) => {\n try {\n const parsed = JSON.parse(readFileSync(join(runsDir, file), \"utf8\")) as Partial<RunLog>;\n if (typeof parsed.ts !== \"string\" || typeof parsed.model !== \"string\") return [];\n return [{\n ts: parsed.ts,\n prompt: typeof parsed.prompt === \"string\" ? parsed.prompt : \"\",\n ...(typeof parsed.provider === \"string\" ? { provider: parsed.provider } : {}),\n model: parsed.model,\n durationMs: typeof parsed.durationMs === \"number\" ? parsed.durationMs : 0,\n promptTokens: typeof parsed.promptTokens === \"number\" ? parsed.promptTokens : 0,\n completionTokens: typeof parsed.completionTokens === \"number\" ? parsed.completionTokens : 0,\n ...(typeof parsed.reasoningTokens === \"number\" ? { reasoningTokens: parsed.reasoningTokens } : {}),\n ...(typeof parsed.systemPromptTokens === \"number\" ? { systemPromptTokens: parsed.systemPromptTokens } : {}),\n ...(typeof parsed.repoMapTokens === \"number\" ? { repoMapTokens: parsed.repoMapTokens } : {}),\n ...(typeof parsed.historyTokens === \"number\" ? { historyTokens: parsed.historyTokens } : {}),\n ...(typeof parsed.toolResultTokens === \"number\" ? { toolResultTokens: parsed.toolResultTokens } : {}),\n ...(typeof parsed.modelOutputTokens === \"number\" ? { modelOutputTokens: parsed.modelOutputTokens } : {}),\n changedFiles: Array.isArray(parsed.changedFiles) ? parsed.changedFiles.filter((file): file is string => typeof file === \"string\") : [],\n blockers: Array.isArray(parsed.blockers) ? parsed.blockers.filter((blocker): blocker is string => typeof blocker === \"string\") : [],\n }];\n } catch {\n return [];\n }\n });\n}\n\nexport function estimateRunCost(log: Pick<RunLog, \"provider\" | \"model\" | \"promptTokens\" | \"completionTokens\"> & { reasoningTokens?: number }): RunCostEstimate {\n const provider = normalizeProvider(log.provider, log.model);\n const pricing = provider === \"deepseek\" ? deepSeekPricingByModel[log.model] : undefined;\n if (!pricing) {\n return { provider, usd: null, display: \"pricing unknown\", cacheModelKnown: false };\n }\n\n const outputTokens = log.completionTokens + (log.reasoningTokens ?? 0);\n const usd = (log.promptTokens / 1_000_000) * pricing.inputPerMillion +\n (outputTokens / 1_000_000) * pricing.outputPerMillion;\n const cacheModelKnown = pricing.cacheModelKnown ?? false;\n return { provider, usd, display: formatUsdWithCacheNote(usd, cacheModelKnown), cacheModelKnown };\n}\n\nexport function formatRunLogLine(log: RunLog): string {\n const cost = estimateRunCost(log);\n const status = log.blockers.length > 0 ? \"BLOCKED\" : \"OK\";\n const duration = `${Math.round(log.durationMs / 1000)}s`;\n const fileCount = log.changedFiles.length;\n return `${log.ts.slice(0, 16)} ${status.padEnd(7)} ${duration.padStart(5)} ${cost.display.padStart(15)} ${fileCount} file(s) ${log.prompt.slice(0, 60)}`;\n}\n\nexport function formatUsd(usd: number): string {\n if (usd < 0.001) return \"<$0.001\";\n return `$${usd.toFixed(3)}`;\n}\n\nexport function formatUsdWithCacheNote(usd: number, cacheModelKnown = false): string {\n return cacheModelKnown ? formatUsd(usd) : `${formatUsd(usd)} ${CACHE_MISS_ESTIMATE_TAG}`;\n}\n\nfunction normalizeProvider(provider: string | undefined, model: string): string {\n if (provider?.trim()) return provider.trim();\n if (model.startsWith(\"deepseek-\")) return \"deepseek\";\n return \"unknown\";\n}\n","import { existsSync, readFileSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { join } from \"node:path\";\nimport { builtInRouteTable, ROUTES_SCHEMA_VERSION } from \"./defaults\";\nimport type {\n EffectiveRouteTable,\n ResolvedRoute,\n RouteCascadeEntry,\n RouteMatch,\n RouteRule,\n RouteSchemaIssue,\n RouteSchemaResult,\n RouteSource,\n RouteTable,\n RouteTarget,\n StepType,\n} from \"./types\";\n\nconst STEP_TYPES = new Set<StepType>([\"planning\", \"tool_call\", \"synthesis\", \"verification\", \"reasoning\", \"unknown\"]);\n\nexport interface LoadRouteTableOptions {\n cwd: string;\n home?: string;\n defaults: RouteTarget;\n}\n\nexport interface LoadedRouteTable {\n table: EffectiveRouteTable;\n issues: Array<RouteSchemaIssue & { file: string }>;\n}\n\nexport function loadRouteTable(options: LoadRouteTableOptions): LoadedRouteTable {\n const home = options.home ?? homedir();\n const builtIn = builtInRouteTable(options.defaults);\n const userFiles = [\n join(home, \".tanya\", \"routes.json\"),\n join(home, \".tania\", \"routes.json\"),\n ];\n const user = readFirstRouteFile(userFiles, \"user\");\n const project = readRouteFile(join(options.cwd, \".tania\", \"routes.json\"), \"project\");\n const sources = [\n ...(project.source ? [project.source] : []),\n ...(user.source ? [user.source] : []),\n \"built-in\",\n ];\n const issues = [...project.issues, ...user.issues];\n const routes = [\n ...sourceRoutes(project.value?.routes ?? [], \"project\"),\n ...sourceRoutes(user.value?.routes ?? [], \"user\"),\n ...sourceRoutes(builtIn.routes, \"built-in\"),\n ];\n const defaultSource: RouteSource = project.value?.defaults ? \"project\" : user.value?.defaults ? \"user\" : \"runtime-default\";\n const defaults = project.value?.defaults ?? user.value?.defaults ?? builtIn.defaults;\n const cascadeSource: RouteSource = project.value\n ? \"project\"\n : user.value\n ? \"user\"\n : \"built-in\";\n const cascade = sourceCascade(\n project.value ? cascadeOrLegacyDefault(project.value) :\n user.value ? cascadeOrLegacyDefault(user.value) :\n builtIn.cascade ?? cascadeOrLegacyDefault(builtIn),\n cascadeSource,\n );\n\n return {\n table: {\n version: ROUTES_SCHEMA_VERSION,\n routes,\n defaults,\n defaultSource,\n cascade,\n cascadeSource,\n sources,\n },\n issues,\n };\n}\n\nexport function parseRoutesJson(raw: string): RouteSchemaResult {\n try {\n return validateRouteTable(JSON.parse(raw) as unknown);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n return { ok: false, issues: [{ path: \"$\", message: `Invalid JSON: ${message}` }] };\n }\n}\n\nexport function validateRouteTable(input: unknown): RouteSchemaResult {\n const issues: RouteSchemaIssue[] = [];\n if (!isRecord(input)) {\n return { ok: false, issues: [{ path: \"$\", message: \"Expected an object.\" }] };\n }\n\n if (input.version !== ROUTES_SCHEMA_VERSION) {\n issues.push({ path: \"$.version\", message: `Expected schema version ${ROUTES_SCHEMA_VERSION}.` });\n }\n\n const routes = validateRoutes(input.routes, issues);\n const defaults = input.defaults === undefined\n ? validateLegacyDefaultTarget(input, issues)\n : validateTarget(input.defaults, \"$.defaults\", issues);\n const cascade = input.cascade === undefined ? undefined : validateCascade(input.cascade, issues);\n\n if (issues.length > 0) return { ok: false, issues };\n return {\n ok: true,\n value: {\n version: ROUTES_SCHEMA_VERSION,\n routes,\n defaults,\n ...(cascade ? { cascade } : {}),\n },\n issues: [],\n };\n}\n\nexport function resolveRoute(stepType: StepType, table: EffectiveRouteTable, text = \"\"): ResolvedRoute {\n const haystack = text || stepType;\n for (const rule of table.routes) {\n if (!routeMatches(rule.match, stepType, haystack)) continue;\n return {\n provider: rule.provider,\n model: rule.model,\n match: rule.match,\n ...(rule.fallback ? { fallback: rule.fallback } : {}),\n escalate: rule.escalate ?? true,\n ...(rule.reasoningCap ? { reasoningCap: rule.reasoningCap } : {}),\n source: rule.source,\n reason: typeof rule.match === \"string\" ? `matched step ${rule.match}` : `matched regex ${rule.match.regex}`,\n };\n }\n\n return {\n provider: table.defaults.provider,\n model: table.defaults.model,\n match: \"defaults\",\n escalate: true,\n source: table.defaultSource,\n reason: \"matched route defaults\",\n };\n}\n\nfunction readFirstRouteFile(files: string[], source: RouteSource): { value?: RouteTable; source?: string; issues: Array<RouteSchemaIssue & { file: string }> } {\n const issues: Array<RouteSchemaIssue & { file: string }> = [];\n for (const file of files) {\n const result = readRouteFile(file, source);\n issues.push(...result.issues);\n if (result.value && result.source) return { value: result.value, source: result.source, issues };\n }\n return { issues };\n}\n\nfunction readRouteFile(file: string, _source: RouteSource): { value?: RouteTable; source?: string; issues: Array<RouteSchemaIssue & { file: string }> } {\n if (!existsSync(file)) return { issues: [] };\n const parsed = parseRoutesJson(readFileSync(file, \"utf8\"));\n if (!parsed.ok) {\n return { issues: parsed.issues.map((issue) => ({ ...issue, file })) };\n }\n return { value: parsed.value, source: file, issues: [] };\n}\n\nfunction sourceRoutes(routes: RouteRule[], source: RouteSource) {\n return routes.map((route) => ({ ...route, source }));\n}\n\nfunction sourceCascade(cascade: RouteCascadeEntry[], source: RouteSource) {\n return cascade.map((route) => ({ ...route, source }));\n}\n\nfunction cascadeOrLegacyDefault(table: RouteTable): RouteCascadeEntry[] {\n return table.cascade?.length ? table.cascade : [targetToCascade(table.defaults)];\n}\n\nfunction targetToCascade(target: RouteTarget): RouteCascadeEntry {\n return {\n provider: target.provider,\n model: target.model,\n maxInputTokens: target.maxInputTokens ?? contextWindowForProvider(target.provider),\n };\n}\n\nfunction validateRoutes(input: unknown, issues: RouteSchemaIssue[]): RouteRule[] {\n if (input === undefined) return [];\n if (!Array.isArray(input)) {\n issues.push({ path: \"$.routes\", message: \"Expected an array.\" });\n return [];\n }\n\n return input.flatMap((item, index) => {\n const path = `$.routes[${index}]`;\n if (!isRecord(item)) {\n issues.push({ path, message: \"Expected an object.\" });\n return [];\n }\n\n const match = validateMatch(item.match, `${path}.match`, issues);\n const target = validateTarget(item, path, issues);\n const fallback = item.fallback === undefined ? undefined : validateTarget(item.fallback, `${path}.fallback`, issues);\n if (item.escalate !== undefined && typeof item.escalate !== \"boolean\") {\n issues.push({ path: `${path}.escalate`, message: \"Expected boolean when present.\" });\n }\n const reasoningCap = validateReasoningCap(item.reasoningCap, `${path}.reasoningCap`, issues);\n\n if (!match || !target) return [];\n return [{\n match,\n provider: target.provider,\n model: target.model,\n ...(target.maxInputTokens ? { maxInputTokens: target.maxInputTokens } : {}),\n ...(fallback ? { fallback } : {}),\n ...(item.escalate !== undefined ? { escalate: Boolean(item.escalate) } : {}),\n ...(reasoningCap ? { reasoningCap } : {}),\n }];\n });\n}\n\nfunction validateCascade(input: unknown, issues: RouteSchemaIssue[]): RouteCascadeEntry[] {\n if (!Array.isArray(input)) {\n issues.push({ path: \"$.cascade\", message: \"Expected an array when present.\" });\n return [];\n }\n return input.flatMap((item, index) => {\n const path = `$.cascade[${index}]`;\n const target = validateTarget(item, path, issues);\n const stepTypes = validateStepTypes(isRecord(item) ? item.stepTypes ?? item.step_types : undefined, `${path}.stepTypes`, issues);\n if (!target || !target.maxInputTokens) return [];\n return [{\n provider: target.provider,\n model: target.model,\n maxInputTokens: target.maxInputTokens,\n ...(stepTypes ? { stepTypes } : {}),\n }];\n });\n}\n\nfunction validateReasoningCap(input: unknown, path: string, issues: RouteSchemaIssue[]): { maxTokens: number } | null {\n if (input === undefined) return null;\n if (!isRecord(input)) {\n issues.push({ path, message: \"Expected an object when present.\" });\n return null;\n }\n if (typeof input.maxTokens !== \"number\" || !Number.isFinite(input.maxTokens) || input.maxTokens <= 0) {\n issues.push({ path: `${path}.maxTokens`, message: \"Expected a positive number.\" });\n return null;\n }\n return { maxTokens: Math.floor(input.maxTokens) };\n}\n\nfunction validateStepTypes(input: unknown, path: string, issues: RouteSchemaIssue[]): StepType[] | null {\n if (input === undefined) return null;\n if (!Array.isArray(input)) {\n issues.push({ path, message: \"Expected an array of step types when present.\" });\n return null;\n }\n const out: StepType[] = [];\n input.forEach((item, index) => {\n if (typeof item !== \"string\" || !STEP_TYPES.has(item as StepType)) {\n issues.push({ path: `${path}[${index}]`, message: \"Expected a known step type.\" });\n return;\n }\n out.push(item as StepType);\n });\n return out.length ? out : null;\n}\n\nfunction validateMatch(input: unknown, path: string, issues: RouteSchemaIssue[]): RouteMatch | null {\n if (typeof input === \"string\") {\n if (!STEP_TYPES.has(input as StepType)) {\n issues.push({ path, message: \"Expected a known step type.\" });\n return null;\n }\n return input as StepType;\n }\n\n if (!isRecord(input)) {\n issues.push({ path, message: \"Expected a step type string or { regex }.\" });\n return null;\n }\n if (typeof input.regex !== \"string\" || input.regex.trim() === \"\") {\n issues.push({ path: `${path}.regex`, message: \"Expected a non-empty regex string.\" });\n return null;\n }\n try {\n new RegExp(input.regex);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n issues.push({ path: `${path}.regex`, message: `Invalid regex: ${message}` });\n return null;\n }\n return { regex: input.regex };\n}\n\nfunction validateTarget(input: unknown, path: string, issues: RouteSchemaIssue[]): RouteTarget {\n if (!isRecord(input)) {\n issues.push({ path, message: \"Expected an object.\" });\n return { provider: \"\", model: \"\" };\n }\n const provider = typeof input.provider === \"string\" && input.provider.trim()\n ? input.provider.trim()\n : typeof input.cli === \"string\" && input.cli.trim()\n ? input.cli.trim()\n : \"\";\n const model = typeof input.model === \"string\" && input.model.trim()\n ? input.model.trim()\n : \"\";\n const maxInputTokens = numericField(input.maxInputTokens ?? input.max_input_tokens);\n if (!provider) {\n issues.push({ path: `${path}.provider`, message: \"Expected a non-empty provider string.\" });\n }\n if (!model) {\n issues.push({ path: `${path}.model`, message: \"Expected a non-empty model string.\" });\n }\n if ((input.maxInputTokens !== undefined || input.max_input_tokens !== undefined) && !maxInputTokens) {\n issues.push({ path: `${path}.maxInputTokens`, message: \"Expected a positive number.\" });\n }\n return {\n provider,\n model,\n ...(maxInputTokens ? { maxInputTokens } : {}),\n };\n}\n\nfunction validateLegacyDefaultTarget(input: Record<string, unknown>, issues: RouteSchemaIssue[]): RouteTarget {\n const defaultModel = typeof input.default_model === \"string\" && input.default_model.trim()\n ? input.default_model.trim()\n : typeof input.defaultModel === \"string\" && input.defaultModel.trim()\n ? input.defaultModel.trim()\n : \"\";\n const defaultProvider = typeof input.default_cli === \"string\" && input.default_cli.trim()\n ? input.default_cli.trim()\n : typeof input.default_provider === \"string\" && input.default_provider.trim()\n ? input.default_provider.trim()\n : typeof input.defaultProvider === \"string\" && input.defaultProvider.trim()\n ? input.defaultProvider.trim()\n : \"\";\n if (!defaultModel) {\n issues.push({ path: \"$.defaults\", message: \"Expected defaults or legacy default_model.\" });\n }\n const provider = defaultProvider || inferProviderForModel(defaultModel);\n if (!provider) {\n issues.push({ path: \"$.default_cli\", message: \"Expected default_cli/default_provider for this default_model.\" });\n }\n const maxInputTokens = numericField(input.maxInputTokens ?? input.max_input_tokens);\n return {\n provider,\n model: defaultModel,\n ...(maxInputTokens ? { maxInputTokens } : {}),\n };\n}\n\nfunction routeMatches(match: RouteMatch, stepType: StepType, text: string): boolean {\n if (typeof match === \"string\") return match === stepType;\n return new RegExp(match.regex).test(text);\n}\n\nfunction numericField(value: unknown): number | undefined {\n if (typeof value !== \"number\" || !Number.isFinite(value) || value <= 0) return undefined;\n return Math.floor(value);\n}\n\nfunction inferProviderForModel(model: string): string {\n if (/^deepseek-/i.test(model)) return \"deepseek\";\n if (/^(?:gpt-|o\\d|o\\d-|chatgpt)/i.test(model)) return \"openai\";\n if (/^claude-/i.test(model)) return \"claude\";\n if (/^gemini-/i.test(model)) return \"gemini\";\n if (/^qwen/i.test(model)) return \"qwen\";\n return \"\";\n}\n\nfunction contextWindowForProvider(provider: string): number {\n switch (provider) {\n case \"claude\":\n return 1_000_000;\n case \"gemini\":\n return 2_000_000;\n case \"openai\":\n return 200_000;\n default:\n return 128_000;\n }\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return Boolean(value && typeof value === \"object\" && !Array.isArray(value));\n}\n","import type { RouteCascadeEntry, RouteTable, RouteTarget } from \"./types\";\n\nexport const ROUTES_SCHEMA_VERSION = 1;\n\nexport const BUILT_IN_ROUTE_DEFAULTS: RouteTarget = {\n provider: \"openai\",\n model: \"gpt-4.1-mini\",\n maxInputTokens: 128_000,\n};\n\nexport const BUILT_IN_ROUTE_CASCADE: RouteCascadeEntry[] = [\n { provider: \"deepseek\", model: \"deepseek-chat\", maxInputTokens: 128_000 },\n { provider: \"openai\", model: \"gpt-5-codex\", maxInputTokens: 200_000 },\n { provider: \"claude\", model: \"claude-sonnet-4-6\", maxInputTokens: 1_000_000 },\n { provider: \"gemini\", model: \"gemini-1.5-pro\", maxInputTokens: 2_000_000 },\n];\n\nexport function builtInRouteTable(defaults: RouteTarget = BUILT_IN_ROUTE_DEFAULTS): RouteTable {\n return {\n version: ROUTES_SCHEMA_VERSION,\n routes: [\n {\n match: \"planning\",\n provider: \"deepseek\",\n model: \"deepseek-chat\",\n fallback: { provider: \"qwen\", model: \"qwen3-coder-plus\" },\n reasoningCap: { maxTokens: 2_000 },\n },\n {\n match: \"tool_call\",\n provider: \"deepseek\",\n model: \"deepseek-chat\",\n fallback: { provider: \"groq\", model: \"llama-3.3-70b-versatile\" },\n },\n {\n match: \"synthesis\",\n provider: \"deepseek\",\n model: \"deepseek-reasoner\",\n fallback: { provider: \"openai\", model: \"gpt-4.1-mini\" },\n reasoningCap: { maxTokens: 8_000 },\n },\n {\n match: \"verification\",\n provider: \"deepseek\",\n model: \"deepseek-reasoner\",\n fallback: { provider: \"openai\", model: \"gpt-4.1-mini\" },\n reasoningCap: { maxTokens: 8_000 },\n },\n {\n match: \"reasoning\",\n provider: \"deepseek\",\n model: \"deepseek-reasoner\",\n fallback: { provider: \"qwen\", model: \"qwen3-coder-plus\" },\n reasoningCap: { maxTokens: 8_000 },\n },\n ],\n defaults,\n cascade: BUILT_IN_ROUTE_CASCADE,\n };\n}\n","import { existsSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport type { ChatMessage, ToolCall } from \"../providers/types\";\nimport type { TanyaRunContext } from \"../context/runContext\";\nimport type { StepType } from \"./types\";\n\nexport interface RunnerStepState {\n messages?: ChatMessage[];\n lastAssistantMessage?: ChatMessage;\n lastToolResults?: ChatMessage[];\n pendingToolCalls?: Array<ToolCall | PendingTool>;\n depth?: number;\n turnIndex?: number;\n providerReasoningActive?: boolean;\n prompt?: string;\n cwd?: string;\n runContext?: TanyaRunContext;\n}\n\ninterface PendingTool {\n name?: string;\n preferredModel?: { match?: \"tool_call\" | \"verification\" };\n function?: { name?: string };\n}\n\nexport function classifyStep(state: RunnerStepState): StepType {\n const lastAssistant = state.lastAssistantMessage ?? lastMessageWithRole(state.messages ?? [], \"assistant\");\n const pendingToolCalls = state.pendingToolCalls ?? lastAssistant?.tool_calls ?? [];\n\n if (hasVerificationTool(pendingToolCalls)) return \"verification\";\n if (hasActiveReasoning(state, lastAssistant)) return \"reasoning\";\n if (!lastAssistant || state.turnIndex === 0) return \"planning\";\n\n const content = textContent(lastAssistant);\n if (pendingToolCalls.length > 0 && content.trim() === \"\") return \"tool_call\";\n\n const toolResultsSinceUser = state.lastToolResults ?? messagesSinceLastUser(state.messages ?? []).filter((message) => message.role === \"tool\");\n if (content.trim() !== \"\" && pendingToolCalls.length === 0 && toolResultsSinceUser.length >= 2) {\n return \"synthesis\";\n }\n\n if (looksLikeCodeEditingTask(state)) return \"tool_call\";\n\n return \"unknown\";\n}\n\nexport function looksLikeCodeEditingTask(state: Pick<RunnerStepState, \"messages\" | \"prompt\" | \"cwd\" | \"runContext\">): boolean {\n const runContext = state.runContext;\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\n const taskText = [\n runContext?.task?.title,\n runContext?.task?.summary,\n runContext?.stack,\n ...(runContext?.languages ?? []),\n ...(runContext?.frameworks ?? []),\n state.prompt,\n ...userMessageContent(state.messages ?? []),\n ].filter(Boolean).join(\"\\n\");\n\n if (/\\bgo-backend-[a-z0-9_-]+\\b/i.test(taskText)) return true;\n if (/template\\s*(?:id|ID)?\\s*[:=]?\\s*[\"'`]?go-backend-[a-z0-9_-]+/i.test(taskText)) return true;\n if (/EXISTING CODE DETECTED/i.test(taskText) && /\\bEXECUTE\\s+mode\\b/i.test(taskText)) return true;\n\n return Boolean(state.cwd && isCodeWorkspace(state.cwd) && taskText.length > 1_200);\n}\n\nfunction isCodeWorkspace(cwd: string): boolean {\n return [\n \"go.mod\",\n \"package.json\",\n \"Cargo.toml\",\n \"pyproject.toml\",\n \"requirements.txt\",\n \"Package.swift\",\n ].some((marker) => existsSync(join(cwd, marker)));\n}\n\nfunction hasVerificationTool(toolCalls: Array<ToolCall | PendingTool>): boolean {\n return toolCalls.some((tool) => {\n if (isPreferredVerification(tool)) return true;\n const name = toolName(tool);\n return name === \"verify\" || name === \"finalize\" || name.startsWith(\"validate_\");\n });\n}\n\nfunction hasActiveReasoning(state: RunnerStepState, lastAssistant: ChatMessage | undefined): boolean {\n if (state.providerReasoningActive) return true;\n const content = textContent(lastAssistant);\n const openThink = content.lastIndexOf(\"<think>\");\n if (openThink === -1) return false;\n const closeThink = content.lastIndexOf(\"</think>\");\n return closeThink < openThink;\n}\n\nfunction isPreferredVerification(tool: ToolCall | PendingTool): boolean {\n return \"preferredModel\" in tool && tool.preferredModel?.match === \"verification\";\n}\n\nfunction toolName(tool: ToolCall | PendingTool): string {\n if (\"name\" in tool && typeof tool.name === \"string\") return tool.name;\n if (tool.function?.name) return tool.function.name;\n return \"\";\n}\n\nfunction textContent(message: ChatMessage | undefined): string {\n return message?.content ?? \"\";\n}\n\nfunction lastMessageWithRole(messages: ChatMessage[], role: ChatMessage[\"role\"]): ChatMessage | undefined {\n for (let index = messages.length - 1; index >= 0; index -= 1) {\n if (messages[index]?.role === role) return messages[index];\n }\n return undefined;\n}\n\nfunction messagesSinceLastUser(messages: ChatMessage[]): ChatMessage[] {\n for (let index = messages.length - 1; index >= 0; index -= 1) {\n if (messages[index]?.role === \"user\") return messages.slice(index + 1);\n }\n return messages;\n}\n\nfunction userMessageContent(messages: ChatMessage[]): string[] {\n return messages\n .filter((message) => message.role === \"user\" && typeof message.content === \"string\")\n .map((message) => message.content ?? \"\");\n}\n","import type { ProviderAdapter } from \"./types\";\n\nexport const deepSeekAdapter: ProviderAdapter = {\n id: \"deepseek\",\n matchBaseUrl: /api\\.deepseek\\.com/i,\n defaultBaseUrl: \"https://api.deepseek.com\",\n defaultModel: \"deepseek-v4-pro\",\n capabilities: {\n toolChoiceRequired: false,\n parallelToolCalls: false,\n jsonMode: true,\n vision: false,\n reasoning: true,\n roundTripReasoning: true,\n flattenSchemas: false,\n contextWindow: 128_000,\n },\n};\n","import type { ChatRequest } from \"../types\";\n\nexport type ProviderCapabilities = {\n toolChoiceRequired: boolean;\n parallelToolCalls: boolean;\n jsonMode: boolean;\n vision: boolean;\n reasoning: boolean;\n roundTripReasoning?: boolean;\n flattenSchemas: boolean;\n contextWindow: number;\n};\n\nexport type ProviderRequest = ChatRequest & Record<string, unknown>;\n\nexport type ChatResponse = Record<string, unknown>;\n\nexport type ProviderAdapter = {\n id: string;\n matchBaseUrl?: RegExp;\n defaultBaseUrl?: string;\n defaultModel?: string;\n capabilities: ProviderCapabilities;\n preRequest?: (req: ProviderRequest) => ProviderRequest;\n postResponse?: (res: ChatResponse) => ChatResponse;\n};\n\nexport function withoutUnsupportedToolChoice(req: ProviderRequest): ProviderRequest {\n if (req.tool_choice === \"required\") {\n const { tool_choice: _toolChoice, ...rest } = req;\n return rest;\n }\n return req;\n}\n\nexport function identityResponse(res: ChatResponse): ChatResponse {\n return res;\n}\n","import type { ProviderAdapter } from \"./types\";\nimport { withoutUnsupportedToolChoice } from \"./types\";\n\nexport const grokAdapter: ProviderAdapter = {\n id: \"grok\",\n matchBaseUrl: /(?:api\\.)?x\\.ai/i,\n defaultBaseUrl: \"https://api.x.ai/v1\",\n defaultModel: \"grok-3-mini\",\n capabilities: {\n toolChoiceRequired: false,\n parallelToolCalls: false,\n jsonMode: true,\n vision: true,\n reasoning: true,\n flattenSchemas: false,\n contextWindow: 131_000,\n },\n preRequest: withoutUnsupportedToolChoice,\n};\n","import type { ProviderAdapter } from \"./types\";\n\nexport const groqAdapter: ProviderAdapter = {\n id: \"groq\",\n matchBaseUrl: /api\\.groq\\.com/i,\n defaultBaseUrl: \"https://api.groq.com/openai/v1\",\n defaultModel: \"llama-3.3-70b-versatile\",\n capabilities: {\n toolChoiceRequired: false,\n parallelToolCalls: false,\n jsonMode: true,\n vision: false,\n reasoning: false,\n flattenSchemas: false,\n contextWindow: 131_000,\n },\n};\n","import type { ProviderAdapter } from \"./types\";\nimport { withoutUnsupportedToolChoice } from \"./types\";\n\nexport const ollamaAdapter: ProviderAdapter = {\n id: \"ollama\",\n matchBaseUrl: /(?:localhost:11434|127\\.0\\.0\\.1:11434|ollama)/i,\n defaultBaseUrl: \"http://localhost:11434/v1\",\n defaultModel: \"qwen2.5-coder:7b\",\n capabilities: {\n toolChoiceRequired: false,\n parallelToolCalls: false,\n jsonMode: true,\n vision: false,\n reasoning: false,\n flattenSchemas: false,\n contextWindow: 32_000,\n },\n preRequest: withoutUnsupportedToolChoice,\n};\n","import type { ProviderAdapter } from \"./types\";\n\nexport const openAiAdapter: ProviderAdapter = {\n id: \"openai\",\n matchBaseUrl: /(?:api\\.)?openai\\.com/i,\n defaultBaseUrl: \"https://api.openai.com/v1\",\n defaultModel: \"gpt-4.1-mini\",\n capabilities: {\n toolChoiceRequired: true,\n parallelToolCalls: true,\n jsonMode: true,\n vision: true,\n reasoning: true,\n flattenSchemas: false,\n contextWindow: 128_000,\n },\n};\n","import type { ProviderAdapter } from \"./types\";\nimport { withoutUnsupportedToolChoice } from \"./types\";\n\nexport const qwenAdapter: ProviderAdapter = {\n id: \"qwen\",\n matchBaseUrl: /(?:dashscope|aliyuncs|qwen)/i,\n defaultBaseUrl: \"https://dashscope.aliyuncs.com/compatible-mode/v1\",\n defaultModel: \"qwen3-coder-plus\",\n capabilities: {\n toolChoiceRequired: false,\n parallelToolCalls: false,\n jsonMode: true,\n vision: true,\n reasoning: true,\n flattenSchemas: true,\n contextWindow: 128_000,\n },\n preRequest: (req) => ({\n ...withoutUnsupportedToolChoice(req),\n parallel_tool_calls: false,\n }),\n};\n","import type { ProviderAdapter } from \"./types\";\nimport { withoutUnsupportedToolChoice } from \"./types\";\n\nexport const togetherAdapter: ProviderAdapter = {\n id: \"together\",\n matchBaseUrl: /api\\.together\\.xyz/i,\n defaultBaseUrl: \"https://api.together.xyz/v1\",\n defaultModel: \"Qwen/Qwen3-Coder-480B-A35B-Instruct-FP8\",\n capabilities: {\n toolChoiceRequired: false,\n parallelToolCalls: false,\n jsonMode: true,\n vision: false,\n reasoning: false,\n flattenSchemas: true,\n contextWindow: 32_000,\n },\n preRequest: withoutUnsupportedToolChoice,\n};\n","import { deepSeekAdapter } from \"./deepseek\";\nimport { grokAdapter } from \"./grok\";\nimport { groqAdapter } from \"./groq\";\nimport { ollamaAdapter } from \"./ollama\";\nimport { openAiAdapter } from \"./openai\";\nimport { qwenAdapter } from \"./qwen\";\nimport { togetherAdapter } from \"./together\";\nimport type { ProviderAdapter } from \"./types\";\n\nexport type { ChatResponse, ProviderAdapter, ProviderCapabilities, ProviderRequest } from \"./types\";\n\nexport const providerAdapters: ProviderAdapter[] = [\n deepSeekAdapter,\n qwenAdapter,\n grokAdapter,\n groqAdapter,\n togetherAdapter,\n ollamaAdapter,\n openAiAdapter,\n];\n\nconst aliases = new Map<string, string>([\n [\"deepseek-reasoner\", \"deepseek\"],\n [\"deepseek-chat\", \"deepseek\"],\n [\"xai\", \"grok\"],\n [\"openai-compatible\", \"openai\"],\n [\"custom\", \"openai\"],\n]);\n\nexport function resolveProviderAdapter(input: { provider?: string; baseUrl?: string } = {}): ProviderAdapter {\n const provider = normalizeProviderId(input.provider);\n if (provider) {\n const explicit = providerAdapters.find((adapter) => adapter.id === provider);\n if (explicit) return explicit;\n }\n\n const baseUrl = input.baseUrl?.trim();\n if (baseUrl) {\n const matched = providerAdapters.find((adapter) => adapter.matchBaseUrl?.test(baseUrl));\n if (matched) return matched;\n }\n\n return openAiAdapter;\n}\n\nexport function listProviderAdapters(): ProviderAdapter[] {\n return [...providerAdapters];\n}\n\nfunction normalizeProviderId(provider: string | undefined): string | null {\n const normalized = provider?.trim().toLowerCase();\n if (!normalized) return null;\n return aliases.get(normalized) ?? normalized;\n}\n","import type { ChatMessage } from \"../providers/types\";\nimport { appendFile, mkdir, readFile } from \"node:fs/promises\";\nimport { existsSync } from \"node:fs\";\nimport { join } from \"node:path\";\n\nexport interface ArchivedMessage {\n archivedAt: string;\n originalTs?: string;\n role: ChatMessage[\"role\"];\n content: string;\n toolName?: string;\n tokens?: number;\n}\n\nexport interface ArchiveOptions {\n workspace?: string;\n}\n\nconst appendQueues = new Map<string, Promise<void>>();\n\nexport async function appendArchive(runId: string, messages: ArchivedMessage[], options: ArchiveOptions = {}): Promise<void> {\n if (messages.length === 0) return;\n const path = archivePath(options.workspace ?? process.cwd(), runId);\n await mkdir(join(options.workspace ?? process.cwd(), \".tanya\", \"runs\", runId), { recursive: true });\n const payload = messages.map((message) => JSON.stringify(message)).join(\"\\n\") + \"\\n\";\n const previous = appendQueues.get(path) ?? Promise.resolve();\n const next = previous.then(() => appendFile(path, payload, \"utf8\"));\n appendQueues.set(path, next.catch(() => {}));\n await next;\n}\n\nexport async function readArchive(runId: string, options: ArchiveOptions = {}): Promise<ArchivedMessage[]> {\n const path = archivePath(options.workspace ?? process.cwd(), runId);\n if (!existsSync(path)) return [];\n const raw = await readFile(path, \"utf8\");\n return raw.split(/\\r?\\n/)\n .filter(Boolean)\n .flatMap((line) => {\n try {\n const parsed = JSON.parse(line) as Partial<ArchivedMessage>;\n if (typeof parsed.archivedAt !== \"string\" || typeof parsed.role !== \"string\" || typeof parsed.content !== \"string\") return [];\n return [{\n archivedAt: parsed.archivedAt,\n ...(typeof parsed.originalTs === \"string\" ? { originalTs: parsed.originalTs } : {}),\n role: parsed.role as ChatMessage[\"role\"],\n content: parsed.content,\n ...(typeof parsed.toolName === \"string\" ? { toolName: parsed.toolName } : {}),\n ...(typeof parsed.tokens === \"number\" ? { tokens: parsed.tokens } : {}),\n }];\n } catch {\n return [];\n }\n });\n}\n\nexport async function searchArchive(runId: string, query: string, options: ArchiveOptions = {}): Promise<ArchivedMessage[]> {\n const needle = query.toLowerCase();\n if (!needle) return [];\n const entries = await readArchive(runId, options);\n return entries.filter((entry) =>\n entry.content.toLowerCase().includes(needle) ||\n entry.toolName?.toLowerCase().includes(needle),\n );\n}\n\nexport function toArchivedMessages(messages: ChatMessage[], archivedAt = new Date().toISOString()): ArchivedMessage[] {\n const toolNamesById = new Map<string, string>();\n for (const message of messages) {\n for (const toolCall of message.tool_calls ?? []) {\n toolNamesById.set(toolCall.id, toolCall.function.name);\n }\n }\n\n return messages.map((message) => {\n const content = JSON.stringify({\n content: message.content,\n ...(message.tool_call_id ? { tool_call_id: message.tool_call_id } : {}),\n ...(message.tool_calls ? { tool_calls: message.tool_calls } : {}),\n });\n const toolName = message.tool_calls?.map((call) => call.function.name).filter(Boolean).join(\",\") ||\n (message.tool_call_id ? toolNamesById.get(message.tool_call_id) : undefined);\n return {\n archivedAt,\n role: message.role,\n content,\n ...(toolName ? { toolName } : {}),\n tokens: Math.ceil(JSON.stringify(message).length / 4),\n };\n });\n}\n\nexport function fileTouchPathsFromArchive(entries: ArchivedMessage[]): string[] {\n const paths = new Set<string>();\n for (const entry of entries) {\n for (const path of fileTouchPathsFromArchivedContent(entry.content)) {\n paths.add(path);\n }\n }\n return [...paths].sort();\n}\n\nfunction archivePath(workspace: string, runId: string): string {\n return join(workspace, \".tanya\", \"runs\", runId, \"archive.jsonl\");\n}\n\nfunction fileTouchPathsFromArchivedContent(content: string): string[] {\n const paths = new Set<string>();\n try {\n const parsed = JSON.parse(content) as { tool_calls?: Array<{ function?: { name?: string; arguments?: string } }> };\n for (const toolCall of parsed.tool_calls ?? []) {\n const name = toolCall.function?.name;\n const rawArgs = toolCall.function?.arguments;\n if (!name || !rawArgs) continue;\n for (const path of fileTouchPathsFromToolArguments(name, rawArgs)) paths.add(path);\n }\n } catch {\n // Fall through to regex extraction below.\n }\n\n for (const match of content.matchAll(/\\*\\*\\*\\s+(?:Add|Update|Delete)\\s+File:\\s+([^\\n]+)/g)) {\n const path = match[1]?.trim();\n if (path) paths.add(path);\n }\n return [...paths];\n}\n\nfunction fileTouchPathsFromToolArguments(toolName: string, rawArguments: string): string[] {\n if (toolName === \"apply_patch\") return patchPaths(rawArguments);\n if (![\"write_file\", \"search_replace\", \"read_file\"].includes(toolName)) return [];\n try {\n const parsed = JSON.parse(rawArguments) as { path?: unknown };\n return typeof parsed.path === \"string\" && parsed.path.trim() ? [parsed.path.trim()] : [];\n } catch {\n return [];\n }\n}\n\nfunction patchPaths(rawArguments: string): string[] {\n const paths = new Set<string>();\n try {\n const parsed = JSON.parse(rawArguments) as { patch?: unknown };\n const patch = typeof parsed.patch === \"string\" ? parsed.patch : rawArguments;\n for (const match of patch.matchAll(/\\*\\*\\*\\s+(?:Add|Update|Delete)\\s+File:\\s+([^\\n]+)/g)) {\n const path = match[1]?.trim();\n if (path) paths.add(path);\n }\n } catch {\n for (const match of rawArguments.matchAll(/\\*\\*\\*\\s+(?:Add|Update|Delete)\\s+File:\\s+([^\\n]+)/g)) {\n const path = match[1]?.trim();\n if (path) paths.add(path);\n }\n }\n return [...paths];\n}\n","import type { ChatMessage, ChatProvider, ToolCall } from \"../providers/types\";\nimport { appendArchive, toArchivedMessages } from \"../memory/runArchive\";\n\nexport type MicrocompactOptions = {\n tokenBudget: number;\n foldRatio?: number;\n};\n\nexport type MicrocompactResult = {\n messages: ChatMessage[];\n removedTokens: number;\n foldedPairs: number;\n archivedMessages: ChatMessage[];\n};\n\nexport type SnipLowSignalResult = {\n messages: ChatMessage[];\n snippedCount: number;\n archivedMessages: ChatMessage[];\n};\n\nexport type CompactionAggression = \"normal\" | \"heavy\";\n\nexport type AutoCompactOptions = {\n provider: ChatProvider;\n model?: string;\n aggression: CompactionAggression;\n archive?: {\n workspace: string;\n runId: string;\n };\n};\n\nexport type AutoCompactResult = {\n messages: ChatMessage[];\n removedTokens: number;\n summaryTokens: number;\n summary: string;\n};\n\ntype FoldableGroup = {\n start: number;\n end: number;\n toolCalls: ToolCall[];\n};\n\nconst READ_ONLY_TOOL_NAMES = new Set([\"list_files\", \"read_file\", \"search\", \"glob\"]);\n\nexport function estimateCompactTokens(messages: ChatMessage[]): number {\n return Math.ceil(JSON.stringify(messages).length / 4);\n}\n\nexport function microcompact(messages: ChatMessage[], options: MicrocompactOptions): MicrocompactResult {\n const beforeTokens = estimateCompactTokens(messages);\n const groups = findFoldableGroups(messages);\n if (groups.length === 0) {\n return { messages: [...messages], removedTokens: 0, foldedPairs: 0, archivedMessages: [] };\n }\n\n const foldRatio = Math.max(0, Math.min(1, options.foldRatio ?? 0.2));\n const maxFoldedGroups = Math.max(1, Math.ceil(groups.length * foldRatio));\n const foldedStarts = new Map<number, FoldableGroup>();\n for (const group of groups.slice(0, maxFoldedGroups)) {\n foldedStarts.set(group.start, group);\n }\n\n const compacted: ChatMessage[] = [];\n const archivedMessages: ChatMessage[] = [];\n let foldedPairs = 0;\n for (let i = 0; i < messages.length; i += 1) {\n const group = foldedStarts.get(i);\n if (!group) {\n const message = messages[i];\n if (message) compacted.push(message);\n continue;\n }\n\n foldedPairs += group.toolCalls.length;\n archivedMessages.push(...messages.slice(group.start, group.end + 1).filter((message): message is ChatMessage => Boolean(message)));\n compacted.push({\n role: \"assistant\",\n content: `<${group.toolCalls.length} tool-call(s) folded; outputs were empty or noop>`,\n });\n i = group.end;\n if (estimateCompactTokens(compacted.concat(messages.slice(i + 1))) <= options.tokenBudget) {\n for (let next = i + 1; next < messages.length; next += 1) {\n const message = messages[next];\n if (message) compacted.push(message);\n }\n const afterTokens = estimateCompactTokens(compacted);\n return {\n messages: compacted,\n removedTokens: Math.max(0, beforeTokens - afterTokens),\n foldedPairs,\n archivedMessages,\n };\n }\n }\n\n const afterTokens = estimateCompactTokens(compacted);\n return {\n messages: compacted,\n removedTokens: Math.max(0, beforeTokens - afterTokens),\n foldedPairs,\n archivedMessages,\n };\n}\n\nexport function snipLowSignal(messages: ChatMessage[]): SnipLowSignalResult {\n const toolCallsById = new Map<string, { call: ToolCall; assistantIndex: number }>();\n const assistantCallIds = new Map<number, string[]>();\n const toolMessageIds = new Set<string>();\n for (let index = 0; index < messages.length; index += 1) {\n const message = messages[index];\n if (isPureToolCallAssistant(message)) {\n const ids = message.tool_calls.map((call) => call.id);\n assistantCallIds.set(index, ids);\n for (const call of message.tool_calls) {\n toolCallsById.set(call.id, { call, assistantIndex: index });\n }\n }\n if (message?.role === \"tool\" && message.tool_call_id) {\n toolMessageIds.add(message.tool_call_id);\n }\n }\n\n const candidateSnippedToolIds = new Set<string>();\n for (const message of messages) {\n if (message.role !== \"tool\" || !message.tool_call_id) continue;\n const toolCall = toolCallsById.get(message.tool_call_id)?.call;\n if (!toolCall) continue;\n if (READ_ONLY_TOOL_NAMES.has(toolCall.function.name) && isNoopToolContent(message.content)) {\n candidateSnippedToolIds.add(message.tool_call_id);\n }\n }\n\n for (const duplicateId of duplicateReadFileCallIds(messages, toolCallsById)) {\n candidateSnippedToolIds.add(duplicateId);\n }\n\n const assistantIndicesToRemove = new Set<number>();\n const actualSnippedToolIds = new Set<string>();\n for (const [assistantIndex, callIds] of assistantCallIds) {\n const allCallsCanBeSnipped = callIds.length > 0 &&\n callIds.every((id) => candidateSnippedToolIds.has(id) && toolMessageIds.has(id));\n if (!allCallsCanBeSnipped) continue;\n assistantIndicesToRemove.add(assistantIndex);\n for (const id of callIds) actualSnippedToolIds.add(id);\n }\n\n if (assistantIndicesToRemove.size === 0 && actualSnippedToolIds.size === 0) {\n return { messages: [...messages], snippedCount: 0, archivedMessages: [] };\n }\n\n const snipped: ChatMessage[] = [];\n const archivedMessages: ChatMessage[] = [];\n let snippedCount = 0;\n for (let index = 0; index < messages.length; index += 1) {\n const message = messages[index];\n const removeAssistant = assistantIndicesToRemove.has(index);\n const removeTool = message?.role === \"tool\" &&\n Boolean(message.tool_call_id && actualSnippedToolIds.has(message.tool_call_id));\n if (removeAssistant || removeTool) {\n snippedCount += 1;\n if (message) archivedMessages.push(message);\n continue;\n }\n if (message) snipped.push(message);\n }\n return { messages: snipped, snippedCount, archivedMessages };\n}\n\nexport class CompactionExhaustedError extends Error {\n constructor(message = \"Context compaction exhausted after repeated provider context-window failures.\") {\n super(message);\n this.name = \"CompactionExhaustedError\";\n }\n}\n\nexport async function autoCompact(messages: ChatMessage[], options: AutoCompactOptions): Promise<AutoCompactResult> {\n const indices = summarizableIndices(messages, options.aggression);\n if (indices.length === 0) {\n return { messages: [...messages], removedTokens: 0, summaryTokens: 0, summary: \"\" };\n }\n\n const summarized = indices.map((index) => messages[index]).filter((message): message is ChatMessage => Boolean(message));\n const summary = await summarizeMessages(options.provider, summarized, options);\n if (options.archive) {\n await appendArchive(options.archive.runId, toArchivedMessages(summarized), { workspace: options.archive.workspace });\n }\n const summaryMessage: ChatMessage = {\n role: \"system\",\n content: `[compaction summary: ${summary}]`,\n };\n const skipped = new Set(indices);\n const firstSummaryIndex = indices[0] ?? 0;\n const compacted: ChatMessage[] = [];\n for (let index = 0; index < messages.length; index += 1) {\n if (index === firstSummaryIndex) {\n compacted.push(summaryMessage);\n }\n if (skipped.has(index)) continue;\n const message = messages[index];\n if (message) compacted.push(message);\n }\n\n const beforeTokens = estimateCompactTokens(messages);\n const afterTokens = estimateCompactTokens(compacted);\n return {\n messages: compacted,\n removedTokens: Math.max(0, beforeTokens - afterTokens),\n summaryTokens: estimateCompactTokens([summaryMessage]),\n summary,\n };\n}\n\nfunction findFoldableGroups(messages: ChatMessage[]): FoldableGroup[] {\n const groups: FoldableGroup[] = [];\n for (let i = 0; i < messages.length; i += 1) {\n const message = messages[i];\n if (!isPureToolCallAssistant(message)) continue;\n\n const expectedIds = new Set(message.tool_calls.map((call) => call.id));\n const toolResults: ChatMessage[] = [];\n let j = i + 1;\n while (j < messages.length && messages[j]?.role === \"tool\") {\n const toolMessage = messages[j];\n if (!toolMessage?.tool_call_id || !expectedIds.has(toolMessage.tool_call_id)) break;\n toolResults.push(toolMessage);\n j += 1;\n }\n\n if (toolResults.length !== expectedIds.size) continue;\n if (!toolResults.every((toolMessage) => isNoopToolContent(toolMessage.content))) continue;\n\n groups.push({ start: i, end: j - 1, toolCalls: message.tool_calls });\n i = j - 1;\n }\n return groups;\n}\n\nfunction summarizableIndices(messages: ChatMessage[], aggression: CompactionAggression): number[] {\n const latestUserIndex = findLatestUserIndex(messages);\n const candidates: number[] = [];\n for (let index = 0; index < messages.length; index += 1) {\n const message = messages[index];\n if (!message || message.role === \"system\") continue;\n if (index === latestUserIndex) continue;\n candidates.push(index);\n }\n\n if (candidates.length === 0) return [];\n const ratio = aggression === \"heavy\" ? 0.75 : 0.5;\n return candidates.slice(0, Math.max(1, Math.floor(candidates.length * ratio)));\n}\n\nfunction findLatestUserIndex(messages: ChatMessage[]): number {\n for (let index = messages.length - 1; index >= 0; index -= 1) {\n if (messages[index]?.role === \"user\") return index;\n }\n return -1;\n}\n\nasync function summarizeMessages(\n provider: ChatProvider,\n messages: ChatMessage[],\n options: AutoCompactOptions,\n): Promise<string> {\n const rendered = JSON.stringify(messages, null, 2);\n const prompt = [\n \"Summarize these older Tanya conversation turns for loss-minimizing context compaction.\",\n \"Keep durable decisions, file paths, tool effects, blockers, and verification facts.\",\n \"Do not include generic narration. Return a compact factual summary.\",\n \"\",\n `Provider/model context: ${provider.id}/${options.model ?? provider.model}`,\n `Aggression: ${options.aggression}`,\n \"\",\n rendered,\n ].join(\"\\n\");\n\n let summary = \"\";\n for await (const delta of provider.streamChat({\n messages: [{ role: \"user\", content: prompt }],\n tools: [],\n temperature: 0,\n topP: 0.2,\n maxTokens: 1024,\n })) {\n if (delta.content) summary += delta.content;\n }\n return summary.trim() || \"No summary returned.\";\n}\n\nfunction duplicateReadFileCallIds(\n messages: ChatMessage[],\n toolCallsById: Map<string, { call: ToolCall; assistantIndex: number }>,\n): Set<string> {\n const latestByPath = new Map<string, string>();\n const duplicates = new Set<string>();\n for (const message of messages) {\n if (message.role !== \"tool\" || !message.tool_call_id) continue;\n const toolCall = toolCallsById.get(message.tool_call_id)?.call;\n if (!toolCall || toolCall.function.name !== \"read_file\") continue;\n const path = readFilePath(toolCall);\n if (!path) continue;\n const previousId = latestByPath.get(path);\n if (previousId) duplicates.add(previousId);\n latestByPath.set(path, message.tool_call_id);\n }\n return duplicates;\n}\n\nfunction readFilePath(toolCall: ToolCall): string | null {\n try {\n const parsed = JSON.parse(toolCall.function.arguments) as unknown;\n if (!parsed || typeof parsed !== \"object\" || Array.isArray(parsed)) return null;\n const path = (parsed as { path?: unknown }).path;\n return typeof path === \"string\" && path.trim() ? path.trim() : null;\n } catch {\n return null;\n }\n}\n\nfunction isPureToolCallAssistant(message: ChatMessage | undefined): message is ChatMessage & { tool_calls: ToolCall[] } {\n return Boolean(\n message &&\n message.role === \"assistant\" &&\n Array.isArray(message.tool_calls) &&\n message.tool_calls.length > 0 &&\n (message.content === null || message.content.trim() === \"\"),\n );\n}\n\nfunction isNoopToolContent(content: string | null): boolean {\n const trimmed = content?.trim() ?? \"\";\n if (!trimmed) return true;\n try {\n const parsed = JSON.parse(trimmed) as unknown;\n return isNoopObject(parsed);\n } catch {\n return false;\n }\n}\n\nfunction isNoopObject(value: unknown): boolean {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) return false;\n const record = value as Record<string, unknown>;\n const keys = Object.keys(record);\n if (keys.length === 1) return record.ok === true;\n if (keys.length === 2) return record.ok === true && record.summary === \"\";\n return false;\n}\n","import { resolveProviderAdapter } from \"../providers/adapters\";\nimport type { ChatMessage } from \"../providers/types\";\nimport type { TanyaRunContext } from \"../context/runContext\";\nimport { estimateCompactTokens } from \"../agent/compact\";\nimport { envValue } from \"../config/envCompat\";\nimport { looksLikeCodeEditingTask } from \"./classify\";\nimport { resolveRoute } from \"./load\";\nimport type { EffectiveRouteTable, ResolvedRoute, RouteAttempt, RouteTarget, StepType } from \"./types\";\n\nexport class RouteContextOverflowError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"RouteContextOverflowError\";\n }\n}\n\nexport class EscalationExhaustedError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"EscalationExhaustedError\";\n }\n}\n\nexport function resolveRouteWithContextGuard(params: {\n stepType: StepType;\n table: EffectiveRouteTable;\n messages: ChatMessage[];\n routeText?: string;\n prompt?: string;\n cwd?: string;\n runContext?: TanyaRunContext;\n forcedRoute?: RouteTarget;\n}): ResolvedRoute {\n const estimate = estimateCompactTokens(params.messages);\n const safetyFactor = routeSafetyFactor();\n\n if (params.forcedRoute) {\n return resolveForcedRoute(params.forcedRoute, params.stepType, estimate, safetyFactor);\n }\n\n const primary = resolveRoute(params.stepType, params.table, params.routeText);\n const guardedPrimary = codeEditingDeepSeekChatGuard(primary, params);\n const candidates: ResolvedRoute[] = [\n guardedPrimary,\n ...(guardedPrimary.fallback ? [routeFromTarget(guardedPrimary.fallback, guardedPrimary, \"fallback\")] : []),\n ...cascadeRoutesForStep(params.table, params.stepType),\n ];\n const seen = new Set<string>();\n const attempts: RouteAttempt[] = [];\n\n for (const candidate of candidates) {\n const key = `${candidate.provider}/${candidate.model}`;\n if (seen.has(key)) continue;\n seen.add(key);\n const attempt = routeAttempt(candidate, estimate, safetyFactor);\n attempts.push(attempt);\n if (estimate <= attempt.safetyLimit) {\n if (attempts.length === 1 && candidate === primary) return candidate;\n const reason = attempts.length > 1\n ? `${candidate.reason}; cascade-fit; declined earlier route due to context-window guard`\n : candidate.reason;\n return {\n ...candidate,\n reason,\n cascade: {\n reason: \"cascade-fit\",\n estimatedTokens: estimate,\n safetyFactor,\n attemptedRoutes: attempts,\n selectedRoute: attempt,\n selectedIndex: attempts.length - 1,\n },\n };\n }\n }\n\n const highest = highestAttempt(attempts);\n if (highest) {\n throw new RouteContextOverflowError(\n `Estimated ${estimate.toLocaleString(\"en-US\")} tokens exceeds the largest configured route ${highest.provider}/${highest.model} ` +\n `(${highest.maxInputTokens.toLocaleString(\"en-US\")} tokens × ${safetyFactor} safety = ${highest.safetyLimit.toLocaleString(\"en-US\")}). ` +\n \"Reduce prompt or add a higher-context route.\",\n );\n }\n throw new RouteContextOverflowError(\n `No route can fit estimated ${estimate} tokens for step ${params.stepType}.`,\n );\n}\n\nexport function contextWindowForTarget(target: RouteTarget): number {\n return target.maxInputTokens ?? modelContextWindow(target) ?? resolveProviderAdapter({ provider: target.provider }).capabilities.contextWindow;\n}\n\nfunction routeFromTarget(target: RouteTarget, primary: ResolvedRoute, label: \"fallback\"): ResolvedRoute {\n return {\n provider: target.provider,\n model: target.model,\n ...(target.maxInputTokens ? { maxInputTokens: target.maxInputTokens } : {}),\n match: primary.match,\n escalate: primary.escalate,\n ...(primary.reasoningCap ? { reasoningCap: primary.reasoningCap } : {}),\n source: primary.source,\n reason: `matched ${label} for ${primary.provider}/${primary.model}`,\n };\n}\n\nfunction cascadeRoutesForStep(table: EffectiveRouteTable, stepType: StepType): ResolvedRoute[] {\n return table.cascade\n .filter((entry) => !entry.stepTypes || entry.stepTypes.includes(stepType))\n .map((entry) => ({\n provider: entry.provider,\n model: entry.model,\n maxInputTokens: entry.maxInputTokens,\n match: \"defaults\" as const,\n escalate: true,\n source: entry.source,\n reason: `matched route cascade ${entry.provider}/${entry.model}`,\n }));\n}\n\nfunction resolveForcedRoute(target: RouteTarget, stepType: StepType, estimate: number, safetyFactor: number): ResolvedRoute {\n const candidate: ResolvedRoute = {\n provider: target.provider,\n model: target.model,\n ...(target.maxInputTokens ? { maxInputTokens: target.maxInputTokens } : {}),\n match: stepType,\n escalate: false,\n source: \"session\",\n reason: `forced route ${target.provider}/${target.model}`,\n };\n const attempt = routeAttempt(candidate, estimate, safetyFactor);\n if (estimate <= attempt.safetyLimit) return candidate;\n throw new RouteContextOverflowError(\n `Forced route ${target.provider}/${target.model} cannot fit estimated ${estimate.toLocaleString(\"en-US\")} tokens ` +\n `(${attempt.maxInputTokens.toLocaleString(\"en-US\")} tokens × ${safetyFactor} safety = ${attempt.safetyLimit.toLocaleString(\"en-US\")}). ` +\n \"Reduce prompt or choose a higher-context forced route.\",\n );\n}\n\nfunction routeAttempt(route: ResolvedRoute, _estimate: number, safetyFactor: number): RouteAttempt {\n const maxInputTokens = contextWindowForTarget(route);\n return {\n provider: route.provider,\n model: route.model,\n maxInputTokens,\n safetyLimit: Math.floor(maxInputTokens * safetyFactor),\n source: route.source,\n reason: route.reason,\n };\n}\n\nfunction highestAttempt(attempts: RouteAttempt[]): RouteAttempt | null {\n return attempts.reduce<RouteAttempt | null>((highest, attempt) => {\n if (!highest || attempt.maxInputTokens > highest.maxInputTokens) return attempt;\n return highest;\n }, null);\n}\n\nfunction routeSafetyFactor(env: NodeJS.ProcessEnv = process.env): number {\n const raw = Number(envValue(env, \"TANYA_ROUTE_SAFETY_FACTOR\"));\n if (!Number.isFinite(raw) || raw <= 0 || raw > 1) return 0.85;\n return raw;\n}\n\nfunction modelContextWindow(target: RouteTarget): number | null {\n const model = target.model.toLowerCase();\n if (target.provider === \"claude\" || model.startsWith(\"claude-\")) return 1_000_000;\n if (target.provider === \"gemini\" || model.startsWith(\"gemini-\")) return 2_000_000;\n if (model.includes(\"gpt-5-codex\") || model.includes(\"o3-codex\")) return 200_000;\n return null;\n}\n\nfunction codeEditingDeepSeekChatGuard(primary: ResolvedRoute, params: {\n stepType: StepType;\n table: EffectiveRouteTable;\n messages: ChatMessage[];\n prompt?: string;\n cwd?: string;\n runContext?: TanyaRunContext;\n}): ResolvedRoute {\n if (params.stepType !== \"unknown\") return primary;\n if (!isDeepSeekChat(primary)) return primary;\n const codeTaskState = {\n messages: params.messages,\n ...(params.prompt ? { prompt: params.prompt } : {}),\n ...(params.cwd ? { cwd: params.cwd } : {}),\n ...(params.runContext ? { runContext: params.runContext } : {}),\n };\n\n if (!looksLikeCodeEditingTask(codeTaskState)) {\n return primary;\n }\n\n const target = firstNonDeepSeekChatTarget([\n primary.fallback,\n params.table.defaults,\n { provider: \"deepseek\", model: \"deepseek-reasoner\" },\n ]);\n if (!target) return primary;\n return {\n ...routeFromTarget(target, primary, \"fallback\"),\n reason: `${primary.reason}; declined deepseek-chat for code-editing task`,\n };\n}\n\nfunction firstNonDeepSeekChatTarget(targets: Array<RouteTarget | undefined>): RouteTarget | null {\n return targets.find((target): target is RouteTarget => Boolean(target && !isDeepSeekChat(target))) ?? null;\n}\n\nfunction isDeepSeekChat(target: RouteTarget): boolean {\n return target.provider === \"deepseek\" && target.model === \"deepseek-chat\";\n}\n","import { spawnSync } from \"node:child_process\";\nimport { existsSync, readdirSync, readFileSync } from \"node:fs\";\nimport { join, relative } from \"node:path\";\n\nconst ignoredNames = new Set([\".git\", \"node_modules\", \".next\", \"dist\", \"build\", \".turbo\", \".cache\"]);\nconst artifactIgnoredNames = new Set([\".DS_Store\", \".git\", \"node_modules\", \"dist\", \"build\"]);\n\nconst instructionFiles = [\"TANYA.md\", \"TANIA.md\", \"AGENTS.md\", \"CLAUDE.md\", \"README.md\", \".tania/INSTRUCTIONS.md\"];\nconst projectMarkers = [\n { file: \"package.json\", type: \"node\" },\n { file: \"pyproject.toml\", type: \"python\" },\n { file: \"requirements.txt\", type: \"python\" },\n { file: \"Cargo.toml\", type: \"rust\" },\n { file: \"go.mod\", type: \"go\" },\n { file: \"Package.swift\", type: \"swift\" },\n] as const;\n\ninterface WorkspaceSummary {\n workspace: string;\n isGitRepo: boolean;\n gitStatus: string | null;\n projectTypes: string[];\n verificationSuggestions: string[];\n tree: string[];\n instructionReads: { path: string; content: string }[];\n packageScripts: Record<string, string>;\n}\n\nfunction readIfExists(filePath: string, maxChars = 4_000): string | null {\n try {\n if (!existsSync(filePath)) return null;\n const content = readFileSync(filePath, \"utf8\");\n return content.length > maxChars ? `${content.slice(0, maxChars)}\\n[truncated]` : content;\n } catch {\n return null;\n }\n}\n\nfunction readFullIfExists(filePath: string): string | null {\n try {\n if (!existsSync(filePath)) return null;\n return readFileSync(filePath, \"utf8\");\n } catch {\n return null;\n }\n}\n\nfunction normalizeTerms(text: string): string[] {\n return [...new Set(text.toLowerCase().match(/[a-z0-9_+-]{2,}/g) ?? [])];\n}\n\nconst artifactDirectoryKeywords: Record<string, string[]> = {\n android: [\"android\", \"kotlin\", \"compose\", \"gradle\", \"room\", \"play\", \"launcher\", \"mipmap\", \"manifest\"],\n backend: [\"backend\", \"api\", \"route\", \"endpoint\", \"server\", \"prisma\", \"database\", \"postgres\", \"auth\", \"jwt\", \"trpc\", \"openapi\"],\n components: [\"component\", \"components\", \"ui\", \"shared\", \"button\", \"card\", \"input\"],\n configs: [\"config\", \"configs\", \"eslint\", \"tailwind\", \"typescript\", \"tsconfig\", \"prettier\"],\n ios: [\"ios\", \"swift\", \"swiftui\", \"xcode\", \"apple\", \"appicon\", \"splash\", \"onboarding\", \"storekit\"],\n landing: [\"landing\", \"marketing\", \"hero\", \"pricing\", \"web\", \"seo\", \"store\", \"badge\"],\n macos: [\"macos\", \"mac\", \"appkit\", \"xcode\", \"apple\"],\n prompts: [\"prompt\", \"prompts\", \"instructions\", \"task\", \"spec\"],\n resources: [\"resource\", \"resources\", \"azure\", \"deploy\", \"email\", \"dns\", \"storage\", \"database\"],\n styles: [\"style\", \"styles\", \"theme\", \"color\", \"typography\", \"css\"],\n testing: [\"test\", \"testing\", \"ci\", \"lint\", \"typecheck\", \"vitest\", \"playwright\", \"workflow\"],\n web: [\"web\", \"react\", \"next\", \"nextjs\", \"frontend\", \"browser\", \"page\", \"route\"],\n};\n\nfunction scoreArtifactDirectory(name: string, taskHint: string): number {\n const lowerName = name.toLowerCase();\n const taskTerms = normalizeTerms(taskHint);\n const keywords = new Set([\n ...normalizeTerms(name),\n ...(artifactDirectoryKeywords[lowerName] ?? []),\n ]);\n let score = 0;\n for (const term of taskTerms) {\n if (term === lowerName) score += 8;\n if (lowerName.includes(term) || term.includes(lowerName)) score += 4;\n if (keywords.has(term)) score += 3;\n }\n return score;\n}\n\nfunction artifactDirectoryPreview(artifactsRoot: string, directory: string, maxEntries = 10): string[] {\n try {\n return readdirSync(join(artifactsRoot, directory), { withFileTypes: true })\n .filter((entry) => !artifactIgnoredNames.has(entry.name))\n .sort((a, b) => Number(a.isDirectory()) - Number(b.isDirectory()) || a.name.localeCompare(b.name))\n .slice(0, maxEntries)\n .map((entry) => entry.isDirectory() ? `${directory}/${entry.name}/` : `${directory}/${entry.name}`);\n } catch {\n return [];\n }\n}\n\nexport function buildArtifactIndexBlock(workspace: string, taskHint = \"\"): string {\n const artifactsRoot = join(workspace, \"artifacts\");\n if (!existsSync(artifactsRoot)) return \"\";\n\n let entries;\n try {\n entries = readdirSync(artifactsRoot, { withFileTypes: true });\n } catch {\n return \"\";\n }\n\n const directories = entries\n .filter((entry) => entry.isDirectory() && !artifactIgnoredNames.has(entry.name) && !entry.name.startsWith(\".\"))\n .map((entry) => ({\n name: entry.name,\n score: scoreArtifactDirectory(entry.name, taskHint),\n preview: artifactDirectoryPreview(artifactsRoot, entry.name),\n }))\n .sort((a, b) => b.score - a.score || a.name.localeCompare(b.name));\n\n const rulesCandidates = [\n { path: \"artifacts/prompts/RULES.md\", absolutePath: join(artifactsRoot, \"prompts\", \"RULES.md\") },\n { path: \"artifacts/RULES.md\", absolutePath: join(artifactsRoot, \"RULES.md\") },\n ];\n const rulesRead = rulesCandidates\n .map((candidate) => ({ path: candidate.path, content: readFullIfExists(candidate.absolutePath) }))\n .find((candidate): candidate is { path: string; content: string } => candidate.content !== null && candidate.content.trim().length > 0);\n const indexReads = [\n { path: \"artifacts/description.md\", content: readIfExists(join(artifactsRoot, \"description.md\"), 12_000) },\n { path: \"artifacts/README.md\", content: readIfExists(join(artifactsRoot, \"README.md\"), 12_000) },\n ].filter((entry): entry is { path: string; content: string } => entry.content !== null && entry.content.trim().length > 0);\n\n if (!rulesRead && indexReads.length === 0 && directories.length === 0) return \"\";\n\n const lines: string[] = [\n \"## Artifact Index\",\n \"Artifacts root: artifacts/\",\n \"Use this index to choose reusable artifacts before writing common app, backend, mobile, landing, deploy, store, auth, billing, onboarding, splash, icon, or testing code from scratch.\",\n ];\n\n if (taskHint.trim()) {\n lines.push(`Task relevance hint: ${taskHint.trim().slice(0, 500)}`);\n }\n\n if (rulesRead) {\n lines.push(\"\", `### Mandatory Artifact Rules (${rulesRead.path})`, rulesRead.content);\n }\n\n if (directories.length > 0) {\n lines.push(\"\", \"### Ranked Artifact Directories\");\n for (const directory of directories.slice(0, 12)) {\n const relevance = directory.score > 0 ? `score=${directory.score}` : \"fallback\";\n lines.push(`- artifacts/${directory.name}/ (${relevance})`);\n for (const item of directory.preview.slice(0, 6)) {\n lines.push(` - artifacts/${item}`);\n }\n }\n }\n\n const preReadParts: string[] = [];\n let totalPreReadChars = 0;\n const maxArtifactContentChars = 5_000;\n const maxArtifactFiles = 4;\n const scoredFiles: Array<{ path: string; fullPath: string; score: number }> = [];\n for (const directory of directories) {\n const subdirPath = join(artifactsRoot, directory.name);\n let mdFiles: string[] = [];\n try {\n mdFiles = readdirSync(subdirPath, { withFileTypes: true })\n .filter((entry) => entry.isFile() && entry.name.toLowerCase().endsWith(\".md\"))\n .map((entry) => entry.name);\n } catch {\n continue;\n }\n for (const mdFile of mdFiles) {\n const fileScore = directory.score + scoreArtifactDirectory(mdFile.replace(/\\.md$/i, \"\"), taskHint);\n if (fileScore > 0) {\n scoredFiles.push({\n path: `artifacts/${directory.name}/${mdFile}`,\n fullPath: join(subdirPath, mdFile),\n score: fileScore,\n });\n }\n }\n }\n\n scoredFiles.sort((a, b) => b.score - a.score || a.path.localeCompare(b.path));\n for (const { path, fullPath } of scoredFiles.slice(0, maxArtifactFiles)) {\n if (totalPreReadChars >= maxArtifactContentChars) break;\n const remaining = maxArtifactContentChars - totalPreReadChars;\n const content = readIfExists(fullPath, remaining);\n if (!content) continue;\n preReadParts.push(`#### ${path}\\n${content}`);\n totalPreReadChars += content.length;\n }\n\n if (preReadParts.length > 0) {\n lines.push(\"\", \"### Pre-read artifact files (apply these patterns before implementing)\", preReadParts.join(\"\\n\\n---\\n\\n\"));\n }\n\n for (const { path, content } of indexReads) {\n lines.push(\"\", `### ${path}`, content.trim());\n }\n\n const output = lines.join(\"\\n\");\n return output.length > 18_000 ? `${output.slice(0, 17_980)}\\n[... truncated]` : output;\n}\n\nfunction runGit(workspace: string, args: string[]): string | null {\n const result = spawnSync(\"git\", args, {\n cwd: workspace,\n encoding: \"utf8\",\n timeout: 5_000,\n });\n if (result.status !== 0) return null;\n return result.stdout.trim();\n}\n\nexport function collectTree(workspace: string, maxEntries = 120, maxDepth = 2): string[] {\n const entries: string[] = [];\n\n function walk(dir: string, depth: number): void {\n if (entries.length >= maxEntries || depth > maxDepth) return;\n\n let dirents;\n try {\n dirents = readdirSync(dir, { withFileTypes: true });\n } catch {\n return;\n }\n\n for (const entry of dirents) {\n if (entries.length >= maxEntries) return;\n if (ignoredNames.has(entry.name)) continue;\n\n const fullPath = join(dir, entry.name);\n const rel = relative(workspace, fullPath).replace(/\\\\/g, \"/\");\n entries.push(entry.isDirectory() ? `${rel}/` : rel);\n if (entry.isDirectory()) walk(fullPath, depth + 1);\n }\n }\n\n walk(workspace, 1);\n return entries;\n}\n\nexport function detectProjectTypes(workspace: string): string[] {\n const types = new Set<string>();\n for (const marker of projectMarkers) {\n if (existsSync(join(workspace, marker.file))) types.add(marker.type);\n }\n if (existsSync(join(workspace, \"gradlew\")) || existsSync(join(workspace, \"settings.gradle\")) || existsSync(join(workspace, \"settings.gradle.kts\"))) {\n types.add(\"android\");\n }\n try {\n const hasXcodeProject = readdirSync(workspace).some((name) => name.endsWith(\".xcodeproj\") || name.endsWith(\".xcworkspace\"));\n if (hasXcodeProject) types.add(\"ios\");\n } catch {\n // ignore unreadable workspace\n }\n return [...types];\n}\n\ntype ExportMapEntry = {\n file: string;\n exports: Array<{ name: string; isDefault: boolean }>;\n};\n\nfunction collectTypeScriptFiles(workspace: string): string[] {\n const files: string[] = [];\n\n function walk(dir: string): void {\n let dirents;\n try {\n dirents = readdirSync(dir, { withFileTypes: true });\n } catch {\n return;\n }\n\n for (const entry of dirents) {\n if (ignoredNames.has(entry.name)) continue;\n const fullPath = join(dir, entry.name);\n if (entry.isDirectory()) {\n walk(fullPath);\n continue;\n }\n if (entry.isFile() && /\\.tsx?$/.test(entry.name)) {\n files.push(relative(workspace, fullPath).replace(/\\\\/g, \"/\"));\n }\n }\n }\n\n walk(workspace);\n return files;\n}\n\nfunction exportMapPriority(file: string): number {\n if (file.startsWith(\"src/lib/\")) return 0;\n if (file.startsWith(\"src/app/api/\")) return 1;\n if (file.startsWith(\"src/server/\")) return 2;\n if (file.startsWith(\"lib/\")) return 3;\n return 4;\n}\n\nfunction formatExportName(entry: { name: string; isDefault: boolean }): string {\n return entry.isDefault ? `${entry.name} (default)` : entry.name;\n}\n\nfunction parseFileExports(workspace: string, file: string): ExportMapEntry | null {\n const content = readIfExists(join(workspace, file), 200_000);\n if (!content) return null;\n const exports: Array<{ name: string; isDefault: boolean }> = [];\n const seen = new Set<string>();\n const namedExportPattern = /^\\s*export\\s+(default\\s+function|default\\s+class|function|const|class|type|interface)\\s+(\\w+)/;\n const defaultExportPattern = /^\\s*export\\s+default(?:\\s+(\\w+))?/;\n\n for (const line of content.split(/\\r?\\n/)) {\n const namedMatch = line.match(namedExportPattern);\n if (namedMatch?.[2]) {\n const isDefault = namedMatch[1]?.startsWith(\"default\") ?? false;\n const key = `${namedMatch[2]}:${isDefault ? \"default\" : \"named\"}`;\n if (!seen.has(key)) {\n seen.add(key);\n exports.push({ name: namedMatch[2], isDefault });\n }\n continue;\n }\n\n const defaultMatch = line.match(defaultExportPattern);\n if (defaultMatch) {\n const name = defaultMatch[1] ?? \"default\";\n const key = `${name}:default`;\n if (!seen.has(key)) {\n seen.add(key);\n exports.push({ name, isDefault: true });\n }\n }\n }\n\n return exports.length > 0 ? { file, exports } : null;\n}\n\nexport function buildExportMap(workspace: string): string {\n const typeScriptFiles = collectTypeScriptFiles(workspace);\n if (typeScriptFiles.length === 0) return \"\";\n\n const entries = typeScriptFiles\n .sort((a, b) => exportMapPriority(a) - exportMapPriority(b) || a.localeCompare(b))\n .map((file) => parseFileExports(workspace, file))\n .filter((entry): entry is ExportMapEntry => entry !== null)\n .slice(0, 80);\n\n if (entries.length === 0) return \"\";\n\n const totalExportingFiles = typeScriptFiles\n .map((file) => parseFileExports(workspace, file))\n .filter((entry): entry is ExportMapEntry => entry !== null)\n .length;\n const lines = [\n \"## Workspace export map\",\n ...entries.map((entry) => `${entry.file}: ${entry.exports.map(formatExportName).join(\", \")}`),\n ];\n if (totalExportingFiles > entries.length) {\n lines.push(`[... ${totalExportingFiles - entries.length} more files]`);\n }\n\n let output = lines.join(\"\\n\");\n if (output.length <= 3_000) return output;\n\n const truncatedLines = [\"## Workspace export map\"];\n let included = 0;\n for (const line of lines.slice(1)) {\n const remaining = entries.length - included;\n const candidate = [...truncatedLines, line, `[... ${Math.max(remaining - 1, 0)} more files]`].join(\"\\n\");\n if (candidate.length > 3_000) break;\n truncatedLines.push(line);\n included += 1;\n }\n const omitted = entries.length - included + Math.max(0, totalExportingFiles - entries.length);\n if (omitted > 0) truncatedLines.push(`[... ${omitted} more files]`);\n output = truncatedLines.join(\"\\n\");\n return output.length > 3_000 ? `${output.slice(0, 2_980)}\\n[... truncated]` : output;\n}\n\nfunction detectVerificationSuggestions(workspace: string, projectTypes: string[], packageScripts: Record<string, string>): string[] {\n const suggestions = new Set<string>();\n if (projectTypes.includes(\"android\")) {\n const gradle = existsSync(join(workspace, \"gradlew\")) ? \"./gradlew\" : \"gradle\";\n suggestions.add(`${gradle} test`);\n suggestions.add(`${gradle} assembleDebug`);\n }\n if (projectTypes.includes(\"ios\")) {\n suggestions.add(\"xcodebuild -list\");\n suggestions.add(\"xcodebuild build -scheme <scheme> -destination 'platform=iOS Simulator,name=iPhone 16'\");\n }\n if (projectTypes.includes(\"swift\")) {\n suggestions.add(\"swift test\");\n suggestions.add(\"swift build\");\n }\n for (const name of [\"typecheck\", \"test\", \"build\", \"lint\"]) {\n if (packageScripts[name]) suggestions.add(`npm run ${name}`);\n }\n return [...suggestions].slice(0, 8);\n}\n\nfunction readPackageScripts(workspace: string): Record<string, string> {\n const content = readIfExists(join(workspace, \"package.json\"), 80_000);\n if (!content) return {};\n\n try {\n const parsed = JSON.parse(content) as { scripts?: unknown };\n if (!parsed.scripts || typeof parsed.scripts !== \"object\") return {};\n const scripts: Record<string, string> = {};\n for (const [name, command] of Object.entries(parsed.scripts)) {\n if (typeof command === \"string\") scripts[name] = command;\n }\n return scripts;\n } catch {\n return {};\n }\n}\n\nexport function loadWorkspaceSummary(workspace: string): WorkspaceSummary {\n const gitRoot = runGit(workspace, [\"rev-parse\", \"--show-toplevel\"]);\n const isGitRepo = Boolean(gitRoot);\n const gitStatus = isGitRepo ? runGit(workspace, [\"status\", \"--short\"]) ?? \"\" : null;\n const instructionReads: { path: string; content: string }[] = [];\n\n for (const fileName of instructionFiles) {\n const filePath = join(workspace, fileName);\n const content = readIfExists(filePath, fileName === \"README.md\" ? 6_000 : 4_000);\n if (content !== null) {\n instructionReads.push({ path: fileName, content });\n }\n }\n const packageScripts = readPackageScripts(workspace);\n const projectTypes = detectProjectTypes(workspace);\n\n return {\n workspace,\n isGitRepo,\n gitStatus,\n projectTypes,\n verificationSuggestions: detectVerificationSuggestions(workspace, projectTypes, packageScripts),\n tree: collectTree(workspace),\n instructionReads,\n packageScripts,\n };\n}\n\nexport function buildContextBlock(workspace: string): string {\n const summary = loadWorkspaceSummary(workspace);\n const lines: string[] = [];\n\n lines.push(\"## Workspace Context\");\n lines.push(`Path: ${summary.workspace}`);\n lines.push(`Git repo: ${summary.isGitRepo ? \"yes\" : \"no\"}`);\n if (summary.gitStatus !== null) {\n lines.push(\"Git status:\");\n lines.push(summary.gitStatus || \" clean\");\n }\n lines.push(`Project type: ${summary.projectTypes.length ? summary.projectTypes.join(\", \") : \"unknown\"}`);\n\n if (summary.verificationSuggestions.length > 0) {\n lines.push(\"Verification suggestions:\");\n for (const command of summary.verificationSuggestions) {\n lines.push(` ${command}`);\n }\n }\n\n if (Object.keys(summary.packageScripts).length > 0) {\n lines.push(\"Package scripts:\");\n for (const [name, command] of Object.entries(summary.packageScripts)) {\n lines.push(` ${name}: ${command}`);\n }\n }\n\n if (summary.tree.length > 0) {\n lines.push(\"File tree:\");\n for (const name of summary.tree) {\n lines.push(` ${name}`);\n }\n }\n\n for (const { path, content } of summary.instructionReads) {\n lines.push(`\\n--- ${path} ---`);\n lines.push(content);\n }\n\n return lines.join(\"\\n\");\n}\n","import { existsSync, readdirSync, readFileSync, statSync } from \"node:fs\";\nimport { dirname, join, relative } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { load as parseYaml } from \"js-yaml\";\nimport { discoverIntegrationEntries } from \"../integrations/discovery\";\nimport type {\n LoadedSkillPack,\n SkillPackContext,\n SkillPackFrontmatter,\n} from \"./types\";\n\nexport const SKILL_PACK_TOKEN_BUDGET = 5_800;\nconst TOKEN_BUDGET = SKILL_PACK_TOKEN_BUDGET;\nconst moduleRoot = dirname(fileURLToPath(import.meta.url));\nconst ignoredDirectories = new Set([\n \".git\",\n \".next\",\n \".turbo\",\n \".cache\",\n \"DerivedData\",\n \"build\",\n \"dist\",\n \"node_modules\",\n]);\n\ntype SkillPackLoadWhen = SkillPackFrontmatter[\"loadWhen\"][number];\n\ntype ParsedSkillPackFrontmatter = SkillPackFrontmatter & {\n title: string;\n};\n\ntype SkillPackFile = {\n frontmatter: ParsedSkillPackFrontmatter;\n relativePath: string;\n title: string;\n body: string;\n tokens: number;\n};\n\ntype WorkspaceSignals = {\n files: string[];\n dirs: string[];\n contentFiles: string[];\n go: boolean;\n goHouse: boolean;\n goHuma: boolean;\n ios: boolean;\n swiftData: boolean;\n revenueCatIos: boolean;\n android: boolean;\n room: boolean;\n retrofit: boolean;\n revenueCatAndroid: boolean;\n next: boolean;\n tailwindV4: boolean;\n shadcn: boolean;\n fastlane: boolean;\n};\n\ntype MatchReason = LoadedSkillPack[\"reason\"] | null;\n\nfunction normalize(value: string): string {\n return value.trim().toLowerCase();\n}\n\nfunction normalizeList(values: string[] | undefined): string[] {\n return [...new Set((values ?? []).map(normalize).filter(Boolean))];\n}\n\nfunction estimateTokens(text: string): number {\n return Math.ceil(text.length / 4);\n}\n\nfunction safeExists(path: string): boolean {\n try {\n return existsSync(path);\n } catch {\n return false;\n }\n}\n\nfunction resolveDefaultSkillsRoot(): string {\n const candidates = [\n moduleRoot,\n join(moduleRoot, \"skills\"),\n join(moduleRoot, \"..\", \"src\", \"skills\"),\n join(moduleRoot, \"..\", \"skills\"),\n ];\n for (const candidate of candidates) {\n try {\n if (existsSync(candidate) && statSync(candidate).isDirectory() && collectSkillFiles(candidate).length > 0) return candidate;\n } catch {\n // Try the next candidate.\n }\n }\n return moduleRoot;\n}\n\nfunction safeRead(path: string, maxChars = 250_000): string {\n try {\n const content = readFileSync(path, \"utf8\");\n return content.length > maxChars ? content.slice(0, maxChars) : content;\n } catch {\n return \"\";\n }\n}\n\nfunction readJson(path: string): Record<string, unknown> | null {\n const content = safeRead(path);\n if (!content) return null;\n try {\n const parsed = JSON.parse(content);\n return parsed && typeof parsed === \"object\" && !Array.isArray(parsed)\n ? parsed as Record<string, unknown>\n : null;\n } catch {\n return null;\n }\n}\n\nfunction walkWorkspace(workspace: string, maxEntries = 8_000): { files: string[]; dirs: string[] } {\n const files: string[] = [];\n const dirs: string[] = [];\n\n function walk(current: string): void {\n if (files.length + dirs.length >= maxEntries) return;\n let entries;\n try {\n entries = readdirSync(current, { withFileTypes: true });\n } catch {\n return;\n }\n\n for (const entry of entries) {\n if (files.length + dirs.length >= maxEntries) return;\n if (ignoredDirectories.has(entry.name)) continue;\n const fullPath = join(current, entry.name);\n const relPath = relative(workspace, fullPath).replace(/\\\\/g, \"/\");\n if (entry.isDirectory()) {\n dirs.push(relPath);\n walk(fullPath);\n } else if (entry.isFile()) {\n files.push(relPath);\n }\n }\n }\n\n walk(workspace);\n return { files, dirs };\n}\n\nfunction collectSkillFiles(skillsRoot: string): string[] {\n const files: string[] = [];\n\n function walk(current: string): void {\n let entries;\n try {\n entries = readdirSync(current, { withFileTypes: true });\n } catch {\n return;\n }\n\n for (const entry of entries) {\n if (entry.name.startsWith(\".\")) continue;\n const fullPath = join(current, entry.name);\n if (entry.isDirectory()) {\n walk(fullPath);\n } else if (entry.isFile() && entry.name.endsWith(\".md\")) {\n files.push(fullPath);\n }\n }\n }\n\n walk(skillsRoot);\n return files.sort((a, b) => a.localeCompare(b));\n}\n\nfunction splitFrontmatter(content: string): { rawFrontmatter: string; body: string } | null {\n const match = content.match(/^---\\r?\\n([\\s\\S]*?)\\r?\\n---\\r?\\n?/);\n if (!match?.[1]) return null;\n return {\n rawFrontmatter: match[1].trim(),\n body: content.slice(match[0].length).trim(),\n };\n}\n\nfunction isLoadWhen(value: Record<string, unknown>): value is SkillPackLoadWhen {\n switch (value.kind) {\n case \"always\":\n return true;\n case \"workspace.has\":\n return typeof value.path === \"string\";\n case \"workspace.hasGlob\":\n return typeof value.glob === \"string\";\n case \"workspace.packageJson\":\n return typeof value.dep === \"string\";\n case \"hint.language\":\n case \"hint.framework\":\n case \"hint.stack\":\n return typeof value.value === \"string\";\n default:\n return false;\n }\n}\n\nfunction asObject(value: unknown): Record<string, unknown> | null {\n return value && typeof value === \"object\" && !Array.isArray(value)\n ? value as Record<string, unknown>\n : null;\n}\n\nfunction parseNumber(value: unknown): number | null {\n if (typeof value === \"number\" && Number.isFinite(value)) return value;\n if (typeof value === \"string\" && value.trim() !== \"\") {\n const numeric = Number(value);\n if (Number.isFinite(numeric)) return numeric;\n }\n return null;\n}\n\nfunction titleFromSlug(slug: string): string {\n return slug\n .split(\"/\")\n .at(-1)!\n .split(/[-_]/)\n .filter(Boolean)\n .map((part) => part.charAt(0).toUpperCase() + part.slice(1))\n .join(\" \");\n}\n\nfunction parseFrontmatter(raw: string): ParsedSkillPackFrontmatter | null {\n let parsed: unknown;\n try {\n parsed = parseYaml(raw);\n } catch {\n return null;\n }\n const data = asObject(parsed);\n if (!data) return null;\n\n const parsedLoadWhen = Array.isArray(data.loadWhen)\n ? data.loadWhen\n .map(asObject)\n .filter((condition): condition is SkillPackLoadWhen => condition !== null && isLoadWhen(condition))\n : [];\n const sizeTarget = parseNumber(data.sizeTarget);\n const priority = parseNumber(data.priority);\n if (\n typeof data.slug !== \"string\" ||\n sizeTarget === null ||\n priority === null\n ) {\n return null;\n }\n\n return {\n slug: data.slug,\n title: typeof data.title === \"string\" && data.title.trim() ? data.title : titleFromSlug(data.slug),\n loadWhen: parsedLoadWhen,\n sizeTarget,\n priority,\n };\n}\n\nfunction readSkillPackFile(skillsRoot: string, filePath: string): SkillPackFile | null {\n const parsed = splitFrontmatter(safeRead(filePath));\n if (!parsed) return null;\n const frontmatter = parseFrontmatter(parsed.rawFrontmatter);\n if (!frontmatter) {\n console.warn(`[skill-packs] Failed to parse frontmatter: ${filePath}`);\n return null;\n }\n const relativePath = relative(skillsRoot, filePath).replace(/\\\\/g, \"/\").replace(/\\.md$/i, \"\");\n return {\n frontmatter,\n relativePath,\n title: frontmatter.title,\n body: parsed.body,\n tokens: estimateTokens(parsed.body),\n };\n}\n\nfunction pathMatchesGlob(path: string, glob: string): boolean {\n const escaped = glob\n .replace(/[.+^${}()|[\\]\\\\]/g, \"\\\\$&\")\n .replace(/\\*\\*/g, \"\\0\")\n .replace(/\\*/g, \"[^/]*\")\n .replace(/\\0/g, \".*\");\n return new RegExp(`^${escaped}$`).test(path);\n}\n\nfunction packageJsonHasDependency(workspace: string, dep: string): boolean {\n const parsed = readJson(join(workspace, \"package.json\"));\n if (!parsed) return false;\n for (const key of [\"dependencies\", \"devDependencies\", \"peerDependencies\", \"optionalDependencies\"]) {\n const deps = parsed[key];\n if (deps && typeof deps === \"object\" && !Array.isArray(deps) && dep in deps) return true;\n }\n return false;\n}\n\nfunction fileHas(files: string[], pattern: RegExp): boolean {\n return files.some((file) => pattern.test(file));\n}\n\nfunction hasRootFile(files: string[], name: string): boolean {\n return files.includes(name);\n}\n\nfunction hasRootDir(dirs: string[], pattern: RegExp): boolean {\n return dirs.some((dir) => pattern.test(dir));\n}\n\nfunction selectContentFiles(files: string[]): string[] {\n return files.filter((file) => {\n if (/\\.(?:swift|kt|kts|go|ts|tsx|js|mjs|css|md|toml|xml|json|resolved|sum|mod)$/i.test(file)) return true;\n return file === \"Podfile\" || file.endsWith(\"/Podfile\");\n });\n}\n\nfunction anyContentContains(workspace: string, files: string[], needle: string | RegExp): boolean {\n return files.some((file) => {\n const content = safeRead(join(workspace, file), 120_000);\n return typeof needle === \"string\" ? content.includes(needle) : needle.test(content);\n });\n}\n\nfunction detectWorkspaceSignals(ctx: SkillPackContext): WorkspaceSignals {\n const workspace = ctx.workspace;\n const { files, dirs } = walkWorkspace(workspace);\n const contentFiles = selectContentFiles(files);\n const go = hasRootFile(files, \"go.mod\");\n const pkgMigrations = files.some((file) => /^pkg\\/[^/]+\\/migrations\\//.test(file));\n const goHouse = go && pkgMigrations && anyContentContains(workspace, contentFiles, \"Module.Attach\");\n const goHuma = go && (\n safeRead(join(workspace, \"go.sum\")).includes(\"github.com/danielgtaylor/huma\") ||\n dirs.includes(\"internal/store/gen\") ||\n normalize(ctx.hints.stack ?? \"\") === \"backend-go-huma\" ||\n /artifacts\\/backend-go|backend-go-huma/i.test(ctx.taskHint ?? \"\")\n );\n\n const ios = hasRootFile(files, \"Package.swift\") || hasRootDir(dirs, /(?:^|\\/)[^/]+\\.xcodeproj$/);\n const swiftData = ios && anyContentContains(workspace, contentFiles, \"@Model\");\n const revenueCatIos = ios && (\n anyContentContains(workspace, contentFiles, \"import RevenueCat\") ||\n anyContentContains(workspace, contentFiles, /RevenueCat/i)\n );\n\n const gradleFiles = files.filter((file) => /(?:^|\\/)build\\.gradle(?:\\.kts)?$/.test(file));\n const android = hasRootFile(files, \"build.gradle.kts\") ||\n gradleFiles.some((file) => file.endsWith(\"build.gradle.kts\") || /kotlin/i.test(safeRead(join(workspace, file), 80_000)));\n const libsVersions = safeRead(join(workspace, \"gradle/libs.versions.toml\"), 120_000);\n const room = android && /room/i.test(libsVersions);\n const retrofit = android && anyContentContains(workspace, contentFiles, /import\\s+retrofit2\\b/);\n const revenueCatAndroid = android && anyContentContains(workspace, contentFiles, \"com.revenuecat.purchases\");\n\n const packageJson = safeRead(join(workspace, \"package.json\"), 120_000);\n const next = (hasRootFile(files, \"next.config.js\") || hasRootFile(files, \"next.config.ts\") || hasRootFile(files, \"next.config.mjs\")) &&\n /\"next\"\\s*:/.test(packageJson);\n const tailwindV4 = anyContentContains(workspace, files.filter((file) => file.endsWith(\".css\")), '@import \"tailwindcss\"') ||\n packageJsonHasDependency(workspace, \"@tailwindcss/postcss\");\n const shadcn = hasRootFile(files, \"components.json\") ||\n safeExists(join(workspace, \"components/ui\")) ||\n safeExists(join(workspace, \"src/components/ui\")) ||\n dirs.includes(\"components/ui\") ||\n dirs.includes(\"src/components/ui\");\n const fastlane = hasRootFile(files, \"fastlane/Fastfile\");\n\n return {\n files,\n dirs,\n contentFiles,\n go,\n goHouse,\n goHuma,\n ios,\n swiftData,\n revenueCatIos,\n android,\n room,\n retrofit,\n revenueCatAndroid,\n next,\n tailwindV4,\n shadcn,\n fastlane,\n };\n}\n\nfunction frontmatterConditionReason(\n condition: SkillPackLoadWhen,\n ctx: SkillPackContext,\n signals: WorkspaceSignals,\n): MatchReason {\n const languages = normalizeList(ctx.hints.languages);\n const frameworks = normalizeList(ctx.hints.frameworks);\n const stack = normalize(ctx.hints.stack ?? \"\");\n\n switch (condition.kind) {\n case \"always\":\n return \"always\";\n case \"workspace.has\":\n return safeExists(join(ctx.workspace, condition.path)) ? \"workspace\" : null;\n case \"workspace.hasGlob\":\n return [...signals.files, ...signals.dirs].some((path) => pathMatchesGlob(path, condition.glob)) ? \"workspace\" : null;\n case \"workspace.packageJson\":\n return packageJsonHasDependency(ctx.workspace, condition.dep) ? \"workspace\" : null;\n case \"hint.language\":\n return languages.includes(normalize(condition.value)) ? \"hint\" : null;\n case \"hint.framework\":\n return frameworks.includes(normalize(condition.value)) ? \"hint\" : null;\n case \"hint.stack\":\n return stack === normalize(condition.value) ? \"hint\" : null;\n }\n}\n\nfunction frameworkHintMatches(frameworks: string[], values: string[]): boolean {\n const normalizedValues = values.map(normalize);\n return frameworks.some((framework) => normalizedValues.includes(framework));\n}\n\nfunction languageHintMatches(languages: string[], values: string[]): boolean {\n const normalizedValues = values.map(normalize);\n return languages.some((language) => normalizedValues.includes(language));\n}\n\nfunction stackHintMatches(stack: string, values: string[]): boolean {\n const normalizedValues = values.map(normalize);\n return normalizedValues.includes(stack);\n}\n\nfunction activeStackReason(\n languages: string[],\n frameworks: string[],\n stack: string,\n signals: WorkspaceSignals,\n): MatchReason {\n if (\n languageHintMatches(languages, [\"go\", \"swift\", \"kotlin\", \"typescript\", \"ts\"]) ||\n stackHintMatches(stack, [\n \"backend-go-huma\",\n \"backend-go-house\",\n \"ios\",\n \"macos\",\n \"android\",\n \"landing\",\n \"web\",\n ]) ||\n frameworkHintMatches(frameworks, [\n \"chi-pgx\",\n \"chi\",\n \"pgx\",\n \"huma-sqlc\",\n \"huma\",\n \"sqlc\",\n \"swiftui\",\n \"swiftdata\",\n \"storekit2\",\n \"storekit\",\n \"revenuecat-ios\",\n \"jetpack-compose\",\n \"compose\",\n \"room-hilt\",\n \"room\",\n \"hilt\",\n \"retrofit-okhttp\",\n \"retrofit\",\n \"okhttp\",\n \"revenuecat-android\",\n \"nextjs-app-router\",\n \"nextjs15\",\n \"nextjs\",\n \"next\",\n \"tailwind-v4\",\n \"tailwind\",\n \"shadcn-ui\",\n \"shadcn\",\n ])\n ) {\n return \"hint\";\n }\n return signals.go || signals.ios || signals.android || signals.next ? \"workspace\" : null;\n}\n\nfunction implicitReason(packPath: string, ctx: SkillPackContext, signals: WorkspaceSignals): MatchReason {\n if (packPath.startsWith(\"failure-modes/\")) return \"always\";\n\n const languages = normalizeList(ctx.hints.languages);\n const frameworks = normalizeList(ctx.hints.frameworks);\n const stack = normalize(ctx.hints.stack ?? \"\");\n if (packPath.startsWith(\"domain/\")) return activeStackReason(languages, frameworks, stack, signals);\n\n switch (packPath) {\n case \"lang/go\":\n if (languages.includes(\"go\")) return \"hint\";\n return signals.go ? \"workspace\" : null;\n case \"lang/swift\":\n if (languages.includes(\"swift\")) return \"hint\";\n return signals.ios ? \"workspace\" : null;\n case \"lang/kotlin\":\n if (languages.includes(\"kotlin\")) return \"hint\";\n return signals.android ? \"workspace\" : null;\n case \"lang/typescript\":\n if (languages.includes(\"typescript\") || languages.includes(\"ts\")) return \"hint\";\n return signals.next ? \"workspace\" : null;\n case \"framework/chi-pgx\":\n if (frameworkHintMatches(frameworks, [\"chi-pgx\", \"chi\", \"pgx\"])) return \"hint\";\n return signals.goHouse ? \"workspace\" : null;\n case \"framework/huma-sqlc\":\n if (frameworkHintMatches(frameworks, [\"huma-sqlc\", \"huma\", \"sqlc\"]) || stack === \"backend-go-huma\") return \"hint\";\n return signals.goHuma ? \"workspace\" : null;\n case \"framework/goose-migrations\":\n if (frameworkHintMatches(frameworks, [\"goose\", \"goose-migrations\"])) return \"hint\";\n return signals.go && (signals.files.some((file) => /migrations\\/.*\\.sql$/.test(file)) || anyContentContains(ctx.workspace, signals.contentFiles, \"+goose\")) ? \"workspace\" : null;\n case \"framework/service-tokens\":\n if (frameworkHintMatches(frameworks, [\"service-tokens\", \"service-token\"])) return \"hint\";\n return signals.go && anyContentContains(ctx.workspace, signals.contentFiles, /X-Service-Token|ServiceToken|service token/i) ? \"workspace\" : null;\n case \"framework/swiftui\":\n if (frameworkHintMatches(frameworks, [\"swiftui\"])) return \"hint\";\n return signals.ios ? \"workspace\" : null;\n case \"framework/swiftdata\":\n if (frameworkHintMatches(frameworks, [\"swiftdata\"])) return \"hint\";\n return signals.swiftData ? \"workspace\" : null;\n case \"framework/revenuecat-ios\":\n if (frameworkHintMatches(frameworks, [\"revenuecat-ios\", \"revenuecat\"])) return \"hint\";\n return signals.revenueCatIos ? \"workspace\" : null;\n case \"framework/storekit2\":\n if (frameworkHintMatches(frameworks, [\"storekit2\", \"storekit\"])) return \"hint\";\n return signals.ios && !signals.revenueCatIos ? \"workspace\" : null;\n case \"framework/jetpack-compose\":\n if (frameworkHintMatches(frameworks, [\"jetpack-compose\", \"compose\"]) || languageHintMatches(languages, [\"kotlin\"]) || stackHintMatches(stack, [\"android\"])) return \"hint\";\n return signals.android ? \"workspace\" : null;\n case \"framework/room-hilt\":\n if (frameworkHintMatches(frameworks, [\"room-hilt\", \"room\", \"hilt\"])) return \"hint\";\n return signals.room ? \"workspace\" : null;\n case \"framework/retrofit-okhttp\":\n if (frameworkHintMatches(frameworks, [\"retrofit-okhttp\", \"retrofit\", \"okhttp\"])) return \"hint\";\n return signals.retrofit ? \"workspace\" : null;\n case \"framework/revenuecat-android\":\n if (frameworkHintMatches(frameworks, [\"revenuecat-android\", \"revenuecat\"])) return \"hint\";\n return signals.revenueCatAndroid ? \"workspace\" : null;\n case \"framework/nextjs-app-router\":\n if (frameworkHintMatches(frameworks, [\"nextjs-app-router\", \"nextjs15\", \"nextjs\", \"next\", \"app-router\"])) return \"hint\";\n return signals.next ? \"workspace\" : null;\n case \"framework/tailwind-v4\":\n if (frameworkHintMatches(frameworks, [\"tailwind-v4\", \"tailwind\"])) return \"hint\";\n return signals.tailwindV4 ? \"workspace\" : null;\n case \"framework/shadcn-ui\":\n if (frameworkHintMatches(frameworks, [\"shadcn-ui\", \"shadcn\"])) return \"hint\";\n return signals.shadcn ? \"workspace\" : null;\n case \"platform-ops/fastlane-apple\":\n if (frameworkHintMatches(frameworks, [\"fastlane-apple\"])) return \"hint\";\n return signals.fastlane && (signals.ios || !signals.android) ? \"workspace\" : null;\n case \"platform-ops/fastlane-android\":\n if (frameworkHintMatches(frameworks, [\"fastlane-android\"])) return \"hint\";\n return signals.fastlane && (signals.android || !signals.ios) ? \"workspace\" : null;\n case \"platform-ops/apple-signing\":\n if (frameworkHintMatches(frameworks, [\"apple-signing\"])) return \"hint\";\n return signals.ios ? \"workspace\" : null;\n case \"platform-ops/deploy-go-backend\":\n if (frameworkHintMatches(frameworks, [\"deploy-go-backend\"])) return \"hint\";\n return signals.go ? \"workspace\" : null;\n case \"platform-ops/windows-signing\":\n if (frameworkHintMatches(frameworks, [\"windows-signing\", \"code-signing\"])) return \"hint\";\n return null;\n case \"platform-ops/packaging-cli\":\n if (frameworkHintMatches(frameworks, [\"packaging-cli\", \"homebrew\", \"winget\", \"scoop\"])) return \"hint\";\n return null;\n default:\n return null;\n }\n}\n\nfunction preferredReason(reasons: LoadedSkillPack[\"reason\"][]): LoadedSkillPack[\"reason\"] {\n if (reasons.includes(\"always\")) return \"always\";\n if (reasons.includes(\"hint\")) return \"hint\";\n return \"workspace\";\n}\n\nfunction matchPack(pack: SkillPackFile, ctx: SkillPackContext, signals: WorkspaceSignals): MatchReason {\n const reasons: LoadedSkillPack[\"reason\"][] = [];\n const implicit = implicitReason(pack.relativePath, ctx, signals);\n if (implicit) reasons.push(implicit);\n\n for (const condition of pack.frontmatter.loadWhen) {\n const reason = frontmatterConditionReason(condition, ctx, signals);\n if (reason) reasons.push(reason);\n }\n\n return reasons.length > 0 ? preferredReason(reasons) : null;\n}\n\nfunction compareMatchedPacks(\n a: SkillPackFile & { reason: LoadedSkillPack[\"reason\"] },\n b: SkillPackFile & { reason: LoadedSkillPack[\"reason\"] },\n): number {\n if (a.reason === \"always\" && b.reason !== \"always\") return -1;\n if (b.reason === \"always\" && a.reason !== \"always\") return 1;\n return a.frontmatter.priority - b.frontmatter.priority ||\n a.relativePath.localeCompare(b.relativePath);\n}\n\nfunction enforceBudget(packs: Array<SkillPackFile & { reason: LoadedSkillPack[\"reason\"] }>): Array<SkillPackFile & { reason: LoadedSkillPack[\"reason\"] }> {\n const sorted = [...packs].sort(compareMatchedPacks);\n let total = sorted.reduce((sum, pack) => sum + pack.tokens, 0);\n if (total <= TOKEN_BUDGET) return sorted;\n\n const kept = [...sorted];\n for (const pack of [...kept].sort((a, b) => b.frontmatter.priority - a.frontmatter.priority || b.relativePath.localeCompare(a.relativePath))) {\n if (total <= TOKEN_BUDGET) break;\n if (pack.reason === \"always\" || pack.relativePath.startsWith(\"stack/\")) continue;\n const index = kept.indexOf(pack);\n if (index >= 0) {\n kept.splice(index, 1);\n total -= pack.tokens;\n }\n }\n\n return kept.sort(compareMatchedPacks);\n}\n\nfunction loadSkillPacksFromFiles(ctx: SkillPackContext, skillsRoot: string, files: string[]): LoadedSkillPack[] {\n const normalizedCtx: SkillPackContext = {\n workspace: ctx.workspace,\n hints: {\n ...(ctx.hints.languages ? { languages: normalizeList(ctx.hints.languages) } : {}),\n ...(ctx.hints.frameworks ? { frameworks: normalizeList(ctx.hints.frameworks) } : {}),\n ...(ctx.hints.stack ? { stack: normalize(ctx.hints.stack) } : {}),\n },\n ...(ctx.taskHint ? { taskHint: ctx.taskHint } : {}),\n };\n const signals = detectWorkspaceSignals(normalizedCtx);\n const matched = files\n .map((filePath) => readSkillPackFile(skillsRoot, filePath))\n .filter((pack): pack is SkillPackFile => pack !== null)\n .map((pack) => {\n const reason = matchPack(pack, normalizedCtx, signals);\n return reason ? { ...pack, reason } : null;\n })\n .filter((pack): pack is SkillPackFile & { reason: LoadedSkillPack[\"reason\"] } => pack !== null);\n\n return enforceBudget(matched).map((pack) => ({\n slug: pack.frontmatter.slug,\n title: pack.title,\n sourcePath: join(skillsRoot, `${pack.relativePath}.md`),\n content: pack.body,\n tokens: pack.tokens,\n reason: pack.reason,\n }));\n}\n\nexport function loadSkillPacksFromRoot(ctx: SkillPackContext, skillsRoot: string): LoadedSkillPack[] {\n if (!safeExists(skillsRoot)) return [];\n try {\n const stats = statSync(skillsRoot);\n if (!stats.isDirectory()) return [];\n } catch {\n return [];\n }\n\n return loadSkillPacksFromFiles(ctx, skillsRoot, collectSkillFiles(skillsRoot));\n}\n\nfunction loadSkillPacksFromPath(ctx: SkillPackContext, path: string): LoadedSkillPack[] {\n try {\n const stats = statSync(path);\n if (stats.isDirectory()) return loadSkillPacksFromRoot(ctx, path);\n if (stats.isFile() && path.toLowerCase().endsWith(\".md\")) {\n return loadSkillPacksFromFiles(ctx, dirname(path), [path]);\n }\n } catch {\n return [];\n }\n return [];\n}\n\nfunction loadIntegrationSkillPacks(ctx: SkillPackContext): LoadedSkillPack[] {\n return discoverIntegrationEntries(\"skills\")\n .flatMap((entry) => loadSkillPacksFromPath(ctx, entry.path));\n}\n\nfunction mergeSkillPacks(bundled: LoadedSkillPack[], discovered: LoadedSkillPack[]): LoadedSkillPack[] {\n const seen = new Set(bundled.map((pack) => pack.slug));\n const merged = [...bundled];\n for (const pack of discovered) {\n if (seen.has(pack.slug)) continue;\n seen.add(pack.slug);\n merged.push(pack);\n }\n return merged;\n}\n\nexport function loadSkillPacks(ctx: SkillPackContext): LoadedSkillPack[] {\n const bundled = loadSkillPacksFromRoot(ctx, resolveDefaultSkillsRoot());\n return mergeSkillPacks(bundled, loadIntegrationSkillPacks(ctx));\n}\n","import { existsSync, readdirSync, statSync } from \"node:fs\";\nimport { basename, dirname, join } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { envValue } from \"../config/envCompat\";\n\nexport type IntegrationKind = \"skills\" | \"suites\" | \"golden\" | \"validators\";\n\nexport interface IntegrationEntry {\n integration: string;\n kind: IntegrationKind;\n path: string;\n}\n\ntype EnvLike = Record<string, string | undefined>;\n\ninterface DiscoverIntegrationEntriesOptions {\n env?: EnvLike;\n root?: string;\n}\n\ntype DirectoryEntry = {\n name: string;\n isDirectory(): boolean;\n isFile(): boolean;\n};\n\nconst moduleRoot = dirname(fileURLToPath(import.meta.url));\nlet defaultIntegrationsRoot: string | null = null;\n\nfunction safeIsDirectory(path: string): boolean {\n try {\n return existsSync(path) && statSync(path).isDirectory();\n } catch {\n return false;\n }\n}\n\nfunction safeReadDirectory(path: string): DirectoryEntry[] {\n try {\n return readdirSync(path, { withFileTypes: true }) as DirectoryEntry[];\n } catch {\n return [];\n }\n}\n\nfunction hasMarkdownFile(root: string): boolean {\n const entries = safeReadDirectory(root);\n for (const entry of entries) {\n const path = join(root, entry.name);\n if (entry.isFile() && entry.name.endsWith(\".md\")) return true;\n if (entry.isDirectory() && hasMarkdownFile(path)) return true;\n }\n return false;\n}\n\nfunction resolveDefaultSkillsRoot(): string {\n const candidates = [\n moduleRoot,\n join(moduleRoot, \"skills\"),\n join(moduleRoot, \"..\", \"src\", \"skills\"),\n join(moduleRoot, \"..\", \"skills\"),\n ];\n\n for (const candidate of candidates) {\n if (safeIsDirectory(candidate) && hasMarkdownFile(candidate)) return candidate;\n }\n\n return join(moduleRoot, \"..\", \"skills\");\n}\n\nfunction packageRootFromSkillsRoot(skillsRoot: string): string {\n const parent = dirname(skillsRoot);\n const parentName = basename(parent);\n if (parentName === \"src\" || parentName === \"dist\") return dirname(parent);\n return parent;\n}\n\nexport function integrationsRoot(env: EnvLike = process.env): string {\n const override = envValue(env, \"TANYA_INTEGRATIONS_DIR\").trim();\n if (override) return override;\n defaultIntegrationsRoot ??= join(packageRootFromSkillsRoot(resolveDefaultSkillsRoot()), \"integrations\");\n return defaultIntegrationsRoot;\n}\n\nexport function discoverIntegrationEntries(\n kind: IntegrationKind,\n opts: DiscoverIntegrationEntriesOptions = {},\n): IntegrationEntry[] {\n const root = opts.root ?? integrationsRoot(opts.env);\n if (!safeIsDirectory(root)) return [];\n\n const entries: IntegrationEntry[] = [];\n const integrations = safeReadDirectory(root)\n .filter((entry) => entry.isDirectory())\n .sort((a, b) => a.name.localeCompare(b.name));\n\n for (const integration of integrations) {\n const kindRoot = join(root, integration.name, kind);\n if (!safeIsDirectory(kindRoot)) continue;\n\n const discovered = safeReadDirectory(kindRoot)\n .filter((entry) => entry.isDirectory() || entry.isFile())\n .sort((a, b) => a.name.localeCompare(b.name));\n\n for (const entry of discovered) {\n entries.push({\n integration: integration.name,\n kind,\n path: join(kindRoot, entry.name),\n });\n }\n }\n\n return entries;\n}\n","import type { LoadedSkillPack } from \"./types\";\nimport { SKILL_PACK_TOKEN_BUDGET } from \"./load\";\n\nexport function formatSkillPackSummary(packs: LoadedSkillPack[]): string {\n const totalTokens = packs.reduce((sum, pack) => sum + pack.tokens, 0);\n const lines = [\n `Skill packs loaded: ${packs.length}`,\n \"| slug | source | reason | tokens |\",\n \"|------|--------|--------|--------|\",\n ...packs.map((pack) => `| ${pack.slug} | ${pack.sourcePath} | ${pack.reason} | ${pack.tokens} |`),\n `Total pack tokens: ${totalTokens} / ${SKILL_PACK_TOKEN_BUDGET}`,\n ];\n return lines.join(\"\\n\");\n}\n","import { existsSync, readFileSync } from \"node:fs\";\nimport { basename, join } from \"node:path\";\nimport { envValue } from \"../config/envCompat\";\nimport { buildArtifactIndexBlock, buildContextBlock, buildExportMap } from \"../context/loader\";\nimport { readRepoMap } from \"../context/repoMap\";\nimport type { RepoMapFile } from \"../context/repoMapSchema\";\nimport { buildRunContextBlock, type TanyaRunContext } from \"../context/runContext\";\nimport { loadSkillPacks, type LoadedSkillPack } from \"../skills\";\n\nexport type BuildSystemPromptOptions = {\n lite?: boolean;\n contextWindow?: number;\n promptBudgetRatio?: number;\n onPromptBudgetExceeded?: (event: PromptBudgetExceeded) => void;\n onRepoMapTokens?: (tokens: number) => void;\n};\n\nexport type PromptBudgetExceeded = {\n droppedSections: string[];\n totalTokens: number;\n cap: number;\n};\n\nfunction readProjectInstructions(workspace: string): string {\n const path = join(workspace, \".tania\", \"INSTRUCTIONS.md\");\n if (!existsSync(path)) return \"\";\n try {\n const content = readFileSync(path, \"utf8\").trim();\n return content ? `\\n## Project Instructions\\n${content}` : \"\";\n } catch {\n return \"\";\n }\n}\n\nexport function loadPromptSkillPacks(workspace: string, runContext?: TanyaRunContext, taskHint = \"\"): LoadedSkillPack[] {\n return loadSkillPacks({\n workspace,\n hints: {\n ...(runContext?.languages ? { languages: runContext.languages } : {}),\n ...(runContext?.frameworks ? { frameworks: runContext.frameworks } : {}),\n ...(runContext?.stack ? { stack: runContext.stack } : {}),\n },\n ...(taskHint ? { taskHint } : {}),\n });\n}\n\nexport function buildSkillPackBlock(packs: LoadedSkillPack[]): string {\n if (packs.length === 0) return \"\";\n return [\n `## Loaded skill packs (${packs.length})`,\n ...packs.map((pack) => `## Skill: ${pack.title}\\n${pack.content}`),\n ].join(\"\\n\\n\");\n}\n\nexport function selectLiteSkillPacks(packs: LoadedSkillPack[], taskHint = \"\"): LoadedSkillPack[] {\n const terms = normalizeLiteTerms(taskHint);\n return packs.filter((pack) => {\n if (pack.slug.startsWith(\"failure-modes/\")) return true;\n if (!pack.slug.startsWith(\"domain/\")) return true;\n return domainPackMatchesTask(pack.slug, terms);\n });\n}\n\nfunction normalizeLiteTerms(text: string): Set<string> {\n return new Set(text.toLowerCase().match(/[a-z0-9+-]{3,}/g) ?? []);\n}\n\nfunction domainPackMatchesTask(slug: string, terms: Set<string>): boolean {\n const domain = slug.replace(/^domain\\//, \"\");\n const aliases: Record<string, string[]> = {\n \"api-contract\": [\"api\", \"contract\", \"route\", \"endpoint\", \"openapi\"],\n \"auth-email-password\": [\"email\", \"password\", \"login\", \"auth\"],\n \"auth-jwt\": [\"auth\", \"jwt\", \"token\", \"session\"],\n \"deep-links\": [\"deep\", \"link\", \"deeplink\", \"universal\"],\n lgpd: [\"lgpd\", \"privacy\", \"pii\", \"gdpr\"],\n \"push-notifications\": [\"push\", \"notification\", \"fcm\", \"apns\"],\n revenuecat: [\"revenuecat\", \"subscription\", \"paywall\", \"purchase\"],\n \"sign-in-apple\": [\"apple\", \"signin\", \"sign\", \"oauth\"],\n \"sign-in-google\": [\"google\", \"signin\", \"sign\", \"oauth\"],\n \"splash-icon\": [\"splash\", \"icon\", \"launcher\", \"appicon\"],\n stripe: [\"stripe\", \"billing\", \"payment\", \"checkout\"],\n };\n const candidates = [\n ...domain.split(/[-/]+/),\n ...(aliases[domain] ?? []),\n ];\n return candidates.some((term) => terms.has(term));\n}\n\nfunction hasArtifactToolActivity(runContext?: TanyaRunContext): boolean {\n const metadata = runContext?.metadata ?? {};\n const direct = metadata.artifactsRead;\n const created = metadata.artifactsCreated;\n return (Array.isArray(direct) && direct.length > 0) ||\n (Array.isArray(created) && created.length > 0);\n}\n\nfunction liteHistoryBlock(historyBlock?: string): string {\n if (!historyBlock?.trim()) return \"\";\n const lines = historyBlock.split(/\\r?\\n/).filter((line) => line.trim());\n const header = lines.find((line) => line.startsWith(\"## \")) ?? \"## Recent task history\";\n const bullets = lines.filter((line) => line.trim().startsWith(\"- \"));\n const latest = bullets.at(-1);\n return latest ? [header, latest].join(\"\\n\") : historyBlock;\n}\n\nfunction baseInstructionLines(lite: boolean): string[] {\n if (lite) {\n return [\n \"You are Tanya, a live CLI coding and productivity agent.\",\n \"Be direct, practical, and transparent about tool use.\",\n \"Use tools when you need current workspace context or need to modify/verify files.\",\n \"Read or search before editing existing files. Do not invent files or APIs without checking context first.\",\n \"Prefer search_replace for targeted single-location edits; use apply_patch for multi-hunk edits; use write_file only for new files or whole-file replacement.\",\n \"When reusable artifacts are listed in caller context or pre-read artifact files, follow those patterns before implementing related code.\",\n \"Run caller-requested verification commands exactly and trust exit code 0 as passed.\",\n \"Use non-interactive, bounded shell commands only; pipe build commands only with `set -o pipefail`.\",\n \"If pip/npm installs, curl, or live network calls fail twice, stop retrying the network path. Scaffold a local mock fallback so the task can complete, and document mock versus live behavior in the README.\",\n \"Never print or store secrets. Do not create or keep backup files such as .orig, .bak, .backup, or .tmp.\",\n \"Final coding reports must list changed files, artifact reuse or none, artifact creation or none, verification lines, git head/root when relevant, and blockers.\",\n ];\n }\n\n return [\n \"You are Tanya, a live CLI coding and productivity agent.\",\n \"Be direct, practical, and transparent about tool use.\",\n \"Use tools when you need current workspace context or need to modify/verify files.\",\n \"For broad coding tasks, setup tasks, or tasks that mention artifacts/contracts/brand/API/deploy/store/mobile platforms, start by calling build_task_brief or inspect_project_context before editing.\",\n \"Before creating common app, backend, mobile, deploy, store, auth, billing, onboarding, splash, icon, or testing patterns from scratch, call find_reusable_artifacts and read any relevant artifact it returns.\",\n \"If pre-read artifact files appear in the system prompt under 'Pre-read artifact files', treat them as the authoritative patterns for this task and follow them before editing any code.\",\n \"Prefer search_replace for targeted single-location edits to existing files — it is more reliable than apply_patch because it matches exact strings without diff context lines.\",\n \"Use apply_patch when you need to edit multiple non-adjacent hunks in the same file in one call.\",\n \"Use write_file only for new files or when you need to replace the entire file content. If you've already created or modified a file in this session, prefer search_replace or apply_patch over re-running write_file with the whole file — full rewrites discard prior surgical fixes and lose accumulated diffs across retries.\",\n \"Test files in particular accumulate iterative fixes (compile errors, import paths, mock arity, type narrowing). When tests fail, fix the failing assertion or import surgically with search_replace; do not rewrite the entire test file unless its scope has fundamentally changed.\",\n \"If search_replace fails with 'not found', re-read the relevant lines of the file first and adjust old_string to match exactly including whitespace and indentation.\",\n \"If apply_patch fails on an existing file, switch to search_replace with the specific lines that need changing instead of retrying the patch.\",\n \"Use copy_file or copy_dir for binary assets, templates, .xcassets, Android resources, and materialized artifacts.\",\n \"For app icons and raster assets, create or adapt an SVG/vector source when useful, render it with render_svg_to_png, resize with resize_image, and generate Apple AppIcon.appiconset assets with create_apple_app_icon_set.\",\n \"When an app icon task asks for both iOS and macOS sizes, call create_apple_app_icon_set with platforms [\\\"ios\\\", \\\"macos\\\"] even if the current workspace is an ios/ folder.\",\n \"For Apple app icon tasks, always run an explicit programmatic Contents.json parse command that confirms iPhone, iPad, ios-marketing, and mac idioms plus required slot counts. The validate_apple_app_icon_set tool is helpful but does not replace this explicit parse command.\",\n \"For Apple app icon tasks, run xcodebuild directly with a concrete available destination or generic simulator destination. Do not pipe xcodebuild through tail/grep unless the shell command uses `set -o pipefail`.\",\n \"For Apple build verification in any task, prefer `xcodebuild build -scheme <scheme> -destination 'generic/platform=iOS Simulator'` unless the caller explicitly requires a named simulator. If a named simulator returns exit 70 or cannot resolve the destination, do not retry that same destination; switch to the generic simulator destination or a different listed device.\",\n \"For Apple build verification in any task, prefer direct xcodebuild commands. If you must pipe xcodebuild output, use `set -o pipefail` in the same shell command and report the full command.\",\n \"For Apple Fastlane setup tasks, include lanes for build and test or lint verification when the caller asks for setup/build/test lanes, and verify at least one non-release lane locally.\",\n \"For Apple release-automation Fastlane tasks, do not repeatedly run simulator test lanes just to validate release lanes; use fastlane lanes, ruby -c fastlane/Fastfile, and a bounded build/archive lane when available, then report simulator test hangs as manual environment checks.\",\n \"For Apple Fastlane verification, trust a Fastlane lane command that exits 0. Do not run grep-only probes like `fastlane ios build | grep ...` as pass/fail verification, because a successful lane may not print the searched token.\",\n \"For Apple Fastlane setup tasks, treat `fastlane/README.md` and `fastlane/report.xml` as generated noise unless the caller explicitly asks for them. Delete them before the final report and do not include them in the required commit.\",\n \"For Apple setup tasks, do not edit `.gitignore` unless the task explicitly requires ignore-rule changes or a generated file cannot otherwise be cleaned up before the final report.\",\n \"For iOS typography tasks, use provided font files when they exist in the workspace. If Playfair Display/Roboto or other brand fonts are named but no .ttf/.otf assets are present, create local typography tokens with system serif/sans fallbacks and do not leave manual font-installation steps as blockers.\",\n \"For iOS splash tasks, use create_ios_splash when available before manually editing the splash. Follow the caller's visual contract exactly: if it asks for solid color, fade-only, no text, or icon-only, do not add gradients, pulse, text, taglines, or extra layout.\",\n \"For Android launcher icons, use create_android_launcher_icon_set against the app module res directory and then verify Manifest launcher icon references if the task asks for Android assets.\",\n \"For Android foundation tasks that ask for Room, Navigation Compose, Material 3 theme, and base composables, use create_android_foundation when available after reading any provided foundation artifacts. Do not hand-write the full foundation from scratch before using that tool; adapt the generated files to the app and then run Gradle build/ktlint verification.\",\n \"For Android setup tasks that do not ask for icons or launcher assets, do not generate launcher icons or change manifest icon references only to satisfy an optional validator warning; report icon gaps as outside scope.\",\n \"For Android coding tasks, do not create or modify local.properties. Use existing ANDROID_HOME or ANDROID_SDK_ROOT environment values for verification, and report a blocker if no SDK is available.\",\n \"For Android coding tasks with a local Gradle wrapper, verify with direct Gradle commands such as `./gradlew assembleDebug --no-daemon` and `./gradlew ktlintCheck --no-daemon` when ktlint is configured. Do not leave these as manual checks when `./gradlew` is present. If ktlintCheck fails on files you changed, prefer running `./gradlew ktlintFormat --no-daemon` once, then rerun ktlintCheck, before manually guessing formatting fixes. Do not add or weaken .editorconfig/ktlint rule suppressions unless the caller explicitly asks for style-rule changes.\",\n \"After any formatter or code-generation command, rerun git status and include every in-scope file changed by that command in your final report and required commit.\",\n \"Do not pipe Gradle through tail/head/grep unless the same shell command starts with `set -o pipefail`, and never use `; echo EXIT_CODE=$?` as verification. Do not change the Gradle wrapper or Android Gradle Plugin version unless the task explicitly requires it.\",\n \"Use validate_apple_app_icon_set, validate_android_launcher_icon_set, validate_android_project_config, validate_apple_project_files, validate_fastlane_config, validate_prisma_schema, validate_api_contract_routes, or scan_secrets when those match the task output.\",\n \"Read or search before editing existing files. Do not invent files or APIs without checking context first.\",\n \"When reusable artifacts are provided, read the relevant artifact before implementing. If the caller says to follow a pattern exactly, preserve the pattern's control flow and only adapt names/assets required by the task.\",\n \"When running commands, use non-interactive commands only. Use run_shell only for bounded verification snippets that require shell features.\",\n \"If pip/npm installs, curl, or live network calls fail twice, stop retrying the network path. Scaffold a local mock fallback so the task can complete, and document mock versus live behavior in the README.\",\n \"When the caller lists explicit verification commands, run those exact commands. Do not replace `npm install` with node_modules/package-lock probes or other equivalent-looking checks.\",\n \"For build and test commands, trust a tool result with exit code 0 as passed; do not rerun the same successful command only to inspect more output.\",\n \"If verification succeeds only after changing a destination, device, path, or tool target from an unavailable value to an available one, update any generated scripts, lanes, or config files to use the verified working value before committing or reporting completion.\",\n \"Before git add or git commit in a nested workspace, run `git rev-parse --show-toplevel`. If the git root differs from the current workspace, either use `git -C <git-root> ...` with repo-relative paths or stay in the workspace with workspace-relative paths; never mix repo-relative paths with a nested cwd.\",\n \"If the caller requires a commit message format, copy that format exactly, including required prefixes and verbs such as Add, Fix, or Improve.\",\n \"If the caller requires a commit, do not leave in-scope task changes uncommitted. Run git status before the final report and either commit the remaining in-scope changes or explain why they are out of scope.\",\n \"If the caller requires a commit and you changed files, do not stop after duplicate verification or status checks. Call commit_platform_changes with `files` and `message` to stage the in-scope files, create one final task commit, verify HEAD changed, then produce the final report. If you already committed and then repair the implementation, amend the existing task commit instead of creating a second task commit.\",\n \"Never print or store secrets. If a key exists, refer only to its presence.\",\n \"Do not create or keep backup files such as .orig, .bak, .backup, or .tmp. Before committing or reporting completion, check and remove backup/temp files you created.\",\n \"Final reports for coding tasks must include one plain `Modified: <path>` line for every changed file, either `Artifact reused: <artifact-path> -> <target-path>` or `Artifact reused: none`, either `Artifact created: <artifact-path> -> reusable artifact` or `Artifact created: none`, verification run/pass-fail lines, git root/head lines when a commit was required, and blockers.\",\n \"Artifact provenance must be precise: only list target files that were directly adapted from that artifact. Do not map release, setup, or manual checklist artifacts to unrelated source files, icons, or formatter-only changes.\",\n \"If a coding setup task is already satisfied and no files need changes, include `Verification-only: existing setup satisfied` and still list verification commands.\",\n ];\n}\n\nfunction estimatePromptTokens(text: string): number {\n return Math.ceil(text.length / 4);\n}\n\nfunction configuredRepoMapPromptBudget(): number {\n const parsed = Number(envValue(process.env, \"TANYA_REPO_MAP_PROMPT_BUDGET\"));\n return Number.isFinite(parsed) && parsed > 0 ? Math.floor(parsed) : 1_000;\n}\n\nfunction collectRunContextPaths(runContext?: TanyaRunContext): Set<string> {\n const paths = new Set<string>();\n const metadata = runContext?.metadata ?? {};\n for (const key of [\"changedFiles\", \"recentlyEditedFiles\", \"filesTouched\", \"artifactsRead\"]) {\n const value = metadata[key];\n if (!Array.isArray(value)) continue;\n for (const entry of value) {\n if (typeof entry === \"string\" && entry.trim()) paths.add(entry.replace(/\\\\/g, \"/\"));\n }\n }\n return paths;\n}\n\nfunction repoMapEntryScore(file: RepoMapFile, terms: Set<string>, recentPaths: Set<string>): number {\n const lowerPath = file.path.toLowerCase();\n const lowerBase = basename(file.path).toLowerCase();\n let score = 0;\n for (const term of terms) {\n if (lowerBase.includes(term)) score += 25;\n else if (lowerPath.includes(term)) score += 15;\n if (file.symbols.some((symbol) => symbol.name.toLowerCase().includes(term))) score += 10;\n if (file.exports.some((name) => name.toLowerCase().includes(term))) score += 8;\n }\n for (const recent of recentPaths) {\n const normalized = recent.toLowerCase();\n if (normalized === lowerPath || lowerPath.endsWith(`/${normalized}`) || normalized.endsWith(`/${lowerPath}`)) score += 30;\n }\n if (/^(src\\/)?(index|main)\\.(ts|tsx|js|jsx|py|go|swift|kt)$/.test(lowerPath)) score += 12;\n if (lowerPath === \"package.json\" || lowerPath.endsWith(\"/package.json\")) score += 10;\n score += Math.min(file.symbols.length, 5);\n return score;\n}\n\nfunction formatRepoMapEntry(file: RepoMapFile): string {\n const symbols = file.symbols\n .slice(0, 8)\n .map((symbol) => `${symbol.kind}:${symbol.name}@${symbol.line}`)\n .join(\", \");\n const imports = file.imports.slice(0, 5).map((entry) => entry.from).join(\", \");\n const exports = file.exports.slice(0, 8).join(\", \");\n const parts = [\n `symbols=${symbols || \"none\"}`,\n ...(exports ? [`exports=${exports}`] : []),\n ...(imports ? [`imports=${imports}`] : []),\n ];\n return `- ${file.path} [${file.lang}/${file.parser}] ${parts.join(\"; \")}`;\n}\n\nfunction buildRepoMapBlock(workspace: string, runContext: TanyaRunContext | undefined, taskHint: string, tokenBudget: number): string {\n if (tokenBudget <= 0) return \"\";\n const map = readRepoMap(workspace);\n if (!map || map.files.length === 0) return \"\";\n const terms = normalizeLiteTerms(taskHint);\n const recentPaths = collectRunContextPaths(runContext);\n const ranked = [...map.files]\n .map((file) => ({ file, score: repoMapEntryScore(file, terms, recentPaths) }))\n .sort((a, b) => b.score - a.score || a.file.path.localeCompare(b.file.path))\n .map((entry) => entry.file);\n const lines = [\n \"## Repo Map (advisory)\",\n \"Generated structure only; read files before editing. Use inspect_repo_map for more.\",\n ];\n for (const file of ranked) {\n const next = [...lines, formatRepoMapEntry(file)].join(\"\\n\");\n if (estimatePromptTokens(next) > tokenBudget) break;\n lines.push(formatRepoMapEntry(file));\n }\n return lines.length > 2 ? lines.join(\"\\n\") : \"\";\n}\n\nfunction dropPackCategory(packs: LoadedSkillPack[], category: string): LoadedSkillPack[] {\n switch (category) {\n case \"failure-mode packs\":\n return packs.filter((pack) => !pack.slug.startsWith(\"failure-modes/\"));\n case \"domain packs\":\n return packs.filter((pack) => !pack.slug.startsWith(\"domain/\"));\n case \"language packs\":\n return packs.filter((pack) => !pack.slug.startsWith(\"lang/\"));\n case \"framework packs\":\n return packs.filter((pack) => !pack.slug.startsWith(\"framework/\"));\n default:\n return packs;\n }\n}\n\nexport function buildSystemPrompt(\n workspace: string,\n runContext?: TanyaRunContext,\n historyBlock?: string,\n taskHint = \"\",\n options: BuildSystemPromptOptions = {},\n): string {\n const lite = options.lite === true;\n const callerContext = buildRunContextBlock(runContext);\n const projectInstructions = readProjectInstructions(workspace);\n const exportMap = buildExportMap(workspace);\n let artifactIndex = lite && !hasArtifactToolActivity(runContext)\n ? \"\"\n : buildArtifactIndexBlock(workspace, taskHint);\n let repoMapBlock = lite\n ? buildRepoMapBlock(workspace, runContext, taskHint, configuredRepoMapPromptBudget())\n : \"\";\n const loadedPacks = loadPromptSkillPacks(workspace, runContext, taskHint);\n let promptPacks = lite ? selectLiteSkillPacks(loadedPacks, taskHint) : loadedPacks;\n const recentHistoryBlock = lite ? liteHistoryBlock(historyBlock) : historyBlock ?? \"\";\n const render = () => [\n ...baseInstructionLines(lite),\n \"\",\n exportMap,\n repoMapBlock,\n artifactIndex,\n buildSkillPackBlock(promptPacks),\n recentHistoryBlock,\n buildContextBlock(workspace),\n projectInstructions,\n callerContext ? `\\n${callerContext}` : \"\",\n ].join(\"\\n\");\n let prompt = render();\n const contextWindow = options.contextWindow;\n const ratio = options.promptBudgetRatio ?? 0.25;\n if (contextWindow && Number.isFinite(contextWindow) && contextWindow > 0 && ratio > 0) {\n const cap = Math.floor(contextWindow * ratio);\n const initialTokens = estimatePromptTokens(prompt);\n const droppedSections: string[] = [];\n for (const section of [\"repo-map\", \"failure-mode packs\", \"artifact index\", \"domain packs\", \"language packs\", \"framework packs\"]) {\n if (estimatePromptTokens(prompt) <= cap) break;\n if (section === \"repo-map\") {\n if (!repoMapBlock) continue;\n repoMapBlock = \"\";\n } else if (section === \"artifact index\") {\n if (!artifactIndex) continue;\n artifactIndex = \"\";\n } else {\n const nextPacks = dropPackCategory(promptPacks, section);\n if (nextPacks.length === promptPacks.length) continue;\n promptPacks = nextPacks;\n }\n droppedSections.push(section);\n prompt = render();\n }\n if (droppedSections.length > 0) {\n options.onPromptBudgetExceeded?.({ droppedSections, totalTokens: initialTokens, cap });\n }\n }\n options.onRepoMapTokens?.(estimatePromptTokens(repoMapBlock));\n return prompt;\n}\n","import type { EventSink, TanyaEvent } from \"./types\";\n\nexport function createSubAgentSink(parent: EventSink, subRunId: string): EventSink {\n return (event: TanyaEvent) => parent({ ...event, subRunId });\n}\n","import type { SchemaFlattenWarning } from \"./schemaFlatten\";\nimport type { ProviderThrottleEvent } from \"./retry\";\n\nexport interface ProviderErrorOptions {\n provider: string;\n rawMessage: string;\n status?: number;\n cause?: unknown;\n}\n\nexport class ProviderError extends Error {\n readonly provider: string;\n readonly rawMessage: string;\n readonly status?: number;\n\n constructor(message: string, options: ProviderErrorOptions) {\n super(message, options.cause === undefined ? undefined : { cause: options.cause });\n this.name = \"ProviderError\";\n this.provider = options.provider;\n this.rawMessage = options.rawMessage;\n if (options.status !== undefined) this.status = options.status;\n }\n}\n\nexport class ContextWindowExceededError extends ProviderError {\n constructor(options: ProviderErrorOptions) {\n const statusText = options.status === undefined ? \"\" : ` HTTP ${options.status}`;\n super(\n `Provider ${options.provider} exceeded the context window${statusText}: ${options.rawMessage.slice(0, 500)}`,\n options,\n );\n this.name = \"ContextWindowExceededError\";\n }\n}\n\nexport function isContextWindowExceededError(error: unknown): error is ContextWindowExceededError {\n return error instanceof ContextWindowExceededError ||\n Boolean(error && typeof error === \"object\" && (error as { name?: unknown }).name === \"ContextWindowExceededError\");\n}\n\nexport type ChatRole = \"system\" | \"user\" | \"assistant\" | \"tool\";\n\nexport interface ChatMessage {\n role: ChatRole;\n content: string | null;\n reasoning_content?: string;\n tool_call_id?: string;\n tool_calls?: ToolCall[];\n}\n\nexport interface ToolCall {\n id: string;\n type: \"function\";\n function: {\n name: string;\n arguments: string;\n };\n}\n\nexport interface ToolDefinition {\n type: \"function\";\n function: {\n name: string;\n description: string;\n parameters: {\n type: \"object\";\n properties: Record<string, unknown>;\n required?: string[];\n additionalProperties?: boolean;\n };\n };\n}\n\nexport interface ChatDelta {\n content?: string;\n reasoningContent?: string;\n toolCalls?: unknown[];\n finishReason?: string | null;\n usage?: { promptTokens: number; completionTokens: number; reasoningTokens?: number };\n schemaWarnings?: SchemaFlattenWarning[];\n}\n\nexport interface ChatRequest {\n messages: ChatMessage[];\n tools?: ToolDefinition[];\n temperature?: number;\n topP?: number;\n maxTokens?: number;\n onProviderThrottle?: (event: ProviderThrottleEvent) => void | Promise<void>;\n}\n\nexport interface ChatProvider {\n id: string;\n model: string;\n contextWindow?: number;\n reasoning?: boolean;\n roundTripReasoning?: boolean;\n streamChat(input: ChatRequest): AsyncGenerator<ChatDelta>;\n}\n","import type { ToolCall } from \"./types\";\n\nexport type ToolCallParseWarning = {\n reason: string;\n toolCallId?: string;\n tool?: string;\n raw?: unknown;\n};\n\nexport type ToolCallParseFailure = {\n reason: string;\n toolCall: ToolCall;\n raw?: unknown;\n};\n\nexport type ToolCallParseResult = {\n toolCalls: ToolCall[];\n warnings: ToolCallParseWarning[];\n failures: ToolCallParseFailure[];\n};\n\nexport type ToolArgumentsParseResult =\n | { ok: true; input: unknown }\n | { ok: false; reason: string; rawArguments: string };\n\ntype RawToolCallRecord = Record<string, unknown>;\n\nexport const TOOL_CALL_CORRECTION_LIMIT = 3;\n\nexport function malformedToolCallCorrectionMessage(reason: string): string {\n return `[your last tool call was malformed: ${reason}. Try again with valid JSON.]`;\n}\n\nexport function parseProviderToolCalls(rawToolCalls: unknown[], options: { turn?: number } = {}): ToolCallParseResult {\n const warnings: ToolCallParseWarning[] = [];\n const failures: ToolCallParseFailure[] = [];\n const toolCalls: ToolCall[] = [];\n\n rawToolCalls.forEach((raw, index) => {\n const parsed = parseOneToolCall(raw, index, options.turn ?? 0);\n warnings.push(...parsed.warnings);\n if (parsed.failure) {\n failures.push(parsed.failure);\n return;\n }\n toolCalls.push(parsed.toolCall);\n });\n\n return { toolCalls, warnings, failures };\n}\n\nexport function parseToolArguments(rawArguments: unknown): ToolArgumentsParseResult {\n if (rawArguments === undefined || rawArguments === null || rawArguments === \"\") {\n return { ok: true, input: {} };\n }\n if (typeof rawArguments === \"object\") {\n return { ok: true, input: rawArguments };\n }\n if (typeof rawArguments !== \"string\") {\n return {\n ok: false,\n reason: `tool arguments must be JSON object or string, got ${typeof rawArguments}`,\n rawArguments: String(rawArguments),\n };\n }\n if (!rawArguments.trim()) return { ok: true, input: {} };\n try {\n return { ok: true, input: JSON.parse(rawArguments) };\n } catch {\n const preview = previewRawToolArguments(rawArguments);\n return {\n ok: false,\n reason: `malformed JSON arguments: ${preview}`,\n rawArguments: preview,\n };\n }\n}\n\nfunction parseOneToolCall(raw: unknown, index: number, turn: number): {\n toolCall: ToolCall;\n warnings: ToolCallParseWarning[];\n failure?: ToolCallParseFailure;\n} {\n const warnings: ToolCallParseWarning[] = [];\n if (!isRecord(raw)) {\n const toolCall = fallbackToolCall(turn, index, \"__malformed_tool_call__\", \"\");\n return {\n toolCall,\n warnings,\n failure: { reason: `tool call must be an object, got ${typeof raw}`, toolCall, raw },\n };\n }\n\n const idValue = typeof raw.id === \"string\" && raw.id.trim() ? raw.id : undefined;\n const id = idValue ?? `call_${turn}_${index}`;\n if (!idValue) {\n warnings.push({\n reason: `missing tool call id; synthesized ${id}`,\n toolCallId: id,\n raw,\n });\n }\n\n const functionRecord = isRecord(raw.function) ? raw.function : raw;\n if (!isRecord(raw.function)) {\n warnings.push({\n reason: \"missing function wrapper; accepted top-level name/arguments\",\n toolCallId: id,\n raw,\n });\n }\n\n const name = typeof functionRecord.name === \"string\" ? functionRecord.name.trim() : \"\";\n if (!name) {\n const toolCall = fallbackToolCall(turn, index, \"__malformed_tool_call__\", stringifyArguments(functionRecord.arguments));\n return {\n toolCall,\n warnings,\n failure: { reason: \"missing function name\", toolCall, raw },\n };\n }\n\n const normalizedArguments = normalizeArguments(functionRecord.arguments, warnings, id, name, raw);\n const toolCall: ToolCall = {\n id,\n type: \"function\",\n function: {\n name,\n arguments: normalizedArguments,\n },\n };\n\n const parsedArguments = parseToolArguments(normalizedArguments);\n if (!parsedArguments.ok) {\n return {\n toolCall,\n warnings,\n failure: { reason: parsedArguments.reason, toolCall, raw },\n };\n }\n\n return { toolCall, warnings };\n}\n\nfunction normalizeArguments(\n value: unknown,\n warnings: ToolCallParseWarning[],\n toolCallId: string,\n tool: string,\n raw: unknown,\n): string {\n if (value === undefined || value === null) {\n warnings.push({\n reason: \"missing arguments; using empty object\",\n toolCallId,\n tool,\n raw,\n });\n return \"{}\";\n }\n if (typeof value === \"string\") return value;\n if (typeof value === \"object\") {\n warnings.push({\n reason: \"arguments arrived as object; stringified for OpenAI-compatible history\",\n toolCallId,\n tool,\n raw,\n });\n return JSON.stringify(value);\n }\n warnings.push({\n reason: `arguments arrived as ${typeof value}; stringified for correction`,\n toolCallId,\n tool,\n raw,\n });\n return String(value);\n}\n\nfunction stringifyArguments(value: unknown): string {\n if (value === undefined || value === null) return \"\";\n if (typeof value === \"string\") return value;\n try {\n return JSON.stringify(value);\n } catch {\n return String(value);\n }\n}\n\nfunction fallbackToolCall(turn: number, index: number, name: string, args: string): ToolCall {\n return {\n id: `call_${turn}_${index}`,\n type: \"function\",\n function: {\n name,\n arguments: args,\n },\n };\n}\n\nfunction previewRawToolArguments(raw: string): string {\n return raw.length > 500 ? `${raw.slice(0, 500)}...[truncated ${raw.length - 500} chars]` : raw;\n}\n\nfunction isRecord(value: unknown): value is RawToolCallRecord {\n return Boolean(value && typeof value === \"object\" && !Array.isArray(value));\n}\n","import type { PermissionMode } from \"./schema\";\nimport type { Decision } from \"./engine\";\n\nexport function modeDefaultDecision(mode: PermissionMode): Decision {\n switch (mode) {\n case \"bypass\":\n return { decision: \"allow\", reason: \"bypass-mode\" };\n case \"default\":\n return { decision: \"allow\", reason: \"default-mode\" };\n case \"ask\":\n return { decision: \"ask\", reason: \"ask-mode\" };\n case \"plan\":\n return { decision: \"deny\", reason: \"plan-mode\" };\n }\n}\n","import { modeDefaultDecision } from \"./modes\";\nimport type { PathRule, PermissionMode, PermissionRulesConfig, SpendRule } from \"./schema\";\nimport { pathIsInsideWorkspace } from \"../workspace\";\n\nexport type PermissionDecision = \"allow\" | \"deny\" | \"ask\";\n\nexport interface Decision {\n decision: PermissionDecision;\n matchedRule?: string;\n reason?: string;\n projectedCostUsd?: number;\n projectedTokens?: number;\n thresholdUsd?: number;\n thresholdTokens?: number;\n}\n\nexport interface SpendState {\n turnTokens: number;\n runTokens: number;\n sessionTokens: number;\n projectedTokens?: number;\n turnUsd: number;\n runUsd: number;\n sessionUsd: number;\n projectedUsd?: number;\n}\n\nexport interface PermissionContext {\n mode: PermissionMode;\n rules: PermissionRulesConfig;\n runId: string;\n cwd: string;\n parentContext?: PermissionContext;\n spendState?: SpendState;\n}\n\nexport function decide(tool: string, input: unknown, ctx: PermissionContext): Decision {\n const local = decideLocal(tool, input, ctx);\n const parent = ctx.parentContext ? decide(tool, input, withoutParent(ctx.parentContext)) : null;\n if (!parent) return local;\n return stricter(parent, local);\n}\n\nexport function inputShape(input: unknown): string {\n const stable = stableStringify(input);\n return stable.startsWith(\"{\") && stable.endsWith(\"}\") ? stable.slice(1, -1) : stable;\n}\n\nfunction decideLocal(tool: string, input: unknown, ctx: PermissionContext): Decision {\n if (ctx.mode === \"bypass\") return { decision: \"allow\", reason: \"bypass-mode\" };\n if (ctx.mode === \"plan\") return { decision: \"deny\", reason: \"plan-mode\" };\n\n const shape = inputShape(input);\n const deny = findMatchingPattern(tool, shape, ctx.rules.alwaysDeny);\n if (deny) return { decision: \"deny\", matchedRule: deny, reason: \"alwaysDeny\" };\n\n const allow = findMatchingPattern(tool, shape, ctx.rules.alwaysAllow);\n if (allow) return { decision: \"allow\", matchedRule: allow, reason: \"alwaysAllow\" };\n\n const ask = findMatchingPattern(tool, shape, ctx.rules.alwaysAsk);\n if (ask) return { decision: \"ask\", matchedRule: ask, reason: \"alwaysAsk\" };\n\n const pathDecision = decidePathRule(input, ctx.rules.pathRules, ctx.cwd);\n if (pathDecision) return pathDecision;\n\n const spendDecision = decideSpendRule(ctx.rules.spendRules, ctx.spendState);\n if (spendDecision) return spendDecision;\n\n return modeDefaultDecision(ctx.mode);\n}\n\nfunction findMatchingPattern(tool: string, shape: string, patterns: string[]): string | null {\n for (const pattern of patterns) {\n const separator = pattern.indexOf(\":\");\n if (separator <= 0) continue;\n const patternTool = pattern.slice(0, separator);\n const regex = pattern.slice(separator + 1);\n if (patternTool === tool && new RegExp(regex).test(shape)) return pattern;\n if (patternTool === \"mcp\" && tool.startsWith(\"mcp:\")) {\n const mcpShape = `${tool.slice(\"mcp:\".length)}:${shape}`;\n if (new RegExp(regex).test(mcpShape)) return pattern;\n }\n }\n return null;\n}\n\nfunction decidePathRule(input: unknown, rules: PathRule[], cwd: string): Decision | null {\n const paths = extractPathValues(input);\n for (const path of paths) {\n for (const rule of rules) {\n if (!globMatches(rule.glob, path)) continue;\n return {\n decision: rule.action,\n matchedRule: `path:${rule.glob}`,\n reason: \"pathRule\",\n };\n }\n if (!pathIsInsideWorkspace(cwd, path)) {\n return {\n decision: \"deny\",\n matchedRule: \"path:<outside-workspace>\",\n reason: \"outsideWorkspace\",\n };\n }\n }\n return null;\n}\n\nfunction decideSpendRule(rules: SpendRule[], spendState: SpendState | undefined): Decision | null {\n if (!spendState || rules.length === 0) return null;\n const projectedTokens = spendState.projectedTokens ?? 0;\n const projectedUsd = spendState.projectedUsd ?? 0;\n for (const rule of rules) {\n const currentTokens = scopeTokens(rule.scope, spendState);\n const currentUsd = scopeUsd(rule.scope, spendState);\n const totalTokens = currentTokens + projectedTokens;\n const totalUsd = currentUsd + projectedUsd;\n if (rule.max_tokens !== undefined && totalTokens > rule.max_tokens) {\n return {\n decision: rule.action,\n matchedRule: `spend:${rule.scope}:max_tokens:${rule.max_tokens}`,\n reason: \"spendRule\",\n projectedTokens: totalTokens,\n thresholdTokens: rule.max_tokens,\n projectedCostUsd: totalUsd,\n ...(rule.max_usd !== undefined ? { thresholdUsd: rule.max_usd } : {}),\n };\n }\n if (rule.max_usd !== undefined && totalUsd > rule.max_usd) {\n return {\n decision: rule.action,\n matchedRule: `spend:${rule.scope}:max_usd:${rule.max_usd}`,\n reason: \"spendRule\",\n projectedCostUsd: totalUsd,\n thresholdUsd: rule.max_usd,\n projectedTokens: totalTokens,\n ...(rule.max_tokens !== undefined ? { thresholdTokens: rule.max_tokens } : {}),\n };\n }\n }\n return null;\n}\n\nfunction stricter(parent: Decision, child: Decision): Decision {\n if (parent.decision === \"deny\") return parent;\n if (child.decision === \"deny\") return child;\n if (parent.decision === \"ask\") return parent;\n if (child.decision === \"ask\") return child;\n return child;\n}\n\nfunction extractPathValues(input: unknown): string[] {\n const paths: string[] = [];\n collectPaths(input, paths);\n return paths;\n}\n\nfunction collectPaths(value: unknown, paths: string[]): void {\n if (!value || typeof value !== \"object\") return;\n if (Array.isArray(value)) {\n for (const item of value) collectPaths(item, paths);\n return;\n }\n const record = value as Record<string, unknown>;\n for (const [key, child] of Object.entries(record)) {\n if (/^(?:path|targetPath|sourcePath|file|filename)$/i.test(key) && typeof child === \"string\") {\n paths.push(child);\n } else {\n collectPaths(child, paths);\n }\n }\n}\n\nfunction scopeTokens(scope: SpendRule[\"scope\"], state: SpendState): number {\n if (scope === \"turn\") return state.turnTokens;\n if (scope === \"run\") return state.runTokens;\n return state.sessionTokens;\n}\n\nfunction scopeUsd(scope: SpendRule[\"scope\"], state: SpendState): number {\n if (scope === \"turn\") return state.turnUsd;\n if (scope === \"run\") return state.runUsd;\n return state.sessionUsd;\n}\n\nfunction globMatches(glob: string, path: string): boolean {\n if (glob === \"**\" || glob === \"**/*\") return true;\n const regex = new RegExp(`^${globToRegex(glob)}$`);\n return regex.test(path);\n}\n\nfunction globToRegex(glob: string): string {\n let output = \"\";\n for (let index = 0; index < glob.length; index += 1) {\n const char = glob[index] ?? \"\";\n if (char === \"*\") {\n const next = glob[index + 1];\n if (next === \"*\") {\n output += \".*\";\n index += 1;\n } else {\n output += \"[^/]*\";\n }\n continue;\n }\n if (char === \"?\") {\n output += \".\";\n continue;\n }\n output += escapeRegex(char);\n }\n return output;\n}\n\nfunction stableStringify(value: unknown): string {\n if (value === null || typeof value !== \"object\") return JSON.stringify(value);\n if (Array.isArray(value)) return `[${value.map(stableStringify).join(\",\")}]`;\n const record = value as Record<string, unknown>;\n return `{${Object.keys(record).sort().map((key) => `${JSON.stringify(key)}:${stableStringify(record[key])}`).join(\",\")}}`;\n}\n\nfunction escapeRegex(value: string): string {\n return value.replace(/[|\\\\{}()[\\]^$+?.]/g, \"\\\\$&\");\n}\n\nfunction withoutParent(ctx: PermissionContext): PermissionContext {\n const { parentContext: _parentContext, ...rest } = ctx;\n return rest;\n}\n","import { existsSync, readFileSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { join } from \"node:path\";\nimport {\n DEFAULT_PERMISSION_RULES,\n parsePermissionsJson,\n type PermissionRulesConfig,\n type PermissionMode,\n type PermissionInheritanceWarning,\n type SchemaIssue,\n} from \"./schema\";\n\nexport interface LoadPermissionRulesOptions {\n cwd: string;\n home?: string;\n}\n\nexport interface LoadedPermissionRules {\n rules: PermissionRulesConfig;\n sources: string[];\n issues: Array<SchemaIssue & { file: string }>;\n}\n\nexport interface InheritedPermissionRules {\n rules: PermissionRulesConfig;\n warnings: PermissionInheritanceWarning[];\n}\n\nexport function loadPermissionRules(options: LoadPermissionRulesOptions): LoadedPermissionRules {\n const home = options.home ?? homedir();\n const candidates = [\n join(home, \".tania\", \"permissions.json\"),\n join(home, \".tanya\", \"permissions.json\"),\n join(options.cwd, \".tania\", \"permissions.json\"),\n ];\n\n let rules = cloneRules(DEFAULT_PERMISSION_RULES);\n const sources: string[] = [];\n const issues: Array<SchemaIssue & { file: string }> = [];\n for (const file of candidates) {\n if (!existsSync(file)) continue;\n const parsed = parsePermissionsJson(readFileSync(file, \"utf8\"));\n if (!parsed.ok) {\n issues.push(...parsed.issues.map((issue) => ({ ...issue, file })));\n continue;\n }\n rules = mergePermissionRules(rules, parsed.value);\n sources.push(file);\n }\n\n return { rules, sources, issues };\n}\n\nexport function mergePermissionRules(base: PermissionRulesConfig, next: PermissionRulesConfig): PermissionRulesConfig {\n if (next.override) return cloneRules(next);\n return {\n version: 1,\n mode: next.mode,\n alwaysAllow: unique([...base.alwaysAllow, ...next.alwaysAllow]),\n alwaysDeny: unique([...base.alwaysDeny, ...next.alwaysDeny]),\n alwaysAsk: unique([...base.alwaysAsk, ...next.alwaysAsk]),\n pathRules: [...base.pathRules, ...next.pathRules],\n spendRules: [...base.spendRules, ...next.spendRules],\n };\n}\n\nexport function mergeInheritedPermissionRules(parent: PermissionRulesConfig, child: PermissionRulesConfig): InheritedPermissionRules {\n const warnings: PermissionInheritanceWarning[] = [];\n if (child.override) {\n warnings.push({\n field: \"override\",\n value: \"true\",\n reason: \"child override ignored; sub-agent permissions can only tighten parent rules\",\n });\n }\n\n const parentGuardPatterns = [...parent.alwaysDeny, ...parent.alwaysAsk];\n const childAlwaysAllow = child.alwaysAllow.filter((pattern) => {\n const blockedBy = parentGuardPatterns.find((parentPattern) => patternsMayOverlap(pattern, parentPattern));\n if (!blockedBy) return true;\n warnings.push({\n field: \"alwaysAllow\",\n value: pattern,\n reason: `child allow overlaps inherited ${blockedBy}`,\n });\n return false;\n });\n\n const childPathRules = child.pathRules.filter((rule) => {\n if (rule.action !== \"allow\") return true;\n const blockedBy = parent.pathRules.find((parentRule) => parentRule.action !== \"allow\" && pathGlobsMayOverlap(rule.glob, parentRule.glob));\n if (!blockedBy) return true;\n warnings.push({\n field: \"pathRules\",\n value: `${rule.glob}:${rule.action}`,\n reason: `child path allow overlaps inherited ${blockedBy.action} for ${blockedBy.glob}`,\n });\n return false;\n });\n\n const mode = stricterPermissionMode(parent.mode, child.mode);\n if (mode !== child.mode) {\n warnings.push({\n field: \"mode\",\n value: child.mode,\n reason: `child mode demoted to inherited ${mode}`,\n });\n }\n\n return {\n rules: {\n version: 1,\n mode,\n alwaysAllow: unique([...parent.alwaysAllow, ...childAlwaysAllow]),\n alwaysDeny: unique([...parent.alwaysDeny, ...child.alwaysDeny]),\n alwaysAsk: unique([...parent.alwaysAsk, ...child.alwaysAsk]),\n pathRules: [...parent.pathRules, ...childPathRules],\n spendRules: [...parent.spendRules, ...child.spendRules],\n },\n warnings,\n };\n}\n\nexport function stricterPermissionMode(parent: PermissionMode, child: PermissionMode): PermissionMode {\n return modeRank(parent) >= modeRank(child) ? parent : child;\n}\n\nfunction cloneRules(rules: PermissionRulesConfig): PermissionRulesConfig {\n return {\n version: 1,\n mode: rules.mode,\n alwaysAllow: [...rules.alwaysAllow],\n alwaysDeny: [...rules.alwaysDeny],\n alwaysAsk: [...rules.alwaysAsk],\n pathRules: rules.pathRules.map((rule) => ({ ...rule })),\n spendRules: rules.spendRules.map((rule) => ({ ...rule })),\n ...(rules.override !== undefined ? { override: rules.override } : {}),\n };\n}\n\nfunction unique(values: string[]): string[] {\n return [...new Set(values)];\n}\n\nfunction modeRank(mode: PermissionMode): number {\n switch (mode) {\n case \"plan\": return 3;\n case \"ask\": return 2;\n case \"default\": return 1;\n case \"bypass\": return 0;\n }\n}\n\nfunction patternsMayOverlap(child: string, parent: string): boolean {\n if (child === parent) return true;\n const childTool = child.slice(0, child.indexOf(\":\"));\n const parentTool = parent.slice(0, parent.indexOf(\":\"));\n if (!childTool || !parentTool || childTool !== parentTool) return false;\n const childRegex = child.slice(child.indexOf(\":\") + 1);\n const parentRegex = parent.slice(parent.indexOf(\":\") + 1);\n if (parentRegex === \".*\") return true;\n if (childRegex === \".*\" && parentRegex.length > 0) return true;\n const childLiteral = regexLiteralPrefix(childRegex);\n const parentLiteral = regexLiteralPrefix(parentRegex);\n return Boolean(childLiteral && parentLiteral && (childLiteral.startsWith(parentLiteral) || parentLiteral.startsWith(childLiteral)));\n}\n\nfunction regexLiteralPrefix(pattern: string): string {\n return pattern\n .replace(/^\\.*/, \"\")\n .replace(/\\\\\\./g, \".\")\n .replace(/\\\\\\//g, \"/\")\n .split(/[()[\\]{}?+*|^$]/, 1)[0] ?? \"\";\n}\n\nfunction pathGlobsMayOverlap(childGlob: string, parentGlob: string): boolean {\n if (childGlob === parentGlob) return true;\n if (parentGlob === \"**\" || parentGlob === \"**/*\") return true;\n const parentPrefix = globPrefix(parentGlob);\n const childPrefix = globPrefix(childGlob);\n return Boolean(parentPrefix && childPrefix && (childPrefix.startsWith(parentPrefix) || parentPrefix.startsWith(childPrefix)));\n}\n\nfunction globPrefix(glob: string): string {\n const wildcard = glob.search(/[*?[\\]{}]/);\n return (wildcard === -1 ? glob : glob.slice(0, wildcard)).replace(/\\/+$/, \"\");\n}\n","export const PERMISSIONS_SCHEMA_VERSION = 1;\n\nexport type PermissionMode = \"default\" | \"ask\" | \"bypass\" | \"plan\";\nexport type PermissionAction = \"allow\" | \"deny\" | \"ask\";\nexport type SpendScope = \"turn\" | \"run\" | \"session\";\n\nexport interface PathRule {\n glob: string;\n action: PermissionAction;\n}\n\nexport interface SpendRule {\n type: \"spend\";\n scope: SpendScope;\n max_usd?: number;\n max_tokens?: number;\n action: Exclude<PermissionAction, \"allow\">;\n}\n\nexport interface PermissionRulesConfig {\n version: 1;\n mode: PermissionMode;\n alwaysAllow: string[];\n alwaysDeny: string[];\n alwaysAsk: string[];\n pathRules: PathRule[];\n spendRules: SpendRule[];\n override?: boolean;\n}\n\nexport type PermissionInheritanceWarning = {\n field: \"alwaysAllow\" | \"pathRules\" | \"mode\" | \"override\";\n value: string;\n reason: string;\n};\n\nexport interface SchemaIssue {\n path: string;\n message: string;\n}\n\nexport type SchemaResult =\n | { ok: true; value: PermissionRulesConfig; issues: [] }\n | { ok: false; issues: SchemaIssue[] };\n\nconst MODES = new Set<PermissionMode>([\"default\", \"ask\", \"bypass\", \"plan\"]);\nconst ACTIONS = new Set<PermissionAction>([\"allow\", \"deny\", \"ask\"]);\nconst SPEND_ACTIONS = new Set<SpendRule[\"action\"]>([\"deny\", \"ask\"]);\nconst SPEND_SCOPES = new Set<SpendScope>([\"turn\", \"run\", \"session\"]);\n\nexport const DEFAULT_PERMISSION_RULES: PermissionRulesConfig = {\n version: PERMISSIONS_SCHEMA_VERSION,\n mode: \"bypass\",\n alwaysAllow: [],\n alwaysDeny: [],\n alwaysAsk: [],\n pathRules: [],\n spendRules: [],\n};\n\nexport function parsePermissionsJson(raw: string): SchemaResult {\n try {\n return validatePermissionsConfig(JSON.parse(raw) as unknown);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n return { ok: false, issues: [{ path: \"$\", message: `Invalid JSON: ${message}` }] };\n }\n}\n\nexport function validatePermissionsConfig(input: unknown): SchemaResult {\n const issues: SchemaIssue[] = [];\n if (!isRecord(input)) {\n return { ok: false, issues: [{ path: \"$\", message: \"Expected an object.\" }] };\n }\n\n const version = input.version;\n if (version !== PERMISSIONS_SCHEMA_VERSION) {\n issues.push({ path: \"$.version\", message: `Expected schema version ${PERMISSIONS_SCHEMA_VERSION}.` });\n }\n\n const mode = input.mode ?? \"bypass\";\n if (typeof mode !== \"string\" || !MODES.has(mode as PermissionMode)) {\n issues.push({ path: \"$.mode\", message: \"Expected one of: default, ask, bypass, plan.\" });\n }\n\n const alwaysAllow = stringArray(input.alwaysAllow, \"$.alwaysAllow\", issues);\n const alwaysDeny = stringArray(input.alwaysDeny, \"$.alwaysDeny\", issues);\n const alwaysAsk = stringArray(input.alwaysAsk, \"$.alwaysAsk\", issues);\n for (const [field, patterns] of [\n [\"alwaysAllow\", alwaysAllow],\n [\"alwaysDeny\", alwaysDeny],\n [\"alwaysAsk\", alwaysAsk],\n ] as const) {\n for (let index = 0; index < patterns.length; index += 1) {\n validatePattern(patterns[index] ?? \"\", `$.${field}[${index}]`, issues);\n }\n }\n\n const pathRules = validatePathRules(input.pathRules, issues);\n const spendRules = validateSpendRules(input.spendRules, issues);\n const override = input.override;\n if (override !== undefined && typeof override !== \"boolean\") {\n issues.push({ path: \"$.override\", message: \"Expected boolean when present.\" });\n }\n\n if (issues.length > 0) return { ok: false, issues };\n\n return {\n ok: true,\n value: {\n version: PERMISSIONS_SCHEMA_VERSION,\n mode: mode as PermissionMode,\n alwaysAllow,\n alwaysDeny,\n alwaysAsk,\n pathRules,\n spendRules,\n ...(override !== undefined ? { override: Boolean(override) } : {}),\n },\n issues: [],\n };\n}\n\nfunction validatePathRules(input: unknown, issues: SchemaIssue[]): PathRule[] {\n if (input === undefined) return [];\n if (!Array.isArray(input)) {\n issues.push({ path: \"$.pathRules\", message: \"Expected an array.\" });\n return [];\n }\n return input.flatMap((item, index) => {\n const path = `$.pathRules[${index}]`;\n if (!isRecord(item)) {\n issues.push({ path, message: \"Expected an object.\" });\n return [];\n }\n if (typeof item.glob !== \"string\" || item.glob.trim() === \"\") {\n issues.push({ path: `${path}.glob`, message: \"Expected a non-empty glob string.\" });\n }\n if (typeof item.action !== \"string\" || !ACTIONS.has(item.action as PermissionAction)) {\n issues.push({ path: `${path}.action`, message: \"Expected action allow, deny, or ask.\" });\n }\n if (typeof item.glob === \"string\" && ACTIONS.has(item.action as PermissionAction)) {\n return [{ glob: item.glob, action: item.action as PermissionAction }];\n }\n return [];\n });\n}\n\nfunction validateSpendRules(input: unknown, issues: SchemaIssue[]): SpendRule[] {\n if (input === undefined) return [];\n if (!Array.isArray(input)) {\n issues.push({ path: \"$.spendRules\", message: \"Expected an array.\" });\n return [];\n }\n return input.flatMap((item, index) => {\n const path = `$.spendRules[${index}]`;\n if (!isRecord(item)) {\n issues.push({ path, message: \"Expected an object.\" });\n return [];\n }\n if (item.type !== \"spend\") {\n issues.push({ path: `${path}.type`, message: \"Expected \\\"spend\\\".\" });\n }\n if (typeof item.scope !== \"string\" || !SPEND_SCOPES.has(item.scope as SpendScope)) {\n issues.push({ path: `${path}.scope`, message: \"Expected turn, run, or session.\" });\n }\n if (typeof item.action !== \"string\" || !SPEND_ACTIONS.has(item.action as SpendRule[\"action\"])) {\n issues.push({ path: `${path}.action`, message: \"Expected action deny or ask.\" });\n }\n const hasUsd = item.max_usd !== undefined;\n const hasTokens = item.max_tokens !== undefined;\n if (!hasUsd && !hasTokens) {\n issues.push({ path, message: \"Expected at least one threshold: max_usd or max_tokens.\" });\n }\n if (hasUsd && !positiveNumber(item.max_usd)) {\n issues.push({ path: `${path}.max_usd`, message: \"Expected a positive number.\" });\n }\n if (hasTokens && !positiveNumber(item.max_tokens)) {\n issues.push({ path: `${path}.max_tokens`, message: \"Expected a positive number.\" });\n }\n if (\n item.type === \"spend\" &&\n SPEND_SCOPES.has(item.scope as SpendScope) &&\n SPEND_ACTIONS.has(item.action as SpendRule[\"action\"]) &&\n (positiveNumber(item.max_usd) || positiveNumber(item.max_tokens))\n ) {\n return [{\n type: \"spend\" as const,\n scope: item.scope as SpendScope,\n ...(positiveNumber(item.max_usd) ? { max_usd: item.max_usd as number } : {}),\n ...(positiveNumber(item.max_tokens) ? { max_tokens: item.max_tokens as number } : {}),\n action: item.action as SpendRule[\"action\"],\n }];\n }\n return [];\n });\n}\n\nfunction stringArray(input: unknown, path: string, issues: SchemaIssue[]): string[] {\n if (input === undefined) return [];\n if (!Array.isArray(input)) {\n issues.push({ path, message: \"Expected an array of strings.\" });\n return [];\n }\n return input.flatMap((item, index) => {\n if (typeof item !== \"string\") {\n issues.push({ path: `${path}[${index}]`, message: \"Expected a string.\" });\n return [];\n }\n return [item];\n });\n}\n\nfunction validatePattern(pattern: string, path: string, issues: SchemaIssue[]): void {\n const separator = pattern.indexOf(\":\");\n if (separator <= 0) {\n issues.push({ path, message: \"Expected pattern format tool:<regex>.\" });\n return;\n }\n const tool = pattern.slice(0, separator).trim();\n const regex = pattern.slice(separator + 1);\n if (!/^[A-Za-z0-9_.-]+$/.test(tool)) {\n issues.push({ path, message: \"Tool name must contain only letters, numbers, '.', '_' or '-'.\" });\n }\n try {\n new RegExp(regex);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n issues.push({ path, message: `Invalid regex: ${message}` });\n }\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return Boolean(value && typeof value === \"object\" && !Array.isArray(value));\n}\n\nfunction positiveNumber(value: unknown): value is number {\n return typeof value === \"number\" && Number.isFinite(value) && value > 0;\n}\n","import { existsSync, readdirSync } from \"node:fs\";\nimport { cp, mkdir, readFile, realpath, unlink, writeFile } from \"node:fs/promises\";\nimport { basename, dirname, isAbsolute, join, relative, resolve } from \"node:path\";\nimport { spawn } from \"node:child_process\";\nimport sharp from \"sharp\";\nimport type { TanyaTool, ToolContext, ToolResult } from \"./types\";\nimport { resolveInsideWorkspace } from \"../safety/workspace\";\nimport {\n createAndroidLauncherIconSetTool,\n createAppleAppIconSetTool,\n renderSvgToPngTool,\n resizeImageTool,\n validateAndroidLauncherIconSetTool,\n validateAppleAppIconSetTool,\n} from \"./imageTools\";\nimport { generateVideoAssetTool } from \"./videoTools\";\nimport { buildTaskBriefTool, findReusableArtifactsTool, inspectProjectContextTool } from \"./projectContextTools\";\nimport { searchObsidianNotesTool } from \"./obsidianTools\";\nimport { expandResultTool } from \"./expandResult\";\nimport { taskTool } from \"./task\";\nimport { editBlockTool } from \"./editBlock\";\nimport { inspectRepoMapTool } from \"./repoMapTools\";\nimport { recordMetricsDashboardHandoffTool } from \"./metricsDashboardTools\";\n\nconst ignoredNames = new Set([\".git\", \"node_modules\", \".next\", \"dist\", \"build\", \".turbo\", \".cache\"]);\n// Throttle for run_shell stdout/stderr → onProgress emits. Default 2s keeps\n// the ink renderer responsive without spamming. Override via\n// TANYA_PROGRESS_THROTTLE_MS so tests can use a smaller value and not flake\n// under CI/publish-pipeline load. Read lazily because ES-module hoisting\n// would otherwise capture the value before any test setup runs.\nexport function getProgressThrottleMs(): number {\n const raw = Number(process.env.TANYA_PROGRESS_THROTTLE_MS);\n return Number.isFinite(raw) && raw >= 0 ? raw : 2_000;\n}\n// Back-compat re-export — most call sites import the constant. Keep it but\n// flag the deprecation via the comment so future readers reach for the fn.\nexport const PROGRESS_THROTTLE_MS = getProgressThrottleMs();\n\nfunction isProtectedLocalConfigPath(filePath: string): boolean {\n return basename(filePath.trim().replace(/\\\\/g, \"/\")) === \"local.properties\";\n}\n\nfunction localPropertiesWriteError(): ToolResult {\n return {\n ok: false,\n summary: \"Rejected write to local.properties.\",\n error: \"local.properties is machine-local Android SDK configuration. Do not create or modify it; use ANDROID_HOME or ANDROID_SDK_ROOT for verification instead.\",\n };\n}\n\nfunction shellSafetyBlock(summary: string, error: string): ToolResult {\n return {\n ok: false,\n summary,\n error,\n output: { ok: false, error, reason: \"shell_safety_block\" },\n };\n}\n\nfunction asRecord(input: unknown): Record<string, unknown> {\n return input && typeof input === \"object\" ? (input as Record<string, unknown>) : {};\n}\n\nfunction asString(input: unknown, key: string): string {\n const value = asRecord(input)[key];\n if (typeof value !== \"string\" || !value.trim()) throw new Error(`Missing string field: ${key}`);\n return value;\n}\n\nfunction asOptionalNumber(input: unknown, key: string, fallback: number): number {\n const value = asRecord(input)[key];\n return typeof value === \"number\" && Number.isFinite(value) ? value : fallback;\n}\n\nfunction asOptionalString(input: unknown, key: string): string | undefined {\n const value = asRecord(input)[key];\n return typeof value === \"string\" && value.trim() ? value.trim() : undefined;\n}\n\nfunction asOptionalBoolean(input: unknown, key: string, fallback: boolean): boolean {\n const value = asRecord(input)[key];\n if (typeof value === \"boolean\") return value;\n if (typeof value === \"string\") return /^(true|yes|1)$/i.test(value.trim());\n return fallback;\n}\n\nasync function pathExists(path: string): Promise<boolean> {\n return existsSync(path);\n}\n\nfunction collectFiles(root: string, maxFiles: number, current = root, out: string[] = []): string[] {\n if (out.length >= maxFiles) return out;\n for (const entry of readdirSync(current, { withFileTypes: true })) {\n if (ignoredNames.has(entry.name)) continue;\n const fullPath = join(current, entry.name);\n if (entry.isDirectory()) {\n collectFiles(root, maxFiles, fullPath, out);\n } else if (entry.isFile()) {\n out.push(relative(root, fullPath));\n }\n if (out.length >= maxFiles) break;\n }\n return out;\n}\n\nfunction runProcess(\n command: string,\n args: string[],\n context: ToolContext,\n timeoutMs: number,\n cwd = context.workspace,\n): Promise<ToolResult> {\n return new Promise((resolve) => {\n const child = spawn(command, args, {\n cwd,\n shell: false,\n env: process.env,\n });\n let stdout = \"\";\n let stderr = \"\";\n const timer = setTimeout(() => {\n child.kill(\"SIGTERM\");\n }, timeoutMs);\n\n child.stdout.on(\"data\", (chunk: Buffer) => {\n stdout += chunk.toString();\n });\n child.stderr.on(\"data\", (chunk: Buffer) => {\n stderr += chunk.toString();\n });\n child.on(\"close\", (code) => {\n clearTimeout(timer);\n const output = `${stdout}${stderr ? `\\n${stderr}` : \"\"}`.trim();\n const truncated = output.length > 12_000;\n const baseResult: ToolResult = {\n ok: code === 0,\n summary: buildProcessSummary(\"Command\", code, output, truncated),\n output,\n };\n resolve(code === 0 ? baseResult : { ...baseResult, error: output.slice(0, 2_000) });\n });\n child.on(\"error\", (err) => {\n clearTimeout(timer);\n resolve({ ok: false, summary: \"Command failed to start.\", error: err.message });\n });\n });\n}\n\nfunction emitToolProgress(context: ToolContext, stream: \"stdout\" | \"stderr\", chunk: string): void {\n if (!context.onProgress || !chunk) return;\n try {\n void Promise.resolve(context.onProgress({\n stream,\n chunk,\n timestamp: new Date().toISOString(),\n })).catch(() => {});\n } catch {\n // Progress is observational; a sink failure must not fail the tool.\n }\n}\n\nfunction runShell(script: string, context: ToolContext, timeoutMs: number, cwd = context.workspace): Promise<ToolResult> {\n return new Promise((resolve) => {\n const child = spawn(\"/bin/zsh\", [\"-lc\", script], {\n cwd,\n shell: false,\n env: process.env,\n detached: process.platform !== \"win32\",\n });\n let stdout = \"\";\n let stderr = \"\";\n let cancelled = context.signal?.aborted ?? false;\n let cancelKillTimer: ReturnType<typeof setTimeout> | null = null;\n const progressBuffers: Record<\"stdout\" | \"stderr\", string> = {\n stdout: \"\",\n stderr: \"\",\n };\n const progressTimers: Record<\"stdout\" | \"stderr\", ReturnType<typeof setTimeout> | null> = {\n stdout: null,\n stderr: null,\n };\n const flushProgress = (stream: \"stdout\" | \"stderr\") => {\n const timer = progressTimers[stream];\n if (timer) clearTimeout(timer);\n progressTimers[stream] = null;\n const chunk = progressBuffers[stream];\n progressBuffers[stream] = \"\";\n emitToolProgress(context, stream, chunk);\n };\n const flushAllProgress = () => {\n flushProgress(\"stdout\");\n flushProgress(\"stderr\");\n };\n const queueProgress = (stream: \"stdout\" | \"stderr\", chunk: string) => {\n if (!context.onProgress || !chunk) return;\n progressBuffers[stream] += chunk;\n if (progressTimers[stream]) return;\n progressTimers[stream] = setTimeout(() => flushProgress(stream), getProgressThrottleMs());\n progressTimers[stream]?.unref?.();\n };\n const outputSoFar = () => `${stdout}${stderr ? `\\n${stderr}` : \"\"}`.trim();\n const killShellProcess = (signal: NodeJS.Signals) => {\n if (child.pid && process.platform !== \"win32\") {\n try {\n process.kill(-child.pid, signal);\n return;\n } catch {\n // Fall back to the direct child if the process group is already gone.\n }\n }\n try {\n child.kill(signal);\n } catch {\n // Process already exited.\n }\n };\n const requestCancel = () => {\n cancelled = true;\n killShellProcess(\"SIGTERM\");\n if (!cancelKillTimer) {\n cancelKillTimer = setTimeout(() => killShellProcess(\"SIGKILL\"), 500);\n cancelKillTimer.unref?.();\n }\n };\n const cleanupShell = () => {\n clearTimeout(timer);\n if (cancelKillTimer) clearTimeout(cancelKillTimer);\n context.signal?.removeEventListener(\"abort\", requestCancel);\n flushAllProgress();\n };\n const timer = setTimeout(() => {\n killShellProcess(\"SIGTERM\");\n }, timeoutMs);\n if (context.signal?.aborted) requestCancel();\n else context.signal?.addEventListener(\"abort\", requestCancel, { once: true });\n\n child.stdout.on(\"data\", (chunk: Buffer) => {\n const text = chunk.toString();\n stdout += text;\n queueProgress(\"stdout\", text);\n });\n child.stderr.on(\"data\", (chunk: Buffer) => {\n const text = chunk.toString();\n stderr += text;\n queueProgress(\"stderr\", text);\n });\n child.on(\"close\", (code) => {\n cleanupShell();\n const output = outputSoFar();\n if (cancelled || context.signal?.aborted) {\n const partialOutput = summarizeProcessOutput(output, 16_000).text;\n resolve({\n ok: false,\n summary: \"Shell cancelled by user. Partial output captured.\",\n output: { cancelled: true, partial_output: partialOutput },\n error: \"Shell cancelled by user.\",\n cancelled: true,\n partial_output: partialOutput,\n });\n return;\n }\n const truncated = output.length > 16_000;\n const baseResult: ToolResult = {\n ok: code === 0,\n summary: buildProcessSummary(\"Shell\", code, output, truncated),\n output,\n };\n resolve(code === 0 ? baseResult : { ...baseResult, error: output.slice(0, 2_000) });\n });\n child.on(\"error\", (err) => {\n cleanupShell();\n resolve({ ok: false, summary: \"Shell failed to start.\", error: err.message });\n });\n });\n}\n\nfunction unsafeMaskedVerification(script: string): string | null {\n const runsMobileBuildTool = /(?:^|[\\s;&|])(?:\\.\\/gradlew|gradle|xcodebuild|fastlane)\\b/.test(script);\n if (!runsMobileBuildTool) return null;\n const isReadOnlyXcodeDiscovery = /\\bxcodebuild\\s+-(?:list|showsdks|version)\\b/i.test(script);\n if (isReadOnlyXcodeDiscovery) return null;\n if (/[|]/.test(script) && !/set\\s+-o\\s+pipefail/.test(script)) {\n return \"Mobile build/test verification commands that use pipes must include `set -o pipefail` so failures are not masked.\";\n }\n if (/;\\s*echo\\s+[\"']?EXIT_CODE=\\$\\?[\"']?/i.test(script)) {\n return \"Do not append `; echo EXIT_CODE=$?` to verification commands because it makes the shell exit 0 even when the build command failed.\";\n }\n return null;\n}\n\nfunction unsafeHostPackageMutation(script: string): string | null {\n if (/\\bbrew\\s+(?:install|reinstall|upgrade|uninstall|tap|extract)\\b/i.test(script)) {\n return \"Host package-manager mutation is not allowed during coding runs. Report the missing/broken Homebrew package as a manual environment blocker instead.\";\n }\n if (/\\bgem\\s+(?:install|update|uninstall)\\b/i.test(script) || /\\bbundle\\s+install\\b/i.test(script)) {\n return \"Host Ruby gem mutation is not allowed during coding runs. Report the missing/broken Ruby/Fastlane dependency as a manual environment blocker instead.\";\n }\n return null;\n}\n\nfunction summarizeProcessOutput(output: string, maxChars: number): { text: string; truncated: boolean } {\n if (output.length <= maxChars) return { text: output, truncated: false };\n const headSize = Math.floor(maxChars * 0.35);\n const tailSize = maxChars - headSize - 120;\n return {\n text: `${output.slice(0, headSize)}\\n\\n[output truncated: showing head and tail; exit code remains authoritative]\\n\\n${output.slice(-tailSize)}`,\n truncated: true,\n };\n}\n\nfunction buildProcessSummary(kind: \"Command\" | \"Shell\", code: number | null, output: string, truncated: boolean): string {\n const exit = code ?? \"unknown\";\n const successHint = code === 0 && /BUILD SUCCEEDED|Test Suite '.+' passed|0 failures|Process completed successfully/i.test(output)\n ? \" Success marker found.\"\n : \"\";\n const truncatedHint = truncated ? \" Output was truncated for display, but the exit code is authoritative.\" : \"\";\n return `${kind} exited ${exit}.${successHint}${truncatedHint}`;\n}\n\nfunction filterTypeScriptErrorOutput(output: unknown): string | null {\n if (typeof output !== \"string\" || !output.trim()) return null;\n const lines = output.split(/\\r?\\n/);\n const kept: string[] = [];\n const errorPattern = /^[^:]+\\.tsx?:\\d+:\\d+\\s+-\\s+error\\s+TS\\d+:/;\n for (let i = 0; i < lines.length; i += 1) {\n const line = lines[i] ?? \"\";\n if (!errorPattern.test(line)) continue;\n kept.push(line);\n const nextLine = lines[i + 1];\n if (nextLine !== undefined) kept.push(nextLine);\n }\n return kept.length > 0 ? `TypeScript errors (filtered):\\n${kept.join(\"\\n\")}` : null;\n}\n\nfunction commandRunsTypeScript(command: string, args: string[]): boolean {\n return basename(command) === \"tsc\" || args.some((arg) => basename(arg) === \"tsc\");\n}\n\nfunction shellRunsTypeScript(script: string): boolean {\n return /(?:^|[\\s;&|])(?:npx\\s+|npm\\s+exec\\s+|pnpm\\s+exec\\s+|yarn\\s+)?tsc(?:\\s|$)/.test(script);\n}\n\nfunction maybeFilterTypeScriptErrorResult(result: ToolResult, shouldFilter: boolean): ToolResult {\n if (!shouldFilter || result.ok) return result;\n const filtered = filterTypeScriptErrorOutput(result.output);\n if (!filtered) return result;\n return {\n ...result,\n output: filtered,\n error: filtered,\n };\n}\n\nfunction normalizeRelativePathForGit(path: string): string {\n return path.replace(/\\\\/g, \"/\").replace(/^\\.\\/+/, \"\").replace(/\\/+/g, \"/\");\n}\n\nfunction ensureRelativePath(path: string): string {\n if (path.startsWith(\"/\")) throw new Error(`Path must be relative to the workspace: ${path}`);\n return path;\n}\n\nfunction resolveToolCwd(context: ToolContext, cwdInput?: string): string {\n if (!cwdInput) return context.workspace;\n return isAbsolute(cwdInput)\n ? resolveInsideWorkspace(context.workspace, cwdInput)\n : resolveInsideWorkspace(context.workspace, ensureRelativePath(cwdInput));\n}\n\nfunction runProcessWithInput(\n command: string,\n args: string[],\n input: string,\n context: ToolContext,\n timeoutMs: number,\n): Promise<ToolResult> {\n return new Promise((resolve) => {\n const child = spawn(command, args, {\n cwd: context.workspace,\n shell: false,\n env: process.env,\n });\n let stdout = \"\";\n let stderr = \"\";\n const timer = setTimeout(() => {\n child.kill(\"SIGTERM\");\n }, timeoutMs);\n\n child.stdout.on(\"data\", (chunk: Buffer) => {\n stdout += chunk.toString();\n });\n child.stderr.on(\"data\", (chunk: Buffer) => {\n stderr += chunk.toString();\n });\n child.on(\"close\", (code) => {\n clearTimeout(timer);\n const output = `${stdout}${stderr ? `\\n${stderr}` : \"\"}`.trim();\n const baseResult: ToolResult = {\n ok: code === 0,\n summary: `Command exited ${code ?? \"unknown\"}.`,\n output: output.slice(0, 12_000),\n };\n resolve(code === 0 ? baseResult : { ...baseResult, error: output.slice(0, 2_000) });\n });\n child.on(\"error\", (err) => {\n clearTimeout(timer);\n resolve({ ok: false, summary: \"Command failed to start.\", error: err.message });\n });\n child.stdin.end(input);\n });\n}\n\nfunction stripPatchPath(path: string, stripLevel: number): string | null {\n const clean = path.trim().split(/\\s+/)[0];\n if (!clean || clean === \"/dev/null\") return null;\n const withoutQuotes = clean.replace(/^\"|\"$/g, \"\");\n const parts = withoutQuotes.split(\"/\").filter(Boolean);\n const stripped = parts.slice(Math.max(0, stripLevel)).join(\"/\");\n return stripped || withoutQuotes;\n}\n\nfunction inferPatchStripLevel(patch: string): number {\n return /^diff --git a\\//m.test(patch) || /^--- a\\//m.test(patch) || /^\\+\\+\\+ b\\//m.test(patch) ? 1 : 0;\n}\n\nfunction extractPatchFiles(patch: string, stripLevel: number): string[] {\n const files = new Set<string>();\n for (const line of patch.split(\"\\n\")) {\n const header = /^(?:---|\\+\\+\\+)\\s+(.+)$/.exec(line);\n if (!header) continue;\n const stripped = stripPatchPath(header[1] ?? \"\", stripLevel);\n if (stripped) files.add(stripped);\n }\n return [...files];\n}\n\nasync function removePatchBackupFiles(files: string[], context: ToolContext): Promise<string[]> {\n const removed: string[] = [];\n for (const file of files) {\n for (const suffix of [\".orig\", \".bak\"]) {\n const backupPath = `${file}${suffix}`;\n try {\n const abs = resolveInsideWorkspace(context.workspace, backupPath);\n await unlink(abs);\n removed.push(backupPath);\n } catch {\n // No backup was created for this file.\n }\n }\n }\n return removed;\n}\n\nfunction pathInsideWorkspace(workspace: string, target: string): boolean {\n const rel = relative(workspace, target);\n return rel === \"\" || (!rel.startsWith(\"..\") && !isAbsolute(rel));\n}\n\nfunction shellUnquote(value: string): string {\n return value.replace(/^['\"]|['\"]$/g, \"\");\n}\n\nfunction shellSnippetMayMutateWorkspace(script: string): boolean {\n return /(?:^|[;&|]\\s*)(?:cat\\s+>|tee\\s+|mkdir\\b|touch\\b|rm\\b|mv\\b|cp\\b|ln\\b|go\\s+mod\\s+(?:init|tidy|edit|download)\\b|go\\s+get\\b|go\\s+work\\b|npm\\s+(?:install|i|update|add)\\b|pnpm\\s+(?:install|add|update)\\b|yarn\\s+(?:add|install)\\b|sqlc\\s+generate\\b|go\\s+run\\s+github\\.com\\/sqlc-dev\\/sqlc\\/cmd\\/sqlc(?:@\\S+)?\\s+generate\\b|git\\s+(?:add|commit|rm|mv|checkout|restore|reset|clean)\\b)/i.test(script) ||\n /(?:^|[^2])>\\s*(?!&)/.test(script);\n}\n\nfunction outsideWorkspaceShellMutationError(script: string, workspace: string, cwd: string): string | null {\n const match = script.match(/^\\s*cd\\s+((?:\"[^\"]+\")|(?:'[^']+')|(?:\\S+))\\s*&&\\s*([\\s\\S]+)$/);\n if (!match) return null;\n const rawTarget = shellUnquote(match[1] ?? \"\");\n if (!rawTarget || rawTarget === \"-\") return null;\n if (/[$`]/.test(rawTarget)) return null;\n const target = isAbsolute(rawTarget) ? resolve(rawTarget) : resolve(cwd, rawTarget);\n if (pathInsideWorkspace(workspace, target)) return null;\n const rest = match[2] ?? \"\";\n if (!shellSnippetMayMutateWorkspace(rest)) return null;\n return `Shell snippet changes directory outside the workspace before a mutating command: cd ${rawTarget}. Use structured file tools or run mutations from the workspace root.`;\n}\n\nexport const listFilesTool: TanyaTool = {\n name: \"list_files\",\n description: \"List workspace files, skipping dependency and build directories.\",\n definition: {\n type: \"function\",\n function: {\n name: \"list_files\",\n description: \"List workspace files, skipping dependency and build directories.\",\n parameters: {\n type: \"object\",\n properties: {\n maxFiles: { type: \"number\", description: \"Maximum number of files to return. Default 120.\" },\n path: { type: \"string\", description: \"Optional directory path relative to the workspace. Default workspace root.\" },\n },\n additionalProperties: false,\n },\n },\n },\n async run(input, context) {\n const maxFiles = Math.min(asOptionalNumber(input, \"maxFiles\", 120), 500);\n const path = asOptionalString(input, \"path\");\n const root = path ? resolveInsideWorkspace(context.workspace, ensureRelativePath(path)) : context.workspace;\n const files = collectFiles(root, maxFiles).map((file) => path ? `${path.replace(/\\/+$/, \"\")}/${file}` : file);\n return { ok: true, summary: `Listed ${files.length} file${files.length === 1 ? \"\" : \"s\"}.`, output: files };\n },\n};\n\nexport const readFileTool: TanyaTool = {\n name: \"read_file\",\n description: \"Read a UTF-8 text file inside the workspace.\",\n truncateLargeResults: false,\n definition: {\n type: \"function\",\n function: {\n name: \"read_file\",\n description: \"Read a UTF-8 text file inside the workspace.\",\n parameters: {\n type: \"object\",\n properties: {\n path: { type: \"string\", description: \"File path relative to the workspace.\" },\n maxChars: { type: \"number\", description: \"Maximum characters to return. Default 12000.\" },\n force: { type: \"boolean\", description: \"Return full content even if Tanya already read the same unchanged file in this run.\" },\n },\n required: [\"path\"],\n additionalProperties: false,\n },\n },\n },\n async run(input, context) {\n const path = asString(input, \"path\");\n const maxChars = Math.min(asOptionalNumber(input, \"maxChars\", 12_000), 40_000);\n const abs = resolveInsideWorkspace(context.workspace, path);\n const content = await readFile(abs, \"utf8\");\n return {\n ok: true,\n summary: `Read ${path}.`,\n output: content.length > maxChars ? `${content.slice(0, maxChars)}\\n[truncated]` : content,\n };\n },\n};\n\nexport const writeFileTool: TanyaTool = {\n name: \"write_file\",\n description: \"Write a UTF-8 text file inside the workspace.\",\n definition: {\n type: \"function\",\n function: {\n name: \"write_file\",\n description: \"Write a UTF-8 text file inside the workspace.\",\n parameters: {\n type: \"object\",\n properties: {\n path: { type: \"string\", description: \"File path relative to the workspace.\" },\n content: { type: \"string\", description: \"Full file content.\" },\n },\n required: [\"path\", \"content\"],\n additionalProperties: false,\n },\n },\n },\n async run(input, context) {\n const path = asString(input, \"path\");\n const content = asString(input, \"content\");\n if (isProtectedLocalConfigPath(path)) return localPropertiesWriteError();\n const abs = resolveInsideWorkspace(context.workspace, path);\n await mkdir(dirname(abs), { recursive: true });\n await writeFile(abs, content, \"utf8\");\n const written = await readFile(abs, \"utf8\");\n const lineCount = written.split(\"\\n\").length;\n const preview = written.split(\"\\n\").slice(0, 4).join(\"\\n\");\n return {\n ok: true,\n summary: `Wrote ${path} (${lineCount} lines).`,\n output: { path, lineCount, preview },\n files: [path],\n };\n },\n};\n\nexport const searchTool: TanyaTool = {\n name: \"search\",\n description: \"Search workspace text using ripgrep.\",\n definition: {\n type: \"function\",\n function: {\n name: \"search\",\n description: \"Search workspace text using ripgrep.\",\n parameters: {\n type: \"object\",\n properties: {\n query: { type: \"string\", description: \"Search query or regex.\" },\n maxResults: { type: \"number\", description: \"Maximum lines to return. Default 80.\" },\n },\n required: [\"query\"],\n additionalProperties: false,\n },\n },\n },\n async run(input, context) {\n const query = asString(input, \"query\");\n const maxResults = Math.min(asOptionalNumber(input, \"maxResults\", 80), 300);\n const result = await runProcess(\"rg\", [\"-n\", \"--hidden\", \"-g\", \"!node_modules\", \"-g\", \"!.git\", query], context, 20_000);\n if (!result.ok && typeof result.output === \"string\" && !result.output) {\n return { ok: true, summary: \"No matches.\", output: [] };\n }\n const lines = String(result.output ?? \"\").split(\"\\n\").slice(0, maxResults);\n return { ok: true, summary: `Found ${lines.filter(Boolean).length} match line${lines.length === 1 ? \"\" : \"s\"}.`, output: lines };\n },\n};\n\nexport const runCommandTool: TanyaTool = {\n name: \"run_command\",\n description: \"Run a non-interactive command inside the workspace.\",\n keepFullForVerifier: true,\n definition: {\n type: \"function\",\n function: {\n name: \"run_command\",\n description: \"Run a non-interactive command inside the workspace.\",\n parameters: {\n type: \"object\",\n properties: {\n command: { type: \"string\", description: \"Command binary, for example npm.\" },\n args: { type: \"array\", items: { type: \"string\" }, description: \"Command arguments.\" },\n cwd: { type: \"string\", description: \"Optional subdirectory relative to the workspace.\" },\n timeoutMs: { type: \"number\", description: \"Timeout in milliseconds. Default 120000.\" },\n },\n required: [\"command\"],\n additionalProperties: false,\n },\n },\n },\n async run(input, context) {\n const command = asString(input, \"command\");\n const rawArgs = asRecord(input).args;\n const args = Array.isArray(rawArgs) ? rawArgs.filter((arg): arg is string => typeof arg === \"string\") : [];\n const cwdInput = asOptionalString(input, \"cwd\");\n const cwd = resolveToolCwd(context, cwdInput);\n const timeoutMs = Math.min(asOptionalNumber(input, \"timeoutMs\", 120_000), 300_000);\n const result = await runProcess(command, args, context, timeoutMs, cwd);\n return maybeFilterTypeScriptErrorResult(result, commandRunsTypeScript(command, args));\n },\n};\n\nexport const runShellTool: TanyaTool = {\n name: \"run_shell\",\n description: \"Run a bounded non-interactive shell snippet inside the workspace.\",\n keepFullForVerifier: true,\n definition: {\n type: \"function\",\n function: {\n name: \"run_shell\",\n description: \"Run a bounded non-interactive shell snippet inside the workspace. Use for mobile verification commands that need environment variables, pipes, or chained arguments.\",\n parameters: {\n type: \"object\",\n properties: {\n script: { type: \"string\", description: \"Non-interactive zsh script.\" },\n command: { type: \"string\", description: \"Alias for script. Prefer script for new calls.\" },\n cwd: { type: \"string\", description: \"Optional subdirectory relative to the workspace.\" },\n timeoutMs: { type: \"number\", description: \"Timeout in milliseconds. Default 120000.\" },\n },\n required: [],\n additionalProperties: false,\n },\n },\n },\n async run(input, context) {\n const script = asOptionalString(input, \"script\") ?? asString(input, \"command\");\n if (/\\b(rm\\s+-rf|sudo|ssh|scp|curl\\s+[^|>]*\\|\\s*(?:sh|bash|zsh)|while\\s+true|tail\\s+-f)\\b/.test(script)) {\n return shellSafetyBlock(\"Shell script rejected by safety checks.\", \"Use bounded, non-destructive, non-interactive commands only.\");\n }\n if (\n /\\bgit\\s+show\\s+\\S+:[^\\s|]+\\s*>/.test(script) ||\n /\\bgit\\s+cat-file\\s+-p\\s+\\S+:[^\\s|]+\\s*>/.test(script) ||\n /\\bgit\\s+(?:checkout|restore)\\s+[^-\\s][^\\s]*\\s+(?:--\\s+)?\\S/.test(script)\n ) {\n return shellSafetyBlock(\"Shell script rejected: git restore of historical content is not allowed.\", \"Do not use 'git show <ref>:<path> >', 'git cat-file -p <ref>:<path> >', or 'git checkout/restore <ref> -- <path>' to recover deleted files. Implement the file fresh using write_file/apply_patch following the artifacts and brief.\");\n }\n if (/\\bgit\\s+(?:-C\\s+\\S+\\s+)?reset\\b/i.test(script)) {\n return { ok: false, summary: \"Shell script rejected: git reset is not allowed.\", error: \"Do not use git reset during coding runs. Use commit_platform_changes with amend: true for task commit repairs, or edit files directly with workspace tools.\" };\n }\n const hostPackageMutationError = unsafeHostPackageMutation(script);\n if (hostPackageMutationError) {\n return { ok: false, summary: \"Shell script rejected by host mutation safety checks.\", error: hostPackageMutationError };\n }\n const maskedVerificationError = unsafeMaskedVerification(script);\n if (maskedVerificationError) {\n return shellSafetyBlock(\"Shell verification rejected by safety checks.\", maskedVerificationError);\n }\n if (/(?:>\\s*[\"']?[^&|;\\n]*local\\.properties\\b|tee\\s+[^|;\\n]*local\\.properties\\b)/.test(script)) {\n return localPropertiesWriteError();\n }\n const cwdInput = asOptionalString(input, \"cwd\");\n const cwd = resolveToolCwd(context, cwdInput);\n const outsideMutationError = outsideWorkspaceShellMutationError(script, context.workspace, cwd);\n if (outsideMutationError) {\n return { ok: false, summary: \"Shell script rejected: mutation outside workspace.\", error: outsideMutationError };\n }\n const timeoutMs = Math.min(asOptionalNumber(input, \"timeoutMs\", 120_000), 300_000);\n const result = await runShell(script, context, timeoutMs, cwd);\n return maybeFilterTypeScriptErrorResult(result, shellRunsTypeScript(script));\n },\n};\n\nexport const applyPatchTool: TanyaTool = {\n name: \"apply_patch\",\n description: \"Apply a unified diff patch inside the workspace.\",\n definition: {\n type: \"function\",\n function: {\n name: \"apply_patch\",\n description: \"Apply a unified diff patch inside the workspace. Prefer this for existing file edits.\",\n parameters: {\n type: \"object\",\n properties: {\n patch: { type: \"string\", description: \"Unified diff patch text.\" },\n stripLevel: { type: \"number\", description: \"Path strip level for patch. Defaults to auto-detect.\" },\n },\n required: [\"patch\"],\n additionalProperties: false,\n },\n },\n },\n async run(input, context) {\n const patch = asString(input, \"patch\");\n const explicitStrip = asOptionalNumber(input, \"stripLevel\", Number.NaN);\n const stripLevel = Number.isFinite(explicitStrip) ? explicitStrip : inferPatchStripLevel(patch);\n const files = extractPatchFiles(patch, stripLevel);\n if (files.length === 0) {\n return { ok: false, summary: \"Patch contains no file headers.\", error: \"Expected unified diff headers.\" };\n }\n try {\n for (const file of files) {\n if (isProtectedLocalConfigPath(file)) return { ...localPropertiesWriteError(), files };\n resolveInsideWorkspace(context.workspace, file);\n }\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n return { ok: false, summary: \"Patch rejected by workspace safety checks.\", error: message, files };\n }\n\n const result = await runProcessWithInput(\n \"patch\",\n [`-p${stripLevel}`, \"--batch\", \"--forward\", \"--reject-file=-\"],\n patch,\n context,\n 60_000,\n );\n const output = typeof result.output === \"string\" ? result.output : \"\";\n if (!result.ok) {\n return {\n ...result,\n summary: \"Patch failed.\",\n files,\n };\n }\n const removedBackups = await removePatchBackupFiles(files, context);\n const backupNote = removedBackups.length > 0\n ? ` Removed patch backup file${removedBackups.length === 1 ? \"\" : \"s\"}: ${removedBackups.join(\", \")}.`\n : \"\";\n return {\n ok: true,\n summary: `Applied patch to ${files.length} file${files.length === 1 ? \"\" : \"s\"}.${backupNote}`,\n output,\n files,\n };\n },\n};\n\nexport const searchReplaceTool: TanyaTool = {\n name: \"search_replace\",\n description: \"Replace an exact string in a file. Fails if the string is not found or appears more times than expected.\",\n definition: {\n type: \"function\",\n function: {\n name: \"search_replace\",\n description: \"Replace an exact string in a file inside the workspace. Prefer this over apply_patch for targeted single-location edits. Fails if old_string is not found or appears more times than expected_count.\",\n parameters: {\n type: \"object\",\n properties: {\n path: { type: \"string\", description: \"File path relative to the workspace.\" },\n old_string: { type: \"string\", description: \"Exact string to find. Must be unique in the file unless expected_count is set.\" },\n new_string: { type: \"string\", description: \"Replacement string.\" },\n expected_count: { type: \"number\", description: \"How many occurrences to replace. Default 1. Use to allow replacing multiple occurrences.\" },\n },\n required: [\"path\", \"old_string\", \"new_string\"],\n additionalProperties: false,\n },\n },\n },\n async run(input, context) {\n const path = asString(input, \"path\");\n const oldString = asString(input, \"old_string\");\n const newString = asRecord(input).new_string;\n if (typeof newString !== \"string\") throw new Error(\"Missing string field: new_string\");\n const expectedCount = asOptionalNumber(input, \"expected_count\", 1);\n if (isProtectedLocalConfigPath(path)) return localPropertiesWriteError();\n let abs: string;\n try {\n abs = resolveInsideWorkspace(context.workspace, path);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n return { ok: false, summary: \"Path rejected by workspace safety checks.\", error: message };\n }\n let content: string;\n try {\n content = await readFile(abs, \"utf8\");\n } catch {\n return { ok: false, summary: `File not found: ${path}`, error: `Cannot read ${path}` };\n }\n const count = content.split(oldString).length - 1;\n if (count === 0) {\n return { ok: false, summary: \"old_string not found in file.\", error: `The exact string was not found in ${path}. Re-read the file and adjust old_string to match exactly.` };\n }\n if (count !== expectedCount) {\n return { ok: false, summary: `old_string appears ${count} time${count === 1 ? \"\" : \"s\"}, expected ${expectedCount}.`, error: `Found ${count} occurrence${count === 1 ? \"\" : \"s\"} in ${path}. Set expected_count: ${count} to replace all, or make old_string more specific.` };\n }\n const updated = content.split(oldString).join(newString);\n await writeFile(abs, updated, \"utf8\");\n const written = await readFile(abs, \"utf8\");\n const lines = written.split(\"\\n\");\n const lineCount = lines.length;\n const firstNewLine = newString.split(\"\\n\")[0] ?? \"\";\n const matchNeedle = firstNewLine.trim();\n const matchIdx = matchNeedle\n ? lines.findIndex((line) => line.includes(matchNeedle))\n : -1;\n const contextLines = matchIdx >= 0\n ? lines.slice(Math.max(0, matchIdx - 1), matchIdx + 3).join(\"\\n\")\n : \"\";\n return {\n ok: true,\n summary: `Replaced ${count} occurrence${count === 1 ? \"\" : \"s\"} in ${path} (${lineCount} lines).`,\n output: { path, count, lineCount, context: contextLines },\n files: [path],\n };\n },\n};\n\nexport const copyFileTool: TanyaTool = {\n name: \"copy_file\",\n description: \"Copy one file inside the workspace, including binary assets.\",\n definition: {\n type: \"function\",\n function: {\n name: \"copy_file\",\n description: \"Copy one file inside the workspace, including binary assets.\",\n parameters: {\n type: \"object\",\n properties: {\n source: { type: \"string\", description: \"Source path relative to the workspace.\" },\n destination: { type: \"string\", description: \"Destination path relative to the workspace.\" },\n overwrite: { type: \"boolean\", description: \"Overwrite destination if it exists. Default true.\" },\n },\n required: [\"source\", \"destination\"],\n additionalProperties: false,\n },\n },\n },\n async run(input, context) {\n const source = ensureRelativePath(asString(input, \"source\"));\n const destination = ensureRelativePath(asString(input, \"destination\"));\n const overwrite = asRecord(input).overwrite !== false;\n const sourceAbs = resolveInsideWorkspace(context.workspace, source);\n const destinationAbs = resolveInsideWorkspace(context.workspace, destination);\n await mkdir(dirname(destinationAbs), { recursive: true });\n await cp(sourceAbs, destinationAbs, { force: overwrite, errorOnExist: !overwrite });\n return { ok: true, summary: `Copied ${source} to ${destination}.`, output: { source, destination }, files: [destination] };\n },\n};\n\nexport const copyDirTool: TanyaTool = {\n name: \"copy_dir\",\n description: \"Copy a directory inside the workspace, including binary assets.\",\n definition: {\n type: \"function\",\n function: {\n name: \"copy_dir\",\n description: \"Copy a directory inside the workspace, including binary assets.\",\n parameters: {\n type: \"object\",\n properties: {\n source: { type: \"string\", description: \"Source directory relative to the workspace.\" },\n destination: { type: \"string\", description: \"Destination directory relative to the workspace.\" },\n overwrite: { type: \"boolean\", description: \"Overwrite destination files if they exist. Default true.\" },\n },\n required: [\"source\", \"destination\"],\n additionalProperties: false,\n },\n },\n },\n async run(input, context) {\n const source = ensureRelativePath(asString(input, \"source\"));\n const destination = ensureRelativePath(asString(input, \"destination\"));\n const overwrite = asRecord(input).overwrite !== false;\n const sourceAbs = resolveInsideWorkspace(context.workspace, source);\n const destinationAbs = resolveInsideWorkspace(context.workspace, destination);\n await cp(sourceAbs, destinationAbs, { recursive: true, force: overwrite, errorOnExist: !overwrite });\n return { ok: true, summary: `Copied directory ${source} to ${destination}.`, output: { source, destination }, files: [destination] };\n },\n};\n\nfunction parseMarkdownApiRoutes(markdown: string): string[] {\n return [...new Set(\n [...markdown.matchAll(/`(?:GET|POST|PUT|PATCH|DELETE)\\s+([^`\\s]+)`/g)]\n .map((match) => String(match[1] ?? \"\").trim())\n .filter(Boolean),\n )].sort((a, b) => a.localeCompare(b));\n}\n\nexport const validateApiContractRoutesTool: TanyaTool = {\n name: \"validate_api_contract_routes\",\n description: \"Compare HTTP route slugs between two markdown API contract files inside the workspace.\",\n definition: {\n type: \"function\",\n function: {\n name: \"validate_api_contract_routes\",\n description: \"Compare HTTP route slugs between two markdown API contract files. Useful for backend/API_FEATURES.md vs brand/api_features.md.\",\n parameters: {\n type: \"object\",\n properties: {\n source: { type: \"string\", description: \"Canonical markdown contract path relative to the workspace.\" },\n target: { type: \"string\", description: \"Generated markdown contract path relative to the workspace.\" },\n },\n required: [\"source\", \"target\"],\n additionalProperties: false,\n },\n },\n },\n async run(input, context) {\n const source = ensureRelativePath(asString(input, \"source\"));\n const target = ensureRelativePath(asString(input, \"target\"));\n const sourceText = await readFile(resolveInsideWorkspace(context.workspace, source), \"utf8\");\n const targetText = await readFile(resolveInsideWorkspace(context.workspace, target), \"utf8\");\n const sourceRoutes = parseMarkdownApiRoutes(sourceText);\n const targetRoutes = parseMarkdownApiRoutes(targetText);\n const missing = sourceRoutes.filter((route) => !targetRoutes.includes(route));\n const extra = targetRoutes.filter((route) => !sourceRoutes.includes(route));\n const ok = missing.length === 0 && extra.length === 0;\n return {\n ok,\n summary: ok\n ? `API route contracts match (${sourceRoutes.length} route${sourceRoutes.length === 1 ? \"\" : \"s\"}).`\n : `API route contract mismatch: ${missing.length} missing, ${extra.length} extra.`,\n output: { source, target, sourceRoutes, targetRoutes, missing, extra },\n ...(ok ? {} : { error: `Missing: ${missing.join(\", \") || \"none\"}. Extra: ${extra.join(\", \") || \"none\"}.` }),\n };\n },\n};\n\nfunction numberFromGradle(text: string, name: string): number | null {\n const match = new RegExp(`${name}\\\\s*(?:=|\\\\()\\\\s*(\\\\d+)`, \"m\").exec(text);\n return match?.[1] ? Number.parseInt(match[1], 10) : null;\n}\n\nexport const validateAndroidProjectConfigTool: TanyaTool = {\n name: \"validate_android_project_config\",\n description: \"Validate Android Manifest launcher icon references and Gradle SDK levels.\",\n definition: {\n type: \"function\",\n function: {\n name: \"validate_android_project_config\",\n description: \"Validate AndroidManifest.xml launcher icon references and build.gradle(.kts) SDK levels.\",\n parameters: {\n type: \"object\",\n properties: {\n manifestPath: { type: \"string\", description: \"AndroidManifest.xml path relative to the workspace.\" },\n gradlePath: { type: \"string\", description: \"Module build.gradle or build.gradle.kts path relative to the workspace.\" },\n minCompileSdk: { type: \"number\", description: \"Minimum compileSdk. Default 35.\" },\n minTargetSdk: { type: \"number\", description: \"Minimum targetSdk. Default 35.\" },\n minSdk: { type: \"number\", description: \"Minimum minSdk. Default 26.\" },\n expectedIcon: { type: \"string\", description: \"Expected android:icon value. Default @mipmap/ic_launcher.\" },\n expectedRoundIcon: { type: \"string\", description: \"Expected android:roundIcon value. Default @mipmap/ic_launcher_round.\" },\n },\n required: [\"manifestPath\", \"gradlePath\"],\n additionalProperties: false,\n },\n },\n },\n async run(input, context) {\n const manifestPath = ensureRelativePath(asString(input, \"manifestPath\"));\n const gradlePath = ensureRelativePath(asString(input, \"gradlePath\"));\n const minCompileSdk = asOptionalNumber(input, \"minCompileSdk\", 35);\n const minTargetSdk = asOptionalNumber(input, \"minTargetSdk\", 35);\n const minSdk = asOptionalNumber(input, \"minSdk\", 26);\n const expectedIcon = asOptionalString(input, \"expectedIcon\") ?? \"@mipmap/ic_launcher\";\n const expectedRoundIcon = asOptionalString(input, \"expectedRoundIcon\") ?? \"@mipmap/ic_launcher_round\";\n const manifest = await readFile(resolveInsideWorkspace(context.workspace, manifestPath), \"utf8\");\n const gradle = await readFile(resolveInsideWorkspace(context.workspace, gradlePath), \"utf8\");\n const problems: string[] = [];\n\n if (!new RegExp(`android:icon=[\"']${expectedIcon.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\")}[\"']`).test(manifest)) {\n problems.push(`Manifest android:icon must be ${expectedIcon}.`);\n }\n if (!new RegExp(`android:roundIcon=[\"']${expectedRoundIcon.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\")}[\"']`).test(manifest)) {\n problems.push(`Manifest android:roundIcon must be ${expectedRoundIcon}.`);\n }\n\n const compileSdk = numberFromGradle(gradle, \"compileSdk\");\n const targetSdk = numberFromGradle(gradle, \"targetSdk\");\n const parsedMinSdk = numberFromGradle(gradle, \"minSdk\");\n if (compileSdk === null || compileSdk < minCompileSdk) problems.push(`compileSdk must be >= ${minCompileSdk}.`);\n if (targetSdk === null || targetSdk < minTargetSdk) problems.push(`targetSdk must be >= ${minTargetSdk}.`);\n if (parsedMinSdk === null || parsedMinSdk < minSdk) problems.push(`minSdk must be >= ${minSdk}.`);\n\n return {\n ok: problems.length === 0,\n summary: problems.length === 0 ? \"Android project config validated.\" : `Android project config has ${problems.length} problem${problems.length === 1 ? \"\" : \"s\"}.`,\n output: { manifestPath, gradlePath, compileSdk, targetSdk, minSdk: parsedMinSdk, problems },\n ...(problems.length > 0 ? { error: problems.join(\"; \") } : {}),\n };\n },\n};\n\nexport const validateAppleProjectFilesTool: TanyaTool = {\n name: \"validate_apple_project_files\",\n description: \"Validate basic Apple/Xcode project file presence and optional pbxproj references.\",\n definition: {\n type: \"function\",\n function: {\n name: \"validate_apple_project_files\",\n description: \"Validate Xcode project presence, required files/assets, and optional project.pbxproj references.\",\n parameters: {\n type: \"object\",\n properties: {\n xcodeprojPath: { type: \"string\", description: \"Optional .xcodeproj directory relative to the workspace.\" },\n requiredPaths: { type: \"array\", items: { type: \"string\" }, description: \"Files or directories that must exist relative to the workspace.\" },\n requireProjectReferences: { type: \"boolean\", description: \"Check project.pbxproj contains each required path basename. Default false.\" },\n },\n additionalProperties: false,\n },\n },\n },\n async run(input, context) {\n const record = asRecord(input);\n const xcodeprojPath = asOptionalString(input, \"xcodeprojPath\");\n const requiredPaths = Array.isArray(record.requiredPaths)\n ? record.requiredPaths.filter((value): value is string => typeof value === \"string\" && value.trim().length > 0)\n : [];\n const requireProjectReferences = record.requireProjectReferences === true;\n const problems: string[] = [];\n let pbxprojText = \"\";\n\n if (xcodeprojPath) {\n const projectDir = resolveInsideWorkspace(context.workspace, ensureRelativePath(xcodeprojPath));\n if (!existsSync(projectDir)) {\n problems.push(`Missing ${xcodeprojPath}.`);\n } else {\n const pbxprojPath = resolveInsideWorkspace(context.workspace, `${xcodeprojPath.replace(/\\/+$/, \"\")}/project.pbxproj`);\n if (existsSync(pbxprojPath)) pbxprojText = await readFile(pbxprojPath, \"utf8\");\n }\n }\n\n for (const requiredPath of requiredPaths) {\n const relPath = ensureRelativePath(requiredPath);\n if (!existsSync(resolveInsideWorkspace(context.workspace, relPath))) {\n problems.push(`Missing ${relPath}.`);\n }\n if (requireProjectReferences && pbxprojText) {\n const basename = relPath.split(\"/\").filter(Boolean).pop() ?? relPath;\n if (!pbxprojText.includes(basename)) problems.push(`project.pbxproj does not reference ${basename}.`);\n }\n }\n\n return {\n ok: problems.length === 0,\n summary: problems.length === 0 ? \"Apple project files validated.\" : `Apple project validation found ${problems.length} problem${problems.length === 1 ? \"\" : \"s\"}.`,\n output: { xcodeprojPath, requiredPaths, problems },\n ...(problems.length > 0 ? { error: problems.join(\"; \") } : {}),\n };\n },\n};\n\nexport const validateFastlaneConfigTool: TanyaTool = {\n name: \"validate_fastlane_config\",\n description: \"Validate Fastlane files, required lanes, required files, and optional forbidden files.\",\n definition: {\n type: \"function\",\n function: {\n name: \"validate_fastlane_config\",\n description: \"Validate a Fastlane setup by inspecting Fastfile lane names, required files, and forbidden files such as Gemfile.\",\n parameters: {\n type: \"object\",\n properties: {\n fastfilePath: { type: \"string\", description: \"Fastfile path relative to the workspace. Default fastlane/Fastfile.\" },\n requiredLanes: { type: \"array\", items: { type: \"string\" }, description: \"Lane names that must exist, without the lane : prefix.\" },\n requiredFiles: { type: \"array\", items: { type: \"string\" }, description: \"Files that must exist relative to the workspace.\" },\n forbiddenFiles: { type: \"array\", items: { type: \"string\" }, description: \"Files that must not exist relative to the workspace.\" },\n requireProjectDirAnchoredToDirname: { type: \"boolean\", description: \"Require File.expand_path(\\\"..\\\", __dir__) in Fastfile. Default false.\" },\n },\n additionalProperties: false,\n },\n },\n },\n async run(input, context) {\n const record = asRecord(input);\n const fastfilePath = asOptionalString(input, \"fastfilePath\") ?? \"fastlane/Fastfile\";\n const requiredLanes = Array.isArray(record.requiredLanes)\n ? record.requiredLanes.filter((value): value is string => typeof value === \"string\" && value.trim().length > 0).map((value) => value.trim())\n : [];\n const requiredFiles = Array.isArray(record.requiredFiles)\n ? record.requiredFiles.filter((value): value is string => typeof value === \"string\" && value.trim().length > 0).map((value) => value.trim())\n : [];\n const forbiddenFiles = Array.isArray(record.forbiddenFiles)\n ? record.forbiddenFiles.filter((value): value is string => typeof value === \"string\" && value.trim().length > 0).map((value) => value.trim())\n : [];\n const requireProjectDirAnchoredToDirname = record.requireProjectDirAnchoredToDirname === true;\n const problems: string[] = [];\n let fastfile = \"\";\n\n const fastfileRel = ensureRelativePath(fastfilePath);\n const fastfileAbs = resolveInsideWorkspace(context.workspace, fastfileRel);\n if (!existsSync(fastfileAbs)) {\n problems.push(`Missing ${fastfileRel}.`);\n } else {\n fastfile = await readFile(fastfileAbs, \"utf8\");\n }\n\n const lanes = [...new Set([...fastfile.matchAll(/^\\s*lane\\s+:([A-Za-z0-9_]+)\\s+do\\b/gm)].map((match) => String(match[1] ?? \"\")))].sort();\n const platformLanes: string[] = [];\n let currentPlatform: string | null = null;\n for (const line of fastfile.split(/\\r?\\n/)) {\n const platformMatch = /^\\s*platform\\s+:([A-Za-z0-9_]+)\\s+do\\b/.exec(line);\n if (platformMatch) currentPlatform = platformMatch[1] ?? null;\n const laneMatch = /^\\s*lane\\s+:([A-Za-z0-9_]+)\\s+do\\b/.exec(line);\n if (currentPlatform && laneMatch?.[1]) platformLanes.push(`${currentPlatform} ${laneMatch[1]}`);\n }\n platformLanes.sort();\n for (const lane of requiredLanes) {\n const normalized = lane.replace(/^:/, \"\").replace(/[:.]/g, \" \").replace(/\\s+/g, \" \").trim();\n if (normalized.includes(\" \")) {\n if (!platformLanes.includes(normalized)) problems.push(`Missing Fastlane platform lane ${normalized}.`);\n } else if (!lanes.includes(normalized)) {\n problems.push(`Missing Fastlane lane :${normalized}.`);\n }\n }\n if (requiredLanes.map((lane) => lane.replace(/^:/, \"\").trim()).includes(\"bump\")) {\n const lines = fastfile.split(/\\r?\\n/);\n const bumpIndex = lines.findIndex((line) => /^\\s*lane\\s+:bump\\s+do\\b/.test(line));\n if (bumpIndex >= 0) {\n const firstBodyLine = lines.slice(bumpIndex + 1).find((line) => line.trim() && !line.trim().startsWith(\"#\"))?.trim() ?? \"\";\n if (/^if\\s+options\\[:version\\]/.test(firstBodyLine)) {\n problems.push(\"Fastlane lane :bump must increment versionCode by default; options[:version] may only control versionName.\");\n }\n }\n }\n if (requireProjectDirAnchoredToDirname && !fastfile.includes('File.expand_path(\"..\", __dir__)')) {\n problems.push('Fastfile must anchor Gradle project_dir with File.expand_path(\"..\", __dir__).');\n }\n for (const file of requiredFiles) {\n const relPath = ensureRelativePath(file);\n if (!existsSync(resolveInsideWorkspace(context.workspace, relPath))) problems.push(`Missing ${relPath}.`);\n }\n for (const file of forbiddenFiles) {\n const relPath = ensureRelativePath(file);\n if (existsSync(resolveInsideWorkspace(context.workspace, relPath))) problems.push(`Forbidden file exists: ${relPath}.`);\n }\n\n return {\n ok: problems.length === 0,\n summary: problems.length === 0 ? `Fastlane config validated (${lanes.length} lane${lanes.length === 1 ? \"\" : \"s\"}).` : `Fastlane config has ${problems.length} problem${problems.length === 1 ? \"\" : \"s\"}.`,\n output: { fastfilePath: fastfileRel, lanes, platformLanes, requiredLanes, requiredFiles, forbiddenFiles, problems },\n ...(problems.length > 0 ? { error: problems.join(\"; \") } : {}),\n };\n },\n};\n\nexport const validatePrismaSchemaTool: TanyaTool = {\n name: \"validate_prisma_schema\",\n description: \"Validate Prisma schema model presence and forbidden drift names.\",\n definition: {\n type: \"function\",\n function: {\n name: \"validate_prisma_schema\",\n description: \"Validate required and forbidden Prisma model names in schema.prisma.\",\n parameters: {\n type: \"object\",\n properties: {\n schemaPath: { type: \"string\", description: \"Prisma schema path relative to the workspace. Default prisma/schema.prisma.\" },\n requiredModels: { type: \"array\", items: { type: \"string\" }, description: \"Model names that must exist.\" },\n forbiddenModels: { type: \"array\", items: { type: \"string\" }, description: \"Model names that must not exist.\" },\n },\n additionalProperties: false,\n },\n },\n },\n async run(input, context) {\n const record = asRecord(input);\n const schemaPath = ensureRelativePath(asOptionalString(input, \"schemaPath\") ?? \"prisma/schema.prisma\");\n const requiredModels = Array.isArray(record.requiredModels)\n ? record.requiredModels.filter((value): value is string => typeof value === \"string\" && value.trim().length > 0)\n : [];\n const forbiddenModels = Array.isArray(record.forbiddenModels)\n ? record.forbiddenModels.filter((value): value is string => typeof value === \"string\" && value.trim().length > 0)\n : [];\n const schema = await readFile(resolveInsideWorkspace(context.workspace, schemaPath), \"utf8\");\n const models = [...schema.matchAll(/^\\s*model\\s+([A-Za-z][A-Za-z0-9_]*)\\s*\\{/gm)].map((match) => String(match[1]));\n const problems: string[] = [];\n for (const model of requiredModels) if (!models.includes(model)) problems.push(`Missing model ${model}.`);\n for (const model of forbiddenModels) if (models.includes(model)) problems.push(`Forbidden model ${model} is present.`);\n const openModelBlocks = (schema.match(/\\bmodel\\s+[A-Za-z][A-Za-z0-9_]*\\s*\\{/g) ?? []).length;\n const closeBraces = (schema.match(/\\}/g) ?? []).length;\n if (closeBraces < openModelBlocks) problems.push(\"Schema appears to have an unclosed model block.\");\n\n return {\n ok: problems.length === 0,\n summary: problems.length === 0 ? `Prisma schema validated (${models.length} model${models.length === 1 ? \"\" : \"s\"}).` : `Prisma schema has ${problems.length} problem${problems.length === 1 ? \"\" : \"s\"}.`,\n output: { schemaPath, models, problems },\n ...(problems.length > 0 ? { error: problems.join(\"; \") } : {}),\n };\n },\n};\n\nexport const applyArtifactTool: TanyaTool = {\n name: \"apply_artifact\",\n description: \"Copy a materialized artifact file or directory to a target path inside the workspace.\",\n definition: {\n type: \"function\",\n function: {\n name: \"apply_artifact\",\n description: \"Apply a local materialized artifact by copying it to a target path. Use after reading an artifact that should become the starting point for an implementation.\",\n parameters: {\n type: \"object\",\n properties: {\n artifactPath: { type: \"string\", description: \"Materialized artifact path relative to the workspace, for example .tania/artifacts/ios/Foo.swift.\" },\n targetPath: { type: \"string\", description: \"Target file or directory path relative to the workspace.\" },\n overwrite: { type: \"boolean\", description: \"Overwrite target if it exists. Default true.\" },\n },\n required: [\"artifactPath\", \"targetPath\"],\n additionalProperties: false,\n },\n },\n },\n async run(input, context) {\n const artifactPath = ensureRelativePath(asString(input, \"artifactPath\"));\n const targetPath = ensureRelativePath(asString(input, \"targetPath\"));\n if (isProtectedLocalConfigPath(targetPath)) return localPropertiesWriteError();\n const overwrite = asRecord(input).overwrite !== false;\n const sourceAbs = resolveInsideWorkspace(context.workspace, artifactPath);\n const targetAbs = resolveInsideWorkspace(context.workspace, targetPath);\n await mkdir(dirname(targetAbs), { recursive: true });\n await cp(sourceAbs, targetAbs, { recursive: true, force: overwrite, errorOnExist: !overwrite });\n return {\n ok: true,\n summary: `Applied artifact ${artifactPath} to ${targetPath}.`,\n output: { artifactPath, targetPath },\n files: [targetPath],\n };\n },\n};\n\nfunction inferIosSplashAssetSetDir(viewPath: string): string {\n const viewDir = dirname(viewPath).replace(/\\\\/g, \"/\");\n return `${viewDir}/Assets.xcassets/SplashIcon.imageset`;\n}\n\nasync function firstExistingWorkspacePath(context: ToolContext, candidates: string[]): Promise<string | null> {\n for (const candidate of candidates) {\n const clean = candidate.replace(/\\\\/g, \"/\").replace(/^\\/+/, \"\");\n const abs = resolveInsideWorkspace(context.workspace, clean);\n if (await pathExists(abs)) return clean;\n }\n return null;\n}\n\nasync function findLargestAppIconPng(context: ToolContext, viewPath: string): Promise<string | null> {\n const viewDir = dirname(viewPath).replace(/\\\\/g, \"/\");\n const appIconDir = `${viewDir}/Assets.xcassets/AppIcon.appiconset`;\n const appIconAbs = resolveInsideWorkspace(context.workspace, appIconDir);\n if (!existsSync(appIconAbs)) return null;\n const pngs = readdirSync(appIconAbs, { withFileTypes: true })\n .filter((entry) => entry.isFile() && /\\.png$/i.test(entry.name))\n .map((entry) => `${appIconDir}/${entry.name}`);\n if (pngs.length === 0) return null;\n const score = (path: string) => {\n const size = path.match(/(\\d{2,4})x\\1|-(\\d{2,4})\\.png|@(\\d)x/i);\n return Number(size?.[1] ?? size?.[2] ?? size?.[3] ?? 0);\n };\n return pngs.sort((a, b) => score(b) - score(a))[0] ?? null;\n}\n\nasync function createFallbackSplashIconPng(destinationAbs: string, brandHex: string, appName: string): Promise<void> {\n const label = appName\n .split(/\\s+/)\n .map((part) => part[0])\n .join(\"\")\n .slice(0, 2)\n .toUpperCase() || \"A\";\n const safeLabel = label.replace(/[<>&\"]/g, \"\");\n const safeBrand = /^#[0-9a-f]{6}$/i.test(brandHex) ? brandHex : \"#000000\";\n const svg = [\n `<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"1024\" height=\"1024\" viewBox=\"0 0 1024 1024\">`,\n `<rect width=\"1024\" height=\"1024\" rx=\"220\" fill=\"${safeBrand}\"/>`,\n `<circle cx=\"512\" cy=\"512\" r=\"312\" fill=\"rgba(0,0,0,0.28)\"/>`,\n `<circle cx=\"512\" cy=\"512\" r=\"244\" fill=\"rgba(255,255,255,0.12)\"/>`,\n `<text x=\"512\" y=\"570\" text-anchor=\"middle\" font-family=\"Arial, Helvetica, sans-serif\" font-size=\"260\" font-weight=\"800\" fill=\"#ffffff\">${safeLabel}</text>`,\n `</svg>`,\n ].join(\"\");\n await mkdir(dirname(destinationAbs), { recursive: true });\n await sharp(Buffer.from(svg)).png({ force: true }).toFile(destinationAbs);\n}\n\nexport const createIosSplashTool: TanyaTool = {\n name: \"create_ios_splash\",\n description: \"Create a standard SwiftUI iOS splash view and SplashIcon asset from a source image or deterministic fallback.\",\n definition: {\n type: \"function\",\n function: {\n name: \"create_ios_splash\",\n description: \"Create SplashScreenView.swift and Assets.xcassets/SplashIcon.imageset resources using explicit brand color.\",\n parameters: {\n type: \"object\",\n properties: {\n viewPath: { type: \"string\", description: \"Destination Swift file, for example CosaNostra/SplashScreenView.swift.\" },\n assetSetDir: { type: \"string\", description: \"Optional SplashIcon.imageset directory relative to workspace. Defaults beside viewPath under Assets.xcassets.\" },\n sourceIcon: { type: \"string\", description: \"Optional source image path relative to workspace. If omitted, Tanya searches common brand/AppIcon paths, then creates a fallback PNG.\" },\n appName: { type: \"string\", description: \"Optional app name shown below the icon.\" },\n brandHex: { type: \"string\", description: \"Brand background color, for example #A52A2A. Default #000000.\" },\n durationMs: { type: \"number\", description: \"Splash delay in milliseconds. Default 1200.\" },\n },\n required: [\"viewPath\"],\n additionalProperties: false,\n },\n },\n },\n async run(input, context) {\n const viewPath = ensureRelativePath(asString(input, \"viewPath\"));\n const assetSetDir = (asOptionalString(input, \"assetSetDir\") ?? inferIosSplashAssetSetDir(viewPath)).replace(/\\/+$/, \"\");\n const sourceIcon = asOptionalString(input, \"sourceIcon\");\n const appName = asOptionalString(input, \"appName\") ?? \"App\";\n const brandHex = asOptionalString(input, \"brandHex\") ?? \"#000000\";\n const durationMs = Math.max(0, Math.round(asOptionalNumber(input, \"durationMs\", 1200)));\n const durationNs = durationMs * 1_000_000;\n const rgb = brandHex.replace(\"#\", \"\").match(/.{1,2}/g)?.slice(0, 3).map((part) => Number.parseInt(part, 16)) ?? [0, 0, 0];\n const view = [\n \"import SwiftUI\",\n \"\",\n \"struct SplashScreenView<Content: View>: View {\",\n \" @State private var isReady = false\",\n \" @State private var iconVisible = false\",\n \" let content: () -> Content\",\n \"\",\n \" private let brandColor = Color(\",\n ` red: ${rgb[0] ?? 0} / 255,`,\n ` green: ${rgb[1] ?? 0} / 255,`,\n ` blue: ${rgb[2] ?? 0} / 255`,\n \" )\",\n \"\",\n \" var body: some View {\",\n \" ZStack {\",\n \" if isReady {\",\n \" content()\",\n \" } else {\",\n \" brandColor\",\n \" .ignoresSafeArea()\",\n \" .overlay(\",\n \" Image(\\\"SplashIcon\\\")\",\n \" .resizable()\",\n \" .scaledToFit()\",\n \" .frame(width: 120, height: 120)\",\n \" .opacity(iconVisible ? 1 : 0)\",\n \" .animation(.easeOut(duration: 0.6), value: iconVisible)\",\n \" .accessibilityLabel(\\\"\" + appName.replace(/\"/g, \"\\\\\\\"\") + \"\\\")\",\n \" )\",\n \" }\",\n \" }\",\n \" .onAppear {\",\n \" iconVisible = true\",\n \" Task {\",\n ` try? await Task.sleep(nanoseconds: ${durationNs})`,\n \" isReady = true\",\n \" }\",\n \" }\",\n \" }\",\n \"}\",\n \"\",\n ].join(\"\\n\");\n\n const viewAbs = resolveInsideWorkspace(context.workspace, viewPath);\n await mkdir(dirname(viewAbs), { recursive: true });\n await writeFile(viewAbs, view, \"utf8\");\n const files = [viewPath];\n\n const cleanAssetSetDir = ensureRelativePath(assetSetDir);\n const iconPath = `${cleanAssetSetDir}/SplashIcon.png`;\n const resolvedSourceIcon = sourceIcon\n ? sourceIcon\n : await firstExistingWorkspacePath(context, [\n \"brand/icons/icon-1024.png\",\n \"brand/icons/ios/AppStore-1024x1024.png\",\n \".tania/context/brand/icons/icon-1024.png\",\n \".tania/context/brand/icons/ios/AppStore-1024x1024.png\",\n ]) ?? await findLargestAppIconPng(context, viewPath);\n\n if (resolvedSourceIcon) {\n const sourceAbs = isAbsolute(resolvedSourceIcon)\n ? resolvedSourceIcon\n : resolveInsideWorkspace(context.workspace, ensureRelativePath(resolvedSourceIcon));\n if (!existsSync(sourceAbs)) {\n return { ok: false, summary: \"Source splash icon not found.\", error: `Missing source icon: ${resolvedSourceIcon}` };\n }\n await mkdir(dirname(resolveInsideWorkspace(context.workspace, iconPath)), { recursive: true });\n await sharp(sourceAbs)\n .resize(1024, 1024, { fit: \"contain\", background: { r: 0, g: 0, b: 0, alpha: 0 } })\n .png()\n .toFile(resolveInsideWorkspace(context.workspace, iconPath));\n } else {\n await createFallbackSplashIconPng(resolveInsideWorkspace(context.workspace, iconPath), brandHex, appName);\n }\n const contentsPath = `${cleanAssetSetDir}/Contents.json`;\n await mkdir(dirname(resolveInsideWorkspace(context.workspace, contentsPath)), { recursive: true });\n await writeFile(resolveInsideWorkspace(context.workspace, contentsPath), `${JSON.stringify({\n images: [{ idiom: \"universal\", filename: \"SplashIcon.png\", scale: \"1x\" }],\n info: { author: \"xcode\", version: 1 },\n }, null, 2)}\\n`, \"utf8\");\n files.push(iconPath, contentsPath);\n\n return { ok: true, summary: `Created iOS splash view and SplashIcon asset at ${viewPath}.`, output: { viewPath, assetSetDir, sourceIcon: resolvedSourceIcon ?? \"generated-fallback\", brandHex, durationMs, appName }, files };\n },\n};\n\nexport const createAndroidSplashTool: TanyaTool = {\n name: \"create_android_splash\",\n description: \"Create Android SplashScreen API resources and optional drawable icon from a source image.\",\n definition: {\n type: \"function\",\n function: {\n name: \"create_android_splash\",\n description: \"Create splash_theme.xml and a drawable PNG for Android SplashScreen API wiring.\",\n parameters: {\n type: \"object\",\n properties: {\n resDir: { type: \"string\", description: \"Android res directory, for example app/src/main/res.\" },\n sourceIcon: { type: \"string\", description: \"Optional source image path relative to workspace.\" },\n brandHex: { type: \"string\", description: \"Brand background color. Default #000000.\" },\n themeName: { type: \"string\", description: \"Splash theme name. Default Theme.App.Starting.\" },\n iconName: { type: \"string\", description: \"Drawable icon resource name. Default ic_splash_logo.\" },\n },\n required: [\"resDir\"],\n additionalProperties: false,\n },\n },\n },\n async run(input, context) {\n const resDir = ensureRelativePath(asString(input, \"resDir\")).replace(/\\/+$/, \"\");\n const sourceIcon = asOptionalString(input, \"sourceIcon\");\n const brandHex = asOptionalString(input, \"brandHex\") ?? \"#000000\";\n const themeName = asOptionalString(input, \"themeName\") ?? \"Theme.App.Starting\";\n const iconName = (asOptionalString(input, \"iconName\") ?? \"ic_splash_logo\").replace(/[^a-z0-9_]/gi, \"_\").toLowerCase();\n const valuesPath = `${resDir}/values/splash_theme.xml`;\n const drawablePath = `${resDir}/drawable/${iconName}.png`;\n const xml = [\n \"<?xml version=\\\"1.0\\\" encoding=\\\"utf-8\\\"?>\",\n \"<resources>\",\n ` <style name=\"${themeName}\" parent=\"Theme.SplashScreen\">`,\n ` <item name=\"windowSplashScreenBackground\">${brandHex}</item>`,\n ` <item name=\"windowSplashScreenAnimatedIcon\">@drawable/${iconName}</item>`,\n \" <item name=\\\"postSplashScreenTheme\\\">@style/Theme.App</item>\",\n \" </style>\",\n \"</resources>\",\n \"\",\n ].join(\"\\n\");\n await mkdir(dirname(resolveInsideWorkspace(context.workspace, valuesPath)), { recursive: true });\n await writeFile(resolveInsideWorkspace(context.workspace, valuesPath), xml, \"utf8\");\n const files = [valuesPath];\n if (sourceIcon) {\n const resizeResult = await resizeImageTool.run(\n { source: ensureRelativePath(sourceIcon), destination: drawablePath, width: 432, height: 432, background: \"transparent\" },\n context,\n );\n if (!resizeResult.ok) return resizeResult;\n files.push(drawablePath);\n }\n return { ok: true, summary: `Created Android splash resources in ${resDir}.`, output: { resDir, themeName, iconName, brandHex }, files };\n },\n};\n\nexport const generateAppIconsTool: TanyaTool = {\n name: \"generate_app_icons\",\n description: \"Generate Apple and/or Android app icon resources from one source image.\",\n definition: {\n type: \"function\",\n function: {\n name: \"generate_app_icons\",\n description: \"Generate app icon resources for Apple AppIcon.appiconset and Android launcher icons.\",\n parameters: {\n type: \"object\",\n properties: {\n source: { type: \"string\", description: \"Source image path relative to workspace. Prefer 1024x1024 PNG.\" },\n appleOutputDir: { type: \"string\", description: \"Optional AppIcon.appiconset output directory.\" },\n applePlatforms: { type: \"array\", items: { type: \"string\", enum: [\"ios\", \"macos\"] }, description: \"Apple platforms. Default ['ios', 'macos'].\" },\n androidResDir: { type: \"string\", description: \"Optional Android res output directory.\" },\n background: { type: \"string\", description: \"Background color used to remove alpha. Default #ffffff.\" },\n },\n required: [\"source\"],\n additionalProperties: false,\n },\n },\n },\n async run(input, context) {\n const source = ensureRelativePath(asString(input, \"source\"));\n const appleOutputDir = asOptionalString(input, \"appleOutputDir\");\n const androidResDir = asOptionalString(input, \"androidResDir\");\n const background = asOptionalString(input, \"background\") ?? \"#ffffff\";\n const rawApplePlatforms = asRecord(input).applePlatforms;\n const applePlatforms = Array.isArray(rawApplePlatforms)\n ? rawApplePlatforms.filter((item): item is string => typeof item === \"string\" && item.trim().length > 0)\n : [\"ios\", \"macos\"];\n const files: string[] = [];\n const outputs: Record<string, unknown> = {};\n\n if (appleOutputDir) {\n const result = await createAppleAppIconSetTool.run({ source, outputDir: ensureRelativePath(appleOutputDir), platforms: applePlatforms, background }, context);\n if (!result.ok) return result;\n files.push(...(result.files ?? []));\n outputs.apple = result.output;\n }\n if (androidResDir) {\n const result = await createAndroidLauncherIconSetTool.run({ source, resDir: ensureRelativePath(androidResDir), background }, context);\n if (!result.ok) return result;\n files.push(...(result.files ?? []));\n outputs.android = result.output;\n }\n if (!appleOutputDir && !androidResDir) {\n return { ok: false, summary: \"No app icon output selected.\", error: \"Provide appleOutputDir, androidResDir, or both.\" };\n }\n\n return { ok: true, summary: `Generated ${files.length} app icon resource file${files.length === 1 ? \"\" : \"s\"}.`, output: outputs, files };\n },\n};\n\nfunction packageToDir(packageName: string): string {\n return packageName.split(\".\").map((part) => part.replace(/[^A-Za-z0-9_]/g, \"\")).filter(Boolean).join(\"/\");\n}\n\nfunction kotlinIdentifier(input: string, fallback: string): string {\n const cleaned = input.replace(/[^A-Za-z0-9_]/g, \"\").replace(/^[0-9]+/, \"\");\n return cleaned || fallback;\n}\n\nfunction addLineBeforeClosingPluginsBlock(gradle: string, line: string): string {\n if (gradle.includes(line)) return gradle;\n return gradle.replace(/plugins\\s*\\{([\\s\\S]*?)\\n\\}/, (match, body) => `plugins {${body}\\n ${line}\\n}`);\n}\n\nfunction addDependencyLine(gradle: string, line: string): string {\n if (gradle.includes(line)) return gradle;\n return gradle.replace(/dependencies\\s*\\{/, `dependencies {\\n ${line}`);\n}\n\nasync function maybePatchAndroidGradle(context: ToolContext, rootGradlePath: string, moduleGradlePath: string): Promise<string[]> {\n const files: string[] = [];\n const rootAbs = resolveInsideWorkspace(context.workspace, rootGradlePath);\n if (existsSync(rootAbs)) {\n const rootGradle = await readFile(rootAbs, \"utf8\");\n const nextRootGradle = addLineBeforeClosingPluginsBlock(rootGradle, \"id(\\\"com.google.devtools.ksp\\\") version \\\"1.9.24-1.0.20\\\" apply false\");\n if (nextRootGradle !== rootGradle) {\n await writeFile(rootAbs, nextRootGradle, \"utf8\");\n files.push(rootGradlePath);\n }\n }\n\n const moduleAbs = resolveInsideWorkspace(context.workspace, moduleGradlePath);\n if (existsSync(moduleAbs)) {\n let moduleGradle = await readFile(moduleAbs, \"utf8\");\n const before = moduleGradle;\n moduleGradle = addLineBeforeClosingPluginsBlock(moduleGradle, \"id(\\\"com.google.devtools.ksp\\\")\");\n for (const dependency of [\n \"implementation(\\\"androidx.navigation:navigation-compose:2.8.3\\\")\",\n \"implementation(\\\"androidx.compose.material:material-icons-extended\\\")\",\n \"implementation(\\\"androidx.room:room-runtime:2.6.1\\\")\",\n \"implementation(\\\"androidx.room:room-ktx:2.6.1\\\")\",\n \"ksp(\\\"androidx.room:room-compiler:2.6.1\\\")\",\n ]) {\n moduleGradle = addDependencyLine(moduleGradle, dependency);\n }\n if (moduleGradle !== before) {\n await writeFile(moduleAbs, moduleGradle, \"utf8\");\n files.push(moduleGradlePath);\n }\n }\n return files;\n}\n\nexport const createAndroidFoundationTool: TanyaTool = {\n name: \"create_android_foundation\",\n description: \"Create a generic Kotlin/Compose Android foundation with Material 3 theme, Navigation Compose, Room, and base UI states.\",\n definition: {\n type: \"function\",\n function: {\n name: \"create_android_foundation\",\n description: \"Create deterministic Android foundation files for a Kotlin/Compose app. Optionally updates Gradle with Navigation Compose and Room/KSP dependencies.\",\n parameters: {\n type: \"object\",\n properties: {\n packageName: { type: \"string\", description: \"Android package name, for example com.example.app.\" },\n appName: { type: \"string\", description: \"Human app name. Default App.\" },\n sourceRoot: { type: \"string\", description: \"Kotlin source root. Default app/src/main/java.\" },\n rootGradlePath: { type: \"string\", description: \"Root build.gradle.kts path. Default build.gradle.kts.\" },\n moduleGradlePath: { type: \"string\", description: \"App module build.gradle.kts path. Default app/build.gradle.kts.\" },\n brandPrimaryHex: { type: \"string\", description: \"Primary brand color, for example #A52A2A. Default #A52A2A.\" },\n brandSecondaryHex: { type: \"string\", description: \"Secondary brand color. Default #2D3748.\" },\n updateGradle: { type: \"boolean\", description: \"Update Gradle plugins/dependencies. Default true.\" },\n preserveExisting: { type: \"boolean\", description: \"Preserve existing foundation source files instead of overwriting them. Default true.\" },\n overwriteExisting: { type: \"boolean\", description: \"Overwrite existing foundation source files. Default false.\" },\n },\n required: [\"packageName\"],\n additionalProperties: false,\n },\n },\n },\n async run(input, context) {\n const packageName = asString(input, \"packageName\").trim();\n const appName = asOptionalString(input, \"appName\") ?? \"App\";\n const sourceRoot = ensureRelativePath(asOptionalString(input, \"sourceRoot\") ?? \"app/src/main/java\").replace(/\\/+$/, \"\");\n const rootGradlePath = ensureRelativePath(asOptionalString(input, \"rootGradlePath\") ?? \"build.gradle.kts\");\n const moduleGradlePath = ensureRelativePath(asOptionalString(input, \"moduleGradlePath\") ?? \"app/build.gradle.kts\");\n const brandPrimaryHex = (asOptionalString(input, \"brandPrimaryHex\") ?? \"#A52A2A\").replace(/^#?/, \"0xFF\");\n const brandSecondaryHex = (asOptionalString(input, \"brandSecondaryHex\") ?? \"#2D3748\").replace(/^#?/, \"0xFF\");\n const updateGradle = asOptionalBoolean(input, \"updateGradle\", true);\n const overwriteExisting = asOptionalBoolean(input, \"overwriteExisting\", false);\n const preserveExisting = overwriteExisting ? false : asOptionalBoolean(input, \"preserveExisting\", true);\n const packageDir = packageToDir(packageName);\n if (!packageDir) return { ok: false, summary: \"Invalid package name.\", error: \"packageName must contain at least one valid package segment.\" };\n\n const classPrefix = kotlinIdentifier(appName, \"App\");\n const baseDir = `${sourceRoot}/${packageDir}`;\n const files: string[] = [];\n const outputs: Array<[string, string]> = [\n [`${baseDir}/ui/theme/AppTheme.kt`, buildAndroidThemeFile(packageName, brandPrimaryHex, brandSecondaryHex)],\n [`${baseDir}/navigation/AppNavigation.kt`, buildAndroidNavigationFile(packageName)],\n [`${baseDir}/data/AppDatabase.kt`, buildAndroidDatabaseFile(packageName, classPrefix)],\n [`${baseDir}/ui/components/FoundationStates.kt`, buildAndroidFoundationStatesFile(packageName)],\n ];\n\n for (const [path, content] of outputs) {\n const target = resolveInsideWorkspace(context.workspace, path);\n if (preserveExisting && existsSync(target)) continue;\n await mkdir(dirname(target), { recursive: true });\n await writeFile(target, content, \"utf8\");\n files.push(path);\n }\n if (updateGradle) files.push(...await maybePatchAndroidGradle(context, rootGradlePath, moduleGradlePath));\n\n return {\n ok: true,\n summary: preserveExisting\n ? `Created missing Android foundation files for ${packageName}; preserved existing source files.`\n : `Created Android foundation for ${packageName}.`,\n output: { packageName, appName, sourceRoot, updateGradle, preserveExisting },\n files,\n };\n },\n};\n\nfunction buildAndroidThemeFile(packageName: string, brandPrimaryHex: string, brandSecondaryHex: string): string {\n return [\n `package ${packageName}.ui.theme`,\n \"\",\n \"import android.os.Build\",\n \"import androidx.compose.foundation.isSystemInDarkTheme\",\n \"import androidx.compose.material3.MaterialTheme\",\n \"import androidx.compose.material3.Typography\",\n \"import androidx.compose.material3.darkColorScheme\",\n \"import androidx.compose.material3.dynamicDarkColorScheme\",\n \"import androidx.compose.material3.dynamicLightColorScheme\",\n \"import androidx.compose.material3.lightColorScheme\",\n \"import androidx.compose.runtime.Composable\",\n \"import androidx.compose.ui.graphics.Color\",\n \"import androidx.compose.ui.platform.LocalContext\",\n \"\",\n \"object BrandColors {\",\n ` val Primary = Color(${brandPrimaryHex})`,\n ` val Secondary = Color(${brandSecondaryHex})`,\n \" val Background = Color(0xFF0B0B0F)\",\n \" val Surface = Color(0xFF16161D)\",\n \" val OnPrimary = Color.White\",\n \" val OnBackground = Color(0xFFF8FAFC)\",\n \" val OnSurface = Color(0xFFE5E7EB)\",\n \"}\",\n \"\",\n \"private val DarkColors = darkColorScheme(\",\n \" primary = BrandColors.Primary,\",\n \" secondary = BrandColors.Secondary,\",\n \" background = BrandColors.Background,\",\n \" surface = BrandColors.Surface,\",\n \" onPrimary = BrandColors.OnPrimary,\",\n \" onBackground = BrandColors.OnBackground,\",\n \" onSurface = BrandColors.OnSurface,\",\n \")\",\n \"\",\n \"private val LightColors = lightColorScheme(\",\n \" primary = BrandColors.Primary,\",\n \" secondary = BrandColors.Secondary,\",\n \")\",\n \"\",\n \"@Composable\",\n \"fun AppTheme(\",\n \" darkTheme: Boolean = isSystemInDarkTheme(),\",\n \" dynamicColor: Boolean = false,\",\n \" content: @Composable () -> Unit,\",\n \") {\",\n \" val colorScheme = when {\",\n \" dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> {\",\n \" val context = LocalContext.current\",\n \" if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context)\",\n \" }\",\n \" darkTheme -> DarkColors\",\n \" else -> LightColors\",\n \" }\",\n \"\",\n \" MaterialTheme(\",\n \" colorScheme = colorScheme,\",\n \" typography = Typography(),\",\n \" content = content,\",\n \" )\",\n \"}\",\n \"\",\n ].join(\"\\n\");\n}\n\nfunction buildAndroidNavigationFile(packageName: string): string {\n return [\n `package ${packageName}.navigation`,\n \"\",\n \"import androidx.compose.foundation.layout.padding\",\n \"import androidx.compose.material.icons.Icons\",\n \"import androidx.compose.material.icons.filled.Home\",\n \"import androidx.compose.material.icons.filled.List\",\n \"import androidx.compose.material.icons.filled.Settings\",\n \"import androidx.compose.material3.Icon\",\n \"import androidx.compose.material3.NavigationBar\",\n \"import androidx.compose.material3.NavigationBarItem\",\n \"import androidx.compose.material3.Scaffold\",\n \"import androidx.compose.material3.Text\",\n \"import androidx.compose.runtime.Composable\",\n \"import androidx.compose.runtime.getValue\",\n \"import androidx.compose.ui.Modifier\",\n \"import androidx.compose.ui.graphics.vector.ImageVector\",\n \"import androidx.navigation.NavHostController\",\n \"import androidx.navigation.compose.NavHost\",\n \"import androidx.navigation.compose.composable\",\n \"import androidx.navigation.compose.currentBackStackEntryAsState\",\n \"import androidx.navigation.compose.rememberNavController\",\n `import ${packageName}.ui.components.EmptyState`,\n \"\",\n \"sealed class AppRoute(val path: String, val label: String, val icon: ImageVector) {\",\n \" data object Home : AppRoute(\\\"home\\\", \\\"Home\\\", Icons.Filled.Home)\",\n \" data object Features : AppRoute(\\\"features\\\", \\\"Features\\\", Icons.Filled.List)\",\n \" data object Settings : AppRoute(\\\"settings\\\", \\\"Settings\\\", Icons.Filled.Settings)\",\n \"}\",\n \"\",\n \"private val bottomNavItems = listOf(AppRoute.Home, AppRoute.Features, AppRoute.Settings)\",\n \"\",\n \"@Composable\",\n \"fun AppScaffold() {\",\n \" val navController = rememberNavController()\",\n \" val backStackEntry by navController.currentBackStackEntryAsState()\",\n \" val currentPath = backStackEntry?.destination?.route\",\n \"\",\n \" Scaffold(\",\n \" bottomBar = {\",\n \" NavigationBar {\",\n \" bottomNavItems.forEach { route ->\",\n \" NavigationBarItem(\",\n \" selected = currentPath == route.path,\",\n \" onClick = {\",\n \" navController.navigate(route.path) {\",\n \" popUpTo(navController.graph.startDestinationId) { saveState = true }\",\n \" launchSingleTop = true\",\n \" restoreState = true\",\n \" }\",\n \" },\",\n \" icon = { Icon(route.icon, contentDescription = route.label) },\",\n \" label = { Text(route.label) },\",\n \" )\",\n \" }\",\n \" }\",\n \" },\",\n \" ) { padding ->\",\n \" AppNavHost(navController = navController, modifier = Modifier.padding(padding))\",\n \" }\",\n \"}\",\n \"\",\n \"@Composable\",\n \"fun AppNavHost(navController: NavHostController, modifier: Modifier = Modifier) {\",\n \" NavHost(navController = navController, startDestination = AppRoute.Home.path, modifier = modifier) {\",\n \" composable(AppRoute.Home.path) { EmptyState(title = \\\"Home\\\", message = \\\"Foundation ready\\\") }\",\n \" composable(AppRoute.Features.path) { EmptyState(title = \\\"Features\\\", message = \\\"Add feature screens here\\\") }\",\n \" composable(AppRoute.Settings.path) { EmptyState(title = \\\"Settings\\\", message = \\\"Configure preferences here\\\") }\",\n \" }\",\n \"}\",\n \"\",\n ].join(\"\\n\");\n}\n\nfunction buildAndroidDatabaseFile(packageName: string, classPrefix: string): string {\n return [\n `package ${packageName}.data`,\n \"\",\n \"import android.content.Context\",\n \"import androidx.room.Dao\",\n \"import androidx.room.Database\",\n \"import androidx.room.Entity\",\n \"import androidx.room.Insert\",\n \"import androidx.room.OnConflictStrategy\",\n \"import androidx.room.PrimaryKey\",\n \"import androidx.room.Query\",\n \"import androidx.room.Room\",\n \"import androidx.room.RoomDatabase\",\n \"import kotlinx.coroutines.flow.Flow\",\n \"\",\n \"@Entity(tableName = \\\"local_items\\\")\",\n \"data class LocalItemEntity(\",\n \" @PrimaryKey(autoGenerate = true) val id: Long = 0,\",\n \" val title: String,\",\n \" val createdAt: Long = System.currentTimeMillis(),\",\n \" val updatedAt: Long = System.currentTimeMillis(),\",\n \" val isDeleted: Boolean = false,\",\n \")\",\n \"\",\n \"@Dao\",\n \"interface LocalItemDao {\",\n \" @Query(\\\"SELECT * FROM local_items WHERE isDeleted = 0 ORDER BY createdAt DESC\\\")\",\n \" fun observeAll(): Flow<List<LocalItemEntity>>\",\n \"\",\n \" @Insert(onConflict = OnConflictStrategy.REPLACE)\",\n \" suspend fun upsert(item: LocalItemEntity): Long\",\n \"\",\n \" @Query(\\\"UPDATE local_items SET isDeleted = 1, updatedAt = :now WHERE id = :id\\\")\",\n \" suspend fun softDelete(id: Long, now: Long = System.currentTimeMillis())\",\n \"}\",\n \"\",\n \"@Database(\",\n \" entities = [LocalItemEntity::class],\",\n \" version = 1,\",\n \" exportSchema = true,\",\n \")\",\n \"abstract class AppDatabase : RoomDatabase() {\",\n \" abstract fun localItemDao(): LocalItemDao\",\n \"\",\n \" companion object {\",\n \" @Volatile\",\n \" private var instance: AppDatabase? = null\",\n \"\",\n \" fun getInstance(context: Context): AppDatabase =\",\n \" instance ?: synchronized(this) {\",\n \" instance ?: Room.databaseBuilder(\",\n \" context.applicationContext,\",\n \" AppDatabase::class.java,\",\n ` \"${classPrefix.toLowerCase()}_database\",`,\n \" )\",\n \" .fallbackToDestructiveMigration()\",\n \" .build()\",\n \" .also { instance = it }\",\n \" }\",\n \" }\",\n \"}\",\n \"\",\n ].join(\"\\n\");\n}\n\nfunction buildAndroidFoundationStatesFile(packageName: string): string {\n return [\n `package ${packageName}.ui.components`,\n \"\",\n \"import androidx.compose.foundation.layout.Arrangement\",\n \"import androidx.compose.foundation.layout.Box\",\n \"import androidx.compose.foundation.layout.Column\",\n \"import androidx.compose.foundation.layout.fillMaxSize\",\n \"import androidx.compose.foundation.layout.padding\",\n \"import androidx.compose.material3.Button\",\n \"import androidx.compose.material3.CircularProgressIndicator\",\n \"import androidx.compose.material3.MaterialTheme\",\n \"import androidx.compose.material3.Text\",\n \"import androidx.compose.runtime.Composable\",\n \"import androidx.compose.ui.Alignment\",\n \"import androidx.compose.ui.Modifier\",\n \"import androidx.compose.ui.unit.dp\",\n \"\",\n \"@Composable\",\n \"fun LoadingState(modifier: Modifier = Modifier) {\",\n \" Box(modifier = modifier.fillMaxSize(), contentAlignment = Alignment.Center) {\",\n \" CircularProgressIndicator()\",\n \" }\",\n \"}\",\n \"\",\n \"@Composable\",\n \"fun EmptyState(\",\n \" title: String,\",\n \" message: String,\",\n \" modifier: Modifier = Modifier,\",\n \") {\",\n \" Column(\",\n \" modifier = modifier.fillMaxSize().padding(24.dp),\",\n \" horizontalAlignment = Alignment.CenterHorizontally,\",\n \" verticalArrangement = Arrangement.Center,\",\n \" ) {\",\n \" Text(text = title, style = MaterialTheme.typography.headlineSmall)\",\n \" Text(text = message, style = MaterialTheme.typography.bodyMedium)\",\n \" }\",\n \"}\",\n \"\",\n \"@Composable\",\n \"fun ErrorState(\",\n \" message: String,\",\n \" onRetry: () -> Unit,\",\n \" modifier: Modifier = Modifier,\",\n \") {\",\n \" Column(\",\n \" modifier = modifier.fillMaxSize().padding(24.dp),\",\n \" horizontalAlignment = Alignment.CenterHorizontally,\",\n \" verticalArrangement = Arrangement.Center,\",\n \" ) {\",\n \" Text(text = message, color = MaterialTheme.colorScheme.error)\",\n \" Button(onClick = onRetry) { Text(\\\"Retry\\\") }\",\n \" }\",\n \"}\",\n \"\",\n ].join(\"\\n\");\n}\n\nexport const commitPlatformChangesTool: TanyaTool = {\n name: \"commit_platform_changes\",\n description: \"Stage selected files and create a git commit from the workspace or repository root.\",\n definition: {\n type: \"function\",\n function: {\n name: \"commit_platform_changes\",\n description: \"Stage explicit changed files and create a git commit. Use this instead of hand-written git add/commit shell commands when possible.\",\n parameters: {\n type: \"object\",\n properties: {\n files: { type: \"array\", items: { type: \"string\" }, description: \"Files to stage, relative to the workspace.\" },\n message: { type: \"string\", description: \"Commit message.\" },\n amend: { type: \"boolean\", description: \"If true, amend the current HEAD with these staged paths instead of creating a new commit.\" },\n },\n required: [\"files\", \"message\"],\n additionalProperties: false,\n },\n },\n },\n async run(input, context) {\n const message = asString(input, \"message\");\n const amend = asOptionalBoolean(input, \"amend\", false);\n const record = asRecord(input);\n const rawPaths = Array.isArray(record.files) ? record.files : record.paths;\n const paths = Array.isArray(rawPaths)\n ? rawPaths.filter((path): path is string => typeof path === \"string\" && path.trim().length > 0).map(ensureRelativePath)\n : [];\n if (paths.length === 0) return { ok: false, summary: \"No paths provided for commit.\", error: \"Provide at least one path to stage.\" };\n for (const path of paths) if (isProtectedLocalConfigPath(path)) return localPropertiesWriteError();\n\n const rootResult = await runProcess(\"git\", [\"rev-parse\", \"--show-toplevel\"], context, 20_000);\n if (!rootResult.ok || typeof rootResult.output !== \"string\") {\n return { ok: false, summary: \"Could not resolve git root.\", error: rootResult.error ?? String(rootResult.output ?? \"\") };\n }\n const repoRoot = rootResult.output.split(/\\r?\\n/)[0]?.trim();\n if (!repoRoot) return { ok: false, summary: \"Could not resolve git root.\", error: \"git rev-parse returned empty output.\" };\n const realRepoRoot = await realpath(repoRoot);\n const realWorkspace = await realpath(context.workspace);\n const repoPaths = await Promise.all(paths.map(async (path) => {\n const cleanPath = normalizeRelativePathForGit(path);\n const workspaceCandidate = resolveInsideWorkspace(realWorkspace, cleanPath);\n const repoCandidate = resolveInsideWorkspace(realRepoRoot, cleanPath);\n if (existsSync(repoCandidate)) return relative(realRepoRoot, await realpath(repoCandidate)).replace(/\\\\/g, \"/\");\n if (existsSync(workspaceCandidate)) return relative(realRepoRoot, await realpath(workspaceCandidate)).replace(/\\\\/g, \"/\");\n const workspacePrefix = normalizeRelativePathForGit(relative(realRepoRoot, realWorkspace));\n if (workspacePrefix && workspacePrefix !== \".\" && (cleanPath === workspacePrefix || cleanPath.startsWith(`${workspacePrefix}/`))) return cleanPath;\n const workspaceRelative = normalizeRelativePathForGit(relative(realRepoRoot, workspaceCandidate));\n if (!workspaceRelative.startsWith(\"../\") && workspaceRelative !== \"..\") return workspaceRelative;\n return cleanPath;\n }));\n if (repoPaths.some((path) => path === \"..\" || path.startsWith(\"../\"))) {\n return { ok: false, summary: \"Commit paths rejected.\", error: \"All commit paths must be inside the git repository root.\" };\n }\n const addResult = await runProcess(\"git\", [\"add\", ...repoPaths], context, 60_000, realRepoRoot);\n if (!addResult.ok) return { ...addResult, summary: \"git add failed.\", files: paths };\n const commitArgs = amend ? [\"commit\", \"--amend\", \"-m\", message] : [\"commit\", \"-m\", message];\n const commitResult = await runProcess(\"git\", commitArgs, context, 60_000, realRepoRoot);\n if (!commitResult.ok) return { ...commitResult, summary: \"git commit failed.\", files: paths };\n const headResult = await runProcess(\"git\", [\"rev-parse\", \"--short\", \"HEAD\"], context, 20_000, realRepoRoot);\n return {\n ok: true,\n summary: `${amend ? \"Amended commit with\" : \"Committed\"} ${paths.length} path${paths.length === 1 ? \"\" : \"s\"}.`,\n output: { repoRoot: realRepoRoot, head: typeof headResult.output === \"string\" ? headResult.output.trim().split(/\\r?\\n/)[0] : null, message, amend },\n files: paths,\n };\n },\n};\n\nconst secretFileExtensions = new Set([\".ts\", \".tsx\", \".js\", \".jsx\", \".mjs\", \".cjs\", \".json\", \".env\", \".example\", \".md\", \".swift\", \".kt\", \".kts\", \".gradle\", \".rb\", \".yml\", \".yaml\"]);\n\nfunction looksLikeSecret(line: string): boolean {\n if (/placeholder|example|changeme|your_|<[^>]+>|\\$\\{|process\\.env|env\\(/i.test(line)) return false;\n return /\\b[A-Za-z0-9_-]*(?:api[_-]?key|secret|token|password|private[_-]?key|client[_-]?secret|database_url)[A-Za-z0-9_-]*\\b\\s*[:=]\\s*[\"']?[A-Za-z0-9_./+=-]{16,}/i.test(line);\n}\n\nexport const scanSecretsTool: TanyaTool = {\n name: \"scan_secrets\",\n description: \"Scan workspace text files for likely hardcoded secrets.\",\n definition: {\n type: \"function\",\n function: {\n name: \"scan_secrets\",\n description: \"Scan workspace text files for likely hardcoded secrets while ignoring obvious placeholders.\",\n parameters: {\n type: \"object\",\n properties: {\n path: { type: \"string\", description: \"Directory path relative to workspace. Default workspace root.\" },\n maxFiles: { type: \"number\", description: \"Maximum files to scan. Default 500.\" },\n },\n additionalProperties: false,\n },\n },\n },\n async run(input, context) {\n const scanPath = asOptionalString(input, \"path\");\n const maxFiles = Math.min(asOptionalNumber(input, \"maxFiles\", 500), 2000);\n const root = scanPath ? resolveInsideWorkspace(context.workspace, ensureRelativePath(scanPath)) : context.workspace;\n const files = collectFiles(root, maxFiles);\n const findings: Array<{ file: string; line: number; key: string }> = [];\n for (const file of files) {\n const lower = file.toLowerCase();\n if (!secretFileExtensions.has(lower.slice(lower.lastIndexOf(\".\")))) continue;\n let text = \"\";\n try {\n text = await readFile(resolveInsideWorkspace(root, file), \"utf8\");\n } catch {\n continue;\n }\n text.split(/\\r?\\n/).forEach((line, index) => {\n if (!looksLikeSecret(line)) return;\n const key = line.match(/\\b([A-Za-z0-9_-]*(?:api[_-]?key|secret|token|password|private[_-]?key|client[_-]?secret|database_url)[A-Za-z0-9_-]*)\\b/i)?.[1] ?? \"secret\";\n findings.push({ file: scanPath ? `${scanPath.replace(/\\/+$/, \"\")}/${file}` : file, line: index + 1, key });\n });\n }\n\n return {\n ok: findings.length === 0,\n summary: findings.length === 0 ? \"No likely hardcoded secrets found.\" : `Found ${findings.length} likely hardcoded secret${findings.length === 1 ? \"\" : \"s\"}.`,\n output: { findings },\n ...(findings.length > 0 ? { error: findings.map((finding) => `${finding.file}:${finding.line} ${finding.key}`).join(\"; \") } : {}),\n };\n },\n};\n\nexport function defaultTools(): TanyaTool[] {\n const verificationPreferredModel = {\n provider: \"deepseek\",\n model: \"deepseek-reasoner\",\n match: \"verification\" as const,\n };\n const tools = [\n listFilesTool,\n expandResultTool,\n taskTool,\n readFileTool,\n searchTool,\n inspectRepoMapTool,\n inspectProjectContextTool,\n findReusableArtifactsTool,\n buildTaskBriefTool,\n searchObsidianNotesTool,\n writeFileTool,\n applyPatchTool,\n editBlockTool,\n searchReplaceTool,\n copyFileTool,\n copyDirTool,\n applyArtifactTool,\n createIosSplashTool,\n createAndroidSplashTool,\n generateAppIconsTool,\n createAndroidFoundationTool,\n commitPlatformChangesTool,\n resizeImageTool,\n renderSvgToPngTool,\n createAppleAppIconSetTool,\n createAndroidLauncherIconSetTool,\n validateAppleAppIconSetTool,\n validateAndroidLauncherIconSetTool,\n validateApiContractRoutesTool,\n validateAndroidProjectConfigTool,\n validateAppleProjectFilesTool,\n validateFastlaneConfigTool,\n validatePrismaSchemaTool,\n scanSecretsTool,\n generateVideoAssetTool,\n recordMetricsDashboardHandoffTool,\n runCommandTool,\n runShellTool,\n ].map((tool): TanyaTool => (\n /^validate_/.test(tool.name) || tool.name === \"scan_secrets\"\n ? { ...tool, preferredModel: verificationPreferredModel }\n : tool\n ));\n return tools.filter((tool) => tool.name !== \"search\" || existsSync(\"/usr/bin/rg\") || existsSync(\"/opt/homebrew/bin/rg\") || existsSync(\"/usr/local/bin/rg\"));\n}\n","import { mkdir, readFile, writeFile } from \"node:fs/promises\";\nimport { dirname } from \"node:path\";\nimport sharp from \"sharp\";\nimport type { TanyaTool } from \"./types\";\nimport { resolveInsideWorkspace } from \"../safety/workspace\";\n\nfunction asRecord(input: unknown): Record<string, unknown> {\n return input && typeof input === \"object\" ? (input as Record<string, unknown>) : {};\n}\n\nfunction asString(input: unknown, key: string): string {\n const value = asRecord(input)[key];\n if (typeof value !== \"string\" || !value.trim()) throw new Error(`Missing string field: ${key}`);\n return value;\n}\n\nfunction asOptionalString(input: unknown, key: string): string | undefined {\n const value = asRecord(input)[key];\n return typeof value === \"string\" && value.trim() ? value.trim() : undefined;\n}\n\nfunction asOptionalNumber(input: unknown, key: string, fallback: number): number {\n const value = asRecord(input)[key];\n return typeof value === \"number\" && Number.isFinite(value) ? value : fallback;\n}\n\nfunction ensureRelativePath(path: string): string {\n if (path.startsWith(\"/\")) throw new Error(`Path must be relative to the workspace: ${path}`);\n return path;\n}\n\nfunction optionalStringArray(input: unknown, key: string, fallback: string[]): string[] {\n const value = asRecord(input)[key];\n if (!Array.isArray(value)) return fallback;\n return value.filter((item): item is string => typeof item === \"string\" && item.trim().length > 0);\n}\n\nfunction sanitizeName(value: string): string {\n return value.replace(/[^a-z0-9@._-]+/gi, \"-\").replace(/^-+|-+$/g, \"\");\n}\n\ntype AppleIconSlot = {\n idiom: string;\n size: string;\n scale: \"1x\" | \"2x\" | \"3x\";\n};\n\nconst iosIconSlots: AppleIconSlot[] = [\n { idiom: \"iphone\", size: \"20x20\", scale: \"2x\" },\n { idiom: \"iphone\", size: \"20x20\", scale: \"3x\" },\n { idiom: \"iphone\", size: \"29x29\", scale: \"2x\" },\n { idiom: \"iphone\", size: \"29x29\", scale: \"3x\" },\n { idiom: \"iphone\", size: \"40x40\", scale: \"2x\" },\n { idiom: \"iphone\", size: \"40x40\", scale: \"3x\" },\n { idiom: \"iphone\", size: \"60x60\", scale: \"2x\" },\n { idiom: \"iphone\", size: \"60x60\", scale: \"3x\" },\n { idiom: \"ipad\", size: \"20x20\", scale: \"1x\" },\n { idiom: \"ipad\", size: \"20x20\", scale: \"2x\" },\n { idiom: \"ipad\", size: \"29x29\", scale: \"1x\" },\n { idiom: \"ipad\", size: \"29x29\", scale: \"2x\" },\n { idiom: \"ipad\", size: \"40x40\", scale: \"1x\" },\n { idiom: \"ipad\", size: \"40x40\", scale: \"2x\" },\n { idiom: \"ipad\", size: \"76x76\", scale: \"1x\" },\n { idiom: \"ipad\", size: \"76x76\", scale: \"2x\" },\n { idiom: \"ipad\", size: \"83.5x83.5\", scale: \"2x\" },\n { idiom: \"ios-marketing\", size: \"1024x1024\", scale: \"1x\" },\n];\n\nconst macIconSlots: AppleIconSlot[] = [\n { idiom: \"mac\", size: \"16x16\", scale: \"1x\" },\n { idiom: \"mac\", size: \"16x16\", scale: \"2x\" },\n { idiom: \"mac\", size: \"32x32\", scale: \"1x\" },\n { idiom: \"mac\", size: \"32x32\", scale: \"2x\" },\n { idiom: \"mac\", size: \"128x128\", scale: \"1x\" },\n { idiom: \"mac\", size: \"128x128\", scale: \"2x\" },\n { idiom: \"mac\", size: \"256x256\", scale: \"1x\" },\n { idiom: \"mac\", size: \"256x256\", scale: \"2x\" },\n { idiom: \"mac\", size: \"512x512\", scale: \"1x\" },\n { idiom: \"mac\", size: \"512x512\", scale: \"2x\" },\n];\n\nfunction pixelSize(slot: AppleIconSlot): number {\n const points = Number.parseFloat(slot.size.split(\"x\")[0] ?? \"0\");\n const scale = Number.parseInt(slot.scale, 10);\n return Math.round(points * scale);\n}\n\nfunction slotsForPlatforms(platforms: string[]): AppleIconSlot[] {\n const normalized = new Set(platforms.map((platform) => platform.toLowerCase()));\n const slots: AppleIconSlot[] = [];\n if (normalized.has(\"ios\") || normalized.has(\"iphone\") || normalized.has(\"ipad\")) slots.push(...iosIconSlots);\n if (normalized.has(\"macos\") || normalized.has(\"mac\")) slots.push(...macIconSlots);\n return slots;\n}\n\nasync function resizePng(params: {\n sourceAbs: string;\n destinationAbs: string;\n width: number;\n height: number;\n background: string;\n}) {\n await mkdir(dirname(params.destinationAbs), { recursive: true });\n await sharp(params.sourceAbs)\n .resize(params.width, params.height, { fit: \"cover\", position: \"center\" })\n .flatten({ background: params.background })\n .png({ force: true })\n .toFile(params.destinationAbs);\n}\n\nexport const resizeImageTool: TanyaTool = {\n name: \"resize_image\",\n description: \"Resize an image to a PNG inside the workspace.\",\n definition: {\n type: \"function\",\n function: {\n name: \"resize_image\",\n description: \"Resize an image to a PNG inside the workspace. Useful for icons, splash assets, and app resources.\",\n parameters: {\n type: \"object\",\n properties: {\n source: { type: \"string\", description: \"Source image path relative to the workspace.\" },\n destination: { type: \"string\", description: \"Destination PNG path relative to the workspace.\" },\n width: { type: \"number\", description: \"Output width in pixels.\" },\n height: { type: \"number\", description: \"Output height in pixels. Defaults to width.\" },\n background: { type: \"string\", description: \"Background color used to remove alpha. Default #ffffff.\" },\n },\n required: [\"source\", \"destination\", \"width\"],\n additionalProperties: false,\n },\n },\n },\n async run(input, context) {\n const source = ensureRelativePath(asString(input, \"source\"));\n const destination = ensureRelativePath(asString(input, \"destination\"));\n const width = Math.round(asOptionalNumber(input, \"width\", 0));\n const height = Math.round(asOptionalNumber(input, \"height\", width));\n const background = asOptionalString(input, \"background\") ?? \"#ffffff\";\n if (width <= 0 || height <= 0) return { ok: false, summary: \"Invalid image dimensions.\", error: \"width and height must be positive.\" };\n\n const sourceAbs = resolveInsideWorkspace(context.workspace, source);\n const destinationAbs = resolveInsideWorkspace(context.workspace, destination);\n await resizePng({ sourceAbs, destinationAbs, width, height, background });\n return {\n ok: true,\n summary: `Resized ${source} to ${width}x${height}.`,\n output: { source, destination, width, height },\n files: [destination],\n };\n },\n};\n\nexport const renderSvgToPngTool: TanyaTool = {\n name: \"render_svg_to_png\",\n description: \"Render an SVG file to a PNG inside the workspace.\",\n definition: {\n type: \"function\",\n function: {\n name: \"render_svg_to_png\",\n description: \"Render an SVG file to a PNG inside the workspace. Useful for creating a source icon PNG from a generated vector design.\",\n parameters: {\n type: \"object\",\n properties: {\n source: { type: \"string\", description: \"Source SVG path relative to the workspace.\" },\n destination: { type: \"string\", description: \"Destination PNG path relative to the workspace.\" },\n width: { type: \"number\", description: \"Output width in pixels. Default 1024.\" },\n height: { type: \"number\", description: \"Output height in pixels. Defaults to width.\" },\n background: { type: \"string\", description: \"Background color used to remove alpha. Default #ffffff.\" },\n },\n required: [\"source\", \"destination\"],\n additionalProperties: false,\n },\n },\n },\n async run(input, context) {\n const source = ensureRelativePath(asString(input, \"source\"));\n const destination = ensureRelativePath(asString(input, \"destination\"));\n const width = Math.round(asOptionalNumber(input, \"width\", 1024));\n const height = Math.round(asOptionalNumber(input, \"height\", width));\n const background = asOptionalString(input, \"background\") ?? \"#ffffff\";\n if (width <= 0 || height <= 0) return { ok: false, summary: \"Invalid image dimensions.\", error: \"width and height must be positive.\" };\n\n const sourceAbs = resolveInsideWorkspace(context.workspace, source);\n const destinationAbs = resolveInsideWorkspace(context.workspace, destination);\n await mkdir(dirname(destinationAbs), { recursive: true });\n const svg = await readFile(sourceAbs);\n await sharp(svg, { density: 384 })\n .resize(width, height, { fit: \"cover\", position: \"center\" })\n .flatten({ background })\n .png({ force: true })\n .toFile(destinationAbs);\n return {\n ok: true,\n summary: `Rendered ${source} to ${width}x${height} PNG.`,\n output: { source, destination, width, height },\n files: [destination],\n };\n },\n};\n\nexport const createAppleAppIconSetTool: TanyaTool = {\n name: \"create_apple_app_icon_set\",\n description: \"Generate an Apple AppIcon.appiconset from a source image.\",\n definition: {\n type: \"function\",\n function: {\n name: \"create_apple_app_icon_set\",\n description: \"Generate PNG sizes and Contents.json for an Apple AppIcon.appiconset. Supports iOS and macOS.\",\n parameters: {\n type: \"object\",\n properties: {\n source: { type: \"string\", description: \"Source image path relative to the workspace. Prefer a 1024x1024 PNG.\" },\n outputDir: { type: \"string\", description: \"Destination .appiconset directory relative to the workspace.\" },\n platforms: {\n type: \"array\",\n items: { type: \"string\", enum: [\"ios\", \"macos\"] },\n description: \"Platforms to generate. Default ['ios'].\",\n },\n background: { type: \"string\", description: \"Background color used to remove alpha. Default #ffffff.\" },\n },\n required: [\"source\", \"outputDir\"],\n additionalProperties: false,\n },\n },\n },\n async run(input, context) {\n const source = ensureRelativePath(asString(input, \"source\"));\n const outputDir = ensureRelativePath(asString(input, \"outputDir\"));\n const platforms = optionalStringArray(input, \"platforms\", [\"ios\"]);\n const slots = slotsForPlatforms(platforms);\n const background = asOptionalString(input, \"background\") ?? \"#ffffff\";\n if (slots.length === 0) {\n return { ok: false, summary: \"No Apple icon platforms selected.\", error: \"Use platforms ['ios'], ['macos'], or both.\" };\n }\n\n const sourceAbs = resolveInsideWorkspace(context.workspace, source);\n const outputAbs = resolveInsideWorkspace(context.workspace, outputDir);\n await mkdir(outputAbs, { recursive: true });\n\n const generatedFiles: string[] = [];\n const images = [];\n for (const slot of slots) {\n const px = pixelSize(slot);\n const filename = `AppIcon-${sanitizeName(slot.idiom)}-${sanitizeName(slot.size)}@${slot.scale}.png`;\n const destination = `${outputDir}/${filename}`;\n const destinationAbs = resolveInsideWorkspace(context.workspace, destination);\n await resizePng({ sourceAbs, destinationAbs, width: px, height: px, background });\n generatedFiles.push(destination);\n images.push({\n idiom: slot.idiom,\n size: slot.size,\n scale: slot.scale,\n filename,\n });\n }\n\n const contentsPath = `${outputDir}/Contents.json`;\n const contents = {\n images,\n info: {\n author: \"xcode\",\n version: 1,\n },\n };\n await writeFile(resolveInsideWorkspace(context.workspace, contentsPath), `${JSON.stringify(contents, null, 2)}\\n`, \"utf8\");\n generatedFiles.push(contentsPath);\n\n return {\n ok: true,\n summary: `Generated ${images.length} Apple app icon image${images.length === 1 ? \"\" : \"s\"}.`,\n output: { source, outputDir, platforms, images: images.length, contentsPath },\n files: generatedFiles,\n };\n },\n};\n\nconst androidLauncherDensities = [\n { dir: \"mipmap-mdpi\", icon: 48, foreground: 108 },\n { dir: \"mipmap-hdpi\", icon: 72, foreground: 162 },\n { dir: \"mipmap-xhdpi\", icon: 96, foreground: 216 },\n { dir: \"mipmap-xxhdpi\", icon: 144, foreground: 324 },\n { dir: \"mipmap-xxxhdpi\", icon: 192, foreground: 432 },\n] as const;\n\nexport const createAndroidLauncherIconSetTool: TanyaTool = {\n name: \"create_android_launcher_icon_set\",\n description: \"Generate Android launcher and adaptive icon resources from a source image.\",\n definition: {\n type: \"function\",\n function: {\n name: \"create_android_launcher_icon_set\",\n description: \"Generate Android launcher PNGs, round icons, adaptive icon foreground PNGs, and adaptive icon XML resources.\",\n parameters: {\n type: \"object\",\n properties: {\n source: { type: \"string\", description: \"Source image path relative to the workspace. Prefer a 1024x1024 PNG.\" },\n resDir: { type: \"string\", description: \"Android res directory relative to the workspace, for example app/src/main/res.\" },\n background: { type: \"string\", description: \"Background color for flattened PNGs and adaptive icon background. Default #ffffff.\" },\n iconName: { type: \"string\", description: \"Launcher icon resource base name. Default ic_launcher.\" },\n roundIconName: { type: \"string\", description: \"Round launcher icon resource base name. Default ic_launcher_round.\" },\n },\n required: [\"source\", \"resDir\"],\n additionalProperties: false,\n },\n },\n },\n async run(input, context) {\n const source = ensureRelativePath(asString(input, \"source\"));\n const resDir = ensureRelativePath(asString(input, \"resDir\"));\n const background = asOptionalString(input, \"background\") ?? \"#ffffff\";\n const iconName = sanitizeName(asOptionalString(input, \"iconName\") ?? \"ic_launcher\");\n const roundIconName = sanitizeName(asOptionalString(input, \"roundIconName\") ?? \"ic_launcher_round\");\n const sourceAbs = resolveInsideWorkspace(context.workspace, source);\n const generatedFiles: string[] = [];\n\n for (const density of androidLauncherDensities) {\n const iconPath = `${resDir}/${density.dir}/${iconName}.png`;\n await resizePng({\n sourceAbs,\n destinationAbs: resolveInsideWorkspace(context.workspace, iconPath),\n width: density.icon,\n height: density.icon,\n background,\n });\n generatedFiles.push(iconPath);\n\n const roundIconPath = `${resDir}/${density.dir}/${roundIconName}.png`;\n await resizePng({\n sourceAbs,\n destinationAbs: resolveInsideWorkspace(context.workspace, roundIconPath),\n width: density.icon,\n height: density.icon,\n background,\n });\n generatedFiles.push(roundIconPath);\n\n const foregroundPath = `${resDir}/${density.dir}/${iconName}_foreground.png`;\n await resizePng({\n sourceAbs,\n destinationAbs: resolveInsideWorkspace(context.workspace, foregroundPath),\n width: density.foreground,\n height: density.foreground,\n background: \"transparent\",\n });\n generatedFiles.push(foregroundPath);\n }\n\n const backgroundPath = `${resDir}/drawable/${iconName}_background.xml`;\n await mkdir(dirname(resolveInsideWorkspace(context.workspace, backgroundPath)), { recursive: true });\n await writeFile(\n resolveInsideWorkspace(context.workspace, backgroundPath),\n `<shape xmlns:android=\"http://schemas.android.com/apk/res/android\" android:shape=\"rectangle\">\\n <solid android:color=\"${background}\" />\\n</shape>\\n`,\n \"utf8\",\n );\n generatedFiles.push(backgroundPath);\n\n const adaptiveDir = `${resDir}/mipmap-anydpi-v26`;\n for (const name of [iconName, roundIconName]) {\n const adaptivePath = `${adaptiveDir}/${name}.xml`;\n await mkdir(dirname(resolveInsideWorkspace(context.workspace, adaptivePath)), { recursive: true });\n await writeFile(\n resolveInsideWorkspace(context.workspace, adaptivePath),\n `<adaptive-icon xmlns:android=\"http://schemas.android.com/apk/res/android\">\\n <background android:drawable=\"@drawable/${iconName}_background\" />\\n <foreground android:drawable=\"@mipmap/${iconName}_foreground\" />\\n</adaptive-icon>\\n`,\n \"utf8\",\n );\n generatedFiles.push(adaptivePath);\n }\n\n const playIconPath = `${resDir}/play-store-icon.png`;\n await resizePng({\n sourceAbs,\n destinationAbs: resolveInsideWorkspace(context.workspace, playIconPath),\n width: 512,\n height: 512,\n background,\n });\n generatedFiles.push(playIconPath);\n\n return {\n ok: true,\n summary: `Generated Android launcher icon resources in ${resDir}.`,\n output: { source, resDir, iconName, roundIconName, densities: androidLauncherDensities.length, files: generatedFiles.length },\n files: generatedFiles,\n };\n },\n};\n\nexport const validateAppleAppIconSetTool: TanyaTool = {\n name: \"validate_apple_app_icon_set\",\n description: \"Validate an Apple AppIcon.appiconset Contents.json, referenced PNGs, dimensions, and alpha.\",\n definition: {\n type: \"function\",\n function: {\n name: \"validate_apple_app_icon_set\",\n description: \"Validate an Apple AppIcon.appiconset. Supports iOS and macOS slot expectations.\",\n parameters: {\n type: \"object\",\n properties: {\n appIconSetDir: { type: \"string\", description: \"AppIcon.appiconset directory relative to the workspace.\" },\n platforms: {\n type: \"array\",\n items: { type: \"string\", enum: [\"ios\", \"macos\"] },\n description: \"Platforms expected. Default ['ios'].\",\n },\n requireNoAlpha: { type: \"boolean\", description: \"Fail if generated PNGs contain alpha. Default true.\" },\n },\n required: [\"appIconSetDir\"],\n additionalProperties: false,\n },\n },\n },\n async run(input, context) {\n const appIconSetDir = ensureRelativePath(asString(input, \"appIconSetDir\"));\n const platforms = optionalStringArray(input, \"platforms\", [\"ios\"]);\n const requireNoAlpha = asRecord(input).requireNoAlpha !== false;\n const expectedSlots = slotsForPlatforms(platforms);\n const contentsPath = `${appIconSetDir}/Contents.json`;\n const contentsText = await readFile(resolveInsideWorkspace(context.workspace, contentsPath), \"utf8\");\n const contents = JSON.parse(contentsText) as { images?: Array<{ idiom?: string; size?: string; scale?: string; filename?: string }> };\n const images = Array.isArray(contents.images) ? contents.images : [];\n const problems: string[] = [];\n\n for (const expected of expectedSlots) {\n const entry = images.find((image) => image.idiom === expected.idiom && image.size === expected.size && image.scale === expected.scale);\n if (!entry?.filename) {\n problems.push(`Missing ${expected.idiom} ${expected.size}@${expected.scale}`);\n continue;\n }\n const metadata = await sharp(resolveInsideWorkspace(context.workspace, `${appIconSetDir}/${entry.filename}`)).metadata();\n const px = pixelSize(expected);\n if (metadata.width !== px || metadata.height !== px) {\n problems.push(`${entry.filename} expected ${px}x${px}, got ${metadata.width}x${metadata.height}`);\n }\n if (requireNoAlpha && metadata.hasAlpha) {\n problems.push(`${entry.filename} contains alpha`);\n }\n }\n\n return {\n ok: problems.length === 0,\n summary: problems.length === 0\n ? `Validated ${expectedSlots.length} Apple app icon slot${expectedSlots.length === 1 ? \"\" : \"s\"}.`\n : `Apple app icon validation found ${problems.length} problem${problems.length === 1 ? \"\" : \"s\"}.`,\n output: { appIconSetDir, expectedSlots: expectedSlots.length, imageEntries: images.length, problems },\n ...(problems.length > 0 ? { error: problems.join(\"; \") } : {}),\n };\n },\n};\n\nexport const validateAndroidLauncherIconSetTool: TanyaTool = {\n name: \"validate_android_launcher_icon_set\",\n description: \"Validate Android launcher PNGs and adaptive icon XML resources.\",\n definition: {\n type: \"function\",\n function: {\n name: \"validate_android_launcher_icon_set\",\n description: \"Validate Android launcher PNG densities, adaptive icon XML resources, and Play Store icon.\",\n parameters: {\n type: \"object\",\n properties: {\n resDir: { type: \"string\", description: \"Android res directory relative to the workspace, for example app/src/main/res.\" },\n iconName: { type: \"string\", description: \"Launcher icon resource base name. Default ic_launcher.\" },\n roundIconName: { type: \"string\", description: \"Round launcher icon resource base name. Default ic_launcher_round.\" },\n },\n required: [\"resDir\"],\n additionalProperties: false,\n },\n },\n },\n async run(input, context) {\n const resDir = ensureRelativePath(asString(input, \"resDir\"));\n const iconName = sanitizeName(asOptionalString(input, \"iconName\") ?? \"ic_launcher\");\n const roundIconName = sanitizeName(asOptionalString(input, \"roundIconName\") ?? \"ic_launcher_round\");\n const problems: string[] = [];\n\n for (const density of androidLauncherDensities) {\n for (const [fileName, expectedPx] of [\n [`${iconName}.png`, density.icon],\n [`${roundIconName}.png`, density.icon],\n [`${iconName}_foreground.png`, density.foreground],\n ] as const) {\n const resourcePath = `${resDir}/${density.dir}/${fileName}`;\n try {\n const metadata = await sharp(resolveInsideWorkspace(context.workspace, resourcePath)).metadata();\n if (metadata.width !== expectedPx || metadata.height !== expectedPx) {\n problems.push(`${resourcePath} expected ${expectedPx}x${expectedPx}, got ${metadata.width}x${metadata.height}`);\n }\n } catch {\n problems.push(`Missing ${resourcePath}`);\n }\n }\n }\n\n for (const xmlPath of [\n `${resDir}/drawable/${iconName}_background.xml`,\n `${resDir}/mipmap-anydpi-v26/${iconName}.xml`,\n `${resDir}/mipmap-anydpi-v26/${roundIconName}.xml`,\n ]) {\n try {\n await readFile(resolveInsideWorkspace(context.workspace, xmlPath), \"utf8\");\n } catch {\n problems.push(`Missing ${xmlPath}`);\n }\n }\n\n try {\n const metadata = await sharp(resolveInsideWorkspace(context.workspace, `${resDir}/play-store-icon.png`)).metadata();\n if (metadata.width !== 512 || metadata.height !== 512) problems.push(\"play-store-icon.png must be 512x512\");\n } catch {\n problems.push(`Missing ${resDir}/play-store-icon.png`);\n }\n\n return {\n ok: problems.length === 0,\n summary: problems.length === 0\n ? \"Validated Android launcher icon resources.\"\n : `Android launcher icon validation found ${problems.length} problem${problems.length === 1 ? \"\" : \"s\"}.`,\n output: { resDir, problems },\n ...(problems.length > 0 ? { error: problems.join(\"; \") } : {}),\n };\n },\n};\n","import { readdir, readFile, stat } from \"node:fs/promises\";\nimport { existsSync } from \"node:fs\";\nimport { basename, extname, join, relative, resolve } from \"node:path\";\nimport type { TanyaTool, ToolContext } from \"./types\";\nimport { resolveInsideWorkspace } from \"../safety/workspace\";\n\nconst ignoredNames = new Set([\n \".git\",\n \"node_modules\",\n \".next\",\n \"dist\",\n \"build\",\n \".turbo\",\n \".cache\",\n \".claude\",\n \".cursor\",\n \".playwright-mcp\",\n \".venv\",\n \"venv\",\n \"coverage\",\n \"out\",\n \"vendor\",\n \"Pods\",\n \"full-ad-renders\",\n \"video-tmp\",\n \"tmp\",\n \"DerivedData\",\n \".gradle\",\n \"ComfyUI\",\n]);\n\nconst queryStopwords = new Set([\n \"a\",\n \"an\",\n \"and\",\n \"app\",\n \"as\",\n \"at\",\n \"by\",\n \"create\",\n \"creating\",\n \"for\",\n \"from\",\n \"implement\",\n \"in\",\n \"into\",\n \"new\",\n \"of\",\n \"on\",\n \"or\",\n \"set\",\n \"task\",\n \"tasks\",\n \"the\",\n \"this\",\n \"to\",\n \"up\",\n \"use\",\n \"using\",\n \"v2\",\n \"verification\",\n \"verify\",\n \"build\",\n \"typecheck\",\n \"script\",\n \"scripts\",\n \"with\",\n]);\n\nconst instructionNames = new Set([\n \"AGENTS.md\",\n \"CLAUDE.md\",\n \"TANYA.md\",\n \"TANIA.md\",\n \"README.md\",\n \"PROJECT.md\",\n \"CONTRIBUTING.md\",\n]);\n\nconst artifactFileExtensions = new Set([\n \".md\",\n \".txt\",\n \".ts\",\n \".tsx\",\n \".js\",\n \".jsx\",\n \".mjs\",\n \".cjs\",\n \".swift\",\n \".kt\",\n \".kts\",\n \".gradle\",\n \".prisma\",\n \".json\",\n \".xml\",\n \".yml\",\n \".yaml\",\n \".css\",\n]);\n\ntype ArtifactIndexEntry = {\n path: string;\n category?: string;\n description?: string;\n useWhen?: string;\n};\n\ntype ArtifactCandidate = ArtifactIndexEntry & {\n root: string;\n extension: string;\n score: number;\n reason: string;\n};\n\nexport type CapabilityPackBrief = {\n id: string;\n reason: string;\n tools: string[];\n artifactHints: string[];\n validators: string[];\n verificationHints: string[];\n};\n\nexport type TanyaTaskBrief = {\n task: string;\n signals: {\n platforms: string[];\n domains: string[];\n };\n contextFiles: Array<{\n path: string;\n role: string;\n }>;\n artifacts: ArtifactCandidate[];\n verification: string[];\n recommendedTools: string[];\n capabilityPacks: CapabilityPackBrief[];\n cautions: string[];\n};\n\nfunction asRecord(input: unknown): Record<string, unknown> {\n return input && typeof input === \"object\" ? (input as Record<string, unknown>) : {};\n}\n\nfunction asString(input: unknown, key: string): string {\n const value = asRecord(input)[key];\n if (typeof value !== \"string\" || !value.trim()) throw new Error(`Missing string field: ${key}`);\n return value.trim();\n}\n\nfunction asOptionalString(input: unknown, key: string): string | undefined {\n const value = asRecord(input)[key];\n return typeof value === \"string\" && value.trim() ? value.trim() : undefined;\n}\n\nfunction asOptionalNumber(input: unknown, key: string, fallback: number): number {\n const value = asRecord(input)[key];\n return typeof value === \"number\" && Number.isFinite(value) ? value : fallback;\n}\n\nfunction asOptionalBoolean(input: unknown, key: string, fallback: boolean): boolean {\n const value = asRecord(input)[key];\n if (typeof value === \"boolean\") return value;\n if (typeof value === \"string\") return /^(true|yes|1)$/i.test(value.trim());\n return fallback;\n}\n\nfunction normalizePath(path: string): string {\n return path.replace(/\\\\/g, \"/\").replace(/^\\.\\/+/, \"\").replace(/\\/+/g, \"/\");\n}\n\nfunction cleanMarkdownCell(value: string): string {\n return value\n .trim()\n .replace(/^`|`$/g, \"\")\n .replace(/\\\\\\|/g, \"|\")\n .trim();\n}\n\nfunction termList(query: string): string[] {\n return [...new Set(query.toLowerCase().match(/[a-z0-9_+-]{2,}/g) ?? [])]\n .filter((term) => !queryStopwords.has(term));\n}\n\nfunction resolveOptionalWorkspacePath(context: ToolContext, inputPath?: string): string {\n if (!inputPath) return context.workspace;\n if (inputPath.startsWith(\"/\")) return resolveInsideWorkspace(context.workspace, inputPath);\n return resolveInsideWorkspace(context.workspace, inputPath);\n}\n\nasync function collectFiles(root: string, maxFiles: number, current = root, out: string[] = []): Promise<string[]> {\n if (out.length >= maxFiles) return out;\n let entries;\n try {\n entries = await readdir(current, { withFileTypes: true });\n } catch {\n return out;\n }\n entries.sort((a, b) => a.name.localeCompare(b.name));\n for (const entry of entries) {\n if (out.length >= maxFiles) break;\n if (ignoredNames.has(entry.name)) continue;\n const fullPath = join(current, entry.name);\n const rel = normalizePath(relative(root, fullPath));\n if (entry.isDirectory()) {\n if (entry.name === \".tania\") {\n out.push(`${rel}/`);\n await collectTanyaFiles(root, fullPath, maxFiles, out);\n continue;\n }\n if (entry.name.startsWith(\".\")) continue;\n out.push(`${rel}/`);\n await collectFiles(root, maxFiles, fullPath, out);\n } else if (entry.isFile()) {\n out.push(rel);\n }\n }\n return out;\n}\n\nasync function collectTanyaFiles(root: string, taniaDir: string, maxFiles: number, out: string[]): Promise<void> {\n for (const rel of [\"INSTRUCTIONS.md\", \"artifacts/manifest.json\"]) {\n if (out.length >= maxFiles) return;\n const abs = join(taniaDir, rel);\n try {\n if ((await stat(abs)).isFile()) out.push(normalizePath(relative(root, abs)));\n } catch {\n // Optional local Tanya files are often absent.\n }\n }\n const contextDir = join(taniaDir, \"context\");\n try {\n if ((await stat(contextDir)).isDirectory()) {\n out.push(normalizePath(relative(root, contextDir)) + \"/\");\n await collectFiles(root, maxFiles, contextDir, out);\n }\n } catch {\n // Optional materialized context is often absent.\n }\n}\n\nasync function readExcerpt(path: string, maxChars: number): Promise<string | null> {\n try {\n const content = await readFile(path, \"utf8\");\n return content.length > maxChars ? `${content.slice(0, maxChars)}\\n[truncated]` : content;\n } catch {\n return null;\n }\n}\n\nasync function readPackageScripts(root: string): Promise<Record<string, string>> {\n const path = join(root, \"package.json\");\n try {\n const parsed = JSON.parse(await readFile(path, \"utf8\")) as { scripts?: Record<string, unknown> };\n return Object.fromEntries(\n Object.entries(parsed.scripts ?? {}).filter((entry): entry is [string, string] => typeof entry[1] === \"string\"),\n );\n } catch {\n return {};\n }\n}\n\nfunction classifyContextFile(relPath: string): string | null {\n const normalized = normalizePath(relPath);\n const name = basename(normalized);\n const lower = normalized.toLowerCase();\n if (normalized === \".tania/INSTRUCTIONS.md\" || instructionNames.has(name)) return \"instruction\";\n if (lower === \"artifacts/description.md\" || lower === \"artifacts/readme.md\" || lower === \".tania/artifacts/manifest.json\") return \"artifact-index\";\n if (lower.startsWith(\".tania/context/\")) return \"materialized-context\";\n if (lower.startsWith(\"brand/\") && /\\.(md|json|txt)$/i.test(lower)) return \"project-contract\";\n if (/(^|\\/)(api_features\\.md|api-features\\.md|openapi\\.json|openapi\\.yaml|openapi\\.yml)$/i.test(normalized)) return \"api-contract\";\n if (/(^|\\/)(schema\\.prisma|prisma\\.schema)$/i.test(normalized)) return \"data-contract\";\n if (/(^|\\/)(safety\\.md|architecture\\.md|product\\.md|features\\.md|deploy\\.md|store\\.md)$/i.test(normalized)) return \"project-contract\";\n if (/^docs\\/[^/]+\\.md$/i.test(normalized)) return \"doc\";\n if (!normalized.includes(\"/\") && /\\.md$/i.test(normalized)) return \"doc\";\n return null;\n}\n\nfunction detectPlatforms(files: string[]): string[] {\n const text = files.join(\"\\n\").toLowerCase();\n const platforms = new Set<string>();\n if (/\\.xcodeproj|\\.xcworkspace|\\/ios\\/|\\.swift\\b/.test(text)) platforms.add(\"ios\");\n if (/\\/macos\\/|\\.entitlements\\b|appkit|\\.xcodeproj/.test(text)) platforms.add(\"macos\");\n if (/gradlew|settings\\.gradle|build\\.gradle|androidmanifest\\.xml|\\/android\\//.test(text)) platforms.add(\"android\");\n if (/package\\.json|next\\.config|src\\/app|src\\/pages/.test(text)) platforms.add(\"node\");\n if (/schema\\.prisma|\\/prisma\\//.test(text)) platforms.add(\"prisma\");\n if (/\\/landing\\/|next\\.config|astro\\.config|vite\\.config/.test(text)) platforms.add(\"web\");\n return [...platforms].sort();\n}\n\nfunction parseArtifactDescription(markdown: string): ArtifactIndexEntry[] {\n const entries: ArtifactIndexEntry[] = [];\n let category = \"\";\n let prefix = \"\";\n for (const line of markdown.split(/\\r?\\n/)) {\n const heading = /^##\\s+(.+?)(?:\\s+\\(`([^`]+)`\\))?\\s*$/.exec(line);\n if (heading) {\n category = heading[1]?.replace(/#+$/, \"\").trim() ?? \"\";\n prefix = normalizePath(heading[2] ?? \"\");\n if (prefix && !prefix.endsWith(\"/\")) prefix += \"/\";\n continue;\n }\n if (!/^\\|/.test(line) || /^(\\|\\s*-+)/.test(line)) continue;\n const cells = line.split(\"|\").slice(1, -1).map(cleanMarkdownCell);\n if (cells.length < 3 || /^file$/i.test(cells[0] ?? \"\")) continue;\n const fileName = cells[0] ?? \"\";\n if (!fileName || fileName.includes(\" \")) continue;\n const path = prefix ? `${prefix}${fileName}` : fileName;\n entries.push({\n path: normalizePath(path),\n category,\n ...(cells[1] ? { description: cells[1] } : {}),\n ...(cells[2] ? { useWhen: cells[2] } : {}),\n });\n }\n return entries;\n}\n\nasync function artifactMetadataByPath(workspace: string, rootRel: string): Promise<Map<string, ArtifactIndexEntry>> {\n const result = new Map<string, ArtifactIndexEntry>();\n const descriptionPath = resolveInsideWorkspace(workspace, `${rootRel}/description.md`);\n const description = await readExcerpt(descriptionPath, 80_000);\n if (!description) return result;\n for (const entry of parseArtifactDescription(description)) {\n const normalizedEntryPath = normalizePath(entry.path);\n result.set(normalizedEntryPath, entry);\n if (normalizedEntryPath.startsWith(\"artifacts/\")) {\n result.set(normalizePath(`${rootRel}/${normalizedEntryPath.replace(/^artifacts\\//, \"\")}`), entry);\n } else {\n result.set(normalizePath(`${rootRel}/${normalizedEntryPath}`), entry);\n }\n }\n return result;\n}\n\nasync function artifactRoots(workspace: string, preferredRoot?: string): Promise<Array<{ rel: string; abs: string }>> {\n const candidates = preferredRoot\n ? [preferredRoot]\n : [\"artifacts\", \".tania/artifacts\"];\n const roots: Array<{ rel: string; abs: string }> = [];\n for (const candidate of candidates) {\n const rel = normalizePath(candidate);\n const abs = resolveInsideWorkspace(workspace, rel);\n try {\n if ((await stat(abs)).isDirectory()) roots.push({ rel, abs });\n } catch {\n // Missing artifact roots are normal.\n }\n }\n return roots;\n}\n\nfunction platformMatches(path: string, platform?: string): boolean {\n if (!platform) return true;\n const lowerPath = path.toLowerCase();\n const normalized = platform.toLowerCase();\n if (normalized === \"apple\") return /\\/(?:ios|macos)\\//.test(lowerPath);\n return lowerPath.includes(`/${normalized}/`) || lowerPath.includes(`${normalized}/`);\n}\n\nfunction scoreArtifact(entry: ArtifactIndexEntry, rootRel: string, query: string): { score: number; reason: string } {\n const terms = termList(query);\n const haystack = [\n entry.path,\n entry.category,\n entry.description,\n entry.useWhen,\n ].filter(Boolean).join(\"\\n\").toLowerCase();\n if (terms.length === 0) return { score: 1, reason: \"listed from artifact root\" };\n\n let score = 0;\n const reasons: string[] = [];\n for (const term of terms) {\n if (entry.path.toLowerCase().includes(term)) {\n score += 5;\n reasons.push(`path:${term}`);\n }\n if ((entry.description ?? \"\").toLowerCase().includes(term)) {\n score += 3;\n reasons.push(`description:${term}`);\n }\n if ((entry.useWhen ?? \"\").toLowerCase().includes(term)) {\n score += 3;\n reasons.push(`useWhen:${term}`);\n }\n if ((entry.category ?? \"\").toLowerCase().includes(term)) {\n score += 2;\n reasons.push(`category:${term}`);\n }\n }\n if (entry.path.startsWith(`${rootRel}/`)) score += 1;\n return { score, reason: reasons.length ? [...new Set(reasons)].join(\", \") : \"weak filename/category match\" };\n}\n\nasync function findArtifacts(params: {\n workspace: string;\n artifactRoot?: string;\n query?: string;\n platform?: string;\n maxResults: number;\n}): Promise<ArtifactCandidate[]> {\n const roots = await artifactRoots(params.workspace, params.artifactRoot);\n const candidates: ArtifactCandidate[] = [];\n for (const root of roots) {\n const metadata = await artifactMetadataByPath(params.workspace, root.rel);\n const files = await collectFiles(root.abs, 1_000);\n for (const relFile of files) {\n if (relFile.endsWith(\"/\")) continue;\n if (/(\\.orig|\\.bak|\\.backup|\\.tmp|\\.DS_Store)$/i.test(relFile)) continue;\n const extension = extname(relFile);\n if (extension && !artifactFileExtensions.has(extension)) continue;\n const fullPath = normalizePath(`${root.rel}/${relFile}`);\n if (!platformMatches(fullPath, params.platform)) continue;\n const metadataEntry = metadata.get(fullPath)\n ?? metadata.get(normalizePath(`artifacts/${relFile}`))\n ?? metadata.get(relFile);\n const entry: ArtifactIndexEntry = {\n path: fullPath,\n ...(metadataEntry?.category ? { category: metadataEntry.category } : {}),\n ...(metadataEntry?.description ? { description: metadataEntry.description } : {}),\n ...(metadataEntry?.useWhen ? { useWhen: metadataEntry.useWhen } : {}),\n };\n const scored = scoreArtifact(entry, root.rel, params.query ?? \"\");\n if ((params.query ?? \"\").trim() && scored.score <= 0) continue;\n candidates.push({\n ...entry,\n root: root.rel,\n extension,\n score: scored.score,\n reason: scored.reason,\n });\n }\n }\n return candidates\n .sort((a, b) => b.score - a.score || a.path.localeCompare(b.path))\n .slice(0, params.maxResults);\n}\n\nfunction inferPlatformFromWorkspacePath(workspace: string): string | null {\n const m = workspace.toLowerCase().match(/\\/(ios|macos|android|backend|landing|web|script|cli)(?:\\/|$)/);\n if (!m) return null;\n // Normalize cli → script (the backing folder may be named either way).\n return m[1] === \"cli\" ? \"script\" : m[1] ?? null;\n}\n\nfunction inferTaskSignals(task: string, workspace?: string): { platforms: string[]; domains: string[] } {\n const text = task.toLowerCase();\n const platforms = new Set<string>();\n const domains = new Set<string>();\n const platformMatchers: Array<[string, RegExp]> = [\n [\"ios\", /\\bios\\b|swiftui|xcode|appicon\\.appiconset/],\n [\"macos\", /\\bmacos\\b|\\bmac\\b|appkit/],\n [\"android\", /\\bandroid\\b|kotlin|compose|gradle|play store/],\n [\"backend\", /\\bbackend\\b|api route|endpoint|server|prisma|postgres|database/],\n [\"web\", /\\bweb\\b|next\\.js|react|landing|vercel/],\n // Script/CLI signals: subcommands, packagers, completions, signing.\n [\"script\", /\\bcli\\b|\\bscript\\b|commander|clap|click\\b|cobra|homebrew|winget|launchd|systemd|pkgbuild|flatpak|notariz|authenticode|sigstore|cargo install|npm install -g|pipx/],\n ];\n const domainMatchers: Array<[string, RegExp]> = [\n [\"setup\", /\\bsetup\\b|scaffold|initialize|environment|foundation/],\n [\"artifact-reuse\", /\\bartifact|template|pattern|reuse|reusable/],\n [\"api-contract\", /\\bapi\\b|openapi|endpoint|route|contract|api_features/],\n [\"auth\", /\\bauth\\b|login|sign in|oauth|session|jwt/],\n [\"billing\", /revenuecat|storekit|subscription|premium|paywall|stripe|billing/],\n [\"icons\", /\\bicon\\b|appicon|launcher/],\n [\"splash\", /\\bsplash\\b|launch screen/],\n [\"onboarding\", /\\bonboarding\\b|first launch/],\n [\"localization\", /\\blocali[sz]ation\\b|translate|language|i18n/],\n [\"notifications\", /notification|push|fcm|apns/],\n [\"deep-links\", /deep link|universal link|app links|url scheme/],\n [\"landing\", /\\blanding\\b|marketing page|hero section|store badges|pricing/],\n [\"deploy\", /\\bdeploy\\b|azure|railway|vercel|app service/],\n [\"store\", /app store|play store|fastlane|release|submission/],\n [\"testing\", /\\btest\\b|ci|lint|typecheck|build|verify/],\n [\"data\", /room|swiftdata|prisma|database|offline|sync/],\n ];\n for (const [platform, matcher] of platformMatchers) if (matcher.test(text)) platforms.add(platform);\n for (const [domain, matcher] of domainMatchers) if (matcher.test(text)) domains.add(domain);\n const workspacePlatform = workspace ? inferPlatformFromWorkspacePath(workspace) : null;\n if (workspacePlatform) {\n return { platforms: [workspacePlatform], domains: [...domains].sort() };\n }\n return { platforms: [...platforms].sort(), domains: [...domains].sort() };\n}\n\nfunction recommendedVerificationCommands(files: string[], packageScripts: Record<string, string>, signals: { platforms: string[]; domains: string[] }): string[] {\n const commands = new Set<string>();\n const hasExplicitPlatformSignal = signals.platforms.length > 0;\n const hasScript = (name: string) => Object.prototype.hasOwnProperty.call(packageScripts, name);\n // Only recommend npm-script verifications when the workspace actually has\n // a package.json with that script. The previous `|| signals.domains.includes(\"data\")`\n // fallback misfired on iOS/Android workspaces where prompts mention session/sync/db\n // for context, which falsely triggered the data domain and made the agent run\n // `npm run prisma:generate` from a workspace with no package.json — leading to\n // a verify-blocker loop. See 2026-05-01 setup/1 incident.\n if (hasScript(\"prisma:generate\")) commands.add(\"npm run prisma:generate\");\n if (hasScript(\"typecheck\")) commands.add(\"npm run typecheck\");\n if (hasScript(\"test\")) commands.add(\"npm test\");\n if (hasScript(\"lint\")) commands.add(\"npm run lint\");\n if (hasScript(\"build\")) commands.add(\"npm run build\");\n const text = files.join(\"\\n\").toLowerCase();\n if (signals.platforms.includes(\"android\") || (!hasExplicitPlatformSignal && /gradlew|settings\\.gradle|androidmanifest\\.xml/.test(text))) {\n commands.add(\"./gradlew test --no-daemon\");\n commands.add(\"./gradlew assembleDebug --no-daemon\");\n if (/ktlint/.test(text)) commands.add(\"./gradlew ktlintCheck --no-daemon\");\n }\n if (signals.platforms.includes(\"ios\") || signals.platforms.includes(\"macos\") || (!hasExplicitPlatformSignal && /\\.xcodeproj|\\.xcworkspace/.test(text))) {\n commands.add(\"xcodebuild -list\");\n }\n // Script/CLI verifications — stack-aware. Detect the build system from\n // marker files in the workspace; never assume `npm run build` for non-Node\n // script projects, that's the same misfire pattern as the prisma:generate\n // bug fixed earlier in this session.\n if (signals.platforms.includes(\"script\")) {\n if (/cargo\\.toml/.test(text)) {\n commands.add(\"cargo build --release\");\n commands.add(\"cargo test\");\n }\n if (/pyproject\\.toml|setup\\.py/.test(text)) {\n commands.add(\"python -m pytest\");\n commands.add(\"python -m build\");\n }\n if (/go\\.mod/.test(text)) {\n commands.add(\"go build ./...\");\n commands.add(\"go test ./...\");\n }\n // Node CLI workspaces just reuse the npm-script recommendations above.\n }\n return [...commands];\n}\n\nfunction capabilityPacksForSignals(signals: { platforms: string[]; domains: string[] }): CapabilityPackBrief[] {\n const packs: CapabilityPackBrief[] = [];\n const hasPlatform = (platform: string) => signals.platforms.includes(platform);\n const hasDomain = (domain: string) => signals.domains.includes(domain);\n const add = (pack: CapabilityPackBrief) => packs.push(pack);\n\n if (hasPlatform(\"backend\") || hasDomain(\"api-contract\") || hasDomain(\"data\")) {\n add({\n id: \"backend-api\",\n reason: \"Task touches backend, API contract, routes, Prisma, database, or endpoint behavior.\",\n tools: [\"find_reusable_artifacts\", \"validate_api_contract_routes\", \"validate_prisma_schema\", \"scan_secrets\"],\n artifactHints: [\"backend/ApiRoutePattern\", \"backend/HealthRoute\", \"backend/OpenApiSwaggerRoutes\", \"backend/PrismaBase\", \"backend/MockDataSeedScript\"],\n validators: [\"api contract parity\", \"Prisma model presence\", \"secret scan\", \"backend health route\"],\n verificationHints: [\"typecheck\", \"test\", \"build\", \"prisma generate\"],\n });\n }\n if (hasPlatform(\"ios\") || hasPlatform(\"macos\")) {\n add({\n id: \"mobile-apple\",\n reason: \"Task touches iOS, macOS, SwiftUI, Xcode, app icons, StoreKit, or Apple release work.\",\n tools: [\"find_reusable_artifacts\", \"generate_app_icons\", \"create_ios_splash\", \"validate_apple_project_files\", \"validate_apple_app_icon_set\"],\n artifactHints: [\"ios/ThemeSystem\", \"ios/NavigationSetup\", \"ios/APIClient\", \"ios/FastlaneSetup\", \"ios/SplashScreenPattern\"],\n validators: [\"Xcode project files\", \"app icon slots\", \"Fastlane config\", \"splash contract\"],\n verificationHints: [\"xcodebuild -list\", \"xcodebuild build\"],\n });\n }\n if (hasPlatform(\"android\")) {\n add({\n id: \"mobile-android\",\n reason: \"Task touches Android, Kotlin, Compose, Gradle, Room, launcher assets, or Play release work.\",\n tools: [\"find_reusable_artifacts\", \"create_android_foundation\", \"create_android_splash\", \"generate_app_icons\", \"validate_android_project_config\"],\n artifactHints: [\"android/ThemeSystem\", \"android/NavigationSetup\", \"android/RoomSetup\", \"android/FastlaneSetup\", \"android/SplashScreenPattern\"],\n validators: [\"Gradle project config\", \"launcher icon resources\", \"foundation files\", \"Fastlane config\"],\n verificationHints: [\"./gradlew assembleDebug --no-daemon\", \"./gradlew test --no-daemon\", \"./gradlew ktlintCheck --no-daemon\"],\n });\n }\n if (hasPlatform(\"web\") || hasDomain(\"landing\")) {\n add({\n id: \"landing-web\",\n reason: \"Task touches web app, landing page, React/Next.js, marketing sections, or frontend build behavior.\",\n tools: [\"find_reusable_artifacts\", \"scan_secrets\"],\n artifactHints: [\"landing/hero\", \"landing/features\", \"landing/pricing\", \"components/store-badges\", \"web/WebAppFoundation\"],\n validators: [\"responsive page structure\", \"SEO/store links\", \"secret scan\"],\n verificationHints: [\"typecheck\", \"test\", \"build\"],\n });\n }\n if (hasDomain(\"store\") || hasDomain(\"billing\")) {\n add({\n id: \"store-release\",\n reason: \"Task touches store submission, Fastlane, subscriptions, paywalls, RevenueCat, StoreKit, Stripe, or release automation.\",\n tools: [\"find_reusable_artifacts\", \"validate_fastlane_config\", \"scan_secrets\"],\n artifactHints: [\"ios/FastlaneSetup\", \"android/FastlaneSetup\", \"ios/PaywallView\", \"ios/SubscriptionManagerFull\", \"android/RevenueCatBilling\"],\n validators: [\"Fastlane lanes\", \"secret placeholders\", \"subscription entitlement wiring\"],\n verificationHints: [\"Fastlane lane validation\", \"build lane\", \"syntax check\"],\n });\n }\n if (hasDomain(\"deploy\")) {\n add({\n id: \"deployment\",\n reason: \"Task touches deploy infrastructure, Azure/Railway/Vercel, DNS, email setup, or live endpoint checks.\",\n tools: [\"find_reusable_artifacts\", \"validate_api_contract_routes\", \"scan_secrets\"],\n artifactHints: [\"resources/azure-setup\", \"resources/email-setup\", \"backend/AzureBackendDeployChecklist\", \"testing/MobileCIWorkflows\"],\n validators: [\"env placeholder safety\", \"live endpoint smoke checks\", \"secret scan\"],\n verificationHints: [\"provider-specific dry run\", \"health endpoint\", \"build\"],\n });\n }\n\n return packs;\n}\n\nfunction artifactPlatformFilters(signals: { platforms: string[]; domains: string[] }): string[] {\n const filters: string[] = [];\n if (signals.platforms.includes(\"backend\")) filters.push(\"backend\");\n if (signals.platforms.includes(\"android\")) filters.push(\"android\");\n if (signals.platforms.includes(\"ios\") || signals.platforms.includes(\"macos\")) filters.push(\"apple\");\n if (signals.platforms.includes(\"web\")) filters.push(\"web\");\n if (signals.domains.includes(\"landing\")) filters.push(\"landing\");\n if (signals.domains.includes(\"store\")) filters.push(\"resources\", \"testing\");\n return [...new Set(filters)];\n}\n\nasync function findArtifactsForSignals(params: {\n workspace: string;\n query: string;\n signals: { platforms: string[]; domains: string[] };\n maxResults: number;\n}): Promise<ArtifactCandidate[]> {\n const filters = artifactPlatformFilters(params.signals);\n if (filters.length === 0) {\n return findArtifacts({\n workspace: params.workspace,\n query: params.query,\n maxResults: params.maxResults,\n });\n }\n\n const lists = await Promise.all(filters.map((platform) =>\n findArtifacts({\n workspace: params.workspace,\n query: params.query,\n platform,\n maxResults: params.maxResults,\n })\n ));\n const merged: ArtifactCandidate[] = [];\n const seen = new Set<string>();\n for (let index = 0; merged.length < params.maxResults && index < params.maxResults; index += 1) {\n for (const list of lists) {\n const candidate = list[index];\n if (!candidate || seen.has(candidate.path)) continue;\n seen.add(candidate.path);\n merged.push(candidate);\n if (merged.length >= params.maxResults) break;\n }\n }\n return merged;\n}\n\nexport async function buildTaskBrief(input: {\n workspace: string;\n task: string;\n maxArtifacts?: number;\n maxContextFiles?: number;\n}): Promise<TanyaTaskBrief> {\n const maxArtifacts = Math.min(input.maxArtifacts ?? 12, 40);\n const maxContextFiles = Math.min(input.maxContextFiles ?? 16, 50);\n const files = await collectFiles(input.workspace, 1_000);\n const packageScripts = await readPackageScripts(input.workspace);\n const signals = inferTaskSignals(input.task, input.workspace);\n const contextFiles = files\n .filter((file) => !file.endsWith(\"/\"))\n .map((file) => ({ path: file, role: classifyContextFile(file) }))\n .filter((file): file is { path: string; role: string } => Boolean(file.role))\n .slice(0, maxContextFiles);\n const artifactQuery = [input.task, signals.platforms.join(\" \"), signals.domains.join(\" \")].filter(Boolean).join(\" \");\n const artifacts = await findArtifactsForSignals({\n workspace: input.workspace,\n query: artifactQuery,\n signals,\n maxResults: maxArtifacts,\n });\n const verification = recommendedVerificationCommands(files, packageScripts, signals);\n const capabilityPacks = capabilityPacksForSignals(signals);\n const recommendedTools = [\n \"inspect_project_context\",\n artifacts.length > 0 ? \"find_reusable_artifacts\" : null,\n signals.domains.includes(\"api-contract\") ? \"validate_api_contract_routes\" : null,\n signals.domains.includes(\"icons\") ? \"generate_app_icons\" : null,\n signals.domains.includes(\"splash\") && (signals.platforms.includes(\"ios\") || signals.platforms.includes(\"macos\")) ? \"create_ios_splash\" : null,\n signals.domains.includes(\"splash\") && signals.platforms.includes(\"android\") ? \"create_android_splash\" : null,\n signals.domains.includes(\"setup\") && signals.platforms.includes(\"android\") ? \"create_android_foundation\" : null,\n ...capabilityPacks.flatMap((pack) => pack.tools),\n \"scan_secrets\",\n ].filter((value): value is string => typeof value === \"string\");\n\n return {\n task: input.task,\n signals,\n contextFiles,\n artifacts,\n verification,\n recommendedTools: [...new Set(recommendedTools)],\n capabilityPacks,\n cautions: [\n \"Do not hardcode secrets; only write placeholders or document required manual configuration.\",\n \"Read contracts such as brand, safety, API_FEATURES, OpenAPI, schema, and artifact indexes before editing affected areas.\",\n \"Prefer existing repo patterns and reusable artifacts before inventing a new implementation.\",\n ],\n };\n}\n\nexport const inspectProjectContextTool: TanyaTool = {\n name: \"inspect_project_context\",\n description: \"Inspect local project instructions, contracts, artifact indexes, platforms, and verification hints.\",\n definition: {\n type: \"function\",\n function: {\n name: \"inspect_project_context\",\n description: \"Inspect local project instructions, contracts, artifact indexes, platforms, and verification hints before a broad coding task.\",\n parameters: {\n type: \"object\",\n properties: {\n path: { type: \"string\", description: \"Optional directory relative to the workspace. Default workspace root.\" },\n includeExcerpts: { type: \"boolean\", description: \"Include short text excerpts from context files. Default true.\" },\n maxFiles: { type: \"number\", description: \"Maximum files to inspect. Default 500.\" },\n maxExcerptChars: { type: \"number\", description: \"Maximum excerpt characters per context file. Default 900.\" },\n },\n additionalProperties: false,\n },\n },\n },\n async run(input, context) {\n const record = asRecord(input);\n const root = resolveOptionalWorkspacePath(context, asOptionalString(record, \"path\"));\n const rootRel = normalizePath(relative(context.workspace, root)) || \".\";\n const includeExcerpts = asOptionalBoolean(input, \"includeExcerpts\", true);\n const maxFiles = Math.min(asOptionalNumber(input, \"maxFiles\", 500), 2_000);\n const maxExcerptChars = Math.min(asOptionalNumber(input, \"maxExcerptChars\", 900), 4_000);\n const files = await collectFiles(root, maxFiles);\n const platforms = detectPlatforms(files);\n const packageScripts = await readPackageScripts(root);\n const contextFiles = [];\n for (const file of files) {\n if (file.endsWith(\"/\")) continue;\n const role = classifyContextFile(file);\n if (!role) continue;\n const abs = resolve(root, file);\n contextFiles.push({\n path: rootRel === \".\" ? file : normalizePath(`${rootRel}/${file}`),\n role,\n ...(includeExcerpts ? { excerpt: await readExcerpt(abs, maxExcerptChars) } : {}),\n });\n }\n const verification = recommendedVerificationCommands(files, packageScripts, { platforms, domains: [] });\n let artifactsCatalog: { hint: string; head: string } | null = null;\n try {\n const candidates = [\"artifacts/description.md\", \".tania/artifacts/description.md\"];\n for (const rel of candidates) {\n const abs = resolve(root, rel);\n if (existsSync(abs)) {\n const head = (await readFile(abs, \"utf8\")).split(\"\\n\").slice(0, 24).join(\"\\n\");\n artifactsCatalog = { hint: `Read ${rel} (full file) for the complete artifact catalog before writing code from scratch.`, head };\n break;\n }\n }\n } catch {\n // best-effort\n }\n return {\n ok: true,\n summary: `Inspected ${files.length} workspace path${files.length === 1 ? \"\" : \"s\"} and found ${contextFiles.length} context file${contextFiles.length === 1 ? \"\" : \"s\"}${artifactsCatalog ? \"; artifacts catalog detected\" : \"\"}.`,\n output: {\n root: rootRel,\n platforms,\n packageScripts,\n contextFiles,\n ...(artifactsCatalog ? { artifactsCatalog } : {}),\n verification,\n notes: [\n \"Read relevant context files before editing.\",\n \"Use find_reusable_artifacts before creating common app, backend, deployment, or UI patterns from scratch.\",\n ],\n },\n };\n },\n};\n\nexport const findReusableArtifactsTool: TanyaTool = {\n name: \"find_reusable_artifacts\",\n description: \"Search local artifacts directories for reusable patterns matching a task, platform, or keyword.\",\n definition: {\n type: \"function\",\n function: {\n name: \"find_reusable_artifacts\",\n description: \"Search local artifacts directories for reusable patterns matching a task, platform, or keyword. Works with artifacts/ and .tania/artifacts.\",\n parameters: {\n type: \"object\",\n properties: {\n query: { type: \"string\", description: \"Task text or search keywords.\" },\n platform: { type: \"string\", description: \"Optional platform/category filter such as ios, android, backend, web, landing, testing, resources, apple.\" },\n artifactRoot: { type: \"string\", description: \"Optional artifact root relative to the workspace. Default searches artifacts and .tania/artifacts.\" },\n maxResults: { type: \"number\", description: \"Maximum results. Default 12.\" },\n },\n additionalProperties: false,\n },\n },\n },\n async run(input, context) {\n const query = asOptionalString(input, \"query\") ?? \"\";\n const platform = asOptionalString(input, \"platform\");\n const maxResults = Math.min(asOptionalNumber(input, \"maxResults\", 12), 50);\n const artifactRoot = asOptionalString(input, \"artifactRoot\");\n const artifacts = await findArtifacts({\n workspace: context.workspace,\n query,\n maxResults,\n ...(artifactRoot ? { artifactRoot } : {}),\n ...(platform ? { platform } : {}),\n });\n return {\n ok: true,\n summary: `Found ${artifacts.length} reusable artifact candidate${artifacts.length === 1 ? \"\" : \"s\"}.`,\n output: {\n query,\n platform: platform ?? null,\n artifacts,\n guidance: artifacts.length > 0\n ? \"Read the relevant artifact path before adapting it, then report precise Artifact reused provenance.\"\n : \"No matching local artifacts were found; proceed with repo patterns and create a reusable artifact only if the task produces a generally reusable pattern.\",\n },\n };\n },\n};\n\nexport const buildTaskBriefTool: TanyaTool = {\n name: \"build_task_brief\",\n description: \"Build a deterministic pre-implementation brief from task text, local context files, artifacts, and verification hints.\",\n definition: {\n type: \"function\",\n function: {\n name: \"build_task_brief\",\n description: \"Build a deterministic pre-implementation brief from task text, local context files, artifacts, and verification hints.\",\n parameters: {\n type: \"object\",\n properties: {\n task: { type: \"string\", description: \"The coding or project task to brief.\" },\n maxArtifacts: { type: \"number\", description: \"Maximum artifact candidates. Default 12.\" },\n maxContextFiles: { type: \"number\", description: \"Maximum context files to list. Default 16.\" },\n },\n required: [\"task\"],\n additionalProperties: false,\n },\n },\n },\n async run(input, context) {\n const task = asString(input, \"task\");\n const brief = await buildTaskBrief({\n workspace: context.workspace,\n task,\n maxArtifacts: Math.min(asOptionalNumber(input, \"maxArtifacts\", 12), 40),\n maxContextFiles: Math.min(asOptionalNumber(input, \"maxContextFiles\", 16), 50),\n });\n\n return {\n ok: true,\n summary: `Built task brief with ${brief.signals.platforms.length} platform signal${brief.signals.platforms.length === 1 ? \"\" : \"s\"}, ${brief.signals.domains.length} domain signal${brief.signals.domains.length === 1 ? \"\" : \"s\"}, and ${brief.artifacts.length} artifact candidate${brief.artifacts.length === 1 ? \"\" : \"s\"}.`,\n output: brief,\n };\n },\n};\n","import { existsSync } from \"node:fs\";\nimport { mkdir, readdir, readFile, stat, writeFile } from \"node:fs/promises\";\nimport { dirname, join, relative, resolve } from \"node:path\";\n\nconst ignoredNames = new Set([\".obsidian\", \".trash\", \".git\", \"node_modules\", \".tania\"]);\n\nconst stopwords = new Set([\n \"a\",\n \"an\",\n \"and\",\n \"app\",\n \"as\",\n \"at\",\n \"by\",\n \"create\",\n \"for\",\n \"from\",\n \"in\",\n \"new\",\n \"of\",\n \"on\",\n \"or\",\n \"the\",\n \"to\",\n \"up\",\n \"use\",\n \"with\",\n]);\n\nexport type ObsidianSearchResult = {\n path: string;\n title: string;\n score: number;\n reason: string;\n excerpt: string;\n modifiedAt: string | null;\n};\n\nexport type MaterializedObsidianContext = {\n contextFiles: Array<{\n path: string;\n sourcePath: string;\n role: \"obsidian-note\";\n status: \"available\";\n reason: string;\n }>;\n notes: ObsidianSearchResult[];\n};\n\nfunction normalizePath(path: string): string {\n return path.replace(/\\\\/g, \"/\").replace(/^\\.\\/+/, \"\").replace(/\\/+/g, \"/\");\n}\n\nfunction terms(query: string): string[] {\n return [...new Set(query.toLowerCase().match(/[a-z0-9_+-]{2,}/g) ?? [])]\n .filter((term) => !stopwords.has(term));\n}\n\nasync function collectMarkdownFiles(root: string, maxFiles: number, current = root, out: string[] = []): Promise<string[]> {\n if (out.length >= maxFiles) return out;\n let entries;\n try {\n entries = await readdir(current, { withFileTypes: true });\n } catch {\n return out;\n }\n entries.sort((a, b) => a.name.localeCompare(b.name));\n for (const entry of entries) {\n if (out.length >= maxFiles) break;\n if (ignoredNames.has(entry.name)) continue;\n const fullPath = join(current, entry.name);\n if (entry.isDirectory()) {\n await collectMarkdownFiles(root, maxFiles, fullPath, out);\n } else if (entry.isFile() && /\\.md$/i.test(entry.name)) {\n out.push(fullPath);\n }\n }\n return out;\n}\n\nfunction titleFromMarkdown(path: string, markdown: string): string {\n const heading = markdown.match(/^#\\s+(.+)$/m)?.[1]?.trim();\n if (heading) return heading;\n return path.split(\"/\").pop()?.replace(/\\.md$/i, \"\") ?? path;\n}\n\nfunction redactSecrets(markdown: string): string {\n return markdown\n .split(/\\r?\\n/)\n .map((line) => {\n if (/placeholder|example|changeme|your_|<[^>]+>|\\$\\{|process\\.env|env\\(/i.test(line)) return line;\n if (/\\b[A-Za-z0-9_-]*(?:api[_-]?key|secret|token|password|private[_-]?key|client[_-]?secret|database_url)[A-Za-z0-9_-]*\\b\\s*[:=]\\s*[\"']?[A-Za-z0-9_./+=-]{16,}/i.test(line)) {\n return \"[redacted possible secret]\";\n }\n return line;\n })\n .join(\"\\n\");\n}\n\nfunction excerptFor(markdown: string, queryTerms: string[], maxChars: number): string {\n const redacted = redactSecrets(markdown);\n const lines = redacted.split(/\\r?\\n/);\n const firstMatch = lines.findIndex((line) => queryTerms.some((term) => line.toLowerCase().includes(term)));\n const start = firstMatch >= 0 ? Math.max(0, firstMatch - 3) : 0;\n const excerpt = lines.slice(start, start + 12).join(\"\\n\").trim() || redacted.slice(0, maxChars);\n return excerpt.length > maxChars ? `${excerpt.slice(0, maxChars)}\\n[truncated]` : excerpt;\n}\n\nfunction scoreNote(relPath: string, title: string, markdown: string, queryTerms: string[]): { score: number; reason: string } {\n const lowerPath = relPath.toLowerCase();\n const lowerTitle = title.toLowerCase();\n const lowerMarkdown = markdown.toLowerCase();\n let score = 0;\n const reasons: string[] = [];\n for (const term of queryTerms) {\n if (lowerPath.includes(term)) {\n score += 5;\n reasons.push(`path:${term}`);\n }\n if (lowerTitle.includes(term)) {\n score += 5;\n reasons.push(`title:${term}`);\n }\n if (lowerMarkdown.includes(term)) {\n score += 1;\n reasons.push(`body:${term}`);\n }\n }\n return { score, reason: reasons.length ? [...new Set(reasons)].join(\", \") : \"recent note fallback\" };\n}\n\nfunction safeMaterializedPath(relPath: string): string {\n return normalizePath(relPath)\n .replace(/^\\.+\\/?/, \"\")\n .replace(/[^A-Za-z0-9._/-]/g, \"_\")\n .replace(/\\/+/g, \"/\");\n}\n\nexport async function searchObsidianNotes(input: {\n vaultPath: string;\n query: string;\n maxResults?: number;\n maxFiles?: number;\n maxExcerptChars?: number;\n}): Promise<ObsidianSearchResult[]> {\n const vault = resolve(input.vaultPath);\n if (!existsSync(vault)) return [];\n const queryTerms = terms(input.query);\n const maxResults = Math.min(input.maxResults ?? 5, 20);\n const maxFiles = Math.min(input.maxFiles ?? 1_000, 5_000);\n const maxExcerptChars = Math.min(input.maxExcerptChars ?? 1_800, 8_000);\n const files = await collectMarkdownFiles(vault, maxFiles);\n const results: ObsidianSearchResult[] = [];\n\n for (const file of files) {\n let markdown = \"\";\n try {\n markdown = await readFile(file, \"utf8\");\n } catch {\n continue;\n }\n const relPath = normalizePath(relative(vault, file));\n const title = titleFromMarkdown(relPath, markdown);\n const scored = scoreNote(relPath, title, markdown, queryTerms);\n if (queryTerms.length > 0 && scored.score <= 0) continue;\n const fileStat = await stat(file);\n results.push({\n path: relPath,\n title,\n score: scored.score,\n reason: scored.reason,\n excerpt: excerptFor(markdown, queryTerms, maxExcerptChars),\n modifiedAt: Number.isFinite(fileStat.mtimeMs) ? fileStat.mtime.toISOString() : null,\n });\n }\n\n return results\n .sort((a, b) => b.score - a.score || String(b.modifiedAt ?? \"\").localeCompare(String(a.modifiedAt ?? \"\")) || a.path.localeCompare(b.path))\n .slice(0, maxResults);\n}\n\nexport async function materializeObsidianContext(input: {\n workspace: string;\n vaultPath: string;\n query: string;\n maxResults?: number;\n keepContext?: boolean;\n}): Promise<MaterializedObsidianContext> {\n const notes = await searchObsidianNotes({\n vaultPath: input.vaultPath,\n query: input.query,\n maxResults: input.maxResults ?? 5,\n });\n const contextRoot = resolve(input.workspace, \".tania\", \"context\", \"obsidian\");\n const contextFiles: MaterializedObsidianContext[\"contextFiles\"] = [];\n for (const note of notes) {\n const targetRel = safeMaterializedPath(note.path);\n const targetPath = resolve(contextRoot, targetRel);\n const localPath = `.tania/context/obsidian/${normalizePath(targetRel)}`;\n const content = [\n `# ${note.title}`,\n \"\",\n `Source: ${note.path}`,\n `Score: ${note.score}`,\n `Reason: ${note.reason}`,\n note.modifiedAt ? `Modified: ${note.modifiedAt}` : null,\n \"\",\n \"## Excerpt\",\n \"\",\n note.excerpt,\n \"\",\n ].filter((line): line is string => typeof line === \"string\").join(\"\\n\");\n await mkdir(dirname(targetPath), { recursive: true });\n await writeFile(targetPath, content, \"utf8\");\n contextFiles.push({\n path: localPath,\n sourcePath: note.path,\n role: \"obsidian-note\",\n status: \"available\",\n reason: \"Materialized from the configured Obsidian vault by task-term search.\",\n });\n }\n\n if (contextFiles.length > 0) {\n await mkdir(contextRoot, { recursive: true });\n await writeFile(\n resolve(contextRoot, \"manifest.json\"),\n JSON.stringify({ generatedAt: new Date().toISOString(), query: input.query, notes }, null, 2),\n \"utf8\",\n );\n }\n\n return { contextFiles, notes };\n}\n","import type { TanyaTool } from \"./types\";\nimport { envValue } from \"../config/envCompat\";\nimport { materializeObsidianContext, searchObsidianNotes } from \"../obsidian/search\";\n\nfunction asRecord(input: unknown): Record<string, unknown> {\n return input && typeof input === \"object\" ? (input as Record<string, unknown>) : {};\n}\n\nfunction asOptionalString(input: unknown, key: string): string | undefined {\n const value = asRecord(input)[key];\n return typeof value === \"string\" && value.trim() ? value.trim() : undefined;\n}\n\nfunction asOptionalNumber(input: unknown, key: string, fallback: number): number {\n const value = asRecord(input)[key];\n return typeof value === \"number\" && Number.isFinite(value) ? value : fallback;\n}\n\nfunction asOptionalBoolean(input: unknown, key: string, fallback: boolean): boolean {\n const value = asRecord(input)[key];\n if (typeof value === \"boolean\") return value;\n if (typeof value === \"string\") return /^(true|yes|1)$/i.test(value.trim());\n return fallback;\n}\n\nexport const searchObsidianNotesTool: TanyaTool = {\n name: \"search_obsidian_notes\",\n description: \"Search the configured Obsidian vault for task-relevant markdown notes and optionally materialize excerpts into .tania/context.\",\n definition: {\n type: \"function\",\n function: {\n name: \"search_obsidian_notes\",\n description: \"Search TANYA_OBSIDIAN_VAULT for task-relevant markdown notes. Use materialize=true before relying on notes as coding context.\",\n parameters: {\n type: \"object\",\n properties: {\n query: { type: \"string\", description: \"Search terms or task text.\" },\n maxResults: { type: \"number\", description: \"Maximum notes to return. Default 5.\" },\n materialize: { type: \"boolean\", description: \"Materialize matching note excerpts into .tania/context/obsidian. Default false.\" },\n },\n required: [\"query\"],\n additionalProperties: false,\n },\n },\n },\n async run(input, context) {\n const query = asOptionalString(input, \"query\");\n if (!query) throw new Error(\"Missing string field: query\");\n const vaultPath = envValue({}, \"TANYA_OBSIDIAN_VAULT\").trim();\n if (!vaultPath) {\n return {\n ok: true,\n summary: \"No Obsidian vault configured.\",\n output: { notes: [], guidance: \"Set TANYA_OBSIDIAN_VAULT to enable generic note retrieval.\" },\n };\n }\n const maxResults = Math.min(asOptionalNumber(input, \"maxResults\", 5), 20);\n if (asOptionalBoolean(input, \"materialize\", false)) {\n const materialized = await materializeObsidianContext({\n workspace: context.workspace,\n vaultPath,\n query,\n maxResults,\n });\n return {\n ok: true,\n summary: `Materialized ${materialized.contextFiles.length} Obsidian note excerpt${materialized.contextFiles.length === 1 ? \"\" : \"s\"}.`,\n output: materialized,\n };\n }\n const notes = await searchObsidianNotes({ vaultPath, query, maxResults });\n return {\n ok: true,\n summary: `Found ${notes.length} Obsidian note${notes.length === 1 ? \"\" : \"s\"}.`,\n output: {\n notes,\n guidance: notes.length > 0\n ? \"Call search_obsidian_notes again with materialize=true before relying on note contents for implementation.\"\n : \"No matching notes were found.\",\n },\n };\n },\n};\n","import { existsSync, mkdirSync, readdirSync, rmSync, statSync, writeFileSync } from \"node:fs\";\nimport { readFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\n\nexport const RESULT_CACHE_MAX_BYTES = 100 * 1024 * 1024;\n\nexport type ResultByteRange = {\n startByte: number;\n endByte: number;\n};\n\nfunction safeSegment(value: string): string {\n return value.replace(/[^A-Za-z0-9_.-]+/g, \"_\").slice(0, 160) || \"result\";\n}\n\nexport function resultCacheDir(workspace: string, runId: string): string {\n return join(workspace, \".tania\", \"cache\", \"results\", safeSegment(runId));\n}\n\nexport function resultCachePath(workspace: string, runId: string, toolCallId: string): string {\n return join(resultCacheDir(workspace, runId), `${safeSegment(toolCallId)}.txt`);\n}\n\nexport function writeCachedToolResult(workspace: string, runId: string, toolCallId: string, content: string): string {\n const dir = resultCacheDir(workspace, runId);\n mkdirSync(dir, { recursive: true });\n const path = resultCachePath(workspace, runId, toolCallId);\n writeFileSync(path, content, \"utf8\");\n evictRunCache(dir);\n return path;\n}\n\nexport async function readCachedToolResult(\n workspace: string,\n runId: string,\n toolCallId: string,\n range?: ResultByteRange,\n): Promise<string | null> {\n const path = resultCachePath(workspace, runId, toolCallId);\n if (!existsSync(path)) return null;\n const buffer = await readFile(path);\n if (!range) return buffer.toString(\"utf8\");\n const start = Math.max(0, Math.floor(range.startByte));\n const end = Math.max(start, Math.min(buffer.length, Math.floor(range.endByte)));\n return buffer.subarray(start, end).toString(\"utf8\");\n}\n\nfunction evictRunCache(dir: string): void {\n let entries = cacheEntries(dir);\n let total = entries.reduce((sum, entry) => sum + entry.size, 0);\n if (total <= RESULT_CACHE_MAX_BYTES) return;\n for (const entry of entries.sort((a, b) => a.mtimeMs - b.mtimeMs)) {\n try {\n rmSync(entry.path, { force: true });\n total -= entry.size;\n if (total <= RESULT_CACHE_MAX_BYTES) break;\n } catch {\n // Cache eviction is best-effort.\n }\n }\n entries = cacheEntries(dir);\n if (entries.length === 0) {\n try { rmSync(dir, { force: true, recursive: true }); } catch { /* best-effort */ }\n }\n}\n\nfunction cacheEntries(dir: string): Array<{ path: string; size: number; mtimeMs: number }> {\n try {\n return readdirSync(dir)\n .filter((file) => file.endsWith(\".txt\"))\n .flatMap((file) => {\n const path = join(dir, file);\n try {\n const stat = statSync(path);\n return stat.isFile() ? [{ path, size: stat.size, mtimeMs: stat.mtimeMs }] : [];\n } catch {\n return [];\n }\n });\n } catch {\n return [];\n }\n}\n","import { readCachedToolResult, type ResultByteRange } from \"../memory/resultCache\";\nimport type { TanyaTool } from \"./types\";\n\nfunction asRecord(input: unknown): Record<string, unknown> {\n return input && typeof input === \"object\" && !Array.isArray(input) ? input as Record<string, unknown> : {};\n}\n\nfunction asString(input: unknown, key: string): string {\n const value = asRecord(input)[key];\n if (typeof value !== \"string\" || !value.trim()) throw new Error(`Missing string field: ${key}`);\n return value.trim();\n}\n\nfunction rangeFromInput(input: unknown): ResultByteRange | undefined {\n const range = asRecord(input).range;\n if (!range || typeof range !== \"object\" || Array.isArray(range)) return undefined;\n const record = range as Record<string, unknown>;\n const startByte = typeof record.startByte === \"number\" ? record.startByte : undefined;\n const endByte = typeof record.endByte === \"number\" ? record.endByte : undefined;\n if (startByte === undefined || endByte === undefined) return undefined;\n return { startByte, endByte };\n}\n\nexport const expandResultTool: TanyaTool = {\n name: \"expand_result\",\n description: \"Expand a previously truncated tool result by tool call id.\",\n truncateLargeResults: false,\n definition: {\n type: \"function\",\n function: {\n name: \"expand_result\",\n description: \"Fetch the full output, or a byte range, for a previously truncated tool result in this run.\",\n parameters: {\n type: \"object\",\n properties: {\n tool_call_id: { type: \"string\", description: \"Tool call id from the truncation marker.\" },\n range: {\n type: \"object\",\n description: \"Optional byte range to return.\",\n properties: {\n startByte: { type: \"number\" },\n endByte: { type: \"number\" },\n },\n required: [\"startByte\", \"endByte\"],\n additionalProperties: false,\n },\n },\n required: [\"tool_call_id\"],\n additionalProperties: false,\n },\n },\n },\n async run(input, context) {\n if (!context.runId) {\n return {\n ok: false,\n summary: \"No run id available for result expansion.\",\n error: \"expand_result can only be used inside an active Tanya run.\",\n };\n }\n const toolCallId = asString(input, \"tool_call_id\");\n const content = await readCachedToolResult(context.workspace, context.runId, toolCallId, rangeFromInput(input));\n if (content === null) {\n return {\n ok: false,\n summary: `No cached result found for ${toolCallId}.`,\n error: \"The result may have expired from the per-run cache or was never truncated.\",\n };\n }\n return {\n ok: true,\n summary: `Expanded result ${toolCallId}.`,\n output: content,\n };\n },\n};\n","import { existsSync, realpathSync } from \"node:fs\";\nimport { randomUUID } from \"node:crypto\";\nimport { relative, resolve } from \"node:path\";\nimport type { TanyaRunContext } from \"../context/runContext\";\nimport type { ChatMessage } from \"../providers/types\";\nimport type { PermissionContext } from \"../safety/permissions/engine\";\nimport type { PermissionRulesConfig, SpendRule } from \"../safety/permissions/schema\";\n\nexport type SubAgentTokenBudget = {\n max_usd?: number;\n max_tokens?: number;\n expectedSiblings?: number;\n};\n\nexport type RunAgentParentContext = {\n runId: string;\n workspace: string;\n permissionContext: PermissionContext;\n runContext?: TanyaRunContext;\n history?: ChatMessage[];\n childIndex?: number;\n tokenBudget?: SubAgentTokenBudget;\n};\n\nexport function createRootRunId(now: Date = new Date()): string {\n return `r-${now.getTime().toString(36)}-${randomUUID().slice(0, 8)}`;\n}\n\nexport function childRunId(parentRunId: string, childIndex: number): string {\n return `${parentRunId}.t-${Math.max(1, Math.floor(childIndex))}`;\n}\n\nexport function runIdDepth(runId: string): number {\n return Math.max(0, runId.split(\".\").length - 1);\n}\n\nexport function resolveSubAgentWorkspace(parentWorkspace: string, requestedWorkspace?: string): string {\n const target = resolve(parentWorkspace, requestedWorkspace ?? \".\");\n const lexicalRel = relative(parentWorkspace, target);\n if (lexicalRel.startsWith(\"..\") || lexicalRel === \"..\") {\n throw new Error(`Sub-agent workspace escapes parent workspace: ${requestedWorkspace ?? target}`);\n }\n if (!existsSync(target)) return target;\n const realParent = realpathSync(parentWorkspace);\n const realTarget = realpathSync(target);\n const realRel = relative(realParent, realTarget);\n if (realRel.startsWith(\"..\") || realRel === \"..\") {\n throw new Error(`Sub-agent workspace escapes parent workspace via symlink: ${requestedWorkspace ?? target}`);\n }\n return realTarget;\n}\n\nexport function mergeRunContexts(parent?: TanyaRunContext, child?: TanyaRunContext): TanyaRunContext | undefined {\n if (!parent) return child;\n if (!child) return cloneRunContext(parent);\n const merged: TanyaRunContext = {};\n if (parent.task || child.task) merged.task = { ...(parent.task ?? {}), ...(child.task ?? {}) };\n const artifacts = mergeObjectLists(parent.artifacts, child.artifacts, \"path\");\n if (artifacts) merged.artifacts = artifacts;\n const contextFiles = mergeObjectLists(parent.contextFiles, child.contextFiles, \"path\");\n if (contextFiles) merged.contextFiles = contextFiles;\n const instructions = unique([...(parent.instructions ?? []), ...(child.instructions ?? [])]);\n if (instructions) merged.instructions = instructions;\n const verificationCommands = unique([...(parent.verification?.commands ?? []), ...(child.verification?.commands ?? [])]);\n if (verificationCommands) merged.verification = { commands: verificationCommands };\n const languages = unique([...(parent.languages ?? []), ...(child.languages ?? [])]);\n if (languages) merged.languages = languages;\n const frameworks = unique([...(parent.frameworks ?? []), ...(child.frameworks ?? [])]);\n if (frameworks) merged.frameworks = frameworks;\n const stack = child.stack ?? parent.stack;\n if (stack) merged.stack = stack;\n const expectedReport = child.expected_report ?? parent.expected_report;\n if (expectedReport) merged.expected_report = expectedReport;\n const metadata = { ...(parent.metadata ?? {}), ...(child.metadata ?? {}) };\n if (Object.keys(metadata).length > 0) merged.metadata = metadata;\n return merged;\n}\n\nexport function applyTokenBudgetRule(rules: PermissionRulesConfig, budget?: SubAgentTokenBudget): PermissionRulesConfig {\n if (!budget || (budget.max_tokens === undefined && budget.max_usd === undefined)) return rules;\n const spendRule: SpendRule = {\n type: \"spend\",\n scope: \"session\",\n ...(budget.max_usd !== undefined ? { max_usd: budget.max_usd } : {}),\n ...(budget.max_tokens !== undefined ? { max_tokens: budget.max_tokens } : {}),\n action: \"deny\",\n };\n return {\n ...rules,\n spendRules: [...rules.spendRules, spendRule],\n };\n}\n\nfunction cloneRunContext(context: TanyaRunContext): TanyaRunContext {\n return {\n ...(context.task ? { task: { ...context.task } } : {}),\n ...(context.artifacts ? { artifacts: context.artifacts.map((item) => ({ ...item })) } : {}),\n ...(context.contextFiles ? { contextFiles: context.contextFiles.map((item) => ({ ...item })) } : {}),\n ...(context.instructions ? { instructions: [...context.instructions] } : {}),\n ...(context.verification ? { verification: { commands: [...(context.verification.commands ?? [])] } } : {}),\n ...(context.languages ? { languages: [...context.languages] } : {}),\n ...(context.frameworks ? { frameworks: [...context.frameworks] } : {}),\n ...(context.stack ? { stack: context.stack } : {}),\n ...(context.expected_report ? { expected_report: { ...context.expected_report } } : {}),\n ...(context.metadata ? { metadata: { ...context.metadata } } : {}),\n };\n}\n\nfunction mergeObjectLists<T extends Record<string, unknown>>(parent: T[] | undefined, child: T[] | undefined, key: keyof T): T[] | undefined {\n const merged = new Map<unknown, T>();\n for (const item of parent ?? []) merged.set(item[key], { ...item });\n for (const item of child ?? []) merged.set(item[key], { ...merged.get(item[key]), ...item });\n return merged.size > 0 ? [...merged.values()] : undefined;\n}\n\nfunction unique(values: string[]): string[] | undefined {\n const result = [...new Set(values.filter((value) => value.trim().length > 0))];\n return result.length > 0 ? result : undefined;\n}\n","import { decide } from \"../safety/permissions/engine\";\nimport { runIdDepth } from \"../agent/subAgentContext\";\nimport { envValue } from \"../config/envCompat\";\nimport type { TanyaTool, SubAgentTaskRequest } from \"./types\";\n\nfunction asRecord(input: unknown): Record<string, unknown> {\n return input && typeof input === \"object\" && !Array.isArray(input) ? input as Record<string, unknown> : {};\n}\n\nfunction parseTaskInput(input: unknown): SubAgentTaskRequest {\n const record = asRecord(input);\n const prompt = typeof record.prompt === \"string\" ? record.prompt.trim() : \"\";\n if (!prompt) throw new Error(\"Missing string field: prompt\");\n const workspace = typeof record.workspace === \"string\" && record.workspace.trim() ? record.workspace.trim() : undefined;\n const maxTurns = typeof record.max_turns === \"number\" && Number.isFinite(record.max_turns)\n ? Math.max(1, Math.floor(record.max_turns))\n : undefined;\n const skillPackOverrides = Array.isArray(record.skill_pack_overrides)\n ? record.skill_pack_overrides.filter((item): item is string => typeof item === \"string\" && item.trim().length > 0)\n : undefined;\n const tokenBudget = asRecord(record.token_budget);\n const maxUsd = typeof tokenBudget.max_usd === \"number\" && Number.isFinite(tokenBudget.max_usd) ? tokenBudget.max_usd : undefined;\n const maxTokens = typeof tokenBudget.max_tokens === \"number\" && Number.isFinite(tokenBudget.max_tokens) ? tokenBudget.max_tokens : undefined;\n const modelRecord = asRecord(record.model);\n const model = typeof modelRecord.provider === \"string\" && modelRecord.provider.trim() &&\n typeof modelRecord.model === \"string\" && modelRecord.model.trim()\n ? { provider: modelRecord.provider.trim(), model: modelRecord.model.trim() }\n : undefined;\n const rawFailurePolicy = record.treat_failure_as;\n const treatFailureAs = rawFailurePolicy === \"warning\" || rawFailurePolicy === \"ignore\" || rawFailurePolicy === \"blocker\"\n ? rawFailurePolicy\n : undefined;\n\n return {\n prompt,\n ...(workspace ? { workspace } : {}),\n ...(maxTurns !== undefined ? { max_turns: maxTurns } : {}),\n ...(skillPackOverrides && skillPackOverrides.length > 0 ? { skill_pack_overrides: skillPackOverrides } : {}),\n ...(maxUsd !== undefined || maxTokens !== undefined\n ? { token_budget: { ...(maxUsd !== undefined ? { max_usd: maxUsd } : {}), ...(maxTokens !== undefined ? { max_tokens: maxTokens } : {}) } }\n : {}),\n ...(model ? { model } : {}),\n ...(treatFailureAs ? { treat_failure_as: treatFailureAs } : {}),\n };\n}\n\nfunction subtaskMaxDepth(): number {\n const raw = envValue(process.env, \"TANYA_SUBTASK_MAX_DEPTH\").trim();\n if (!raw) return 2;\n const parsed = Number(raw);\n return Number.isFinite(parsed) && parsed >= 0 ? Math.floor(parsed) : 2;\n}\n\nexport const taskTool: TanyaTool = {\n name: \"task\",\n description: \"Delegate a scoped prompt to a child Tanya agent and return its verifier-aware result.\",\n keepFullForVerifier: true,\n definition: {\n type: \"function\",\n function: {\n name: \"task\",\n description: \"Spawn a child Tanya agent with inherited context, permissions, and workspace scope.\",\n parameters: {\n type: \"object\",\n properties: {\n prompt: { type: \"string\", description: \"Task prompt for the child agent.\" },\n workspace: { type: \"string\", description: \"Optional subdirectory of the parent workspace.\" },\n max_turns: { type: \"number\", description: \"Maximum child turns. Defaults to 20.\" },\n skill_pack_overrides: { type: \"array\", description: \"Optional skill pack ids to override for the child.\" },\n token_budget: {\n type: \"object\",\n description: \"Optional child token or USD budget cap.\",\n properties: {\n max_usd: { type: \"number\" },\n max_tokens: { type: \"number\" },\n },\n additionalProperties: false,\n },\n model: {\n type: \"object\",\n description: \"Optional provider/model pin for the whole child run.\",\n properties: {\n provider: { type: \"string\" },\n model: { type: \"string\" },\n },\n additionalProperties: false,\n },\n treat_failure_as: {\n type: \"string\",\n description: \"How the parent should treat a failed child: blocker, warning, or ignore.\",\n },\n },\n required: [\"prompt\"],\n additionalProperties: false,\n },\n },\n },\n async canRun(input, context) {\n if (runIdDepth(context.runId) >= subtaskMaxDepth()) {\n return { decision: \"deny\", reason: \"subtask-depth-limit\", matchedRule: \"task:<depth>\" };\n }\n return decide(\"task\", input, context);\n },\n async run(input, context) {\n if (runIdDepth(context.runId ?? \"\") >= subtaskMaxDepth()) {\n return {\n ok: false,\n summary: \"Subtask depth limit reached.\",\n error: `Subtask recursion depth is capped at ${subtaskMaxDepth()}.`,\n output: { ok: false, error: \"subtask-depth-limit\" },\n };\n }\n if (!context.runSubAgent) {\n return {\n ok: false,\n summary: \"Sub-agent runner is unavailable.\",\n error: \"task can only run inside an active Tanya agent loop.\",\n };\n }\n const request = parseTaskInput(input);\n const result = await context.runSubAgent(request);\n return {\n ok: result.ok,\n summary: `${result.verdict === \"passed\" ? \"Subtask passed\" : \"Subtask failed\"} (${result.subRunId}).`,\n output: {\n ok: result.ok,\n subRunId: result.subRunId,\n verdict: result.verdict,\n blockers: result.blockers,\n changedFiles: result.changedFiles,\n summary: result.summary,\n tokensUsed: result.tokensUsed,\n childRunIds: result.childRunIds,\n treatFailureAs: result.treatFailureAs,\n ...(result.cancelled ? { cancelled: result.cancelled, reason: result.reason } : {}),\n },\n files: result.changedFiles,\n ...(result.ok ? {} : { error: result.blockers.join(\"; \") || \"subtask failed\" }),\n };\n },\n};\n","import { createHash } from \"node:crypto\";\nimport { readFile, writeFile } from \"node:fs/promises\";\nimport type { Decision, PermissionContext } from \"../safety/permissions/engine\";\nimport { decide, inputShape } from \"../safety/permissions/engine\";\nimport { resolveInsideWorkspace } from \"../safety/workspace\";\nimport type { TanyaTool } from \"./types\";\n\nexport type EditBlockInput = {\n path: string;\n search: string;\n replace: string;\n expectedCount: number;\n matchPolicy: \"exact\" | \"fuzzy\";\n};\n\nconst binaryExtensions = /\\.(?:png|jpe?g|pdf|zip|exe|dll|so|dylib|woff2?|ttf|bin)$/i;\n\nexport function parseEditBlockInput(input: unknown, workspace: string): EditBlockInput {\n const record = input && typeof input === \"object\" ? input as Record<string, unknown> : {};\n const path = typeof record.path === \"string\" ? record.path.trim() : \"\";\n const search = typeof record.search === \"string\" ? record.search : \"\";\n const replace = typeof record.replace === \"string\" ? record.replace : \"\";\n const expectedCountRaw = record.expectedCount;\n const matchPolicyRaw = record.matchPolicy;\n if (!path) throw new Error(\"Missing string field: path\");\n if (!search) throw new Error(\"Missing string field: search\");\n if (search === replace) throw new Error(\"search and replace must differ\");\n if (binaryExtensions.test(path)) throw new Error(\"edit_block refuses binary file targets\");\n resolveInsideWorkspace(workspace, path);\n const expectedCount = expectedCountRaw === undefined\n ? 1\n : typeof expectedCountRaw === \"number\" && Number.isInteger(expectedCountRaw) && expectedCountRaw > 0\n ? expectedCountRaw\n : NaN;\n if (!Number.isFinite(expectedCount)) throw new Error(\"expectedCount must be a positive integer\");\n const matchPolicy = matchPolicyRaw === undefined\n ? \"exact\"\n : matchPolicyRaw === \"exact\" || matchPolicyRaw === \"fuzzy\"\n ? matchPolicyRaw\n : \"\";\n if (matchPolicy !== \"exact\" && matchPolicy !== \"fuzzy\") throw new Error(\"matchPolicy must be exact or fuzzy\");\n return { path, search, replace, expectedCount, matchPolicy };\n}\n\nfunction hasExplicitEditBlockAllow(input: unknown, context: PermissionContext): boolean {\n const shape = inputShape(input);\n for (const pattern of context.rules.alwaysAllow) {\n const separator = pattern.indexOf(\":\");\n if (separator <= 0) continue;\n const tool = pattern.slice(0, separator);\n const regex = pattern.slice(separator + 1);\n if (tool === \"edit_block\" && new RegExp(regex).test(shape)) return true;\n }\n return false;\n}\n\nfunction countOccurrences(content: string, search: string): number {\n return content.split(search).length - 1;\n}\n\nfunction hashContent(content: string): string {\n return createHash(\"sha256\").update(content).digest(\"hex\");\n}\n\nfunction unifiedDiff(path: string, before: string, after: string): string {\n const beforeLines = before.split(\"\\n\");\n const afterLines = after.split(\"\\n\");\n const lines = [\n `--- a/${path}`,\n `+++ b/${path}`,\n `@@ -1,${beforeLines.length} +1,${afterLines.length} @@`,\n ...beforeLines.map((line) => `-${line}`),\n ...afterLines.map((line) => `+${line}`),\n ];\n const diff = lines.join(\"\\n\");\n return diff.length > 32_000 ? `${diff.slice(0, 31_980)}\\n[diff truncated]` : diff;\n}\n\nfunction exactMismatch(path: string, expected: number, found: number) {\n const reason = found === 0\n ? \"no_match\"\n : found > expected && expected === 1\n ? \"too_many_matches\"\n : \"count_mismatch\";\n return {\n ok: false as const,\n summary: \"exact match failed\",\n error: `exact match failed in ${path}: expected ${expected}, found ${found}`,\n output: {\n ok: false,\n error: \"exact match failed\",\n reason,\n expected,\n found,\n },\n };\n}\n\ntype FuzzyCandidate = {\n start: number;\n end: number;\n recoveredVia: \"whitespace\" | \"nearby-context\";\n confidence: number;\n};\n\ntype FuzzyFailure = {\n reason: \"too_many_matches\" | \"no_match\" | \"low_confidence\";\n confidence?: number;\n candidateExcerpt?: string;\n};\n\nfunction normalizeWithSpans(text: string): { normalized: string; spans: Array<{ start: number; end: number }> } {\n const chars: string[] = [];\n const spans: Array<{ start: number; end: number }> = [];\n let index = 0;\n while (index < text.length) {\n const char = text[index] ?? \"\";\n if (/\\s/.test(char)) {\n const start = index;\n while (index < text.length && /\\s/.test(text[index] ?? \"\")) index += 1;\n chars.push(\" \");\n spans.push({ start, end: index });\n continue;\n }\n chars.push(char);\n spans.push({ start: index, end: index + 1 });\n index += 1;\n }\n let startToken = 0;\n let endToken = chars.length;\n while (startToken < endToken && chars[startToken] === \" \") startToken += 1;\n while (endToken > startToken && chars[endToken - 1] === \" \") endToken -= 1;\n return {\n normalized: chars.slice(startToken, endToken).join(\"\"),\n spans: spans.slice(startToken, endToken),\n };\n}\n\nfunction findStringOccurrences(content: string, needle: string): number[] {\n const hits: number[] = [];\n if (!needle) return hits;\n let index = content.indexOf(needle);\n while (index >= 0) {\n hits.push(index);\n index = content.indexOf(needle, index + Math.max(1, needle.length));\n }\n return hits;\n}\n\nfunction whitespaceCandidate(content: string, search: string): FuzzyCandidate[] | FuzzyFailure {\n const normalizedContent = normalizeWithSpans(content);\n const normalizedSearch = normalizeWithSpans(search).normalized;\n const hits = findStringOccurrences(normalizedContent.normalized, normalizedSearch);\n if (hits.length > 1) return { reason: \"too_many_matches\" };\n if (hits.length === 0) return { reason: \"no_match\" };\n const startToken = hits[0] ?? 0;\n const endToken = startToken + normalizedSearch.length - 1;\n const first = normalizedContent.spans[startToken];\n const last = normalizedContent.spans[endToken];\n if (!first || !last) return { reason: \"no_match\" };\n return [{ start: first.start, end: last.end, recoveredVia: \"whitespace\", confidence: 1 }];\n}\n\nfunction anchorLines(search: string): { first: string; last: string; lineCount: number } | null {\n const lines = search.split(/\\r?\\n/).filter((line) => line.trim().length > 0);\n if (lines.length < 2) return null;\n const first = lines.slice(0, Math.min(3, lines.length)).join(\"\\n\");\n const last = lines.slice(Math.max(0, lines.length - 3)).join(\"\\n\");\n return { first, last, lineCount: lines.length };\n}\n\nfunction lineCount(text: string): number {\n return text.split(/\\r?\\n/).filter((line) => line.trim().length > 0).length;\n}\n\nfunction nearbyContextCandidate(content: string, search: string): FuzzyCandidate[] | FuzzyFailure {\n const anchors = anchorLines(search);\n if (!anchors) return { reason: \"no_match\" };\n const starts = findStringOccurrences(content, anchors.first);\n const candidates: Array<{ start: number; end: number; confidence: number; excerpt: string }> = [];\n for (const start of starts) {\n const lastIndex = content.indexOf(anchors.last, start + anchors.first.length);\n if (lastIndex < 0) continue;\n const end = lastIndex + anchors.last.length;\n const candidate = content.slice(start, end);\n if (Math.abs(lineCount(candidate) - anchors.lineCount) > 1) continue;\n const confidence = levenshteinRatio(normalizeForSimilarity(candidate), normalizeForSimilarity(search));\n candidates.push({ start, end, confidence, excerpt: candidate.slice(0, 500) });\n }\n if (candidates.length > 1) return { reason: \"too_many_matches\" };\n if (candidates.length === 0) return { reason: \"no_match\" };\n const candidate = candidates[0];\n if (!candidate) return { reason: \"no_match\" };\n if (candidate.confidence < 0.95) {\n return { reason: \"low_confidence\", confidence: candidate.confidence, candidateExcerpt: candidate.excerpt };\n }\n return [{ start: candidate.start, end: candidate.end, recoveredVia: \"nearby-context\", confidence: candidate.confidence }];\n}\n\nfunction normalizeForSimilarity(text: string): string {\n return text.replace(/\\s+/g, \" \").trim();\n}\n\nfunction levenshteinRatio(a: string, b: string): number {\n if (a === b) return 1;\n if (!a || !b) return 0;\n const prev = Array.from({ length: b.length + 1 }, (_, index) => index);\n const curr = Array.from({ length: b.length + 1 }, () => 0);\n for (let i = 1; i <= a.length; i += 1) {\n curr[0] = i;\n for (let j = 1; j <= b.length; j += 1) {\n const cost = a[i - 1] === b[j - 1] ? 0 : 1;\n curr[j] = Math.min(\n (curr[j - 1] ?? 0) + 1,\n (prev[j] ?? 0) + 1,\n (prev[j - 1] ?? 0) + cost,\n );\n }\n for (let j = 0; j < prev.length; j += 1) prev[j] = curr[j] ?? 0;\n }\n const distance = prev[b.length] ?? Math.max(a.length, b.length);\n return 1 - distance / Math.max(a.length, b.length);\n}\n\nfunction findFuzzyCandidate(content: string, search: string): FuzzyCandidate[] | FuzzyFailure {\n const whitespace = whitespaceCandidate(content, search);\n if (Array.isArray(whitespace) || whitespace.reason === \"too_many_matches\") return whitespace;\n const nearby = nearbyContextCandidate(content, search);\n return nearby;\n}\n\nfunction applyCandidate(content: string, candidate: FuzzyCandidate, replace: string): string {\n return `${content.slice(0, candidate.start)}${replace}${content.slice(candidate.end)}`;\n}\n\nfunction candidateExcerpt(content: string, candidate: FuzzyCandidate): string {\n return content.slice(candidate.start, candidate.end).slice(0, 500);\n}\n\nasync function canRunEditBlock(input: unknown, context: PermissionContext): Promise<Decision> {\n const base = decide(\"edit_block\", input, context);\n const record = input && typeof input === \"object\" ? input as Record<string, unknown> : {};\n if (record.matchPolicy !== \"fuzzy\") return base;\n if (base.decision === \"deny\") return base;\n if (!hasExplicitEditBlockAllow(input, context)) {\n return {\n decision: \"deny\",\n matchedRule: \"edit_block:fuzzy\",\n reason: \"fuzzy edit blocks require explicit permission\",\n };\n }\n return base;\n}\n\nexport const editBlockTool: TanyaTool = {\n name: \"edit_block\",\n description: \"Apply a bounded search/replace block. Defaults to exact matching; fuzzy matching requires explicit permission.\",\n keepFullForVerifier: true,\n definition: {\n type: \"function\",\n function: {\n name: \"edit_block\",\n description: \"Replace one or more occurrences of a search block in a workspace file. Fuzzy matching is opt-in and permission-gated.\",\n parameters: {\n type: \"object\",\n properties: {\n path: { type: \"string\", description: \"Workspace-relative text file path.\" },\n search: { type: \"string\", description: \"Block to search for.\" },\n replace: { type: \"string\", description: \"Replacement block.\" },\n expectedCount: { type: \"number\", description: \"Expected replacement count. Default 1.\" },\n matchPolicy: { type: \"string\", enum: [\"exact\", \"fuzzy\"], description: \"Match policy. Default exact.\" },\n },\n required: [\"path\", \"search\", \"replace\"],\n additionalProperties: false,\n },\n },\n },\n canRun: canRunEditBlock,\n async run(input, context) {\n const parsed = parseEditBlockInput(input, context.workspace);\n const abs = resolveInsideWorkspace(context.workspace, parsed.path);\n let content: string;\n try {\n content = await readFile(abs, \"utf8\");\n } catch {\n return { ok: false, summary: `File not found: ${parsed.path}`, error: `Cannot read ${parsed.path}` };\n }\n const found = countOccurrences(content, parsed.search);\n if (parsed.matchPolicy === \"exact\") {\n if (found !== parsed.expectedCount) return exactMismatch(parsed.path, parsed.expectedCount, found);\n const updated = content.split(parsed.search).join(parsed.replace);\n await writeFile(abs, updated, \"utf8\");\n return {\n ok: true,\n summary: `replaced ${found} occurrence${found === 1 ? \"\" : \"s\"} in ${parsed.path}`,\n output: {\n path: parsed.path,\n count: found,\n matchPolicy: \"exact\",\n diff: unifiedDiff(parsed.path, content, updated),\n beforeHash: hashContent(content),\n afterHash: hashContent(updated),\n },\n files: [parsed.path],\n };\n }\n if (found === parsed.expectedCount) {\n const updated = content.split(parsed.search).join(parsed.replace);\n await writeFile(abs, updated, \"utf8\");\n return {\n ok: true,\n summary: `replaced ${found} exact occurrence${found === 1 ? \"\" : \"s\"} in ${parsed.path}`,\n output: {\n path: parsed.path,\n count: found,\n matchPolicy: \"fuzzy\",\n recoveredVia: \"exact\",\n confidence: 1,\n candidateExcerpt: parsed.search.slice(0, 500),\n diff: unifiedDiff(parsed.path, content, updated),\n beforeHash: hashContent(content),\n afterHash: hashContent(updated),\n },\n files: [parsed.path],\n };\n }\n const candidateResult = findFuzzyCandidate(content, parsed.search);\n if (!Array.isArray(candidateResult)) {\n return {\n ok: false,\n summary: \"fuzzy match failed\",\n error: `fuzzy match failed in ${parsed.path}: ${candidateResult.reason}`,\n output: {\n ok: false,\n error: \"fuzzy match failed\",\n reason: candidateResult.reason,\n matchPolicy: \"fuzzy\",\n ...(candidateResult.confidence !== undefined ? { confidence: candidateResult.confidence } : {}),\n ...(candidateResult.candidateExcerpt ? { candidateExcerpt: candidateResult.candidateExcerpt } : {}),\n },\n };\n }\n if (candidateResult.length !== parsed.expectedCount) {\n return {\n ok: false,\n summary: \"fuzzy match failed\",\n error: `fuzzy match failed in ${parsed.path}: expected ${parsed.expectedCount}, found ${candidateResult.length}`,\n output: {\n ok: false,\n error: \"fuzzy match failed\",\n reason: candidateResult.length > parsed.expectedCount ? \"too_many_matches\" : \"count_mismatch\",\n expected: parsed.expectedCount,\n found: candidateResult.length,\n matchPolicy: \"fuzzy\",\n },\n };\n }\n const candidate = candidateResult[0];\n if (!candidate) return exactMismatch(parsed.path, parsed.expectedCount, 0);\n const updated = applyCandidate(content, candidate, parsed.replace);\n await writeFile(abs, updated, \"utf8\");\n return {\n ok: true,\n summary: `recovered fuzzy edit in ${parsed.path} via ${candidate.recoveredVia}`,\n output: {\n path: parsed.path,\n count: 1,\n matchPolicy: \"fuzzy\",\n recoveredVia: candidate.recoveredVia,\n confidence: candidate.confidence,\n candidateExcerpt: candidateExcerpt(content, candidate),\n diff: unifiedDiff(parsed.path, content, updated),\n beforeHash: hashContent(content),\n afterHash: hashContent(updated),\n },\n files: [parsed.path],\n };\n },\n};\n","import { buildRepoMap, readRepoMap } from \"../context/repoMap\";\nimport { RepoMapLangSchema, type RepoMapFile, type RepoMapLang } from \"../context/repoMapSchema\";\nimport type { TanyaTool } from \"./types\";\n\ntype InspectRepoMapInput = {\n file?: string;\n symbol?: string;\n lang?: RepoMapLang;\n};\n\nfunction asInput(input: unknown): InspectRepoMapInput {\n const record = input && typeof input === \"object\" ? input as Record<string, unknown> : {};\n const file = typeof record.file === \"string\" && record.file.trim() ? record.file.trim() : undefined;\n const symbol = typeof record.symbol === \"string\" && record.symbol.trim() ? record.symbol.trim() : undefined;\n const rawLang = typeof record.lang === \"string\" && record.lang.trim() ? record.lang.trim() : undefined;\n const lang = rawLang ? RepoMapLangSchema.parse(rawLang) : undefined;\n return {\n ...(file ? { file } : {}),\n ...(symbol ? { symbol } : {}),\n ...(lang ? { lang } : {}),\n };\n}\n\nfunction entryMatches(file: RepoMapFile, input: InspectRepoMapInput): boolean {\n if (input.file && !file.path.toLowerCase().includes(input.file.toLowerCase())) return false;\n if (input.lang && file.lang !== input.lang) return false;\n if (input.symbol) {\n const needle = input.symbol.toLowerCase();\n const symbolHit = file.symbols.some((symbol) => symbol.name.toLowerCase().includes(needle));\n const exportHit = file.exports.some((name) => name.toLowerCase().includes(needle));\n if (!symbolHit && !exportHit) return false;\n }\n return true;\n}\n\nfunction compactEntry(file: RepoMapFile): RepoMapFile {\n return {\n ...file,\n symbols: file.symbols.slice(0, 30),\n imports: file.imports.slice(0, 30),\n exports: file.exports.slice(0, 30),\n };\n}\n\nexport const inspectRepoMapTool: TanyaTool = {\n name: \"inspect_repo_map\",\n description: \"Inspect the cached structural repo-map by file, symbol, or language. Advisory only; read files before editing.\",\n definition: {\n type: \"function\",\n function: {\n name: \"inspect_repo_map\",\n description: \"Inspect structural repo-map entries by file, symbol, or language without spending prompt tokens on the full map.\",\n parameters: {\n type: \"object\",\n properties: {\n file: { type: \"string\", description: \"Workspace-relative file path substring to inspect.\" },\n symbol: { type: \"string\", description: \"Symbol/export substring to search for.\" },\n lang: { type: \"string\", enum: [\"ts\", \"tsx\", \"js\", \"jsx\", \"py\", \"go\", \"swift\", \"kt\", \"unknown\"], description: \"Optional language filter.\" },\n },\n additionalProperties: false,\n },\n },\n },\n async run(input, context) {\n const parsed = asInput(input);\n let map = readRepoMap(context.workspace);\n if (!map) map = await buildRepoMap(context.workspace, { writeCache: true });\n const matches = map.files\n .filter((file) => entryMatches(file, parsed))\n .sort((a, b) => a.path.localeCompare(b.path))\n .slice(0, 25)\n .map(compactEntry);\n return {\n ok: true,\n summary: `Found ${matches.length} repo-map file entr${matches.length === 1 ? \"y\" : \"ies\"}.`,\n output: {\n generatedAt: map.generatedAt,\n totalFiles: map.files.length,\n matches,\n },\n };\n },\n};\n","import { mkdir, writeFile } from \"node:fs/promises\";\nimport { dirname } from \"node:path\";\nimport { resolveInsideWorkspace } from \"../safety/workspace\";\nimport type { TanyaTool } from \"./types\";\n\nfunction asRecord(input: unknown): Record<string, unknown> {\n return input && typeof input === \"object\" ? (input as Record<string, unknown>) : {};\n}\n\nfunction asOptionalArray(input: unknown, key: string): unknown[] {\n const value = asRecord(input)[key];\n return Array.isArray(value) ? value : [];\n}\n\nfunction asOptionalString(input: unknown, key: string): string | undefined {\n const value = asRecord(input)[key];\n return typeof value === \"string\" && value.trim() ? value.trim() : undefined;\n}\n\nexport const recordMetricsDashboardHandoffTool: TanyaTool = {\n name: \"record_metrics_dashboard_handoff\",\n description: \"Record a structured handoff after app analytics events are implemented so an external dashboard system can regenerate/provision dashboards next.\",\n definition: {\n type: \"function\",\n function: {\n name: \"record_metrics_dashboard_handoff\",\n description: \"Write a structured metrics-dashboard handoff file after implementing app analytics tracking events. This does not provision external dashboards.\",\n parameters: {\n type: \"object\",\n properties: {\n appName: { type: \"string\", description: \"App name, for example DemoApp.\" },\n implementedEvents: {\n type: \"array\",\n description: \"Implemented tracking events with emit-site details.\",\n items: {\n type: \"object\",\n properties: {\n event: { type: \"string\" },\n platform: { type: \"string\" },\n emitSite: { type: \"string\" },\n file: { type: \"string\" },\n properties: { type: \"array\", items: { type: \"string\" } },\n },\n required: [\"event\", \"emitSite\"],\n additionalProperties: true,\n },\n },\n unresolvedGaps: {\n type: \"array\",\n description: \"Requested events that could not be implemented.\",\n items: { type: \"object\", additionalProperties: true },\n },\n changedFiles: { type: \"array\", items: { type: \"string\" } },\n verification: {\n type: \"array\",\n description: \"Verification commands and results.\",\n items: {\n type: \"object\",\n properties: {\n command: { type: \"string\" },\n result: { type: \"string\" },\n },\n required: [\"command\", \"result\"],\n additionalProperties: true,\n },\n },\n nextStep: { type: \"string\", description: \"What the dashboard owner should do after this app-code run.\" },\n outputPath: { type: \"string\", description: \"Optional workspace-relative output path. Default .tania/metrics-dashboard-handoff.json.\" },\n },\n required: [\"appName\", \"implementedEvents\", \"changedFiles\", \"verification\"],\n additionalProperties: false,\n },\n },\n },\n async run(input, context) {\n const outputPath = asOptionalString(input, \"outputPath\") ?? \".tania/metrics-dashboard-handoff.json\";\n const abs = resolveInsideWorkspace(context.workspace, outputPath);\n const payload = {\n appName: asOptionalString(input, \"appName\") ?? \"unknown\",\n implementedEvents: asOptionalArray(input, \"implementedEvents\"),\n unresolvedGaps: asOptionalArray(input, \"unresolvedGaps\"),\n changedFiles: asOptionalArray(input, \"changedFiles\"),\n verification: asOptionalArray(input, \"verification\"),\n nextStep: asOptionalString(input, \"nextStep\") ?? \"Regenerate and provision the metrics dashboard from the updated app instrumentation.\",\n createdAt: new Date().toISOString(),\n };\n\n await mkdir(dirname(abs), { recursive: true });\n await writeFile(abs, `${JSON.stringify(payload, null, 2)}\\n`, \"utf8\");\n\n return {\n ok: true,\n summary: `Recorded metrics dashboard handoff at ${outputPath}.`,\n output: {\n path: outputPath,\n implementedEventCount: payload.implementedEvents.length,\n unresolvedGapCount: payload.unresolvedGaps.length,\n nextStep: payload.nextStep,\n },\n files: [outputPath],\n };\n },\n};\n","import type { TanyaTool, ToolContext, ToolResult } from \"./types\";\nimport { defaultTools } from \"./fsTools\";\n\nexport type ToolExecutionOptions = {\n onProgress?: ToolContext[\"onProgress\"];\n signal?: AbortSignal;\n};\n\nexport class ToolRegistry {\n private readonly tools = new Map<string, TanyaTool>();\n\n constructor(tools: TanyaTool[] = defaultTools()) {\n for (const tool of tools) this.tools.set(tool.name, tool);\n }\n\n register(tool: TanyaTool): void {\n this.tools.set(tool.name, tool);\n }\n\n list(): TanyaTool[] {\n return [...this.tools.values()];\n }\n\n get(name: string): TanyaTool | undefined {\n return this.tools.get(name);\n }\n\n run(tool: TanyaTool, input: unknown, context: ToolContext, options: ToolExecutionOptions = {}): Promise<ToolResult> {\n const runContext: ToolContext = { ...context };\n if (options.onProgress) runContext.onProgress = options.onProgress;\n if (options.signal) runContext.signal = options.signal;\n return tool.run(input, runContext);\n }\n}\n","import { appendFile, mkdir, readFile, stat, writeFile, rename } from \"node:fs/promises\";\nimport { createHash } from \"node:crypto\";\nimport { dirname, join } from \"node:path\";\nimport type { TanyaRunContext } from \"../context/runContext\";\n\nconst GOLDEN_TASK_MAX_BYTES = 10 * 1024 * 1024; // 10 MB\nconst GOLDEN_TASK_KEEP_LATEST = 200;\n\nasync function rotateGoldenTaskFileIfTooLarge(memoryPath: string): Promise<void> {\n let info;\n try {\n info = await stat(memoryPath);\n } catch {\n return;\n }\n if (info.size <= GOLDEN_TASK_MAX_BYTES) return;\n let raw = \"\";\n try {\n raw = await readFile(memoryPath, \"utf8\");\n } catch {\n return;\n }\n const lines = raw.split(/\\r?\\n/).filter((line) => line.trim().length > 0);\n const kept = lines.slice(-GOLDEN_TASK_KEEP_LATEST);\n await writeFile(`${memoryPath}.compact`, `${kept.join(\"\\n\")}\\n`, \"utf8\");\n await rename(`${memoryPath}.compact`, memoryPath);\n}\n\ntype GoldenTaskManifest = {\n changedFiles: string[];\n artifactsRead: string[];\n artifactsCreated: string[];\n verification: string[];\n blockers: string[];\n toolErrors: number;\n childRunIds?: string[];\n validation?: {\n passed: boolean;\n issues: Array<{ id: string; severity: string; message: string; files?: string[] }>;\n };\n};\n\nexport type GoldenTaskRecord = {\n schemaVersion: 1;\n recordedAt: string;\n signature: string;\n task: TanyaRunContext[\"task\"] | null;\n caller: unknown;\n outcome: \"passed\" | \"failed\";\n changedFiles: string[];\n artifactsRead: string[];\n artifactsCreated: string[];\n verificationCount: number;\n toolErrors: number;\n blockers: string[];\n childRunIds: string[];\n validation: GoldenTaskManifest[\"validation\"] | null;\n};\n\nexport type GoldenTaskSummary = {\n total: number;\n passed: number;\n failed: number;\n signatures: number;\n latestBySignature: GoldenTaskRecord[];\n failureReasons: Array<{ reason: string; count: number }>;\n};\n\nfunction enabled(runContext?: TanyaRunContext): boolean {\n if (runContext?.metadata?.subAgent === true || runContext?.metadata?.subAgent === \"true\") return false;\n const value = runContext?.metadata?.goldenTask ?? runContext?.metadata?.goldenTaskCandidate;\n return value === true || value === \"true\" || value === \"yes\";\n}\n\nfunction taskSignature(runContext: TanyaRunContext | undefined, manifest: GoldenTaskManifest): string {\n const source = JSON.stringify({\n kind: runContext?.task?.kind ?? null,\n title: runContext?.task?.title ?? null,\n artifacts: manifest.artifactsRead,\n changedExtensions: [...new Set(manifest.changedFiles.map((file) => file.split(\".\").pop()?.toLowerCase()).filter(Boolean))].sort(),\n });\n return createHash(\"sha256\").update(source).digest(\"hex\").slice(0, 16);\n}\n\nexport async function recordGoldenTaskMemory(workspace: string, manifest: GoldenTaskManifest, runContext?: TanyaRunContext): Promise<void> {\n if (!enabled(runContext)) return;\n const memoryPath = join(workspace, \".tania\", \"memory\", \"golden-tasks.jsonl\");\n const validationErrors = manifest.validation?.issues.filter((issue) => issue.severity === \"error\") ?? [];\n const record: GoldenTaskRecord = {\n schemaVersion: 1,\n recordedAt: new Date().toISOString(),\n signature: taskSignature(runContext, manifest),\n task: runContext?.task ?? null,\n caller: runContext?.metadata?.caller ?? null,\n outcome: manifest.blockers.length === 0 && validationErrors.length === 0 ? \"passed\" : \"failed\",\n changedFiles: manifest.changedFiles,\n artifactsRead: manifest.artifactsRead,\n artifactsCreated: manifest.artifactsCreated,\n verificationCount: manifest.verification.length,\n toolErrors: manifest.toolErrors,\n blockers: manifest.blockers,\n childRunIds: manifest.childRunIds ?? [],\n validation: manifest.validation ?? null,\n };\n await mkdir(dirname(memoryPath), { recursive: true });\n await appendFile(memoryPath, `${JSON.stringify(record)}\\n`, \"utf8\");\n await rotateGoldenTaskFileIfTooLarge(memoryPath);\n}\n\nexport async function readGoldenTaskMemory(workspace: string): Promise<GoldenTaskRecord[]> {\n const memoryPath = join(workspace, \".tania\", \"memory\", \"golden-tasks.jsonl\");\n let raw = \"\";\n try {\n raw = await readFile(memoryPath, \"utf8\");\n } catch {\n return [];\n }\n const records: GoldenTaskRecord[] = [];\n for (const line of raw.split(/\\r?\\n/)) {\n if (!line.trim()) continue;\n try {\n const parsed = JSON.parse(line) as GoldenTaskRecord;\n if (parsed?.schemaVersion === 1 && typeof parsed.signature === \"string\") {\n records.push({ ...parsed, childRunIds: parsed.childRunIds ?? [] });\n }\n } catch {\n // Ignore corrupt historical lines; the suite summary should remain usable.\n }\n }\n return records;\n}\n\nexport function buildGoldenTaskSummary(records: GoldenTaskRecord[]): GoldenTaskSummary {\n const latest = new Map<string, GoldenTaskRecord>();\n for (const record of records) {\n const previous = latest.get(record.signature);\n if (!previous || previous.recordedAt < record.recordedAt) latest.set(record.signature, record);\n }\n\n const failureCounts = new Map<string, number>();\n for (const record of records.filter((item) => item.outcome === \"failed\")) {\n const validationErrors = record.validation?.issues\n .filter((issue) => issue.severity === \"error\")\n .map((issue) => issue.id) ?? [];\n const reasons = [...record.blockers, ...validationErrors];\n for (const reason of reasons.length ? reasons : [\"failed-without-reason\"]) {\n failureCounts.set(reason, (failureCounts.get(reason) ?? 0) + 1);\n }\n }\n\n return {\n total: records.length,\n passed: records.filter((record) => record.outcome === \"passed\").length,\n failed: records.filter((record) => record.outcome === \"failed\").length,\n signatures: latest.size,\n latestBySignature: [...latest.values()].sort((a, b) => a.signature.localeCompare(b.signature)),\n failureReasons: [...failureCounts.entries()]\n .map(([reason, count]) => ({ reason, count }))\n .sort((a, b) => b.count - a.count || a.reason.localeCompare(b.reason)),\n };\n}\n\nexport function validateGoldenTaskSummary(summary: GoldenTaskSummary): string[] {\n const problems: string[] = [];\n if (summary.total === 0) problems.push(\"No golden task records found.\");\n const latestFailures = summary.latestBySignature.filter((record) => record.outcome === \"failed\");\n for (const record of latestFailures) {\n const title = record.task?.title ?? record.signature;\n const errors = record.validation?.issues.filter((issue) => issue.severity === \"error\").map((issue) => issue.id) ?? [];\n const reasons = [...record.blockers, ...errors];\n problems.push(`${title}: ${reasons.join(\"; \") || \"failed\"}`);\n }\n return problems;\n}\n","import { appendFile, mkdir, readFile } from \"node:fs/promises\";\nimport { createHash } from \"node:crypto\";\nimport { homedir } from \"node:os\";\nimport { dirname, join } from \"node:path\";\nimport { envValue } from \"../config/envCompat\";\nimport type { TanyaRunContext } from \"../context/runContext\";\n\nexport type RepairAttemptSnapshot = {\n attempt: number;\n issueIds: string[];\n blockerCount: number;\n changedFileCount: number;\n};\n\nexport type RepairRunRecord = {\n schemaVersion: 1;\n recordedAt: string;\n signature: string;\n task: TanyaRunContext[\"task\"] | null;\n caller: unknown;\n attempts: RepairAttemptSnapshot[];\n outcome: \"passed\" | \"failed\";\n finalIssueIds: string[];\n finalBlockers: string[];\n};\n\ntype RepairManifest = {\n changedFiles: string[];\n blockers: string[];\n validation?: {\n passed: boolean;\n issues: Array<{ id: string; severity: string; message: string; files?: string[] }>;\n };\n};\n\nfunction memoryRoot(): string {\n return envValue({}, \"TANYA_MEMORY_HOME\").trim() || join(homedir(), \".tania\", \"memory\");\n}\n\nfunction taskSignature(runContext: TanyaRunContext | undefined, attempts: RepairAttemptSnapshot[]): string {\n const source = JSON.stringify({\n kind: runContext?.task?.kind ?? null,\n title: runContext?.task?.title ?? null,\n issueIds: [...new Set(attempts.flatMap((attempt) => attempt.issueIds))].sort(),\n });\n return createHash(\"sha256\").update(source).digest(\"hex\").slice(0, 16);\n}\n\nexport async function recordRepairRunMemory(runContext: TanyaRunContext | undefined, attempts: RepairAttemptSnapshot[], manifest: RepairManifest): Promise<void> {\n if (attempts.length === 0) return;\n const finalErrors = manifest.validation?.issues.filter((issue) => issue.severity === \"error\").map((issue) => issue.id) ?? [];\n const record: RepairRunRecord = {\n schemaVersion: 1,\n recordedAt: new Date().toISOString(),\n signature: taskSignature(runContext, attempts),\n task: runContext?.task ?? null,\n caller: runContext?.metadata?.caller ?? null,\n attempts,\n outcome: manifest.blockers.length === 0 && finalErrors.length === 0 ? \"passed\" : \"failed\",\n finalIssueIds: finalErrors,\n finalBlockers: manifest.blockers,\n };\n const path = join(memoryRoot(), \"repair-runs.jsonl\");\n await mkdir(dirname(path), { recursive: true });\n await appendFile(path, `${JSON.stringify(record)}\\n`, \"utf8\");\n}\n\nexport async function readRepairRunMemory(): Promise<RepairRunRecord[]> {\n const path = join(memoryRoot(), \"repair-runs.jsonl\");\n let raw = \"\";\n try {\n raw = await readFile(path, \"utf8\");\n } catch {\n return [];\n }\n const records: RepairRunRecord[] = [];\n for (const line of raw.split(/\\r?\\n/)) {\n if (!line.trim()) continue;\n try {\n const parsed = JSON.parse(line) as RepairRunRecord;\n if (parsed?.schemaVersion === 1 && typeof parsed.signature === \"string\") records.push(parsed);\n } catch {\n // Ignore corrupt historical lines so memory remains best-effort.\n }\n }\n return records;\n}\n","import { appendFile, mkdir, writeFile } from \"node:fs/promises\";\nimport { dirname, join } from \"node:path\";\nimport type { TanyaRunContext } from \"../context/runContext\";\nimport type { TanyaFinalManifest } from \"../agent/runner\";\n\nfunction dailyNoteName(date = new Date()): string {\n const year = date.getFullYear();\n const month = String(date.getMonth() + 1).padStart(2, \"0\");\n const day = String(date.getDate()).padStart(2, \"0\");\n return `${year}-${month}-${day}.md`;\n}\n\nfunction taskTitle(runContext?: TanyaRunContext): string {\n return runContext?.task?.title?.trim() || \"Tanya task\";\n}\n\nfunction taskOutcome(manifest: TanyaFinalManifest): \"passed\" | \"blocked\" {\n const validationErrors = manifest.validation?.issues.filter((issue) => issue.severity === \"error\") ?? [];\n return manifest.blockers.length === 0 && validationErrors.length === 0 ? \"passed\" : \"blocked\";\n}\n\nfunction listSection(title: string, values: string[]): string[] {\n return [\n `**${title}:**`,\n ...(values.length > 0 ? values.map((value) => `- ${value}`) : [\"- none\"]),\n ];\n}\n\nfunction buildTaskSection(manifest: TanyaFinalManifest, runContext?: TanyaRunContext): string {\n return [\n \"\",\n `## ${taskTitle(runContext)}`,\n `- Outcome: ${taskOutcome(manifest)}`,\n `- Git HEAD: ${manifest.git.head ?? \"unavailable\"}`,\n \"\",\n ...listSection(\"Changed files\", manifest.changedFiles),\n \"\",\n ...listSection(\"Verification\", manifest.verification),\n \"\",\n ].join(\"\\n\");\n}\n\nexport async function appendTaskToVault(\n vaultPath: string,\n manifest: TanyaFinalManifest,\n runContext?: TanyaRunContext,\n): Promise<void> {\n const notePath = join(vaultPath, dailyNoteName());\n await mkdir(dirname(notePath), { recursive: true });\n try {\n await writeFile(notePath, \"\", { flag: \"wx\" });\n } catch {\n // Existing notes are expected. Append below.\n }\n await appendFile(notePath, buildTaskSection(manifest, runContext), \"utf8\");\n}\n","import { existsSync, mkdirSync, readFileSync, statSync, unlinkSync, writeFileSync } from \"node:fs\";\nimport { gzipSync } from \"node:zlib\";\nimport { basename, join } from \"node:path\";\nimport type { PermissionMode } from \"../safety/permissions/schema\";\n\nexport interface AuditDecisionEntry {\n ts: string;\n runId: string;\n parentRunId?: string;\n tool: string;\n input: unknown;\n decision: \"allow\" | \"deny\" | \"ask\";\n matchedRule?: string;\n reason?: string;\n source: \"user\" | \"rule\" | \"engine\" | \"bypass\" | `mcp:${string}`;\n projectedCostUsd?: number;\n projectedTokens?: number;\n thresholdUsd?: number;\n thresholdTokens?: number;\n mode: PermissionMode;\n}\n\nexport interface AuditReadFilters {\n limit?: number;\n denyOnly?: boolean;\n sinceMs?: number;\n tool?: string;\n}\n\nexport const DEFAULT_AUDIT_MAX_BYTES = 50 * 1024 * 1024;\nexport const DEFAULT_AUDIT_MAX_AGE_MS = 90 * 24 * 60 * 60 * 1000;\n\nexport function appendAuditDecision(workspace: string, entry: AuditDecisionEntry, options: {\n maxBytes?: number;\n maxAgeMs?: number;\n now?: Date;\n} = {}): void {\n const path = auditPath(workspace);\n mkdirSync(join(workspace, \".tania\"), { recursive: true });\n rotateAuditIfNeeded(workspace, options);\n writeFileSync(path, `${JSON.stringify(entry)}\\n`, { encoding: \"utf8\", flag: \"a\" });\n}\n\nexport function readAuditDecisions(workspace: string, filters: AuditReadFilters = {}): AuditDecisionEntry[] {\n const path = auditPath(workspace);\n if (!existsSync(path)) return [];\n const sinceTs = filters.sinceMs === undefined ? null : Date.now() - filters.sinceMs;\n const entries = readFileSync(path, \"utf8\")\n .split(\"\\n\")\n .filter(Boolean)\n .flatMap((line) => {\n try {\n return [JSON.parse(line) as AuditDecisionEntry];\n } catch {\n return [];\n }\n })\n .filter((entry) => !filters.denyOnly || entry.decision === \"deny\")\n .filter((entry) => !filters.tool || entry.tool === filters.tool)\n .filter((entry) => sinceTs === null || Date.parse(entry.ts) >= sinceTs)\n .sort((a, b) => a.ts.localeCompare(b.ts));\n const limit = filters.limit ?? entries.length;\n return entries.slice(Math.max(0, entries.length - limit));\n}\n\nexport function auditPath(workspace: string): string {\n return join(workspace, \".tania\", \"audit.jsonl\");\n}\n\nfunction rotateAuditIfNeeded(workspace: string, options: {\n maxBytes?: number;\n maxAgeMs?: number;\n now?: Date;\n}): void {\n const path = auditPath(workspace);\n if (!existsSync(path)) return;\n const stats = statSync(path);\n const maxBytes = options.maxBytes ?? DEFAULT_AUDIT_MAX_BYTES;\n const maxAgeMs = options.maxAgeMs ?? DEFAULT_AUDIT_MAX_AGE_MS;\n const now = options.now ?? new Date();\n if (stats.size < maxBytes && now.getTime() - stats.mtimeMs < maxAgeMs) return;\n\n const archiveDir = join(workspace, \".tania\", \"audit\", \"archive\");\n mkdirSync(archiveDir, { recursive: true });\n const stamp = now.toISOString().replace(/[:.]/g, \"-\");\n const archivePath = join(archiveDir, `audit-${stamp}-${basename(path)}.gz`);\n writeFileSync(archivePath, gzipSync(readFileSync(path)));\n unlinkSync(path);\n}\n","import { stat } from \"node:fs/promises\";\nimport { resolveInsideWorkspace } from \"../safety/workspace\";\nimport type { ToolResult } from \"../tools/types\";\n\nexport type FileReadDedupEntry = {\n path: string;\n key: string;\n turn: number;\n toolCallId: string;\n};\n\nfunction asRecord(input: unknown): Record<string, unknown> {\n return input && typeof input === \"object\" && !Array.isArray(input) ? input as Record<string, unknown> : {};\n}\n\nexport function readFilePathFromInput(input: unknown): string | null {\n const path = asRecord(input).path;\n return typeof path === \"string\" && path.trim() ? path.trim() : null;\n}\n\nexport function readFileForceFromInput(input: unknown): boolean {\n const force = asRecord(input).force;\n if (typeof force === \"boolean\") return force;\n return typeof force === \"string\" && /^(1|true|yes)$/i.test(force.trim());\n}\n\nexport class FileReadDedupCache {\n private readonly entries = new Map<string, FileReadDedupEntry>();\n\n constructor(private readonly workspace: string) {}\n\n async lookup(input: unknown): Promise<ToolResult | null> {\n if (readFileForceFromInput(input)) return null;\n const key = await this.keyFor(input);\n if (!key) return null;\n const entry = this.entries.get(key.key);\n if (!entry) return null;\n const marker = `[file unchanged since turn ${entry.turn}, see tool_call ${entry.toolCallId} for content]`;\n return {\n ok: true,\n summary: `Read skipped for ${entry.path}; file unchanged.`,\n output: marker,\n };\n }\n\n async remember(input: unknown, toolCallId: string, turn: number): Promise<void> {\n const key = await this.keyFor(input);\n if (!key) return;\n for (const [existingKey, entry] of this.entries) {\n if (entry.path === key.path) this.entries.delete(existingKey);\n }\n this.entries.set(key.key, { ...key, toolCallId, turn });\n }\n\n clear(): void {\n this.entries.clear();\n }\n\n size(): number {\n return this.entries.size;\n }\n\n private async keyFor(input: unknown): Promise<{ path: string; key: string } | null> {\n const path = readFilePathFromInput(input);\n if (!path) return null;\n try {\n const abs = resolveInsideWorkspace(this.workspace, path);\n const info = await stat(abs);\n if (!info.isFile()) return null;\n return {\n path,\n key: `${path}\\0${info.size}\\0${Math.floor(info.mtimeMs)}`,\n };\n } catch {\n return null;\n }\n }\n}\n","import { existsSync, mkdirSync, readFileSync, renameSync, statSync, writeFileSync } from \"node:fs\";\nimport { appendFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\n\nexport type ReasoningArchiveEntry = {\n ts: string;\n runId: string;\n turn?: number;\n provider: string;\n model: string;\n content: string;\n tokens?: number;\n evicted?: boolean;\n};\n\nexport async function appendReasoningChunk(params: {\n workspace: string;\n runId: string;\n turn?: number;\n provider: string;\n model: string;\n content: string;\n tokens?: number;\n}): Promise<void> {\n if (!params.content) return;\n const dir = reasoningRunDir(params.workspace, params.runId);\n mkdirSync(dir, { recursive: true });\n const entry: ReasoningArchiveEntry = {\n ts: new Date().toISOString(),\n runId: params.runId,\n ...(params.turn !== undefined ? { turn: params.turn } : {}),\n provider: params.provider,\n model: params.model,\n content: params.content,\n ...(params.tokens !== undefined ? { tokens: params.tokens } : {}),\n };\n await appendFile(reasoningArchivePath(params.workspace, params.runId), `${JSON.stringify(entry)}\\n`, \"utf8\");\n}\n\nexport function readReasoningArchive(workspace: string, runId: string): ReasoningArchiveEntry[] {\n const file = reasoningArchivePath(workspace, runId);\n if (!existsSync(file)) return [];\n return readFileSync(file, \"utf8\")\n .split(/\\n+/)\n .filter(Boolean)\n .flatMap((line) => {\n try {\n const parsed = JSON.parse(line) as Partial<ReasoningArchiveEntry>;\n if (typeof parsed.content !== \"string\") return [];\n return [{\n ts: typeof parsed.ts === \"string\" ? parsed.ts : \"\",\n runId: typeof parsed.runId === \"string\" ? parsed.runId : runId,\n ...(typeof parsed.turn === \"number\" ? { turn: parsed.turn } : {}),\n provider: typeof parsed.provider === \"string\" ? parsed.provider : \"unknown\",\n model: typeof parsed.model === \"string\" ? parsed.model : \"unknown\",\n content: parsed.content,\n ...(typeof parsed.tokens === \"number\" ? { tokens: parsed.tokens } : {}),\n ...(parsed.evicted === true ? { evicted: true } : {}),\n }];\n } catch {\n return [];\n }\n });\n}\n\nexport function evictReasoningFromArchive(workspace: string, runId: string, thresholdBytes: number): number {\n const file = reasoningArchivePath(workspace, runId);\n if (!existsSync(file)) return 0;\n const before = statSync(file).size;\n if (before <= thresholdBytes) return 0;\n const entries = readReasoningArchive(workspace, runId);\n const tombstone: ReasoningArchiveEntry = {\n ts: new Date().toISOString(),\n runId,\n provider: \"archive\",\n model: \"eviction\",\n content: `<reasoning archive evicted ${before} bytes; live conversation history was already reasoning-free>`,\n evicted: true,\n };\n const next = `${entries\n .filter((entry) => entry.evicted)\n .concat(tombstone)\n .map((entry) => JSON.stringify(entry))\n .join(\"\\n\")}\\n`;\n const tmp = `${file}.tmp`;\n writeFileSync(tmp, next, \"utf8\");\n renameSync(tmp, file);\n return Math.max(0, before - statSync(file).size);\n}\n\nexport function reasoningArchivePath(workspace: string, runId: string): string {\n return join(reasoningRunDir(workspace, runId), \"reasoning.jsonl\");\n}\n\nfunction reasoningRunDir(workspace: string, runId: string): string {\n return join(workspace, \".tania\", \"runs\", runId);\n}\n","import { createWriteStream, existsSync, mkdirSync, renameSync, statSync, unlinkSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { Client } from \"@modelcontextprotocol/sdk/client/index.js\";\nimport { StdioClientTransport } from \"@modelcontextprotocol/sdk/client/stdio.js\";\nimport { SSEClientTransport } from \"@modelcontextprotocol/sdk/client/sse.js\";\nimport { StreamableHTTPClientTransport } from \"@modelcontextprotocol/sdk/client/streamableHttp.js\";\nimport type { Transport } from \"@modelcontextprotocol/sdk/shared/transport.js\";\nimport type { CallToolResult, Tool } from \"@modelcontextprotocol/sdk/types.js\";\nimport type { EventSink } from \"../events/types\";\nimport type { ToolDefinition } from \"../providers/types\";\nimport type { ToolRegistry } from \"../tools/registry\";\nimport type { TanyaTool, ToolContext, ToolResult } from \"../tools/types\";\nimport { numberEnvValue } from \"../config/envCompat\";\nimport { runIdDepth } from \"../agent/subAgentContext\";\nimport { loadMcpConfig, type LoadedMcpConfig, type McpServerConfig } from \"./config\";\n\nexport type McpConnectionStatus = \"connected\" | \"disconnected\" | \"restarting\" | \"failed\";\n\nexport interface McpServerStatus {\n name: string;\n transport: McpServerConfig[\"transport\"];\n status: McpConnectionStatus;\n toolNames: string[];\n error?: string;\n restarts: number;\n}\n\ntype ManagedServer = {\n config: McpServerConfig;\n client: Client;\n transport: Transport;\n status: McpConnectionStatus;\n tools: Tool[];\n restarts: number;\n error?: string;\n heartbeat?: ReturnType<typeof setInterval>;\n};\n\nexport class McpClientManager {\n private readonly servers = new Map<string, ManagedServer>();\n\n constructor(\n private readonly workspace: string,\n private readonly loadedConfig: LoadedMcpConfig,\n private readonly sink?: EventSink,\n ) {}\n\n get configSources(): string[] {\n return this.loadedConfig.sources;\n }\n\n get configIssues() {\n return this.loadedConfig.issues;\n }\n\n async connectAll(): Promise<void> {\n for (const server of this.loadedConfig.config.servers) {\n if (server.enabled === false) continue;\n await this.connectServer(server, this.servers.get(server.name)?.restarts ?? 0);\n }\n }\n\n registerTools(registry: ToolRegistry): void {\n for (const server of this.servers.values()) {\n for (const tool of server.tools) {\n registry.register(this.toTanyaTool(server, tool));\n }\n }\n }\n\n statuses(): McpServerStatus[] {\n return [...this.servers.values()]\n .map((server) => ({\n name: server.config.name,\n transport: server.config.transport,\n status: server.status,\n toolNames: server.tools.map((tool) => tool.name).sort(),\n restarts: server.restarts,\n ...(server.error ? { error: server.error } : {}),\n }))\n .sort((a, b) => a.name.localeCompare(b.name));\n }\n\n async closeAll(): Promise<void> {\n await Promise.all([...this.servers.values()].map(async (server) => {\n server.status = \"disconnected\";\n try {\n if (server.heartbeat) clearInterval(server.heartbeat);\n await server.transport.close();\n } catch {\n // Best effort shutdown; the process is ending or tests are cleaning up.\n }\n }));\n this.servers.clear();\n }\n\n async restartServer(name: string): Promise<void> {\n const existing = this.servers.get(name);\n if (!existing) throw new Error(`MCP server not found: ${name}`);\n await this.handleServerClose(name);\n }\n\n private async connectServer(config: McpServerConfig, restarts: number): Promise<void> {\n const client = new Client({ name: \"tanya\", version: \"0.10.0-beta.0\" }, { capabilities: {} });\n const transport = this.createTransport(config);\n const managed: ManagedServer = {\n config,\n client,\n transport,\n status: \"disconnected\",\n tools: [],\n restarts,\n };\n this.servers.set(config.name, managed);\n client.onclose = () => {\n void this.handleServerClose(config.name).catch(() => {});\n };\n client.onerror = (error) => {\n const current = this.servers.get(config.name);\n if (current) current.error = error.message;\n };\n try {\n await client.connect(transport);\n const listed = await client.listTools(undefined, { timeout: mcpCallTimeoutMs() });\n managed.tools = listed.tools;\n managed.status = \"connected\";\n managed.heartbeat = setInterval(() => {\n void client.ping({ timeout: 5_000 }).catch((error) => {\n managed.error = error instanceof Error ? error.message : String(error);\n void this.handleServerClose(config.name).catch(() => {});\n });\n }, 30_000);\n managed.heartbeat.unref?.();\n } catch (error) {\n managed.status = \"failed\";\n managed.error = error instanceof Error ? error.message : String(error);\n await this.sink?.({ type: \"status\", message: `MCP server ${config.name} failed to connect: ${managed.error}` });\n }\n }\n\n private async handleServerClose(name: string): Promise<void> {\n const current = this.servers.get(name);\n if (!current || current.status === \"disconnected\") return;\n if (current.restarts >= 3) {\n current.status = \"failed\";\n current.error = \"server exited after 3 restart attempts\";\n await this.sink?.({ type: \"status\", message: `MCP server ${name} failed after 3 restart attempts.` });\n return;\n }\n const restarts = current.restarts + 1;\n current.status = \"restarting\";\n current.restarts = restarts;\n await this.sink?.({ type: \"status\", message: `MCP server ${name} exited; restarting (${restarts}/3).` });\n await sleep(Math.min(500 * 2 ** (restarts - 1), 4_000));\n await this.connectServer(current.config, restarts);\n }\n\n private createTransport(config: McpServerConfig): Transport {\n if (config.transport === \"stdio\") {\n const logPath = mcpLogPath(this.workspace, config.name);\n mkdirSync(join(this.workspace, \".tania\", \"mcp\", \"logs\"), { recursive: true });\n rotateMcpLogIfNeeded(logPath);\n const transport = new StdioClientTransport({\n command: config.command ?? \"\",\n args: config.args ?? [],\n env: { ...process.env, ...(config.env ?? {}) } as Record<string, string>,\n stderr: \"pipe\",\n });\n const stderr = transport.stderr;\n if (stderr) stderr.pipe(createWriteStream(logPath, { flags: \"a\" }));\n return transport;\n }\n if (!config.url) throw new Error(`MCP server ${config.name} requires url.`);\n const url = new URL(config.url);\n return config.transport === \"sse\"\n ? new SSEClientTransport(url)\n : new StreamableHTTPClientTransport(url) as unknown as Transport;\n }\n\n private toTanyaTool(server: ManagedServer, tool: Tool): TanyaTool {\n const mcpToolName = tool.name;\n const name = `mcp:${server.config.name}:${mcpToolName}`;\n return {\n name,\n description: `[MCP ${server.config.name}] ${tool.description ?? mcpToolName}`,\n definition: {\n type: \"function\",\n function: {\n name,\n description: `[MCP ${server.config.name}] ${tool.description ?? mcpToolName}`,\n parameters: toToolParameters(tool.inputSchema),\n },\n },\n keepFullForVerifier: true,\n async run(input: unknown, _context: ToolContext): Promise<ToolResult> {\n try {\n const result = await server.client.callTool(\n {\n name: mcpToolName,\n arguments: isRecord(input) ? input : {},\n _meta: {\n \"tanya/mcp-depth\": runIdDepth(_context.runId ?? \"\"),\n },\n },\n undefined,\n { timeout: mcpCallTimeoutMs() },\n );\n const schemaViolation = validateMcpToolOutput(tool.outputSchema, result);\n if (schemaViolation) {\n return {\n ok: false,\n summary: `mcp schema violation: ${schemaViolation}`,\n error: `mcp schema violation: ${schemaViolation}`,\n output: { ok: false, error: `mcp schema violation: ${schemaViolation}` },\n };\n }\n return mcpResultToToolResult(result);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n return {\n ok: false,\n summary: `MCP tool ${name} failed.`,\n error: message,\n output: { ok: false, error: message },\n };\n }\n },\n };\n }\n}\n\nlet activeManager: { workspace: string; manager: McpClientManager } | null = null;\n\nexport async function loadMcpToolsForWorkspace(options: {\n cwd: string;\n registry: ToolRegistry;\n sink?: EventSink;\n home?: string;\n}): Promise<McpClientManager> {\n if (activeManager?.workspace === options.cwd) {\n activeManager.manager.registerTools(options.registry);\n return activeManager.manager;\n }\n if (activeManager) await activeManager.manager.closeAll();\n const manager = new McpClientManager(options.cwd, loadMcpConfig({ cwd: options.cwd, ...(options.home ? { home: options.home } : {}) }), options.sink);\n await manager.connectAll();\n manager.registerTools(options.registry);\n activeManager = { workspace: options.cwd, manager };\n return manager;\n}\n\nexport function getActiveMcpManager(): McpClientManager | null {\n return activeManager?.manager ?? null;\n}\n\nexport async function resetMcpClientManagerForTests(): Promise<void> {\n if (activeManager) await activeManager.manager.closeAll();\n activeManager = null;\n}\n\nfunction toToolParameters(inputSchema: Tool[\"inputSchema\"]): ToolDefinition[\"function\"][\"parameters\"] {\n const properties = isRecord(inputSchema.properties) ? inputSchema.properties : {};\n const required = Array.isArray(inputSchema.required)\n ? inputSchema.required.filter((item): item is string => typeof item === \"string\")\n : undefined;\n const additional = typeof inputSchema.additionalProperties === \"boolean\" ? inputSchema.additionalProperties : undefined;\n return {\n type: \"object\",\n properties,\n ...(required ? { required } : {}),\n ...(additional !== undefined ? { additionalProperties: additional } : {}),\n };\n}\n\nfunction mcpResultToToolResult(result: Awaited<ReturnType<Client[\"callTool\"]>>): ToolResult {\n if (\"toolResult\" in result) {\n return {\n ok: true,\n summary: \"MCP tool returned a compatibility result.\",\n output: result.toolResult,\n };\n }\n const output = callToolResultOutput(result);\n const text = typeof output === \"string\" ? output : JSON.stringify(output);\n return {\n ok: result.isError !== true,\n summary: result.isError === true\n ? `MCP tool returned an error: ${text.slice(0, 200)}`\n : `MCP tool returned ${result.content.length} content item${result.content.length === 1 ? \"\" : \"s\"}.`,\n output,\n ...(result.isError === true ? { error: text.slice(0, 2_000) } : {}),\n };\n}\n\nfunction callToolResultOutput(result: CallToolResult): unknown {\n if (result.structuredContent) return result.structuredContent;\n const textParts = result.content.flatMap((item) => {\n if (item.type === \"text\") return [item.text];\n if (item.type === \"resource\" && \"text\" in item.resource) return [item.resource.text];\n if (item.type === \"image\") return [`[image:${item.mimeType}; ${item.data.length} base64 chars]`];\n if (item.type === \"audio\") return [`[audio:${item.mimeType}; ${item.data.length} base64 chars]`];\n if (item.type === \"resource_link\") return [`[resource:${item.uri}]`];\n return [];\n });\n return textParts.length === 1 ? textParts[0] : textParts;\n}\n\nfunction validateMcpToolOutput(outputSchema: Tool[\"outputSchema\"], result: Awaited<ReturnType<Client[\"callTool\"]>>): string | null {\n if (!outputSchema) return null;\n if (\"toolResult\" in result) return null;\n if (!result.structuredContent) return \"missing structuredContent for declared output schema\";\n if (!isRecord(result.structuredContent)) return \"structuredContent must be an object\";\n return validateObjectSchema(outputSchema, result.structuredContent, \"$.structuredContent\");\n}\n\nfunction validateObjectSchema(schema: Tool[\"outputSchema\"], value: Record<string, unknown>, path: string): string | null {\n for (const key of schema?.required ?? []) {\n if (!(key in value)) return `${path}.${key} is required`;\n }\n const properties = isRecord(schema?.properties) ? schema.properties : {};\n for (const [key, propertySchema] of Object.entries(properties)) {\n if (!(key in value) || !isRecord(propertySchema)) continue;\n const expected = typeof propertySchema.type === \"string\" ? propertySchema.type : \"\";\n if (!expected) continue;\n const actual = Array.isArray(value[key]) ? \"array\" : typeof value[key];\n if (actual !== expected) return `${path}.${key} expected ${expected}, got ${actual}`;\n }\n return null;\n}\n\nfunction mcpCallTimeoutMs(): number {\n return Math.max(1_000, numberEnvValue(process.env, \"TANYA_MCP_CALL_TIMEOUT_MS\", 30_000));\n}\n\nfunction mcpLogPath(workspace: string, serverName: string): string {\n return join(workspace, \".tania\", \"mcp\", \"logs\", `${serverName}.log`);\n}\n\nfunction rotateMcpLogIfNeeded(path: string): void {\n if (!existsSync(path)) return;\n try {\n if (statSync(path).size < 10 * 1024 * 1024) return;\n const rotated = `${path}.1`;\n try {\n if (existsSync(rotated)) unlinkSync(rotated);\n } catch {\n // Ignore stale rotated log cleanup failures.\n }\n renameSync(path, rotated);\n } catch {\n // Log rotation is best-effort; a bad log file must not block startup.\n }\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return Boolean(value && typeof value === \"object\" && !Array.isArray(value));\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\nexport const validateMcpToolOutputForTests = validateMcpToolOutput;\n","import { existsSync, readFileSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { join } from \"node:path\";\n\nexport type McpTransportKind = \"stdio\" | \"sse\" | \"http\";\n\nexport interface McpServerConfig {\n name: string;\n transport: McpTransportKind;\n command?: string;\n args?: string[];\n env?: Record<string, string>;\n url?: string;\n enabled?: boolean;\n}\n\nexport interface McpConfig {\n version: 1;\n servers: McpServerConfig[];\n}\n\nexport interface McpConfigIssue {\n file: string;\n path: string;\n message: string;\n}\n\nexport interface LoadedMcpConfig {\n config: McpConfig;\n sources: string[];\n issues: McpConfigIssue[];\n}\n\nconst EMPTY_CONFIG: McpConfig = { version: 1, servers: [] };\nconst TRANSPORTS = new Set<McpTransportKind>([\"stdio\", \"sse\", \"http\"]);\n\nexport function loadMcpConfig(options: { cwd: string; home?: string }): LoadedMcpConfig {\n const home = options.home ?? homedir();\n const userCurrent = join(home, \".tanya\", \"mcp.json\");\n const userLegacy = join(home, \".tania\", \"mcp.json\");\n const userFile = existsSync(userCurrent) ? userCurrent : existsSync(userLegacy) ? userLegacy : null;\n const candidates = [\n ...(userFile ? [userFile] : []),\n join(options.cwd, \".tania\", \"mcp.json\"),\n ];\n\n let config = cloneConfig(EMPTY_CONFIG);\n const sources: string[] = [];\n const issues: McpConfigIssue[] = [];\n for (const file of candidates) {\n if (!existsSync(file)) continue;\n const parsed = parseMcpConfig(readFileSync(file, \"utf8\"), file);\n if (!parsed.ok) {\n issues.push(...parsed.issues);\n continue;\n }\n config = mergeMcpConfig(config, parsed.config);\n sources.push(file);\n }\n\n return { config, sources, issues };\n}\n\nexport function mergeMcpConfig(base: McpConfig, next: McpConfig): McpConfig {\n const byName = new Map<string, McpServerConfig>();\n for (const server of base.servers) byName.set(server.name, cloneServer(server));\n for (const server of next.servers) byName.set(server.name, cloneServer(server));\n const nextNames = new Set(next.servers.map((server) => server.name));\n return {\n version: 1,\n servers: [\n ...next.servers.map((server) => cloneServer(server)),\n ...base.servers.filter((server) => !nextNames.has(server.name)).map((server) => cloneServer(server)),\n ],\n };\n}\n\nexport function parseMcpConfig(raw: string, file = \"<memory>\"): { ok: true; config: McpConfig } | { ok: false; issues: McpConfigIssue[] } {\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n return { ok: false, issues: [{ file, path: \"$\", message: `Invalid JSON: ${message}` }] };\n }\n return validateMcpConfig(parsed, file);\n}\n\nexport function validateMcpConfig(input: unknown, file = \"<memory>\"): { ok: true; config: McpConfig } | { ok: false; issues: McpConfigIssue[] } {\n const issues: McpConfigIssue[] = [];\n if (!isRecord(input)) {\n return { ok: false, issues: [{ file, path: \"$\", message: \"Expected an object.\" }] };\n }\n if (input.version !== 1) {\n issues.push({ file, path: \"$.version\", message: \"Expected schema version 1.\" });\n }\n if (!Array.isArray(input.servers)) {\n issues.push({ file, path: \"$.servers\", message: \"Expected an array.\" });\n }\n const servers = Array.isArray(input.servers)\n ? input.servers.flatMap((server, index) => validateServer(server, `$.servers[${index}]`, file, issues))\n : [];\n if (issues.length > 0) return { ok: false, issues };\n return { ok: true, config: { version: 1, servers } };\n}\n\nfunction validateServer(input: unknown, path: string, file: string, issues: McpConfigIssue[]): McpServerConfig[] {\n if (!isRecord(input)) {\n issues.push({ file, path, message: \"Expected an object.\" });\n return [];\n }\n const name = typeof input.name === \"string\" ? input.name.trim() : \"\";\n if (!name) issues.push({ file, path: `${path}.name`, message: \"Expected a non-empty server name.\" });\n if (name && !/^[A-Za-z0-9_.-]+$/.test(name)) {\n issues.push({ file, path: `${path}.name`, message: \"Server names may contain letters, numbers, '.', '_' and '-'.\" });\n }\n const transport = typeof input.transport === \"string\" && TRANSPORTS.has(input.transport as McpTransportKind)\n ? input.transport as McpTransportKind\n : null;\n if (!transport) issues.push({ file, path: `${path}.transport`, message: \"Expected stdio, sse, or http.\" });\n if (transport === \"stdio\" && (typeof input.command !== \"string\" || input.command.trim() === \"\")) {\n issues.push({ file, path: `${path}.command`, message: \"stdio servers require command.\" });\n }\n if ((transport === \"sse\" || transport === \"http\") && (typeof input.url !== \"string\" || input.url.trim() === \"\")) {\n issues.push({ file, path: `${path}.url`, message: `${transport} servers require url.` });\n }\n const args = input.args === undefined ? undefined : stringArray(input.args, `${path}.args`, file, issues);\n const env = input.env === undefined ? undefined : stringRecord(input.env, `${path}.env`, file, issues);\n if (input.enabled !== undefined && typeof input.enabled !== \"boolean\") {\n issues.push({ file, path: `${path}.enabled`, message: \"Expected boolean when present.\" });\n }\n if (!name || !transport) return [];\n return [{\n name,\n transport,\n ...(typeof input.command === \"string\" && input.command.trim() ? { command: input.command.trim() } : {}),\n ...(args ? { args } : {}),\n ...(env ? { env } : {}),\n ...(typeof input.url === \"string\" && input.url.trim() ? { url: input.url.trim() } : {}),\n ...(input.enabled !== undefined ? { enabled: Boolean(input.enabled) } : {}),\n }];\n}\n\nfunction stringArray(input: unknown, path: string, file: string, issues: McpConfigIssue[]): string[] {\n if (!Array.isArray(input)) {\n issues.push({ file, path, message: \"Expected an array of strings.\" });\n return [];\n }\n return input.flatMap((item, index) => {\n if (typeof item === \"string\") return [item];\n issues.push({ file, path: `${path}[${index}]`, message: \"Expected a string.\" });\n return [];\n });\n}\n\nfunction stringRecord(input: unknown, path: string, file: string, issues: McpConfigIssue[]): Record<string, string> {\n if (!isRecord(input)) {\n issues.push({ file, path, message: \"Expected an object with string values.\" });\n return {};\n }\n const output: Record<string, string> = {};\n for (const [key, value] of Object.entries(input)) {\n if (typeof value === \"string\") {\n output[key] = value;\n } else {\n issues.push({ file, path: `${path}.${key}`, message: \"Expected a string.\" });\n }\n }\n return output;\n}\n\nfunction cloneConfig(config: McpConfig): McpConfig {\n return { version: 1, servers: config.servers.map((server) => cloneServer(server)) };\n}\n\nfunction cloneServer(server: McpServerConfig): McpServerConfig {\n return {\n name: server.name,\n transport: server.transport,\n ...(server.command ? { command: server.command } : {}),\n ...(server.args ? { args: [...server.args] } : {}),\n ...(server.env ? { env: { ...server.env } } : {}),\n ...(server.url ? { url: server.url } : {}),\n ...(server.enabled !== undefined ? { enabled: server.enabled } : {}),\n };\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return Boolean(value && typeof value === \"object\" && !Array.isArray(value));\n}\n","import { existsSync, readFileSync } from \"node:fs\";\nimport type { TanyaRunContext } from \"../../context/runContext\";\nimport { noopShell, realShell } from \"./shell\";\nimport { builtinVerifiers } from \"./registry\";\n\nfunction defaultShell() {\n if (process.env.VITEST === \"true\" || process.env.TANIA_VERIFIER_SHELL === \"noop\") {\n return noopShell;\n }\n return realShell;\n}\nimport type {\n FinalStateVerification,\n Verifier,\n VerifierCheck,\n VerifierContext,\n VerifierShell,\n} from \"./types\";\n\nexport type { FinalStateVerification, Verifier, VerifierCheck, VerifierShell } from \"./types\";\n\nexport type VerifyFinalStateOptions = {\n workspace: string;\n prompt?: string | undefined;\n runContext?: TanyaRunContext | undefined;\n shell?: VerifierShell | undefined;\n verifiers?: Verifier[] | undefined;\n};\n\nfunction buildContext(options: VerifyFinalStateOptions): VerifierContext {\n return {\n workspace: options.workspace,\n runContext: options.runContext,\n prompt: options.prompt ?? \"\",\n shell: options.shell ?? defaultShell(),\n fileExists: (path: string) => existsSync(path),\n readText: (path: string) => {\n try {\n return readFileSync(path, \"utf8\");\n } catch {\n return null;\n }\n },\n };\n}\n\nfunction uniquePlatforms<T>(values: T[]): T[] {\n return Array.from(new Set(values));\n}\n\nexport async function verifyFinalState(options: VerifyFinalStateOptions): Promise<FinalStateVerification> {\n const ctx = buildContext(options);\n const candidates = options.verifiers ?? builtinVerifiers;\n const applicable: Verifier[] = [];\n for (const verifier of candidates) {\n if (await verifier.appliesTo(ctx)) applicable.push(verifier);\n }\n\n const ranPlatforms = uniquePlatforms(applicable.map((verifier) => verifier.platform));\n const checks: VerifierCheck[] = [];\n for (const verifier of applicable) {\n try {\n const verifierChecks = await verifier.run(ctx);\n checks.push(...verifierChecks);\n } catch (err) {\n checks.push({\n id: `${verifier.id}-crash`,\n description: `${verifier.id} verifier crashed`,\n passed: false,\n authoritative: false,\n error: err instanceof Error ? err.message : String(err),\n });\n }\n }\n\n const authoritativeChecks = checks.filter((check) => check.authoritative);\n const authoritativePassed = authoritativeChecks.length > 0 && authoritativeChecks.every((check) => check.passed);\n\n const formatFailedCheck = (check: VerifierCheck) =>\n `final-state check failed: ${check.description}${check.error ? ` (${check.error})` : \"\"}`;\n\n const newBlockers = checks\n .filter((check) => !check.passed && check.authoritative === true)\n .map(formatFailedCheck);\n\n const warnings = checks\n .filter((check) => !check.passed && check.authoritative !== true)\n .map((check) => `final-state check failed: ${check.description}${check.error ? ` (${check.error})` : \"\"}`);\n\n // Recovered failure commands are advisory: callers use them to mark soft probe failures.\n // We don't enumerate concrete commands here; the runner's existing recovery heuristics\n // already handle that classification. Returning the list lets future callers/tests\n // add finer-grained matching if needed.\n const recoveredFailureCommands: string[] = [];\n\n return {\n ranVerifiers: ranPlatforms,\n checks,\n authoritativePassed,\n newBlockers,\n warnings,\n recoveredFailureCommands,\n };\n}\n","import { execFile } from \"node:child_process\";\nimport { promisify } from \"node:util\";\nimport type { VerifierShell, VerifierShellResult } from \"./types\";\n\nconst execFileAsync = promisify(execFile);\n\nexport const noopShell: VerifierShell = async () => ({\n exit: 1,\n stdout: \"\",\n stderr: \"noop shell\",\n binaryMissing: true,\n});\n\nexport const realShell: VerifierShell = async (cwd, command, args, options) => {\n try {\n const { stdout, stderr } = await execFileAsync(command, args, {\n cwd,\n timeout: options?.timeoutMs ?? 60_000,\n maxBuffer: 8 * 1024 * 1024,\n env: options?.env ?? process.env,\n });\n return { exit: 0, stdout, stderr };\n } catch (err) {\n const error = err as NodeJS.ErrnoException & { stdout?: string; stderr?: string; code?: number | string; killed?: boolean; signal?: string };\n const timedOut = error.killed === true || error.signal === \"SIGTERM\";\n const binaryMissing = error.code === \"ENOENT\";\n const result: VerifierShellResult = {\n exit: typeof error.code === \"number\" ? error.code : 1,\n stdout: error.stdout ?? \"\",\n stderr: error.stderr ?? error.message ?? \"\",\n };\n if (timedOut) result.timedOut = true;\n if (binaryMissing) result.binaryMissing = true;\n return result;\n }\n};\n","import { existsSync, readdirSync, statSync } from \"node:fs\";\nimport { dirname, join, relative, resolve } from \"node:path\";\nimport { load as loadYaml } from \"js-yaml\";\nimport type { Verifier, VerifierCheck, VerifierContext } from \"../types\";\nimport { makeCheck } from \"../types\";\nimport { combinedTaskText, mentionsAny } from \"../textHints\";\n\nconst HUMA_PATTERNS = [/\\bhuma\\b/i, /\\bhuma\\/v2\\b/i];\nconst CHI_PATTERNS = [/\\bgo-?chi\\b/i, /\\bchi\\/v5\\b/i, /\\bchi router\\b/i];\nconst PGX_PATTERNS = [/\\bpgx\\b/i, /\\bjackc\\/pgx\\b/i, /\\bpostgres\\b/i, /\\bpostgresql\\b/i];\nconst REST_SERVER_PATTERNS = [/\\bcmd\\/server\\b/i, /\\bmain\\.go\\b/i, /\\brest server\\b/i, /\\bhttp server\\b/i];\nconst INTERNAL_PKG_PATTERNS = [...REST_SERVER_PATTERNS, /\\binternal\\//i];\nconst SQLC_PATTERNS = [/\\bsqlc\\b/i];\n\nfunction listDir(path: string): string[] {\n try {\n return readdirSync(path);\n } catch {\n return [];\n }\n}\n\nfunction dirContainsGoFile(path: string): boolean {\n if (!existsSync(path)) return false;\n for (const entry of listDir(path)) {\n const full = join(path, entry);\n try {\n const st = statSync(full);\n if (st.isFile() && entry.endsWith(\".go\")) return true;\n if (st.isDirectory() && dirContainsGoFile(full)) return true;\n } catch {\n // ignore\n }\n }\n return false;\n}\n\ntype GoFileScan = { hasAnyGoFile: boolean; hasAnyTestFile: boolean };\n\nfunction scanGoFiles(workspace: string): GoFileScan {\n const queue = [workspace];\n let visited = 0;\n let hasAnyGoFile = false;\n let hasAnyTestFile = false;\n while (queue.length > 0 && visited < 500) {\n const dir = queue.shift();\n if (!dir) break;\n visited += 1;\n for (const entry of listDir(dir)) {\n if (entry === \"node_modules\" || entry === \".git\" || entry === \"dist\" || entry === \"build\") continue;\n const full = join(dir, entry);\n try {\n const st = statSync(full);\n if (st.isFile() && entry.endsWith(\".go\")) {\n hasAnyGoFile = true;\n if (entry.endsWith(\"_test.go\")) hasAnyTestFile = true;\n }\n if (st.isDirectory()) queue.push(full);\n } catch {\n // ignore\n }\n }\n }\n return { hasAnyGoFile, hasAnyTestFile };\n}\n\nfunction parseSqlcGenDirs(text: string): string[] {\n const dirs: string[] = [];\n for (const raw of text.split(/\\r?\\n/)) {\n const match = raw.match(/^\\s*out\\s*:\\s*[\"']?([^\"'\\s#]+)/i);\n if (match?.[1]) dirs.push(match[1]);\n }\n return dirs;\n}\n\ntype SqlcConfigEntry = {\n outDirs: string[];\n queryPaths: string[];\n};\n\nfunction stringsFromSqlcValue(value: unknown): string[] {\n if (typeof value === \"string\") return [value];\n if (Array.isArray(value)) {\n return value.flatMap((item) => stringsFromSqlcValue(item));\n }\n return [];\n}\n\nfunction parseSqlcConfig(text: string): SqlcConfigEntry[] {\n try {\n const parsed = loadYaml(text);\n if (!parsed || typeof parsed !== \"object\") {\n return parseSqlcGenDirs(text).map((dir) => ({ outDirs: [dir], queryPaths: [] }));\n }\n const root = parsed as Record<string, unknown>;\n const sql = Array.isArray(root.sql) ? root.sql : [];\n const entries: SqlcConfigEntry[] = [];\n for (const rawEntry of sql) {\n if (!rawEntry || typeof rawEntry !== \"object\") continue;\n const entry = rawEntry as Record<string, unknown>;\n const queryPaths = stringsFromSqlcValue(entry.queries);\n const gen = entry.gen;\n const outDirs: string[] = [];\n if (gen && typeof gen === \"object\" && !Array.isArray(gen)) {\n for (const rawGenConfig of Object.values(gen as Record<string, unknown>)) {\n if (!rawGenConfig || typeof rawGenConfig !== \"object\" || Array.isArray(rawGenConfig)) continue;\n const out = (rawGenConfig as Record<string, unknown>).out;\n if (typeof out === \"string\") outDirs.push(out);\n }\n }\n if (typeof entry.out === \"string\") outDirs.push(entry.out);\n entries.push({ outDirs, queryPaths });\n }\n return entries;\n } catch {\n return parseSqlcGenDirs(text).map((dir) => ({ outDirs: [dir], queryPaths: [] }));\n }\n}\n\nfunction sqlFilesUnder(path: string): string[] {\n try {\n const st = statSync(path);\n if (st.isFile()) return path.endsWith(\".sql\") ? [path] : [];\n if (!st.isDirectory()) return [];\n } catch {\n return [];\n }\n const out: string[] = [];\n const queue = [path];\n let visited = 0;\n while (queue.length > 0 && visited < 500) {\n const dir = queue.shift();\n if (!dir) break;\n visited += 1;\n for (const entry of listDir(dir)) {\n const full = join(dir, entry);\n try {\n const st = statSync(full);\n if (st.isFile() && entry.endsWith(\".sql\")) out.push(full);\n if (st.isDirectory()) queue.push(full);\n } catch {\n // ignore\n }\n }\n }\n return out;\n}\n\nfunction globToRegExp(pattern: string): RegExp {\n let out = \"^\";\n for (let i = 0; i < pattern.length; i += 1) {\n const ch = pattern[i] ?? \"\";\n const next = pattern[i + 1];\n if (ch === \"*\" && next === \"*\") {\n out += \".*\";\n i += 1;\n continue;\n }\n if (ch === \"*\") {\n out += \"[^/]*\";\n continue;\n }\n if (ch === \"?\") {\n out += \"[^/]\";\n continue;\n }\n out += ch.replace(/[|\\\\{}()[\\]^$+*?.]/g, \"\\\\$&\");\n }\n out += \"$\";\n return new RegExp(out);\n}\n\nfunction referencedSqlQueryFiles(workspace: string, queryPath: string): string[] {\n const cleanQueryPath = queryPath.trim();\n if (!cleanQueryPath) return [];\n if (!/[*?]/.test(cleanQueryPath)) {\n return sqlFilesUnder(join(workspace, cleanQueryPath));\n }\n\n const firstGlob = cleanQueryPath.search(/[*?]/);\n const prefix = cleanQueryPath.slice(0, firstGlob);\n const searchRoot = resolve(workspace, dirname(prefix || \".\"));\n const workspaceRoot = resolve(workspace);\n if (relative(workspaceRoot, searchRoot).startsWith(\"..\")) return [];\n\n const matcher = globToRegExp(cleanQueryPath.replace(/\\\\/g, \"/\"));\n return sqlFilesUnder(searchRoot).filter((file) => {\n const rel = relative(workspaceRoot, file).replace(/\\\\/g, \"/\");\n return matcher.test(rel);\n });\n}\n\nfunction hasReferencedSqlQueries(workspace: string, queryPaths: string[]): boolean {\n return queryPaths.some((queryPath) => referencedSqlQueryFiles(workspace, queryPath).length > 0);\n}\n\nexport const goBackendVerifier: Verifier = {\n id: \"go-backend\",\n platform: \"go-backend\",\n appliesTo(ctx) {\n if (ctx.fileExists(join(ctx.workspace, \"go.mod\"))) return true;\n const text = combinedTaskText(ctx.runContext, ctx.prompt);\n return /\\bgo\\.mod\\b/.test(text) || /\\bgolang\\b/.test(text);\n },\n async run(ctx) {\n const checks: VerifierCheck[] = [];\n const goModPath = join(ctx.workspace, \"go.mod\");\n const goModText = ctx.readText(goModPath);\n const text = combinedTaskText(ctx.runContext, ctx.prompt);\n\n checks.push(makeCheck({\n id: \"go.mod-present\",\n description: \"go.mod exists\",\n passed: goModText !== null,\n authoritative: false,\n error: goModText === null ? `go.mod not found at ${goModPath}` : undefined,\n }));\n\n const requireDep = (depPattern: RegExp, depLabel: string, requiredWhen: boolean) => {\n if (!requiredWhen) return;\n const present = goModText !== null && depPattern.test(goModText);\n checks.push(makeCheck({\n id: `go.mod-dep-${depLabel}`,\n description: `go.mod declares ${depLabel}`,\n passed: present,\n authoritative: false,\n error: present ? undefined : `expected ${depLabel} dependency in go.mod`,\n }));\n };\n\n requireDep(/github\\.com\\/danielgtaylor\\/huma\\/v2/, \"huma/v2\", mentionsAny(text, HUMA_PATTERNS));\n requireDep(/github\\.com\\/go-chi\\/chi\\/v5/, \"chi/v5\", mentionsAny(text, CHI_PATTERNS));\n requireDep(/github\\.com\\/jackc\\/pgx\\/v5/, \"pgx/v5\", mentionsAny(text, PGX_PATTERNS));\n\n if (mentionsAny(text, REST_SERVER_PATTERNS)) {\n const mainPath = join(ctx.workspace, \"cmd\", \"server\", \"main.go\");\n const present = ctx.fileExists(mainPath);\n checks.push(makeCheck({\n id: \"cmd-server-main\",\n description: \"cmd/server/main.go exists\",\n passed: present,\n authoritative: false,\n error: present ? undefined : \"expected entrypoint at cmd/server/main.go\",\n }));\n }\n\n const internalPath = join(ctx.workspace, \"internal\");\n if (mentionsAny(text, INTERNAL_PKG_PATTERNS)) {\n const hasInternalGo = dirContainsGoFile(internalPath);\n checks.push(makeCheck({\n id: \"internal-packages\",\n description: \"internal/ contains at least one Go package\",\n passed: hasInternalGo,\n authoritative: false,\n error: hasInternalGo ? undefined : \"expected at least one Go package under internal/\",\n }));\n }\n\n const sqlcPath = join(ctx.workspace, \"sqlc.yaml\");\n const sqlcText = ctx.readText(sqlcPath);\n if (sqlcText && mentionsAny(text, SQLC_PATTERNS)) {\n for (const entry of parseSqlcConfig(sqlcText)) {\n const hasQueries = hasReferencedSqlQueries(ctx.workspace, entry.queryPaths);\n for (const dir of entry.outDirs) {\n if (!hasQueries) {\n checks.push(makeCheck({\n id: `sqlc-out-${dir}`,\n description: `sqlc generated code present at ${dir}`,\n passed: true,\n authoritative: false,\n skipped: true,\n evidence: \"skipped: sqlc.yaml does not reference any existing .sql query files yet\",\n }));\n continue;\n }\n const target = join(ctx.workspace, dir);\n const present = ctx.fileExists(target) && dirContainsGoFile(target);\n checks.push(makeCheck({\n id: `sqlc-out-${dir}`,\n description: `sqlc generated code present at ${dir}`,\n passed: present,\n authoritative: false,\n error: present ? undefined : `sqlc.yaml references ${dir} but no Go files were generated there`,\n }));\n }\n }\n }\n\n const scan = scanGoFiles(ctx.workspace);\n if (goModText !== null && !scan.hasAnyGoFile) {\n checks.push(makeCheck({\n id: \"go-build\",\n description: \"go build ./...\",\n passed: true,\n authoritative: true,\n evidence: \"skipped: no Go source files in workspace yet\",\n }));\n return checks;\n }\n if (goModText !== null) {\n const buildResult = await ctx.shell(ctx.workspace, \"go\", [\"build\", \"./...\"], { timeoutMs: 90_000 });\n if (buildResult.binaryMissing) {\n checks.push(makeCheck({\n id: \"go-toolchain-missing\",\n description: \"go toolchain available\",\n passed: true,\n authoritative: false,\n evidence: \"skipped: 'go' binary not found on PATH\",\n }));\n return checks;\n }\n const buildPassed = buildResult.exit === 0;\n checks.push(makeCheck({\n id: \"go-build\",\n description: \"go build ./...\",\n passed: buildPassed,\n authoritative: true,\n evidence: buildPassed ? \"go build ./... -> exit 0\" : undefined,\n error: buildPassed ? undefined : (buildResult.stderr || buildResult.stdout || \"go build failed\").slice(0, 500),\n }));\n\n if (buildPassed) {\n const vetResult = await ctx.shell(ctx.workspace, \"go\", [\"vet\", \"./...\"], { timeoutMs: 60_000 });\n const vetPassed = vetResult.exit === 0;\n checks.push(makeCheck({\n id: \"go-vet\",\n description: \"go vet ./...\",\n passed: vetPassed,\n authoritative: false,\n evidence: vetPassed ? \"go vet ./... -> exit 0\" : undefined,\n error: vetPassed ? undefined : (vetResult.stderr || vetResult.stdout || \"go vet failed\").slice(0, 500),\n }));\n\n if (scan.hasAnyTestFile) {\n const testResult = await ctx.shell(ctx.workspace, \"go\", [\"test\", \"./...\"], { timeoutMs: 180_000 });\n const testPassed = testResult.exit === 0;\n checks.push(makeCheck({\n id: \"go-test\",\n description: \"go test ./...\",\n passed: testPassed,\n authoritative: true,\n evidence: testPassed ? \"go test ./... -> exit 0\" : undefined,\n error: testPassed ? undefined : (testResult.stderr || testResult.stdout || \"go test failed\").slice(0, 800),\n }));\n }\n }\n }\n\n return checks;\n },\n};\n","export type ChildFailureDisposition = \"blocker\" | \"warning\" | \"ignore\";\n\nexport type ChildVerdict = {\n subRunId: string;\n verdict: \"passed\" | \"failed\";\n blockers: string[];\n summary: string;\n changedFiles: string[];\n treatFailureAs: ChildFailureDisposition;\n};\n\nexport type ReasoningAnnotation = {\n runId: string;\n turn?: number;\n provider: string;\n model: string;\n blocker?: string;\n excerpt: string;\n confidence: \"advisory\";\n};\n\n// ──────────────────────────────────────────────────────────\n// Final-state verifier types (salvaged from F-fix.5+8 WIP)\n// ──────────────────────────────────────────────────────────\n\nimport type { TanyaRunContext } from \"../../context/runContext\";\n\nexport type VerifierShellResult = {\n exit: number;\n stdout: string;\n stderr: string;\n timedOut?: boolean;\n binaryMissing?: boolean;\n};\n\nexport type VerifierShell = (\n cwd: string,\n command: string,\n args: string[],\n options?: { timeoutMs?: number; env?: NodeJS.ProcessEnv },\n) => Promise<VerifierShellResult>;\n\nexport type VerifierCheck = {\n id: string;\n description: string;\n passed: boolean;\n authoritative: boolean;\n skipped?: boolean;\n evidence?: string;\n error?: string;\n};\n\nexport function makeCheck(input: {\n id: string;\n description: string;\n passed: boolean;\n authoritative: boolean;\n skipped?: boolean | undefined;\n evidence?: string | undefined;\n error?: string | undefined;\n}): VerifierCheck {\n const check: VerifierCheck = {\n id: input.id,\n description: input.description,\n passed: input.passed,\n authoritative: input.authoritative,\n };\n if (input.skipped !== undefined) check.skipped = input.skipped;\n if (input.evidence !== undefined) check.evidence = input.evidence;\n if (input.error !== undefined) check.error = input.error;\n return check;\n}\n\nexport type VerifierPlatform =\n | \"go-backend\"\n | \"node-backend\"\n | \"frontend\"\n | \"ios\"\n | \"android\"\n | \"generic\";\n\nexport type VerifierContext = {\n workspace: string;\n runContext?: TanyaRunContext | undefined;\n prompt: string;\n shell: VerifierShell;\n fileExists: (path: string) => boolean;\n readText: (path: string) => string | null;\n};\n\nexport type Verifier = {\n id: string;\n platform: VerifierPlatform;\n appliesTo(ctx: VerifierContext): boolean | Promise<boolean>;\n run(ctx: VerifierContext): Promise<VerifierCheck[]>;\n};\n\nexport type FinalStateVerification = {\n ranVerifiers: VerifierPlatform[];\n checks: VerifierCheck[];\n authoritativePassed: boolean;\n newBlockers: string[];\n warnings: string[];\n recoveredFailureCommands: string[];\n};\n","import type { TanyaRunContext } from \"../../context/runContext\";\n\nexport function combinedTaskText(runContext: TanyaRunContext | undefined, prompt: string): string {\n return [\n prompt,\n runContext?.task?.title,\n runContext?.task?.summary,\n ...(runContext?.instructions ?? []),\n ]\n .filter((value): value is string => typeof value === \"string\" && value.trim().length > 0)\n .join(\"\\n\")\n .toLowerCase();\n}\n\nexport function mentionsAny(text: string, needles: RegExp[]): boolean {\n return needles.some((needle) => needle.test(text));\n}\n","import { join } from \"node:path\";\nimport type { Verifier, VerifierCheck, VerifierContext } from \"../types\";\nimport { makeCheck } from \"../types\";\n\nconst BACKEND_DEP_HINTS = [\"express\", \"fastify\", \"@nestjs/core\", \"hono\", \"koa\", \"@fastify/\", \"@hono/\"];\n\ntype PackageJson = {\n scripts?: Record<string, string>;\n dependencies?: Record<string, string>;\n devDependencies?: Record<string, string>;\n};\n\nfunction readPackageJson(ctx: VerifierContext): PackageJson | null {\n const text = ctx.readText(join(ctx.workspace, \"package.json\"));\n if (!text) return null;\n try {\n return JSON.parse(text) as PackageJson;\n } catch {\n return null;\n }\n}\n\nfunction looksLikeBackend(pkg: PackageJson): boolean {\n const deps = { ...(pkg.dependencies ?? {}), ...(pkg.devDependencies ?? {}) };\n return BACKEND_DEP_HINTS.some((hint) => Object.keys(deps).some((k) => k === hint || k.startsWith(hint)));\n}\n\nexport const nodeBackendVerifier: Verifier = {\n id: \"node-backend\",\n platform: \"node-backend\",\n appliesTo(ctx) {\n const pkg = readPackageJson(ctx);\n if (!pkg) return false;\n return looksLikeBackend(pkg);\n },\n async run(ctx) {\n const checks: VerifierCheck[] = [];\n const pkg = readPackageJson(ctx);\n checks.push(makeCheck({\n id: \"package-json-parse\",\n description: \"package.json parses\",\n passed: pkg !== null,\n authoritative: false,\n error: pkg === null ? \"package.json missing or unparseable\" : undefined,\n }));\n if (!pkg) return checks;\n\n const scripts = pkg.scripts ?? {};\n if (typeof scripts.typecheck === \"string\") {\n const res = await ctx.shell(ctx.workspace, \"npm\", [\"run\", \"--silent\", \"typecheck\"], { timeoutMs: 180_000 });\n if (res.binaryMissing) return checks;\n const passed = res.exit === 0;\n checks.push(makeCheck({\n id: \"npm-typecheck\",\n description: \"npm run typecheck\",\n passed,\n authoritative: true,\n error: passed ? undefined : (res.stderr || res.stdout || \"typecheck failed\").slice(0, 500),\n }));\n }\n if (typeof scripts.test === \"string\" && !/no test specified/i.test(scripts.test)) {\n const res = await ctx.shell(ctx.workspace, \"npm\", [\"test\", \"--silent\"], { timeoutMs: 240_000 });\n if (res.binaryMissing) return checks;\n const passed = res.exit === 0;\n checks.push(makeCheck({\n id: \"npm-test\",\n description: \"npm test\",\n passed,\n authoritative: true,\n error: passed ? undefined : (res.stderr || res.stdout || \"tests failed\").slice(0, 500),\n }));\n }\n return checks;\n },\n};\n","import { join } from \"node:path\";\nimport type { Verifier, VerifierCheck, VerifierContext } from \"../types\";\nimport { makeCheck } from \"../types\";\n\nconst FRONTEND_DEP_HINTS = [\"next\", \"react\", \"vite\", \"@vitejs/\", \"@tanstack/router\", \"remix\", \"@remix-run/\"];\n\ntype PackageJson = {\n scripts?: Record<string, string>;\n dependencies?: Record<string, string>;\n devDependencies?: Record<string, string>;\n};\n\nfunction readPackageJson(ctx: VerifierContext): PackageJson | null {\n const text = ctx.readText(join(ctx.workspace, \"package.json\"));\n if (!text) return null;\n try {\n return JSON.parse(text) as PackageJson;\n } catch {\n return null;\n }\n}\n\nfunction looksLikeFrontend(pkg: PackageJson): boolean {\n const deps = { ...(pkg.dependencies ?? {}), ...(pkg.devDependencies ?? {}) };\n return FRONTEND_DEP_HINTS.some((hint) => Object.keys(deps).some((k) => k === hint || k.startsWith(hint)));\n}\n\nexport const frontendVerifier: Verifier = {\n id: \"frontend\",\n platform: \"frontend\",\n appliesTo(ctx) {\n const pkg = readPackageJson(ctx);\n if (!pkg) return false;\n return looksLikeFrontend(pkg);\n },\n async run(ctx) {\n const checks: VerifierCheck[] = [];\n const pkg = readPackageJson(ctx);\n checks.push(makeCheck({\n id: \"package-json-parse\",\n description: \"package.json parses\",\n passed: pkg !== null,\n authoritative: false,\n error: pkg === null ? \"package.json missing or unparseable\" : undefined,\n }));\n if (!pkg) return checks;\n\n const scripts = pkg.scripts ?? {};\n if (typeof scripts.typecheck === \"string\") {\n const res = await ctx.shell(ctx.workspace, \"npm\", [\"run\", \"--silent\", \"typecheck\"], { timeoutMs: 180_000 });\n if (res.binaryMissing) return checks;\n const passed = res.exit === 0;\n checks.push(makeCheck({\n id: \"npm-typecheck\",\n description: \"npm run typecheck\",\n passed,\n authoritative: true,\n error: passed ? undefined : (res.stderr || res.stdout || \"typecheck failed\").slice(0, 500),\n }));\n }\n if (typeof scripts.lint === \"string\") {\n const res = await ctx.shell(ctx.workspace, \"npm\", [\"run\", \"--silent\", \"lint\"], { timeoutMs: 180_000 });\n if (res.binaryMissing) return checks;\n const passed = res.exit === 0;\n checks.push(makeCheck({\n id: \"npm-lint\",\n description: \"npm run lint\",\n passed,\n authoritative: false,\n error: passed ? undefined : (res.stderr || res.stdout || \"lint failed\").slice(0, 500),\n }));\n }\n return checks;\n },\n};\n","import { join } from \"node:path\";\nimport type { Verifier, VerifierCheck } from \"../types\";\nimport { makeCheck } from \"../types\";\n\nexport const iosVerifier: Verifier = {\n id: \"ios\",\n platform: \"ios\",\n appliesTo(ctx) {\n return ctx.fileExists(join(ctx.workspace, \"Package.swift\"));\n },\n async run(ctx) {\n const checks: VerifierCheck[] = [];\n const text = ctx.readText(join(ctx.workspace, \"Package.swift\"));\n checks.push(makeCheck({\n id: \"package-swift-present\",\n description: \"Package.swift exists\",\n passed: text !== null,\n authoritative: false,\n error: text === null ? \"Package.swift missing\" : undefined,\n }));\n return checks;\n },\n};\n\nexport const androidVerifier: Verifier = {\n id: \"android\",\n platform: \"android\",\n appliesTo(ctx) {\n return ctx.fileExists(join(ctx.workspace, \"build.gradle.kts\")) ||\n ctx.fileExists(join(ctx.workspace, \"settings.gradle.kts\"));\n },\n async run(ctx) {\n const checks: VerifierCheck[] = [];\n const buildGradle = ctx.readText(join(ctx.workspace, \"build.gradle.kts\"));\n const settingsGradle = ctx.readText(join(ctx.workspace, \"settings.gradle.kts\"));\n const passed = buildGradle !== null || settingsGradle !== null;\n checks.push(makeCheck({\n id: \"gradle-config-present\",\n description: \"build.gradle.kts or settings.gradle.kts exists\",\n passed,\n authoritative: false,\n error: passed ? undefined : \"Gradle Kotlin DSL config missing\",\n }));\n return checks;\n },\n};\n","import type { Verifier } from \"./types\";\nimport { goBackendVerifier } from \"./verifiers/goBackend\";\nimport { nodeBackendVerifier } from \"./verifiers/nodeBackend\";\nimport { frontendVerifier } from \"./verifiers/frontend\";\nimport { iosVerifier, androidVerifier } from \"./verifiers/mobile\";\n\nexport const builtinVerifiers: Verifier[] = [\n goBackendVerifier,\n nodeBackendVerifier,\n frontendVerifier,\n iosVerifier,\n androidVerifier,\n];\n","import { readFile, writeFile, mkdir } from \"node:fs/promises\";\nimport { existsSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport type { ValidationIssue } from \"./validators\";\n\nexport type ForbiddenPattern = {\n id: string;\n pattern: RegExp;\n filePattern: RegExp;\n message: string;\n severity?: \"error\" | \"warning\";\n excludeFilePattern?: RegExp;\n // Optional file-level guard: if this regex matches the file's full content,\n // suppress the violation. Used for \"the pattern's intent is conditional on\n // surrounding context.\" Example: `Purchases.logLevel = .debug` is a violation\n // ONLY if the file doesn't wrap it in `#if DEBUG ... #endif`. Set\n // `suppressIfFileMatches` to a regex that detects the safe wrapping form.\n suppressIfFileMatches?: RegExp;\n};\n\nconst TEST_DIR_EXCLUSIONS = /(?:^|\\/)(?:test|tests|__tests__|spec|specs|androidTest)(?:\\/|$)/;\n\nexport const DEFAULT_FORBIDDEN_PATTERNS: ForbiddenPattern[] = [\n {\n id: \"android-http-logging-body\",\n pattern: /HttpLoggingInterceptor\\.Level\\.BODY\\b/,\n filePattern: /\\.kt$/,\n excludeFilePattern: TEST_DIR_EXCLUSIONS,\n message: \"HttpLoggingInterceptor.Level.BODY logs Bearer/refresh tokens to logcat. Use Level.NONE in production, or Level.BASIC gated behind BuildConfig.DEBUG.\",\n severity: \"error\",\n },\n {\n id: \"ios-google-signin-stub\",\n pattern: /\\/\\/\\s*(?:GoogleSignInButton|GoogleSignIn[A-Za-z]*\\(\\)|Uncomment\\s+when\\s+Google\\s+Sign[\\s-]?In)/i,\n filePattern: /LoginView\\.swift$/,\n message: \"Google Sign In button is commented out. Either implement fully via the GoogleSignIn SPM package, or omit the button entirely — do not leave a commented stub.\",\n severity: \"error\",\n },\n {\n id: \"ios-google-signin-todo-stub\",\n pattern: /\\/\\/\\s*TODO[^\\n]*Google\\s*Sign[\\s-]?In/i,\n filePattern: /\\.swift$/,\n excludeFilePattern: TEST_DIR_EXCLUSIONS,\n message: \"Google Sign In integration is TODO-stubbed. Implement fully via GoogleSignIn SPM, or remove the placeholder.\",\n severity: \"error\",\n },\n {\n id: \"android-missing-google-client-id-literal\",\n // Match every realistic placeholder shape we've seen ship: the fully-qualified\n // YOUR_WEB_CLIENT_ID.apps.googleusercontent.com, the bare YOUR_WEB_CLIENT_ID_HERE\n // sentinel that a prior audit caught in strings.xml, plus generic\n // YOUR_*_CLIENT_ID and *_CLIENT_ID_HERE shapes. Anchored so legitimate identifier\n // names like 'GOOGLE_CLIENT_ID' (no _HERE/_PLACEHOLDER suffix, used in real env\n // var docstrings) don't fire.\n pattern: /MISSING_GOOGLE_CLIENT_ID|YOUR_(?:WEB_|IOS_|ANDROID_)?CLIENT_ID(?:_HERE|_PLACEHOLDER|\\.apps\\.googleusercontent\\.com)|YOUR_WEB_CLIENT_ID_HERE/,\n filePattern: /(?:strings\\.xml|\\.kt|\\.java)$/,\n excludeFilePattern: TEST_DIR_EXCLUSIONS,\n message: \"Google Client ID is a literal placeholder (YOUR_*_CLIENT_ID_HERE or YOUR_*.apps.googleusercontent.com). Replace with the real ID from Google Cloud Console before shipping.\",\n severity: \"error\",\n },\n {\n id: \"stub-todo-in-auth-or-billing-route\",\n // Catches the 2026-05-01 audit finding: auth/3 backend shipped routes with\n // `// TODO: Send email via Brevo API` and returned success without delivering.\n // Pattern: any `// TODO` or `# TODO` comment inside backend route files for\n // auth/billing/email/payment paths. These stubs let the route succeed in CI\n // but fail silently in production. The route must either implement fully or\n // fail-closed (HTTP 500 + structured error code).\n pattern: /(?:\\/\\/|#)\\s*(?:TODO|FIXME|XXX)\\s*[:\\-]?\\s*(?:send|implement|wire|integrate|connect|add)\\s+(?:email|brevo|stripe|webhook|notification|sms|push|payment|charge|refund|otp|magic\\s*link)/i,\n filePattern: /(?:\\/api\\/(?:auth|billing|webhooks|payment|email|notifications)\\/|routes\\/(?:auth|billing|webhooks|payment|email|notifications)\\/).*\\.(?:ts|tsx|js|mjs|py|rb|go)$/i,\n excludeFilePattern: TEST_DIR_EXCLUSIONS,\n message: \"Stub TODO in a security-critical route handler (auth/billing/webhook/email/notifications). Either implement the call OR fail-closed with HTTP 500 + a structured error code (e.g. { error: \\\"EMAIL_NOT_CONFIGURED\\\" }). Routes that return success without doing the work cause silent production failures.\",\n severity: \"error\",\n },\n {\n id: \"android-paywall-empty-callback\",\n // 2026-05-01 audit: AppNavigation.kt shipped with\n // `onSubscribeClick = { /* RevenueCat integration placeholder */ }`. The\n // happy path worked because PaywallScreen called billing.purchase()\n // directly inline, but the fallback FallbackPricingCard route was silent.\n pattern: /onSubscribeClick\\s*=\\s*\\{\\s*(?:\\/\\*[^*]*(?:placeholder|TODO|FIXME|stub)[^*]*\\*\\/|\\/\\/[^\\n]*(?:placeholder|TODO|FIXME|stub)[^\\n]*)?\\s*\\}/i,\n filePattern: /\\.kt$/,\n excludeFilePattern: TEST_DIR_EXCLUSIONS,\n message: \"Empty / placeholder paywall callback in Kotlin. Fallback path must call billing.purchase() the same way the happy path does — silent fallback failures break premium when RevenueCat offerings can't load.\",\n severity: \"error\",\n },\n {\n id: \"ios-purchases-loglevel-debug\",\n // Caught in 2026-05-01 audit: RevenueCatManager.swift shipped with\n // `Purchases.logLevel = .debug` not gated behind #if DEBUG. The artifact\n // (SubscriptionManagerFull.swift) uses `.info` — agent didn't faithfully\n // reuse and substituted a louder default. Keep verbose RevenueCat logs\n // out of release builds.\n pattern: /\\bPurchases\\.logLevel\\s*=\\s*\\.(?:debug|verbose)\\b/,\n filePattern: /\\.swift$/,\n excludeFilePattern: TEST_DIR_EXCLUSIONS,\n // Suppress when the file already wraps the assignment in `#if DEBUG ... #endif`\n // with a release-build branch using .info or .error. Detected with two\n // independent file-level checks (#if DEBUG present + .debug + .info/.error\n // present + #endif). This avoids the false positive caught 2026-05-01 where\n // RevenueCatManager.swift was correctly wrapped but the gate still fired.\n suppressIfFileMatches: /#if\\s+DEBUG[\\s\\S]{0,200}?Purchases\\.logLevel\\s*=\\s*\\.(?:debug|verbose)[\\s\\S]{0,200}?#else[\\s\\S]{0,200}?Purchases\\.logLevel\\s*=\\s*\\.(?:info|error|warn)[\\s\\S]{0,200}?#endif/,\n message: \"Purchases.logLevel set to .debug or .verbose unconditionally. Wrap in `#if DEBUG ... #endif` so release builds use .info or .error. Verbose logs in production add console noise and on some SDK versions can leak sandbox-receipt blobs — treat as a release-build security issue.\",\n severity: \"error\",\n },\n {\n id: \"ios-rolled-own-rounded-rect\",\n // Catches `RoundedRectangle(cornerRadius:` in feature/screen files, which\n // signals the agent rolled its own card/button instead of using BrandedComponents.\n // Token files (Theme*, Colors*) and the BrandedComponents/ReusableComponents files\n // legitimately use it — those are excluded.\n pattern: /\\bRoundedRectangle\\s*\\(\\s*cornerRadius\\s*:/,\n filePattern: /(?:Feature|Screen|View|Paywall|Dashboard|Tab|Detail)\\.swift$/i,\n excludeFilePattern: /(?:BrandedComponents|ReusableComponents|Theme|Colors|Typography|ColorHex|StoreKit|RevenueCat|Tests?|Preview)\\.swift$/i,\n message: \"Feature screen contains `RoundedRectangle(cornerRadius:`. Use BrandedComponents (PrimaryCTAButton / BrandedHeroCard / StatTile / BrandedListRow / BrandedEmptyState) instead of rolling your own primitives. Brand consistency depends on every screen using the same component vocabulary.\",\n severity: \"warning\",\n },\n {\n id: \"android-rolled-own-card\",\n // Catches `Card(` Material 3 usage in feature/screen files (it bypasses\n // BrandedComponents). Allow ElevatedCard/OutlinedCard distinction explicitly\n // by matching only the bare `Card(` form.\n pattern: /(?<!\\w)Card\\s*\\(\\s*(?:modifier|content|onClick|colors|elevation|border|shape|enabled|interactionSource)/,\n filePattern: /(?:Screen|View|Composable|Paywall|Dashboard)\\.kt$/i,\n excludeFilePattern: /(?:BrandedComponents|Theme|ColorScheme|Typography|Tokens|Tests?|Preview)\\.kt$/i,\n message: \"Feature screen uses Material 3 `Card(...)` directly. Use BrandedComponents (BrandedHeroCard / StatTile / BrandedListRow / BrandedEmptyState) instead — they wrap Card with brand-correct surface/border/elevation tokens.\",\n severity: \"warning\",\n },\n {\n id: \"ios-todo-replace-pinned-hash\",\n // Caught in 2026-05-01 audit: SessionStore.swift had pinnedHashes containing\n // 'TODO-REPLACE-WITH-PRODUCTION-PINNED-HASH-1' literal strings while certificate\n // pinning was actively enforced — meant ALL API calls would be cancelled in\n // production. This pattern is broader than the iOS-Google-Sign-In one because\n // pinning failures are silent and only show up under live network use.\n pattern: /[\"']TODO[-_]?REPLACE[-_]?WITH[-_]?(?:PRODUCTION[-_]?)?PINNED[-_]?HASH[^\"']*[\"']/,\n filePattern: /\\.swift$/,\n excludeFilePattern: TEST_DIR_EXCLUSIONS,\n message: \"Certificate pinning hash is a TODO-REPLACE placeholder. With pinning enforced, every production API call will be cancelled. Either replace with the real SHA-256 hash or disable the pinning delegate before release.\",\n severity: \"error\",\n },\n {\n id: \"leaked-token-console-log\",\n pattern: /console\\.log\\([^)]*\\b(?:accessToken|refreshToken|password|bearer)\\b/i,\n filePattern: /\\.(?:ts|tsx|js|jsx)$/,\n excludeFilePattern: TEST_DIR_EXCLUSIONS,\n message: \"console.log includes a token/password. Strip secret fields before logging.\",\n severity: \"error\",\n },\n {\n id: \"react-dangerouslysetinnerhtml-without-sanitizer\",\n pattern: /dangerouslySetInnerHTML\\s*=\\s*\\{\\s*\\{\\s*__html\\s*:(?!\\s*(?:DOMPurify|sanitize|sanitizeHtml|purify))/,\n filePattern: /\\.(?:tsx|jsx)$/,\n excludeFilePattern: TEST_DIR_EXCLUSIONS,\n message: \"dangerouslySetInnerHTML used without a recognized sanitizer call. Wrap with DOMPurify/sanitize/sanitizeHtml or render the value as text.\",\n severity: \"error\",\n },\n {\n id: \"javascript-eval\",\n pattern: /(?:^|[^.\\w])eval\\s*\\(/,\n filePattern: /\\.(?:ts|tsx|js|jsx)$/,\n excludeFilePattern: TEST_DIR_EXCLUSIONS,\n message: \"eval() is a code-injection vector. Use JSON.parse, function references, or a safe interpreter instead.\",\n severity: \"error\",\n },\n {\n id: \"hardcoded-bearer-token\",\n pattern: /[\"']\\s*Bearer\\s+(?:eyJ|sk-|gho_|ghp_|ghs_|gha_|ghu_|xox[abops]-)/i,\n filePattern: /\\.(?:ts|tsx|js|jsx|swift|kt|java)$/,\n excludeFilePattern: TEST_DIR_EXCLUSIONS,\n message: \"Hardcoded Bearer token detected. Read from env / Keychain / EncryptedSharedPreferences instead.\",\n severity: \"error\",\n },\n {\n id: \"production-bind-all-interfaces\",\n pattern: /(?:host|address|listen|bind)\\s*[:=]\\s*['\"]0\\.0\\.0\\.0['\"]/,\n filePattern: /\\.(?:ts|tsx|js|jsx|json|ya?ml|conf|env)$/,\n excludeFilePattern: /(?:^|\\/)(?:test|tests|__tests__|spec|specs|androidTest|docker|Dockerfile)(?:\\/|$)|\\.local\\.|\\.example\\./,\n message: \"Binding to 0.0.0.0 in non-container code can expose services unintentionally. Use 127.0.0.1 (or environment-driven host) outside of explicit container/dev configs.\",\n severity: \"warning\",\n },\n {\n id: \"unsafe-json-parse-network-input\",\n pattern: /JSON\\.parse\\(\\s*await\\s+(?:response|res|fetch|r)\\.text\\(\\)\\s*\\)/,\n filePattern: /\\.(?:ts|tsx|js|jsx)$/,\n excludeFilePattern: TEST_DIR_EXCLUSIONS,\n message: \"JSON.parse on raw network text without try/catch will crash on malformed responses. Wrap in try/catch or use response.json() with a guard.\",\n severity: \"warning\",\n },\n {\n id: \"android-plain-shared-preferences-for-tokens\",\n pattern: /getSharedPreferences\\([^)]+\\)[\\s\\S]{0,400}?\\b(?:accessToken|refreshToken|authToken|jwt)\\b/i,\n filePattern: /\\.kt$/,\n excludeFilePattern: TEST_DIR_EXCLUSIONS,\n message: \"Storing tokens in plain SharedPreferences is unsafe. Use EncryptedSharedPreferences (androidx.security.crypto).\",\n severity: \"error\",\n },\n {\n id: \"backend-prisma-db-push-in-deploy\",\n pattern: /\\bprisma\\s+db\\s+push\\b/,\n filePattern: /(?:^|\\/)(?:Dockerfile|docker-compose\\.ya?ml|\\.github\\/workflows\\/.*\\.ya?ml)$/i,\n message: \"Use `prisma migrate deploy` (versioned migrations) in production, not `prisma db push`. The latter applies declarative diffs that can drop tables silently. Author migrations locally with `prisma migrate dev` and commit prisma/migrations/.\",\n severity: \"error\",\n },\n {\n id: \"backend-silent-db-failure-in-boot\",\n pattern: /\\bprisma\\s+(?:migrate\\s+deploy|db\\s+push|migrate\\s+resolve)\\b[^\\n]*\\|\\|\\s*true\\b/,\n filePattern: /(?:^|\\/)(?:Dockerfile|docker-compose\\.ya?ml|\\.github\\/workflows\\/.*\\.ya?ml|.*\\.sh)$/i,\n message: \"`|| true` after a Prisma migrate/push command silently swallows schema drift and produces a half-broken backend. Let the command fail loudly so the deploy is marked unhealthy.\",\n severity: \"error\",\n },\n {\n id: \"backend-db-bootstrap-redirected-to-tmp\",\n pattern: /\\bprisma\\s+(?:migrate\\s+deploy|db\\s+push)\\b[^\\n]*>\\s*\\/tmp\\/[^\\s]+\\b/,\n filePattern: /(?:^|\\/)(?:Dockerfile|docker-compose\\.ya?ml|.*\\.sh)$/i,\n message: \"Redirecting prisma output to /tmp hides failures from Azure App Service log streams. Stream to stdout/stderr so failures show up in the platform logs.\",\n severity: \"warning\",\n },\n {\n id: \"backend-from-email-rfc822-passed-to-provider\",\n pattern: /(?:from|sender)\\s*:\\s*\\{[^}]*email\\s*:\\s*(?:fromEmail|process\\.env\\.FROM_EMAIL)[^}]*\\}/,\n filePattern: /\\.(?:ts|tsx|js|mjs)$/,\n excludeFilePattern: TEST_DIR_EXCLUSIONS,\n message: \"Brevo/Sendgrid/Mailgun reject sender.email when it contains an RFC-822 display-name wrapper (e.g. \\\"Name <a@b.com>\\\"). Parse FROM_EMAIL into name + email before sending. See lib/email.ts parser pattern.\",\n severity: \"error\",\n },\n {\n id: \"backend-prisma-postinstall-without-schema\",\n // Positive match for the broken order: `RUN npm ci` line followed somewhere\n // later in the file by `COPY ... prisma`. If that pairing exists, the\n // postinstall hook (prisma generate) runs before the schema is on disk.\n pattern: /^[^\\n]*RUN\\s+npm\\s+(?:ci|install)\\b[\\s\\S]*?\\bCOPY\\s+(?:[^\\n]*\\s)?prisma\\b/m,\n filePattern: /(?:^|\\/)Dockerfile$/i,\n message: \"Dockerfile runs `npm ci/install` (which triggers `postinstall: prisma generate`) before `COPY prisma/`. The schema won't exist yet — generate fails. Move `COPY prisma ./prisma/` BEFORE `npm ci`.\",\n severity: \"error\",\n },\n];\n\ntype ForbiddenPatternConfig = {\n patterns?: Array<{\n id: string;\n pattern: string;\n flags?: string;\n filePattern: string;\n filePatternFlags?: string;\n excludeFilePattern?: string;\n excludeFilePatternFlags?: string;\n message: string;\n severity?: \"error\" | \"warning\";\n }>;\n};\n\nasync function loadProjectForbiddenPatterns(workspace: string): Promise<ForbiddenPattern[]> {\n const candidate = join(workspace, \".tania\", \"forbidden-patterns.json\");\n if (!existsSync(candidate)) return [];\n try {\n const raw = await readFile(candidate, \"utf8\");\n const parsed = JSON.parse(raw) as ForbiddenPatternConfig;\n return (parsed.patterns ?? []).map((p) => ({\n id: p.id,\n pattern: new RegExp(p.pattern, p.flags),\n filePattern: new RegExp(p.filePattern, p.filePatternFlags),\n ...(p.excludeFilePattern ? { excludeFilePattern: new RegExp(p.excludeFilePattern, p.excludeFilePatternFlags) } : {}),\n message: p.message,\n ...(p.severity ? { severity: p.severity } : {}),\n }));\n } catch {\n return [];\n }\n}\n\nexport async function scanForbiddenPatterns(\n workspace: string,\n changedFiles: string[],\n patterns?: ForbiddenPattern[],\n): Promise<ValidationIssue[]> {\n const projectPatterns = await loadProjectForbiddenPatterns(workspace);\n const effective = patterns ?? [...DEFAULT_FORBIDDEN_PATTERNS, ...projectPatterns];\n const issues: ValidationIssue[] = [];\n const fireCounts = new Map<string, number>();\n for (const file of changedFiles) {\n const matchingPatterns = effective.filter((p) => p.filePattern.test(file) && !(p.excludeFilePattern && p.excludeFilePattern.test(file)));\n if (matchingPatterns.length === 0) continue;\n let content: string;\n try {\n content = await readFile(join(workspace, file), \"utf8\");\n } catch {\n continue;\n }\n for (const pattern of matchingPatterns) {\n if (pattern.pattern.test(content)) {\n // File-level suppression: if pattern.suppressIfFileMatches matches the\n // full file content, the violation is contextually wrapped (e.g.\n // `.debug` inside `#if DEBUG ... #endif`) and not actionable.\n if (pattern.suppressIfFileMatches && pattern.suppressIfFileMatches.test(content)) continue;\n issues.push({\n id: pattern.id,\n severity: pattern.severity ?? \"error\",\n message: `${pattern.message} (in ${file})`,\n files: [file],\n });\n fireCounts.set(pattern.id, (fireCounts.get(pattern.id) ?? 0) + 1);\n }\n }\n }\n if (fireCounts.size > 0) {\n await recordFireMetrics(workspace, fireCounts);\n }\n return issues;\n}\n\ntype FireMetricsFile = {\n totals: Record<string, number>;\n lastFiredAt: Record<string, string>;\n totalScans?: number;\n};\n\nasync function recordFireMetrics(workspace: string, fireCounts: Map<string, number>): Promise<void> {\n try {\n const metricsDir = join(workspace, \".tania\", \"memory\");\n const metricsPath = join(metricsDir, \"forbidden-patterns-metrics.json\");\n let existing: FireMetricsFile = { totals: {}, lastFiredAt: {} };\n if (existsSync(metricsPath)) {\n try {\n const raw = await readFile(metricsPath, \"utf8\");\n const parsed = JSON.parse(raw);\n if (parsed && typeof parsed === \"object\") {\n existing = {\n totals: (parsed.totals && typeof parsed.totals === \"object\") ? parsed.totals : {},\n lastFiredAt: (parsed.lastFiredAt && typeof parsed.lastFiredAt === \"object\") ? parsed.lastFiredAt : {},\n totalScans: typeof parsed.totalScans === \"number\" ? parsed.totalScans : 0,\n };\n }\n } catch {\n // Corrupt metrics file should not block writes; reset.\n }\n }\n const now = new Date().toISOString();\n for (const [patternId, count] of fireCounts) {\n existing.totals[patternId] = (existing.totals[patternId] ?? 0) + count;\n existing.lastFiredAt[patternId] = now;\n }\n existing.totalScans = (existing.totalScans ?? 0) + 1;\n await mkdir(metricsDir, { recursive: true });\n await writeFile(metricsPath, JSON.stringify(existing, null, 2), \"utf8\");\n } catch {\n // Metrics are best-effort; never fail the gate because of metrics IO.\n }\n}\n","import { readdir, readFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport type { TanyaRunContext } from \"../../context/runContext\";\nimport { loadValidatorRules } from \"./rules/load\";\nimport type {\n BackendSetupEnvironmentRule,\n ValidatorRuleIssue,\n ValidatorRulePattern,\n} from \"./rules/types\";\n\nexport type ValidationIssue = {\n id: string;\n severity: \"error\" | \"warning\";\n message: string;\n files?: string[];\n};\n\nexport type ValidationSummary = {\n passed: boolean;\n issues: ValidationIssue[];\n firedValidatorIds?: string[];\n primaryPlatform?: \"ios\" | \"macos\" | \"android\" | \"backend\" | \"landing\" | \"web\" | \"script\" | \"unknown\";\n};\n\nexport type ValidationManifest = {\n changedFiles: string[];\n artifactsRead?: string[];\n artifactsCreated?: string[];\n contextFilesRead?: string[];\n verification?: string[];\n blockers?: string[];\n git?: {\n root: string | null;\n head: string | null;\n };\n};\n\nexport type Validator = {\n id: string;\n run(workspace: string, manifest: ValidationManifest, runContext?: TanyaRunContext): Promise<ValidationIssue[]> | ValidationIssue[];\n};\n\nexport function taskText(runContext?: TanyaRunContext): string {\n return [\n runContext?.task?.title,\n runContext?.task?.summary,\n ...(runContext?.instructions ?? []),\n ].filter(Boolean).join(\"\\n\").toLowerCase();\n}\n\nexport function constraintText(runContext?: TanyaRunContext): string {\n const rawPrompt = runContext?.metadata?.validationPrompt;\n return [\n taskText(runContext),\n typeof rawPrompt === \"string\" ? rawPrompt : null,\n ].filter(Boolean).join(\"\\n\").toLowerCase();\n}\n\nfunction metadataArray(runContext: TanyaRunContext | undefined, key: string): string[] {\n const value = runContext?.metadata?.[key];\n if (!Array.isArray(value)) return [];\n return value.filter((item): item is string => typeof item === \"string\" && item.trim().length > 0);\n}\n\nfunction metadataBoolean(runContext: TanyaRunContext | undefined, key: string): boolean {\n const value = runContext?.metadata?.[key];\n return value === true || value === \"true\" || value === \"yes\";\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === \"object\" && !Array.isArray(value);\n}\n\nfunction metadataRecord(runContext: TanyaRunContext | undefined, key: string): Record<string, unknown> | undefined {\n const value = runContext?.metadata?.[key];\n return isRecord(value) ? value : undefined;\n}\n\nfunction recordArray(value: unknown): Record<string, unknown>[] {\n return Array.isArray(value) ? value.filter(isRecord) : [];\n}\n\nfunction autoBriefRecords(runContext: TanyaRunContext | undefined, key: string): Record<string, unknown>[] {\n return recordArray(metadataRecord(runContext, \"autoBrief\")?.[key]);\n}\n\nfunction hasExpectedReportFlag(runContext: TanyaRunContext | undefined, key: string): boolean {\n return runContext?.expected_report?.[key] === true;\n}\n\nexport function uniqueSorted(values: Iterable<string>): string[] {\n return [...new Set([...values].filter(Boolean))].sort();\n}\n\nexport function hasChanged(manifest: ValidationManifest, pattern: RegExp): boolean {\n return manifest.changedFiles.some((file) => pattern.test(file));\n}\n\nexport function changedMatching(manifest: ValidationManifest, pattern: RegExp): string[] {\n return manifest.changedFiles.filter((file) => pattern.test(file));\n}\n\nexport function hasSuccessfulVerification(manifest: ValidationManifest, pattern: RegExp): boolean {\n return (manifest.verification ?? []).some((line) =>\n pattern.test(line) &&\n /(?:->\\s*passed|\\bpassed\\b|success marker found|shell exited 0|build succeeded)/i.test(line) &&\n !/->\\s*failed\\b/i.test(line)\n );\n}\n\nfunction hasSuccessfulCodegenVerification(manifest: ValidationManifest): boolean {\n return hasSuccessfulVerification(\n manifest,\n /\\b(?:sqlc\\s+generate|go\\s+generate|buf\\s+generate|protoc\\b|prisma\\s+generate|graphql-codegen|openapi-generator|swiftgen|xcodegen|make(?:\\s+-C\\s+\\S+)?\\s+gen)\\b/i,\n );\n}\n\nfunction isGeneratedCodeHeader(text: string): boolean {\n return /\\bCode generated by\\b[\\s\\S]{0,300}\\bDO NOT EDIT\\b/i.test(text.slice(0, 2000));\n}\n\nasync function validateGeneratedCodeProvenance(workspace: string, manifest: ValidationManifest): Promise<ValidationIssue[]> {\n if (hasSuccessfulCodegenVerification(manifest)) return [];\n const generatedFiles: string[] = [];\n for (const file of manifest.changedFiles) {\n const content = await readWorkspaceFile(workspace, file);\n if (content && isGeneratedCodeHeader(content)) generatedFiles.push(file);\n }\n if (generatedFiles.length === 0) return [];\n return [{\n id: \"core-generated-code-without-generator-verification\",\n severity: \"error\",\n message: \"Changed files claim to be generated code, but no successful generator command was reported. Run the generator or remove the generated-code header; do not hand-write generated output.\",\n files: generatedFiles.slice(0, 10),\n }];\n}\n\nexport function isAppIconTask(text: string): boolean {\n return /\\b(?:app icon|icon generation|launcher icon)\\b/i.test(text) ||\n /\\b(?:icone|ícone)\\s+(?:do\\s+)?app\\b/i.test(text) ||\n /\\bappicon\\.appiconset\\b/i.test(text) ||\n /\\bic_launcher\\b/i.test(text);\n}\n\nexport function isApplePlatformTask(text: string): boolean {\n return /\\b(?:ios|macos|apple|xcode|xcodebuild)\\b/i.test(text) ||\n /\\bappicon\\.appiconset\\b/i.test(text) ||\n /\\bassets\\.xcassets\\b/i.test(text);\n}\n\nexport function isAndroidPlatformTask(text: string): boolean {\n return /\\bandroid\\b/i.test(text) ||\n /\\bic_launcher\\b/i.test(text) ||\n /\\bmipmap\\b/i.test(text);\n}\n\nfunction normalizeSearchText(text: string): string {\n return text\n .normalize(\"NFD\")\n .replace(/[\\u0300-\\u036f]/g, \"\")\n .toLowerCase();\n}\n\ntype PromptFeature = {\n name: string;\n tier: \"free\" | \"premium\" | \"unknown\";\n};\n\nexport function extractPromptFeatures(text: string): PromptFeature[] {\n const features: PromptFeature[] = [];\n const seen = new Set<string>();\n for (const line of text.split(/\\r?\\n/)) {\n const match = line.match(/^\\s*[-*]\\s+\\*\\*(.+?)\\*\\*[\\s\\S]*?\\[(premium|free)\\]/i);\n if (!match) continue;\n const name = match[1]?.replace(/:\\s*$/, \"\").trim();\n if (!name) continue;\n const key = normalizeSearchText(name);\n if (seen.has(key)) continue;\n seen.add(key);\n features.push({ name, tier: (match[2]?.toLowerCase() === \"premium\" ? \"premium\" : \"free\") });\n }\n return features;\n}\n\nfunction containsAny(haystack: string, words: string[]): boolean {\n return words.some((word) => {\n const normalized = normalizeSearchText(word);\n if (!normalized) return false;\n const escaped = normalized.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n const pattern = new RegExp(`(?:^|[^a-z0-9])${escaped}`);\n return pattern.test(haystack);\n });\n}\n\nexport function featureCoveredByText(feature: PromptFeature, implementationText: string): boolean {\n const name = normalizeSearchText(feature.name);\n const text = normalizeSearchText(implementationText);\n if (name.includes(\"perfi\") && name.includes(\"juiz\")) {\n return containsAny(text, [\"perfil\", \"profile\"]) &&\n containsAny(text, [\"juiz\", \"juizes\", \"judge\", \"judges\"]) &&\n containsAny(text, [\"metrica\", \"metric\", \"performance\"]);\n }\n if (name.includes(\"busca\") || name.includes(\"jurisprudencia\")) {\n return containsAny(text, [\"busca\", \"search\"]) &&\n containsAny(text, [\"jurisprudencia\", \"decision\", \"decisao\", \"case\", \"cases\", \"juiz\", \"judge\"]);\n }\n if (name.includes(\"alerta\")) {\n return containsAny(text, [\"alerta\", \"alert\", \"alerts\", \"notificacao\", \"notification\"]);\n }\n if (name.includes(\"favorit\") || name.includes(\"organiz\")) {\n return containsAny(text, [\"favorito\", \"favoritos\", \"favorite\", \"favorites\", \"organizacao\", \"organize\"]);\n }\n if (name.includes(\"painel\") || name.includes(\"dashboard\")) {\n return containsAny(text, [\"painel\", \"dashboard\", \"overview\", \"visao geral\"]);\n }\n const meaningfulWords = name\n .split(/[^a-z0-9]+/i)\n .filter((word) => word.length >= 5 && ![\"feature\", \"modulo\", \"modulos\", \"sistema\"].includes(word));\n if (meaningfulWords.length === 0) return true;\n return meaningfulWords.some((word) => containsAny(text, [word]));\n}\n\nexport async function readWorkspaceFile(workspace: string, filePath: string): Promise<string | null> {\n try {\n return await readFile(join(workspace, filePath), \"utf8\");\n } catch {\n return null;\n }\n}\n\nexport async function workspaceFileExists(workspace: string, filePath: string): Promise<boolean> {\n return (await readWorkspaceFile(workspace, filePath)) !== null;\n}\n\nexport async function findWorkspaceFiles(\n workspace: string,\n predicate: (filePath: string) => boolean,\n options: { roots?: string[]; limit?: number } = {},\n): Promise<string[]> {\n const roots = options.roots?.length ? options.roots : [\".\"];\n const limit = options.limit ?? 200;\n const results: string[] = [];\n const ignored = new Set([\".git\", \".gradle\", \".tania\", \"build\", \"DerivedData\", \"node_modules\"]);\n\n async function walk(relativeDir: string) {\n if (results.length >= limit) return;\n let entries: Array<{ name: string; isDirectory(): boolean; isFile(): boolean }>;\n try {\n entries = await readdir(join(workspace, relativeDir), { withFileTypes: true });\n } catch {\n return;\n }\n for (const entry of entries) {\n if (results.length >= limit) return;\n const relativePath = relativeDir === \".\" ? entry.name : `${relativeDir}/${entry.name}`;\n if (entry.isDirectory()) {\n if (!ignored.has(entry.name)) await walk(relativePath);\n continue;\n }\n if (entry.isFile() && predicate(relativePath)) results.push(relativePath);\n }\n }\n\n for (const root of roots) await walk(root.replace(/\\/$/, \"\") || \".\");\n return results;\n}\n\nfunction pathMatchesPattern(filePath: string, pattern: string): boolean {\n const normalizedPattern = pattern.replace(/\\\\/g, \"/\");\n if (normalizedPattern.endsWith(\"/**\")) {\n return filePath === normalizedPattern.slice(0, -3) || filePath.startsWith(normalizedPattern.slice(0, -2));\n }\n if (normalizedPattern.startsWith(\"**/*.\")) {\n return filePath.endsWith(normalizedPattern.slice(4));\n }\n if (normalizedPattern.includes(\"*\")) {\n const escaped = normalizedPattern\n .replace(/[.+?^${}()|[\\]\\\\]/g, \"\\\\$&\")\n .replace(/\\*\\*/g, \".*\")\n .replace(/\\*/g, \"[^/]*\");\n return new RegExp(`^${escaped}$`).test(filePath);\n }\n return filePath === normalizedPattern || filePath.startsWith(`${normalizedPattern.replace(/\\/$/, \"\")}/`);\n}\n\nfunction isForbiddenFile(filePath: string): boolean {\n const base = filePath.split(\"/\").pop() ?? filePath;\n return base === \"local.properties\" ||\n /^\\.env(?:\\.|$)/.test(base) && base !== \".env.example\" ||\n /\\.(?:orig|bak|backup|tmp)$/i.test(base) ||\n filePath.includes(\"/.tania/\") ||\n filePath.startsWith(\".tania/\");\n}\n\nfunction isTextFile(filePath: string): boolean {\n return /\\.(?:ts|tsx|js|jsx|mjs|cjs|json|md|swift|kt|kts|gradle|rb|yml|yaml|xml|txt|env|example|properties|prisma)$/i.test(filePath);\n}\n\nexport function isExplicitPlaceholderText(text: string): boolean {\n return /(?:\\bexample\\b|\\bplaceholder\\b|\\bchange[\\s_-]*me\\b|\\breplace[\\s_-]*me\\b|\\bchangeme\\b|\\breplaceme\\b|\\byour[\\s_-]+[a-z0-9_-]+|(?:^|[^a-z0-9])(?:REPLACE|CHANGE)_+[A-Z0-9_]+|xxxx|dummy|test[_-]?only|<[^>]+>)/i.test(text);\n}\n\nfunction escapeRegExp(value: string): string {\n return value.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n\nfunction issueFromRule(issue: ValidatorRuleIssue): ValidationIssue {\n return {\n id: issue.id,\n severity: issue.severity,\n message: issue.message,\n ...(issue.files ? { files: issue.files } : {}),\n };\n}\n\nfunction rulePatternMatches(text: string, pattern: ValidatorRulePattern): boolean {\n try {\n return new RegExp(pattern.pattern, pattern.flags).test(text);\n } catch {\n return false;\n }\n}\n\nfunction envValue(env: string, key: string): string {\n const match = env.match(new RegExp(`^${escapeRegExp(key)}\\\\s*=\\\\s*[\"']?([^\"'\\\\n#]+)`, \"m\"));\n return match?.[1]?.trim() ?? \"\";\n}\n\nasync function docTextForRule(\n workspace: string,\n rule: BackendSetupEnvironmentRule,\n fileCache: Map<string, string | null>,\n): Promise<string> {\n const files = rule.docsFiles?.length ? rule.docsFiles : [rule.envFile ?? \".env.example\"];\n const contents = await Promise.all(files.map(async (file) => {\n if (!fileCache.has(file)) fileCache.set(file, await readWorkspaceFile(workspace, file));\n return fileCache.get(file) ?? \"\";\n }));\n return contents.join(\"\\n\");\n}\n\nasync function validateBackendSetupEnvironmentRule(\n workspace: string,\n rule: BackendSetupEnvironmentRule,\n fileCache: Map<string, string | null>,\n): Promise<ValidationIssue[]> {\n const issues: ValidationIssue[] = [];\n const envFile = rule.envFile ?? \".env.example\";\n if (!fileCache.has(envFile)) fileCache.set(envFile, await readWorkspaceFile(workspace, envFile));\n const env = fileCache.get(envFile);\n if (env == null) return issues;\n\n for (const requirement of rule.requiredEnv ?? []) {\n const value = envValue(env, requirement.name);\n if (!value) {\n issues.push(issueFromRule(requirement.missingIssue));\n continue;\n }\n for (const forbidden of requirement.forbiddenValues ?? []) {\n if (rulePatternMatches(value, forbidden)) {\n issues.push(issueFromRule(forbidden));\n }\n }\n const placeholder = requirement.placeholder;\n if (placeholder) {\n const explicitPlaceholderOk = placeholder.acceptedExplicitPlaceholder !== false && isExplicitPlaceholderText(value);\n const allowedPatternOk = (placeholder.allowedPatterns ?? []).some((pattern) => rulePatternMatches(value, pattern));\n if (!explicitPlaceholderOk && !allowedPatternOk) {\n issues.push(issueFromRule(placeholder.unclearIssue));\n }\n }\n }\n\n const docs = await docTextForRule(workspace, rule, fileCache);\n for (const requirement of rule.documentation ?? []) {\n const allMatched = (requirement.all ?? []).every((pattern) => rulePatternMatches(docs, pattern));\n const anyMatched = (requirement.any ?? []).length === 0 ||\n (requirement.any ?? []).some((pattern) => rulePatternMatches(docs, pattern));\n if (!allMatched || !anyMatched) {\n issues.push(issueFromRule(requirement.issue));\n }\n }\n\n return issues;\n}\n\nfunction looksLikeSecretLine(line: string): boolean {\n const match = line.match(/\\b[A-Za-z0-9_-]*(?:api[_-]?key|secret|token|password|private[_-]?key|client[_-]?secret|database_url)[A-Za-z0-9_-]*\\b\\s*[:=]\\s*[\"']?([^\"',}\\s]+)/i);\n if (!match) return false;\n const value = match[1] ?? \"\";\n if (isExplicitPlaceholderText(value)) return false;\n if (/^(?:process\\.env\\.|state\\.|data\\.|[\\w$]+\\.)/.test(value)) return false;\n // Pure-letters bare identifier (camelCase variable reference) — almost\n // always a code symbol, not a literal secret. Real secrets contain digits OR\n // underscores OR other separators (Stripe `sk_live_...`, AWS `AKIA...`, JWT `.`).\n // 2026-05-01 Cosa Nostra audit: `val pendingToken = pendingGoogleIdToken` tripped\n // this rule because pendingGoogleIdToken is 22 chars alnum.\n if (/^[A-Za-z_$][A-Za-z]*$/.test(value)) return false;\n return /^[A-Za-z0-9_./+=-]{16,}$/.test(value);\n}\n\nfunction commandKey(command: string): string {\n return command\n .replace(/^Verification:\\s*/i, \"\")\n .replace(/\\s*->.*$/, \"\")\n .replace(/\\s+/g, \" \")\n .trim();\n}\n\nfunction capturedSatisfiesRequested(captured: string[], requested: string): boolean {\n const normalizedRequested = requested.trim().replace(/\\s+/g, \" \");\n if (captured.includes(normalizedRequested)) return true;\n const escaped = normalizedRequested.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n const pattern = new RegExp(`(?:^|[\\\\s;|&])${escaped}(?=$|[\\\\s;|&]|2>&1|>>?\\\\s|<\\\\s)`, \"i\");\n return captured.some((line) => pattern.test(line));\n}\n\nfunction isExactRequiredVerificationCommand(command: string): boolean {\n return /^(?:npm|pnpm|yarn|bun)\\s+(?:install|ci|test|run\\s+[\\w:-]+)\\b/i.test(command) ||\n /^npx\\s+[\\w@./:-]+/i.test(command) ||\n /^\\.\\/gradlew\\s+[\\w:-]+/i.test(command) ||\n /^xcodebuild\\s+(?:build|test|archive|-list)\\b/i.test(command);\n}\n\nfunction exactVerificationCommandsRequired(runContext: TanyaRunContext | undefined): boolean {\n if (metadataBoolean(runContext, \"exactVerificationCommands\") || metadataBoolean(runContext, \"strictVerificationCommands\")) {\n return true;\n }\n return runContext?.metadata?.caller !== \"cosmochat\";\n}\n\nexport const coreValidators: Validator[] = [\n {\n id: \"core.scope.forbiddenFiles\",\n run(_workspace, manifest) {\n return manifest.changedFiles\n .filter(isForbiddenFile)\n .map((file) => ({\n id: \"core-scope-forbidden-file\",\n severity: \"error\",\n message: `Changed forbidden or generated file: ${file}`,\n files: [file],\n }));\n },\n },\n {\n id: \"core.generatedCode.provenance\",\n run(workspace, manifest) {\n return validateGeneratedCodeProvenance(workspace, manifest);\n },\n },\n {\n id: \"core.scope.allowedPaths\",\n run(_workspace, manifest, runContext) {\n const allowedPaths = metadataArray(runContext, \"allowedPaths\");\n if (allowedPaths.length === 0) return [];\n return manifest.changedFiles\n .filter((file) => !allowedPaths.some((pattern) => pathMatchesPattern(file, pattern)))\n .map((file) => ({\n id: \"core-scope-outside-allowed-paths\",\n severity: \"error\",\n message: `Changed file outside configured allowed paths: ${file}`,\n files: [file],\n }));\n },\n },\n {\n id: \"core.artifact.provenance\",\n run(_workspace, manifest, runContext) {\n if (!hasExpectedReportFlag(runContext, \"artifact_reuse\")) return [];\n const availableArtifacts = runContext?.artifacts?.filter((artifact) => artifact.status !== \"missing\") ?? [];\n if (availableArtifacts.length === 0) return [];\n if ((manifest.artifactsRead ?? []).length > 0 || (manifest.artifactsCreated ?? []).length > 0) return [];\n return [{\n id: \"core-artifact-provenance-missing\",\n severity: \"error\",\n message: \"Caller supplied artifacts and required artifact provenance, but no artifact was read or created.\",\n }];\n },\n },\n {\n id: \"core.autoBrief.artifactConsideration\",\n run(_workspace, manifest, runContext) {\n if (!metadataBoolean(runContext, \"autoBriefEnforceArtifacts\")) return [];\n if (manifest.changedFiles.length === 0) return [];\n if (autoBriefRecords(runContext, \"artifacts\").length === 0) return [];\n if ((manifest.artifactsRead ?? []).length > 0 || (manifest.artifactsCreated ?? []).length > 0) return [];\n return [{\n id: \"core-auto-brief-artifact-not-considered\",\n severity: \"error\",\n message: \"Automatic task brief found reusable artifact candidates, but no artifact was read or created before changing files.\",\n }];\n },\n },\n {\n id: \"core.context.review\",\n run(_workspace, manifest, runContext) {\n const hasContextToReview = hasExpectedReportFlag(runContext, \"context_review\") ||\n autoBriefRecords(runContext, \"contextFiles\").length > 0 ||\n (runContext?.contextFiles ?? []).length > 0;\n if (!hasContextToReview) return [];\n if (manifest.changedFiles.length === 0) return [];\n if ((manifest.contextFilesRead ?? []).length > 0) return [];\n return [{\n id: \"core-context-review-missing\",\n severity: \"warning\",\n message: \"Automatic task brief found context files, but none were read before changing files.\",\n }];\n },\n },\n {\n id: \"core.verification.executed\",\n run(_workspace, manifest, runContext) {\n if (!hasExpectedReportFlag(runContext, \"verification\")) return [];\n const verification = manifest.verification ?? [];\n if (verification.length === 0) {\n return [{ id: \"core-verification-missing\", severity: \"error\", message: \"Expected verification, but no verification command was captured.\" }];\n }\n const requested = runContext?.verification?.commands ?? [];\n const passedKeys = verification\n .filter((line) => /->\\s*passed\\b/i.test(line))\n .map(commandKey);\n const strictRequestedCommands = exactVerificationCommandsRequired(runContext);\n return requested\n .filter((command) => !capturedSatisfiesRequested(passedKeys, command))\n .map((command) => ({\n id: \"core-verification-requested-command-missing\",\n severity: strictRequestedCommands && isExactRequiredVerificationCommand(command) ? \"error\" : \"warning\",\n message: `Requested verification command was not captured exactly: ${command}`,\n }));\n },\n },\n {\n id: \"core.git.commit\",\n run(_workspace, manifest, runContext) {\n if (!metadataBoolean(runContext, \"requireCommit\") && !hasExpectedReportFlag(runContext, \"commit\")) return [];\n if (manifest.changedFiles.length === 0) return [];\n if (manifest.git?.head) return [];\n return [{ id: \"core-git-commit-missing\", severity: \"error\", message: \"A commit was required, but no git HEAD was captured.\" }];\n },\n },\n {\n id: \"core.secrets.noLeak\",\n async run(workspace, manifest) {\n const issues: ValidationIssue[] = [];\n for (const file of manifest.changedFiles.filter(isTextFile)) {\n const content = await readWorkspaceFile(workspace, file);\n if (!content) continue;\n const lineNumber = content.split(/\\r?\\n/).findIndex(looksLikeSecretLine);\n if (lineNumber >= 0) {\n issues.push({\n id: \"core-secrets-possible-leak\",\n severity: \"error\",\n message: `Possible hardcoded secret in ${file}:${lineNumber + 1}`,\n files: [file],\n });\n }\n }\n return issues;\n },\n },\n];\n\nexport function looksLikeCtaTitle(value: string): boolean {\n return /\\b(?:começar|comecar|comece|começo|comeco|pronto|vamos|conta|grátis|gratis|cta|iniciar|start|get started|unlock|desbloquear)\\b/i.test(value);\n}\n\nexport function hasDedicatedCtaSlide(content: string, platform: \"ios\" | \"android\"): boolean {\n if (/\\b(?:isCta|isCTA|cta|finalSlide|FinalSlide|OnboardingCta|CTA)\\b/.test(content)) return true;\n const titles = platform === \"ios\"\n ? [...content.matchAll(/title:\\s*\"([^\"]+)\"/g)].map((match) => match[1] ?? \"\")\n : [...content.matchAll(/title\\s*=\\s*\"([^\"]+)\"/g)].map((match) => match[1] ?? \"\");\n if (titles.length === 0) return /\\bComeçar grátis\\b[\\s\\S]*\\bJá tenho conta\\b/.test(content);\n const lastTitle = titles[titles.length - 1] ?? \"\";\n return looksLikeCtaTitle(lastTitle);\n}\n\nexport async function validateSetupEnvironment(workspace: string, manifest: ValidationManifest, runContext?: TanyaRunContext): Promise<ValidationIssue[]> {\n const issues: ValidationIssue[] = [];\n const text = taskText(runContext);\n if (/\\bios\\b/.test(text)) {\n const fastlaneFiles = changedMatching(manifest, /(?:^|\\/)fastlane\\/Fastfile$/);\n const swiftLintFiles = changedMatching(manifest, /(?:^|\\/)\\.swiftlint\\.yml$/);\n if (fastlaneFiles.length === 0) {\n issues.push({ id: \"setup-ios-fastlane-missing\", severity: \"error\", message: \"iOS setup must create or update fastlane/Fastfile.\" });\n }\n if (swiftLintFiles.length === 0) {\n issues.push({ id: \"setup-ios-swiftlint-missing\", severity: \"error\", message: \"iOS setup must create or update .swiftlint.yml.\" });\n }\n for (const file of fastlaneFiles) {\n const content = await readWorkspaceFile(workspace, file);\n if (content && !/\\blane\\s+:build\\b/.test(content)) {\n issues.push({ id: \"setup-ios-fastlane-build-lane-missing\", severity: \"error\", message: \"Fastfile must define a build lane.\", files: [file] });\n }\n }\n }\n if (/\\bandroid\\b/.test(text)) {\n const gradleFiles = changedMatching(manifest, /(?:^|\\/)(?:build\\.gradle\\.kts|build\\.gradle|libs\\.versions\\.toml|settings\\.gradle\\.kts)$/);\n if (gradleFiles.length === 0) {\n issues.push({ id: \"setup-android-gradle-missing\", severity: \"error\", message: \"Android setup must update Gradle project configuration.\" });\n }\n for (const file of gradleFiles) {\n const content = await readWorkspaceFile(workspace, file);\n if (content && /compileSdk\\s*(?:=|\\()\\s*(\\d+)/.test(content)) {\n const compileSdk = Number(content.match(/compileSdk\\s*(?:=|\\()\\s*(\\d+)/)?.[1]);\n if (compileSdk < 35) issues.push({ id: \"setup-android-compile-sdk-low\", severity: \"error\", message: \"compileSdk must be at least 35.\", files: [file] });\n }\n }\n }\n return issues;\n}\n\nexport async function validateApiClient(workspace: string, manifest: ValidationManifest): Promise<ValidationIssue[]> {\n const issues: ValidationIssue[] = [];\n const clientFiles = changedMatching(manifest, /(?:ApiClient|APIClient|ApiRepository|APIRepository|Repository).*\\.(?:swift|kt|ts)$/);\n if (clientFiles.length === 0) {\n return [{ id: \"api-client-files-missing\", severity: \"error\", message: \"API client/repository task did not modify a recognizable client or repository file.\" }];\n }\n for (const file of clientFiles) {\n const content = await readWorkspaceFile(workspace, file);\n if (!content) continue;\n if (!/\\bhttps?:\\/\\/|baseURL|baseUrl|BASE_URL|URLSession|OkHttp|Retrofit|fetch\\(/.test(content)) {\n issues.push({ id: \"api-client-base-url-missing\", severity: \"warning\", message: \"Could not confirm base URL or HTTP client wiring.\", files: [file] });\n }\n if (!/\\basync\\b|suspend\\s+fun|URLSession|OkHttp|Retrofit|fetch\\(/.test(content)) {\n issues.push({ id: \"api-client-async-flow-missing\", severity: \"warning\", message: \"Could not confirm async API call handling.\", files: [file] });\n }\n }\n return issues;\n}\n\nexport async function validateAuthSession(workspace: string, manifest: ValidationManifest): Promise<ValidationIssue[]> {\n const issues: ValidationIssue[] = [];\n const authFiles = changedMatching(manifest, /(?:Auth|Session|Token|Keychain|SecureStorage|DataStore).*\\.(?:swift|kt|ts)$/);\n if (authFiles.length === 0) {\n return [{ id: \"auth-session-files-missing\", severity: \"error\", message: \"Auth/session task did not modify a recognizable auth, session, token, or secure storage file.\" }];\n }\n for (const file of authFiles) {\n const content = await readWorkspaceFile(workspace, file);\n if (!content) continue;\n if (/UserDefaults|SharedPreferences/.test(content) && !/Keychain|EncryptedSharedPreferences|DataStore|Secure/i.test(content)) {\n issues.push({ id: \"auth-session-insecure-storage\", severity: \"error\", message: \"Auth tokens must not be stored in plain UserDefaults or SharedPreferences.\", files: [file] });\n }\n if (/\\b(?:token|jwt|accessToken|refreshToken)\\b/i.test(content) && !/logout|signOut|clear/i.test(content)) {\n issues.push({ id: \"auth-session-clear-missing\", severity: \"warning\", message: \"Token/session code should include a clear/logout path.\", files: [file] });\n }\n }\n return issues;\n}\n\nexport async function validateBackendHealthApi(workspace: string, manifest: ValidationManifest, runContext?: TanyaRunContext): Promise<ValidationIssue[]> {\n const issues: ValidationIssue[] = [];\n const backendFiles = changedMatching(manifest, /(?:^|\\/)(?:src\\/|routes\\/|server\\/|prisma\\/|backend\\/).*\\.(?:ts|js|mjs|prisma|md)$/);\n if (backendFiles.length === 0) {\n return [{ id: \"backend-api-files-missing\", severity: \"error\", message: \"Backend/API task did not modify recognizable backend files.\" }];\n }\n const combined = (await Promise.all(backendFiles.slice(0, 40).map(async (file) => await readWorkspaceFile(workspace, file) ?? \"\"))).join(\"\\n\");\n if (/\\bhealth\\b/i.test(taskText(runContext)) && !/health|status|ready/i.test(combined)) {\n issues.push({ id: \"backend-health-route-missing\", severity: \"warning\", message: \"Could not confirm a health/status endpoint in backend changes.\", files: backendFiles.slice(0, 5) });\n }\n if (/process\\.env\\.[A-Z0-9_]+/.test(combined) && !manifest.changedFiles.some((file) => /(?:^|\\/)\\.env\\.example$|EnvExample/i.test(file))) {\n issues.push({ id: \"backend-env-example-missing\", severity: \"warning\", message: \"Backend task references env vars but did not update .env.example or an env artifact.\", files: backendFiles.slice(0, 5) });\n }\n return issues;\n}\n\nexport async function validateBackendSetupEnvironment(workspace: string): Promise<ValidationIssue[]> {\n const issues: ValidationIssue[] = [];\n const env = await readWorkspaceFile(workspace, \".env.example\");\n\n if (!env) {\n return [{\n id: \"backend-setup-env-example-missing\",\n severity: \"error\",\n message: \"Backend setup must create or update .env.example with safe placeholders.\",\n files: [\".env.example\"],\n }];\n }\n\n const fileCache = new Map<string, string | null>([[\".env.example\", env]]);\n for (const rule of loadValidatorRules().filter((item): item is BackendSetupEnvironmentRule => item.kind === \"backend_setup_environment\")) {\n issues.push(...await validateBackendSetupEnvironmentRule(workspace, rule, fileCache));\n }\n\n return issues;\n}\n\nexport async function validateRevenueCat(workspace: string, manifest: ValidationManifest): Promise<ValidationIssue[]> {\n const issues: ValidationIssue[] = [];\n const files = changedMatching(manifest, /(?:RevenueCat|Paywall|Subscription|Premium|Entitlement|Purchases|Webhook).*\\.(?:swift|kt|ts|js)$/);\n if (files.length === 0) {\n return [{ id: \"revenuecat-files-missing\", severity: \"error\", message: \"RevenueCat task did not modify recognizable RevenueCat, paywall, subscription, premium, entitlement, or webhook files.\" }];\n }\n const combined = (await Promise.all(files.map(async (file) => await readWorkspaceFile(workspace, file) ?? \"\"))).join(\"\\n\");\n if (!/RevenueCat|Purchases|entitlement|paywall|subscription|webhook/i.test(combined)) {\n issues.push({ id: \"revenuecat-wiring-missing\", severity: \"error\", message: \"Could not confirm RevenueCat/paywall/subscription wiring.\", files });\n }\n if (/api[_-]?key|secret|token/i.test(combined) && /[\"'][A-Za-z0-9_./+=-]{16,}[\"']/.test(combined) && !/process\\.env|\\$\\{|BuildConfig|Info\\.plist|Environment/i.test(combined)) {\n issues.push({ id: \"revenuecat-hardcoded-secret-risk\", severity: \"error\", message: \"RevenueCat credentials appear hardcoded instead of environment/config driven.\", files });\n }\n return issues;\n}\n\nexport function inferPrimaryPlatform(workspace: string): ValidationSummary[\"primaryPlatform\"] {\n const m = workspace.toLowerCase().match(/\\/(ios|macos|android|backend|landing|web|script|cli)(?:\\/|$)/);\n if (!m) return \"unknown\";\n // cli → script: workspace folders are sometimes named cli/, treat them as script.\n return m[1] === \"cli\" ? \"script\" : (m[1] as ValidationSummary[\"primaryPlatform\"]);\n}\n","import { readdirSync, readFileSync, statSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { discoverIntegrationEntries } from \"../../../integrations/discovery\";\nimport { builtInValidatorRuleFiles } from \"./index\";\nimport type {\n BackendSetupEnvironmentRule,\n DocumentationRequirement,\n PlaceholderRequirement,\n RequiredEnvValueRule,\n ValidatorRule,\n ValidatorRuleFile,\n ValidatorRuleIssue,\n ValidatorRulePattern,\n ValidatorRulePatternIssue,\n} from \"./types\";\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === \"object\" && !Array.isArray(value);\n}\n\nfunction stringArray(value: unknown): string[] | undefined {\n if (!Array.isArray(value)) return undefined;\n const values = value.filter((item): item is string => typeof item === \"string\" && item.trim().length > 0);\n return values.length > 0 ? values : undefined;\n}\n\nfunction pattern(value: unknown): ValidatorRulePattern | undefined {\n if (!isRecord(value) || typeof value.pattern !== \"string\" || value.pattern.trim().length === 0) return undefined;\n return {\n pattern: value.pattern,\n ...(typeof value.flags === \"string\" ? { flags: value.flags } : {}),\n };\n}\n\nfunction patterns(value: unknown): ValidatorRulePattern[] | undefined {\n if (!Array.isArray(value)) return undefined;\n const values = value.map(pattern).filter((item): item is ValidatorRulePattern => Boolean(item));\n return values.length > 0 ? values : undefined;\n}\n\nfunction severity(value: unknown): \"error\" | \"warning\" | undefined {\n return value === \"error\" || value === \"warning\" ? value : undefined;\n}\n\nfunction issue(value: unknown): ValidatorRuleIssue | undefined {\n if (!isRecord(value) || typeof value.id !== \"string\" || typeof value.message !== \"string\") return undefined;\n const parsedSeverity = severity(value.severity);\n if (!parsedSeverity) return undefined;\n const parsed: ValidatorRuleIssue = {\n id: value.id,\n severity: parsedSeverity,\n message: value.message,\n };\n const files = stringArray(value.files);\n if (files) parsed.files = files;\n return parsed;\n}\n\nfunction patternIssue(value: unknown): ValidatorRulePatternIssue | undefined {\n const parsedPattern = pattern(value);\n const parsedIssue = issue(value);\n return parsedPattern && parsedIssue ? { ...parsedPattern, ...parsedIssue } : undefined;\n}\n\nfunction placeholderRequirement(value: unknown): PlaceholderRequirement | undefined {\n if (!isRecord(value)) return undefined;\n const unclearIssue = issue(value.unclearIssue);\n if (!unclearIssue) return undefined;\n const parsed: PlaceholderRequirement = {\n unclearIssue,\n };\n if (typeof value.acceptedExplicitPlaceholder === \"boolean\") parsed.acceptedExplicitPlaceholder = value.acceptedExplicitPlaceholder;\n const allowedPatterns = patterns(value.allowedPatterns);\n if (allowedPatterns) parsed.allowedPatterns = allowedPatterns;\n return parsed;\n}\n\nfunction requiredEnvValueRule(value: unknown): RequiredEnvValueRule | undefined {\n if (!isRecord(value) || typeof value.name !== \"string\" || value.name.trim().length === 0) return undefined;\n const missingIssue = issue(value.missingIssue);\n if (!missingIssue) return undefined;\n const forbiddenValues = Array.isArray(value.forbiddenValues)\n ? value.forbiddenValues.map(patternIssue).filter((item): item is ValidatorRulePatternIssue => Boolean(item))\n : undefined;\n const parsed: RequiredEnvValueRule = {\n name: value.name,\n missingIssue,\n };\n if (forbiddenValues && forbiddenValues.length > 0) parsed.forbiddenValues = forbiddenValues;\n const placeholder = placeholderRequirement(value.placeholder);\n if (placeholder) parsed.placeholder = placeholder;\n return parsed;\n}\n\nfunction documentationRequirement(value: unknown): DocumentationRequirement | undefined {\n if (!isRecord(value)) return undefined;\n const parsedIssue = issue(value.issue);\n if (!parsedIssue) return undefined;\n const parsed: DocumentationRequirement = {\n issue: parsedIssue,\n };\n const all = patterns(value.all);\n if (all) parsed.all = all;\n const any = patterns(value.any);\n if (any) parsed.any = any;\n return parsed;\n}\n\nfunction backendSetupEnvironmentRule(value: unknown): BackendSetupEnvironmentRule | undefined {\n if (!isRecord(value) || value.kind !== \"backend_setup_environment\" || typeof value.id !== \"string\") return undefined;\n const requiredEnv = Array.isArray(value.requiredEnv)\n ? value.requiredEnv.map(requiredEnvValueRule).filter((item): item is RequiredEnvValueRule => Boolean(item))\n : undefined;\n const documentation = Array.isArray(value.documentation)\n ? value.documentation.map(documentationRequirement).filter((item): item is DocumentationRequirement => Boolean(item))\n : undefined;\n const parsed: BackendSetupEnvironmentRule = {\n kind: \"backend_setup_environment\",\n id: value.id,\n };\n if (typeof value.envFile === \"string\") parsed.envFile = value.envFile;\n const docsFiles = stringArray(value.docsFiles);\n if (docsFiles) parsed.docsFiles = docsFiles;\n if (requiredEnv && requiredEnv.length > 0) parsed.requiredEnv = requiredEnv;\n if (documentation && documentation.length > 0) parsed.documentation = documentation;\n return parsed;\n}\n\nfunction validatorRule(value: unknown): ValidatorRule | undefined {\n if (!isRecord(value)) return undefined;\n if (value.kind === \"backend_setup_environment\") return backendSetupEnvironmentRule(value);\n return undefined;\n}\n\nfunction validatorRuleFile(value: unknown): ValidatorRuleFile | undefined {\n if (!isRecord(value) || !Array.isArray(value.rules)) return undefined;\n const rules = value.rules.map(validatorRule).filter((item): item is ValidatorRule => Boolean(item));\n return { version: 1, rules };\n}\n\nfunction safeStat(path: string): { isFile(): boolean; isDirectory(): boolean } | undefined {\n try {\n return statSync(path);\n } catch {\n return undefined;\n }\n}\n\nfunction jsonFiles(path: string): string[] {\n const stat = safeStat(path);\n if (!stat) return [];\n if (stat.isFile()) return path.endsWith(\".json\") ? [path] : [];\n if (!stat.isDirectory()) return [];\n\n try {\n return readdirSync(path, { withFileTypes: true })\n .flatMap((entry) => jsonFiles(join(path, entry.name)))\n .sort((a, b) => a.localeCompare(b));\n } catch {\n return [];\n }\n}\n\nfunction readRuleFile(path: string): ValidatorRuleFile | undefined {\n try {\n return validatorRuleFile(JSON.parse(readFileSync(path, \"utf8\")));\n } catch {\n return undefined;\n }\n}\n\nfunction discoveredValidatorRuleFiles(): ValidatorRuleFile[] {\n return discoverIntegrationEntries(\"validators\")\n .flatMap((entry) => jsonFiles(entry.path))\n .map(readRuleFile)\n .filter((file): file is ValidatorRuleFile => Boolean(file));\n}\n\nexport function loadValidatorRules(): ValidatorRule[] {\n return [...builtInValidatorRuleFiles, ...discoveredValidatorRuleFiles()]\n .flatMap((file) => file.rules);\n}\n","import type { ValidatorRuleFile } from \"./types\";\n\nexport const builtInValidatorRuleFiles: ValidatorRuleFile[] = [];\n\nexport type {\n BackendSetupEnvironmentRule,\n DocumentationRequirement,\n PlaceholderRequirement,\n RequiredEnvValueRule,\n ValidatorRule,\n ValidatorRuleFile,\n ValidatorRuleIssue,\n ValidatorRulePattern,\n ValidatorRulePatternIssue,\n ValidatorRuleSeverity,\n} from \"./types\";\n","import type { TanyaRunContext } from \"../../context/runContext\";\nimport {\n changedMatching,\n constraintText,\n findWorkspaceFiles,\n hasChanged,\n hasDedicatedCtaSlide,\n hasSuccessfulVerification,\n readWorkspaceFile,\n taskText,\n uniqueSorted,\n type ValidationIssue,\n type ValidationManifest,\n} from \"./core\";\n\nexport async function validateIosSplash(workspace: string, manifest: ValidationManifest, runContext?: TanyaRunContext): Promise<ValidationIssue[]> {\n const issues: ValidationIssue[] = [];\n const text = constraintText(runContext);\n const wantsSolidBackground = /\\bsolid\\b/i.test(text) || /\\bno gradients?\\b/i.test(text);\n const wantsGradient = /\\bgradient\\b/i.test(text) && !wantsSolidBackground;\n const wantsElevatedTile = /\\b(?:rounded|elevated|tile|card)\\b/i.test(text);\n const wantsShadow = /\\b(?:shadow|glow)\\b/i.test(text);\n const wantsPulse = /\\b(?:pulse|repeat(?:-| )?forever)\\b/i.test(text);\n const wantsAppName = /\\b(?:app name|application name|show (?:the )?(?:name|title)|title below|name below)\\b/i.test(text);\n const forbidsText = /\\b(?:no taglines?|no text|image\\(\\\"splashicon\\\"\\)\\s+only|icon\\s+only)\\b/i.test(text);\n if (!hasChanged(manifest, /(?:^|\\/)SplashScreenView\\.swift$/)) {\n issues.push({\n id: \"ios-splash-view-missing\",\n severity: \"error\",\n message: \"iOS splash task did not modify or create SplashScreenView.swift.\",\n });\n return issues;\n }\n\n const splashPath = manifest.changedFiles.find((file) => /(?:^|\\/)SplashScreenView\\.swift$/.test(file)) ?? \"SplashScreenView.swift\";\n const splash = await readWorkspaceFile(workspace, splashPath);\n if (!splash) {\n issues.push({ id: \"ios-splash-view-unreadable\", severity: \"error\", message: \"Could not read SplashScreenView.swift for validation.\", files: [splashPath] });\n return issues;\n }\n\n if (!/Image\\(\\s*\"SplashIcon\"\\s*\\)/.test(splash)) {\n issues.push({ id: \"ios-splash-icon-image\", severity: \"error\", message: \"SplashScreenView.swift must use Image(\\\"SplashIcon\\\").\", files: [splashPath] });\n }\n if (!/onAppear\\s*\\{[\\s\\S]*Task\\s*\\{[\\s\\S]*Task\\.sleep[\\s\\S]*isReady\\s*=\\s*true/.test(splash)) {\n issues.push({ id: \"ios-splash-onappear-task\", severity: \"error\", message: \"SplashScreenView.swift must use onAppear with Task.sleep before setting isReady = true.\", files: [splashPath] });\n }\n if (/\\.task\\s*\\{/.test(splash)) {\n issues.push({ id: \"ios-splash-task-modifier\", severity: \"error\", message: \"SplashScreenView.swift must not use a SwiftUI .task modifier for the splash delay.\", files: [splashPath] });\n }\n if (wantsGradient && !/LinearGradient\\s*\\(/.test(splash) && !/RadialGradient\\s*\\(/.test(splash)) {\n issues.push({ id: \"ios-splash-gradient-missing\", severity: \"error\", message: \"SplashScreenView.swift must render a brand gradient background, not a flat color only.\", files: [splashPath] });\n }\n if (wantsElevatedTile && !/RoundedRectangle\\s*\\(/.test(splash)) {\n issues.push({ id: \"ios-splash-elevated-tile-missing\", severity: \"error\", message: \"SplashScreenView.swift must place SplashIcon inside a rounded elevated tile.\", files: [splashPath] });\n }\n if (wantsShadow && !/shadow\\s*\\(/.test(splash)) {\n issues.push({ id: \"ios-splash-shadow-missing\", severity: \"error\", message: \"Splash icon tile must include an elevated shadow/glow.\", files: [splashPath] });\n }\n if (wantsPulse && (!/repeatForever\\s*\\(/.test(splash) || !/scaleEffect\\s*\\(/.test(splash))) {\n issues.push({ id: \"ios-splash-pulse-missing\", severity: \"error\", message: \"Splash icon tile must include a slow repeat-forever pulse animation.\", files: [splashPath] });\n }\n if (wantsAppName && !/Text\\s*\\(\\s*\"/.test(splash)) {\n issues.push({ id: \"ios-splash-app-name-missing\", severity: \"error\", message: \"SplashScreenView.swift must show the app name below the icon.\", files: [splashPath] });\n }\n if (forbidsText && /Text\\s*\\(/.test(splash)) {\n issues.push({ id: \"ios-splash-text-forbidden\", severity: \"error\", message: \"Splash task requested no taglines/text; SplashScreenView.swift must render only the splash icon.\", files: [splashPath] });\n }\n if (wantsSolidBackground && (/LinearGradient\\s*\\(/.test(splash) || /RadialGradient\\s*\\(/.test(splash) || /AngularGradient\\s*\\(/.test(splash))) {\n issues.push({ id: \"ios-splash-solid-background-violated\", severity: \"error\", message: \"Splash task requested a solid background, but SplashScreenView.swift uses a gradient.\", files: [splashPath] });\n }\n if (/\\bnothing else\\b|brief fade-in/i.test(text) && (/repeatForever\\s*\\(/.test(splash) || /scaleEffect\\s*\\(/.test(splash) || /\\.transition\\s*\\(/.test(splash) || /\\.animation\\s*\\([\\s\\S]{0,120}value:\\s*isReady/.test(splash))) {\n issues.push({ id: \"ios-splash-extra-animation\", severity: \"error\", message: \"Splash task requested only a brief fade-in, but SplashScreenView.swift adds extra animation.\", files: [splashPath] });\n }\n const usesExplicitBrandRed = /#A52A2A/i.test(splash) || /165\\s*\\/\\s*255[\\s\\S]*42\\s*\\/\\s*255[\\s\\S]*42\\s*\\/\\s*255/.test(splash) || /0\\.647[\\s\\S]*0\\.165[\\s\\S]*0\\.165/.test(splash);\n if (/Color\\.accentColor/.test(splash) && !usesExplicitBrandRed) {\n issues.push({ id: \"ios-splash-accentcolor-only\", severity: \"error\", message: \"Splash background uses Color.accentColor without explicit brand-red fallback evidence.\", files: [splashPath] });\n }\n if (!usesExplicitBrandRed && !/brand/i.test(splash)) {\n issues.push({ id: \"ios-splash-brand-color-missing\", severity: \"warning\", message: \"Could not confirm explicit brand color usage in SplashScreenView.swift.\", files: [splashPath] });\n }\n if (!hasChanged(manifest, /(?:^|\\/)SplashIcon\\.imageset\\/Contents\\.json$/)) {\n issues.push({ id: \"ios-splash-asset-json-missing\", severity: \"error\", message: \"iOS splash task did not create SplashIcon.imageset/Contents.json.\" });\n }\n return issues;\n}\n\nexport async function validateAppleAppIcon(workspace: string, manifest: ValidationManifest, runContext?: TanyaRunContext): Promise<ValidationIssue[]> {\n const issues: ValidationIssue[] = [];\n const text = taskText(runContext);\n const contentsPath = manifest.changedFiles.find((file) => /(?:^|\\/)AppIcon\\.appiconset\\/Contents\\.json$/.test(file));\n if (!contentsPath) {\n return [{ id: \"apple-app-icon-contents-missing\", severity: \"error\", message: \"Apple app icon task did not create or modify AppIcon.appiconset/Contents.json.\" }];\n }\n const raw = await readWorkspaceFile(workspace, contentsPath);\n if (!raw) {\n return [{ id: \"apple-app-icon-contents-unreadable\", severity: \"error\", message: \"Could not read AppIcon.appiconset/Contents.json.\", files: [contentsPath] }];\n }\n let parsed: { images?: Array<{ idiom?: string; size?: string; filename?: string }> };\n try {\n parsed = JSON.parse(raw) as { images?: Array<{ idiom?: string; size?: string; filename?: string }> };\n } catch {\n return [{ id: \"apple-app-icon-contents-invalid-json\", severity: \"error\", message: \"AppIcon.appiconset/Contents.json is not valid JSON.\", files: [contentsPath] }];\n }\n const images = Array.isArray(parsed.images) ? parsed.images : [];\n const idioms = new Set(images.map((image) => image.idiom).filter(Boolean));\n for (const idiom of [\"iphone\", \"ipad\", \"ios-marketing\"]) {\n if (!idioms.has(idiom)) {\n issues.push({ id: \"apple-app-icon-idiom-missing\", severity: \"error\", message: `AppIcon.appiconset is missing required idiom: ${idiom}.`, files: [contentsPath] });\n }\n }\n if (/\\bmac(?:os)?\\b/.test(text)) {\n const macImages = images.filter((image) => image.idiom === \"mac\");\n const macSizes = new Set(macImages.map((image) => (image as { size?: string }).size).filter(Boolean));\n for (const size of [\"16x16\", \"32x32\", \"128x128\", \"256x256\", \"512x512\"]) {\n if (!macSizes.has(size)) {\n issues.push({ id: \"apple-app-icon-mac-size-missing\", severity: \"error\", message: `AppIcon.appiconset is missing required macOS size: ${size}.`, files: [contentsPath] });\n }\n }\n if (macImages.length < 10) {\n issues.push({ id: \"apple-app-icon-mac-slots-incomplete\", severity: \"error\", message: \"AppIcon.appiconset must include the 10 standard macOS icon slots.\", files: [contentsPath] });\n }\n }\n const pngFiles = images.map((image) => image.filename).filter((filename): filename is string => !!filename);\n if (pngFiles.length === 0) {\n issues.push({ id: \"apple-app-icon-pngs-missing\", severity: \"error\", message: \"AppIcon.appiconset has no PNG filenames.\", files: [contentsPath] });\n }\n const iconDir = contentsPath.replace(/Contents\\.json$/, \"\");\n for (const filename of pngFiles.slice(0, 80)) {\n const iconPath = `${iconDir}${filename}`;\n if (!await readWorkspaceFile(workspace, iconPath).then((content) => content !== null)) {\n issues.push({ id: \"apple-app-icon-png-missing\", severity: \"error\", message: `AppIcon PNG listed in Contents.json is missing: ${iconPath}`, files: [contentsPath] });\n break;\n }\n }\n if (!hasSuccessfulVerification(manifest, /\\bxcodebuild\\s+build\\b/i)) {\n issues.push({\n id: \"apple-app-icon-xcodebuild-missing\",\n severity: \"error\",\n message: \"Apple app icon task must run and report a successful xcodebuild build to catch asset catalog warnings.\",\n files: [contentsPath],\n });\n }\n return issues;\n}\n\nexport async function validateIosOnboarding(workspace: string, manifest: ValidationManifest): Promise<ValidationIssue[]> {\n const issues: ValidationIssue[] = [];\n const onboardingPath = manifest.changedFiles.find((file) => /(?:^|\\/)OnboardingView\\.swift$/.test(file)) ??\n (await findWorkspaceFiles(workspace, (file) => /(?:^|\\/)OnboardingView\\.swift$/.test(file), { limit: 10 }))[0];\n if (!onboardingPath) {\n return [{ id: \"ios-onboarding-view-missing\", severity: \"error\", message: \"iOS onboarding task must create or update OnboardingView.swift.\" }];\n }\n const onboarding = await readWorkspaceFile(workspace, onboardingPath);\n if (!onboarding) return [{ id: \"ios-onboarding-view-unreadable\", severity: \"error\", message: \"Could not read OnboardingView.swift.\", files: [onboardingPath] }];\n\n if (!/TabView\\s*\\(/.test(onboarding) || !/\\.tabViewStyle\\s*\\(\\s*\\.page/.test(onboarding)) {\n issues.push({ id: \"ios-onboarding-tabview-missing\", severity: \"error\", message: \"OnboardingView.swift must use a paged TabView.\", files: [onboardingPath] });\n }\n if (!/@AppStorage\\s*\\(\\s*\"hasSeenOnboarding\"\\s*\\)/.test(onboarding) && !/UserDefaults[\\s\\S]*hasSeenOnboarding/.test(onboarding)) {\n issues.push({ id: \"ios-onboarding-storage-key-missing\", severity: \"error\", message: \"iOS onboarding must persist completion with the exact hasSeenOnboarding key.\", files: [onboardingPath] });\n }\n if (!/\\bPular\\b/.test(onboarding)) {\n issues.push({ id: \"ios-onboarding-skip-missing\", severity: \"error\", message: \"OnboardingView.swift must include the pt-BR skip button `Pular`.\", files: [onboardingPath] });\n } else {\n const skipIndex = onboarding.indexOf(\"Pular\");\n const bottomOverlayIndex = onboarding.search(/VStack\\s*\\{\\s*Spacer\\s*\\(\\s*\\)/);\n if (bottomOverlayIndex >= 0 && skipIndex > bottomOverlayIndex) {\n issues.push({ id: \"ios-onboarding-skip-not-top-right\", severity: \"error\", message: \"`Pular` must be positioned in a top-right overlay outside the bottom controls stack.\", files: [onboardingPath] });\n }\n if (!/currentPage\\s*<\\s*(?:totalPages|slides\\.count)\\s*-\\s*1[\\s\\S]{0,220}\\bPular\\b|\\bPular\\b[\\s\\S]{0,220}currentPage\\s*<\\s*(?:totalPages|slides\\.count)\\s*-\\s*1/.test(onboarding)) {\n issues.push({ id: \"ios-onboarding-skip-last-slide-guard\", severity: \"error\", message: \"`Pular` must be hidden on the final CTA slide.\", files: [onboardingPath] });\n }\n }\n if (!hasDedicatedCtaSlide(onboarding, \"ios\")) {\n issues.push({ id: \"ios-onboarding-final-cta-slide-missing\", severity: \"error\", message: \"The final onboarding page must be a dedicated CTA slide, not another feature slide with footer CTA buttons.\", files: [onboardingPath] });\n }\n if (!/\\bComeçar grátis\\b/.test(onboarding) || !/\\bJá tenho conta\\b/.test(onboarding)) {\n issues.push({ id: \"ios-onboarding-cta-copy-missing\", severity: \"error\", message: \"Final CTA slide must include `Começar grátis` and `Já tenho conta`.\", files: [onboardingPath] });\n }\n if (!hasSuccessfulVerification(manifest, /\\bxcodebuild\\s+build\\b/i)) {\n issues.push({ id: \"ios-onboarding-xcodebuild-missing\", severity: \"error\", message: \"iOS onboarding task must run and report a successful xcodebuild build.\", files: [onboardingPath] });\n }\n return issues;\n}\n\nexport async function validateIosFoundation(workspace: string, manifest: ValidationManifest, runContext?: TanyaRunContext): Promise<ValidationIssue[]> {\n const issues: ValidationIssue[] = [];\n const discoveredSwiftFiles = await findWorkspaceFiles(\n workspace,\n (file) => /\\.swift$/.test(file) && !/(?:^|\\/)\\.tania\\//.test(file),\n { roots: [\".\"], limit: 160 },\n );\n const swiftFiles = uniqueSorted([\n ...changedMatching(manifest, /(?:^|\\/)[^/].*\\.swift$/),\n ...discoveredSwiftFiles,\n ]);\n const fontFiles = await findWorkspaceFiles(\n workspace,\n (file) => /\\.(?:ttf|otf)$/i.test(file) && !/(?:^|\\/)\\.tania\\//.test(file),\n { roots: [\".\"], limit: 80 },\n );\n const fileTexts = new Map<string, string>();\n for (const file of swiftFiles) fileTexts.set(file, await readWorkspaceFile(workspace, file) ?? \"\");\n const combinedSwift = swiftFiles.map((file) => fileTexts.get(file) ?? \"\").join(\"\\n\");\n const text = constraintText(runContext);\n const wantsDarkMode = /\\bdark mode\\b|\\bdark-mode\\b|\\bmodo escuro\\b/i.test(text);\n const wantsBrandFonts = /\\bplayfair\\b|\\broboto\\b|\\bbrand rules?\\b|\\btypograph/i.test(text);\n\n if (!/#1A2F4B|0x1A2F4B|26\\s*\\/\\s*255[\\s\\S]*47\\s*\\/\\s*255[\\s\\S]*75\\s*\\/\\s*255/.test(combinedSwift) ||\n !/#C8AE7F|0xC8AE7F|200\\s*\\/\\s*255[\\s\\S]*174\\s*\\/\\s*255[\\s\\S]*127\\s*\\/\\s*255/.test(combinedSwift)) {\n issues.push({ id: \"ios-foundation-brand-colors-missing\", severity: \"error\", message: \"iOS foundation must define the Cosa Nostra brand colors (#1A2F4B and #C8AE7F).\", files: swiftFiles });\n }\n if (!/@Model\\b|ModelContainer\\s*\\(|Schema\\s*\\(/.test(combinedSwift)) {\n issues.push({ id: \"ios-foundation-swiftdata-missing\", severity: \"error\", message: \"iOS foundation must add SwiftData models and app container wiring.\", files: swiftFiles });\n }\n if (!/TabView\\s*(?:\\(|\\{)|NavigationStack\\s*(?:\\(|\\{)/.test(combinedSwift)) {\n issues.push({ id: \"ios-foundation-navigation-missing\", severity: \"error\", message: \"iOS foundation must add TabView/NavigationStack app navigation.\", files: swiftFiles });\n }\n if (!/ViewModifier\\b|ButtonStyle\\b|EmptyState|LoadingView|ErrorView/.test(combinedSwift)) {\n issues.push({ id: \"ios-foundation-base-ui-missing\", severity: \"error\", message: \"iOS foundation must add reusable view modifiers, button styles, and empty/loading/error UI states.\", files: swiftFiles });\n }\n if (wantsDarkMode) {\n if (!/preferredColorScheme\\s*\\(/.test(combinedSwift)) {\n issues.push({ id: \"ios-foundation-dark-mode-scheme-missing\", severity: \"error\", message: \"iOS foundation must wire dark-mode color scheme support.\", files: swiftFiles });\n }\n if (!/Toggle\\s*\\([^)]*(?:isDarkMode|darkMode|colorScheme)|Picker\\s*\\([^)]*(?:Color Scheme|Appearance|Theme)/.test(combinedSwift)) {\n issues.push({ id: \"ios-foundation-dark-mode-control-missing\", severity: \"error\", message: \"iOS foundation must include a user-facing dark-mode control, not only stored state.\", files: swiftFiles });\n }\n if (/foreground(?:Style|Color)\\s*\\(\\s*Color\\.brandWhite\\s*\\)|foreground(?:Style|Color)\\s*\\(\\s*\\.brandWhite\\s*\\)/.test(combinedSwift)) {\n issues.push({ id: \"ios-foundation-hardcoded-dark-text\", severity: \"warning\", message: \"iOS foundation uses hardcoded brandWhite foregrounds; confirm adaptive text colors for light and dark mode.\", files: swiftFiles });\n }\n }\n if (wantsBrandFonts) {\n const mentionsFonts = /Playfair|Roboto/.test(combinedSwift);\n const hasFontFiles = fontFiles.some((file) => /(?:Playfair|Roboto)/i.test(file));\n if (!mentionsFonts) {\n issues.push({ id: \"ios-foundation-brand-fonts-missing\", severity: \"error\", message: \"iOS foundation must define Playfair Display and Roboto typography tokens.\", files: swiftFiles });\n } else if (/\\bmanual action\\b|\\bmanual follow-?up\\b|add .*font files|UIAppFonts/i.test(combinedSwift)) {\n issues.push({ id: \"ios-foundation-manual-font-action\", severity: \"error\", message: \"iOS foundation must not leave brand font setup as a manual action; use provided font assets or a local system-font fallback.\", files: swiftFiles });\n } else if (!hasFontFiles && !/\\.serif\\b|design:\\s*\\.serif|system\\s+serif|system\\s+font/i.test(combinedSwift)) {\n issues.push({ id: \"ios-foundation-brand-font-fallback-missing\", severity: \"warning\", message: \"Playfair/Roboto font files were not found; typography should include an explicit local system-font fallback.\", files: swiftFiles });\n }\n }\n return issues;\n}\n","import type { TanyaRunContext } from \"../../context/runContext\";\nimport {\n changedMatching,\n constraintText,\n extractPromptFeatures,\n featureCoveredByText,\n findWorkspaceFiles,\n hasChanged,\n hasDedicatedCtaSlide,\n hasSuccessfulVerification,\n readWorkspaceFile,\n uniqueSorted,\n workspaceFileExists,\n type ValidationIssue,\n type ValidationManifest,\n} from \"./core\";\n\nasync function androidGradleVerificationIssues(workspace: string, manifest: ValidationManifest): Promise<ValidationIssue[]> {\n if (!await workspaceFileExists(workspace, \"gradlew\")) return [];\n const issues: ValidationIssue[] = [];\n if (!hasSuccessfulVerification(manifest, /(?:^|[\\s;&|])\\.\\/gradlew\\s+assembleDebug\\b/i)) {\n issues.push({\n id: \"android-gradle-assembledebug-missing\",\n severity: \"error\",\n message: \"Android task has a local Gradle wrapper and must run/report `./gradlew assembleDebug --no-daemon` instead of deferring it as a manual check.\",\n files: [\"gradlew\"],\n });\n }\n const gradleTexts = (await Promise.all([\n readWorkspaceFile(workspace, \"build.gradle.kts\"),\n readWorkspaceFile(workspace, \"app/build.gradle.kts\"),\n readWorkspaceFile(workspace, \"settings.gradle.kts\"),\n readWorkspaceFile(workspace, \"build.gradle\"),\n readWorkspaceFile(workspace, \"app/build.gradle\"),\n ])).filter((text): text is string => text !== null).join(\"\\n\");\n if (/ktlint/i.test(gradleTexts) && !hasSuccessfulVerification(manifest, /(?:^|[\\s;&|])\\.\\/gradlew\\s+ktlintCheck\\b/i)) {\n issues.push({\n id: \"android-gradle-ktlintcheck-missing\",\n severity: \"error\",\n message: \"Android task has ktlint configured and must run/report `./gradlew ktlintCheck --no-daemon`.\",\n files: [\"build.gradle.kts\", \"app/build.gradle.kts\"],\n });\n }\n return issues;\n}\n\nexport async function validateAndroidSplash(workspace: string, manifest: ValidationManifest): Promise<ValidationIssue[]> {\n const issues: ValidationIssue[] = [...await androidGradleVerificationIssues(workspace, manifest)];\n const manifestPath = manifest.changedFiles.find((file) => /(?:^|\\/)AndroidManifest\\.xml$/.test(file)) ?? \"app/src/main/AndroidManifest.xml\";\n const androidManifest = await readWorkspaceFile(workspace, manifestPath);\n const splashThemePath = manifest.changedFiles.find((file) => /(?:^|\\/)splash_theme\\.xml$/.test(file)) ?? \"app/src/main/res/values/splash_theme.xml\";\n const splashTheme = await readWorkspaceFile(workspace, splashThemePath);\n const mainActivityPath = manifest.changedFiles.find((file) => /(?:^|\\/)MainActivity\\.kt$/.test(file)) ?? \"app/src/main/java/MainActivity.kt\";\n const mainActivity = await readWorkspaceFile(workspace, mainActivityPath);\n\n if (!splashTheme) {\n issues.push({ id: \"android-splash-theme-missing\", severity: \"error\", message: \"Android splash task did not create app/src/main/res/values/splash_theme.xml.\" });\n } else {\n if (!/Theme\\.SplashScreen/.test(splashTheme)) {\n issues.push({ id: \"android-splash-theme-parent\", severity: \"error\", message: \"splash_theme.xml must use Theme.SplashScreen.\", files: [splashThemePath] });\n }\n if (/@mipmap\\//.test(splashTheme)) {\n issues.push({ id: \"android-splash-mipmap-icon\", severity: \"error\", message: \"splash_theme.xml must reference splash icons from @drawable, not @mipmap.\", files: [splashThemePath] });\n }\n if (!/@drawable\\//.test(splashTheme)) {\n issues.push({ id: \"android-splash-drawable-icon\", severity: \"error\", message: \"splash_theme.xml must reference a @drawable splash icon.\", files: [splashThemePath] });\n }\n }\n if (!androidManifest || !/android:theme\\s*=\\s*\"@style\\//.test(androidManifest)) {\n issues.push({ id: \"android-splash-manifest-theme\", severity: \"error\", message: \"AndroidManifest.xml must set the application/activity splash theme.\", files: [manifestPath] });\n }\n if (!mainActivity || !/installSplashScreen\\s*\\(/.test(mainActivity)) {\n issues.push({ id: \"android-splash-install-call\", severity: \"error\", message: \"MainActivity.kt must call installSplashScreen().\", files: [mainActivityPath] });\n }\n if (!hasChanged(manifest, /(?:^|\\/)res\\/drawable\\/[^/]+\\.png$/)) {\n issues.push({ id: \"android-splash-drawable-png\", severity: \"error\", message: \"Android splash task must place the splash icon PNG under res/drawable/.\" });\n }\n return issues;\n}\n\nexport async function validateAndroidAppIcon(workspace: string, manifest: ValidationManifest): Promise<ValidationIssue[]> {\n const issues: ValidationIssue[] = [...await androidGradleVerificationIssues(workspace, manifest)];\n const launcherPngs = manifest.changedFiles.filter((file) => /(?:^|\\/)res\\/mipmap-[^/]+\\/ic_launcher(?:_round)?\\.png$/.test(file));\n if (launcherPngs.length === 0) {\n issues.push({ id: \"android-app-icon-mipmap-pngs-missing\", severity: \"error\", message: \"Android app icon task did not create launcher PNGs under res/mipmap-*.\" });\n }\n const manifestPath = manifest.changedFiles.find((file) => /(?:^|\\/)AndroidManifest\\.xml$/.test(file)) ?? \"app/src/main/AndroidManifest.xml\";\n const androidManifest = await readWorkspaceFile(workspace, manifestPath);\n if (androidManifest) {\n if (!/android:icon\\s*=\\s*\"@mipmap\\/ic_launcher\"/.test(androidManifest)) {\n issues.push({ id: \"android-app-icon-manifest-icon\", severity: \"warning\", message: \"AndroidManifest.xml does not reference @mipmap/ic_launcher.\", files: [manifestPath] });\n }\n if (!/android:roundIcon\\s*=\\s*\"@mipmap\\/ic_launcher_round\"/.test(androidManifest)) {\n issues.push({ id: \"android-app-icon-manifest-round-icon\", severity: \"warning\", message: \"AndroidManifest.xml does not reference @mipmap/ic_launcher_round.\", files: [manifestPath] });\n }\n }\n return issues;\n}\n\nexport async function validateAndroidOnboarding(workspace: string, manifest: ValidationManifest): Promise<ValidationIssue[]> {\n const issues: ValidationIssue[] = [...await androidGradleVerificationIssues(workspace, manifest)];\n const onboardingPath = manifest.changedFiles.find((file) => /(?:^|\\/)OnboardingScreen\\.kt$/.test(file)) ??\n (await findWorkspaceFiles(workspace, (file) => /(?:^|\\/)OnboardingScreen\\.kt$/.test(file), { roots: [\"app/src/main/java\"], limit: 10 }))[0];\n if (!onboardingPath) {\n return [{ id: \"android-onboarding-screen-missing\", severity: \"error\", message: \"Android onboarding task must create or update OnboardingScreen.kt.\" }, ...issues];\n }\n const onboarding = await readWorkspaceFile(workspace, onboardingPath);\n if (!onboarding) return [{ id: \"android-onboarding-screen-unreadable\", severity: \"error\", message: \"Could not read OnboardingScreen.kt.\", files: [onboardingPath] }, ...issues];\n\n if (!/HorizontalPager\\s*\\(/.test(onboarding)) {\n issues.push({ id: \"android-onboarding-horizontalpager-missing\", severity: \"error\", message: \"OnboardingScreen.kt must use HorizontalPager.\", files: [onboardingPath] });\n }\n if (!/\\bPular\\b/.test(onboarding)) {\n issues.push({ id: \"android-onboarding-skip-missing\", severity: \"error\", message: \"OnboardingScreen.kt must include the pt-BR skip button `Pular`.\", files: [onboardingPath] });\n } else if (!/Alignment\\.TopEnd|align\\s*\\(\\s*Alignment\\.TopEnd\\s*\\)|Arrangement\\.End/.test(onboarding)) {\n issues.push({ id: \"android-onboarding-skip-not-top-right\", severity: \"error\", message: \"`Pular` must be positioned top-right and hidden on the final CTA slide.\", files: [onboardingPath] });\n }\n if (!hasDedicatedCtaSlide(onboarding, \"android\")) {\n issues.push({ id: \"android-onboarding-final-cta-slide-missing\", severity: \"error\", message: \"The final pager page must be a dedicated CTA slide, not another feature slide with footer CTA buttons.\", files: [onboardingPath] });\n }\n if (!/\\bComeçar grátis\\b/.test(onboarding) || !/\\bJá tenho conta\\b/.test(onboarding)) {\n issues.push({ id: \"android-onboarding-cta-copy-missing\", severity: \"error\", message: \"Final CTA slide must include `Começar grátis` and `Já tenho conta`.\", files: [onboardingPath] });\n }\n const stateFiles = uniqueSorted([\n ...manifest.changedFiles.filter((file) => /(?:Onboarding|DataStore|Preferences).*\\.(?:kt|kts)$/.test(file)),\n onboardingPath,\n ]);\n const stateText = (await Promise.all(stateFiles.map(async (file) => await readWorkspaceFile(workspace, file) ?? \"\"))).join(\"\\n\");\n if (!/hasSeenOnboarding/.test(stateText)) {\n issues.push({ id: \"android-onboarding-storage-key-missing\", severity: \"error\", message: \"Android onboarding must persist completion with the exact hasSeenOnboarding key.\", files: stateFiles });\n }\n return issues;\n}\n\nexport async function validateAndroidFoundation(workspace: string, manifest: ValidationManifest): Promise<ValidationIssue[]> {\n const issues: ValidationIssue[] = [...await androidGradleVerificationIssues(workspace, manifest)];\n const discoveredKotlinFiles = await findWorkspaceFiles(\n workspace,\n (file) => /(?:^|\\/)app\\/src\\/main\\/java\\/.*\\.kt$/.test(file) &&\n /(?:\\/data\\/|\\/navigation\\/|\\/ui\\/theme\\/|\\/ui\\/components\\/|MainActivity\\.kt$)/.test(file),\n { roots: [\"app/src/main/java\"], limit: 120 },\n );\n const kotlinFiles = uniqueSorted([\n ...changedMatching(manifest, /(?:^|\\/)app\\/src\\/main\\/java\\/.*\\.kt$/),\n ...discoveredKotlinFiles,\n ]);\n const gradleFiles = uniqueSorted([\n ...changedMatching(manifest, /(?:^|\\/)(?:build\\.gradle\\.kts|app\\/build\\.gradle\\.kts)$/),\n \"build.gradle.kts\",\n \"app/build.gradle.kts\",\n \"settings.gradle.kts\",\n \"gradle/libs.versions.toml\",\n ]);\n const fileTexts = new Map<string, string>();\n for (const file of [...kotlinFiles, ...gradleFiles]) {\n fileTexts.set(file, await readWorkspaceFile(workspace, file) ?? \"\");\n }\n const combinedKotlin = kotlinFiles.map((file) => fileTexts.get(file) ?? \"\").join(\"\\n\");\n const combinedGradle = gradleFiles.map((file) => fileTexts.get(file) ?? \"\").join(\"\\n\");\n\n if (!/@Database\\s*\\(|RoomDatabase|@Entity\\s*\\(|@Dao\\b/.test(combinedKotlin)) {\n issues.push({ id: \"android-foundation-room-missing\", severity: \"error\", message: \"Android foundation must add Room database/entity/DAO code.\", files: kotlinFiles });\n }\n if (!/NavHost\\s*\\(|rememberNavController\\s*\\(|NavigationBarItem\\s*\\(/.test(combinedKotlin)) {\n issues.push({ id: \"android-foundation-navigation-missing\", severity: \"error\", message: \"Android foundation must add Navigation Compose scaffolding.\", files: kotlinFiles });\n }\n if (!/MaterialTheme\\s*\\(|darkColorScheme\\s*\\(|lightColorScheme\\s*\\(|dynamic(?:Dark|Light)ColorScheme\\s*\\(/.test(combinedKotlin)) {\n issues.push({ id: \"android-foundation-theme-missing\", severity: \"error\", message: \"Android foundation must add a Material 3 theme with brand colors.\", files: kotlinFiles });\n }\n if (!/EmptyState|LoadingState|ErrorState|SearchableFeatureListScreen/.test(combinedKotlin)) {\n issues.push({ id: \"android-foundation-base-composables-missing\", severity: \"error\", message: \"Android foundation must add reusable base composables or UI states.\", files: kotlinFiles });\n }\n if (!/navigation-compose/.test(combinedGradle)) {\n issues.push({ id: \"android-foundation-nav-dependency-missing\", severity: \"error\", message: \"Android foundation must add Navigation Compose dependency.\", files: gradleFiles });\n }\n if (!/androidx\\.room:room-runtime|androidx\\.room:room-ktx/.test(combinedGradle) || !/room-compiler/.test(combinedGradle)) {\n issues.push({ id: \"android-foundation-room-dependency-missing\", severity: \"error\", message: \"Android foundation must add Room runtime/ktx/compiler dependencies.\", files: gradleFiles });\n }\n return issues;\n}\n\nexport async function validateAndroidBaseLayout(workspace: string, manifest: ValidationManifest, runContext?: TanyaRunContext): Promise<ValidationIssue[]> {\n const issues: ValidationIssue[] = [...await androidGradleVerificationIssues(workspace, manifest)];\n const text = constraintText(runContext);\n const features = extractPromptFeatures(text);\n if (features.length === 0) return issues;\n\n const kotlinFiles = await findWorkspaceFiles(\n workspace,\n (file) => /(?:^|\\/)app\\/src\\/main\\/java\\/.*\\.kt$/.test(file) &&\n /(?:\\/navigation\\/|\\/ui\\/|MainActivity\\.kt$)/.test(file),\n { roots: [\"app/src/main/java\"], limit: 180 },\n );\n const fileTexts = new Map<string, string>();\n for (const file of kotlinFiles) fileTexts.set(file, await readWorkspaceFile(workspace, file) ?? \"\");\n const combinedKotlin = kotlinFiles.map((file) => fileTexts.get(file) ?? \"\").join(\"\\n\");\n\n if (!/NavHost\\s*\\(|NavigationBarItem\\s*\\(|composable\\s*\\(/.test(combinedKotlin)) {\n issues.push({\n id: \"android-base-layout-navigation-missing\",\n severity: \"error\",\n message: \"Android base layout must wire feature navigation with Navigation Compose routes and bottom navigation items.\",\n files: kotlinFiles,\n });\n }\n\n for (const feature of features) {\n if (!featureCoveredByText(feature, combinedKotlin)) {\n issues.push({\n id: \"android-base-layout-feature-missing\",\n severity: \"error\",\n message: `Android base layout is missing a placeholder navigation route/screen for requested feature: ${feature.name}. Do not substitute generic tabs such as Settings for app feature modules.`,\n files: kotlinFiles,\n });\n }\n }\n\n const premiumFeatures = features.filter((feature) => feature.tier === \"premium\");\n if (premiumFeatures.length > 0 && !/\\b(?:PremiumGate|premiumState|hasPremium|isPaidFeature|paywall|entitlement)\\b/.test(combinedKotlin)) {\n issues.push({\n id: \"android-base-layout-premium-gate-missing\",\n severity: \"error\",\n message: \"Android base layout includes premium feature modules and must gate premium feature content with PremiumGate/equivalent entitlement state instead of exposing screens directly.\",\n files: kotlinFiles,\n });\n }\n\n return issues;\n}\n","import type { TanyaRunContext } from \"../../context/runContext\";\nimport {\n constraintText,\n findWorkspaceFiles,\n hasChanged,\n inferPrimaryPlatform,\n readWorkspaceFile,\n uniqueSorted,\n workspaceFileExists,\n type ValidationIssue,\n type ValidationManifest,\n} from \"./core\";\n\nexport async function validateGoBackendConfigEnvConsistency(workspace: string): Promise<ValidationIssue[]> {\n const issues: ValidationIssue[] = [];\n const envExample = await readWorkspaceFile(workspace, \".env.example\");\n if (!envExample) return [];\n\n const configFiles = await findWorkspaceFiles(\n workspace,\n (filePath) => /(?:^|\\/)internal\\/config\\/.*\\.go$/.test(filePath) || /(?:^|\\/)config\\.go$/.test(filePath),\n { roots: [\"internal\", \".\"], limit: 20 },\n );\n if (configFiles.length === 0) return [];\n\n const configText = (await Promise.all(\n configFiles.map(async (filePath) => await readWorkspaceFile(workspace, filePath) ?? \"\"),\n )).join(\"\\n\");\n const configKeys = uniqueSorted(\n [...configText.matchAll(/\\b(?:envOr|envDuration|parseIntOr|parseDurationOr|os\\.Getenv)\\(\\s*\"([A-Z][A-Z0-9_]*)\"/g)]\n .map((match) => match[1] ?? \"\"),\n );\n if (configKeys.length === 0) return [];\n\n const exampleKeys = new Set(\n [...envExample.matchAll(/^\\s*([A-Z][A-Z0-9_]*)\\s*=/gm)].map((match) => match[1] ?? \"\"),\n );\n const missing = configKeys.filter((key) => !exampleKeys.has(key));\n for (const key of missing) {\n issues.push({\n id: \"backend-config-env-example-key-missing\",\n severity: \"error\",\n message: `internal/config reads ${key}, but .env.example does not document that exact key. Keep Config.Load and .env.example names identical.`,\n files: [\".env.example\", ...configFiles.slice(0, 3)],\n });\n }\n\n return issues;\n}\n\nexport async function validateGoBackendAuthQuality(workspace: string, manifest: ValidationManifest, runContext?: TanyaRunContext): Promise<ValidationIssue[]> {\n const issues: ValidationIssue[] = [];\n const text = constraintText(runContext);\n const isBackendWorkspace = inferPrimaryPlatform(workspace) === \"backend\" || /(?:^|\\/)backend(?:\\/|$)/.test(workspace);\n const authTask = /\\b(auth|authentication|jwe|nextauth|refresh\\s+token|sign-?in|sign-?out)\\b/i.test(text);\n const touchedAuth = hasChanged(manifest, /(?:^|\\/)internal\\/auth\\/.*\\.go$/) ||\n hasChanged(manifest, /(?:^|\\/)internal\\/handlers\\/auth(?:_test)?\\.go$/) ||\n hasChanged(manifest, /(?:^|\\/)sql\\/queries\\/refresh_tokens\\.sql$/);\n if (!isBackendWorkspace || (!authTask && !touchedAuth)) return [];\n\n const discoveredAuthFiles = await findWorkspaceFiles(\n workspace,\n (filePath) => /(?:^|\\/)internal\\/(?:auth\\/.*\\.go|handlers\\/auth(?:_test)?\\.go)$/.test(filePath) ||\n /(?:^|\\/)sql\\/queries\\/refresh_tokens\\.sql$/.test(filePath),\n { roots: [\"internal\", \"sql\"], limit: 80 },\n );\n const candidateFiles = uniqueSorted([\n ...manifest.changedFiles.filter((file) =>\n /(?:^|\\/)internal\\/(?:auth\\/.*\\.go|handlers\\/auth(?:_test)?\\.go)$/.test(file) ||\n /(?:^|\\/)sql\\/queries\\/refresh_tokens\\.sql$/.test(file)\n ),\n ...discoveredAuthFiles,\n ]);\n\n const testFiles = candidateFiles.filter((file) => /(?:^|\\/)internal\\/(?:auth|handlers)\\/.*_test\\.go$/.test(file));\n const handlerTestFiles = testFiles.filter((file) => /(?:^|\\/)internal\\/handlers\\/.*_test\\.go$/.test(file));\n const authTestFiles = testFiles.filter((file) => /(?:^|\\/)internal\\/auth\\/.*_test\\.go$/.test(file));\n const sourceFiles = candidateFiles.filter((file) => /(?:^|\\/)internal\\/handlers\\/auth\\.go$/.test(file));\n\n const handlerTests = (await Promise.all(handlerTestFiles.map(async (file) => await readWorkspaceFile(workspace, file) ?? \"\"))).join(\"\\n\");\n const authTests = (await Promise.all(authTestFiles.map(async (file) => await readWorkspaceFile(workspace, file) ?? \"\"))).join(\"\\n\");\n const authSources = (await Promise.all(sourceFiles.map(async (file) => await readWorkspaceFile(workspace, file) ?? \"\"))).join(\"\\n\");\n\n if (/RegisterPublicAuth\\s*\\([\\s\\S]{0,240},\\s*nil\\s*,/m.test(handlerTests) || /\\bnil\\s+pool\\b/i.test(handlerTests)) {\n issues.push({\n id: \"go-auth-test-nil-pool\",\n severity: \"error\",\n message: \"Go auth route tests must not pass a nil *pgxpool.Pool or skip refresh because the pool is nil. Use a real test pool/harness so transaction paths execute.\",\n files: handlerTestFiles,\n });\n }\n\n if (/verified\\s+by\\s+code\\s+review|comments?-only|manual\\s+review\\s+test/i.test(handlerTests)) {\n issues.push({\n id: \"go-auth-comments-only-test\",\n severity: \"error\",\n message: \"Go auth tests must assert runtime behavior. Do not use comments, t.Log, or 'verified by code review' as test evidence.\",\n files: handlerTestFiles,\n });\n }\n\n const hasRefreshRouteMention = /[\"'`]\\/(?:v1\\/)?auth\\/refresh[\"'`]/.test(handlerTests);\n const hasRefreshHTTPExercise =\n /(?:httptest\\.NewRequest|http\\.NewRequest|NewRequest)\\s*\\([\\s\\S]{0,500}[\"'`]\\/(?:v1\\/)?auth\\/refresh[\"'`][\\s\\S]{0,1200}(?:ServeHTTP|Do\\s*\\(|RoundTrip)/m.test(handlerTests) ||\n /[\"'`]\\/(?:v1\\/)?auth\\/refresh[\"'`][\\s\\S]{0,1200}(?:ServeHTTP|Do\\s*\\(|RoundTrip)/m.test(handlerTests);\n if (handlerTestFiles.length > 0 && (!hasRefreshRouteMention || !hasRefreshHTTPExercise)) {\n issues.push({\n id: \"go-auth-refresh-http-test-missing\",\n severity: \"error\",\n message: \"Go auth work must include a real HTTP/handler test for POST /v1/auth/refresh. OpenAPI/spec-only checks do not prove refresh rotation, expiry, or reuse behavior.\",\n files: handlerTestFiles,\n });\n }\n\n const registerMatch = authSources.match(/func\\s+registerRegister\\s*\\([^)]*\\)\\s*\\{[\\s\\S]*?(?=\\nfunc\\s+register|\\n\\/\\/\\s*-{3,}|\\nfunc\\s+Register|$)/);\n const registerBody = registerMatch?.[0] ?? \"\";\n if (registerBody && /\\bCreateUser\\b/.test(registerBody) && /\\b(?:CreateRefreshToken|issuer\\.Issue|Issue\\s*\\()/.test(registerBody) && !/\\b(?:WithTx|Begin|db\\.WithTx)\\b/.test(registerBody)) {\n issues.push({\n id: \"go-auth-register-not-transactional\",\n severity: \"error\",\n message: \"Registration creates a user and first refresh token without a transaction. User creation and initial refresh-token persistence must commit or roll back together.\",\n files: sourceFiles,\n });\n }\n\n const hasJWEImplementation = candidateFiles.some((file) => /(?:^|\\/)internal\\/auth\\/jwe\\.go$/.test(file)) ||\n await workspaceFileExists(workspace, \"internal/auth/jwe.go\");\n const hasJWEFixture = /\\b(?:fixture|golden|known\\s+token|jose|nextauth|NextAuth\\.js|generated\\s+by\\s+nextauth)\\b/i.test(authTests);\n const hasOnlyRoundTripEvidence = /\\b(?:SignForTest|Encrypt|Issue|DecodeNextAuthJWE|round[-\\s]?trip)\\b/i.test(authTests);\n if (hasJWEImplementation && authTestFiles.length > 0 && hasOnlyRoundTripEvidence && !hasJWEFixture) {\n issues.push({\n id: \"go-auth-nextauth-fixture-missing\",\n severity: \"error\",\n message: \"JWE tests must include a fixed NextAuth/Jose-compatible fixture. A Go sign/decode round trip only proves internal symmetry, not NextAuth compatibility.\",\n files: authTestFiles,\n });\n }\n\n return issues;\n}\n","import { inferPrimaryPlatform, type ValidationIssue, type Validator } from \"./core\";\n\nexport const schemaMigrationValidator: Validator = {\n id: \"task.schemaMigration\",\n // Couples Prisma schema edits with versioned migration files. If schema.prisma\n // is touched in a backend phase, a sibling prisma/migrations/<ts>_<slug>/migration.sql\n // must also exist (either pre-existing in the repo or freshly written in this run).\n // Without this, schema changes ride along on the next deploy via `prisma db push`,\n // which silently drops/creates tables in production.\n //\n // Prior incident: VerificationCode rename shipped without a\n // migration; old EmailVerificationCode + PasswordResetToken tables persisted\n // in prod, password-reset endpoint 500'd until manual intervention.\n async run(workspace, manifest) {\n const platform = inferPrimaryPlatform(workspace);\n if (platform !== \"backend\") return [];\n\n const schemaTouched = manifest.changedFiles.some((f) =>\n /(?:^|\\/)prisma\\/schema\\.prisma$/.test(f),\n );\n if (!schemaTouched) return [];\n\n const fs = await import(\"fs/promises\");\n const path = await import(\"path\");\n // If schema.prisma was removed as part of replacing a Prisma backend\n // with a different stack, there is no Prisma migration to generate.\n // This validator protects live Prisma schemas; it should not block\n // deliberate stack replacement work.\n try {\n await fs.access(path.join(workspace, \"prisma\", \"schema.prisma\"));\n } catch {\n return [];\n }\n // Detect either a freshly-written migration file (changed in this run)\n // OR a pre-existing migrations directory next to the schema (idempotent boot\n // workflows like `migrate deploy` are the standard).\n const freshMigration = manifest.changedFiles.some((f) =>\n /(?:^|\\/)prisma\\/migrations\\/\\d{4,}_[^/]+\\/migration\\.sql$/.test(f),\n );\n if (freshMigration) return [];\n\n const migrationsDir = path.join(workspace, \"prisma\", \"migrations\");\n let hasAnyMigration = false;\n try {\n const entries = await fs.readdir(migrationsDir, { withFileTypes: true });\n hasAnyMigration = entries.some(\n (e) => e.isDirectory() && /^\\d{4,}_/.test(e.name),\n );\n } catch {\n hasAnyMigration = false;\n }\n\n if (!hasAnyMigration) {\n return [{\n id: \"task-schema-migration-missing\",\n severity: \"error\",\n message: \"prisma/schema.prisma changed but no prisma/migrations/<ts>_<slug>/migration.sql was generated. Run `npx prisma migrate dev --name describe_change` locally and commit the resulting migration directory. Production deploys via `prisma migrate deploy` and will not pick up schema-only edits.\",\n files: [\"prisma/schema.prisma\"],\n }];\n }\n\n // Repo has migrations but this run only edited the schema. That's OK\n // for renames-without-data-impact only if the change is captured in a\n // freshly-baselined migration. Warn so a human sanity-checks.\n return [{\n id: \"task-schema-migration-not-regenerated\",\n severity: \"warning\",\n message: \"schema.prisma changed but no new migration file was added in this run. If the diff requires SQL (rename, type change, new column), generate a migration with `prisma migrate dev` and commit it. If the change is documentation-only (comments), this warning is safe to ignore.\",\n files: [\"prisma/schema.prisma\"],\n }];\n },\n };\n","import {\n inferPrimaryPlatform,\n readWorkspaceFile,\n taskText,\n type ValidationIssue,\n type ValidationManifest,\n type Validator,\n} from \"./core\";\n\n// Semantic validator: every domain resource declared in brand/api_features.md\n// must have an `auth-posture: <posture>` field, AND every route file's\n// middleware composition must match that declared posture. Catches the class\n// of issue where /api/cases shipped without authentication because the contract\n// was undefined and the runtime gate had nothing to compare against. See\n// 2026-05-01 audit foundation/4 finding.\nconst VALID_POSTURES = new Set([\"public-read\", \"authenticated-read\", \"authenticated-write\", \"owner-only\", \"admin-only\"]);\n\nexport async function validateBackendAuthPosture(workspace: string, manifest: ValidationManifest): Promise<ValidationIssue[]> {\n const issues: ValidationIssue[] = [];\n // Find api_features.md — typically at workspace's parent ../brand/ or workspace/brand/\n const apiFeaturesCandidates = [\n \"../brand/api_features.md\",\n \"brand/api_features.md\",\n \"../../brand/api_features.md\",\n ];\n let apiFeaturesContent: string | null = null;\n let apiFeaturesPath: string | null = null;\n for (const rel of apiFeaturesCandidates) {\n const content = await readWorkspaceFile(workspace, rel);\n if (content) { apiFeaturesContent = content; apiFeaturesPath = rel; break; }\n }\n if (!apiFeaturesContent) {\n // No contract document — can't validate posture. This is itself a soft issue\n // for backend tasks but not blocking; the foundation/4 prompt requires it.\n return [{\n id: \"auth-posture-no-contract\",\n severity: \"warning\",\n message: \"No brand/api_features.md found to validate auth posture against. Backend foundation should produce this file.\",\n }];\n }\n // Parse endpoint declarations. Two supported formats:\n // 1) Header-style: `### POST /api/cases` (legacy) — scan ahead for posture\n // 2) Bullet-style: `- \\`GET /cases\\` — auth-posture: public-read. Description...`\n // where the path may omit the `/api` prefix (the contract declares Base URL `/api`).\n // For both, posture may appear inline on the same line OR within the following ~5 lines.\n const lines = apiFeaturesContent.split(/\\r?\\n/);\n const endpointHeaderRe = /^#{2,4}\\s+(?:(GET|POST|PATCH|PUT|DELETE)\\s+)?(\\/(?:api\\/)?[A-Za-z0-9_\\-\\/{}\\[\\]:]+)/;\n const bulletEndpointRe = /^[-*]\\s+`(GET|POST|PATCH|PUT|DELETE)\\s+(\\/[A-Za-z0-9_\\-\\/{}\\[\\]:]+)`/;\n const postureRe = /auth[\\s\\-]posture\\s*[:\\-]\\s*(public-read|authenticated-read|authenticated-write|owner-only|admin-only)/i;\n type Endpoint = { method: string | null; path: string; headerLine: number; posture: string | null };\n const endpoints: Endpoint[] = [];\n for (let i = 0; i < lines.length; i += 1) {\n const line = lines[i]!;\n let method: string | null = null;\n let path: string | null = null;\n const headerMatch = endpointHeaderRe.exec(line);\n const bulletMatch = bulletEndpointRe.exec(line);\n if (headerMatch) {\n method = headerMatch[1] ?? null;\n path = headerMatch[2]!;\n } else if (bulletMatch) {\n method = bulletMatch[1]!;\n path = bulletMatch[2]!;\n } else {\n continue;\n }\n const ep: Endpoint = { method, path, headerLine: i, posture: null };\n // Inline posture on same line first (common for bullet-style)\n const inline = postureRe.exec(line);\n if (inline) {\n ep.posture = inline[1]!.toLowerCase();\n } else {\n // Scan ahead up to 8 lines for posture before next bullet/header\n for (let j = i + 1; j < Math.min(i + 8, lines.length); j += 1) {\n if (/^#{2,4}\\s/.test(lines[j]!) || bulletEndpointRe.test(lines[j]!)) break;\n const pm = postureRe.exec(lines[j]!);\n if (pm) { ep.posture = pm[1]!.toLowerCase(); break; }\n }\n }\n endpoints.push(ep);\n }\n if (endpoints.length === 0) {\n return [{\n id: \"auth-posture-no-endpoints-parsed\",\n severity: \"warning\",\n message: `Could not parse any endpoint declarations from ${apiFeaturesPath}. Expected ## /api/<resource> headers.`,\n files: apiFeaturesPath ? [apiFeaturesPath] : [],\n }];\n }\n // Endpoints missing posture declaration\n const missingPosture = endpoints.filter((e) => e.posture === null);\n for (const ep of missingPosture) {\n issues.push({\n id: \"auth-posture-undeclared\",\n severity: \"error\",\n message: `Endpoint ${ep.method ?? \"\"} ${ep.path} in ${apiFeaturesPath} has no auth-posture declaration. Add \\`auth-posture: <public-read|authenticated-read|authenticated-write|owner-only|admin-only>\\` so the runtime gate can verify the route's middleware matches.`.trim(),\n files: apiFeaturesPath ? [apiFeaturesPath] : [],\n });\n }\n // Validate route file middleware against declared posture. Only check route\n // files within the changedFiles set OR known under app/api (so we don't pay\n // for full repo walks on unrelated tasks).\n const routeFiles = manifest.changedFiles.filter((f) => /(?:^|\\/)(?:app|src)\\/api\\/.*\\/route\\.ts$/.test(f));\n for (const file of routeFiles) {\n const content = await readWorkspaceFile(workspace, file);\n if (!content) continue;\n // Extract path from filename: app/api/cases/route.ts → /api/cases\n const pathMatch = /\\/api\\/([^/]+(?:\\/\\[?[^\\]]+\\]?)*?)\\/route\\.ts$/.exec(file);\n if (!pathMatch) continue;\n const routePath = `/api/${pathMatch[1]!.replace(/\\[(\\w+)\\]/g, \"{$1}\")}`;\n const ep = endpoints.find((e) => normalizeApiPath(e.path) === normalizeApiPath(routePath));\n if (!ep || !ep.posture) continue;\n const usesAuth = /\\bwithAuth\\b/.test(content);\n const usesOwnership = /userId|ownerId|req\\.user|ctx\\.userId/.test(content);\n if (ep.posture === \"public-read\") {\n // Should NOT use withAuth (or only on POST/write paths). Soft warning.\n if (usesAuth) {\n issues.push({\n id: \"auth-posture-public-read-with-auth\",\n severity: \"warning\",\n message: `Route ${routePath} declared public-read in api_features.md but file uses withAuth. Either remove withAuth or update the contract.`,\n files: [file],\n });\n }\n } else if (ep.posture === \"authenticated-read\" || ep.posture === \"authenticated-write\") {\n if (!usesAuth) {\n issues.push({\n id: \"auth-posture-missing-withauth\",\n severity: \"error\",\n message: `Route ${routePath} declared ${ep.posture} but file does not include withAuth middleware. Wrap the handler: e.g. withSecurityHeaders(withCors(withErrorHandler(withAuth(handler)))).`,\n files: [file],\n });\n }\n } else if (ep.posture === \"owner-only\") {\n if (!usesAuth) {\n issues.push({\n id: \"auth-posture-owner-only-missing-withauth\",\n severity: \"error\",\n message: `Route ${routePath} declared owner-only but file does not include withAuth. Owner-only routes MUST require auth + check req.user.userId === resource.userId.`,\n files: [file],\n });\n } else if (!usesOwnership) {\n issues.push({\n id: \"auth-posture-owner-only-missing-ownership-check\",\n severity: \"error\",\n message: `Route ${routePath} declared owner-only and uses withAuth but does not appear to filter by userId/ownerId. Add a where: { userId: ctx.userId } scope so users can only see their own resources.`,\n files: [file],\n });\n }\n } else if (ep.posture === \"admin-only\") {\n if (!usesAuth || !/\\b(admin|isAdmin|role\\s*==?=?\\s*['\\\"]admin)\\b/.test(content)) {\n issues.push({\n id: \"auth-posture-admin-only-missing-check\",\n severity: \"error\",\n message: `Route ${routePath} declared admin-only but file does not include both withAuth and an admin role check.`,\n files: [file],\n });\n }\n }\n }\n return issues;\n}\n\nfunction normalizeApiPath(p: string): string {\n // Normalize {id} vs [id] vs :id parameter syntax, strip optional /api prefix,\n // and trim trailing slash. Contract bullets often write `/cases` while route\n // files live at `/api/cases/route.ts` — treat them as equivalent.\n return p\n .replace(/\\[(\\w+)\\]/g, \"{$1}\")\n .replace(/:(\\w+)/g, \"{$1}\")\n .replace(/^\\/api(?=\\/)/, \"\")\n .replace(/\\/+$/, \"\")\n .toLowerCase();\n}\n\nexport const backendAuthPostureValidator: Validator = {\n id: \"task.backendAuthPosture\",\n async run(workspace, manifest, runContext) {\n // Only fires for backend foundation/auth/feature tasks where api_features.md\n // is the contract source. Not for client/script tasks.\n if (!/\\/(?:backend)(?:\\/|$)/.test(workspace)) return [];\n const text = taskText(runContext);\n if (!/\\b(foundation|fundações|auth|api|endpoint|route|feature)\\b/i.test(text)) return [];\n return await validateBackendAuthPosture(workspace, manifest);\n },\n };\n\nexport const brandFidelityValidator: Validator = {\n id: \"task.brandFidelity\",\n // Brand-fidelity check for client UI work. Catches the class of issue where\n // a feature screen embeds an inline hex code or default font instead of\n // referencing brand tokens. brand.md (at repo root) is the authoritative\n // source of brand colors/fonts; tokens in Colors.swift/Theme.kt must match;\n // feature screens must reference the tokens, never inline literals.\n //\n // Prior audit: feature screens used MaterialTheme defaults\n // and inline Color(0xFF...) calls instead of brand-token references.\n async run(workspace, manifest, runContext) {\n const platform = inferPrimaryPlatform(workspace);\n if (platform !== \"ios\" && platform !== \"android\" && platform !== \"macos\") return [];\n const text = taskText(runContext);\n // Only fires for feature/* and polish/* tasks — not foundation (which is\n // where tokens are first declared, hex codes are expected there).\n if (!/\\b(feature|polish|tela|screen|view|paywall)\\b/i.test(text)) return [];\n const issues: ValidationIssue[] = [];\n // Patterns: Color(hex: \"#RRGGBB\"), Color(0xFFRRGGBB), Color.rgb(255,...),\n // bare \"#RRGGBB\" string literal, raw 0xFFRRGGBB literal in Compose code.\n const HEX_RE = /(?:Color\\s*\\(\\s*hex:\\s*\"#?[0-9A-Fa-f]{6,8}\"|Color\\s*\\(\\s*0x[0-9A-Fa-f]{6,8}|\"#[0-9A-Fa-f]{6,8}\"|\\b0x[FfAa]{2}[0-9A-Fa-f]{6}\\b)/;\n const FEATURE_LIKE = /(?:Feature|Screen|View|Composable|Paywall|Dashboard)\\.(?:swift|kt)$/i;\n for (const file of manifest.changedFiles) {\n // Skip token files / theme files — hex codes belong there\n if (/(?:Colors|Theme|ColorScheme|Typography|Tokens|Palette|BrandedComponents)\\.(?:swift|kt)$/i.test(file)) continue;\n // Only check feature-like files\n if (!FEATURE_LIKE.test(file) && !/\\/(?:features|ui)\\//i.test(file)) continue;\n const content = await readWorkspaceFile(workspace, file);\n if (!content) continue;\n if (HEX_RE.test(content)) {\n issues.push({\n id: \"brand-fidelity-inline-hex\",\n severity: \"error\",\n message: `Feature/screen file ${file} contains an inline hex color literal. Move colors to the token file (Colors.swift / Theme.kt) and reference them as Theme.<token> / MaterialTheme.colorScheme.<token>. Hex codes belong only in the token file, populated from brand.md.`,\n files: [file],\n });\n }\n }\n return issues;\n },\n };\n\nexport const toneOfVoiceValidator: Validator = {\n id: \"task.toneOfVoice\",\n // Catches generic UI copy on feature screens when brand.md declares a specific\n // tone of voice. Heuristic: feature screens with literal \"Loading...\", \"No items\",\n // \"Error\" without brand-voiced alternatives. Brand.md must be present at repo root\n // (or one level up); we read its tone-of-voice section to scope the check.\n async run(workspace, manifest, runContext) {\n const platform = inferPrimaryPlatform(workspace);\n if (platform !== \"ios\" && platform !== \"android\" && platform !== \"macos\") return [];\n const text = taskText(runContext);\n if (!/\\b(feature|polish|tela|screen|paywall)\\b/i.test(text)) return [];\n\n const brandMdContent = (await readWorkspaceFile(workspace, \"../brand.md\")) || (await readWorkspaceFile(workspace, \"brand.md\"));\n if (!brandMdContent) return []; // No brand.md → can't enforce tone\n\n // Detect declared tone — look for keywords in the tone section\n const lower = brandMdContent.toLowerCase();\n const isFormal = /(?:autoritário|profissional|sóbrio|sofisticado|direto|formal|authoritative|professional)/i.test(lower);\n const isPlayful = /(?:divertido|jovial|amigável|playful|friendly|casual)/i.test(lower);\n // If neither signal is strong, skip — we don't have an opinion to enforce\n if (!isFormal && !isPlayful) return [];\n\n const issues: ValidationIssue[] = [];\n const GENERIC_COPY = [\n \"\\\"Loading...\\\"\",\n \"\\\"Loading\\\\.\\\\.\\\\.\\\"\",\n \"\\\"Carregando\\\\.\\\\.\\\\.\\\"\",\n \"\\\"No items\\\"\",\n \"\\\"Nenhum item\\\"\",\n \"\\\"Error\\\"\",\n \"\\\"Erro\\\"\",\n \"\\\"Try again\\\"\",\n \"\\\"Tente novamente\\\"\",\n ];\n const GENERIC_RE = new RegExp(`(?:${GENERIC_COPY.join(\"|\")})`);\n const FEATURE_LIKE = /(?:Feature|Screen|View|Composable|Paywall|Dashboard)\\.(?:swift|kt)$/i;\n for (const file of manifest.changedFiles) {\n if (!FEATURE_LIKE.test(file) && !/\\/(?:features|ui)\\//i.test(file)) continue;\n const content = await readWorkspaceFile(workspace, file);\n if (!content) continue;\n if (GENERIC_RE.test(content)) {\n issues.push({\n id: \"tone-of-voice-generic-copy\",\n severity: \"warning\",\n message: `Feature screen ${file} contains generic UI copy (\"Loading...\", \"Error\", \"No items\") while brand.md declares a ${isFormal ? \"formal/authoritative\" : \"playful\"} tone of voice. Replace with brand-voiced strings (e.g. for legal apps: \"Buscando jurisprudência…\" instead of \"Loading…\", \"Nenhuma decisão encontrada para esses critérios\" instead of \"No items\").`,\n files: [file],\n });\n }\n }\n return issues;\n },\n };\n\nexport const accessibilityValidator: Validator = {\n id: \"task.accessibility\",\n // Catches missing accessibilityLabel on Image / Icon in feature screens. Won't\n // hold a screen back from shipping but surfaces the gap so the polish step can\n // sweep them. Severity warning.\n async run(workspace, manifest, runContext) {\n const platform = inferPrimaryPlatform(workspace);\n if (platform !== \"ios\" && platform !== \"android\" && platform !== \"macos\") return [];\n const text = taskText(runContext);\n if (!/\\b(feature|polish|tela|screen|paywall)\\b/i.test(text)) return [];\n\n const issues: ValidationIssue[] = [];\n const FEATURE_LIKE = /(?:Feature|Screen|View|Composable|Paywall|Dashboard)\\.(?:swift|kt)$/i;\n for (const file of manifest.changedFiles) {\n if (!FEATURE_LIKE.test(file) && !/\\/(?:features|ui)\\//i.test(file)) continue;\n const content = await readWorkspaceFile(workspace, file);\n if (!content) continue;\n // iOS: SwiftUI Image without .accessibilityLabel within ~5 lines, or\n // Image(systemName:) used as a button without a Button wrapper.\n if (platform === \"ios\" || platform === \"macos\") {\n // Image(systemName: \"...\") not followed within 4 lines by accessibilityLabel\n // and not wrapped in a Label/Text-bearing context.\n const lines = content.split(/\\r?\\n/);\n for (let i = 0; i < lines.length; i += 1) {\n if (!/Image\\s*\\(\\s*systemName\\s*:/.test(lines[i]!)) continue;\n const window = lines.slice(i, Math.min(i + 5, lines.length)).join(\"\\n\");\n if (/\\b(?:accessibilityLabel|accessibilityHidden|Label\\s*\\()/i.test(window)) continue;\n // Also okay if the Image is decorative — flagged via `// decorative`\n if (/\\/\\/\\s*decorative/i.test(window)) continue;\n issues.push({\n id: \"a11y-image-missing-label\",\n severity: \"warning\",\n message: `${file}:${i + 1} — Image(systemName:) has no accessibilityLabel within 5 lines. Add .accessibilityLabel(\"…\") for VoiceOver, or .accessibilityHidden(true) if purely decorative.`,\n files: [file],\n });\n break; // one issue per file is enough\n }\n }\n // Android: Icon(...) with contentDescription = null in non-decorative use\n if (platform === \"android\") {\n // contentDescription = null — okay only when paired with adjacent Text\n // for an iconified label. Flag plain Icon(...) buttons with null cd.\n const lines = content.split(/\\r?\\n/);\n for (let i = 0; i < lines.length; i += 1) {\n if (!/Icon\\s*\\(/.test(lines[i]!)) continue;\n const window = lines.slice(i, Math.min(i + 8, lines.length)).join(\"\\n\");\n if (!/contentDescription\\s*=\\s*null/.test(window)) continue;\n // Skip if there's a Text() in the same window (the Text labels it)\n if (/\\bText\\s*\\(/.test(window)) continue;\n issues.push({\n id: \"a11y-icon-missing-content-description\",\n severity: \"warning\",\n message: `${file}:${i + 1} — Icon(...) has contentDescription = null without an adjacent Text label. Add a contentDescription for TalkBack, or pair it with a sibling Text.`,\n files: [file],\n });\n break;\n }\n }\n }\n return issues;\n },\n };\n\nexport const platformIsolationValidator: Validator = {\n id: \"core.platform.isolation\",\n // Caught in a prior drain: an iOS feature step's run committed\n // 7 Android files (and vice-versa) because the agent saw the multi-platform\n // brief and used run_shell to write into ../android/. Each step runs against\n // a single platform's workspace; writes outside that platform's directory\n // contaminate commit attribution and can race with the other platform's queue.\n run(workspace, manifest) {\n const platform = inferPrimaryPlatform(workspace);\n if (platform === \"unknown\") return [];\n const SIBLING_PLATFORM_DIRS = [\"ios/\", \"macos/\", \"android/\", \"backend/\", \"web/\", \"script/\", \"landing/\"];\n const offenders: string[] = [];\n for (const file of manifest.changedFiles) {\n const lower = file.toLowerCase();\n for (const dir of SIBLING_PLATFORM_DIRS) {\n // Skip the active platform's own dir prefix\n if (dir === `${platform}/`) continue;\n if (lower.startsWith(dir)) { offenders.push(file); break; }\n }\n }\n if (offenders.length === 0) return [];\n return [{\n id: \"core-platform-isolation-violated\",\n severity: \"error\",\n message: `This is a ${platform} step. Files were modified in sibling platform directories: ${offenders.slice(0, 5).join(\", \")}${offenders.length > 5 ? ` (+${offenders.length - 5} more)` : \"\"}. Each step runs one platform; the orchestrator picks up other platforms in their own runs. Move these changes to a separate ${offenders[0]!.split(\"/\")[0]} step or revert them.`,\n files: offenders,\n }];\n },\n };\n\nexport const deployShapeValidator: Validator = {\n id: \"task.deployShape\",\n // Static-analyzes Dockerfile + GitHub Actions workflow files for known\n // deploy-time foot-guns. The forbidden-pattern gates already catch some\n // (prisma db push, || true, /tmp redirects); this validator covers the\n // structural checks that need cross-line / cross-file context.\n //\n // Prior incident: Dockerfile copied package.json before\n // prisma/, breaking the postinstall hook. Caught only by failed GitHub\n // Actions build — but the static signature is detectable.\n async run(workspace) {\n const fs = await import(\"fs/promises\");\n const path = await import(\"path\");\n const issues: ValidationIssue[] = [];\n\n const dockerfilePath = path.join(workspace, \"Dockerfile\");\n let dockerfile = \"\";\n try { dockerfile = await fs.readFile(dockerfilePath, \"utf8\"); } catch { /* no Dockerfile in this workspace */ }\n\n if (dockerfile) {\n // 1. CMD must run prisma migrate deploy synchronously, not in a\n // background subshell.\n const cmdLine = dockerfile.split(/\\r?\\n/).find((l) => /^\\s*CMD\\b/.test(l)) ?? \"\";\n if (cmdLine && /\\(\\s*npx[^)]*prisma[^)]*\\)\\s*&/.test(cmdLine)) {\n issues.push({\n id: \"task-deploy-shape-async-prisma-on-boot\",\n severity: \"error\",\n message: \"Dockerfile CMD runs prisma migrate/push in a background subshell (`( ... ) &`). Schema sync must complete BEFORE `npm start` so the container exits non-zero on schema drift instead of serving a half-broken backend.\",\n files: [\"Dockerfile\"],\n });\n }\n // 2. CMD must guard DATABASE_URL — empty/missing should refuse to start.\n if (cmdLine && /CMD\\s/.test(cmdLine) && !/DATABASE_URL/.test(dockerfile)) {\n issues.push({\n id: \"task-deploy-shape-no-database-url-guard\",\n severity: \"warning\",\n message: \"Dockerfile CMD doesn't reference DATABASE_URL. Production boot should refuse to start when DATABASE_URL is missing, instead of serving a backend that 503s every request.\",\n files: [\"Dockerfile\"],\n });\n }\n // 3. Recommend versioned migrations.\n if (/\\bprisma\\s+db\\s+push\\b/.test(dockerfile)) {\n issues.push({\n id: \"task-deploy-shape-uses-db-push\",\n severity: \"error\",\n message: \"Production boot uses `prisma db push` (declarative diff). Switch to `prisma migrate deploy` and ship migration files under prisma/migrations/. db push can drop tables silently and leaves no audit trail.\",\n files: [\"Dockerfile\"],\n });\n }\n }\n\n // 4. GitHub Actions workflow shouldn't bypass test/lint gates.\n const ghWorkflowDir = path.join(workspace, \".github\", \"workflows\");\n try {\n const files = await fs.readdir(ghWorkflowDir);\n for (const f of files) {\n if (!/\\.ya?ml$/.test(f)) continue;\n const content = await fs.readFile(path.join(ghWorkflowDir, f), \"utf8\");\n if (/--no-verify\\b/.test(content) || /SKIP_TESTS/.test(content)) {\n issues.push({\n id: \"task-deploy-shape-tests-bypassed\",\n severity: \"error\",\n message: `Workflow .github/workflows/${f} bypasses tests or commit hooks (--no-verify or SKIP_TESTS). Production deploys must run the full test suite.`,\n files: [`.github/workflows/${f}`],\n });\n }\n }\n } catch { /* no workflows dir */ }\n\n return issues;\n },\n };\n\nexport const externalApiContractValidator: Validator = {\n id: \"task.externalApiContract\",\n // Lightweight static checks that catch known wire-format mismatches with\n // third-party APIs. Not a substitute for a real integration test, but\n // catches the most common copy-paste-from-LLM bug shapes.\n //\n // Prior incident: lib/email.ts passed FROM_EMAIL whole\n // (RFC-822 form \"Name <addr@host>\") to Brevo's sender.email field, which\n // requires a bare address. Brevo rejected with 400; route returned 500.\n async run(workspace, manifest) {\n const fs = await import(\"fs/promises\");\n const path = await import(\"path\");\n const issues: ValidationIssue[] = [];\n\n // Only inspect files actually changed in this run — keeps validator\n // O(changes) instead of O(repo).\n const candidateFiles = manifest.changedFiles.filter((f) =>\n /\\.(?:ts|tsx|js|mjs)$/.test(f) &&\n /(?:email|brevo|sendgrid|mailgun|resend|notification)/i.test(f),\n );\n for (const rel of candidateFiles) {\n let content = \"\";\n try { content = await fs.readFile(path.join(workspace, rel), \"utf8\"); }\n catch { continue; }\n\n // Brevo / Sendgrid / Mailgun all want sender.email to be a bare address.\n // If the code passes process.env.FROM_EMAIL (or a `fromEmail` var that\n // holds it) directly into a `sender.email` / `from.email` JSON field\n // without first stripping the RFC-822 wrapper, fire.\n const passesRawFromEmail = /(?:from|sender)\\s*:\\s*\\{[^}]*\\bemail\\s*:\\s*(?:fromEmail|process\\.env\\.FROM_EMAIL)\\b/.test(content);\n const hasRfcParser = /<\\s*\\(\\?\\?\\)?\\[\\^<>\\\\s\\]\\+@\\[\\^<>\\\\s\\]\\+|rfcMatch|parseAddress|<.*@.*>.*\\.exec/.test(content);\n if (passesRawFromEmail && !hasRfcParser) {\n issues.push({\n id: \"task-external-api-contract-from-email-rfc822\",\n severity: \"error\",\n message: `${rel} passes FROM_EMAIL (an RFC-822 string like \"Name <a@b>\") directly to a transactional-email provider's sender.email field. Brevo/Sendgrid/Mailgun all reject this with invalid_parameter. Parse FROM_EMAIL into name + email before sending — see lib/email.ts parser pattern.`,\n files: [rel],\n });\n }\n }\n\n return issues;\n },\n };\n","import type { TanyaRunContext } from \"../../context/runContext\";\nimport { scanForbiddenPatterns } from \"../forbiddenPatterns\";\nimport {\n coreValidators,\n constraintText,\n hasChanged,\n inferPrimaryPlatform,\n isAndroidPlatformTask,\n isAppIconTask,\n isApplePlatformTask,\n taskText,\n validateApiClient,\n validateAuthSession,\n validateBackendHealthApi,\n validateBackendSetupEnvironment,\n validateRevenueCat,\n validateSetupEnvironment,\n type ValidationIssue,\n type ValidationManifest,\n type ValidationSummary,\n type Validator,\n} from \"./core\";\nimport {\n validateAppleAppIcon,\n validateIosFoundation,\n validateIosOnboarding,\n validateIosSplash,\n} from \"./apple\";\nimport {\n validateAndroidAppIcon,\n validateAndroidBaseLayout,\n validateAndroidFoundation,\n validateAndroidOnboarding,\n validateAndroidSplash,\n} from \"./android\";\nimport { validateGoBackendAuthQuality, validateGoBackendConfigEnvConsistency } from \"./go\";\nimport { schemaMigrationValidator } from \"./prisma\";\nimport {\n accessibilityValidator,\n backendAuthPostureValidator,\n brandFidelityValidator,\n deployShapeValidator,\n externalApiContractValidator,\n platformIsolationValidator,\n toneOfVoiceValidator,\n} from \"./security\";\n\nexport type { ValidationIssue, ValidationSummary } from \"./core\";\n\nconst taskValidators: Validator[] = [\n {\n id: \"task.setup.environment\",\n run(workspace, manifest, runContext) {\n const text = taskText(runContext);\n return /\\b(setup|environment|fastlane|swiftlint|gradle|ktlint)\\b/.test(text)\n ? validateSetupEnvironment(workspace, manifest, runContext)\n : [];\n },\n },\n {\n id: \"task.splash.ios\",\n run(workspace, manifest, runContext) {\n if (/\\/(?:android|backend|landing|web)(?:\\/|$)/.test(workspace) && !/\\/(?:ios|macos)(?:\\/|$)/.test(workspace)) return [];\n const text = taskText(runContext);\n return /\\bsplash\\b/.test(text) && /\\bios\\b/.test(text) ? validateIosSplash(workspace, manifest, runContext) : [];\n },\n },\n {\n id: \"task.splash.android\",\n run(workspace, manifest, runContext) {\n // Only EXCLUDE when workspace explicitly indicates a different platform.\n // Empty/test/temp workspaces should fall through to text-based detection.\n if (/\\/(?:ios|macos|backend|landing|web)(?:\\/|$)/.test(workspace) && !/\\/android(?:\\/|$)/.test(workspace)) return [];\n const text = taskText(runContext);\n return /\\bsplash\\b/.test(text) && /\\bandroid\\b/.test(text) ? validateAndroidSplash(workspace, manifest) : [];\n },\n },\n {\n id: \"task.onboarding.ios\",\n run(workspace, manifest, runContext) {\n if (/\\/(?:android|backend|landing|web)(?:\\/|$)/.test(workspace) && !/\\/(?:ios|macos)(?:\\/|$)/.test(workspace)) return [];\n const text = taskText(runContext);\n return /\\bonboarding\\b/.test(text) && /\\bios\\b/.test(text) ? validateIosOnboarding(workspace, manifest) : [];\n },\n },\n {\n id: \"task.onboarding.android\",\n run(workspace, manifest, runContext) {\n // Only EXCLUDE when workspace explicitly indicates a different platform.\n // Empty/test/temp workspaces should fall through to text-based detection.\n if (/\\/(?:ios|macos|backend|landing|web)(?:\\/|$)/.test(workspace) && !/\\/android(?:\\/|$)/.test(workspace)) return [];\n const text = taskText(runContext);\n return /\\bonboarding\\b/.test(text) && /\\bandroid\\b/.test(text) ? validateAndroidOnboarding(workspace, manifest) : [];\n },\n },\n {\n id: \"task.appIcon.apple\",\n run(workspace, manifest, runContext) {\n if (/\\/(?:android|backend|landing|web)(?:\\/|$)/.test(workspace) && !/\\/(?:ios|macos)(?:\\/|$)/.test(workspace)) return [];\n const text = taskText(runContext);\n const fullText = constraintText(runContext);\n const touchedAppleIcon = hasChanged(manifest, /(?:^|\\/)AppIcon\\.appiconset(?:\\/|$)/);\n return (isAppIconTask(text) || (touchedAppleIcon && isAppIconTask(fullText))) &&\n (isApplePlatformTask(text) || touchedAppleIcon)\n ? validateAppleAppIcon(workspace, manifest, runContext)\n : [];\n },\n },\n {\n id: \"task.appIcon.android\",\n run(workspace, manifest, runContext) {\n // Only EXCLUDE when workspace explicitly indicates a different platform.\n // Empty/test/temp workspaces should fall through to text-based detection.\n if (/\\/(?:ios|macos|backend|landing|web)(?:\\/|$)/.test(workspace) && !/\\/android(?:\\/|$)/.test(workspace)) return [];\n const text = taskText(runContext);\n const fullText = constraintText(runContext);\n const touchedAndroidIcon = hasChanged(manifest, /(?:^|\\/)res\\/mipmap-[^/]+\\/(?:ic_launcher|launcher).*\\.(?:png|xml|webp)$/) ||\n hasChanged(manifest, /(?:^|\\/)AndroidManifest\\.xml$/);\n return (isAppIconTask(text) || (touchedAndroidIcon && isAppIconTask(fullText))) &&\n (isAndroidPlatformTask(text) || touchedAndroidIcon)\n ? validateAndroidAppIcon(workspace, manifest)\n : [];\n },\n },\n {\n id: \"task.baseLayout.android\",\n run(workspace, manifest, runContext) {\n // Workspace-platform gate: this validator is Android-specific and must\n // not fire on iOS or backend workspaces, even if the prompt text mentions\n // \"android\" in cross-platform brand or architecture sections.\n // Only EXCLUDE when workspace explicitly indicates a different platform.\n // Empty/test/temp workspaces should fall through to text-based detection.\n if (/\\/(?:ios|macos|backend|landing|web)(?:\\/|$)/.test(workspace) && !/\\/android(?:\\/|$)/.test(workspace)) return [];\n const text = taskText(runContext);\n const fullText = constraintText(runContext);\n const touchedAndroidBaseLayout = hasChanged(manifest, /(?:^|\\/)app\\/src\\/main\\/java\\/.*(?:navigation|ui)\\/.*\\.kt$/);\n return (/\\bbase layout\\b|\\blayout base\\b|\\bplaceholder screens per feature\\b|\\btelas placeholder por feature\\b/.test(fullText) ||\n (touchedAndroidBaseLayout && /\\bandroid\\b/.test(text))) &&\n /\\bandroid\\b/.test(fullText)\n ? validateAndroidBaseLayout(workspace, manifest, runContext)\n : [];\n },\n },\n {\n id: \"task.foundation.android\",\n run(workspace, manifest, runContext) {\n // Only EXCLUDE when workspace explicitly indicates a different platform.\n // Empty/test/temp workspaces should fall through to text-based detection.\n if (/\\/(?:ios|macos|backend|landing|web)(?:\\/|$)/.test(workspace) && !/\\/android(?:\\/|$)/.test(workspace)) return [];\n const text = taskText(runContext);\n const fullText = constraintText(runContext);\n if (/\\bbase layout\\b|\\blayout base\\b|\\bplaceholder screens per feature\\b|\\btelas placeholder por feature\\b/.test(fullText)) return [];\n const touchedAndroidFoundation = hasChanged(manifest, /(?:^|\\/)app\\/src\\/main\\/java\\/.*(?:data|navigation|ui\\/theme|ui\\/components)\\/.*\\.kt$/) ||\n (manifest.artifactsRead ?? []).some((artifact) => /(?:^|\\/)android\\/(?:ThemeSystem|NavigationSetup|RoomSetup|FeatureScreenPatterns)\\.kt$/.test(artifact));\n return (/\\b(foundation|foundations|fundações)\\b/.test(text) && /\\bandroid\\b/.test(text)) || touchedAndroidFoundation\n ? validateAndroidFoundation(workspace, manifest)\n : [];\n },\n },\n {\n id: \"task.foundation.ios\",\n run(workspace, manifest, runContext) {\n if (/\\/(?:android|backend|landing|web)(?:\\/|$)/.test(workspace) && !/\\/(?:ios|macos)(?:\\/|$)/.test(workspace)) return [];\n const text = taskText(runContext);\n return /\\b(foundation|foundations|fundações)\\b/.test(text) && /\\bios\\b/.test(text)\n ? validateIosFoundation(workspace, manifest, runContext)\n : [];\n },\n },\n {\n id: \"task.apiClient\",\n run(workspace, manifest, runContext) {\n return /\\b(api client|api repository|repository|network layer|endpoint)\\b/.test(taskText(runContext))\n ? validateApiClient(workspace, manifest)\n : [];\n },\n },\n {\n id: \"task.authSession\",\n run(workspace, manifest, runContext) {\n return /\\b(auth|authentication|session|login|token|profile)\\b/.test(taskText(runContext))\n ? validateAuthSession(workspace, manifest)\n : [];\n },\n },\n {\n id: \"task.backendHealthApi\",\n run(workspace, manifest, runContext) {\n return /\\b(backend|api setup|health|route|endpoint|prisma)\\b/.test(taskText(runContext))\n ? validateBackendHealthApi(workspace, manifest, runContext)\n : [];\n },\n },\n {\n id: \"task.backendSetupEnvironment\",\n run(workspace, _manifest, runContext) {\n const text = constraintText(runContext);\n return /\\bset\\s+up\\s+backend\\b|\\bsetup\\s+backend\\b|\\bbackend\\s+(?:setup|environment)\\b|\\bsetup\\s+environment\\s+[-—]\\s+backend\\b/.test(text)\n ? validateBackendSetupEnvironment(workspace)\n : [];\n },\n },\n {\n id: \"task.goBackendConfigEnvConsistency\",\n run(workspace, _manifest, runContext) {\n const text = constraintText(runContext);\n const isBackendWorkspace = inferPrimaryPlatform(workspace) === \"backend\" || /(?:^|\\/)backend(?:\\/|$)/.test(workspace);\n const isGoBackendSetup = /\\binitialize\\s+go\\s+backend\\b|\\bgo-backend-init\\b|\\bgo\\s+backend\\s+(?:init|setup|skeleton)\\b|\\bbackend\\s+(?:setup|environment)\\b/i.test(text);\n return isBackendWorkspace && isGoBackendSetup\n ? validateGoBackendConfigEnvConsistency(workspace)\n : [];\n },\n },\n {\n id: \"task.goBackendAuthQuality\",\n run(workspace, manifest, runContext) {\n return validateGoBackendAuthQuality(workspace, manifest, runContext);\n },\n },\n {\n id: \"task.revenuecat\",\n run(workspace, manifest, runContext) {\n return /\\b(revenuecat|paywall|subscription|premium|entitlement|purchase|webhook)\\b/.test(taskText(runContext))\n ? validateRevenueCat(workspace, manifest)\n : [];\n },\n },\n backendAuthPostureValidator,\n brandFidelityValidator,\n toneOfVoiceValidator,\n accessibilityValidator,\n platformIsolationValidator,\n schemaMigrationValidator,\n deployShapeValidator,\n externalApiContractValidator,\n];\n\nexport async function validateCodingTask(\n workspace: string,\n manifest: ValidationManifest,\n runContext?: TanyaRunContext,\n options: { gateScanFiles?: string[] } = {},\n): Promise<ValidationSummary> {\n const validators = [...coreValidators, ...taskValidators];\n const issues: ValidationIssue[] = [];\n const firedValidatorIds: string[] = [];\n for (const validator of validators) {\n const validatorIssues = await validator.run(workspace, manifest, runContext);\n if (validatorIssues.length > 0) {\n firedValidatorIds.push(validator.id);\n issues.push(...validatorIssues);\n }\n }\n // Gate also runs against any files committed since the run started, even when\n // changedFiles is empty (verification-only attempt). Closes the blind spot where\n // a prior attempt's violation persisted in HEAD but the current attempt didn't\n // touch it. Caller passes \\`gateScanFiles = union(changedFiles, committedFiles)\\`.\n const filesForGate = (options.gateScanFiles && options.gateScanFiles.length > 0)\n ? options.gateScanFiles\n : manifest.changedFiles;\n const gateIssues = await scanForbiddenPatterns(workspace, filesForGate);\n if (gateIssues.length > 0) firedValidatorIds.push(\"forbidden-patterns-gate\");\n issues.push(...gateIssues);\n const primaryPlatform = inferPrimaryPlatform(workspace) ?? \"unknown\";\n return {\n passed: !issues.some((issue) => issue.severity === \"error\"),\n issues,\n firedValidatorIds,\n primaryPlatform,\n };\n}\n","import type { TanyaRunContext } from \"../context/runContext\";\nimport type { TanyaFinalManifest } from \"./runner\";\nimport { execFile } from \"node:child_process\";\nimport { readdir, realpath, stat } from \"node:fs/promises\";\nimport { relative, resolve } from \"node:path\";\nimport { promisify } from \"node:util\";\n\nconst execFileAsync = promisify(execFile);\n\nexport type GitSnapshot = {\n repoRoot: string;\n head: string | null;\n files: string[];\n};\n\nexport function normalizeGitPath(filePath: string): string {\n return filePath.trim().replace(/\\\\/g, \"/\").replace(/^\"|\"$/g, \"\");\n}\n\nexport function isIgnoredReportPath(filePath: string): boolean {\n return filePath === \"..\" ||\n filePath.startsWith(\"../\") ||\n /\\.(?:orig|bak|backup|tmp)$/i.test(filePath) ||\n /(?:^|\\/)DerivedData[^/]*(?:\\/|$)/.test(filePath) ||\n /(?:^|\\/)[^/]+\\.xcresult(?:\\/|$)/.test(filePath) ||\n /(?:^|\\/)ModuleCache\\.noindex(?:\\/|$)/.test(filePath) ||\n /(?:^|\\/)SDKStatCaches\\.noindex(?:\\/|$)/.test(filePath) ||\n /(?:^|\\/)\\.(?:tania|tanya|cosmo)\\//.test(filePath) ||\n filePath.startsWith(\".git/\") ||\n filePath.startsWith(\"node_modules/\") ||\n filePath.startsWith(\".next/\") ||\n filePath.startsWith(\"dist/\") ||\n filePath.startsWith(\"build/\");\n}\n\nfunction parsePorcelainPath(line: string): string | null {\n if (line.length < 4) return null;\n const rawPath = line.slice(3).trim();\n if (!rawPath) return null;\n const renameTarget = rawPath.includes(\" -> \") ? rawPath.split(\" -> \").pop() : rawPath;\n return renameTarget ? normalizeGitPath(renameTarget) : null;\n}\n\nexport function uniqueSorted(values: Iterable<string>): string[] {\n return [...new Set(values)].sort((a, b) => a.localeCompare(b));\n}\n\nexport async function listFilesRecursive(root: string, current = root, maxDepth = 10, depth = 0, visited = new Set<string>()): Promise<string[]> {\n const files: string[] = [];\n if (depth > maxDepth) return files;\n let currentRealPath: string;\n try {\n currentRealPath = await realpath(current);\n } catch {\n return files;\n }\n if (visited.has(currentRealPath)) return files;\n visited.add(currentRealPath);\n let entries;\n try {\n entries = await readdir(current, { withFileTypes: true });\n } catch {\n return files;\n }\n for (const entry of entries) {\n const fullPath = resolve(current, entry.name);\n if (entry.isDirectory()) {\n let fullRealPath: string;\n try {\n fullRealPath = await realpath(fullPath);\n } catch {\n continue;\n }\n if (visited.has(fullRealPath)) continue;\n files.push(...await listFilesRecursive(root, fullPath, maxDepth, depth + 1, visited));\n } else if (entry.isFile()) {\n files.push(normalizeGitPath(relative(root, fullPath)));\n }\n }\n return files;\n}\n\nexport async function pathIsGitTracked(workspace: string, relPath: string): Promise<boolean> {\n try {\n await execFileAsync(\"git\", [\"ls-files\", \"--error-unmatch\", relPath], {\n cwd: workspace,\n timeout: 5_000,\n maxBuffer: 1024 * 1024,\n });\n return true;\n } catch {\n return false;\n }\n}\n\nexport async function hasTrackedPathUnder(workspace: string, relPath: string): Promise<boolean> {\n try {\n const { stdout } = await execFileAsync(\"git\", [\"ls-files\", relPath], {\n cwd: workspace,\n timeout: 5_000,\n maxBuffer: 1024 * 1024,\n });\n return stdout.trim().length > 0;\n } catch {\n return false;\n }\n}\n\nexport async function captureGitSnapshot(workspace: string): Promise<GitSnapshot | null> {\n try {\n const { stdout: rootOut } = await execFileAsync(\"git\", [\"rev-parse\", \"--show-toplevel\"], {\n cwd: workspace,\n timeout: 5_000,\n maxBuffer: 1024 * 1024,\n });\n const repoRoot = rootOut.trim();\n const { stdout: statusOut } = await execFileAsync(\"git\", [\"status\", \"--porcelain=1\"], {\n cwd: repoRoot,\n timeout: 5_000,\n maxBuffer: 1024 * 1024,\n });\n let head: string | null = null;\n try {\n const { stdout: headOut } = await execFileAsync(\"git\", [\"rev-parse\", \"HEAD\"], {\n cwd: repoRoot,\n timeout: 5_000,\n maxBuffer: 1024 * 1024,\n });\n head = headOut.trim() || null;\n } catch {\n head = null;\n }\n const files: string[] = [];\n for (const filePath of statusOut\n .split(/\\r?\\n/)\n .map(parsePorcelainPath)\n .filter((pathValue): pathValue is string => !!pathValue && !isIgnoredReportPath(pathValue))) {\n const absolutePath = resolve(repoRoot, filePath);\n try {\n const fileStat = await stat(absolutePath);\n if (fileStat.isDirectory()) {\n const nestedFiles = await listFilesRecursive(absolutePath);\n files.push(...nestedFiles.map((nestedPath) => normalizeGitPath(`${filePath.replace(/\\/$/, \"\")}/${nestedPath}`)));\n continue;\n }\n } catch {\n // Keep the original porcelain path as fallback evidence.\n }\n files.push(filePath);\n }\n return {\n repoRoot,\n head,\n files: uniqueSorted(files.filter((filePath) => filePath && !isIgnoredReportPath(filePath))),\n };\n } catch {\n return null;\n }\n}\n\nfunction toWorkspaceReportPath(filePath: string, snapshot: GitSnapshot, workspace: string): string | null {\n const absPath = resolve(snapshot.repoRoot, filePath);\n const relPath = normalizeGitPath(relative(workspace, absPath));\n if (!relPath || relPath === \".\" || relPath.startsWith(\"../\") || relPath === \"..\") {\n return null;\n }\n return relPath;\n}\n\nexport async function changedFilesFromGit(before: GitSnapshot | null, workspace: string): Promise<string[]> {\n const after = await captureGitSnapshot(workspace);\n if (!after) return [];\n const beforeFiles = new Set(before?.files ?? []);\n const changed = after.files.filter((filePath) => !beforeFiles.has(filePath));\n\n if (before?.head && after.head && before.head !== after.head) {\n try {\n const { stdout } = await execFileAsync(\"git\", [\"diff\", \"--name-only\", before.head, after.head], {\n cwd: after.repoRoot,\n timeout: 5_000,\n maxBuffer: 1024 * 1024,\n });\n changed.push(\n ...stdout\n .split(/\\r?\\n/)\n .map(normalizeGitPath)\n .filter((filePath) => filePath && !isIgnoredReportPath(filePath)),\n );\n } catch {\n // The live tool-tracked file list still provides useful fallback evidence.\n }\n }\n\n return uniqueSorted(\n changed\n .map((filePath) => toWorkspaceReportPath(filePath, after, workspace))\n .filter((filePath): filePath is string => !!filePath && !isIgnoredReportPath(filePath)),\n );\n}\n\nexport async function committedFilesFromGit(before: GitSnapshot | null, after: GitSnapshot | null, workspace: string): Promise<string[]> {\n if (!before?.head || !after?.head || before.head === after.head) return [];\n try {\n const { stdout } = await execFileAsync(\"git\", [\"diff\", \"--name-only\", before.head, after.head], {\n cwd: after.repoRoot,\n timeout: 5_000,\n maxBuffer: 1024 * 1024,\n });\n return uniqueSorted(\n stdout\n .split(/\\r?\\n/)\n .map(normalizeGitPath)\n .filter((filePath) => filePath && !isIgnoredReportPath(filePath))\n .map((filePath) => toWorkspaceReportPath(filePath, after, workspace))\n .filter((filePath): filePath is string => !!filePath && !isIgnoredReportPath(filePath)),\n );\n } catch {\n return [];\n }\n}\n\nexport function uncommittedFilesSince(before: GitSnapshot | null, after: GitSnapshot | null, workspace: string): string[] {\n if (!after) return [];\n const beforeFiles = new Set(before?.files ?? []);\n return normalizeReportPathsForWorkspace(\n after.files.filter((filePath) => !beforeFiles.has(filePath)),\n after,\n workspace,\n );\n}\n\nexport function normalizeReportFiles(files: string[]): string[] {\n return uniqueSorted(files.map(normalizeGitPath).filter((filePath) => filePath && !isIgnoredReportPath(filePath)));\n}\n\nexport function normalizeReportPathsForWorkspace(files: string[], snapshot: GitSnapshot | null, workspace: string): string[] {\n if (!snapshot) return normalizeReportFiles(files);\n const workspacePrefix = normalizeGitPath(relative(snapshot.repoRoot, workspace));\n if (!workspacePrefix || workspacePrefix === \".\" || workspacePrefix.startsWith(\"../\") || workspacePrefix === \"..\") {\n return normalizeReportFiles(files);\n }\n return normalizeReportFiles(files.map((filePath) => {\n const normalized = normalizeGitPath(filePath);\n return normalized.startsWith(`${workspacePrefix}/`)\n ? normalized.slice(workspacePrefix.length + 1)\n : normalized;\n }));\n}\n\nfunction runContextBoolean(record: Record<string, unknown> | undefined, key: string): boolean {\n return record?.[key] === true;\n}\n\nfunction expectedReportIncludes(runContext: TanyaRunContext | undefined, key: string): boolean {\n const value = runContext?.expected_report?.[key];\n if (value === true) return true;\n if (Array.isArray(value)) return value.includes(key);\n if (typeof value === \"string\") return value.split(/[\\s,]+/).includes(key);\n return false;\n}\n\nexport function runContextRequiresCommit(runContext?: TanyaRunContext): boolean {\n return runContextBoolean(runContext?.metadata, \"requireCommit\") || expectedReportIncludes(runContext, \"commit\");\n}\n\nexport function commitStillRequired(manifest: TanyaFinalManifest, beforeGitSnapshot: GitSnapshot | null, runContext?: TanyaRunContext): boolean {\n if (!runContextRequiresCommit(runContext)) return false;\n if (manifest.changedFiles.length === 0) return false;\n if (manifest.uncommittedFiles.length > 0) return true;\n if (!beforeGitSnapshot?.head || !manifest.git.head) return false;\n return manifest.git.head === beforeGitSnapshot.head.slice(0, 7);\n}\n","import type { TanyaRunContext } from \"../context/runContext\";\nimport type { TanyaFinalManifest } from \"./runner\";\nimport type { ChildVerdict, ReasoningAnnotation } from \"./verifier/types\";\nimport { verifyFinalState, type VerifierShell } from \"./verifier\";\nimport { envValue } from \"../config/envCompat\";\nimport { fileTouchPathsFromArchive, readArchive } from \"../memory/runArchive\";\nimport { readReasoningArchive } from \"../memory/reasoningArchive\";\nimport { validateCodingTask, type ValidationSummary } from \"./validators\";\nimport {\n captureGitSnapshot,\n changedFilesFromGit,\n committedFilesFromGit,\n type GitSnapshot,\n isIgnoredReportPath,\n listFilesRecursive,\n normalizeReportFiles,\n normalizeReportPathsForWorkspace,\n pathIsGitTracked,\n runContextRequiresCommit,\n uncommittedFilesSince,\n uniqueSorted,\n} from \"./git\";\nimport { execFile } from \"node:child_process\";\nimport { existsSync } from \"node:fs\";\nimport { readdir, rm, stat } from \"node:fs/promises\";\nimport { resolve } from \"node:path\";\nimport { promisify } from \"node:util\";\n\nconst execFileAsync = promisify(execFile);\n\nexport function collectChangedFiles(existing: string[], next?: string[]): string[] {\n return [...new Set([...existing, ...(next ?? [])].filter((file) => !isIgnoredReportPath(file)))];\n}\n\nasync function cleanupGeneratedNoise(workspace: string): Promise<void> {\n const generatedFastlanePaths = [\n \"fastlane/README.md\",\n \"fastlane/report.xml\",\n \"fastlane/test_output\",\n ];\n try {\n const entries = await readdir(workspace, { withFileTypes: true });\n for (const entry of entries) {\n if (entry.isDirectory() && /^DerivedData(?:[-_].*)?$/i.test(entry.name)) {\n generatedFastlanePaths.push(entry.name);\n }\n if (entry.isDirectory() && /\\.xcresult$/i.test(entry.name)) {\n generatedFastlanePaths.push(entry.name);\n }\n }\n } catch {\n // Ignore cleanup discovery failures.\n }\n try {\n for (const relPath of await listFilesRecursive(workspace)) {\n if (/\\.(?:orig|bak|backup|tmp)$/i.test(relPath)) generatedFastlanePaths.push(relPath);\n }\n } catch {\n // Ignore recursive cleanup discovery failures.\n }\n for (const relPath of generatedFastlanePaths) {\n const absPath = resolve(workspace, relPath);\n if (!existsSync(absPath)) continue;\n if (await pathIsGitTracked(workspace, relPath)) continue;\n try {\n await rm(absPath, { recursive: true, force: true });\n } catch {\n // Cleanup is best-effort. The final manifest/report still filters generated noise.\n }\n }\n}\n\nasync function fileReportPathIsNotDirectory(workspace: string, filePath: string): Promise<boolean> {\n try {\n return !(await stat(resolve(workspace, filePath))).isDirectory();\n } catch {\n return true;\n }\n}\n\nasync function normalizeReportFileList(workspace: string, files: string[]): Promise<string[]> {\n const normalized = normalizeReportFiles(files);\n const keep = await Promise.all(normalized.map(async (filePath) => ({\n filePath,\n keep: await fileReportPathIsNotDirectory(workspace, filePath),\n })));\n return keep.filter((entry) => entry.keep).map((entry) => entry.filePath);\n}\n\nexport function isCodingTask(runContext?: TanyaRunContext): boolean {\n return runContext?.task?.kind === \"coding\" || Boolean(runContext?.expected_report);\n}\n\nfunction truthy(value: unknown): boolean {\n if (value === true) return true;\n if (typeof value !== \"string\") return false;\n return /^(1|true|yes|on)$/i.test(value.trim());\n}\n\nfunction verifierReasoningAnnotationsEnabled(runContext?: TanyaRunContext): boolean {\n return truthy(runContext?.metadata?.verboseVerifier) ||\n truthy(runContext?.metadata?.includeReasoningInVerifier) ||\n truthy(envValue(process.env, \"TANYA_VERIFIER_INCLUDE_REASONING\"));\n}\n\nfunction excerptReasoning(content: string): string {\n return content.replace(/\\s+/g, \" \").trim().slice(0, 280);\n}\n\nfunction buildReasoningAnnotations(params: {\n workspace: string;\n runId?: string;\n blockers: string[];\n runContext?: TanyaRunContext;\n}): ReasoningAnnotation[] {\n if (!params.runId || !verifierReasoningAnnotationsEnabled(params.runContext)) return [];\n const entries = readReasoningArchive(params.workspace, params.runId)\n .filter((entry) => !entry.evicted && entry.content.trim().length > 0)\n .slice(-3);\n if (entries.length === 0) return [];\n return entries.map((entry, index) => ({\n runId: entry.runId,\n ...(entry.turn !== undefined ? { turn: entry.turn } : {}),\n provider: entry.provider,\n model: entry.model,\n ...(params.blockers[index] ? { blocker: params.blockers[index] } : {}),\n excerpt: excerptReasoning(entry.content),\n confidence: \"advisory\",\n }));\n}\n\nexport function hasRequiredCodingReport(text: string): boolean {\n return /Verification:\\s*.+->/i.test(text)\n && (/Modified:\\s*/i.test(text) || /Verification-only:\\s*existing setup satisfied/i.test(text) || /Blocked?:/i.test(text));\n}\n\nfunction sourceArtifactPath(localPath: string, runContext?: TanyaRunContext): string {\n const match = runContext?.artifacts?.find((artifact) => artifact.path === localPath || artifact.sourcePath === localPath);\n if (match?.sourcePath) return match.sourcePath;\n if (localPath.startsWith(\".tania/artifacts/\")) return localPath.replace(/^\\.tania\\/artifacts\\//, \"artifacts/\");\n return localPath;\n}\n\nexport function buildFallbackCodingReport(\n changedFiles: string[],\n verificationLines: string[],\n toolErrorCount: number,\n artifactPaths: string[],\n createdArtifactPaths: string[],\n runContext?: TanyaRunContext,\n blockers: string[] = [],\n finalText = \"\",\n): string {\n const artifactLines = buildArtifactReportLines(\n { artifactsRead: artifactPaths.slice(0, 5), changedFiles },\n runContext,\n finalText,\n );\n const artifactCreatedLines = createdArtifactPaths.length > 0\n ? createdArtifactPaths.map((artifactPath) => `Artifact created: ${artifactPath} -> reusable artifact`)\n : [\"Artifact created: none\"];\n return [\n ...artifactLines,\n ...artifactCreatedLines,\n changedFiles.length === 0\n ? \"Verification-only: existing setup satisfied\"\n : changedFiles.map((filePath) => `Modified: ${filePath}`).join(\"\\n\"),\n verificationLines.length > 0\n ? verificationLines.join(\"\\n\")\n : \"Verification: not completed -> blocked before verification command was captured\",\n toolErrorCount > 0\n ? `Tool errors observed: ${toolErrorCount}`\n : \"Tool errors observed: 0\",\n blockers.length > 0 ? `Blocked: ${blockers.join(\"; \")}` : \"Blocked: none\",\n ].join(\"\\n\");\n}\n\nexport async function buildFinalManifest(params: {\n workspace: string;\n beforeGitSnapshot: GitSnapshot | null;\n changed: string[];\n verificationLines: string[];\n toolErrorCount: number;\n readArtifactPaths: string[];\n readContextPaths: string[];\n createdArtifactPaths: string[];\n blockers?: string[];\n childVerdicts?: ChildVerdict[];\n runContext?: TanyaRunContext | undefined;\n prompt?: string;\n runId?: string;\n verifierShell?: VerifierShell | undefined;\n terminationReason?: \"turn_budget_exhausted\" | string | undefined;\n}): Promise<TanyaFinalManifest> {\n await cleanupGeneratedNoise(params.workspace);\n const afterGitSnapshot = await captureGitSnapshot(params.workspace);\n const committedFiles = await committedFilesFromGit(params.beforeGitSnapshot, afterGitSnapshot, params.workspace);\n const uncommittedFiles = uncommittedFilesSince(params.beforeGitSnapshot, afterGitSnapshot, params.workspace);\n const liveChangedFiles = normalizeReportPathsForWorkspace(\n collectChangedFiles(params.changed, await changedFilesFromGit(params.beforeGitSnapshot, params.workspace)),\n afterGitSnapshot,\n params.workspace,\n );\n const reportSourceFiles = (committedFiles.length > 0 || uncommittedFiles.length > 0)\n ? uniqueSorted([...committedFiles, ...uncommittedFiles])\n : liveChangedFiles;\n const reportFiles = await normalizeReportFileList(params.workspace, reportSourceFiles);\n const childVerdicts = (params.childVerdicts ?? []).filter((verdict) => verdict.treatFailureAs !== \"ignore\");\n const childBlockers = childVerdicts\n .filter((verdict) => verdict.verdict === \"failed\" && verdict.treatFailureAs === \"blocker\")\n .map((verdict) => childVerdictMessage(verdict));\n const childWarnings = childVerdicts\n .filter((verdict) => verdict.verdict === \"failed\" && verdict.treatFailureAs === \"warning\")\n .map((verdict) => childVerdictMessage(verdict));\n const blockers = uniqueSorted([...(params.blockers ?? []), ...childBlockers]);\n const reasoningAnnotations = buildReasoningAnnotations({\n workspace: params.workspace,\n ...(params.runId !== undefined ? { runId: params.runId } : {}),\n blockers,\n ...(params.runContext !== undefined ? { runContext: params.runContext } : {}),\n });\n const manifest: TanyaFinalManifest = {\n schemaVersion: 1,\n changedFiles: reportFiles,\n uncommittedFiles: await normalizeReportFileList(params.workspace, uncommittedFiles),\n artifactsRead: uniqueSorted(params.readArtifactPaths.map((artifactPath) => sourceArtifactPath(artifactPath, params.runContext))),\n artifactsCreated: uniqueSorted(params.createdArtifactPaths),\n contextFilesRead: uniqueSorted(params.readContextPaths),\n verification: params.verificationLines.filter((line) => !isRecoveredVerificationFailure(line, params.verificationLines)),\n git: {\n root: afterGitSnapshot?.repoRoot ?? params.beforeGitSnapshot?.repoRoot ?? null,\n head: afterGitSnapshot?.head ? afterGitSnapshot.head.slice(0, 7) : params.beforeGitSnapshot?.head?.slice(0, 7) ?? null,\n },\n toolErrors: params.toolErrorCount,\n blockers,\n ...((params.childVerdicts ?? []).length > 0\n ? { childRunIds: uniqueSorted((params.childVerdicts ?? []).map((verdict) => verdict.subRunId)) }\n : {}),\n ...(childVerdicts.length > 0 ? { childVerdicts } : {}),\n ...(childWarnings.length > 0 ? { childWarnings: uniqueSorted(childWarnings) } : {}),\n ...(reasoningAnnotations.length > 0 ? { reasoningAnnotations } : {}),\n };\n if (isCodingTask(params.runContext)) {\n const validationRunContext = params.prompt\n ? {\n ...params.runContext,\n metadata: {\n ...(params.runContext?.metadata ?? {}),\n validationPrompt: params.prompt,\n },\n }\n : params.runContext;\n // Hand the forbidden-pattern gate the union of changedFiles + committedFiles so\n // it can catch violations introduced by a prior attempt that the current\n // verification-only run did not modify.\n const archivedTouchFiles = params.runId\n ? fileTouchPathsFromArchive(await readArchive(params.runId, { workspace: params.workspace }))\n : [];\n let gateScanFiles = uniqueSorted([...manifest.changedFiles, ...committedFiles, ...archivedTouchFiles]);\n // 2026-05-01 audit gap: in pure verification-only mode (agent confirmed\n // existing code without committing or modifying anything), the gate had\n // nothing to scan and missed pre-existing TODO stubs in security-critical\n // routes. Backfill with the security-critical path globs so the gate can\n // still reject existing violations the agent should have fixed.\n if (gateScanFiles.length === 0) {\n gateScanFiles = await listSecurityCriticalTrackedFiles(params.workspace);\n }\n manifest.validation = await validateCodingTask(params.workspace, manifest, validationRunContext, { gateScanFiles });\n const finalStateVerification = await verifyFinalState({\n workspace: params.workspace,\n runContext: params.runContext,\n prompt: params.prompt ?? \"\",\n shell: params.verifierShell,\n });\n manifest.finalStateVerification = finalStateVerification;\n if (finalStateVerification.authoritativePassed) {\n manifest.verification = reclassifyExploratoryFailuresAsRecovered(manifest.verification);\n manifest.blockers = manifest.blockers.filter((blocker) => !isExploratoryVerificationBlocker(blocker));\n }\n // Filter out blockers that match later-passing verification lines (stale failures).\n manifest.blockers = manifest.blockers.filter((blocker) => {\n if (!/^failed verification:/i.test(blocker)) return true;\n const blockerLine = blocker.replace(/^failed verification:\\s*/i, \"\");\n return !isRecoveredVerificationFailure(blockerLine, manifest.verification);\n });\n if (params.terminationReason === \"turn_budget_exhausted\" && finalStateVerification.authoritativePassed) {\n manifest.blockers = manifest.blockers.filter((blocker) =>\n !isLastFailedProbeVerificationBlocker(blocker, params.verificationLines)\n );\n }\n if (finalStateVerification.newBlockers.length > 0) {\n manifest.blockers = uniqueSorted([...manifest.blockers, ...finalStateVerification.newBlockers]);\n }\n }\n return manifest;\n}\n\n// Salvaged from F-fix.5+8 WIP — reclassifies exploratory verification\n// failures as \"recovered\" when the final-state verifier's authoritative\n// checks have passed. Lets the report show \"this build/test passed\" even\n// when intermediate probes failed during the run.\nfunction isRecoverableBootstrapAttempt(command: string): boolean {\n return /^\\s*(?:git\\s+(?:-C\\s+\\S+\\s+)?rm\\b|mkdir\\s+|sed\\s+-i\\b|cat\\s+>|go\\s+mod\\s+init\\b)/i.test(command);\n}\n\nfunction isRecoverableProbeCommand(command: string): boolean {\n return /^\\s*(?:cat|head|tail|sed\\s+-n|ls|find)\\b/i.test(command);\n}\n\nconst PROBE_COMMANDS = new Set([\n \"go vet\",\n \"go build\",\n \"go test\",\n \"grep\",\n \"rg\",\n \"ls\",\n \"cat\",\n \"head\",\n \"tail\",\n \"find\",\n]);\n\nfunction isProbeCommand(command: string): boolean {\n const localCommand = commandAfterLeadingCd(command);\n const [first = \"\", second = \"\"] = localCommand.trim().split(/\\s+/, 2);\n if (first === \"go\") return PROBE_COMMANDS.has(`go ${second}`);\n return PROBE_COMMANDS.has(first);\n}\n\nfunction isRecoverableGeneratorCommand(command: string): boolean {\n return /\\b(?:sqlc|go\\s+run\\s+github\\.com\\/sqlc-dev\\/sqlc\\/cmd\\/sqlc(?:@\\S+)?)\\s+generate\\b/i.test(command);\n}\n\nfunction isRecoverableToolInstallCommand(command: string): boolean {\n return /\\bgo\\s+install\\s+github\\.com\\/(?:sqlc-dev\\/sqlc\\/cmd\\/sqlc|pressly\\/goose\\/v3\\/cmd\\/goose)(?:@\\S+)?\\b/i.test(command);\n}\n\nfunction commandAfterLeadingCd(command: string): string {\n const match = command.match(/^\\s*cd\\s+((?:\"[^\"]+\")|(?:'[^']+')|(?:\\S+))\\s*&&\\s*([\\s\\S]+)$/);\n return (match?.[2] ?? command).trim();\n}\n\nfunction failedVerificationCommand(blocker: string): string | null {\n const raw = blocker\n .replace(/^failed verification:\\s*/i, \"\")\n .replace(/^Verification:\\s*/i, \"\");\n const match = raw.match(/^(.*?)\\s*->\\s*failed\\b/i);\n const command = (match?.[1] ?? raw).trim();\n return command.length > 0 ? command : null;\n}\n\nfunction verificationCommand(line: string): string | null {\n const raw = line\n .replace(/^failed verification:\\s*/i, \"\")\n .replace(/^Verification:\\s*/i, \"\");\n const match = raw.match(/^(.*?)\\s*->\\s*(?:failed|passed|recovered)\\b/i);\n const command = match?.[1]?.trim() ?? \"\";\n return command.length > 0 ? command : null;\n}\n\nfunction lastVerificationCommand(verificationLines: string[]): { command: string; failed: boolean } | null {\n for (let i = verificationLines.length - 1; i >= 0; i -= 1) {\n const line = verificationLines[i] ?? \"\";\n const command = verificationCommand(line);\n if (!command) continue;\n return { command, failed: /->\\s*failed\\b/i.test(line) };\n }\n return null;\n}\n\nfunction isLastFailedProbeVerificationBlocker(blocker: string, verificationLines: string[]): boolean {\n if (!/^failed verification:/i.test(blocker)) return false;\n const blockerCommand = failedVerificationCommand(blocker);\n if (!blockerCommand || !isProbeCommand(blockerCommand)) return false;\n const lastCommand = lastVerificationCommand(verificationLines);\n return Boolean(lastCommand?.failed && normalizeVerificationCommand(blockerCommand) === normalizeVerificationCommand(lastCommand.command));\n}\n\nfunction isExploratoryVerificationBlocker(blocker: string): boolean {\n if (!/^failed verification:/i.test(blocker)) return false;\n const command = failedVerificationCommand(blocker);\n if (!command) return false;\n const localCommand = commandAfterLeadingCd(command);\n return (\n isRecoverableBootstrapAttempt(localCommand) ||\n isRecoverableProbeCommand(localCommand) ||\n isRecoverableGeneratorCommand(localCommand) ||\n isRecoverableToolInstallCommand(localCommand)\n );\n}\n\nfunction reclassifyExploratoryFailuresAsRecovered(verificationLines: string[]): string[] {\n return verificationLines.map((line) => {\n if (!/->\\s*failed/i.test(line)) return line;\n const command = failedVerificationCommand(line);\n if (!command) return line;\n const localCommand = commandAfterLeadingCd(command);\n const recoverable =\n isRecoverableBootstrapAttempt(localCommand) ||\n isRecoverableProbeCommand(localCommand) ||\n isRecoverableGeneratorCommand(localCommand) ||\n isRecoverableToolInstallCommand(localCommand);\n if (!recoverable) return line;\n return line.replace(/->\\s*failed[^\\n]*/i, \"-> recovered (final-state verifier authoritative checks passed)\");\n });\n}\n\n// Path globs for files the gate should scan even on verification-only runs.\n// Kept narrow so we don't blow up cost on large repos: just route handlers\n// for auth/billing/webhooks/email/notifications and the matching mobile\n// session/auth/payment files. Project-level overrides in\n// .tania/forbidden-patterns.json `alwaysScanGlobs` (future).\nconst SECURITY_CRITICAL_PATH_PATTERNS: RegExp[] = [\n /(?:^|\\/)(?:app|src)\\/api\\/(?:auth|billing|webhooks|payment|email|notifications)\\/.*\\.(?:ts|tsx|js|mjs)$/i,\n /(?:^|\\/)routes\\/(?:auth|billing|webhooks|payment|email|notifications)\\/.*\\.(?:ts|tsx|js|mjs|py|rb|go)$/i,\n // Mobile auth/billing files where placeholders cause silent prod failures\n /(?:^|\\/)SessionStore\\.swift$/i,\n /(?:^|\\/)(?:APIClient|ApiClient|RevenueCatManager)\\.swift$/i,\n /(?:^|\\/)(?:AuthRepository|RevenueCatBilling)\\.kt$/i,\n /(?:^|\\/)values\\/strings\\.xml$/i,\n];\n\nasync function listSecurityCriticalTrackedFiles(workspace: string): Promise<string[]> {\n try {\n const { stdout } = await execFileAsync(\"git\", [\"ls-files\"], {\n cwd: workspace,\n timeout: 10_000,\n maxBuffer: 8 * 1024 * 1024,\n });\n const all = stdout.split(/\\r?\\n/).filter(Boolean);\n return all.filter((file) => SECURITY_CRITICAL_PATH_PATTERNS.some((pattern) => pattern.test(file)));\n } catch {\n return [];\n }\n}\n\ntype StructuredArtifactReuse = {\n artifact: string;\n targets: string[];\n};\n\ntype TanyaStructuredReport = {\n schemaVersion: 1;\n modified: string[];\n artifactsReused: StructuredArtifactReuse[];\n artifactsCreated: string[];\n verification: string[];\n manualChecks: string[];\n blocked: string[];\n blockers: string[];\n warnings: string[];\n validation: ValidationSummary;\n git: TanyaFinalManifest[\"git\"];\n metrics: {\n toolErrors: number;\n };\n};\n\nexport function normalizeVerificationCommand(line: string): string {\n return line\n .replace(/^Verification:\\s*/i, \"\")\n .replace(/\\s*->\\s*(passed|failed|BUILD SUCCESSFUL|BUILD FAILED|blocked|.+)$/i, \"\")\n .replace(/\\s+2>&1\\b/g, \"\")\n .replace(/\\s+/g, \" \")\n .trim();\n}\n\nfunction successfulVerificationCommands(text: string): Set<string> {\n const commands = new Set<string>();\n for (const line of text.split(/\\r?\\n/)) {\n if (!/^Verification:\\s*/i.test(line)) continue;\n if (!/->\\s*(passed|BUILD SUCCESSFUL)\\b/i.test(line)) continue;\n const command = normalizeVerificationCommand(line);\n if (command) commands.add(command);\n }\n return commands;\n}\n\nfunction hasSuccessfulVerification(verificationLines: string[], pattern: RegExp): boolean {\n return verificationLines.some((line) => /->\\s*passed\\b/i.test(line) && pattern.test(line));\n}\n\nfunction hasSuccessfulAuthoritativeBuild(verificationLines: string[]): boolean {\n return hasSuccessfulVerification(verificationLines, /\\bxcodebuild\\s+build\\b/i) ||\n hasSuccessfulVerification(verificationLines, /\\b(?:\\.\\/gradlew\\s+)?(?:assembleDebug|test|check|build)\\b/i) ||\n hasSuccessfulVerification(verificationLines, /\\b(?:npm|pnpm|yarn)\\s+(?:run\\s+)?(?:build|test|typecheck)\\b/i) ||\n hasSuccessfulVerification(verificationLines, /\\b(?:swift|cargo|go)\\s+(?:build|test)\\b/i);\n}\n\nfunction shellPathTokens(command: string): string[] {\n return command\n .split(/\\s+/)\n .map((token) => token.replace(/^['\"]|['\"]$/g, \"\").replace(/[;,]$/g, \"\"))\n .filter((token) => /(?:^|\\/)[\\w.-]+\\.[\\w.-]+$/.test(token));\n}\n\nfunction hasSuccessfulCommandTouchingSamePath(line: string, verificationLines: string[], commandPattern: RegExp): boolean {\n const failedCommand = normalizeVerificationCommand(line);\n const failedPaths = shellPathTokens(failedCommand);\n if (!failedPaths.length) return false;\n return verificationLines.some((candidate) => {\n if (!/->\\s*passed\\b/i.test(candidate)) return false;\n const candidateCommand = normalizeVerificationCommand(candidate);\n if (!commandPattern.test(candidateCommand)) return false;\n const candidatePaths = shellPathTokens(candidateCommand);\n return failedPaths.some((failedPath) => candidatePaths.includes(failedPath));\n });\n}\n\nfunction isRecoveredVerificationFailure(line: string, verificationLines: string[]): boolean {\n if (!/->\\s*failed\\b/i.test(line)) return false;\n if (/Shell (?:script|verification) rejected by safety checks/i.test(line)) return true;\n if (/Shell script rejected: git restore of historical content is not allowed/i.test(line)) return true;\n if (/bundle\\s+install\\b/i.test(line) &&\n /Host Ruby gem mutation is not allowed|host mutation safety checks/i.test(line) &&\n hasSuccessfulVerification(verificationLines, /\\bfastlane\\s+\\w+\\s+build\\b/i)) {\n return true;\n }\n if (/\\bktlintCheck\\b/i.test(line) && hasSuccessfulVerification(verificationLines, /\\bktlintCheck\\b/i)) return true;\n if (/ktlintFormat\\b/i.test(line) && hasSuccessfulVerification(verificationLines, /\\bktlintCheck\\b/i)) return true;\n if (/\\.swiftlint\\.yml\\b/i.test(line) && hasSuccessfulVerification(verificationLines, /\\bswiftlint\\b/i)) return true;\n if (/\\bcp\\s+/i.test(line) && hasSuccessfulCommandTouchingSamePath(line, verificationLines, /\\bcp\\s+/i)) return true;\n if (/\\bmkdir\\s+-p\\s+/i.test(line) && hasSuccessfulCommandTouchingSamePath(line, verificationLines, /\\bmkdir\\s+-p\\s+/i)) return true;\n if (/\\bfastlane\\s+(\\w+)\\s+build\\b/i.test(line)) {\n const laneMatch = line.match(/\\bfastlane\\s+(\\w+)\\s+build\\b/i);\n const lane = laneMatch?.[1];\n if (lane && hasSuccessfulVerification(verificationLines, new RegExp(`\\\\bfastlane\\\\s+${lane}\\\\s+build\\\\b`, \"i\"))) {\n return true;\n }\n }\n if (/git\\s+(?:-C\\s+\\S+\\s+)?add\\b/i.test(line) &&\n (hasSuccessfulVerification(verificationLines, /git\\s+(?:-C\\s+\\S+\\s+)?add\\b/i) ||\n verificationLines.some((candidate) => /->\\s*passed\\b/i.test(candidate) && /git\\s+(?:-C\\s+\\S+\\s+)?add\\b/i.test(candidate)))) {\n return true;\n }\n if (/git\\s+(?:-C\\s+\\S+\\s+)?add[\\s\\S]*git\\s+(?:-C\\s+\\S+\\s+)?commit/i.test(line) &&\n hasSuccessfulVerification(verificationLines, /git\\s+(?:-C\\s+\\S+\\s+)?add[\\s\\S]*git\\s+(?:-C\\s+\\S+\\s+)?commit/i)) {\n return true;\n }\n if (/xcodebuild[\\s\\S]*destination/i.test(line) &&\n hasSuccessfulVerification(verificationLines, /xcodebuild[\\s\\S]*destination/i)) {\n return true;\n }\n if (/assembleDebug\\b/i.test(line) && hasSuccessfulVerification(verificationLines, /\\bassembleDebug\\b/i)) return true;\n if (/\\b(?:grep|rg)\\s+-c\\b[\\s\\S]*(?:project\\.pbxproj|build\\.gradle\\.kts|package\\.json|tsconfig\\.json|Info\\.plist)/i.test(line) &&\n hasSuccessfulAuthoritativeBuild(verificationLines)) {\n return true;\n }\n const npmScriptMatch = line.match(/\\b(?:npm|pnpm|yarn|bun)\\s+(?:run\\s+)?([\\w:.-]+)\\b/i);\n if (npmScriptMatch?.[1]) {\n const script = npmScriptMatch[1].replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n if (hasSuccessfulVerification(verificationLines, new RegExp(`\\\\b(?:npm|pnpm|yarn|bun)\\\\s+(?:run\\\\s+)?${script}\\\\b`, \"i\"))) {\n return true;\n }\n }\n // Generic: same shell command later succeeded (with optional exit-echo suffix).\n // Salvaged from F-fix.5+8 — handles the `cmd` -> failed / `cmd 2>&1; echo \"EXIT=$?\"` -> passed pattern.\n const failedCmd = line.replace(/^Verification:\\s*/i, \"\").replace(/\\s*->\\s*failed\\b[\\s\\S]*$/i, \"\").trim();\n if (failedCmd) {\n const escaped = failedCmd.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n const reSamePassed = new RegExp(`^(?:Verification:\\\\s*)?${escaped}(?:\\\\s+2>&1;?\\\\s*echo\\\\s+\"EXIT=\\\\$\\\\?\")?\\\\s*->\\\\s*passed\\\\b`, \"i\");\n if (verificationLines.some((other) => other !== line && reSamePassed.test(other))) {\n return true;\n }\n }\n return false;\n}\n\nfunction isSuccessfulAbsenceSearch(line: string, finalText: string): boolean {\n if (!/->\\s*failed\\b/i.test(line)) return false;\n const command = normalizeVerificationCommand(line);\n if (!/\\b(?:grep|rg)\\b/i.test(command)) return false;\n if (!/\\b(?:no|none|without|absent|not found|not present|zero)\\b/i.test(finalText)) return false;\n if (!/\\b(?:references?|matches?|occurrences?|old|legacy|forbidden|stale)\\b/i.test(finalText)) return false;\n return true;\n}\n\nexport function failedVerificationBlockers(verificationLines: string[], finalText = \"\"): string[] {\n const successfulCommands = successfulVerificationCommands(finalText);\n return verificationLines\n .filter((line) => /->\\s*failed\\b/i.test(line))\n .filter((line) => !successfulCommands.has(normalizeVerificationCommand(line)))\n .filter((line) => !isSuccessfulAbsenceSearch(line, finalText))\n .filter((line) => !isRecoveredVerificationFailure(line, verificationLines))\n .map((line) => `failed verification: ${line.replace(/^Verification:\\s*/i, \"\")}`);\n}\n\nfunction explicitArtifactReuseNone(text: string): boolean {\n return text\n .split(/\\r?\\n/)\n .some((line) => /^Artifact reused:\\s*none\\b/i.test(normalizeReportLabel(line)));\n}\n\nfunction explicitArtifactReuseNoneWithRationale(text: string): boolean {\n return text\n .split(/\\r?\\n/)\n .some((line) => {\n const normalized = normalizeReportLabel(line);\n return /^Artifact reused:\\s*none\\b/i.test(normalized) &&\n /\\b(?:read for context|not directly|doesn'?t directly|already in place|not used|no matched artifacts? relevant)\\b/i.test(normalized);\n });\n}\n\nfunction cleanArtifactTargetPath(value: string): string {\n return value\n .replace(/`/g, \"\")\n .replace(/\\s+[—-]\\s+.*$/, \"\")\n .replace(/\\s+\\(.*$/, \"\")\n .replace(/;.*$/, \"\")\n .trim();\n}\n\nfunction isArtifactTargetPath(value: string): boolean {\n return value === \"verification-only\" ||\n value === \"reusable artifact\" ||\n /(?:^|\\/)[^/\\s]+\\.[A-Za-z0-9]+$/.test(value);\n}\n\nfunction normalizeReportLabel(line: string): string {\n return line\n .replace(/^[-*]\\s*/, \"\")\n .replace(/^\\*\\*(Artifact reused|Artifact created|Modified|Verification|Manual check|Blocked):\\*\\*/i, \"$1:\")\n .replace(/^`(Artifact reused|Artifact created|Modified|Verification|Manual check|Blocked):`/i, \"$1:\")\n .replace(/\\*\\*/g, \"\")\n .replace(/`/g, \"\")\n .replace(/\\s*→\\s*/g, \" -> \")\n .trim();\n}\n\nfunction canonicalArtifactReuseLine(line: string): string {\n const cleaned = normalizeReportLabel(line);\n const match = cleaned.match(/^(Artifact reused:\\s*.+?)\\s*->\\s*(.+)$/i);\n if (!match) return cleaned;\n const prefix = match[1]?.trim() ?? \"\";\n const rawTarget = (match[2] ?? \"\").trim();\n if (/^(?:none|n\\/a|not used|unused)\\b/i.test(rawTarget)) return \"Artifact reused: none\";\n const targets = (match[2] ?? \"\")\n .split(\",\")\n .map(cleanArtifactTargetPath)\n .filter(isArtifactTargetPath);\n return targets.length > 0 ? `${prefix} -> ${targets.join(\", \")}` : \"Artifact reused: none\";\n}\n\nfunction explicitArtifactReuseLines(text: string): string[] {\n return uniqueSorted(text\n .split(/\\r?\\n/)\n .map(canonicalArtifactReuseLine)\n .filter((line) => /^Artifact reused:\\s+/i.test(line))\n .filter((line) => !/^Artifact reused:\\s*none\\b/i.test(line)));\n}\n\nfunction explicitArtifactReuseLinesForManifest(\n text: string,\n manifest: Pick<TanyaFinalManifest, \"artifactsRead\" | \"changedFiles\">,\n runContext?: TanyaRunContext,\n): string[] {\n if (manifest.artifactsRead.length === 0) return explicitArtifactReuseLines(text);\n const artifactPaths = new Set(manifest.artifactsRead.flatMap((artifactPath) => [\n artifactPath,\n sourceArtifactPath(artifactPath, runContext),\n ]));\n const changedFiles = new Set(manifest.changedFiles);\n return explicitArtifactReuseLines(text).filter((line) => {\n const match = line.match(/^Artifact reused:\\s*(.+?)\\s*->\\s*(.+)$/i);\n if (!match) return false;\n const artifact = match[1]?.trim();\n if (!artifact || !artifactPaths.has(artifact)) return false;\n const targets = (match[2] ?? \"\")\n .split(\",\")\n .map((target) => target.trim())\n .filter(Boolean);\n return targets.length > 0 && targets.every((target) => target === \"verification-only\" || changedFiles.has(target));\n });\n}\n\nfunction artifactTargetFiles(artifactPath: string, changedFiles: string[]): string[] {\n if (/artifacts\\/ios\\/SplashScreenPattern\\.swift$|\\.tania\\/artifacts\\/ios\\/SplashScreenPattern\\.swift$/.test(artifactPath)) {\n return changedFiles.filter((file) => /(?:^|\\/)SplashScreenView\\.swift$/.test(file));\n }\n if (/artifacts\\/ios\\/OnboardingFlowPattern\\.swift$|\\.tania\\/artifacts\\/ios\\/OnboardingFlowPattern\\.swift$/.test(artifactPath)) {\n return changedFiles.filter((file) => /(?:^|\\/)(?:OnboardingView|OnboardingPageView)\\.swift$|(?:^|\\/)[^/]+App\\.swift$/.test(file));\n }\n if (/artifacts\\/ios\\/ColorHex\\.swift$|\\.tania\\/artifacts\\/ios\\/ColorHex\\.swift$/.test(artifactPath)) {\n return changedFiles.filter((file) => /(?:^|\\/)(?:ColorHex|Colors|ThemeSystem)\\.swift$/.test(file));\n }\n if (/artifacts\\/ios\\/ThemeSystem\\.swift$|\\.tania\\/artifacts\\/ios\\/ThemeSystem\\.swift$/.test(artifactPath)) {\n return changedFiles.filter((file) => /(?:^|\\/)(?:Theme\\/)?(?:ThemeSystem|Colors|Typography|ViewModifiers)\\.swift$/.test(file));\n }\n if (/artifacts\\/ios\\/NavigationSetup\\.swift$|\\.tania\\/artifacts\\/ios\\/NavigationSetup\\.swift$/.test(artifactPath)) {\n return changedFiles.filter((file) => /(?:^|\\/)(?:Navigation\\/)?(?:NavigationSetup|AppNavigation|NavigationView)\\.swift$|(?:^|\\/)ContentView\\.swift$|(?:^|\\/)[^/]+App\\.swift$/.test(file));\n }\n if (/artifacts\\/ios\\/SwiftDataSetup\\.swift$|\\.tania\\/artifacts\\/ios\\/SwiftDataSetup\\.swift$/.test(artifactPath)) {\n return changedFiles.filter((file) => /(?:^|\\/)(?:Models\\/)?(?:SwiftDataSetup|Models|.*Model)\\.swift$|(?:^|\\/)[^/]+App\\.swift$/.test(file));\n }\n if (/artifacts\\/ios\\/MultiPlatformAppleSetup\\.swift$|\\.tania\\/artifacts\\/ios\\/MultiPlatformAppleSetup\\.swift$/.test(artifactPath)) {\n return changedFiles.filter((file) => /(?:^|\\/)(?:ContentView|[^/]+App|Platform|Root)\\.swift$/.test(file));\n }\n if (/artifacts\\/ios\\/DebugLogger\\.swift$|\\.tania\\/artifacts\\/ios\\/DebugLogger\\.swift$/.test(artifactPath)) {\n return changedFiles.filter((file) => /(?:^|\\/)(?:DebugLogger|Logger|Logging)\\.swift$/.test(file));\n }\n if (/artifacts\\/ios\\/Localization\\.swift$|\\.tania\\/artifacts\\/ios\\/Localization\\.swift$/.test(artifactPath)) {\n return changedFiles.filter((file) => /(?:^|\\/)(?:Localization|Localiz(?:able|ation)|Strings)\\.swift$|(?:^|\\/)[^/]+\\.strings$/.test(file));\n }\n if (/artifacts\\/ios\\/OfflineCachePatterns\\.swift$|\\.tania\\/artifacts\\/ios\\/OfflineCachePatterns\\.swift$/.test(artifactPath)) {\n return changedFiles.filter((file) => /(?:^|\\/)(?:Offline|Cache|Sync|Repository|Store)[^/]*\\.swift$/.test(file));\n }\n if (/artifacts\\/android\\/SplashScreenPattern\\.kt$|\\.tania\\/artifacts\\/android\\/SplashScreenPattern\\.kt$/.test(artifactPath)) {\n return changedFiles.filter((file) => /(?:^|\\/)(?:SplashScreen|MainActivity)\\.kt$/.test(file));\n }\n if (/artifacts\\/android\\/OnboardingFlowPattern\\.kt$|\\.tania\\/artifacts\\/android\\/OnboardingFlowPattern\\.kt$/.test(artifactPath)) {\n return changedFiles.filter((file) => /(?:^|\\/)(?:OnboardingScreen|OnboardingDataStore|MainActivity|AppNavigation)\\.kt$|(?:^|\\/)app\\/build\\.gradle\\.kts$/.test(file));\n }\n if (/artifacts\\/android\\/ThemeSystem\\.kt$|\\.tania\\/artifacts\\/android\\/ThemeSystem\\.kt$/.test(artifactPath)) {\n return changedFiles.filter((file) => /(?:^|\\/)ui\\/theme\\/(?:AppTheme|Color|Theme|Type)\\.kt$/.test(file));\n }\n if (/artifacts\\/android\\/NavigationSetup\\.kt$|\\.tania\\/artifacts\\/android\\/NavigationSetup\\.kt$/.test(artifactPath)) {\n return changedFiles.filter((file) => /(?:^|\\/)navigation\\/[^/]+\\.kt$|(?:^|\\/)MainActivity\\.kt$/.test(file));\n }\n if (/artifacts\\/android\\/RoomSetup\\.kt$|\\.tania\\/artifacts\\/android\\/RoomSetup\\.kt$/.test(artifactPath)) {\n return changedFiles.filter((file) =>\n /(?:^|\\/)(?:app\\/schemas\\/|build\\.gradle\\.kts$|app\\/build\\.gradle\\.kts$)/.test(file) ||\n /(?:^|\\/)data\\/.*(?:Database|Entity|Dao|Room|Migration|Repository)\\.kt$/.test(file)\n );\n }\n if (/artifacts\\/android\\/FeatureScreenPatterns\\.kt$|\\.tania\\/artifacts\\/android\\/FeatureScreenPatterns\\.kt$/.test(artifactPath)) {\n return changedFiles.filter((file) => /(?:^|\\/)ui\\/components\\/[^/]+\\.kt$|(?:^|\\/)ui\\/screens\\/[^/]+\\.kt$/.test(file));\n }\n if (/artifacts\\/android\\/OfflineCachePatterns\\.kt$|\\.tania\\/artifacts\\/android\\/OfflineCachePatterns\\.kt$/.test(artifactPath)) {\n return changedFiles.filter((file) => /(?:^|\\/)(?:data\\/.*(?:Cache|Sync|Offline)|work\\/|network\\/).*\\.kt$/.test(file));\n }\n if (artifactPath.endsWith(\"artifacts/ios/FastlaneSetup.md\") || artifactPath.endsWith(\".tania/artifacts/ios/FastlaneSetup.md\")) {\n return changedFiles.filter((file) => file === \"fastlane/Fastfile\" || file === \"fastlane/Appfile\" || /(?:^|\\/)ExportOptions-[^/]+\\.plist$/.test(file));\n }\n if (/artifacts\\/android\\/FastlaneSetup\\.md$|\\.tania\\/artifacts\\/android\\/FastlaneSetup\\.md$/.test(artifactPath)) {\n return changedFiles.filter((file) => /(?:^|\\/)fastlane\\/Fastfile$|(?:^|\\/)fastlane\\/Appfile$/.test(file));\n }\n if (/artifacts\\/android\\/PlayRelease_ManualSteps\\.md$|\\.tania\\/artifacts\\/android\\/PlayRelease_ManualSteps\\.md$/.test(artifactPath)) {\n return changedFiles.filter((file) => /(?:^|\\/)fastlane\\/Fastfile$|(?:^|\\/)gradle\\.properties$/.test(file));\n }\n if (/artifacts\\/backend\\/JwtAuthRoutes\\.ts$|\\.tania\\/artifacts\\/backend\\/JwtAuthRoutes\\.ts$/.test(artifactPath)) {\n return changedFiles.filter((file) => /(?:^|\\/)app\\/api\\/[^/]+(?:\\/.*)?\\/route\\.ts$|(?:^|\\/)(?:lib\\/(?:auth|.*Auth|routeWrappers)\\.ts|middleware\\.ts)$/.test(file));\n }\n if (/artifacts\\/backend\\/OpenApiSwaggerRoutes\\.ts$|\\.tania\\/artifacts\\/backend\\/OpenApiSwaggerRoutes\\.ts$/.test(artifactPath)) {\n return changedFiles.filter((file) => /(?:^|\\/)(?:lib\\/openapi\\.ts|app\\/api\\/(?:docs|openapi\\.json)\\/route\\.ts|API_FEATURES\\.md|brand\\/api_features\\.md)$/.test(file));\n }\n if (/artifacts\\/backend\\/PrismaBase\\.prisma$|\\.tania\\/artifacts\\/backend\\/PrismaBase\\.prisma$/.test(artifactPath)) {\n return changedFiles.filter((file) => /(?:^|\\/)prisma\\/schema\\.prisma$/.test(file));\n }\n if (/artifacts\\/backend\\/EnvExample\\.txt$|\\.tania\\/artifacts\\/backend\\/EnvExample\\.txt$/.test(artifactPath)) {\n return changedFiles.filter((file) => /(?:^|\\/)\\.env\\.example$/.test(file));\n }\n if (/artifacts\\/testing\\/MobileCIWorkflows\\.md$|\\.tania\\/artifacts\\/testing\\/MobileCIWorkflows\\.md$/.test(artifactPath)) {\n return changedFiles.filter((file) => /(?:^|\\/)\\.github\\/workflows\\/[^/]+\\.ya?ml$/.test(file));\n }\n return [];\n}\n\nfunction stripConflictingArtifactReuseLines(text: string, manifest: TanyaFinalManifest, force = false): string {\n if (!force && manifest.artifactsRead.length === 0) return text;\n const zeroChangeVerificationOnly = manifest.changedFiles.length === 0;\n return text\n .split(/\\r?\\n/)\n .filter((line) => {\n const trimmed = line.trim();\n if (/^[-*]?\\s*(?:\\*\\*)?`?Artifact reused:/i.test(trimmed)) return false;\n if (zeroChangeVerificationOnly && /\\bArtifact reused:\\s*/i.test(trimmed)) return false;\n return true;\n })\n .join(\"\\n\");\n}\n\nfunction normalizeArtifactReuseLines(text: string): string {\n const lines = text\n .split(/\\r?\\n/)\n .map((line) => {\n const normalized = normalizeReportLabel(line);\n if (/^Artifact reused:\\s*/i.test(normalized)) return canonicalArtifactReuseLine(normalized);\n if (/^Manual check:\\s*/i.test(normalized) && !/\\s->\\s/.test(normalized)) return `${normalized} -> required after CLI`;\n return /^(Artifact created|Modified|Verification|Manual check|Blocked):\\s*/i.test(normalized) ? normalized : line;\n });\n const hasSpecificReuse = lines.some((line) => /^Artifact reused:\\s+/i.test(line) && !/^Artifact reused:\\s*none\\b/i.test(line));\n return lines\n .filter((line) => !(hasSpecificReuse && /^Artifact reused:\\s*none\\b/i.test(line)))\n .join(\"\\n\");\n}\n\nfunction explicitManualCheckLines(text: string): string[] {\n const lines: string[] = [];\n let inManualSection = false;\n for (const line of text.split(/\\r?\\n/)) {\n const normalized = normalizeReportLabel(line);\n if (/^Manual check:\\s*/i.test(normalized)) {\n lines.push(/\\s->\\s/.test(normalized) ? normalized : `${normalized} -> required after CLI`);\n continue;\n }\n if (\n /^#{1,6}\\s*(?:Manual (?:checks?|testing)|What to test manually)\\b/i.test(line.trim()) ||\n /^(?:Manual (?:checks?|testing)|What to test manually)\\b/i.test(normalized)\n ) {\n inManualSection = true;\n continue;\n }\n if (inManualSection && /^#{1,6}\\s+\\S/.test(line.trim())) {\n inManualSection = false;\n continue;\n }\n if (!inManualSection) continue;\n const item = line.match(/^\\s*(?:[-*]|\\d+[.)])\\s+(.+?)\\s*$/)?.[1];\n if (!item) continue;\n const cleaned = item\n .replace(/\\*\\*/g, \"\")\n .replace(/`/g, \"\")\n .replace(/\\s+/g, \" \")\n .trim();\n if (cleaned) lines.push(`Manual check: ${cleaned}${/\\s->\\s/.test(cleaned) ? \"\" : \" -> required after CLI\"}`);\n }\n return uniqueSorted(lines);\n}\n\nfunction hasCompleteCodingReport(text: string): boolean {\n return hasRequiredCodingReport(text)\n && /Artifact reused:\\s*/i.test(text)\n && /Artifact created:\\s*/i.test(text)\n && (/Modified:\\s*/i.test(text) || /Verification-only:\\s*existing setup satisfied/i.test(text))\n && /Blocked:\\s*/i.test(text);\n}\n\nfunction buildArtifactReportLines(\n manifest: Pick<TanyaFinalManifest, \"artifactsRead\" | \"changedFiles\">,\n runContext?: TanyaRunContext,\n finalText = \"\",\n): string[] {\n const availableCallerArtifacts = runContext?.artifacts\n ?.filter((artifact) => artifact.status !== \"missing\")\n .map((artifact) => artifact.path) ?? [];\n const explicitReuseLines = explicitArtifactReuseLinesForManifest(finalText, manifest, runContext);\n const shouldRespectExplicitNone = explicitReuseLines.length === 0 && explicitArtifactReuseNone(finalText);\n if (manifest.changedFiles.length === 0) return [\"Artifact reused: none\"];\n const artifactReportPaths = shouldRespectExplicitNone\n ? []\n : manifest.artifactsRead.length > 0\n ? manifest.artifactsRead\n : availableCallerArtifacts;\n if (artifactReportPaths.length > 0) {\n const mapped = artifactReportPaths.flatMap((artifactPath) => {\n const targetFiles = artifactTargetFiles(artifactPath, manifest.changedFiles);\n if (targetFiles.length > 0) return [`Artifact reused: ${sourceArtifactPath(artifactPath, runContext)} -> ${targetFiles.join(\", \")}`];\n return [];\n });\n if (mapped.length > 0) return mapped;\n }\n if (explicitReuseLines.length > 0) {\n return uniqueSorted(explicitReuseLines);\n }\n return [\"Artifact reused: none\"];\n}\n\nfunction structuredArtifactReuse(manifest: Pick<TanyaFinalManifest, \"artifactsRead\" | \"changedFiles\">, runContext?: TanyaRunContext, finalText = \"\"): StructuredArtifactReuse[] {\n const lines = buildArtifactReportLines(manifest, runContext, finalText);\n return lines\n .map((line): StructuredArtifactReuse | null => {\n const match = line.match(/^Artifact reused:\\s*(.+?)\\s*->\\s*(.+)$/i);\n if (!match) return null;\n const artifact = match[1]?.trim();\n const targets = (match[2] ?? \"\")\n .split(\",\")\n .map((target) => target.trim())\n .filter(Boolean);\n if (!artifact || /^none$/i.test(artifact)) return null;\n return { artifact, targets };\n })\n .filter((entry): entry is StructuredArtifactReuse => entry !== null);\n}\n\nfunction buildStructuredReport(manifest: TanyaFinalManifest, runContext?: TanyaRunContext, finalText = \"\"): TanyaStructuredReport {\n const validationBlockers = (manifest.validation?.issues ?? [])\n .filter((issue) => issue.severity === \"error\")\n .map((issue) => `${issue.id}: ${issue.message}`);\n const blocked = uniqueSorted([...manifest.blockers, ...validationBlockers]);\n const artifactsReused = structuredArtifactReuse(manifest, runContext, finalText);\n const hasStrictArtifactMapping = manifest.artifactsRead.some((artifactPath) =>\n /artifacts\\/(?:ios\\/(?:FastlaneSetup\\.md|SplashScreenPattern\\.swift)|android\\/(?:FastlaneSetup\\.md|PlayRelease_ManualSteps\\.md|SplashScreenPattern\\.kt|ThemeSystem\\.kt|NavigationSetup\\.kt|RoomSetup\\.kt|FeatureScreenPatterns\\.kt|OfflineCachePatterns\\.kt)|backend\\/(?:JwtAuthRoutes\\.ts|OpenApiSwaggerRoutes\\.ts|PrismaBase\\.prisma|EnvExample\\.txt)|testing\\/MobileCIWorkflows\\.md)$|\\.tania\\/artifacts\\/(?:ios\\/(?:FastlaneSetup\\.md|SplashScreenPattern\\.swift)|android\\/(?:FastlaneSetup\\.md|PlayRelease_ManualSteps\\.md|SplashScreenPattern\\.kt|ThemeSystem\\.kt|NavigationSetup\\.kt|RoomSetup\\.kt|FeatureScreenPatterns\\.kt|OfflineCachePatterns\\.kt)|backend\\/(?:JwtAuthRoutes\\.ts|OpenApiSwaggerRoutes\\.ts|PrismaBase\\.prisma|EnvExample\\.txt)|testing\\/MobileCIWorkflows\\.md)$/.test(artifactPath)\n );\n const explicitNoneOnly = explicitArtifactReuseNoneWithRationale(finalText)\n && explicitArtifactReuseLines(finalText).length === 0\n && artifactsReused.length === 0\n && !/Verification:\\s*not completed\\s*->\\s*blocked before verification command was captured/i.test(finalText)\n && !manifest.artifactsRead.some((artifactPath) => finalText.includes(sourceArtifactPath(artifactPath, runContext)));\n const inferredArtifactsReused = manifest.artifactsRead.flatMap((artifactPath): StructuredArtifactReuse[] => {\n const targets = artifactTargetFiles(artifactPath, manifest.changedFiles);\n if (targets.length === 0) return [];\n return [{ artifact: sourceArtifactPath(artifactPath, runContext), targets }];\n });\n const repairedArtifactsReused = explicitNoneOnly\n ? []\n : inferredArtifactsReused.length > 0\n ? inferredArtifactsReused\n : artifactsReused;\n return {\n schemaVersion: 1,\n modified: manifest.changedFiles,\n artifactsReused: repairedArtifactsReused,\n artifactsCreated: manifest.artifactsCreated,\n verification: manifest.verification,\n manualChecks: explicitManualCheckLines(finalText),\n blocked,\n blockers: blocked,\n warnings: manifest.childWarnings ?? [],\n validation: manifest.validation ?? { passed: true, issues: [] },\n git: manifest.git,\n metrics: {\n toolErrors: manifest.toolErrors,\n },\n };\n}\n\nfunction buildDeterministicCodingFooter(manifest: TanyaFinalManifest, runContext?: TanyaRunContext, finalText = \"\"): string {\n const structuredReport = buildStructuredReport(manifest, runContext, finalText);\n const artifactLines = structuredReport.artifactsReused.length > 0\n ? structuredReport.artifactsReused.map((entry) => `Artifact reused: ${entry.artifact} -> ${entry.targets.length > 0 ? entry.targets.join(\", \") : \"verification-only\"}`)\n : [\"Artifact reused: none\"];\n const artifactCreatedLines = structuredReport.artifactsCreated.length > 0\n ? structuredReport.artifactsCreated.map((artifactPath) => `Artifact created: ${artifactPath} -> reusable artifact`)\n : [\"Artifact created: none\"];\n const modifiedLines = structuredReport.modified.length > 0\n ? structuredReport.modified.map((filePath) => `Modified: ${filePath}`)\n : [\"Modified: none\", \"Verification-only: existing setup satisfied\"];\n const verification = structuredReport.verification.length > 0\n ? structuredReport.verification\n : [\"Verification: not completed -> blocked before verification command was captured\"];\n return [\n \"## Tanya deterministic report\",\n \"_(authoritative — overrides any conflicting artifact reuse or modification claim above)_\",\n ...artifactLines,\n ...artifactCreatedLines,\n ...modifiedLines,\n ...verification,\n ...(structuredReport.warnings.length > 0\n ? [\"Warnings:\", ...structuredReport.warnings.map((warning) => `- ${warning}`)]\n : []),\n ...(manifest.reasoningAnnotations && manifest.reasoningAnnotations.length > 0\n ? [\n \"Reasoning annotations (advisory, not verifier authority):\",\n ...manifest.reasoningAnnotations.map((annotation) =>\n `- Why the agent thought this (${annotation.provider}/${annotation.model}, ${annotation.confidence}): ${annotation.excerpt}`\n ),\n ]\n : []),\n ...structuredReport.manualChecks,\n `Verification: git rev-parse --show-toplevel -> ${structuredReport.git.root ?? \"unavailable\"}`,\n `Verification: git rev-parse --short HEAD -> ${structuredReport.git.head ?? \"unavailable\"}`,\n structuredReport.blocked.length > 0 ? `Blocked: ${structuredReport.blocked.join(\"; \")}` : \"Blocked: none\",\n \"Tanya structured report:\",\n JSON.stringify(structuredReport, null, 2),\n \"Tanya manifest:\",\n JSON.stringify(manifest, null, 2),\n ].join(\"\\n\");\n}\n\nfunction childVerdictMessage(verdict: ChildVerdict): string {\n const detail = verdict.blockers.join(\"; \") || verdict.summary || \"failed\";\n return `subtask ${verdict.subRunId} failed: ${detail}`;\n}\n\nfunction appendTaniaResultLine(text: string, verdict: \"PASSED\" | \"FAIL\"): string {\n const lines = text\n .trim()\n .split(/\\r?\\n/)\n .filter((line) => !/^TANIA RESULT:\\s*(?:PASSED|FAIL)\\s*$/i.test(line.trim()));\n return [...lines, `TANIA RESULT: ${verdict}`].join(\"\\n\").trim();\n}\n\nfunction manifestVerdict(manifest: TanyaFinalManifest): \"PASSED\" | \"FAIL\" {\n if (manifest.blockers.length > 0) return \"FAIL\";\n const fsv = manifest.finalStateVerification;\n if (fsv && fsv.authoritativePassed === false) return \"FAIL\";\n return \"PASSED\";\n}\n\nexport function ensureCodingReport(text: string, manifest: TanyaFinalManifest, runContext?: TanyaRunContext): string {\n const verdict = manifestVerdict(manifest);\n if (!manifest.changedFiles.length && !manifest.artifactsRead.length && !manifest.artifactsCreated.length && !manifest.verification.length && !manifest.git.root) return appendTaniaResultLine(text, verdict);\n const normalizedText = normalizeArtifactReuseLines(text);\n const bodyText = stripConflictingArtifactReuseLines(normalizedText, manifest, !!runContext?.expected_report?.artifact_reuse);\n const explicitReuseLines = explicitArtifactReuseLinesForManifest(normalizedText, manifest, runContext);\n const footerSourceText = explicitReuseLines.length > 0\n ? normalizedText\n : manifest.artifactsRead.length > 0 && !explicitArtifactReuseNone(normalizedText)\n ? bodyText\n : normalizedText;\n const footer = buildDeterministicCodingFooter(manifest, runContext, footerSourceText);\n if (isCodingTask(runContext) && runContext?.expected_report && runContextRequiresCommit(runContext) && manifest.git.head) return appendTaniaResultLine(footer, verdict);\n const needsManualCheckLines = /^#{1,6}\\s*(?:Manual (?:checks?|testing)|What to test manually)\\b/im.test(bodyText) && !/^Manual check:\\s*/im.test(bodyText);\n if (/Tanya manifest:/i.test(bodyText) || /## Tanya deterministic report/i.test(bodyText)) return appendTaniaResultLine(bodyText, verdict);\n if (hasCompleteCodingReport(bodyText) && !needsManualCheckLines) return appendTaniaResultLine(`${bodyText.trim()}\\n\\n${footer}`, verdict);\n return appendTaniaResultLine(bodyText.trim() ? `${bodyText.trim()}\\n\\n${footer}` : footer, verdict);\n}\n","export type BudgetReservationRequest = {\n maxTokens?: number;\n maxUsd?: number;\n};\n\nexport type BudgetReservation = {\n id: string;\n tokensReserved: number;\n usdReserved: number;\n};\n\nexport class BudgetLedger {\n private remainingTokens: number | null;\n private remainingUsd: number | null;\n private sequence = 0;\n private readonly reservations = new Map<string, BudgetReservation>();\n\n constructor(initial: BudgetReservationRequest = {}) {\n this.remainingTokens = initial.maxTokens ?? null;\n this.remainingUsd = initial.maxUsd ?? null;\n }\n\n reserve(request: BudgetReservationRequest): BudgetReservation {\n const tokensReserved = request.maxTokens ?? 0;\n const usdReserved = request.maxUsd ?? 0;\n if (this.remainingTokens !== null && tokensReserved > this.remainingTokens) {\n throw new Error(\"budget: token reservation exceeds parent remaining budget\");\n }\n if (this.remainingUsd !== null && usdReserved > this.remainingUsd) {\n throw new Error(\"budget: USD reservation exceeds parent remaining budget\");\n }\n if (this.remainingTokens !== null) this.remainingTokens -= tokensReserved;\n if (this.remainingUsd !== null) this.remainingUsd -= usdReserved;\n const reservation = {\n id: `reservation-${++this.sequence}`,\n tokensReserved,\n usdReserved,\n };\n this.reservations.set(reservation.id, reservation);\n return reservation;\n }\n\n release(reservationId: string, used: BudgetReservationRequest = {}): void {\n const reservation = this.reservations.get(reservationId);\n if (!reservation) return;\n this.reservations.delete(reservationId);\n if (this.remainingTokens !== null) {\n this.remainingTokens += Math.max(0, reservation.tokensReserved - (used.maxTokens ?? 0));\n }\n if (this.remainingUsd !== null) {\n this.remainingUsd += Math.max(0, reservation.usdReserved - (used.maxUsd ?? 0));\n }\n }\n}\n\nexport class AsyncSemaphore {\n private active = 0;\n private readonly queue: Array<() => void> = [];\n\n constructor(readonly limit: number) {}\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 = Math.max(0, this.active - 1);\n const next = this.queue.shift();\n if (next) next();\n }\n}\n","export function isLikelySubtaskCycle(prompt: string, recentPrompts: string[], threshold = 0.85): boolean {\n const normalizedPrompt = normalizePrompt(prompt);\n if (!normalizedPrompt) return false;\n return recentPrompts.slice(-3).some((candidate) => {\n const normalizedCandidate = normalizePrompt(candidate);\n if (!normalizedCandidate) return false;\n if (normalizedCandidate.includes(normalizedPrompt) || normalizedPrompt.includes(normalizedCandidate)) return true;\n return similarity(normalizedPrompt, normalizedCandidate) > threshold;\n });\n}\n\nexport function similarity(a: string, b: string): number {\n const maxLength = Math.max(a.length, b.length);\n if (maxLength === 0) return 1;\n return 1 - levenshtein(a, b) / maxLength;\n}\n\nfunction normalizePrompt(prompt: string): string {\n return prompt.toLowerCase().replace(/[^a-z0-9]+/g, \" \").replace(/\\s+/g, \" \").trim();\n}\n\nfunction levenshtein(a: string, b: string): number {\n const previous = Array.from({ length: b.length + 1 }, (_, index) => index);\n const current = Array.from({ length: b.length + 1 }, () => 0);\n for (let i = 1; i <= a.length; i += 1) {\n current[0] = i;\n for (let j = 1; j <= b.length; j += 1) {\n const cost = a[i - 1] === b[j - 1] ? 0 : 1;\n current[j] = Math.min(\n current[j - 1]! + 1,\n previous[j]! + 1,\n previous[j - 1]! + cost,\n );\n }\n for (let j = 0; j <= b.length; j += 1) previous[j] = current[j]!;\n }\n return previous[b.length]!;\n}\n","import type { EventSink } from \"../events/types\";\nimport { createSubAgentSink } from \"../events/subAgentSink\";\nimport type { TanyaRunContext } from \"../context/runContext\";\nimport type { FinalStateVerification, VerifierShell } from \"./verifier\";\nimport { isContextWindowExceededError, type ChatMessage, type ChatProvider, type ToolCall } from \"../providers/types\";\nimport {\n TOOL_CALL_CORRECTION_LIMIT,\n malformedToolCallCorrectionMessage,\n parseProviderToolCalls,\n parseToolArguments,\n} from \"../providers/parser\";\nimport { resolveWorkspace } from \"../safety/workspace\";\nimport { decide, inputShape, type Decision, type PermissionContext } from \"../safety/permissions/engine\";\nimport type { HostPermissionAnswer, PermissionRequest, PermissionRequestHandler } from \"../safety/permissions/host\";\nimport { loadPermissionRules, mergeInheritedPermissionRules, stricterPermissionMode } from \"../safety/permissions/rules\";\nimport type { PermissionMode } from \"../safety/permissions/schema\";\nimport { ToolRegistry } from \"../tools/registry\";\nimport { recordGoldenTaskMemory } from \"../memory/goldenTasks\";\nimport { recordRepairRunMemory, type RepairAttemptSnapshot } from \"../memory/repairRuns\";\nimport { appendTaskHistory, buildHistoryBlock, readRecentTaskHistory } from \"../memory/taskHistory\";\nimport { appendTaskToVault } from \"../obsidian/vaultAppender\";\nimport { envValue, numberEnvValue } from \"../config/envCompat\";\nimport { appendArchive, toArchivedMessages } from \"../memory/runArchive\";\nimport { appendAuditDecision } from \"../memory/auditLog\";\nimport { estimateRunCost } from \"../memory/runLogs\";\nimport { writeCachedToolResult } from \"../memory/resultCache\";\nimport { FileReadDedupCache } from \"../memory/fileReadDedup\";\nimport { buildRepoMap } from \"../context/repoMap\";\nimport { appendReasoningChunk, evictReasoningFromArchive } from \"../memory/reasoningArchive\";\nimport { loadMcpToolsForWorkspace } from \"../mcp/client\";\nimport type { SubAgentTaskRequest, SubAgentTaskResult, TanyaTool, ToolResult } from \"../tools/types\";\nimport {\n classifyStep,\n contextWindowForTarget,\n EscalationExhaustedError,\n resolveRouteWithContextGuard,\n type EffectiveRouteTable,\n type ResolvedRoute,\n type RouteTarget,\n type StepType,\n} from \"../router\";\nimport type { ValidationSummary } from \"./validators\";\nimport {\n autoCompact,\n CompactionExhaustedError,\n estimateCompactTokens,\n microcompact,\n snipLowSignal,\n type CompactionAggression,\n} from \"./compact\";\nimport {\n buildFallbackCodingReport,\n buildFinalManifest,\n collectChangedFiles,\n ensureCodingReport,\n failedVerificationBlockers,\n hasRequiredCodingReport,\n isCodingTask,\n} from \"./report\";\nimport { captureGitSnapshot, commitStillRequired, hasTrackedPathUnder, listFilesRecursive, uniqueSorted } from \"./git\";\nimport { buildSystemPrompt } from \"./systemPrompt\";\nimport {\n applyTokenBudgetRule,\n childRunId,\n createRootRunId,\n mergeRunContexts,\n resolveSubAgentWorkspace,\n type RunAgentParentContext,\n} from \"./subAgentContext\";\nimport { AsyncSemaphore, BudgetLedger } from \"./budgetLedger\";\nimport { isLikelySubtaskCycle } from \"./cycleDetect\";\nimport type { ChildVerdict, ReasoningAnnotation } from \"./verifier/types\";\nimport { existsSync, mkdirSync, readdirSync, unlinkSync, writeFileSync } from \"node:fs\";\nimport { cp, mkdir, rm, stat } from \"node:fs/promises\";\nimport { dirname, isAbsolute, join, relative, resolve } from \"node:path\";\nconst CONTEXT_TOKEN_LIMIT = 48_000;\nconst CONTEXT_SUMMARY_KEEP_RECENT = 6;\nconst permissionModes = new Set<PermissionMode>([\"default\", \"ask\", \"bypass\", \"plan\"]);\nlet sessionSpendTokens = 0;\nlet sessionSpendUsd = 0;\nlet sessionEscalations = 0;\nconst TOOL_RESULT_TRUNCATE_THRESHOLD = 2_048;\nconst TOOL_RESULT_HEAD_CHARS = 1_024;\nconst TOOL_RESULT_TAIL_CHARS = 500;\nconst EXPAND_RESULT_LIMIT_PER_TURN = 3;\n\nexport type TanyaFinalManifest = {\n schemaVersion: 1;\n changedFiles: string[];\n uncommittedFiles: string[];\n artifactsRead: string[];\n artifactsCreated: string[];\n contextFilesRead: string[];\n verification: string[];\n git: {\n root: string | null;\n head: string | null;\n };\n toolErrors: number;\n blockers: string[];\n childRunIds?: string[];\n childVerdicts?: ChildVerdict[];\n childWarnings?: string[];\n reasoningAnnotations?: ReasoningAnnotation[];\n validation?: ValidationSummary;\n finalStateVerification?: FinalStateVerification;\n};\n\nexport type RunAgentResult = {\n message: string;\n manifest: TanyaFinalManifest;\n metrics?: FinalMetrics;\n};\n\ntype FinalMetrics = {\n durationMs: number;\n toolCallCount: number;\n toolErrorCount: number;\n changedFileCount: number;\n repairAttemptCount: number;\n retryAttemptCount: number;\n promptTokens: number;\n completionTokens: number;\n reasoningTokens: number;\n costUsd: number;\n systemPromptTokens: number;\n repoMapTokens: number;\n toolResultTokens: number;\n};\n\nexport interface RunAgentOptions {\n provider: ChatProvider;\n prompt: string;\n cwd: string;\n sink: EventSink;\n maxTurns?: number;\n history?: ChatMessage[];\n runContext?: TanyaRunContext;\n parentContext?: RunAgentParentContext;\n runId?: string;\n repairAttempts?: number;\n retryAttempt?: number;\n signal?: AbortSignal;\n onPermissionRequest?: PermissionRequestHandler;\n verifierShell?: VerifierShell | undefined;\n routing?: {\n enabled: boolean;\n table: EffectiveRouteTable;\n providerFactory: (target: RouteTarget) => ChatProvider;\n };\n}\n\nfunction findSafeCompressionBoundary(messages: ChatMessage[], desiredKeepCount: number): number {\n if (messages.length <= desiredKeepCount + 1) return Math.max(1, messages.length - desiredKeepCount);\n let startIndex = messages.length - desiredKeepCount;\n // Cap how many leading tool messages we'll walk past — a runaway loop of\n // back-to-back tool results without an assistant tool_calls header indicates\n // a corrupt history; in that case fall back to the original boundary.\n const maxWalk = Math.min(8, messages.length - startIndex);\n let walked = 0;\n while (startIndex < messages.length && messages[startIndex]?.role === \"tool\" && walked < maxWalk) {\n const prev = messages[startIndex - 1];\n if (prev?.role === \"assistant\" && Array.isArray(prev.tool_calls) && prev.tool_calls.length > 0) {\n startIndex -= 1;\n break;\n }\n startIndex += 1;\n walked += 1;\n }\n if (startIndex >= messages.length) return messages.length - 1;\n return Math.max(1, startIndex);\n}\n\nfunction fieldMatchesType(value: unknown, expectedType: string): boolean {\n if (expectedType === \"array\") return Array.isArray(value);\n return typeof value === expectedType;\n}\n\nfunction validateToolInput(\n input: unknown,\n definition: { function: { parameters?: { properties?: Record<string, { type?: string }>; required?: string[] } } },\n): string | null {\n const params = definition.function.parameters;\n if (!params) return null;\n const record = input && typeof input === \"object\" ? input as Record<string, unknown> : {};\n for (const key of params.required ?? []) {\n if (!(key in record) || record[key] === undefined || record[key] === null) {\n return `Missing required field: \"${key}\"`;\n }\n const expectedType = params.properties?.[key]?.type;\n if (expectedType && !fieldMatchesType(record[key], expectedType)) {\n const actualType = Array.isArray(record[key]) ? \"array\" : typeof record[key];\n return `Field \"${key}\" must be ${expectedType}, got ${actualType}`;\n }\n }\n return null;\n}\n\nfunction materializedContextCleanupEnabled(manifest: TanyaFinalManifest, runContext?: TanyaRunContext): boolean {\n const metadata = runContext?.metadata ?? {};\n if (metadata.tanyaMaterializedContext !== true) return false;\n if (metadata.keepMaterializedContext === true) return false;\n if (manifest.blockers.length > 0) return false;\n if (manifest.validation && !manifest.validation.passed) return false;\n return true;\n}\n\nasync function cleanupMaterializedContext(workspace: string, manifest: TanyaFinalManifest, runContext?: TanyaRunContext): Promise<void> {\n if (!materializedContextCleanupEnabled(manifest, runContext)) return;\n const taniaDir = resolve(workspace, \".tania\");\n if (!existsSync(taniaDir)) return;\n if (await hasTrackedPathUnder(workspace, \".tania\")) return;\n try {\n await rm(taniaDir, { recursive: true, force: true });\n } catch {\n // Best-effort cleanup; successful task output should not fail because temp cleanup failed.\n }\n}\n\nasync function appendObsidianTaskIfConfigured(manifest: TanyaFinalManifest, runContext?: TanyaRunContext): Promise<void> {\n const metadataVault = runContext?.metadata?.obsidianVault;\n const vaultPath = typeof metadataVault === \"string\" && metadataVault.trim()\n ? metadataVault.trim()\n : envValue({}, \"TANYA_OBSIDIAN_VAULT\").trim();\n if (!vaultPath) return;\n try {\n await appendTaskToVault(vaultPath, manifest, runContext);\n } catch {\n // Obsidian logging is best-effort and must never fail a Tanya run.\n }\n}\n\nasync function appendTaskHistorySilently(\n workspace: string,\n prompt: string,\n manifest: TanyaFinalManifest,\n runContext?: TanyaRunContext,\n): Promise<void> {\n try {\n await appendTaskHistory(workspace, prompt, manifest, runContext);\n } catch {\n // Local history is best-effort and must never fail a Tanya run.\n }\n}\n\nasync function recordRepairRunMemorySilently(\n runContext: TanyaRunContext | undefined,\n attempts: RepairAttemptSnapshot[],\n manifest: TanyaFinalManifest,\n): Promise<void> {\n try {\n await recordRepairRunMemory(runContext, attempts, manifest);\n } catch {\n // Cross-session repair memory is best-effort and must never fail a Tanya run.\n }\n}\n\n// Keep at most this many run summary files per workspace; older ones are deleted.\n// One workspace can produce 30+ run files in a single session (orchestrated loops),\n// so the directory grows unbounded without rotation.\nexport const RUN_SUMMARY_MAX_FILES = 50;\n\nexport function rotateRunSummaryFiles(runsDir: string): void {\n try {\n const entries = readdirSync(runsDir).filter((f) => f.endsWith(\".json\")).sort();\n const excess = entries.length - RUN_SUMMARY_MAX_FILES;\n if (excess <= 0) return;\n for (const stale of entries.slice(0, excess)) {\n try { unlinkSync(join(runsDir, stale)); } catch { /* best-effort */ }\n }\n } catch {\n // Rotation must never fail the task.\n }\n}\n\nfunction logRunSummarySilently(params: {\n workspace: string;\n runId: string;\n parentRunId?: string;\n prompt: string;\n provider: string;\n model: string;\n metrics: FinalMetrics;\n manifest: TanyaFinalManifest;\n}): void {\n try {\n const runsDir = join(params.workspace, \".tania\", \"runs\");\n const outputDir = params.parentRunId ? join(runsDir, params.parentRunId) : runsDir;\n mkdirSync(outputDir, { recursive: true });\n const ts = new Date().toISOString();\n const logPath = join(outputDir, params.parentRunId ? `${params.runId}.json` : `${params.runId}.json`);\n writeFileSync(\n logPath,\n JSON.stringify(\n {\n ts,\n runId: params.runId,\n ...(params.parentRunId ? { parentRunId: params.parentRunId } : {}),\n prompt: params.prompt.slice(0, 200),\n provider: params.provider,\n model: params.model,\n durationMs: params.metrics.durationMs,\n promptTokens: params.metrics.promptTokens,\n completionTokens: params.metrics.completionTokens,\n reasoningTokens: params.metrics.reasoningTokens,\n systemPromptTokens: params.metrics.systemPromptTokens,\n repoMapTokens: params.metrics.repoMapTokens,\n toolResultTokens: params.metrics.toolResultTokens,\n changedFiles: params.manifest.changedFiles,\n blockers: params.manifest.blockers,\n toolCallCount: params.metrics.toolCallCount,\n repairAttemptCount: params.metrics.repairAttemptCount,\n retryAttemptCount: params.metrics.retryAttemptCount,\n validation: params.manifest.validation ?? null,\n artifactsRead: params.manifest.artifactsRead,\n },\n null,\n 2,\n ),\n \"utf8\",\n );\n rotateRunSummaryFiles(outputDir);\n } catch {\n // Run logs are best-effort and must never fail the task.\n }\n}\n\nfunction buildFinalReportReminder(changedFiles: string[], toolErrorCount: number): string {\n return [\n \"You must now stop using tools and produce the final coding report.\",\n \"Use the caller's required final report format.\",\n \"Include either `Artifact reused: <artifact-path> -> <target-path>` for adapted artifacts or exactly `Artifact reused: none`.\",\n \"Include either `Artifact created: <artifact-path> -> reusable artifact` for reusable artifacts created or exactly `Artifact created: none`.\",\n \"Include one `Verification: <command> -> <result>` line for every verification command you ran.\",\n \"Include one plain `Artifact reused: <artifact-path> -> <target-path>` line for every artifact you adapted.\",\n \"Only attribute files directly adapted from an artifact; do not list unrelated config, formatter-only files, generated icons, or source files under an artifact just because the artifact was read.\",\n changedFiles.length > 0\n ? \"Include one `Modified: <path>` line for every changed file.\"\n : \"If no files needed changes because the existing setup already satisfied the task, include exactly: `Verification-only: existing setup satisfied`.\",\n \"Do not create or keep backup files such as `.orig`, `.bak`, `.backup`, or `.tmp`.\",\n toolErrorCount > 0\n ? `Mention the ${toolErrorCount} tool error${toolErrorCount === 1 ? \"\" : \"s\"} as recovered issues if later verification passed; only list active blockers under Blocked.`\n : \"If there are no blockers, say so briefly.\",\n \"Do not call more tools unless the final report is impossible without one specific missing fact.\",\n ].join(\"\\n\");\n}\n\nfunction buildCommitRequiredReminder(manifest: TanyaFinalManifest): string {\n const uncommitted = manifest.uncommittedFiles.length > 0 ? manifest.uncommittedFiles : manifest.changedFiles;\n return [\n manifest.uncommittedFiles.length > 0\n ? \"The caller requires a git commit, and there are still in-scope changed files that are not included in the task commit.\"\n : \"You changed files and the caller requires a git commit, but HEAD has not changed yet.\",\n \"Do not produce the final report until the commit is created.\",\n manifest.git.head\n ? \"Call `commit_platform_changes` with `amend: true` to add the remaining in-scope files to the existing task commit.\"\n : \"Call `commit_platform_changes` now with the in-scope changed files and the exact required commit-message prefix from the prompt.\",\n `Files that must be committed: ${uncommitted.join(\", \") || \"none\"}`,\n \"After the commit succeeds, run `git rev-parse --short HEAD`, then produce the final report.\",\n ].join(\"\\n\");\n}\n\nfunction buildValidationRepairReminder(manifest: TanyaFinalManifest, attempt: number, maxAttempts: number): string {\n const issues = manifest.validation?.issues ?? [];\n const issueLines = issues.length > 0\n ? issues.map((issue) => `- ${issue.id}: ${issue.message}${issue.files?.length ? ` (${issue.files.join(\", \")})` : \"\"}`)\n : [\"- validation failed without detailed issues\"];\n const blockerLines = manifest.blockers.length > 0\n ? manifest.blockers.map((blocker) => `- ${blocker}`)\n : [];\n const repairHints: string[] = [];\n const issueIds = new Set(issues.map((issue) => issue.id));\n if (issueIds.has(\"apple-app-icon-xcodebuild-missing\")) {\n repairHints.push(\"For Apple app icon verification, run a direct `xcodebuild build` command with an available scheme and a concrete or generic simulator destination. Report the exact command only after it passes.\");\n }\n if (manifest.blockers.some((blocker) => /failed verification:/i.test(blocker))) {\n repairHints.push(\"Resolve every failed verification with a later passing rerun of the same check, or keep the task blocked and do not claim completion.\");\n }\n if (issueIds.has(\"core-verification-requested-command-missing\")) {\n repairHints.push(\"Run every missing requested verification command exactly as named in the issue message. Do not substitute file-existence probes, package-lock checks, or equivalent commands for required commands such as `npm install`.\");\n }\n if (issueIds.has(\"core-artifact-provenance-missing\")) {\n repairHints.push(\"READ at least one caller-provided artifact NOW using read_file on a path under .tania/artifacts/, then report it as `Artifact reused: <artifact-path> -> <target-file-or-verification-only>`. This applies even when the existing setup is already complete: pick one artifact under .tania/artifacts/ and read it to confirm the canonical pattern, then report the line.\");\n }\n if (issueIds.has(\"android-gradle-assembledebug-missing\")) {\n repairHints.push(\"For Android Gradle verification, run `./gradlew assembleDebug --no-daemon` from the Android workspace root and report it only after it exits successfully.\");\n }\n if (issueIds.has(\"android-gradle-ktlintcheck-missing\")) {\n repairHints.push(\"For Android ktlint verification, run `./gradlew ktlintCheck --no-daemon` from the Android workspace root and report it only after it exits successfully.\");\n }\n if (issueIds.has(\"ios-splash-solid-background-violated\")) {\n repairHints.push(\"For iOS splash solid-background violations, remove LinearGradient/RadialGradient/AngularGradient and use a single explicit brand Color value.\");\n }\n if (issueIds.has(\"ios-splash-text-forbidden\")) {\n repairHints.push(\"For iOS splash text-forbidden violations, remove all Text(...) views, taglines, labels, and captions from SplashScreenView.swift.\");\n }\n if (issueIds.has(\"ios-splash-extra-animation\")) {\n repairHints.push(\"For iOS splash extra-animation violations, keep only the brief icon fade-in; remove pulse, scale, rotation, shimmer, and repeatForever animations.\");\n }\n if (issueIds.has(\"ios-splash-icon-image\")) {\n repairHints.push(\"For iOS splash icon-image violations, render Image(\\\"SplashIcon\\\") from SplashIcon.imageset instead of app names, SF Symbols, or remote images.\");\n }\n if ([...issueIds].some((id) => /onboarding-final-cta-slide-missing/.test(id))) {\n repairHints.push(\"For onboarding CTA violations, make the final pager page a dedicated CTA slide with `Começar grátis` and `Já tenho conta`; do not use a normal feature slide with CTA buttons only in the footer.\");\n }\n if ([...issueIds].some((id) => /onboarding-skip-not-top-right/.test(id))) {\n repairHints.push(\"For onboarding skip placement violations, move `Pular` into a top-right overlay aligned to the safe area and hide it on the final CTA slide.\");\n }\n if ([...issueIds].some((id) => /onboarding-storage-key-missing/.test(id))) {\n repairHints.push(\"For onboarding persistence violations, use the exact completion key `hasSeenOnboarding` in UserDefaults/AppStorage or DataStore.\");\n }\n if (issueIds.has(\"android-base-layout-feature-missing\")) {\n repairHints.push(\"For Android base layout feature coverage, derive the tabs/routes from every named feature in the prompt. Do not use generic buckets like Settings unless Settings is explicitly one of the requested app features.\");\n }\n if (issueIds.has(\"android-base-layout-premium-gate-missing\")) {\n repairHints.push(\"For Android premium feature coverage, wrap premium feature placeholder content with PremiumGate or an equivalent entitlement-state gate. Premium placeholders can show locked/paywall states until RevenueCat is fully configured.\");\n }\n return [\n `Tanya validation found task-specific problems before finalization. Repair attempt ${attempt} of ${maxAttempts}.`,\n \"Fix the implementation directly, rerun the relevant verification commands, then produce the required final report.\",\n \"If you already created a task commit before this validation repair, amend that task commit after fixing the files instead of creating a second task commit.\",\n \"Use `commit_platform_changes` with `amend: true` when amending is needed.\",\n \"\",\n \"Validation issues:\",\n ...issueLines,\n ...(blockerLines.length > 0 ? [\"\", \"Blocking verification failures:\", ...blockerLines] : []),\n ...(repairHints.length > 0 ? [\"\", \"Targeted repair instructions:\", ...repairHints.map((hint) => `- ${hint}`)] : []),\n \"\",\n \"Current changed files:\",\n manifest.changedFiles.length > 0 ? manifest.changedFiles.map((file) => `- ${file}`).join(\"\\n\") : \"- none\",\n ].join(\"\\n\");\n}\n\nfunction validationRepairSignature(manifest: TanyaFinalManifest): string {\n const issueIds = manifest.validation?.issues\n .filter((issue) => issue.severity === \"error\")\n .map((issue) => `${issue.id}:${issue.files?.join(\",\") ?? \"\"}`) ?? [];\n return [...issueIds, ...manifest.blockers].sort().join(\"|\") || \"unknown-validation-failure\";\n}\n\nfunction pruneStaleRepairReminders(messages: ChatMessage[]): ChatMessage[] {\n const isRepairReminder = (msg: ChatMessage | undefined): boolean => {\n if (!msg) return false;\n if (msg.role !== \"user\") return false;\n if (typeof msg.content !== \"string\") return false;\n return /Tanya validation found task-specific problems before finalization\\. Repair attempt/i.test(msg.content);\n };\n let lastIndex = -1;\n for (let i = 0; i < messages.length; i += 1) {\n if (isRepairReminder(messages[i])) lastIndex = i;\n }\n if (lastIndex === -1) return messages;\n return messages.filter((msg, idx) => idx === lastIndex || !isRepairReminder(msg));\n}\n\nfunction isTypeScriptProject(workspace: string): boolean {\n return existsSync(join(workspace, \"tsconfig.json\"));\n}\n\nfunction repairAttemptBudget(options: RunAgentOptions): number {\n const configured = typeof options.runContext?.metadata?.repairAttempts === \"number\"\n ? options.runContext.metadata.repairAttempts\n : typeof options.runContext?.metadata?.repairAttempts === \"string\"\n ? Number(options.runContext.metadata.repairAttempts)\n : options.repairAttempts;\n if (typeof configured === \"number\" && Number.isFinite(configured)) return Math.max(0, Math.min(5, Math.floor(configured)));\n if (!isCodingTask(options.runContext)) return 0;\n return isTypeScriptProject(options.cwd) ? 3 : 2;\n}\n\nfunction repairAttemptSnapshot(attempt: number, manifest: TanyaFinalManifest): RepairAttemptSnapshot {\n return {\n attempt,\n issueIds: manifest.validation?.issues.filter((issue) => issue.severity === \"error\").map((issue) => issue.id).sort() ?? [],\n blockerCount: manifest.blockers.length,\n changedFileCount: manifest.changedFiles.length,\n };\n}\n\nfunction commandLabel(toolName: string, input: unknown): string | null {\n const record = input && typeof input === \"object\" ? input as Record<string, unknown> : {};\n if (toolName === \"run_shell\") {\n const script = typeof record.script === \"string\"\n ? record.script.trim()\n : typeof record.command === \"string\"\n ? record.command.trim()\n : \"\";\n return script || null;\n }\n if (toolName === \"run_command\") {\n const command = typeof record.command === \"string\" ? record.command.trim() : \"\";\n const args = Array.isArray(record.args) ? record.args.filter((arg): arg is string => typeof arg === \"string\") : [];\n return command ? [command, ...args].join(\" \") : null;\n }\n if (/^validate_/.test(toolName)) return toolName;\n return null;\n}\n\nfunction toolResultMutatedFiles(toolName: string, result: { ok: boolean; files?: string[] }): boolean {\n if (!result.ok) return false;\n if ((result.files ?? []).length > 0) return true;\n return mutatingToolNames.has(toolName);\n}\n\nconst mutatingToolNames = new Set([\n \"write_file\",\n \"apply_patch\",\n \"search_replace\",\n \"copy_file\",\n \"copy_directory\",\n \"apply_artifact\",\n \"commit_platform_changes\",\n \"create_apple_app_icon_set\",\n \"create_android_launcher_icon_set\",\n \"create_android_foundation\",\n \"render_svg_to_png\",\n \"resize_image\",\n]);\n\nfunction requiredHighLevelTool(runContext: TanyaRunContext | undefined, prompt = \"\"): string | null {\n const includeRawPrompt = runContext?.metadata?.caller === \"cosmochat\";\n const text = [\n includeRawPrompt ? prompt : \"\",\n runContext?.task?.title,\n runContext?.task?.summary,\n ...(runContext?.instructions ?? []),\n ].filter(Boolean).join(\"\\n\").toLowerCase();\n if (/\\b(?:android\\s+foundation|foundation\\s+(?:—|-|for)\\s+android|fundações\\s+(?:—|-)\\s+android|build android foundation)\\b/.test(text)) {\n return \"create_android_foundation\";\n }\n if (/\\b(?:ios\\s+splash|splash\\s+screen\\s+(?:—|-|for)\\s+ios|splash\\s+screen.*\\bios\\b|create the splash screen.*\\bios\\b)\\b/.test(text)) {\n return \"create_ios_splash\";\n }\n return null;\n}\n\nfunction toolCallMayMutate(toolName: string, input: unknown): boolean {\n if (mutatingToolNames.has(toolName)) return true;\n const record = input && typeof input === \"object\" ? input as Record<string, unknown> : {};\n if (toolName === \"run_shell\") {\n const script = typeof record.script === \"string\" ? record.script : \"\";\n return /\\b(?:cat|printf|echo)\\b[\\s\\S]{0,200}>\\s*[^&|;\\n]|\\btee\\s+[^|;\\n]+|\\b(?:mkdir|touch|rm|mv|cp)\\s+|\\bsed\\s+-i\\b|\\bperl\\s+-pi\\b|\\bktlintFormat\\b/.test(script);\n }\n if (toolName === \"run_command\") {\n const command = typeof record.command === \"string\" ? record.command : \"\";\n const args = Array.isArray(record.args) ? record.args.join(\" \") : \"\";\n return /\\b(?:git|npm|pnpm|yarn|gradle|\\.\\/gradlew)\\b/.test(command) && /\\b(?:add|commit|install|ktlintFormat)\\b/.test(args);\n }\n return false;\n}\n\nfunction verificationKey(label: string): string {\n const isUnsafeXcodebuildPipe = /\\bxcodebuild\\b/i.test(label) && /\\|/.test(label) && !/set\\s+-o\\s+pipefail/.test(label);\n const usesGradle = /(?:^|[\\s;&|])(?:\\.\\/gradlew|gradle)\\b/i.test(label);\n const usesMobileBuildTool = /(?:^|[\\s;&|])(?:\\.\\/gradlew|gradle|xcodebuild)\\b/i.test(label);\n const isUnsafeGradlePipe = usesGradle && /\\|/.test(label) && !/set\\s+-o\\s+pipefail/.test(label);\n const masksExitCode = usesMobileBuildTool && /;\\s*echo\\s+[\"']?EXIT_CODE=\\$\\?[\"']?/i.test(label);\n if (isUnsafeGradlePipe || masksExitCode) return label.replace(/\\s+/g, \" \").trim();\n if (!isUnsafeXcodebuildPipe && /\\bxcodebuild\\s+build\\b/i.test(label)) return \"xcodebuild build\";\n if (!isUnsafeXcodebuildPipe && /\\bxcodebuild\\s+test\\b/i.test(label)) return \"xcodebuild test\";\n if (/\\bxcodebuild\\s+-list\\b/i.test(label)) return \"xcodebuild -list\";\n if (/\\bfastlane\\s+lanes\\b/i.test(label)) return \"fastlane lanes\";\n if (/\\bgit\\s+rev-parse\\s+--show-toplevel\\b/i.test(label)) return \"git root\";\n if (/\\bgit\\s+rev-parse\\s+--short\\s+HEAD\\b/i.test(label)) return \"git head\";\n return label.replace(/\\s+/g, \" \").trim();\n}\n\nfunction shellCommandSpiralKey(input: unknown): string | null {\n const record = input && typeof input === \"object\" ? input as Record<string, unknown> : {};\n const script = typeof record.script === \"string\"\n ? record.script\n : typeof record.command === \"string\"\n ? record.command\n : \"\";\n const normalized = script\n .replace(/\\$\\(\\s*go\\s+env\\s+GOMODCACHE\\s*\\)/g, \"$(go env GOMODCACHE)\")\n .replace(/\\s+/g, \" \")\n .trim();\n return normalized || null;\n}\n\nfunction shouldApplyShellSpiralDetector(command: string): boolean {\n return /\\bgrep\\b/i.test(command) &&\n /\\b(?:GOMODCACHE|go env GOMODCACHE|pkg\\/mod|github\\.com\\/danielgtaylor\\/huma\\/v2|huma\\/v2)\\b/i.test(command);\n}\n\nfunction artifactPathFromRead(toolName: string, input: unknown): string | null {\n if (toolName !== \"read_file\") return null;\n const record = input && typeof input === \"object\" ? input as Record<string, unknown> : {};\n const path = typeof record.path === \"string\" ? record.path.trim() : \"\";\n if (!path) return null;\n if (path.startsWith(\".tania/artifacts/\")) return path;\n if (path.startsWith(\"artifacts/\")) return path;\n return null;\n}\n\nfunction contextPathFromRead(toolName: string, input: unknown, runContext?: TanyaRunContext): string | null {\n if (toolName !== \"read_file\") return null;\n const record = input && typeof input === \"object\" ? input as Record<string, unknown> : {};\n const path = typeof record.path === \"string\" ? record.path.trim() : \"\";\n if (!path) return null;\n if (path.startsWith(\".tania/context/\")) return path;\n if ((runContext?.contextFiles ?? []).some((contextFile) => contextFile.path === path)) return path;\n return null;\n}\n\nfunction outsideWorkspaceReadMessage(workspace: string, toolName: string, input: unknown): string | null {\n if (toolName !== \"read_file\") return null;\n const record = input && typeof input === \"object\" ? input as Record<string, unknown> : {};\n const path = typeof record.path === \"string\" ? record.path.trim() : \"\";\n if (!path || !isAbsolute(path)) return null;\n const target = resolve(path);\n const rel = relative(workspace, target);\n if (!rel.startsWith(\"..\") && rel !== \"..\") return null;\n return [\n `Skipped external path outside workspace: ${path}.`,\n \"The caller should materialize external context inside the workspace or embed it in the prompt.\",\n \"Do not retry this absolute path; continue with the workspace-local context and report the skipped external read only if it matters.\",\n ].join(\" \");\n}\n\nfunction resolvePermissionMode(loadedMode: PermissionMode): PermissionMode {\n const rawMode = envValue(process.env, \"TANYA_MODE\")?.trim();\n return rawMode && permissionModes.has(rawMode as PermissionMode) ? rawMode as PermissionMode : loadedMode;\n}\n\nfunction permissionEventSource(decision: Decision, mode: PermissionMode): \"rule\" | \"engine\" | \"bypass\" {\n if (mode === \"bypass\" && decision.decision === \"allow\" && decision.reason === \"bypass-mode\") return \"bypass\";\n return decision.matchedRule ? \"rule\" : \"engine\";\n}\n\nfunction auditPermissionDecision(workspace: string, context: PermissionContext, tool: string, input: unknown, decision: Decision, source: \"user\" | \"rule\" | \"engine\" | \"bypass\"): void {\n const auditSource = mcpAuditSource(tool) ?? source;\n appendAuditDecision(workspace, {\n ts: new Date().toISOString(),\n runId: context.runId,\n ...(context.parentContext?.runId ? { parentRunId: context.parentContext.runId } : {}),\n tool,\n input,\n decision: decision.decision,\n source: auditSource,\n mode: context.mode,\n ...(decision.matchedRule ? { matchedRule: decision.matchedRule } : {}),\n ...(decision.reason ? { reason: decision.reason } : {}),\n ...(decision.projectedCostUsd !== undefined ? { projectedCostUsd: decision.projectedCostUsd } : {}),\n ...(decision.projectedTokens !== undefined ? { projectedTokens: decision.projectedTokens } : {}),\n ...(decision.thresholdUsd !== undefined ? { thresholdUsd: decision.thresholdUsd } : {}),\n ...(decision.thresholdTokens !== undefined ? { thresholdTokens: decision.thresholdTokens } : {}),\n });\n}\n\nfunction mcpAuditSource(tool: string): `mcp:${string}` | null {\n if (!tool.startsWith(\"mcp:\")) return null;\n const [, server] = tool.split(\":\");\n return server ? `mcp:${server}` : \"mcp:unknown\";\n}\n\nfunction providerKey(provider: ChatProvider): string {\n return `${provider.id}/${provider.model}`;\n}\n\nfunction auditModelRouted(workspace: string, context: PermissionContext, event: {\n stepType: StepType;\n provider: string;\n model: string;\n reason: string;\n cacheImpact?: \"hit\" | \"miss\" | \"unknown\";\n}): void {\n appendAuditDecision(workspace, {\n ts: new Date().toISOString(),\n runId: context.runId,\n ...(context.parentContext?.runId ? { parentRunId: context.parentContext.runId } : {}),\n tool: \"model_routed\",\n input: event,\n decision: \"allow\",\n source: \"engine\",\n mode: context.mode,\n reason: event.reason,\n });\n}\n\nfunction forcedRouteFromRunContext(runContext: TanyaRunContext | undefined): RouteTarget | null {\n const metadata = runContext?.metadata;\n if (!metadata) return null;\n const forcedModel = stringMetadata(metadata, \"forced_model\") ?? stringMetadata(metadata, \"forcedModel\");\n const forcedProvider = stringMetadata(metadata, \"forced_cli\") ??\n stringMetadata(metadata, \"forcedCli\") ??\n stringMetadata(metadata, \"forced_provider\") ??\n stringMetadata(metadata, \"forcedProvider\");\n if (!forcedModel && !forcedProvider) return null;\n if (forcedModel?.includes(\"/\") && !forcedProvider) {\n const [provider, model] = forcedModel.split(\"/\", 2);\n if (provider?.trim() && model?.trim()) return { provider: provider.trim(), model: model.trim() };\n }\n const provider = forcedProvider ?? inferForcedProvider(forcedModel ?? \"\");\n if (!provider || !forcedModel) return null;\n return { provider, model: forcedModel };\n}\n\nfunction stringMetadata(metadata: Record<string, unknown>, key: string): string | undefined {\n const value = metadata[key];\n return typeof value === \"string\" && value.trim() ? value.trim() : undefined;\n}\n\nfunction inferForcedProvider(model: string): string | null {\n if (/^deepseek-/i.test(model)) return \"deepseek\";\n if (/^(?:gpt-|o\\d|o\\d-|chatgpt)/i.test(model)) return \"openai\";\n if (/^claude-/i.test(model)) return \"claude\";\n if (/^gemini-/i.test(model)) return \"gemini\";\n if (/^qwen/i.test(model)) return \"qwen\";\n return null;\n}\n\nfunction auditEscalation(workspace: string, context: PermissionContext, event: {\n from: { provider: string; model: string };\n to: { provider: string; model: string };\n reason: \"parse_failure\" | \"schema_failure\" | \"context_too_small\";\n stepType: StepType;\n}): void {\n appendAuditDecision(workspace, {\n ts: new Date().toISOString(),\n runId: context.runId,\n ...(context.parentContext?.runId ? { parentRunId: context.parentContext.runId } : {}),\n tool: \"escalation_event\",\n input: event,\n decision: \"allow\",\n source: \"engine\",\n mode: context.mode,\n reason: event.reason,\n });\n}\n\nfunction outputRecord(result: ToolResult): Record<string, unknown> {\n return result.output && typeof result.output === \"object\" && !Array.isArray(result.output)\n ? result.output as Record<string, unknown>\n : {};\n}\n\nfunction withEditBlockRepairHint(tool: string, result: ToolResult): ToolResult {\n if (tool !== \"edit_block\" || result.ok) return result;\n const output = outputRecord(result);\n const candidateExcerpt = typeof output.candidateExcerpt === \"string\" && output.candidateExcerpt.trim()\n ? output.candidateExcerpt.trim()\n : \"\";\n const hint = candidateExcerpt\n ? `consider re-reading the file and emitting a closer search block. Closest candidate excerpt:\\n${candidateExcerpt}`\n : \"consider re-reading the file and emitting a closer search block\";\n return {\n ...result,\n error: result.error ? `${result.error}; ${hint}` : hint,\n output: { ...output, repairHint: hint },\n };\n}\n\nconst shellSafetyRepairHint = [\n \"Your cleanup command was blocked by Tanya's safety policy.\",\n \"Safer alternatives:\",\n \"- For build artifacts: rely on the next run's clean step; don't manually rm\",\n \"- For temporary files: use mktemp -d and let the OS clean /tmp eventually\",\n \"- For workspace state: use git clean -fd inside the workspace instead\",\n \"Re-attempt the task; cleanup isn't required for verification.\",\n].join(\"\\n\");\n\nfunction toolResultReason(result: ToolResult): string | undefined {\n const output = outputRecord(result);\n const reason = output.reason;\n return typeof reason === \"string\" ? reason : undefined;\n}\n\nfunction withShellSafetyRepairHint(result: ToolResult): ToolResult {\n if (result.ok || toolResultReason(result) !== \"shell_safety_block\") return result;\n const output = outputRecord(result);\n const error = result.error && result.error.includes(shellSafetyRepairHint)\n ? result.error\n : [result.error, shellSafetyRepairHint].filter(Boolean).join(\"\\n\\n\");\n return {\n ...result,\n error,\n output: { ...output, repairHint: shellSafetyRepairHint },\n };\n}\n\nfunction withRunnerRepairHints(tool: string, result: ToolResult): ToolResult {\n return withShellSafetyRepairHint(withEditBlockRepairHint(tool, result));\n}\n\nfunction networkFailureCommandText(toolName: string, input: unknown): string {\n const record = input && typeof input === \"object\" ? input as Record<string, unknown> : {};\n if (toolName === \"run_shell\") {\n return typeof record.script === \"string\"\n ? record.script\n : typeof record.command === \"string\" ? record.command : \"\";\n }\n if (toolName === \"run_command\") {\n const command = typeof record.command === \"string\" ? record.command : \"\";\n const args = Array.isArray(record.args) ? record.args.filter((arg): arg is string => typeof arg === \"string\").join(\" \") : \"\";\n return `${command} ${args}`.trim();\n }\n return \"\";\n}\n\nfunction looksLikeNetworkOrDependencyFailure(toolName: string, input: unknown, result: ToolResult): boolean {\n if (result.ok) return false;\n if (toolName !== \"run_shell\" && toolName !== \"run_command\") return false;\n const command = networkFailureCommandText(toolName, input);\n const output = [result.summary, result.error, typeof result.output === \"string\" ? result.output : \"\"].join(\"\\n\");\n return /\\b(?:pip3?|python3?\\s+-m\\s+pip|npm\\s+(?:install|i)|pnpm\\s+install|yarn\\s+install|bun\\s+install|curl|wget|requests|beautifulsoup|bs4)\\b/i.test(command) ||\n /\\b(?:ENOTFOUND|ECONNRESET|ECONNREFUSED|ETIMEDOUT|EAI_AGAIN|network|DNS|timeout|certificate|Could not resolve|Temporary failure|No matching distribution|command not found: pip|pip: command not found)\\b/i.test(output);\n}\n\nfunction buildNetworkFallbackReminder(): string {\n return [\n \"Network or dependency operations failed twice.\",\n \"Stop retrying the same live network/install path in this run.\",\n \"Scaffold a local mock fallback so the task can complete:\",\n \"- include deterministic sample data or a mock response path\",\n \"- keep the real network code path when practical\",\n \"- document mock versus live behavior and the network/dependency limitation in README.md\",\n \"Then run a local verification command that does not require the unavailable network path.\",\n ].join(\"\\n\");\n}\n\nfunction auditEditBlockCandidate(workspace: string, context: PermissionContext, input: unknown, result: ToolResult): void {\n const output = outputRecord(result);\n if (output.matchPolicy !== \"fuzzy\") return;\n if (output.recoveredVia === undefined || output.recoveredVia === \"exact\") return;\n appendAuditDecision(workspace, {\n ts: new Date().toISOString(),\n runId: context.runId,\n ...(context.parentContext?.runId ? { parentRunId: context.parentContext.runId } : {}),\n tool: \"edit_block\",\n input: {\n path: typeof output.path === \"string\" ? output.path : undefined,\n requested: input,\n fuzzyCandidate: {\n recoveredVia: output.recoveredVia,\n confidence: output.confidence,\n candidateExcerpt: output.candidateExcerpt,\n },\n },\n decision: \"allow\",\n source: \"engine\",\n mode: context.mode,\n reason: \"fuzzy-candidate-applied\",\n });\n}\n\nfunction deniedPermissionResult(decision: Decision, fallback = \"permission denied\"): {\n ok: false;\n summary: string;\n error: string;\n output: { ok: false; error: string; rule?: string; reason?: string };\n} {\n const matched = decision.matchedRule ?? decision.reason;\n const error = matched ? `denied by rule: ${matched}` : fallback;\n return {\n ok: false,\n summary: error,\n error,\n output: {\n ok: false,\n error,\n ...(decision.matchedRule ? { rule: decision.matchedRule } : {}),\n ...(decision.reason ? { reason: decision.reason } : {}),\n },\n };\n}\n\nfunction permissionCacheKey(tool: string, input: unknown): string {\n return `${tool}:${inputShape(input)}`;\n}\n\nfunction permissionRequestFromDecision(id: string, tool: string, input: unknown, decision: Decision): PermissionRequest {\n return {\n id,\n tool,\n input,\n ...(decision.matchedRule ? { matchedRule: decision.matchedRule } : {}),\n ...(decision.projectedCostUsd !== undefined ? { projectedCostUsd: decision.projectedCostUsd } : {}),\n ...(decision.projectedTokens !== undefined ? { projectedTokens: decision.projectedTokens } : {}),\n };\n}\n\nfunction projectedToolSpend(input: unknown, provider: ChatProvider): { projectedTokens: number; projectedUsd: number } {\n const record = input && typeof input === \"object\" ? input as Record<string, unknown> : {};\n const projectedTokens = numberField(record, \"projectedTokens\") ??\n numberField(record, \"estimatedTokens\") ??\n numberField(record, \"estimatedOutputTokens\") ??\n 0;\n const explicitUsd = numberField(record, \"projectedCostUsd\") ?? numberField(record, \"estimatedCostUsd\");\n const projectedUsd = explicitUsd ?? (\n projectedTokens > 0\n ? estimateRunCost({\n provider: provider.id,\n model: provider.model,\n promptTokens: 0,\n completionTokens: projectedTokens,\n }).usd ?? 0\n : 0\n );\n return { projectedTokens, projectedUsd };\n}\n\nfunction numberField(record: Record<string, unknown>, key: string): number | undefined {\n const value = record[key];\n if (typeof value === \"number\" && Number.isFinite(value) && value >= 0) return value;\n if (typeof value === \"string\" && value.trim()) {\n const parsed = Number(value);\n if (Number.isFinite(parsed) && parsed >= 0) return parsed;\n }\n return undefined;\n}\n\nfunction truthyEnv(key: string): boolean {\n return /^(1|true|yes|on)$/i.test(envValue(process.env, key).trim());\n}\n\nfunction promptBudgetRatio(): number {\n const parsed = Number(envValue(process.env, \"TANYA_PROMPT_BUDGET_RATIO\"));\n return Number.isFinite(parsed) && parsed > 0 && parsed <= 1 ? parsed : 0.25;\n}\n\nfunction subtaskMaxParallel(): number {\n return Math.max(1, Math.floor(numberEnvValue(process.env, \"TANYA_SUBTASK_MAX_PARALLEL\", 3)));\n}\n\nfunction subtaskCycleCheckEnabled(): boolean {\n const raw = envValue(process.env, \"TANYA_SUBTASK_CYCLE_CHECK\").trim();\n return raw === \"\" || !/^(0|false|off|no)$/i.test(raw);\n}\n\nfunction escalationCap(): number {\n return Math.max(0, Math.floor(numberEnvValue(process.env, \"TANYA_ESCALATION_CAP\", 5)));\n}\n\n// reasoningCapForTurn picks the per-turn reasoning-token budget. An explicit\n// per-route reasoningCap always wins. Otherwise the budget falls back to two\n// env-configurable tiers — short (planning / tool_call / unknown) and long\n// (synthesis / verification / reasoning) — so heavier reasoning models can be\n// given more headroom without hand-writing a full routes.json route table.\nexport function reasoningCapForTurn(stepType: StepType, route?: ResolvedRoute): number {\n if (route?.reasoningCap?.maxTokens) return route.reasoningCap.maxTokens;\n const shortCap = Math.max(1, Math.floor(numberEnvValue(process.env, \"TANYA_REASONING_CAP_SHORT\", 2_000)));\n const longCap = Math.max(1, Math.floor(numberEnvValue(process.env, \"TANYA_REASONING_CAP_LONG\", 8_000)));\n return stepType === \"planning\" || stepType === \"tool_call\" || stepType === \"unknown\" ? shortCap : longCap;\n}\n\nfunction resultOutputText(result: ToolResult): string | null {\n if (result.output === undefined || result.output === null) return null;\n if (typeof result.output === \"string\") return result.output;\n try {\n return JSON.stringify(result.output, null, 2);\n } catch {\n return String(result.output);\n }\n}\n\nfunction truncateToolResultForModel(params: {\n tool: TanyaTool;\n result: ToolResult;\n workspace: string;\n runId: string;\n toolCallId: string;\n expandCallsRemaining: number;\n}): { modelResult: ToolResult; truncated: boolean } {\n if (params.tool.truncateLargeResults === false) {\n return { modelResult: params.result, truncated: false };\n }\n const output = resultOutputText(params.result);\n if (!output || output.length <= TOOL_RESULT_TRUNCATE_THRESHOLD) {\n return { modelResult: params.result, truncated: false };\n }\n\n writeCachedToolResult(params.workspace, params.runId, params.toolCallId, output);\n const omittedChars = Math.max(0, output.length - TOOL_RESULT_HEAD_CHARS - TOOL_RESULT_TAIL_CHARS);\n const marker = [\n `<truncated ${omittedChars} chars; ask for more (tool_call_id=${params.toolCallId}; `,\n `you have ${Math.max(0, params.expandCallsRemaining)} expand_result call${params.expandCallsRemaining === 1 ? \"\" : \"s\"} left this turn)>`,\n ].join(\"\");\n const modelOutput = [\n output.slice(0, TOOL_RESULT_HEAD_CHARS),\n marker,\n output.slice(-TOOL_RESULT_TAIL_CHARS),\n ].join(\"\\n\");\n return {\n modelResult: {\n ...params.result,\n summary: `${params.result.summary} Output was truncated for the model; use expand_result if more is needed.`,\n output: modelOutput,\n },\n truncated: true,\n };\n}\n\nexport async function runAgent(options: RunAgentOptions): Promise<RunAgentResult> {\n const parentContext = options.parentContext;\n const workspace = parentContext\n ? resolveSubAgentWorkspace(parentContext.workspace, options.cwd)\n : resolveWorkspace(options.cwd);\n if (parentContext) {\n const mergedRunContext = mergeRunContexts(parentContext.runContext, options.runContext);\n if (mergedRunContext) options.runContext = mergedRunContext;\n options.history = [...(parentContext.history ?? []), ...(options.history ?? [])];\n }\n const beforeGitSnapshot = await captureGitSnapshot(workspace);\n const registry = new ToolRegistry();\n await loadMcpToolsForWorkspace({ cwd: workspace, registry, sink: options.sink });\n const runStartedAt = new Date();\n const startedAt = runStartedAt.getTime();\n const runId = options.runId ?? (parentContext\n ? childRunId(parentContext.runId, parentContext.childIndex ?? 1)\n : createRootRunId(runStartedAt));\n const loadedPermissions = loadPermissionRules({ cwd: workspace });\n const inheritedPermissions = parentContext\n ? mergeInheritedPermissionRules(parentContext.permissionContext.rules, loadedPermissions.rules)\n : { rules: loadedPermissions.rules, warnings: [] };\n const rulesWithBudget = applyTokenBudgetRule(inheritedPermissions.rules, parentContext?.tokenBudget);\n const localMode = resolvePermissionMode(rulesWithBudget.mode);\n const permissionMode = parentContext\n ? stricterPermissionMode(parentContext.permissionContext.mode, localMode)\n : localMode;\n const permissionContext: PermissionContext = {\n mode: permissionMode,\n rules: { ...rulesWithBudget, mode: permissionMode },\n runId,\n cwd: workspace,\n ...(parentContext ? { parentContext: parentContext.permissionContext } : {}),\n };\n for (const warning of inheritedPermissions.warnings) {\n await options.sink({ type: \"status\", message: `Sub-agent permission inheritance warning: ${warning.reason}` });\n }\n const fileReadDedup = new FileReadDedupCache(workspace);\n const permissionAnswers = new Map<string, { answer: HostPermissionAnswer; source: \"user\" | \"engine\" }>();\n const changedFiles: string[] = [];\n let changed = changedFiles;\n let toolCallCount = 0;\n let toolErrorCount = 0;\n let totalPromptTokens = 0;\n let totalCompletionTokens = 0;\n let totalReasoningTokens = 0;\n let totalToolResultTokens = 0;\n let runSpendTokens = 0;\n let runSpendUsd = 0;\n let activeProvider = options.provider;\n let lastProviderKey = providerKey(activeProvider);\n if (options.routing?.enabled) {\n try {\n const forcedRoute = forcedRouteFromRunContext(options.runContext);\n const initialRoute = resolveRouteWithContextGuard({\n stepType: \"planning\",\n table: options.routing.table,\n messages: [...(options.history ?? []), { role: \"user\", content: options.prompt }],\n ...(forcedRoute ? { forcedRoute } : {}),\n });\n activeProvider = options.routing.providerFactory(initialRoute);\n lastProviderKey = providerKey(activeProvider);\n } catch {\n activeProvider = options.provider;\n lastProviderKey = providerKey(activeProvider);\n }\n }\n const historyBlock = buildHistoryBlock(await readRecentTaskHistory(workspace));\n const promptBudgetEvents: Array<{ droppedSections: string[]; totalTokens: number; cap: number }> = [];\n const litePrompt = truthyEnv(\"TANYA_LITE_PROMPT\");\n if (litePrompt) {\n try {\n await buildRepoMap(workspace, { writeCache: true });\n } catch {\n // Repo-map is advisory context. Indexing failures should not block a run.\n }\n }\n let repoMapTokens = 0;\n const systemPrompt = buildSystemPrompt(workspace, options.runContext, historyBlock, options.prompt, {\n lite: litePrompt,\n ...(activeProvider.contextWindow ? { contextWindow: activeProvider.contextWindow } : {}),\n promptBudgetRatio: promptBudgetRatio(),\n onPromptBudgetExceeded: (event) => {\n promptBudgetEvents.push(event);\n },\n onRepoMapTokens: (tokens) => {\n repoMapTokens = tokens;\n },\n });\n const systemPromptTokens = Math.ceil(systemPrompt.length / 4);\n let messages: ChatMessage[] = [\n { role: \"system\", content: systemPrompt },\n ...(options.history ?? []),\n { role: \"user\", content: options.prompt },\n ];\n const maxTurns = options.maxTurns ?? 12;\n let finalText = \"\";\n let requestedFinalReport = false;\n let requestedCommitRepair = false;\n let validationRepairAttempts = 0;\n let lastValidationRepairSignature: string | null = null;\n const seenValidationRepairSignatures = new Set<string>();\n const repairAttempts: RepairAttemptSnapshot[] = [];\n let consecutiveNoToolNoReportTurns = 0;\n const MAX_NO_TOOL_NO_REPORT_TURNS = 2;\n const maxRepairAttempts = repairAttemptBudget(options);\n const verificationLines: string[] = [];\n const passedVerificationKeys = new Map<string, number>();\n const skippedDuplicateKeys = new Map<string, number>();\n const shellCommandSpiralCounts = new Map<string, number>();\n let shellCommandSpiralAdvisorySent = false;\n let consecutiveNetworkFailures = 0;\n let networkFallbackReminderSent = false;\n let networkFallbackReminderPending = false;\n let mutationRevision = 0;\n let readArtifactPaths: string[] = [];\n let readContextPaths: string[] = [];\n let createdArtifactPaths: string[] = [];\n const requiredTool = requiredHighLevelTool(options.runContext, options.prompt);\n let requiredToolUsed = requiredTool ? false : true;\n let toolCallCorrectionAttempts = 0;\n let parseEscalationUsed = false;\n let forcedNextRoute: { target: RouteTarget; stepType: StepType; reason: string } | null = null;\n let childSequence = 0;\n const childVerdicts: ChildVerdict[] = [];\n const subtaskSemaphore = new AsyncSemaphore(subtaskMaxParallel());\n const budgetLedger = new BudgetLedger({\n ...(parentContext?.tokenBudget?.max_tokens !== undefined ? { maxTokens: parentContext.tokenBudget.max_tokens } : {}),\n ...(parentContext?.tokenBudget?.max_usd !== undefined ? { maxUsd: parentContext.tokenBudget.max_usd } : {}),\n });\n\n function evictReasoningArchiveForCompaction(): void {\n try {\n evictReasoningFromArchive(workspace, runId, 0);\n } catch {\n // Reasoning archive eviction is best-effort; compaction must still proceed.\n }\n }\n\n for (const event of promptBudgetEvents) {\n await options.sink({ type: \"prompt_budget_exceeded\", ...event });\n auditPermissionDecision(\n workspace,\n permissionContext,\n \"system_prompt\",\n event,\n { decision: \"allow\", reason: \"prompt-budget-enforced\" },\n \"engine\",\n );\n }\n\n async function runSubAgentTask(request: SubAgentTaskRequest): Promise<SubAgentTaskResult> {\n childSequence += 1;\n const subRunId = childRunId(runId, childSequence);\n return subtaskSemaphore.run(async () => {\n const recentPrompts = [\n options.prompt,\n ...messages\n .filter((message) => message.role === \"user\" && typeof message.content === \"string\")\n .map((message) => message.content ?? \"\"),\n ].slice(-3);\n if (subtaskCycleCheckEnabled() && isLikelySubtaskCycle(request.prompt, recentPrompts)) {\n throw new Error(\"cycle_detected: child prompt is too similar to recent parent prompts\");\n }\n\n const reservation = budgetLedger.reserve({\n ...(request.token_budget?.max_tokens !== undefined ? { maxTokens: request.token_budget.max_tokens } : {}),\n ...(request.token_budget?.max_usd !== undefined ? { maxUsd: request.token_budget.max_usd } : {}),\n });\n let usedForRelease: { maxTokens?: number; maxUsd?: number } = {};\n try {\n const childWorkspace = resolveSubAgentWorkspace(workspace, request.workspace);\n const historySnapshot = messages.filter((message) => message.role !== \"system\").map((message) => ({ ...message }));\n const childRunContext = {\n metadata: {\n subAgent: true,\n goldenTask: false,\n goldenTaskCandidate: false,\n ...(request.skill_pack_overrides?.length\n ? { subAgentSkillPackOverrides: request.skill_pack_overrides }\n : {}),\n },\n };\n await options.sink({\n type: \"subtask_started\",\n subRunId,\n parentRunId: runId,\n prompt: request.prompt,\n workspace: childWorkspace,\n });\n const childProvider = request.model && options.routing\n ? options.routing.providerFactory(request.model)\n : activeProvider;\n const childRouting = request.model ? undefined : options.routing;\n const runResult = await runAgent({\n provider: childProvider,\n prompt: request.prompt,\n cwd: childWorkspace,\n sink: createSubAgentSink(options.sink, subRunId),\n maxTurns: request.max_turns ?? 20,\n runContext: childRunContext,\n parentContext: {\n runId,\n workspace,\n permissionContext,\n history: historySnapshot,\n childIndex: childSequence,\n ...(options.runContext ? { runContext: options.runContext } : {}),\n ...(request.token_budget ? { tokenBudget: request.token_budget } : {}),\n },\n runId: subRunId,\n ...(options.signal ? { signal: options.signal } : {}),\n ...(options.onPermissionRequest ? { onPermissionRequest: options.onPermissionRequest } : {}),\n ...(childRouting ? { routing: childRouting } : {}),\n });\n const validationErrors = runResult.manifest.validation?.issues\n .filter((issue) => issue.severity === \"error\")\n .map((issue) => issue.message) ?? [];\n const tokensUsed = {\n in: runResult.metrics?.promptTokens ?? 0,\n out: runResult.metrics?.completionTokens ?? 0,\n reasoning: runResult.metrics?.reasoningTokens ?? 0,\n };\n const usedTokens = tokensUsed.in + tokensUsed.out + tokensUsed.reasoning;\n const usedUsd = estimateRunCost({\n provider: childProvider.id,\n model: childProvider.model,\n promptTokens: tokensUsed.in,\n completionTokens: tokensUsed.out,\n reasoningTokens: tokensUsed.reasoning,\n }).usd ?? 0;\n usedForRelease = {\n maxTokens: usedTokens,\n maxUsd: usedUsd,\n };\n const budgetExceeded = (request.token_budget?.max_tokens !== undefined && usedTokens > request.token_budget.max_tokens) ||\n (request.token_budget?.max_usd !== undefined && usedUsd > request.token_budget.max_usd);\n const budgetBlockers = budgetExceeded ? [\"budget exceeded\"] : [];\n const blockers = uniqueSorted([...runResult.manifest.blockers, ...validationErrors, ...budgetBlockers]);\n const verdict = blockers.length === 0 ? \"passed\" : \"failed\";\n const childVerdict: ChildVerdict = {\n subRunId,\n verdict,\n blockers,\n changedFiles: uniqueSorted(runResult.manifest.changedFiles),\n summary: budgetExceeded ? \"Subtask exceeded its token budget.\" : runResult.message.slice(0, 2_000),\n treatFailureAs: request.treat_failure_as ?? \"blocker\",\n };\n childVerdicts.push(childVerdict);\n auditPermissionDecision(workspace, permissionContext, \"task\", {\n subRunId,\n verdict,\n blockers,\n treatFailureAs: childVerdict.treatFailureAs,\n }, {\n decision: verdict === \"passed\" ? \"allow\" : \"deny\",\n reason: \"child-verdict\",\n }, \"engine\");\n await options.sink({\n type: \"subtask_completed\",\n subRunId,\n parentRunId: runId,\n verdict,\n summary: runResult.message.slice(0, 500),\n tokensUsed,\n });\n return {\n ok: verdict === \"passed\",\n subRunId,\n verdict,\n blockers,\n changedFiles: childVerdict.changedFiles,\n summary: childVerdict.summary,\n tokensUsed,\n childRunIds: [],\n manifest: runResult.manifest,\n runResult,\n treatFailureAs: request.treat_failure_as ?? \"blocker\",\n ...(budgetExceeded ? { cancelled: true, reason: \"budget\" } : {}),\n };\n } finally {\n budgetLedger.release(reservation.id, usedForRelease);\n }\n });\n }\n\n async function syncArtifactOutput(): Promise<string[]> {\n const outputRootValue = options.runContext?.metadata?.artifactOutputRoot;\n if (typeof outputRootValue !== \"string\" || !outputRootValue.trim()) return [];\n const localOutputRoot = resolve(workspace, \".tania\", \"artifact-output\");\n if (!existsSync(localOutputRoot)) return [];\n const localFiles = await listFilesRecursive(localOutputRoot);\n if (localFiles.length === 0) return [];\n const outputRoot = resolve(outputRootValue);\n const copied: string[] = [];\n for (const relPath of localFiles) {\n const source = resolve(localOutputRoot, relPath);\n const target = resolve(outputRoot, relPath);\n const sourceStat = await stat(source);\n if (!sourceStat.isFile()) continue;\n await mkdir(dirname(target), { recursive: true });\n await cp(source, target, { force: true, recursive: true });\n copied.push(`artifacts/${relPath}`);\n }\n return uniqueSorted(copied);\n }\n\n function finalMetrics(manifest: TanyaFinalManifest): FinalMetrics {\n return {\n durationMs: Date.now() - startedAt,\n toolCallCount,\n toolErrorCount,\n changedFileCount: manifest.changedFiles.length,\n repairAttemptCount: repairAttempts.length,\n retryAttemptCount: options.retryAttempt ?? 0,\n promptTokens: totalPromptTokens,\n completionTokens: totalCompletionTokens,\n reasoningTokens: totalReasoningTokens,\n costUsd: runSpendUsd,\n systemPromptTokens,\n repoMapTokens,\n toolResultTokens: totalToolResultTokens,\n };\n }\n\n async function finishRun(finalMessage: string, manifest: TanyaFinalManifest): Promise<FinalMetrics> {\n const metrics = finalMetrics(manifest);\n await options.sink({\n type: \"final\",\n message: finalMessage,\n files: manifest.changedFiles,\n manifest,\n metrics,\n });\n await cleanupMaterializedContext(workspace, manifest, options.runContext);\n logRunSummarySilently({\n workspace,\n runId,\n ...(parentContext?.runId ? { parentRunId: parentContext.runId } : {}),\n prompt: options.prompt,\n provider: activeProvider.id,\n model: activeProvider.model,\n metrics,\n manifest,\n });\n return metrics;\n }\n\n function pendingToolCallsForRouting(): Array<ToolCall & { preferredModel?: TanyaTool[\"preferredModel\"] }> {\n const lastAssistant = [...messages].reverse().find((message) => message.role === \"assistant\");\n return (lastAssistant?.tool_calls ?? []).map((call) => {\n const preferredModel = registry.get(call.function.name)?.preferredModel;\n return preferredModel ? { ...call, preferredModel } : call;\n });\n }\n\n function preferredRouteForStep(stepType: StepType): ResolvedRoute | null {\n if (stepType !== \"tool_call\" && stepType !== \"verification\") return null;\n const pending = pendingToolCallsForRouting();\n for (const call of pending) {\n const preferred = call.preferredModel;\n if (!preferred) continue;\n if (preferred.match && preferred.match !== stepType) continue;\n if (estimateCompactTokens(messages) > contextWindowForTarget(preferred)) continue;\n return {\n provider: preferred.provider,\n model: preferred.model,\n match: stepType,\n escalate: true,\n source: \"session\",\n reason: `preferred model for tool ${call.function.name}`,\n };\n }\n return null;\n }\n\n async function routeProviderForTurn(turn: number): Promise<{\n provider: ChatProvider;\n stepType: StepType;\n route?: ResolvedRoute;\n }> {\n if (!options.routing?.enabled) {\n return { provider: activeProvider, stepType: \"unknown\" };\n }\n\n if (forcedNextRoute) {\n const forced = forcedNextRoute;\n forcedNextRoute = null;\n const provider = options.routing.providerFactory(forced.target);\n const key = providerKey(provider);\n const cacheImpact: \"hit\" | \"miss\" = key === lastProviderKey ? \"hit\" : \"miss\";\n activeProvider = provider;\n lastProviderKey = key;\n const event = {\n type: \"model_routed\" as const,\n stepType: forced.stepType,\n provider: provider.id,\n model: provider.model,\n reason: forced.reason,\n cacheImpact,\n };\n await options.sink(event);\n auditModelRouted(workspace, permissionContext, event);\n return { provider, stepType: forced.stepType };\n }\n\n const classifierState = {\n messages,\n turnIndex: turn,\n pendingToolCalls: pendingToolCallsForRouting(),\n cwd: workspace,\n ...(options.prompt ? { prompt: options.prompt } : {}),\n ...(options.runContext ? { runContext: options.runContext } : {}),\n };\n const stepType = classifyStep(classifierState);\n const forcedRoute = forcedRouteFromRunContext(options.runContext);\n const route = forcedRoute\n ? resolveRouteWithContextGuard({\n stepType,\n table: options.routing.table,\n messages,\n prompt: options.prompt,\n cwd: workspace,\n ...(options.runContext ? { runContext: options.runContext } : {}),\n forcedRoute,\n })\n : preferredRouteForStep(stepType) ?? resolveRouteWithContextGuard({\n stepType,\n table: options.routing.table,\n messages,\n prompt: options.prompt,\n cwd: workspace,\n ...(options.runContext ? { runContext: options.runContext } : {}),\n });\n const provider = options.routing.providerFactory(route);\n const key = providerKey(provider);\n const cacheImpact: \"hit\" | \"miss\" = key === lastProviderKey ? \"hit\" : \"miss\";\n activeProvider = provider;\n lastProviderKey = key;\n const event = {\n type: \"model_routed\" as const,\n stepType,\n provider: provider.id,\n model: provider.model,\n reason: route.reason,\n cacheImpact,\n };\n await options.sink(event);\n if (route.cascade && route.cascade.selectedIndex > 0) {\n await options.sink({\n type: \"provider.raw\",\n provider: provider.id,\n model: provider.model,\n event: {\n type: \"model_routed\",\n reason: \"cascade-fit\",\n stepType,\n provider: provider.id,\n model: provider.model,\n attempted_routes: route.cascade.attemptedRoutes,\n estimated_tokens: route.cascade.estimatedTokens,\n safety_factor: route.cascade.safetyFactor,\n selected_route: route.cascade.selectedRoute,\n },\n });\n }\n auditModelRouted(workspace, permissionContext, event);\n return { provider, stepType, route };\n }\n\n async function routeFallbackProvider(params: {\n fallback: RouteTarget;\n stepType: StepType;\n reason: string;\n }): Promise<ChatProvider> {\n const provider = options.routing?.providerFactory(params.fallback) ?? activeProvider;\n const key = providerKey(provider);\n const cacheImpact: \"hit\" | \"miss\" = key === lastProviderKey ? \"hit\" : \"miss\";\n activeProvider = provider;\n lastProviderKey = key;\n const event = {\n type: \"model_routed\" as const,\n stepType: params.stepType,\n provider: provider.id,\n model: provider.model,\n reason: params.reason,\n cacheImpact,\n };\n await options.sink(event);\n auditModelRouted(workspace, permissionContext, event);\n return provider;\n }\n\n async function scheduleEscalation(params: {\n from: ChatProvider;\n route?: ResolvedRoute;\n stepType: StepType;\n reason: \"parse_failure\" | \"schema_failure\" | \"context_too_small\";\n }): Promise<boolean> {\n if (!options.routing?.enabled) return false;\n if (params.route?.escalate === false) return false;\n const target = params.route?.fallback ?? options.routing.table.defaults;\n if (`${target.provider}/${target.model}` === `${params.from.id}/${params.from.model}`) return false;\n const cap = escalationCap();\n if (sessionEscalations >= cap) {\n throw new EscalationExhaustedError(`Escalation cap reached (${cap}) for this session.`);\n }\n sessionEscalations += 1;\n const event = {\n type: \"escalation_event\" as const,\n from: { provider: params.from.id, model: params.from.model },\n to: { provider: target.provider, model: target.model },\n reason: params.reason,\n stepType: params.stepType,\n };\n await options.sink(event);\n auditEscalation(workspace, permissionContext, event);\n forcedNextRoute = {\n target,\n stepType: params.stepType,\n reason: `escalated after ${params.reason}`,\n };\n return true;\n }\n\n let compactionsThisRun = 0;\n const COMPACTION_LIMIT = 3;\n\n for (let turn = 0; turn < maxTurns; turn += 1) {\n if (parentContext && options.signal?.aborted) {\n const manifest = await buildFinalManifest({\n workspace,\n beforeGitSnapshot,\n changed,\n verificationLines,\n toolErrorCount,\n readArtifactPaths,\n readContextPaths,\n createdArtifactPaths,\n blockers: [\"run cancelled\"],\n childVerdicts,\n runContext: options.runContext,\n prompt: options.prompt,\n runId,\n verifierShell: options.verifierShell,\n });\n const metrics = await finishRun(\"Run cancelled.\", manifest);\n return { message: \"Run cancelled.\", manifest, metrics };\n }\n let turnSpendTokens = 0;\n let turnSpendUsd = 0;\n let expandResultCallsThisTurn = 0;\n const compactTokenEstimate = estimateCompactTokens(messages);\n if (compactTokenEstimate >= CONTEXT_TOKEN_LIMIT * 0.85) {\n const compacted = microcompact(messages, {\n tokenBudget: Math.floor(CONTEXT_TOKEN_LIMIT * 0.85),\n foldRatio: 0.2,\n });\n if (compacted.foldedPairs > 0) {\n evictReasoningArchiveForCompaction();\n await appendArchive(runId, toArchivedMessages(compacted.archivedMessages), { workspace });\n messages = compacted.messages;\n fileReadDedup.clear();\n await options.sink({\n type: \"compact_event\",\n compactType: \"micro\",\n removedTokens: compacted.removedTokens,\n });\n }\n }\n\n if (estimateCompactTokens(messages) >= CONTEXT_TOKEN_LIMIT * 0.85) {\n const snipped = snipLowSignal(messages);\n if (snipped.snippedCount > 0) {\n evictReasoningArchiveForCompaction();\n const beforeSnipTokens = estimateCompactTokens(messages);\n await appendArchive(runId, toArchivedMessages(snipped.archivedMessages), { workspace });\n messages = snipped.messages;\n fileReadDedup.clear();\n const afterSnipTokens = estimateCompactTokens(messages);\n await options.sink({\n type: \"compact_event\",\n compactType: \"snip\",\n removedTokens: Math.max(0, beforeSnipTokens - afterSnipTokens),\n });\n }\n }\n\n let routed = await routeProviderForTurn(turn);\n let turnProvider = routed.provider;\n const reasoningCapTokens = reasoningCapForTurn(routed.stepType, routed.route);\n let turnReasoningTokens = 0;\n let reasoningBudgetExceeded = false;\n\n await options.sink({ type: \"message_start\" });\n let assistantText = \"\";\n let assistantReasoningText = \"\";\n let rawToolCalls: unknown[] = [];\n let schemaFlattenedThisTurn = false;\n\n const codingProviderOptions = isCodingTask(options.runContext)\n ? { temperature: 0, topP: 0.2 }\n : {};\n // Provider transient retry: if the stream errors before any content or tool\n // call has been emitted (e.g. DeepSeek 'fetch failed' or 'timed out before\n // streaming a response'), retry the same turn once. Once content has been\n // streamed, retry would corrupt the conversation — fall through to the\n // existing repair-loop instead. This eliminates the most common case of\n // losing a whole loop cycle to a 1-second network blip.\n let providerAttempt = 0;\n let contextCompactionsThisTurn = 0;\n let routeFallbackIndex = 0;\n const routeFallbackTargets = [\n routed.route?.fallback,\n options.routing?.table.defaults,\n ].filter((target): target is RouteTarget => Boolean(target));\n const PROVIDER_TRANSIENT_RETRIES = 1;\n streamLoop: while (true) {\n try {\n for await (const delta of turnProvider.streamChat({\n messages,\n tools: registry.list().map((tool) => tool.definition),\n onProviderThrottle: (event) => {\n void Promise.resolve(options.sink({\n type: \"provider_throttle\",\n provider: event.provider,\n attempt: event.attempt,\n waitMs: event.waitMs,\n })).catch(() => {});\n },\n ...codingProviderOptions,\n })) {\n if (delta.usage) {\n totalPromptTokens += delta.usage.promptTokens;\n totalCompletionTokens += delta.usage.completionTokens;\n totalReasoningTokens += delta.usage.reasoningTokens ?? 0;\n const usageTokens = delta.usage.promptTokens + delta.usage.completionTokens + (delta.usage.reasoningTokens ?? 0);\n const usageUsd = estimateRunCost({\n provider: turnProvider.id,\n model: turnProvider.model,\n promptTokens: delta.usage.promptTokens,\n completionTokens: delta.usage.completionTokens,\n reasoningTokens: delta.usage.reasoningTokens ?? 0,\n }).usd ?? 0;\n turnSpendTokens += usageTokens;\n runSpendTokens += usageTokens;\n sessionSpendTokens += usageTokens;\n turnSpendUsd += usageUsd;\n runSpendUsd += usageUsd;\n sessionSpendUsd += usageUsd;\n }\n if (delta.schemaWarnings) {\n schemaFlattenedThisTurn = true;\n for (const warning of delta.schemaWarnings) {\n await options.sink({\n type: \"schema_flatten_warning\",\n reason: warning.reason,\n path: warning.path,\n provider: turnProvider.id,\n ...(warning.tool ? { tool: warning.tool } : {}),\n });\n }\n }\n if (delta.content) {\n assistantText += delta.content;\n finalText += delta.content;\n await options.sink({ type: \"message_delta\", text: delta.content });\n }\n if (delta.reasoningContent) {\n assistantReasoningText += delta.reasoningContent;\n const tokens = delta.usage?.reasoningTokens ?? Math.ceil(delta.reasoningContent.length / 4);\n if (delta.usage?.reasoningTokens === undefined) totalReasoningTokens += tokens;\n turnReasoningTokens += tokens;\n await appendReasoningChunk({\n workspace,\n runId,\n turn,\n provider: turnProvider.id,\n model: turnProvider.model,\n content: delta.reasoningContent,\n tokens,\n });\n if (!reasoningBudgetExceeded && turnReasoningTokens > reasoningCapTokens) {\n reasoningBudgetExceeded = true;\n await options.sink({\n type: \"reasoning_truncated\",\n provider: turnProvider.id,\n model: turnProvider.model,\n usedTokens: turnReasoningTokens,\n capTokens: reasoningCapTokens,\n stepType: routed.stepType,\n });\n }\n await options.sink({\n type: \"reasoning_chunk\",\n content: delta.reasoningContent,\n provider: turnProvider.id,\n model: turnProvider.model,\n runId,\n turn,\n tokens,\n });\n }\n if (delta.toolCalls?.length) rawToolCalls = delta.toolCalls;\n }\n break; // stream completed normally\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n const noProgressYet = assistantText.length === 0 && assistantReasoningText.length === 0 && rawToolCalls.length === 0;\n if (isContextWindowExceededError(err)) {\n if (!noProgressYet || contextCompactionsThisTurn >= 2 || compactionsThisRun >= COMPACTION_LIMIT) {\n if (noProgressYet) {\n const escalated = await scheduleEscalation({\n from: turnProvider,\n ...(routed.route ? { route: routed.route } : {}),\n stepType: routed.stepType,\n reason: \"context_too_small\",\n });\n if (escalated && forcedNextRoute) {\n const forced = forcedNextRoute;\n forcedNextRoute = null;\n turnProvider = await routeFallbackProvider({\n fallback: forced.target,\n stepType: forced.stepType,\n reason: forced.reason,\n });\n contextCompactionsThisTurn = 0;\n continue streamLoop;\n }\n }\n throw new CompactionExhaustedError(`Context compaction exhausted after ${compactionsThisRun} compaction(s): ${message}`);\n }\n\n const micro = microcompact(messages, {\n tokenBudget: Math.floor(CONTEXT_TOKEN_LIMIT * 0.85),\n foldRatio: 0.2,\n });\n if (micro.foldedPairs > 0) {\n evictReasoningArchiveForCompaction();\n await appendArchive(runId, toArchivedMessages(micro.archivedMessages), { workspace });\n messages = micro.messages;\n fileReadDedup.clear();\n await options.sink({\n type: \"compact_event\",\n compactType: \"micro\",\n removedTokens: micro.removedTokens,\n });\n }\n\n const beforeSnipTokens = estimateCompactTokens(messages);\n const snipped = snipLowSignal(messages);\n if (snipped.snippedCount > 0) {\n evictReasoningArchiveForCompaction();\n await appendArchive(runId, toArchivedMessages(snipped.archivedMessages), { workspace });\n messages = snipped.messages;\n fileReadDedup.clear();\n await options.sink({\n type: \"compact_event\",\n compactType: \"snip\",\n removedTokens: Math.max(0, beforeSnipTokens - estimateCompactTokens(messages)),\n });\n }\n\n const aggression: CompactionAggression = contextCompactionsThisTurn === 0 ? \"normal\" : \"heavy\";\n const compacted = await autoCompact(messages, {\n provider: turnProvider,\n model: turnProvider.model,\n aggression,\n archive: { workspace, runId },\n });\n evictReasoningArchiveForCompaction();\n messages = compacted.messages;\n fileReadDedup.clear();\n compactionsThisRun += 1;\n contextCompactionsThisTurn += 1;\n await options.sink({\n type: \"compact_event\",\n compactType: \"auto\",\n removedTokens: compacted.removedTokens,\n summaryTokens: compacted.summaryTokens,\n aggression,\n });\n continue;\n }\n const isTransient = /timed out|fetch failed|ECONNRESET|EAI_AGAIN|ENOTFOUND|socket hang up/i.test(message);\n if (isTransient && noProgressYet && providerAttempt < PROVIDER_TRANSIENT_RETRIES) {\n providerAttempt += 1;\n await options.sink({ type: \"status\", message: `Provider transient error (${message.slice(0, 120)}); retrying same turn (${providerAttempt}/${PROVIDER_TRANSIENT_RETRIES}).` });\n continue;\n }\n if (options.routing?.enabled && noProgressYet) {\n while (routeFallbackIndex < routeFallbackTargets.length) {\n const fallback = routeFallbackTargets[routeFallbackIndex];\n routeFallbackIndex += 1;\n if (!fallback || `${fallback.provider}/${fallback.model}` === `${turnProvider.id}/${turnProvider.model}`) continue;\n turnProvider = await routeFallbackProvider({\n fallback,\n stepType: routed.stepType,\n reason: `fallback after provider error: ${message.slice(0, 120)}`,\n });\n routed = { provider: turnProvider, stepType: routed.stepType };\n providerAttempt = 0;\n continue streamLoop;\n }\n }\n throw err;\n }\n }\n\n await options.sink({ type: \"message_end\" });\n\n const assistantHistoryMessage = (toolCalls: ToolCall[] = []): ChatMessage => {\n const message: ChatMessage = {\n role: \"assistant\",\n content: assistantText || null,\n };\n if (assistantReasoningText.length > 0 && turnProvider.roundTripReasoning === true) {\n message.reasoning_content = assistantReasoningText;\n }\n if (toolCalls.length) message.tool_calls = toolCalls;\n return message;\n };\n\n if (reasoningBudgetExceeded && turn < maxTurns - 1) {\n messages.push(assistantHistoryMessage());\n messages.push({\n role: \"user\",\n content: \"[your reasoning budget for this turn is exhausted. Give your final answer now.]\",\n });\n continue;\n }\n\n const parsedToolCalls = rawToolCalls.length > 0\n ? parseProviderToolCalls(rawToolCalls, { turn })\n : { toolCalls: [] as ToolCall[], warnings: [], failures: [] };\n for (const warning of parsedToolCalls.warnings) {\n await options.sink({\n type: \"tool_call_parse_warning\",\n reason: warning.reason,\n provider: turnProvider.id,\n turn,\n attempt: toolCallCorrectionAttempts,\n ...(warning.toolCallId ? { toolCallId: warning.toolCallId } : {}),\n ...(warning.tool ? { tool: warning.tool } : {}),\n });\n }\n for (const failure of parsedToolCalls.failures) {\n await options.sink({\n type: \"tool_call_parse_warning\",\n reason: failure.reason,\n provider: turnProvider.id,\n turn,\n attempt: toolCallCorrectionAttempts + 1,\n toolCallId: failure.toolCall.id,\n tool: failure.toolCall.function.name,\n });\n }\n\n if (\n parsedToolCalls.failures.length > 0 &&\n !parseEscalationUsed &&\n toolCallCorrectionAttempts + 1 >= TOOL_CALL_CORRECTION_LIMIT &&\n turn < maxTurns - 1\n ) {\n const escalated = await scheduleEscalation({\n from: turnProvider,\n ...(routed.route ? { route: routed.route } : {}),\n stepType: routed.stepType,\n reason: schemaFlattenedThisTurn ? \"schema_failure\" : \"parse_failure\",\n });\n if (escalated) {\n parseEscalationUsed = true;\n toolCallCorrectionAttempts += 1;\n messages.push(assistantHistoryMessage());\n messages.push({\n role: \"user\",\n content: malformedToolCallCorrectionMessage(parsedToolCalls.failures.map((failure) => failure.reason).join(\"; \")),\n });\n continue;\n }\n }\n\n if (parsedToolCalls.failures.length > 0 && toolCallCorrectionAttempts < TOOL_CALL_CORRECTION_LIMIT && turn < maxTurns - 1) {\n toolCallCorrectionAttempts += 1;\n messages.push(assistantHistoryMessage());\n messages.push({\n role: \"user\",\n content: malformedToolCallCorrectionMessage(parsedToolCalls.failures.map((failure) => failure.reason).join(\"; \")),\n });\n continue;\n }\n\n if (parsedToolCalls.failures.length > 0) {\n const failedToolCalls = parsedToolCalls.failures.map((failure) => failure.toolCall);\n toolErrorCount += failedToolCalls.length;\n messages.push(assistantHistoryMessage(failedToolCalls));\n for (const failure of parsedToolCalls.failures) {\n const error = `malformed tool call after ${TOOL_CALL_CORRECTION_LIMIT} correction attempts: ${failure.reason}`;\n messages.push({ role: \"tool\", tool_call_id: failure.toolCall.id, content: JSON.stringify({ ok: false, error }) });\n await options.sink({\n type: \"tool_result\",\n id: failure.toolCall.id,\n tool: failure.toolCall.function.name,\n ok: false,\n summary: \"Malformed tool call after correction attempts.\",\n error,\n });\n }\n continue;\n }\n\n const toolCalls = parsedToolCalls.toolCalls;\n if (toolCalls.length > 0) {\n toolCallCorrectionAttempts = 0;\n parseEscalationUsed = false;\n }\n\n messages.push(assistantHistoryMessage(toolCalls));\n\n if (\n toolCalls.length === 0 &&\n isCodingTask(options.runContext) &&\n !hasRequiredCodingReport(assistantText || finalText)\n ) {\n consecutiveNoToolNoReportTurns += 1;\n if (!requestedFinalReport && consecutiveNoToolNoReportTurns < MAX_NO_TOOL_NO_REPORT_TURNS && turn < maxTurns - 1) {\n requestedFinalReport = true;\n messages.push({\n role: \"user\",\n content: buildFinalReportReminder(changed, toolErrorCount),\n });\n continue;\n }\n } else {\n consecutiveNoToolNoReportTurns = 0;\n }\n\n if (toolCalls.length === 0) {\n createdArtifactPaths = uniqueSorted([...createdArtifactPaths, ...await syncArtifactOutput()]);\n const manifest = await buildFinalManifest({\n workspace,\n beforeGitSnapshot,\n changed,\n verificationLines,\n toolErrorCount,\n readArtifactPaths,\n readContextPaths,\n createdArtifactPaths,\n blockers: failedVerificationBlockers(verificationLines, assistantText || finalText),\n childVerdicts,\n runContext: options.runContext,\n prompt: options.prompt,\n runId,\n verifierShell: options.verifierShell,\n });\n if (\n isCodingTask(options.runContext) &&\n !requestedCommitRepair &&\n commitStillRequired(manifest, beforeGitSnapshot, options.runContext) &&\n turn < maxTurns - 1\n ) {\n requestedCommitRepair = true;\n messages.push({\n role: \"user\",\n content: buildCommitRequiredReminder(manifest),\n });\n continue;\n }\n if (\n isCodingTask(options.runContext) &&\n ((manifest.validation && !manifest.validation.passed) || manifest.blockers.length > 0) &&\n validationRepairAttempts < maxRepairAttempts &&\n !seenValidationRepairSignatures.has(validationRepairSignature(manifest)) &&\n turn < maxTurns - 1\n ) {\n validationRepairAttempts += 1;\n const signature = validationRepairSignature(manifest);\n lastValidationRepairSignature = signature;\n seenValidationRepairSignatures.add(signature);\n repairAttempts.push(repairAttemptSnapshot(validationRepairAttempts, manifest));\n messages = pruneStaleRepairReminders(messages);\n messages.push({\n role: \"user\",\n content: buildValidationRepairReminder(manifest, validationRepairAttempts, maxRepairAttempts),\n });\n continue;\n }\n const finalMessage = isCodingTask(options.runContext)\n ? ensureCodingReport(assistantText || finalText || \"Done.\", manifest, options.runContext)\n : assistantText || finalText || \"Done.\";\n await recordGoldenTaskMemory(workspace, manifest, options.runContext);\n await appendTaskHistorySilently(workspace, options.prompt, manifest, options.runContext);\n await appendObsidianTaskIfConfigured(manifest, options.runContext);\n await recordRepairRunMemorySilently(options.runContext, repairAttempts, manifest);\n const metrics = await finishRun(finalMessage, manifest);\n return { message: finalMessage, manifest, metrics };\n }\n\n for (const toolCall of toolCalls) {\n const toolName = toolCall.function.name;\n const tool = registry.get(toolName);\n const parsedInput = parseToolArguments(toolCall.function.arguments);\n if (!parsedInput.ok) {\n toolErrorCount += 1;\n messages.push({\n role: \"tool\",\n tool_call_id: toolCall.id,\n content: JSON.stringify({\n ok: false,\n error: parsedInput.reason,\n rawArguments: parsedInput.rawArguments,\n }),\n });\n await options.sink({\n type: \"tool_result\",\n id: toolCall.id,\n tool: toolName,\n ok: false,\n summary: \"Invalid tool arguments (malformed JSON).\",\n output: `raw arguments (preview): ${parsedInput.rawArguments}`,\n error: parsedInput.reason,\n });\n continue;\n }\n const callInput = parsedInput.input;\n toolCallCount += 1;\n await options.sink({ type: \"tool_call\", id: toolCall.id, tool: toolName, input: callInput });\n\n if (!tool) {\n const error = toolName.startsWith(\"mcp:\")\n ? `MCP tool is not configured or allowlisted: ${toolName}`\n : `Unknown tool: ${toolName}`;\n toolErrorCount += 1;\n messages.push({ role: \"tool\", tool_call_id: toolCall.id, content: JSON.stringify({ ok: false, error }) });\n await options.sink({ type: \"tool_result\", id: toolCall.id, tool: toolName, ok: false, summary: error, error });\n continue;\n }\n\n const validationError = validateToolInput(callInput, tool.definition as {\n function: { parameters?: { properties?: Record<string, { type?: string }>; required?: string[] } };\n });\n if (validationError) {\n toolErrorCount += 1;\n messages.push({ role: \"tool\", tool_call_id: toolCall.id, content: JSON.stringify({ ok: false, error: validationError }) });\n await options.sink({ type: \"tool_result\", id: toolCall.id, tool: toolName, ok: false, summary: validationError, error: validationError });\n continue;\n }\n\n if (requiredTool && !requiredToolUsed && toolCallMayMutate(toolName, callInput) && toolName !== requiredTool) {\n const error = `This task must use ${requiredTool} before manual file mutation. Read context/artifacts first if needed, then call ${requiredTool}.`;\n toolErrorCount += 1;\n messages.push({ role: \"tool\", tool_call_id: toolCall.id, content: JSON.stringify({ ok: false, summary: \"Required high-level tool not used.\", error }) });\n await options.sink({ type: \"tool_result\", id: toolCall.id, tool: toolName, ok: false, summary: \"Required high-level tool not used.\", error });\n continue;\n }\n\n const projectedSpend = projectedToolSpend(callInput, turnProvider);\n permissionContext.spendState = {\n turnTokens: turnSpendTokens,\n runTokens: runSpendTokens,\n sessionTokens: sessionSpendTokens,\n projectedTokens: projectedSpend.projectedTokens,\n turnUsd: turnSpendUsd,\n runUsd: runSpendUsd,\n sessionUsd: sessionSpendUsd,\n projectedUsd: projectedSpend.projectedUsd,\n };\n const permissionDecision: Decision = tool.canRun\n ? await tool.canRun(callInput, permissionContext)\n : permissionContext.mode === \"bypass\"\n ? { decision: \"allow\", reason: \"bypass-mode\" }\n : decide(toolName, callInput, permissionContext);\n let finalPermissionDecision: Decision = permissionDecision;\n let finalPermissionSource: \"user\" | \"rule\" | \"engine\" | \"bypass\" = permissionEventSource(permissionDecision, permissionContext.mode);\n if (permissionContext.mode !== \"bypass\") {\n if (permissionDecision.decision === \"ask\") {\n const permissionKey = permissionCacheKey(toolName, callInput);\n let cached = permissionAnswers.get(permissionKey);\n if (!cached) {\n await options.sink({ type: \"permission_request\", ...permissionRequestFromDecision(toolCall.id, toolName, callInput, permissionDecision) });\n const answer = options.onPermissionRequest\n ? await options.onPermissionRequest(permissionRequestFromDecision(toolCall.id, toolName, callInput, permissionDecision))\n : { decision: \"deny\" as const };\n cached = { answer, source: options.onPermissionRequest ? \"user\" : \"engine\" };\n permissionAnswers.set(permissionKey, cached);\n }\n finalPermissionDecision = {\n ...permissionDecision,\n decision: cached.answer.decision,\n reason: cached.answer.decision === \"allow\" ? \"user-approved\" : (permissionDecision.reason ?? \"permission-denied\"),\n };\n finalPermissionSource = cached.source;\n await options.sink({\n type: \"permission_decision\",\n id: toolCall.id,\n decision: cached.answer.decision,\n source: cached.source,\n ...(cached.answer.persistAs ? { persistAs: cached.answer.persistAs } : {}),\n ...(permissionDecision.matchedRule ? { matchedRule: permissionDecision.matchedRule } : {}),\n ...(permissionDecision.projectedCostUsd !== undefined ? { projectedCostUsd: permissionDecision.projectedCostUsd } : {}),\n ...(permissionDecision.projectedTokens !== undefined ? { projectedTokens: permissionDecision.projectedTokens } : {}),\n ...(permissionDecision.thresholdUsd !== undefined ? { thresholdUsd: permissionDecision.thresholdUsd } : {}),\n ...(permissionDecision.thresholdTokens !== undefined ? { thresholdTokens: permissionDecision.thresholdTokens } : {}),\n });\n } else {\n await options.sink({\n type: \"permission_decision\",\n id: toolCall.id,\n decision: permissionDecision.decision,\n source: permissionEventSource(permissionDecision, permissionContext.mode),\n ...(permissionDecision.matchedRule ? { matchedRule: permissionDecision.matchedRule } : {}),\n ...(permissionDecision.projectedCostUsd !== undefined ? { projectedCostUsd: permissionDecision.projectedCostUsd } : {}),\n ...(permissionDecision.projectedTokens !== undefined ? { projectedTokens: permissionDecision.projectedTokens } : {}),\n ...(permissionDecision.thresholdUsd !== undefined ? { thresholdUsd: permissionDecision.thresholdUsd } : {}),\n ...(permissionDecision.thresholdTokens !== undefined ? { thresholdTokens: permissionDecision.thresholdTokens } : {}),\n });\n }\n }\n auditPermissionDecision(workspace, permissionContext, toolName, callInput, finalPermissionDecision, finalPermissionSource);\n if (finalPermissionDecision.decision !== \"allow\") {\n const result = deniedPermissionResult(\n finalPermissionDecision,\n permissionDecision.decision === \"ask\" ? \"permission approval required\" : \"permission denied\",\n );\n toolErrorCount += 1;\n messages.push({ role: \"tool\", tool_call_id: toolCall.id, content: JSON.stringify(result.output) });\n await options.sink({\n type: \"tool_result\",\n id: toolCall.id,\n tool: toolName,\n ok: false,\n summary: result.summary,\n output: result.output,\n error: result.error,\n });\n continue;\n }\n\n let removeToolAbortListener: (() => void) | undefined;\n try {\n const label = commandLabel(toolName, callInput);\n const key = label ? verificationKey(label) : null;\n const outsideReadMessage = outsideWorkspaceReadMessage(workspace, toolName, callInput);\n let duplicateVerification = key ? passedVerificationKeys.get(key) === mutationRevision : false;\n const dedupedReadResult = !outsideReadMessage && toolName === \"read_file\"\n ? await fileReadDedup.lookup(callInput)\n : null;\n let spiralResult: ToolResult | null = null;\n if (!outsideReadMessage && toolName === \"run_shell\") {\n const spiralKey = shellCommandSpiralKey(callInput);\n if (spiralKey && shouldApplyShellSpiralDetector(spiralKey)) {\n const previousExecutions = shellCommandSpiralCounts.get(spiralKey) ?? 0;\n if (previousExecutions >= 5) {\n duplicateVerification = false;\n const advisory = `Detected repeated verification of ${spiralKey} — embed result in prompt or move on. Skipping further attempts.`;\n if (!shellCommandSpiralAdvisorySent) {\n shellCommandSpiralAdvisorySent = true;\n await options.sink({ type: \"status\", message: advisory });\n }\n spiralResult = {\n ok: true,\n summary: \"Skipped repeated shell command: verification spiral detected.\",\n output: `skipped: spiral detected\\n${advisory}`,\n };\n } else {\n shellCommandSpiralCounts.set(spiralKey, previousExecutions + 1);\n duplicateVerification = false;\n }\n }\n }\n if (toolName === \"expand_result\" && expandResultCallsThisTurn >= EXPAND_RESULT_LIMIT_PER_TURN) {\n const result = {\n ok: false,\n summary: \"expand_result limit reached for this turn.\",\n error: `Only ${EXPAND_RESULT_LIMIT_PER_TURN} expand_result calls are allowed per turn.`,\n output: { ok: false, error: \"expand_result limit reached for this turn\" },\n } satisfies ToolResult;\n toolErrorCount += 1;\n messages.push({ role: \"tool\", tool_call_id: toolCall.id, content: JSON.stringify(result) });\n await options.sink({\n type: \"tool_result\",\n id: toolCall.id,\n tool: toolName,\n ok: false,\n summary: result.summary,\n output: result.output,\n error: result.error,\n });\n continue;\n }\n const runRegisteredTool = () => {\n const toolAbortController = new AbortController();\n let cancelRequested = false;\n const requestToolCancellation = () => {\n if (cancelRequested) return;\n cancelRequested = true;\n void Promise.resolve(options.sink({\n type: \"tool_cancel_requested\",\n toolCallId: toolCall.id,\n tool: toolName,\n timestamp: new Date().toISOString(),\n })).catch(() => {});\n toolAbortController.abort(options.signal?.reason);\n };\n if (options.signal?.aborted) {\n requestToolCancellation();\n } else if (options.signal) {\n options.signal.addEventListener(\"abort\", requestToolCancellation, { once: true });\n removeToolAbortListener = () => options.signal?.removeEventListener(\"abort\", requestToolCancellation);\n }\n return registry.run(tool, callInput, { workspace, runId, runSubAgent: runSubAgentTask }, {\n signal: toolAbortController.signal,\n onProgress: (progress) => {\n void Promise.resolve(options.sink({\n type: \"tool_progress\",\n toolCallId: toolCall.id,\n chunk: progress.chunk,\n timestamp: progress.timestamp,\n stream: progress.stream,\n })).catch(() => {});\n },\n });\n };\n const rawResult = outsideReadMessage\n ? {\n ok: true,\n summary: outsideReadMessage,\n output: outsideReadMessage,\n }\n : duplicateVerification\n ? {\n ok: true,\n summary: \"Skipped duplicate verification; the previous matching command already exited 0 and is authoritative.\",\n output: \"Already verified in this run. Do not call this verification again; produce the final report now.\",\n }\n : spiralResult\n ? spiralResult\n : dedupedReadResult\n ? dedupedReadResult\n : await runRegisteredTool();\n const result = withRunnerRepairHints(toolName, rawResult);\n if (toolName === \"expand_result\" && result.ok) expandResultCallsThisTurn += 1;\n if (duplicateVerification && key) {\n skippedDuplicateKeys.set(key, (skippedDuplicateKeys.get(key) ?? 0) + 1);\n }\n if (toolName === \"edit_block\" && result.ok) {\n auditEditBlockCandidate(workspace, permissionContext, callInput, result);\n }\n if (result.ok) {\n changed = collectChangedFiles(changed, result.files);\n if (toolName === requiredTool) requiredToolUsed = true;\n }\n if (looksLikeNetworkOrDependencyFailure(toolName, callInput, result)) {\n consecutiveNetworkFailures += 1;\n if (consecutiveNetworkFailures >= 2 && !networkFallbackReminderSent) {\n networkFallbackReminderPending = true;\n }\n } else if (result.ok && toolName !== \"read_file\" && toolName !== \"list_files\" && toolName !== \"search\") {\n consecutiveNetworkFailures = 0;\n }\n if (toolName === \"read_file\" && result.ok && !dedupedReadResult && !outsideReadMessage) {\n await fileReadDedup.remember(callInput, toolCall.id, turn);\n }\n if (toolResultMutatedFiles(toolName, result)) {\n mutationRevision += 1;\n fileReadDedup.clear();\n }\n const artifactPath = artifactPathFromRead(toolName, callInput);\n if (artifactPath && result.ok) readArtifactPaths = uniqueSorted([...readArtifactPaths, artifactPath]);\n const contextPath = contextPathFromRead(toolName, callInput, options.runContext);\n if (contextPath && result.ok) readContextPaths = uniqueSorted([...readContextPaths, contextPath]);\n if (label) {\n const line = `Verification: ${label} -> ${result.ok ? \"passed\" : \"failed\"} (${result.summary})`;\n const existingIndex = verificationLines.findIndex((existing) => existing.includes(label));\n if (existingIndex === -1) {\n verificationLines.push(line);\n } else if (result.ok && /->\\s*failed\\b/i.test(verificationLines[existingIndex] ?? \"\")) {\n verificationLines[existingIndex] = line;\n }\n }\n if (key && result.ok) passedVerificationKeys.set(key, mutationRevision);\n if (!result.ok) toolErrorCount += 1;\n if (result.cancelled) {\n const cancelledEvent = {\n type: \"tool_cancelled\",\n toolCallId: toolCall.id,\n tool: toolName,\n timestamp: new Date().toISOString(),\n } as const;\n await options.sink(result.partial_output !== undefined\n ? { ...cancelledEvent, partialOutput: result.partial_output }\n : cancelledEvent);\n }\n const rendered = truncateToolResultForModel({\n tool,\n result,\n workspace,\n runId,\n toolCallId: toolCall.id,\n expandCallsRemaining: EXPAND_RESULT_LIMIT_PER_TURN - expandResultCallsThisTurn,\n });\n totalToolResultTokens += Math.ceil(JSON.stringify(rendered.modelResult).length / 4);\n messages.push({ role: \"tool\", tool_call_id: toolCall.id, content: JSON.stringify(rendered.modelResult) });\n const reason = toolResultReason(result);\n const event = {\n type: \"tool_result\",\n id: toolCall.id,\n tool: toolName,\n ok: result.ok,\n summary: rendered.modelResult.summary,\n output: rendered.modelResult.output,\n ...(reason ? { reason } : {}),\n ...(rendered.truncated ? { modelView: rendered.modelResult, verifierView: result } : {}),\n } as const;\n await options.sink(result.error ? { ...event, error: result.error } : event);\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n toolErrorCount += 1;\n messages.push({ role: \"tool\", tool_call_id: toolCall.id, content: JSON.stringify({ ok: false, error: message }) });\n await options.sink({ type: \"tool_result\", id: toolCall.id, tool: toolName, ok: false, summary: message, error: message });\n } finally {\n removeToolAbortListener?.();\n }\n }\n\n if (networkFallbackReminderPending && !networkFallbackReminderSent && turn < maxTurns - 1) {\n networkFallbackReminderPending = false;\n networkFallbackReminderSent = true;\n messages.push({ role: \"user\", content: buildNetworkFallbackReminder() });\n continue;\n }\n\n const repeatedDuplicateSkips = [...skippedDuplicateKeys.values()].reduce((sum, count) => sum + Math.max(0, count - 1), 0);\n if (isCodingTask(options.runContext) && repeatedDuplicateSkips >= 1) {\n createdArtifactPaths = uniqueSorted([...createdArtifactPaths, ...await syncArtifactOutput()]);\n const manifest = await buildFinalManifest({\n workspace,\n beforeGitSnapshot,\n changed,\n verificationLines,\n toolErrorCount,\n readArtifactPaths,\n readContextPaths,\n createdArtifactPaths,\n blockers: failedVerificationBlockers(verificationLines, finalText),\n childVerdicts,\n runContext: options.runContext,\n prompt: options.prompt,\n runId,\n verifierShell: options.verifierShell,\n });\n if (!requestedCommitRepair && commitStillRequired(manifest, beforeGitSnapshot, options.runContext)) {\n requestedCommitRepair = true;\n skippedDuplicateKeys.clear();\n messages.push({\n role: \"user\",\n content: buildCommitRequiredReminder(manifest),\n });\n continue;\n }\n const finalMessage = [\n \"Finalized after repeated duplicate verification requests.\",\n \"\",\n buildFallbackCodingReport(manifest.changedFiles, verificationLines, toolErrorCount, readArtifactPaths, createdArtifactPaths, options.runContext, manifest.blockers, finalText),\n ].join(\"\\n\");\n const finalMessageWithFooter = ensureCodingReport(finalMessage, manifest, options.runContext);\n await recordGoldenTaskMemory(workspace, manifest, options.runContext);\n await appendTaskHistorySilently(workspace, options.prompt, manifest, options.runContext);\n await appendObsidianTaskIfConfigured(manifest, options.runContext);\n await recordRepairRunMemorySilently(options.runContext, repairAttempts, manifest);\n const metrics = await finishRun(finalMessageWithFooter, manifest);\n return { message: finalMessageWithFooter, manifest, metrics };\n }\n }\n\n const message = `Stopped after reaching the tool-turn limit. (Max dialog turn budget = ${maxTurns}; the agent did not produce a final coding report and may have stalled in a tool-call loop. Inspect the verification log and rerun with --retries if appropriate.)`;\n createdArtifactPaths = uniqueSorted([...createdArtifactPaths, ...await syncArtifactOutput()]);\n const manifest = await buildFinalManifest({\n workspace,\n beforeGitSnapshot,\n changed,\n verificationLines,\n toolErrorCount,\n readArtifactPaths,\n readContextPaths,\n createdArtifactPaths,\n blockers: [\n \"tool-turn limit reached before final completion\",\n ...failedVerificationBlockers(verificationLines, finalText),\n ],\n childVerdicts,\n runContext: options.runContext,\n prompt: options.prompt,\n terminationReason: \"turn_budget_exhausted\",\n runId,\n verifierShell: options.verifierShell,\n });\n const fallbackReport = isCodingTask(options.runContext)\n ? buildFallbackCodingReport(manifest.changedFiles, verificationLines, toolErrorCount, readArtifactPaths, createdArtifactPaths, options.runContext, manifest.blockers, finalText)\n : \"\";\n const finalMessage = isCodingTask(options.runContext)\n ? [\n message,\n \"\",\n fallbackReport,\n ].join(\"\\n\")\n : message;\n const finalMessageWithFooter = isCodingTask(options.runContext)\n ? ensureCodingReport(finalMessage, manifest, options.runContext)\n : finalMessage;\n await recordGoldenTaskMemory(workspace, manifest, options.runContext);\n await appendTaskHistorySilently(workspace, options.prompt, manifest, options.runContext);\n await appendObsidianTaskIfConfigured(manifest, options.runContext);\n await recordRepairRunMemorySilently(options.runContext, repairAttempts, manifest);\n const metrics = await finishRun(finalMessageWithFooter, manifest);\n return { message: finalMessageWithFooter, manifest, metrics };\n}\n","import { stdout } from \"node:process\";\nimport { deleteSession, listSessions, loadSession, pruneOlderThan } from \"../sessions/storage\";\nimport type { SessionSummary } from \"../sessions/types\";\n\nexport interface SessionsCommandOptions {\n action?: string | undefined;\n args?: string[] | undefined;\n cwd?: string | undefined;\n global?: boolean | undefined;\n all?: boolean | undefined;\n limit?: number | undefined;\n olderThan?: string | undefined;\n output?: NodeJS.WritableStream | undefined;\n}\n\nconst HEADER = `${\"ID\".padEnd(24)} ${\"AGE\".padEnd(10)} ${\"TURNS\".padStart(5)} LABEL`;\n\nexport async function runSessionsCommand(options: SessionsCommandOptions): Promise<void> {\n const output = options.output ?? stdout;\n const action = options.action ?? \"list\";\n if (action === \"list\") {\n output.write(formatSessionList(listSessions({\n cwd: options.cwd,\n global: options.global,\n all: options.all,\n limit: options.limit,\n }), outputColumns(output)));\n return;\n }\n if (action === \"show\") {\n const id = options.args?.[0];\n if (!id) throw new Error(\"Usage: tanya sessions show <id>\");\n const loaded = loadSession(id, { cwd: options.cwd });\n output.write(formatSessionTranscript(loaded.session));\n return;\n }\n if (action === \"rm\") {\n const id = options.args?.[0];\n if (!id) throw new Error(\"Usage: tanya sessions rm <id>\");\n const deleted = deleteSession(id, { cwd: options.cwd });\n output.write(`Deleted session ${deleted}\\n`);\n return;\n }\n if (action === \"prune\") {\n const raw = options.olderThan ?? flagValue(options.args ?? [], \"--older-than\");\n if (!raw) throw new Error(\"Usage: tanya sessions prune --older-than 30d\");\n const deleted = pruneOlderThan(parseDurationMs(raw), { cwd: options.cwd, global: options.global });\n output.write(`Deleted ${deleted} session${deleted === 1 ? \"\" : \"s\"}.\\n`);\n return;\n }\n throw new Error(\"Usage: tanya sessions list|show|rm|prune\");\n}\n\nexport function formatSessionList(sessions: SessionSummary[], columns = 100): string {\n const fixedWidth = 24 + 1 + 10 + 1 + 5 + 2;\n const labelWidth = Math.max(20, columns - fixedWidth);\n const lines = [HEADER];\n for (const session of sessions) {\n lines.push([\n session.id.padEnd(24),\n relativeAge(new Date(session.lastUpdatedAt), new Date()).padEnd(10),\n String(session.turnCount).padStart(5),\n truncate(session.label || \"(untitled)\", labelWidth),\n ].join(\" \"));\n }\n if (sessions.length === 0) lines.push(\"No sessions found.\");\n return `${lines.join(\"\\n\")}\\n`;\n}\n\nexport function formatSessionTranscript(session: { id: string; turns: Array<{ role: string; content: string; timestampMs: number; elapsedMs?: number | null }> }): string {\n const lines = [`Session ${session.id}`, \"\"];\n for (const turn of session.turns) {\n const stamp = new Date(turn.timestampMs).toISOString();\n const elapsed = typeof turn.elapsedMs === \"number\" ? ` · ${Math.round(turn.elapsedMs / 1000)}s` : \"\";\n lines.push(`[${stamp}] ${turn.role}${elapsed}`);\n lines.push(turn.content);\n lines.push(\"\");\n }\n return lines.join(\"\\n\");\n}\n\nexport function parseDurationMs(raw: string): number {\n const match = raw.trim().match(/^(\\d+(?:\\.\\d+)?)(ms|s|m|h|d)$/i);\n if (!match) throw new Error(`Invalid duration \"${raw}\". Use values like 30d, 12h, or 45m.`);\n const value = Number(match[1]);\n const unit = match[2]!.toLowerCase();\n const multiplier = unit === \"ms\" ? 1 : unit === \"s\" ? 1000 : unit === \"m\" ? 60_000 : unit === \"h\" ? 3_600_000 : 86_400_000;\n return value * multiplier;\n}\n\nfunction outputColumns(output: NodeJS.WritableStream): number {\n return Math.max(60, (output as NodeJS.WritableStream & { columns?: number }).columns ?? 100);\n}\n\nfunction flagValue(args: string[], flag: string): string | undefined {\n const index = args.indexOf(flag);\n const value = index >= 0 ? args[index + 1] : undefined;\n return value && !value.startsWith(\"--\") ? value : undefined;\n}\n\nfunction truncate(value: string, width: number): string {\n if (value.length <= width) return value;\n return `${value.slice(0, Math.max(0, width - 3))}...`;\n}\n\nfunction relativeAge(then: Date, now: Date): string {\n const seconds = Math.max(0, Math.round((now.getTime() - then.getTime()) / 1000));\n if (seconds < 60) return `${seconds}s ago`;\n const minutes = Math.round(seconds / 60);\n if (minutes < 60) return `${minutes} min ago`;\n const hours = Math.round(minutes / 60);\n if (hours < 48) return `${hours} hr ago`;\n const days = Math.round(hours / 24);\n return `${days} days ago`;\n}\n","import { randomBytes } from \"node:crypto\";\nimport {\n existsSync,\n mkdirSync,\n readFileSync,\n readdirSync,\n rmSync,\n statSync,\n writeFileSync,\n appendFileSync,\n} from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { basename, dirname, join, parse, relative, resolve } from \"node:path\";\nimport { estimateRunCost } from \"../memory/runLogs\";\nimport type { ChatSession, LoadedSession, SessionStats, SessionSummary, SessionTurn } from \"./types\";\n\ninterface StorageOptions {\n cwd?: string | undefined;\n homeDir?: string | undefined;\n}\n\nexport interface CreateSessionOptions extends StorageOptions {\n provider: string;\n model: string;\n label?: string;\n id?: string;\n now?: Date;\n}\n\nexport interface ListSessionsOptions extends StorageOptions {\n global?: boolean | undefined;\n limit?: number | undefined;\n all?: boolean | undefined;\n}\n\nconst activeSessionPaths = new Map<string, string>();\n\nfunction defaultCwd(cwd?: string): string {\n return resolve(cwd ?? process.cwd());\n}\n\nfunction defaultHome(homeDir?: string): string {\n return resolve(homeDir ?? homedir());\n}\n\nfunction globalSessionsDir(homeDir?: string): string {\n return join(defaultHome(homeDir), \".tania\", \"sessions\", \"global\");\n}\n\nfunction findProjectTaniaDir(cwd: string): string | null {\n let current = resolve(cwd);\n while (true) {\n const candidate = join(current, \".tania\");\n if (existsSync(candidate) && statSync(candidate).isDirectory()) return candidate;\n const parent = dirname(current);\n if (parent === current) return null;\n current = parent;\n }\n}\n\nexport function resolveSessionsDir(options: StorageOptions = {}): { dir: string; scope: \"project\" | \"global\" } {\n const projectTania = findProjectTaniaDir(defaultCwd(options.cwd));\n if (projectTania) return { dir: join(projectTania, \"sessions\"), scope: \"project\" };\n return { dir: globalSessionsDir(options.homeDir), scope: \"global\" };\n}\n\nfunction ensureSessionsDir(dir: string, scope: \"project\" | \"global\"): void {\n mkdirSync(dir, { recursive: true });\n if (scope === \"project\") {\n const ignorePath = join(dir, \".gitignore\");\n if (!existsSync(ignorePath)) writeFileSync(ignorePath, \"*\\n\", \"utf8\");\n }\n}\n\nfunction shortLabel(content: string): string {\n const singleLine = content.replace(/\\s+/g, \" \").trim();\n return singleLine.length <= 80 ? singleLine : `${singleLine.slice(0, 77)}...`;\n}\n\nexport function createSession(options: CreateSessionOptions): ChatSession {\n const now = options.now ?? new Date();\n const cwd = defaultCwd(options.cwd);\n const id = options.id ?? createSessionId(now);\n const { dir, scope } = resolveSessionsDir({ cwd, ...(options.homeDir ? { homeDir: options.homeDir } : {}) });\n ensureSessionsDir(dir, scope);\n const session: ChatSession = {\n id,\n createdAt: now.toISOString(),\n lastUpdatedAt: now.toISOString(),\n cwd,\n provider: options.provider,\n model: options.model,\n turns: [],\n sessionStats: emptyStats(),\n label: shortLabel(options.label ?? \"\"),\n };\n writeFileSync(sessionPath(dir, id), `${JSON.stringify(session, null, 2)}\\n`, \"utf8\");\n activeSessionPaths.set(id, sessionPath(dir, id));\n return session;\n}\n\nexport function createSessionId(now = new Date()): string {\n const pad = (value: number) => String(value).padStart(2, \"0\");\n const timestamp = [\n now.getUTCFullYear(),\n pad(now.getUTCMonth() + 1),\n pad(now.getUTCDate()),\n \"-\",\n pad(now.getUTCHours()),\n pad(now.getUTCMinutes()),\n pad(now.getUTCSeconds()),\n ].join(\"\");\n return `${timestamp}-${randomBytes(3).toString(\"hex\")}`;\n}\n\nexport function appendTurn(sessionId: string, turn: SessionTurn): void {\n const path = resolveSessionJsonPath(sessionId);\n appendFileSync(jsonlPathFor(path), `${JSON.stringify(sanitizeTurn(turn))}\\n`, \"utf8\");\n}\n\nexport function materialize(sessionId: string, options: StorageOptions & { label?: string } = {}): ChatSession {\n const path = resolveSessionJsonPath(sessionId, options);\n const base = readBaseSession(path);\n const { turns, warnings } = readTurnsFromJsonl(jsonlPathFor(path), path);\n for (const warning of warnings) console.warn(warning);\n const now = new Date().toISOString();\n const session: ChatSession = {\n ...base,\n lastUpdatedAt: now,\n turns,\n sessionStats: buildStats(base, turns, now),\n label: shortLabel(options.label ?? (base.label || firstUserLabel(turns))),\n };\n writeFileSync(path, `${JSON.stringify(session, null, 2)}\\n`, \"utf8\");\n activeSessionPaths.set(session.id, path);\n return session;\n}\n\nexport function updateSessionLabel(sessionId: string, label: string, options: StorageOptions = {}): ChatSession {\n const session = materialize(sessionId, options);\n const path = resolveSessionJsonPath(sessionId, options);\n const updated = { ...session, label: shortLabel(label), lastUpdatedAt: new Date().toISOString() };\n writeFileSync(path, `${JSON.stringify(updated, null, 2)}\\n`, \"utf8\");\n return updated;\n}\n\nexport function listSessions(options: ListSessionsOptions = {}): SessionSummary[] {\n const cwd = defaultCwd(options.cwd);\n const dirs = sessionDirsForListing(options);\n const sessions = dirs.flatMap(({ dir, scope }) => readSessionSummaries(dir, scope));\n const filtered = options.cwd && !options.global\n ? sessions.filter((session) => cwdMatches(session.cwd, cwd) || session.scope === \"global\")\n : sessions;\n const sorted = filtered.sort((a, b) => b.lastUpdatedAt.localeCompare(a.lastUpdatedAt) || b.id.localeCompare(a.id));\n return options.all ? sorted : sorted.slice(0, options.limit ?? 10);\n}\n\nexport function findContinueSession(options: StorageOptions = {}): LoadedSession | null {\n const cwd = defaultCwd(options.cwd);\n const projectSessions = sessionDirsForListing({ ...options, global: false })\n .filter((entry) => entry.scope === \"project\")\n .flatMap(({ dir, scope }) => readSessionSummaries(dir, scope))\n .filter((session) => cwdMatches(session.cwd, cwd))\n .sort((a, b) => b.lastUpdatedAt.localeCompare(a.lastUpdatedAt));\n const selected = projectSessions[0] ?? readSessionSummaries(globalSessionsDir(options.homeDir), \"global\")\n .sort((a, b) => b.lastUpdatedAt.localeCompare(a.lastUpdatedAt))[0];\n return selected ? loadSession(selected.id, options) : null;\n}\n\nexport function loadSession(idOrPrefix: string, options: StorageOptions = {}): LoadedSession {\n const matches = findSessionPathMatches(idOrPrefix, options);\n if (matches.length === 0) throw new Error(`Session not found: ${idOrPrefix}`);\n if (matches.length > 1) {\n throw new Error(`Session id \"${idOrPrefix}\" is ambiguous: ${matches.map((match) => match.id).join(\", \")}`);\n }\n const match = matches[0]!;\n const base = readBaseSession(match.path);\n const { turns, warnings } = readTurnsFromJsonl(jsonlPathFor(match.path), match.path);\n for (const warning of warnings) console.warn(warning);\n const lastUpdatedAt = latestUpdatedAt(base, turns);\n const session: ChatSession = {\n ...base,\n turns,\n lastUpdatedAt,\n sessionStats: buildStats(base, turns, lastUpdatedAt),\n label: base.label || firstUserLabel(turns),\n };\n activeSessionPaths.set(session.id, match.path);\n return { session, path: match.path, jsonlPath: jsonlPathFor(match.path), scope: match.scope, warnings };\n}\n\nexport function deleteSession(idOrPrefix: string, options: StorageOptions = {}): string {\n const loaded = loadSession(idOrPrefix, options);\n rmSync(loaded.path, { force: true });\n rmSync(loaded.jsonlPath, { force: true });\n activeSessionPaths.delete(loaded.session.id);\n return loaded.session.id;\n}\n\nexport function pruneOlderThan(ms: number, options: ListSessionsOptions = {}): number {\n const cutoff = Date.now() - ms;\n let deleted = 0;\n for (const session of listSessions({ ...options, all: true })) {\n const updatedMs = Date.parse(session.lastUpdatedAt);\n if (Number.isFinite(updatedMs) && updatedMs < cutoff) {\n rmSync(session.path, { force: true });\n rmSync(jsonlPathFor(session.path), { force: true });\n activeSessionPaths.delete(session.id);\n deleted += 1;\n }\n }\n return deleted;\n}\n\nfunction emptyStats(): SessionStats {\n return { elapsedMs: 0, generateMs: 0, turnCount: 0, costUsd: 0, totalTokens: 0 };\n}\n\nfunction sanitizeTurn(turn: SessionTurn): SessionTurn {\n const sanitized: SessionTurn = {\n role: turn.role,\n content: String(turn.content ?? \"\"),\n timestampMs: Number.isFinite(turn.timestampMs) ? turn.timestampMs : Date.now(),\n };\n if (turn.elapsedMs !== undefined) sanitized.elapsedMs = turn.elapsedMs;\n if (turn.metrics) sanitized.metrics = { ...turn.metrics };\n return sanitized;\n}\n\nfunction sessionPath(dir: string, id: string): string {\n return join(dir, `${id}.json`);\n}\n\nfunction jsonlPathFor(path: string): string {\n return path.replace(/\\.json$/, \".jsonl\");\n}\n\nfunction readBaseSession(path: string): ChatSession {\n const parsed = JSON.parse(readFileSync(path, \"utf8\")) as Partial<ChatSession>;\n if (!parsed.id || !parsed.createdAt || !parsed.cwd || !parsed.provider || !parsed.model) {\n throw new Error(`Invalid session file: ${path}`);\n }\n return {\n id: parsed.id,\n createdAt: parsed.createdAt,\n lastUpdatedAt: parsed.lastUpdatedAt ?? parsed.createdAt,\n cwd: parsed.cwd,\n provider: parsed.provider,\n model: parsed.model,\n turns: Array.isArray(parsed.turns) ? parsed.turns.flatMap(parseTurn) : [],\n sessionStats: parsed.sessionStats ?? emptyStats(),\n label: typeof parsed.label === \"string\" ? parsed.label : \"\",\n };\n}\n\nfunction readTurnsFromJsonl(path: string, fallbackJsonPath: string): { turns: SessionTurn[]; warnings: string[] } {\n if (!existsSync(path)) return { turns: readBaseSession(fallbackJsonPath).turns, warnings: [] };\n const raw = readFileSync(path, \"utf8\");\n const turns: SessionTurn[] = [];\n const warnings: string[] = [];\n const lines = raw.split(/\\r?\\n/);\n lines.forEach((line, index) => {\n if (!line.trim()) return;\n try {\n const parsed = JSON.parse(line) as unknown;\n const turn = parseTurn(parsed);\n if (turn.length === 0) throw new Error(\"not a session turn\");\n turns.push(...turn);\n } catch (error) {\n warnings.push(`Warning: ignored corrupt session JSONL line ${index + 1} in ${path}: ${error instanceof Error ? error.message : String(error)}`);\n }\n });\n return { turns, warnings };\n}\n\nfunction parseTurn(value: unknown): SessionTurn[] {\n if (!value || typeof value !== \"object\") return [];\n const record = value as Partial<SessionTurn>;\n if ((record.role !== \"user\" && record.role !== \"assistant\") || typeof record.content !== \"string\" || typeof record.timestampMs !== \"number\") return [];\n return [sanitizeTurn(record as SessionTurn)];\n}\n\nfunction buildStats(base: ChatSession, turns: SessionTurn[], lastUpdatedAt: string): SessionStats {\n let generateMs = 0;\n let totalTokens = 0;\n let costUsd = 0;\n let costKnown = false;\n let assistantTurns = 0;\n for (const turn of turns) {\n if (turn.role !== \"assistant\") continue;\n assistantTurns += 1;\n generateMs += typeof turn.elapsedMs === \"number\" ? turn.elapsedMs : 0;\n const promptTokens = turn.metrics?.promptTokens ?? 0;\n const completionTokens = turn.metrics?.completionTokens ?? 0;\n const reasoningTokens = turn.metrics?.reasoningTokens ?? 0;\n totalTokens += promptTokens + completionTokens + reasoningTokens;\n const estimate = estimateRunCost({\n provider: base.provider,\n model: base.model,\n promptTokens,\n completionTokens,\n reasoningTokens,\n });\n if (estimate.usd !== null) {\n costKnown = true;\n costUsd += estimate.usd;\n }\n }\n const createdMs = Date.parse(base.createdAt);\n const updatedMs = Date.parse(lastUpdatedAt);\n return {\n elapsedMs: Number.isFinite(createdMs) && Number.isFinite(updatedMs) ? Math.max(0, updatedMs - createdMs) : 0,\n generateMs,\n turnCount: assistantTurns,\n costUsd: costKnown ? costUsd : 0,\n totalTokens,\n };\n}\n\nfunction firstUserLabel(turns: SessionTurn[]): string {\n return shortLabel(turns.find((turn) => turn.role === \"user\")?.content ?? \"\");\n}\n\nfunction latestUpdatedAt(base: ChatSession, turns: SessionTurn[]): string {\n const latestTurn = turns.reduce((latest, turn) => Math.max(latest, turn.timestampMs), 0);\n const baseUpdated = Date.parse(base.lastUpdatedAt);\n const latest = Math.max(Number.isFinite(baseUpdated) ? baseUpdated : 0, latestTurn);\n return latest > 0 ? new Date(latest).toISOString() : base.lastUpdatedAt;\n}\n\nfunction resolveSessionJsonPath(sessionId: string, options: StorageOptions = {}): string {\n const active = activeSessionPaths.get(sessionId);\n if (active && existsSync(active)) return active;\n const matches = findSessionPathMatches(sessionId, options);\n if (matches.length === 1) return matches[0]!.path;\n if (matches.length > 1) throw new Error(`Session id \"${sessionId}\" is ambiguous: ${matches.map((match) => match.id).join(\", \")}`);\n throw new Error(`Session not found: ${sessionId}`);\n}\n\nfunction findSessionPathMatches(idOrPrefix: string, options: StorageOptions): Array<{ id: string; path: string; scope: \"project\" | \"global\" }> {\n const needle = idOrPrefix.trim();\n if (!needle) return [];\n const dirs = sessionDirsForListing({ ...options, all: true });\n const candidates = dirs.flatMap(({ dir, scope }) => sessionJsonFiles(dir).map((path) => ({ id: basename(path, \".json\"), path, scope })));\n return candidates.filter((candidate) => candidate.id === needle || candidate.id.startsWith(needle) || shortId(candidate.id).startsWith(needle));\n}\n\nfunction shortId(id: string): string {\n return id.split(\"-\").at(-1) ?? id;\n}\n\nfunction readSessionSummaries(dir: string, scope: \"project\" | \"global\"): SessionSummary[] {\n return sessionJsonFiles(dir).flatMap((path) => {\n try {\n const session = readBaseSession(path);\n const { turns } = readTurnsFromJsonl(jsonlPathFor(path), path);\n const lastUpdatedAt = latestUpdatedAt(session, turns);\n const normalized: ChatSession = {\n ...session,\n turns,\n lastUpdatedAt,\n sessionStats: buildStats(session, turns, lastUpdatedAt),\n label: session.label || firstUserLabel(turns),\n };\n return [{\n id: normalized.id,\n createdAt: normalized.createdAt,\n lastUpdatedAt: normalized.lastUpdatedAt,\n cwd: normalized.cwd,\n provider: normalized.provider,\n model: normalized.model,\n label: normalized.label,\n turnCount: normalized.sessionStats.turnCount,\n path,\n scope,\n }];\n } catch {\n return [];\n }\n });\n}\n\nfunction sessionJsonFiles(dir: string): string[] {\n if (!existsSync(dir)) return [];\n return readdirSync(dir)\n .filter((file) => file.endsWith(\".json\"))\n .sort()\n .map((file) => join(dir, file));\n}\n\nfunction sessionDirsForListing(options: ListSessionsOptions): Array<{ dir: string; scope: \"project\" | \"global\" }> {\n if (options.global) return [{ dir: globalSessionsDir(options.homeDir), scope: \"global\" }];\n const dirs: Array<{ dir: string; scope: \"project\" | \"global\" }> = [];\n const cwd = defaultCwd(options.cwd);\n const projectTania = findProjectTaniaDir(cwd);\n if (projectTania) dirs.push({ dir: join(projectTania, \"sessions\"), scope: \"project\" });\n dirs.push({ dir: globalSessionsDir(options.homeDir), scope: \"global\" });\n return dirs;\n}\n\nfunction cwdMatches(sessionCwd: string, cwd: string): boolean {\n const fromSession = relative(resolve(sessionCwd), cwd);\n const fromCurrent = relative(cwd, resolve(sessionCwd));\n return fromSession === \"\" || (!fromSession.startsWith(\"..\") && !parse(fromSession).root) ||\n fromCurrent === \"\" || (!fromCurrent.startsWith(\"..\") && !parse(fromCurrent).root);\n}\n","import type { RunAgentResult } from \"../agent/runner\";\nimport type { ChatMessage } from \"../providers/types\";\nimport type { InkMessage, InkSessionStats } from \"../ui/ink/types\";\nimport { appendTurn, createSession, findContinueSession, loadSession, materialize, updateSessionLabel } from \"./storage\";\nimport type { ChatSession, LoadedSession, SessionStats, SessionTurn } from \"./types\";\n\nexport interface ChatSessionControllerOptions {\n cwd: string;\n provider: string;\n model: string;\n continueSession?: boolean | undefined;\n resumeSessionId?: string | undefined;\n}\n\nexport interface ChatSessionStart {\n controller: ChatSessionController;\n resumedSession?: ChatSession;\n notice?: string;\n}\n\nexport class ChatSessionController {\n session: ChatSession;\n unsavedTurnCount = 0;\n\n constructor(session: ChatSession) {\n this.session = session;\n }\n\n appendCompletedTurn(prompt: string, message: string, startedAt: number, elapsedMs: number, result: RunAgentResult): void {\n const userTurn: SessionTurn = {\n role: \"user\",\n content: prompt,\n timestampMs: startedAt,\n elapsedMs: null,\n };\n const assistantTurn: SessionTurn = {\n role: \"assistant\",\n content: message,\n timestampMs: Date.now(),\n elapsedMs,\n ...(result.metrics ? {\n metrics: {\n promptTokens: result.metrics.promptTokens,\n completionTokens: result.metrics.completionTokens,\n reasoningTokens: result.metrics.reasoningTokens,\n },\n } : {}),\n };\n appendTurn(this.session.id, userTurn);\n appendTurn(this.session.id, assistantTurn);\n this.session.turns.push(userTurn, assistantTurn);\n this.unsavedTurnCount += 1;\n }\n\n materialize(label?: string): ChatSession {\n this.session = materialize(this.session.id, { cwd: this.session.cwd, ...(label ? { label } : {}) });\n this.unsavedTurnCount = 0;\n return this.session;\n }\n\n save(label?: string): ChatSession {\n this.session = label ? updateSessionLabel(this.session.id, label, { cwd: this.session.cwd }) : materialize(this.session.id, { cwd: this.session.cwd });\n this.unsavedTurnCount = 0;\n return this.session;\n }\n\n resume(id: string, cwd: string): LoadedSession {\n const loaded = loadSession(id, { cwd });\n this.session = loaded.session;\n this.unsavedTurnCount = 0;\n return loaded;\n }\n}\n\nexport function startChatSession(options: ChatSessionControllerOptions): ChatSessionStart {\n if (options.resumeSessionId) {\n const loaded = loadSession(options.resumeSessionId, { cwd: options.cwd });\n return { controller: new ChatSessionController(loaded.session), resumedSession: loaded.session };\n }\n if (options.continueSession) {\n const loaded = findContinueSession({ cwd: options.cwd });\n if (loaded) return { controller: new ChatSessionController(loaded.session), resumedSession: loaded.session };\n return {\n controller: new ChatSessionController(createSession({\n cwd: options.cwd,\n provider: options.provider,\n model: options.model,\n })),\n notice: `No previous session found in ${options.cwd}. Starting fresh.`,\n };\n }\n return {\n controller: new ChatSessionController(createSession({\n cwd: options.cwd,\n provider: options.provider,\n model: options.model,\n })),\n };\n}\n\nexport function sessionToChatHistory(session: ChatSession): ChatMessage[] {\n return session.turns\n .filter((turn) => turn.role === \"user\" || turn.role === \"assistant\")\n .map((turn) => ({ role: turn.role, content: turn.content }));\n}\n\nexport function sessionToInkMessages(session: ChatSession, limit = 10): InkMessage[] {\n return replayTurns(session, limit).map((turn, index) => ({\n id: `resume-${session.id}-${index}`,\n role: turn.role,\n content: turn.content,\n timestampMs: turn.timestampMs,\n ...(typeof turn.elapsedMs === \"number\" ? { elapsedMs: turn.elapsedMs } : {}),\n }));\n}\n\nexport function replayTurns(session: ChatSession, limit = 10): SessionTurn[] {\n return session.turns.slice(Math.max(0, session.turns.length - limit));\n}\n\nexport function statsToInkStats(stats: SessionStats): InkSessionStats {\n return {\n costUsd: stats.costUsd,\n totalTokens: stats.totalTokens,\n };\n}\n\nexport function resumeBanner(session: ChatSession): string {\n return `Resumed session ${session.id} · ${session.sessionStats.turnCount} turns · /save to label, /sessions to switch`;\n}\n","import { createInterface } from \"node:readline/promises\";\nimport { stdin as processInput, stdout as processOutput } from \"node:process\";\nimport type { ChatMessage, ChatProvider } from \"../providers/types\";\nimport type { EventSink, TanyaEvent } from \"../events/types\";\nimport { runAgent, type RunAgentOptions, type RunAgentResult } from \"./runner\";\nimport { commandNameFromLine, loadProjectCommands, runCommand } from \"../commands\";\nimport type { CommandContext } from \"../commands\";\nimport { createReplPermissionRequestHandler } from \"../ui/permissionPrompt\";\nimport { formatClock, formatElapsed } from \"../utils/formatElapsed\";\nimport {\n replayTurns,\n resumeBanner,\n sessionToChatHistory,\n startChatSession,\n type ChatSessionController,\n} from \"../sessions/repl\";\nimport type { ChatSession } from \"../sessions/types\";\n\nconst thinkingFrames = [\"⠋\", \"⠙\", \"⠹\", \"⠸\", \"⠼\", \"⠴\", \"⠦\", \"⠧\", \"⠇\", \"⠏\"];\n\nfunction streamIsTTY(stream: NodeJS.WritableStream): boolean {\n return Boolean((stream as NodeJS.WritableStream & { isTTY?: boolean }).isTTY);\n}\n\nexport function createThinkingSpinner(output: NodeJS.WritableStream): () => void {\n if (!streamIsTTY(output)) return () => {};\n let frame = 0;\n let stopped = false;\n let maxRenderedWidth = 0;\n const startedAt = Date.now();\n const render = () => {\n const elapsedSec = Math.floor((Date.now() - startedAt) / 1000);\n const text = `Tanya: ${thinkingFrames[frame % thinkingFrames.length]} thinking… (${elapsedSec}s)`;\n maxRenderedWidth = Math.max(maxRenderedWidth, text.length);\n output.write(`\\r${text}`);\n frame += 1;\n };\n render();\n const timer = setInterval(render, 120);\n return () => {\n if (stopped) return;\n stopped = true;\n clearInterval(timer);\n output.write(`\\r${\" \".repeat(Math.max(maxRenderedWidth, 1))}\\r`);\n };\n}\n\nfunction wrapSinkForInteractiveTurn(params: {\n sink: EventSink;\n startedAt: number;\n stopSpinner: () => void;\n}): EventSink {\n let spinnerStopped = false;\n let streamedAnyMessageDelta = false;\n const supportsElapsedHeading = (params.sink as EventSink & { tanyaSinkKind?: string }).tanyaSinkKind === \"human\";\n let pendingMessageStart: Extract<TanyaEvent, { type: \"message_start\" }> | null = null;\n const stopSpinner = () => {\n if (spinnerStopped) return;\n spinnerStopped = true;\n params.stopSpinner();\n };\n const flushPendingMessageStart = () => {\n if (!pendingMessageStart) return;\n const event = pendingMessageStart;\n pendingMessageStart = null;\n const now = Date.now();\n return params.sink({ ...event, elapsedMs: now - params.startedAt, headingStartedAt: now });\n };\n return (event) => {\n if (!supportsElapsedHeading) {\n stopSpinner();\n return params.sink(event);\n }\n if (event.type === \"message_start\") {\n pendingMessageStart = event;\n return;\n }\n stopSpinner();\n const pendingResult = flushPendingMessageStart();\n if (event.type === \"message_delta\") {\n streamedAnyMessageDelta = true;\n }\n if (event.type === \"final\" && streamedAnyMessageDelta) {\n if (pendingResult && typeof (pendingResult as Promise<void>).then === \"function\") {\n return Promise.resolve(pendingResult).then(() => params.sink({ ...event, suppressHumanMessage: true }));\n }\n return params.sink({ ...event, suppressHumanMessage: true });\n }\n if (pendingResult && typeof (pendingResult as Promise<void>).then === \"function\") {\n return Promise.resolve(pendingResult).then(() => params.sink(event));\n }\n return params.sink(event);\n };\n}\n\nfunction isReadlineClosedError(error: unknown): boolean {\n return error instanceof Error && /readline was closed/i.test(error.message);\n}\n\nexport async function dispatchInteractiveCommand(prompt: string, ctx: CommandContext): Promise<boolean> {\n if (!prompt.startsWith(\"/\")) return false;\n const handled = await runCommand(prompt, ctx);\n if (handled) return true;\n const commandName = commandNameFromLine(prompt);\n ctx.output.write(`unknown command: /${commandName ?? \"\"}; try /help\\n`);\n return true;\n}\n\nexport async function startInteractiveChat(inputOptions: {\n provider: ChatProvider;\n cwd: string;\n sink: EventSink;\n input?: NodeJS.ReadableStream;\n output?: NodeJS.WritableStream;\n routing?: RunAgentOptions[\"routing\"];\n continueSession?: boolean | undefined;\n resumeSessionId?: string | undefined;\n}): Promise<void> {\n const input = inputOptions.input ?? processInput;\n const output = inputOptions.output ?? processOutput;\n const rl = createInterface({ input, output });\n const sessionStart = startChatSession({\n cwd: inputOptions.cwd,\n provider: inputOptions.provider.id,\n model: inputOptions.provider.model,\n continueSession: inputOptions.continueSession,\n resumeSessionId: inputOptions.resumeSessionId,\n });\n const sessionController = sessionStart.controller;\n const history: ChatMessage[] = sessionStart.resumedSession ? sessionToChatHistory(sessionStart.resumedSession) : [];\n let activeAbortController: AbortController | null = null;\n let stopActiveSpinner: () => void = () => {};\n const sessionStartMs = Date.now();\n let sessionGenerateMs = sessionStart.resumedSession?.sessionStats.generateMs ?? 0;\n let turnCount = sessionStart.resumedSession?.sessionStats.turnCount ?? 0;\n let sessionSummaryPrinted = false;\n const onPermissionRequest = createReplPermissionRequestHandler({\n question: (message) => rl.question(message),\n output,\n });\n await loadProjectCommands(inputOptions.cwd);\n output.write(`Tanya live chat (${inputOptions.provider.id}:${inputOptions.provider.model}). Type /exit to quit.\\n`);\n if (sessionStart.notice) output.write(`${sessionStart.notice}\\n`);\n if (sessionStart.resumedSession) {\n output.write(`${resumeBanner(sessionStart.resumedSession)}\\n`);\n writeSessionReplay(output, sessionStart.resumedSession);\n }\n const printSessionSummary = () => {\n if (sessionSummaryPrinted) return;\n sessionSummaryPrinted = true;\n safeMaterialize(sessionController);\n output.write(`Session: ${formatElapsed(Date.now() - sessionStartMs)} elapsed · ${formatElapsed(sessionGenerateMs)} generating · ${turnCount} turn${turnCount === 1 ? \"\" : \"s\"}\\n`);\n };\n const handleBeforeExit = () => {\n safeMaterialize(sessionController);\n };\n const handleSigint = () => {\n stopActiveSpinner();\n if (activeAbortController && !activeAbortController.signal.aborted) {\n output.write(\"\\nCancelling active tool...\\n\");\n activeAbortController.abort();\n return;\n }\n printSessionSummary();\n rl.close();\n process.exitCode = 130;\n };\n process.on(\"SIGINT\", handleSigint);\n process.on(\"beforeExit\", handleBeforeExit);\n\n try {\n while (true) {\n let rawPrompt: string;\n try {\n const promptShownAt = new Date();\n rawPrompt = await rl.question(streamIsTTY(output) ? `\\n[${formatClock(promptShownAt)}] You: ` : \"\\nYou: \");\n } catch (error) {\n if (isReadlineClosedError(error)) {\n printSessionSummary();\n break;\n }\n throw error;\n }\n const prompt = rawPrompt.trim();\n if (!prompt) continue;\n if (prompt === \"/exit\" || prompt === \"/quit\") {\n printSessionSummary();\n break;\n }\n if (await dispatchInteractiveCommand(prompt, {\n provider: inputOptions.provider,\n cwd: inputOptions.cwd,\n sink: inputOptions.sink,\n output,\n history,\n ...(inputOptions.routing ? { routing: inputOptions.routing } : {}),\n sessionController,\n clearHistory: () => {\n history.length = 0;\n },\n replaceHistory: (nextHistory) => {\n history.splice(0, history.length, ...nextHistory);\n },\n onSessionResumed: (session) => {\n sessionGenerateMs = session.sessionStats.generateMs;\n turnCount = session.sessionStats.turnCount;\n writeSessionReplay(output, session);\n },\n onPermissionRequest,\n })) {\n continue;\n }\n\n const abortController = new AbortController();\n activeAbortController = abortController;\n const startedAt = Date.now();\n stopActiveSpinner = createThinkingSpinner(output);\n const turnSink = wrapSinkForInteractiveTurn({\n sink: inputOptions.sink,\n startedAt,\n stopSpinner: stopActiveSpinner,\n });\n let message: string;\n let result: RunAgentResult | undefined;\n let elapsedMs = 0;\n try {\n result = await runAgent({\n provider: inputOptions.provider,\n prompt,\n cwd: inputOptions.cwd,\n sink: turnSink,\n history,\n signal: abortController.signal,\n onPermissionRequest,\n ...(inputOptions.routing ? { routing: inputOptions.routing } : {}),\n });\n message = result.message;\n elapsedMs = Date.now() - startedAt;\n } finally {\n stopActiveSpinner();\n stopActiveSpinner = () => {};\n activeAbortController = null;\n }\n sessionGenerateMs += elapsedMs;\n turnCount += 1;\n history.push({ role: \"user\", content: prompt });\n history.push({ role: \"assistant\", content: message });\n if (result) sessionController.appendCompletedTurn(prompt, message, startedAt, elapsedMs, result);\n }\n } finally {\n safeMaterialize(sessionController);\n process.off(\"SIGINT\", handleSigint);\n process.off(\"beforeExit\", handleBeforeExit);\n rl.close();\n }\n}\n\nfunction writeSessionReplay(output: NodeJS.WritableStream, session: ChatSession): void {\n output.write(`── resumed ${session.turns.length} turns ──\\n`);\n for (const turn of replayTurns(session, 10)) {\n const clock = formatClock(new Date(turn.timestampMs));\n const label = turn.role === \"user\" ? \"You\" : \"Tanya\";\n const elapsed = typeof turn.elapsedMs === \"number\" ? ` · ${formatElapsed(turn.elapsedMs)}` : \"\";\n output.write(`[${clock}] ${label}${elapsed}: ${turn.content}\\n`);\n }\n}\n\nfunction safeMaterialize(controller: ChatSessionController): void {\n try {\n controller.materialize();\n } catch {\n // Session materialization should not mask REPL shutdown.\n }\n}\n","import type { EventSink } from \"../events/types\";\nimport type { ChatMessage, ChatProvider } from \"../providers/types\";\nimport type { PermissionRequestHandler } from \"../safety/permissions/host\";\nimport type { RunAgentOptions } from \"../agent/runner\";\nimport type { ChatSessionController } from \"../sessions/repl\";\nimport type { ChatSession } from \"../sessions/types\";\n\nexport type CommandCategory = \"built-in\" | \"project\";\n\nexport interface CommandContext {\n cwd: string;\n sink: EventSink;\n output: NodeJS.WritableStream;\n provider?: ChatProvider;\n history?: ChatMessage[];\n clearHistory?: () => void;\n replaceHistory?: (history: ChatMessage[]) => void;\n onSessionResumed?: (session: ChatSession) => void;\n sessionController?: ChatSessionController | undefined;\n runId?: string;\n onPermissionRequest?: PermissionRequestHandler;\n routing?: RunAgentOptions[\"routing\"];\n}\n\nexport interface CommandDefinition {\n name: string;\n description: string;\n category?: CommandCategory;\n availability?: (ctx: CommandContext) => boolean | Promise<boolean>;\n handler: (args: string[], ctx: CommandContext) => void | Promise<void>;\n}\n\nconst commands = new Map<string, CommandDefinition>();\n\nexport function registerCommand(command: CommandDefinition): void {\n const name = normalizeCommandName(command.name);\n if (!name) throw new Error(\"Command name cannot be empty.\");\n commands.set(name, { ...command, name });\n}\n\nexport function getCommand(name: string): CommandDefinition | undefined {\n return commands.get(normalizeCommandName(name));\n}\n\nexport function listCommands(): CommandDefinition[] {\n return [...commands.values()].sort((a, b) => {\n const category = (a.category ?? \"built-in\").localeCompare(b.category ?? \"built-in\");\n return category || a.name.localeCompare(b.name);\n });\n}\n\nexport function removeCommandsByCategory(category: CommandCategory): void {\n for (const [name, command] of commands) {\n if (command.category === category) commands.delete(name);\n }\n}\n\nexport async function commandIsAvailable(command: CommandDefinition, ctx: CommandContext): Promise<boolean> {\n return command.availability ? await command.availability(ctx) : true;\n}\n\nexport function normalizeCommandName(name: string): string {\n return name.trim().replace(/^\\//, \"\").toLowerCase();\n}\n","import { readAuditDecisions } from \"../../memory/auditLog\";\nimport { registerCommand } from \"../registry\";\nimport type { CommandDefinition } from \"../registry\";\n\nconst DEFAULT_LIMIT = 20;\n\nconst auditCommand: CommandDefinition = {\n name: \"audit\",\n description: \"Show recent permission decisions.\",\n category: \"built-in\",\n handler(args, ctx) {\n const limit = parseLimit(flagValue(args, \"--limit\"));\n const tool = flagValue(args, \"--tool\");\n const since = parseDuration(flagValue(args, \"--since\"));\n const entries = readAuditDecisions(ctx.cwd, {\n limit,\n denyOnly: args.includes(\"--deny-only\"),\n ...(tool ? { tool } : {}),\n ...(since !== undefined ? { sinceMs: since } : {}),\n });\n if (entries.length === 0) {\n ctx.output.write(\"No permission audit entries found.\\n\");\n return;\n }\n\n ctx.output.write(\"Recent permission decisions:\\n\");\n for (const entry of entries) {\n const rule = entry.matchedRule ? ` ${entry.matchedRule}` : \"\";\n ctx.output.write(`${entry.ts.slice(0, 19)} ${entry.decision.padEnd(5)} ${entry.mode.padEnd(7)} ${entry.tool}${rule}\\n`);\n }\n },\n};\n\nfunction flagValue(args: string[], flag: string): string | undefined {\n const index = args.indexOf(flag);\n const value = index >= 0 ? args[index + 1] : undefined;\n return value && !value.startsWith(\"--\") ? value : undefined;\n}\n\nfunction parseLimit(raw: string | undefined): number {\n const parsed = raw ? Number(raw) : DEFAULT_LIMIT;\n return Number.isInteger(parsed) && parsed > 0 ? parsed : DEFAULT_LIMIT;\n}\n\nfunction parseDuration(raw: string | undefined): number | undefined {\n if (!raw) return undefined;\n const match = raw.match(/^(\\d+)(ms|s|m|h|d)$/);\n if (!match) return undefined;\n const value = Number(match[1]);\n const unit = match[2];\n if (unit === \"ms\") return value;\n if (unit === \"s\") return value * 1000;\n if (unit === \"m\") return value * 60 * 1000;\n if (unit === \"h\") return value * 60 * 60 * 1000;\n return value * 24 * 60 * 60 * 1000;\n}\n\nregisterCommand(auditCommand);\n","import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\nimport { DEFAULT_PERMISSION_RULES, parsePermissionsJson, type PermissionMode, type PermissionRulesConfig, type SpendRule } from \"./schema\";\n\nexport function writeProjectPermissionMode(cwd: string, mode: PermissionMode): string {\n const path = join(cwd, \".tania\", \"permissions.json\");\n const current = readProjectPermissions(path);\n const next: PermissionRulesConfig = {\n ...current,\n mode,\n };\n mkdirSync(dirname(path), { recursive: true });\n const tmpPath = `${path}.tmp-${process.pid}-${Date.now()}`;\n writeFileSync(tmpPath, `${JSON.stringify(next, null, 2)}\\n`, \"utf8\");\n renameSync(tmpPath, path);\n return path;\n}\n\nexport function appendProjectSpendRule(cwd: string, rule: SpendRule): string {\n const path = join(cwd, \".tania\", \"permissions.json\");\n const current = readProjectPermissions(path);\n const next: PermissionRulesConfig = {\n ...current,\n spendRules: [...current.spendRules, rule],\n };\n writeProjectPermissions(path, next);\n return path;\n}\n\nfunction readProjectPermissions(path: string): PermissionRulesConfig {\n if (!existsSync(path)) return { ...DEFAULT_PERMISSION_RULES };\n const parsed = parsePermissionsJson(readFileSync(path, \"utf8\"));\n return parsed.ok ? parsed.value : { ...DEFAULT_PERMISSION_RULES };\n}\n\nfunction writeProjectPermissions(path: string, rules: PermissionRulesConfig): void {\n mkdirSync(dirname(path), { recursive: true });\n const tmpPath = `${path}.tmp-${process.pid}-${Date.now()}`;\n writeFileSync(tmpPath, `${JSON.stringify(rules, null, 2)}\\n`, \"utf8\");\n renameSync(tmpPath, path);\n}\n","import { appendProjectSpendRule } from \"../../safety/permissions/config\";\nimport { estimateRunCost, formatUsdWithCacheNote, readRunLogs, type RunLog } from \"../../memory/runLogs\";\nimport { registerCommand } from \"../registry\";\nimport type { CommandDefinition } from \"../registry\";\n\ntype BudgetSection = {\n name: \"system prompt\" | \"repo map\" | \"history\" | \"tool results\" | \"model output\" | \"reasoning\";\n tokens: number;\n usd: number | null;\n cacheModelKnown: boolean;\n};\n\ntype ExpensiveTurn = {\n ts: string;\n provider: string;\n model: string;\n prompt: string;\n totalTokens: number;\n usd: number | null;\n cacheModelKnown: boolean;\n sections: BudgetSection[];\n};\n\ntype BudgetSummary = {\n runs: number;\n inputTokens: number;\n outputTokens: number;\n reasoningTokens: number;\n knownUsd: number;\n cacheModelKnown: boolean;\n unknownPricingRuns: number;\n projectedUsdPerHour: number | null;\n byProvider: Array<{ provider: string; inputTokens: number; outputTokens: number; usd: number | null; cacheModelKnown: boolean; unknownRuns: number }>;\n expensiveTurns: ExpensiveTurn[];\n suggestion: string;\n};\n\nconst numberFormat = new Intl.NumberFormat(\"en-US\");\n\nconst budgetCommand: CommandDefinition = {\n name: \"budget\",\n description: \"Show session token spend, expensive turns, and optimization suggestions.\",\n category: \"built-in\",\n handler(args, ctx) {\n if (args.includes(\"--enforce\")) {\n const maxUsd = parsePositiveNumber(flagValue(args, \"--max-usd\"));\n const maxTokens = parsePositiveNumber(flagValue(args, \"--max-tokens\"));\n if (maxUsd === undefined && maxTokens === undefined) {\n ctx.output.write(\"Usage: /budget --enforce --max-usd <amount> [--max-tokens <count>]\\n\");\n return;\n }\n const path = appendProjectSpendRule(ctx.cwd, {\n type: \"spend\",\n scope: \"session\",\n ...(maxUsd !== undefined ? { max_usd: maxUsd } : {}),\n ...(maxTokens !== undefined ? { max_tokens: maxTokens } : {}),\n action: \"ask\",\n });\n ctx.output.write(`Session budget rule written to ${path}\\n`);\n return;\n }\n\n const logs = readRunLogs(ctx.cwd, 100);\n if (logs.length === 0) {\n ctx.output.write(\"No run logs found. Run tanya run first.\\n\");\n return;\n }\n const summary = buildBudgetSummary(logs);\n if (args.includes(\"--json\")) {\n ctx.output.write(`${JSON.stringify(summary, null, 2)}\\n`);\n return;\n }\n ctx.output.write(formatBudgetSummary(summary));\n },\n};\n\nexport function buildBudgetSummary(logs: RunLog[], now = Date.now()): BudgetSummary {\n const inputTokens = logs.reduce((sum, log) => sum + log.promptTokens, 0);\n const outputTokens = logs.reduce((sum, log) => sum + log.completionTokens, 0);\n const reasoningTokens = logs.reduce((sum, log) => sum + (log.reasoningTokens ?? 0), 0);\n let knownUsd = 0;\n let cacheModelKnown = true;\n let unknownPricingRuns = 0;\n const byProvider = new Map<string, { provider: string; inputTokens: number; outputTokens: number; usd: number | null; cacheModelKnown: boolean; unknownRuns: number }>();\n\n for (const log of logs) {\n const estimate = estimateRunCost(log);\n if (estimate.usd === null) unknownPricingRuns += 1;\n else {\n knownUsd += estimate.usd;\n cacheModelKnown &&= estimate.cacheModelKnown;\n }\n const provider = estimate.provider;\n const current = byProvider.get(provider) ?? { provider, inputTokens: 0, outputTokens: 0, usd: 0, cacheModelKnown: true, unknownRuns: 0 };\n current.inputTokens += log.promptTokens;\n current.outputTokens += log.completionTokens;\n if (estimate.usd === null) {\n current.unknownRuns += 1;\n current.usd = current.usd === null ? null : current.usd;\n } else if (current.usd !== null) {\n current.usd += estimate.usd;\n current.cacheModelKnown &&= estimate.cacheModelKnown;\n }\n byProvider.set(provider, current);\n }\n\n const recentUsd = logs\n .filter((log) => now - Date.parse(log.ts) <= 30 * 60 * 1000)\n .reduce((sum, log) => sum + (estimateRunCost(log).usd ?? 0), 0);\n const projectedUsdPerHour = recentUsd > 0 ? recentUsd * 2 : null;\n const expensiveTurns = [...logs]\n .map(toExpensiveTurn)\n .sort((a, b) => (b.usd ?? 0) - (a.usd ?? 0) || b.totalTokens - a.totalTokens)\n .slice(0, 3);\n\n return {\n runs: logs.length,\n inputTokens,\n outputTokens,\n reasoningTokens,\n knownUsd,\n cacheModelKnown,\n unknownPricingRuns,\n projectedUsdPerHour,\n byProvider: [...byProvider.values()].sort((a, b) => a.provider.localeCompare(b.provider)),\n expensiveTurns,\n suggestion: budgetSuggestion(logs, expensiveTurns),\n };\n}\n\nfunction toExpensiveTurn(log: RunLog): ExpensiveTurn {\n const estimate = estimateRunCost(log);\n const provider = estimate.provider;\n const sections = budgetSections(log);\n return {\n ts: log.ts,\n provider,\n model: log.model,\n prompt: log.prompt,\n totalTokens: log.promptTokens + log.completionTokens + (log.reasoningTokens ?? 0),\n usd: estimate.usd,\n cacheModelKnown: estimate.cacheModelKnown,\n sections,\n };\n}\n\nfunction budgetSections(log: RunLog): BudgetSection[] {\n const systemPrompt = log.systemPromptTokens ?? 0;\n const repoMap = log.repoMapTokens ?? 0;\n const history = log.historyTokens ?? 0;\n const toolResults = log.toolResultTokens ?? 0;\n return [\n estimateSection(\"system prompt\", systemPrompt, estimateInputCost(log, systemPrompt)),\n estimateSection(\"repo map\", repoMap, estimateInputCost(log, repoMap)),\n estimateSection(\"history\", history, estimateInputCost(log, history)),\n estimateSection(\"tool results\", toolResults, estimateInputCost(log, toolResults)),\n estimateSection(\"model output\", log.completionTokens, estimateOutputCost(log, log.completionTokens)),\n estimateSection(\"reasoning\", log.reasoningTokens ?? 0, estimateOutputCost(log, log.reasoningTokens ?? 0)),\n ];\n}\n\nfunction estimateSection(name: BudgetSection[\"name\"], tokens: number, estimate: ReturnType<typeof estimateRunCost>): BudgetSection {\n return { name, tokens, usd: estimate.usd, cacheModelKnown: estimate.cacheModelKnown };\n}\n\nfunction estimateInputCost(log: RunLog, tokens: number): ReturnType<typeof estimateRunCost> {\n if (tokens <= 0) return zeroCostEstimate(log);\n return estimateRunCost({ ...log, promptTokens: tokens, completionTokens: 0 });\n}\n\nfunction estimateOutputCost(log: RunLog, tokens: number): ReturnType<typeof estimateRunCost> {\n if (tokens <= 0) return zeroCostEstimate(log);\n return estimateRunCost({ ...log, promptTokens: 0, completionTokens: tokens });\n}\n\nfunction zeroCostEstimate(log: RunLog): ReturnType<typeof estimateRunCost> {\n const estimate = estimateRunCost({ ...log, promptTokens: 0, completionTokens: 0, reasoningTokens: 0 });\n return { ...estimate, usd: estimate.usd === null ? null : 0 };\n}\n\nfunction budgetSuggestion(logs: RunLog[], expensiveTurns: ExpensiveTurn[]): string {\n const top = expensiveTurns[0];\n if (!top) return \"No suggestion yet; run a Tanya session first.\";\n const systemPromptTokens = logs.reduce((sum, log) => sum + (log.systemPromptTokens ?? 0), 0);\n const toolResultTokens = logs.reduce((sum, log) => sum + (log.toolResultTokens ?? 0), 0);\n if (toolResultTokens > systemPromptTokens && toolResultTokens > 1_000) {\n return \"Tool results dominate recent input tokens; rely on visible truncation markers and call expand_result only when the missing range is needed.\";\n }\n if (systemPromptTokens > 0 && systemPromptTokens >= logs.reduce((sum, log) => sum + log.promptTokens, 0) * 0.25) {\n return \"System prompts are a large share of input tokens; try TANYA_LITE_PROMPT=1 for cheap-provider exploration turns.\";\n }\n return \"Budget looks balanced; keep /budget in the loop when long sessions start repeating file reads or tool output.\";\n}\n\nfunction formatBudgetSummary(summary: BudgetSummary): string {\n const lines = [\n \"Session budget:\",\n `- Runs: ${summary.runs}`,\n `- Input tokens: ${numberFormat.format(summary.inputTokens)}`,\n `- Output tokens: ${numberFormat.format(summary.outputTokens)}`,\n `- Reasoning tokens: ${numberFormat.format(summary.reasoningTokens)}`,\n `- Known spend: ${formatUsdWithCacheNote(summary.knownUsd, summary.cacheModelKnown)}${summary.unknownPricingRuns > 0 ? ` (${summary.unknownPricingRuns} run${summary.unknownPricingRuns === 1 ? \"\" : \"s\"} pricing unknown)` : \"\"}`,\n `- Projected cost/hour: ${summary.projectedUsdPerHour === null ? \"pricing unknown\" : formatUsdWithCacheNote(summary.projectedUsdPerHour, summary.cacheModelKnown)}`,\n \"\",\n \"Providers:\",\n ];\n for (const provider of summary.byProvider) {\n lines.push(`- ${provider.provider}: ${numberFormat.format(provider.inputTokens)} in / ${numberFormat.format(provider.outputTokens)} out, ${provider.usd === null ? \"pricing unknown\" : formatUsdWithCacheNote(provider.usd, provider.cacheModelKnown)}`);\n }\n lines.push(\"\", \"Top expensive turns:\");\n for (const turn of summary.expensiveTurns) {\n lines.push(`- ${turn.ts.slice(0, 16)} ${turn.provider}:${turn.model} ${numberFormat.format(turn.totalTokens)} tokens ${turn.usd === null ? \"pricing unknown\" : formatUsdWithCacheNote(turn.usd, turn.cacheModelKnown)}`);\n for (const section of turn.sections) {\n lines.push(` ${section.name}: ${numberFormat.format(section.tokens)} tokens, ${section.usd === null ? \"pricing unknown\" : formatUsdWithCacheNote(section.usd, section.cacheModelKnown)}`);\n }\n }\n lines.push(\"\", `Suggestion: ${summary.suggestion}`, \"\");\n return lines.join(\"\\n\");\n}\n\nfunction flagValue(args: string[], flag: string): string | undefined {\n const index = args.indexOf(flag);\n const value = index >= 0 ? args[index + 1] : undefined;\n return value && !value.startsWith(\"--\") ? value : undefined;\n}\n\nfunction parsePositiveNumber(raw: string | undefined): number | undefined {\n const parsed = raw ? Number(raw) : NaN;\n return Number.isFinite(parsed) && parsed > 0 ? parsed : undefined;\n}\n\nregisterCommand(budgetCommand);\n","import { registerCommand } from \"../registry\";\nimport type { CommandDefinition } from \"../registry\";\n\nconst clearCommand: CommandDefinition = {\n name: \"clear\",\n description: \"Clear the active conversation history.\",\n category: \"built-in\",\n handler(_args, ctx) {\n if (ctx.clearHistory) {\n ctx.clearHistory();\n } else if (ctx.history) {\n ctx.history.length = 0;\n }\n ctx.output.write(\"Conversation history cleared.\\n\");\n },\n};\n\nregisterCommand(clearCommand);\n","import { estimateRunCost, formatUsdWithCacheNote, readRunLogs } from \"../../memory/runLogs\";\nimport { appendProjectSpendRule } from \"../../safety/permissions/config\";\nimport { registerCommand } from \"../registry\";\nimport type { CommandDefinition } from \"../registry\";\n\nconst costCommand: CommandDefinition = {\n name: \"cost\",\n description: \"Show token usage and estimated run costs.\",\n category: \"built-in\",\n handler(args, ctx) {\n if (args.includes(\"--enforce\")) {\n const maxUsd = parsePositiveNumber(flagValue(args, \"--max-usd\"));\n const maxTokens = parsePositiveNumber(flagValue(args, \"--max-tokens\"));\n if (maxUsd === undefined && maxTokens === undefined) {\n ctx.output.write(\"Usage: /cost --enforce --max-usd <amount> [--max-tokens <count>]\\n\");\n return;\n }\n const path = appendProjectSpendRule(ctx.cwd, {\n type: \"spend\",\n scope: \"session\",\n ...(maxUsd !== undefined ? { max_usd: maxUsd } : {}),\n ...(maxTokens !== undefined ? { max_tokens: maxTokens } : {}),\n action: \"deny\",\n });\n ctx.output.write(`Session spend rule written to ${path}\\n`);\n return;\n }\n\n const logs = readRunLogs(ctx.cwd);\n if (logs.length === 0) {\n ctx.output.write(\"No run logs found. Run tanya run first.\\n\");\n return;\n }\n\n let knownTotal = 0;\n let unknownCount = 0;\n let hasCacheMissEstimate = false;\n ctx.output.write(\"Recent run costs:\\n\");\n for (const log of logs) {\n const estimate = estimateRunCost(log);\n if (estimate.usd === null) {\n unknownCount += 1;\n } else {\n knownTotal += estimate.usd;\n hasCacheMissEstimate ||= !estimate.cacheModelKnown;\n }\n const reasoning = log.reasoningTokens ?? 0;\n ctx.output.write(\n `${log.ts.slice(0, 16)} ${estimate.provider}:${log.model} ${log.promptTokens.toLocaleString(\"en-US\")} in / ${log.completionTokens.toLocaleString(\"en-US\")} out / ${reasoning.toLocaleString(\"en-US\")} reasoning ${estimate.display}\\n`,\n );\n }\n ctx.output.write(`Session total: ${formatUsdWithCacheNote(knownTotal, !hasCacheMissEstimate)}${unknownCount > 0 ? ` (${unknownCount} run${unknownCount === 1 ? \"\" : \"s\"} pricing unknown)` : \"\"}\\n`);\n },\n};\n\nfunction flagValue(args: string[], flag: string): string | undefined {\n const index = args.indexOf(flag);\n const value = index >= 0 ? args[index + 1] : undefined;\n return value && !value.startsWith(\"--\") ? value : undefined;\n}\n\nfunction parsePositiveNumber(raw: string | undefined): number | undefined {\n const parsed = raw ? Number(raw) : NaN;\n return Number.isFinite(parsed) && parsed > 0 ? parsed : undefined;\n}\n\nregisterCommand(costCommand);\n","import { commandIsAvailable, listCommands, registerCommand } from \"../registry\";\nimport type { CommandDefinition } from \"../registry\";\n\nconst helpCommand: CommandDefinition = {\n name: \"help\",\n description: \"List available slash commands.\",\n category: \"built-in\",\n async handler(_args, ctx) {\n const commands = [];\n for (const command of listCommands()) {\n if (await commandIsAvailable(command, ctx)) commands.push(command);\n }\n ctx.output.write(\"Built-in commands:\\n\");\n for (const command of commands.filter((candidate) => (candidate.category ?? \"built-in\") === \"built-in\")) {\n ctx.output.write(`/${command.name} — ${command.description}\\n`);\n }\n const projectCommands = commands.filter((candidate) => candidate.category === \"project\");\n if (projectCommands.length > 0) {\n ctx.output.write(\"Project commands:\\n\");\n for (const command of projectCommands) {\n ctx.output.write(`/${command.name} — ${command.description}\\n`);\n }\n }\n },\n};\n\nregisterCommand(helpCommand);\n","import { readdir, readFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport { readGoldenTaskMemory } from \"../../memory/goldenTasks\";\nimport { readReasoningArchive } from \"../../memory/reasoningArchive\";\nimport { registerCommand } from \"../registry\";\nimport type { CommandDefinition } from \"../registry\";\n\nconst DEFAULT_LIMIT = 10;\n\nconst memoryCommand: CommandDefinition = {\n name: \"memory\",\n description: \"Show recent golden-task memory.\",\n category: \"built-in\",\n async handler(args, ctx) {\n const reasoningRunId = flagValue(args, \"--reasoning\");\n if (reasoningRunId) {\n const turn = parseOptionalNumber(flagValue(args, \"--turn\"));\n const entries = readReasoningArchive(ctx.cwd, reasoningRunId)\n .filter((entry) => turn === undefined || entry.turn === turn);\n if (entries.length === 0) {\n ctx.output.write(`No reasoning archive found for ${reasoningRunId}${turn === undefined ? \"\" : ` turn ${turn}`}.\\n`);\n return;\n }\n ctx.output.write(`Reasoning archive for ${reasoningRunId}:\\n`);\n for (const entry of entries) {\n const turnLabel = entry.turn === undefined ? \"turn ?\" : `turn ${entry.turn}`;\n ctx.output.write(`- ${entry.ts} ${turnLabel} ${entry.provider}:${entry.model} ${entry.tokens ?? 0} tokens\\n`);\n ctx.output.write(`${indent(entry.content.trim() || \"(empty)\")}\\n`);\n }\n return;\n }\n\n const records = [...await readGoldenTaskMemory(ctx.cwd)]\n .sort((a, b) => b.recordedAt.localeCompare(a.recordedAt));\n const fullId = flagValue(args, \"--full\");\n if (fullId) {\n const record = records.find((candidate) => candidate.signature === fullId);\n if (!record) {\n ctx.output.write(`Golden task not found: ${fullId}\\n`);\n return;\n }\n ctx.output.write(`${JSON.stringify(record, null, 2)}\\n`);\n const children = await Promise.all(record.childRunIds.map((runId) => readChildRunSummary(ctx.cwd, runId)));\n const found = children.filter((child): child is ChildRunSummary => child !== null);\n if (found.length > 0) {\n ctx.output.write(\"Child runs:\\n\");\n for (const child of found) {\n const status = child.blockers.length > 0 ? \"failed\" : \"passed\";\n ctx.output.write(` - ${child.runId} ${status} ${child.prompt}\\n`);\n }\n }\n return;\n }\n\n const limit = parseLimit(flagValue(args, \"--limit\"));\n if (records.length === 0) {\n ctx.output.write(\"No golden task memory found.\\n\");\n return;\n }\n\n ctx.output.write(\"Recent golden tasks:\\n\");\n for (const record of records.slice(0, limit)) {\n const title = record.task?.title ?? \"(untitled)\";\n ctx.output.write(`${record.recordedAt.slice(0, 16)} ${record.outcome.padEnd(6)} ${record.signature} ${title}\\n`);\n }\n },\n};\n\nfunction flagValue(args: string[], flag: string): string | undefined {\n const index = args.indexOf(flag);\n const value = index >= 0 ? args[index + 1] : undefined;\n return value && !value.startsWith(\"--\") ? value : undefined;\n}\n\nfunction parseLimit(raw: string | undefined): number {\n const parsed = raw ? Number(raw) : DEFAULT_LIMIT;\n return Number.isInteger(parsed) && parsed > 0 ? parsed : DEFAULT_LIMIT;\n}\n\nfunction parseOptionalNumber(raw: string | undefined): number | undefined {\n const parsed = raw ? Number(raw) : NaN;\n return Number.isInteger(parsed) && parsed >= 0 ? parsed : undefined;\n}\n\nfunction indent(text: string): string {\n return text.split(\"\\n\").map((line) => ` ${line}`).join(\"\\n\");\n}\n\nregisterCommand(memoryCommand);\n\ntype ChildRunSummary = {\n runId: string;\n prompt: string;\n blockers: string[];\n};\n\nasync function readChildRunSummary(workspace: string, runId: string): Promise<ChildRunSummary | null> {\n const runsRoot = join(workspace, \".tania\", \"runs\");\n const path = await findRunSummaryPath(runsRoot, `${runId}.json`);\n if (!path) return null;\n try {\n const parsed = JSON.parse(await readFile(path, \"utf8\")) as Partial<ChildRunSummary>;\n return {\n runId: typeof parsed.runId === \"string\" ? parsed.runId : runId,\n prompt: typeof parsed.prompt === \"string\" ? parsed.prompt : \"(prompt unavailable)\",\n blockers: Array.isArray(parsed.blockers)\n ? parsed.blockers.filter((item): item is string => typeof item === \"string\")\n : [],\n };\n } catch {\n return null;\n }\n}\n\nasync function findRunSummaryPath(dir: string, filename: string): Promise<string | null> {\n let entries;\n try {\n entries = await readdir(dir, { withFileTypes: true });\n } catch {\n return null;\n }\n for (const entry of entries) {\n const path = join(dir, entry.name);\n if (entry.isFile() && entry.name === filename) return path;\n if (entry.isDirectory()) {\n const nested = await findRunSummaryPath(path, filename);\n if (nested) return nested;\n }\n }\n return null;\n}\n","import { ToolRegistry } from \"../../tools/registry\";\nimport { getActiveMcpManager, loadMcpToolsForWorkspace } from \"../../mcp/client\";\nimport { registerCommand } from \"../registry\";\nimport type { CommandDefinition } from \"../registry\";\n\nconst mcpCommand: CommandDefinition = {\n name: \"mcp\",\n description: \"List configured MCP servers, status, and tools.\",\n category: \"built-in\",\n async handler(_args, ctx) {\n const manager = getActiveMcpManager() ?? await loadMcpToolsForWorkspace({\n cwd: ctx.cwd,\n registry: new ToolRegistry([]),\n sink: ctx.sink,\n });\n const statuses = manager.statuses();\n if (statuses.length === 0) {\n ctx.output.write(\"No MCP servers configured.\\n\");\n return;\n }\n ctx.output.write(\"MCP servers:\\n\");\n for (const status of statuses) {\n const tools = status.toolNames.length > 0 ? status.toolNames.join(\", \") : \"-\";\n const error = status.error ? ` (${status.error})` : \"\";\n ctx.output.write(`${status.name} ${status.status} ${status.transport} restarts=${status.restarts} tools=${tools}${error}\\n`);\n }\n },\n};\n\nregisterCommand(mcpCommand);\n","import { writeProjectPermissionMode } from \"../../safety/permissions/config\";\nimport type { PermissionMode } from \"../../safety/permissions/schema\";\nimport { registerCommand } from \"../registry\";\nimport type { CommandDefinition } from \"../registry\";\n\nconst MODES = new Set<PermissionMode>([\"default\", \"ask\", \"bypass\", \"plan\"]);\n\nconst modeCommand: CommandDefinition = {\n name: \"mode\",\n description: \"Switch the project permission mode.\",\n category: \"built-in\",\n handler(args, ctx) {\n const mode = args[0] as PermissionMode | undefined;\n if (!mode || !MODES.has(mode)) {\n ctx.output.write(\"Usage: /mode <default|ask|bypass|plan>\\n\");\n return;\n }\n const path = writeProjectPermissionMode(ctx.cwd, mode);\n ctx.output.write(`Permission mode set to ${mode} in ${path}\\n`);\n },\n};\n\nregisterCommand(modeCommand);\n","import { loadRouteTable, resolveRoute, type EffectiveRouteTable, type RouteTarget, type StepType } from \"../../router\";\nimport { registerCommand } from \"../registry\";\nimport type { CommandContext, CommandDefinition } from \"../registry\";\n\nconst STEP_TYPES = new Set<StepType>([\"planning\", \"tool_call\", \"synthesis\", \"verification\", \"reasoning\", \"unknown\"]);\n\nconst routeCommand: CommandDefinition = {\n name: \"route\",\n description: \"Show or patch the active model route table.\",\n category: \"built-in\",\n handler(args, ctx) {\n const table = effectiveTable(ctx);\n const subcommand = args[0];\n if (!subcommand) {\n printTable(ctx, table);\n return;\n }\n\n if (subcommand === \"show\") {\n const stepType = parseStep(args[1]);\n if (!stepType) {\n ctx.output.write(\"Usage: /route show <planning|tool_call|synthesis|verification|reasoning|unknown>\\n\");\n return;\n }\n const route = resolveRoute(stepType, table);\n ctx.output.write(`${stepType}: ${route.provider}/${route.model} (${route.source}; ${route.reason})`);\n if (route.fallback) ctx.output.write(` fallback ${route.fallback.provider}/${route.fallback.model}`);\n ctx.output.write(\"\\n\");\n return;\n }\n\n if (subcommand === \"set\") {\n const stepType = parseStep(args[1]);\n const target = parseTarget(args[2]);\n if (!stepType || !target) {\n ctx.output.write(\"Usage: /route set <stepType> <provider>/<model>\\n\");\n return;\n }\n if (!ctx.routing) {\n ctx.output.write(\"Route patching requires an active Tanya routing session.\\n\");\n return;\n }\n ctx.routing.enabled = true;\n ctx.routing.table.routes = [\n { match: stepType, provider: target.provider, model: target.model, source: \"session\" },\n ...ctx.routing.table.routes.filter((route) => !(route.source === \"session\" && route.match === stepType)),\n ];\n ctx.output.write(`Route ${stepType} set to ${target.provider}/${target.model} for this session.\\n`);\n return;\n }\n\n if (subcommand === \"reset\") {\n if (ctx.routing) {\n ctx.routing.table.routes = ctx.routing.table.routes.filter((route) => route.source !== \"session\");\n ctx.routing.enabled = ctx.routing.table.sources.some((source) => source !== \"built-in\");\n }\n ctx.output.write(\"Session route patches cleared.\\n\");\n return;\n }\n\n ctx.output.write(\"Usage: /route [show <stepType>|set <stepType> <provider>/<model>|reset]\\n\");\n },\n};\n\nfunction effectiveTable(ctx: CommandContext): EffectiveRouteTable {\n if (ctx.routing) return ctx.routing.table;\n const provider = ctx.provider ? { provider: ctx.provider.id, model: ctx.provider.model } : { provider: \"openai\", model: \"gpt-4.1-mini\" };\n return loadRouteTable({ cwd: ctx.cwd, defaults: provider }).table;\n}\n\nfunction printTable(ctx: CommandContext, table: EffectiveRouteTable): void {\n ctx.output.write(\"stepType | provider | model | fallback | source\\n\");\n ctx.output.write(\"--- | --- | --- | --- | ---\\n\");\n for (const route of table.routes) {\n const match = typeof route.match === \"string\" ? route.match : `/${route.match.regex}/`;\n const fallback = route.fallback ? `${route.fallback.provider}/${route.fallback.model}` : \"-\";\n ctx.output.write(`${match} | ${route.provider} | ${route.model} | ${fallback} | ${route.source}\\n`);\n }\n ctx.output.write(`defaults | ${table.defaults.provider} | ${table.defaults.model} | - | ${table.defaultSource}\\n`);\n}\n\nfunction parseStep(value: string | undefined): StepType | null {\n return value && STEP_TYPES.has(value as StepType) ? value as StepType : null;\n}\n\nfunction parseTarget(value: string | undefined): RouteTarget | null {\n if (!value) return null;\n const slash = value.indexOf(\"/\");\n if (slash <= 0 || slash === value.length - 1) return null;\n return { provider: value.slice(0, slash), model: value.slice(slash + 1) };\n}\n\nregisterCommand(routeCommand);\n","import { loadPromptSkillPacks } from \"../../agent/systemPrompt\";\nimport { formatSkillPackSummary } from \"../../skills\";\nimport { registerCommand } from \"../registry\";\nimport type { CommandDefinition } from \"../registry\";\n\nconst skillsCommand: CommandDefinition = {\n name: \"skills\",\n description: \"Show skill packs matched for this workspace.\",\n category: \"built-in\",\n handler(args, ctx) {\n const taskHint = args.join(\" \");\n const packs = loadPromptSkillPacks(ctx.cwd, undefined, taskHint);\n ctx.output.write(`${formatSkillPackSummary(packs)}\\n`);\n },\n};\n\nregisterCommand(skillsCommand);\n","import { buildFinalManifest, ensureCodingReport } from \"../../agent/report\";\nimport { captureGitSnapshot } from \"../../agent/git\";\nimport { registerCommand } from \"../registry\";\nimport type { CommandDefinition } from \"../registry\";\n\nconst verifyCommand: CommandDefinition = {\n name: \"verify\",\n description: \"Run Tanya's deterministic final-state verifier for the current workspace.\",\n category: \"built-in\",\n async handler(_args, ctx) {\n const beforeGitSnapshot = await captureGitSnapshot(ctx.cwd);\n const manifest = await buildFinalManifest({\n workspace: ctx.cwd,\n beforeGitSnapshot,\n changed: [],\n verificationLines: [],\n toolErrorCount: 0,\n readArtifactPaths: [],\n readContextPaths: [],\n createdArtifactPaths: [],\n blockers: [],\n prompt: \"Ad-hoc /verify command\",\n });\n const report = ensureCodingReport(\"\", manifest);\n ctx.output.write(`${report.trim() || \"No verifier evidence available for this workspace.\"}\\n`);\n },\n};\n\nregisterCommand(verifyCommand);\n","export function formatElapsed(elapsedMs: number): string {\n const ms = Math.max(0, Math.floor(elapsedMs));\n if (ms < 60_000) return `${(ms / 1000).toFixed(1)}s`;\n if (ms < 3_600_000) {\n const minutes = Math.floor(ms / 60_000);\n const seconds = Math.floor((ms % 60_000) / 1000);\n return `${minutes}m ${seconds}s`;\n }\n\n const hours = Math.floor(ms / 3_600_000);\n const minutes = Math.floor((ms % 3_600_000) / 60_000);\n return `${hours}h ${minutes.toString().padStart(2, \"0\")}m`;\n}\n\nexport function formatClock(date: Date): string {\n return [\n date.getHours(),\n date.getMinutes(),\n date.getSeconds(),\n ].map((part) => part.toString().padStart(2, \"0\")).join(\":\");\n}\n","import { formatSessionList } from \"../cli/sessionsCommand\";\nimport { listSessions } from \"../sessions/storage\";\nimport { replayTurns, resumeBanner, sessionToChatHistory } from \"../sessions/repl\";\nimport type { ChatSession } from \"../sessions/types\";\nimport { formatClock, formatElapsed } from \"../utils/formatElapsed\";\nimport { registerCommand } from \"./registry\";\nimport type { CommandContext, CommandDefinition } from \"./registry\";\n\nconst sessionsCommand: CommandDefinition = {\n name: \"sessions\",\n description: \"List recent chat sessions.\",\n category: \"built-in\",\n handler(_args, ctx) {\n ctx.output.write(formatSessionList(listSessions({ cwd: ctx.cwd, limit: 10 }), outputColumns(ctx.output)));\n },\n};\n\nconst resumeCommand: CommandDefinition = {\n name: \"resume\",\n description: \"Resume a saved chat session.\",\n category: \"built-in\",\n async handler(args, ctx) {\n const id = args[0];\n if (!id) {\n ctx.output.write(\"Usage: /resume <id>\\n\");\n return;\n }\n if (!ctx.sessionController) {\n ctx.output.write(\"Session persistence is not available in this context.\\n\");\n return;\n }\n const unsaved = ctx.sessionController.unsavedTurnCount;\n if (unsaved > 0) {\n const ok = await confirm(ctx, `Current session has ${unsaved} turn${unsaved === 1 ? \"\" : \"s\"}. Discard and resume ${id}?`);\n if (!ok) {\n ctx.output.write(\"Resume cancelled.\\n\");\n return;\n }\n }\n const loaded = ctx.sessionController.resume(id, ctx.cwd);\n const history = sessionToChatHistory(loaded.session);\n if (ctx.replaceHistory) ctx.replaceHistory(history);\n else if (ctx.history) ctx.history.splice(0, ctx.history.length, ...history);\n ctx.output.write(`${resumeBanner(loaded.session)}\\n`);\n if (ctx.onSessionResumed) ctx.onSessionResumed(loaded.session);\n else writeReplay(ctx, loaded.session);\n },\n};\n\nconst saveCommand: CommandDefinition = {\n name: \"save\",\n description: \"Persist the active session now and optionally label it.\",\n category: \"built-in\",\n handler(args, ctx) {\n if (!ctx.sessionController) {\n ctx.output.write(\"Session persistence is not available in this context.\\n\");\n return;\n }\n const label = args.join(\" \").trim();\n const session = ctx.sessionController.save(label || undefined);\n ctx.output.write(`Saved session ${session.id}${session.label ? ` · ${session.label}` : \"\"}\\n`);\n },\n};\n\nasync function confirm(ctx: CommandContext, question: string): Promise<boolean> {\n if (!ctx.onPermissionRequest) return true;\n const answer = await ctx.onPermissionRequest({\n id: `resume-session-${Date.now()}`,\n tool: \"resume_session\",\n input: { question },\n });\n return answer.decision === \"allow\";\n}\n\nfunction writeReplay(ctx: CommandContext, session: ChatSession): void {\n const turns = replayTurns(session, 10);\n ctx.output.write(`── resumed ${session.turns.length} turns ──\\n`);\n for (const turn of turns) {\n const clock = formatClock(new Date(turn.timestampMs));\n const elapsed = typeof turn.elapsedMs === \"number\" ? ` · ${formatElapsed(turn.elapsedMs)}` : \"\";\n ctx.output.write(`[${clock}] ${turn.role}${elapsed}: ${turn.content}\\n`);\n }\n}\n\nfunction outputColumns(output: NodeJS.WritableStream): number {\n return Math.max(60, (output as NodeJS.WritableStream & { columns?: number }).columns ?? 100);\n}\n\nregisterCommand(sessionsCommand);\nregisterCommand(resumeCommand);\nregisterCommand(saveCommand);\n","import { existsSync, readdirSync } from \"node:fs\";\nimport { basename, extname, join, relative } from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport { tsImport } from \"tsx/esm/api\";\nimport { runShellTool } from \"../tools/fsTools\";\nimport { registerCommand, removeCommandsByCategory } from \"./registry\";\nimport type { CommandContext, CommandDefinition } from \"./registry\";\nimport { envValue } from \"../config/envCompat\";\nimport { appendAuditDecision } from \"../memory/auditLog\";\nimport { decide, type Decision, type PermissionContext } from \"../safety/permissions/engine\";\nimport { loadPermissionRules } from \"../safety/permissions/rules\";\nimport type { PermissionMode } from \"../safety/permissions/schema\";\n\nconst supportedExtensions = new Set([\".js\", \".ts\", \".sh\"]);\nconst permissionModes = new Set<PermissionMode>([\"default\", \"ask\", \"bypass\", \"plan\"]);\nlet loadedWorkspace: string | null = null;\n\nexport async function loadProjectCommands(workspace: string): Promise<void> {\n if (loadedWorkspace === workspace) return;\n loadedWorkspace = workspace;\n removeCommandsByCategory(\"project\");\n\n const commandsDir = join(workspace, \".tania\", \"commands\");\n if (!existsSync(commandsDir)) return;\n\n let files: string[] = [];\n try {\n files = readdirSync(commandsDir)\n .filter((file) => supportedExtensions.has(extname(file)))\n .sort();\n } catch (error) {\n warnProjectCommand(commandsDir, error);\n return;\n }\n\n for (const file of files) {\n const path = join(commandsDir, file);\n try {\n const extension = extname(file);\n if (extension === \".sh\") {\n registerShellCommand(workspace, path);\n } else {\n await registerModuleCommand(path);\n }\n } catch (error) {\n warnProjectCommand(path, error);\n }\n }\n}\n\nexport function resetProjectCommandsForTests(): void {\n loadedWorkspace = null;\n removeCommandsByCategory(\"project\");\n}\n\nfunction registerShellCommand(workspace: string, path: string): void {\n const slug = basename(path, extname(path));\n const relativePath = relative(workspace, path).replace(/\\\\/g, \"/\");\n registerCommand({\n name: `project:${slug}`,\n description: `Run ${relativePath}.`,\n category: \"project\",\n async handler(args, ctx) {\n if (!(await guardProjectCommand(ctx, `project:${slug}`, { path: relativePath, args, kind: \"shell\" }))) return;\n const script = [\"zsh\", quoteShell(relativePath), ...args.map(quoteShell)].join(\" \");\n const result = await runShellTool.run({ script }, { workspace: ctx.cwd });\n const output = typeof result.output === \"string\" ? result.output : \"\";\n if (output) ctx.output.write(`${output}${output.endsWith(\"\\n\") ? \"\" : \"\\n\"}`);\n if (!result.ok) ctx.output.write(`${result.error ?? result.summary}\\n`);\n },\n });\n}\n\nasync function registerModuleCommand(path: string): Promise<void> {\n const href = pathToFileURL(path).href;\n const imported = extname(path) === \".ts\"\n ? await tsImport(href, import.meta.url) as { default?: unknown }\n : await import(href) as { default?: unknown };\n const command = unwrapDefaultCommand(imported);\n if (!isCommandDefinition(command)) {\n throw new Error(\"default export is not a CommandDefinition\");\n }\n registerCommand({\n ...command,\n name: command.name.startsWith(\"project:\") ? command.name : `project:${command.name}`,\n category: \"project\",\n async handler(args, ctx) {\n const name = command.name.startsWith(\"project:\") ? command.name : `project:${command.name}`;\n if (!(await guardProjectCommand(ctx, name, { path, args, kind: \"module\" }))) return;\n await command.handler(args, ctx);\n },\n });\n}\n\nasync function guardProjectCommand(ctx: CommandContext, name: string, input: unknown): Promise<boolean> {\n const loaded = loadPermissionRules({ cwd: ctx.cwd });\n const rawMode = envValue(process.env, \"TANYA_MODE\")?.trim();\n const mode = rawMode && permissionModes.has(rawMode as PermissionMode) ? rawMode as PermissionMode : loaded.rules.mode;\n const permissionContext: PermissionContext = {\n mode,\n rules: loaded.rules,\n runId: ctx.runId ?? `command-${Date.now()}`,\n cwd: ctx.cwd,\n };\n let decision: Decision = mode === \"bypass\"\n ? { decision: \"allow\", reason: \"bypass-mode\" }\n : decide(\"project_command\", { name, ...input as Record<string, unknown> }, permissionContext);\n let source: \"user\" | \"rule\" | \"engine\" | \"bypass\" = mode === \"bypass\" ? \"bypass\" : decision.matchedRule ? \"rule\" : \"engine\";\n const id = `command:${name}`;\n\n if (mode !== \"bypass\" && decision.decision === \"ask\") {\n await ctx.sink({\n type: \"permission_request\",\n id,\n tool: \"project_command\",\n input: { name, ...input as Record<string, unknown> },\n ...(decision.matchedRule ? { matchedRule: decision.matchedRule } : {}),\n });\n const answer = ctx.onPermissionRequest\n ? await ctx.onPermissionRequest({ id, tool: \"project_command\", input: { name, ...input as Record<string, unknown> }, ...(decision.matchedRule ? { matchedRule: decision.matchedRule } : {}) })\n : { decision: \"deny\" as const };\n decision = { ...decision, decision: answer.decision, reason: answer.decision === \"allow\" ? \"user-approved\" : \"permission-denied\" };\n source = ctx.onPermissionRequest ? \"user\" : \"engine\";\n await ctx.sink({\n type: \"permission_decision\",\n id,\n decision: answer.decision,\n source,\n ...(answer.persistAs ? { persistAs: answer.persistAs } : {}),\n ...(decision.matchedRule ? { matchedRule: decision.matchedRule } : {}),\n });\n } else if (mode !== \"bypass\") {\n await ctx.sink({\n type: \"permission_decision\",\n id,\n decision: decision.decision === \"deny\" ? \"deny\" : \"allow\",\n source,\n ...(decision.matchedRule ? { matchedRule: decision.matchedRule } : {}),\n });\n }\n\n appendAuditDecision(ctx.cwd, {\n ts: new Date().toISOString(),\n runId: permissionContext.runId,\n tool: \"project_command\",\n input: { name, ...input as Record<string, unknown> },\n decision: decision.decision,\n source,\n mode,\n ...(decision.matchedRule ? { matchedRule: decision.matchedRule } : {}),\n });\n\n if (decision.decision === \"allow\") return true;\n ctx.output.write(`permission denied: ${decision.matchedRule ?? decision.reason ?? \"project command\"}\\n`);\n return false;\n}\n\nfunction unwrapDefaultCommand(imported: { default?: unknown }): unknown {\n if (isCommandDefinition(imported.default)) return imported.default;\n const nested = imported.default;\n if (nested && typeof nested === \"object\" && \"default\" in nested) {\n return (nested as { default?: unknown }).default;\n }\n return imported.default;\n}\n\nfunction isCommandDefinition(value: unknown): value is CommandDefinition {\n return Boolean(\n value &&\n typeof value === \"object\" &&\n typeof (value as { name?: unknown }).name === \"string\" &&\n typeof (value as { description?: unknown }).description === \"string\" &&\n typeof (value as { handler?: unknown }).handler === \"function\",\n );\n}\n\nfunction quoteShell(value: string): string {\n return `'${value.replace(/'/g, \"'\\\\''\")}'`;\n}\n\nfunction warnProjectCommand(path: string, error: unknown): void {\n const message = error instanceof Error ? error.message : String(error);\n console.warn(`[tanya] Skipping project command ${path}: ${message}`);\n}\n","import \"./builtin/audit\";\nimport \"./builtin/budget\";\nimport \"./builtin/clear\";\nimport \"./builtin/cost\";\nimport \"./builtin/help\";\nimport \"./builtin/memory\";\nimport \"./builtin/mcp\";\nimport \"./builtin/mode\";\nimport \"./builtin/route\";\nimport \"./builtin/skills\";\nimport \"./builtin/verify\";\nimport \"./sessions\";\nimport { commandIsAvailable, getCommand, normalizeCommandName } from \"./registry\";\nimport type { CommandContext } from \"./registry\";\nimport { loadProjectCommands } from \"./project\";\n\nexport type ParsedCommandLine = {\n name: string;\n args: string[];\n};\n\nexport function parseCommandLine(line: string): ParsedCommandLine | null {\n const trimmed = line.trim();\n if (!trimmed.startsWith(\"/\")) return null;\n const body = trimmed.slice(1).trim();\n if (!body) return null;\n const firstWhitespace = body.search(/\\s/);\n const rawName = firstWhitespace === -1 ? body : body.slice(0, firstWhitespace);\n const rawArgs = firstWhitespace === -1 ? \"\" : body.slice(firstWhitespace).trim();\n const name = normalizeCommandName(rawName);\n if (!/^[a-z0-9:_-]+$/.test(name)) return null;\n return { name, args: splitCommandArgs(rawArgs) };\n}\n\nexport function commandNameFromLine(line: string): string | null {\n return parseCommandLine(line)?.name ?? null;\n}\n\nexport async function runCommand(line: string, ctx: CommandContext): Promise<boolean> {\n const parsed = parseCommandLine(line);\n if (!parsed) return false;\n await loadProjectCommands(ctx.cwd);\n\n const command = getCommand(parsed.name);\n if (!command) return false;\n if (!(await commandIsAvailable(command, ctx))) return false;\n\n await ctx.sink({\n type: \"command_invoked\",\n name: command.name,\n args: parsed.args,\n ...(ctx.runId ? { runId: ctx.runId } : {}),\n });\n await command.handler(parsed.args, ctx);\n return true;\n}\n\nfunction splitCommandArgs(input: string): string[] {\n const args: string[] = [];\n let current = \"\";\n let quote: \"\\\"\" | \"'\" | null = null;\n let escaping = false;\n\n for (const char of input) {\n if (escaping) {\n current += char;\n escaping = false;\n continue;\n }\n if (char === \"\\\\\") {\n escaping = true;\n continue;\n }\n if (quote) {\n if (char === quote) {\n quote = null;\n } else {\n current += char;\n }\n continue;\n }\n if (char === \"\\\"\" || char === \"'\") {\n quote = char;\n continue;\n }\n if (/\\s/.test(char)) {\n if (current) {\n args.push(current);\n current = \"\";\n }\n continue;\n }\n current += char;\n }\n\n if (escaping) current += \"\\\\\";\n if (current) args.push(current);\n return args;\n}\n\nexport {\n commandIsAvailable,\n getCommand,\n listCommands,\n normalizeCommandName,\n registerCommand,\n removeCommandsByCategory,\n} from \"./registry\";\nexport { loadProjectCommands } from \"./project\";\nexport type { CommandContext, CommandDefinition } from \"./registry\";\n","import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { dirname, join } from \"node:path\";\nimport { inputShape } from \"./engine\";\nimport { DEFAULT_PERMISSION_RULES, parsePermissionsJson, type PermissionRulesConfig } from \"./schema\";\n\nexport type LearnedPermissionPersistence = \"always\" | \"never\";\n\nexport function permissionPatternForInput(tool: string, input: unknown): string {\n return `${tool}:${escapeRegex(inputShape(input))}`;\n}\n\nexport function appendLearnedPermissionRule(options: {\n tool: string;\n input: unknown;\n persistAs: LearnedPermissionPersistence;\n home?: string;\n}): string {\n const home = options.home ?? homedir();\n const path = join(home, \".tanya\", \"permissions.json\");\n const pattern = permissionPatternForInput(options.tool, options.input);\n const current = readUserPermissions(path);\n const next: PermissionRulesConfig = {\n ...current,\n alwaysAllow: options.persistAs === \"always\" ? appendUnique(current.alwaysAllow, pattern) : current.alwaysAllow,\n alwaysDeny: options.persistAs === \"never\" ? appendUnique(current.alwaysDeny, pattern) : current.alwaysDeny,\n };\n mkdirSync(dirname(path), { recursive: true });\n const tmpPath = `${path}.tmp-${process.pid}-${Date.now()}`;\n writeFileSync(tmpPath, `${JSON.stringify(next, null, 2)}\\n`, \"utf8\");\n renameSync(tmpPath, path);\n return pattern;\n}\n\nfunction readUserPermissions(path: string): PermissionRulesConfig {\n if (!existsSync(path)) return { ...DEFAULT_PERMISSION_RULES };\n const parsed = parsePermissionsJson(readFileSync(path, \"utf8\"));\n if (!parsed.ok) return { ...DEFAULT_PERMISSION_RULES };\n return parsed.value;\n}\n\nfunction appendUnique(items: string[], item: string): string[] {\n return items.includes(item) ? items : [...items, item];\n}\n\nfunction escapeRegex(value: string): string {\n return value.replace(/[|\\\\{}()[\\]^$+?.]/g, \"\\\\$&\");\n}\n","import type { PermissionRequestHandler } from \"../safety/permissions/host\";\nimport { appendLearnedPermissionRule } from \"../safety/permissions/learning\";\n\ntype Question = (prompt: string) => Promise<string>;\n\nexport function createReplPermissionRequestHandler(options: {\n question: Question;\n output?: NodeJS.WritableStream;\n home?: string;\n}): PermissionRequestHandler {\n return async (request) => {\n const label = request.matchedRule ? `${request.tool} (${request.matchedRule})` : request.tool;\n const question = requestQuestion(request.input);\n while (true) {\n const prompt = question ? `${question} [y/N]` : `Permission required for ${label}. Allow? [y/n/always/never]`;\n const answer = (await options.question(`\\x1b[33m${prompt}\\x1b[0m `)).trim().toLowerCase();\n if (answer === \"y\" || answer === \"yes\") return { decision: \"allow\" };\n if (answer === \"n\" || answer === \"no\") return { decision: \"deny\" };\n if (question && answer === \"\") return { decision: \"deny\" };\n if (question) {\n options.output?.write(\"Please answer y or n.\\n\");\n continue;\n }\n if (answer === \"always\") {\n const pattern = appendLearnedPermissionRule({\n tool: request.tool,\n input: request.input,\n persistAs: \"always\",\n ...(options.home ? { home: options.home } : {}),\n });\n options.output?.write(`Saved allow rule: ${pattern}\\n`);\n return { decision: \"allow\", persistAs: \"always\" };\n }\n if (answer === \"never\") {\n const pattern = appendLearnedPermissionRule({\n tool: request.tool,\n input: request.input,\n persistAs: \"never\",\n ...(options.home ? { home: options.home } : {}),\n });\n options.output?.write(`Saved deny rule: ${pattern}\\n`);\n return { decision: \"deny\", persistAs: \"never\" };\n }\n options.output?.write(\"Please answer y, n, always, or never.\\n\");\n }\n };\n}\n\nfunction requestQuestion(input: unknown): string | undefined {\n if (!input || typeof input !== \"object\") return undefined;\n const question = (input as { question?: unknown }).question;\n return typeof question === \"string\" && question.trim() ? question : undefined;\n}\n"],"mappings":";;;AAAA,IAAM,mBAAmB,oBAAI,IAAY;AAEzC,SAAS,QAAQ,OAA2C,KAAiC;AAC3F,SAAO,QAAQ,IAAI,GAAG,KAAK,MAAM,GAAG;AACtC;AAEA,SAAS,UAAU,KAA4B;AAC7C,SAAO,IAAI,WAAW,QAAQ,IAAI,SAAS,IAAI,MAAM,SAAS,MAAM,CAAC,KAAK;AAC5E;AAEA,SAAS,cAAc,QAAgB,SAAuB;AAC5D,MAAI,iBAAiB,IAAI,MAAM,EAAG;AAClC,mBAAiB,IAAI,MAAM;AAC3B,UAAQ,KAAK,WAAW,MAAM,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AAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA,wBAAwB,YAAY,YAAY,CAAC;AAAA,IACjD;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF,EAAE,KAAK,IAAI;AACb;AAEA,SAAS,iCAAiC,aAA6B;AACrE,SAAO;AAAA,IACL,WAAW,WAAW;AAAA,IACtB;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAA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AAA,UAClB,MAAM;AAAA,UACN;AAAA,UACA,QAAQ,gBAAgB;AAAA,UACxB;AAAA,UACA,GAAI,aAAa,UAAU,EAAE,SAAS,aAAa,QAAQ,IAAI,CAAC;AAAA,QAClE,CAAC;AACD,kBAAU,OAAO;AACjB,oBAAY,KAAK,IAAI,IAAI;AAAA,MAC3B,UAAE;AACA,0BAAkB;AAClB,4BAAoB,MAAM;AAAA,QAAC;AAC3B,gCAAwB;AAAA,MAC1B;AACA,2BAAqB;AACrB,mBAAa;AACb,cAAQ,KAAK,EAAE,MAAM,QAAQ,SAAS,OAAO,CAAC;AAC9C,cAAQ,KAAK,EAAE,MAAM,aAAa,SAAS,QAAQ,CAAC;AACpD,UAAI,OAAQ,mBAAkB,oBAAoB,QAAQ,SAAS,WAAW,WAAW,MAAM;AAAA,IACjG;AAAA,EACF,UAAE;AACA,oBAAgB,iBAAiB;AACjC,YAAQ,IAAI,UAAU,YAAY;AAClC,YAAQ,IAAI,cAAc,gBAAgB;AAC1C,OAAG,MAAM;AAAA,EACX;AACF;AAEA,SAAS,mBAAmB,QAA+B,SAA4B;AACrF,SAAO,MAAM,wBAAc,QAAQ,MAAM,MAAM;AAAA,CAAa;AAC5D,aAAW,QAAQ,YAAY,SAAS,EAAE,GAAG;AAC3C,UAAM,QAAQ,YAAY,IAAI,KAAK,KAAK,WAAW,CAAC;AACpD,UAAM,QAAQ,KAAK,SAAS,SAAS,QAAQ;AAC7C,UAAM,UAAU,OAAO,KAAK,cAAc,WAAW,SAAM,cAAc,KAAK,SAAS,CAAC,KAAK;AAC7F,WAAO,MAAM,IAAI,KAAK,KAAK,KAAK,GAAG,OAAO,KAAK,KAAK,OAAO;AAAA,CAAI;AAAA,EACjE;AACF;AAEA,SAAS,gBAAgB,YAAyC;AAChE,MAAI;AACF,eAAW,YAAY;AAAA,EACzB,QAAQ;AAAA,EAER;AACF;","names":["existsSync","dirname","resolve","existsSync","resolve","dirname","basename","existsSync","readFileSync","join","relative","resolve","issue","resolve","join","existsSync","readFileSync","stdout","relative","stat","pattern","writeFile","mkdir","join","dirname","issue","existsSync","readFileSync","join","file","existsSync","readFileSync","join","join","isRecord","text","existsSync","readFileSync","issue","existsSync","join","taskText","mkdir","readFile","existsSync","join","toolName","join","afterTokens","spawnSync","existsSync","readdirSync","readFileSync","join","relative","text","existsSync","readdirSync","readFileSync","statSync","dirname","join","relative","fileURLToPath","existsSync","readdirSync","statSync","dirname","join","dirname","existsSync","statSync","readdirSync","join","moduleRoot","dirname","fileURLToPath","text","existsSync","resolveDefaultSkillsRoot","join","statSync","readFileSync","readdirSync","relative","pattern","join","statSync","dirname","resolveDefaultSkillsRoot","existsSync","readFileSync","basename","join","join","existsSync","readFileSync","terms","text","aliases","basename","isRecord","toolCall","patterns","pattern","existsSync","readFileSync","homedir","join","isRecord","stringArray","patterns","pattern","homedir","join","existsSync","readFileSync","issue","pattern","existsSync","readdirSync","mkdir","readFile","writeFile","basename","dirname","join","relative","resolve","spawn","sharp","mkdir","readFile","writeFile","dirname","asRecord","asString","asOptionalString","asOptionalNumber","ensureRelativePath","optionalStringArray","sanitizeName","mkdir","dirname","readFile","writeFile","readdir","readFile","existsSync","basename","join","relative","resolve","ignoredNames","asRecord","asString","asOptionalString","asOptionalNumber","readdir","join","relative","readFile","readPackageScripts","basename","text","terms","extension","commands","resolve","existsSync","existsSync","mkdir","readdir","readFile","stat","writeFile","dirname","join","relative","resolve","ignoredNames","normalizePath","asRecord","asOptionalString","asOptionalNumber","asOptionalBoolean","existsSync","mkdirSync","readdirSync","statSync","writeFileSync","readFile","join","stat","asRecord","asString","existsSync","realpathSync","relative","resolve","unique","asRecord","readFile","writeFile","pattern","text","candidate","readFile","updated","writeFile","mkdir","writeFile","dirname","asRecord","asOptionalString","mkdir","dirname","writeFile","ignoredNames","basename","asRecord","asString","asOptionalNumber","asOptionalString","asOptionalBoolean","existsSync","collectFiles","readdirSync","join","relative","resolve","spawn","stdout","timer","text","ensureRelativePath","readFile","mkdir","dirname","writeFile","lineCount","sourceRoutes","sharp","appendFile","mkdir","readFile","stat","writeFile","createHash","dirname","join","issue","appendFile","mkdir","readFile","createHash","homedir","dirname","join","join","homedir","taskSignature","createHash","issue","mkdir","dirname","appendFile","appendFile","mkdir","writeFile","dirname","join","issue","existsSync","mkdirSync","readFileSync","statSync","writeFileSync","basename","join","archivePath","stat","asRecord","stat","existsSync","mkdirSync","readFileSync","statSync","writeFileSync","appendFile","join","existsSync","mkdirSync","renameSync","statSync","unlinkSync","join","existsSync","readFileSync","homedir","join","isRecord","stringArray","sleep","mkdirSync","join","isRecord","isRecord","text","join","existsSync","statSync","unlinkSync","renameSync","sleep","resolve","existsSync","readFileSync","execFile","promisify","execFileAsync","stdout","existsSync","readdirSync","statSync","dirname","join","relative","resolve","text","readdirSync","existsSync","join","statSync","text","pattern","resolve","dirname","relative","join","text","join","join","readPackageJson","text","join","join","join","text","existsSync","readFileSync","readFile","writeFile","mkdir","existsSync","join","patterns","pattern","readdir","readFile","join","readdirSync","readFileSync","statSync","join","isRecord","stringArray","statSync","stat","readdirSync","join","readFileSync","isRecord","recordArray","pattern","text","readFile","join","readdir","issue","envValue","text","text","text","text","text","issue","execFile","readdir","realpath","stat","relative","resolve","promisify","execFileAsync","uniqueSorted","stdout","execFile","existsSync","readdir","stat","resolve","promisify","execFileAsync","text","uniqueSorted","stdout","pattern","commands","hasSuccessfulVerification","issue","resolve","existsSync","mkdirSync","readdirSync","unlinkSync","writeFileSync","cp","mkdir","rm","stat","dirname","isAbsolute","join","relative","resolve","resolve","existsSync","rm","readdirSync","unlinkSync","join","mkdirSync","writeFileSync","issue","toolName","text","isAbsolute","relative","provider","candidateExcerpt","message","uniqueSorted","stat","mkdir","dirname","cp","manifest","finalMessage","metrics","key","cacheImpact","event","toolCalls","result","finalMessageWithFooter","existsSync","mkdirSync","readFileSync","readdirSync","rmSync","statSync","writeFileSync","homedir","basename","dirname","join","relative","resolve","resolve","homedir","join","existsSync","statSync","dirname","mkdirSync","writeFileSync","match","rmSync","readFileSync","latest","basename","readdirSync","relative","flagValue","existsSync","mkdirSync","readFileSync","renameSync","writeFileSync","dirname","join","join","mkdirSync","dirname","writeFileSync","renameSync","existsSync","readFileSync","flagValue","parsePositiveNumber","flagValue","commands","readdir","readFile","join","DEFAULT_LIMIT","flagValue","parseLimit","text","join","readFile","readdir","MODES","STEP_TYPES","minutes","outputColumns","existsSync","readdirSync","basename","extname","join","relative","permissionModes","join","existsSync","readdirSync","extname","extension","basename","extname","relative","permissionModes","existsSync","mkdirSync","readFileSync","renameSync","writeFileSync","homedir","dirname","join","escapeRegex","homedir","join","pattern","mkdirSync","dirname","writeFileSync","renameSync","existsSync","readFileSync","pattern","text"]}
|