@matheuskrumenauer/tanya 0.2.0-beta.0
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/LICENSE +21 -0
- package/README.md +235 -0
- package/dist/cli.js +12088 -0
- package/dist/cli.js.map +1 -0
- package/package.json +66 -0
package/dist/cli.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/cli.ts","../src/config/env.ts","../src/config/envCompat.ts","../src/context/runContext.ts","../src/context/artifacts.ts","../src/events/cosmo.ts","../src/events/jsonl.ts","../src/providers/openAiCompatible.ts","../src/providers/factory.ts","../src/safety/workspace.ts","../src/tools/fsTools.ts","../src/tools/imageTools.ts","../src/tools/videoTools.ts","../src/tools/projectContextTools.ts","../src/obsidian/search.ts","../src/tools/obsidianTools.ts","../src/tools/registry.ts","../src/memory/goldenTasks.ts","../src/memory/repairRuns.ts","../src/memory/taskHistory.ts","../src/obsidian/vaultAppender.ts","../src/agent/compression.ts","../src/agent/forbiddenPatterns.ts","../src/agent/validators/core.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/systemPrompt.ts","../src/context/loader.ts","../src/skills/load.ts","../src/agent/runner.ts","../src/agent/postCheck.ts","../src/agent/planner.ts","../src/agent/reviewer.ts","../src/agent/chat.ts","../src/ui/humanSink.ts","../src/tools/adRenderTools.ts","../src/golden/profiles.ts","../src/golden/run.ts","../src/golden/suite.ts","../src/init/projectInit.ts","../src/context/autoContext.ts"],"sourcesContent":["import { existsSync, readFileSync } from \"node:fs\";\nimport { join, resolve } from \"node:path\";\nimport { Command, Option } from \"commander\";\nimport { loadConfig } from \"./config/env\";\nimport { loadRunContextFile, type TanyaRunContext } from \"./context/runContext\";\nimport { materializeCliArtifacts } from \"./context/artifacts\";\nimport { createCosmoSink } from \"./events/cosmo\";\nimport { createJsonlSink } from \"./events/jsonl\";\nimport { createProvider } from \"./providers/factory\";\nimport type { EventSink } from \"./events/types\";\nimport { runAgent, type RunAgentResult, type TanyaFinalManifest } from \"./agent/runner\";\nimport { detectPostRunBlockers } from \"./agent/postCheck\";\nimport { buildExecutionPlan } from \"./agent/planner\";\nimport { reviewChanges } from \"./agent/reviewer\";\nimport { buildSystemPrompt, loadPromptSkillPacks } from \"./agent/systemPrompt\";\nimport { startInteractiveChat } from \"./agent/chat\";\nimport { createHumanSink } from \"./ui/humanSink\";\nimport { generateVideoAsset, videoPresets } from \"./tools/videoTools\";\nimport { renderFullAd } from \"./tools/adRenderTools\";\nimport { runGoldenSuiteCommand } from \"./golden/suite\";\nimport { initTanyaProject } from \"./init/projectInit\";\nimport { buildExportMap } from \"./context/loader\";\nimport { OpenAiCompatibleProvider } from \"./providers/openAiCompatible\";\nimport { buildAutoRunContext } from \"./context/autoContext\";\nimport { buildHistoryBlock, readRecentTaskHistory } from \"./memory/taskHistory\";\nimport { SKILL_PACK_TOKEN_BUDGET, type LoadedSkillPack } from \"./skills\";\n\ninterface ParsedArgs {\n command: string;\n positional: string[];\n flags: Map<string, string | string[] | boolean>;\n}\n\ntype CliOptionKind = \"array\" | \"boolean\" | \"negated\" | \"string\";\n\ntype CliOptionDefinition = {\n flags: string;\n key: string;\n kind: CliOptionKind;\n property: string;\n aliases?: string[];\n};\n\nconst knownCommands = new Set([\"chat\", \"ask\", \"run\", \"review\", \"init\", \"video\", \"golden\", \"benchmark\", \"providers\", \"doctor\", \"debug-prompt\", \"runs\", \"patterns\", \"help\"]);\n\nconst cliOptionDefinitions: CliOptionDefinition[] = [\n { flags: \"--artifact <path>\", key: \"artifact\", kind: \"array\", property: \"artifact\" },\n { flags: \"--artifact-output-root <path>\", key: \"artifact-output-root\", kind: \"string\", property: \"artifactOutputRoot\" },\n { flags: \"--artifacts-root <path>\", key: \"artifacts-root\", kind: \"string\", property: \"artifactsRoot\" },\n { flags: \"--badge <text>\", key: \"badge\", kind: \"string\", property: \"badge\" },\n { flags: \"--basename <name>\", key: \"basename\", kind: \"string\", property: \"basename\" },\n { flags: \"--context-file <path>\", key: \"context-file\", kind: \"string\", property: \"contextFile\" },\n { flags: \"--context-path <path>\", key: \"context-path\", kind: \"array\", property: \"contextPath\" },\n { flags: \"--cosmo\", key: \"cosmo\", kind: \"boolean\", property: \"cosmo\" },\n { flags: \"--cwd <path>\", key: \"cwd\", kind: \"string\", property: \"cwd\" },\n { flags: \"--duration <seconds>\", key: \"duration\", kind: \"string\", property: \"duration\" },\n { flags: \"--ffmpeg-path <path>\", key: \"ffmpeg-path\", kind: \"string\", property: \"ffmpegPath\", aliases: [\"ffmpegPath\"] },\n { flags: \"--format <format>\", key: \"format\", kind: \"array\", property: \"format\" },\n { flags: \"--fps <number>\", key: \"fps\", kind: \"string\", property: \"fps\" },\n { flags: \"--height <number>\", key: \"height\", kind: \"string\", property: \"height\" },\n { flags: \"--input <path>\", key: \"input\", kind: \"string\", property: \"input\" },\n { flags: \"--json\", key: \"json\", kind: \"boolean\", property: \"json\" },\n { flags: \"--keep-context\", key: \"keep-context\", kind: \"boolean\", property: \"keepContext\" },\n { flags: \"--line <text>\", key: \"line\", kind: \"array\", property: \"line\" },\n { flags: \"--mode <mode>\", key: \"mode\", kind: \"string\", property: \"mode\" },\n { flags: \"--no-auto-brief\", key: \"no-auto-brief\", kind: \"negated\", property: \"autoBrief\" },\n { flags: \"--no-obsidian-context\", key: \"no-obsidian-context\", kind: \"negated\", property: \"obsidianContext\" },\n { flags: \"--no-post-check\", key: \"no-post-check\", kind: \"negated\", property: \"postCheck\" },\n { flags: \"--no-retry-stash\", key: \"no-retry-stash\", kind: \"negated\", property: \"retryStash\" },\n { flags: \"--output-dir <path>\", key: \"output-dir\", kind: \"string\", property: \"outputDir\", aliases: [\"outputDir\"] },\n { flags: \"--plan\", key: \"plan\", kind: \"boolean\", property: \"plan\" },\n { flags: \"--profile <id>\", key: \"profile\", kind: \"string\", property: \"profile\" },\n { flags: \"--prompt-file <path>\", key: \"prompt-file\", kind: \"string\", property: \"promptFile\" },\n { flags: \"--repair-attempts <count>\", key: \"repair-attempts\", kind: \"string\", property: \"repairAttempts\" },\n { flags: \"--require-verification <command>\", key: \"require-verification\", kind: \"array\", property: \"requireVerification\" },\n { flags: \"--retries <count>\", key: \"retries\", kind: \"string\", property: \"retries\" },\n { flags: \"--review\", key: \"review\", kind: \"boolean\", property: \"review\" },\n { flags: \"--section <name>\", key: \"section\", kind: \"array\", property: \"section\" },\n { flags: \"--secondary-tab <name>\", key: \"secondary-tab\", kind: \"string\", property: \"secondaryTab\", aliases: [\"secondaryTab\"] },\n { flags: \"--spec-generation\", key: \"spec-generation\", kind: \"boolean\", property: \"specGeneration\" },\n { flags: \"--tab <name>\", key: \"tab\", kind: \"string\", property: \"tab\" },\n { flags: \"--title <text>\", key: \"title\", kind: \"string\", property: \"title\" },\n { flags: \"--verify <command>\", key: \"verify\", kind: \"array\", property: \"verify\" },\n { flags: \"--width <number>\", key: \"width\", kind: \"string\", property: \"width\" },\n { flags: \"--all\", key: \"all\", kind: \"boolean\", property: \"all\" },\n];\n\nfunction collectOptionValue(value: string, previous: string[] | undefined): string[] {\n return [...(previous ?? []), value];\n}\n\nfunction addCliOptions(command: Command): Command {\n for (const definition of cliOptionDefinitions) {\n const option = new Option(definition.flags);\n if (definition.kind === \"array\") {\n option.argParser(collectOptionValue).default([]);\n }\n command.addOption(option);\n }\n return command;\n}\n\nfunction normalizeCommanderArgv(argv: string[]): string[] {\n if (argv.length === 0) return [\"chat\"];\n if (argv[0] === \"--help\" || argv[0] === \"-h\") return argv;\n if (argv[0] && knownCommands.has(argv[0])) return normalizeOptionAliases(argv);\n return [\"chat\", ...normalizeOptionAliases(argv)];\n}\n\nfunction normalizeOptionAliases(argv: string[]): string[] {\n return argv.map((arg) => {\n if (arg === \"--ffmpegPath\") return \"--ffmpeg-path\";\n if (arg.startsWith(\"--ffmpegPath=\")) return `--ffmpeg-path=${arg.slice(\"--ffmpegPath=\".length)}`;\n if (arg === \"--outputDir\") return \"--output-dir\";\n if (arg.startsWith(\"--outputDir=\")) return `--output-dir=${arg.slice(\"--outputDir=\".length)}`;\n if (arg === \"--secondaryTab\") return \"--secondary-tab\";\n if (arg.startsWith(\"--secondaryTab=\")) return `--secondary-tab=${arg.slice(\"--secondaryTab=\".length)}`;\n return arg;\n });\n}\n\nfunction optionSource(command: Command, property: string): string | undefined {\n return command.getOptionValueSource(property);\n}\n\nfunction parsedFromCommand(commandName: string, positional: string[], command: Command): ParsedArgs {\n const opts = command.opts<Record<string, unknown>>();\n const flags = new Map<string, string | string[] | boolean>();\n for (const definition of cliOptionDefinitions) {\n const source = optionSource(command, definition.property);\n const value = opts[definition.property];\n if (definition.kind === \"array\") {\n if (Array.isArray(value) && value.length > 0) {\n for (const item of value) appendFlagValue(flags, definition.key, String(item));\n for (const alias of definition.aliases ?? []) {\n for (const item of value) appendFlagValue(flags, alias, String(item));\n }\n }\n continue;\n }\n if (definition.kind === \"negated\") {\n if (source === \"cli\" && value === false) flags.set(definition.key, true);\n continue;\n }\n if (definition.kind === \"boolean\") {\n if (source === \"cli\" && value === true) flags.set(definition.key, true);\n continue;\n }\n if (source === \"cli\" && typeof value === \"string\") {\n flags.set(definition.key, value);\n for (const alias of definition.aliases ?? []) flags.set(alias, value);\n }\n }\n return { command: commandName, positional, flags };\n}\n\nfunction configureCliCommand(command: Command, commandName: string, onParsed: (args: ParsedArgs) => void): Command {\n addCliOptions(command)\n .argument(\"[args...]\", \"command arguments\")\n .allowExcessArguments(true)\n .action((positional: string[]) => {\n onParsed(parsedFromCommand(commandName, positional, command));\n });\n return command;\n}\n\nfunction buildCliProgram(onParsed: (args: ParsedArgs) => void): Command {\n const program = new Command();\n program\n .name(\"tanya\")\n .description(\"Tanya CLI\")\n .helpCommand(false)\n .showHelpAfterError()\n .allowExcessArguments(true);\n\n configureCliCommand(program.command(\"chat\").description(\"Start live chat\"), \"chat\", onParsed);\n configureCliCommand(program.command(\"ask\").description(\"Run one prompt without tools\"), \"ask\", onParsed);\n configureCliCommand(program.command(\"run\").description(\"Run an agent task with tools\"), \"run\", onParsed);\n configureCliCommand(program.command(\"review\").description(\"Review uncommitted changes against a task\"), \"review\", onParsed);\n configureCliCommand(program.command(\"init\").description(\"Create .tania/INSTRUCTIONS.md for this project\"), \"init\", onParsed);\n configureCliCommand(program.command(\"video\").description(\"Generate Tanya video assets\"), \"video\", onParsed);\n configureCliCommand(program.command(\"golden\").description(\"Manage local golden task memory\"), \"golden\", onParsed);\n configureCliCommand(program.command(\"benchmark\").description(\"Run executable regression benchmarks\"), \"benchmark\", onParsed);\n configureCliCommand(program.command(\"providers\").description(\"Provider utilities\"), \"providers\", onParsed);\n configureCliCommand(program.command(\"doctor\").description(\"Check local setup\"), \"doctor\", onParsed);\n configureCliCommand(program.command(\"debug-prompt\").description(\"Print system prompt without running agent\"), \"debug-prompt\", onParsed);\n configureCliCommand(program.command(\"runs\").description(\"Show recent run logs\"), \"runs\", onParsed);\n configureCliCommand(program.command(\"patterns\").description(\"Show forbidden-pattern fire metrics\"), \"patterns\", onParsed);\n return program;\n}\n\nfunction parseArgs(argv: string[]): ParsedArgs {\n if (argv[0] === \"help\") return { command: \"help\", positional: argv.slice(1), flags: new Map() };\n let parsed: ParsedArgs | undefined;\n const program = buildCliProgram((args) => {\n parsed = args;\n });\n program.parse(normalizeCommanderArgv(argv), { from: \"user\" });\n return parsed ?? { command: \"chat\", positional: [], flags: new Map() };\n}\n\nfunction appendFlagValue(flags: Map<string, string | string[] | boolean>, key: string, value: string) {\n const existing = flags.get(key);\n if (typeof existing === \"string\") {\n flags.set(key, [existing, value]);\n } else if (Array.isArray(existing)) {\n existing.push(value);\n } else {\n flags.set(key, value);\n }\n}\n\nfunction flagString(args: ParsedArgs, name: string): string | undefined {\n const value = args.flags.get(name);\n return typeof value === \"string\" ? value : undefined;\n}\n\nfunction flagStrings(args: ParsedArgs, name: string): string[] {\n const value = args.flags.get(name);\n if (typeof value === \"string\") return [value];\n if (Array.isArray(value)) return value;\n return [];\n}\n\nfunction hasFlag(args: ParsedArgs, name: string): boolean {\n const value = args.flags.get(name);\n return value === true || typeof value === \"string\" || Array.isArray(value);\n}\n\nfunction flagNumber(args: ParsedArgs, name: string): number | undefined {\n const value = flagString(args, name);\n if (!value) return undefined;\n const parsed = Number(value);\n return Number.isFinite(parsed) ? parsed : undefined;\n}\n\nfunction applyCliProfileFlag(args: ParsedArgs): void {\n if (args.command !== \"run\" && args.command !== \"chat\") return;\n const profile = flagString(args, \"profile\");\n if (!profile) return;\n process.env.TANYA_PROFILE = profile;\n}\n\nfunction buildRetryContext(manifest: TanyaFinalManifest, attempt: number, extraBlockers: string[] = []): string {\n const lines = [\n `RETRY CONTEXT (attempt ${attempt}): the previous run did not complete cleanly.`,\n \"Do not repeat the same approach that failed.\",\n ];\n const allBlockers = [...manifest.blockers, ...extraBlockers];\n if (allBlockers.length > 0) {\n lines.push(\"\", \"Previous run blockers:\");\n for (const blocker of allBlockers) lines.push(`- ${blocker}`);\n }\n if (manifest.changedFiles.length > 0) {\n lines.push(\"\", \"Files already changed in previous attempt (verify their current state before editing):\");\n for (const file of manifest.changedFiles) lines.push(`- ${file}`);\n }\n if (manifest.verification.length > 0) {\n lines.push(\"\", \"Verification results from previous attempt:\");\n for (const verification of manifest.verification) lines.push(`- ${verification}`);\n }\n lines.push(\"\", \"Fix the blockers above and complete the task.\");\n return lines.join(\"\\n\");\n}\n\nfunction estimateRunCost(\n model: string,\n promptTokens: number,\n completionTokens: number,\n): string {\n const isReasoner = model.includes(\"reasoner\");\n const inputRate = isReasoner ? 0.55 : 0.27;\n const outputRate = isReasoner ? 2.19 : 1.10;\n const cost = (promptTokens / 1_000_000) * inputRate + (completionTokens / 1_000_000) * outputRate;\n if (cost < 0.001) return \"<$0.001\";\n return `~$${cost.toFixed(3)}`;\n}\n\nfunction usage(): string {\n return `Tanya CLI\n\nUsage:\n tanya Start live chat\n tanya chat [--profile reasoner] Start live chat\n tanya ask \"prompt\" Run one prompt without tools\n tanya init [--cwd path] Create .tania/INSTRUCTIONS.md for this project\n tanya run [--cwd path] [--profile reasoner] \"task\" Run an agent task with tools\n tanya run \"task\" Auto-detects ./artifacts if present\n tanya run --context-file /tmp/context.json --prompt-file /tmp/prompt.txt\n tanya run --artifacts-root <path> \"task\" Use a custom artifacts directory\n tanya run --artifacts-root /path/to/artifacts --artifact ios/FastlaneSetup.md \"task\"\n tanya run --context-path /path/to/brand/safety.md --artifact-output-root /path/to/artifacts \"task\"\n tanya run --no-auto-brief \"task\" Skip automatic local task briefing\n tanya run --no-obsidian-context \"task\" Skip automatic Obsidian context retrieval\n tanya run --no-post-check \"task\" Skip independent TypeScript/test verification\n tanya run --repair-attempts 2 --context-file /tmp/context.json --prompt-file /tmp/prompt.txt\n tanya run --keep-context --artifacts-root /path/to/artifacts --artifact ios/FastlaneSetup.md \"task\"\n tanya run --verify \"npm run typecheck\" --verify \"npm run build\" \"task\"\n tanya run --retries 2 \"task\" Retry up to 2 times if the run has blockers\n tanya run --plan \"task\" Pre-plan with deepseek-reasoner before executing\n tanya run --plan --retries 2 \"task\"\n tanya run --review \"task\" Run task then auto-review the diff\n tanya run --plan --retries 2 --review \"task\" Full autonomous mode\n tanya run --json --prompt-file /tmp/prompt.txt\n tanya run --cosmo --cwd /tmp/project --prompt-file /tmp/prompt.txt\n tanya debug-prompt \"task\" Print system prompt without running agent\n tanya debug-prompt --cwd <path> \"task\" Print system prompt for a specific project\n tanya debug-prompt --section artifacts \"task\" Print only the artifact section\n tanya debug-prompt --section exports \"task\" Print only the export map section\n tanya runs [--cwd <path>] Show last 10 run logs with cost and status\n tanya review \"task description\" Review uncommitted changes against the task\n tanya review --cwd <path> \"task\" Review changes in a specific project\n tanya video presets\n tanya video one-terminal-simctl --output-dir assets/video\n tanya video render-ad --input spec.json --output-dir assets/video-ads --format mp4 --format poster\n tanya golden summary Summarize local golden task memory\n tanya golden profiles List built-in golden task profiles\n tanya golden run Run executable golden task fixtures\n tanya golden validate Fail if latest golden task signatures are failing\n tanya benchmark profiles List benchmark profiles\n tanya benchmark run --all Run executable regression benchmarks\n tanya benchmark validate Validate recent benchmark signatures\n tanya providers test Test provider configuration\n tanya doctor Check local setup\n tanya patterns Show forbidden-pattern fire metrics for this workspace\n\nInstall locally during development:\n npm install\n npm run link:local\n`;\n}\n\nfunction readPrompt(args: ParsedArgs): string {\n const promptFile = flagString(args, \"prompt-file\");\n if (promptFile) return readFileSync(resolve(promptFile), \"utf8\");\n return args.positional.join(\" \").trim();\n}\n\nasync function buildRunContextForCli(\n args: ParsedArgs,\n cwd: string,\n prompt: string,\n obsidianVault?: string,\n): Promise<TanyaRunContext | undefined> {\n const contextFile = flagString(args, \"context-file\");\n const baseRunContext = contextFile ? loadRunContextFile(contextFile) : undefined;\n const explicitArtifactsRoot = flagString(args, \"artifacts-root\");\n const localArtifactsRoot = resolve(cwd, \"artifacts\");\n const artifactsRoot = explicitArtifactsRoot ?? (existsSync(localArtifactsRoot) ? localArtifactsRoot : undefined);\n let runContext = materializeCliArtifacts({\n cwd,\n root: artifactsRoot,\n artifacts: flagStrings(args, \"artifact\"),\n contextPaths: flagStrings(args, \"context-path\"),\n artifactOutputRoot: flagString(args, \"artifact-output-root\"),\n keepContext: hasFlag(args, \"keep-context\"),\n baseContext: baseRunContext,\n });\n if (!explicitArtifactsRoot && artifactsRoot) {\n const autoArtifactInstructions = [\n \"This workspace contains an artifacts/ directory with reusable patterns.\",\n \"The artifact index and rules have been injected into your system prompt.\",\n \"Before implementing anything, check the artifact index and read relevant artifacts.\",\n ];\n runContext = {\n ...(runContext ?? {}),\n instructions: [...(runContext?.instructions ?? []), ...autoArtifactInstructions],\n };\n }\n const extraVerify = flagStrings(args, \"verify\");\n if (extraVerify.length > 0) {\n const existing = runContext?.verification?.commands ?? [];\n const merged = [...new Set([...existing, ...extraVerify])];\n runContext = { ...(runContext ?? {}), task: { ...(runContext?.task ?? {}), kind: \"coding\" }, verification: { commands: merged } };\n }\n const requireVerify = flagStrings(args, \"require-verification\");\n if (requireVerify.length > 0) {\n // --require-verification REPLACES the auto-brief verification list with exactly\n // these commands. Use when the caller knows the canonical verification set\n // and the auto-generated recommendations would over-require.\n runContext = {\n ...(runContext ?? {}),\n task: { ...(runContext?.task ?? {}), kind: \"coding\" },\n verification: { commands: [...new Set(requireVerify)] },\n metadata: { ...(runContext?.metadata ?? {}), verificationOverridden: true },\n };\n }\n return buildAutoRunContext({\n cwd,\n prompt,\n ...(runContext ? { runContext } : {}),\n obsidianVault,\n enableBrief: !hasFlag(args, \"no-auto-brief\"),\n enableObsidian: !hasFlag(args, \"no-obsidian-context\"),\n keepContext: hasFlag(args, \"keep-context\"),\n });\n}\n\nfunction selectPromptSections(systemPrompt: string, sections: string[]): string {\n if (sections.length === 0) return systemPrompt;\n const sectionMap: Record<string, { starts: string[]; ends: string[] }> = {\n artifacts: {\n starts: [\"## Artifact Index\", \"## Project Artifacts\"],\n ends: [\"## Workspace Context\", \"## Project Instructions\", \"## Caller Context\"],\n },\n exports: {\n starts: [\"## Workspace export map\"],\n ends: [\"## Artifact Index\", \"## Project Artifacts\", \"## Workspace Context\", \"## Project Instructions\", \"## Caller Context\"],\n },\n context: {\n starts: [\"## Workspace Context\"],\n ends: [\"## Project Instructions\", \"## Caller Context\"],\n },\n instructions: {\n starts: [\"## Project Instructions\"],\n ends: [\"## Caller Context\"],\n },\n };\n\n const findHeading = (heading: string, from = 0): number => {\n if (systemPrompt.startsWith(`${heading}\\n`)) return 0;\n return systemPrompt.indexOf(`\\n${heading}\\n`, from);\n };\n\n const extractSection = (starts: string[], ends: string[]): string | null => {\n const startCandidates = starts\n .map((heading) => findHeading(heading))\n .filter((index) => index >= 0);\n if (startCandidates.length === 0) return null;\n let start = Math.min(...startCandidates);\n if (systemPrompt[start] === \"\\n\") start += 1;\n\n const endCandidates = ends\n .map((heading) => findHeading(heading, start + 1))\n .filter((index) => index > start);\n const end = endCandidates.length > 0 ? Math.min(...endCandidates) : systemPrompt.length;\n return systemPrompt.slice(start, end).trim();\n };\n\n const matched: string[] = [];\n for (const section of sections) {\n const definition = sectionMap[section];\n if (!definition) {\n process.stderr.write(`[debug-prompt] Unknown section \"${section}\". Available: ${Object.keys(sectionMap).join(\", \")}\\n`);\n continue;\n }\n const match = extractSection(definition.starts, definition.ends);\n if (match) {\n matched.push(match);\n } else {\n process.stderr.write(`[debug-prompt] Section \"${section}\" not found in prompt.\\n`);\n }\n }\n return matched.join(\"\\n\\n---\\n\\n\");\n}\n\nfunction 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 | reason | tokens |\",\n \"|------|--------|--------|\",\n ...packs.map((pack) => `| ${pack.slug} | ${pack.reason} | ${pack.tokens} |`),\n `Total pack tokens: ${totalTokens} / ${SKILL_PACK_TOKEN_BUDGET}`,\n ];\n return lines.join(\"\\n\");\n}\n\nasync function askOnce(provider: ReturnType<typeof createProvider>, prompt: string): Promise<string> {\n let text = \"\";\n for await (const delta of provider.streamChat({ messages: [{ role: \"user\", content: prompt }], tools: [] })) {\n if (delta.content) {\n process.stdout.write(delta.content);\n text += delta.content;\n }\n }\n process.stdout.write(\"\\n\");\n return text;\n}\n\nasync function testProvider(): Promise<void> {\n const config = loadConfig();\n const provider = createProvider(config);\n const startedAt = Date.now();\n let text = \"\";\n for await (const delta of provider.streamChat({\n messages: [{ role: \"user\", content: \"Reply with exactly: pong\" }],\n tools: [],\n maxTokens: 12,\n temperature: 0,\n })) {\n if (delta.content) text += delta.content;\n }\n console.log(`ok ${provider.id}:${provider.model} ${Date.now() - startedAt}ms ${text.trim()}`);\n}\n\nasync function doctor(args?: ParsedArgs): Promise<void> {\n const cwd = resolve(args ? flagString(args, \"cwd\") ?? process.cwd() : process.cwd());\n const config = loadConfig(cwd);\n const checks: Array<{ name: string; status: \"ok\" | \"warn\" | \"fail\"; detail: string }> = [];\n const ok = (name: string, detail: string) => checks.push({ name, status: \"ok\", detail });\n const warn = (name: string, detail: string) => checks.push({ name, status: \"warn\", detail });\n const fail = (name: string, detail: string) => checks.push({ name, status: \"fail\", detail });\n\n // Node + runtime\n const major = Number(process.version.replace(/^v/, \"\").split(\".\")[0] ?? \"0\");\n if (major >= 20) ok(\"node\", `${process.version}`);\n else fail(\"node\", `${process.version} — tanya requires Node 20+`);\n\n // Provider config\n if (config.apiKey) ok(\"provider.apiKey\", \"present\");\n else fail(\"provider.apiKey\", \"missing — set TANYA_API_KEY or DEEPSEEK_API_KEY\");\n if (config.baseUrl) ok(\"provider.baseUrl\", config.baseUrl);\n else fail(\"provider.baseUrl\", \"missing — set TANYA_BASE_URL\");\n ok(\"provider.model\", `${config.provider}:${config.model} (profile=${config.profile})`);\n ok(\"provider.timeoutMs\", `${config.timeoutMs}ms`);\n\n // Workspace\n const cwdHasGit = existsSync(join(cwd, \".git\"));\n if (cwdHasGit) ok(\"workspace.git\", `${cwd}`);\n else warn(\"workspace.git\", `${cwd} is not a git repository — stash/retry recovery will be disabled`);\n const cwdHasArtifacts = existsSync(join(cwd, \"artifacts\"));\n if (cwdHasArtifacts) ok(\"workspace.artifacts\", `${join(cwd, \"artifacts\")} (auto-detected)`);\n else warn(\"workspace.artifacts\", \"no ./artifacts dir — pass --artifacts-root or run from a project that has one\");\n\n // Project-level forbidden patterns\n const fpPath = join(cwd, \".tania\", \"forbidden-patterns.json\");\n if (existsSync(fpPath)) {\n try {\n const raw = readFileSync(fpPath, \"utf8\");\n const parsed = JSON.parse(raw);\n const count = Array.isArray(parsed?.patterns) ? parsed.patterns.length : 0;\n ok(\"workspace.forbiddenPatterns\", `${count} project pattern(s) loaded from ${fpPath}`);\n } catch (err) {\n fail(\"workspace.forbiddenPatterns\", `${fpPath} exists but is invalid JSON: ${err instanceof Error ? err.message : String(err)}`);\n }\n } else {\n ok(\"workspace.forbiddenPatterns\", \"no project overrides (using defaults)\");\n }\n\n // Forbidden-pattern fire metrics (from accumulated runs)\n const fpMetricsPath = join(cwd, \".tania\", \"memory\", \"forbidden-patterns-metrics.json\");\n if (existsSync(fpMetricsPath)) {\n try {\n const raw = readFileSync(fpMetricsPath, \"utf8\");\n const parsed = JSON.parse(raw) as { totals?: Record<string, number>; totalScans?: number };\n const totals = parsed.totals ?? {};\n const top = Object.entries(totals).sort((a, b) => b[1] - a[1]).slice(0, 5);\n if (top.length > 0) {\n const summary = top.map(([id, n]) => `${id}=${n}`).join(\", \");\n ok(\"workspace.forbiddenPatterns.metrics\", `top fires across ${parsed.totalScans ?? 0} scans: ${summary}`);\n } else {\n ok(\"workspace.forbiddenPatterns.metrics\", `no patterns ever fired (${parsed.totalScans ?? 0} scans)`);\n }\n } catch {\n warn(\"workspace.forbiddenPatterns.metrics\", `${fpMetricsPath} exists but is unreadable`);\n }\n } else {\n ok(\"workspace.forbiddenPatterns.metrics\", \"no metrics yet (no scans recorded)\");\n }\n\n // Obsidian vault\n if (config.obsidianVault) {\n if (existsSync(config.obsidianVault)) ok(\"obsidian.vault\", config.obsidianVault);\n else warn(\"obsidian.vault\", `${config.obsidianVault} configured but path does not exist`);\n } else {\n ok(\"obsidian.vault\", \"not configured (optional)\");\n }\n\n // ffmpeg presence (informational; only required for tanya video)\n try {\n const { execFileSync } = await import(\"node:child_process\");\n execFileSync(\"ffmpeg\", [\"-version\"], { stdio: \"ignore\" });\n ok(\"ffmpeg\", \"available (tanya video commands enabled)\");\n } catch {\n warn(\"ffmpeg\", \"not found on PATH — tanya video commands will fail until installed\");\n }\n\n // Render\n console.log(`Tanya doctor — ${cwd}`);\n console.log(\"\");\n for (const check of checks) {\n const tag = check.status === \"ok\" ? \"[ok] \" : check.status === \"warn\" ? \"[warn]\" : \"[FAIL]\";\n console.log(`${tag} ${check.name.padEnd(28)} ${check.detail}`);\n }\n const failed = checks.filter((c) => c.status === \"fail\").length;\n const warned = checks.filter((c) => c.status === \"warn\").length;\n console.log(\"\");\n console.log(`Summary: ${checks.length - failed - warned} ok, ${warned} warn, ${failed} fail`);\n if (failed > 0) process.exitCode = 1;\n}\n\nasync function runVideoCommand(args: ParsedArgs): Promise<void> {\n const preset = args.positional[0] ?? \"one-terminal-simctl\";\n if (preset === \"presets\" || preset === \"list\") {\n console.log(\"Video presets:\");\n for (const item of videoPresets) {\n const aliases = item.aliases.length ? ` aliases: ${item.aliases.join(\", \")}` : \"\";\n console.log(`- ${item.name} (${item.width}x${item.height}, ${item.fps}fps, ${item.duration}s)${aliases}`);\n console.log(` ${item.description}`);\n }\n return;\n }\n if (preset === \"render-ad\") {\n const cwd = resolve(flagString(args, \"cwd\") ?? process.cwd());\n const input = flagString(args, \"input\");\n if (!input) {\n console.log(\"Usage: tanya video render-ad --input spec.json [--output-dir dir] [--basename name] [--format mp4] [--format poster]\");\n return;\n }\n const formats = flagStrings(args, \"format\");\n const renderOptions: Parameters<typeof renderFullAd>[0] = {\n input,\n formats: formats.length ? formats as Array<\"mp4\" | \"poster\"> : [\"mp4\", \"poster\"],\n };\n const outputDir = flagString(args, \"output-dir\") ?? flagString(args, \"outputDir\");\n const basename = flagString(args, \"basename\");\n const ffmpegPath = flagString(args, \"ffmpeg-path\") ?? flagString(args, \"ffmpegPath\");\n if (outputDir) renderOptions.outputDir = outputDir;\n if (basename) renderOptions.basename = basename;\n if (ffmpegPath) renderOptions.ffmpegPath = ffmpegPath;\n const result = await renderFullAd(renderOptions, cwd);\n console.log(JSON.stringify({\n mp4Path: result.mp4Path,\n posterPath: result.posterPath,\n durationMs: result.durationMs,\n frameCount: result.frameCount,\n width: result.width,\n height: result.height,\n warnings: result.warnings,\n }, null, 2));\n return;\n }\n if (preset !== \"one-terminal-simctl\" && preset !== \"terminal-simctl\") {\n console.log(\"Usage: tanya video one-terminal-simctl [--output-dir dir] [--basename name] [--width 980] [--height 1012] [--duration 3] [--fps 30] [--format webm] [--format mov] [--format poster] [--line text]\\n tanya video render-ad --input spec.json [--output-dir dir] [--format mp4] [--format poster]\");\n return;\n }\n const cwd = resolve(flagString(args, \"cwd\") ?? process.cwd());\n const formats = flagStrings(args, \"format\");\n const options: Parameters<typeof generateVideoAsset>[0] = { preset };\n const outputDir = flagString(args, \"output-dir\") ?? flagString(args, \"outputDir\");\n const basename = flagString(args, \"basename\");\n const width = flagNumber(args, \"width\");\n const height = flagNumber(args, \"height\");\n const fps = flagNumber(args, \"fps\");\n const duration = flagNumber(args, \"duration\");\n const title = flagString(args, \"title\");\n const tab = flagString(args, \"tab\");\n const secondaryTab = flagString(args, \"secondary-tab\") ?? flagString(args, \"secondaryTab\");\n const badge = flagString(args, \"badge\");\n const lines = flagStrings(args, \"line\");\n if (outputDir) options.outputDir = outputDir;\n if (basename) options.basename = basename;\n if (width !== undefined) options.width = width;\n if (height !== undefined) options.height = height;\n if (fps !== undefined) options.fps = fps;\n if (duration !== undefined) options.duration = duration;\n if (formats.length > 0) options.formats = formats as Array<\"webm\" | \"mov\" | \"poster\">;\n if (title) options.title = title;\n if (tab) options.tab = tab;\n if (secondaryTab) options.secondaryTab = secondaryTab;\n if (badge) options.badge = badge;\n if (lines.length > 0) options.lines = lines;\n const result = await generateVideoAsset(options, cwd);\n console.log(`Generated ${result.files.length} video asset file${result.files.length === 1 ? \"\" : \"s\"}:`);\n for (const file of result.files) console.log(`- ${file}`);\n}\n\nasync function main(): Promise<void> {\n const args = parseArgs(process.argv.slice(2));\n if (args.command === \"help\" || args.command === \"--help\" || args.command === \"-h\") {\n console.log(usage());\n return;\n }\n\n if (args.command === \"doctor\") {\n await doctor(args);\n return;\n }\n\n if (args.command === \"patterns\") {\n const cwd = resolve(flagString(args, \"cwd\") ?? process.cwd());\n const metricsPath = join(cwd, \".tania\", \"memory\", \"forbidden-patterns-metrics.json\");\n if (!existsSync(metricsPath)) {\n console.log(`No metrics file at ${metricsPath}. Run a tanya task in this workspace first.`);\n return;\n }\n try {\n const parsed = JSON.parse(readFileSync(metricsPath, \"utf8\")) as {\n totals?: Record<string, number>;\n lastFiredAt?: Record<string, string>;\n totalScans?: number;\n };\n const totals = parsed.totals ?? {};\n const lastFiredAt = parsed.lastFiredAt ?? {};\n const entries = Object.entries(totals).sort((a, b) => b[1] - a[1]);\n console.log(`Forbidden-pattern fire metrics — ${cwd}`);\n console.log(`Total scans: ${parsed.totalScans ?? 0}`);\n console.log(\"\");\n if (entries.length === 0) {\n console.log(\"No patterns have fired in this workspace yet.\");\n return;\n }\n console.log(`${\"PATTERN\".padEnd(48)} ${\"FIRES\".padStart(7)} LAST FIRED`);\n for (const [id, count] of entries) {\n const last = lastFiredAt[id]?.slice(0, 16) ?? \"—\";\n console.log(`${id.padEnd(48)} ${String(count).padStart(7)} ${last}`);\n }\n } catch (err) {\n console.error(`Could not read metrics: ${err instanceof Error ? err.message : String(err)}`);\n process.exitCode = 1;\n }\n return;\n }\n\n if (args.command === \"providers\") {\n if (args.positional[0] !== \"test\") {\n console.log(\"Usage: tanya providers test\");\n return;\n }\n await testProvider();\n return;\n }\n\n if (args.command === \"init\") {\n const cwd = resolve(flagString(args, \"cwd\") ?? process.cwd());\n const path = await initTanyaProject(cwd);\n console.log(path);\n return;\n }\n\n if (args.command === \"video\") {\n await runVideoCommand(args);\n return;\n }\n\n if (args.command === \"golden\" || args.command === \"benchmark\") {\n const cwd = resolve(flagString(args, \"cwd\") ?? process.cwd());\n const action = args.positional[0] ?? \"summary\";\n if (![\"summary\", \"list\", \"profiles\", \"run\", \"validate\"].includes(action)) {\n console.log(`Usage: tanya ${args.command} summary|list|profiles|run|validate [--cwd path] [--json] [--profile id] [--all]`);\n return;\n }\n const profile = flagString(args, \"profile\");\n const exitCode = await runGoldenSuiteCommand(cwd, action, hasFlag(args, \"json\"), {\n ...(profile ? { profile } : {}),\n all: hasFlag(args, \"all\"),\n });\n process.exitCode = exitCode;\n return;\n }\n\n if (args.command === \"runs\") {\n const cwd = resolve(flagString(args, \"cwd\") ?? process.cwd());\n const runsDir = join(cwd, \".tania\", \"runs\");\n\n if (!existsSync(runsDir)) {\n process.stdout.write(\"No run logs found. Run tanya run first.\\n\");\n return;\n }\n\n const { readdirSync, readFileSync } = await import(\"node:fs\");\n const files = readdirSync(runsDir)\n .filter((file) => file.endsWith(\".json\"))\n .sort()\n .reverse()\n .slice(0, 10);\n\n if (files.length === 0) {\n process.stdout.write(\"No run logs found.\\n\");\n return;\n }\n\n for (const file of files) {\n try {\n const log = JSON.parse(readFileSync(join(runsDir, file), \"utf8\")) as {\n ts: string;\n prompt: string;\n model: string;\n durationMs: number;\n promptTokens: number;\n completionTokens: number;\n changedFiles: string[];\n blockers: string[];\n };\n const cost = estimateRunCost(log.model, log.promptTokens ?? 0, log.completionTokens ?? 0);\n const status = log.blockers?.length > 0 ? \"BLOCKED\" : \"OK\";\n const duration = `${Math.round((log.durationMs ?? 0) / 1000)}s`;\n const fileCount = log.changedFiles?.length ?? 0;\n process.stdout.write(\n `${log.ts?.slice(0, 16)} ${status.padEnd(7)} ${duration.padStart(5)} ${cost.padStart(8)} ${fileCount} file(s) ${log.prompt?.slice(0, 60)}\\n`,\n );\n } catch {\n // Corrupt logs should not break listing.\n }\n }\n return;\n }\n\n applyCliProfileFlag(args);\n const config = loadConfig();\n\n if (args.command === \"debug-prompt\") {\n const cwd = resolve(flagString(args, \"cwd\") ?? process.cwd());\n const task = readPrompt(args);\n if (!task) throw new Error(\"Missing task. Usage: tanya debug-prompt --cwd <path> \\\"task description\\\"\");\n\n const runContext = await buildRunContextForCli(args, cwd, task, config.obsidianVault);\n const historyBlock = buildHistoryBlock(await readRecentTaskHistory(cwd));\n const systemPrompt = buildSystemPrompt(cwd, runContext, historyBlock, task);\n const skillPacks = loadPromptSkillPacks(cwd, runContext, task);\n const sections = flagStrings(args, \"section\");\n const output = selectPromptSections(systemPrompt, sections);\n\n process.stdout.write(\"=== SYSTEM PROMPT ===\\n\\n\");\n process.stdout.write(output);\n process.stdout.write(\"\\n\\n=== END SYSTEM PROMPT ===\\n\");\n if (sections.length === 0) {\n process.stdout.write(`\\nLength: ${systemPrompt.length} chars (~${Math.ceil(systemPrompt.length / 4)} tokens)\\n`);\n process.stdout.write(`${formatSkillPackSummary(skillPacks)}\\n`);\n }\n return;\n }\n\n const provider = createProvider(config);\n\n if (args.command === \"ask\") {\n const prompt = readPrompt(args);\n if (!prompt) throw new Error(\"Missing prompt.\");\n await askOnce(provider, prompt);\n return;\n }\n\n if (args.command === \"review\") {\n const cwd = resolve(flagString(args, \"cwd\") ?? process.cwd());\n const task = readPrompt(args);\n if (!task) throw new Error(\"Missing task description. Usage: tanya review --cwd <path> \\\"task description\\\"\");\n\n const { execFileSync } = await import(\"node:child_process\");\n let diff = \"\";\n try {\n diff = execFileSync(\"git\", [\"diff\", \"HEAD\"], { cwd, encoding: \"utf8\" });\n if (!diff.trim()) {\n diff = execFileSync(\"git\", [\"show\", \"--format=\", \"HEAD\"], { cwd, encoding: \"utf8\" });\n }\n } catch {\n throw new Error(\"tanya review requires a git repository with changes.\");\n }\n\n process.stdout.write(\"Reviewing changes...\\n\\n\");\n const review = await reviewChanges(provider, task, diff);\n process.stdout.write(`${review}\\n`);\n return;\n }\n\n const cwd = resolve(flagString(args, \"cwd\") ?? process.cwd());\n const json = hasFlag(args, \"json\");\n const cosmo = hasFlag(args, \"cosmo\");\n const sink = cosmo ? createCosmoSink() : json ? createJsonlSink() : createHumanSink();\n let runPromptTokens = 0;\n let runCompletionTokens = 0;\n const trackingSink: EventSink = async (event) => {\n if (event.type === \"final\" && event.metrics) {\n runPromptTokens += event.metrics.promptTokens ?? 0;\n runCompletionTokens += event.metrics.completionTokens ?? 0;\n }\n return sink(event);\n };\n\n if (args.command === \"run\") {\n const prompt = readPrompt(args);\n if (!prompt) throw new Error(\"Missing prompt.\");\n const runContext = await buildRunContextForCli(args, cwd, prompt, config.obsidianVault);\n const maxTurns = runContext?.task?.kind === \"coding\" ? 100 : undefined;\n const repairAttempts = flagNumber(args, \"repair-attempts\");\n const maxRetries = flagNumber(args, \"retries\") ?? 0;\n const skipPostCheck = hasFlag(args, \"no-post-check\");\n const usePlan = hasFlag(args, \"plan\");\n let planBlock = \"\";\n\n if (usePlan) {\n process.stderr.write(\"[tanya] Building execution plan with reasoner...\\n\");\n const reasonerConfig = loadConfig(cwd);\n const reasonerProvider = new OpenAiCompatibleProvider({\n id: \"deepseek-reasoner\",\n apiKey: reasonerConfig.apiKey,\n baseUrl: reasonerConfig.baseUrl,\n model: \"deepseek-reasoner\",\n timeoutMs: 180_000,\n temperature: 0,\n topP: 0.2,\n });\n const exportMap = buildExportMap(cwd);\n try {\n const plan = await buildExecutionPlan(reasonerProvider, prompt, exportMap);\n if (plan) {\n planBlock = `## Execution plan (pre-approved, follow it)\\n${plan}`;\n process.stderr.write(\"[tanya] Plan ready.\\n\");\n }\n } catch {\n process.stderr.write(\"[tanya] Planner failed, continuing without plan.\\n\");\n }\n }\n\n let lastResult: RunAgentResult | null = null;\n let previousPostBlockers: string[] = [];\n let attempt = 0;\n let stashedAttemptResult: RunAgentResult | null = null;\n let stashedAttemptLabel: string | null = null;\n // --no-retry-stash: skip stash-and-clean between retries so the agent sees\n // its previous attempt's files and can fix them incrementally instead of\n // rewriting from scratch. Use for tasks where partial progress is valuable\n // (e.g. test-writing where the agent's repeated rewrites burn context). The\n // default (stash) is best for tasks where a wrong-direction first attempt\n // should be discarded.\n const noRetryStash = hasFlag(args, \"no-retry-stash\");\n\n while (attempt <= maxRetries) {\n if (!noRetryStash && attempt > 0 && lastResult && lastResult.manifest.changedFiles.length > 0) {\n try {\n const { execFileSync } = await import(\"node:child_process\");\n const label = `tanya-retry-${attempt}`;\n // Exclude `.tania/` from the stash: those are runner-internal artifacts\n // (history.json, runs/*, memory/*) regenerated each attempt, and\n // including them in the stash causes pop conflicts on retry-recovery.\n execFileSync(\n \"git\",\n [\"stash\", \"push\", \"--include-untracked\", \"-m\", label, \"--\", \":(exclude).tania\", \":!**/.tania/**\"],\n { cwd, stdio: \"ignore\" },\n );\n stashedAttemptResult = lastResult;\n stashedAttemptLabel = label;\n process.stderr.write(\"[tanya] Stashed previous attempt changes. Retrying from clean state.\\n\");\n } catch {\n // Not a git repo or stash failed; retry context still helps.\n }\n }\n const retryContext = attempt > 0 && lastResult\n ? buildRetryContext(lastResult.manifest, attempt, previousPostBlockers)\n : \"\";\n const attemptPrompt = [planBlock, retryContext, \"Original task:\", prompt]\n .filter(Boolean)\n .join(\"\\n\\n---\\n\");\n\n lastResult = await runAgent({\n provider,\n prompt: attemptPrompt,\n cwd,\n sink: trackingSink,\n ...(runContext ? { runContext } : {}),\n ...(maxTurns ? { maxTurns } : {}),\n ...(repairAttempts !== undefined ? { repairAttempts } : {}),\n retryAttempt: attempt,\n });\n\n const postBlockers = skipPostCheck\n ? []\n : await detectPostRunBlockers(cwd, lastResult.manifest);\n if (postBlockers.length > 0) {\n process.stderr.write(\n `[tanya] Post-run checks found ${postBlockers.length} issue(s) not reported by model:\\n${postBlockers.map((blocker) => ` - ${blocker}`).join(\"\\n\")}\\n`,\n );\n }\n previousPostBlockers = postBlockers;\n\n const failed =\n lastResult.manifest.blockers.length > 0 ||\n postBlockers.length > 0 ||\n (lastResult.manifest.validation !== undefined && !lastResult.manifest.validation.passed);\n\n if (!failed || attempt >= maxRetries) break;\n\n attempt += 1;\n process.stderr.write(\n `\\n[tanya] Attempt ${attempt} had blockers. Starting attempt ${attempt + 1} of ${maxRetries + 1}...\\n`,\n );\n }\n\n if (\n stashedAttemptResult &&\n stashedAttemptLabel &&\n lastResult &&\n lastResult.manifest.changedFiles.length === 0 &&\n stashedAttemptResult.manifest.changedFiles.length > 0\n ) {\n const { execFileSync } = await import(\"node:child_process\");\n let stashList = \"\";\n try { stashList = execFileSync(\"git\", [\"stash\", \"list\"], { cwd, encoding: \"utf8\" }); } catch { stashList = \"\"; }\n if (!stashList.includes(stashedAttemptLabel)) {\n process.stderr.write(`[tanya] Stashed attempt (${stashedAttemptLabel}) was already consumed; nothing to recover.\\n`);\n } else {\n try {\n execFileSync(\"git\", [\"stash\", \"pop\"], { cwd, stdio: \"pipe\" });\n process.stderr.write(\n `[tanya] Final attempt produced 0 file changes; restoring stashed attempt (${stashedAttemptResult.manifest.changedFiles.length} files) so the work isn't lost.\\n`,\n );\n lastResult = stashedAttemptResult;\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n if (/conflict|merge|CONFLICT/i.test(msg)) {\n process.stderr.write(`[tanya] Stash pop conflicted with current tree; aborting pop and keeping current attempt. Conflict: ${msg.slice(0, 240)}\\n`);\n try { execFileSync(\"git\", [\"checkout\", \".\"], { cwd, stdio: \"ignore\" }); } catch {}\n } else {\n process.stderr.write(`[tanya] Could not pop stash to recover previous attempt's work: ${msg.slice(0, 240)}\\n`);\n }\n }\n }\n }\n\n if (runPromptTokens > 0 || runCompletionTokens > 0) {\n const costStr = estimateRunCost(config.model, runPromptTokens, runCompletionTokens);\n process.stderr.write(\n `[tanya] Tokens: ${runPromptTokens.toLocaleString()} in / ${runCompletionTokens.toLocaleString()} out ${costStr}\\n`,\n );\n }\n\n if (hasFlag(args, \"review\") && lastResult) {\n let diff = \"\";\n try {\n const { execFileSync } = await import(\"node:child_process\");\n diff = execFileSync(\"git\", [\"diff\", \"HEAD\"], { cwd, encoding: \"utf8\" });\n if (!diff.trim() && lastResult.manifest.git.head) {\n diff = execFileSync(\"git\", [\"show\", \"--format=\", \"HEAD\"], { cwd, encoding: \"utf8\" });\n }\n } catch {\n // No git repository or diff unavailable; skip optional auto-review.\n }\n\n if (diff.trim()) {\n process.stdout.write(\"\\n--- Auto-review ---\\n\");\n const review = await reviewChanges(provider, prompt, diff);\n process.stdout.write(`${review}\\n`);\n }\n }\n return;\n }\n\n await startInteractiveChat({ provider, cwd, sink });\n}\n\nmain().catch((err) => {\n const message = err instanceof Error ? err.message : String(err);\n console.error(`Tanya error: ${message}`);\n process.exitCode = 1;\n});\n","import { existsSync, readFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { parse } from \"dotenv\";\nimport { envValue, numberEnvValue } from \"./envCompat\";\n\nexport interface TanyaConfig {\n provider: \"deepseek\" | \"custom\";\n profile: \"chat\" | \"reasoner\";\n apiKey: string;\n baseUrl: string;\n model: string;\n temperature: number;\n topP: number;\n timeoutMs: number;\n obsidianVault?: string;\n}\n\nfunction loadDotEnv(cwd: string): Record<string, string> {\n const envPath = join(cwd, \".env\");\n if (!existsSync(envPath)) return {};\n return parse(readFileSync(envPath, \"utf8\"));\n}\n\nexport function loadConfig(cwd = process.cwd()): TanyaConfig {\n const local = loadDotEnv(cwd);\n const provider = envValue(local, \"TANYA_PROVIDER\") === \"custom\" ? \"custom\" : \"deepseek\";\n const profile = envValue(local, \"TANYA_PROFILE\") === \"reasoner\" ? \"reasoner\" : \"chat\";\n\n const apiKey =\n provider === \"deepseek\"\n ? envValue(local, \"DEEPSEEK_API_KEY\") || envValue(local, \"TANYA_API_KEY\")\n : envValue(local, \"TANYA_API_KEY\");\n\n const baseUrl =\n provider === \"deepseek\"\n ? envValue(local, \"DEEPSEEK_BASE_URL\") || envValue(local, \"TANYA_BASE_URL\") || \"https://api.deepseek.com\"\n : envValue(local, \"TANYA_BASE_URL\");\n\n const profileModelDefault = profile === \"reasoner\" ? \"deepseek-reasoner\" : \"deepseek-chat\";\n const model = envValue(local, \"TANYA_MODEL\") || profileModelDefault;\n\n const profileTimeoutDefault = profile === \"reasoner\" ? 180_000 : 90_000;\n const timeoutMs = numberEnvValue(local, \"TANYA_TIMEOUT_MS\", profileTimeoutDefault);\n\n const config: TanyaConfig = {\n provider,\n profile,\n apiKey,\n baseUrl: baseUrl.replace(/\\/$/, \"\"),\n model,\n temperature: numberEnvValue(local, \"TANYA_TEMPERATURE\", 0),\n topP: numberEnvValue(local, \"TANYA_TOP_P\", 0.2),\n timeoutMs,\n ...(envValue(local, \"TANYA_OBSIDIAN_VAULT\") ? { obsidianVault: envValue(local, \"TANYA_OBSIDIAN_VAULT\") } : {}),\n };\n\n if (!config.apiKey.trim()) {\n throw new Error(\"TANYA_API_KEY is not set. Add it to your .env file or environment.\");\n }\n\n return config;\n}\n","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 { copyFileSync, cpSync, existsSync, mkdirSync, statSync, writeFileSync } from \"node:fs\";\nimport { basename, dirname, isAbsolute, relative, resolve } from \"node:path\";\nimport type { TanyaRunContext } from \"./runContext\";\n\nexport type MaterializeCliArtifactsInput = {\n cwd: string;\n root?: string | undefined;\n artifacts: string[];\n contextPaths?: string[] | undefined;\n artifactOutputRoot?: string | undefined;\n keepContext?: boolean | undefined;\n baseContext?: TanyaRunContext | undefined;\n};\n\nfunction normalizePath(path: string): string {\n return path.trim().replace(/\\\\/g, \"/\").replace(/^\"|\"$/g, \"\");\n}\n\nfunction unique(values: string[]): string[] {\n return [...new Set(values.map(normalizePath).filter(Boolean))];\n}\n\nfunction sourceLabel(root: string | undefined, artifact: string): string {\n const clean = normalizePath(artifact);\n if (!root || isAbsolute(clean)) return clean;\n const rootBase = basename(resolve(root));\n return rootBase === \"artifacts\" ? `artifacts/${clean}` : clean;\n}\n\nfunction relativeMaterializedPath(root: string | undefined, artifact: string, source: string): string {\n const clean = normalizePath(artifact);\n if (root && !isAbsolute(clean)) return clean;\n if (root) {\n const rel = normalizePath(relative(resolve(root), source));\n if (rel && !rel.startsWith(\"../\") && rel !== \"..\") return rel;\n }\n return basename(source);\n}\n\nexport function materializeCliArtifacts(input: MaterializeCliArtifactsInput): TanyaRunContext | undefined {\n const artifactInputs = unique(input.artifacts);\n const contextInputs = unique(input.contextPaths ?? []);\n if (artifactInputs.length === 0 && contextInputs.length === 0 && !input.artifactOutputRoot) return input.baseContext;\n\n const cwd = resolve(input.cwd);\n const root = input.root ? resolve(input.root) : undefined;\n const targetRoot = resolve(cwd, \".tania\", \"artifacts\");\n const contextTargetRoot = resolve(cwd, \".tania\", \"context\");\n const materialized: NonNullable<TanyaRunContext[\"artifacts\"]> = [];\n const contextFiles: NonNullable<TanyaRunContext[\"contextFiles\"]> = [];\n\n for (const artifact of artifactInputs) {\n const source = isAbsolute(artifact)\n ? resolve(artifact)\n : resolve(root ?? cwd, artifact);\n const rel = relativeMaterializedPath(root, artifact, source);\n const target = resolve(targetRoot, rel);\n const localPath = `.tania/artifacts/${normalizePath(rel)}`;\n const label = sourceLabel(root, artifact);\n\n if (!target.startsWith(`${targetRoot}/`) || !existsSync(source)) {\n materialized.push({\n path: localPath,\n sourcePath: label,\n role: \"source-pattern\",\n status: \"missing\",\n reason: \"Artifact was requested by the caller but was not found.\",\n });\n continue;\n }\n\n const sourceStat = statSync(source);\n if (sourceStat.isDirectory()) {\n mkdirSync(target, { recursive: true });\n cpSync(source, target, { recursive: true, force: true });\n } else {\n mkdirSync(dirname(target), { recursive: true });\n copyFileSync(source, target);\n }\n materialized.push({\n path: localPath,\n sourcePath: label,\n role: \"source-pattern\",\n status: \"available\",\n reason: \"Materialized into this workspace from a caller-provided artifact input.\",\n });\n }\n\n if (materialized.some((artifact) => artifact.status === \"available\")) {\n mkdirSync(targetRoot, { recursive: true });\n writeFileSync(\n resolve(targetRoot, \"manifest.json\"),\n JSON.stringify({ generatedAt: new Date().toISOString(), artifacts: materialized }, null, 2),\n \"utf8\",\n );\n }\n\n for (const contextPath of contextInputs) {\n const source = resolve(contextPath);\n const rel = normalizePath(relative(dirname(source), source)) || basename(source);\n const parentLabel = basename(dirname(source));\n const targetRel = parentLabel ? `${parentLabel}/${basename(source)}` : rel;\n const target = resolve(contextTargetRoot, targetRel);\n const localPath = `.tania/context/${normalizePath(targetRel)}`;\n\n if (!target.startsWith(`${contextTargetRoot}/`) || !existsSync(source)) {\n contextFiles.push({\n path: localPath,\n sourcePath: contextPath,\n role: \"caller-context\",\n status: \"missing\",\n reason: \"Context file was requested by the caller but was not found.\",\n });\n continue;\n }\n\n mkdirSync(dirname(target), { recursive: true });\n copyFileSync(source, target);\n contextFiles.push({\n path: localPath,\n sourcePath: contextPath,\n role: \"caller-context\",\n status: \"available\",\n reason: \"Materialized into this workspace from a caller-provided context input.\",\n });\n }\n\n if (contextFiles.some((contextFile) => contextFile.status === \"available\")) {\n mkdirSync(contextTargetRoot, { recursive: true });\n writeFileSync(\n resolve(contextTargetRoot, \"manifest.json\"),\n JSON.stringify({ generatedAt: new Date().toISOString(), contextFiles }, null, 2),\n \"utf8\",\n );\n }\n\n const artifactOutputRoot = input.artifactOutputRoot ? resolve(input.artifactOutputRoot) : undefined;\n\n return {\n ...(input.baseContext ?? {}),\n artifacts: [...(input.baseContext?.artifacts ?? []), ...materialized],\n contextFiles: [...(input.baseContext?.contextFiles ?? []), ...contextFiles],\n instructions: [\n ...(input.baseContext?.instructions ?? []),\n ...(materialized.length > 0 ? [\n \"Caller artifacts were provided through Tanya's artifact input contract and materialized under .tania/artifacts.\",\n \"Read relevant materialized artifact paths before implementing related code.\",\n ] : []),\n ...(contextFiles.length > 0 ? [\n \"Caller context files were materialized under .tania/context.\",\n \"Read relevant materialized context paths before implementing safety, brand, architecture, or API contract requirements.\",\n ] : []),\n ...(artifactOutputRoot ? [\n \"If you create a reusable artifact, write it inside .tania/artifact-output using the intended artifact-relative path and mention it as Artifact created.\",\n ] : []),\n \"When reporting artifact reuse, use the artifact sourcePath label when available.\",\n ],\n expected_report: {\n ...(input.baseContext?.expected_report ?? {}),\n artifact_reuse: true,\n },\n metadata: {\n ...(input.baseContext?.metadata ?? {}),\n ...(artifactOutputRoot ? { artifactOutputRoot } : {}),\n tanyaMaterializedContext: true,\n keepMaterializedContext: input.keepContext === true,\n },\n };\n}\n","import type { EventSink } from \"./types\";\n\nconst PREFIX = \"__E:\";\n\nfunction writeEvent(stream: NodeJS.WritableStream, event: unknown): void {\n stream.write(`${PREFIX}${JSON.stringify(event)}\\n`);\n}\n\nexport function createCosmoSink(stream: NodeJS.WritableStream = process.stdout): EventSink {\n let textOpen = false;\n\n function ensureEventLine(): void {\n if (textOpen) {\n stream.write(\"\\n\");\n textOpen = false;\n }\n }\n\n return (event) => {\n switch (event.type) {\n case \"status\":\n ensureEventLine();\n writeEvent(stream, { t: \"status\", message: event.message, key: `tanya:${event.message.slice(0, 80)}` });\n break;\n case \"message_delta\":\n stream.write(event.text);\n textOpen = !event.text.endsWith(\"\\n\");\n break;\n case \"tool_call\":\n ensureEventLine();\n writeEvent(stream, {\n t: \"tool_call\",\n tool: event.tool,\n detail: JSON.stringify(event.input).slice(0, 200),\n content: \"\",\n id: event.id,\n });\n break;\n case \"tool_result\":\n ensureEventLine();\n writeEvent(stream, {\n t: \"tool_result\",\n id: event.id,\n output: event.summary,\n error: !event.ok,\n });\n break;\n case \"tool_progress\":\n ensureEventLine();\n writeEvent(stream, {\n t: \"tool_progress\",\n id: event.toolCallId,\n stream: event.stream,\n chunk: event.chunk,\n timestamp: event.timestamp,\n });\n break;\n case \"tool_cancel_requested\":\n ensureEventLine();\n writeEvent(stream, {\n t: \"tool_cancel_requested\",\n id: event.toolCallId,\n tool: event.tool,\n timestamp: event.timestamp,\n });\n break;\n case \"tool_cancelled\":\n ensureEventLine();\n writeEvent(stream, {\n t: \"tool_cancelled\",\n id: event.toolCallId,\n tool: event.tool,\n timestamp: event.timestamp,\n partialOutput: event.partialOutput,\n });\n break;\n case \"final\":\n ensureEventLine();\n if (event.message.trim()) {\n stream.write(`${event.message.trim()}\\n`);\n }\n writeEvent(stream, {\n t: \"status\",\n message: `Tanya finished. Changed files: ${event.files?.length ?? 0}. Tool errors: ${event.metrics?.toolErrorCount ?? 0}.`,\n key: \"tanya:final\",\n metrics: event.metrics,\n files: event.files ?? [],\n });\n break;\n case \"error\":\n ensureEventLine();\n writeEvent(stream, {\n t: \"tool_result\",\n id: \"tanya:error\",\n output: event.detail ? `${event.message}\\n${event.detail}` : event.message,\n error: true,\n });\n break;\n case \"message_start\":\n break;\n case \"message_end\":\n if (textOpen) {\n stream.write(\"\\n\");\n textOpen = false;\n }\n break;\n default:\n break;\n }\n };\n}\n","import type { EventSink, TanyaEvent } from \"./types\";\n\nconst knownEventTypes = new Set([\n \"status\",\n \"message_start\",\n \"message_delta\",\n \"message_end\",\n \"tool_call\",\n \"tool_progress\",\n \"tool_cancel_requested\",\n \"tool_cancelled\",\n \"tool_result\",\n \"final\",\n \"error\",\n]);\n\nfunction isKnownEvent(event: unknown): event is TanyaEvent {\n return Boolean(\n event &&\n typeof event === \"object\" &&\n typeof (event as { type?: unknown }).type === \"string\" &&\n knownEventTypes.has((event as { type: string }).type),\n );\n}\n\nexport function createJsonlSink(stream: NodeJS.WritableStream = process.stdout): EventSink {\n return (event: TanyaEvent) => {\n if (!isKnownEvent(event)) return;\n stream.write(`${JSON.stringify(event)}\\n`);\n };\n}\n","import type { ChatDelta, ChatProvider, ChatRequest, ToolCall } from \"./types\";\nimport { envValue } from \"../config/envCompat\";\n\nexport interface OpenAiCompatibleProviderOptions {\n id: string;\n apiKey: string;\n baseUrl: string;\n model: string;\n timeoutMs?: number;\n temperature?: number;\n topP?: number;\n}\n\ninterface StreamChoice {\n delta?: {\n content?: string | null;\n tool_calls?: Array<{\n index?: number;\n id?: string;\n type?: \"function\";\n function?: {\n name?: string;\n arguments?: string;\n };\n }>;\n };\n finish_reason?: string | null;\n}\n\ninterface StreamChunk {\n choices?: StreamChoice[];\n usage?: {\n prompt_tokens?: number;\n completion_tokens?: number;\n };\n}\n\nconst RETRYABLE_HTTP_STATUSES = new Set([429, 500, 502, 503]);\nconst MAX_FETCH_ATTEMPTS = 3;\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\nfunction retryAfterMs(response: Response): number | null {\n const raw = response.headers.get(\"retry-after\");\n if (!raw) return null;\n const seconds = Number(raw);\n if (Number.isFinite(seconds) && seconds >= 0) return Math.min(seconds * 1000, 60_000);\n const dateMs = Date.parse(raw);\n if (!Number.isNaN(dateMs)) return Math.min(Math.max(dateMs - Date.now(), 0), 60_000);\n return null;\n}\n\nfunction backoffMs(attempt: number, response?: Response): number {\n const retryAfter = response?.status === 429 ? retryAfterMs(response) : null;\n if (retryAfter !== null) return retryAfter;\n const base = 100 * 2 ** attempt;\n const jitter = base * 0.1 * (Math.random() * 2 - 1);\n return Math.max(0, Math.round(base + jitter));\n}\n\nexport class OpenAiCompatibleProvider implements ChatProvider {\n readonly id: string;\n readonly model: string;\n private readonly apiKey: string;\n private readonly baseUrl: string;\n private readonly timeoutMs: number;\n private readonly temperature: number;\n private readonly topP: number;\n\n constructor(options: OpenAiCompatibleProviderOptions) {\n this.id = options.id;\n this.apiKey = options.apiKey;\n this.baseUrl = options.baseUrl.replace(/\\/$/, \"\");\n this.model = options.model;\n const envTimeout = parseInt(envValue({}, \"TANYA_TIMEOUT_MS\"), 10);\n const envTimeoutMs = Number.isFinite(envTimeout) && envTimeout > 0 ? envTimeout : null;\n this.timeoutMs = envTimeoutMs ?? options.timeoutMs ?? 90_000;\n this.temperature = options.temperature ?? 0;\n this.topP = options.topP ?? 0.2;\n }\n\n async *streamChat(input: ChatRequest): AsyncGenerator<ChatDelta> {\n if (!this.apiKey) {\n throw new Error(`Missing API key for provider \"${this.id}\".`);\n }\n\n const controller = new AbortController();\n let timeout: ReturnType<typeof setTimeout> | null = null;\n const resetTimeout = () => {\n if (timeout) clearTimeout(timeout);\n timeout = setTimeout(() => controller.abort(), this.timeoutMs);\n };\n\n const requestBody = JSON.stringify({\n model: this.model,\n messages: input.messages,\n tools: input.tools?.length ? input.tools : undefined,\n tool_choice: input.tools?.length ? \"auto\" : undefined,\n temperature: input.temperature ?? this.temperature,\n top_p: input.topP ?? this.topP,\n max_tokens: input.maxTokens ?? 8192,\n stream: true,\n });\n\n let response: Response | null = null;\n let finalHttpErrorDetail = \"\";\n\n for (let attempt = 0; attempt < MAX_FETCH_ATTEMPTS; attempt += 1) {\n resetTimeout();\n response = await fetch(`${this.baseUrl}/chat/completions`, {\n method: \"POST\",\n signal: controller.signal,\n headers: {\n Authorization: `Bearer ${this.apiKey}`,\n \"Content-Type\": \"application/json\",\n },\n body: requestBody,\n }).catch((error) => {\n if (controller.signal.aborted) {\n throw new Error(`Provider ${this.id} timed out before streaming a response.`);\n }\n throw error;\n });\n\n if (response.ok && response.body) break;\n\n if (!RETRYABLE_HTTP_STATUSES.has(response.status) || attempt === MAX_FETCH_ATTEMPTS - 1) {\n break;\n }\n\n finalHttpErrorDetail = await response.text().catch(() => \"\");\n await sleep(backoffMs(attempt, response));\n }\n\n if (!response) {\n if (timeout) clearTimeout(timeout);\n throw new Error(`Provider ${this.id} failed to open a streaming response.`);\n }\n\n if (!response.ok || !response.body) {\n if (timeout) clearTimeout(timeout);\n const detail = finalHttpErrorDetail || await response.text().catch(() => \"\");\n throw new Error(`Provider ${this.id} returned HTTP ${response.status}: ${detail.slice(0, 500)}`);\n }\n\n const decoder = new TextDecoder();\n let buffer = \"\";\n const toolCallParts = new Map<number, ToolCall>();\n\n try {\n for await (const chunk of response.body as unknown as AsyncIterable<Uint8Array>) {\n resetTimeout();\n buffer += decoder.decode(chunk, { stream: true });\n const lines = buffer.split(\"\\n\");\n buffer = lines.pop() ?? \"\";\n\n for (const rawLine of lines) {\n const line = rawLine.trim();\n if (!line || !line.startsWith(\"data:\")) continue;\n const data = line.slice(\"data:\".length).trim();\n if (data === \"[DONE]\") return;\n\n let parsed: StreamChunk;\n try {\n parsed = JSON.parse(data) as StreamChunk;\n } catch (error) {\n if (envValue({}, \"TANYA_DEBUG\")) {\n const message = error instanceof Error ? error.message : String(error);\n console.debug(`[tanya] Skipping malformed SSE chunk: ${message}`);\n }\n continue;\n }\n if (parsed.usage?.prompt_tokens !== undefined) {\n yield {\n usage: {\n promptTokens: parsed.usage.prompt_tokens ?? 0,\n completionTokens: parsed.usage.completion_tokens ?? 0,\n },\n };\n }\n\n const choice = parsed.choices?.[0];\n if (!choice) continue;\n\n const content = choice.delta?.content ?? undefined;\n if (content) yield { content };\n\n const rawToolCalls = choice.delta?.tool_calls ?? [];\n for (const rawToolCall of rawToolCalls) {\n const index = rawToolCall.index ?? 0;\n const existing =\n toolCallParts.get(index) ??\n ({\n id: rawToolCall.id ?? `tool-${index}`,\n type: \"function\",\n function: { name: \"\", arguments: \"\" },\n } satisfies ToolCall);\n\n if (rawToolCall.id) existing.id = rawToolCall.id;\n if (rawToolCall.function?.name) existing.function.name += rawToolCall.function.name;\n if (rawToolCall.function?.arguments) existing.function.arguments += rawToolCall.function.arguments;\n toolCallParts.set(index, existing);\n }\n\n if (choice.finish_reason) {\n const toolCalls = [...toolCallParts.values()].filter((call) => call.function.name);\n yield toolCalls.length\n ? { finishReason: choice.finish_reason, toolCalls }\n : { finishReason: choice.finish_reason };\n }\n }\n }\n } catch (error) {\n if (controller.signal.aborted) {\n throw new Error(`Provider ${this.id} timed out while streaming a response.`);\n }\n throw error;\n } finally {\n if (timeout) clearTimeout(timeout);\n }\n }\n}\n","import type { TanyaConfig } from \"../config/env\";\nimport { OpenAiCompatibleProvider } from \"./openAiCompatible\";\nimport type { ChatProvider } from \"./types\";\n\nexport function createProvider(config: TanyaConfig): ChatProvider {\n return new OpenAiCompatibleProvider({\n id: config.profile === \"reasoner\" ? \"deepseek-reasoner\" : config.provider,\n apiKey: config.apiKey,\n baseUrl: config.baseUrl,\n model: config.model,\n temperature: config.temperature,\n topP: config.topP,\n timeoutMs: config.timeoutMs,\n });\n}\n","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 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 { 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\";\n\nconst ignoredNames = new Set([\".git\", \"node_modules\", \".next\", \"dist\", \"build\", \".turbo\", \".cache\"]);\nexport const PROGRESS_THROTTLE_MS = 2_000;\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 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 displayOutput = summarizeProcessOutput(output, 12_000);\n const baseResult: ToolResult = {\n ok: code === 0,\n summary: buildProcessSummary(\"Command\", code, output, displayOutput.truncated),\n output: displayOutput.text,\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), PROGRESS_THROTTLE_MS);\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 displayOutput = summarizeProcessOutput(output, 16_000);\n const baseResult: ToolResult = {\n ok: code === 0,\n summary: buildProcessSummary(\"Shell\", code, output, displayOutput.truncated),\n output: displayOutput.text,\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\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 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 },\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 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 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 { ok: false, summary: \"Shell script rejected by safety checks.\", error: \"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 { ok: false, summary: \"Shell script rejected: git restore of historical content is not allowed.\", error: \"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 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 { ok: false, summary: \"Shell verification rejected by safety checks.\", error: 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 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 tools = [\n listFilesTool,\n readFileTool,\n searchTool,\n inspectProjectContextTool,\n findReusableArtifactsTool,\n buildTaskBriefTool,\n searchObsidianNotesTool,\n writeFileTool,\n applyPatchTool,\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 runCommandTool,\n runShellTool,\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 { 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 CosmoKit.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() || \"CosmoKit 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 CosmoKit 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 { 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 \"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 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 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 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 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 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 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\") records.push(parsed);\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 { 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 { 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 type { ChatMessage, ChatProvider } from \"../providers/types\";\n\nexport function estimateTokens(messages: ChatMessage[]): number {\n return messages.reduce((sum, msg) => {\n const text = typeof msg.content === \"string\" ? msg.content : JSON.stringify(msg.content ?? \"\");\n return sum + Math.ceil(text.length / 4);\n }, 0);\n}\n\nexport async function summarizeOldMessages(\n provider: ChatProvider,\n messages: ChatMessage[],\n): Promise<ChatMessage> {\n const text = messages\n .map((message) => {\n const role = message.role.toUpperCase();\n const content = typeof message.content === \"string\" ? message.content : JSON.stringify(message.content ?? \"\");\n return `[${role}]: ${content.slice(0, 800)}`;\n })\n .join(\"\\n\\n\");\n\n try {\n let summary = \"\";\n for await (const delta of provider.streamChat({\n messages: [\n {\n role: \"user\",\n content: `Summarize these agent turns into a compact factual block (max 400 words).\nInclude: what files were read, what edits were made, what commands ran and their outcomes, any blockers hit.\nDo not include reasoning or explanations — only facts.\n\n${text}`,\n },\n ],\n tools: [],\n temperature: 0,\n maxTokens: 512,\n })) {\n if (delta.content) summary += delta.content;\n }\n\n return {\n role: \"user\",\n content: `[CONTEXT SUMMARY — earlier turns compressed to save context]\\n${summary.trim()}\\n[END SUMMARY — continuing task below]`,\n };\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n console.warn(`[tanya] Context summarization failed; dropping ${messages.length} older turns without summarization: ${message}`);\n return {\n role: \"user\",\n content: `[CONTEXT SUMMARY — earlier turns dropped to save context]\\nDropped ${messages.length} older turns because summarization failed: ${message}\\n[END SUMMARY — continuing task below]`,\n };\n }\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 2026-05-01 audit caught in cosa-nostra 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\";\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 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 const readme = await readWorkspaceFile(workspace, \"README.md\") ?? \"\";\n const docs = `${env ?? \"\"}\\n${readme}`;\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 for (const key of [\"DATABASE_URL\", \"DIRECT_URL\"]) {\n const match = env.match(new RegExp(`^${key}\\\\s*=\\\\s*[\\\"']?([^\\\"'\\\\n#]+)`, \"m\"));\n const value = match?.[1]?.trim() ?? \"\";\n if (!value) {\n issues.push({\n id: \"backend-setup-postgres-placeholder-missing\",\n severity: \"error\",\n message: `${key} must be present in .env.example as a placeholder.`,\n files: [\".env.example\"],\n });\n continue;\n }\n if (/postgres(?:ql)?:\\/\\/[^\"'\\s]*localhost|postgres(?:ql)?:\\/\\/[^\"'\\s]*127\\.0\\.0\\.1|postgres(?:ql)?:\\/\\/postgres:postgres@/i.test(value)) {\n issues.push({\n id: \"backend-setup-postgres-localhost-hardcoded\",\n severity: \"error\",\n message: `${key} must use a placeholder-only value, not a concrete localhost PostgreSQL URL.`,\n files: [\".env.example\"],\n });\n }\n if (!isExplicitPlaceholderText(value) && !/(?:\\bcosmohq\\b|\\bazure\\b)/i.test(value)) {\n issues.push({\n id: \"backend-setup-postgres-placeholder-unclear\",\n severity: \"warning\",\n message: `${key} should be clearly marked as a placeholder in .env.example.`,\n files: [\".env.example\"],\n });\n }\n }\n\n if (!/CosmoHQ Deploy/i.test(docs) || !/Azure PostgreSQL/i.test(docs) || !/DATABASE_URL/i.test(docs) || !/DIRECT_URL/i.test(docs) || !/(seed|mock|test-account)/i.test(docs)) {\n issues.push({\n id: \"backend-setup-deploy-provisioning-note-missing\",\n severity: \"error\",\n message: \"Backend setup must document that CosmoHQ Deploy provisions Azure PostgreSQL and DATABASE_URL/DIRECT_URL before seed/mock/test-account actions.\",\n files: [\".env.example\", \"README.md\"],\n });\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 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 // 2026-05-01 cosa-nostra 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 // 2026-05-01 cosa-nostra 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 2026-05-01 cosa-nostra 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 // 2026-05-01 cosa-nostra 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 // 2026-05-01 cosa-nostra 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 /(?:^|\\/)\\.(?: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 { 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\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 runContext?: TanyaRunContext | undefined;\n prompt?: string;\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 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: uniqueSorted(params.blockers ?? []),\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 let gateScanFiles = uniqueSorted([...manifest.changedFiles, ...committedFiles]);\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 }\n return manifest;\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 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 verification rejected by safety checks/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 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 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.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\nexport function ensureCodingReport(text: string, manifest: TanyaFinalManifest, runContext?: TanyaRunContext): string {\n if (!manifest.changedFiles.length && !manifest.artifactsRead.length && !manifest.artifactsCreated.length && !manifest.verification.length && !manifest.git.root) return text;\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 footer;\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 bodyText;\n if (hasCompleteCodingReport(bodyText) && !needsManualCheckLines) return `${bodyText.trim()}\\n\\n${footer}`;\n return bodyText.trim() ? `${bodyText.trim()}\\n\\n${footer}` : footer;\n}\n","import { existsSync, readFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { buildArtifactIndexBlock, buildContextBlock, buildExportMap } from \"../context/loader\";\nimport { buildRunContextBlock, type TanyaRunContext } from \"../context/runContext\";\nimport { loadSkillPacks, type LoadedSkillPack } from \"../skills\";\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 buildSystemPrompt(workspace: string, runContext?: TanyaRunContext, historyBlock?: string, taskHint = \"\"): string {\n const callerContext = buildRunContextBlock(runContext);\n const projectInstructions = readProjectInstructions(workspace);\n const exportMap = buildExportMap(workspace);\n const artifactIndex = buildArtifactIndexBlock(workspace, taskHint);\n const skillPackBlock = buildSkillPackBlock(loadPromptSkillPacks(workspace, runContext, taskHint));\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 \"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 exportMap,\n artifactIndex,\n skillPackBlock,\n historyBlock ?? \"\",\n buildContextBlock(workspace),\n projectInstructions,\n callerContext ? `\\n${callerContext}` : \"\",\n ].join(\"\\n\");\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 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 \"go-backend-cosmohq\",\n \"backend-go-huma\",\n \"backend-go-house\",\n \"ios-cosmohq\",\n \"ios\",\n \"macos\",\n \"android-cosmohq\",\n \"android\",\n \"nextjs-cosmohq\",\n \"landing-cosmohq\",\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\", \"android-cosmohq\"])) 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 \"stack/go-backend-cosmohq\":\n if (stackHintMatches(stack, [\"go-backend-cosmohq\", \"backend-go-huma\", \"backend-go-house\"]) || languageHintMatches(languages, [\"go\"])) return \"hint\";\n return signals.go ? \"workspace\" : null;\n case \"stack/ios-cosmohq\":\n if (stackHintMatches(stack, [\"ios-cosmohq\", \"ios\", \"macos\"]) || languageHintMatches(languages, [\"swift\"])) return \"hint\";\n return signals.ios ? \"workspace\" : null;\n case \"stack/android-cosmohq\":\n if (stackHintMatches(stack, [\"android-cosmohq\", \"android\"]) || languageHintMatches(languages, [\"kotlin\"])) return \"hint\";\n return signals.android ? \"workspace\" : null;\n case \"stack/nextjs-cosmohq\":\n if (stackHintMatches(stack, [\"nextjs-cosmohq\", \"landing-cosmohq\", \"landing\", \"web\"]) || languageHintMatches(languages, [\"typescript\", \"ts\"])) return \"hint\";\n return signals.next ? \"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\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 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 = collectSkillFiles(skillsRoot)\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 content: pack.body,\n tokens: pack.tokens,\n reason: pack.reason,\n }));\n}\n\nexport function loadSkillPacks(ctx: SkillPackContext): LoadedSkillPack[] {\n return loadSkillPacksFromRoot(ctx, resolveDefaultSkillsRoot());\n}\n","import type { EventSink } from \"../events/types\";\nimport type { TanyaRunContext } from \"../context/runContext\";\nimport type { ChatMessage, ChatProvider, ToolCall } from \"../providers/types\";\nimport { resolveWorkspace } from \"../safety/workspace\";\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 } from \"../config/envCompat\";\nimport type { ValidationSummary } from \"./validators\";\nimport { estimateTokens, summarizeOldMessages } from \"./compression\";\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 { 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;\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 validation?: ValidationSummary;\n};\n\nexport type RunAgentResult = {\n message: string;\n manifest: TanyaFinalManifest;\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};\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 repairAttempts?: number;\n retryAttempt?: number;\n signal?: AbortSignal;\n}\n\ntype MalformedToolArguments = {\n ok: false;\n error: string;\n rawArguments: string;\n};\n\nfunction isMalformedToolArguments(value: unknown): value is MalformedToolArguments {\n return Boolean(value && typeof value === \"object\" && (value as { ok?: unknown }).ok === false &&\n typeof (value as { rawArguments?: unknown }).rawArguments === \"string\");\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 parseToolArguments(raw: string): unknown {\n if (!raw.trim()) return {};\n try {\n return JSON.parse(raw);\n } catch {\n const rawPreview = previewRawToolArguments(raw);\n return {\n ok: false,\n error: `malformed tool arguments: ${rawPreview}`,\n rawArguments: rawPreview,\n } satisfies MalformedToolArguments;\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 prompt: string;\n model: string;\n metrics: FinalMetrics;\n manifest: TanyaFinalManifest;\n}): void {\n try {\n const runsDir = join(params.workspace, \".tania\", \"runs\");\n mkdirSync(runsDir, { recursive: true });\n const ts = new Date().toISOString();\n const logPath = join(runsDir, `${ts.replace(/[:.]/g, \"-\")}.json`);\n writeFileSync(\n logPath,\n JSON.stringify(\n {\n ts,\n prompt: params.prompt.slice(0, 200),\n model: params.model,\n durationMs: params.metrics.durationMs,\n promptTokens: params.metrics.promptTokens,\n completionTokens: params.metrics.completionTokens,\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(runsDir);\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 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\nexport async function runAgent(options: RunAgentOptions): Promise<RunAgentResult> {\n const workspace = resolveWorkspace(options.cwd);\n const beforeGitSnapshot = await captureGitSnapshot(workspace);\n const registry = new ToolRegistry();\n const startedAt = Date.now();\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 const historyBlock = buildHistoryBlock(await readRecentTaskHistory(workspace));\n let messages: ChatMessage[] = [\n { role: \"system\", content: buildSystemPrompt(workspace, options.runContext, historyBlock, options.prompt) },\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 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\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 };\n }\n\n async function finishRun(finalMessage: string, manifest: TanyaFinalManifest): Promise<void> {\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 prompt: options.prompt,\n model: options.provider.model,\n metrics,\n manifest,\n });\n }\n\n for (let turn = 0; turn < maxTurns; turn += 1) {\n if (estimateTokens(messages) > CONTEXT_TOKEN_LIMIT && messages.length > CONTEXT_SUMMARY_KEEP_RECENT + 1) {\n const systemMsg = messages[0];\n const safeStart = findSafeCompressionBoundary(messages, CONTEXT_SUMMARY_KEEP_RECENT);\n const recentMessages = messages.slice(safeStart);\n const oldMessages = messages.slice(1, safeStart);\n if (systemMsg && oldMessages.length > 2) {\n try {\n const summaryMsg = await summarizeOldMessages(options.provider, oldMessages);\n messages = [systemMsg, summaryMsg, ...recentMessages];\n await options.sink({ type: \"status\", message: `Context compressed: ${oldMessages.length} turns summarized.` });\n } catch {\n // Summarization failed; continue with full history rather than crashing.\n }\n }\n }\n\n await options.sink({ type: \"message_start\" });\n let assistantText = \"\";\n let toolCalls: ToolCall[] = [];\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 const PROVIDER_TRANSIENT_RETRIES = 1;\n while (true) {\n try {\n for await (const delta of options.provider.streamChat({\n messages,\n tools: registry.list().map((tool) => tool.definition),\n ...codingProviderOptions,\n })) {\n if (delta.usage) {\n totalPromptTokens += delta.usage.promptTokens;\n totalCompletionTokens += delta.usage.completionTokens;\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.toolCalls?.length) toolCalls = delta.toolCalls;\n }\n break; // stream completed normally\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n const isTransient = /timed out|fetch failed|ECONNRESET|EAI_AGAIN|ENOTFOUND|socket hang up/i.test(message);\n const noProgressYet = assistantText.length === 0 && toolCalls.length === 0;\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 throw err;\n }\n }\n\n await options.sink({ type: \"message_end\" });\n\n const assistantMessage: ChatMessage = {\n role: \"assistant\",\n content: assistantText || null,\n };\n if (toolCalls.length) assistantMessage.tool_calls = toolCalls;\n messages.push(assistantMessage);\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 runContext: options.runContext,\n prompt: options.prompt,\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 await finishRun(finalMessage, manifest);\n return { message: finalMessage, manifest };\n }\n\n for (const toolCall of toolCalls) {\n const toolName = toolCall.function.name;\n const tool = registry.get(toolName);\n const callInput = parseToolArguments(toolCall.function.arguments);\n if (isMalformedToolArguments(callInput)) {\n toolErrorCount += 1;\n messages.push({\n role: \"tool\",\n tool_call_id: toolCall.id,\n content: JSON.stringify({\n ok: false,\n error: callInput.error,\n rawArguments: callInput.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): ${callInput.rawArguments}`,\n error: callInput.error,\n });\n continue;\n }\n toolCallCount += 1;\n await options.sink({ type: \"tool_call\", id: toolCall.id, tool: toolName, input: callInput });\n\n if (!tool) {\n const error = `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 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 const duplicateVerification = key ? passedVerificationKeys.get(key) === mutationRevision : false;\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 }, {\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 result = 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 : await runRegisteredTool();\n if (duplicateVerification && key) {\n skippedDuplicateKeys.set(key, (skippedDuplicateKeys.get(key) ?? 0) + 1);\n }\n if (result.ok) {\n changed = collectChangedFiles(changed, result.files);\n if (toolName === requiredTool) requiredToolUsed = true;\n }\n if (toolResultMutatedFiles(toolName, result)) mutationRevision += 1;\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 messages.push({ role: \"tool\", tool_call_id: toolCall.id, content: JSON.stringify(result) });\n const event = {\n type: \"tool_result\",\n id: toolCall.id,\n tool: toolName,\n ok: result.ok,\n summary: result.summary,\n output: result.output,\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 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 runContext: options.runContext,\n prompt: options.prompt,\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 await finishRun(finalMessageWithFooter, manifest);\n return { message: finalMessageWithFooter, manifest };\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 runContext: options.runContext,\n prompt: options.prompt,\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 await finishRun(finalMessageWithFooter, manifest);\n return { message: finalMessageWithFooter, manifest };\n}\n","import { spawnSync } from \"node:child_process\";\nimport { existsSync, readFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport type { TanyaFinalManifest } from \"./runner\";\n\nconst POST_CHECK_TIMEOUT_MS = 25_000;\n\nfunction hasPassingVerification(manifest: TanyaFinalManifest, pattern: RegExp): boolean {\n return manifest.verification.some(\n (line) => /->\\s*passed\\b/i.test(line) && pattern.test(line),\n );\n}\n\nfunction readPackageScripts(cwd: string): Record<string, string> {\n try {\n const raw = readFileSync(join(cwd, \"package.json\"), \"utf8\");\n const parsed = JSON.parse(raw) as { scripts?: Record<string, string> };\n return parsed.scripts ?? {};\n } catch {\n return {};\n }\n}\n\nfunction readPackageManager(cwd: string): \"npm\" | \"pnpm\" | \"yarn\" | \"bun\" {\n try {\n const raw = readFileSync(join(cwd, \"package.json\"), \"utf8\");\n const parsed = JSON.parse(raw) as { packageManager?: string };\n const packageManager = parsed.packageManager?.split(\"@\")[0];\n if (packageManager === \"pnpm\" || packageManager === \"yarn\" || packageManager === \"bun\") return packageManager;\n } catch {\n // fall through to lockfile detection\n }\n if (existsSync(join(cwd, \"pnpm-lock.yaml\"))) return \"pnpm\";\n if (existsSync(join(cwd, \"yarn.lock\"))) return \"yarn\";\n if (existsSync(join(cwd, \"bun.lockb\")) || existsSync(join(cwd, \"bun.lock\"))) return \"bun\";\n return \"npm\";\n}\n\nfunction packageScriptCommand(\n packageManager: \"npm\" | \"pnpm\" | \"yarn\" | \"bun\",\n script: string,\n): { cmd: string; args: string[] } {\n if (packageManager === \"yarn\") return { cmd: \"yarn\", args: [script] };\n return { cmd: packageManager, args: [\"run\", script] };\n}\n\nfunction runCommand(\n cmd: string,\n args: string[],\n cwd: string,\n timeoutMs: number,\n): { exitCode: number; output: string } {\n const result = spawnSync(cmd, args, {\n cwd,\n encoding: \"utf8\",\n timeout: timeoutMs,\n shell: false,\n });\n const output = `${result.stdout ?? \"\"}${result.stderr ?? \"\"}`.trim();\n const exitCode = result.status ?? (result.error ? 1 : 0);\n return { exitCode, output };\n}\n\nfunction parseTypeScriptErrors(output: string): string[] {\n return output\n .split(/\\r?\\n/)\n .filter((line) => /\\.tsx?:\\d+:\\d+\\s*-?\\s*error\\s+TS\\d+:/i.test(line) || /error TS\\d+:/i.test(line))\n .slice(0, 5);\n}\n\nexport async function detectPostRunBlockers(\n cwd: string,\n manifest: TanyaFinalManifest,\n): Promise<string[]> {\n const blockers: string[] = [];\n const tsconfigExists =\n existsSync(join(cwd, \"tsconfig.json\")) || existsSync(join(cwd, \"tsconfig.base.json\"));\n const scripts = readPackageScripts(cwd);\n const packageManager = readPackageManager(cwd);\n\n if (tsconfigExists && !hasPassingVerification(manifest, /tsc|typecheck|type-check/i)) {\n const typecheckCommand = scripts.typecheck\n ? packageScriptCommand(packageManager, \"typecheck\")\n : { cmd: \"npx\", args: [\"tsc\", \"--noEmit\", \"--pretty\", \"false\"] };\n const { exitCode, output } = runCommand(typecheckCommand.cmd, typecheckCommand.args, cwd, POST_CHECK_TIMEOUT_MS);\n if (exitCode !== 0) {\n const errorLines = parseTypeScriptErrors(output);\n const summary = errorLines.length > 0\n ? `TypeScript errors after run:\\n${errorLines.map((line) => ` ${line}`).join(\"\\n\")}`\n : \"TypeScript compilation failed (post-run check)\";\n blockers.push(summary);\n }\n }\n\n if (scripts.test && !hasPassingVerification(manifest, /\\btest\\b/i)) {\n const testCommand = packageScriptCommand(packageManager, \"test\");\n const { exitCode } = runCommand(testCommand.cmd, testCommand.args, cwd, POST_CHECK_TIMEOUT_MS);\n if (exitCode !== 0) {\n blockers.push(\"Tests failed after run (post-run check)\");\n }\n }\n\n return blockers;\n}\n","import type { ChatProvider } from \"../providers/types\";\n\nconst PLAN_SYSTEM = [\n \"You are a senior engineer producing a concise execution plan for a coding agent.\",\n \"Given a task description and a workspace export map, output ONLY a structured plan.\",\n \"Format:\",\n \"Files to read first: <comma-separated list>\",\n \"Files to modify: <comma-separated list>\",\n \"Key steps:\",\n \"1. <step>\",\n \"2. <step>\",\n \"...\",\n \"Verification: <command to run>\",\n \"Do not write any code. Do not explain. Output the plan only.\",\n].join(\"\\n\");\n\nexport async function buildExecutionPlan(\n reasonerProvider: ChatProvider,\n task: string,\n exportMap: string,\n): Promise<string> {\n const userContent = exportMap\n ? `Workspace export map:\\n${exportMap}\\n\\nTask: ${task}`\n : `Task: ${task}`;\n\n let plan = \"\";\n for await (const delta of reasonerProvider.streamChat({\n messages: [\n { role: \"system\", content: PLAN_SYSTEM },\n { role: \"user\", content: userContent },\n ],\n tools: [],\n temperature: 0,\n maxTokens: 512,\n })) {\n if (delta.content) plan += delta.content;\n }\n return plan.trim();\n}\n","import type { ChatProvider } from \"../providers/types\";\n\nconst REVIEW_SYSTEM = [\n \"You are a senior code reviewer. You will be given a task description and the diff of changes made.\",\n \"Review only what was changed. Be concise. Flag only real issues.\",\n \"Output format:\",\n \"## Review\",\n \"**Verdict:** LGTM | NEEDS CHANGES\",\n \"\",\n \"**Issues:** (list only if verdict is NEEDS CHANGES)\",\n \"- <file>:<line> — <issue>\",\n \"\",\n \"**Suggestions:** (optional minor improvements, max 3)\",\n \"- <suggestion>\",\n \"\",\n \"Do not praise the code. Do not explain what the code does. Only flag problems.\",\n].join(\"\\n\");\n\nexport async function reviewChanges(\n provider: ChatProvider,\n task: string,\n diff: string,\n): Promise<string> {\n if (!diff.trim()) return \"## Review\\n**Verdict:** LGTM\\n\\nNo changes to review.\";\n\n let review = \"\";\n for await (const delta of provider.streamChat({\n messages: [\n { role: \"system\", content: REVIEW_SYSTEM },\n {\n role: \"user\",\n content: `Task: ${task}\\n\\nDiff:\\n\\`\\`\\`diff\\n${diff.slice(0, 8000)}\\n\\`\\`\\``,\n },\n ],\n tools: [],\n temperature: 0,\n maxTokens: 600,\n })) {\n if (delta.content) review += delta.content;\n }\n return review.trim();\n}\n","import { createInterface } from \"node:readline/promises\";\nimport { stdin as input, stdout as output } from \"node:process\";\nimport type { ChatMessage, ChatProvider } from \"../providers/types\";\nimport type { EventSink } from \"../events/types\";\nimport { runAgent } from \"./runner\";\n\nexport async function startInteractiveChat(inputOptions: {\n provider: ChatProvider;\n cwd: string;\n sink: EventSink;\n}): Promise<void> {\n const rl = createInterface({ input, output });\n const history: ChatMessage[] = [];\n let activeAbortController: AbortController | null = null;\n output.write(`Tanya live chat (${inputOptions.provider.id}:${inputOptions.provider.model}). Type /exit to quit.\\n`);\n const handleSigint = () => {\n if (activeAbortController && !activeAbortController.signal.aborted) {\n output.write(\"\\nCancelling active tool...\\n\");\n activeAbortController.abort();\n return;\n }\n rl.close();\n process.exitCode = 130;\n };\n process.on(\"SIGINT\", handleSigint);\n\n try {\n while (true) {\n const prompt = (await rl.question(\"\\nYou: \")).trim();\n if (!prompt) continue;\n if (prompt === \"/exit\" || prompt === \"/quit\") break;\n\n const abortController = new AbortController();\n activeAbortController = abortController;\n const { message } = await runAgent({\n provider: inputOptions.provider,\n prompt,\n cwd: inputOptions.cwd,\n sink: inputOptions.sink,\n history,\n signal: abortController.signal,\n });\n activeAbortController = null;\n history.push({ role: \"user\", content: prompt });\n history.push({ role: \"assistant\", content: message });\n }\n } finally {\n process.off(\"SIGINT\", handleSigint);\n rl.close();\n }\n}\n","import type { EventSink } from \"../events/types\";\n\nconst toolGlyph = \">\";\n\nexport function createHumanSink(stream: NodeJS.WritableStream = process.stdout): EventSink {\n let inMessage = false;\n\n return (event) => {\n switch (event.type) {\n case \"status\":\n stream.write(`\\n${event.message}\\n`);\n break;\n case \"message_start\":\n inMessage = true;\n stream.write(\"\\nTania: \");\n break;\n case \"message_delta\":\n stream.write(event.text);\n break;\n case \"message_end\":\n if (inMessage) stream.write(\"\\n\");\n inMessage = false;\n break;\n case \"tool_call\":\n if (inMessage) stream.write(\"\\n\");\n inMessage = false;\n stream.write(`\\n${toolGlyph} ${event.tool}\\n`);\n stream.write(` input: ${JSON.stringify(event.input)}\\n`);\n break;\n case \"tool_result\":\n stream.write(` ${event.ok ? \"ok\" : \"error\"}: ${event.summary}\\n`);\n break;\n case \"tool_progress\":\n if (inMessage) stream.write(\"\\n\");\n inMessage = false;\n stream.write(` ${event.stream}: ${event.chunk}${event.chunk.endsWith(\"\\n\") ? \"\" : \"\\n\"}`);\n break;\n case \"tool_cancel_requested\":\n stream.write(` cancelling: ${event.tool ?? event.toolCallId}\\n`);\n break;\n case \"tool_cancelled\":\n stream.write(` cancelled: ${event.tool ?? event.toolCallId}\\n`);\n break;\n case \"final\":\n stream.write(`\\n${event.message.trim()}\\n`);\n if (event.files?.length) stream.write(`Files: ${event.files.join(\", \")}\\n`);\n break;\n case \"error\":\n stream.write(`\\nError: ${event.message}${event.detail ? `\\n${event.detail}` : \"\"}\\n`);\n break;\n default:\n break;\n }\n };\n}\n","import { existsSync } from \"node:fs\";\nimport { mkdir, readFile, readdir, rm, writeFile } from \"node:fs/promises\";\nimport { dirname, isAbsolute, join, resolve } from \"node:path\";\nimport { spawn, spawnSync } from \"node:child_process\";\nimport sharp from \"sharp\";\nimport { envValue } from \"../config/envCompat\";\nimport { resolveInsideWorkspace } from \"../safety/workspace\";\n\ntype LayerAnimation = \"fade-up\" | \"type-in\" | \"scale-in\" | \"hold\" | \"fade-in\" | \"slide-up\" | \"subtle-parallax\";\ntype SceneTransition = \"cut\" | \"crossfade\" | \"slide-left\" | \"slide-up\" | \"push\";\n\nexport interface FullAdRenderSpec {\n version: 1;\n canvas: {\n width: number;\n height: number;\n fps: number;\n safeArea?: { x: number; y: number; width: number; height: number };\n };\n project?: { id: string; name: string; appName: string; platform: string };\n brand?: {\n primary: string;\n secondary: string;\n accent: string;\n background: string;\n iconAssetId?: string;\n };\n assets: Array<{\n id: string;\n type: \"image\" | \"gif\" | \"video\";\n mimeType: string;\n src: string;\n width?: number;\n height?: number;\n durationMs?: number | null;\n }>;\n scenes: FullAdSceneSpec[];\n}\n\nexport interface FullAdSceneSpec {\n id: string;\n order: number;\n durationMs: number;\n backgroundPreset: string;\n backgroundAssetId?: string;\n layoutPreset?: string;\n transition: SceneTransition;\n layers: FullAdLayerSpec[];\n}\n\nexport type FullAdLayerSpec = FullAdTextLayerSpec | FullAdMediaLayerSpec;\n\nexport interface FullAdBaseLayerSpec {\n id: string;\n x: number;\n y: number;\n width: number;\n height: number;\n zIndex: number;\n startTimeMs: number;\n endTimeMs: number | null;\n opacity: number;\n}\n\nexport interface FullAdTextLayerSpec extends FullAdBaseLayerSpec {\n type: \"text\";\n text: string;\n role: \"title\" | \"subtitle\" | \"caption\" | \"cta\" | \"badge\";\n color: string;\n fontSize: number;\n fontWeight: number;\n align: \"center\";\n animation: LayerAnimation;\n}\n\nexport interface FullAdMediaLayerSpec extends FullAdBaseLayerSpec {\n type: \"image\" | \"video\";\n assetId: string;\n fit: \"cover\" | \"contain\" | \"fill\";\n borderRadius: number;\n shadow: boolean;\n animation: LayerAnimation;\n}\n\nexport interface RenderAdOptions {\n input: string;\n outputDir?: string;\n basename?: string;\n formats?: Array<\"mp4\" | \"poster\">;\n ffmpegPath?: string;\n}\n\nexport interface RenderAdResult {\n mp4Path?: string;\n posterPath?: string;\n durationMs: number;\n frameCount: number;\n width: number;\n height: number;\n warnings: string[];\n renderSpec: FullAdRenderSpec;\n}\n\ninterface MediaFrames {\n frames: Buffer[];\n fps: number;\n}\n\nfunction findExecutable(name: string, explicit?: string): string {\n if (explicit) return explicit;\n const result = spawnSync(\"which\", [name], { encoding: \"utf8\" });\n return result.status === 0 && result.stdout.trim() ? result.stdout.trim() : name;\n}\n\nfunction run(command: string, args: string[], cwd: string): void {\n const result = spawnSync(command, args, { cwd, stdio: \"pipe\", encoding: \"utf8\" });\n if (result.status !== 0) {\n throw new Error(`${command} ${args.join(\" \")}\\n${result.stderr || result.stdout}`);\n }\n}\n\nfunction easeOut(t: number): number {\n const v = Math.max(0, Math.min(1, t));\n return 1 - Math.pow(1 - v, 3);\n}\n\nconst SCENE_TRANSITION_DURATION_MS = 560;\nconst SCENE_TRANSITION_TRAVEL_PX = 52;\n\nfunction escapeXml(value: string): string {\n return value.replaceAll(\"&\", \"&\").replaceAll(\"<\", \"<\").replaceAll(\">\", \">\").replaceAll('\"', \""\");\n}\n\nfunction backgroundColor(preset: string): string {\n if (preset === \"solid-light\") return \"#f5f5f7\";\n if (preset === \"gradient-brand\") return \"#101628\";\n if (preset === \"gradient-dark\") return \"#10111d\";\n if (preset === \"blur-asset\") return \"#0a0a0c\";\n return \"#0a0a0c\";\n}\n\nfunction renderBrand(spec: FullAdRenderSpec): Required<NonNullable<FullAdRenderSpec[\"brand\"]>> {\n return {\n primary: spec.brand?.primary ?? \"#8C4CEB\",\n secondary: spec.brand?.secondary ?? \"#6B33CC\",\n accent: spec.brand?.accent ?? \"#F59E0B\",\n background: spec.brand?.background ?? \"#080A12\",\n iconAssetId: spec.brand?.iconAssetId ?? \"\",\n };\n}\n\nfunction backgroundSvg(spec: FullAdRenderSpec, scene: FullAdSceneSpec): Buffer {\n const { width, height } = spec.canvas;\n const brand = renderBrand(spec);\n const base = scene.backgroundPreset === \"gradient-brand\" ? brand.background : backgroundColor(scene.backgroundPreset);\n const brandGlow = scene.backgroundPreset === \"gradient-brand\" ? brand.primary : \"#4f8eff\";\n const secondaryGlow = scene.backgroundPreset === \"gradient-brand\" ? brand.secondary : brandGlow;\n const warmGlow = scene.backgroundPreset === \"gradient-brand\" ? brand.accent : \"#f59e0b\";\n const svg = `<svg width=\"${width}\" height=\"${height}\" xmlns=\"http://www.w3.org/2000/svg\">\n <defs>\n <radialGradient id=\"g1\" cx=\"28%\" cy=\"12%\" r=\"64%\">\n <stop offset=\"0%\" stop-color=\"${brandGlow}\" stop-opacity=\"0.34\"/>\n <stop offset=\"54%\" stop-color=\"${brandGlow}\" stop-opacity=\"0.08\"/>\n <stop offset=\"100%\" stop-color=\"${base}\" stop-opacity=\"0\"/>\n </radialGradient>\n <radialGradient id=\"g2\" cx=\"88%\" cy=\"86%\" r=\"54%\">\n <stop offset=\"0%\" stop-color=\"${warmGlow}\" stop-opacity=\"0.18\"/>\n <stop offset=\"100%\" stop-color=\"${base}\" stop-opacity=\"0\"/>\n </radialGradient>\n <radialGradient id=\"g3\" cx=\"50%\" cy=\"42%\" r=\"58%\">\n <stop offset=\"0%\" stop-color=\"${secondaryGlow}\" stop-opacity=\"${scene.backgroundPreset === \"gradient-brand\" ? \"0.2\" : \"0.06\"}\"/>\n <stop offset=\"100%\" stop-color=\"${base}\" stop-opacity=\"0\"/>\n </radialGradient>\n <linearGradient id=\"v\" x1=\"0\" y1=\"0\" x2=\"0\" y2=\"1\">\n <stop offset=\"0%\" stop-color=\"#ffffff\" stop-opacity=\"0.04\"/>\n <stop offset=\"46%\" stop-color=\"#000000\" stop-opacity=\"0\"/>\n <stop offset=\"100%\" stop-color=\"#000000\" stop-opacity=\"0.28\"/>\n </linearGradient>\n </defs>\n <rect width=\"100%\" height=\"100%\" fill=\"${base}\"/>\n <rect width=\"100%\" height=\"100%\" fill=\"url(#g1)\"/>\n <rect width=\"100%\" height=\"100%\" fill=\"url(#g2)\"/>\n <rect width=\"100%\" height=\"100%\" fill=\"url(#g3)\"/>\n <rect width=\"100%\" height=\"100%\" fill=\"url(#v)\"/>\n </svg>`;\n return Buffer.from(svg);\n}\n\nfunction resolveAssetPath(src: string, workspace: string): string {\n if (src.startsWith(\"file://\")) return new URL(src).pathname;\n if (isAbsolute(src)) return src;\n return resolveInsideWorkspace(workspace, src);\n}\n\nasync function loadStaticFrame(src: string, workspace: string): Promise<Buffer> {\n if (src.startsWith(\"data:\")) {\n return Buffer.from(src.split(\",\")[1] ?? \"\", \"base64\");\n }\n if (src.startsWith(\"http://\") || src.startsWith(\"https://\")) {\n const response = await fetch(src);\n if (!response.ok) throw new Error(`Unable to fetch asset ${src}: ${response.status}`);\n return Buffer.from(await response.arrayBuffer());\n }\n return readFile(resolveAssetPath(src, workspace));\n}\n\nasync function extractVideoFrames(params: {\n src: string;\n workspace: string;\n outDir: string;\n fps: number;\n ffmpegPath: string;\n}): Promise<Buffer[]> {\n await mkdir(params.outDir, { recursive: true });\n const input = resolveAssetPath(params.src, params.workspace);\n run(params.ffmpegPath, [\n \"-y\",\n \"-i\",\n input,\n \"-vf\",\n `fps=${params.fps}`,\n join(params.outDir, \"frame-%05d.png\"),\n ], params.workspace);\n const files = (await readdir(params.outDir)).filter((file) => file.endsWith(\".png\")).sort();\n return Promise.all(files.map((file) => readFile(join(params.outDir, file))));\n}\n\nasync function buildMediaFrames(spec: FullAdRenderSpec, workspace: string, tmpDir: string, ffmpegPath: string, warnings: string[]): Promise<Map<string, MediaFrames>> {\n const media = new Map<string, MediaFrames>();\n for (const asset of spec.assets) {\n try {\n if (asset.type === \"video\" || asset.type === \"gif\") {\n const frames = await extractVideoFrames({\n src: asset.src,\n workspace,\n outDir: join(tmpDir, \"media\", asset.id),\n fps: spec.canvas.fps,\n ffmpegPath,\n });\n media.set(asset.id, { frames: frames.length ? frames : [await sharp(await loadStaticFrame(asset.src, workspace)).png().toBuffer()], fps: spec.canvas.fps });\n } else {\n media.set(asset.id, { frames: [await sharp(await loadStaticFrame(asset.src, workspace)).png().toBuffer()], fps: 1 });\n }\n } catch (error) {\n warnings.push(`Asset ${asset.id} could not be decoded: ${error instanceof Error ? error.message : String(error)}`);\n }\n }\n return media;\n}\n\nfunction wrapText(text: string, maxChars: number, maxLines = 4): string[] {\n const words = text.trim().split(/\\s+/).filter(Boolean);\n const lines: string[] = [];\n let current = \"\";\n for (const word of words) {\n const next = current ? `${current} ${word}` : word;\n if (next.length > maxChars && current) {\n lines.push(current);\n current = word;\n } else {\n current = next;\n }\n }\n if (current) lines.push(current);\n return lines.slice(0, maxLines);\n}\n\nfunction renderTextSvg(layer: FullAdTextLayerSpec, progress: number, brand?: FullAdRenderSpec[\"brand\"]): Buffer {\n const resolvedBrand = {\n primary: brand?.primary ?? \"#8C4CEB\",\n secondary: brand?.secondary ?? \"#6B33CC\",\n accent: brand?.accent ?? \"#F59E0B\",\n };\n const visibleChars = layer.animation === \"type-in\"\n ? Math.max(1, Math.ceil(layer.text.length * easeOut(progress)))\n : layer.text.length;\n const text = layer.text.slice(0, visibleChars);\n const maxChars = Math.max(8, Math.floor(layer.width / Math.max(12, layer.fontSize * 0.55)));\n const maxLines = layer.role === \"badge\" ? 6 : 4;\n const lines = wrapText(text, maxChars, maxLines);\n const fontSize = Math.max(24, Math.min(layer.fontSize, Math.floor(layer.height / Math.max(1.4, lines.length * 1.18))));\n const lineHeight = Math.round(fontSize * 1.16);\n const startY = Math.round((layer.height - lineHeight * lines.length) / 2 + fontSize * 0.88);\n const tspans = lines.map((line, index) =>\n `<tspan x=\"50%\" y=\"${startY + index * lineHeight}\">${escapeXml(line)}</tspan>`,\n ).join(\"\");\n const glowOpacity = layer.role === \"title\" || layer.role === \"cta\" ? 0.28 : 0.12;\n const chrome = layer.role === \"cta\"\n ? `<linearGradient id=\"ctaFill\" x1=\"0\" y1=\"0\" x2=\"1\" y2=\"1\">\n <stop offset=\"0%\" stop-color=\"${resolvedBrand.primary}\"/>\n <stop offset=\"100%\" stop-color=\"${resolvedBrand.secondary}\"/>\n </linearGradient>`\n : layer.role === \"badge\" || layer.role === \"caption\"\n ? `<linearGradient id=\"badgeFill\" x1=\"0\" y1=\"0\" x2=\"1\" y2=\"0\">\n <stop offset=\"0%\" stop-color=\"${resolvedBrand.accent}\" stop-opacity=\"0.2\"/>\n <stop offset=\"100%\" stop-color=\"${resolvedBrand.primary}\" stop-opacity=\"0.14\"/>\n </linearGradient>`\n : \"\";\n const rect = layer.role === \"cta\"\n ? `<rect x=\"2\" y=\"2\" width=\"${Math.round(layer.width) - 4}\" height=\"${Math.round(layer.height) - 4}\" rx=\"${Math.round(layer.height / 2)}\" fill=\"url(#ctaFill)\" stroke=\"rgba(255,255,255,0.22)\" stroke-width=\"2\"/>`\n : layer.role === \"badge\" || layer.role === \"caption\"\n ? `<rect x=\"2\" y=\"6\" width=\"${Math.round(layer.width) - 4}\" height=\"${Math.round(layer.height) - 12}\" rx=\"${Math.round((layer.height - 12) / 2)}\" fill=\"url(#badgeFill)\" stroke=\"${resolvedBrand.accent}\" stroke-opacity=\"0.34\" stroke-width=\"1.5\"/>`\n : \"\";\n const svg = `<svg width=\"${Math.round(layer.width)}\" height=\"${Math.round(layer.height)}\" xmlns=\"http://www.w3.org/2000/svg\">\n <defs>\n ${chrome}\n <filter id=\"softShadow\" x=\"-20%\" y=\"-20%\" width=\"140%\" height=\"160%\">\n <feDropShadow dx=\"0\" dy=\"10\" stdDeviation=\"10\" flood-color=\"#000000\" flood-opacity=\"${glowOpacity}\"/>\n </filter>\n </defs>\n ${rect}\n <text text-anchor=\"middle\" font-family=\"-apple-system, BlinkMacSystemFont, Inter, Helvetica, Arial, sans-serif\"\n font-size=\"${fontSize}\" font-weight=\"${layer.fontWeight}\" fill=\"${escapeXml(layer.color)}\" filter=\"url(#softShadow)\">${tspans}</text>\n </svg>`;\n return Buffer.from(svg);\n}\n\nasync function roundedMask(width: number, height: number, radius: number): Promise<Buffer> {\n const r = Math.max(0, Math.min(radius, Math.floor(Math.min(width, height) / 2)));\n return Buffer.from(`<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"${width}\" height=\"${height}\"><rect width=\"${width}\" height=\"${height}\" rx=\"${r}\" fill=\"#fff\"/></svg>`);\n}\n\nasync function renderMediaLayer(layer: FullAdMediaLayerSpec, frame: Buffer): Promise<Buffer> {\n const width = Math.max(1, Math.round(layer.width));\n const height = Math.max(1, Math.round(layer.height));\n const resized = sharp(frame)\n .resize(width, height, {\n fit: layer.fit === \"contain\" ? \"inside\" : layer.fit === \"fill\" ? \"fill\" : \"cover\",\n position: \"center\",\n background: { r: 0, g: 0, b: 0, alpha: 0 },\n })\n .ensureAlpha();\n const png = await resized.png().toBuffer();\n if (!layer.borderRadius) return png;\n return sharp(png).composite([{ input: await roundedMask(width, height, layer.borderRadius), blend: \"dest-in\" }]).png().toBuffer();\n}\n\nasync function shadowLayer(width: number, height: number, radius: number): Promise<Buffer> {\n const mask = await roundedMask(width, height, radius);\n return sharp({\n create: {\n width,\n height,\n channels: 4,\n background: { r: 0, g: 0, b: 0, alpha: 0.52 },\n },\n })\n .composite([{ input: mask, blend: \"dest-in\" }])\n .blur(18)\n .extend({ top: 24, bottom: 24, left: 24, right: 24, background: { r: 0, g: 0, b: 0, alpha: 0 } })\n .png()\n .toBuffer();\n}\n\nasync function scaleOverlay(input: Buffer, scale: number): Promise<{ input: Buffer; dx: number; dy: number }> {\n if (Math.abs(scale - 1) < 0.001) return { input, dx: 0, dy: 0 };\n const meta = await sharp(input).metadata();\n const width = Math.max(1, Math.round((meta.width ?? 1) * scale));\n const height = Math.max(1, Math.round((meta.height ?? 1) * scale));\n return {\n input: await sharp(input).resize(width, height).png().toBuffer(),\n dx: Math.round(((meta.width ?? width) - width) / 2),\n dy: Math.round(((meta.height ?? height) - height) / 2),\n };\n}\n\nfunction layerTransform(layer: FullAdLayerSpec, localMs: number): { opacity: number; dx: number; dy: number; scale: number } {\n const progress = easeOut((localMs - layer.startTimeMs) / 360);\n const baseOpacity = layer.opacity ?? 1;\n if (layer.animation === \"hold\") return { opacity: baseOpacity, dx: 0, dy: 0, scale: 1 };\n if (layer.animation === \"fade-up\" || layer.animation === \"slide-up\") {\n return { opacity: baseOpacity * progress, dx: 0, dy: (1 - progress) * 34, scale: 1 };\n }\n if (layer.animation === \"scale-in\") {\n return { opacity: baseOpacity * progress, dx: 0, dy: 0, scale: 0.965 + progress * 0.035 };\n }\n if (layer.animation === \"subtle-parallax\") {\n return { opacity: baseOpacity * progress, dx: 0, dy: Math.sin(localMs / 1000) * 8, scale: 1.02 };\n }\n return { opacity: baseOpacity * progress, dx: 0, dy: 0, scale: 1 };\n}\n\nfunction sceneTransform(scene: FullAdSceneSpec, localMs: number): { opacity: number; dx: number; dy: number; scale: number } {\n const progress = easeOut(localMs / SCENE_TRANSITION_DURATION_MS);\n if (scene.transition === \"cut\") return { opacity: 1, dx: 0, dy: 0, scale: 1 };\n if (scene.transition === \"slide-left\" || scene.transition === \"push\") return { opacity: 1, dx: (1 - progress) * SCENE_TRANSITION_TRAVEL_PX, dy: 0, scale: 1 };\n if (scene.transition === \"slide-up\") return { opacity: 1, dx: 0, dy: (1 - progress) * SCENE_TRANSITION_TRAVEL_PX, scale: 1 };\n return { opacity: progress, dx: 0, dy: 0, scale: 1 };\n}\n\nasync function renderFrame(spec: FullAdRenderSpec, scene: FullAdSceneSpec, mediaFrames: Map<string, MediaFrames>, frameInScene: number): Promise<Buffer> {\n const fps = spec.canvas.fps;\n const localMs = (frameInScene / fps) * 1000;\n const sceneFx = sceneTransform(scene, localMs);\n const overlays: sharp.OverlayOptions[] = [];\n const sorted = [...scene.layers].sort((a, b) => a.zIndex - b.zIndex);\n for (const layer of sorted) {\n const end = layer.endTimeMs ?? scene.durationMs;\n if (localMs < layer.startTimeMs || localMs >= end) continue;\n const fx = layerTransform(layer, localMs);\n const opacity = Math.max(0, Math.min(1, fx.opacity * sceneFx.opacity));\n if (opacity <= 0.001) continue;\n if (layer.type === \"text\") {\n let textPng = await sharp(renderTextSvg(layer, (localMs - layer.startTimeMs) / 520, spec.brand)).png().toBuffer();\n const scaled = await scaleOverlay(textPng, fx.scale * sceneFx.scale);\n textPng = scaled.input;\n if (opacity < 0.999) textPng = await sharp(textPng).linear(opacity, 0).png().toBuffer();\n overlays.push({\n input: textPng,\n left: Math.round(layer.x + fx.dx + sceneFx.dx + scaled.dx),\n top: Math.round(layer.y + fx.dy + sceneFx.dy + scaled.dy),\n });\n continue;\n }\n const frames = mediaFrames.get(layer.assetId);\n if (!frames?.frames.length) continue;\n const elapsed = Math.max(0, localMs - layer.startTimeMs);\n const sourceIndex = frames.frames.length === 1\n ? 0\n : Math.floor((elapsed / 1000) * frames.fps) % frames.frames.length;\n let mediaPng = await renderMediaLayer(layer, frames.frames[sourceIndex]!);\n const scaled = await scaleOverlay(mediaPng, fx.scale * sceneFx.scale);\n mediaPng = scaled.input;\n if (opacity < 0.999) mediaPng = await sharp(mediaPng).linear(opacity, 0).png().toBuffer();\n if (layer.shadow) {\n const shadow = await shadowLayer(Math.round(layer.width), Math.round(layer.height), layer.borderRadius);\n const scaledShadow = await scaleOverlay(shadow, fx.scale * sceneFx.scale);\n overlays.push({\n input: scaledShadow.input,\n left: Math.round(layer.x + fx.dx + sceneFx.dx + scaled.dx - 24 + scaledShadow.dx),\n top: Math.round(layer.y + fx.dy + sceneFx.dy + scaled.dy - 2 + scaledShadow.dy),\n });\n }\n overlays.push({\n input: mediaPng,\n left: Math.round(layer.x + fx.dx + sceneFx.dx + scaled.dx),\n top: Math.round(layer.y + fx.dy + sceneFx.dy + scaled.dy),\n });\n }\n\n const backgroundFrame = scene.backgroundAssetId ? mediaFrames.get(scene.backgroundAssetId)?.frames[0] : null;\n let image = backgroundFrame\n ? sharp(backgroundFrame).resize(spec.canvas.width, spec.canvas.height, { fit: \"cover\" })\n : sharp(backgroundSvg(spec, scene));\n if (overlays.length) image = image.composite(overlays);\n return image.png({ compressionLevel: 1 }).toBuffer();\n}\n\nfunction parseSpec(value: unknown): FullAdRenderSpec {\n const spec = value as FullAdRenderSpec;\n if (!spec || spec.version !== 1 || !spec.canvas || !Array.isArray(spec.scenes) || !Array.isArray(spec.assets)) {\n throw new Error(\"Invalid full-ad render spec.\");\n }\n if (spec.canvas.width !== 1080 || spec.canvas.height !== 1920) {\n throw new Error(\"Full-ad render spec must use a 1080x1920 canvas.\");\n }\n if (!Number.isFinite(spec.canvas.fps) || spec.canvas.fps < 1 || spec.canvas.fps > 60) {\n throw new Error(\"Full-ad render spec fps must be between 1 and 60.\");\n }\n return spec;\n}\n\nexport async function renderFullAd(options: RenderAdOptions, workspace: string): Promise<RenderAdResult> {\n const inputPath = isAbsolute(options.input) ? options.input : resolveInsideWorkspace(workspace, options.input);\n const spec = parseSpec(JSON.parse(await readFile(inputPath, \"utf8\")));\n const outputDir = resolveInsideWorkspace(workspace, options.outputDir ?? \"tanya-video-ads\");\n const basename = (options.basename ?? `full-ad-${Date.now()}`).replace(/[^a-zA-Z0-9._-]+/g, \"-\");\n const formats = options.formats?.length ? options.formats : [\"mp4\", \"poster\"];\n const ffmpegPath = findExecutable(\"ffmpeg\", options.ffmpegPath ?? envValue({}, \"TANYA_FFMPEG_PATH\"));\n const tmpRoot = resolveInsideWorkspace(workspace, \".tania/tmp\");\n const tmpDir = await fsMkdtemp(join(tmpRoot, \"tanya-render-ad-\"));\n const frameDir = join(tmpDir, \"frames\");\n const warnings: string[] = [];\n await mkdir(frameDir, { recursive: true });\n await mkdir(outputDir, { recursive: true });\n const mediaFrames = await buildMediaFrames(spec, workspace, tmpDir, ffmpegPath, warnings);\n\n let frameIndex = 0;\n const scenes = [...spec.scenes].sort((a, b) => a.order - b.order);\n for (const scene of scenes) {\n const frameCount = Math.max(1, Math.round((scene.durationMs / 1000) * spec.canvas.fps));\n for (let i = 0; i < frameCount; i += 1) {\n const frame = await renderFrame(spec, scene, mediaFrames, i);\n await writeFile(\n join(frameDir, `frame_${String(frameIndex).padStart(6, \"0\")}.jpg`),\n await sharp(frame).jpeg({ quality: 84, mozjpeg: true }).toBuffer(),\n );\n frameIndex += 1;\n }\n }\n\n const result: RenderAdResult = {\n durationMs: scenes.reduce((sum, scene) => sum + scene.durationMs, 0),\n frameCount: frameIndex,\n width: spec.canvas.width,\n height: spec.canvas.height,\n warnings,\n renderSpec: spec,\n };\n\n if (formats.includes(\"poster\")) {\n const posterPath = join(outputDir, `${basename}-poster.png`);\n await sharp(await readFile(join(frameDir, \"frame_000000.jpg\"))).png().toFile(posterPath);\n result.posterPath = posterPath;\n }\n\n if (formats.includes(\"mp4\")) {\n const mp4Path = join(outputDir, `${basename}.mp4`);\n run(ffmpegPath, [\n \"-y\",\n \"-framerate\",\n String(spec.canvas.fps),\n \"-i\",\n join(frameDir, \"frame_%06d.jpg\"),\n \"-c:v\",\n \"libx264\",\n \"-pix_fmt\",\n \"yuv420p\",\n \"-preset\",\n \"fast\",\n \"-crf\",\n \"23\",\n \"-movflags\",\n \"+faststart\",\n mp4Path,\n ], workspace);\n result.mp4Path = mp4Path;\n }\n\n await rm(tmpDir, { recursive: true, force: true }).catch(() => {});\n return result;\n}\n\nasync function fsMkdtemp(prefix: string): Promise<string> {\n const { mkdtemp } = await import(\"node:fs/promises\");\n await mkdir(dirname(prefix), { recursive: true });\n return mkdtemp(prefix);\n}\n","export type GoldenTaskProfile = {\n id: string;\n title: string;\n platform: \"ios\" | \"android\" | \"backend\" | \"cross-platform\";\n purpose: string;\n requiredCapabilities: string[];\n};\n\nexport const GENERIC_BENCHMARK_PROFILES: GoldenTaskProfile[] = [\n {\n id: \"tanya.low.search-replace\",\n title: \"Low - Targeted Search Replace\",\n platform: \"cross-platform\",\n purpose: \"Update one existing source file with a precise replacement and verify the marker.\",\n requiredCapabilities: [\"read before edit\", \"search_replace\", \"bounded verification\"],\n },\n {\n id: \"tanya.low.new-helper\",\n title: \"Low - New Helper File\",\n platform: \"cross-platform\",\n purpose: \"Create a small helper module and verify it exists with expected content.\",\n requiredCapabilities: [\"write_file\", \"final report\", \"bounded verification\"],\n },\n {\n id: \"tanya.low.config-update\",\n title: \"Low - Config Update\",\n platform: \"cross-platform\",\n purpose: \"Update a simple JSON-like config file without touching unrelated files.\",\n requiredCapabilities: [\"targeted edit\", \"changed-file reporting\", \"bounded verification\"],\n },\n {\n id: \"tanya.low.readme-update\",\n title: \"Low - README Update\",\n platform: \"cross-platform\",\n purpose: \"Append a concise documentation note and verify the note is present.\",\n requiredCapabilities: [\"documentation edit\", \"artifact reuse none\", \"bounded verification\"],\n },\n {\n id: \"tanya.low.package-script\",\n title: \"Low - Package Script\",\n platform: \"cross-platform\",\n purpose: \"Add a package script while preserving existing package metadata.\",\n requiredCapabilities: [\"JSON edit\", \"package script reporting\", \"bounded verification\"],\n },\n {\n id: \"tanya.medium.service-module\",\n title: \"Medium - Service Module\",\n platform: \"cross-platform\",\n purpose: \"Create a service module and matching index export in a small multi-file change.\",\n requiredCapabilities: [\"multi-file edit\", \"verification\", \"complete report\"],\n },\n {\n id: \"tanya.medium.test-harness\",\n title: \"Medium - Test Harness\",\n platform: \"cross-platform\",\n purpose: \"Add a tiny executable test harness and verify it runs.\",\n requiredCapabilities: [\"test file creation\", \"run_command\", \"complete report\"],\n },\n {\n id: \"tanya.medium.artifact-component\",\n title: \"Medium - Artifact Component\",\n platform: \"cross-platform\",\n purpose: \"Read a reusable UI artifact and adapt it into a project component.\",\n requiredCapabilities: [\"artifact read\", \"artifact provenance\", \"multi-file report\"],\n },\n {\n id: \"tanya.medium.artifact-service\",\n title: \"Medium - Artifact Service\",\n platform: \"backend\",\n purpose: \"Read a reusable service artifact and adapt it into a project helper.\",\n requiredCapabilities: [\"artifact read\", \"artifact provenance\", \"bounded verification\"],\n },\n {\n id: \"tanya.medium.dirty-worktree\",\n title: \"Medium - Dirty Worktree\",\n platform: \"cross-platform\",\n purpose: \"Complete a task in a repo that already has unrelated uncommitted changes.\",\n requiredCapabilities: [\"git snapshot\", \"unrelated dirty preservation\", \"final report\"],\n },\n {\n id: \"tanya.medium.report-repair\",\n title: \"Medium - Report Repair\",\n platform: \"cross-platform\",\n purpose: \"Recover when the model initially omits the required coding final report.\",\n requiredCapabilities: [\"final report reminder\", \"repair loop\", \"verification preservation\"],\n },\n {\n id: \"tanya.medium.multi-file\",\n title: \"Medium - Multi-File Feature\",\n platform: \"cross-platform\",\n purpose: \"Create coordinated source and docs changes and verify both outputs.\",\n requiredCapabilities: [\"multi-file edit\", \"changed-file reporting\", \"bounded verification\"],\n },\n {\n id: \"tanya.medium.package-manager\",\n title: \"Medium - Package Manager Script\",\n platform: \"cross-platform\",\n purpose: \"Use a workspace script path that also exercises post-check package-manager detection.\",\n requiredCapabilities: [\"package metadata\", \"script verification\", \"post-check readiness\"],\n },\n {\n id: \"tanya.medium.context-aware\",\n title: \"Medium - Context-Aware Edit\",\n platform: \"cross-platform\",\n purpose: \"Read caller context before editing and preserve that provenance in the run.\",\n requiredCapabilities: [\"context read\", \"context provenance\", \"complete report\"],\n },\n {\n id: \"tanya.medium.existing-tests\",\n title: \"Medium - Existing Tests\",\n platform: \"cross-platform\",\n purpose: \"Modify implementation while running an existing local verification script.\",\n requiredCapabilities: [\"existing test command\", \"verification reporting\", \"changed-file reporting\"],\n },\n {\n id: \"tanya.medium.dependency-install\",\n title: \"Medium - Dependency Install\",\n platform: \"cross-platform\",\n purpose: \"Update package metadata and lockfile-style state while verifying dependency intent without network access.\",\n requiredCapabilities: [\"package manifest update\", \"lockfile update\", \"bounded verification\"],\n },\n {\n id: \"tanya.medium.framework-migration\",\n title: \"Medium - Framework Migration\",\n platform: \"cross-platform\",\n purpose: \"Move a small legacy page into an app-router-style layout while preserving a compatibility entrypoint.\",\n requiredCapabilities: [\"framework convention\", \"multi-file migration\", \"changed-file reporting\"],\n },\n {\n id: \"tanya.medium.failing-test-repair\",\n title: \"Medium - Failing Test Repair\",\n platform: \"cross-platform\",\n purpose: \"Observe a failing verification, repair the implementation, and rerun the same check successfully.\",\n requiredCapabilities: [\"failed verification recovery\", \"targeted edit\", \"verification rerun\"],\n },\n {\n id: \"tanya.medium.frontend-smoke\",\n title: \"Medium - Frontend Smoke\",\n platform: \"cross-platform\",\n purpose: \"Create a minimal component, styles, and smoke check that verifies rendered content markers.\",\n requiredCapabilities: [\"frontend files\", \"visual smoke proxy\", \"bounded verification\"],\n },\n {\n id: \"tanya.medium.run-log-history\",\n title: \"Medium - Usage Metrics Run Log\",\n platform: \"cross-platform\",\n purpose: \"Complete a normal edit while emitting usage counts that should be persisted to .tania/runs.\",\n requiredCapabilities: [\"usage metrics\", \"run log persistence\", \"history visibility\"],\n },\n {\n id: \"tanya.medium.streaming-long-tool\",\n title: \"Medium - Streaming Long Tool\",\n platform: \"cross-platform\",\n purpose: \"Run a >10s shell verification that streams progress while preserving the final tool result contract.\",\n requiredCapabilities: [\"tool_progress\", \"long-running run_shell\", \"provider-history isolation\"],\n },\n];\n\nexport const BUILT_IN_GOLDEN_TASK_PROFILES: GoldenTaskProfile[] = [\n {\n id: \"cosmohq.ios.setup-environment\",\n title: \"Setup Environment - iOS\",\n platform: \"ios\",\n purpose: \"Verify Fastlane/SwiftLint/project setup without false artifact or changed-file failures.\",\n requiredCapabilities: [\"artifact provenance\", \"xcodebuild verification\", \"commit reporting\"],\n },\n {\n id: \"cosmohq.android.setup-environment\",\n title: \"Setup Environment - Android\",\n platform: \"android\",\n purpose: \"Verify Gradle/Fastlane setup while preserving local SDK boundaries.\",\n requiredCapabilities: [\"Gradle verification\", \"local.properties protection\", \"commit reporting\"],\n },\n {\n id: \"cosmohq.ios.foundation\",\n title: \"Fundações - iOS\",\n platform: \"ios\",\n purpose: \"Create theme, SwiftData models, navigation, base UI states, and dark-mode support.\",\n requiredCapabilities: [\"iOS foundation validator\", \"artifact mapping\", \"font fallback policy\", \"xcodebuild verification\"],\n },\n {\n id: \"cosmohq.android.foundation\",\n title: \"Fundações - Android\",\n platform: \"android\",\n purpose: \"Create/preserve Material 3 theme, Room, Navigation Compose, and base composables.\",\n requiredCapabilities: [\"create_android_foundation\", \"preserve existing files\", \"ktlint/Gradle verification\"],\n },\n {\n id: \"cosmohq.ios.splash\",\n title: \"Splash Screen - iOS\",\n platform: \"ios\",\n purpose: \"Create a brand-compliant splash screen and SplashIcon asset without over-scoping other iOS foundation validators.\",\n requiredCapabilities: [\"create_ios_splash\", \"iOS splash validator\", \"artifact provenance\"],\n },\n {\n id: \"cosmohq.android.splash\",\n title: \"Splash Screen - Android\",\n platform: \"android\",\n purpose: \"Create or verify native AndroidX splash resources and Compose runtime splash.\",\n requiredCapabilities: [\"Android splash validator\", \"zero-change verification reporting\", \"Gradle verification\"],\n },\n {\n id: \"cosmohq.apple.app-icon\",\n title: \"App Icon - Apple\",\n platform: \"ios\",\n purpose: \"Generate iOS/iPad/macOS AppIcon slots and verify Contents.json programmatically.\",\n requiredCapabilities: [\"create_apple_app_icon_set\", \"programmatic Contents.json parse\", \"asset validation\"],\n },\n {\n id: \"cosmohq.backend.api-foundation\",\n title: \"Backend API Foundation\",\n platform: \"backend\",\n purpose: \"Implement backend API contracts while keeping brand/api_features route parity.\",\n requiredCapabilities: [\"API contract validation\", \"Prisma validation\", \"typecheck/test verification\"],\n },\n ...GENERIC_BENCHMARK_PROFILES,\n];\n","import { execFile } from \"node:child_process\";\nimport { mkdtemp, mkdir, writeFile } from \"node:fs/promises\";\nimport { tmpdir } from \"node:os\";\nimport { join } from \"node:path\";\nimport { promisify } from \"node:util\";\nimport { runAgent } from \"../agent/runner\";\nimport type { TanyaRunContext } from \"../context/runContext\";\nimport type { TanyaEvent } from \"../events/types\";\nimport type { ChatDelta, ChatProvider, ChatRequest, ToolCall } from \"../providers/types\";\nimport { BUILT_IN_GOLDEN_TASK_PROFILES, type GoldenTaskProfile } from \"./profiles\";\n\ntype GoldenTaskFixture = {\n workspace: string;\n prompt: string;\n runContext: TanyaRunContext;\n provider: ChatProvider;\n};\n\ntype GenericBenchmarkSpec = {\n id: string;\n targetFiles: Array<{ path: string; content: string }>;\n prompt: string;\n preFiles?: Array<{ path: string; content: string }>;\n useArtifact?: boolean;\n useContext?: boolean;\n useSearchReplace?: boolean;\n dirtyWorktree?: boolean;\n reportRepair?: boolean;\n preVerifyBeforeEdit?: boolean;\n usage?: { promptTokens: number; completionTokens: number };\n};\n\nexport type GoldenRunResult = {\n profile: GoldenTaskProfile;\n workspace: string;\n passed: boolean;\n finalText: string;\n problems: string[];\n};\n\nfunction toolCall(id: string, name: string, args: unknown): ToolCall {\n return {\n id,\n type: \"function\",\n function: {\n name,\n arguments: JSON.stringify(args),\n },\n };\n}\n\nfunction scriptedProvider(id: string, turns: ChatDelta[]): ChatProvider & { requests: ChatRequest[] } {\n const requests: ChatRequest[] = [];\n return {\n id: `golden:${id}`,\n model: \"scripted\",\n requests,\n async *streamChat(input: ChatRequest) {\n requests.push({ ...input, messages: [...input.messages] });\n yield turns[Math.min(requests.length - 1, turns.length - 1)] ?? { content: \"\" };\n },\n };\n}\n\nconst execFileAsync = promisify(execFile);\n\nasync function createBaseWorkspace(profileId: string): Promise<string> {\n return mkdtemp(join(tmpdir(), `tanya-golden-${profileId.replace(/[^a-z0-9]+/gi, \"-\")}-`));\n}\n\nconst GENERIC_BENCHMARK_SPECS: Record<string, GenericBenchmarkSpec> = {\n \"tanya.low.search-replace\": {\n id: \"tanya.low.search-replace\",\n prompt: \"Replace the pending marker in an existing helper and verify it.\",\n useSearchReplace: true,\n targetFiles: [{ path: \"src/searchReplaceTarget.ts\", content: \"export const status = 'search-replace-ready';\\n\" }],\n },\n \"tanya.low.new-helper\": {\n id: \"tanya.low.new-helper\",\n prompt: \"Create a small helper file and verify it.\",\n targetFiles: [{ path: \"src/newHelper.ts\", content: \"export function newHelper() { return 'new-helper-ready'; }\\n\" }],\n },\n \"tanya.low.config-update\": {\n id: \"tanya.low.config-update\",\n prompt: \"Update a small config file with the requested marker.\",\n useSearchReplace: true,\n targetFiles: [{ path: \"config/settings.json\", content: \"{\\n \\\"mode\\\": \\\"config-update-ready\\\"\\n}\\n\" }],\n },\n \"tanya.low.readme-update\": {\n id: \"tanya.low.readme-update\",\n prompt: \"Append the benchmark readiness note to the README.\",\n useSearchReplace: true,\n targetFiles: [{ path: \"README.md\", content: \"# Demo\\n\\nBenchmark note: readme-update-ready\\n\" }],\n },\n \"tanya.low.package-script\": {\n id: \"tanya.low.package-script\",\n prompt: \"Add a benchmark package script while preserving package metadata.\",\n targetFiles: [{ path: \"package.json\", content: \"{\\n \\\"name\\\": \\\"benchmark-fixture\\\",\\n \\\"scripts\\\": {\\n \\\"benchmark:ok\\\": \\\"node scripts/check.js\\\"\\n },\\n \\\"marker\\\": \\\"package-script-ready\\\"\\n}\\n\" }],\n },\n \"tanya.medium.service-module\": {\n id: \"tanya.medium.service-module\",\n prompt: \"Create a service module and export it from the index.\",\n targetFiles: [\n { path: \"src/services/taskService.ts\", content: \"export function taskService() { return 'service-module-ready'; }\\n\" },\n { path: \"src/index.ts\", content: \"export { taskService } from './services/taskService';\\n\" },\n ],\n },\n \"tanya.medium.test-harness\": {\n id: \"tanya.medium.test-harness\",\n prompt: \"Add a tiny executable test harness and verify it runs.\",\n targetFiles: [\n { path: \"src/harness.js\", content: \"module.exports = () => 'test-harness-ready';\\n\" },\n { path: \"test/harness.test.js\", content: \"const run = require('../src/harness'); if (run() !== 'test-harness-ready') process.exit(1);\\n\" },\n ],\n },\n \"tanya.medium.artifact-component\": {\n id: \"tanya.medium.artifact-component\",\n prompt: \"Adapt the reusable component artifact into the project.\",\n useArtifact: true,\n targetFiles: [{ path: \"src/components/BenchmarkCard.tsx\", content: \"export function BenchmarkCard() { return 'artifact-component-ready'; }\\n\" }],\n },\n \"tanya.medium.artifact-service\": {\n id: \"tanya.medium.artifact-service\",\n prompt: \"Adapt the reusable service artifact into the project.\",\n useArtifact: true,\n targetFiles: [{ path: \"src/services/artifactService.ts\", content: \"export function artifactService() { return 'artifact-service-ready'; }\\n\" }],\n },\n \"tanya.medium.dirty-worktree\": {\n id: \"tanya.medium.dirty-worktree\",\n prompt: \"Complete the task while preserving an unrelated dirty file.\",\n dirtyWorktree: true,\n targetFiles: [{ path: \"src/dirtyTask.ts\", content: \"export const dirtyTask = 'dirty-worktree-ready';\\n\" }],\n },\n \"tanya.medium.report-repair\": {\n id: \"tanya.medium.report-repair\",\n prompt: \"Complete the task and recover if the first final response omits the required report.\",\n reportRepair: true,\n targetFiles: [{ path: \"src/reportRepair.ts\", content: \"export const reportRepair = 'report-repair-ready';\\n\" }],\n },\n \"tanya.medium.multi-file\": {\n id: \"tanya.medium.multi-file\",\n prompt: \"Create a coordinated source and documentation update.\",\n targetFiles: [\n { path: \"src/multiFile.ts\", content: \"export const multiFile = 'multi-file-ready';\\n\" },\n { path: \"docs/multi-file.md\", content: \"# Multi File\\n\\nmulti-file-ready\\n\" },\n ],\n },\n \"tanya.medium.package-manager\": {\n id: \"tanya.medium.package-manager\",\n prompt: \"Add package-manager metadata and a source marker.\",\n targetFiles: [\n { path: \"package.json\", content: \"{\\n \\\"name\\\": \\\"benchmark-fixture\\\",\\n \\\"packageManager\\\": \\\"npm@10.0.0\\\",\\n \\\"scripts\\\": {\\n \\\"typecheck\\\": \\\"node scripts/check.js\\\",\\n \\\"test\\\": \\\"node scripts/check.js\\\"\\n },\\n \\\"marker\\\": \\\"package-manager-ready\\\"\\n}\\n\" },\n { path: \"src/packageManager.ts\", content: \"export const packageManager = 'package-manager-ready';\\n\" },\n ],\n },\n \"tanya.medium.context-aware\": {\n id: \"tanya.medium.context-aware\",\n prompt: \"Read the provided context note before editing the implementation.\",\n useContext: true,\n targetFiles: [{ path: \"src/contextAware.ts\", content: \"export const contextAware = 'context-aware-ready';\\n\" }],\n },\n \"tanya.medium.existing-tests\": {\n id: \"tanya.medium.existing-tests\",\n prompt: \"Modify implementation while running the existing verification script.\",\n targetFiles: [\n { path: \"src/existingTests.js\", content: \"module.exports = 'existing-tests-ready';\\n\" },\n { path: \"test/existingTests.test.js\", content: \"if (require('../src/existingTests') !== 'existing-tests-ready') process.exit(1);\\n\" },\n ],\n },\n \"tanya.medium.dependency-install\": {\n id: \"tanya.medium.dependency-install\",\n prompt: \"Add the requested runtime dependency and lockfile state, then verify the manifest.\",\n targetFiles: [\n { path: \"package.json\", content: \"{\\n \\\"name\\\": \\\"benchmark-fixture\\\",\\n \\\"scripts\\\": {\\n \\\"check\\\": \\\"node scripts/check.js\\\"\\n },\\n \\\"dependencies\\\": {\\n \\\"zod\\\": \\\"^3.25.0\\\"\\n },\\n \\\"marker\\\": \\\"dependency-install-ready\\\"\\n}\\n\" },\n { path: \"package-lock.json\", content: \"{\\n \\\"name\\\": \\\"benchmark-fixture\\\",\\n \\\"lockfileVersion\\\": 3,\\n \\\"packages\\\": {\\n \\\"\\\": {\\n \\\"dependencies\\\": {\\n \\\"zod\\\": \\\"^3.25.0\\\"\\n },\\n \\\"marker\\\": \\\"dependency-install-ready\\\"\\n }\\n }\\n}\\n\" },\n ],\n },\n \"tanya.medium.framework-migration\": {\n id: \"tanya.medium.framework-migration\",\n prompt: \"Migrate the legacy page into an app-router-style page and preserve compatibility.\",\n preFiles: [\n { path: \"src/pages/index.tsx\", content: \"export default function LegacyHome() { return 'legacy'; }\\n\" },\n ],\n targetFiles: [\n { path: \"src/app/page.tsx\", content: \"export default function Page() { return 'framework-migration-ready'; }\\n\" },\n { path: \"src/app/layout.tsx\", content: \"export default function Layout({ children }: { children: unknown }) { return children; }\\n// framework-migration-ready\\n\" },\n { path: \"src/pages/index.tsx\", content: \"export { default } from '../app/page';\\n// framework-migration-ready\\n\" },\n ],\n },\n \"tanya.medium.failing-test-repair\": {\n id: \"tanya.medium.failing-test-repair\",\n prompt: \"Run the existing check, repair the failing implementation, and rerun verification.\",\n useSearchReplace: true,\n preVerifyBeforeEdit: true,\n targetFiles: [\n { path: \"src/math.js\", content: \"module.exports = function add(a, b) { return a + b; };\\n// failing-test-repair-ready\\n\" },\n { path: \"test/math.test.js\", content: \"const add = require('../src/math'); if (add(2, 2) !== 4) process.exit(1);\\n// failing-test-repair-ready\\n\" },\n ],\n },\n \"tanya.medium.frontend-smoke\": {\n id: \"tanya.medium.frontend-smoke\",\n prompt: \"Create a small frontend component and smoke check that proves the key UI marker is present.\",\n targetFiles: [\n { path: \"src/App.tsx\", content: \"export function App() { return <main className=\\\"dashboard\\\">frontend-smoke-ready</main>; }\\n\" },\n { path: \"src/App.css\", content: \".dashboard { display: grid; gap: 12px; }\\n/* frontend-smoke-ready */\\n\" },\n { path: \"test/render-smoke.js\", content: \"const fs = require('fs'); const text = fs.readFileSync('src/App.tsx', 'utf8'); if (!text.includes('frontend-smoke-ready')) process.exit(1);\\n// frontend-smoke-ready\\n\" },\n ],\n },\n \"tanya.medium.run-log-history\": {\n id: \"tanya.medium.run-log-history\",\n prompt: \"Complete a normal edit and make sure usage metrics are available for run history.\",\n usage: { promptTokens: 2_400, completionTokens: 620 },\n targetFiles: [{ path: \"src/runLogHistory.ts\", content: \"export const runLogHistory = 'run-log-history-ready';\\n\" }],\n },\n};\n\nasync function genericBenchmarkFixture(profile: GoldenTaskProfile): Promise<GoldenTaskFixture> {\n const spec = GENERIC_BENCHMARK_SPECS[profile.id];\n if (!spec) throw new Error(`No generic benchmark spec for ${profile.id}`);\n const workspace = await createBaseWorkspace(profile.id);\n const marker = `${profile.id.split(\".\").pop() ?? \"benchmark\"}-ready`;\n\n await mkdir(join(workspace, \"scripts\"), { recursive: true });\n await writeFile(join(workspace, \"scripts/check.js\"), [\n \"const fs = require('fs');\",\n `const targets = ${JSON.stringify(spec.targetFiles.map((file) => ({ path: file.path, marker })))};`,\n \"for (const target of targets) {\",\n \" const text = fs.readFileSync(target.path, 'utf8');\",\n \" if (!text.includes(target.marker)) {\",\n \" console.error(`missing ${target.marker} in ${target.path}`);\",\n \" process.exit(1);\",\n \" }\",\n \"}\",\n \"console.log('benchmark ok');\",\n \"\",\n ].join(\"\\n\"));\n\n if (spec.useSearchReplace) {\n for (const file of spec.targetFiles) {\n const dir = file.path.split(\"/\").slice(0, -1).join(\"/\");\n if (dir) await mkdir(join(workspace, dir), { recursive: true });\n await writeFile(join(workspace, file.path), file.content.replace(marker, \"PENDING_MARKER\"));\n }\n }\n for (const file of spec.preFiles ?? []) {\n const dir = file.path.split(\"/\").slice(0, -1).join(\"/\");\n if (dir) await mkdir(join(workspace, dir), { recursive: true });\n await writeFile(join(workspace, file.path), file.content);\n }\n if (spec.useArtifact) {\n await mkdir(join(workspace, \".tania/artifacts/generic\"), { recursive: true });\n await writeFile(join(workspace, \".tania/artifacts/generic/Pattern.md\"), `# Pattern\\n\\nUse ${marker} in the adapted output.\\n`);\n }\n if (spec.useContext) {\n await mkdir(join(workspace, \".tania/context\"), { recursive: true });\n await writeFile(join(workspace, \".tania/context/task.md\"), `# Task Context\\n\\nUse ${marker}.\\n`);\n }\n if (spec.dirtyWorktree) {\n await writeFile(join(workspace, \"unrelated.txt\"), \"baseline\\n\");\n await execFileAsync(\"git\", [\"init\"], { cwd: workspace });\n await execFileAsync(\"git\", [\"config\", \"user.email\", \"tanya@example.test\"], { cwd: workspace });\n await execFileAsync(\"git\", [\"config\", \"user.name\", \"Tanya Benchmark\"], { cwd: workspace });\n await execFileAsync(\"git\", [\"add\", \"unrelated.txt\"], { cwd: workspace });\n await execFileAsync(\"git\", [\"commit\", \"-m\", \"baseline\"], { cwd: workspace });\n await writeFile(join(workspace, \"unrelated.txt\"), \"pre-existing dirty change\\n\");\n }\n\n const toolCalls: ToolCall[] = [];\n if (spec.useArtifact) toolCalls.push(toolCall(\"read-artifact\", \"read_file\", { path: \".tania/artifacts/generic/Pattern.md\" }));\n if (spec.useContext) toolCalls.push(toolCall(\"read-context\", \"read_file\", { path: \".tania/context/task.md\" }));\n if (spec.preVerifyBeforeEdit) toolCalls.push(toolCall(\"verify-before\", \"run_command\", { command: \"node\", args: [\"scripts/check.js\"] }));\n if (spec.useSearchReplace) {\n for (const file of spec.targetFiles) {\n toolCalls.push(toolCall(`edit-${file.path}`, \"search_replace\", {\n path: file.path,\n old_string: file.content.replace(marker, \"PENDING_MARKER\"),\n new_string: file.content,\n }));\n }\n } else {\n for (const file of spec.targetFiles) toolCalls.push(toolCall(`write-${file.path}`, \"write_file\", file));\n }\n toolCalls.push(toolCall(\"verify\", \"run_command\", { command: \"node\", args: [\"scripts/check.js\"] }));\n\n const artifactLine = spec.useArtifact\n ? `Artifact reused: artifacts/generic/Pattern.md -> ${spec.targetFiles.map((file) => file.path).join(\", \")}`\n : \"Artifact reused: none\";\n const finalReport = [\n artifactLine,\n \"Artifact created: none\",\n ...spec.targetFiles.map((file) => `Modified: ${file.path}`),\n \"Verification: node scripts/check.js -> passed\",\n \"Blocked: none\",\n ].join(\"\\n\");\n\n return {\n workspace,\n prompt: spec.prompt,\n provider: scriptedProvider(profile.id, [\n { content: spec.prompt, toolCalls, ...(spec.usage ? { usage: spec.usage } : {}) },\n ...(spec.reportRepair ? [{ content: \"Done.\" }] : []),\n { content: finalReport },\n ]),\n runContext: {\n task: { kind: \"coding\", title: profile.title, summary: profile.purpose },\n artifacts: spec.useArtifact ? [{ path: \".tania/artifacts/generic/Pattern.md\", sourcePath: \"artifacts/generic/Pattern.md\", status: \"available\" }] : [],\n contextFiles: spec.useContext ? [{ path: \".tania/context/task.md\", sourcePath: \"context/task.md\", status: \"available\" }] : [],\n expected_report: { verification: true, artifact_reuse: true },\n metadata: { goldenTaskCandidate: true, caller: \"tanya-benchmark\" },\n },\n };\n}\n\nasync function streamingLongToolFixture(profile: GoldenTaskProfile): Promise<GoldenTaskFixture> {\n const workspace = await createBaseWorkspace(profile.id);\n const script = \"for i in 1 2 3 4 5 6; do printf \\\"stream-$i\\\\n\\\"; sleep 2; done; node scripts/check.js\";\n await mkdir(join(workspace, \"scripts\"), { recursive: true });\n await writeFile(join(workspace, \"scripts/check.js\"), [\n \"const fs = require('fs');\",\n \"const text = fs.readFileSync('src/streamingLongTool.ts', 'utf8');\",\n \"if (!text.includes('streaming-long-tool-ready')) process.exit(1);\",\n \"console.log('benchmark ok');\",\n \"\",\n ].join(\"\\n\"));\n\n const provider = scriptedProvider(profile.id, [\n {\n content: \"Create a marker file and verify it with a long-running streaming shell command.\",\n toolCalls: [\n toolCall(\"write-marker\", \"write_file\", {\n path: \"src/streamingLongTool.ts\",\n content: \"export const streamingLongTool = 'streaming-long-tool-ready';\\n\",\n }),\n toolCall(\"long-verify\", \"run_shell\", { script, timeoutMs: 20_000 }),\n ],\n },\n {\n content: [\n \"Artifact reused: none\",\n \"Artifact created: none\",\n \"Modified: src/streamingLongTool.ts\",\n `Verification: ${script} -> passed`,\n \"Blocked: none\",\n ].join(\"\\n\"),\n },\n ]);\n\n return {\n workspace,\n prompt: \"Create a marker file and verify it with a >10s shell command that streams output.\",\n provider,\n runContext: {\n task: { kind: \"coding\", title: profile.title, summary: profile.purpose },\n expected_report: { verification: true, artifact_reuse: true },\n metadata: { goldenTaskCandidate: true, caller: \"tanya-golden\" },\n },\n };\n}\n\nasync function androidSplashFixture(profile: GoldenTaskProfile): Promise<GoldenTaskFixture> {\n const workspace = await createBaseWorkspace(profile.id);\n await mkdir(join(workspace, \".tania/artifacts/android\"), { recursive: true });\n await mkdir(join(workspace, \"app/src/main/java/com/example/app/ui/splash\"), { recursive: true });\n await mkdir(join(workspace, \"app/src/main/res/values\"), { recursive: true });\n await mkdir(join(workspace, \"app/src/main/res/drawable\"), { recursive: true });\n await writeFile(join(workspace, \".tania/artifacts/android/SplashScreenPattern.kt\"), \"fun SplashPattern() {}\\n\");\n await writeFile(join(workspace, \"gradlew\"), \"#!/bin/sh\\ncase \\\"$*\\\" in\\n *ktlintCheck*) echo ktlint ok ;;\\n *) echo BUILD SUCCESSFUL ;;\\nesac\\n\");\n await writeFile(join(workspace, \"app/src/main/res/drawable/ic_splash_logo.png\"), \"png\\n\");\n\n const provider = scriptedProvider(profile.id, [\n {\n content: \"Create Android splash resources from the artifact.\",\n toolCalls: [\n toolCall(\"read-artifact\", \"read_file\", { path: \".tania/artifacts/android/SplashScreenPattern.kt\" }),\n toolCall(\"write-manifest\", \"write_file\", {\n path: \"app/src/main/AndroidManifest.xml\",\n content: \"<manifest xmlns:android=\\\"http://schemas.android.com/apk/res/android\\\"><application><activity android:name=\\\".MainActivity\\\" android:theme=\\\"@style/Theme.App.Splash\\\" /></application></manifest>\\n\",\n }),\n toolCall(\"write-theme\", \"write_file\", {\n path: \"app/src/main/res/values/splash_theme.xml\",\n content: \"<resources><style name=\\\"Theme.App.Splash\\\" parent=\\\"Theme.SplashScreen\\\"><item name=\\\"windowSplashScreenAnimatedIcon\\\">@drawable/ic_splash_logo</item><item name=\\\"postSplashScreenTheme\\\">@style/Theme.App</item></style></resources>\\n\",\n }),\n toolCall(\"write-icon\", \"write_file\", {\n path: \"app/src/main/res/drawable/ic_splash_logo.png\",\n content: \"png\\n\",\n }),\n toolCall(\"write-main\", \"write_file\", {\n path: \"app/src/main/java/com/example/app/MainActivity.kt\",\n content: \"package com.example.app\\nfun onCreate() { installSplashScreen() }\\n\",\n }),\n toolCall(\"write-splash\", \"write_file\", {\n path: \"app/src/main/java/com/example/app/ui/splash/SplashScreen.kt\",\n content: \"package com.example.app.ui.splash\\nfun CosaNostraSplashScreen() {}\\n\",\n }),\n toolCall(\"verify\", \"run_shell\", { script: \"chmod +x ./gradlew && ./gradlew assembleDebug --no-daemon\" }),\n ],\n },\n {\n content: [\n \"Artifact reused: artifacts/android/SplashScreenPattern.kt -> app/src/main/java/com/example/app/ui/splash/SplashScreen.kt\",\n \"Artifact created: none\",\n \"Modified: app/src/main/AndroidManifest.xml\",\n \"Modified: app/src/main/res/values/splash_theme.xml\",\n \"Modified: app/src/main/res/drawable/ic_splash_logo.png\",\n \"Modified: app/src/main/java/com/example/app/MainActivity.kt\",\n \"Modified: app/src/main/java/com/example/app/ui/splash/SplashScreen.kt\",\n \"Verification: ./gradlew assembleDebug --no-daemon -> passed\",\n \"Blocked: none\",\n ].join(\"\\n\"),\n },\n ]);\n\n return {\n workspace,\n prompt: \"Create Android splash screen using artifacts/android/SplashScreenPattern.kt.\",\n provider,\n runContext: {\n task: { kind: \"coding\", title: \"Splash Screen - Android\", summary: profile.purpose },\n artifacts: [{ path: \".tania/artifacts/android/SplashScreenPattern.kt\", sourcePath: \"artifacts/android/SplashScreenPattern.kt\", status: \"available\" }],\n expected_report: { verification: true, artifact_reuse: true },\n metadata: { goldenTaskCandidate: true, caller: \"tanya-golden\" },\n },\n };\n}\n\nasync function iosFoundationFixture(profile: GoldenTaskProfile): Promise<GoldenTaskFixture> {\n const workspace = await createBaseWorkspace(profile.id);\n await mkdir(join(workspace, \".tania/artifacts/ios\"), { recursive: true });\n await writeFile(join(workspace, \".tania/artifacts/ios/ThemeSystem.swift\"), \"import SwiftUI\\n\");\n await writeFile(join(workspace, \".tania/artifacts/ios/SwiftDataSetup.swift\"), \"import SwiftData\\n\");\n await writeFile(join(workspace, \".tania/artifacts/ios/NavigationSetup.swift\"), \"import SwiftUI\\n\");\n\n const provider = scriptedProvider(profile.id, [\n {\n content: \"Create iOS foundation from theme, SwiftData, and navigation artifacts.\",\n toolCalls: [\n toolCall(\"read-theme\", \"read_file\", { path: \".tania/artifacts/ios/ThemeSystem.swift\" }),\n toolCall(\"read-data\", \"read_file\", { path: \".tania/artifacts/ios/SwiftDataSetup.swift\" }),\n toolCall(\"read-nav\", \"read_file\", { path: \".tania/artifacts/ios/NavigationSetup.swift\" }),\n toolCall(\"mkdirs\", \"run_shell\", { script: \"mkdir -p CosaNostra/Theme CosaNostra/Models CosaNostra/Navigation\" }),\n toolCall(\"write-colors\", \"write_file\", {\n path: \"CosaNostra/Theme/Colors.swift\",\n content: \"import SwiftUI\\nextension Color { static let brandPrimary = Color(red: 26 / 255, green: 47 / 255, blue: 75 / 255); static let brandSecondary = Color(red: 200 / 255, green: 174 / 255, blue: 127 / 255); static let textPrimary = Color.primary }\\n\",\n }),\n toolCall(\"write-type\", \"write_file\", {\n path: \"CosaNostra/Theme/Typography.swift\",\n content: \"import SwiftUI\\nenum AppTypography { static let title = Font.system(size: 28, design: .serif); static let body = Font.system(size: 16, design: .default) /* Playfair Display / Roboto local fallback */ }\\n\",\n }),\n toolCall(\"write-mods\", \"write_file\", {\n path: \"CosaNostra/Theme/ViewModifiers.swift\",\n content: \"import SwiftUI\\nstruct CardStyle: ViewModifier { func body(content: Content) -> some View { content } }\\nstruct PrimaryButtonStyle: ButtonStyle { func makeBody(configuration: Configuration) -> some View { configuration.label } }\\nstruct EmptyStateView: View { var body: some View { Text(\\\"Empty\\\") } }\\nstruct LoadingView: View { var body: some View { ProgressView() } }\\nstruct ErrorView: View { var body: some View { Text(\\\"Error\\\") } }\\n\",\n }),\n toolCall(\"write-models\", \"write_file\", {\n path: \"CosaNostra/Models/SwiftDataSetup.swift\",\n content: \"import SwiftData\\n@Model final class UserProfile { var id: String = \\\"\\\" }\\nlet appSchema = Schema([UserProfile.self])\\n\",\n }),\n toolCall(\"write-nav\", \"write_file\", {\n path: \"CosaNostra/Navigation/NavigationSetup.swift\",\n content: \"import SwiftUI\\nstruct RootTabView: View { @AppStorage(\\\"isDarkMode\\\") private var isDarkMode = false; var body: some View { TabView { NavigationStack { Toggle(\\\"Dark Mode\\\", isOn: $isDarkMode); Text(\\\"Dashboard\\\") } } } }\\n\",\n }),\n toolCall(\"write-app\", \"write_file\", {\n path: \"CosaNostra/CosaNostraApp.swift\",\n content: \"import SwiftUI\\nimport SwiftData\\n@main struct CosaNostraApp: App { @AppStorage(\\\"isDarkMode\\\") private var isDarkMode = false; var body: some Scene { WindowGroup { RootTabView().preferredColorScheme(isDarkMode ? .dark : nil).modelContainer(for: [UserProfile.self]) } } }\\n\",\n }),\n toolCall(\"verify\", \"run_shell\", { script: \"grep -R \\\"TabView\\\" CosaNostra/Navigation && echo xcodebuild\" }),\n ],\n },\n {\n content: [\n \"Artifact reused: artifacts/ios/ThemeSystem.swift -> CosaNostra/Theme/Colors.swift, CosaNostra/Theme/Typography.swift, CosaNostra/Theme/ViewModifiers.swift\",\n \"Artifact reused: artifacts/ios/SwiftDataSetup.swift -> CosaNostra/Models/SwiftDataSetup.swift\",\n \"Artifact reused: artifacts/ios/NavigationSetup.swift -> CosaNostra/Navigation/NavigationSetup.swift\",\n \"Artifact created: none\",\n \"Modified: CosaNostra/Theme/Colors.swift\",\n \"Modified: CosaNostra/Theme/Typography.swift\",\n \"Modified: CosaNostra/Theme/ViewModifiers.swift\",\n \"Modified: CosaNostra/Models/SwiftDataSetup.swift\",\n \"Modified: CosaNostra/Navigation/NavigationSetup.swift\",\n \"Modified: CosaNostra/CosaNostraApp.swift\",\n \"Verification: grep -R \\\"TabView\\\" CosaNostra/Navigation && echo xcodebuild -> passed\",\n \"Blocked: none\",\n ].join(\"\\n\"),\n },\n ]);\n\n return {\n workspace,\n prompt: \"Create bounded iOS foundation from the provided artifacts. Ensure dark mode support and local typography fallback.\",\n provider,\n runContext: {\n task: { kind: \"coding\", title: \"Fundações - iOS\", summary: profile.purpose },\n artifacts: [\n { path: \".tania/artifacts/ios/ThemeSystem.swift\", sourcePath: \"artifacts/ios/ThemeSystem.swift\", status: \"available\" },\n { path: \".tania/artifacts/ios/SwiftDataSetup.swift\", sourcePath: \"artifacts/ios/SwiftDataSetup.swift\", status: \"available\" },\n { path: \".tania/artifacts/ios/NavigationSetup.swift\", sourcePath: \"artifacts/ios/NavigationSetup.swift\", status: \"available\" },\n ],\n expected_report: { verification: true, artifact_reuse: true },\n metadata: { goldenTaskCandidate: true, caller: \"tanya-golden\" },\n },\n };\n}\n\nasync function appleAppIconFixture(profile: GoldenTaskProfile): Promise<GoldenTaskFixture> {\n const workspace = await createBaseWorkspace(profile.id);\n await mkdir(join(workspace, \"CosaNostra/Assets.xcassets\"), { recursive: true });\n const provider = scriptedProvider(profile.id, [\n {\n content: \"Generate Apple app icon set with iOS and macOS slots.\",\n toolCalls: [\n toolCall(\"write-svg\", \"write_file\", {\n path: \"brand-icon.svg\",\n content: \"<svg xmlns=\\\"http://www.w3.org/2000/svg\\\" width=\\\"1024\\\" height=\\\"1024\\\"><rect width=\\\"1024\\\" height=\\\"1024\\\" fill=\\\"#1A2F4B\\\"/><circle cx=\\\"512\\\" cy=\\\"512\\\" r=\\\"280\\\" fill=\\\"#C8AE7F\\\"/></svg>\\n\",\n }),\n toolCall(\"create-icons\", \"create_apple_app_icon_set\", {\n source: \"brand-icon.svg\",\n outputDir: \"CosaNostra/Assets.xcassets/AppIcon.appiconset\",\n platforms: [\"ios\", \"macos\"],\n }),\n toolCall(\"parse-json\", \"run_shell\", { script: \"node -e \\\"const c=require('./CosaNostra/Assets.xcassets/AppIcon.appiconset/Contents.json'); const idioms=new Set(c.images.map(i=>i.idiom)); if(!idioms.has('iphone')||!idioms.has('ipad')||!idioms.has('ios-marketing')||!idioms.has('mac')) process.exit(1); console.log(c.images.length)\\\"\" }),\n toolCall(\"xcodebuild\", \"run_shell\", { script: \"printf '#!/bin/sh\\\\necho BUILD SUCCEEDED\\\\n' > xcodebuild && chmod +x xcodebuild && PATH=\\\"$PWD:$PATH\\\" xcodebuild build -scheme CosaNostra -destination 'generic/platform=iOS Simulator'\" }),\n ],\n },\n {\n content: [\n \"Artifact reused: none\",\n \"Artifact created: none\",\n \"Modified: brand-icon.svg\",\n \"Modified: CosaNostra/Assets.xcassets/AppIcon.appiconset/Contents.json\",\n \"Verification: node Contents.json idiom parse -> passed\",\n \"Verification: xcodebuild build -scheme CosaNostra -destination 'generic/platform=iOS Simulator' -> passed\",\n \"Blocked: none\",\n ].join(\"\\n\"),\n },\n ]);\n\n return {\n workspace,\n prompt: \"Generate Apple app icon assets for iOS, iPad, ios-marketing, and macOS.\",\n provider,\n runContext: {\n task: { kind: \"coding\", title: \"App Icon - Apple\", summary: profile.purpose },\n expected_report: { verification: true, artifact_reuse: true },\n metadata: { goldenTaskCandidate: true, caller: \"tanya-golden\" },\n },\n };\n}\n\nasync function androidFoundationFixture(profile: GoldenTaskProfile): Promise<GoldenTaskFixture> {\n const workspace = await createBaseWorkspace(profile.id);\n await mkdir(join(workspace, \".tania/artifacts/android\"), { recursive: true });\n await mkdir(join(workspace, \"app\"), { recursive: true });\n await writeFile(join(workspace, \".tania/artifacts/android/ThemeSystem.kt\"), \"package artifact\\n\");\n await writeFile(join(workspace, \".tania/artifacts/android/NavigationSetup.kt\"), \"package artifact\\n\");\n await writeFile(join(workspace, \".tania/artifacts/android/RoomSetup.kt\"), \"package artifact\\n\");\n await writeFile(join(workspace, \"gradlew\"), \"#!/bin/sh\\ncase \\\"$*\\\" in\\n *ktlintCheck*) echo ktlint ok ;;\\n *) echo BUILD SUCCESSFUL ;;\\nesac\\n\");\n await writeFile(join(workspace, \"build.gradle.kts\"), \"plugins {\\n id(\\\"com.android.application\\\") version \\\"8.7.2\\\" apply false\\n}\\n\");\n await writeFile(join(workspace, \"app/build.gradle.kts\"), [\n \"plugins {\",\n \" id(\\\"com.android.application\\\")\",\n \" id(\\\"org.jetbrains.kotlin.android\\\")\",\n \"}\",\n \"\",\n \"dependencies {\",\n \"}\",\n \"\",\n ].join(\"\\n\"));\n\n const provider = scriptedProvider(profile.id, [\n {\n content: \"Create Android foundation with the deterministic high-level tool.\",\n toolCalls: [\n toolCall(\"read-theme\", \"read_file\", { path: \".tania/artifacts/android/ThemeSystem.kt\" }),\n toolCall(\"read-nav\", \"read_file\", { path: \".tania/artifacts/android/NavigationSetup.kt\" }),\n toolCall(\"read-room\", \"read_file\", { path: \".tania/artifacts/android/RoomSetup.kt\" }),\n toolCall(\"create-foundation\", \"create_android_foundation\", {\n packageName: \"com.example.app\",\n appName: \"Golden\",\n brandPrimaryHex: \"#1A2F4B\",\n brandSecondaryHex: \"#C8AE7F\",\n }),\n toolCall(\"verify\", \"run_shell\", { script: \"chmod +x ./gradlew && ./gradlew assembleDebug --no-daemon\" }),\n ],\n },\n {\n content: [\n \"Artifact reused: artifacts/android/ThemeSystem.kt -> app/src/main/java/com/example/app/ui/theme/AppTheme.kt\",\n \"Artifact reused: artifacts/android/NavigationSetup.kt -> app/src/main/java/com/example/app/navigation/AppNavigation.kt\",\n \"Artifact reused: artifacts/android/RoomSetup.kt -> app/src/main/java/com/example/app/data/AppDatabase.kt\",\n \"Artifact created: none\",\n \"Modified: build.gradle.kts\",\n \"Modified: app/build.gradle.kts\",\n \"Modified: app/src/main/java/com/example/app/ui/theme/AppTheme.kt\",\n \"Modified: app/src/main/java/com/example/app/navigation/AppNavigation.kt\",\n \"Modified: app/src/main/java/com/example/app/data/AppDatabase.kt\",\n \"Modified: app/src/main/java/com/example/app/ui/components/FoundationStates.kt\",\n \"Verification: ./gradlew assembleDebug --no-daemon -> passed\",\n \"Blocked: none\",\n ].join(\"\\n\"),\n },\n ]);\n\n return {\n workspace,\n prompt: \"Create Android foundation using Room, Navigation Compose, Material 3 theme, and base composables.\",\n provider,\n runContext: {\n task: { kind: \"coding\", title: \"Fundações - Android\", summary: profile.purpose },\n artifacts: [\n { path: \".tania/artifacts/android/ThemeSystem.kt\", sourcePath: \"artifacts/android/ThemeSystem.kt\", status: \"available\" },\n { path: \".tania/artifacts/android/NavigationSetup.kt\", sourcePath: \"artifacts/android/NavigationSetup.kt\", status: \"available\" },\n { path: \".tania/artifacts/android/RoomSetup.kt\", sourcePath: \"artifacts/android/RoomSetup.kt\", status: \"available\" },\n ],\n expected_report: { verification: true, artifact_reuse: true },\n metadata: { goldenTaskCandidate: true, caller: \"tanya-golden\" },\n },\n };\n}\n\nasync function backendApiFoundationFixture(profile: GoldenTaskProfile): Promise<GoldenTaskFixture> {\n const workspace = await createBaseWorkspace(profile.id);\n await mkdir(join(workspace, \".tania/artifacts/backend\"), { recursive: true });\n await mkdir(join(workspace, \"app/api/health\"), { recursive: true });\n await mkdir(join(workspace, \"lib\"), { recursive: true });\n await mkdir(join(workspace, \"prisma\"), { recursive: true });\n await writeFile(join(workspace, \".tania/artifacts/backend/JwtAuthRoutes.ts\"), \"export function authRoutePattern() {}\\n\");\n await writeFile(join(workspace, \"package.json\"), JSON.stringify({ scripts: { typecheck: \"tsc --noEmit\", test: \"node --test\" }, dependencies: {} }, null, 2));\n\n const provider = scriptedProvider(profile.id, [\n {\n content: \"Create backend health/API foundation from the route artifact.\",\n toolCalls: [\n toolCall(\"read-artifact\", \"read_file\", { path: \".tania/artifacts/backend/JwtAuthRoutes.ts\" }),\n toolCall(\"write-health\", \"write_file\", {\n path: \"app/api/health/route.ts\",\n content: \"export async function GET() { return Response.json({ status: 'ok', health: true }); }\\n\",\n }),\n toolCall(\"write-openapi\", \"write_file\", {\n path: \"lib/openapi.ts\",\n content: \"export const openApiSpec = { paths: { '/api/health': { get: { summary: 'health' } } } };\\n\",\n }),\n toolCall(\"write-prisma\", \"write_file\", {\n path: \"prisma/schema.prisma\",\n content: \"datasource db { provider = \\\"postgresql\\\" url = env(\\\"DATABASE_URL\\\") }\\ngenerator client { provider = \\\"prisma-client-js\\\" }\\nmodel User { id String @id }\\n\",\n }),\n toolCall(\"write-env\", \"write_file\", {\n path: \".env.example\",\n content: [\n \"# CosmoHQ Deploy provisions Azure PostgreSQL.\",\n \"# Set DATABASE_URL and DIRECT_URL before seed:mock-data and seed:test-account actions.\",\n \"DATABASE_URL=\\\"replace-me-cosmohq-deploy-azure-postgresql-url\\\"\",\n \"DIRECT_URL=\\\"replace-me-cosmohq-deploy-azure-postgresql-direct-url\\\"\",\n \"\",\n ].join(\"\\n\"),\n }),\n toolCall(\"verify\", \"run_shell\", { script: \"node -e \\\"require('fs').accessSync('app/api/health/route.ts'); console.log('typecheck')\\\"\" }),\n ],\n },\n {\n content: [\n \"Artifact reused: artifacts/backend/JwtAuthRoutes.ts -> app/api/health/route.ts\",\n \"Artifact created: none\",\n \"Modified: app/api/health/route.ts\",\n \"Modified: lib/openapi.ts\",\n \"Modified: prisma/schema.prisma\",\n \"Modified: .env.example\",\n \"Verification: node -e route exists -> passed\",\n \"Blocked: none\",\n ].join(\"\\n\"),\n },\n ]);\n\n return {\n workspace,\n prompt: \"Implement backend API foundation with health endpoint, OpenAPI seed, Prisma schema, and env example.\",\n provider,\n runContext: {\n task: { kind: \"coding\", title: \"Backend API Foundation\", summary: profile.purpose },\n artifacts: [{ path: \".tania/artifacts/backend/JwtAuthRoutes.ts\", sourcePath: \"artifacts/backend/JwtAuthRoutes.ts\", status: \"available\" }],\n expected_report: { verification: true, artifact_reuse: true },\n metadata: { goldenTaskCandidate: true, caller: \"tanya-golden\" },\n },\n };\n}\n\nexport function goldenRunnableProfiles(): GoldenTaskProfile[] {\n const runnable = new Set([\n \"cosmohq.android.foundation\",\n \"cosmohq.android.splash\",\n \"cosmohq.ios.foundation\",\n \"cosmohq.apple.app-icon\",\n \"cosmohq.backend.api-foundation\",\n \"tanya.medium.streaming-long-tool\",\n ...Object.keys(GENERIC_BENCHMARK_SPECS),\n ]);\n return BUILT_IN_GOLDEN_TASK_PROFILES.filter((profile) => runnable.has(profile.id));\n}\n\nasync function createFixture(profile: GoldenTaskProfile): Promise<GoldenTaskFixture> {\n if (profile.id === \"tanya.medium.streaming-long-tool\") return streamingLongToolFixture(profile);\n if (profile.id in GENERIC_BENCHMARK_SPECS) return genericBenchmarkFixture(profile);\n if (profile.id === \"cosmohq.android.foundation\") return androidFoundationFixture(profile);\n if (profile.id === \"cosmohq.android.splash\") return androidSplashFixture(profile);\n if (profile.id === \"cosmohq.ios.foundation\") return iosFoundationFixture(profile);\n if (profile.id === \"cosmohq.apple.app-icon\") return appleAppIconFixture(profile);\n if (profile.id === \"cosmohq.backend.api-foundation\") return backendApiFoundationFixture(profile);\n throw new Error(`Golden profile is not executable yet: ${profile.id}`);\n}\n\nexport async function runGoldenTask(profileId: string): Promise<GoldenRunResult> {\n const profile = BUILT_IN_GOLDEN_TASK_PROFILES.find((item) => item.id === profileId);\n if (!profile) throw new Error(`Unknown golden profile: ${profileId}`);\n const fixture = await createFixture(profile);\n const events: TanyaEvent[] = [];\n const { message: finalText } = await runAgent({\n provider: fixture.provider,\n prompt: fixture.prompt,\n cwd: fixture.workspace,\n sink: async (event) => { events.push(event); },\n runContext: fixture.runContext,\n });\n const problems = [\n ...finalText.matchAll(/\"severity\"\\s*:\\s*\"error\"[\\s\\S]{0,220}?\"id\"\\s*:\\s*\"([^\"]+)\"/g),\n ].map((match) => match[1] ?? \"validation-error\");\n if (profileId === \"tanya.medium.streaming-long-tool\" && !events.some((event) => event.type === \"tool_progress\")) {\n problems.push(\"missing-tool-progress\");\n }\n const blocked = finalText\n .split(/\\r?\\n/)\n .some((line) => {\n const match = line.trim().match(/^Blocked:\\s*(.+)$/i);\n return !!match?.[1] && !/^none\\b/i.test(match[1].trim());\n });\n return {\n profile,\n workspace: fixture.workspace,\n passed: !blocked && problems.length === 0,\n finalText,\n problems,\n };\n}\n","import { buildGoldenTaskSummary, readGoldenTaskMemory, validateGoldenTaskSummary } from \"../memory/goldenTasks\";\nimport { BUILT_IN_GOLDEN_TASK_PROFILES } from \"./profiles\";\nimport { goldenRunnableProfiles, runGoldenTask } from \"./run\";\n\nexport async function runGoldenSuiteCommand(workspace: string, action: string, json = false, options: { profile?: string; all?: boolean } = {}): Promise<number> {\n const records = await readGoldenTaskMemory(workspace);\n const summary = buildGoldenTaskSummary(records);\n const problems = validateGoldenTaskSummary(summary);\n\n if (action === \"run\") {\n const profiles = options.all\n ? goldenRunnableProfiles()\n : [options.profile ?? \"cosmohq.android.splash\"]\n .map((profileId) => BUILT_IN_GOLDEN_TASK_PROFILES.find((profile) => profile.id === profileId))\n .filter((profile): profile is NonNullable<typeof profile> => !!profile);\n if (profiles.length === 0) {\n const message = `No executable golden profile matched ${options.profile ?? \"(default)\"}.`;\n if (json) console.log(JSON.stringify({ results: [], problems: [message] }, null, 2));\n else console.log(message);\n return 1;\n }\n const results = [];\n for (const profile of profiles) results.push(await runGoldenTask(profile.id));\n if (json) {\n console.log(JSON.stringify({\n results: results.map((result) => ({\n profileId: result.profile.id,\n title: result.profile.title,\n workspace: result.workspace,\n passed: result.passed,\n problems: result.problems,\n })),\n }, null, 2));\n } else {\n for (const result of results) {\n console.log(`${result.passed ? \"PASS\" : \"FAIL\"} ${result.profile.id} ${result.profile.title}`);\n console.log(` workspace: ${result.workspace}`);\n if (result.problems.length > 0) console.log(` problems: ${result.problems.join(\", \")}`);\n }\n }\n return results.every((result) => result.passed) ? 0 : 1;\n }\n\n if (json) {\n console.log(JSON.stringify({\n summary,\n problems,\n profiles: action === \"profiles\" ? BUILT_IN_GOLDEN_TASK_PROFILES : undefined,\n executableProfiles: action === \"profiles\" ? goldenRunnableProfiles().map((profile) => profile.id) : undefined,\n }, null, 2));\n return action === \"validate\" && problems.length > 0 ? 1 : 0;\n }\n\n if (action === \"profiles\") {\n console.log(`Built-in golden task profiles: ${BUILT_IN_GOLDEN_TASK_PROFILES.length}`);\n for (const profile of BUILT_IN_GOLDEN_TASK_PROFILES) {\n const executable = goldenRunnableProfiles().some((item) => item.id === profile.id) ? \" executable\" : \"\";\n console.log(`${profile.id} [${profile.platform}${executable}] ${profile.title}`);\n console.log(` ${profile.purpose}`);\n console.log(` capabilities: ${profile.requiredCapabilities.join(\", \")}`);\n }\n return 0;\n }\n\n if (action === \"list\") {\n if (summary.latestBySignature.length === 0) {\n console.log(\"No golden task records found.\");\n return 0;\n }\n for (const record of summary.latestBySignature) {\n const title = record.task?.title ?? record.signature;\n console.log(`${record.outcome.toUpperCase()} ${record.signature} ${title}`);\n }\n return 0;\n }\n\n console.log(`Golden tasks: ${summary.total} record(s), ${summary.signatures} signature(s), ${summary.passed} passed, ${summary.failed} failed.`);\n if (summary.failureReasons.length > 0) {\n console.log(\"Top failure reasons:\");\n for (const reason of summary.failureReasons.slice(0, 8)) console.log(`- ${reason.reason}: ${reason.count}`);\n }\n if (action === \"validate\") {\n if (problems.length === 0) {\n console.log(\"Golden suite validation passed.\");\n return 0;\n }\n console.log(\"Golden suite validation failed:\");\n for (const problem of problems) console.log(`- ${problem}`);\n return 1;\n }\n return 0;\n}\n","import { mkdir, readFile, readdir, stat, writeFile } from \"node:fs/promises\";\nimport { dirname, join, resolve } from \"node:path\";\n\ntype PackageJson = {\n scripts?: Record<string, unknown>;\n dependencies?: Record<string, unknown>;\n devDependencies?: Record<string, unknown>;\n};\n\ntype StackDetection = {\n projectTypes: string[];\n verificationCommands: string[];\n signals: string[];\n};\n\nasync function fileExists(path: string): Promise<boolean> {\n try {\n const entry = await stat(path);\n return entry.isFile() || entry.isDirectory();\n } catch {\n return false;\n }\n}\n\nasync function readPackageJson(workspace: string): Promise<PackageJson | null> {\n const packagePath = join(workspace, \"package.json\");\n try {\n return JSON.parse(await readFile(packagePath, \"utf8\")) as PackageJson;\n } catch {\n return null;\n }\n}\n\nfunction hasDependency(pkg: PackageJson | null, name: string): boolean {\n return !!pkg && (Object.hasOwn(pkg.dependencies ?? {}, name) || Object.hasOwn(pkg.devDependencies ?? {}, name));\n}\n\nfunction scriptCommand(pkg: PackageJson | null, scriptName: \"typecheck\" | \"build\" | \"test\"): string | null {\n const script = pkg?.scripts?.[scriptName];\n return typeof script === \"string\" && script.trim() ? `npm run ${scriptName}` : null;\n}\n\nasync function rootEntries(workspace: string): Promise<string[]> {\n try {\n return await readdir(workspace);\n } catch {\n return [];\n }\n}\n\nfunction unique(values: string[]): string[] {\n return [...new Set(values)];\n}\n\nasync function detectStack(workspace: string): Promise<StackDetection> {\n const pkg = await readPackageJson(workspace);\n const entries = await rootEntries(workspace);\n const hasPackageJson = pkg !== null;\n const hasPrisma = await fileExists(join(workspace, \"prisma\", \"schema.prisma\"));\n const hasNextConfig = entries.some((entry) => /^next\\.config\\.(?:js|mjs|cjs|ts)$/.test(entry));\n const hasTsconfig = await fileExists(join(workspace, \"tsconfig.json\"));\n const hasGradlew = await fileExists(join(workspace, \"gradlew\"));\n const xcodeProjects = entries.filter((entry) => entry.endsWith(\".xcodeproj\"));\n\n const projectTypes: string[] = [];\n if (hasNextConfig || hasDependency(pkg, \"next\")) projectTypes.push(\"Next.js\");\n if (hasGradlew) projectTypes.push(\"Android\");\n if (xcodeProjects.length > 0) projectTypes.push(\"iOS\");\n if (hasPackageJson && projectTypes.length === 0) projectTypes.push(\"Node\");\n if (projectTypes.length === 0) projectTypes.push(\"Unknown\");\n\n const verificationCommands = [\n scriptCommand(pkg, \"typecheck\") ?? (hasTsconfig ? \"npx tsc --noEmit\" : null),\n scriptCommand(pkg, \"build\"),\n scriptCommand(pkg, \"test\"),\n hasPrisma ? \"npx prisma generate\" : null,\n hasGradlew ? \"./gradlew assembleDebug --no-daemon\" : null,\n ...xcodeProjects.map((project) => `xcodebuild -list -project '${project}'`),\n ].filter((command): command is string => !!command);\n\n const signals = [\n hasPackageJson ? \"package.json\" : null,\n hasPrisma ? \"prisma/schema.prisma\" : null,\n hasNextConfig ? entries.find((entry) => /^next\\.config\\.(?:js|mjs|cjs|ts)$/.test(entry)) ?? \"next.config.*\" : null,\n hasTsconfig ? \"tsconfig.json\" : null,\n hasGradlew ? \"gradlew\" : null,\n ...xcodeProjects,\n ].filter((signal): signal is string => !!signal);\n\n return {\n projectTypes: unique(projectTypes),\n verificationCommands: unique(verificationCommands),\n signals: unique(signals),\n };\n}\n\nfunction buildInstructions(detection: StackDetection): string {\n const verificationLines = detection.verificationCommands.length > 0\n ? detection.verificationCommands.map((command) => `- \\`${command}\\``)\n : [\"- Add project-specific verification commands here.\"];\n const signalLines = detection.signals.length > 0\n ? detection.signals.map((signal) => `- ${signal}`)\n : [\"- No common stack markers detected.\"];\n\n return [\n \"# Tanya Project Instructions\",\n \"\",\n `Project type: ${detection.projectTypes.join(\" / \")}`,\n \"\",\n \"## Detected Stack Signals\",\n ...signalLines,\n \"\",\n \"## Verification Commands\",\n ...verificationLines,\n \"\",\n \"## Custom Instructions\",\n \"- Add project-specific rules, safety constraints, architecture notes, and preferred workflows here.\",\n \"\",\n ].join(\"\\n\");\n}\n\nexport async function initTanyaProject(cwd: string): Promise<string> {\n const workspace = resolve(cwd);\n const instructionsPath = join(workspace, \".tania\", \"INSTRUCTIONS.md\");\n const detection = await detectStack(workspace);\n await mkdir(dirname(instructionsPath), { recursive: true });\n try {\n await writeFile(instructionsPath, buildInstructions(detection), { encoding: \"utf8\", flag: \"wx\" });\n } catch (error) {\n const code = typeof error === \"object\" && error !== null && \"code\" in error ? String((error as { code?: unknown }).code) : \"\";\n if (code === \"EEXIST\") throw new Error(`${instructionsPath} already exists. Refusing to overwrite.`);\n throw error;\n }\n return instructionsPath;\n}\n","import type { TanyaRunContext } from \"./runContext\";\nimport { buildTaskBrief, type TanyaTaskBrief } from \"../tools/projectContextTools\";\nimport { materializeObsidianContext } from \"../obsidian/search\";\n\nexport type AutoRunContextOptions = {\n cwd: string;\n prompt: string;\n runContext?: TanyaRunContext;\n obsidianVault?: string | undefined;\n enableBrief?: boolean | undefined;\n enableObsidian?: boolean | undefined;\n keepContext?: boolean | undefined;\n};\n\nfunction unique(values: string[]): string[] {\n return [...new Set(values.filter((value) => value.trim().length > 0))];\n}\n\nfunction shouldTreatAsCodingTask(brief: TanyaTaskBrief, runContext?: TanyaRunContext): boolean {\n if (runContext?.task?.kind === \"coding\") return true;\n if (runContext?.expected_report && Object.keys(runContext.expected_report).length > 0) return true;\n if (runContext?.verification?.commands?.length) return true;\n if (runContext?.artifacts?.length || runContext?.contextFiles?.length) return true;\n return brief.signals.platforms.length > 0 || brief.signals.domains.length > 0;\n}\n\nexport async function buildAutoRunContext(options: AutoRunContextOptions): Promise<TanyaRunContext | undefined> {\n let runContext = options.runContext;\n let brief: TanyaTaskBrief | undefined;\n const instructions: string[] = [...(runContext?.instructions ?? [])];\n const contextFiles: NonNullable<TanyaRunContext[\"contextFiles\"]> = [...(runContext?.contextFiles ?? [])];\n const metadata: Record<string, unknown> = { ...(runContext?.metadata ?? {}) };\n const expectedReport: Record<string, unknown> = { ...(runContext?.expected_report ?? {}) };\n const verificationCommands = [...(runContext?.verification?.commands ?? [])];\n let didMaterializeContext = false;\n\n if (options.enableBrief !== false) {\n brief = await buildTaskBrief({\n workspace: options.cwd,\n task: options.prompt,\n });\n metadata.autoBrief = brief;\n metadata.autoBriefEnforceArtifacts = brief.artifacts.length > 0;\n instructions.push(\n \"Tanya generated an automatic task brief before the run. Use it to choose context files, artifacts, capability packs, tools, and verification.\",\n \"If the automatic task brief lists artifact candidates and you change code, read at least one relevant artifact or explicitly explain why none applies before the final report.\",\n );\n if (shouldTreatAsCodingTask(brief, runContext)) {\n expectedReport.verification = true;\n expectedReport.artifact_reuse = true;\n expectedReport.context_review = true;\n // Skip auto-recommended verification commands when the caller explicitly\n // overrode the list (e.g. via --require-verification). Preserves caller intent.\n if (!metadata.verificationOverridden) {\n for (const command of brief.verification) verificationCommands.push(command);\n }\n runContext = {\n ...(runContext ?? {}),\n task: {\n ...(runContext?.task ?? {}),\n kind: \"coding\",\n title: runContext?.task?.title ?? brief.task.slice(0, 120),\n },\n };\n }\n }\n\n if (options.enableObsidian !== false && options.obsidianVault?.trim()) {\n const materialized = await materializeObsidianContext({\n workspace: options.cwd,\n vaultPath: options.obsidianVault,\n query: options.prompt,\n maxResults: 5,\n ...(options.keepContext !== undefined ? { keepContext: options.keepContext } : {}),\n });\n if (materialized.contextFiles.length > 0) {\n didMaterializeContext = true;\n contextFiles.push(...materialized.contextFiles);\n metadata.obsidianContext = {\n vaultConfigured: true,\n noteCount: materialized.notes.length,\n notes: materialized.notes.map((note) => ({\n path: note.path,\n title: note.title,\n score: note.score,\n reason: note.reason,\n })),\n };\n instructions.push(\n \"Relevant Obsidian note excerpts were materialized under .tania/context/obsidian.\",\n \"Read relevant Obsidian context paths before implementing if the task depends on prior decisions, project memory, or historical fixes.\",\n );\n } else {\n metadata.obsidianContext = { vaultConfigured: true, noteCount: 0 };\n }\n }\n\n if (!brief && contextFiles.length === 0 && instructions.length === (runContext?.instructions?.length ?? 0)) {\n return runContext;\n }\n\n return {\n ...(runContext ?? {}),\n ...(runContext?.task ? { task: runContext.task } : {}),\n ...(contextFiles.length > 0 ? { contextFiles } : {}),\n ...(instructions.length > 0 ? { instructions: unique(instructions) } : {}),\n ...(verificationCommands.length > 0 ? { verification: { commands: unique(verificationCommands) } } : {}),\n ...(Object.keys(expectedReport).length > 0 ? { expected_report: expectedReport } : {}),\n metadata: {\n ...metadata,\n autoContext: true,\n tanyaMaterializedContext: didMaterializeContext,\n keepMaterializedContext: options.keepContext === true,\n ...(options.obsidianVault ? { obsidianVault: options.obsidianVault } : {}),\n },\n };\n}\n"],"mappings":";;;AAAA,SAAS,cAAAA,cAAY,gBAAAC,qBAAoB;AACzC,SAAS,QAAAC,QAAM,WAAAC,iBAAe;AAC9B,SAAS,SAAS,cAAc;;;ACFhC,SAAS,YAAY,oBAAoB;AACzC,SAAS,YAAY;AACrB,SAAS,aAAa;;;ACFtB,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,uBAAuB,OAAO,GAAG;AACjE;AAEO,SAAS,SAAS,QAA4C,CAAC,GAAG,KAAqB;AAC5F,QAAM,UAAU,QAAQ,OAAO,GAAG;AAClC,MAAI,YAAY,OAAW,QAAO;AAElC,QAAM,SAAS,UAAU,GAAG;AAC5B,MAAI,CAAC,OAAQ,QAAO;AAEpB,QAAM,cAAc,QAAQ,OAAO,MAAM;AACzC,MAAI,gBAAgB,OAAW,QAAO;AACtC,gBAAc,QAAQ,GAAG;AACzB,SAAO;AACT;AAEO,SAAS,eAAe,OAA2C,KAAa,UAA0B;AAC/G,QAAM,MAAM,SAAS,OAAO,GAAG;AAC/B,MAAI,CAAC,IAAK,QAAO;AACjB,QAAM,SAAS,OAAO,GAAG;AACzB,SAAO,OAAO,SAAS,MAAM,IAAI,SAAS;AAC5C;;;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U,WAAW;AAAA,IACrB;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,EACF,EAAE,KAAK,IAAI;AACb;AAEA,SAAS,yBAAyB,aAAqB,aAA6B;AAClF,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,wBAAwB,YAAY,YAAY,CAAC;AAAA,IAC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C,QAAQ;AACpB,QAAM,UAAU,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG;AAC/D,UAAQ,MAAM,gBAAgB,OAAO,EAAE;AACvC,UAAQ,WAAW;AACrB,CAAC;","names":["existsSync","readFileSync","join","resolve","readFileSync","input","existsSync","resolve","input","resolve","input","existsSync","dirname","resolve","relative","existsSync","mkdir","readFile","writeFile","basename","dirname","isAbsolute","join","relative","spawn","sharp","dirname","input","asString","dirname","existsSync","mkdir","writeFile","dirname","join","asRecord","input","asOptionalString","asOptionalNumber","optionalStringArray","ensureRelativePath","sanitizeName","existsSync","sleep","resolve","writeFile","join","mkdir","dirname","basename","readFile","existsSync","basename","join","relative","resolve","asRecord","input","asString","asOptionalString","asOptionalNumber","normalizePath","join","relative","readFile","basename","text","terms","resolve","existsSync","existsSync","mkdir","readdir","readFile","stat","writeFile","dirname","join","relative","resolve","ignoredNames","normalizePath","input","asRecord","input","asOptionalString","asOptionalNumber","asOptionalBoolean","ignoredNames","basename","asRecord","input","asString","asOptionalNumber","asOptionalString","asOptionalBoolean","existsSync","collectFiles","join","relative","resolve","spawn","output","timer","text","ensureRelativePath","isAbsolute","readFile","mkdir","dirname","writeFile","sharp","input","mkdir","readFile","stat","writeFile","dirname","join","appendFile","mkdir","readFile","createHash","dirname","join","join","taskSignature","createHash","mkdir","dirname","appendFile","readFile","writeFile","mkdir","join","dirname","appendFile","mkdir","writeFile","dirname","join","text","readFile","writeFile","mkdir","existsSync","join","readdir","readFile","join","isRecord","recordArray","text","text","text","text","text","text","readdir","realpath","stat","relative","resolve","uniqueSorted","execFile","existsSync","readdir","stat","resolve","promisify","execFileAsync","text","uniqueSorted","hasSuccessfulVerification","existsSync","readFileSync","join","spawnSync","existsSync","readdirSync","readFileSync","join","relative","ignoredNames","text","output","readPackageScripts","existsSync","readdirSync","readFileSync","statSync","dirname","join","relative","estimateTokens","text","join","statSync","join","existsSync","readFileSync","existsSync","mkdirSync","readdirSync","writeFileSync","cp","mkdir","rm","stat","dirname","isAbsolute","join","relative","resolve","input","text","uniqueSorted","manifest","finalMessage","message","toolCall","finalMessageWithFooter","spawnSync","existsSync","readFileSync","join","readPackageScripts","output","mkdir","readFile","readdir","rm","writeFile","dirname","isAbsolute","join","spawnSync","sharp","findExecutable","spawnSync","run","escapeXml","isAbsolute","readFile","mkdir","input","join","readdir","sharp","text","rect","scaled","basename","writeFile","rm","mkdtemp","dirname","execFile","mkdir","writeFile","join","promisify","input","execFileAsync","promisify","execFile","join","mkdir","writeFile","mkdir","readFile","readdir","stat","writeFile","dirname","join","resolve","unique","unique","readFileSync","resolve","existsSync","text","join","cwd","input","formats","outputDir","basename","result","readdirSync","output"]}
|