diff --git a/docs/studio/development.md b/docs/studio/development.md index 2bf14648..40136c55 100644 --- a/docs/studio/development.md +++ b/docs/studio/development.md @@ -43,7 +43,7 @@ - `hook/tests/answer.rs`: the answer hook's contract (Seam 4), including a blocked command's denial returned at once with no decision, a payload on stdin and the studio played by the test in a scratch `HOME`: an answer's `allow` with the questions and each label, a multi-select's joined; an approved plan's `allow` with its input and a rejected one's `deny`; a permission's `allow` or `deny`; each card answer logged as `StudioAnswer`, a terminal one not; for questions, plans and permissions alike, an immediate return with no decision when nobody watches, another session is watched, the studio's pid is dead or its heartbeat old; no decision at the timeout or for "Answer in the terminal"; a wrong nonce or an answer file others may write refused; - the unit tests of the event log's path and of the turn the shell's `StudioInterrupted` line ends, its own and never a later one (`hook`), of what `scrub` keeps (`studio-core`), of the weekly rates' dates (`understanding`), of the shell's risk-note log lines, which keep no reply and no command, and of a worker's view joining its session's risk notes and asks and of the cards key changing with a second card of a judged command and of the server's own lines waiting for the log's lock, then landing whole (`server/src/lib.rs`) and of the settings file's reads (`server/src/settings.rs`: the writer, `briefBackfill.hours` and its older name `catchUp.hours`, `prBriefs.model`, Opus unless it says another, `prBriefs.effort`, low unless it names another claude takes or `default`, and a background run's `backgroundRuns`, `checks` and `setup`, its project's own with no default) and of the settings' write: a comment and a trailing comma beside the edited key kept byte for byte, a value replaced, a missing parent inserted, reset removing the key, a text that does not parse or a file that changed refused and left as it was, a missing file created, the file replaced whole with nothing left beside it, and a symbolic link written through and kept. and of the PR briefs (`server/src/prs.rs`: which PRs are ready from the sessions' branches and the repository's open list, a failed lookup keeping what was known; `pr_briefs.rs`: the write once per head, stale on a new head, no lock held across a write, a failed head not retried, what waits for Daniel and what a chapter lights, and which ready PRs the start writes, at most 3, the newest head first within `briefBackfill.hours`; `part_catch_ups.rs`: which fogged part gets a part catch-up and which opens its one PR's chapter, completion clearing the part's fog and completing no brief, a stored catch-up read only for the fog list it covers, and, with a fake writer, a shown map writing at most 8 fogged Core parts' catch-ups oldest fog first and none of the others, a part that is not Core written on click, the catch-up's state carrying the stage as each call starts, a new fog entry rewriting it on the next show and an unchanged one never, and two shows in a row starting one write; `ratify.rs`: the decisions file read and written back whole, what has landed; `fog.rs`: reads and the fog a push after reading files; `history.rs`: a PR's files for the drawer). -Each crate's integration tests are one test binary, `it`: its `Cargo.toml` sets `autotests = false`, and `tests/main.rs` declares each `tests/*.rs` file as a module, so a new test file needs a `mod` line there. Helpers the files share live in `tests/common.rs`; the git helpers that `hook`, `understanding` and `workbench` share (an isolated `git`, a one-commit repository, also in a folder the test names, a bare `origin`) and the `LauncherGuard` that `server`'s tests hold to stop the `plotkeeper-run` launchers a test leaves running live in the `studio-test-support` crate (`test-support/`), a dev-dependency that depends on no workspace crate. The fake writers of `understanding/tests` are `Scripted` in its `common.rs`. In `ui/tests/`, `dom.mjs` holds the fake document (`fakeDocument`) and the `invoke` stub (`tauri`). +Each crate's integration tests are one test binary, `it`: its `Cargo.toml` sets `autotests = false`, and `tests/main.rs` declares each `tests/*.rs` file as a module, so a new test file needs a `mod` line there. Helpers the files share live in `tests/common.rs`; the git helpers that `hook`, `understanding` and `workbench` share (an isolated `git`, a one-commit repository, also in a folder the test names, a bare `origin`) and the `LauncherGuard` that `server`'s tests hold to stop the `plotkeeper-run` launchers a test leaves running live in the `studio-test-support` crate (`test-support/`), a dev-dependency that depends on no workspace crate. The fake writers of `understanding/tests` are `Scripted` in its `common.rs`. In `ui/tests/`, `dom.mjs` holds the fake document (`fakeDocument`) and the `invoke` stub (`tauri`), and `delegate-fixtures.mjs` the stand-in programs and scratch checkouts the `delegate-*.test.mjs` files share. `npm test` (after `npm ci`), or `npm run test:node`, builds the UI with `tsc`, type-checks the tests against the build's `dist/*.d.ts` (`npm run test:types`, `ui/tests/tsconfig.json`, #554) and runs `ui/tests/`: the UI's pure functions on the `tsc` output in `dist/`, such as the page's frame: the list's width and focus mode (`layout`), the page's key mapping (`keys`), what "now" holds in each state, a folded turn's line, and the story's draws keeping its turns, folds, buttons, counting times, focus and open folds the same nodes, on a stand-in that is in a page (`rail`), the evidence line (`evidence`), the banner's 14 and 15 minutes (`banner`), hover as a state machine on an injected clock (`hover`), and Ask and the diff pane (`ask`, `diff`), the agent logos and the rows that show them (`logos`), each text the layout cuts, whole in its own element and scrolled into view in place, or, shortened or very long, whole in a hint, and no `title` left (`full-text`), a listener-path hint across redraws: the trigger `patch` keeps opens the hint of its current words, a hint gains no listeners per draw and goes once its trigger is dropped, and a step's detail drops the last step's hint (`hint-redraw`), the note toast, its fade held by the pointer or the focus on an injected clock, and the unseen chip (`notes`), the what's-new toast's decision after an update (`whats-new`), the toasts in the keyboard (`focus`), the PR brief's logic (`map-brief`: a story's and a chapter's playlist, the player that reopens where it left off, the reading gate on the last story step, the checks, the story steps without the Ratify one), the tray's rows (`map-tray`), the background runs' rows, Cancel and its wait for the server's answer, the pause's indicator, the prompt a failed run copies and its note kept across a redraw (`map-runs`), back a law's rows, the patch review, Open draft PR's line and Guard with a law's confirm step (`patch-review`), Explore this's offers and the micro-world's sandboxed frame and overlay (`micro-world`), the host check's network guard on a fake and, when `PLOTKEEPER_DSH_VISUAL` names it, the real `verify.mjs` (`micro-world-guard`), the rail's row of a brief waiting (`rail-brief`) and the accept and overturn rows (`ratify`), the snap page and its fixtures (`snap`: the stub, the rail's and the recorded terminal's), and the README's limits, links and npm rewrite (`readme`), and the Map view's logic: the map file, placement, drag, links and the layered Esc, and which scrub is the newest (`map`), live agents on the parts and the not-placed line (`map-agents`), broken laws and the proof drawer (`map-drawer`), when an element counts as seen (`seen`), and the stop rules' review (`stop-rules`); opening a thing in place leaves every other node of the rail the same object, on the tests' small DOM (`dom.mjs`). diff --git a/ui/tests/delegate-critic.test.mjs b/ui/tests/delegate-critic.test.mjs new file mode 100644 index 00000000..e67089a7 --- /dev/null +++ b/ui/tests/delegate-critic.test.mjs @@ -0,0 +1,134 @@ +// `node scripts/agents/delegate.mjs pick critic`, with a stand-in `agy` first on the PATH. +// These tests run no real `agy`. Run: `npm test`. +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { spawnSync } from "node:child_process"; +import { existsSync } from "node:fs"; +import { join } from "node:path"; +import { pickCritic, script } from "./delegate-fixtures.mjs"; + +test("with both Gemini windows at their floors, pick critic runs the Gemini critic read-only and prints its findings", () => { + const ran = pickCritic({ FAKE_AGY_5H: "0.5", FAKE_AGY_WEEKLY: "0.3", FAKE_AGY_RUN: "ok" }); + assert.equal(ran.status, 0, ran.stderr); + assert.equal( + ran.stdout, + "critic: agy gemini-test-model\n\n1. high, contradiction: The store reads src/store.rs:7\n Evidence: src/store.rs:1\n The file has one line.\n", + ); + const critic = ran.calls.find((call) => !call.argv.includes("/usage")); + assert.ok(critic, "agy -p was not called for the critic"); + const argv = critic.argv; + const after = (flag) => argv[argv.indexOf(flag) + 1]; + // Not plan mode, which ends the run at the first denied command (#618): the deny hook keeps it read-only. + assert.equal(argv.includes("--mode"), false); + assert.equal(after("--model"), "gemini-test-model"); + assert.equal(after("--print-timeout"), "15m"); + assert.equal(after("--output-format"), "json"); + assert.equal(after("--json-schema"), join(critic.cwd, "review/schema.json")); + assert.match(after("-p"), /check every claim/i); + assert.match(after("-p"), /Your only working tool is read_file/); + assert.equal(after("-p").includes("@"), false, "an at-sign may read a file past the hook"); + assert.notEqual(critic.cwd, ran.repo); + assert.equal(critic.internal, "1"); + // It read the draft through the hook, in a worktree of HEAD whose files tree.txt lists. + assert.deepEqual(ran.seen, [{ draft: "# A draft\n\nThe store reads `src/store.rs:7`.\n", worktree: true, tree: `${join(critic.cwd, "repo/src/store.rs")}\n` }]); + // And left no throwaway folder or worktree behind. + assert.equal(existsSync(critic.cwd), false); + assert.equal(ran.worktrees.match(/^worktree /gm).length, 1, ran.worktrees); +}); + +test("a Gemini critic run with no findings says so", () => { + const ran = pickCritic({ FAKE_AGY_5H: "0.9", FAKE_AGY_WEEKLY: "0.9", FAKE_AGY_RUN: "none" }); + assert.equal(ran.status, 0, ran.stderr); + assert.equal(ran.stdout, "critic: agy gemini-test-model\n\nNo findings.\n"); +}); + +// A breakdown's critic gets a brief of its own: the routing rules to hold the routes to, not only claims to check. +const BREAKDOWN = /^You are the critic of a draft ticket breakdown[\s\S]*Routing section of docs\/agents\/issue-tracker\.md[\s\S]*Risk isolation[\s\S]*CI[\s\S]*departs from the spec[\s\S]*Daniel/; + +test("pick critic --breakdown gives the Gemini critic and the Claude fallback the breakdown brief, then the breakdown", () => { + const gemini = pickCritic({ FAKE_AGY_5H: "0.9", FAKE_AGY_WEEKLY: "0.9", FAKE_AGY_RUN: "ok" }, "breakdown"); + assert.equal(gemini.status, 0, gemini.stderr); + const argv = gemini.calls.find((call) => !call.argv.includes("/usage")).argv; + const brief = argv[argv.indexOf("-p") + 1]; + assert.match(brief, BREAKDOWN); + assert.match(brief, /The breakdown, with its spec: \S+\/review\/draft\.md/); + assert.equal(gemini.seen[0].draft, "# A draft\n\nThe store reads `src/store.rs:7`.\n"); + const claude = pickCritic({ FAKE_AGY_5H: "0.49", FAKE_AGY_WEEKLY: "0.9" }, "breakdown"); + assert.equal(claude.status, 0, claude.stderr); + const { head, prompt } = claudeCritic(claude.stdout); + assert.match(head, /^critic: claude opus effort high\n/); + assert.match(prompt, BREAKDOWN); + assert.match(prompt, /\n\nThe breakdown, with its spec:\n\n# A draft\n\nThe store reads `src\/store\.rs:7`\.\n$/); + assert.ok(brief.startsWith(prompt.slice(0, prompt.indexOf("\n\nThe breakdown, with its spec:"))), "the Claude critic gets the brief Gemini got"); +}); + +for (const [what, args] of [ + ["neither --spec nor --breakdown", []], + ["both --spec and --breakdown", ["--spec", "a.md", "--breakdown", "b.md"]], +]) { + test(`pick critic with ${what} is a usage error`, () => { + const ran = spawnSync(process.execPath, [script, "pick", "critic", ...args], { encoding: "utf8" }); + assert.equal(ran.status, 2); + assert.match(ran.stderr, /one of --spec or --breakdown is required/); + }); +} + +const ranCritic = (calls) => calls.some((call) => !call.argv.includes("/usage")); + +/** Splits what `pick critic` printed for a Claude critic into its first lines and the prompt it printed after them. */ +const claudeCritic = (stdout) => { + const [head, ...rest] = stdout.split("\n\n"); + return { head, prompt: rest.join("\n\n") }; +}; + +// The prompt a Claude critic gets: the critic's brief, then the draft. +const BRIEFED = /^You are the critic of a draft spec[\s\S]*Check every claim[\s\S]*\n\nThe draft:\n\n# A draft\n\nThe store reads `src\/store\.rs:7`\.\n$/; + +test("with the 5-hour window below its floor, pick critic names Opus at high and prints its prompt, without running Gemini", () => { + const ran = pickCritic({ FAKE_AGY_5H: "0.49", FAKE_AGY_WEEKLY: "0.9", FAKE_AGY_RUN: "ok" }); + assert.equal(ran.status, 0, ran.stderr); + const { head, prompt } = claudeCritic(ran.stdout); + assert.equal(head, "critic: claude opus effort high\nwhy: agy gemini-test-model has 49% of its 5h window and 90% of its weekly window left, under its floors of 50% and 30%"); + assert.match(prompt, BRIEFED); + assert.equal(ranCritic(ran.calls), false); +}); + +test("with the weekly window below its floor, pick critic names Opus at high without running Gemini", () => { + const ran = pickCritic({ FAKE_AGY_5H: "0.9", FAKE_AGY_WEEKLY: "0.29", FAKE_AGY_RUN: "ok" }); + assert.equal(ran.status, 0, ran.stderr); + const { head, prompt } = claudeCritic(ran.stdout); + assert.equal(head, "critic: claude opus effort high\nwhy: agy gemini-test-model has 90% of its 5h window and 29% of its weekly window left, under its floors of 50% and 30%"); + assert.match(prompt, BRIEFED); + assert.equal(ranCritic(ran.calls), false); +}); + +test("with no quota reading, pick critic names Opus at high without running Gemini", () => { + const ran = pickCritic({ FAKE_AGY_USAGE: "none", FAKE_AGY_RUN: "ok" }); + assert.equal(ran.status, 0, ran.stderr); + const { head, prompt } = claudeCritic(ran.stdout); + assert.equal(head, "critic: claude opus effort high\nwhy: agy gemini-test-model gave no quota reading"); + assert.match(prompt, BRIEFED); + assert.equal(ran.calls.length, 1); + assert.ok(ran.calls[0].argv.includes("/usage")); +}); + +for (const [run, said] of [ + ["fail", "agy gemini-test-model failed: exit 1: something broke"], + ["error", "agy gemini-test-model failed: status ERROR (conversation conv-test)"], + ["empty", "agy gemini-test-model answered nothing (status SUCCESS, conversation conv-test)"], + ["pointer", "agy gemini-test-model answered only with a pointer to implementation_plan.md (conversation conv-test)"], + ["noread", "agy gemini-test-model read no file, so it saw no draft (conversation conv-test)"], + ["timeout", "agy gemini-test-model was cut at 15 minutes"], +]) { + test(`a Gemini critic run that ends with "${run}" names Opus at high as the fallback, with the brief Gemini got`, () => { + const ran = pickCritic({ FAKE_AGY_5H: "0.9", FAKE_AGY_WEEKLY: "0.9", FAKE_AGY_RUN: run }); + assert.equal(ran.status, 0, ran.stderr); + const { head, prompt } = claudeCritic(ran.stdout); + assert.equal(head, `critic: claude opus effort high\nwhy: ${said}`); + assert.equal(ranCritic(ran.calls), true); + assert.match(prompt, BRIEFED); + const gemini = ran.calls.find((call) => !call.argv.includes("/usage")).argv; + const critic = prompt.slice(0, prompt.indexOf("\n\nThe draft:")); + assert.ok(gemini[gemini.indexOf("-p") + 1].startsWith(critic), "the Claude critic gets the brief Gemini got"); + }); +} diff --git a/ui/tests/delegate-fixtures.mjs b/ui/tests/delegate-fixtures.mjs new file mode 100644 index 00000000..004c37ed --- /dev/null +++ b/ui/tests/delegate-fixtures.mjs @@ -0,0 +1,288 @@ +// The stand-ins and scratch checkouts the `delegate-*.test.mjs` files share: `node scripts/agents/delegate.mjs`, run as +// the orchestrator runs it, with stand-in programs first on the PATH. Not a test file itself. +import assert from "node:assert/strict"; +import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, writeFileSync } from "node:fs"; +import { execFileSync, spawnSync } from "node:child_process"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; + +export const script = join(import.meta.dirname, "../../scripts/agents/delegate.mjs"); + +// The stand-in `agy`. `/usage` reports FAKE_AGY_5H and FAKE_AGY_WEEKLY as the Gemini windows left, or fails +// with no output when FAKE_AGY_USAGE is "none". A critic run reads the draft through the hook the script wrote (unless +// FAKE_AGY_RUN is "noread"), then answers as FAKE_AGY_RUN says: "ok", "none" (no findings), "error" (status ERROR), +// "empty" (status SUCCESS and no answer, how a run ended on a denied command, #618), "pointer" (an answer that only +// points at a plan file, #618), "fail" (exit 1) or "timeout" (exit 3, how `--print-timeout` ends). Every call is logged. +const fakeAgy = `#!/usr/bin/env node +const { execSync } = require("node:child_process"); +const { appendFileSync, existsSync, readFileSync } = require("node:fs"); +const { join } = require("node:path"); +const env = process.env; +const call = { argv: process.argv.slice(2), cwd: process.cwd(), internal: env.PLOTKEEPER_INTERNAL }; +appendFileSync(join(env.FAKE_AGY_DIR, "agy-calls.jsonl"), JSON.stringify(call) + "\\n"); +if (process.argv.includes("/usage")) { + if (env.FAKE_AGY_USAGE === "none") process.exit(1); + const bucket = (window, remaining_fraction) => ({ window, remaining_fraction }); + const buckets = [bucket("weekly", Number(env.FAKE_AGY_WEEKLY)), bucket("5h", Number(env.FAKE_AGY_5H))]; + console.log(JSON.stringify({ command: { data: { groups: [{ name: "Gemini Models", buckets }] } } })); + process.exit(0); +} +const run = env.FAKE_AGY_RUN; +const seen = { draft: null, worktree: existsSync("repo/.git"), tree: readFileSync("review/tree.txt", "utf8") }; +if (run !== "noread") { + const command = JSON.parse(readFileSync(".agents/hooks.json", "utf8")).readonly.PreToolUse[0].hooks[0].command; + const path = join(process.cwd(), "review/draft.md"); + const decided = JSON.parse(execSync(command, { input: JSON.stringify({ cwd: process.cwd(), toolCall: { name: "read_file", args: { Path: path } } }) })); + if (decided.decision === "allow") seen.draft = readFileSync(path, "utf8"); +} +appendFileSync(join(env.FAKE_AGY_DIR, "agy-seen.jsonl"), JSON.stringify(seen) + "\\n"); +if (run === "fail") { console.error("something broke"); process.exit(1); } +if (run === "timeout") process.exit(3); +const conversation_id = "conv-test"; +const answer = (rest) => { console.log(JSON.stringify({ conversation_id, status: "SUCCESS", ...rest })); process.exit(0); }; +if (run === "error") { console.log(JSON.stringify({ conversation_id, status: "ERROR", error: "no" })); process.exit(0); } +if (run === "empty") answer({ response: "" }); +if (run === "pointer") answer({ response: "I have created the implementation plan in [implementation_plan.md](file:///home/me/.gemini/antigravity-cli/brain/conv-test/implementation_plan.md). Please review and let me know if you'd like me to proceed." }); +if (run === "none") answer({ response: "", structured_output: { findings: [] } }); +const finding = { severity: "high", claim: "The store reads src/store.rs:7", status: "contradiction", evidence: "src/store.rs:1", summary: "The file has one line." }; +answer({ response: "", structured_output: { findings: [finding] } }); +`; + +const routing = { + strong: [{ cli: "claude", model: "opus" }], + medium: [{ cli: "claude", model: "sonnet" }], + cheap: [], + critic: [ + { cli: "agy", model: "gemini-test-model" }, + { cli: "claude", model: "opus", effort: "high" }, + ], +}; + +/** Runs `pick critic`, from a git repository's root, on a draft (a spec, or with `kind` "breakdown" a breakdown) with the fake `agy` set by `fake`; returns its output, agy's calls and what it saw. */ +export const pickCritic = (fake, kind = "spec") => { + const dir = realpathSync(mkdtempSync(join(tmpdir(), "delegate-test-"))); + const repo = join(dir, "repo"); + mkdirSync(join(dir, "bin")); + mkdirSync(join(repo, "src"), { recursive: true }); + writeFileSync(join(dir, "bin/agy"), fakeAgy); + chmodSync(join(dir, "bin/agy"), 0o755); + writeFileSync(join(dir, "routing.json"), JSON.stringify(routing)); + writeFileSync(join(dir, "draft.md"), "# A draft\n\nThe store reads `src/store.rs:7`.\n"); + const gitEnv = { GIT_CONFIG_GLOBAL: "/dev/null", GIT_CONFIG_NOSYSTEM: "1", GIT_AUTHOR_NAME: "t", GIT_AUTHOR_EMAIL: "t@t", GIT_COMMITTER_NAME: "t", GIT_COMMITTER_EMAIL: "t@t" }; + const git = (...args) => execFileSync("git", args, { cwd: repo, env: { ...process.env, ...gitEnv }, stdio: "ignore" }); + writeFileSync(join(repo, "src/store.rs"), "fn main() {}\n"); + git("init", "--quiet"); + git("add", "."); + git("commit", "--quiet", "-m", "one"); + const env = { ...process.env, ...gitEnv, PATH: `${join(dir, "bin")}:${process.env.PATH}`, TMPDIR: dir, FAKE_AGY_DIR: dir, ...fake }; + const args = [script, "pick", "critic", `--${kind}`, join(dir, "draft.md"), "--routing", join(dir, "routing.json")]; + const ran = spawnSync(process.execPath, args, { cwd: repo, env, encoding: "utf8" }); + const lines = (name) => (existsSync(join(dir, name)) ? readFileSync(join(dir, name), "utf8").trim().split("\n").map((line) => JSON.parse(line)) : []); + const worktrees = execFileSync("git", ["worktree", "list", "--porcelain"], { cwd: repo, encoding: "utf8" }); + return { ...ran, calls: lines("agy-calls.jsonl"), seen: lines("agy-seen.jsonl"), repo, dir, worktrees }; +}; + +// `delegate.mjs run`, in a scratch main checkout with a bare origin and stand-ins for `opencode`, `npm`, `gh` and +// `herdr` first on the PATH. These tests run none of the real ones. + +// The stand-in worker. FAKE_OPENCODE says what it does: "edit" (changes a file and exits 0), "commit" (also commits +// it, twice), "moved" (edits, and someone else moves the integration branch), "conflict" (edits a line someone else +// also changes on the integration branch), "pull" (someone else moves the integration branch, the worker pulls it, then +// edits), "pullmoved" (as "pull", then someone else changes the pulled file again), "linger" (edits and exits 0, leaving a \`sleep\` that holds its stdout and writes its pid to sleeper.pid), "pushint" (edits, commits and pushes its commit to the integration branch), "lost" (edits, and origin goes away), "empty" (exits 0 with no change), "fail" (exits 1), "chatty" (prints an event +// every 50 ms and never ends), "push" (edits, commits and pushes its commit to a branch of its own), "branch" (edits and +// pushes the integration tip as \`issue-7-cheap\`, no commit of its own), "escape" (edits, and also writes escaped.txt into +// the main checkout \`repo\`), "pushescape" (as "push", and also writes escaped.txt into \`repo\`) or "silent" (prints nothing and waits). FAKE_SILENT_MODELS, a comma-separated list, makes those models "silent" whatever FAKE_OPENCODE says; +// a silent worker leaves a stray file first. Every worker call is logged with the environment it got. \`models\` +// (v2.4: no provider argument, which it refuses as the real one does) lists FAKE_MODELS, a comma-separated list, or the test models by default, and is not logged. Like \`opencode run\` +// without \`--dir\` (1.19.6: \`process.env.PWD??process.cwd()\`), it works in PWD's folder, not in the cwd it was given. +const fakeOpencode = `#!/usr/bin/env node +const { execFileSync, spawn } = require("node:child_process"); +const { appendFileSync, writeFileSync } = require("node:fs"); +const { join } = require("node:path"); +const env = process.env; +if (process.argv[2] === "models") { + if (process.argv[3]) { + console.error('Unexpected positional argument: "' + process.argv[3] + '"'); + process.exit(1); + } + console.log((env.FAKE_MODELS ?? "opencode/test-free,opencode/a-free,opencode/b-free").split(",").join("\\n")); + process.exit(0); +} +process.chdir(env.PWD ?? process.cwd()); +const seen = Object.fromEntries(Object.entries(env).filter(([key]) => key.startsWith("OPENCODE_") || key === "PLOTKEEPER_INTERNAL")); +appendFileSync(join(env.FAKE_DIR, "opencode-calls.jsonl"), JSON.stringify({ argv: process.argv.slice(2), cwd: process.cwd(), env: seen }) + "\\n"); +const model = process.argv[process.argv.indexOf("-m") + 1].split("#")[0]; +const mode = (env.FAKE_SILENT_MODELS ?? "").split(",").includes(model) ? "silent" : env.FAKE_OPENCODE; +const event = (type, part) => console.log(JSON.stringify({ type, timestamp: 1, sessionID: "ses_test", part: { sessionID: "ses_test", ...part } })); +const other = (file, text) => { + const git = (...args) => execFileSync("git", args, { cwd: join(env.FAKE_DIR, "other"), stdio: "ignore" }); + git("pull", "--quiet", "origin", "int"); + writeFileSync(join(env.FAKE_DIR, "other", file), text); + git("add", "--all"); + git("commit", "--quiet", "-m", "someone else"); + git("push", "--quiet", "origin", "HEAD:int"); +}; +if (mode === "chatty") setInterval(() => event("text", { type: "text", text: "still going" }), 50); +else if (mode === "silent") { + writeFileSync("stray.txt", "left by a silent worker\\n"); + setTimeout(() => {}, 60000); +} +else { + event("step_start", { type: "step-start" }); + event("tool_use", { type: "tool", tool: "read", state: { status: "completed", input: { filePath: join(process.cwd(), "AGENTS.md") }, output: "long" } }); + if (mode === "pull" || mode === "pullmoved") { + other("other.txt", "someone else's file\\n"); + execFileSync("git", ["pull", "--quiet", "--no-rebase", "--no-edit", "origin", "int"]); + } + if (["edit", "unignore", "commit", "moved", "conflict", "lost", "push", "pushint", "branch", "pull", "pullmoved", "linger", "escape", "pushescape"].includes(mode)) { + writeFileSync("shared.txt", "the worker's line\\n"); + event("tool_use", { type: "tool", tool: "edit", state: { status: "completed", input: { filePath: "shared.txt" }, output: "ok" } }); + } + if (mode === "commit") { + execFileSync("git", ["commit", "--quiet", "-am", "worker one"]); + writeFileSync("added.txt", "more\\n"); + execFileSync("git", ["add", "added.txt"]); + execFileSync("git", ["commit", "--quiet", "-m", "worker two"]); + } + if (mode === "push" || mode === "pushescape") { + execFileSync("git", ["commit", "--quiet", "-am", "worker"]); + execFileSync("git", ["push", "--quiet", "origin", "HEAD:refs/heads/sneaky"]); + } + if (mode === "pushint") { + execFileSync("git", ["commit", "--quiet", "-am", "worker"]); + execFileSync("git", ["push", "--quiet", "origin", "HEAD:int"]); + } + if (mode === "linger") { + const sleeper = spawn("sleep", ["30"], { stdio: ["ignore", "inherit", "ignore"] }); + writeFileSync(join(env.FAKE_DIR, "sleeper.pid"), String(sleeper.pid)); + sleeper.unref(); + } + if (mode === "escape" || mode === "pushescape") writeFileSync(join(env.FAKE_DIR, "repo", "escaped.txt"), "written outside the worktree\\n"); + if (mode === "branch") execFileSync("git", ["push", "--quiet", "origin", "origin/int:refs/heads/issue-7-cheap"]); + if (mode === "pullmoved") other("other.txt", "someone else's file, changed again\\n"); + if (mode === "moved") other("other.txt", "someone else's file\\n"); + if (mode === "conflict") other("shared.txt", "someone else's line\\n"); + if (mode === "unignore") writeFileSync(".gitignore", ""); + if (mode === "lost") require("node:fs").renameSync(join(env.FAKE_DIR, "origin.git"), join(env.FAKE_DIR, "origin-gone.git")); + event("text", { type: "text", text: "Done: the ticket is implemented." }); + event("step_finish", { type: "step-finish", reason: "stop" }); + if (mode === "fail") process.exit(1); +} +`; + +// The stand-in npm: \`ci\` does nothing, \`run check\` passes unless FAKE_NPM_CHECK is "red", or "red-once" and this +// is the first check. Every call is logged. +const fakeNpm = `#!/usr/bin/env node +const { appendFileSync, existsSync, readFileSync } = require("node:fs"); +const { join } = require("node:path"); +const env = process.env; +const log = join(env.FAKE_DIR, "npm-calls.jsonl"); +const checks = existsSync(log) ? readFileSync(log, "utf8").split("\\n").filter((line) => line.includes('"check"')).length : 0; +appendFileSync(log, JSON.stringify({ argv: process.argv.slice(2), cwd: process.cwd(), internal: env.PLOTKEEPER_INTERNAL }) + "\\n"); +const red = env.FAKE_NPM_CHECK === "red" || (env.FAKE_NPM_CHECK === "red-once" && checks === 0); +if (process.argv[2] === "run" && process.argv[3] === "check" && red) { + console.log("test agents::reads ... FAILED"); + process.exit(1); +} +`; + +// The stand-in gh: \`issue view --json title,body\` prints \`issues/.json\`; \`pr list\` prints FAKE_GH_PRS, no PR +// by default. Every call is logged. +const fakeGh = `#!/usr/bin/env node +const { appendFileSync, readFileSync } = require("node:fs"); +const { join } = require("node:path"); +const argv = process.argv.slice(2); +appendFileSync(join(process.env.FAKE_DIR, "gh-calls.jsonl"), JSON.stringify({ argv }) + "\\n"); +const [noun, verb, number] = argv; +if (noun === "pr" && verb === "list") { + console.log(process.env.FAKE_GH_PRS || "[]"); + process.exit(0); +} +if (noun !== "issue" || verb !== "view") process.exit(1); +process.stdout.write(readFileSync(join(process.env.FAKE_DIR, "issues", number + ".json"), "utf8")); +`; + +// The stand-in herdr. \`tab list\` gives FAKE_HERDR_TABS, \`pane list\` FAKE_HERDR_PANES; \`tab create\` makes tab w1:t9 +// with root pane w1:p9, \`pane split\` makes pane w1:p8. Every call is logged. +const fakeHerdr = `#!/usr/bin/env node +const { appendFileSync } = require("node:fs"); +const { join } = require("node:path"); +const env = process.env; +const argv = process.argv.slice(2); +appendFileSync(join(env.FAKE_DIR, "herdr-calls.jsonl"), JSON.stringify({ argv }) + "\\n"); +const command = argv.slice(0, 2).join(" "); +const result = + command === "tab list" ? { tabs: JSON.parse(env.FAKE_HERDR_TABS || "[]") } + : command === "pane list" ? { panes: JSON.parse(env.FAKE_HERDR_PANES || "[]") } + : command === "tab create" ? { tab: { tab_id: "w1:t9", label: "workers" }, root_pane: { pane_id: "w1:p9", tab_id: "w1:t9" } } + : command === "pane split" ? { pane: { pane_id: "w1:p8", tab_id: "w1:t2" } } + : {}; +console.log(JSON.stringify({ id: "1", result })); +`; + +const ticket = { title: "Workflow: the thing", body: "## Parent\n\n#5\n\n## What to build\n\nThe thing.\n" }; +const spec = { title: "Spec: things", body: "## Problem Statement\n\nNo things.\n" }; + +/** + * A main checkout `repo` whose origin has the integration branch `int`, and a second clone `other` of it. + * @param {{ cheap?: object[] }} [options] the `cheap` list of the routing file, one test candidate by default + */ +export const scratchRun = ({ cheap } = {}) => { + const dir = realpathSync(mkdtempSync(join(tmpdir(), "delegate-run-test-"))); + const repo = join(dir, "repo"); + for (const folder of ["bin", "issues", "repo"]) mkdirSync(join(dir, folder)); + for (const [name, text] of Object.entries({ opencode: fakeOpencode, npm: fakeNpm, gh: fakeGh, herdr: fakeHerdr })) { + writeFileSync(join(dir, "bin", name), text); + chmodSync(join(dir, "bin", name), 0o755); + } + writeFileSync(join(dir, "issues/7.json"), JSON.stringify(ticket)); + writeFileSync(join(dir, "issues/5.json"), JSON.stringify(spec)); + const candidates = cheap ?? [{ cli: "opencode", model: "opencode/test-free", variant: { medium: null, high: "high" } }]; + writeFileSync(join(dir, "routing.json"), JSON.stringify({ ...routing, cheap: candidates })); + writeFileSync(join(dir, "gitconfig"), "[user]\n\tname = t\n\temail = t@example.com\n[commit]\n\tgpgsign = false\n"); + const env = { + ...process.env, + PATH: `${join(dir, "bin")}:${process.env.PATH}`, + GIT_CONFIG_GLOBAL: join(dir, "gitconfig"), + GIT_CONFIG_NOSYSTEM: "1", + PLOTKEEPER_INTERNAL: "1", + FAKE_DIR: dir, + // The run is launched from \`repo\` by a shell, which sets PWD to it. + PWD: repo, + }; + for (const key of ["HERDR_ENV", "HERDR_WORKSPACE_ID", "HERDR_TAB_ID", "HERDR_PANE_ID"]) delete env[key]; + const git = (...args) => execFileSync("git", args, { cwd: repo, env, encoding: "utf8" }).trim(); + git("init", "--quiet", "--initial-branch=main"); + writeFileSync(join(repo, "shared.txt"), "the first line\n"); + // As the repository's own `.gitignore` does (#662). + writeFileSync(join(repo, ".gitignore"), ".delegate/\n"); + git("add", "-A"); + git("commit", "--quiet", "-m", "base"); + git("clone", "--quiet", "--bare", ".", join(dir, "origin.git")); + git("remote", "add", "origin", join(dir, "origin.git")); + git("push", "--quiet", "origin", "main:int"); + git("clone", "--quiet", "--branch", "int", join(dir, "origin.git"), join(dir, "other")); + const run = (fake = {}, more = []) => { + const args = [script, "run", "--ticket", "7", "--integration", "int", "--effort", "medium", "--routing", join(dir, "routing.json"), ...more]; + const ran = spawnSync(process.execPath, args, { cwd: repo, env: { ...env, ...fake }, encoding: "utf8" }); + const calls = (name) => { + const log = join(dir, `${name}-calls.jsonl`); + return existsSync(log) ? readFileSync(log, "utf8").trim().split("\n").map((line) => JSON.parse(line)) : []; + }; + return { ...ran, calls }; + }; + const worktree = join(repo, ".claude/worktrees/issue-7-cheap"); + return { dir, repo, git, run, worktree }; +}; + +/** The commit bodies on `branch` that are not on the integration branch, merges left out. */ +export const commitsOn = (git, branch) => + git("log", "--no-merges", "--format=%B%x00", `origin/int..${branch}`) + .split("\0") + .map((body) => body.trim()) + .filter(Boolean); + +export const gone = ({ git, worktree }) => { + assert.equal(existsSync(worktree), false, "the worktree is removed"); + assert.equal(git("branch", "--list", "issue-7-cheap"), "", "the branch is removed"); +}; diff --git a/ui/tests/delegate-run-candidates.test.mjs b/ui/tests/delegate-run-candidates.test.mjs new file mode 100644 index 00000000..172b3df0 --- /dev/null +++ b/ui/tests/delegate-run-candidates.test.mjs @@ -0,0 +1,116 @@ +// `delegate.mjs run`'s cheap candidates: which models it starts, the silent ones it marks out, a process a worker +// leaves holding its output, and a run that could not start. Stand-ins for `opencode`, `npm`, `gh` and `herdr` are first on the PATH. Run: `npm test`. +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { existsSync, mkdirSync, readFileSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; +import { join } from "node:path"; +import { gone, scratchRun } from "./delegate-fixtures.mjs"; + +const two = [ + { cli: "opencode", model: "opencode/a-free", variant: { medium: null, high: "high" } }, + { cli: "opencode", model: "opencode/b-free", variant: { medium: "medium", high: "high" } }, +]; + +// A silence limit long enough that a worker that does answer is never killed while Node starts it, even on a loaded +// machine: at 300 ms the healthy candidate was once killed as silent too. +const HEALTHY_SILENCE_MS = "2000"; + +const models = (calls) => calls.map((call) => call.argv[call.argv.indexOf("-m") + 1].split("#")[0]); + +test("run: a silent worker is killed and marked out, and the next candidate runs in the reset worktree", () => { + const { repo, run, worktree } = scratchRun({ cheap: two }); + const ran = run({ FAKE_OPENCODE: "edit", FAKE_SILENT_MODELS: "opencode/a-free", DELEGATE_SILENCE_MS: HEALTHY_SILENCE_MS }); + assert.equal(ran.status, 0, ran.stderr); + const lines = ran.stdout.trimEnd().split("\n"); + assert.equal(lines[0], "pass"); + assert.match(lines.at(-1), /^Route outcome: cheap·medium opencode\/a-free → silent → opencode\/b-free → pass \| \d+m; \d+m$/); + assert.deepEqual(models(ran.calls("opencode")), ["opencode/a-free", "opencode/b-free"]); + assert.equal(existsSync(join(worktree, "stray.txt")), false, "the silent worker's file is cleaned away"); + assert.equal(readFileSync(join(worktree, "shared.txt"), "utf8"), "the worker's line\n"); + const out = JSON.parse(readFileSync(join(repo, ".git/delegate-silent.json"), "utf8")); + const midnight = new Date(); + midnight.setUTCHours(24, 0, 0, 0); + assert.deepEqual(out, { "opencode/a-free": midnight.toISOString() }); +}); + +test("run: a model marked out today is skipped by the next run, and with none left the run escalates as silent", () => { + const scratch = scratchRun({ cheap: two }); + scratch.run({ FAKE_OPENCODE: "edit", FAKE_SILENT_MODELS: "opencode/a-free", DELEGATE_SILENCE_MS: HEALTHY_SILENCE_MS }); + const second = scratch.run({ FAKE_OPENCODE: "edit", FAKE_SILENT_MODELS: "opencode/b-free", DELEGATE_SILENCE_MS: "300" }); + assert.equal(second.status, 0, second.stderr); + assert.deepEqual(models(second.calls("opencode")), ["opencode/a-free", "opencode/b-free", "opencode/b-free"], "the second run skips a-free"); + const lines = second.stdout.trimEnd().split("\n"); + assert.equal(lines[0], "escalate medium (silent)"); + assert.match(lines.at(-1), /^Route outcome: cheap·medium opencode\/b-free → silent \| \d+m$/); + gone(scratch); + const third = scratch.run({ FAKE_OPENCODE: "edit" }); + assert.equal(third.stdout, "escalate medium (silent)\n"); + assert.equal(third.calls("opencode").length, 3, "no worker starts when every model is marked out"); + assert.equal(third.calls("npm").filter((call) => call.argv[0] === "ci").length, 2, "nor npm ci"); +}); + +test("run: a mark from an earlier UTC day has expired", () => { + const scratch = scratchRun({ cheap: two }); + writeFileSync(join(scratch.repo, ".git/delegate-silent.json"), JSON.stringify({ "opencode/a-free": "2020-01-02T00:00:00.000Z" })); + const ran = scratch.run({ FAKE_OPENCODE: "edit" }); + assert.deepEqual(models(ran.calls("opencode")), ["opencode/a-free"]); +}); + +/** A PATH with the stand-ins and node only, so that a stand-in removed from `bin` is missing, never the real one. */ +const bare = (dir) => { + mkdirSync(join(dir, "node-bin")); + symlinkSync(process.execPath, join(dir, "node-bin/node")); + return `${join(dir, "bin")}:${join(dir, "node-bin")}:/usr/bin:/bin`; +}; + +test("run: with opencode missing, the run could not start: exit 1, and no worktree or branch left", () => { + const scratch = scratchRun(); + rmSync(join(scratch.dir, "bin/opencode")); + const ran = scratch.run({ FAKE_OPENCODE: "edit", PATH: bare(scratch.dir) }); + assert.equal(ran.status, 1, ran.stderr); + assert.match(ran.stderr, /^could not start: opencode .*ENOENT/); + assert.equal(ran.stdout, ""); + gone(scratch); +}); + +test("run: with no cheap candidate in opencode's models, the run could not start: exit 1, and no worker or worktree", () => { + const scratch = scratchRun({ cheap: two }); + const ran = scratch.run({ FAKE_OPENCODE: "edit", FAKE_MODELS: "opencode/beam-free,opencode/big-pickle" }); + assert.equal(ran.status, 1, ran.stderr); + assert.equal(ran.stderr, "could not start: opencode serves none of the cheap models opencode/a-free, opencode/b-free\n"); + assert.equal(ran.stdout, ""); + assert.deepEqual(ran.calls("opencode"), []); + gone(scratch); +}); + +test("run: with one cheap candidate left in opencode's models, the run goes on with that one, not the first", () => { + const ran = scratchRun({ cheap: two }).run({ FAKE_OPENCODE: "edit", FAKE_MODELS: "opencode/b-free" }); + assert.equal(ran.status, 0, ran.stderr); + assert.match(ran.stdout, /^pass\n/); + assert.deepEqual(models(ran.calls("opencode")), ["opencode/b-free"], "the unserved a-free never runs"); +}); + +test("run: with the served candidates all marked out, it escalates as silent without starting a worker", () => { + const scratch = scratchRun({ cheap: two }); + writeFileSync(join(scratch.repo, ".git/delegate-silent.json"), JSON.stringify({ "opencode/b-free": "2999-01-01T00:00:00.000Z" })); + const ran = scratch.run({ FAKE_OPENCODE: "edit", FAKE_MODELS: "opencode/b-free" }); + assert.equal(ran.status, 0, ran.stderr); + assert.equal(ran.stdout, "escalate medium (silent)\n"); + assert.deepEqual(ran.calls("opencode"), []); +}); + +test("run: a worker that exits 0 while a process it started holds its output gives pass, and that process is killed", () => { + const scratch = scratchRun(); + const ran = scratch.run({ FAKE_OPENCODE: "linger", DELEGATE_SILENCE_MS: HEALTHY_SILENCE_MS }); + assert.equal(ran.status, 0, ran.stderr); + assert.match(ran.stdout, /^pass\n/); + const pid = Number(readFileSync(join(scratch.dir, "sleeper.pid"), "utf8")); + assert.throws(() => process.kill(pid, 0), { code: "ESRCH" }, "the sleeper is gone"); +}); + +test("run: with no cheap candidate, it escalates as silent without starting a worker", () => { + const ran = scratchRun({ cheap: [] }).run({ FAKE_OPENCODE: "edit" }); + assert.equal(ran.status, 0, ran.stderr); + assert.equal(ran.stdout, "escalate medium (silent)\n"); + assert.deepEqual(ran.calls("opencode"), []); +}); diff --git a/ui/tests/delegate-run-verdicts.test.mjs b/ui/tests/delegate-run-verdicts.test.mjs new file mode 100644 index 00000000..8f177d7e --- /dev/null +++ b/ui/tests/delegate-run-verdicts.test.mjs @@ -0,0 +1,91 @@ +// `delegate.mjs run`'s verdicts: escalate, the one retry, stop, and the Route outcome line. Stand-ins for `opencode`, +// `npm`, `gh` and `herdr` are first on the PATH. Run: `npm test`. +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { existsSync } from "node:fs"; +import { commitsOn, gone, script, scratchRun } from "./delegate-fixtures.mjs"; + +for (const [what, fake, reason, result] of [ + ["an empty change, twice", { FAKE_OPENCODE: "empty" }, "red: no change", "red,red"], + ["an error exit", { FAKE_OPENCODE: "fail" }, "exit 1", "error"], + ["a red check, twice", { FAKE_OPENCODE: "edit", FAKE_NPM_CHECK: "red" }, "red check", "red,red"], + ["a merge conflict", { FAKE_OPENCODE: "conflict" }, "conflict", "conflict"], + ["a worker silent past the limit", { FAKE_OPENCODE: "silent", DELEGATE_SILENCE_MS: "300" }, "silent", "silent"], + ["a worker past the attempt limit", { FAKE_OPENCODE: "chatty", DELEGATE_ATTEMPT_MS: "600" }, "timeout", "error"], +]) { + test(`run: ${what} gives escalate medium (${reason}) and removes the worktree and branch`, () => { + const scratch = scratchRun(); + const ran = scratch.run(fake); + assert.equal(ran.status, 0, ran.stderr); + const lines = ran.stdout.trimEnd().split("\n"); + assert.equal(lines[0], `escalate medium (${reason})`); + assert.match(lines.at(-1), new RegExp(`^Route outcome: cheap·medium opencode/test-free → ${result} \\| \\d+m(, \\d+m)*$`)); + gone(scratch); + }); +} + +test("run: a red check, then green after one retry on the same session with the check's tail, gives pass", () => { + const { git, run, worktree } = scratchRun(); + const ran = run({ FAKE_OPENCODE: "edit", FAKE_NPM_CHECK: "red-once" }); + assert.equal(ran.status, 0, ran.stderr); + const lines = ran.stdout.trimEnd().split("\n"); + assert.equal(lines[0], "pass"); + assert.match(lines.at(-1), /^Route outcome: cheap·medium opencode\/test-free → red,pass \| \d+m, \d+m$/); + const [first, retry, ...more] = ran.calls("opencode"); + assert.equal(more.length, 0, "one retry only"); + assert.equal(first.argv.includes("--session"), false); + assert.equal(retry.cwd, worktree); + assert.deepEqual(retry.argv.slice(0, 8), ["run", "--auto", "--format", "json", "-m", "opencode/test-free", "--session", "ses_test"]); + assert.match(retry.argv.at(-1), /test agents::reads \.\.\. FAILED/); + assert.equal(retry.env.OPENCODE_DISABLE_CLAUDE_CODE_PROMPT, "1"); + assert.deepEqual(ran.calls("npm").map((call) => call.argv.join(" ")), ["ci", "run check", "run check"]); + assert.deepEqual(commitsOn(git, "issue-7-cheap"), ["Workflow: the thing\n\nWorker: opencode/test-free"]); +}); + +test("run: an empty change is retried with the message that no change was made", () => { + const ran = scratchRun().run({ FAKE_OPENCODE: "empty" }); + const [, retry] = ran.calls("opencode"); + assert.ok(retry, "the empty change is retried"); + assert.match(retry.argv.at(-1), /no change was made/i); +}); + +for (const [what, fake, said] of /** @type {[string, Record, RegExp][]} */ ([ + ["a worker that pushed its commit", { FAKE_OPENCODE: "push" }, /^stop: origin\/sneaky has the worker's commit [0-9a-f]{12}$/], + ["a worker that pushed its commit to the integration branch", { FAKE_OPENCODE: "pushint" }, /^stop: origin\/int has the worker's commit [0-9a-f]{12}$/], + ["an issue--cheap branch on origin", { FAKE_OPENCODE: "branch" }, /^stop: origin has the branch issue-7-cheap$/], + ["a worker that pushed and wrote outside its worktree", { FAKE_OPENCODE: "pushescape" }, /^stop: origin\/sneaky has the worker's commit [0-9a-f]{12}; worker wrote outside its worktree \(escaped\.txt\)$/], + ["an open PR from issue--cheap", { FAKE_OPENCODE: "edit", FAKE_GH_PRS: JSON.stringify([{ url: "https://github.com/o/r/pull/9" }]) }, /^stop: a PR from issue-7-cheap is open: https:\/\/github\.com\/o\/r\/pull\/9$/], +])) { + test(`run: ${what} gives stop, exit 0, and leaves the worktree for Daniel`, () => { + const { run, worktree } = scratchRun(); + const ran = run(fake); + assert.equal(ran.status, 0, ran.stderr); + const lines = ran.stdout.trimEnd().split("\n"); + assert.match(lines[0], said); + assert.match(lines.at(-1), /^Route outcome: cheap·medium opencode\/test-free → stop \| \d+m$/); + assert.ok(existsSync(worktree), "the worktree is kept as evidence"); + assert.deepEqual(ran.calls("npm").map((call) => call.argv.join(" ")), ["ci"], "no check runs once the worker pushed"); + }); +} + +test("outcomeSegment writes each attempt's worker and results, and one time per worker run", async () => { + const { outcomeSegment } = await import(script); + const run = (result, minutes) => ({ result, ms: minutes * 60_000 }); + assert.equal(outcomeSegment({ tier: "cheap", effort: "high", attempts: [{ worker: "opencode/beam-free", runs: [run("red", 9.6)] }] }), "cheap·high opencode/beam-free → red | 10m"); + assert.equal(outcomeSegment({ tier: "cheap", effort: "medium", attempts: [{ worker: "opencode/beam-free", runs: [{ result: "pass", ms: 5_000 }] }] }), "cheap·medium opencode/beam-free → pass | 1m"); + const attempts = [ + { worker: "opencode/deepseek-v4.1-flash-free", runs: [run("silent", 10)] }, + { worker: "opencode/beam-free", runs: [run("red", 14), run("red", 6)] }, + ]; + assert.equal(outcomeSegment({ tier: "cheap", effort: "medium", attempts }), "cheap·medium opencode/deepseek-v4.1-flash-free → silent → opencode/beam-free → red,red | 10m; 14m, 6m"); +}); + +test("run: a failure after the worker ran escalates with exit 0, not as a run that could not start", () => { + const scratch = scratchRun(); + const ran = scratch.run({ FAKE_OPENCODE: "lost" }); + assert.equal(ran.status, 0, ran.stderr); + const lines = ran.stdout.trimEnd().split("\n"); + assert.match(lines[0], /^escalate medium \(error: git fetch failed: .+\)$/); + assert.match(lines.at(-1), /^Route outcome: cheap·medium opencode\/test-free → error \| \d+m$/); + gone(scratch); +}); diff --git a/ui/tests/delegate-run-worktree.test.mjs b/ui/tests/delegate-run-worktree.test.mjs new file mode 100644 index 00000000..77c38d79 --- /dev/null +++ b/ui/tests/delegate-run-worktree.test.mjs @@ -0,0 +1,183 @@ +// `delegate.mjs run`'s worktree: the worker's commit, its brief and environment, the launching checkout, and Herdr's +// pane. Stand-ins for `opencode`, `npm`, `gh` and `herdr` are first on the PATH. Run: `npm test`. +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { execFileSync } from "node:child_process"; +import { existsSync, readFileSync, writeFileSync } from "node:fs"; +import { join } from "node:path"; +import { commitsOn, scratchRun } from "./delegate-fixtures.mjs"; + +test("run: a worker that edits and exits 0 with a green check gives pass and one commit with the Worker trailer", () => { + const { git, run, worktree } = scratchRun(); + const ran = run({ FAKE_OPENCODE: "edit" }); + assert.equal(ran.status, 0, ran.stderr); + const [verdict, ...rest] = ran.stdout.trimEnd().split("\n"); + assert.equal(verdict, "pass"); + assert.match(rest.join("\n"), /shared\.txt \| 2 \+-/); + assert.match(rest.at(-1), /^Route outcome: cheap·medium opencode\/test-free → pass \| \d+m$/); + const commits = git("log", "--format=%B%x00", "origin/int..issue-7-cheap").split("\0").map((body) => body.trim()).filter(Boolean); + assert.deepEqual(commits, ["Workflow: the thing\n\nWorker: opencode/test-free"]); + assert.equal(git("diff", "--name-only", "origin/int", "issue-7-cheap"), "shared.txt", "the gitignored .delegate/ is not committed"); + assert.equal(readFileSync(join(worktree, "shared.txt"), "utf8"), "the worker's line\n"); +}); + +test("run: a worker that drops .delegate/ from .gitignore still gets no .delegate/ committed", () => { + const { git, run } = scratchRun(); + const ran = run({ FAKE_OPENCODE: "unignore" }); + assert.equal(ran.status, 0, ran.stderr); + assert.match(ran.stdout, /^pass\n/); + assert.equal(git("diff", "--name-only", "origin/int", "issue-7-cheap"), ".gitignore\nshared.txt"); +}); + +test("run: on pass, the worker's own commits are squashed into the one commit, and the moved integration tip is merged in", () => { + const { git, run, worktree } = scratchRun(); + const ran = run({ FAKE_OPENCODE: "commit" }); + assert.equal(ran.status, 0, ran.stderr); + assert.match(ran.stdout, /^pass\n/); + assert.deepEqual(commitsOn(git, "issue-7-cheap"), ["Workflow: the thing\n\nWorker: opencode/test-free"]); + assert.equal(readFileSync(join(worktree, "added.txt"), "utf8"), "more\n"); + + const moved = scratchRun(); + const after = moved.run({ FAKE_OPENCODE: "moved" }); + assert.match(after.stdout, /^pass\n/); + moved.git("fetch", "--quiet", "origin"); + assert.doesNotThrow(() => moved.git("merge-base", "--is-ancestor", "origin/int", "issue-7-cheap")); + assert.deepEqual(commitsOn(moved.git, "issue-7-cheap"), ["Workflow: the thing\n\nWorker: opencode/test-free"]); + assert.doesNotMatch(after.stdout, /other\.txt/, "the diff stat shows only the worker's change"); +}); + +test("run: the worker runs in the worktree with the brief, the ticket and its spec, and no PLOTKEEPER_INTERNAL anywhere", () => { + const { run, worktree } = scratchRun(); + const ran = run({ FAKE_OPENCODE: "edit" }); + assert.equal(ran.status, 0, ran.stderr); + const [worker] = ran.calls("opencode"); + assert.equal(worker.cwd, worktree); + assert.deepEqual(worker.argv.slice(0, 6), ["run", "--auto", "--format", "json", "-m", "opencode/test-free"]); + assert.equal(worker.argv.length, 7, "effort medium maps to no variant for this model"); + assert.match(worker.argv[6], /Read \.delegate\/ticket\.md/); + assert.equal(readFileSync(join(worktree, ".delegate/brief.md"), "utf8").trim(), worker.argv[6]); + assert.deepEqual(worker.env, { + OPENCODE_EXPERIMENTAL_BASH_DEFAULT_TIMEOUT_MS: "480000", + OPENCODE_PERMISSION: JSON.stringify({ bash: { "*": "allow", "git push*": "deny", "gh *": "deny" } }), + OPENCODE_DISABLE_CLAUDE_CODE_PROMPT: "1", + OPENCODE_DISABLE_EXTERNAL_SKILLS: "1", + }); + const npm = ran.calls("npm"); + assert.deepEqual(npm.map((call) => call.argv.join(" ")), ["ci", "run check"]); + assert.ok(npm.every((call) => call.cwd === worktree && call.internal === undefined)); + const brief = readFileSync(join(worktree, ".delegate/ticket.md"), "utf8"); + assert.match(brief, /^# Workflow: the thing\n\n## Parent\n\n#5\n/); + assert.match(brief, /\n---\n\n# Parent spec: Spec: things\n\n## Problem Statement\n\nNo things\.\n$/); + assert.equal(readFileSync(join(worktree, ".delegate/run.log"), "utf8"), `> read {"filePath":"${worktree}/AGENTS.md"}\n> edit {"filePath":"shared.txt"}\nDone: the ticket is implemented.\n`); +}); + +test("run: effort high passes the candidate's variant for high on the model id, not as --variant", () => { + const { run } = scratchRun(); + const ran = run({ FAKE_OPENCODE: "edit" }, ["--effort", "high"]); + assert.equal(ran.status, 0, ran.stderr); + const [worker] = ran.calls("opencode"); + assert.equal(worker.argv[5], "opencode/test-free#high"); + assert.ok(!worker.argv.includes("--variant")); + assert.match(ran.stdout, /Route outcome: cheap·high opencode\/test-free → pass/); +}); + +test("run: a worker launched from the main checkout works in its own worktree and leaves the launching checkout untouched", () => { + const { git, run, worktree } = scratchRun(); + const ran = run({ FAKE_OPENCODE: "edit" }); + assert.equal(ran.status, 0, ran.stderr); + const [worker] = ran.calls("opencode"); + assert.equal(worker.cwd, worktree, "the worker works in its worktree, not in the folder delegate.mjs was launched from"); + assert.equal(git("status", "--porcelain", "--untracked-files=no"), "", "the launching checkout has no change"); + assert.equal(readFileSync(join(worktree, "shared.txt"), "utf8"), "the worker's line\n"); + assert.match(ran.stdout, /^pass\n/); +}); + +test("run: a worker that changes the launching checkout gives stop naming the paths, and stages nothing", () => { + const { git, run, worktree } = scratchRun(); + const ran = run({ FAKE_OPENCODE: "escape" }); + assert.equal(ran.status, 0, ran.stderr); + const lines = ran.stdout.trimEnd().split("\n"); + assert.equal(lines[0], "stop: worker wrote outside its worktree (escaped.txt)"); + assert.match(lines.at(-1), /^Route outcome: cheap·medium opencode\/test-free → stop \| \d+m$/); + assert.ok(existsSync(worktree), "the worktree is kept as evidence"); + assert.deepEqual(ran.calls("npm").map((call) => call.argv.join(" ")), ["ci"], "no check runs once the worker wrote outside"); + const wt = (...args) => execFileSync("git", args, { cwd: worktree, encoding: "utf8" }).trim(); + assert.equal(wt("diff", "--cached", "--name-only"), "", "nothing is staged"); + assert.equal(git("rev-parse", "issue-7-cheap"), git("rev-parse", "origin/int"), "nothing is committed"); +}); + +test("run: the guard asks gh for a PR from the ticket's branch, and a ref someone else moved gives no stop", () => { + const ran = scratchRun().run({ FAKE_OPENCODE: "moved" }); + assert.match(ran.stdout, /^pass\n/); + const pr = ran.calls("gh").find((call) => call.argv[0] === "pr"); + assert.ok(pr, "gh pr list was called"); + assert.deepEqual(pr.argv.slice(0, 4), ["pr", "list", "--head", "issue-7-cheap"]); +}); + +test("run: a worker that pulls the moved integration branch gives pass, not stop", () => { + const ran = scratchRun().run({ FAKE_OPENCODE: "pull" }); + assert.equal(ran.status, 0, ran.stderr); + assert.match(ran.stdout, /^pass\n/); +}); + +test("run: the worker's commit holds only its own change when it pulled the integration branch, which then moved again", () => { + const { git, run } = scratchRun(); + const ran = run({ FAKE_OPENCODE: "pullmoved" }); + assert.equal(ran.status, 0, ran.stderr); + assert.match(ran.stdout, /^pass\n/); + const [worker, ...more] = git("log", "--no-merges", "--format=%H", "origin/int..issue-7-cheap").split("\n").filter(Boolean); + assert.equal(more.length, 0, "one commit of the worker's"); + assert.equal(git("show", "--format=", "--name-only", worker), "shared.txt"); +}); + +test("run: a leftover issue--cheap worktree and branch are removed first", () => { + const scratch = scratchRun(); + const { git, run, worktree } = scratch; + git("worktree", "add", "--quiet", "-b", "issue-7-cheap", worktree, "main"); + writeFileSync(join(worktree, "leftover.txt"), "old\n"); + execFileSync("git", ["add", "leftover.txt"], { cwd: worktree }); + execFileSync("git", ["-c", "user.name=t", "-c", "user.email=t@example.com", "commit", "--quiet", "-m", "leftover"], { cwd: worktree }); + const ran = run({ FAKE_OPENCODE: "edit" }); + assert.equal(ran.status, 0, ran.stderr); + assert.match(ran.stdout, /^pass\n/); + assert.equal(existsSync(join(worktree, "leftover.txt")), false); + assert.deepEqual(commitsOn(git, "issue-7-cheap"), ["Workflow: the thing\n\nWorker: opencode/test-free"]); +}); + +test("run: outside Herdr, no pane is opened", () => { + const ran = scratchRun().run({ FAKE_OPENCODE: "edit" }); + assert.equal(ran.status, 0, ran.stderr); + assert.deepEqual(ran.calls("herdr"), []); +}); + +test("run: in Herdr, a new workers tab tails the log at the worktree, and only its pane is closed", () => { + const { run, worktree } = scratchRun(); + const ran = run({ FAKE_OPENCODE: "edit", HERDR_ENV: "1", HERDR_WORKSPACE_ID: "w1", FAKE_HERDR_TABS: JSON.stringify([{ tab_id: "w1:t1", label: "main" }]) }); + assert.equal(ran.status, 0, ran.stderr); + assert.deepEqual(ran.calls("herdr").map((call) => call.argv), [ + ["tab", "list", "--workspace", "w1"], + ["tab", "create", "--workspace", "w1", "--label", "workers", "--cwd", worktree, "--no-focus"], + ["pane", "run", "w1:p9", "tail -f .delegate/run.log"], + ["pane", "close", "w1:p9"], + ]); +}); + +test("run: in Herdr, an existing workers tab gets a split pane without focus, and only that pane is closed", () => { + const { run, worktree } = scratchRun(); + const ran = run({ + FAKE_OPENCODE: "fail", + HERDR_ENV: "1", + HERDR_WORKSPACE_ID: "w1", + FAKE_HERDR_TABS: JSON.stringify([{ tab_id: "w1:t1", label: "main" }, { tab_id: "w1:t2", label: "workers" }]), + FAKE_HERDR_PANES: JSON.stringify([{ pane_id: "w1:p1", tab_id: "w1:t1" }, { pane_id: "w1:p5", tab_id: "w1:t2" }]), + }); + assert.equal(ran.status, 0, ran.stderr); + assert.match(ran.stdout, /^escalate medium \(exit 1\)/); + const argv = ran.calls("herdr").map((call) => call.argv); + assert.deepEqual(argv.slice(2), [ + ["pane", "split", "w1:p5", "--direction", "down", "--cwd", worktree, "--no-focus"], + ["pane", "run", "w1:p8", "tail -f .delegate/run.log"], + ["pane", "close", "w1:p8"], + ]); + assert.equal(argv.filter(([, verb]) => verb === "close").length, 1); +}); diff --git a/ui/tests/delegate.test.mjs b/ui/tests/delegate.test.mjs deleted file mode 100644 index 3ea06640..00000000 --- a/ui/tests/delegate.test.mjs +++ /dev/null @@ -1,784 +0,0 @@ -// `node scripts/agents/delegate.mjs`, run as the orchestrator runs it, with a stand-in `agy` first on the PATH. -// These tests run no real `agy`. Run: `npm test`. -import { test } from "node:test"; -import assert from "node:assert/strict"; -import { execFileSync, spawnSync } from "node:child_process"; -import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; -import { tmpdir } from "node:os"; -import { join } from "node:path"; - -const script = join(import.meta.dirname, "../../scripts/agents/delegate.mjs"); - -// The stand-in `agy`. `/usage` reports FAKE_AGY_5H and FAKE_AGY_WEEKLY as the Gemini windows left, or fails -// with no output when FAKE_AGY_USAGE is "none". A critic run reads the draft through the hook the script wrote (unless -// FAKE_AGY_RUN is "noread"), then answers as FAKE_AGY_RUN says: "ok", "none" (no findings), "error" (status ERROR), -// "empty" (status SUCCESS and no answer, how a run ended on a denied command, #618), "pointer" (an answer that only -// points at a plan file, #618), "fail" (exit 1) or "timeout" (exit 3, how `--print-timeout` ends). Every call is logged. -const fakeAgy = `#!/usr/bin/env node -const { execSync } = require("node:child_process"); -const { appendFileSync, existsSync, readFileSync } = require("node:fs"); -const { join } = require("node:path"); -const env = process.env; -const call = { argv: process.argv.slice(2), cwd: process.cwd(), internal: env.PLOTKEEPER_INTERNAL }; -appendFileSync(join(env.FAKE_AGY_DIR, "agy-calls.jsonl"), JSON.stringify(call) + "\\n"); -if (process.argv.includes("/usage")) { - if (env.FAKE_AGY_USAGE === "none") process.exit(1); - const bucket = (window, remaining_fraction) => ({ window, remaining_fraction }); - const buckets = [bucket("weekly", Number(env.FAKE_AGY_WEEKLY)), bucket("5h", Number(env.FAKE_AGY_5H))]; - console.log(JSON.stringify({ command: { data: { groups: [{ name: "Gemini Models", buckets }] } } })); - process.exit(0); -} -const run = env.FAKE_AGY_RUN; -const seen = { draft: null, worktree: existsSync("repo/.git"), tree: readFileSync("review/tree.txt", "utf8") }; -if (run !== "noread") { - const command = JSON.parse(readFileSync(".agents/hooks.json", "utf8")).readonly.PreToolUse[0].hooks[0].command; - const path = join(process.cwd(), "review/draft.md"); - const decided = JSON.parse(execSync(command, { input: JSON.stringify({ cwd: process.cwd(), toolCall: { name: "read_file", args: { Path: path } } }) })); - if (decided.decision === "allow") seen.draft = readFileSync(path, "utf8"); -} -appendFileSync(join(env.FAKE_AGY_DIR, "agy-seen.jsonl"), JSON.stringify(seen) + "\\n"); -if (run === "fail") { console.error("something broke"); process.exit(1); } -if (run === "timeout") process.exit(3); -const conversation_id = "conv-test"; -const answer = (rest) => { console.log(JSON.stringify({ conversation_id, status: "SUCCESS", ...rest })); process.exit(0); }; -if (run === "error") { console.log(JSON.stringify({ conversation_id, status: "ERROR", error: "no" })); process.exit(0); } -if (run === "empty") answer({ response: "" }); -if (run === "pointer") answer({ response: "I have created the implementation plan in [implementation_plan.md](file:///home/me/.gemini/antigravity-cli/brain/conv-test/implementation_plan.md). Please review and let me know if you'd like me to proceed." }); -if (run === "none") answer({ response: "", structured_output: { findings: [] } }); -const finding = { severity: "high", claim: "The store reads src/store.rs:7", status: "contradiction", evidence: "src/store.rs:1", summary: "The file has one line." }; -answer({ response: "", structured_output: { findings: [finding] } }); -`; - -const routing = { - strong: [{ cli: "claude", model: "opus" }], - medium: [{ cli: "claude", model: "sonnet" }], - cheap: [], - critic: [ - { cli: "agy", model: "gemini-test-model" }, - { cli: "claude", model: "opus", effort: "high" }, - ], -}; - -/** Runs `pick critic`, from a git repository's root, on a draft (a spec, or with `kind` "breakdown" a breakdown) with the fake `agy` set by `fake`; returns its output, agy's calls and what it saw. */ -const pickCritic = (fake, kind = "spec") => { - const dir = realpathSync(mkdtempSync(join(tmpdir(), "delegate-test-"))); - const repo = join(dir, "repo"); - mkdirSync(join(dir, "bin")); - mkdirSync(join(repo, "src"), { recursive: true }); - writeFileSync(join(dir, "bin/agy"), fakeAgy); - chmodSync(join(dir, "bin/agy"), 0o755); - writeFileSync(join(dir, "routing.json"), JSON.stringify(routing)); - writeFileSync(join(dir, "draft.md"), "# A draft\n\nThe store reads `src/store.rs:7`.\n"); - const gitEnv = { GIT_CONFIG_GLOBAL: "/dev/null", GIT_CONFIG_NOSYSTEM: "1", GIT_AUTHOR_NAME: "t", GIT_AUTHOR_EMAIL: "t@t", GIT_COMMITTER_NAME: "t", GIT_COMMITTER_EMAIL: "t@t" }; - const git = (...args) => execFileSync("git", args, { cwd: repo, env: { ...process.env, ...gitEnv }, stdio: "ignore" }); - writeFileSync(join(repo, "src/store.rs"), "fn main() {}\n"); - git("init", "--quiet"); - git("add", "."); - git("commit", "--quiet", "-m", "one"); - const env = { ...process.env, ...gitEnv, PATH: `${join(dir, "bin")}:${process.env.PATH}`, TMPDIR: dir, FAKE_AGY_DIR: dir, ...fake }; - const args = [script, "pick", "critic", `--${kind}`, join(dir, "draft.md"), "--routing", join(dir, "routing.json")]; - const ran = spawnSync(process.execPath, args, { cwd: repo, env, encoding: "utf8" }); - const lines = (name) => (existsSync(join(dir, name)) ? readFileSync(join(dir, name), "utf8").trim().split("\n").map((line) => JSON.parse(line)) : []); - const worktrees = execFileSync("git", ["worktree", "list", "--porcelain"], { cwd: repo, encoding: "utf8" }); - return { ...ran, calls: lines("agy-calls.jsonl"), seen: lines("agy-seen.jsonl"), repo, dir, worktrees }; -}; - -test("with both Gemini windows at their floors, pick critic runs the Gemini critic read-only and prints its findings", () => { - const ran = pickCritic({ FAKE_AGY_5H: "0.5", FAKE_AGY_WEEKLY: "0.3", FAKE_AGY_RUN: "ok" }); - assert.equal(ran.status, 0, ran.stderr); - assert.equal( - ran.stdout, - "critic: agy gemini-test-model\n\n1. high, contradiction: The store reads src/store.rs:7\n Evidence: src/store.rs:1\n The file has one line.\n", - ); - const critic = ran.calls.find((call) => !call.argv.includes("/usage")); - assert.ok(critic, "agy -p was not called for the critic"); - const argv = critic.argv; - const after = (flag) => argv[argv.indexOf(flag) + 1]; - // Not plan mode, which ends the run at the first denied command (#618): the deny hook keeps it read-only. - assert.equal(argv.includes("--mode"), false); - assert.equal(after("--model"), "gemini-test-model"); - assert.equal(after("--print-timeout"), "15m"); - assert.equal(after("--output-format"), "json"); - assert.equal(after("--json-schema"), join(critic.cwd, "review/schema.json")); - assert.match(after("-p"), /check every claim/i); - assert.match(after("-p"), /Your only working tool is read_file/); - assert.equal(after("-p").includes("@"), false, "an at-sign may read a file past the hook"); - assert.notEqual(critic.cwd, ran.repo); - assert.equal(critic.internal, "1"); - // It read the draft through the hook, in a worktree of HEAD whose files tree.txt lists. - assert.deepEqual(ran.seen, [{ draft: "# A draft\n\nThe store reads `src/store.rs:7`.\n", worktree: true, tree: `${join(critic.cwd, "repo/src/store.rs")}\n` }]); - // And left no throwaway folder or worktree behind. - assert.equal(existsSync(critic.cwd), false); - assert.equal(ran.worktrees.match(/^worktree /gm).length, 1, ran.worktrees); -}); - -test("a Gemini critic run with no findings says so", () => { - const ran = pickCritic({ FAKE_AGY_5H: "0.9", FAKE_AGY_WEEKLY: "0.9", FAKE_AGY_RUN: "none" }); - assert.equal(ran.status, 0, ran.stderr); - assert.equal(ran.stdout, "critic: agy gemini-test-model\n\nNo findings.\n"); -}); - -// A breakdown's critic gets a brief of its own: the routing rules to hold the routes to, not only claims to check. -const BREAKDOWN = /^You are the critic of a draft ticket breakdown[\s\S]*Routing section of docs\/agents\/issue-tracker\.md[\s\S]*Risk isolation[\s\S]*CI[\s\S]*departs from the spec[\s\S]*Daniel/; - -test("pick critic --breakdown gives the Gemini critic and the Claude fallback the breakdown brief, then the breakdown", () => { - const gemini = pickCritic({ FAKE_AGY_5H: "0.9", FAKE_AGY_WEEKLY: "0.9", FAKE_AGY_RUN: "ok" }, "breakdown"); - assert.equal(gemini.status, 0, gemini.stderr); - const argv = gemini.calls.find((call) => !call.argv.includes("/usage")).argv; - const brief = argv[argv.indexOf("-p") + 1]; - assert.match(brief, BREAKDOWN); - assert.match(brief, /The breakdown, with its spec: \S+\/review\/draft\.md/); - assert.equal(gemini.seen[0].draft, "# A draft\n\nThe store reads `src/store.rs:7`.\n"); - const claude = pickCritic({ FAKE_AGY_5H: "0.49", FAKE_AGY_WEEKLY: "0.9" }, "breakdown"); - assert.equal(claude.status, 0, claude.stderr); - const { head, prompt } = claudeCritic(claude.stdout); - assert.match(head, /^critic: claude opus effort high\n/); - assert.match(prompt, BREAKDOWN); - assert.match(prompt, /\n\nThe breakdown, with its spec:\n\n# A draft\n\nThe store reads `src\/store\.rs:7`\.\n$/); - assert.ok(brief.startsWith(prompt.slice(0, prompt.indexOf("\n\nThe breakdown, with its spec:"))), "the Claude critic gets the brief Gemini got"); -}); - -for (const [what, args] of [ - ["neither --spec nor --breakdown", []], - ["both --spec and --breakdown", ["--spec", "a.md", "--breakdown", "b.md"]], -]) { - test(`pick critic with ${what} is a usage error`, () => { - const ran = spawnSync(process.execPath, [script, "pick", "critic", ...args], { encoding: "utf8" }); - assert.equal(ran.status, 2); - assert.match(ran.stderr, /one of --spec or --breakdown is required/); - }); -} - -const ranCritic = (calls) => calls.some((call) => !call.argv.includes("/usage")); - -/** Splits what `pick critic` printed for a Claude critic into its first lines and the prompt it printed after them. */ -const claudeCritic = (stdout) => { - const [head, ...rest] = stdout.split("\n\n"); - return { head, prompt: rest.join("\n\n") }; -}; - -// The prompt a Claude critic gets: the critic's brief, then the draft. -const BRIEFED = /^You are the critic of a draft spec[\s\S]*Check every claim[\s\S]*\n\nThe draft:\n\n# A draft\n\nThe store reads `src\/store\.rs:7`\.\n$/; - -test("with the 5-hour window below its floor, pick critic names Opus at high and prints its prompt, without running Gemini", () => { - const ran = pickCritic({ FAKE_AGY_5H: "0.49", FAKE_AGY_WEEKLY: "0.9", FAKE_AGY_RUN: "ok" }); - assert.equal(ran.status, 0, ran.stderr); - const { head, prompt } = claudeCritic(ran.stdout); - assert.equal(head, "critic: claude opus effort high\nwhy: agy gemini-test-model has 49% of its 5h window and 90% of its weekly window left, under its floors of 50% and 30%"); - assert.match(prompt, BRIEFED); - assert.equal(ranCritic(ran.calls), false); -}); - -test("with the weekly window below its floor, pick critic names Opus at high without running Gemini", () => { - const ran = pickCritic({ FAKE_AGY_5H: "0.9", FAKE_AGY_WEEKLY: "0.29", FAKE_AGY_RUN: "ok" }); - assert.equal(ran.status, 0, ran.stderr); - const { head, prompt } = claudeCritic(ran.stdout); - assert.equal(head, "critic: claude opus effort high\nwhy: agy gemini-test-model has 90% of its 5h window and 29% of its weekly window left, under its floors of 50% and 30%"); - assert.match(prompt, BRIEFED); - assert.equal(ranCritic(ran.calls), false); -}); - -test("with no quota reading, pick critic names Opus at high without running Gemini", () => { - const ran = pickCritic({ FAKE_AGY_USAGE: "none", FAKE_AGY_RUN: "ok" }); - assert.equal(ran.status, 0, ran.stderr); - const { head, prompt } = claudeCritic(ran.stdout); - assert.equal(head, "critic: claude opus effort high\nwhy: agy gemini-test-model gave no quota reading"); - assert.match(prompt, BRIEFED); - assert.equal(ran.calls.length, 1); - assert.ok(ran.calls[0].argv.includes("/usage")); -}); - -for (const [run, said] of [ - ["fail", "agy gemini-test-model failed: exit 1: something broke"], - ["error", "agy gemini-test-model failed: status ERROR (conversation conv-test)"], - ["empty", "agy gemini-test-model answered nothing (status SUCCESS, conversation conv-test)"], - ["pointer", "agy gemini-test-model answered only with a pointer to implementation_plan.md (conversation conv-test)"], - ["noread", "agy gemini-test-model read no file, so it saw no draft (conversation conv-test)"], - ["timeout", "agy gemini-test-model was cut at 15 minutes"], -]) { - test(`a Gemini critic run that ends with "${run}" names Opus at high as the fallback, with the brief Gemini got`, () => { - const ran = pickCritic({ FAKE_AGY_5H: "0.9", FAKE_AGY_WEEKLY: "0.9", FAKE_AGY_RUN: run }); - assert.equal(ran.status, 0, ran.stderr); - const { head, prompt } = claudeCritic(ran.stdout); - assert.equal(head, `critic: claude opus effort high\nwhy: ${said}`); - assert.equal(ranCritic(ran.calls), true); - assert.match(prompt, BRIEFED); - const gemini = ran.calls.find((call) => !call.argv.includes("/usage")).argv; - const critic = prompt.slice(0, prompt.indexOf("\n\nThe draft:")); - assert.ok(gemini[gemini.indexOf("-p") + 1].startsWith(critic), "the Claude critic gets the brief Gemini got"); - }); -} - -// `delegate.mjs run`, in a scratch main checkout with a bare origin and stand-ins for `opencode`, `npm`, `gh` and -// `herdr` first on the PATH. These tests run none of the real ones. - -// The stand-in worker. FAKE_OPENCODE says what it does: "edit" (changes a file and exits 0), "commit" (also commits -// it, twice), "moved" (edits, and someone else moves the integration branch), "conflict" (edits a line someone else -// also changes on the integration branch), "pull" (someone else moves the integration branch, the worker pulls it, then -// edits), "pullmoved" (as "pull", then someone else changes the pulled file again), "linger" (edits and exits 0, leaving a \`sleep\` that holds its stdout and writes its pid to sleeper.pid), "pushint" (edits, commits and pushes its commit to the integration branch), "lost" (edits, and origin goes away), "empty" (exits 0 with no change), "fail" (exits 1), "chatty" (prints an event -// every 50 ms and never ends), "push" (edits, commits and pushes its commit to a branch of its own), "branch" (edits and -// pushes the integration tip as \`issue-7-cheap\`, no commit of its own), "escape" (edits, and also writes escaped.txt into -// the main checkout \`repo\`), "pushescape" (as "push", and also writes escaped.txt into \`repo\`) or "silent" (prints nothing and waits). FAKE_SILENT_MODELS, a comma-separated list, makes those models "silent" whatever FAKE_OPENCODE says; -// a silent worker leaves a stray file first. Every worker call is logged with the environment it got. \`models\` -// (v2.4: no provider argument, which it refuses as the real one does) lists FAKE_MODELS, a comma-separated list, or the test models by default, and is not logged. Like \`opencode run\` -// without \`--dir\` (1.19.6: \`process.env.PWD??process.cwd()\`), it works in PWD's folder, not in the cwd it was given. -const fakeOpencode = `#!/usr/bin/env node -const { execFileSync, spawn } = require("node:child_process"); -const { appendFileSync, writeFileSync } = require("node:fs"); -const { join } = require("node:path"); -const env = process.env; -if (process.argv[2] === "models") { - if (process.argv[3]) { - console.error('Unexpected positional argument: "' + process.argv[3] + '"'); - process.exit(1); - } - console.log((env.FAKE_MODELS ?? "opencode/test-free,opencode/a-free,opencode/b-free").split(",").join("\\n")); - process.exit(0); -} -process.chdir(env.PWD ?? process.cwd()); -const seen = Object.fromEntries(Object.entries(env).filter(([key]) => key.startsWith("OPENCODE_") || key === "PLOTKEEPER_INTERNAL")); -appendFileSync(join(env.FAKE_DIR, "opencode-calls.jsonl"), JSON.stringify({ argv: process.argv.slice(2), cwd: process.cwd(), env: seen }) + "\\n"); -const model = process.argv[process.argv.indexOf("-m") + 1].split("#")[0]; -const mode = (env.FAKE_SILENT_MODELS ?? "").split(",").includes(model) ? "silent" : env.FAKE_OPENCODE; -const event = (type, part) => console.log(JSON.stringify({ type, timestamp: 1, sessionID: "ses_test", part: { sessionID: "ses_test", ...part } })); -const other = (file, text) => { - const git = (...args) => execFileSync("git", args, { cwd: join(env.FAKE_DIR, "other"), stdio: "ignore" }); - git("pull", "--quiet", "origin", "int"); - writeFileSync(join(env.FAKE_DIR, "other", file), text); - git("add", "--all"); - git("commit", "--quiet", "-m", "someone else"); - git("push", "--quiet", "origin", "HEAD:int"); -}; -if (mode === "chatty") setInterval(() => event("text", { type: "text", text: "still going" }), 50); -else if (mode === "silent") { - writeFileSync("stray.txt", "left by a silent worker\\n"); - setTimeout(() => {}, 60000); -} -else { - event("step_start", { type: "step-start" }); - event("tool_use", { type: "tool", tool: "read", state: { status: "completed", input: { filePath: join(process.cwd(), "AGENTS.md") }, output: "long" } }); - if (mode === "pull" || mode === "pullmoved") { - other("other.txt", "someone else's file\\n"); - execFileSync("git", ["pull", "--quiet", "--no-rebase", "--no-edit", "origin", "int"]); - } - if (["edit", "unignore", "commit", "moved", "conflict", "lost", "push", "pushint", "branch", "pull", "pullmoved", "linger", "escape", "pushescape"].includes(mode)) { - writeFileSync("shared.txt", "the worker's line\\n"); - event("tool_use", { type: "tool", tool: "edit", state: { status: "completed", input: { filePath: "shared.txt" }, output: "ok" } }); - } - if (mode === "commit") { - execFileSync("git", ["commit", "--quiet", "-am", "worker one"]); - writeFileSync("added.txt", "more\\n"); - execFileSync("git", ["add", "added.txt"]); - execFileSync("git", ["commit", "--quiet", "-m", "worker two"]); - } - if (mode === "push" || mode === "pushescape") { - execFileSync("git", ["commit", "--quiet", "-am", "worker"]); - execFileSync("git", ["push", "--quiet", "origin", "HEAD:refs/heads/sneaky"]); - } - if (mode === "pushint") { - execFileSync("git", ["commit", "--quiet", "-am", "worker"]); - execFileSync("git", ["push", "--quiet", "origin", "HEAD:int"]); - } - if (mode === "linger") { - const sleeper = spawn("sleep", ["30"], { stdio: ["ignore", "inherit", "ignore"] }); - writeFileSync(join(env.FAKE_DIR, "sleeper.pid"), String(sleeper.pid)); - sleeper.unref(); - } - if (mode === "escape" || mode === "pushescape") writeFileSync(join(env.FAKE_DIR, "repo", "escaped.txt"), "written outside the worktree\\n"); - if (mode === "branch") execFileSync("git", ["push", "--quiet", "origin", "origin/int:refs/heads/issue-7-cheap"]); - if (mode === "pullmoved") other("other.txt", "someone else's file, changed again\\n"); - if (mode === "moved") other("other.txt", "someone else's file\\n"); - if (mode === "conflict") other("shared.txt", "someone else's line\\n"); - if (mode === "unignore") writeFileSync(".gitignore", ""); - if (mode === "lost") require("node:fs").renameSync(join(env.FAKE_DIR, "origin.git"), join(env.FAKE_DIR, "origin-gone.git")); - event("text", { type: "text", text: "Done: the ticket is implemented." }); - event("step_finish", { type: "step-finish", reason: "stop" }); - if (mode === "fail") process.exit(1); -} -`; - -// The stand-in npm: \`ci\` does nothing, \`run check\` passes unless FAKE_NPM_CHECK is "red", or "red-once" and this -// is the first check. Every call is logged. -const fakeNpm = `#!/usr/bin/env node -const { appendFileSync, existsSync, readFileSync } = require("node:fs"); -const { join } = require("node:path"); -const env = process.env; -const log = join(env.FAKE_DIR, "npm-calls.jsonl"); -const checks = existsSync(log) ? readFileSync(log, "utf8").split("\\n").filter((line) => line.includes('"check"')).length : 0; -appendFileSync(log, JSON.stringify({ argv: process.argv.slice(2), cwd: process.cwd(), internal: env.PLOTKEEPER_INTERNAL }) + "\\n"); -const red = env.FAKE_NPM_CHECK === "red" || (env.FAKE_NPM_CHECK === "red-once" && checks === 0); -if (process.argv[2] === "run" && process.argv[3] === "check" && red) { - console.log("test agents::reads ... FAILED"); - process.exit(1); -} -`; - -// The stand-in gh: \`issue view --json title,body\` prints \`issues/.json\`; \`pr list\` prints FAKE_GH_PRS, no PR -// by default. Every call is logged. -const fakeGh = `#!/usr/bin/env node -const { appendFileSync, readFileSync } = require("node:fs"); -const { join } = require("node:path"); -const argv = process.argv.slice(2); -appendFileSync(join(process.env.FAKE_DIR, "gh-calls.jsonl"), JSON.stringify({ argv }) + "\\n"); -const [noun, verb, number] = argv; -if (noun === "pr" && verb === "list") { - console.log(process.env.FAKE_GH_PRS || "[]"); - process.exit(0); -} -if (noun !== "issue" || verb !== "view") process.exit(1); -process.stdout.write(readFileSync(join(process.env.FAKE_DIR, "issues", number + ".json"), "utf8")); -`; - -// The stand-in herdr. \`tab list\` gives FAKE_HERDR_TABS, \`pane list\` FAKE_HERDR_PANES; \`tab create\` makes tab w1:t9 -// with root pane w1:p9, \`pane split\` makes pane w1:p8. Every call is logged. -const fakeHerdr = `#!/usr/bin/env node -const { appendFileSync } = require("node:fs"); -const { join } = require("node:path"); -const env = process.env; -const argv = process.argv.slice(2); -appendFileSync(join(env.FAKE_DIR, "herdr-calls.jsonl"), JSON.stringify({ argv }) + "\\n"); -const command = argv.slice(0, 2).join(" "); -const result = - command === "tab list" ? { tabs: JSON.parse(env.FAKE_HERDR_TABS || "[]") } - : command === "pane list" ? { panes: JSON.parse(env.FAKE_HERDR_PANES || "[]") } - : command === "tab create" ? { tab: { tab_id: "w1:t9", label: "workers" }, root_pane: { pane_id: "w1:p9", tab_id: "w1:t9" } } - : command === "pane split" ? { pane: { pane_id: "w1:p8", tab_id: "w1:t2" } } - : {}; -console.log(JSON.stringify({ id: "1", result })); -`; - -const ticket = { title: "Workflow: the thing", body: "## Parent\n\n#5\n\n## What to build\n\nThe thing.\n" }; -const spec = { title: "Spec: things", body: "## Problem Statement\n\nNo things.\n" }; - -/** - * A main checkout `repo` whose origin has the integration branch `int`, and a second clone `other` of it. - * @param {{ cheap?: object[] }} [options] the `cheap` list of the routing file, one test candidate by default - */ -const scratchRun = ({ cheap } = {}) => { - const dir = realpathSync(mkdtempSync(join(tmpdir(), "delegate-run-test-"))); - const repo = join(dir, "repo"); - for (const folder of ["bin", "issues", "repo"]) mkdirSync(join(dir, folder)); - for (const [name, text] of Object.entries({ opencode: fakeOpencode, npm: fakeNpm, gh: fakeGh, herdr: fakeHerdr })) { - writeFileSync(join(dir, "bin", name), text); - chmodSync(join(dir, "bin", name), 0o755); - } - writeFileSync(join(dir, "issues/7.json"), JSON.stringify(ticket)); - writeFileSync(join(dir, "issues/5.json"), JSON.stringify(spec)); - const candidates = cheap ?? [{ cli: "opencode", model: "opencode/test-free", variant: { medium: null, high: "high" } }]; - writeFileSync(join(dir, "routing.json"), JSON.stringify({ ...routing, cheap: candidates })); - writeFileSync(join(dir, "gitconfig"), "[user]\n\tname = t\n\temail = t@example.com\n[commit]\n\tgpgsign = false\n"); - const env = { - ...process.env, - PATH: `${join(dir, "bin")}:${process.env.PATH}`, - GIT_CONFIG_GLOBAL: join(dir, "gitconfig"), - GIT_CONFIG_NOSYSTEM: "1", - PLOTKEEPER_INTERNAL: "1", - FAKE_DIR: dir, - // The run is launched from \`repo\` by a shell, which sets PWD to it. - PWD: repo, - }; - for (const key of ["HERDR_ENV", "HERDR_WORKSPACE_ID", "HERDR_TAB_ID", "HERDR_PANE_ID"]) delete env[key]; - const git = (...args) => execFileSync("git", args, { cwd: repo, env, encoding: "utf8" }).trim(); - git("init", "--quiet", "--initial-branch=main"); - writeFileSync(join(repo, "shared.txt"), "the first line\n"); - // As the repository's own `.gitignore` does (#662). - writeFileSync(join(repo, ".gitignore"), ".delegate/\n"); - git("add", "-A"); - git("commit", "--quiet", "-m", "base"); - git("clone", "--quiet", "--bare", ".", join(dir, "origin.git")); - git("remote", "add", "origin", join(dir, "origin.git")); - git("push", "--quiet", "origin", "main:int"); - git("clone", "--quiet", "--branch", "int", join(dir, "origin.git"), join(dir, "other")); - const run = (fake = {}, more = []) => { - const args = [script, "run", "--ticket", "7", "--integration", "int", "--effort", "medium", "--routing", join(dir, "routing.json"), ...more]; - const ran = spawnSync(process.execPath, args, { cwd: repo, env: { ...env, ...fake }, encoding: "utf8" }); - const calls = (name) => { - const log = join(dir, `${name}-calls.jsonl`); - return existsSync(log) ? readFileSync(log, "utf8").trim().split("\n").map((line) => JSON.parse(line)) : []; - }; - return { ...ran, calls }; - }; - const worktree = join(repo, ".claude/worktrees/issue-7-cheap"); - return { dir, repo, git, run, worktree }; -}; - -test("run: a worker that edits and exits 0 with a green check gives pass and one commit with the Worker trailer", () => { - const { git, run, worktree } = scratchRun(); - const ran = run({ FAKE_OPENCODE: "edit" }); - assert.equal(ran.status, 0, ran.stderr); - const [verdict, ...rest] = ran.stdout.trimEnd().split("\n"); - assert.equal(verdict, "pass"); - assert.match(rest.join("\n"), /shared\.txt \| 2 \+-/); - assert.match(rest.at(-1), /^Route outcome: cheap·medium opencode\/test-free → pass \| \d+m$/); - const commits = git("log", "--format=%B%x00", "origin/int..issue-7-cheap").split("\0").map((body) => body.trim()).filter(Boolean); - assert.deepEqual(commits, ["Workflow: the thing\n\nWorker: opencode/test-free"]); - assert.equal(git("diff", "--name-only", "origin/int", "issue-7-cheap"), "shared.txt", "the gitignored .delegate/ is not committed"); - assert.equal(readFileSync(join(worktree, "shared.txt"), "utf8"), "the worker's line\n"); -}); - -test("run: a worker that drops .delegate/ from .gitignore still gets no .delegate/ committed", () => { - const { git, run } = scratchRun(); - const ran = run({ FAKE_OPENCODE: "unignore" }); - assert.equal(ran.status, 0, ran.stderr); - assert.match(ran.stdout, /^pass\n/); - assert.equal(git("diff", "--name-only", "origin/int", "issue-7-cheap"), ".gitignore\nshared.txt"); -}); - -/** The commit bodies on `branch` that are not on the integration branch, merges left out. */ -const commitsOn = (git, branch) => - git("log", "--no-merges", "--format=%B%x00", `origin/int..${branch}`) - .split("\0") - .map((body) => body.trim()) - .filter(Boolean); - -test("run: on pass, the worker's own commits are squashed into the one commit, and the moved integration tip is merged in", () => { - const { git, run, worktree } = scratchRun(); - const ran = run({ FAKE_OPENCODE: "commit" }); - assert.equal(ran.status, 0, ran.stderr); - assert.match(ran.stdout, /^pass\n/); - assert.deepEqual(commitsOn(git, "issue-7-cheap"), ["Workflow: the thing\n\nWorker: opencode/test-free"]); - assert.equal(readFileSync(join(worktree, "added.txt"), "utf8"), "more\n"); - - const moved = scratchRun(); - const after = moved.run({ FAKE_OPENCODE: "moved" }); - assert.match(after.stdout, /^pass\n/); - moved.git("fetch", "--quiet", "origin"); - assert.doesNotThrow(() => moved.git("merge-base", "--is-ancestor", "origin/int", "issue-7-cheap")); - assert.deepEqual(commitsOn(moved.git, "issue-7-cheap"), ["Workflow: the thing\n\nWorker: opencode/test-free"]); - assert.doesNotMatch(after.stdout, /other\.txt/, "the diff stat shows only the worker's change"); -}); - -test("run: the worker runs in the worktree with the brief, the ticket and its spec, and no PLOTKEEPER_INTERNAL anywhere", () => { - const { run, worktree } = scratchRun(); - const ran = run({ FAKE_OPENCODE: "edit" }); - assert.equal(ran.status, 0, ran.stderr); - const [worker] = ran.calls("opencode"); - assert.equal(worker.cwd, worktree); - assert.deepEqual(worker.argv.slice(0, 6), ["run", "--auto", "--format", "json", "-m", "opencode/test-free"]); - assert.equal(worker.argv.length, 7, "effort medium maps to no variant for this model"); - assert.match(worker.argv[6], /Read \.delegate\/ticket\.md/); - assert.equal(readFileSync(join(worktree, ".delegate/brief.md"), "utf8").trim(), worker.argv[6]); - assert.deepEqual(worker.env, { - OPENCODE_EXPERIMENTAL_BASH_DEFAULT_TIMEOUT_MS: "480000", - OPENCODE_PERMISSION: JSON.stringify({ bash: { "*": "allow", "git push*": "deny", "gh *": "deny" } }), - OPENCODE_DISABLE_CLAUDE_CODE_PROMPT: "1", - OPENCODE_DISABLE_EXTERNAL_SKILLS: "1", - }); - const npm = ran.calls("npm"); - assert.deepEqual(npm.map((call) => call.argv.join(" ")), ["ci", "run check"]); - assert.ok(npm.every((call) => call.cwd === worktree && call.internal === undefined)); - const brief = readFileSync(join(worktree, ".delegate/ticket.md"), "utf8"); - assert.match(brief, /^# Workflow: the thing\n\n## Parent\n\n#5\n/); - assert.match(brief, /\n---\n\n# Parent spec: Spec: things\n\n## Problem Statement\n\nNo things\.\n$/); - assert.equal(readFileSync(join(worktree, ".delegate/run.log"), "utf8"), `> read {"filePath":"${worktree}/AGENTS.md"}\n> edit {"filePath":"shared.txt"}\nDone: the ticket is implemented.\n`); -}); - -test("run: effort high passes the candidate's variant for high on the model id, not as --variant", () => { - const { run } = scratchRun(); - const ran = run({ FAKE_OPENCODE: "edit" }, ["--effort", "high"]); - assert.equal(ran.status, 0, ran.stderr); - const [worker] = ran.calls("opencode"); - assert.equal(worker.argv[5], "opencode/test-free#high"); - assert.ok(!worker.argv.includes("--variant")); - assert.match(ran.stdout, /Route outcome: cheap·high opencode\/test-free → pass/); -}); - -const gone = ({ git, worktree }) => { - assert.equal(existsSync(worktree), false, "the worktree is removed"); - assert.equal(git("branch", "--list", "issue-7-cheap"), "", "the branch is removed"); -}; - -for (const [what, fake, reason, result] of [ - ["an empty change, twice", { FAKE_OPENCODE: "empty" }, "red: no change", "red,red"], - ["an error exit", { FAKE_OPENCODE: "fail" }, "exit 1", "error"], - ["a red check, twice", { FAKE_OPENCODE: "edit", FAKE_NPM_CHECK: "red" }, "red check", "red,red"], - ["a merge conflict", { FAKE_OPENCODE: "conflict" }, "conflict", "conflict"], - ["a worker silent past the limit", { FAKE_OPENCODE: "silent", DELEGATE_SILENCE_MS: "300" }, "silent", "silent"], - ["a worker past the attempt limit", { FAKE_OPENCODE: "chatty", DELEGATE_ATTEMPT_MS: "600" }, "timeout", "error"], -]) { - test(`run: ${what} gives escalate medium (${reason}) and removes the worktree and branch`, () => { - const scratch = scratchRun(); - const ran = scratch.run(fake); - assert.equal(ran.status, 0, ran.stderr); - const lines = ran.stdout.trimEnd().split("\n"); - assert.equal(lines[0], `escalate medium (${reason})`); - assert.match(lines.at(-1), new RegExp(`^Route outcome: cheap·medium opencode/test-free → ${result} \\| \\d+m(, \\d+m)*$`)); - gone(scratch); - }); -} - -test("run: a red check, then green after one retry on the same session with the check's tail, gives pass", () => { - const { git, run, worktree } = scratchRun(); - const ran = run({ FAKE_OPENCODE: "edit", FAKE_NPM_CHECK: "red-once" }); - assert.equal(ran.status, 0, ran.stderr); - const lines = ran.stdout.trimEnd().split("\n"); - assert.equal(lines[0], "pass"); - assert.match(lines.at(-1), /^Route outcome: cheap·medium opencode\/test-free → red,pass \| \d+m, \d+m$/); - const [first, retry, ...more] = ran.calls("opencode"); - assert.equal(more.length, 0, "one retry only"); - assert.equal(first.argv.includes("--session"), false); - assert.equal(retry.cwd, worktree); - assert.deepEqual(retry.argv.slice(0, 8), ["run", "--auto", "--format", "json", "-m", "opencode/test-free", "--session", "ses_test"]); - assert.match(retry.argv.at(-1), /test agents::reads \.\.\. FAILED/); - assert.equal(retry.env.OPENCODE_DISABLE_CLAUDE_CODE_PROMPT, "1"); - assert.deepEqual(ran.calls("npm").map((call) => call.argv.join(" ")), ["ci", "run check", "run check"]); - assert.deepEqual(commitsOn(git, "issue-7-cheap"), ["Workflow: the thing\n\nWorker: opencode/test-free"]); -}); - -test("run: an empty change is retried with the message that no change was made", () => { - const ran = scratchRun().run({ FAKE_OPENCODE: "empty" }); - const [, retry] = ran.calls("opencode"); - assert.ok(retry, "the empty change is retried"); - assert.match(retry.argv.at(-1), /no change was made/i); -}); - -const two = [ - { cli: "opencode", model: "opencode/a-free", variant: { medium: null, high: "high" } }, - { cli: "opencode", model: "opencode/b-free", variant: { medium: "medium", high: "high" } }, -]; - -// A silence limit long enough that a worker that does answer is never killed while Node starts it, even on a loaded -// machine: at 300 ms the healthy candidate was once killed as silent too. -const HEALTHY_SILENCE_MS = "2000"; - -const models = (calls) => calls.map((call) => call.argv[call.argv.indexOf("-m") + 1].split("#")[0]); - -test("run: a silent worker is killed and marked out, and the next candidate runs in the reset worktree", () => { - const { repo, run, worktree } = scratchRun({ cheap: two }); - const ran = run({ FAKE_OPENCODE: "edit", FAKE_SILENT_MODELS: "opencode/a-free", DELEGATE_SILENCE_MS: HEALTHY_SILENCE_MS }); - assert.equal(ran.status, 0, ran.stderr); - const lines = ran.stdout.trimEnd().split("\n"); - assert.equal(lines[0], "pass"); - assert.match(lines.at(-1), /^Route outcome: cheap·medium opencode\/a-free → silent → opencode\/b-free → pass \| \d+m; \d+m$/); - assert.deepEqual(models(ran.calls("opencode")), ["opencode/a-free", "opencode/b-free"]); - assert.equal(existsSync(join(worktree, "stray.txt")), false, "the silent worker's file is cleaned away"); - assert.equal(readFileSync(join(worktree, "shared.txt"), "utf8"), "the worker's line\n"); - const out = JSON.parse(readFileSync(join(repo, ".git/delegate-silent.json"), "utf8")); - const midnight = new Date(); - midnight.setUTCHours(24, 0, 0, 0); - assert.deepEqual(out, { "opencode/a-free": midnight.toISOString() }); -}); - -test("run: a model marked out today is skipped by the next run, and with none left the run escalates as silent", () => { - const scratch = scratchRun({ cheap: two }); - scratch.run({ FAKE_OPENCODE: "edit", FAKE_SILENT_MODELS: "opencode/a-free", DELEGATE_SILENCE_MS: HEALTHY_SILENCE_MS }); - const second = scratch.run({ FAKE_OPENCODE: "edit", FAKE_SILENT_MODELS: "opencode/b-free", DELEGATE_SILENCE_MS: "300" }); - assert.equal(second.status, 0, second.stderr); - assert.deepEqual(models(second.calls("opencode")), ["opencode/a-free", "opencode/b-free", "opencode/b-free"], "the second run skips a-free"); - const lines = second.stdout.trimEnd().split("\n"); - assert.equal(lines[0], "escalate medium (silent)"); - assert.match(lines.at(-1), /^Route outcome: cheap·medium opencode\/b-free → silent \| \d+m$/); - gone(scratch); - const third = scratch.run({ FAKE_OPENCODE: "edit" }); - assert.equal(third.stdout, "escalate medium (silent)\n"); - assert.equal(third.calls("opencode").length, 3, "no worker starts when every model is marked out"); - assert.equal(third.calls("npm").filter((call) => call.argv[0] === "ci").length, 2, "nor npm ci"); -}); - -test("run: a mark from an earlier UTC day has expired", () => { - const scratch = scratchRun({ cheap: two }); - writeFileSync(join(scratch.repo, ".git/delegate-silent.json"), JSON.stringify({ "opencode/a-free": "2020-01-02T00:00:00.000Z" })); - const ran = scratch.run({ FAKE_OPENCODE: "edit" }); - assert.deepEqual(models(ran.calls("opencode")), ["opencode/a-free"]); -}); - -for (const [what, fake, said] of /** @type {[string, Record, RegExp][]} */ ([ - ["a worker that pushed its commit", { FAKE_OPENCODE: "push" }, /^stop: origin\/sneaky has the worker's commit [0-9a-f]{12}$/], - ["a worker that pushed its commit to the integration branch", { FAKE_OPENCODE: "pushint" }, /^stop: origin\/int has the worker's commit [0-9a-f]{12}$/], - ["an issue--cheap branch on origin", { FAKE_OPENCODE: "branch" }, /^stop: origin has the branch issue-7-cheap$/], - ["a worker that pushed and wrote outside its worktree", { FAKE_OPENCODE: "pushescape" }, /^stop: origin\/sneaky has the worker's commit [0-9a-f]{12}; worker wrote outside its worktree \(escaped\.txt\)$/], - ["an open PR from issue--cheap", { FAKE_OPENCODE: "edit", FAKE_GH_PRS: JSON.stringify([{ url: "https://github.com/o/r/pull/9" }]) }, /^stop: a PR from issue-7-cheap is open: https:\/\/github\.com\/o\/r\/pull\/9$/], -])) { - test(`run: ${what} gives stop, exit 0, and leaves the worktree for Daniel`, () => { - const { run, worktree } = scratchRun(); - const ran = run(fake); - assert.equal(ran.status, 0, ran.stderr); - const lines = ran.stdout.trimEnd().split("\n"); - assert.match(lines[0], said); - assert.match(lines.at(-1), /^Route outcome: cheap·medium opencode\/test-free → stop \| \d+m$/); - assert.ok(existsSync(worktree), "the worktree is kept as evidence"); - assert.deepEqual(ran.calls("npm").map((call) => call.argv.join(" ")), ["ci"], "no check runs once the worker pushed"); - }); -} - -test("run: a worker launched from the main checkout works in its own worktree and leaves the launching checkout untouched", () => { - const { git, run, worktree } = scratchRun(); - const ran = run({ FAKE_OPENCODE: "edit" }); - assert.equal(ran.status, 0, ran.stderr); - const [worker] = ran.calls("opencode"); - assert.equal(worker.cwd, worktree, "the worker works in its worktree, not in the folder delegate.mjs was launched from"); - assert.equal(git("status", "--porcelain", "--untracked-files=no"), "", "the launching checkout has no change"); - assert.equal(readFileSync(join(worktree, "shared.txt"), "utf8"), "the worker's line\n"); - assert.match(ran.stdout, /^pass\n/); -}); - -test("run: a worker that changes the launching checkout gives stop naming the paths, and stages nothing", () => { - const { git, run, worktree } = scratchRun(); - const ran = run({ FAKE_OPENCODE: "escape" }); - assert.equal(ran.status, 0, ran.stderr); - const lines = ran.stdout.trimEnd().split("\n"); - assert.equal(lines[0], "stop: worker wrote outside its worktree (escaped.txt)"); - assert.match(lines.at(-1), /^Route outcome: cheap·medium opencode\/test-free → stop \| \d+m$/); - assert.ok(existsSync(worktree), "the worktree is kept as evidence"); - assert.deepEqual(ran.calls("npm").map((call) => call.argv.join(" ")), ["ci"], "no check runs once the worker wrote outside"); - const wt = (...args) => execFileSync("git", args, { cwd: worktree, encoding: "utf8" }).trim(); - assert.equal(wt("diff", "--cached", "--name-only"), "", "nothing is staged"); - assert.equal(git("rev-parse", "issue-7-cheap"), git("rev-parse", "origin/int"), "nothing is committed"); -}); - -test("run: the guard asks gh for a PR from the ticket's branch, and a ref someone else moved gives no stop", () => { - const ran = scratchRun().run({ FAKE_OPENCODE: "moved" }); - assert.match(ran.stdout, /^pass\n/); - const pr = ran.calls("gh").find((call) => call.argv[0] === "pr"); - assert.ok(pr, "gh pr list was called"); - assert.deepEqual(pr.argv.slice(0, 4), ["pr", "list", "--head", "issue-7-cheap"]); -}); - -test("run: a worker that pulls the moved integration branch gives pass, not stop", () => { - const ran = scratchRun().run({ FAKE_OPENCODE: "pull" }); - assert.equal(ran.status, 0, ran.stderr); - assert.match(ran.stdout, /^pass\n/); -}); - -test("run: the worker's commit holds only its own change when it pulled the integration branch, which then moved again", () => { - const { git, run } = scratchRun(); - const ran = run({ FAKE_OPENCODE: "pullmoved" }); - assert.equal(ran.status, 0, ran.stderr); - assert.match(ran.stdout, /^pass\n/); - const [worker, ...more] = git("log", "--no-merges", "--format=%H", "origin/int..issue-7-cheap").split("\n").filter(Boolean); - assert.equal(more.length, 0, "one commit of the worker's"); - assert.equal(git("show", "--format=", "--name-only", worker), "shared.txt"); -}); - -/** A PATH with the stand-ins and node only, so that a stand-in removed from `bin` is missing, never the real one. */ -const bare = (dir) => { - mkdirSync(join(dir, "node-bin")); - symlinkSync(process.execPath, join(dir, "node-bin/node")); - return `${join(dir, "bin")}:${join(dir, "node-bin")}:/usr/bin:/bin`; -}; - -test("run: with opencode missing, the run could not start: exit 1, and no worktree or branch left", () => { - const scratch = scratchRun(); - rmSync(join(scratch.dir, "bin/opencode")); - const ran = scratch.run({ FAKE_OPENCODE: "edit", PATH: bare(scratch.dir) }); - assert.equal(ran.status, 1, ran.stderr); - assert.match(ran.stderr, /^could not start: opencode .*ENOENT/); - assert.equal(ran.stdout, ""); - gone(scratch); -}); - -test("run: with no cheap candidate in opencode's models, the run could not start: exit 1, and no worker or worktree", () => { - const scratch = scratchRun({ cheap: two }); - const ran = scratch.run({ FAKE_OPENCODE: "edit", FAKE_MODELS: "opencode/beam-free,opencode/big-pickle" }); - assert.equal(ran.status, 1, ran.stderr); - assert.equal(ran.stderr, "could not start: opencode serves none of the cheap models opencode/a-free, opencode/b-free\n"); - assert.equal(ran.stdout, ""); - assert.deepEqual(ran.calls("opencode"), []); - gone(scratch); -}); - -test("run: with one cheap candidate left in opencode's models, the run goes on with that one, not the first", () => { - const ran = scratchRun({ cheap: two }).run({ FAKE_OPENCODE: "edit", FAKE_MODELS: "opencode/b-free" }); - assert.equal(ran.status, 0, ran.stderr); - assert.match(ran.stdout, /^pass\n/); - assert.deepEqual(models(ran.calls("opencode")), ["opencode/b-free"], "the unserved a-free never runs"); -}); - -test("run: with the served candidates all marked out, it escalates as silent without starting a worker", () => { - const scratch = scratchRun({ cheap: two }); - writeFileSync(join(scratch.repo, ".git/delegate-silent.json"), JSON.stringify({ "opencode/b-free": "2999-01-01T00:00:00.000Z" })); - const ran = scratch.run({ FAKE_OPENCODE: "edit", FAKE_MODELS: "opencode/b-free" }); - assert.equal(ran.status, 0, ran.stderr); - assert.equal(ran.stdout, "escalate medium (silent)\n"); - assert.deepEqual(ran.calls("opencode"), []); -}); - -test("run: a worker that exits 0 while a process it started holds its output gives pass, and that process is killed", () => { - const scratch = scratchRun(); - const ran = scratch.run({ FAKE_OPENCODE: "linger", DELEGATE_SILENCE_MS: HEALTHY_SILENCE_MS }); - assert.equal(ran.status, 0, ran.stderr); - assert.match(ran.stdout, /^pass\n/); - const pid = Number(readFileSync(join(scratch.dir, "sleeper.pid"), "utf8")); - assert.throws(() => process.kill(pid, 0), { code: "ESRCH" }, "the sleeper is gone"); -}); - -test("run: a leftover issue--cheap worktree and branch are removed first", () => { - const scratch = scratchRun(); - const { git, run, worktree } = scratch; - git("worktree", "add", "--quiet", "-b", "issue-7-cheap", worktree, "main"); - writeFileSync(join(worktree, "leftover.txt"), "old\n"); - execFileSync("git", ["add", "leftover.txt"], { cwd: worktree }); - execFileSync("git", ["-c", "user.name=t", "-c", "user.email=t@example.com", "commit", "--quiet", "-m", "leftover"], { cwd: worktree }); - const ran = run({ FAKE_OPENCODE: "edit" }); - assert.equal(ran.status, 0, ran.stderr); - assert.match(ran.stdout, /^pass\n/); - assert.equal(existsSync(join(worktree, "leftover.txt")), false); - assert.deepEqual(commitsOn(git, "issue-7-cheap"), ["Workflow: the thing\n\nWorker: opencode/test-free"]); -}); - -test("run: outside Herdr, no pane is opened", () => { - const ran = scratchRun().run({ FAKE_OPENCODE: "edit" }); - assert.equal(ran.status, 0, ran.stderr); - assert.deepEqual(ran.calls("herdr"), []); -}); - -test("run: in Herdr, a new workers tab tails the log at the worktree, and only its pane is closed", () => { - const { run, worktree } = scratchRun(); - const ran = run({ FAKE_OPENCODE: "edit", HERDR_ENV: "1", HERDR_WORKSPACE_ID: "w1", FAKE_HERDR_TABS: JSON.stringify([{ tab_id: "w1:t1", label: "main" }]) }); - assert.equal(ran.status, 0, ran.stderr); - assert.deepEqual(ran.calls("herdr").map((call) => call.argv), [ - ["tab", "list", "--workspace", "w1"], - ["tab", "create", "--workspace", "w1", "--label", "workers", "--cwd", worktree, "--no-focus"], - ["pane", "run", "w1:p9", "tail -f .delegate/run.log"], - ["pane", "close", "w1:p9"], - ]); -}); - -test("run: in Herdr, an existing workers tab gets a split pane without focus, and only that pane is closed", () => { - const { run, worktree } = scratchRun(); - const ran = run({ - FAKE_OPENCODE: "fail", - HERDR_ENV: "1", - HERDR_WORKSPACE_ID: "w1", - FAKE_HERDR_TABS: JSON.stringify([{ tab_id: "w1:t1", label: "main" }, { tab_id: "w1:t2", label: "workers" }]), - FAKE_HERDR_PANES: JSON.stringify([{ pane_id: "w1:p1", tab_id: "w1:t1" }, { pane_id: "w1:p5", tab_id: "w1:t2" }]), - }); - assert.equal(ran.status, 0, ran.stderr); - assert.match(ran.stdout, /^escalate medium \(exit 1\)/); - const argv = ran.calls("herdr").map((call) => call.argv); - assert.deepEqual(argv.slice(2), [ - ["pane", "split", "w1:p5", "--direction", "down", "--cwd", worktree, "--no-focus"], - ["pane", "run", "w1:p8", "tail -f .delegate/run.log"], - ["pane", "close", "w1:p8"], - ]); - assert.equal(argv.filter(([, verb]) => verb === "close").length, 1); -}); - -test("run: with no cheap candidate, it escalates as silent without starting a worker", () => { - const ran = scratchRun({ cheap: [] }).run({ FAKE_OPENCODE: "edit" }); - assert.equal(ran.status, 0, ran.stderr); - assert.equal(ran.stdout, "escalate medium (silent)\n"); - assert.deepEqual(ran.calls("opencode"), []); -}); - -test("outcomeSegment writes each attempt's worker and results, and one time per worker run", async () => { - const { outcomeSegment } = await import(script); - const run = (result, minutes) => ({ result, ms: minutes * 60_000 }); - assert.equal(outcomeSegment({ tier: "cheap", effort: "high", attempts: [{ worker: "opencode/beam-free", runs: [run("red", 9.6)] }] }), "cheap·high opencode/beam-free → red | 10m"); - assert.equal(outcomeSegment({ tier: "cheap", effort: "medium", attempts: [{ worker: "opencode/beam-free", runs: [{ result: "pass", ms: 5_000 }] }] }), "cheap·medium opencode/beam-free → pass | 1m"); - const attempts = [ - { worker: "opencode/deepseek-v4.1-flash-free", runs: [run("silent", 10)] }, - { worker: "opencode/beam-free", runs: [run("red", 14), run("red", 6)] }, - ]; - assert.equal(outcomeSegment({ tier: "cheap", effort: "medium", attempts }), "cheap·medium opencode/deepseek-v4.1-flash-free → silent → opencode/beam-free → red,red | 10m; 14m, 6m"); -}); - -test("run: a failure after the worker ran escalates with exit 0, not as a run that could not start", () => { - const scratch = scratchRun(); - const ran = scratch.run({ FAKE_OPENCODE: "lost" }); - assert.equal(ran.status, 0, ran.stderr); - const lines = ran.stdout.trimEnd().split("\n"); - assert.match(lines[0], /^escalate medium \(error: git fetch failed: .+\)$/); - assert.match(lines.at(-1), /^Route outcome: cheap·medium opencode\/test-free → error \| \d+m$/); - gone(scratch); -});