import { exec, execFile, spawn } from "node:child_process"; import { readFileSync } from "node:fs"; import { mkdir, readdir, readFile, stat } from "node:fs/promises"; import { dirname, join } from "node:path"; import { fileURLToPath } from "node:url"; import { promisify } from "node:util"; import type { CheckTask } from "./tasks.js"; const execAsync = promisify(exec); const execFileAsync = promisify(execFile); /** Safety watchdog, not a performance limit: pauses runs that stopped making progress. */ export const DEFAULT_STALL_TIMEOUT_MS = 15 * 60 * 1_000; const ACCEPTANCE_TIMEOUT_MS = 120_000; const DIFF_BUDGET_CHARS = 10_000; export interface PiCli { node: string; script: string; version?: string; } function readPiPackage(pkgPath: string): PiCli | undefined { try { const pkg: unknown = JSON.parse(readFileSync(pkgPath, "utf8")); if ( typeof pkg === "object" && pkg !== null && (pkg as { name?: unknown }).name === "@earendil-works/pi-coding-agent" ) { const bin = (pkg as { bin?: unknown }).bin; const script = typeof bin === "string" ? bin : typeof bin === "object" && bin !== null && typeof (bin as Record).pi === "string" ? ((bin as Record).pi as string) : undefined; if (script) return { node: process.execPath, script: join(dirname(pkgPath), script), version: (pkg as { version?: string }).version, }; } } catch { // Keep looking elsewhere. } return undefined; } /** * Resolves the host's own pi CLI so candidates always run the same harness * version: prefer the running pi, then a nested node_modules install. */ function findPiCliUp(startDir: string): PiCli | undefined { let dir = startDir; for (;;) { const found = readPiPackage(join(dir, "package.json")) ?? readPiPackage( join( dir, "node_modules", "@earendil-works", "pi-coding-agent", "package.json", ), ); if (found) return found; const parent = dirname(dir); if (parent === dir) return undefined; dir = parent; } } export function piCliCommand(): PiCli { const fromRunning = process.argv[1] ? findPiCliUp(dirname(process.argv[1])) : undefined; if (fromRunning) return fromRunning; const fromSelf = findPiCliUp(dirname(fileURLToPath(import.meta.url))); if (fromSelf) return fromSelf; throw new Error("could not locate the pi CLI bundle for IQ check"); } export interface CandidateUsage { inputTokens: number; outputTokens: number; cost: number; } export type CheckStepExitState = | "completed" | "nonzero" | "stalled" | "spawn-error" | "cancelled"; export interface CheckStepSpawnOptions { pi: PiCli; workspaceDir: string; sessionDir: string; /** Session file resumed from the previous step; pass the path, not the id. */ sessionFile?: string; modelReference: string; message: string; stallTimeoutMs?: number; signal: AbortSignal; env?: NodeJS.ProcessEnv; } export interface CheckStepResult { exitState: CheckStepExitState; detail?: string; sessionFile?: string; ids: Set; usage: CandidateUsage; } export function emptyCandidateUsage(): CandidateUsage { return { inputTokens: 0, outputTokens: 0, cost: 0 }; } function tail(text: string, limit = 500): string { return text.length <= limit ? text : text.slice(-limit); } /** Keeps the start, where error headers live; tail() would cut them off. */ function head(text: string, limit: number): string { return text.length <= limit ? text : `${text.slice(0, limit)}…`; } /** Reads ids and assistant usage from a session file; missing files read as empty. */ export async function scanSessionFile( path: string, ): Promise<{ ids: Set; usage: CandidateUsage; entries: number }> { const ids = new Set(); const usage = emptyCandidateUsage(); let entries = 0; let raw: string; try { raw = await readFile(path, "utf8"); } catch { return { ids, usage, entries }; } for (const line of raw.split("\n")) { if (!line.trim()) continue; let parsed: unknown; try { parsed = JSON.parse(line); } catch { continue; } if ( typeof parsed !== "object" || parsed === null || typeof (parsed as { id?: unknown }).id !== "string" ) continue; entries++; ids.add((parsed as { id: string }).id); const message = (parsed as { message?: unknown }).message; if ( typeof message === "object" && message !== null && (message as { role?: unknown }).role === "assistant" ) { const u = (message as { usage?: unknown }).usage; if (typeof u === "object" && u !== null) { const record = u as Record; for (const key of ["input", "output"] as const) { const value = record[key]; if (typeof value === "number" && Number.isFinite(value)) { usage[key === "input" ? "inputTokens" : "outputTokens"] += value; } } const cost = record.cost; if ( typeof cost === "object" && cost !== null && typeof (cost as { total?: unknown }).total === "number" ) usage.cost += (cost as { total: number }).total; } } } return { ids, usage, entries }; } async function newestSessionFile( sessionDir: string, ): Promise { let newest: { path: string; mtimeMs: number } | undefined; try { for (const file of await readdir(sessionDir)) { if (!file.endsWith(".jsonl")) continue; const path = join(sessionDir, file); const info = await stat(path); if (!newest || info.mtimeMs > newest.mtimeMs) newest = { path, mtimeMs: info.mtimeMs }; } } catch { return undefined; } return newest?.path; } /** * Delivers one recipe item to the candidate as a scripted user turn. * The stall watchdog is a safety pause for runs that stopped producing * output; it never judges the candidate's quality. */ export async function runCheckStep( options: CheckStepSpawnOptions, ): Promise { const { pi, workspaceDir, sessionDir, sessionFile: resumedFile, modelReference, message, signal, } = options; await mkdir(sessionDir, { recursive: true }); if (signal.aborted) return { exitState: "cancelled", ids: new Set(), usage: emptyCandidateUsage(), }; const args = [ pi.script, "--mode", "json", "--no-extensions", "--no-skills", "--no-themes", "--session-dir", sessionDir, ...(resumedFile ? ["--session", resumedFile] : []), "--model", modelReference, message, ]; const env = { ...(options.env ?? process.env) }; env.PI_SKIP_VERSION_CHECK = "1"; let exitState: CheckStepExitState | undefined; let detail: string | undefined; let stdoutTail = ""; let stderrTail = ""; let lastOutputAt = Date.now(); const settled = Promise.withResolvers(); const child = spawn(pi.node, args, { cwd: workspaceDir, env, stdio: ["ignore", "pipe", "pipe"], }); const stallTimer = setInterval(() => { const silentFor = Date.now() - lastOutputAt; if (silentFor > (options.stallTimeoutMs ?? DEFAULT_STALL_TIMEOUT_MS)) { exitState = "stalled"; detail = `no output for ${Math.round(silentFor / 1000)}s`; child.kill("SIGTERM"); setTimeout(() => child.kill("SIGKILL"), 5_000).unref?.(); } }, 1_000); stallTimer.unref?.(); const onAbort = () => { if (exitState === undefined) { exitState = "cancelled"; child.kill("SIGTERM"); setTimeout(() => child.kill("SIGKILL"), 5_000).unref?.(); } }; signal.addEventListener("abort", onAbort, { once: true }); const collect = ( stream: NodeJS.ReadableStream, keep: (t: string) => void, ) => { stream.on("data", (chunk: Buffer) => { lastOutputAt = Date.now(); keep(chunk.toString("utf8")); }); }; collect(child.stdout, (t) => { stdoutTail = tail(stdoutTail + t); }); collect(child.stderr, (t) => { stderrTail = tail(stderrTail + t); }); child.on("error", (error) => { if (exitState === undefined) { exitState = "spawn-error"; detail = error.message; } }); child.on("close", (code) => { if (exitState === undefined) exitState = code === 0 ? "completed" : "nonzero"; if (exitState === "nonzero" && code !== 0) detail = `exit ${code}${stderrTail ? `: ${head(stderrTail, 200)}` : ""}`; settled.resolve(); }); await settled.promise; clearInterval(stallTimer); signal.removeEventListener("abort", onAbort); // pi matches --session by id or by path, and resumed session files are // named "_.jsonl", so the runner always tracks the path. const sessionFile = (resumedFile && (await stat(resumedFile).then( () => resumedFile, () => undefined, ))) ?? (await newestSessionFile(sessionDir)); const scan = sessionFile ? await scanSessionFile(sessionFile) : { ids: new Set(), usage: emptyCandidateUsage(), entries: 0 }; const finalState: CheckStepExitState = exitState ?? "nonzero"; if (finalState === "stalled" && !detail) detail = tail(stdoutTail || stderrTail, 200); return { exitState: finalState, detail, sessionFile, ids: scan.ids, usage: scan.usage, }; } export interface CheckAcceptanceResult { label: string; command: string; exitCode: number | null; passed: boolean; output: string; } export async function runAcceptance( workspaceDir: string, task: CheckTask, ): Promise { const results: CheckAcceptanceResult[] = []; for (const check of task.acceptance.checks) { // Command checks run in the workspace; script checks run from the // fixture directory so the candidate cannot tamper with them. const spec = "command" in check ? { label: check.label, display: check.command, expected: check.expectExit ?? 0, run: () => execAsync(check.command, { cwd: workspaceDir, timeout: ACCEPTANCE_TIMEOUT_MS, maxBuffer: 1024 * 1024, }), } : { label: check.label, display: `node ${check.script}`, expected: 0, run: () => execFileAsync(process.execPath, [join(task.dir, check.script)], { cwd: workspaceDir, timeout: ACCEPTANCE_TIMEOUT_MS, maxBuffer: 1024 * 1024, }), }; try { const { stdout } = await spec.run(); results.push({ label: spec.label, command: spec.display, exitCode: 0, passed: spec.expected === 0, output: tail(stdout.trim(), 300), }); } catch (error) { const exitCode = typeof (error as { code?: unknown }).code === "number" ? ((error as { code: number }).code as number) : null; results.push({ label: spec.label, command: spec.display, exitCode, passed: exitCode === spec.expected && exitCode !== null, output: tail( ( (error as { stderr?: unknown }).stderr ?? (error as { message?: unknown }).message ?? "" ).toString(), 300, ), }); } } return results; } export interface GitEndState { pathsTouched: string[]; diffStat: string; diff: string; } export async function gitEndState(workspaceDir: string): Promise { await execFileAsync("git", ["add", "-A"], { cwd: workspaceDir }); const { stdout: status } = await execFileAsync( "git", ["status", "--porcelain"], { cwd: workspaceDir, maxBuffer: 1024 * 1024 }, ); const pathsTouched = status .split("\n") .map((line) => line.trim()) .filter(Boolean) .map((line) => { const path = line.slice(2).trim(); const arrow = path.indexOf(" -> "); return arrow >= 0 ? path.slice(arrow + 4) : path; }); const { stdout: diffStat } = await execFileAsync( "git", ["diff", "--cached", "--stat"], { cwd: workspaceDir, maxBuffer: 1024 * 1024 }, ); const { stdout: diff } = await execFileAsync("git", ["diff", "--cached"], { cwd: workspaceDir, maxBuffer: 4 * 1024 * 1024, }); return { pathsTouched, diffStat: tail(diffStat.trim(), 2_000), diff: diff.length <= DIFF_BUDGET_CHARS ? diff : `${diff.slice(0, DIFF_BUDGET_CHARS)}\n…[diff truncated]…`, }; } export function forbiddenViolations( pathsTouched: readonly string[], forbidden: readonly string[], ): string[] { return pathsTouched.filter((path) => forbidden.some((entry) => path === entry || path.startsWith(`${entry}/`)), ); }