/** * Orchestrator Extension - Full-cycle project planning and execution * * WORKFLOW (single command): * /plan → 5 sequential agent phases → each with its own model * * The orchestrator uses event-driven phase chaining: * 1. Send phase 1 message with model A * 2. Detect when agent goes idle (output event + polling) * 3. Switch to model B, send phase 2 * 4. Repeat until all 5 phases complete * * Commands: * /plan — Full workflow: plan + execute with agents * /run — Re-execute an existing plan * /plans — List plans and their execution status */ import { existsSync, readFileSync, unlinkSync, writeFileSync } from "node:fs"; import { mkdir, readdir, readFile, writeFile } from "node:fs/promises"; import { join } from "node:path"; import { Type } from "@sinclair/typebox"; import type { ExtensionAPI } from "phi-code"; import { getAgentDir, isDestructiveCommand, runParallel } from "phi-code"; import type { Api, Model } from "phi-code-ai"; import { type AgentDef, loadAgentDef } from "./providers/agent-def.ts"; import { runCandidateFanout } from "./providers/candidate-fanout.ts"; import { diffChangedLines } from "./providers/candidate-select.ts"; import { buildVerifyInstruction, debugPhaseInstructions, reproAuditInstruction, singleShotInstruction, } from "./providers/debug-build-commands.ts"; import { decideVerify, type FailingState, parseFailingState, type VerifiedCandidate, } from "./providers/debug-contract.ts"; import { decideEscalation, parseReproCmd, pickCandidateModels, type RoutingLike } from "./providers/escalation.ts"; import { passed, runCommand, tail } from "./providers/execution.ts"; import { defaultExplorerSpecs, type ExplorerResult, mergeExplorerResults, READONLY_EXPLORER_TOOLS, runExplorer, } from "./providers/explore-fanout.ts"; import { composePhaseSystemPrompt, resolveModelRef } from "./providers/orchestrator-helpers.ts"; import { analyzePhaseMessages, buildNextBrief, decidePhaseTransition, resolvePhaseOutcome, type StructuredPhaseResult, } from "./providers/phase-machine.ts"; import { resolveSandbox, type Sandbox } from "./providers/sandbox.ts"; import { appendRunRecord, buildRunRecord, type PhaseRecord, parseRunsJsonl, summarizeRuns, } from "./providers/telemetry.ts"; import { discoverTargetedTests, fsSeamsFor } from "./providers/test-discovery.ts"; import { looksLikeBugReport, triage } from "./providers/triage.ts"; // ─── Types ─────────────────────────────────────────────────────────────── /** Wall-clock budget of the /fix single shot (measured: a real shot runs 8 to 18 min). */ const FIX_SHOT_BUDGET_MS = 25 * 60 * 1000; interface TaskDef { title: string; description: string; agent?: string; priority?: string; dependencies?: number[]; subtasks?: string[]; } // ─── Extension ─────────────────────────────────────────────────────────── export default function orchestratorExtension(pi: ExtensionAPI) { const plansDir = join(process.cwd(), ".phi", "plans"); async function ensurePlansDir() { await mkdir(plansDir, { recursive: true }); } function timestamp(): string { return new Date().toISOString().replace(/[:.]/g, "-").replace("T", "_").slice(0, 19); } // ─── Plan File Generators ──────────────────────────────────────── function generateSpec(p: { title: string; description: string; goals: string[]; requirements: string[]; architecture?: string[]; constraints?: string[]; successCriteria?: string[]; tasks: TaskDef[]; }): string { let spec = `# ${p.title}\n\n`; spec += `**Created:** ${new Date().toLocaleString()}\n\n`; spec += `## Description\n\n${p.description}\n\n`; spec += `## Goals\n\n`; p.goals.forEach((g, i) => { spec += `${i + 1}. ${g}\n`; }); spec += "\n## Requirements\n\n"; p.requirements.forEach((r) => { spec += `- ${r}\n`; }); spec += "\n"; if (p.architecture?.length) { spec += `## Architecture\n\n`; p.architecture.forEach((a) => { spec += `- ${a}\n`; }); spec += "\n"; } if (p.constraints?.length) { spec += `## Constraints\n\n`; p.constraints.forEach((c) => { spec += `- ${c}\n`; }); spec += "\n"; } if (p.successCriteria?.length) { spec += `## Success Criteria\n\n`; p.successCriteria.forEach((s) => { spec += `- [ ] ${s}\n`; }); spec += "\n"; } spec += `## Task Overview\n\n| # | Task | Agent | Priority | Dependencies |\n|---|------|-------|----------|-------------|\n`; p.tasks.forEach((t, i) => { const deps = t.dependencies?.map((d) => `#${d}`).join(", ") || "—"; spec += `| ${i + 1} | ${t.title} | ${t.agent || "code"} | ${t.priority || "medium"} | ${deps} |\n`; }); spec += `\n---\n*Generated by Phi Code Orchestrator*\n`; return spec; } function generateTodo(title: string, tasks: TaskDef[]): string { let todo = `# TODO: ${title}\n\n`; todo += `**Created:** ${new Date().toLocaleString()}\n`; todo += `**Tasks:** ${tasks.length}\n**Status:** executing\n\n`; tasks.forEach((t, i) => { const agentTag = t.agent ? ` [${t.agent}]` : ""; const prioTag = t.priority === "high" ? " 🔴" : t.priority === "low" ? " 🟢" : " 🟡"; const depsTag = t.dependencies?.length ? ` (after #${t.dependencies.join(", #")})` : ""; todo += `## Task ${i + 1}: ${t.title}${prioTag}${agentTag}${depsTag}\n\n- [ ] ${t.description}\n`; if (t.subtasks) t.subtasks.forEach((st) => { todo += ` - [ ] ${st}\n`; }); todo += "\n"; }); todo += `---\n\n## Progress\n\n- Total: ${tasks.length} tasks\n`; todo += `- High priority: ${tasks.filter((t) => t.priority === "high").length}\n`; todo += `- Agents: ${[...new Set(tasks.map((t) => t.agent || "code"))].join(", ")}\n`; return todo; } // ─── Orchestrate Tool — Structured planning with prompt-architect pattern ─── pi.registerTool({ name: "orchestrate", label: "Project Orchestrator", description: "Create a structured project plan with spec, todo, and task breakdown. Forces the model to decompose the project into goals, requirements, architecture, constraints, and success criteria before execution.", promptSnippet: "Plan + structure projects using the prompt-architect pattern. Each task gets [CONTEXT] → [TASK] → [FORMAT] → [CONSTRAINTS].", promptGuidelines: [ // NOTE: The old guideline "When asked to plan or build a project, call the orchestrate tool" // was REMOVED because it hijacked the /plan command flow. The orchestrate tool is now // only called explicitly or when the model decides structured planning is needed outside of /plan. "IMPORTANT: Do NOT call orchestrate during /plan orchestration phases. The /plan command handles its own workflow.", "Structure each task description using the prompt-architect pattern: [CONTEXT] what exists and why → [TASK] what to do specifically → [FORMAT] expected output → [CONSTRAINTS] rules and limitations.", "Assign agent types strategically: 'explore' (read-only analysis), 'plan' (architecture), 'code' (implementation), 'test' (write+run tests), 'review' (quality audit).", "Set dependencies to maximize parallelism: tasks without dependencies run simultaneously.", "Set priority=high for critical-path tasks, medium for standard work, low for nice-to-haves.", ], parameters: Type.Object({ title: Type.String({ description: "Concise project title" }), description: Type.String({ description: "Full project description: what to build, why, and any relevant context", }), goals: Type.Union([Type.Array(Type.String()), Type.String()], { description: "Measurable project goals (what success looks like)", }), requirements: Type.Union([Type.Array(Type.String()), Type.String()], { description: "Technical and functional requirements", }), architecture: Type.Optional( Type.Union([Type.Array(Type.String()), Type.String()], { description: "Architecture decisions, tech stack choices, trade-offs", }), ), tasks: Type.Array( Type.Object({ title: Type.String({ description: "Clear, action-oriented task title" }), description: Type.String({ description: "SELF-CONTAINED task description. Include ALL context the sub-agent needs.", }), agent: Type.Optional(Type.String({ description: "Agent type: explore, plan, code, test, review" })), priority: Type.Optional(Type.String({ description: "high, medium, low" })), dependencies: Type.Optional( Type.Array(Type.Number(), { description: "Task numbers this depends on (1-indexed)" }), ), subtasks: Type.Optional( Type.Array(Type.String(), { description: "Specific sub-steps within this task" }), ), }), { description: "Ordered list of tasks" }, ), constraints: Type.Optional( Type.Union([Type.Array(Type.String()), Type.String()], { description: "Hard constraints: things to avoid, rules", }), ), successCriteria: Type.Optional( Type.Union([Type.Array(Type.String()), Type.String()], { description: "How to verify the project is complete", }), ), }), async execute(_toolCallId, params, _signal, _onUpdate, _ctx) { // Block if /plan orchestration is active — prevent hijacking if (orchestrationActive) { return { content: [ { type: "text", text: "⚠️ Orchestration is already active via /plan. Do NOT call orchestrate during /plan phases. Follow the phase instructions instead.", }, ], details: undefined, }; } const raw = params as any; // Normalize string fields to arrays const toArray = (v: any): string[] => { if (!v) return []; if (Array.isArray(v)) return v; if (typeof v === "string") return v .split("\n") .map((s: string) => s.replace(/^[-•*]\s*/, "").trim()) .filter(Boolean); return []; }; const p = { title: raw.title as string, description: raw.description as string, goals: toArray(raw.goals), requirements: toArray(raw.requirements), architecture: raw.architecture ? toArray(raw.architecture) : undefined, tasks: raw.tasks as TaskDef[], constraints: raw.constraints ? toArray(raw.constraints) : undefined, successCriteria: raw.successCriteria ? toArray(raw.successCriteria) : undefined, }; try { await ensurePlansDir(); const ts = timestamp(); const specFile = `spec-${ts}.md`; const todoFile = `todo-${ts}.md`; // Generate and write structured plan files const spec = generateSpec(p); const todo = generateTodo(p.title, p.tasks); await writeFile(join(plansDir, specFile), spec, "utf-8"); await writeFile(join(plansDir, todoFile), todo, "utf-8"); const summary = `📋 **Project "${p.title}" — Structured plan created!**\n\n` + `**Spec:** \`${specFile}\` | **Todo:** \`${todoFile}\`\n\n` + `**Goals:** ${p.goals.length} | **Requirements:** ${p.requirements.length} | **Tasks:** ${p.tasks.length}\n\n` + `The spec and todo files are ready in \`.phi/plans/\`. ` + `Use \`/plan ${p.description.slice(0, 100)}\` to execute with the 5-phase orchestrator, ` + `or work through the tasks manually.`; return { content: [{ type: "text", text: summary }], details: { specFile, todoFile, taskCount: p.tasks.length }, }; } catch (error) { return { content: [{ type: "text", text: `Orchestration failed: ${error}` }], details: { error: String(error) }, }; } }, }); // ─── Orchestration State ───────────────────────────────────────── interface OrchestratorPhase { key: string; label: string; model: string; fallback: string; agent: AgentDef | null; instruction: string; // Set true once this phase has been retried once (transient proxy failure / // timeout / 0-tool-call). Hard cap of one retry per phase. retried?: boolean; // Generic driver (/debug, /build) only: set true once this phase was re-run // after a BLOCKED verdict. One second chance on the fallback model — a hasty // BLOCKED (measured: 51s on sympy-11897) is cheaper to re-check than to // trust — then the halt is honest. blockedRetried?: boolean; // When true, switchModelForPhase resolves the fallback model first (used on retry // to swap to a different model family rather than re-hit the one that just failed). useFallback?: boolean; // 0..4 for the five base phases (explore..review); undefined for synthetic // phases (the review fix + re-review). Used to checkpoint resume position. baseIndex?: number; // Per-phase timeout override (generic driver only). Defaults to // MAX_PHASE_DURATION_MS. Measured need: a /fix single shot legitimately // runs 8–18 min — the flat 10 min cap killed it mid-work and lost its // REPRO-CMD handoff (telemetry: 601s run, phases empty, UNVERIFIED). timeoutMs?: number; } let phaseQueue: OrchestratorPhase[] = []; let orchestrationActive = false; // Which pipeline is running. "plan" keeps the existing 5-phase agent_end path // untouched; "debug"/"build"/"fix" are driven by the separate linear generic // driver so /plan's fragile review-fix + "/5" logic is never engaged for them. let orchestrationMode: "plan" | "debug" | "build" | "fix" = "plan"; // /fix escalation state: the failing state the command started from, whether // the driver-level oracle already ran (it must run exactly once, after the // single-shot phase), and the reproduction the shot itself declared via its // REPRO-CMD handoff line (prose inputs have no runnable check otherwise). let fixContext: { state: FailingState; oracleRan: boolean; reproFromShot?: string } | null = null; // /debug --candidates N state: each FIX candidate's captured patch, the // reproduction command used for deterministic arbitration (from the input or // the REPRODUCE handoff's REPRO-CMD line), and whether arbitration ran. let candidateContext: { total: number; reproCmd?: string; list: { source: string; patch: string }[]; arbitrated: boolean; // Experimental --parallel: FIX specs fanned out to worktrees after LOCALIZE. parallelSpecs?: { model: string; instruction: string }[]; } | null = null; // Telemetry: per-phase records for the current generic run + sandbox_run // invocation count (reset at orchestration start, flushed at finish). let runPhaseRecords: PhaseRecord[] = []; let sandboxExecCount = 0; // Generic driver: the last phase that completed (its effective verdict), so // the final headline is honest: a FAIL or a missing VERIFY verdict must // never end as "finished" green (only BLOCKED used to stop the run). let lastGenericPhase: { key: string; label: string; verdict: string | null } | null = null; // True while the driver runs its async end-of-queue steps (oracle / // arbitration): a duplicate agent_end must not finish the run meanwhile. let genericFinalizing = false; // Cumulative sandbox execution time this orchestration (drift guard #2) and // its budget; per-call cap (#4) is tightenable for batch harnesses via env. let sandboxExecMs = 0; let currentPhaseStartedAt = 0; const SANDBOX_BUDGET_MS = Math.max( 1_000, Number(process.env.PHI_SANDBOX_BUDGET_MS ?? 20 * 60 * 1000) || 20 * 60 * 1000, ); const SANDBOX_MAX_TIMEOUT_S = Math.max(30, Number(process.env.PHI_SANDBOX_MAX_TIMEOUT_S ?? 1800) || 1800); /** Run a git command in cwd; returns stdout ("" on any failure). */ function gitIn(cwd: string, args: string): string { const r = runCommand(`git ${args}`, { cwd, timeoutMs: 60_000 }); return passed(r) ? r.stdout : ""; } let activeAgentPrompt: string | null = null; let _activeAgentTools: string[] | null = null; let savedTools: string[] | null = null; let phasePending = false; // true while waiting for a phase to complete let phaseTimeoutId: ReturnType | null = null; const MAX_PHASE_DURATION_MS = 10 * 60 * 1000; // 10 minutes per phase const MAX_TOOL_CALLS_PER_PHASE = 60; // Safety limit let phaseStartTime: number | null = null; // User's model before /plan started, restored once orchestration ends let originalModel: any | null = null; // Real phase counters for the final summary let completedPhases = 0; let skippedPhases = 0; // The phase currently executing (so agent_end can read its report + apply // phase-specific logic like verdict parsing and the review->fix loop). let currentPhase: OrchestratorPhase | null = null; // Timestamp shared by all phase report file names in the current run. let currentRunTs = ""; // The original /plan description, kept so a checkpoint can be resumed. let currentDescription = ""; // Hard cap: at most one REVIEW->fix->re-REVIEW cycle per run. let reviewFixRounds = 0; // Set true right before an INTERNAL ctx.abort() (phase timeout) so the // resulting agent_end is not mistaken for a user Ctrl+C cancellation. let internalAbort = false; // Structured result emitted by the current phase via the `phase_result` tool // (robust primary path). Reset at each phase start; read in agent_end and // merged with the parsed markdown report (fallback) by resolvePhaseOutcome. // currentPhaseResultKey stamps which phase produced it, so a stale result // from a previous run/phase (or a tool call that lands after the phase // transition) is never mistaken for the current phase's output. let currentPhaseResult: StructuredPhaseResult | null = null; let currentPhaseResultKey: string | null = null; // ─── phase_result Tool — structured phase outcome (robust primary path) ─── // A phase agent CALLS this to emit its verdict/handoff/blocking as data // instead of relying on the orchestrator regex-scraping its markdown report. // It is only meaningful during /plan; outside orchestration it is a no-op so // a stray call never errors. The markdown report is still written (it is the // human-readable artifact); this just makes the machine-read path exact. pi.registerTool({ name: "phase_result", label: "Phase Result", description: "Report THIS /plan phase's structured outcome so the orchestrator reads it exactly instead of parsing your markdown. Call it once, at the end, IN ADDITION to writing your report file. TEST and REVIEW phases MUST call it with a verdict.", promptGuidelines: [ "During a /plan phase, after writing your report file, call phase_result once with your verdict (TEST/REVIEW) and a concise handoff for the next phase.", "verdict: PASS only if you OBSERVED success; FAIL if any blocking issue; BLOCKED if you could not run; SKIP if not applicable.", "blocking: the must-fix findings (REVIEW), one per line. handoff: what is done, open risks, and the single most important next action.", ], parameters: Type.Object({ verdict: Type.Optional( Type.Union([Type.Literal("PASS"), Type.Literal("FAIL"), Type.Literal("BLOCKED"), Type.Literal("SKIP")], { description: "Phase verdict (required for TEST and REVIEW phases)", }), ), blocking: Type.Optional( Type.String({ description: "Must-fix findings, one per line (REVIEW). Empty when none." }), ), handoff: Type.Optional( Type.String({ description: "Concise handoff for the next phase: state, open risks, next action." }), ), }), async execute(_toolCallId, params, _signal, _onUpdate, _ctx) { if (!orchestrationActive) { return { content: [{ type: "text", text: "phase_result is only used during /plan orchestration; ignored here." }], details: undefined, }; } const raw = params as { verdict?: StructuredPhaseResult["verdict"]; blocking?: string; handoff?: string }; // Merge only the fields this call actually set, so a phase that emits // its result across several calls (verdict first, handoff later — a // common LLM pattern) does not erase earlier fields. Start fresh when // the previous result belonged to a different phase. const defined: StructuredPhaseResult = {}; if (raw.verdict !== undefined) defined.verdict = raw.verdict; if (typeof raw.blocking === "string") defined.blocking = raw.blocking; if (typeof raw.handoff === "string") defined.handoff = raw.handoff; const samePhase = currentPhaseResultKey === (currentPhase?.key ?? null); currentPhaseResult = { ...(samePhase && currentPhaseResult ? currentPhaseResult : {}), ...defined }; currentPhaseResultKey = currentPhase?.key ?? null; const parts = [ raw.verdict ? `verdict ${raw.verdict}` : null, raw.blocking?.trim() ? "blocking findings" : null, raw.handoff?.trim() ? "handoff" : null, ].filter(Boolean); return { content: [{ type: "text", text: `Phase result recorded${parts.length ? ` (${parts.join(", ")})` : ""}.` }], details: undefined, }; }, }); // ─── Execution sandbox — the guaranteed oracle ────────────────── // Resolved once per cwd and cached (resolveSandbox probes the Docker daemon). // This is what turns "the agent says it ran the test" into "a real container // ran the test and here is its exit code". // Project trust gates the project-scope shellPath setting (same rule as the bash tool). let sessionSandbox: { cwd: string; trusted: boolean; sandbox: Sandbox } | null = null; function getSessionSandbox(cwd: string, ctx?: { isProjectTrusted?: () => boolean }): Sandbox { let trusted = false; try { trusted = ctx?.isProjectTrusted?.() === true; } catch { trusted = false; } if (!sessionSandbox || sessionSandbox.cwd !== cwd || sessionSandbox.trusted !== trusted) { sessionSandbox = { cwd, trusted, sandbox: resolveSandbox({ cwd, projectTrusted: trusted }) }; } return sessionSandbox.sandbox; } /** * The bash tool's destructive-command gate, applied to commands the * orchestration runs ON THE HOST (local sandbox backend): sandbox_run and the * driver's oracle/arbitration runs of model-declared reproductions would * otherwise bypass it. Docker runs are left alone (container paths such as * /work would be misread as outside the workspace). Returns the block reason. */ function hostGuardReason(command: string, sandbox: Sandbox, cwd: string): string | undefined { if (!orchestrationActive || sandbox.backend !== "local") return undefined; const verdict = isDestructiveCommand(command, cwd); return verdict?.blocked ? (verdict.reason ?? "destructive command") : undefined; } pi.registerTool({ name: "sandbox_run", label: "Sandbox Run", description: "Run a command in the project's guaranteed environment (a Docker container when available) and get its REAL exit code. Use this for the reproduction, the test suite, and acceptance checks in /debug and /build — the verdict MUST come from this tool's result, not from your own reasoning. If it reports SANDBOX UNAVAILABLE, do not fabricate a result — emit BLOCKED.", promptGuidelines: [ "In /debug and /build, run the reproduction, the existing suite, and acceptance/red-team checks with sandbox_run — never claim a pass you did not get back from it.", "A command PASSES iff sandbox_run returns exit 0. Treat any non-zero exit, TIMEOUT, or UNAVAILABLE as not-passing.", "The sandbox mounts the project, so edits you make are visible to the next sandbox_run (fix, then re-run to verify).", ], parameters: Type.Object({ command: Type.String({ description: "The shell command to run in the project sandbox (e.g. 'pytest tests/x.py::test_y').", }), timeoutSeconds: Type.Optional( Type.Number({ description: "Max seconds before the run is killed (default 300)." }), ), }), async execute(_toolCallId, params, _signal, _onUpdate, ctx) { const p = params as { command: string; timeoutSeconds?: number }; const cwd = ctx?.cwd || process.cwd(); // Guard #2 against runtime drift: a cumulative execution budget per // orchestration. Even with async runs, an agent chaining long commands // can eat a whole session — beyond the budget it must conclude with // what it has. (Measured: back-to-back long runs drifted a 25-min cap // to 6h18 before the async fix.) if (orchestrationActive && sandboxExecMs >= SANDBOX_BUDGET_MS) { return { content: [ { type: "text", text: `SANDBOX BUDGET EXHAUSTED — ${Math.round(sandboxExecMs / 60000)} min of cumulative execution used this run (budget ${Math.round(SANDBOX_BUDGET_MS / 60000)} min). No further runs this orchestration: conclude with the evidence you already have, honestly (BLOCKED/PARTIAL if unverified).`, }, ], details: { verdict: "BUDGET_EXHAUSTED", budgetMs: SANDBOX_BUDGET_MS, usedMs: sandboxExecMs }, }; } const sandbox = getSessionSandbox(cwd, ctx); const blockedReason = hostGuardReason(p.command, sandbox, cwd); if (blockedReason) { return { content: [ { type: "text", text: `Command blocked by safety gate: ${blockedReason}\nThis guard is active only during autonomous orchestration.`, }, ], details: { verdict: "BLOCKED_BY_GUARD", reason: blockedReason }, isError: true, }; } if (orchestrationActive) sandboxExecCount++; // Guard #4: per-call cap, tightenable for batch harnesses via env. const result = await sandbox.execAsync(p.command, { timeoutMs: Math.max(1, Math.min(SANDBOX_MAX_TIMEOUT_S, p.timeoutSeconds ?? 300)) * 1000, }); if (orchestrationActive) sandboxExecMs += result.durationMs; const verdict = !sandbox.available() ? "UNAVAILABLE" : result.timedOut ? "TIMEOUT" : passed(result) ? "PASS" : "FAIL"; const text = `[sandbox: ${sandbox.describe()}]\n$ ${p.command}\n→ exit ${result.exitCode ?? "?"} ${verdict}\n\n` + `${tail(result, 60) || "(no output)"}`; return { content: [{ type: "text", text }], details: { backend: sandbox.backend, exitCode: result.exitCode, passed: passed(result), timedOut: result.timedOut, verdict, }, }; }, }); // A phase's report file is not always named -.md: PLAN writes its // handoff into todo-.md and CODE into progress-.md. Map key -> file // stem so the text fallback for HANDOFF/BLOCKING actually finds them. const REPORT_FILE_STEM: Record = { plan: "todo", code: "progress" }; /** Read a phase's report file (.phi/plans/-.md). Null-safe. */ function readPhaseReport(key: string, ts: string): string | null { try { const stem = REPORT_FILE_STEM[key] ?? key; const f = join(process.cwd(), ".phi", "plans", `${stem}-${ts}.md`); if (existsSync(f)) return readFileSync(f, "utf-8"); } catch { /* ignore */ } return null; } // ─── Resume checkpoint ─────────────────────────────────────────────── // A tiny JSON marker tracking POSITION in the 5 base phases, so a crashed / // aborted orchestration can be resumed with `/plan --resume`. The handoff .md // files hold the real content; this only records where to pick up. function checkpointPath(): string { return join(process.cwd(), ".phi", "plans", "orchestration-state.json"); } function writeCheckpoint(nextBaseIndex: number): void { try { if (nextBaseIndex >= 5) { clearCheckpoint(); return; } writeFileSync( checkpointPath(), JSON.stringify({ description: currentDescription, ts: currentRunTs, nextBaseIndex }, null, 2), "utf-8", ); } catch { /* best effort */ } } function readCheckpoint(): { description: string; ts: string; nextBaseIndex: number } | null { try { const p = checkpointPath(); if (!existsSync(p)) return null; const c = JSON.parse(readFileSync(p, "utf-8")); if (typeof c?.description === "string" && typeof c?.ts === "string" && typeof c?.nextBaseIndex === "number") { return c; } } catch { /* ignore */ } return null; } function clearCheckpoint(): void { try { const p = checkpointPath(); if (existsSync(p)) unlinkSync(p); } catch { /* best effort */ } } /** * Common rules appended to every phase instruction. Pure prompt (zero latency, * robust to the proxy): honest reporting, autonomous operation, a canonical * handoff block, and a verdict line for phases that produce one. */ const COMMON_PHASE_RULES = ` --- ## Operating rules (apply to this phase) - **Autonomous orchestration:** you run inside an automated /plan pipeline. The user does NOT answer during this phase. For any reversible action that follows from the request, ACT without asking. Do not end your turn with a question or a "shall I". Do the work. - **Honest reporting (evidence before assertion):** report faithfully. If a command fails, paste its exact output. Only write PASS / ✅ when you OBSERVED success. If you skipped a step, say so. Never claim something works without having run it. - **Root cause, not workaround:** before changing code to make a check pass, find the real cause. Never bypass a failure (no --no-verify, no skipped test, no mock that hides the bug). Read the full log first. - **Handoff for a colleague who left the room:** the next phase sees ONLY your report file, not your reasoning or tool results. End your report file with a block exactly like: \`\`\` ## HANDOFF Critical Files: path/a.ts:42, path/b.ts:13 (3-5 max, the files that matter) State: Open Risks: Next: \`\`\` - **Internal orchestration data:** notes injected as "Previous phase summary" or budget/handoff reminders are for YOUR use only. Do not repeat them back to the user.`; /** * Load a skill body (SKILL.md) so a phase instruction can embed it verbatim. * Search order mirrors agent-def.ts: project .phi/skills, then the global * ~/.phi/agent/skills (postinstall copies bundled skills there), then the * bundled /skills for the repo layout. YAML frontmatter is * stripped. Returns null when the skill is not installed. */ function loadSkillContent(name: string): string | null { const dirs = [ join(process.cwd(), ".phi", "skills"), join(getAgentDir(), "skills"), join(__dirname, "..", "..", "skills"), ]; for (const dir of dirs) { try { const content = readFileSync(join(dir, name, "SKILL.md"), "utf-8"); const fmMatch = content.match(/^---\s*\n[\s\S]*?\n---\s*\n([\s\S]*)$/); const body = (fmMatch ? fmMatch[1] : content).trim(); if (body) return body; } catch { /* try next dir */ } } return null; } /** * Load routing config and build phase queue with model assignments + agent definitions. * Each phase now reads outputs from previous phases and writes structured outputs. */ function buildPhases(description: string, tsOverride?: string): OrchestratorPhase[] { const routingPath = join(getAgentDir(), "routing.json"); let routing: any = { routes: {}, default: { model: "default" } }; try { routing = JSON.parse(readFileSync(routingPath, "utf-8")); } catch { /* no routing config */ } function getModel(routeKey: string): { preferred: string; fallback: string } { const route = routing.routes?.[routeKey]; return { preferred: route?.preferredModel || routing.default?.model || "default", fallback: route?.fallback || routing.default?.model || "default", }; } const explore = getModel("explore"); const plan = getModel("plan"); const code = getModel("code"); const test = getModel("test"); const review = getModel("review"); const ts = tsOverride || timestamp(); currentRunTs = ts; // shared by all phase report file names this run (or resumed) // Inject runtime info so agents can adapt to the host OS const shellNote = process.platform === "win32" ? `\nShell: bash (Git Bash), NOT cmd.exe. Always use Unix syntax: rm not del, test -f not if exist, / not \\\\` : ""; const runtimeInfo = `\n\nRuntime: ${process.platform} (${process.arch})${shellNote}`; // Embed the prompt-architect skill so the PLAN phase applies it to every // task it writes. The skill ships bundled and is copied to // ~/.phi/agent/skills by postinstall; when missing, the inline task format // still enforces the [CONTEXT]/[TASK]/[FORMAT]/[CONSTRAINTS] structure. const promptArchitectSkill = loadSkillContent("prompt-architect"); const promptArchitectSection = promptArchitectSkill ? `\n**Prompt-architect skill (apply it to every task you write):**\n\n${promptArchitectSkill}\n` : ""; const phases: OrchestratorPhase[] = [ { key: "explore", label: "🔍 Phase 1 — EXPLORE", model: explore.preferred, fallback: explore.fallback, agent: loadAgentDef("explore"), instruction: `You are the EXPLORE agent. Analyze the project requirements and existing codebase. **FIRST ACTION (MANDATORY):** Call \`memory_search\` with project-relevant keywords to check for prior context. **Project Request:** ${description} **Your tasks:** **Parallelization:** When making multiple tool calls that don't depend on each other (e.g., memory_search + ontology_query, or reading 2+ files), call them IN PARALLEL in the same response. This is faster. 1. Call \`memory_search\` with project-relevant keywords (MANDATORY) 2. List all existing files and read key ones 3. Identify tech stack, patterns, and constraints 4. Create a STRUCTURED PROJECT BRIEF in \`.phi/plans/brief-${ts}.md\`: - Context: what exists now - Objective: what needs to be built - Requirements: specific features needed - Tech decisions: frameworks, patterns to use - Constraints: what to NOT break - Run Recipe: from package.json scripts / Makefile / Dockerfile / README, a \`## Run Recipe\` with the build command, run command, port/URL, and ready signal (the TEST phase uses this to actually run the code) 5. **MANDATORY:** Write your findings to \`.phi/plans/explore-${ts}.md\` using the \`write\` tool. This file is READ by Phase 2 PLAN — if you skip it, the plan agent has no context. Do NOT skip this step. **LAST ACTION (MANDATORY):** Call \`memory_write\` to save your exploration findings for downstream agents. **Knowledge Graph:** After your analysis, use \`ontology_batch_add\` to save ALL key project entities AND their relations in ONE call: - Add entities for: the project, each major library, each module/directory - Add relations between them: "uses", "contains", "depends_on", "implements" - Example: entity "finance-tracker" (type: Project) → relation "uses" → entity "ink" (type: Library) - ALWAYS create relations — entities without relations are useless **Format for the project brief:** \`\`\`markdown ## Project Brief ### Context [Analyze what the user is asking for] ### Objective [Clear, specific goal] ### Requirements [Bullet list of what must be built] ### Tech Decisions [Frameworks, patterns, architecture choices] ### Constraints - Production-quality code, no placeholders - Every function fully implemented - Follow existing patterns if codebase exists - [Any other specific constraints] \`\`\`` + runtimeInfo + COMMON_PHASE_RULES, }, { key: "plan", label: "📐 Phase 2 — PLAN", model: plan.preferred, fallback: plan.fallback, agent: loadAgentDef("plan"), instruction: `You are the PLAN agent. Design the architecture and create a detailed task list. **Context Retrieval:** 1. Use \`ontology_query\` to retrieve all entities and relations from Phase 1 2. Use \`memory_search\` with project-relevant keywords to find existing notes 3. Use this knowledge to inform your plan **Project Request:** ${description} **Step 1:** Read \`.phi/plans/brief-*.md\` (created by the explore phase) **Step 2:** Read \`.phi/plans/explore-*.md\` to understand the codebase analysis **Step 3:** Design the architecture based on findings **Step 4:** Create a DETAILED TODO LIST in \`.phi/plans/todo-${ts}.md\`. Every task is a PROMPT for the CODE agent, which starts with ZERO memory of this conversation. Write each task with the prompt-architect structure: - **[CONTEXT]** what exists and why this task (real paths from the explore phase) - **[TASK]** exactly what to do — files to create/modify with full paths - **[FORMAT]** expected deliverable — exports, signatures, style, tests - **[CONSTRAINTS]** what NOT to break, patterns to respect Plus: task number + title, agent assignment (code/test), dependencies. **Format for the todo list:** \`\`\`markdown # TODO: Project Tasks ## Task 1: [Task Title] [agent-type] **[CONTEXT]** [What exists now, why this task, real paths (src/x.ts:42)] **[TASK]** - [ ] Create path/to/file.ext with [specific behavior] - [ ] Modify path/to/other.ext: [exact change] **[FORMAT]** [Expected exports/signatures/tests] **[CONSTRAINTS]** [What not to break, patterns to follow] - Dependencies: None ## Task 2: [Task Title] [agent-type] **[CONTEXT]** ... **[TASK]** - [ ] ... **[FORMAT]** ... **[CONSTRAINTS]** ... - Dependencies: Task 1 \`\`\` ${promptArchitectSection} Before finishing, use \`memory_write\` to save your plan summary with relevant tags for future reference.` + runtimeInfo + COMMON_PHASE_RULES, }, { key: "code", label: "💻 Phase 3 — CODE", model: code.preferred, fallback: code.fallback, agent: loadAgentDef("code"), instruction: `You are the CODE agent. Implement the complete project. **Context Retrieval:** 1. Use \`memory_search\` with project keywords to find notes from previous phases 2. Use \`ontology_query\` to understand the project structure and dependencies 3. Use this context to guide implementation **Project Request:** ${description} **Step 1:** Read \`.phi/plans/brief-*.md\` for project context **Step 2:** Read \`.phi/plans/todo-*.md\` to get your task list **Step 3:** Implement EVERY task from the todo list, in order **Step 4:** Write a progress report to \`.phi/plans/progress-${ts}.md\` **Rules:** - Create every file listed in the plan - No placeholders, no TODOs, no stubs - Every function must be fully implemented - Follow the architecture from the plan - Check off tasks in your progress report as you complete them **Progress report format:** \`\`\`markdown # Progress Report ## Completed Tasks - [x] Task 1: Description - DONE - [x] Task 2: Description - DONE ## Files Created - path/to/file1.ext - Purpose - path/to/file2.ext - Purpose ## Implementation Notes [Any important decisions or changes made] \`\`\` After implementation, use \`memory_write\` to save a summary of what was built, patterns used, and any issues encountered. **Ontology update:** Use \`ontology_add\` to update the project status (e.g., entity "implementation" type "Phase" with properties {status: "complete", files: "N"}) and add a relation to the project entity. **CRITICAL RULES:** - **Minimal diff, root cause.** Prefer the SMALLEST change that fixes the underlying cause. Every extra condition, guard, or early-return you add is a liability — it can silently make the fix a no-op in the real scenario (a guard that skips the fix on the exact input the bug is about). When in doubt, do LESS and match the existing code's pattern rather than adding cleverness. A fix more elaborate than the problem is a red flag, not thoroughness. - Write ONE file per tool call — NEVER combine multiple files in a single response - Keep each file under 500 lines. If longer, split into modules - After writing ALL files, verify they exist with a single \`find . -name '*.ts' -o -name '*.js' -o -name '*.html' | sort\`` + runtimeInfo + COMMON_PHASE_RULES, }, { key: "test", label: "🧪 Phase 4 — TEST", model: test.preferred, fallback: test.fallback, agent: loadAgentDef("test"), instruction: `You are the TEST agent. Verify the implementation. **Context Retrieval:** 1. Use \`memory_search\` to find implementation notes from the CODE phase 2. Use \`ontology_query\` to understand the project architecture 3. Use this context to focus your testing **Project Request:** ${description} **Step 1:** Read \`.phi/plans/todo-*.md\` to know what was planned **Step 2:** Read \`.phi/plans/progress-*.md\` to see what was done **Step 3 (GROUND TRUTH — the single most important step):** Derive the expected behaviour from the **Project Request above**, NEVER from the code that was written. Write a reproduction of the EXACT scenario the request describes — same conditions, same inputs. If the request is about a streaming response with no charset, stream a chunked response with no charset; if it is about an empty list, pass an empty list. Assert the behaviour the **request** says is correct, and make each assertion trace to a specific phrase in the request. - **CRITICAL ANTI-PATTERN:** do NOT write a test that merely re-states what the CODE now does — that only confirms the code's own assumptions, which is exactly how a wrong fix passes its own tests. The test must be written as if you had NOT seen the fix. - **FALSIFY FIRST:** your reproduction MUST FAIL against the ORIGINAL (pre-fix) code — \`git stash\` the fix, run it, confirm it fails, then \`git stash pop\` and confirm it now passes. If it passes on the original code, it does not reproduce the bug: rewrite it. Paste both runs. **Step 3b:** ACTUALLY RUN it and paste runtime evidence (stdout + exit code). Add at least one adversarial probe per feature (empty input, wrong type, missing arg). Running \`npm test\`/the existing suite alone is NOT sufficient — it does not cover the new scenario. **Step 4:** Fix any real errors you find (root cause, not a workaround). If the fix is a no-op in the request's own scenario, that is a FAIL, not a pass. **Step 5:** Write test results to \`.phi/plans/test-${ts}.md\`, starting the file with a VERDICT line. **Step 6 (MANDATORY):** Call the \`phase_result\` tool with your \`verdict\` (PASS/FAIL/BLOCKED) and a concise \`handoff\`. This is how the orchestrator reads your outcome exactly; the report file above is the human-readable copy. **Test report format (the FIRST line MUST be the verdict):** \`\`\`markdown ## VERDICT: PASS|FAIL|BLOCKED # Test Report ## Commands Run (with pasted output) \`\`\` $ (exit code: N) \`\`\` ## Tests Executed - Feature 1: -> PASS/FAIL (evidence above) ## Errors Found & Fixed - Error: ... -> Fix: ... \`\`\` **Launch:** if the brief contains a "## Run Recipe" (build command, run command, port/URL, ready signal), use it. Distinguish a real failure (FAIL) from a stale launch recipe (BLOCKED) and report the recipe that actually works. **Verdict rules:** PASS only if you OBSERVED every feature working at runtime. When in doubt, FAIL. No partial pass (3/4 working = FAIL). Use BLOCKED only when you could not run anything (broken launch recipe, missing env, provider down) and say what is needed. **CRITICAL RULES:** - NEVER run a server with \`&\` without cleanup. Always use: \`timeout 15 bash -c 'node src/index.js & PID=$!; sleep 2; curl ...; kill $PID'\` - ALWAYS kill background processes after testing - If a test hangs, use \`timeout\` to prevent deadlock - NEVER put tool calls inside thinking blocks. Always use the proper JSON tool call format - NEVER modify source code permanently for testing. Use environment variables: \`PORT=3001 node server.js\` instead of editing files - NEVER create .env files with fake credentials. Use inline env vars: \`API_KEY=test node server.js\` - For port conflicts, prefer: \`npx kill-port PORT\` (cross-platform) - On Windows fallback: \`netstat -ano | findstr :PORT\` and \`taskkill /PID /F\` - On Linux/Mac fallback: \`lsof -ti:PORT | xargs kill -9\` - Always clean up after tests: kill background processes, remove temp files **Anti-loop rule:** If the SAME test fails 3 times in a row with the same error after your fixes, STOP trying to fix it. Write the failure in your test report as "UNRESOLVED" and move on. Do not waste more than 3 iterations on the same issue. After testing, use \`memory_write\` to save test results, bugs found, and lessons learned. **Ontology update:** Use \`ontology_add\` to update the project status (e.g., entity "test-results" type "Phase" with properties {passed: "N", failed: "M", coverage: "X%"}) and add a relation to the project entity.` + runtimeInfo + COMMON_PHASE_RULES, }, { key: "review", label: "🔍 Phase 5 — REVIEW", model: review.preferred, fallback: review.fallback, agent: loadAgentDef("review"), instruction: `You are the REVIEW agent. Final quality review. **FIRST ACTIONS (MANDATORY — do these before anything else):** 1. Call \`memory_search\` to find all notes from previous phases (explore, plan, code, test) 2. Call \`ontology_query\` to understand the full project architecture and entity relationships **Context Retrieval:** 3. Review all \`.phi/plans/*.md\` files for complete context **Project Request:** ${description} **Step 1:** Get the diff to review. Run \`git diff\` and \`git diff --stat\` (and \`git status\`) if it is a git repo; otherwise read the files listed in the progress/handoff reports. Skip test/fixture hunks. **Scale your effort to the diff size:** a small diff (under ~50 changed lines) gets one focused precision pass, bias to high confidence, at most 4 findings; a large diff gets all three angles below plus the verification step. Never spend so long that you risk the phase time limit. **Step 2:** Review in SEQUENTIAL ANGLES (do all in this one turn, no sub-agents). Collect raw candidates first, judge after: - **Angle 1 - Correctness:** read the diff line by line. What behaviour did it change or remove? Off-by-one, null/undefined, wrong condition, broken invariant. - **Angle 2 - Cross-file:** grep the callers and callees of changed symbols. Did a signature/return/contract change break a caller elsewhere? - **Angle 3 - Security & language pitfalls:** input validation, injection, secrets, auth, error handling; plus language traps (async not awaited, shadowed scope, mutation of shared state). - **Angle 4 - Over-engineering & dead guards (the failure mode that ships confident-wrong fixes — check this FIRST):** for EVERY new condition, guard, or early-return the diff added, name the concrete input where it takes the SKIP / else branch, and check the behaviour is still correct THERE — *especially against the exact scenario in the Project Request*. A guard that makes the fix a no-op in the request's own scenario (e.g. an \`if buffered\` guard on a bug that is about the streaming path) is a **CONFIRMED** blocking bug. Then compare the diff's size to the problem: if the fix is more elaborate than the request requires, or does not match the surrounding code's existing pattern, that itself is a finding — the minimal change is usually the correct one. **Step 3 - VERIFY (3-state, cite the line):** for EACH candidate, quote the exact line and classify: - **CONFIRMED** - you can name the input/state that triggers it and the wrong output. Quote the line. - **PLAUSIBLE** - the mechanism is real but the trigger is uncertain. Say what would confirm it. - **REFUTED** - drop it. Only refute if you can quote the line that proves it cannot happen (a type, guard, or constant). When unsure, keep it PLAUSIBLE. Keep only CONFIRMED + PLAUSIBLE. A finding with no concrete failure scenario is noise: drop it. **Step 4:** Write \`.phi/plans/review-${ts}.md\`, starting with the VERDICT line. **Step 5 (MANDATORY):** Call the \`phase_result\` tool with your \`verdict\` (PASS/FAIL), the \`blocking\` findings (one per line, empty when none), and a short \`handoff\`. A FAIL here drives the one bounded fix→re-review cycle, so the orchestrator must read it exactly — do not rely on markdown parsing alone. **Final report format (the FIRST line MUST be the verdict):** \`\`\`markdown ## VERDICT: PASS|FAIL # Final Review ## Findings (correctness first, then security, then cleanup) - path/file.ts:123 - - failure scenario: wrong output> [CONFIRMED|PLAUSIBLE] ## BLOCKING (Only the must-fix findings. If empty, write "none" and set VERDICT: PASS.) - path/file.ts:123 - \`\`\` **Final sweep (large diffs only):** before writing the verdict, re-read the diff once more as if you had never seen it; add ONLY bugs not already in your list. If there are none, do not pad. **Verdict rules:** VERDICT: FAIL if there is ANY CONFIRMED correctness/security finding (it goes under BLOCKING). VERDICT: PASS only if BLOCKING is empty. Do NOT pad: if the code is clean, return PASS with no findings. After your review, use \`memory_write\` ONCE to save: - Key lessons learned about this project type - Patterns that worked well - Common mistakes to avoid in future projects Tag the note with relevant keywords for vector search. **Important:** Write lessons-learned ONCE. Do not call memory_write twice with the same filename or duplicate content. **Ontology enrichment:** After your review, use \`ontology_add\` to save your key findings: - Add a "review-report" entity with type "Document" - Add relations to the project: "reviews" → project, quality score as entity property - Save any new architectural decisions or patterns discovered` + runtimeInfo + COMMON_PHASE_RULES, }, ]; phases.forEach((p, i) => { p.baseIndex = i; }); return phases; } // resolveModelRef ("provider/id" or bare id) lives in orchestrator-helpers.ts, // shared with the smart router. /** * Switch model for the current phase. * Returns the model id actually in use plus an optional warning when the * requested routing.json model could not be applied (not in registry or no * API key), so the caller can surface the degraded routing to the user. */ async function switchModelForPhase( phase: OrchestratorPhase, ctx: any, ): Promise<{ modelId: string; warning?: string }> { const available: Model[] = ctx.modelRegistry?.getAvailable?.() || []; // On a retry, resolve the fallback FIRST so we swap to a different model // (ideally another family) rather than re-hitting the one that just failed. const target = phase.useFallback ? resolveModelRef(available, phase.fallback) || resolveModelRef(available, phase.model) : resolveModelRef(available, phase.model) || resolveModelRef(available, phase.fallback); const currentId = ctx.model?.id || phase.model; if (!target) { // Neither the preferred nor the fallback ref resolved to a registered model. return { modelId: currentId, warning: `Phase ${phase.label} model '${phase.model}' unavailable (not in registry); running on '${currentId}'`, }; } if (target.id !== ctx.model?.id || target.provider !== ctx.model?.provider) { const switched = await pi.setModel(target); if (switched) return { modelId: target.id }; // setModel returns false when the target has no configured auth. return { modelId: currentId, warning: `Phase ${phase.label} model '${phase.model}' unavailable (no API key); running on '${currentId}'`, }; } return { modelId: target.id }; } /** * Activate agent for a phase: set system prompt + restrict tools. */ function activateAgent(phase: OrchestratorPhase, _ctx: any) { // Fallback capture: savedTools is normally taken in the /plan handler at // orchestration start, but capture it here too so restoration is always defined. if (!savedTools) { savedTools = pi.getActiveTools(); } if (phase.agent) { const agentDef = phase.agent; // Set agent's system prompt (will be injected via before_agent_start) activeAgentPrompt = agentDef.systemPrompt; // Restrict tools to agent's allowed tools if (agentDef.tools.length > 0) { // Always include the memory tools and phase_result in orchestration phases. // ontology_batch_add: EXPLORE's instruction requires it. lsp: the // /debug rules recommend it (read-only; ignored when not loaded). const forcedTools = [ "memory_search", "memory_write", "memory_read", "ontology_add", "ontology_batch_add", "ontology_query", "phase_result", "sandbox_run", "lsp", ]; const agentTools = [...agentDef.tools, ...forcedTools.filter((t) => !agentDef.tools.includes(t))]; _activeAgentTools = agentTools; pi.setActiveTools(agentTools); } else if (savedTools) { // Agent with no tool restriction: reset to the full toolset so the // previous phase's narrower restriction does not leak into this one. _activeAgentTools = null; pi.setActiveTools(savedTools); } } else { // No agent for this phase: restore the full toolset, otherwise the prior // phase's restriction would persist. activeAgentPrompt = null; _activeAgentTools = null; if (savedTools) { pi.setActiveTools(savedTools); } } } /** * Deactivate agent: restore tools, clear prompt override. */ function deactivateAgent() { activeAgentPrompt = null; _activeAgentTools = null; if (savedTools) { pi.setActiveTools(savedTools); savedTools = null; } } /** * Send the next phase in the queue. */ function setOrchestrationActive(active: boolean) { orchestrationActive = active; (globalThis as any).__phiOrchestrationActive = active; } /** * Tear down orchestration state without chaining to the next phase. * Used by the user-abort and auth-error paths so they restore the user's * model and tools exactly like the normal completion branch. */ function stopOrchestration() { setOrchestrationActive(false); phasePending = false; deactivateAgent(); if (phaseTimeoutId) { clearTimeout(phaseTimeoutId); phaseTimeoutId = null; } if (originalModel) { const toRestore = originalModel; originalModel = null; Promise.resolve(pi.setModel(toRestore)).catch(() => { /* best effort */ }); } } function sendNextPhase(ctx: any) { if (phaseQueue.length === 0) { // All phases done — clean up and notify setOrchestrationActive(false); phasePending = false; clearCheckpoint(); deactivateAgent(); // Restore the user's model so /plan does not overwrite their /model choice. if (originalModel) { const toRestore = originalModel; originalModel = null; Promise.resolve(pi.setModel(toRestore)).catch(() => { /* best effort */ }); } if (phaseTimeoutId) { clearTimeout(phaseTimeoutId); phaseTimeoutId = null; } // Generate global final summary using the real phase counters const elapsed = phaseStartTime ? Math.round((Date.now() - phaseStartTime) / 1000) : 0; const minutes = Math.floor(elapsed / 60); const seconds = elapsed % 60; const skippedNote = skippedPhases ? ` (${skippedPhases} skipped on timeout)` : ""; ctx.ui.notify( `\n📊 **Orchestration Summary**\n` + ` Phases: ${completedPhases}/5 completed${skippedNote}\n` + ` Duration: ${minutes}m ${seconds}s\n` + ` Check \`.phi/plans/\` for all reports`, "info", ); const allDone = completedPhases >= 5 && skippedPhases === 0; const doneMsg = allDone ? `\n✅ **All 5 phases complete!**` : `\n⚠️ **Orchestration finished:** ${completedPhases}/5 phases completed${skippedNote}.`; try { ctx.ui.notify(doneMsg, "info"); } catch { // Fallback: inject completion message into conversation stream try { pi.sendUserMessage(`Orchestration finished: ${completedPhases}/5 phases completed${skippedNote}.`); } catch { /* best effort */ } } return; } const phase = phaseQueue.shift()!; phasePending = true; currentPhase = phase; currentPhaseStartedAt = Date.now(); // New phase starts with no structured result; it is set only if this // phase's agent calls phase_result. currentPhaseResult = null; currentPhaseResultKey = null; switchModelForPhase(phase, ctx).then(({ modelId, warning }) => { activateAgent(phase, ctx); const agentName = phase.agent?.name || phase.key; ctx.ui.notify(`\n${phase.label} → \`${modelId}\` (agent: ${agentName})`, "info"); if (warning) ctx.ui.notify(`\n⚠️ ${warning}`, "warning"); // Small delay to let the model switch settle, then send instruction. // deliverAs:"followUp" queues the message instead of throwing when the // agent is still streaming (e.g. on the timeout path). setTimeout(() => pi.sendUserMessage(phase.instruction, { deliverAs: "followUp" }), 500); // Set phase timeout — abort if phase takes too long if (phaseTimeoutId) clearTimeout(phaseTimeoutId); phaseTimeoutId = setTimeout(() => { if (orchestrationActive && phasePending) { phasePending = false; // Abort the stuck phase first so the next instruction does not // race a still-streaming phase. Mark it internal so the resulting // agent_end is not treated as a user cancellation. internalAbort = true; try { ctx.abort(); } catch { /* best effort */ } // Retry the SAME phase once on the fallback model before skipping: // a timed-out phase usually means the model/route stalled, and a // different family often gets through (cap = one retry per phase). if (!phase.retried) { phase.retried = true; phase.useFallback = true; phaseQueue.unshift(phase); ctx.ui.notify( `\n⏰ **Phase timed out** (${MAX_PHASE_DURATION_MS / 60000} min) — retrying once on the fallback model.`, "warning", ); } else { skippedPhases++; ctx.ui.notify(`\n⏰ **Phase timed out again** — skipping to next phase.`, "warning"); } sendNextPhase(ctx); } }, MAX_PHASE_DURATION_MS); }); } // ─── Generic linear driver (/debug, /build) ───────────────────── // A deliberately simpler engine than /plan's: phases run in order, a BLOCKED // verdict halts, and there is no review-fix cycle or "/5" bookkeeping. It // reuses the tested primitives (switchModelForPhase, activateAgent, // resolvePhaseOutcome) but never the /plan-specific agent_end path. function routeFor(routeKey: string): { preferred: string; fallback: string } { const routingPath = join(getAgentDir(), "routing.json"); try { const routing = JSON.parse(readFileSync(routingPath, "utf-8")); const route = routing.routes?.[routeKey]; return { preferred: route?.preferredModel || routing.default?.model || "default", fallback: route?.fallback || routing.default?.model || "default", }; } catch { return { preferred: "default", fallback: "default" }; } } function genericPhase( key: string, label: string, routeKey: string, agentKey: string, instruction: string, ): OrchestratorPhase { const route = routeFor(routeKey); return { key, label, model: route.preferred, fallback: route.fallback, agent: loadAgentDef(agentKey), instruction: instruction + COMMON_PHASE_RULES, }; } // /debug: REPRODUCE → [REPRO-AUDIT] → LOCALIZE → FIX → VERIFY. Each phase // routes to a model that does NOT share the coder's blind spot. The audit // phase (adversary from the review family) runs ONLY when the reproduction // was CONSTRUCTED from prose — a user-supplied failing test is ground truth // (twice-measured failure: a prose-derived repro validated the agent's // interpretation while the real tests failed). function buildDebugPhases(state: FailingState, candidates = 1, parallel = false): OrchestratorPhase[] { const ins = debugPhaseInstructions(state); const constructed = !state.failingTest?.trim() && !state.reproCommand?.trim(); const audit = constructed ? [ genericPhase( "repro-audit", "🕵️ Phase 1b — REPRO-AUDIT (adversary)", "review", "review", reproAuditInstruction(state), ), ] : []; if (candidates <= 1) { return [ genericPhase("reproduce", "🔴 Phase 1 — REPRODUCE", "test", "test", ins.reproduce), ...audit, genericPhase("localize", "🔎 Phase 2 — LOCALIZE", "explore", "explore", ins.localize), genericPhase("fix", "🔧 Phase 3 — FIX", "code", "code", ins.fix), genericPhase("verify", "✅ Phase 4 — VERIFY", "test", "test", ins.verify), ]; } // Multi-candidate: N independent FIX attempts on DIVERSE model families // (diversity proposes), then the driver arbitrates each candidate with a // REAL run (the oracle disposes) — no VERIFY agent phase, no vote. const models = pickCandidateModels(readRoutingConfig(), candidates); const codeRoute = routeFor("code"); const fixPhases = Array.from({ length: candidates }, (_, i) => { const ref = models[i % Math.max(1, models.length)] ?? codeRoute.preferred; const phase = genericPhase( "fix-cand", `🔧 Phase ${3 + i} — FIX candidate ${i + 1}/${candidates}`, "code", "code", `${ins.fix}\n\n**Candidate protocol:** you are INDEPENDENT candidate ${i + 1} of ${candidates}. Other candidates attempt the same fault separately; a REAL run of the reproduction and the suite arbitrates between the resulting patches. Make your own best minimal fix — do not hedge for the others.`, ); phase.model = ref; phase.fallback = codeRoute.fallback; return phase; }); if (parallel) { // Parallel candidates: the queue stops at LOCALIZE; the driver then // fans the FIX out to worktrees and arbitration takes over. return [ genericPhase("reproduce", "🔴 Phase 1 — REPRODUCE", "test", "test", ins.reproduce), ...audit, genericPhase("localize", "🔎 Phase 2 — LOCALIZE", "explore", "explore", ins.localize), ]; } return [ genericPhase("reproduce", "🔴 Phase 1 — REPRODUCE", "test", "test", ins.reproduce), ...audit, genericPhase("localize", "🔎 Phase 2 — LOCALIZE", "explore", "explore", ins.localize), ...fixPhases, ]; } /** Read ~/.phi/agent/routing.json (shape shared with routeFor). */ function readRoutingConfig(): RoutingLike { try { return JSON.parse(readFileSync(join(getAgentDir(), "routing.json"), "utf-8")) as RoutingLike; } catch { return {}; } } // /build: reuse /plan's EXPLORE→PLAN→CODE, then an execution-grounded // BUILD-VERIFY that runs the recipe, checks acceptance, red-teams the // boundary, and routes real failures to the /debug protocol. function buildBuildPhases(spec: string, ts: string): OrchestratorPhase[] { const planLike = buildPhases(spec, ts).slice(0, 3); // explore, plan, code const verify = genericPhase( "verify", "🧪 Phase 4 — BUILD-VERIFY", "review", "review", buildVerifyInstruction(spec), ); return [...planLike, verify]; } function finishGenericOrchestration(ctx: any, headline: string) { const elapsed = phaseStartTime ? Math.round((Date.now() - phaseStartTime) / 1000) : 0; const minutes = Math.floor(elapsed / 60); const seconds = elapsed % 60; const mode = orchestrationMode; // Telemetry: one JSONL line per run — continuous measurement for free. appendRunRecord( ctx.cwd || process.cwd(), buildRunRecord({ mode, startedAtMs: phaseStartTime, endedAtMs: Date.now(), phases: runPhaseRecords, completedPhases, skippedPhases, sandboxExecs: sandboxExecCount, outcome: headline, }), ); setOrchestrationActive(false); phasePending = false; orchestrationMode = "plan"; fixContext = null; candidateContext = null; lastGenericPhase = null; deactivateAgent(); if (phaseTimeoutId) { clearTimeout(phaseTimeoutId); phaseTimeoutId = null; } if (originalModel) { const toRestore = originalModel; originalModel = null; Promise.resolve(pi.setModel(toRestore)).catch(() => { /* best effort */ }); } ctx.ui.notify( `\n📊 **/${mode} summary** — ${completedPhases} phase(s) in ${minutes}m ${seconds}s${ skippedPhases ? ` (${skippedPhases} skipped on timeout)` : "" }\n${headline}`, "info", ); } // /fix driver-level oracle: after the single shot, run the reproduction and // the project suite in the REAL sandbox. Green → finish at baseline cost. // Red → escalate: enqueue the full /debug pipeline seeded with the red run. // Deterministic — zero model tokens; the verdict comes from exit codes. async function runFixOracleAndMaybeEscalate(ctx: any): Promise { if (orchestrationMode !== "fix" || !fixContext || fixContext.oracleRan) return false; fixContext.oracleRan = true; const cwd = ctx.cwd || process.cwd(); const sandbox = getSessionSandbox(cwd, ctx); let reproCmd = fixContext.state.failingTest?.trim() || fixContext.state.reproCommand?.trim() || fixContext.reproFromShot; // Conventional fallback: the shot is instructed to write `repro_issue.py`. // If its handoff was lost (phase timeout/abort) but the file exists, the // oracle can still run it instead of going blind (telemetry-measured gap). if (!reproCmd && existsSync(join(cwd, "repro_issue.py"))) { reproCmd = "python repro_issue.py"; ctx.ui.notify( `\n🧷 Oracle fallback: found \`repro_issue.py\` — using \`${reproCmd}\` as the reproduction.`, "info", ); } // Oracle upgrade (measured on flask-4992: the agent's own repro passed // while the module's REAL tests failed): when no suite command is known, // auto-discover the EXISTING test files of the modules the change touched // and use them as the suite leg of the oracle. let suiteCmd = sandbox.recipe.test?.trim(); const inGitRepo = passed(runCommand("git rev-parse --is-inside-work-tree", { cwd, timeoutMs: 15_000 })); if (!suiteCmd && inGitRepo) { const changed = gitIn(cwd, "diff --name-only") .split("\n") .map((s) => s.trim()) .filter(Boolean); const targeted = discoverTargetedTests(changed, fsSeamsFor(cwd)); if (targeted.command) { suiteCmd = targeted.command; ctx.ui.notify( `\n🎯 Targeted tests discovered for the touched modules: ${targeted.files.join(", ")}`, "info", ); } } // A shot that changed NOTHING has nothing to verify — "UNVERIFIED" would be // a lie of omission (measured: a text-only 91s shot ended UNVERIFIED with // zero edits). In a git repo with a clean diff, escalate to the full // pipeline instead: the work simply was not done. if (inGitRepo && !gitIn(cwd, "diff").trim() && !gitIn(cwd, "status --porcelain").trim()) { ctx.ui.notify( `\n🔺 **/fix escalating: the single shot made NO changes** — nothing to verify, the full /debug pipeline takes over.`, "warning", ); phaseQueue.push(...buildDebugPhases(fixContext.state)); return false; // dispatch REPRODUCE } if (!sandbox.available() && (reproCmd || suiteCmd)) { ctx.ui.notify( `\n⚠️ **/fix oracle: sandbox unavailable** (${sandbox.reason}) — the single shot cannot be verified. Treating it as UNVERIFIED.`, "warning", ); finishGenericOrchestration(ctx, `⚠️ **/fix finished UNVERIFIED — no executable environment for the oracle.**`); return true; } // The reproduction may be model-declared (REPRO-CMD): same destructive // gate as the bash tool before running it on the host. const reproBlocked = reproCmd ? hostGuardReason(reproCmd, sandbox, cwd) : undefined; if (reproCmd && reproBlocked) { ctx.ui.notify( `\n🛑 Oracle reproduction \`${reproCmd}\` blocked by the safety gate: ${reproBlocked}`, "warning", ); reproCmd = undefined; } const suiteBlocked = suiteCmd ? hostGuardReason(suiteCmd, sandbox, cwd) : undefined; if (suiteCmd && suiteBlocked) { ctx.ui.notify(`\n🛑 Oracle suite \`${suiteCmd}\` blocked by the safety gate: ${suiteBlocked}`, "warning"); suiteCmd = undefined; } ctx.ui.notify( `\n🧪 **/fix oracle** — running ${[reproCmd && "the reproduction", suiteCmd && "the suite"].filter(Boolean).join(" and ") || "nothing (no runnable check)"} in ${sandbox.describe()}…`, "info", ); // ASYNC runs: they can take up to 10 + 20 min; a sync spawn here froze // the whole TUI (event loop blocked) for that long. const state = fixContext.state; const repro = reproCmd ? await sandbox.execAsync(reproCmd, { timeoutMs: 10 * 60 * 1000 }) : null; const suite = suiteCmd ? await sandbox.execAsync(suiteCmd, { timeoutMs: 20 * 60 * 1000 }) : null; // Cancelled while the oracle ran: nothing left to decide. if (!orchestrationActive) return true; const decision = decideEscalation(state, { repro, suite }); if (decision.action === "done-green") { finishGenericOrchestration( ctx, `✅ **/fix finished GREEN at single-shot cost** — oracle evidence: ${decision.evidence}.`, ); return true; } if (decision.action === "done-unverified") { finishGenericOrchestration( ctx, `⚠️ **/fix finished UNVERIFIED** — ${decision.reason}. Provide a failing test or a repro command for a guaranteed verdict.`, ); return true; } // escalate: the pipeline inherits the RED run as its concrete failing // state. REPRODUCE is SKIPPED — the oracle just executed the reproduction // and it is red; re-confirming it would burn ~10 min re-running what the // driver already ran (measured: escalations were dying on outer budgets). ctx.ui.notify( `\n🔺 **/fix escalating** — ${decision.diagnostic}. The reproduction is already established (the oracle just ran it); going straight to LOCALIZE → FIX → VERIFY.`, "warning", ); phaseQueue.push(...buildDebugPhases(decision.failing).slice(1)); return false; // fall through: sendNextGenericPhase dispatches LOCALIZE } // Multi-candidate arbitration — the oracle disposes. Apply each captured // candidate in turn, run the reproduction (and the suite when known) in the // REAL sandbox, select the minimal passing candidate (candidate-select), and // leave the WINNER applied. If none passes: never a blank page — the smallest // non-empty candidate is left applied, clearly labelled UNVERIFIED. async function runCandidateArbitration(ctx: any): Promise { if (!candidateContext || candidateContext.arbitrated) return false; candidateContext.arbitrated = true; const cc = candidateContext; const cwd = ctx.cwd || process.cwd(); const sandbox = getSessionSandbox(cwd, ctx); const suiteCmd = sandbox.recipe.test?.trim(); const nonEmpty = cc.list.filter((c) => c.patch.trim()); // The arbitration reproduction comes from a phase handoff (REPRO-CMD): // same destructive gate as the bash tool before running it on the host. const reproBlocked = cc.reproCmd ? hostGuardReason(cc.reproCmd, sandbox, cwd) : undefined; if (cc.reproCmd && reproBlocked) { ctx.ui.notify( `\n🛑 Arbitration reproduction \`${cc.reproCmd}\` blocked by the safety gate: ${reproBlocked}`, "warning", ); cc.reproCmd = undefined; } if (nonEmpty.length === 0) { finishGenericOrchestration(ctx, `⏸️ **/${orchestrationMode} BLOCKED — no candidate produced a patch.**`); return true; } const applyPatch = (patch: string): boolean => { try { const f = join(cwd, ".phi", "candidate.patch"); writeFileSync(f, patch, "utf-8"); const r = runCommand(`git apply --whitespace=nowarn "${f}"`, { cwd, timeoutMs: 60_000 }); try { unlinkSync(f); } catch { /* best effort */ } return passed(r); } catch { return false; } }; ctx.ui.notify( `\n⚖️ **Arbitrating ${nonEmpty.length} candidate(s)** with real runs${cc.reproCmd ? ` — repro \`${cc.reproCmd}\`` : ""}${suiteCmd ? `, suite \`${suiteCmd}\`` : ""} in ${sandbox.describe()}…`, "info", ); const verified: VerifiedCandidate[] = []; for (const cand of nonEmpty) { if (!applyPatch(cand.patch)) { verified.push({ source: cand.source, patch: cand.patch, reproAfter: null, suite: null }); continue; } // Per-candidate suite: the recipe's, else the targeted tests of the // modules THIS candidate touched (flask-4992 oracle upgrade). let candSuite = suiteCmd; if (!candSuite) { const changed = gitIn(cwd, "diff --name-only") .split("\n") .map((s) => s.trim()) .filter(Boolean); candSuite = discoverTargetedTests(changed, fsSeamsFor(cwd)).command; } if (candSuite && hostGuardReason(candSuite, sandbox, cwd)) candSuite = undefined; // ASYNC runs (up to 10 + 20 min per candidate): never block the event loop. const reproAfter = cc.reproCmd && sandbox.available() ? await sandbox.execAsync(cc.reproCmd, { timeoutMs: 10 * 60 * 1000 }) : null; const suite = candSuite && sandbox.available() ? await sandbox.execAsync(candSuite, { timeoutMs: 20 * 60 * 1000 }) : null; verified.push({ source: cand.source, patch: cand.patch, reproAfter, suite }); gitIn(cwd, "checkout -- ."); // Cancelled while a candidate ran: the tree is reset, stop here. if (!orchestrationActive) return true; const rp = reproAfter ? `repro exit ${reproAfter.exitCode}${reproAfter.timedOut ? " TIMEOUT" : ""}` : "repro n/a"; const st = suite ? `suite exit ${suite.exitCode}${suite.timedOut ? " TIMEOUT" : ""}` : "suite n/a"; ctx.ui.notify(` ${cand.source}: ${rp}, ${st}`, "info"); } const outcome = decideVerify(verified, Boolean(suiteCmd) || verified.some((v) => v.suite !== null)); if (outcome.verdict === "FIXED" && outcome.patch) { applyPatch(outcome.patch); finishGenericOrchestration( ctx, `✅ **/${orchestrationMode} FIXED by candidate arbitration** — ${outcome.reason}. Evidence: repro passes${suiteCmd ? ", suite green" : ""} (real runs above). The winning patch is applied.`, ); return true; } // Honest failure — but never a blank page: leave the smallest non-empty // candidate applied, clearly labelled unverified (lesson: sympy-11870). const smallest = [...nonEmpty].sort((a, b) => diffChangedLines(a.patch) - diffChangedLines(b.patch))[0]; const draftApplied = applyPatch(smallest.patch); finishGenericOrchestration( ctx, `⏸️ **/${orchestrationMode} BLOCKED — no candidate passed arbitration** (${outcome.reason ?? "see runs above"}).` + (draftApplied ? ` An **UNVERIFIED draft** (smallest candidate, ${smallest.source}) is left in the working tree — \`git diff\` to inspect, \`git checkout -- .\` to discard.` : ""), ); return true; } /** * Final headline of a run whose phase queue drained normally. Only a VERIFY * phase that reported PASS is a green finish; a FAIL, a missing verdict or a * phase skipped on timeout is reported as such (and /runs counts it so). */ function genericCompletionHeadline(): string { const mode = orchestrationMode; const last = lastGenericPhase; if (last?.verdict === "FAIL") { return `❌ **/${mode} finished with FAIL** at ${last.label}: the change is NOT verified green.`; } if (skippedPhases > 0) { return `⚠️ **/${mode} finished UNVERIFIED**: ${skippedPhases} phase(s) skipped on timeout.`; } if (last?.key === "verify" && last.verdict !== "PASS") { return `⚠️ **/${mode} finished UNVERIFIED**: ${last.label} reported no PASS verdict.`; } return `✅ **/${mode} finished.**`; } async function sendNextGenericPhase(ctx: any): Promise { if (phaseQueue.length === 0) { if (genericFinalizing) return; genericFinalizing = true; try { if (await runCandidateArbitration(ctx)) return; if (await runFixOracleAndMaybeEscalate(ctx)) return; } catch (err) { finishGenericOrchestration( ctx, `⚠️ **/${orchestrationMode} finished UNVERIFIED**: the driver's verification step failed: ${err instanceof Error ? err.message : String(err)}`, ); return; } finally { genericFinalizing = false; } if (phaseQueue.length === 0) { finishGenericOrchestration(ctx, genericCompletionHeadline()); return; } } const phase = phaseQueue.shift()!; phasePending = true; currentPhase = phase; currentPhaseStartedAt = Date.now(); currentPhaseResult = null; currentPhaseResultKey = null; switchModelForPhase(phase, ctx).then(({ modelId, warning }) => { activateAgent(phase, ctx); const agentName = phase.agent?.name || phase.key; ctx.ui.notify(`\n${phase.label} → \`${modelId}\` (agent: ${agentName})`, "info"); if (warning) ctx.ui.notify(`\n⚠️ ${warning}`, "warning"); setTimeout(() => pi.sendUserMessage(phase.instruction, { deliverAs: "followUp" }), 500); if (phaseTimeoutId) clearTimeout(phaseTimeoutId); const phaseBudget = phase.timeoutMs ?? MAX_PHASE_DURATION_MS; phaseTimeoutId = setTimeout(() => { if (orchestrationActive && phasePending) { phasePending = false; internalAbort = true; try { ctx.abort(); } catch { /* best effort */ } // Telemetry: a timed-out attempt is a row too (the observed // phases:[] bug — the swallowed agent_end never pushed one). runPhaseRecords.push({ key: phase.key, label: phase.label, model: phase.useFallback ? phase.fallback : phase.model, verdict: "TIMEOUT", retried: Boolean(phase.retried), blockedRetried: Boolean(phase.blockedRetried), durationMs: currentPhaseStartedAt ? Date.now() - currentPhaseStartedAt : undefined, }); if (!phase.retried) { phase.retried = true; phase.useFallback = true; phaseQueue.unshift(phase); ctx.ui.notify( `\n⏰ **Phase timed out** (${Math.round(phaseBudget / 60000)} min) — retrying once on the fallback model.`, "warning", ); } else { skippedPhases++; ctx.ui.notify(`\n⏰ **Phase timed out again** — skipping to next phase.`, "warning"); } void sendNextGenericPhase(ctx); } }, phaseBudget); }); } async function handleGenericPhaseEnd(event: any, ctx: any) { const messages = event.messages || []; const analysis = analyzePhaseMessages(messages); if (analysis.userAborted) { ctx.ui.notify(`\n🛑 **/${orchestrationMode} cancelled** by user. Remaining phases skipped.`, "warning"); finishGenericOrchestration(ctx, "🛑 Cancelled."); return; } if (!phasePending) { // Route through sendNextGenericPhase so the /fix oracle still runs on // this (duplicate-event) completion path instead of being bypassed. if (phaseQueue.length === 0) await sendNextGenericPhase(ctx); return; } if (phaseTimeoutId) { clearTimeout(phaseTimeoutId); phaseTimeoutId = null; } // Route through the SAME pure decision machine as /plan so the generic // driver gets the protections it was measured to lack (sympy-11897, a 51s // hasty halt): fatal 401 stop, one retry on a transient provider error. const structuredForThisPhase = currentPhaseResultKey === (currentPhase?.key ?? null) ? currentPhaseResult : null; const outcome = resolvePhaseOutcome(structuredForThisPhase, null); const decision = decidePhaseTransition({ analysis, phase: currentPhase ? { key: currentPhase.key, retried: currentPhase.retried } : null, verdict: outcome.verdict, // The generic driver has no review-fix cycle; pass the cap as spent. reviewFixRounds: 1, maxToolCallsPerPhase: MAX_TOOL_CALLS_PER_PHASE, }); // Telemetry: one record per phase attempt (retries appear as extra rows). if (currentPhase) { runPhaseRecords.push({ key: currentPhase.key, label: currentPhase.label, model: currentPhase.useFallback ? currentPhase.fallback : currentPhase.model, verdict: outcome.verdict, retried: Boolean(currentPhase.retried), blockedRetried: Boolean(currentPhase.blockedRetried), durationMs: currentPhaseStartedAt ? Date.now() - currentPhaseStartedAt : undefined, }); } if (decision.action === "stop") { ctx.ui.notify( `\n❌ **/${orchestrationMode} aborted:** API authentication error (401). Check your API key.`, "error", ); finishGenericOrchestration(ctx, `❌ **/${orchestrationMode} aborted (auth error).**`); return; } if (decision.action === "retry-fallback" && currentPhase) { // Transient provider failure (timeout / 5xx / 429 / broken stream): retry // the SAME phase once on the fallback model before treating any of its // output as a real outcome. currentPhase.retried = true; currentPhase.useFallback = true; phaseQueue.unshift(currentPhase); phasePending = false; ctx.ui.notify( `\n🔁 **Transient provider error** in ${currentPhase.label} — retrying once on the fallback model.`, "warning", ); await sendNextGenericPhase(ctx); return; } // BLOCKED (REPRODUCE cannot reproduce / VERIFY could not confirm): give the // phase ONE second chance on the fallback model — a hasty BLOCKED is cheaper // to re-check than to trust — then halt honestly. No fabricated success. if (decision.action === "pause-blocked" && currentPhase) { if (!currentPhase.blockedRetried) { currentPhase.blockedRetried = true; currentPhase.useFallback = true; phaseQueue.unshift(currentPhase); phasePending = false; ctx.ui.notify( `\n🔁 **${currentPhase.label} reported BLOCKED on the first attempt** — retrying once on the fallback model before halting. ${outcome.handoff || ""}`, "warning", ); await sendNextGenericPhase(ctx); return; } ctx.ui.notify( `\n⏸️ **${currentPhase.label} reported BLOCKED (confirmed on retry).** ${outcome.handoff || "No reproducible/verifiable result."}`, "warning", ); // Never a silent blank page: if the run left changes in the tree (an // unverified FIX attempt), say so instead of pretending nothing exists. const draft = gitIn(ctx.cwd || process.cwd(), "diff --stat").trim(); finishGenericOrchestration( ctx, `⏸️ **/${orchestrationMode} stopped: BLOCKED at ${currentPhase.label}.**` + (draft ? `\n📝 An **UNVERIFIED draft** remains in the working tree (\`git diff\` to inspect, \`git checkout -- .\` to discard):\n\`\`\`\n${draft.slice(0, 600)}\n\`\`\`` : ""), ); return; } // Multi-candidate bookkeeping (mode debug, --candidates N): // - after REPRODUCE: learn the exact repro command from the REPRO-CMD // handoff line (used later for deterministic arbitration); // - after each FIX candidate: capture its patch (git diff of tracked // files) and RESET the tree so the next candidate starts clean. // /fix: the single shot may have WRITTEN its own reproduction (prose // inputs) and declared it via REPRO-CMD — the driver oracle re-runs it. if (fixContext && currentPhase?.key === "shot" && !fixContext.reproFromShot) { fixContext.reproFromShot = parseReproCmd(outcome.handoff); if (fixContext.reproFromShot) { ctx.ui.notify(`\n🧷 Shot-declared reproduction registered: \`${fixContext.reproFromShot}\``, "info"); } } if (candidateContext && currentPhase) { const cwd = ctx.cwd || process.cwd(); if (currentPhase.key === "repro-audit") { // The adversary may have EXTENDED the reproduction — its REPRO-CMD // overrides the one REPRODUCE registered. const updated = parseReproCmd(outcome.handoff); if (updated && updated !== candidateContext.reproCmd) { candidateContext.reproCmd = updated; ctx.ui.notify(`\n🧷 Arbitration reproduction UPDATED by the audit: \`${updated}\``, "info"); } } if (currentPhase.key === "reproduce" && !candidateContext.reproCmd) { candidateContext.reproCmd = parseReproCmd(outcome.handoff); if (candidateContext.reproCmd) { ctx.ui.notify(`\n🧷 Arbitration reproduction registered: \`${candidateContext.reproCmd}\``, "info"); } } if ( currentPhase.key === "localize" && candidateContext.parallelSpecs?.length && candidateContext.list.length === 0 ) { ctx.ui.notify( ` 🧵 **Fanning ${candidateContext.parallelSpecs.length} FIX candidates out to parallel worktrees** (experimental)…`, "info", ); const fan = await runCandidateFanout( cwd, candidateContext.parallelSpecs.map((sp) => ({ model: sp.model, instruction: sp.instruction })), ); for (const o of fan.outcomes) candidateContext.list.push({ source: o.source, patch: o.patch }); if (fan.failures.length) ctx.ui.notify(`⚠️ Candidate failures: ${fan.failures.join("; ")}`, "warning"); ctx.ui.notify( `🧵 Fan-out done — ${fan.outcomes.filter((o) => o.ok).length}/${fan.outcomes.length} candidate patch(es) collected; arbitration next.`, "info", ); } if (currentPhase.key === "fix-cand") { const patch = gitIn(cwd, "diff").trim(); candidateContext.list.push({ source: `${currentPhase.label} (${currentPhase.useFallback ? currentPhase.fallback : currentPhase.model})`, patch: patch ? `${patch}\n` : "", }); gitIn(cwd, "checkout -- ."); ctx.ui.notify( `\n📦 Candidate ${candidateContext.list.length}/${candidateContext.total} captured (${patch ? `${patch.length} bytes` : "EMPTY"}) — tree reset for the next candidate.`, "info", ); } } // Propagate a concise handoff to the next phase, like /plan does. const nextBrief = buildNextBrief( analysis, outcome.handoff, currentPhase?.label || "previous phase", MAX_TOOL_CALLS_PER_PHASE, ); if (nextBrief && phaseQueue.length > 0) { phaseQueue[0].instruction += `\n\n**Previous phase summary:**\n${nextBrief}`; } if (currentPhase) { lastGenericPhase = { key: currentPhase.key, label: currentPhase.label, verdict: outcome.verdict }; } completedPhases++; phasePending = false; await sendNextGenericPhase(ctx); } function startGenericOrchestration( mode: "debug" | "build" | "fix", phases: OrchestratorPhase[], ctx: any, headline: string, ) { phaseQueue = phases.slice(1); orchestrationMode = mode; // Defensive: stale /fix or candidate state must never leak across runs. if (mode !== "fix") fixContext = null; if (mode !== "debug") candidateContext = null; runPhaseRecords = []; lastGenericPhase = null; genericFinalizing = false; sandboxExecCount = 0; sandboxExecMs = 0; setOrchestrationActive(true); phasePending = true; originalModel = ctx.model || null; savedTools = pi.getActiveTools(); completedPhases = 0; skippedPhases = 0; internalAbort = false; currentPhaseResult = null; currentPhaseResultKey = null; phaseStartTime = Date.now(); const first = phases[0]; currentPhase = first; currentPhaseStartedAt = Date.now(); ctx.ui.notify(headline, "info"); for (const p of phases) { const agentName = p.agent?.name || p.key; ctx.ui.notify(` ${p.label} → \`${p.model}\` (agent: ${agentName})`, "info"); } switchModelForPhase(first, ctx).then(({ modelId, warning }) => { activateAgent(first, ctx); ctx.ui.notify(`\n${first.label} → \`${modelId}\``, "info"); if (warning) ctx.ui.notify(`\n⚠️ ${warning}`, "warning"); if (phaseTimeoutId) clearTimeout(phaseTimeoutId); const firstBudget = first.timeoutMs ?? MAX_PHASE_DURATION_MS; phaseTimeoutId = setTimeout(() => { if (orchestrationActive && phasePending) { phasePending = false; internalAbort = true; try { ctx.abort(); } catch { /* best effort */ } // Same policy as every other phase: one retry on the fallback // model before skipping (the old skip-direct lost the whole run // when the very first phase was slow). runPhaseRecords.push({ key: first.key, label: first.label, model: first.useFallback ? first.fallback : first.model, verdict: "TIMEOUT", retried: Boolean(first.retried), blockedRetried: Boolean(first.blockedRetried), durationMs: currentPhaseStartedAt ? Date.now() - currentPhaseStartedAt : undefined, }); if (!first.retried) { first.retried = true; first.useFallback = true; phaseQueue.unshift(first); ctx.ui.notify( `\n⏰ **First phase timed out** (${Math.round(firstBudget / 60000)} min) — retrying once on the fallback model.`, "warning", ); } else { skippedPhases++; ctx.ui.notify(`\n⏰ **First phase timed out again** — skipping.`, "warning"); } void sendNextGenericPhase(ctx); } }, firstBudget); setTimeout(() => pi.sendUserMessage(first.instruction, { deliverAs: "followUp" }), 200); }); } // ─── System Prompt Injection — Agent personas ──────────────────── pi.on("before_agent_start", async (event, _ctx) => { if (!orchestrationActive || !activeAgentPrompt) { return {}; } // COMPOSE, never replace: the base prompt carries AGENTS.md/CLAUDE.md, // the skills list, the active tools' guidelines (phase_result, // sandbox_run...), cwd and date. Replacing it left phase agents blind to // all of that. The persona goes last so its role instructions prevail. return { systemPrompt: composePhaseSystemPrompt(event?.systemPrompt, activeAgentPrompt) }; }); // ─── Agent End Event — Phase Chaining ──────────────────────────── // "agent_end" fires when the full agent loop completes (all tool calls // resolved, response fully generated). This is the ONLY reliable signal // that a phase has finished. // // Previous approach used "output" event which DOES NOT EXIST in Pi. // That's why phases 2-5 never executed. pi.on("agent_end", async (event, ctx) => { if (!orchestrationActive) return; // pi 0.84 retries transient provider errors (429, overloaded, 5xx) inside the // same run and fires agent_end BEFORE the retry. Chaining on that event would // advance to the next phase while the retried turn is still coming, so the // phase would be skipped and the next one would run twice. if (event.willRetry) return; // An internal abort (phase timeout) re-emits agent_end; that transition was // already handled by the timeout. Consume the flag and ignore this event so // it is not mistaken for a user cancellation below. if (internalAbort) { internalAbort = false; return; } // /debug and /build run on the separate linear driver — never through the // /plan-specific review-fix + "/5" transition logic below. if (orchestrationMode !== "plan") { await handleGenericPhaseEnd(event, ctx); return; } const messages = event.messages || []; // Analyze what happened, read the phase's report, and let the pure state // machine (providers/phase-machine.ts, unit tested) decide the transition. // This hook only interprets the decision: notifications, queue edits, // checkpoints, model switches. const analysis = analyzePhaseMessages(messages); // User abort (Ctrl+C / ESC): the aborted run still emits agent_end, but it // must NOT be treated as phase completion. if (analysis.userAborted) { ctx.ui.notify(`\n🛑 **Orchestration cancelled** by user. Remaining phases skipped.`, "warning"); stopOrchestration(); return; } // Allow completion even if phasePending was cleared by a duplicate event if (!phasePending) { // If queue is empty and orchestration is active, force completion if (phaseQueue.length === 0) { sendNextPhase(ctx); } return; } // Clear phase timeout on normal completion if (phaseTimeoutId) { clearTimeout(phaseTimeoutId); phaseTimeoutId = null; } // Resolve the phase outcome: prefer the structured phase_result emission // (exact) and fall back per-field to the regex-scraped markdown report. // Only trust a structured result stamped with THIS phase's key — a stale // result from a previous run or a late tool call is ignored. const reportContent = currentPhase ? readPhaseReport(currentPhase.key, currentRunTs) : null; const structuredForThisPhase = currentPhaseResultKey === (currentPhase?.key ?? null) ? currentPhaseResult : null; const outcome = resolvePhaseOutcome(structuredForThisPhase, reportContent); const verdict = outcome.verdict; const decision = decidePhaseTransition({ analysis, phase: currentPhase ? { key: currentPhase.key, retried: currentPhase.retried } : null, verdict, reviewFixRounds, maxToolCallsPerPhase: MAX_TOOL_CALLS_PER_PHASE, }); if (decision.action === "stop") { // Only a genuine auth failure (401) is fatal — abort the whole workflow. ctx.ui.notify( `\n❌ **Orchestrator aborted:** API authentication error (401)\nCheck your API key and model configuration.`, "error", ); stopOrchestration(); return; } if (decision.action === "retry-fallback" && currentPhase) { // Transient provider/proxy failure (timeout text / 5xx / 429 / broken // JSON tool call) that is NOT a 401: retry the SAME phase once on the // fallback model (a different family often gets through). currentPhase.retried = true; currentPhase.useFallback = true; phaseQueue.unshift(currentPhase); phasePending = false; ctx.ui.notify( `\n🔁 **Transient provider error** in ${currentPhase.label} — retrying once on the fallback model.`, "warning", ); sendNextPhase(ctx); return; } if (decision.action === "pause-blocked" && currentPhase) { ctx.ui.notify( `\n⏸️ **${currentPhase.label} reported BLOCKED.** Pausing /plan — see \`.phi/plans/${currentPhase.key}-${currentRunTs}.md\`. Fix the blocker and re-run \`/plan\` to continue.`, "warning", ); stopOrchestration(); return; } if (decision.action === "continue" && decision.zeroToolCalls && messages.length > 0) { // A phase that made 0 tool calls is NOT fatal: a model may legitimately // answer with text only (e.g. an inline plan). Warn and continue rather // than killing phases 2-5, mirroring the graceful phase-timeout path. ctx.ui.notify( `\n⚠️ **Phase made 0 tool calls** — it may have responded with text only. Continuing to the next phase.`, "warning", ); if (phaseQueue.length > 0) { phaseQueue[0].instruction += `\n\n**Note:** The previous phase made 0 tool calls and may have responded with text only. Make sure you actually call the required tools.`; } } if (decision.action === "continue" && decision.missingVerdict && currentPhase) { // The model deviated from BOTH contract paths: it neither called // phase_result with a verdict nor wrote a parseable "VERDICT:" line. // Surface it instead of silently treating the phase as passed. ctx.ui.notify( `\n⚠️ **${currentPhase.label} reported no verdict** (no phase_result call and no VERDICT line in \`.phi/plans/${currentPhase.key}-${currentRunTs}.md\`) — treating it as passed. Check the report manually.`, "warning", ); } // Prefer the resolved HANDOFF (structured phase_result, else the report's // "## HANDOFF" block) over the heuristic summary; fall back to the // heuristic when neither was provided. const nextBrief = buildNextBrief( analysis, outcome.handoff, currentPhase?.label || "previous phase", MAX_TOOL_CALLS_PER_PHASE, ); if (nextBrief && phaseQueue.length > 0) { phaseQueue[0].instruction += `\n\n**Previous phase summary:**\n${nextBrief}`; } if (decision.action === "review-fix-cycle" && currentPhase) { // REVIEW FAIL: open ONE bounded fix -> re-review cycle. reviewFixRounds++; const blocking = outcome.blocking.slice(0, 4000); const fixPhase: OrchestratorPhase = { key: "code", label: "🔧 Fix — CODE (review remediation)", model: currentPhase.model, fallback: currentPhase.fallback, agent: loadAgentDef("code"), instruction: `You are the CODE agent. REVIEW found BLOCKING issues. Fix ONLY these, root cause not workaround, then update \`.phi/plans/progress-${currentRunTs}.md\`.\n\n## BLOCKING findings to fix:\n${blocking || "(see the review report in .phi/plans/)"}\n` + COMMON_PHASE_RULES, }; const reReviewPhase: OrchestratorPhase = { ...currentPhase, retried: false, useFallback: false, label: "🔍 Re-REVIEW (after fix)", }; // Run next: fix, then re-review. phaseQueue.unshift(reReviewPhase); phaseQueue.unshift(fixPhase); ctx.ui.notify(`\n🔁 **REVIEW verdict: FAIL** — running one targeted fix + re-review cycle.`, "warning"); } // Checkpoint resume position after each base phase (synthetic fix/re-review // phases have no baseIndex and do not advance it). if (currentPhase && typeof currentPhase.baseIndex === "number") { writeCheckpoint(currentPhase.baseIndex + 1); } // Phase complete — chain to next completedPhases++; phasePending = false; sendNextPhase(ctx); }); // ─── /plan Command — Full workflow ─────────────────────────────── pi.registerCommand("plan", { description: "Plan AND execute a project — 5 phases, each with its own model from routing.json", handler: async (args, ctx) => { const rawArgs = args.trim(); // Resume a crashed / aborted orchestration from its checkpoint. if (/^(--resume|resume)\b/i.test(rawArgs)) { const cp = readCheckpoint(); if (!cp) { ctx.ui.notify("No orchestration checkpoint to resume. Start one with `/plan `.", "warning"); return; } await ensurePlansDir(); currentDescription = cp.description; // Reuse the saved timestamp so the rebuilt phases point at the same // .phi/plans/*.md handoff files that the earlier run produced. const rphases = buildPhases(cp.description, cp.ts); const remaining = rphases.slice(Math.max(0, Math.min(5, cp.nextBaseIndex))); if (remaining.length === 0) { clearCheckpoint(); ctx.ui.notify("Checkpoint already complete — nothing to resume.", "info"); return; } setOrchestrationActive(true); phasePending = true; originalModel = ctx.model || null; savedTools = pi.getActiveTools(); completedPhases = cp.nextBaseIndex; skippedPhases = 0; reviewFixRounds = 0; internalAbort = false; // Clear any structured result left over from a prior run so this // resumed phase's outcome is read fresh (see phase-result leak guard). currentPhaseResult = null; currentPhaseResultKey = null; phaseStartTime = Date.now(); const firstResume = remaining[0]; currentPhase = firstResume; phaseQueue = remaining.slice(1); ctx.ui.notify( `📋 **Resuming orchestration** at ${firstResume.label} (${remaining.length} phase(s) left)\n`, "info", ); const { modelId, warning } = await switchModelForPhase(firstResume, ctx); activateAgent(firstResume, ctx); ctx.ui.notify(`${firstResume.label} → \`${modelId}\``, "info"); if (warning) ctx.ui.notify(`\n⚠️ ${warning}`, "warning"); setTimeout(() => pi.sendUserMessage(firstResume.instruction, { deliverAs: "followUp" }), 200); return; } // Opt-in: `--fanout` runs a small read-only parallel exploration before // phase 1 (default OFF — single-agent EXPLORE, the safe behaviour). const wantFanout = /(^|\s)--fanout\b/.test(rawArgs); const description = rawArgs.replace(/(^|\s)--fanout\b/g, " ").trim(); if (!description) { ctx.ui.notify( `**Usage:** \`/plan \` (or \`/plan --resume\` to continue a checkpointed run, \`/plan --fanout \` for parallel exploration) **Examples:** /plan Build a REST API for user authentication with JWT /plan Create a cyberpunk Pong browser game /plan Add test coverage to the payment module **Other commands:** /plans — List all plans`, "info", ); return; } // Create plan files await ensurePlansDir(); const ts = timestamp(); const specFile = `spec-${ts}.md`; await writeFile( join(plansDir, specFile), `# ${description}\n\n**Created:** ${new Date().toLocaleString()}\n`, "utf-8", ); // Build phases with model assignments + agent definitions currentDescription = description; const phases = buildPhases(description); phaseQueue = phases.slice(1); // Queue phases 2-5 setOrchestrationActive(true); phasePending = true; // Capture the user's model + full toolset so they can be restored when // orchestration ends (otherwise /plan permanently overwrites /model and // per-phase tool restrictions can leak). originalModel = ctx.model || null; savedTools = pi.getActiveTools(); completedPhases = 0; skippedPhases = 0; reviewFixRounds = 0; internalAbort = false; // Clear any structured result left over from a previous /plan run in // this session; the first phase is launched directly (not via // sendNextPhase), so without this a stale verdict/handoff would leak. currentPhaseResult = null; currentPhaseResultKey = null; const firstPhase = phases[0]; currentPhase = firstPhase; ctx.ui.notify(`📋 **Orchestrator started** — 5 phases with model routing + agent roles\n`, "info"); // Show the plan for (const p of phases) { const agentName = p.agent?.name || p.key; const toolCount = p.agent?.tools.length || 0; ctx.ui.notify(` ${p.label} → \`${p.model}\` (agent: ${agentName}, ${toolCount} tools)`, "info"); } ctx.ui.notify("", "info"); // Record orchestration start time for final summary phaseStartTime = Date.now(); // Opt-in parallel EXPLORE fan-out (read-only, <=2 concurrent, sequential // fallback on rate limit). Best-effort: any failure degrades to the normal // single-agent EXPLORE below by simply not enriching the instruction. if (wantFanout) { try { const available: Model[] = ctx.modelRegistry?.getAvailable?.() || []; const exploreModelId = resolveModelRef(available, firstPhase.model)?.id || firstPhase.model; ctx.ui.notify( `\n🔭 **Parallel exploration** (read-only, up to 2 concurrent) — building a fuller map before phase 1...`, "info", ); // --fanout is wired on the parallel-agents executor (phase 5): each // explorer spec becomes a registry-visible task (live in /agents, // killable via /agents kill). Read-only: no worktree isolation. const specs = defaultExplorerSpecs(description); const explorerResults: ExplorerResult[] = []; const parallelResults = await runParallel( specs.map((spec, i) => ({ id: `explorer-${i + 1}:${spec.focus.slice(0, 24)}`, run: async () => { const r = await runExplorer(spec, { model: exploreModelId, tools: READONLY_EXPLORER_TOOLS, cwd: ctx.cwd || process.cwd(), timeoutMs: 4 * 60 * 1000, }); explorerResults[i] = r; return r.text; }, })), { maxConcurrency: 2, useWorktrees: false }, ); const present = explorerResults.filter(Boolean); const merged = mergeExplorerResults(present); const rateLimited = present.some((r) => r.rateLimited); const okCount = parallelResults.filter((r) => r.verdict === "success").length; if (merged.trim()) { firstPhase.instruction = `## Parallel exploration findings (${okCount} read-only sub-explorer(s))\nUse these as a starting map; verify and synthesize them into your brief, do not trust them blindly.\n\n${merged}\n\n---\n${firstPhase.instruction}`; ctx.ui.notify( `\n🔭 ${okCount} sub-exploration(s) merged into EXPLORE${rateLimited ? " (rate limit hit)" : ""}.`, "info", ); } else { ctx.ui.notify( `\n🔭 Parallel exploration returned nothing usable${rateLimited ? " (rate-limited)" : ""} — running the normal single-agent EXPLORE.`, "warning", ); } } catch { ctx.ui.notify( `\n🔭 Parallel exploration skipped (error) — running the normal single-agent EXPLORE.`, "warning", ); } } // Switch model and activate agent for first phase const { modelId, warning } = await switchModelForPhase(firstPhase, ctx); activateAgent(firstPhase, ctx); const agentName = firstPhase.agent?.name || firstPhase.key; ctx.ui.notify(`${firstPhase.label} → \`${modelId}\` (agent: ${agentName})`, "info"); if (warning) ctx.ui.notify(`\n⚠️ ${warning}`, "warning"); setTimeout(() => pi.sendUserMessage(firstPhase.instruction, { deliverAs: "followUp" }), 200); }, }); // ─── /run Command — Re-execute existing plan ───────────────────── pi.registerCommand("run", { description: "Re-execute an existing plan (deprecated — use /plan instead)", handler: async (_args, ctx) => { ctx.ui.notify( "⚠️ `/run` is deprecated. Use `/plan ` to create and execute a new plan with the 5-phase orchestrator.", "warning", ); }, }); // ─── /plans Command ────────────────────────────────────────────── pi.registerCommand("plans", { description: "List all project plans and their execution status", handler: async (_args, ctx) => { if (!existsSync(plansDir)) { ctx.ui.notify("No plans yet. Use `/plan ` to create and execute one.", "info"); return; } const files = await readdir(plansDir); const specs = files .filter((f) => f.startsWith("spec-") && f.endsWith(".md")) .sort() .reverse(); if (specs.length === 0) { ctx.ui.notify("No plans found.", "info"); return; } let output = `📁 **Project Plans** (${specs.length})\n\n`; for (const specFile of specs) { const ts = specFile.replace("spec-", "").replace(".md", ""); const todoFile = `todo-${ts}.md`; const progressFile = `progress-${ts}.md`; try { const content = await readFile(join(plansDir, specFile), "utf-8"); const titleMatch = content.match(/^# (.+)$/m); const title = titleMatch ? titleMatch[1] : specFile; const taskCount = (content.match(/\| \d+ \|/g) || []).length; const date = ts.replace(/_/g, " ").substring(0, 10); const hasTodo = files.includes(todoFile); const hasProgress = files.includes(progressFile); const status = hasProgress ? "🟢 executed" : hasTodo ? "🟡 planned" : "⚪ spec only"; output += `📋 **${title}** (${date}) ${status}\n`; output += ` Spec: \`${specFile}\``; if (hasTodo) output += ` | Todo: \`${todoFile}\``; if (hasProgress) output += ` | Progress: \`${progressFile}\``; output += "\n"; if (taskCount > 0) output += ` Tasks: ${taskCount}\n`; output += "\n"; } catch { output += `📋 \`${specFile}\`\n\n`; } } output += `_Commands: \`/plan\` (create+execute), \`/run\` (re-execute), \`read .phi/plans/\` (view)_`; ctx.ui.notify(output, "info"); }, }); // ─── /debug Command — turn a real failure green (execution-grounded) ── pi.registerCommand("debug", { description: "Fix a REAL failing state — REPRODUCE → LOCALIZE → FIX → VERIFY, verdict backed by a real run", handler: async (args, ctx) => { if (orchestrationActive) { ctx.ui.notify("An orchestration is already running. Let it finish, or restart the session.", "warning"); return; } const raw = args.trim(); if (!raw) { ctx.ui.notify( `**Usage:** \`/debug \` /debug never guesses — it needs something reproducible. **Examples:** /debug pytest tests/test_auth.py::test_login_returns_jwt /debug node repro.js (segfaults on empty input, should return []) /debug the /login route 500s when the body is missing It runs REPRODUCE → LOCALIZE → FIX → VERIFY and only reports FIXED with a real before/after run — otherwise BLOCKED.`, "info", ); return; } // Opt-in multi-candidate FIX: `--candidates N` (2..4). Diversity // proposes (N model families patch independently), the oracle disposes // (a real run arbitrates). Cost-disciplined: default stays 1. const wantParallel = /(^|\s)--parallel\b/.test(raw); const candMatch = raw.match(/(^|\s)--candidates[= ](\d)\b/); let candidates = candMatch ? Math.max(1, Math.min(4, Number(candMatch[2]))) : 1; const cleaned = raw .replace(/(^|\s)--candidates[= ]\d\b/g, " ") .replace(/(^|\s)--parallel\b/g, " ") .trim(); const cwd = ctx.cwd || process.cwd(); const state: FailingState = parseFailingState(cleaned, { cwd }); // Honest gate at the boundary: /debug needs a reproducible failure. A bare // prose description with no test/command still runs (REPRODUCE will try to // derive one), but we tell the user the oracle depends on a real run. if (!state.failingTest && !state.reproCommand) { ctx.ui.notify( `⚠️ No failing test or repro command detected — /debug works best with one (e.g. \`pytest …\` or \`node repro.js\`). Proceeding: REPRODUCE will try to construct a reproduction from your description, and will emit **BLOCKED** if it cannot run one (no fabricated PASS).`, "warning", ); } if (candidates > 1) { // Candidate capture RESETS the tree between attempts — refuse to do // that over a user's uncommitted work (non-deletion policy). const porcelain = runCommand("git status --porcelain", { cwd, timeoutMs: 30_000 }); if (!passed(porcelain)) { ctx.ui.notify( "⚠️ `--candidates` needs a git repository (candidate patches are captured and arbitrated via git). Falling back to the single-candidate pipeline.", "warning", ); candidates = 1; } else if (porcelain.stdout.trim()) { ctx.ui.notify( "⚠️ Your working tree has uncommitted changes — candidate arbitration resets the tree between attempts and will NOT run over them. Commit/stash first for multi-candidate. Falling back to the single-candidate pipeline.", "warning", ); candidates = 1; } } await ensurePlansDir(); const parallel = wantParallel && candidates > 1; const phases = buildDebugPhases(state, candidates, parallel); if (candidates > 1) { candidateContext = { total: candidates, reproCmd: state.failingTest?.trim() || state.reproCommand?.trim() || undefined, list: [], arbitrated: false, parallelSpecs: parallel ? pickCandidateModels(readRoutingConfig(), candidates).map((model, i) => ({ model, instruction: `${debugPhaseInstructions(state).fix} **Candidate protocol:** you are INDEPENDENT candidate ${i + 1} of ${candidates}, working in an isolated worktree. A REAL run arbitrates between candidates afterwards. Make your own best minimal fix.`, })) : undefined, }; } startGenericOrchestration( "debug", phases, ctx, candidates > 1 ? `🐛 **/debug started (multi-candidate ×${candidates})** — REPRODUCE → LOCALIZE → ${candidates} independent FIXes → real-run arbitration\n` : `🐛 **/debug started** — 4 execution-grounded phases (verdict requires a real run)\n`, ); }, }); // ─── /fix Command — single-shot first, oracle next, escalate on red ── // Measured (n=13, official SWE-bench harness): the single shot resolved 7/13 // vs the full pipeline's 6/13 at ~2.5× the time, and both arms converged on // 11/13. /fix is the composition: by construction never worse than the // single shot, and it inherits the pipeline exactly where a REAL red run // proves the shot failed. pi.registerCommand("fix", { description: "Fix at single-shot cost, verified by the sandbox oracle — escalates to the full /debug pipeline only if a real run stays red", handler: async (args, ctx) => { if (orchestrationActive) { ctx.ui.notify("An orchestration is already running. Let it finish, or restart the session.", "warning"); return; } const raw = args.trim(); if (!raw) { ctx.ui.notify( `**Usage:** \`/fix \` /fix = one direct attempt, then the ORACLE (reproduction + suite in the sandbox): green → done at single-shot cost; red → the full /debug pipeline takes over, seeded with the red run. **Examples:** /fix pytest tests/test_auth.py::test_login_returns_jwt /fix node repro.js (crashes on empty input, should return []) /fix the /login route 500s when the body is missing With no runnable check at all, the result is honestly labelled UNVERIFIED.`, "info", ); return; } const state: FailingState = parseFailingState(raw, { cwd: ctx.cwd || process.cwd() }); if (!state.failingTest && !state.reproCommand) { ctx.ui.notify( `⚠️ No failing test or repro command detected — the /fix oracle will rely on the project suite alone (or report UNVERIFIED if none is known). A concrete repro gives a guaranteed verdict.`, "warning", ); } await ensurePlansDir(); fixContext = { state, oracleRan: false }; // Tiered budget (measured: hard instances burned the whole run in the // shot, leaving the escalation nothing): triage decides how long the // single shot deserves before the pipeline takes over. const t = triage({ text: raw, hasFailingState: Boolean(state.failingTest || state.reproCommand) }); const shot = genericPhase("shot", "🎯 Phase 1 — SINGLE SHOT", "code", "code", singleShotInstruction(state)); // A real single shot legitimately runs 8–18 min (measured on the // baselines); the flat 10 min phase cap was killing it mid-work. The // tiered shotBudgetMs (6 to 12 min) used to be computed, announced, then // overwritten by this value: announce the budget that actually applies. shot.timeoutMs = FIX_SHOT_BUDGET_MS; ctx.ui.notify( `⏱️ Shot budget: ${Math.round(FIX_SHOT_BUDGET_MS / 60000)} min (triage: ${t.route}, ${t.reason}).`, "info", ); startGenericOrchestration( "fix", [shot], ctx, `🎯 **/fix started** — single shot, then the sandbox oracle decides (green = done, red = full pipeline)\n`, ); }, }); // ─── /build Command — build until it runs (plan + execution loop) ──── pi.registerCommand("build", { description: "Build from a spec AND prove it runs — EXPLORE → PLAN → CODE → BUILD-VERIFY (run + red-team + debug)", handler: async (args, ctx) => { if (orchestrationActive) { ctx.ui.notify("An orchestration is already running. Let it finish, or restart the session.", "warning"); return; } const spec = args.trim(); if (!spec) { ctx.ui.notify( `**Usage:** \`/build \` /build = /plan then an execution-grounded verify loop (run the recipe, check acceptance, executable red-team, fix real failures via /debug). **Examples:** /build a REST API for user auth with JWT and refresh tokens /build a CLI that converts CSV to JSON with a --pretty flag It reports SUCCESS only when a real run meets the acceptance criteria — otherwise an honest PARTIAL listing what still fails. For a pure decomposition use \`/plan\`; to fix a known failure use \`/debug\`.`, "info", ); return; } // Cheap triage note (transparency): confirm /build is the right depth. const decision = triage({ text: spec }); if (decision.route === "single-shot") { ctx.ui.notify( `ℹ️ This looks small and self-contained (${decision.reason}). /build will still run, but a single request may be cheaper.`, "info", ); } await ensurePlansDir(); const ts = timestamp(); await writeFile( join(plansDir, `spec-${ts}.md`), `# ${spec}\n\n**Created:** ${new Date().toLocaleString()}\n`, "utf-8", ); currentDescription = spec; const phases = buildBuildPhases(spec, ts); startGenericOrchestration( "build", phases, ctx, `🏗️ **/build started** — plan + execution loop (SUCCESS requires a real run, else honest PARTIAL)\n`, ); }, }); // ─── /sandbox Command — inspect / prepare the guaranteed environment ── // ─── /runs Command — exploit the telemetry (continuous measurement) ── pi.registerCommand("runs", { description: "Aggregate .phi/runs.jsonl — green-at-shot rate, escalations, durations, slowest phases", handler: async (_args, ctx) => { const cwd = ctx.cwd || process.cwd(); let blob = ""; try { blob = readFileSync(join(cwd, ".phi", "runs.jsonl"), "utf-8"); } catch { /* no file yet */ } ctx.ui.notify(summarizeRuns(parseRunsJsonl(blob)), "info"); }, }); // ─── /fix suggestion — the measured-best default, surfaced once ───── // A message that reads like a bug report gets a one-line tip pointing at // /fix (never worse than a single shot, oracle-verified). Suggest once per // session, never during an orchestration, and NEVER intercept the input. let fixHintShown = false; pi.on("input", async (event: any, ctx: any) => { try { const text = typeof event?.text === "string" ? event.text : ""; if (!fixHintShown && !orchestrationActive && looksLikeBugReport(text)) { fixHintShown = true; ctx.ui.notify( "💡 This looks like a bug report — `/fix ` runs one attempt, verifies it in the sandbox oracle, and escalates to the full /debug pipeline only if a real run stays red.", "info", ); } } catch { /* a hint must never break input */ } return undefined; // pass through untouched }); pi.registerCommand("sandbox", { description: "Inspect or prepare the project's execution sandbox (Docker when available) — status | prepare | run ", handler: async (args, ctx) => { const cwd = ctx.cwd || process.cwd(); const raw = args.trim(); const [sub, ...rest] = raw.split(/\s+/); const sandbox = getSessionSandbox(cwd, ctx); if (!sub || sub === "status") { const r = sandbox.recipe; ctx.ui.notify( `🧪 **Sandbox status**\n` + ` Backend: \`${sandbox.backend}\` — ${sandbox.reason}\n` + ` Environment: ${sandbox.describe()}\n` + ` Image: \`${r.image}\` (source: ${r.source})\n` + ` Setup: ${r.setup ? `\`${r.setup}\`` : "—"}\n` + ` Test: ${r.test ? `\`${r.test}\`` : "—"}\n` + (sandbox.backend === "unavailable" ? `\n⚠️ No guaranteed environment. /debug and /build will emit BLOCKED rather than fabricate a pass. Install/start Docker, or add \`.phi/sandbox.json\`.` : sandbox.backend === "local" ? `\n⚠️ Running on the host (not dependency-guaranteed). Start Docker for a guaranteed environment.` : `\n✅ Guaranteed environment ready. Run \`/sandbox prepare\` to pull the image and install deps.`), "info", ); return; } if (sub === "prepare") { ctx.ui.notify(`🧪 Preparing sandbox (${sandbox.describe()})… this can take a while on first run.`, "info"); const p = sandbox.prepare(); ctx.ui.notify( `${p.ok ? "✅" : "❌"} **Sandbox prepare** — ${p.detail}` + (p.result && !p.ok ? `\n\n\`\`\`\n${tail(p.result, 30)}\n\`\`\`` : ""), p.ok ? "info" : "warning", ); return; } if (sub === "run") { const command = rest.join(" ").trim(); if (!command) { ctx.ui.notify("**Usage:** `/sandbox run `", "warning"); return; } if (!sandbox.available()) { ctx.ui.notify(`❌ Sandbox unavailable — ${sandbox.reason}. Cannot run.`, "warning"); return; } ctx.ui.notify(`🧪 \`${command}\` in ${sandbox.describe()}…`, "info"); // Async: a user-invoked run can last minutes; never freeze the TUI. const result = await sandbox.execAsync(command); const verdict = result.timedOut ? "TIMEOUT" : passed(result) ? "PASS" : "FAIL"; ctx.ui.notify( `${passed(result) ? "✅" : "❌"} exit ${result.exitCode ?? "?"} ${verdict}\n\n\`\`\`\n${tail(result, 40) || "(no output)"}\n\`\`\``, passed(result) ? "info" : "warning", ); return; } ctx.ui.notify("**Usage:** `/sandbox [status | prepare | run ]`", "info"); }, }); }