Harness engineering: give your agent a workshop, not just a prompt

The model is only one part of an agent. The interesting engineering is everything that lets it do useful work, recover from mistakes, and stop spending your money.

A selection of tools arranged across a workbench in a workshop
A selection of tools arranged across a workbench in a workshop

The short answer

Harness engineering is designing the system around an AI model so it can act reliably: the instructions, context, tools, execution loop, persistent state, permissions, verification, and operational limits. It turns model-generated proposals into controlled actions with observable outcomes.

Key takeaways

  • The model proposes actions; the harness controls execution, state, permissions, and verification.
  • Use a clear task contract and targeted context rather than one giant prompt.
  • Persist checkpoints and tool receipts so work can resume safely.
  • Verify artifacts and external state instead of trusting completion messages.
  • Measure cost per accepted outcome, including failed runs, tools, and human review.
A selection of tools arranged across a workbench in a workshop
A capable worker still needs the right tools, workspace, and checks. The same is true of an agent. Photo by Tima Miroshnichenko on Pexels.

Harness engineering is designing the system around an AI model so it can act reliably: the instructions, context, tools, execution loop, persistent state, permissions, verification, and operational limits. It turns model-generated proposals into controlled actions with observable outcomes.

A model says it fixed the bug. Your test suite disagrees. The agent retries, rereads the repository, and confidently fixes a different bug. Congratulations: you have automated activity.

The missing piece may not be a smarter model. It may be a better harness.

Think workshop, not magic employee

Imagine hiring a skilled machinist. Their skill matters. So do the drawing, labeled tools, machine guards, measuring instruments, job log, and supervisor’s sign-off. Handing them an unlabeled warehouse and saying “make it excellent” is not empowerment. It is management by wishful thinking.

In this analogy, the model is the machinist; the harness is the workshop and its operating procedures. Prompt engineering improves the work order. Context engineering puts the right drawings on the bench. Harness engineering also decides which machines can run, what survives a shift change, and what counts as finished.

The term’s boundaries vary. Anthropic defines an agent harness as the system that processes inputs, orchestrates tool calls, and returns results. OpenAI’s February 2026 account uses harness engineering more broadly for agent-friendly repositories, constraints, and feedback loops. This article covers both the runtime and the environment it operates in—not model training. [1] [2]

One useful distinction: a workflow follows predefined code paths; an agent chooses its next actions dynamically. A sensible product can combine them: deterministic admission and security checks around a model-directed investigation. You do not need to delegate every if statement to a language model. [3]

The core components—and what each buys you

1. Task contract and operating instructions

Specify the goal, allowed scope, constraints, and evidence required for acceptance. “Fix checkout” is a wish. “Prevent duplicate charges; preserve the API; provide regression tests; do not deploy” is a contract.

Keep repository guidance discoverable, with an entry point such as AGENTS.md linking to relevant architecture and test instructions. OpenAI describes using this kind of structured knowledge rather than one giant instruction file. [2] The trade-off: documentation costs time to maintain, but unclear instructions create avoidable exploration and rework.

2. Context assembly and retrieval

The harness chooses what the model sees at each turn: instructions, current objective, relevant files, tool results, and recent decisions. Retrieve targeted material instead of attaching the company’s entire digital attic.

Anthropic treats context as a finite resource and describes techniques including just-in-time retrieval, compaction, and structured notes. [4] Smaller, relevant inputs can reduce token spend; excessive trimming can hide a critical dependency. Preserve evidence locations so a summary can be checked against its source.

3. Tools and the execution environment

Tools translate proposals into effects: search files, run tests, query an order, create a branch. Give each tool an explicit schema, meaningful errors, bounded output, and a clear description of when to use it. Anthropic’s tool-design guidance emphasizes these interfaces and token-efficient responses. [5]

Prefer task-shaped operations over an ambiguous pile of overlapping endpoints. A sandbox should expose only necessary files, credentials, and network destinations. Better tools can reduce failed calls; extra wrappers add maintenance. A framework can supply plumbing, but installing one does not make your task contract correct.

4. The controller: plan, act, observe, stop

The model proposes a next step. The controller validates it, executes permitted tools, records observations, and calls the model again when needed. It also owns deadlines, iteration limits, cancellation, and terminal states such as verified, blocked, or budget_exhausted.

Use a short, revisable plan—not a ceremonial essay before every file read. Start with one agent. Parallel workers make sense for independent investigations, but introduce duplicated context, coordination, and conflicting edits. More agents is an architectural choice, not a performance setting. [3]

5. Durable state and recovery

Conversation history is not a durable job record. Store artifacts, completed steps, outstanding questions, versions, and tool receipts outside the model’s context. Separate temporary working context from persistent task state; treat longer-term user memory as scoped data, not universal truth.

