Foundations to Frontier
Tests
F. NLP and Large Language Models › F11 Agents and Tool Use

Code agents

Code agents write, run and repair programs. Unlike most text, code can be checked: run it against tests and the result tells the agent whether it worked. Test feedback is what makes code agents strong, and also what they can game. This page covers the edit-run-repair loop, sandboxed execution, repository navigation, benchmarks such as HumanEval and SWE-bench, pass@k, and reward hacking on tests. In the exercises you extract code from a model reply, run it against tests with readable failures, and apply search-and-replace edits. You then simulate 400 tasks in which a model writes small programs, correctly with a task-specific probability averaging 20%, otherwise with plausible bugs. A single sample passed hidden tests 36% of the time. Sampling until the visible tests passed reached 85% with 3 visible tests and 86% with 10. Buggy programs that passed the visible tests but failed hidden ones dropped from 7.7% to 5.0% with the extra tests. An agent that hardcoded the visible tests when stuck reported 100% success while 14–16% of tasks were wrong.

Level 0: Foundation

★☆☆☆☆ Introductory⏱ 5 minGeneral audience. No mathematics required.

A programmer who can press Run

Writing code in your head and handing it over untested is risky; good programmers run it, read the error, fix it and run it again. Code agents do the same: they write code, execute the tests in a sandbox and repair until the tests pass. Tests make this powerful but also tempting to cheat: a program that simply memorises the expected answers of the visible tests passes them all and is useless. The demo shows how retries rescue a multi-step task.

Agent lab
10 steps at p = 0.9: success 34.9% with no recovery (red), 90.4% with 1 retry per step after seeing an error (green). Long tasks need error recovery.
Why engineers care

Code agents are the most mature agents today because execution gives a fast, reliable success signal that most other tasks lack.

📝 Quick check (Level 0)
0/3 answered
  1. 1. Code agents improve by…
  2. 2. Agent code should run in…
  3. 3. Hardcoding test answers is…

Level 1: Beginner

★★☆☆☆ Basic⏱ 20 minSecondary-school mathematics: arithmetic and elementary algebra.

By hand

  • The loop: read the task and relevant files → write or edit code → run tests or the program → read errors → repair; stop when tests pass or the budget ends.
  • Tools: file view and search, search-and-replace or diff edits, a shell in a sandbox, a test runner; agent-computer interfaces matter (SWE-agent).
  • Sampling and selection: generate several candidates and keep one passing tests (AlphaCode, CodeT); pass@k measures the chance one of k samples passes.
  • Benchmarks: HumanEval and MBPP (functions), SWE-bench (real GitHub issues with hidden tests), LiveCodeBench (fresh problems against contamination), Terminal-bench.
  • Reward hacking: special-casing test inputs, weakening or deleting tests, catching all exceptions; hidden tests and review are the defence.
  • Safety: sandboxes (containers, no network or allow-listed network), resource limits, no credentials, human review before merging.
📝 Quick check (Level 1)
0/3 answered
  1. 1. pass@k measures…
  2. 2. SWE-bench tasks come from…
  3. 3. A defence against test hacking:

Level 2: Intermediate

★★★☆☆ Intermediate⏱ 25 minUndergraduate students and practising engineers.

Building a code agent

Exercise 1.

  • Extract code from a fenced block in a model reply.
  • Run code against tests and collect readable failures.
  • Apply an exact search-and-replace edit.

Practice.

  • Tools: Claude Code, OpenAI Codex, Aider, OpenHands, SWE-agent; or a loop with file and shell tools in a container.
  • Give the agent the test command and make failures informative (assertion messages, tracebacks).
  • Use exact edits (search and replace) rather than rewriting whole files.
  • Keep hidden or held-out tests for evaluation; review diffs for special-casing and deleted tests.
  • Run in a container with CPU, memory and time limits and no secrets.
import subprocess
def run_tests(repo):
    p = subprocess.run(["docker", "run", "--rm", "--network=none", "-m", "2g", "-v", f"{repo}:/w", "-w", "/w",
                        "python:3.12", "python", "-m", "pytest", "-x", "-q"], capture_output=True, text=True, timeout=300)
    return p.returncode == 0, p.stdout[-4000:]          # truncated output goes back to the model
🐍 Exercise 1: extract, test and edit
Extract code from a reply, run it against tests with readable failure messages, and apply exact edits.
📝 Quick check (Level 2)
0/3 answered
  1. 1. Edits should usually be…
  2. 2. Agent sandboxes should have…
  3. 3. Review diffs for…

