Suryanand/ Bootcamp
suryanand.com ↗Let's talk
← AI system designAI guideAdvanced#system-design#coding-agents#indexing#sandboxes
Frame · ai-engineering / case-studies / 04-ai-coding-assistant.mdGuide 095 / 103

Design an AI coding assistant

Coding assistants have moved from autocomplete to agents that read a repo, edit many files, run tests, and open a pull request. If you get this question in an interview, the interviewer wants to hear three things: how you get the right code into a limited context window, how you turn model output into correct file edits, and how you let an agent run commands without letting it break anything. I'll cover an IDE assistant with a cloud agent mode, since that is where products like Cursor, GitHub Copilot and Codex have converged.

Requirements

Functional

  • Inline completions as you type.
  • Chat about the codebase ("where is auth handled?") with answers that cite files.
  • Agent mode: given a task, plan, edit multiple files, run tests and commands, iterate, and present a diff or PR.
  • Background agents that run in the cloud on a branch while the developer keeps working.

Non-functional

  • Completions need very low latency (a few hundred ms) or they are useless.
  • Code privacy: customers may require zero retention and no training on their code.
  • Indexes stay fresh as files change, without re-uploading the repo.
  • Agent commands run isolated, with controlled network access and no access to production secrets.

Scale estimates (assumptions)

QuantityAssumptionResult
Active developers1M
Completion requests1,000 per dev per day1B/day, about 35,000/s at peak
Repo size20,000 files average, 500 chunks per 1,000 filesabout 10,000 chunks per repo
Agent tasks5 per dev per day5M sandboxed sessions/day
Agent session length10 minutes averageabout 35,000 concurrent sandboxes at average load

Completions dominate request volume (small model, tiny prompts). Agents dominate cost and infrastructure complexity (big model, long contexts, containers).

High-level architecture

Rendering diagram…

Request flow

Rendering diagram…

Components

ComponentResponsibilityNotes
Index syncDetect changed files and upload only thoseMerkle tree of file hashes, compared with server copy
AST chunkerSplit code at function or class boundariestree-sitter grammars cover most languages
Embedding serviceEmbed chunks; cache by content hashUnchanged chunks never re-embed
Vector indexPer-repo or per-tenant namespaceStore obfuscated paths and line ranges, not raw code, if privacy requires
Symbol graphDefinitions, references, importsPowers "go to definition" style retrieval and repo maps
Completion serviceFill-in-the-middle completionsSmall model, speculative decoding, aggressive caching
Agent orchestratorTool loop, budgets, checkpointsTracks token, time and command budgets per task
Sandbox fleetIsolated containers or microVMsTwo phases: setup with network, agent phase restricted

Data model

CREATE TABLE repo_index (
  repo_id        TEXT,
  user_or_team   TEXT,
  root_hash      TEXT,          -- Merkle root of last synced tree
  embedding_model TEXT,
  updated_at     TIMESTAMPTZ,
  PRIMARY KEY (repo_id, user_or_team)
);

CREATE TABLE chunks (
  chunk_hash     TEXT PRIMARY KEY,   -- hash of chunk content
  embedding      VECTOR(1024)
);

CREATE TABLE file_chunks (
  repo_id        TEXT,
  path_token     TEXT,          -- obfuscated path
  chunk_hash     TEXT,
  start_line     INT,
  end_line       INT
);

CREATE TABLE agent_tasks (
  id             UUID PRIMARY KEY,
  repo_id        TEXT,
  branch         TEXT,
  status         TEXT,          -- queued | running | needs_input | done | failed
  sandbox_id     TEXT,
  tokens_used    BIGINT,
  commands_run   INT
);

Keying embeddings by content hash means two developers on the same repo share most embeddings, and a branch switch only embeds what is new.

Deep dives

Incremental indexing with a Merkle tree

Cursor has written publicly about this approach. The client hashes every file, folder hashes are derived from their children, and the root hash summarizes the repo. On sync, the client and server compare hashes top-down and only descend into subtrees that differ, so a one-file edit uploads one file's chunks. Files in .gitignore and a separate ignore file never leave the machine. Embeddings are cached by chunk content, so reformatting a file that does not change chunk text costs nothing.

Context assembly

Embeddings alone are not enough for code. The context engine blends several signals:

  • Lexical search (ripgrep style) for exact identifiers and error strings. Agents use this heavily as a tool.
  • Semantic search for "where do we validate JWTs" style questions.
  • Symbol graph to pull in definitions of types and functions referenced by the code being edited. Aider's repo map builds this with tree-sitter and ranks files with PageRank over references.
  • Recency and proximity: open tabs, recently edited files, the file's tests.

In agent mode, I lean toward giving the model search tools and letting it explore rather than pre-stuffing context. Modern models are good at grep-read-edit loops, and it avoids filling the window with irrelevant chunks.

Applying edits

Asking the model to rewrite whole files is slow and error prone for large files. The common formats are:

Edit formatHow it worksTrade-off
Whole fileModel outputs the entire new fileSimple, expensive for big files
Search and replaceModel outputs exact old snippet and new snippetCompact; fails if old snippet does not match exactly
Unified diffModel outputs a patchModels get line numbers wrong; needs fuzzy apply
Fast apply modelBig model sketches change, small model merges into fileExtra hop, very robust

Whichever you choose, validate after applying: does the file parse, does the linter pass, does the type checker pass. Feed errors straight back into the loop.

Sandboxing agent execution

Agents run arbitrary commands, so isolation is non-negotiable. Use containers with a hardened runtime (gVisor) or microVMs (Firecracker) per task. OpenAI's Codex docs describe a pattern I like: a setup phase with network access to install dependencies, then the agent phase offline by default, with an optional domain allowlist, and secrets available only during setup. Snapshot the container after setup so the next task on the same repo starts warm. Enforce CPU, memory, disk and wall-clock limits, and kill anything that tries to reach cloud metadata endpoints.

Completions latency

Fill-in-the-middle completions use a small model with the prefix and suffix around the cursor plus a few snippets from related files. Tricks: debounce keystrokes, cancel in-flight requests when the user keeps typing, cache by prefix, and use speculative decoding. A completion that arrives after the developer typed the line is pure cost.

Trade-offs and pitfalls

  • Index freshness vs cost. Real-time indexing on every keystroke wastes embedding calls. Sync on save or on a short interval.
  • Privacy claims. If you promise not to store code, embeddings and caches count too. Some providers store only embeddings with obfuscated paths and fetch code from the client at query time.
  • Agents grading themselves. An agent that writes the tests it then passes can "succeed" with a broken change. Run the repo's existing tests and show the diff for human review.
  • Runaway loops. Cap iterations, tokens and wall time per task, and surface "needs input" instead of thrashing.
  • Prompt injection from repos. A README or dependency can contain instructions. Restricted network and no production credentials limit the blast radius.
  • Monorepos. Index size and per-query filtering by subdirectory matter; let users scope the agent to a package.

Checklist

  • Indexing is incremental (Merkle tree diff) and embeddings are cached by content hash.
  • Retrieval mixes lexical, semantic and symbol-graph signals, with search exposed as agent tools.
  • Edits use a robust format and are validated by parser, linter and tests.
  • Agents run in isolated sandboxes with setup and agent phases and restricted network.
  • Budgets on tokens, time and commands; tasks can pause for input.
  • Completions meet a strict latency budget with cancellation and caching.
  • Privacy policy covers code, embeddings, logs and caches.

Further reading

Why this exists README

I learn best by explaining things, so I record the explanations. Everything here is free, with no sign-up. If a lesson helps you ship something, I'd love to hear about it.