# Ralph Gets a Job: A Linear Project, One Issue at a Time URL: https://stevekinney.com/writing/ralph-gets-a-job Canonical: https://stevekinney.com/writing/ralph-gets-a-job Author: Steve Kinney Language: en-US Date: 2026-12-03 Modified: 2026-12-03T23:44:22.000Z Description: How to build a Ralph loop that picks unblocked Linear issues, routes each one to a model and effort level, and drives the pull request to merge. --- When I wrote about [the Ralph loop](/writing/the-ralph-loop), the task list was a Markdown file. `ROADMAP.md`, a `progress.txt`, a prompt that says "pick the next incomplete task." That's the right place to start, and it's also the first thing you outgrow—because the plan I actually work from doesn't live in a Markdown file. It lives in [Linear](https://linear.app), where the issues have estimates, priorities, acceptance criteria, and those little orange "blocked by" flags that are the whole point of planning the thing in a tracker. So the obvious next question: what would it take to point the loop at a Linear project and let it work through the whole thing? One issue at a time. Fresh context for every issue. Respecting the blocking relationships. Picking a sensible model and effort level for each one instead of running everything on the most expensive setting I've got. Not falling over when I hit a usage limit. Keeping the board up to date. And—this is the spicy part—driving each issue all the way through a pull request to merge. I want to walk through how I'd build that twice: once around [Claude Code](https://code.claude.com/docs/en/headless) and once around [Codex](https://learn.chatgpt.com/docs/non-interactive-mode). Most of the script would be identical either way, and the part that isn't is where the two tools turn out to have very different ideas about what "unattended" means. > [!NOTE] This is a blueprint, not a package > This is a blueprint assembled from pieces of a script, not a thing you can install, and I haven't run the whole loop in anger yet. The snippets are written in [TypeScript](https://www.typescriptlang.org/) for Bun 1.4. I checked the flags and API shapes against Claude Code 2.1.334, Codex CLI 0.171.0, and the [GitHub CLI](https://cli.github.com/) 2.106.0, and I'll point out the spots I couldn't verify. All three tools ship faster than I can write, so treat the exact flags as "true the day I wrote this" and the shape as the part worth keeping. ## You might not need to build this Let me save some of y'all an afternoon. A lot of this exists already, and if one of these fits, use it: - **[Linear's cloud coding agent](https://linear.app/docs/linear-cloud-coding-agent)**: runs Claude Code or Codex in a sandbox when you delegate an issue to it, and hands you a draft pull request. - **[Codex for Linear](https://learn.chatgpt.com/docs/third-party/linear)**: lets you assign an issue to Codex like a teammate. It works in the cloud and posts back a summary and a link so _you_ can create the pull request. - **[Symphony](https://github.com/openai/symphony)**: [OpenAI](https://openai.com/)'s open-source orchestrator polls a Linear board and runs a Codex agent per issue. It's the closest prior art to what we're building, it calls itself "a low-key engineering preview," and it's worth reading even if you never run it. Every one of them stops short of the merge unless a human steps in—Symphony's reference workflow waits for a person to drag the issue into a `Merging` status before the agent is allowed to land anything. And none of them route work by difficulty: Symphony's sample config pins one model at one reasoning effort for every issue on the board. I want the cheap model on the rename and the expensive one on the migration, I want it running against the subscriptions I'm already paying for, and I want to decide exactly where the human gate goes. So: a script of my own. I'd write it in TypeScript and run it with [Bun](https://bun.sh), for two reasons. Linear's API hands back deeply nested JSON, and that's a lot more pleasant as typed objects than as a pile of [`jq`](https://jqlang.org/) filters. And Bun's `$` shell escapes every value you interpolate into a command, which matters when some of those values—commit messages, pull request titles—were written by a model. (Both tools have TypeScript SDKs, too. I'm shelling out to the CLIs anyway, because the CLI flags are what I checked, and because "a brand-new process for every issue" is the whole trick. I'd rather be able to see the process.) ## The division of labor The [original Ralph rule](https://ghuntley.com/ralph/) is one thing per loop. Only one thing. In the Markdown-file version, the agent reads the plan and decides what that one thing is. With a real tracker, I'd take that decision away from it entirely. - **The script**: reads Linear, picks the issue, chooses the model, checks the limits, runs the tests, commits, pushes, opens the pull request, updates the board, and handles the merge. - **The agent**: gets one issue and a clean checkout. It edits files and tells me how it went. That's a deliberately stingy job description. Everything on the script's list is either a decision I want made deterministically or an action I can't take back, and I've been burned enough times to not hand either of those to something that was feeling creative today. The design goal is an agent that never needs a Linear token, never needs to push, and never needs to merge. (How well each tool actually _enforces_ that is the most interesting difference between them, and we'll get there.) ```mermaid graph TD A["Read the project from Linear"] --> B{"Any open PR need attention?"} B -->|"CI failed or review threads open"| C["Fix pass: fresh agent, same branch"] B -->|"No"| D{"Any unblocked issue?"} D -->|"Yes"| E["Route model and effort by estimate"] E --> F["Fresh agent in a new worktree"] F --> G{"Do my checks pass?"} G -->|"Yes"| H["Script commits, pushes, opens the PR"] G -->|"No"| I["Label it needs-human and move on"] D -->|"No, but PRs are waiting"| J["Stop: waiting on PRs"] D -->|"No, nothing left"| K["Done"] C --> A H --> A I --> A ``` And here's that diagram as the loop itself. The functions that make decisions are written out below. A few are plumbing that I only describe: `pullRequestNeedingAttention` and `pullRequestsWaiting` sweep open pull requests, `fixPass` reruns the agent on review feedback, and `needsHuman` adds a label and comment. The constants in capitals—`AGENT`, `PROJECT`, `MAX_PASSES`, and friends—come from environment variables. Add those, stubs for the plumbing, and the usual imports (`$` from `bun`, `mkdir` and `rm` from [`node:fs/promises`](https://nodejs.org/api/fs.html#promises-api), `resolve` from [`node:path`](https://nodejs.org/api/path.html)), and the snippets typecheck together. ```typescript async function main(): Promise { for (let pass = 1; pass <= MAX_PASSES; pass++) { if (await Bun.file('.ralph/STOP').exists()) return 0; if (!(await limitsOk())) return 3; // out of quota const issues = await fetchIssues(); const needsWork = await pullRequestNeedingAttention(issues); if (needsWork) { await fixPass(needsWork); continue; } const issue = pick(issues); if (!issue) return (await pullRequestsWaiting(issues)) ? 4 : 0; // waiting on PRs, or finished const tier = route(issue.estimate); if (!tier) { await needsHuman(issue, 'No estimate, or too big for one context.'); continue; } const run = await startIssue(issue); if (!run) continue; // it couldn't set up the worktree, and already said so const result = await runAgent(run, tier); if (!result && (await outOfQuota(run))) return 3; if ( result?.status === 'done' && (await runChecks(run)) && (await commitAndPush(run, result.commit_message)) ) { await openPullRequest(run, result); } else { await needsHuman(issue, result?.summary ?? 'The run failed. See the logs.'); } } return 2; // out of passes } ``` There's no state file in there. Every pass rebuilds its picture of the world from Linear and [GitHub](https://github.com/), so if the script dies at 2am, I start it again and it finds its place. `AGENT` is either `claude` or `codex`. And `main` returns different exit codes on purpose: `0` is finished, `2` is out of passes, `3` is out of quota, `4` is "nothing I can start until a pull request merges," and anything else is the script itself falling over. Those call for very different responses from me in the morning. (`4` is also the one I'd put on a schedule. Every pass starts from scratch anyway, so running it again in half an hour costs nothing, and it beats a script that sleeps in a loop.) ## Getting the project out of Linear You could do this through Linear's [Model Context Protocol (MCP) server](https://linear.app/docs/mcp), and for interactive work I do. But the script is the one talking to Linear here, not the model, so plain `fetch` against the [GraphQL API](https://graphql.org/) is simpler and has fewer moving parts: ```typescript // The script's secrets. Anything it launches for the agent gets `agentEnv`, which has none. const { LINEAR_API_KEY = '', GH_TOKEN, GITHUB_TOKEN, ANTHROPIC_API_KEY, ANTHROPIC_AUTH_TOKEN, CLAUDE_CODE_OAUTH_TOKEN, CODEX_ACCESS_TOKEN, CODEX_API_KEY, OPENAI_API_KEY, ...agentEnv } = process.env; async function linear(query: string, variables: Record = {}): Promise { const response = await fetch('https://api.linear.app/graphql', { method: 'POST', headers: { 'Content-Type': 'application/json', Authorization: LINEAR_API_KEY }, body: JSON.stringify({ query, variables }), }); if (!response.ok) { throw new Error(`Linear said ${response.status}: ${(await response.text()).slice(0, 500)}`); } const body = (await response.json()) as { data?: T; errors?: unknown[] }; if (body.errors || !body.data) throw new Error(`Linear said: ${JSON.stringify(body.errors ?? body)}`); return body.data; } ``` > [!TIP] No `Bearer` here > A personal API key goes in the `Authorization` header with _no_ `Bearer` prefix for the GraphQL API. The MCP server takes the same key _with_ `Bearer`. (I'll let you guess how I feel about that.) While you're in the settings, scope the key to the one team the loop works on. That destructuring at the top is doing more than it looks like. It pulls the secrets the script knows about out of the environment by name—naming them is the only reason they're there—and `agentEnv` is whatever's left. Anything the script launches on the agent's behalf gets `agentEnv` instead of the real environment, so the agent never sees the Linear key, the GitHub tokens, or the [Anthropic](https://www.anthropic.com/) and OpenAI keys we'll get to in a minute. If your shell exports other credentials, add them to the list. Then the query, which is everything the loop needs to know about every issue in the project, and the few lines that walk the pages: ```typescript const ISSUES_QUERY = /* GraphQL */ ` query ProjectIssues($project: String!, $after: String) { project(id: $project) { issues(first: 50, after: $after) { pageInfo { hasNextPage endCursor } nodes { id identifier title description priority sortOrder estimate branchName state { name type } labels(first: 20) { nodes { name } } inverseRelations(first: 25) { pageInfo { hasNextPage endCursor } nodes { type issue { identifier state { type } } } } } } } } `; const INCOMING_RELATIONS_QUERY = /* GraphQL */ ` query IssueRelations($issueId: String!, $after: String) { issue(id: $issueId) { inverseRelations(first: 25, after: $after) { pageInfo { hasNextPage endCursor } nodes { type issue { identifier state { type } } } } } } `; type PageInfo = { hasNextPage: boolean; endCursor: string | null }; type Connection = { pageInfo: PageInfo; nodes: T[] }; type Relation = { type: string; issue: { identifier: string; state: { type: string } } }; type Issue = { id: string; identifier: string; title: string; description: string | null; priority: number; sortOrder: number; estimate: number | null; branchName: string; state: { name: string; type: string }; labels: { nodes: { name: string }[] }; inverseRelations: Connection; }; type IssuesPage = { project: { issues: Connection; }; }; type IncomingRelationsPage = { issue: { inverseRelations: Connection } }; function nextCursor(pageInfo: PageInfo): string | null { if (!pageInfo.hasNextPage) return null; if (!pageInfo.endCursor) throw new Error('Linear returned another page without an end cursor.'); return pageInfo.endCursor; } async function fetchIssues(): Promise { const issues: Issue[] = []; let after: string | null = null; do { const { project }: IssuesPage = await linear(ISSUES_QUERY, { project: PROJECT, after, }); for (const issue of project.issues.nodes) { let relationAfter = nextCursor(issue.inverseRelations.pageInfo); while (relationAfter) { const { issue: relatedIssue }: IncomingRelationsPage = await linear( INCOMING_RELATIONS_QUERY, { issueId: issue.id, after: relationAfter }, ); const nextPage = relatedIssue.inverseRelations; issue.inverseRelations.nodes.push(...nextPage.nodes); relationAfter = nextCursor(nextPage.pageInfo); } issues.push(issue); } after = nextCursor(project.issues.pageInfo); } while (after); return issues; } ``` The project issue list and each issue's incoming relations are separate connections, so both have their own cursor. The first query gets a bounded page of each; if an issue has more than 25 incoming relations, the second query fetches the remaining pages before we make a readiness decision. Linear's [pagination guide](https://linear.app/developers/pagination) describes the `first`/`after` pattern: keep passing `pageInfo.endCursor` until `hasNextPage` is false. `inverseRelations` first, because the direction is the kind of thing that's easy to get backwards. If issue A blocks issue B, Linear stores one relation of type `blocks` with A as the source. It shows up in A's `relations` and in B's `inverseRelations`. So "what's blocking me?" is my `inverseRelations` where the type is `blocks`. There's no handy `isBlocked` field on an issue; you derive it. Then those explicit `first:` arguments. Linear [scores every query for complexity](https://linear.app/developers/rate-limiting) and multiplies each nested connection by its page size, which defaults to 50. Fifty issues, each carrying fifty labels and fifty relations, works out to roughly 11,000 points by Linear's formula—over the 10,000-point ceiling for a single query. Capping the inner connections brings it down to about half that. ## What "unblocked" has to mean Here's the selection logic, and it's the part of the whole design I'd defend the hardest: ```typescript function openBlockers(issue: Issue): string[] { return issue.inverseRelations.nodes .filter(({ type, issue }) => type === 'blocks' && issue.state.type !== 'completed') .map(({ issue }) => issue.identifier); } function pick(issues: Issue[]): Issue | undefined { const rank = (issue: Issue): number => (issue.priority === 0 ? 5 : issue.priority); return issues .filter((issue) => issue.state.type === 'unstarted') .filter((issue) => !issue.labels.nodes.some(({ name }) => name === 'needs-human')) .filter((issue) => openBlockers(issue).length === 0) .sort((a, b) => rank(a) - rank(b) || a.sortOrder - b.sortOrder)[0]; } ``` An issue is ready when it's in a "to do" status, nobody has flagged it for a human, and every issue blocking it is `completed`. Then it's highest priority first, with Linear's manual ordering as the tiebreaker. (Priority `0` means "no priority," which sorts _first_ if you're not careful—hence the remapping.) Everything hangs on that `completed` check, because of a rule I'd enforce everywhere else in the script: _nothing marks an issue Done except a merge._ Not the agent, not the script when the pull request opens—only the merge. If that holds, then "my blocker is completed" means "my blocker's code is on `main`," and the worktree I'm about to cut for the dependent issue actually contains the thing it depends on. Break that rule and you get a failure that's easy to miss. Every tool I looked at keys readiness on tracker status, and at least one community loop marks issues Done when the pull request _opens_. Do that, and the loop happily starts the dependent issue on a branch cut from a `main` that doesn't have the blocker's code in it yet. The agent, being helpful, reimplements whatever's missing. Now you have two pull requests that both add the same module in slightly different ways. The filter makes a couple of smaller choices, too: - **A canceled blocker doesn't unblock anything**: neither does one that got marked as a duplicate. Linear's own `hasBlockedByRelations` filter only counts a blocker while both issues are still open, so as far as I can tell a canceled blocker stops counting there—and that filter would do this whole dance in one query. But if I planned an issue assuming some other work would exist and then that work got canceled, I want a human to look at it, not an agent improvising around the hole. - **`Backlog` isn't `Todo`**: the loop only picks from the `unstarted` state type. Backlog is where I keep things I haven't decided to do. Moving an issue to Todo is me saying "yes, this one." ## Deciding how hard to think In [the post about using Codex as a worker](/writing/codex-as-a-worker), I said the worker never guesses how hard to think, because effort is a money-and-time dial and the agent doing the work is the worst-placed party to set it. Same principle here, one step removed: the dial gets set at planning time, in Linear, by the person who scoped the issue. The loop just reads it. I'd use the estimate. (Yes, this means I have to actually estimate my issues. I'm as upset about it as you are.) ```typescript type Tier = { name: 'small' | 'standard' | 'hard'; claude: { model: string; effort: string; budgetUsd: number }; codex: { model: string; effort: string }; }; const TIERS = { small: { name: 'small', claude: { model: 'haiku', effort: 'medium', budgetUsd: 2 }, codex: { model: 'gpt-6-luna', effort: 'high' }, }, standard: { name: 'standard', claude: { model: 'sonnet', effort: 'high', budgetUsd: 8 }, codex: { model: 'gpt-6.2-sol', effort: 'medium' }, }, hard: { name: 'hard', claude: { model: 'opus', effort: 'xhigh', budgetUsd: 25 }, codex: { model: 'gpt-6.2-astra', effort: 'high' }, }, } satisfies Record; function route(estimate: number | null): Tier | undefined { switch (estimate) { case 1: case 2: return TIERS.small; case 3: case 5: return TIERS.standard; case 8: return TIERS.hard; default: return undefined; // unestimated, or too big for one context } } ``` Linear stores T-shirt sizes as numbers under the hood—XS through XL come back from the API as 1, 2, 3, 5, and 8—so this works for T-shirt and Fibonacci teams as written. If your team uses the linear or exponential scale, redraw the cut points. And look at the `default` case. No estimate means no run: the loop labels the issue `needs-human` and moves on. Same for anything bigger than an 8, which isn't a job for a more expensive model. It's an issue that needs to be split. Each tier carries the settings for both tools, so the routing decision doesn't care which one is doing the work. `budgetUsd` is a per-run dollar cap we'll use in a minute. That table is a starting point I'd expect to tune, not a recommendation I'd defend in court. The effort scales are calibrated per model, so `high` on one isn't `high` on another, and the only way to find your mapping is to watch a few issues go through each tier. What I'd push back on is skipping the table altogether. On Codex's own published limits, the cheap model gets you something like twenty times as many messages per window as the everyday one, and the gap to the top model is wider still. Running a rename at the top tier doesn't make the rename better. It just means the loop stops at lunchtime. Codex doesn't have an `--effort` flag, but `-c` overrides any config key for a single run, so the script passes `model_reasoning_effort` that way. You'll see it in the Codex runner in a bit. > [!WARNING] Three ways to spend money you didn't mean to > If `ANTHROPIC_API_KEY` is set in your environment, `claude -p` always uses it—every iteration bills the API instead of your subscription. Codex can also use `OPENAI_API_KEY` for API-key authentication. Keep both out of `agentEnv`; it also strips `CODEX_API_KEY` for setups that use that variable. Be careful putting Claude's Fable models in the hard tier: in `-p` mode, a Fable request that would bill to usage credits [gets billed without asking](https://code.claude.com/docs/en/model-config#fable-and-usage-credits), because there's nobody there to ask. And on either tool, if your account has purchased credits, hitting a plan limit may not stop anything. It may just start spending them. ## Checking the usage limits (if possible) Can a script ask how much of my plan is left? Sort of, and differently for each tool. Neither one has a `usage --json` command. I looked. Codex has the better preflight check. The JSON stream from `codex exec` doesn't carry any rate-limit information, which surprised me. But the [app server](https://learn.chatgpt.com/docs/app-server) has a documented method for it, and you can call it from a script without spending a single token. (The `app-server` subcommand is still labeled experimental in `codex --help`, so hold this one loosely.) ```typescript type RateLimitWindow = { usedPercent: number; windowDurationMins: number | null; resetsAt: number | null; }; type RateLimitBucket = { primary: RateLimitWindow | null; secondary: RateLimitWindow | null }; type RateLimits = { rateLimits: RateLimitBucket; rateLimitsByLimitId?: Record | null; }; type RpcResponse = { id: number; result?: T; error?: { message: string } }; async function* lines(stream: ReadableStream): AsyncGenerator { const decoder = new TextDecoder(); let buffer = ''; for await (const chunk of stream) { buffer += decoder.decode(chunk, { stream: true }); const complete = buffer.split('\n'); buffer = complete.pop() ?? ''; yield* complete.filter(Boolean); } } async function codexLimits(): Promise { const server = Bun.spawn(['codex', 'app-server'], { stdin: 'pipe', stdout: 'pipe', stderr: 'ignore', timeout: 30_000, }); const send = (message: object): void => { server.stdin.write(JSON.stringify(message) + '\n'); }; const output = lines(server.stdout)[Symbol.asyncIterator](); const readResponse = async (id: number): Promise | undefined> => { for (;;) { const next = await output.next(); if (next.done) return undefined; const message = JSON.parse(next.value) as RpcResponse; if (message.id === id) return message; } }; send({ method: 'initialize', id: 0, params: { clientInfo: { name: 'ralph', title: 'Ralph loop', version: '0.0.1' } }, }); await server.stdin.flush(); try { const initialization = await readResponse(0); if (initialization?.error || !initialization?.result) { throw new Error(initialization?.error?.message ?? 'Codex app-server did not initialize.'); } send({ method: 'initialized', params: {} }); send({ method: 'account/rateLimits/read', id: 1 }); await server.stdin.flush(); const response = await readResponse(1); if (response?.error) throw new Error(response.error.message); return response?.result; } finally { server.kill(); } } async function limitsOk(): Promise { if (AGENT !== 'codex') return true; // Claude Code has nothing to ask up front const limits = await codexLimits(); if (!limits) throw new Error("Couldn't read Codex's rate limits."); const byLimitId = limits.rateLimitsByLimitId; const buckets = byLimitId && Object.keys(byLimitId).length > 0 ? Object.values(byLimitId) : [limits.rateLimits]; const windows = buckets.flatMap(({ primary, secondary }) => [primary, secondary]); return windows.every((window) => !window || window.usedPercent < 90); } ``` The `initialize` response matters: the app server rejects requests until the client completes that handshake. The rate-limit call requires a ChatGPT-backed Codex login; an API-key-only login can't read these limits. Current responses can include several buckets under `rateLimitsByLimitId`, so this example conservatively checks every reported window. The API doesn't tell you which bucket maps to each model, so that can stop a run because an unrelated model's bucket is nearly exhausted. If your response only has the compatibility `rateLimits` bucket, the code checks that one. If any reported window is past 90%, the loop stops with its out-of-quota exit code instead of starting an issue it can't finish. Don't assume `primary` is the five-hour window, by the way. On my account it's the weekly one and `secondary` is `null`. Read `windowDurationMins` and believe what it says. The script starts the server, sends three messages, reads until the answer shows up, and kills it. That takes a couple of seconds. If no answer comes back at all, `limitsOk` throws, because "I couldn't check" isn't the same thing as "you're fine." (The same response also reports whether you have usage credits and how many, which is worth logging, given the warning above.) Claude Code does a better job of waiting it out. There's nothing to ask before the run. The status line gets a nice `rate_limits` object, but that's documented for the interactive UI and nothing says a `-p` run feeds it. What Claude Code has instead is a [retry watchdog](https://code.claude.com/docs/en/errors#tune-retry-behavior) that will sit out a plan limit for you. The Claude Code runner gets `agentEnv` plus three settings: ```typescript const USAGE_LIMIT_WAIT_MS = 5 * 60 * 60 * 1000; const claudeEnv = { ...agentEnv, CLAUDE_CODE_RETRY_WATCHDOG: '1', CLAUDE_CODE_RETRY_WATCHDOG_MAX_WAIT_MS: String(30 * 60 * 1000), CLAUDE_CODE_RETRY_WATCHDOG_MAX_USAGE_LIMIT_WAIT_MS: String(USAGE_LIMIT_WAIT_MS), }; ``` With those set, a run that hits the session limit waits for the reset and then picks up where it was. If the reset is further away than the cap—so, the weekly limit—it fails right away instead of sleeping for four days. (The documented exception is the one from the warning above: if usage credits have room, it retries against those instead.) For telling "out of quota" from "actually broken" after a run dies, the stream output has a `rate_limit_event`, and Codex has an error string: ```typescript type StreamEvent = { type?: string; is_error?: boolean; structured_output?: AgentResult; rate_limit_info?: { status?: string }; }; function jsonLines(text: string): StreamEvent[] { return text.split('\n').flatMap((line) => { try { return [JSON.parse(line)]; } catch { return []; } }); } async function outOfQuota(run: Run): Promise { const log = Bun.file(`${run.dir}/${AGENT}.jsonl`); if (!(await log.exists())) return false; const text = await log.text(); if (AGENT === 'codex') return text.includes('hit your usage limit'); return jsonLines(text).some( (event) => event.type === 'rate_limit_event' && event.rate_limit_info?.status === 'rejected', ); } ``` I haven't caught either of those live, so check them against a real limit before you trust them. And `--fallback-model` won't save you here: it's for a model that's overloaded or unavailable, and rate-limit errors never trigger it. The session and weekly limits are shared across models anyway, so there'd be nothing to fall back _to_. ## One issue, one fresh context Now the part that's actually a Ralph loop. For each issue, the script claims it, then cuts a worktree from a freshly fetched `main` using the branch name Linear suggests: ```typescript const MOVE_ISSUE = /* GraphQL */ ` mutation Move($id: String!, $stateId: String!) { issueUpdate(id: $id, input: { stateId: $stateId }) { success } } `; type Run = { issue: Issue; branch: string; worktree: string; dir: string }; async function startIssue(issue: Issue): Promise { const run: Run = { issue, branch: issue.branchName, worktree: resolve('..', 'ralph-worktrees', issue.identifier), dir: resolve('.ralph', 'runs', issue.identifier), }; await mkdir(run.dir, { recursive: true }); await linear(MOVE_ISSUE, { id: issue.identifier, stateId: IN_PROGRESS }); await $`git fetch -q origin main`; await $`git worktree remove --force ${run.worktree}`.quiet().nothrow(); await $`git worktree add -q ${run.worktree} -B ${run.branch} origin/main`; const install = await $`bun install --frozen-lockfile`.cwd(run.worktree).nothrow(); if (install.exitCode !== 0) { await needsHuman(issue, '`bun install --frozen-lockfile` failed in a fresh worktree.'); return undefined; } await Bun.write( `${run.dir}/issue.md`, `# ${issue.identifier}: ${issue.title}\n\n${issue.description ?? ''}`, ); return run; } ``` If you haven't met Bun's `$` before: every `${}` inside it is escaped for you. A string becomes exactly one argument and an array becomes one argument per element, so a branch name with a space or a semicolon in it stays a branch name. And if `bun install` fails, the issue goes straight to `needs-human`, before any model gets involved. Three things in there look like trivia and aren't. The claim comes first, so a second copy of the loop is unlikely to grab the same issue. (It's a claim, not a lock. Run one loop per project.) `IN_PROGRESS` is the workflow state's ID, not its name—you look it up once with a `workflowStates` query. And the `remove` plus `-B` is what makes a restart safe: if a previous run died halfway through this issue, its leftovers get thrown away and the issue starts clean. Linear's `branchName` has the issue identifier in it, which is what links the eventual pull request to the issue with no extra API call. And dependencies get installed by the script, before the agent starts, because the agent isn't going to have a network. The prompt is the same file every single time. The issue gets appended to it: ```markdown You are working on exactly one issue, included below. The repository is already checked out on a fresh branch for it. 1. Read the issue and its acceptance criteria. Search before you build. 2. Write a failing test, then implement until it passes. 3. Run the project's checks and fix what you broke. 4. Do not commit, push, open a pull request, or touch the issue tracker. The harness does all of that. If the issue is ambiguous, or needs a decision you can't make from the repository, stop and report `blocked` with the question a human needs to answer. A wrong guess costs more than a question. ``` And the agent's whole answer is a tiny piece of structured output. It's the same schema for both tools, plus a type to match: ```typescript const RESULT_SCHEMA = { type: 'object', properties: { status: { type: 'string', enum: ['done', 'blocked'] }, summary: { type: 'string' }, commit_message: { type: 'string' }, pull_request_title: { type: 'string' }, pull_request_body: { type: 'string' }, }, required: ['status', 'summary', 'commit_message', 'pull_request_title', 'pull_request_body'], additionalProperties: false, }; type AgentResult = { status: 'done' | 'blocked'; summary: string; commit_message: string; pull_request_title: string; pull_request_body: string; }; ``` ### The Claude Code version ```typescript async function promptFor(run: Run): Promise { const instructions = await Bun.file('PROMPT.md').text(); const issue = await Bun.file(`${run.dir}/issue.md`).text(); return `${instructions}\n\n${issue}`; } async function runClaude(run: Run, tier: Tier, prompt?: string): Promise { const log = `${run.dir}/claude.jsonl`; await rm(log, { force: true }); // Bun overwrites an existing file without truncating it const args = [ ['-p'], ['--model', tier.claude.model, '--effort', tier.claude.effort], ['--permission-mode', 'auto', '--permission-prompts', 'none'], ['--disallowedTools', 'Bash(git push *)', 'Bash(gh pr *)'], ['--strict-mcp-config'], ['--max-budget-usd', String(tier.claude.budgetUsd)], ['--json-schema', JSON.stringify(RESULT_SCHEMA)], ['--output-format', 'stream-json', '--verbose'], ].flat(); const agent = Bun.spawn(['claude', ...args], { cwd: run.worktree, env: claudeEnv, stdin: new Blob([prompt ?? (await promptFor(run))]), stdout: Bun.file(log), timeout: AGENT_TIMEOUT_MS + USAGE_LIMIT_WAIT_MS, // room for the watchdog to wait }); await agent.exited; const results = jsonLines(await Bun.file(log).text()).filter( (event) => event.type === 'result' && !event.is_error, ); return results.at(-1)?.structured_output; } ``` The flags worth caring about: - **`--permission-mode auto --permission-prompts none`**: the documented combination for unattended runs. A classifier reviews what the agent tries to do, and anything that would've fallen back to a prompt is denied—with the agent told nobody's there to approve it, so it doesn't keep retrying. The denials come back in the result as `permission_denials`, which makes a surprisingly good log of what the agent wanted and couldn't have. - **`--disallowedTools`**: blocks the obvious spellings of pushing and `gh pr`. Claude Code's docs are clear that a Bash rule matches the command as written—`git -C . push` slips right past `Bash(git push *)`—so this is a seatbelt, not a wall. Auto mode's classifier is the second layer, and by default it refuses to merge a pull request no human has approved. Credit where it's due: that's the right default. - **`--strict-mcp-config`** and `claudeEnv`: how the agent ends up without Linear access. A `-p` run otherwise loads every MCP server and connector I've set up—including Linear's—and hands the whole environment to every Bash command it runs. - **`--max-budget-usd`**: caps one run. It's a client-side estimate at list prices, not what a subscription actually charges, but it's a real circuit breaker and Codex doesn't have one. - **`timeout`**: Bun's wall-clock limit, not Claude Code's. Every unattended loop needs one: 45 minutes of work, plus the usage-limit wait from earlier, so Bun doesn't kill the watchdog while it's sitting out a reset. Shrink that wait and the timeout shrinks with it. A failed run taught me one more thing (thanks, expired login): check `is_error`, not `subtype`. The result came back with `"subtype": "success"` and `"is_error": true` in the same object, with the actual complaint sitting in `result`. A success that isn't. That's why `runClaude` only hands back `structured_output` from a result that isn't an error. (And the `rm` at the top is there because Bun writes a child's output over an existing file without truncating it. I caught that with a quick probe: a shorter second write left the end of the first one in the file. Here, that would mean a second run on an issue could leave the first run's `result` line at the bottom of the log—and `runClaude` would happily hand back the old answer.) ### The Codex version ```typescript async function runCodex(run: Run, tier: Tier, prompt?: string): Promise { const schema = `${run.dir}/schema.json`; const result = `${run.dir}/result.json`; const log = `${run.dir}/codex.jsonl`; await Bun.write(schema, JSON.stringify(RESULT_SCHEMA)); await rm(result, { force: true }); await rm(log, { force: true }); const args = [ ['exec', '-'], ['--profile', 'ralph'], ['--model', tier.codex.model, '-c', `model_reasoning_effort="${tier.codex.effort}"`], ['--sandbox', 'workspace-write', '-c', 'sandbox_workspace_write.network_access=false'], ['--cd', run.worktree], ['--output-schema', schema, '--output-last-message', result], ['--json'], ].flat(); const agent = Bun.spawn(['codex', ...args], { env: agentEnv, stdin: new Blob([prompt ?? (await promptFor(run))]), stdout: Bun.file(log), timeout: AGENT_TIMEOUT_MS, }); if ((await agent.exited) !== 0) return undefined; return Bun.file(result) .json() .catch(() => undefined); // exited cleanly, but left nothing usable } const runAgent = AGENT === 'codex' ? runCodex : runClaude; ``` Claude Code's guardrail in this setup is a _permission_ layer: rules and a classifier deciding what's allowed. Codex's default is an operating-system sandbox. Under `workspace-write`, the agent can edit files inside the worktree and that's roughly it. Network access is off by default—but everything layers on top of your normal config, and mine turns it on, so the script turns it back off explicitly. And `.git` is read-only. I didn't believe that last one until I tried it. I asked Codex to make a commit under `workspace-write` and got: ```text fatal: Unable to create '.git/index.lock': Operation not permitted ``` At first that looks like a limitation. But think about what we set out to build: an agent that edits files while the script does everything irreversible. On Claude Code, I wrote a deny rule and a line in the prompt to get that. On Codex, the sandbox draws the same line and the model can't talk its way across it. I'm comparing defaults here, not ceilings. Claude Code [has an OS sandbox too](https://code.claude.com/docs/en/sandboxing). It's off by default and it deliberately lets `git commit` through, so you'd get the network wall but not the free "no commits" line. And Codex has a classifier path of its own in `--approve-for-me`. Codex has the same inheritance catch as Claude Code, though: every run brings along the MCP servers in your base config, and MCP connections aren't covered by the sandbox's network setting. That's what `--profile ralph` is for. It layers `~/.codex/ralph.config.toml` on top of the base config, and that file is where I'd switch off Linear's server and anything else the agent has no business talking to. One catch: if that file doesn't exist, Codex doesn't complain. It quietly runs on the base config, MCP servers and all—so have the script check the file exists before the first pass. And that last line in the Codex block is the entire switch between the two tools. ## Keeping Linear up to date The fastest way to make a mess of the board is to have two things fighting over it. Linear's [GitHub integration](https://linear.app/docs/github) already moves issues around on its own, so I'd give every transition exactly one owner: | Transition | Owner | | ----------------------- | ----------------------------------------------- | | Todo → In Progress | The script, at the moment it claims the issue | | In Progress → In Review | Linear's integration, when review is requested | | In Review → Done | Linear's integration, when the PR merges | | Anything → stuck | The script: a `needs-human` label and a comment | The middle two rows need a little setup. Out of the box, Linear moves an issue to In Progress when a pull request opens and to Done when it merges. In Review isn't in the default workflow at all. If you want it, add the status and map the "review requested" event to it in the team's pull request automations—and make sure something actually requests a review. The script never sets Done. There's no code path for it, which is the cheapest way I know to keep that rule from getting refactored away six weeks from now. To make the integration do its half, the pull request body ends with a closing magic word—`Fixes ENG-123`. The branch name already links the pull request to the issue, but the closing word is what guarantees the merge applies the Done status. (The softer words, like `Refs` or `Part of`, link the issue without ever closing it. That's handy when one issue takes several pull requests.) When the agent reports `blocked`, or my checks fail, the script adds the label, leaves a comment with the agent's summary, the model and effort it ran at, and where the logs are. If there's no pull request yet, it also moves the issue back to Todo. If there is one, the issue stays put, because re-claiming it would reset the branch out from under an open pull request. Either way, the label keeps both the picker and the sweep away from it, and removing the label is the whole human action. Everything downstream of the stuck issue stays blocked, which is the blocking relations doing exactly their job. > [!WARNING] Don't cancel issues from a script > It's tempting to move a failed issue to Canceled. Linear's docs say that when you cancel an issue directly, it closes the open pull requests linked to it. They don't say whether an API call counts as "directly," and I'd rather not find out. A label is reversible. ## From pull request to merge Okay. The spicy part. First, the script decides whether the work is good, not the agent. After the agent reports `done`, the script runs the project's checks itself, and if they pass, it does the part the agent wasn't allowed to: ```typescript async function runChecks(run: Run): Promise { const { exitCode } = await $`bun run test`.cwd(run.worktree).env(agentEnv).nothrow(); return exitCode === 0; } async function commitAndPush(run: Run, message: string): Promise { const { worktree, branch } = run; await $`git -C ${worktree} add -A`; const changed = await $`git -C ${worktree} diff --cached --quiet origin/main`.nothrow(); if (changed.exitCode === 0) return false; // "done," but nothing changed const staged = await $`git -C ${worktree} diff --cached --quiet`.nothrow(); if (staged.exitCode !== 0) { const commit = await $`git -C ${worktree} commit -q -m ${message}`.nothrow(); if (commit.exitCode !== 0) return false; // a hook said no } const push = await $`git -C ${worktree} push -q -u origin ${branch}`.nothrow(); return push.exitCode === 0; // never forced: a rejected push goes to a human } async function openPullRequest(run: Run, result: AgentResult): Promise { const title = result.pull_request_title; const body = `${result.pull_request_body}\n\nFixes ${run.issue.identifier}`; const created = await $`gh pr create --base main --head ${run.branch} --title ${title} --body ${body}` .quiet() .nothrow(); if (created.exitCode !== 0) await needsHuman(run.issue, `gh pr create failed: ${created.stderr}`); } ``` `commitAndPush` compares against `origin/main` instead of just checking for staged files, because nothing on the Claude Code side truly stops the agent from committing on its own. If it did, the work still ships. Now the merge itself. I have to be straight with y'all, because [the course version of this](/courses/agentic-engineering-playbook/the-ralph-loop) says—in so many words—that a person decides what merges into `main`, and that a second-model reviewer is advisory. I still believe that. So the loop has two modes. The default is the boring one, and the other one is me knowingly coloring outside my own lines. `MERGE_MODE=human`. The loop gets each pull request green and then leaves it alone. I merge. And here's why that isn't as slow as it sounds: the loop is serial about _working_, not about _waiting_. A pull request sitting in review doesn't stop the loop from picking up the next issue that doesn't depend on it. Only the dependents wait. The idea is that I'd come back to a stack of green pull requests and a board that shows exactly which issues are waiting on me. `MERGE_MODE=auto`. The loop still never merges. What it does, during the sweep at the top of a later pass, is arm GitHub's auto-merge and let GitHub do it when the repository's own rules are satisfied: ```typescript async function armMerge(url: string): Promise { const view: { mergeStateStatus: string; headRefOid: string } = await $`gh pr view ${url} --json mergeStateStatus,headRefOid`.json(); switch (view.mergeStateStatus) { case 'BLOCKED': break; // something is guarding it: arm case 'CLEAN': case 'HAS_HOOKS': case 'UNSTABLE': console.error( `Refusing to arm ${url}: nothing is blocking it, so --auto would merge right now.`, ); return false; default: console.error(`Not arming ${url} yet: merge state is ${view.mergeStateStatus}.`); return false; } await $`gh pr merge ${url} --auto --squash --match-head-commit ${view.headRefOid}`; return true; } ``` That `switch` is there because of a detail in how `gh pr merge --auto` behaves that I think is really easy to get hurt by. The flag sounds like "merge when the requirements are met." But if there are no requirements—no branch protection, no ruleset—then they're already met, and `--auto` merges _right now_. It'll even do that with non-required checks failing. So the script only arms a pull request that GitHub says is currently blocked by something. Anything else either waits for a later pass (GitHub reports `UNKNOWN` for a bit after a push while it works out mergeability) or stops and tells me. `BLOCKED` tells you there's a gate, though, not which one. The real merge gate isn't in my script at all. It's in the repository settings: - **Allow auto-merge**: in the general settings. Without it there's nothing for the script to arm. - **Required status checks**: CI has to pass. - **A required review**: GitHub won't let a pull request's author approve their own pull request, and the loop opens these as me, so the approval has to come from some other identity. If that's a teammate, you're still inside the course's rule. Both [Copilot](https://docs.github.com/en/copilot/how-tos/copilot-on-github/set-up-copilot/configure-code-review) and [Claude](https://code.claude.com/docs/en/approvals) have opt-in settings that let a bot's approval count (Claude's is a Team and Enterprise beta). The moment you flip one of those on, there's no human gate left. That's your call, not mine. Just make it on purpose. - **Conversation resolution**: review comments can't be ignored. - **No bypass for admins**: by default, branch protection doesn't apply to administrators, and the loop is running as you. If you've read [the post about getting a second opinion from Codex](/writing/codex-as-a-second-opinion), you can guess where I'd go with the reviewer: a different model family from the one that wrote the code. Claude builds, Codex reviews, or the other way around. Just know that most of the review bots don't produce a verdict a script can read off a status check. They leave comments. So "wait for the reviewer" in practice means "wait until there are no unresolved threads—and don't mistake a stale change request for new feedback." ### When the pull request needs work That's what the sweep at the top of every pass is for. Before picking anything new, the script looks at the pull request for every issue in a `started`-type status—In Progress or In Review: ```typescript const REVIEW_THREADS = /* GraphQL */ ` query ($owner: String!, $name: String!, $branch: String!, $after: String) { repository(owner: $owner, name: $name) { pullRequests(headRefName: $branch, states: OPEN, first: 1) { nodes { headRefOid latestReviews(first: 100) { pageInfo { hasNextPage endCursor } nodes { state commit { oid } } } reviewThreads(first: 100, after: $after) { pageInfo { hasNextPage endCursor } nodes { isResolved comments(last: 1) { nodes { body } } } } } } } } `; type PullRequestReview = { state: string; commit: { oid: string } | null }; type ReviewThread = { isResolved: boolean; comments: { nodes: { body: string }[] } }; type PullRequestReviewPage = { headRefOid: string; latestReviews: Connection; reviewThreads: Connection; }; type ReviewQuery = { data: { repository: { pullRequests: { nodes: PullRequestReviewPage[] } } } }; async function fetchReviewPage( branch: string, after: string | null, ): Promise { const fields = ['-F', 'owner={owner}', '-F', 'name={repo}', '-f', `branch=${branch}`]; if (after) fields.push('-F', `after=${after}`); const response: ReviewQuery = await $`gh api graphql ${fields} -f query=${REVIEW_THREADS}`.json(); return response.data.repository.pullRequests.nodes[0]; } async function needsAttention(branch: string): Promise { // --json exits 0 when checks fail. "No checks reported" (CI hasn't started) still exits 1. const checksRun = await $`gh pr checks ${branch} --json bucket`.quiet().nothrow(); const checks: { bucket: string }[] = checksRun.exitCode === 0 ? checksRun.json() : []; const firstPage = await fetchReviewPage(branch, null); if (!firstPage) return checks.some(({ bucket }) => bucket === 'fail'); const threads: ReviewThread[] = []; let page = firstPage; let after: string | null = null; do { if (page.headRefOid !== firstPage.headRefOid) return true; threads.push(...page.reviewThreads.nodes); after = nextCursor(page.reviewThreads.pageInfo); if (after) { const nextPage = await fetchReviewPage(branch, after); if (!nextPage) return true; page = nextPage; } } while (after); const unanswered = threads.filter( (thread) => !thread.isResolved && !(thread.comments.nodes[0]?.body ?? '').startsWith('fix-pass:'), ); const changeRequestOnCurrentHead = page.latestReviews.nodes.some( (review) => review.state === 'CHANGES_REQUESTED' && review.commit?.oid === page.headRefOid, ); const reviewListIsTruncated = page.latestReviews.pageInfo.hasNextPage; if (reviewListIsTruncated) { console.error(`Review history for ${branch} exceeds one page; leaving it for a human.`); } return ( checks.some(({ bucket }) => bucket === 'fail') || unanswered.length > 0 || changeRequestOnCurrentHead || reviewListIsTruncated ); } ``` If a pull request needs attention, that _is_ this pass's one thing. The script gathers the failing check output and the unresolved comments into a file, and calls the same `runAgent` against the same worktree, passing a fix-pass prompt in place of `PROMPT.md`: here's the feedback, fix it, don't do anything else. Then it calls `commitAndPush` with a message that starts with `fix-pass:`—no new pull request. What it doesn't do is resolve the threads. I just told you conversation resolution is one of the gates, and a loop that resolves its own review comments has quietly removed it. So the script replies on each thread it handed over with `fix-pass:` and the SHA of the fix, and leaves the resolving to whoever left the comment. That last-comment check in `needsAttention` is what keeps the next sweep from picking the same threads up again. If the reviewer isn't satisfied and says so, their reply becomes the last comment and the thread is live again. There's a second bit of state to watch: GitHub can leave the pull request's review decision at `CHANGES_REQUESTED` after the agent pushes a fix. Each latest review carries the commit it reviewed as `commit.oid` in [GitHub's GraphQL pull request review data](https://docs.github.com/en/graphql/reference/pulls). The sweep compares that value with `headRefOid` and only starts another fix pass when the change request is for the current head. After a fix pass, an old request waits for the reviewer to take another look. If either the review thread list or the latest-review list is incomplete, the script leaves the pull request for a human instead of treating a partial response as settled. One guard on all of that: `fixPass` notes `HEAD` before the agent runs. If `HEAD` hasn't moved afterward, nothing was fixed, so nothing gets a reply and the issue goes straight to `needs-human`. (Yes, this means that in auto mode with a bot reviewer, somebody still has to click "Resolve" before GitHub will merge. I think that's annoying and also the entire point.) Fresh context, again. The agent that addresses the review has never seen the conversation that produced the code. It reads the diff and the comments cold, which is closer to how a human would do it anyway. I'd cap that at three rounds per pull request, counted from the `fix-pass:` commits on the branch so there's still no state file. If three fresh attempts can't get it green, a fourth isn't going to, and the issue gets its `needs-human` label. The sweep has one more case: an issue that's In Progress with no open pull request and no run going. That's an orphan from a pass that died—or ran out of quota—halfway through. It goes back to Todo, and `startIssue` cleans up after it the next time it's picked. If that earlier attempt had already pushed its branch, the fresh push gets rejected, and the issue lands on `needs-human` instead. The script never force-pushes. Deciding which version of a branch wins is a human job. And that's every piece. The one line I haven't shown is the one that starts it all, and it has to be the very last line of the file. Everything above it is a `function` or a `const`, and `main` reaches for those `const`s on its first pass, so they need to exist by the time it runs: ```typescript if (import.meta.main) process.exit(await main()); ``` ## Claude Code versus Codex On paper, both of these can run this loop. Here's where I'd expect each one to make the job easier or harder: | | Claude Code | Codex | | --------------------- | --------------------------------------------- | ---------------------------------------------------- | | Fresh context per run | `claude -p` | `codex exec` | | Model and effort | `--model`, `--effort` | `--model`, `-c model_reasoning_effort=...` | | Structured result | `--json-schema`, inline in the result | `--output-schema`, written to a file | | Per-run spend cap | `--max-budget-usd` | None | | Guardrail | Rules plus a classifier; OS sandbox is opt-in | OS sandbox by default; `.git` read-only, network off | | Limits, before a run | Nothing scriptable | `account/rateLimits/read` | | Limits, during a run | Retry watchdog waits it out | The turn in flight finishes; the next run exits `1` | | Failure detail | Result subtypes, `permission_denials` | Exit `1` and a message string | If I had to compress that table: Claude Code is the better-instrumented process, and Codex is the better-fenced one. Claude tells you _why_ a run ended, caps what it spends, and will wait out a five-hour limit. Codex tells you almost nothing—the usage-limit message has a curly apostrophe and a local-time reset in it, which tells you everything about how much it wants to be parsed—but its sandbox enforces the division of labor without my having to ask, and it's the only one of the two that will answer "how much do I have left?" before you spend any of it. And the unique advantage of having both? You have two sets of limits. I said in the worker post that sometimes the whole reason I delegate to Codex is to spread the five-hour and weekly limits around. Still true. `AGENT` is just a variable, so the loop can build with one and review with the other, or run on one until it's out and then flip. If you want the flip, set Claude's usage-limit wait to a minute instead of five hours. Then a limit is a fast failure the script can react to. The five-hour wait is for when Claude Code is the only one you've got. ## Where this would hurt I haven't run this in anger yet, so take this as the list of places I'd _expect_ to bleed. **Your issues have to be good enough for a stranger**: a fresh agent knows what's in the issue and what's in the repository. That's it. Every acceptance criterion that lives in your head is one the agent will cheerfully not meet. The `blocked` status helps, but the real fix is upstream: write the issue for someone who wasn't in the planning meeting. **A dependency chain moves at the speed of its merges**: if A blocks B blocks C, the loop can't start B until A is on `main`. In human mode, that's the speed of my review. I'd pay that every time over letting agents stack work on unmerged branches—but plan your blocking relations knowing it. Wide and shallow beats long and thin. **An issue description is input you don't fully control**: anyone who can edit an issue in that project can put instructions in front of your agent. That's the real reason for the stingy job description up top. But be honest about where the fence actually is. `runChecks` executes whatever the agent just wrote—tests, package scripts, configuration—on my machine. Leaving the tokens out of `agentEnv` doesn't hide my `gh` login from it. The strict version runs the checks in a container or leaves them to CI entirely. And the agent writes the pull request body, so a body that says `Fixes ENG-200` closes ENG-200 on merge; I'd strip any magic-word lines the script didn't add. **`main` keeps moving**: every merge can leave the other open pull requests behind or in conflict. `gh pr update-branch` handles the easy case. A real conflict is a fix pass, and sometimes it's a `needs-human`. **You're still on the hook for the governor**: the pass cap, the stop file, the exit codes, and the `timeout` on each agent run don't come for free from either tool. I made the case for the iteration cap in [the original post](/writing/the-ralph-loop), and [the course version](/courses/agentic-engineering-playbook/the-ralph-loop) covers the rest. None of it is less true with a nicer task list. ## Same loop, bigger plan file Strip away the flags and this is the same loop it always was. The only real change is that the plan file grew up. It's a tracker now, with a dependency graph and a status the rest of your team can see, and the loop reads it instead of a checklist. The important design choice is where the lines go. The agent gets one issue and a checkout. The script owns every decision that should be deterministic and every action that can't be undone. And the merge—the one thing in the whole pipeline that's truly irreversible—belongs to the repository's own rules. That's the one layer I'd never let the agent or my script argue with. Ralph can absolutely work the backlog. He just doesn't get the keys.