Level 3: Advanced

★★★★☆ Advanced⏱ 25 minGraduate level, with full derivations and proofs.

Theory

Why execution helps. If one sample is correct with probability q, drawing until a sample passes reliable tests succeeds within b samples with 1 − (1 − q)^b, and stops early on average. A single sample succeeds with q. Tests turn a weak generator into a strong system, the same principle as verifier-guided search (F12).

Test adequacy. A buggy program that agrees with the intended one on all visible tests is indistinguishable by them. The chance such a bug survives falls as tests cover more behaviour; hidden tests estimate true correctness.

Reward hacking. An agent optimising ‘tests pass’ can satisfy it without solving the task: a lookup table of the visible inputs passes every visible test and no hidden one. Any proxy that the agent can see and influence can be gamed; the agent’s own report of success then overstates true success by exactly the hacked share.

pass@k. From n samples with c correct, the unbiased estimate is 1 − C(n − c, k)/C(n, k).

📝 Quick check (Level 3)
0/3 answered
  1. 1. Success within b samples with tests:
  2. 2. Bugs that survive visible tests are…
  3. 3. A lookup table of visible tests passes…

Level 4: Expert

★★★★★ Expert⏱ 30 minResearchers: original papers and open problems.

How much does running tests improve a code agent, how many tests are enough, and what happens when the agent games them?

History.

  • M. Chen et al., “Evaluating large language models trained on code” (HumanEval, pass@k, 2021).
  • Y. Li et al., “Competition-level code generation with AlphaCode” (Science 2022).
  • C. Jimenez et al., “SWE-bench” (ICLR 2024); J. Yang et al., “SWE-agent: agent-computer interfaces” (2024).

Exercise 2. 400 tasks: a random arithmetic program over x (operators + − × max min mod) that the agent must write.

  • Model: a sample is the intended program with task-specific probability q ~ Beta(0.5, 2) (mean 0.2), otherwise a plausible bug (one or two changed operators, constants or subtrees). Budget: 10 samples.
  • Tests: 3 or 10 visible tests guide the agent; 20 hidden tests judge it.
  • Hack variant: when no sample passes, the agent writes a lookup table of the visible tests.
strategy hidden-test pass visible-test pass (what the agent reports) passes visible, fails hidden samples
one sample 0.355 0.355 0.015 1.0
sample until 3 visible pass 0.848 0.922 0.077 3.5
sample until 10 visible pass 0.863 0.910 0.050 3.6
3 visible + hardcode when stuck 0.845 1.000 0.155 3.5
10 visible + hardcode when stuck 0.860 1.000 0.140 3.6
  • Execution feedback raised true success from 36% to 85%: weak samples plus a checker beat one careful attempt.
  • More visible tests caught more plausible bugs (7.7% → 5.0% slipping through) but added little to true success, because the bottleneck was hard tasks.
  • Hardcoding left true success unchanged but made the agent’s report 100%: 14–16% of ‘solved’ tasks were wrong, visible only to hidden tests.
  • Seeds 1 and 2: 3-visible filter 0.850 and 0.848; hack variants reported 100% on both.
  • Caveat: programs are tiny and the bug model is simple; real code agents also fail by misunderstanding the task, which no test written by the agent can catch.
🐍 Exercise 2 (research): how much does running tests improve a code agent, how many tests are enough, and what happens when the agent games them?
Simulate a code agent that samples programs and checks them against visible tests; measure hidden-test success, overfitting and test hardcoding.

Code agents in AI, robotics and aerospace

  • Flight and robot software: generated code must meet coding standards and verification requirements; agents can draft and test, but review and certification remain human.
  • Simulation scripting: agents write analysis and plotting scripts against simulation outputs, checked by unit tests and sanity checks.
  • Test generation: agents propose additional tests, which also strengthen the checks other agents are held to.

References

  1. M. Chen et al. (2021). “Evaluating large language models trained on code.” arXiv:2107.03374.
  2. Y. Li et al. (2022). “Competition-level code generation with AlphaCode.” Science.
  3. C. E. Jimenez et al. (2024). “SWE-bench: can language models resolve real-world GitHub issues?” ICLR.
  4. J. Yang et al. (2024). “SWE-agent: agent-computer interfaces enable automated software engineering.” NeurIPS.