Coding Agent Harnesses: Four Design Layers and Implementation Guidelines
A coding agent harness provides the engineering controls that turn model-driven coding into a manageable team workflow. This article outlines four layers—context management, tool orchestration and permissions, verification, and session artifacts—and details practical policies for context budgets, command execution, validation, retries, and checkpoints. These controls limit risk and improve traceability, but do not guarantee correctness.
1. The Problem and the Boundaries
Building a coding assistant that works is no longer particularly difficult. Models can read code, edit files, and execute commands, often producing a runnable utility within a few interactions. The harder problem is making that assistant reliable enough for sustained use on real projects while limiting the impact of failures.
Models do not inherently manage context growth, enforce permission boundaries, validate results, or recover from interruptions. Those responsibilities belong to the engineering layer around the model, commonly called an agent harness.
A usable harness needs to cover at least four layers:
- Context management: What the model sees and retains.
- Tool orchestration and permissions: What the model can do and which actions require human approval.
- Verification: How changes are checked and what happens when checks fail.
- Session artifacts: How work resumes after an interruption and which auditable records are retained.
This article focuses on harness design and implementation for engineering teams, not model selection. A harness can reduce risk and contain failures, but it cannot prevent every agent error. Treat it as a system for enforcing constraints and recording activity—not as a guarantee of correctness.
2. Layer One: Context Management
Context is the agent’s working memory. Too little information encourages guesswork. Too much information, or stale information, can lead the model to change code based on false assumptions.
A common failure in long-running tasks is constraint drift: after dozens of steps, the agent forgets the original requirements, repeats earlier edits, or overwrites its own previous changes.
2.1 Control What Enters the Prompt
Organize context into three layers based on its role:
- Fixed layer: System rules, project conventions, and coding standards. Include these on every turn and exclude them from compression.
- Task layer: The current objective, acceptance criteria, and relevant file list.
- Evidence layer: File excerpts, command output, and error traces. Load these on demand and release them when no longer needed.
Do not put the entire repository into the prompt. First locate relevant material through search, symbol indexes, or directory summaries, then read the specific files.
The following is an illustrative budget. Adjust the numbers to the model’s context window.
| Area | Share | Example: 32,000-token total budget |
|---|---|---|
| Fixed layer | 15% | Approximately 4,800 tokens |
| Task layer | 15% | Approximately 4,800 tokens |
| Evidence layer | 50% | Approximately 16,000 tokens |
| Model output and headroom | 20% | Approximately 6,400 tokens |
The evidence layer receives the largest allocation and is the easiest to let grow unchecked. Give it a separate limit. When it exceeds that limit, discard older evidence first rather than compressing the task objective.
2.2 When and How to Compress History
Conversation history grows continuously, so compression needs explicit triggers—for example, when usage exceeds 70% of the budget or when a subtask is complete.
A summary should preserve:
- Confirmed facts.
- Unfinished steps.
- Changes already made.
- Failed attempts and why they failed.
Verbose raw tool output can be discarded. The reasoning behind decisions should not be.
The following conceptual pseudocode illustrates the approach:
def compact_history(messages, budget_tokens, summary_max_tokens=800):if count_tokens(messages) < budget_tokens * 0.7:return messagesfixed = [m for m in messages if m.layer == "fixed"] # Always retain the fixed layer; never summarize itdynamic = [m for m in messages if m.layer != "fixed"]keep_recent = dynamic[-6:] # Preserve recent messages verbatimolder = dynamic[:-6]summary = summarize(older,fields=["confirmed_facts", "pending_steps", "changed_files", "failed_attempts"],max_tokens=summary_max_tokens, # Limit the summary itself)compacted = fixed + [system_summary(summary)] + keep_recentif count_tokens(compacted) > budget_tokens:raise ContextOverflow("Context still exceeds the budget after compression; ""reduce the evidence layer or stop and ask the user")return compacted
Three principles matter here.
First, system rules and project conventions belong to the fixed layer and must not be replaced by a summary.
Second, the summary itself needs a size limit. Otherwise, compression merely moves the growth problem into the summary.
Third, if the compressed context still exceeds the budget, raise an error instead of silently truncating it.
2.3 When to Require a Fresh Source Read
Summaries can lose or distort information. Re-read the source file rather than relying on memory in these situations:
- Before editing a file.
- When an editing tool returns an unexpected result.
- After multiple writes to a file since its last read.
- When a failing test’s stack trace points to that file.
Making “read the latest contents before editing” a hard requirement can substantially reduce accidental overwrites. Enforce this rule in the execution layer, not just in the prompt.
3. Layer Two: Tool Orchestration and Permission Boundaries
Tools are how an agent affects its environment. Reading files, writing files, executing commands, calling external services, and requesting approval all need explicit boundaries.
More tools do not necessarily mean greater capability. The more their permissions overlap, the harder they are to audit and the larger the potential impact of an error.
3.1 Permission Matrix
The following table defines default policies and implementation requirements for each operation category. Retry and rollback handling are discussed further in Section 4.
| Category | Typical operations | Default policy | Timeout | Failure retries | Audit log | Rollback |
|---|---|---|---|---|---|---|
| Read-only | Read files, list directories, search content | Execute automatically | 30 seconds | Environmental errors only; up to 2 retries | Record paths and invocation times | Not required |
| Reversible writes | Modify version-controlled workspace files | Execute automatically; create a checkpoint before each write | None | No automatic retries | Record changed files and diff statistics | Restore to checkpoint |
| Command execution | Run project-configured tests, lint, type checks, and builds | Automatically execute allowlisted actions; require approval for others | 120 seconds | Timeouts and network errors only; up to 2 retries | Record command, arguments, exit code, and duration | Restore workspace changes with user approval |
| Irreversible actions or external effects | Delete files, push code, call production APIs, install global dependencies | Require separate human approval for each action | Determined during approval | No automatic retries | Record approver, time, and full parameters | No automatic rollback; manual intervention required |
3.2 Enforce Permissions in the Execution Layer
A prompt instruction such as “do not delete files” is not a reliable security boundary. Enforce permissions in the execution layer.
For example:
# Action names map to concrete commands in project configuration.# The model can select an action name, but cannot submit arbitrary command strings.COMMAND_MAP = load_project_commands() # For example: {"test": ["pytest", "-q"], "lint": ["ruff", "check", "."]}def run_command(action: str, workdir: str):if action not in COMMAND_MAP:return require_user_approval(action) # Send non-allowlisted actions for human approvalargv = COMMAND_MAP[action]assert_inside(workdir, PROJECT_ROOT) # Reject working directories outside the projectaudit_log(action=action, argv=argv, workdir=workdir)return run_argv(argv, cwd=workdir, timeout=120, shell=False)
Three details are important.
First, pass commands as argument lists and disable shell interpretation. This avoids injection through concatenated command strings.
Second, the allowlist should contain only actions already defined in project configuration. The model must not be able to bypass it by appending arguments or make commands access paths outside the project directory. The working-directory check shown above is one part of that boundary, not a complete restriction on what a command can access.
Third, even allowlisted commands can cause damage. Builds may overwrite output directories, tests may delete temporary data, and dependency installation may modify lockfiles. Run these commands in a version-controlled workspace without production connections. If a test requires a production database or real account, remove it from the allowlist.
3.3 Treat Tool Results as Untrusted Input
File contents, command output, and web text returned by tools are data, not instructions.
Even if a file says “ignore previous instructions,” the agent should treat that phrase as ordinary text and notify the user when appropriate. File contents may inform the task, but they must not change permission policies or bypass approval steps.
3.4 Are Fewer Tools Always Better?
No. The goal is to cover the required actions while maintaining clear boundaries.
Even an agent limited to file reads and writes can be dangerous without permission controls. A smaller toolset with well-defined permissions is safer than one whose boundaries are unclear.
Define each tool’s inputs, outputs, and side effects before deciding whether to expose it to the agent.
4. Layer Three: The Verification Loop
Writing code is not enough to complete a task. A reliable coding agent should run checks after making changes and use the results to determine its next step.
4.1 Run Checks in Layers
Run checks from fastest to slowest. If an earlier layer fails, skip subsequent checks to save time and reduce noise.
| Order | Check | Minimal command examples, subject to project configuration | Suggested timeout | Action on failure |
|---|---|---|---|---|
| 1 | Syntax and type checks | python -m py_compile <changed_files>, mypy src |
60 seconds | Stop subsequent checks, locate the reported lines, and re-read the source |
| 2 | Lint | ruff check . |
60 seconds | Automatically fix only through project-configured formatting tools; leave other changes to a human |
| 3 | Unit tests | pytest tests/unit -q |
120 seconds | Distinguish newly introduced failures from existing failures before fixing |
| 4 | Relevant integration tests | pytest tests/integration -k <relevant_module> |
300 seconds | Record failing cases and ask the user to confirm the environment if needed |
| 5 | Build | The project-configured build command | 600 seconds | Inspect dependency and lockfile changes; stop and report unexpected changes |
Create a checkpoint before running checks. This can be a commit on a temporary branch or a saved workspace patch. The checkpoint provides the basis for rollback if validation fails.
4.2 Handle Failures by Category
Different checks call for different responses.
Syntax and Type Failures
- Stop subsequent checks.
- Re-read the latest source using the reported file paths and line numbers.
- Attempt a fix, with no more than two automatic repair attempts.
- If the check still fails, stop and report the error locations and changes attempted.
Lint Failures
- Apply automatic fixes only through formatting commands already configured for the project.
- Run lint again to determine how many issues remain.
- Leave remaining issues that involve program logic to a human rather than modifying them automatically.
Unit Test Failures
- Run the same tests against an unchanged baseline, separately from the checkpointed workspace, to distinguish pre-existing failures from newly introduced ones.
- Fix only failures caused by the current changes.
- After the fix, run the full unit test suite—not just the previously failing test.
Build Failures
- Check for dependency changes and modified lockfiles.
- Retain dependency changes only after user approval.
- If the issue cannot be resolved within two attempts, stop and report it.
Environmental errors, such as timeouts or network interruptions, may be retried. Logic errors should not be retried without a corrective change.
The following pattern illustrates retry handling:
def run_with_retry(step, max_retries=2):for attempt in range(max_retries + 1):result = step()if result.ok or not result.is_transient: # Return immediately for logic errorsreturn resultsleep(2 ** attempt) # Exponential backoffreturn result
Before rolling back, inspect the current diff with version control to confirm the scope of the changes.
