Introduction
AI coding agents can inspect repositories, change files, run commands and open pull requests. But producing a plausible patch is not the same as delivering production-ready software. Harness engineering is the discipline of designing the context, tools, permissions, feedback loops and verification that make agent-driven development safe and useful.
This guide moves beyond definitions. You will build a practical harness for a Spring Boot service, follow an agent through a realistic feature, examine failure cases, add security controls, and measure whether the system is actually improving engineering outcomes. The examples are illustrative starting points: adapt package names, versions, policies and checks to your own repository.
1. The Real Problem: Code Generation Is Not Software Delivery
A coding agent can generate a controller that compiles and still implement the wrong business rule. It can add a test that passes while missing an authorization flaw. It can update a database query without considering an index, a migration, or the production data volume.
These are not unusual edge cases. They reveal a basic distinction:
- Code generation asks whether a model can produce a syntactically plausible change.
- Software delivery asks whether the change satisfies requirements, preserves system invariants, is secure, is maintainable and can be operated.
A developer normally supplies much of the missing context through experience: which module owns a rule, which test command matters, how migrations are handled, what must never be logged, and when a design needs review. An agent does not automatically inherit that knowledge.
A useful way to think about the problem is:
Outcome = model capability × harness quality × task clarity
This is a conceptual model, not a scientific formula. It highlights that a strong model cannot compensate indefinitely for an unsafe or confusing environment. Likewise, a carefully designed harness cannot make an incapable model solve every task.
The engineering goal is not to remove developers from the process. It is to move their effort toward architecture, task definition, risk decisions and verification, while delegating bounded implementation work.
2. What a Harness Actually Contains
A harness is the system around the model that determines what it can see, what it can do, how it receives feedback and how completion is established. It is more than a long instruction file.
A practical coding harness has these components:
| Component | Responsibility | Example |
|---|---|---|
| Task contract | Defines the requested outcome | Acceptance criteria and non-goals |
| Context | Makes relevant project knowledge discoverable | AGENTS.md, architecture docs, API contracts |
| Tools | Provides controlled ways to inspect and change the system | Git, shell, test runner, browser |
| Permissions | Limits possible actions | Read-only credentials, isolated worktree |
| State | Records progress and decisions | Plan, changed files, test results |
| Feedback | Shows whether the change works | Compiler, tests, linters, static analysis |
| Verification | Independently checks completion | CI and human review |
| Observability | Makes the run understandable after the fact | Logs, command history, diffs, trace |
| Stop conditions | Prevents endless or unsafe execution | Attempt, time and cost limits |
The model is only one part of this arrangement. A harness can be implemented with a coding-agent CLI, an IDE agent, a hosted agent platform or an internal runtime. The principles remain similar even when the product interfaces differ.
Do not confuse the harness with the agent's prompt. A prompt communicates intent. The harness enforces boundaries and supplies evidence. If a rule is important enough that violating it could expose data or damage a system, do not rely on prose alone.
3. Start With a Legible Repository
An agent cannot reliably follow architecture that exists only in a senior engineer's memory. The repository should explain how it is organized, how to run it, how to test it and which constraints matter.
A useful starting layout might look like this:
orders-service/
├── AGENTS.md
├── README.md
├── docs/
│ ├── architecture.md
│ ├── testing.md
│ ├── security.md
│ └── decisions/
├── src/
│ ├── main/
│ └── test/
├── build.gradle
└── .github/
└── workflows/
└── ci.yml
Keep the top-level agent instructions short. Treat them as a map to the right documentation, not as a dumping ground for every fact about the application. Put detailed domain rules near the relevant module when your agent tooling supports scoped instructions.
For example:
# Repository guide for coding agents
## First steps
- Read README.md and the relevant document in docs/.
- Inspect existing code before proposing a new abstraction.
- Follow the package structure and naming conventions already in use.
## Architecture
- Controllers handle HTTP concerns only.
- Business rules belong in services or domain objects.
- Repositories own persistence access.
- Do not introduce a new framework without approval.
## Verification
- Run ./gradlew test for relevant changes.
- Run ./gradlew check before declaring a task complete.
- Add or update tests for every behavior change.
## Safety
- Never access production systems or production credentials.
- Never commit secrets, tokens, private keys or real customer data.
- Do not run destructive database or infrastructure commands.
- Report commands that could not be run and explain why.
## Completion report
Summarize the implementation, files changed, tests run,
known limitations and any decisions requiring human review.
This is a baseline, not a universal standard. Some agent tools recognize AGENTS.md; others use different instruction files or configuration mechanisms. Check the documentation for the specific tool you use.
Make documentation actionable
Weak instruction: "Follow clean architecture."
Actionable instruction: "Controllers must not call repositories directly. Put business rules in the service layer. A controller test should verify HTTP mapping; service tests should verify the business rule."
The second version can be understood and checked. Prefer concrete examples, links to canonical documents and commands that can be executed.
4. Define Tasks Like Small Engineering Contracts
A vague request such as "improve order handling" gives an agent too much room to invent scope. A strong task defines the user-visible outcome, constraints, acceptance criteria and non-goals.
Use a task contract like this:
# Task: Add an order payment-status endpoint
## Goal
Expose the payment status of an order to its owner.
## Endpoint
GET /api/orders/{orderId}/payment-status
## Acceptance criteria
- Return 200 with the current status for the authenticated owner.
- Return 404 when the order does not exist.
- Do not disclose whether another user's order exists.
- Return 401 when the request is unauthenticated.
- Do not return payment-provider credentials or internal metadata.
- Add tests for owner access, another user's order, missing order
and unauthenticated access.
## Constraints
- Reuse the existing authentication and service patterns.
- Do not change the database schema.
- Do not add a new dependency.
- Do not call a real payment provider in tests.
## Out of scope
- Changing payment state.
- Refunds or payment retries.
- Administrative endpoints.
## Before implementation
Inspect the existing order, payment and security code.
Write a short plan and identify assumptions.
Acceptance criteria should describe observable behavior, not prescribe every line of code. If the implementation is over-specified, the agent may follow instructions mechanically while missing a simpler design already used in the codebase.
Split work at meaningful boundaries
A task is a good candidate for an agent when it has a clear result and can be verified. Split broad work into smaller tasks when each part has different risks or ownership. For example, database migration design, payment-provider integration and authorization policy may deserve separate review gates.
A useful rule: if a reviewer cannot explain how to prove the task is complete, the task is not ready to delegate.
5. Build a Safe Execution Environment
An agent that can run shell commands is powerful. That does not mean it should inherit every permission of the developer's laptop.
Start with least privilege:
- Use a dedicated development environment or isolated worktree.
- Give the agent access only to the repository and tools required for the task.
- Keep production credentials out of local agent environments.
- Prefer short-lived, scoped credentials where access is unavoidable.
- Require approval for deployments, destructive operations and external side effects.
- Restrict network access when the task does not need it.
- Set limits for execution time, retries and spending.
A useful permission matrix:
| Action | Default policy | Reason |
|---|---|---|
| Read repository files | Allow | Needed to understand the project |
| Edit files in task worktree | Allow | Core implementation activity |
| Run unit tests and linters | Allow | Local feedback |
| Install arbitrary packages | Review or restrict | Supply-chain and execution risk |
| Read environment secrets | Deny | Not needed for ordinary coding |
| Access production database | Deny | High-impact data access |
| Push directly to protected branch | Deny | Bypasses review |
| Deploy to production | Human approval | External, high-impact action |
The exact controls depend on the agent runtime. A configuration file may describe allowed commands, but the operating system, container, credential store and CI permissions must enforce the actual boundary.
Treat repository content as untrusted input
An agent may read issue descriptions, comments, documentation, generated files or test fixtures that contain instructions. Those instructions should not automatically override the task or the system's security policy. A malicious string in a README or issue comment should not be able to authorize secret disclosure or deployment.
This is one reason prompt-injection defenses cannot rely on asking the model to "ignore malicious instructions." Restrict tools and credentials so that a mistaken decision cannot become a high-impact action.
6. Create a Feedback Loop That Can Prove Progress
An agent needs fast, useful feedback. "Try again" is not feedback. A compiler error, failing assertion or static-analysis finding is much more useful because it identifies a concrete condition.
A sensible verification ladder is:
- Formatting and linting: Catch simple style and consistency issues.
- Compilation: Verify that the project builds.
- Unit tests: Check focused business behavior.
- Integration tests: Check interactions with persistence, messaging and frameworks.
- Security checks: Scan dependencies, secrets and code patterns.
- Architecture checks: Verify boundaries and dependency rules.
- End-to-end tests: Validate critical user journeys.
- Human review: Evaluate design, risk and business correctness.
Run fast checks frequently and expensive checks at appropriate gates. Do not run a full end-to-end suite after every tiny edit if a focused unit test gives faster feedback. But do not let a green unit test become a substitute for the integration checks the change actually needs.
Example: a test that checks ownership
The following service-level example illustrates the security property. Adapt the constructors and exception handling to your domain model.
@Test
void shouldNotExposeOrderOwnedByAnotherUser() {
UUID orderId = UUID.randomUUID();
UUID currentUserId = UUID.randomUUID();
UUID differentOwnerId = UUID.randomUUID();
Order order = new Order(orderId, differentOwnerId);
when(orderRepository.findById(orderId))
.thenReturn(Optional.of(order));
assertThrows(
OrderNotFoundException.class,
() -> orderService.getPaymentStatus(orderId, currentUserId)
);
}
Returning the same not-found result for a missing order and an order owned by someone else can avoid disclosing resource existence. The exact API policy is a product and security decision; make it explicit and test it.
A test like this is more valuable than a test that only checks whether the endpoint returns JSON. It encodes a security invariant.
7. A Worked Example: From Request to Verified Pull Request
Consider the payment-status endpoint from Section 4. A disciplined agent run should produce evidence at each stage.
Step 1: Inspect. The agent reads the controller, service, repository, authentication model and existing tests. It identifies how the current user is represented and how the application handles inaccessible resources.
Step 2: Plan. It proposes a small change: add a response DTO, a service method that checks ownership, a controller mapping and focused tests. It does not change the schema or contact the payment provider.
Step 3: Implement. The agent follows existing project conventions. It reuses the authentication principal and does not invent a second authorization mechanism.
Step 4: Verify. It runs the relevant service and controller tests, then the project verification command. CI repeats the required checks independently.
Step 5: Report. It summarizes the files changed, commands executed, test results, assumptions and unresolved issues.
A good completion report might look like:
Implemented:
- Added GET /api/orders/{id}/payment-status.
- Added owner check in OrderService.
- Added response DTO and controller mapping.
Verification:
- OrderServiceTest: passed
- OrderControllerTest: passed
- ./gradlew check: passed
Security behavior:
- Unauthenticated requests are rejected.
- Requests for another user's order return the configured
not-found response.
Not changed:
- Database schema
- Payment-provider integration
- Payment state transitions
Review notes:
- Confirm that the not-found behavior matches the public API policy.
This report is not proof by itself. It is an index to evidence: the diff, test output and CI run. A harness should make it easy for a reviewer to inspect that evidence.
8. Put Independent Verification in CI
Local agent feedback is useful, but the agent should not be the final authority on whether its own work passes. CI provides a repeatable check in a separate environment and creates a shared record for reviewers.
A simplified GitHub Actions workflow for a Gradle project:
name: CI
on:
pull_request:
push:
branches: [main]
permissions:
contents: read
jobs:
verify:
runs-on: ubuntu-latest
steps:
- name: Check out repository
uses: actions/checkout@<REVIEWED_FULL_COMMIT_SHA>
- name: Set up Java
uses: actions/setup-java@<REVIEWED_FULL_COMMIT_SHA>
with:
distribution: temurin
java-version: '21'
cache: gradle
- name: Run verification
run: ./gradlew --no-daemon clean check
The SHA values above are deliberate placeholders. Replace them with reviewed, full-length commit SHAs for the exact action versions you choose. Do not paste placeholder values into a live workflow.
The workflow uses read-only repository permissions because this job only checks code. Add permissions at the narrowest level only when a job genuinely needs them. A publishing or deployment job should be separate from ordinary verification and should have its own approval and credential controls.
CI should not simply rerun whatever command the agent says it ran. The repository's trusted workflow defines the required checks. Protect the default branch so changes cannot bypass those checks and required human reviews.
9. Prevent the Agent From Marking Its Own Homework
A subtle failure occurs when the same agent writes code, writes tests that encode its assumptions and then declares the task complete because those tests pass.
The answer is not to distrust every generated test. It is to use independent sources of verification.
Useful techniques include:
- Derive acceptance criteria from the task contract before implementation.
- Keep critical security and business invariants in tests maintained by the team.
- Use integration tests to verify behavior across real boundaries.
- Use static analysis and dependency scanning that do not depend on the agent's interpretation.
- Review the diff for deleted tests, weakened assertions and disabled checks.
- Test negative cases, not only the happy path.
- Use a separate reviewer or review process for high-risk changes.
For example, if the task is to prevent users from reading other users' orders, the test must construct a different owner. A test that only checks that the endpoint returns 200 OK does not verify the security requirement.
Also inspect test changes carefully. An agent may "fix" a failing test by changing the expected result instead of fixing the implementation. That can be legitimate when requirements changed, but it requires an explanation and review.
10. Security: Prompt Injection, Secrets and Excessive Agency
Coding agents combine language-model reasoning with tools that can read files, execute commands and interact with external systems. That creates a security boundary around the agent runtime.
Three risks deserve special attention.
Prompt injection and untrusted content
An issue description, web page, source comment or dependency README may contain instructions that attempt to redirect the agent. Treat such content as data, not as authority. The agent should not be able to elevate its permissions because text told it to do so.
Secret exposure
Do not make secrets available just because a tool might need them someday. Keep secrets out of repository files, prompts, logs and test fixtures. Use scoped credentials and avoid exposing deployment credentials to ordinary coding tasks.
Excessive agency
An agent may have more tools, permissions or autonomy than the task requires. Limit each of these separately. A read-only research task does not need write access. A code change does not need production access. A pull-request agent does not need permission to merge to the protected branch.
A useful threat-model question is:
If the agent follows a malicious instruction or makes a serious mistake, what is the maximum damage it can cause?
Reduce that blast radius through isolation, least privilege, approval gates and independent monitoring. For a broader taxonomy, consult the OWASP Top 10 for Agentic Applications 2026 and OWASP's guidance on Excessive Agency.
11. Common Harness Engineering Mistakes
| Mistake | Why it fails | Better approach |
|---|---|---|
| One enormous instruction file | Important rules become hard to find and maintain | Keep a short index and link focused docs |
| Vague tasks | The agent invents scope and assumptions | Define outcomes, constraints and non-goals |
| Broad shell access | A mistake can affect unrelated files or systems | Isolate execution and restrict permissions |
| Trusting self-reported tests | Reports can be incomplete or inaccurate | Re-run checks in independent CI |
| Testing only happy paths | Authorization and failure behavior remain untested | Add negative and boundary cases |
| Letting the agent change CI freely | Verification can be weakened to make a build green | Protect workflows and require review |
| Optimizing for lines of code | Output volume is not business value | Measure accepted, correct outcomes |
| Unlimited retries | Cost rises while the agent can repeat the same failure | Set budgets and escalation conditions |
| Ignoring documentation drift | Agents keep using obsolete guidance | Review docs as part of normal changes |
| Giving every task equal autonomy | Risk differs dramatically by change type | Use risk-based approval levels |
The most dangerous mistake is treating a successful tool call as a successful engineering outcome. The agent may have completed every command and still delivered the wrong behavior.
12. Measure Quality, Speed and Cost
If a harness is meant to improve engineering, measure outcomes rather than activity. Token counts, generated lines and number of tool calls can help diagnose a run, but they are not success metrics.
Start with a baseline using ordinary team workflows. Then run a representative set of tasks with the harness. Compare similar task types and record the sample size, task difficulty and review policy.
| Metric | What it tells you | How to measure |
|---|---|---|
| Acceptance rate | How often a task is accepted without major rework | Accepted tasks ÷ completed tasks |
| Escaped defect rate | Whether defects reach later stages | Defects found after merge per change |
| Review time | Human effort needed to validate changes | Active review minutes per pull request |
| Rework rate | How often changes need substantial correction | Reworked tasks ÷ completed tasks |
| Lead time | Time from task start to accepted change | Timestamp difference |
| Cost per accepted task | Economic cost of useful output | Model and infrastructure cost ÷ accepted tasks |
| Policy violations | Whether the agent crosses defined boundaries | Logged denied or blocked actions |
| Test effectiveness | Whether checks catch seeded or known faults | Detected faults ÷ faults introduced in controlled tests |
A small measurement example
Suppose a team completes 40 comparable tasks during a pilot. If 30 are accepted without major rework, the observed acceptance rate is:
30 / 40 = 75%
That is a result for this hypothetical sample, not a claim about coding agents generally. The team should also record task complexity, defect severity and human review time. A 75% acceptance rate may be poor for low-risk formatting tasks and entirely different for complex changes involving authorization or money.
Do not compare a pilot with a historical baseline unless the tasks and review rules are reasonably comparable. Report the sample size and uncertainty. Small samples can produce misleading conclusions.
13. Use Risk-Based Autonomy, Not One Permission Level
Not every task deserves the same amount of freedom. A documentation typo and a payment authorization change have different consequences.
A practical autonomy model:
| Level | Agent may do | Human involvement |
|---|---|---|
| 0: Assist | Explain, search and propose changes | Human performs edits |
| 1: Local edit | Modify an isolated worktree and run safe checks | Human reviews all changes |
| 2: Pull request | Prepare a branch and open a PR | Human approves merge |
| 3: Bounded maintenance | Handle predefined low-risk tasks under policy | Sampling and exception review |
| 4: Sensitive operations | No independent production authority by default | Explicit approval and controlled execution |
This is an example maturity model, not an industry standard. An organization should define levels according to its threat model, regulatory obligations and operational controls.
Increase autonomy only after evidence shows that the system performs reliably for a particular task class. Do not infer that because an agent handles dependency updates well, it is ready to change payment logic or infrastructure.
14. Keep the Harness Healthy Over Time
A harness is not a one-time setup. Repositories change, dependencies evolve, architecture decisions are revised and tests become stale. An outdated instruction can be worse than no instruction because it gives the agent confidence in the wrong approach.
Create a maintenance loop:
- Capture recurring agent mistakes and reviewer feedback.
- Decide whether each issue needs documentation, a test, a lint rule or a permission change.
- Make the smallest durable change that prevents recurrence.
- Run a fixed evaluation set to check for regressions.
- Review whether the new rule creates unnecessary friction.
- Record the decision and its owner.
Prefer executable rules for important invariants. If a dependency direction must never be violated, an architecture test is stronger than a paragraph saying "please keep modules decoupled." Documentation explains intent; automated checks enforce conditions that can be expressed mechanically.
Avoid adding a rule for every isolated mistake. Too many overlapping instructions create noise. Look for repeated failure patterns and address the underlying cause.
15. A Practical 30-Day Adoption Plan
A small pilot is more informative than a company-wide rollout based on enthusiasm.
Week 1: Establish the baseline
- Choose one repository and one task category.
- Record normal lead time, review time, rework and defect data.
- Document the build and test commands.
- Identify sensitive files, credentials and production boundaries.
Week 2: Make the repository legible
- Add a concise agent instruction file.
- Document architecture and testing conventions.
- Create a task template with acceptance criteria.
- Add or repair automated checks for critical invariants.
Week 3: Run a controlled pilot
- Use isolated worktrees or an equivalent sandbox.
- Start with low- and medium-risk tasks.
- Require pull requests and human review.
- Record agent actions, failed checks, costs and reviewer feedback.
Week 4: Evaluate and adjust
- Compare results with the baseline.
- Review defects and near misses, not just successful tasks.
- Remove ineffective instructions and add durable checks for repeated failures.
- Decide which task categories can safely receive more autonomy.
At the end of the pilot, the team should be able to answer three questions: Did the harness improve useful delivery? Did it preserve or improve quality? Did it keep risk within acceptable limits? If the data cannot answer those questions, extend the experiment rather than declaring success.
16. A Pre-Production Checklist
Before allowing an agent to work on a production repository, check the following:
- The task has a clear outcome, acceptance criteria and non-goals.
- Repository instructions are short, current and linked to detailed documentation.
- Build, test and lint commands are documented and reproducible.
- The agent works in an isolated environment or worktree.
- Credentials are scoped and production secrets are unavailable by default.
- File, shell, network and tool permissions follow least privilege.
- Destructive actions and external side effects require approval.
- CI independently runs required checks.
- Critical security and business invariants have tests.
- Reviewers can inspect the diff and verification evidence.
- Retries, runtime and cost have explicit limits.
- Agent runs leave enough logs or artifacts to investigate failures.
- A human owns the decision to merge and deploy sensitive changes.
A checked box is not a substitute for testing the control. Verify the actual behavior of the environment, including what happens when the agent attempts a denied action.
17. Further Reading and Technical References
These sources provide useful starting points for deeper study:
- OpenAI: Harness engineering in an agent-first world — a production-oriented account of repository legibility, feedback loops and agent-driven engineering.
- Martin Fowler: Harness engineering for coding agent users — a useful discussion of feedback, confidence and engineering controls around coding agents.
- OWASP Top 10 for Agentic Applications 2026 — security risks and mitigation guidance for agentic systems.
- OWASP: Excessive Agency — why excessive functionality, permissions and autonomy create risk.
- GitHub: Secure use of GitHub Actions — workflow permissions, action pinning and supply-chain considerations.
- Spring Boot: Testing Spring Boot Applications — official guidance for application testing.
- Spring Boot: Testcontainers — integration testing with real services in containers.
Conclusion: Engineer the Conditions for Trust
Harness engineering is not about giving an AI agent more freedom and hoping that a better model will make the risks disappear. It is about creating an environment where the agent has enough context to do useful work, enough feedback to correct mistakes and only the permissions required for the task.
The practical lessons are straightforward:
- Make the repository legible: Put architecture, conventions and commands where both people and agents can find them.
- Make success verifiable: Define acceptance criteria and use independent tests and CI rather than trusting a completion message.
- Make failure bounded: Isolate execution, restrict permissions, set limits and keep humans responsible for high-impact decisions.
Start with one repository and one well-defined task category. Measure the results, fix recurring failure modes and expand autonomy only when the evidence supports it. The goal is not to maximize the amount of code an agent writes. It is to increase the amount of correct, maintainable software a team can confidently deliver.




