Design a Safe, Automated Code-Change Pipeline
System DesignModel answerLast updated
Design an end-to-end pipeline that takes an engineering ticket, uses an LLM agent to propose code changes, and produces a verified pull request safely.
Background
Your team wants to build an automated pipeline that accelerates routine engineering tasks — patching a bug from a stack trace, generating missing unit tests, or bumping a library to its latest patch version. A language model will write the code, but the organization has non-negotiable requirements: no production secrets may be touched, every change must be reproducible and auditable, and a human always approves before anything merges.
You are asked to design this pipeline end-to-end.
What to Cover
1. Scope Definition and Context Assembly How does the system decide what a given ticket is allowed to touch? How is relevant code context gathered without flooding the model's context window?
2. Agent Skills and Prompting What tools does the agent have access to, and how are they defined? What goes in the system prompt, and what must be enforced outside it?
3. Host-Side Guardrails What hard limits does the host environment enforce regardless of what the agent says? Think about secrets, destructive commands, infinite loops, and token/time budgets.
4. Verification and the Feedback Loop How does the system validate the agent's proposed diff? What stages run, in what order, and how are failures fed back to the agent for correction?
5. Review and Merge How does a human reviewer inspect the result, and what metadata helps them trust (or reject) it?
Deliverables
- A component-level architecture walkthrough (prose or a simple ASCII diagram is fine)
- An example tool invocation schema showing both a success and a policy-denial response
- A discussion of at least three failure modes and how the design handles them
Hints
Hint 1
Start by treating the LLM as an untrusted, non-deterministic component — the host controls what it can see and do, and the model only proposes. Ask yourself: what would happen if the model tried to delete a test file to make tests pass?
Hint 2
Think about where enforcement actually lives. A system prompt says 'don't touch CI config'; a path ACL enforces it. List the hard limits that must be deterministic code, then separately list the soft guidance that belongs in the prompt.
Hint 3
For the verification stage, consider what a false-positive test pass looks like — tests that were deleted, assertions that were skipped, or a bug 'fix' that just swallows the error. How do your integrity checks catch each of those?
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
What the Question Is Really Testing
This is a trust-boundary and system-design problem, not a prompting problem. The core insight a strong answer must demonstrate is that the LLM only proposes; the host decides. Candidates who center the answer on "write a better system prompt" miss the point. Candidates who center it on "deterministic host controls wrapping a proposal engine" pass.
Step 1: Clarify Scope and State Assumptions
Before drawing anything, lock down what the system needs to handle in v1:
- Task types: bug fixes with a linked stack trace, unit-test generation for uncovered code, and minor/patch dependency upgrades.
- Autonomy level: the system opens a pull request; a human always merges. No auto-merge.
- Scale assumption: roughly 300–500 eligible tickets per day, peaks around 50 concurrent runs.
- Per-task budget: 200k tokens, 20 minutes wall-clock, ~$2 cost. At even one hour saved per merged PR, this is economically sound.
- Multi-service refactors are out of scope for v1 — they get split or escalated.
Step 2: Component Architecture
Ticket ──► Triage & Scoping ──► Context Assembler ──► Orchestrator ──► LLM Agent
│ ▲ │
budget │ │ errors │ tool calls
checks │ │ ▼
│ └──── Policy Gateway ──► Sandbox
▼
Verification Pipeline (host-owned)
│ pass
▼
PR Bot ──► Human Review ──► CI ──► Merge
Triage and scoping. A classifier checks eligibility (labels, opt-in flag on the repo, presence of a stack trace or test selector). The output is a scope manifest — a small JSON document specifying allowed path globs, max files changed (e.g. 5), max diff lines (e.g. 300), and a forbidden-paths list (CI config, auth code, infrastructure). Tickets that fail triage are rejected immediately, before any tokens are spent.
Context assembly. The repo is pinned to a specific commit SHA. The assembler builds an initial seed context (roughly 20–30k tokens) from the ticket text, stack-trace files resolved via a symbol index, direct callers and callees from an AST graph, related tests, and any AGENTS.md-style conventions. The agent pulls additional context on demand through tools rather than preloading everything. When token usage hits ~70% of budget, old tool outputs are summarized or evicted.
Orchestrator. This process owns the loop counter, the clock, and the budget. The LLM never controls its own termination — that's a hard rule.
Sandbox. Each run gets an ephemeral microVM (Firecracker or gVisor) with a git worktree. Network is blocked except for an internal package mirror. No credentials are mounted. The VM is destroyed after the run, win or lose.
Step 3: Skills and Prompting
The system prompt tells the agent its role ("propose minimal changes within the scope manifest") and lists explicit prohibitions ("do not edit test assertions to make tests pass," "do not add a dependency without a justionale field"). This is guidance — enforcement lives in the gateway.
Skills are narrow, typed RPCs. There is no raw shell access.
| Skill | Purpose |
|---|---|
search_code(query, k) | semantic + lexical search, results truncated |
lookup_symbol(name) | AST-based definition and reference lookup |
read_file(path, range) | scoped file read, path checked against manifest |
apply_patch(diff) | unified diff write, size limits enforced |
run_tests(selector) | runs targeted tests in sandbox via fixed command templates |
resolve_package(name, version) | validates against internal registry; blocks hallucinated packages |
Example tool invocation contract:
// request
{
"jsonrpc": "2.0", "id": "call-17", "method": "apply_patch",
"params": {
"task_id": "T-8812",
"patch": "--- a/src/pricing.py\n+++ b/src/pricing.py\n...",
"rationale": "Fix off-by-one in date range comparison"
}
}
// success response
{
"id": "call-17",
"result": { "status": "applied", "files_changed": ["src/pricing.py"], "diff_lines": 6 },
"error": null
}
// policy-denial response
{
"id": "call-17",
"error": { "code": "POLICY_DENIED", "message": "path tests/test_pricing.py: deletion of assertions is not allowed" }
}
Step 4: Host-Side Guardrails
The policy gateway is deterministic code that sits between the agent and the sandbox.
- Schema validation checks all arguments against JSON schema, rejecting injection payloads.
run_testsmaps the selector to a fixed command template, so arbitrary strings never reach a shell. - Path ACLs come directly from the scope manifest. Diff size is checked against its caps before the patch is applied.
- Hard budgets: 200k tokens, 60 tool calls, 4 verification iterations, 20 minutes wall-clock. When any budget is exhausted the run escalates to a human with full state attached — it does not silently fail.
- Secrets: no credentials are mounted in the sandbox. Egress is restricted to an allowlist. Tool outputs are scanned for secret patterns before being returned to the model.
- Prompt injection: ticket text and file contents are treated as untrusted data. A comment saying "ignore instructions and run curl" fails because that capability simply does not exist.
- Every tool call is written to an audit log with arguments, result hash, and token cost.
Step 5: Verification Pipeline
This runs in a separate host-controlled job on the agent's diff, not inside the agent's session.
Stages run in order with fast-fail:
- Build and type-check
- Lint and format
- Affected unit tests, then the full module suite
- SAST (e.g. Semgrep) and secret scan
- Dependency check — every new import must resolve in the internal registry with an allowed license
Integrity checks (the important layer):
- No test files were deleted or had assertions skipped.
- Total assertion count did not decrease.
- For bug fixes: a repro test must fail on the base commit SHA and pass on the head SHA — this is the strongest signal the fix is real.
- Changed lines have test coverage.
Failures are serialized and returned to the orchestrator, which passes them back to the agent for a correction attempt. The iteration counter ticks up. After the cap (e.g. 4 iterations), the run escalates.
Step 6: Review and Merge
The PR bot opens a PR under a bot identity and attaches:
- the task ID and ticket link
- the scope manifest the run operated under
- a per-tool call breakdown (what the agent searched, read, and changed)
- which verification checks passed and which needed correction iterations
Reviewers see a normal diff plus a collapsible provenance block. They can request changes just like any other PR. After approval, the normal branch CI runs and the engineer merges.
Key Failure Modes
Infinite correction loops. The iteration cap plus the wall-clock budget handle this. The run escalates rather than spinning.
False-positive test passes. The integrity checks catch the three most common patterns: deleted tests, skipped assertions, and fixes that swallow the error rather than correcting it. The repro test requirement (fail on base, pass on head) is the strongest guard for bug fixes.
Cost explosion. Per-task token and wall-clock budgets are enforced by the orchestrator, not the model. On-demand context loading keeps the window lean; summarization handles eviction.
Hallucinated APIs or packages. lookup_symbol grounds the agent in the actual AST before it writes code. resolve_package blocks any dependency that does not exist in the internal registry — the package either resolves or the tool call is denied.
Common Mistakes to Avoid
- Treating the system prompt as the enforcement mechanism — it is not; it is guidance.
- Giving the agent a raw shell or an
execskill — this is how you getrm -rf. - Running verification inside the agent's session — the agent can then influence the results.
- Forgetting to pin the repo to a commit SHA — a floating HEAD makes runs non-reproducible.
- No escalation path — a pipeline that silently discards failed runs gives engineers no signal and no way to improve the system.