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C,gBAAgB,CAAC,CAiD5F","sourcesContent":["import { chmodSync, existsSync, mkdirSync, mkdtempSync, readdirSync, rmSync, statSync, writeFileSync } from \"node:fs\";\nimport { readFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { spawn } from \"node:child_process\";\nimport { loadProjectTasks } from \"./tasks.js\";\nimport type { ProjectTask } from \"./tasks.js\";\nimport type { ContributionStore } from \"./store.js\";\nimport { readProjectConfig } from \"./project-config.js\";\n\nfunction listProduct(projectDir: string, productDir: string): string {\n\tconst base = join(projectDir, productDir);\n\tconst rootExists = existsSync(base) || existsSync(join(projectDir, \"package.json\"));\n\tif (!rootExists) {\n\t\treturn `empty (nothing built yet — ${productDir} does not exist and there is no package.json at the repository root)`;\n\t}\n\tconst entries: string[] = [];\n\tconst walk = (dir: string, depth: number): void => {\n\t\tif (depth > 2 || entries.length > 25) {\n\t\t\treturn;\n\t\t}\n\t\tfor (const name of readdirSync(dir)) {\n\t\t\tif (name === \"node_modules\" || name === \".git\" || name === \".agora\" || name === \"tasks\") {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst full = join(dir, name);\n\t\t\tentries.push(full.slice(projectDir.length + 1) + (statSync(full).isDirectory() ? \"/\" : \"\"));\n\t\t\tif (statSync(full).isDirectory()) {\n\t\t\t\twalk(full, depth + 1);\n\t\t\t}\n\t\t}\n\t};\n\twalk(existsSync(base) ? base : projectDir, 0);\n\treturn entries.length === 0 ? \"empty directories only\" : entries.join(\"\\n\");\n}\n\nexport interface GeneratedTask {\n\tname: string;\n\ttaskMd: string;\n\tverifySh: string;\n}\n\nconst NAME_PATTERN = /^[a-z0-9][a-z0-9-]{2,48}$/;\n\n// LLMs often emit literal newlines/tabs inside JSON string values, which\n// strict JSON.parse rejects. Escape raw control characters while inside a\n// string before parsing.\nfunction repairJsonish(raw: string): string {\n\tlet out = \"\";\n\tlet inString = false;\n\tlet escaped = false;\n\tfor (const ch of raw) {\n\t\tif (escaped) {\n\t\t\tout += ch;\n\t\t\tescaped = false;\n\t\t\tcontinue;\n\t\t}\n\t\tif (ch === \"\\\\\") {\n\t\t\tout += ch;\n\t\t\tescaped = true;\n\t\t\tcontinue;\n\t\t}\n\t\tif (ch === '\"') {\n\t\t\tinString = !inString;\n\t\t\tout += ch;\n\t\t\tcontinue;\n\t\t}\n\t\tif (inString && ch === \"\\n\") {\n\t\t\tout += \"\\\\n\";\n\t\t\tcontinue;\n\t\t}\n\t\tif (inString && ch === \"\\r\") {\n\t\t\tout += \"\\\\r\";\n\t\t\tcontinue;\n\t\t}\n\t\tif (inString && ch === \"\\t\") {\n\t\t\tout += \"\\\\t\";\n\t\t\tcontinue;\n\t\t}\n\t\tout += ch;\n\t}\n\treturn out;\n}\n\nexport function parseGeneratedTask(raw: string): GeneratedTask | null {\n\tconst fenced = raw.replace(/```json|```/g, \"\");\n\tconst start = fenced.indexOf(\"{\");\n\tconst end = fenced.lastIndexOf(\"}\");\n\tif (start === -1 || end <= start) {\n\t\treturn null;\n\t}\n\tlet parsed: { name?: string; taskMd?: string; verifySh?: string } | undefined;\n\ttry {\n\t\tparsed = JSON.parse(fenced.slice(start, end + 1)) as typeof parsed;\n\t} catch {\n\t\ttry {\n\t\t\tparsed = JSON.parse(repairJsonish(fenced.slice(start, end + 1))) as typeof parsed;\n\t\t} catch {\n\t\t\treturn null;\n\t\t}\n\t}\n\tif (parsed === undefined) {\n\t\treturn null;\n\t}\n\tconst { name, taskMd, verifySh } = parsed;\n\tif (typeof name !== \"string\" || !NAME_PATTERN.test(name)) {\n\t\treturn null;\n\t}\n\tif (typeof taskMd !== \"string\" || taskMd.trim().length < 10) {\n\t\treturn null;\n\t}\n\tif (typeof verifySh !== \"string\" || verifySh.trim().length < 8) {\n\t\treturn null;\n\t}\n\treturn { name, taskMd, verifySh };\n}\n\nexport function writeGeneratedTask(projectDir: string, task: GeneratedTask): ProjectTask {\n\tconst taskDir = join(projectDir, \"tasks\", task.name);\n\tif (existsSync(taskDir)) {\n\t\tthrow new Error(`Generated task directory already exists: ${taskDir}`);\n\t}\n\tmkdirSync(taskDir, { recursive: true });\n\twriteFileSync(join(taskDir, \"TASK.md\"), `${task.taskMd.trim()}\\n`);\n\twriteFileSync(join(taskDir, \"verify.sh\"), `${task.verifySh.trim()}\\n`);\n\tchmodSync(join(taskDir, \"verify.sh\"), 0o755);\n\treturn {\n\t\tname: task.name,\n\t\tdir: taskDir,\n\t\tdescription: task.taskMd.trim(),\n\t\tverifyPath: join(taskDir, \"verify.sh\"),\n\t};\n}\n\nfunction runScript(path: string, cwd: string): Promise<number> {\n\treturn new Promise((resolve) => {\n\t\tconst child = spawn(path, [], { cwd });\n\t\tchild.on(\"error\", () => resolve(-1));\n\t\tchild.on(\"exit\", (code) => resolve(code ?? -1));\n\t});\n}\n\nconst GENERATOR_SYSTEM = `You plan the next increment of a software project.\nYou receive the project goal, the finished tasks, and the open tasks.\nYou propose ONE new task that moves the project toward the goal.\nThe task must not repeat finished work. The task must be small enough for one session.\nThe product lives in the directory given below. New tasks work on that directory.\nThe verify script must fail against the current product state. It must pass after the task is done.\nPrefer verify scripts that run the product and check its output. Avoid fragile checks.\nOUTPUT CONTRACT: the first character of your response is { and the last is }.\nNo narration. No analysis. No markdown fences. If you notice gaps like missing\ntests, encode them as the task itself.\nRespond with ONLY JSON:\n{\"name\":\"kebab-case-name\",\"taskMd\":\"# Title\\\\ninstructions in markdown\",\"verifySh\":\"#!/usr/bin/env bash\\\\nset -euo pipefail\\\\ncheck commands\"}\nIf the goal is complete and no useful task remains, respond with ONLY the word: complete`;\n\nexport interface GenerateNextTaskDeps {\n\tprojectDir: string;\n\tgoalPath: string;\n\tstore: ContributionStore;\n\tcaller: { call(systemPrompt: string, userPrompt: string): Promise<string> };\n\tproductDir?: string;\n\thint?: string;\n}\n\nexport type GenerationResult =\n\t| { status: \"installed\"; task: ProjectTask }\n\t| { status: \"complete\" }\n\t| { status: \"unparseable\"; raw: string }\n\t| { status: \"already-satisfied\"; name: string }\n\t| { status: \"duplicate-name\"; name: string };\n\nexport async function generateNextTask(deps: GenerateNextTaskDeps): Promise<GenerationResult> {\n\tconst goal = readFileSync(deps.goalPath, \"utf8\");\n\tconst contributions = await deps.store.query();\n\tconst finished = contributions\n\t\t.filter((c) => c.type === \"result\" && c.metric?.value === 1)\n\t\t.map((c) => c.tags.find((tag) => tag.startsWith(\"task:\"))?.slice(5) ?? \"\")\n\t\t.filter((name) => name.length > 0);\nconst openTasks = loadProjectTasks(deps.projectDir);\nconst { productAtRoot, productDir: configuredProductDir } = readProjectConfig(deps.projectDir);\nconst productDir = deps.productDir ?? configuredProductDir ?? (productAtRoot ? \".\" : \"tasks/product/workspace\");\nconst productListing = listProduct(deps.projectDir, productDir);\nconst exhaustedNames = [...new Set(contributions\n\t.filter((c) => c.type === \"failure\")\n\t.map((c) => c.tags.find((tag) => tag.startsWith(\"task:\"))?.slice(5) ?? \"\")\n\t.filter((name) => name.length > 0))];\nconst prompt = [\n\t`Goal:\\n${goal}`,\n\t`Product directory: ${productDir}`,\n\t`Current product state: ${productListing}`,\n\t`Finished tasks: ${finished.join(\", \") || \"none\"}`,\n\t`Existing task directories: ${openTasks.map((task) => task.name).join(\", \") || \"none\"}`,\n\t`Exhausted tasks (attempted but never passed; if this work still matters, propose a DIFFERENT approach with a NEW name): ${exhaustedNames.join(\", \") || \"none\"}`,\n\t\t\"The next task must match the CURRENT product state. If the product is empty, the next task is the project scaffold (Vite + TypeScript install, npm run dev boots, npm run build and npm test pass with one trivial test).\",\n\t\t...(deps.hint ? [deps.hint] : []),\n\t\t\"Propose the next task.\",\n\t].join(\"\\n\\n\");\n\tconst raw = await deps.caller.call(GENERATOR_SYSTEM, prompt);\n\tif (raw.trim().toLowerCase().startsWith(\"complete\")) {\n\t\treturn { status: \"complete\" };\n\t}\n\tconst parsed = parseGeneratedTask(raw);\n\tif (!parsed) {\n\t\treturn { status: \"unparseable\", raw };\n\t}\n\tif (existsSync(join(deps.projectDir, \"tasks\", parsed.name))) {\n\t\treturn { status: \"duplicate-name\", name: parsed.name };\n\t}\n\t// Quality gate: the new verify script must fail against the current product,\n\t// otherwise the task encodes no new work.\n\tconst staging = mkdtempSync(join(deps.projectDir, \"tasks\", \".staging-\"));\n\trmSync(staging, { recursive: true, force: true });\n\tconst staged = writeGeneratedTask(staging, parsed);\n\tconst exit = await runScript(staged.verifyPath, staged.dir);\n\trmSync(staging, { recursive: true, force: true });\n\tif (exit === 0) {\n\t\treturn { status: \"already-satisfied\", name: parsed.name };\n\t}\n\tconst task = writeGeneratedTask(deps.projectDir, parsed);\n\treturn { status: \"installed\", task };\n}\n"]}