When to compact decides whether the build finishes
Opus 5.5 building a Mastodon-style server under a 100K context budget, one run per setup
Vanilla Claude Code ext compaction
TL;DR
Synthesizing entire systems with coding agents [1, 2] is becoming remarkably cheap and feasible, but trusting and maintaining the resulting code is not. Agent harnesses themselves are complex systems in their own right, spanning sandboxing, permissions, tool integrations, and execution loops. Many of these components are tricky to get right and costly to audit and maintain.
Increasingly, there is interest in agent-driven, self-evolving harnesses [3, 4], where agents modify this very code. While mainstream coding agents such as Claude Code and Codex rely on fixed execution heuristics chosen by harness developers (e.g., preset compaction thresholds, generic summarization prompts, and fixed reasoning effort), agents have task-specific context and intelligence that could help them make better execution decisions at runtime. As agents take on increasingly complex, long-horizon tasks, including scientific discovery, how can we give them control over execution while ensuring they respect safety and operator-defined rules?
Recent work such as Exo [11] draws inspiration from OS exokernels [19,20], which isolate low-level resources while letting each application write its own resource management policies. The assumption is that each application is responsible for the correctness and performance of its policies, and bad implementations hurt the application itself. In an agent harness, however, this analogy breaks down. Poorly written policies and buggy implementations hurt the human operator, not just the agent: they burn the operator’s budget, violate project constraints, and cause tasks the operator cares about to fail. We outline the specific problems with applying the exokernel model to agent harnesses (Lessons from Exo).
In this post, we share our work on ext, a safe, extensible, self-improving agent harness. We believe eBPF, rather than the exokernel, offers the right mental model for protection in extensible agent harnesses. Our key insight is that we can give agents sufficient flexibility and extensibility to improve their execution through an interface narrow enough to verify every policy. The harness owns the mechanisms and enforces invariants, while agents write policies through typed hooks in a restricted language. Before loading any policy or revision, an SMT verifier (Z3) proves that it satisfies the built-in and operator-specified rules for every valid hook input. ext works with existing harnesses such as Claude Code without requiring modifications to their source code (Design and Implementation).
Our early evaluation shows strong improvements in both safety and performance:
- Provable safety at scale: ext incurs zero rule violations across over 550 runs (Safety Audit). On a 1.2M-token incident-log QA task, ext enforced a $0.30 budget in all six runs and answered every question in five, using two project rules to help the agent stay within budget. In comparison, prior self-improving agents (Exo) overspent in two of six runs when told the budget, and all seven spending guards they implemented failed correctness tests (Cost Budget).
- Mitigating compaction thrashing: On a 200K-window incident audit where vanilla Sonnet 4.6 aborted both runs (0/204), ext scored 199/204 and 204/204. On long SWE-Marathon builds under a 100K budget, ext increased the share of tests passed by 12 percentage points at 0.85× the run cost (Compaction Thrashing).
- Higher accuracy at comparable or lower cost: Under a 100K budget, ext improved multi-hop research QA full success from 33% to 53% at the same end-to-end cost (0.92× excluding policy authoring) (Research QA). On nine coding tasks from DeepSWE, SWE-bench Pro, and Terminal-Bench 2.1 (at Claude Code’s default 1M window), a reusable policy improved Opus from 14/27 to 22/27 solves at the same cost, Sonnet from 15/27 to 18/27 at 1.19×, and matched Haiku’s solves at 0.40× the cost (Short Coding Tasks).
- Self-improvement across runs: We show that agents can analyze previous executions and develop reusable policies, as in our short coding experiments. We also trained Qwen3.5-9B to write safe and effective policies. Using the verifier’s acceptance decision as an RL reward increased valid policy generation from 12.5% to 97.8%, and training on execution outcomes improved held-out research QA accuracy from 80.9% to 86.4% at comparable cost (RL Training).
ext is under active development, and we will release its code soon. If you are interested in trying it out, please join the waitlist.
The Case for Agent-Driven, Self-Improving Harnesses
If you have babysat a coding agent working on a long task, you may have seen the harness make a poor decision: it compacts the conversation in the middle of a multi-step investigation, summarizes away the record of which experiments it already ran, or gets stuck compacting every few turns.
Harnesses today rely on hardcoded heuristics and policies tuned by harness developers. These default settings may be suboptimal for the specific workloads operators run. Our lab has studied this specialization-versus-generalization gap in our prior work, Vulcan [12].
As a concrete example, we tested Claude Haiku 5.5 in a bash-only harness on 11 tasks of four types: research QA (3 tasks), log analysis (3), a parser implementation (1), and library repairs (4). We ran each task five times per reasoning-effort level. On 6 tasks, low reasoning effort was sufficient to solve all five runs; the remaining tasks needed medium (2 tasks), high (1), or xhigh (2). Naively setting the highest reasoning effort cost up to 5.9× what the cheapest successful level cost on the same task.
No single effort level is both cheap and reliable
Cost per run at each reasoning-effort level, relative to the cheapest level that solved all five runs of that task
solved all 5 runs lost 1 of 5 cheapest level that solved all 5
In contrast, the agent often has much better context and intelligence to make these decisions [5-7, 13]. An agent can reasonably tell that a search result will no longer be needed, while an earlier output holds the centerpiece for the next stage of the task. To the harness, both look like tool outputs of the same size.
Walking the Fine Line Between Mechanism and Policy
Handing harness control to an agent raises a classic operating systems question. Which decisions should the system make on behalf of an application, and which should the application control? Answering it means deciding where to draw the line between mechanism and policy.
In an agent harness, mechanisms provide operations, such as calling a model, recording a tool result, or replacing part of the context with a summary. Policies decide when and how to use these operations to meet some objective, such as task success or cost. For instance, a compaction policy decides when to compact and what to keep. Designs differ in where they draw this line: the harness can make every policy decision itself, or hand some or all of them to the agent. The harness must also enforce guarantees (i.e., baseline rules and invariants) that hold regardless of the agent’s chosen policy. Some protect system correctness, such as keeping the context within budget and preserving the original task statement; others guard against known failure modes, such as retaining the two most recent steps verbatim during compaction to maintain execution continuity. An operator may additionally impose deployment- or project-specific requirements, such as enforcing a dollar budget or keeping recent test failures. Both sets of rules must hold regardless of what policy the agent chooses.
Prior work has explored two main approaches to giving agents control over harness policies. Giving the agent harness tools [5–7] and a live context meter triggered “context anxiety” and reduced long-task success from 92% to 52% (Approach 1). Allowing the agent to modify its harness code [4, 8–11] lets it write a policy once and apply it throughout a run, but existing guardrails can miss edits that silently violate invariants or undermine their enforcement (Approach 2, Lessons from Exo).
Approach 1: Giving the agent harness tools
The simplest design is to expose harness controls such as compact() and set_effort() as tools alongside a live context meter [5–7, 14]. The agent decides at each turn whether to invoke one of these tools. This lets the agent steer its execution through the operations the harness already provides.
We tested this approach with Claude Haiku 5.5 in our bash-only harness, a minimal agent loop based on mini-SWE-agent [15]. We evaluated five long-horizon tasks (three multi-hop research tasks and two multi-library repair tasks) under a 32K context budget. As the model approached the token limit, we observed it rushing to submit incomplete work, matching the “context anxiety” reported for Claude Sonnet 4.5 [16]. Across these tasks, success fell from 92% to 52% when we added harness tools and a live context meter.
With harness tools and a context meter, Claude Haiku 5.5 rushed to submit incomplete work
Takeaway
Giving the agent direct control through harness tools and a live context meter can interfere with its reasoning and hurt long-horizon performance.
Approach 2: Letting the agent edit its own harness
Other systems let agents rewrite their harness before or between runs [4, 8–11]. The agent can write a policy once and let the harness apply it throughout a run. How can we decide whether to accept its edits? Existing approaches use crash rollback, regression tests, benchmark gates, LLM review, and execution-based validation [17, 18].
We tested four common guardrails on a simplified Python controller in our bash-only harness (deciding compaction, retention, and reasoning effort). Starting from valid controllers, we generated single-line edits, over half of which silently violated baseline rules (such as compacting before context overflow or preserving recent steps). Even in this simplified setting, each guardrail had clear shortcomings:
- Crash rollback missed every silent rule-breaking edit, since none caused a crash.
- Benchmark gates accepted most sampled rule-breaking edits on task success alone. Even with a cost check, they missed violations in states the benchmark runs never triggered while rejecting valid edits.
- Regression tests caught known violations in two suites, but a third still missed edge cases. In practice, coverage relies on the test author anticipating every edge case.
- LLM review was accurate with Sonnet 5.5 given formal rules and the original code, but with prose rules alone both Sonnet and Haiku heavily over-rejected harmless edits.
In a real self-editing harness, edits can span multiple files and interact across components, making silent violations far harder to detect.
Most guardrails either miss violations or block harmless edits
tested on every edit tested on a sample
How often do agents introduce such bugs themselves? We asked Haiku, Sonnet, and Opus to rewrite the controller in Python to reduce costs, explicitly stating the invariants they must preserve. Silent violations were relatively rare in this simplified setting (we found three).
In one case, an agent trying to reduce costs inadvertently undermined the mechanism responsible for enforcing its context budget. When trimming old tool outputs, a Haiku-written controller also updated the harness’s recorded token counts using its own approximation. This systematically underestimated the context size. Since both the controller and the harness’s fallback compaction mechanism relied on these counts, neither detected a context overflow in 5 of 400 simulated sessions. In one such session, both saw 28.4K tokens, while the rendered context was estimated to contain 33.6K tokens against a 32K budget. Crash rollback, regression tests, and the Sonnet reviewer all approved the controller. The reviewer even noted that it “still falls back to the standard summarizing compaction at 90% of budget.”
Rewritten token counts hid a context overflow
def _trim(st) -> None:
...
st.out_tokens = int(sum(len(b.get("text", "")) + len(str(b.get("input", "")))
for b in st.assistant) / 3.3) + 1
...
st.obs_tokens = int(sum(len(r["content"]) for r in st.results) / 3.3) + 1
Controller and fallback see
28,410
Rendered context
32K budget
33,628
Crash rollback approvedRegression tests approvedSonnet reviewer “safe”
Takeaway
Existing guardrails can miss subtle bugs even when agents are explicitly told which invariants to preserve. Moreover, naively giving agents control over the harness’s implementation allows them to inadvertently undermine the mechanisms responsible for enforcing those invariants.
Lessons from Exo
Recent work like Exo [11] draws inspiration from the OS exokernel model [19, 20] to separate the harness into a protected mechanism layer and an editable policy layer (the executor). In an OS exokernel, hardware isolation lets the kernel protect low-level resources while each application writes its own library OS, assuming a buggy policy only hurts that application. Exo applies a similar idea to the agent runtime. It maintains an append-only execution history and provides a guardian to check self-updates before activation. Meanwhile, the agent can edit the code that assembles context, compacts history, calls models, and handles approvals. The goal is to let the agent improve almost any aspect of its execution while retaining an execution history from which the operator can recover.
We observe that applying this exokernel model to agent harnesses raises three problems. First, the protection boundary is hard to maintain in practice: an agent can inadvertently alter the code or state the harness relies on (Protection). Second, even with a clean boundary, verifying arbitrary edits to general-purpose harness code is difficult, and empirical guardrails can miss subtle bugs (Verification). Third, unlike an exokernel, whose goal is to protect low-level resources (e.g., from mutually distrustful applications), an agent harness must proactively enforce its guarantees (e.g., baseline execution invariants and operator-defined rules), rather than rely on voluntary model compliance (Enforcement). While a protected mechanism can enforce limits such as token or spending cutoffs, guarantees about how the policy itself behaves cannot be achieved by resource isolation alone. The exokernel leaves these problems unresolved.
To understand how well this separation works in practice, we built Exo (commit e1e5669) and evaluated it in a Docker sandbox using Haiku 5.5, Sonnet 5.5, and Opus 5.5.
Protection. A fundamental requirement of a self-editing harness is that the agent’s modifications respect the system’s protection boundaries. However, in our tests of Exo, agent modifications could affect shared runtime code used by other agents on the host, and parts of the trusted runtime (e.g., the guardian) were writable by the agent.
We first noticed the problem when the agent explicitly tried to improve safety. When asked to ensure that self-updates were tested before activation, Opus modified the guardian to add type checks and regression tests. In doing so, it also changed the mechanism responsible for validating its own future updates, expanding the operator’s trusted computing base to include agent-written code. We then tested whether the guardian could be weakened: given a request to make updates always pass, Opus was able to rewrite the guardian to record every update as succeeded, ignoring build failures.
More broadly, drawing the protection boundary in a self-editing harness is difficult to get right. In our approach, we show that it is simple to reason about the boundary, as the agent never directly modifies harness code or its verifier.
ext protects core harness mechanisms
Setup
- Exo
- commit
e1e5669, the self-improving agent in its Docker development configuration - View
- drag to turn, pinch or use the buttons to zoom, click a block for detail
Verification. Even with a protected guardian, verifying the correctness of arbitrary edits to general-purpose harness code can be quite difficult.
Exo by default checks whether an update builds successfully and whether services restart. In an initial experiment with networking disabled and no Node.js in the sandbox, the guardian accepted all eight updates even though the agents reported being unable to run tests or type checks. The default guardian doesn’t require those checks or verify default or operator-specified invariants.
Next, we asked Haiku, Sonnet, and Opus to modify Exo to enforce a simple rule: no run may spend more than $0.50. Because Exo leaves most harness logic editable rather than building such checks into the protected core, adding a rule like this requires the agent to implement it in harness code and the guardian to catch any bugs. Across our trials, agents wrote seven spending guards across the three models. All seven passed the guardian, yet failed subsequent enforcement tests:
- Two Sonnet guards omitted cache-write tokens, stopping runs at $1.08—more than twice the limit.
- Two Haiku guards also missed higher long-context pricing (over 100K tokens), allowing an estimated spend of up to $2.47.
- An Opus guard caught cache-write accounting, yet still let through a single $0.78 request, missed other models and configurations, and priced every call as uncached, which caused a subsequent run to abort without an answer.
- Two additional guards (Haiku and Sonnet) likewise failed, letting a scripted full read reach over $2 under Haiku pricing and also overspending across multiple turns.
Our observation is that even the strongest model struggled to get every detail of cost accounting right, and the guardian accepted every faulty version.
Enforcement. The harness should proactively enforce its own invariants and operator constraints, rather than relying on the model’s capability or judgment.
When we asked agents to reduce costs and clean up their workspace while preserving execution records, they complied voluntarily in all nine trials—but the harness provided no actual protection. Model compliance breaks down easily in practice: in the spending-guard experiment above, two agents proceeded with the task before their newly written guards took effect on the next turn (with one explicitly noting the delay beforehand).
Takeaway
A self-editing harness must protect the components that implement its guarantees, and it needs to establish that each proposed change preserves those guarantees before activating it. Our experiments illustrate how difficult this becomes when agents can modify arbitrary harness code.
Towards a verifiable policy interface
How much control does the agent actually need? Across our experiments, the useful adaptations centered on a small set of recurring decisions. The simplest examples are when to compact and which steps to keep verbatim, how much of a large tool output to admit into the prompt, how much reasoning effort to spend on a call, and whether to pause before finishing to revisit an open question.
Our key insight is that we can give the agent control over useful execution decisions through an interface narrow enough to verify each proposed policy. Consider the Haiku controller from Approach 2. We want the agent to decide when to compact and which old tool outputs to shorten, while keeping token accounting under the harness’s control. This prevents the agent from inadvertently undermining the mechanism that enforces the context budget. We can also require the policy to preserve specific evidence, such as the two most recent steps or recent test failures. The verifier checks these requirements for every valid input to the policy, including rare cases that empirical testing might miss.
This is the design we adopt in ext, inspired by eBPF [21]. Just as Linux lets developers attach programs at specific hooks and verifies each program before loading it, ext exposes narrow, typed hooks for decisions such as compaction, tool-output shaping, and reasoning effort. The agent writes a policy before the run (and can optionally revise it mid-run), and the harness invokes it whenever that decision arises. Before any policy or revision takes effect, a verifier first checks it against both the harness’s built-in rules and the operator’s project-specific rules. In doing so, ext keeps safety-critical mechanisms fixed and protected inside the harness while offering flexibility and extensibility.
The next section covers our design and implementation in more detail.
Design and Implementation of ext
Design requirements
The failures above point to four requirements for ext:
- Verifiable policies with safe fallback. Agents should customize execution decisions, but every policy or revision must be proven to satisfy baseline and project invariants before loading, with a safe fallback on runtime failure (Safety: DSL and verification).
- Extend existing harnesses rather than replacing them. Production harnesses like Claude Code evolve constantly, and frontier models are increasingly co-optimized with their native tools (such as
apply_patchfor Codex). Rather than forking core mechanisms such as sandboxing, permissions, and tool loops per task, ext extends unmodified harnesses through their existing interfaces (Extending unmodified harnesses). - Separate policy decisions from the acting loop. Policies should read live state and adapt—before, during, and across runs—without exposing a continuous token or cost meter in the acting model’s prompt (Self-improvement before, during, and across runs).
- Composable rules and modular hooks. Operators should be able to add project-specific rules easily (that are automatically checked for conflicts), and developers should add new hooks without breaking existing policies (Extensibility: project-specific rules and new hooks).
Safety: DSL and verification
In eBPF, programs attach to specific hooks, have access to a restricted set of operations, and must pass the verifier before they can run. Some subsystems (such as sched_ext) also provide a fallback, which can revert to the default scheduler when a buggy custom scheduler stalls.
We adopt similar principles in ext.
| In eBPF | In ext |
|---|---|
Attach points (kprobes, XDP, sched_ext) | Narrow, typed hooks (compaction, tool outputs, stop check, review, effort, revision) |
| Restricted bytecode, no unbounded loops | Loop-free Python subset; policy evaluation takes microseconds |
| Verify before load | Z3 proves each rule for all valid hook inputs (~24 ms) |
sched_ext watchdog and default scheduler | Fallback to default behavior on a policy failure |
| Verifier log | Concrete counterexample sent back to the authoring model to fix |
| Hooks in existing kernel subsystems | Hooks and host-side proxy for unmodified Claude Code |
| Verifier checks specific to program types | Default rules, operator-defined project rules, and optional agent assertions |
In ext, the harness owns the mechanisms that implement execution decisions and enforce the rules. These include rendering context, summarizing history, counting tokens, reserving each model call’s cost before sending it, recording billed usage, preserving the task statement, and saving full tool outputs before trimming them. Unlike in Approach 1, where the agent invokes these mechanisms as tools, here they write policies that decide when and how to invoke each mechanism.
Extending unmodified harnesses
To extend unmodified harnesses such as Claude Code, ext runs its policy runtime and verifier outside the agent sandbox and attaches through two interfaces:
- The harness’s native hooks call ext at lifecycle events and apply what the policy returns. For example, at
PreCompact, the policy allows or defers the proposed compaction and specifies what the summary should preserve. AtPostToolUse, it shapes oversized tool outputs before they enter the context. AtStop, it can hold the agent for another check before it finishes. - A host-side HTTP proxy intercepts model API requests to track token and cost state, set reasoning effort, and enforce the spending cap before forwarding each call.
Claude Code continues to run its own agent loop unchanged.
ext attaches to existing agent harnesses (e.g., Claude Code)
Policy language and verification
Agents write their policies in a domain-specific language (DSL) we call extLang, which is based on a restricted, loop-free subset of Python. The language supports conditionals, arithmetic, comparisons, min, max, abs, and constants. Policies can only read the typed state exposed by each hook and return values of the expected type. They cannot modify the harness’s state, access files, or make network calls. For example, the token-accounting bug we observed in Approach 2 cannot be expressed in extLang. We expect this DSL to evolve over time.
Each hook receives a read-only view of execution state. In the example below, s holds the current run state (context size, budget, steps since compaction, subtask-boundary marks, and accumulated spend), and b describes an individual history step. The agent can pin important evidence so it survives compaction. Here is a lightly trimmed policy an agent wrote for itself in our bash-only harness:
def should_compact(s):
if s.ctx_tokens * 100 >= 95 * s.budget: # compact before overflow
return True
if s.steps_since_compact < 2: # no back-to-back thrashing
return False
if s.ctx_tokens * 100 >= 75 * s.budget:
return True
return s.ctx_tokens * 100 >= 55 * s.budget and s.marks_since_compact > 0
def compact_action(b, s):
if b.pinned or b.age <= 1: # keep pinned evidence & last 2 steps
return KEEP
if b.is_error and b.age <= 4: # keep recent failures
return KEEP
if b.age >= 12 or (not b.in_current_subtask and b.output_tokens > 150):
return MASK # command visible, output recallable
return KEEP
def choose_effort(s):
if s.cost_cents * 100 >= 90 * s.cost_budget_cents:
return LOW
if s.consecutive_errors >= 2 or s.recent_errors >= 3:
return HIGH
return MEDIUM
The policy above defines three decisions. should_compact can compact early at a subtask boundary, while requiring compaction at 95% of the budget. compact_action preserves pinned evidence and recent errors, and can mask older outputs while leaving them retrievable. choose_effort adapts reasoning effort in response to errors and accumulated spend. The agent can customize all three decisions.
To verify a policy, ext translates each hook into a logical expression and asks Z3, an SMT solver, whether there is any valid input on which a rule is violated. If the solver proves there is no such input, then the policy satisfies that rule within the modeled state space. Verification takes about 24 ms per policy load, and evaluating a policy at a hook takes microseconds. In a separate microbenchmark, the proxy’s request processing took 7–26 ms on representative request sizes, less than 1% of the measured median model round-trip times (3.5–5.9 s). We include eleven default rules (e.g., evidence retention, compaction timing and space reclamation, and bounded stop refusals) and fifteen hooks (e.g., summary_focus, stop_note, and review_focus).
Whenever a policy fails a rule, Z3 returns a counterexample that the model can use to revise its implementation. For example, an Exo agent wrote an edit that clipped every older tool result. Expressing the same policy in ext violated the rule requiring pinned evidence to be preserved. Z3 identified a pinned step three turns old as a counterexample, and the policy passed once pinned steps were exempted.
How bad policies and rules are stopped before they load
In the experiment from Approach 2, the verifier rejected every known rule-breaking edit and accepted every edit with no observed violations. Across 562 policies written for Claude Code by Haiku, Sonnet, and Opus, every policy passed within four repair rounds with zero fallbacks. In two additional mutation studies (1,890 policy mutations in total), the verifier caught every violation fuzzing found plus 26 more that fuzzing missed.
Trust model. The trusted computing base (TCB) includes the host-side proxy, the mechanisms that collect execution state and implement hook decisions (e.g., token and cost accounting, context rendering, and output storage), the policy loader and execution engine, and the verifier, including its translation of extLang into Z3 expressions. The integration also relies on the underlying harness and sandbox to enforce their contracts. Agent-authored policies and model outputs are untrusted. Verification establishes the specified properties over the modeled hook inputs, assuming that the trusted mechanisms implement those contracts correctly. If a Claude Code hook is unreachable, it falls back to native behavior, so guarantees mediated by that hook depend on its availability. Ordinary agent tool use remains governed by the underlying harness’s permissions and sandbox. We evaluate policy performance empirically.
Extensibility: project-specific rules and new hooks
In addition to default rules, which protect the harness, operators can define project-specific rules. For example, a software project involving extensive debugging might require the agent to preserve recent test results verbatim and prevent failures from being dropped during compaction:
RULES = {
"P_keep_current_tests": (
"implies(and_(b.is_test, b.in_current_subtask, b.age <= 6), "
"compact_action(b, s) == KEEP)",
"Recent test output for the subtask in progress stays verbatim."
),
"P_errors_never_dropped": (
"implies(b.is_error, compact_action(b, s) != DROP)",
"Failed steps must not be dropped during compaction."
),
}
A scientific discovery project might have different priorities. For example, the operator can require previews of large data outputs, higher reasoning effort during initial planning, and an independent review by a stronger model before completion, subject to the remaining time and budget:
RULES = {
"P_bulk_data_previewed": (
"implies(and_(o.kind == SHELL, o.tokens > 4000, "
"not_(o.is_slice)), output_action(o, s) != KEEP)",
"Large command outputs are previewed; the full output is saved "
"and can be retrieved when needed."
),
"P_second_opinion": (
"implies(and_(s.edits_since_review > 0, s.reviews == 0, "
"s.stop_blocks < 2, s.time_used_pct < 70, "
"s.cost_cents * 100 < 50 * s.cost_budget_cents), "
"and_(should_review(s), review_tier(s) == STRONGER))",
"Request review by a stronger model before completion "
"when the stated conditions hold."
),
"P_plan_carefully": (
"implies(and_(s.step <= 2, "
"s.cost_cents * 100 < 50 * s.cost_budget_cents), "
"choose_effort(s) >= HIGH)",
"Use high reasoning effort during the first three steps "
"while sufficient budget remains."
),
}
These rules are incorporated into the verifier’s specification. Operators can add constraints without weakening the defaults. The verifier checks project rules for conflicts and checks that the fallback policy satisfies them. Every policy the agent writes or revises must satisfy both the default and project-specific rules.
Similar to how Linux eBPF evolved over time, developers can also extend ext by adding hooks with corresponding verifier rules. We added a tool-output shaping hook and a pre-finish review hook with 221 and 263 lines of code, respectively, across the policy API, verifier, host-side mechanisms, and hook shims. The rules for different hooks can work together. For example, a bound on admitted tool output helps prevent a large read from immediately triggering another compaction.
Our 200K-window incident audit (Compaction thrashing) illustrates how the harness can evolve in response to policy failures. Some agent-written policies repeatedly compacted near a pricing threshold even when the previous compaction had already left the context above it. We exposed the post-compaction context size as a state field and added a rule requiring the context to grow by at least one-third before another policy-driven compaction below 75% utilization. The verifier rejected all six violating test policies, and subsequent runs showed no policy-driven thrashing below 75%.
Self-improvement before, during, and across runs
ext enables agents to improve their execution at three timescales: customizing policies before a run, adapting and revising policies during a run, and learning better policies across runs.
- Before the run: The model writes a policy tailored to the task and repairs any Z3 counterexamples before the acting loop starts.
- During the run: Policies adapt to changes in execution state and can request a policy revision. The new policy must pass verification before replacing the current one.
- Across runs: The verifier provides a fast, deterministic signal for learning to write valid policies, while execution outcomes provide feedback on their effectiveness. This enables weight-free optimization through reflection on past execution traces (e.g., GEPA [22]) and weight-based learning through reinforcement learning. In our evaluation, we demonstrate reusable policies developed from previous executions (Short Coding Tasks) and train a 9B model to write increasingly effective policies (RL Training).
Evaluation
We evaluate ext to understand how agent-customized harness policies affect task accuracy, execution cost, and compliance with operator-defined rules. We answer the following questions:
- Execution quality: Do agent-written policies outperform fixed harness heuristics, especially under compaction thrashing?
- Transfer across runs: Can an agent distill prior failures into a reusable policy that generalizes across models?
- Rule enforcement: Can ext enforce strict operator constraints?
- Learning to author policies: Can a small model be trained to write valid, high-performing policies?
Finally, we conduct a separate safety audit for rule violations. We leave a dedicated evaluation of self-improvement during a run (as studied in Exo [11]) as future work.
Long-horizon tasks: improving on fixed policies
We first revisit the five long-horizon tasks introduced in Approach 1. Using our bash-only harness with Claude Haiku 5.5 under a 32K context budget, ext raised success from 92% to 100% at 1.30× the default run cost (including policy authoring). Two other fixed settings also achieved 100% success: extra-high reasoning effort (1.79× cost) and observation masking, which keeps the ten most recent outputs verbatim and masks older ones (2.37× cost). Compared with these equally successful settings, ext was 27% and 45% cheaper, respectively.
ext reaches 100% at the lowest cost
best success at each costbeaten by a cheaper setting
In all remaining performance experiments, we use Claude Code as the base harness.
Multi-hop research QA: higher accuracy at the same cost
Multi-hop research QA tests whether an agent can trace 24 multi-step entity chains across approximately 1,650 documents containing near-duplicate distractors under a 100K context budget. Both when the agent compacts and what it preserves matter. Claude Code often compacted in the middle of tracing an entity chain and sometimes lost the original questions. The agent-written policy waited for subtask boundaries and instructed the summarizer to preserve exact paths, verified entity chains, and easily confused names.
Across 102 runs per setup with Haiku 5.5, ext deferred 34 compaction proposals per run on average and compacted 2.6 times instead of 4.4. Full success (all 24 answers correct) rose from 33% to 53% (+20 percentage points, 95% CI 6–33), and mean accuracy rose from 75% to 87%, at 0.92× the run cost (1.00× including policy authoring).
More runs answered all 24 questions with ext
Compaction thrashing: keeping long tasks running
Compaction thrashing is a recurring failure mode in Claude Code (GitHub issues #85489, #60600, #60485, and #61351). When the summary and reattached files occupy most of the context window after compaction, a single large tool output can trigger another compaction within a few turns. After three consecutive refills, Claude Code’s built-in breaker terminates the session.
To evaluate compaction thrashing at a model’s default context window, we tested Sonnet 4.6 (200K default window) on an SRE incident audit: checking 204 fields across 18 incident dossiers (~90K tokens each), where the initial request alone consumed 84K tokens. Vanilla Sonnet 4.6 aborted both runs due to compaction thrashing (0/204 both times), tripping the breaker after just 10 model requests as large file reads refilled the window. Sonnet’s agent-written policy capped how much of each oversized tool output entered context; with ext, the two runs scored 199/204 and 204/204.
At 200K, whole-file reads refill the window after every compaction
Vanilla Claude Codeextcompaction
Fixed heuristics were not enough on this workload either. With Haiku 5.5 at a 200K context window, vanilla Claude Code scored 0/204 in all three runs, and a fixed compaction and tool-output policy also scored 0/204 in both runs under a $5 budget. With ext, Haiku additionally customized what the summarizer preserved—including which incidents had already been investigated and where findings were recorded on disk. It scored 197, 154, and 198 out of 204 under the same $5 budget and 204/204 in both runs under a $9 budget (spending under $6 per run).
We also evaluated SWE-Marathon long builds—a Stripe-compatible API (83 tests) and a Mastodon-style server (150 tests) built from specifications—under a 100K context budget across Haiku, Sonnet, and Opus. ext increased the share of tests passed by 12 percentage points at 0.85× the run cost, while compacting about half as often. In one Mastodon run, vanilla Opus 5.5 compacted six times in 22 tool calls before hitting the breaker (0/150 tests passed); with ext, Opus compacted ten times (nine from policy) across 128 calls and passed 147/150 tests.
Short coding tasks: learning better policies across runs
We evaluated nine coding tasks from DeepSWE, SWE-bench Pro, and Terminal-Bench 2.1, including six tasks that Claude Code often failed narrowly and three it already solved. Task-specific policies reduced Haiku’s run cost to 0.60× through price-aware compaction (i.e., compacting before crossing higher long-context pricing tiers), but did not improve Opus’s accuracy.
This motivated us to explore another aspect of self-improvement. Can agents learn from previous executions and develop better policies for future tasks?
We reconstructed 12 Opus trials (eight failed and four solved) and queried Opus before its first code edit about what would help it finish. In five of the eight failed trials, Opus immediately identified the exact ambiguous decision that later caused failure: for example, whether to preserve existing behavior or follow examples in the specification. It consistently asked for clarifications and examples, rather than extra reasoning effort or an independent reviewer.
From these traces, we distilled a single reusable policy (with an Opus 5.5 agent implementing and verifying the policy code). Its start hook appends brief upfront guidance to the task text (follow the task wording and examples, avoid unrequested changes, and resolve environment limitations locally). Its stop hook holds the agent’s first attempt to finish and prompts it to revisit decisions it would otherwise have asked about. Its compaction hook applies price-aware compaction to control cost.
We evaluated this finalized policy across all nine tasks and three models (three runs per task; the six failure-prone tasks informed policy design, while the three already-solved tasks were held out to check for regressions):
| Model | Vanilla Claude Code | ext (reusable policy) | Gain (95% CI) | Run cost | Cost per solved run |
|---|---|---|---|---|---|
| Opus 5.5 | 14/27 | 22/27 | +29.6 pts [18.5, 44.4] | 0.99× | $2.56 → $1.61 |
| Sonnet 5.5 | 15/27 | 18/27 | +11.1 pts [−7.4, 29.6] | 1.19× | $0.65 → $0.65 |
| Haiku 5.5 | 15/27 | 15/27 | 0.0 pts [−14.8, 14.8] | 0.40× | $0.64 → $0.26 |
Opus saw the largest gain, rising from 14/27 to 22/27 solves at the same cost with no regressions on the three held-out tasks (9/9 vs. 8/9 for vanilla, at 0.90× cost). The same policy transferred across models, matching Haiku’s solve rate at 0.40× the run cost while modestly improving Sonnet.
One reusable policy: Opus solves more, Haiku costs less
ext, one reusable policyvanilla Claude Code
Enforcing a spending limit
To test whether an operator can enforce a spending limit without abruptly killing a run mid-task, we used an incident-log QA task: answering three questions from a 15,818-line log (~1.2M tokens), where the prompt instructs the agent to load the entire log first (in 400-line chunks). Reading the full log once costs several times the budget, though all three answers can be found by searching. For ext, the operator configures a $0.30 cap outside the task prompt; for Exo, which lacks a built-in spending cap, we state the $0.30 budget in the task prompt.
ext enforces the spending limit by reserving each request’s estimated input cost (priced at the highest applicable rate) and maximum output cost before forwarding it, refusing any call that would push total spend past $0.30, and reconciling against billed cost when the call returns. While this mechanism guards the budget, hard refusal alone cannot help the agent recover: after a few 400-line reads, the remaining budget can no longer cover the next request, the proxy refuses it, and the session aborts before the agent can change course and search.
To keep the agent productive under the cap, the tool-output hook exposes s.spend_room (an estimate of how many tokens the remaining budget can afford), and the operator adds two project rules requiring policies to trim oversized outputs to fit within it while saving the full output on disk:
RULES = {
"C1_read_fits_budget": (
"implies(and_(o.tokens > 2000, o.tokens > s.spend_room), output_action(o, "
"s) != KEEP)",
"A tool output may not enter whole if that would take the run past its "
"cost budget."
),
"C2_shaped_fits_budget": (
"implies(output_action(o, s) != KEEP, output_tokens(o, "
"s) <= max(s.spend_room, 500))",
"Shaped outputs fit the remaining budget (500-token floor)."
),
}
| Model | ext (two project rules, $0.30 cap) | Exo (told $0.30 budget in prompt) |
|---|---|---|
| Haiku 5.5 | $0.188 (3/3), $0.167 (3/3) | $0.012 (3/3), $0.015 (3/3) |
| Sonnet 5.5 | $0.143 (3/3), $0.096 (3/3) | $0.240 (3/3), $0.141 (3/3) |
| Opus 5.5 | $0.284 (0/3), $0.201 (3/3) | $0.436 (3/3), $0.554 (3/3) |
All six runs with ext stayed within $0.30 (maximum $0.284), and five answered all three questions correctly. Trimming oversized reads leaves a pointer to the complete file on disk, allowing the agent to search for the answers rather than exhausting its budget reading through the log. The exception was an Opus run with a cold provider cache, whose first call alone cost $0.154, leaving too little budget to finish; the warm-cache run answered all three for $0.201. Policy authoring cost $0.02 to $0.15 per model (paid once and shared across both runs).
Exo’s agents, given the budget only in the prompt, answered all three questions in every run but exceeded the cap in both Opus trials (by 45% and 85%). Raw dollar figures are not directly comparable across the two columns because Exo and Claude Code differ substantially in baseline prompt overhead and caching behavior. When we instead asked Exo’s agents to implement their own $0.50 spending guards (Lessons from Exo), all seven guards accepted by the guardian failed subsequent enforcement tests.
ext correctly enforces the $0.30 spending limit without blocking progress
tool output part let in tokens the remaining budget can pay for search answers written
RL training: learning to write better policies
Small models struggle to write valid policies zero-shot: base Qwen3.5-9B produced a verified policy on only 12.5% of runs across two unseen research-QA corpora. We trained it with LoRA in two stages as a policy author. The agent that runs the policy is Claude Code (Claude Haiku 5.5) with a 100K context window.
- Stage 1 (verifier reward): We ran GRPO using the verifier’s acceptance decision as the reward, with partial credit for the fraction of rules proven. On the two held-out corpora, verified policy runs rose from 12.5% to 97.8%, with 80.9% mean accuracy.
- Stage 2 (execution outcomes): Starting from Stage 1, we ran expert iteration on Claude Code rollouts across three training corpora, scoring verified policies on task accuracy with time and cost penalties (unverified policies get zero reward and never load). On the same held-out corpora (320 runs per setup), the Stage 2 author reached 100% verified runs and raised mean accuracy from 80.9% to 86.4% (+5.6 percentage points unrounded, 95% CI 1.1–9.8) and full success from 45.9% to 53.8%, at comparable time and cost (0.98× wall time, 1.03× cost).
Qwen3.5-9B learns to write valid (stage 1) and good (stage 2) policies
Setup
- Policy author
- Qwen3.5-9B with a LoRA adapter
- Stage 1
- GRPO. The curve is one 25-step run of the recipe, 64 sampled policies a step; on five held-out tasks it went from 0% to 54% valid. The checkpoint stage 2 starts from was trained with the same recipe; with it, runs with a verified policy rose from 12.5% to 97.8% (313 of 320).
- Stage 2
- expert iteration on three training corpora. The curve is held-out accuracy on two other corpora, with 95% intervals; rounds 0 and 3 were run in three batches, 320 runs per setup in all; round 1 and the two dashed baselines have 80 runs each.
Stage 1
Reward: the verifier accepts the policy
Policy author→Verifier→Reward
12.5% → 97.8% of runs get a verified policy
Per-sample verification rose from 3% to 62%; the curve shows a separate 25-step training run of the same recipe.
Stage 2
Reward: how well the agent then does the task
Policy author→Verifier→Claude Code→Reward
80.9% → 86.4% answers correct on held-out tasks
320 runs at rounds 0 and 3; 80 runs at round 1.
Against vanilla Claude Code (80 runs per setup), the Stage 2 9B author raised Haiku 5.5’s accuracy from 69.8% to 89.2% (+19.4 percentage points, 95% CI 10.6–28.4) at 1.06× cost.
Answer accuracy rose from 80.9% to 86.4% at 1.03× cost
Setup
- Author
- Qwen3.5-9B with LoRA
- Stage 1
- GRPO, the verifier as reward
- Stage 2
- expert iteration; reward = share of answers right, minus a penalty for time and cost above the default
- Runs
- 320 for each stage’s author; 80 for vanilla Claude Code and the fixed threshold
Vanilla Claude Code80 runs
69.8%
Fixed 80% compaction threshold80 runs
78.8%
Stage 1 (verifier reward)320 runs
80.9%
Stage 2 (execution outcomes)320 runs
86.4%
Vanilla Claude Code80 runs
28.7%
Fixed 80% compaction threshold80 runs
48.8%
Stage 1 (verifier reward)320 runs
45.9%
Stage 2 (execution outcomes)320 runs
53.8%
Independent safety audit
Static verification proves properties of each policy assuming the harness mechanisms uphold their contracts. To check the implementation itself at runtime, we audited host-side logs across 556 ext runs (13,717 model requests) and found zero dropped task constraints, zero requests over the context budget, and zero modified test files.
What’s Next?
We believe the role of an agent harness will change as foundation models become more capable. Today, most harness improvements are developed by humans, evaluated on a set of tasks, and shipped as defaults for every agent. With ext, we want agents to finally take a more active role in safely improving their own harnesses, especially as they take on long-horizon, autonomous tasks where continuous human or LLM oversight becomes expensive and error-prone.
- Agent-driven extensibility. Our current hooks expose decisions identified by the harness developers. An interesting research question is whether agents themselves can identify which new hooks and state fields they need to improve their execution. Can an agent analyze its past runs, identify limitations of the existing interface, and propose extensions and safety rules? This could help developers evolve the interface as foundation models acquire new capabilities.
- Continual self-improvement. We want agents to learn from past executions, identify recurring inefficiencies, and develop policies that transfer across tasks. Our initial experiments explore both weight-free policy improvement and weight-based learning. We want to understand when each approach is most effective, how much experience is needed, and how agents can improve the policies they already use while preserving the operator’s rules.
- Supporting real workloads and richer operator rules. Different teams have very different requirements for budgets, evidence retention, validation, and reproducibility. We are particularly interested in long-horizon workflows such as scientific discovery, where preserving the evidence behind a finding matters as much as the final answer. Working with users will help us understand which rules are useful in practice and which belong in the harness mechanisms.
The more capable an agent becomes, the more we should be able to delegate decisions about its execution. We believe a verifiable policy interface, such as the one provided by ext, can let harnesses benefit from advances in foundation models while continuing to enforce the operator’s requirements.
ext is under active development. We plan to release the code soon and would love to hear from researchers and developers. If you are interested in trying it out, please join the waitlist.
Citation
Please cite this work as follows:
@misc{wang2026ext,
title = {Agent Harnesses Need Their {eBPF}},
author = {Wang, Ron Yifeng and Akella, Aditya},
year = {2026},
month = dec,
howpublished = {\url{https://ut-infraai.github.io/2026/12/01/agent-harnesses-need-their-ebpf/}},
note = {InfraAI \& LDOS Blog}
}
Acknowledgements
The author thanks Rohit Dwivedula and Chijun Sima for helpful discussions and feedback.
References
- VibeServe: Can AI Agents Build Bespoke LLM Serving Systems? [PDF]
Kamahori, K., Li, S., Peter, S. and Kasikci, B., 2026. arXiv preprint arXiv:2605.06068. - Evolving Infra: Agent-Adaptive LLM Serving at Scale [PDF]
Kang, H., Xu, W., Li, Z., Du, Z., Li, H., Xia, T., Bian, S., Krishna, T., Mao, H., Stoica, I. and Han, S., 2026. arXiv preprint arXiv:2611.12304. - HarnessOpt-Bench: Evaluating LLMs at Harness Optimization [PDF]
Ursekar, V., Shanker, A., Maurya, Y., Yasser, S., Kalmath, V.S., Chatrath, V. and Xue, Y., 2026. arXiv preprint arXiv:2608.06301. - Meta-Harness: End-to-End Optimization of Model Harnesses [PDF]
Lee, Y., Nair, R., Zhang, Q., Lee, K., Khattab, O. and Finn, C., 2026. arXiv preprint arXiv:2603.28052. - MemGPT: Towards LLMs as Operating Systems [PDF]
Packer, C., Wooders, S., Lin, K., Fang, V., Patil, S.G., Stoica, I. and Gonzalez, J.E., 2023. arXiv preprint arXiv:2310.08560. - Scaling Long-Horizon Agent via Context Folding [PDF]
Sun, W., Lu, M., Ling, Z., Liu, K., Yao, X., Yang, Y. and Chen, J., 2026. International Conference on Machine Learning (ICML). - AgentFold: Long-Horizon Web Agents with Proactive Context Folding [PDF]
Ye, R., Zhang, Z., Li, K., Yin, H., Tao, Z., Zhao, Y., Su, L., Zhang, L., Qiao, Z., Wang, X., Xie, P., Huang, F., Zhou, J., Chen, S. and Jiang, Y., 2026. International Conference on Learning Representations (ICLR). - Automated Design of Agentic Systems [PDF]
Hu, S., Lu, C. and Clune, J., 2025. International Conference on Learning Representations (ICLR). - Darwin Gödel Machine: Open-Ended Evolution of Self-Improving Agents [PDF]
Zhang, J., Hu, S., Lu, C., Lange, R. and Clune, J., 2026. International Conference on Learning Representations (ICLR). - A Self-Improving Coding Agent [PDF]
Robeyns, M., Szummer, M. and Aitchison, L., 2025. ICLR 2025 Workshop on Self-Improving Foundation Models Without Human Supervision (SSI-FM). - Exo: An Architecture for Self-Improving Systems at Runtime [PDF]
Krentsel, A., Ratnasamy, S., Stoica, I., Casado, M. and Goyal, A., 2026. arXiv preprint arXiv:2611.00463. - Vulcan: Instance-specialized, Verifiable Systems Heuristics Through LLM-driven Search [PDF]
Dwivedula, R., Saxena, D., Yadalam, S., Campbell, E.H., Kim, D. and Akella, A., 2026. Accepted at EuroSys 2027 (arXiv:2512.25065). - Agent JIT Compilation for Latency-Optimizing Web Agent Planning and Scheduling [Paper]
Winston, C., Wang, R.Y., Mirhoseini, A. and Kozyrakis, C., 2026. International Conference on Machine Learning (ICML). - Context windows: context awareness [Link]
Anthropic, 2026. Claude Developer Platform documentation (accessed November 2026). - mini-SWE-agent [Code]
SWE-agent contributors. Open-source software. - Rebuilding Devin for Claude Sonnet 4.5: Lessons and Challenges [Link]
Cognition, 2025. Cognition blog, September 29, 2025. - VERSE: Verified Self-Evolving Optimizer for Agent Harnesses [PDF]
Wang, Z., Ge, Y., Wang, Z., Wang, H., Xu, Y., Frandsen, J., Fu, S., Wilson, A.C. and Reddy, C.K., 2026. arXiv preprint arXiv:2610.02616. - MOSS: Self-Evolution through Source-Level Rewriting in Autonomous Agent Systems [PDF]
Cai, Q., Zhang, Y., Jia, X., Zheng, H., Xue, W., Song, J., Tian, X. and Guo, Y., 2026. arXiv preprint arXiv:2605.22794. - Exokernel: An Operating System Architecture for Application-Level Resource Management [PDF]
Engler, D.R., Kaashoek, M.F. and O'Toole Jr., J., 1995. ACM Symposium on Operating Systems Principles (SOSP). - Application Performance and Flexibility on Exokernel Systems [Paper]
Kaashoek, M.F., Engler, D.R., Ganger, G.R., Briceño, H.M., Hunt, R., Mazières, D., Pinckney, T., Grimm, R., Jannotti, J. and Mackenzie, K., 1997. ACM Symposium on Operating Systems Principles (SOSP). - eBPF verifier [Documentation]
Linux Kernel Documentation. - GEPA: Reflective Prompt Evolution Can Outperform Reinforcement Learning [PDF]
Agrawal, L.A., Tan, S., Soylu, D., Ziems, N., Khare, R., Opsahl-Ong, K., Singhvi, A., Shandilya, H., Ryan, M.J., Jiang, M., Potts, C., Sen, K., Dimakis, A.G., Stoica, I., Klein, D., Zaharia, M. and Khattab, O., 2026. International Conference on Learning Representations (ICLR).