Anthropic’s long-running-agent work uses initialization, progress files, and version-control artifacts to bridge sessions; compaction alone was insufficient in its experiments. [6] Checkpointing adds storage and implementation work but avoids restarting from guesses. For side effects, use operation IDs or idempotency keys: retrying a timed-out payment is not the same as retrying a file search.

6. Permissions and trust boundaries

Model-visible instructions are guidance, not access control. Enforce authorization outside the model. Separate read access from writes; require explicit approval for consequential actions; keep production secrets out of exploratory environments.

Retrieved text, issue comments, and tool output may contain hostile instructions. Treat them as data, not authority. Structured handoffs and approval gates help constrain risk, but do not eliminate prompt injection. [7] Approval increases latency and human effort. That can be a good trade when the alternative is an unauthorized refund.

7. Verification, traces, and evaluations

A completion message is a claim. Verify the changed artifact or external state: tests pass, a reservation exists, the correct record changed. A second model’s approval can be useful, but it is not a substitute for an executable check. Anthropic explicitly distinguishes an agent’s transcript from its outcome. [1]

Record tool calls, versions, failures, durations, and usage, with sensitive data redacted. Turn failures into evaluation cases and repeat trials because outputs vary. Tests and tracing add cost; they also let you find out whether a cheaper configuration actually works.

8. Budgets and model selection

Put ceilings on tokens, tool calls, runtime, and repair attempts. Route routine work to cheaper models only after evaluation; reserve stronger reasoning for cases that justify it. Count tool fees and human review, not just inference.

Reserve budget before launching work. Stop or escalate when the next step cannot fit. No amount of “be cost-efficient” in a prompt replaces a controller that can say no.

Harness design: the trade-offs at a glance
LeverPotential benefitPrice or failure mode
Targeted contextLess irrelevant input; more focused decisionsRetrieval latency; missing dependencies
Narrow, typed toolsClearer actions; smaller blast radiusInterface maintenance; reduced flexibility
CheckpointsResume without repeating completed workStale state unless versions are checked
Verification gatesCatch unsupported completion claimsExtra runtime; weak tests can mislead
Human approvalControl over consequential changesQueue time and reviewer attention
Parallel agentsIndependent work may finish soonerMore tokens, coordination, merge conflicts
Hard budgetsBound a run’s resource exposureSome valid tasks stop unfinished

A concrete coding-agent walkthrough

Let’s repair an actual, small code defect. The example is reproducible locally; the agent trajectory below is an illustrative design trace, not a measured production run.

Task: “Make the discount function reject percentages outside 0–100. Preserve valid behavior. Add regression tests. Do not commit or deploy.” Our starting file:

# pricing.py
def discounted_total(cents, percent):
    return cents * (100 - percent) // 100

The admission layer creates an isolated workspace with no production credentials. It allows repository reads, patching, and an allowlisted test command. An example policy permits eight model turns, two repair attempts, and a five-minute deadline. These are demonstration limits, not universal defaults.

The controlled loop

  • Admit task — Scope + budget
  • Inspect — Code + callers
  • Reproduce — Failing tests
  • Patch — Minimal change
  • Verify — Tests + diff
  • Checkpoint — Evidence + handoff

Step 1: inspect before editing

The agent requests read_file("pricing.py") and searches callers. The harness returns bounded results with file paths. The agent sees that 120% currently produces a negative total. It records the intended behavior: out-of-range percentages raise ValueError; valid integer percentages remain unchanged.

The contract does not define floating-point, string, or boolean inputs. Rather than silently redesign the API, the agent keeps those outside this patch’s claimed coverage.

Step 2: reproduce, then patch

The agent writes this test file. The controller runs the approved command, not arbitrary model-generated shell text:

# test_pricing.py
import unittest
from pricing import discounted_total

class PricingTests(unittest.TestCase):
    def test_valid_discounts(self):
        for percent, expected in [(0, 1000), (20, 800), (100, 0)]:
            with self.subTest(percent=percent):
                self.assertEqual(discounted_total(1000, percent), expected)

    def test_invalid_discounts(self):
        for percent in [-1, 101, 120]:
            with self.subTest(percent=percent):
                with self.assertRaises(ValueError):
                    discounted_total(1000, percent)

if __name__ == "__main__":
    unittest.main()

Run python3 -m unittest -v. Against the original function, the invalid-input subtests fail. The agent then proposes the minimal implementation:

# pricing.py
def discounted_total(cents, percent):
    if not 0 <= percent <= 100:
        raise ValueError("percent must be between 0 and 100")
    return cents * (100 - percent) // 100

Step 3: verify the result, not the narration

The controller reruns tests and checks the diff against scope: only the function and regression tests should change. In a real repository it also runs the existing relevant suite. A green result here establishes only the tested behavior—not that all pricing logic is correct.

If a test fails, the model receives the error and remaining repair allowance. Repeating the same failed action without new evidence triggers a stop. Infrastructure failures get bounded retries; permission denials require escalation, not creative workarounds.

Step 4: persist an honest handoff

The harness stores the patch, test output, source revision, usage, and terminal status. A reviewer gets what changed, what was tested, and what remains unspecified. The agent cannot deploy because deployment is neither authorized nor exposed as a tool.

If the process crashes, the next session reloads that record and checks the workspace revision before resuming. Durable evidence beats “I think we already tested this.”

Optimize cost per accepted outcome

A cheap unsuccessful run is not cheap work. Track total operating cost divided by accepted outcomes, including failed attempts, repair work, infrastructure, and review.

For token accounting, sum each call’s billable input and output at its applicable rates. Account separately for cache reads/writes and other provider-specific charges. Repeated context can be billed across turns; a transcript’s final length is not the run’s total usage.

run cost = Σ(input_tokens × input_rate
           + output_tokens × output_rate)
           + tool costs + runtime costs + review costs

Here is deliberately fictional pricing: $2 per million input tokens and $10 per million output tokens, with no caching, tool fees, runtime, or review included. These are arithmetic assumptions, not current provider prices.

Illustrative inference cost—not a benchmark
DesignTotal input / outputCost
Broad context, repeated exploration60,000 / 6,000 tokens$0.180
Targeted context, focused checks20,000 / 4,000 tokens$0.080

That is a hypothetical $0.10 saving per run. It proves nothing about quality. If the cheaper design’s acceptance rate drops, its economic advantage can disappear.

Evaluate configurations on the same representative tasks, repeated across trials. Record acceptance rate, unauthorized-action rate, cost per accepted task, median and tail latency, repair frequency, and human-review minutes. Define acceptance before seeing the results. Change one lever at a time; otherwise you learn that “something helped.” Very scientific.

Start boring: one agent, a narrow task, a few well-designed tools, durable checkpoints, executable checks, and a budget. Add retrieval, routing, or parallel workers only when traces show a problem they can solve.

The harness cannot guarantee correctness or manufacture missing model capability. What it can do is make work inspectable, constrain failure, and distinguish a verified result from a persuasive sentence. That distinction is where the engineering starts.

Sources and further reading

Primary engineering accounts and documentation, reviewed November 27, 2026. Recommendations and illustrative examples above are a synthesis, not claimed benchmark results.


- Demystifying evals for AI agents — Anthropic. Harness definitions, trials, traces, and outcome-based grading.


- Harness engineering: leveraging Codex in an agent-first world — OpenAI, February 11, 2026. Agent-friendly environments and feedback loops; its reported productivity figures are not generalized here.


- Building effective agents — Anthropic. Workflow/agent distinctions and simplicity-first architecture. Originally published in 2024; used for patterns, not current tooling recommendations.


- Effective context engineering for AI agents — Anthropic. Context curation, retrieval, compaction, and notes.


- Writing effective tools for agents—with agents — Anthropic. Schemas, meaningful results, and evaluation-driven tool design.


- Effective harnesses for long-running agents — Anthropic. Initialization, incremental progress, and session handoffs.


- Safety in building agents — OpenAI. Prompt injection, structured data flow, and approvals. Cited for safety principles, not as a recommendation of the Agent Builder product.

Frequently asked questions

Is harness engineering just prompt engineering?

No. Prompts specify behavior; the harness also executes tools, persists state, enforces permissions, checks results, and controls resource use.

Do I need an agent framework?

No. Use one if its runtime, checkpointing, or instrumentation saves you work. Evaluate its defaults and failure behavior instead of assuming the abstraction handles them.

Does a better harness always reduce cost?

No. Verification and approval can increase immediate cost while improving accepted outcomes or reducing risk. Measure the whole task, not the cheapest call.

What should I build first?

Define success, implement one safe tool path, and record a trace. Add a failure case and a stop condition before adding another agent.

Sources

  1. Demystifying evals for AI agents Anthropic
  2. Harness engineering: leveraging Codex in an agent-first world OpenAI
  3. Building effective agents Anthropic
  4. Effective context engineering for AI agents Anthropic
  5. Writing effective tools for agents—with agents Anthropic
  6. Effective harnesses for long-running agents Anthropic
  7. Safety in building agents OpenAI

Found this useful?

Clap (up to 50×) so more people find it.

Written by

Noaman

Markdown version