Paul: Today, the spotlight is on Tejas Kumar.
He’s an AI Engineer at IBM in Berlin, the bestselling author of Fluent React, and the host of the ConTejas Code podcast. At tej.as, he digs into the mechanics of agent harnesses, bringing the practical, hype-free technical rigor we love to highlight here.
Enough chitchat. Let’s get into it 👀 ↓
Once your agent loop works, harness engineering keeps coming back to 4 decisions about who owns what:
Who decides the task is done,
who holds the keys,
who says stop, and
who’s to blame when a run goes wrong.
My answer to the first 3 is the harness, in code, with the model proposing and the harness deciding. The fourth is how you find out which of the two to fix.
In April I gave a talk at AI Engineer Europe in London where I harnessed GPT-3.5 Turbo into upvoting a story on Hacker News without changing the prompt once, and it’s been watched over 275,000 times since. The code is public, one branch per step. Since then 2 things have happened to that code that the talk never covered: a developer fixed a bug that made my agent upvote 2 stories when I’d asked for 1, and when I reread the code for this post, I found that my harness could be talked into typing a Hacker News password into a page that wasn’t Hacker News.
Now, to be fair, it’s because I made it to serve a bigger purpose: teach people “baby’s first harness” in ~20 minutes, and it accomplished its mission. Still, there’s a lot we could do to make this a lot more robust.
Paul has spent this series in his course building a coding agent’s harness from a bare loop up through the harness architecture and a sandbox, so I won’t rebuild the loop here. Let’s pick up after it, at the decisions a framework can’t make for you. We’ll use those 2 bugs as the examples.
TL;DR
A model saying it’s done is a claim. Let the harness decide when a task is done by reading the world before and after, from somewhere the agent can’t write to.
Keep secrets, fragile deterministic steps and irreversible actions in the harness and pin where they’re allowed to go by parsing URLs instead of searching them.
Split guardrails into budgets, which end the run, and policies, which refuse 1 action and let the model carry on.
Before you fix a failed run, find the first step that went wrong and replay it: wrong context means a harness bug, and right context that fails some of the time means you measure the model.
Every new piece of code here runs offline with tests, on the after-the-loop branch of the demo repo. The snippets below are trimmed.
The Demo
The agent’s job is to open Hacker News and upvote the highest-ranked story it hasn’t voted on yet, driving a real browser through Playwright. The bare loop hit a login page and reported success anyway. Guardrails capped the iterations and trimmed the context, a verifier read the tool trace and turned the lie into an honest failure. From there, a login handler let the harness sign in so the password never went near the prompt. GPT-3.5 Turbo succeeded in 6 iterations with the same prompt. The full write-up is on my site, and everything below builds on its last branch.
1. Let the harness decide when the task is done
In June, a developer named jonjia opened a pull request called “Fix duplicate upvotes after login redirect” that addressed this directly. When you’re logged out, Hacker News sends an upvote click to /vote?id=NNN&how=up&goto=news, which shows a login form. My harness logged in right there. The thing is, when you log in from that URL, it completes the vote. The harness’s success check only recognized an upvote click that landed back on the front page, so it didn’t count this one, and it told the model, word for word, “Authentication completed by harness. You are now logged in. Navigate back to https://news.ycombinator.com and complete your upvote task.”
So the model did exactly that, and since the top story was already voted on by then, it upvoted the next one. Read the code from before the fix, and you can see how the run ends: the loop stops with “Successfully upvoted”, my verifier finds an upvote click that landed on the front page and passes the run, and 2 stories have been upvoted for a task that asked for 1.
My verifier answered the question I’d asked it, “did an upvote click happen?”, while the task was asking something else: “is exactly the right story upvoted now, and nothing else?”
That’s the gap between the 3 things a harness can trust:

The trace is a real step up from the model’s word, and it’s still a proxy for what you care about. Sierra’s τ-bench, a benchmark for customer service agents, grades a run the bottom-row way: it “compares the database state at the end of a conversation with the annotated goal state”. Anthropic ran into the top row in their harness for long-running coding agents, where they saw “Claude’s tendency to mark a feature as complete without proper testing.” Asking the model whether it’s really done doesn’t close the gap either. Huang and colleagues found that models struggle to correct their own reasoning without external feedback, and sometimes do worse after trying.
Here’s the verifier from the branch, written from the task:
export function verifyOneUpvote(before: Snapshot, after: Snapshot): Verdict {
const target = [...before]
.filter(([, story]) => !story.voted)
.sort(([, a], [, b]) => a.rank - b.rank)[0]?.[0];
if (!target) return { status: “stop”, reason: “Every story on the page was already voted on” };
const newVotes = [...after]
.filter(([id, story]) => story.voted && before.get(id)?.voted === false)
.map(([id]) => id);
if (newVotes.length > 1) return { status: “stop”, reason: `Expected 1 new vote, found ${newVotes.length}: ${newVotes.join(”, “)}` };
if (newVotes.length === 1) {
return newVotes[0] === target
? { status: “done”, reason: `Story ${target} is now voted on` }
: { status: “stop”, reason: `Voted on story ${newVotes[0]}, expected ${target}` };
}
if (!after.has(target)) return { status: “unknown”, reason: `Story ${target} left the front page, so the vote can’t be checked` };
return { status: “retry”, reason: `Story ${target} isn’t voted on yet` };
}The branch has a test that runs the PR #2 run through both verifiers: the trace verifier passes it, and this one stops it with “Expected 1 new vote, found 2: 111, 222”. Three rules go with it:
Take the before snapshot once per task, not once per attempt. A retry that reads a fresh “before” counts the last attempt’s side effect as part of the starting state, and then happily does the task again.
Read the world through the harness, and keep the check where the agent can’t write. In the branch, snapshot is a function the harness owns, and no tool the agent has can reach it. A stronger model doesn’t make this go away: METR reported recent frontier models “attempting (often successfully) to get a higher score by modifying the tests or scoring code”.
Give the verifier 4 answers. done ends the task, retry means nothing happened yet so another attempt is safe, stop means something happened that another attempt would make worse, and unknown means the check can’t tell. A verifier that can only say yes or no has to round “I can’t tell” one way or the other, and whichever way it rounds, you find out in production.
LangChain made the same move from another direction when they took their coding agent from 52.8% to 66.5% on Terminal Bench 2.0 without changing the model: one of their changes was middleware that catches the agent on its way out and reminds it to check its work against the task, so the harness decides whether the run gets to end.
Pro tip: write the verifier from the task, not the trace. “Upvote a story” means exactly 1 new vote, on the right story, and nothing else.
2. Keep the keys in the harness, and pin where they go
Branch 4’s login handler does the thing I still believe in: the password lives in environment variables the model never sees, and the harness types it in. Here’s how it decides it’s looking at a login page:
const isLoginPage = currentUrl.includes(”login”) || currentUrl.includes(”vote”);
Now put that next to the tool registry. browser_navigate accepts any URL and browser_get_text reads any page, so all it takes is a page, or a story title, that talks the model into visiting https://some-other-site.example/login, and if that page has fields named acct and pw, my harness fills in the credentials from its environment and presses submit. The model never saw the password, and it still got to decide where the password went. I haven’t seen this happen, and it would take a page built for it, but nothing in the code stops it, and a test in the branch shows the handler typing the password into https://evil.example/login. Simon Willison calls this combination the lethal trifecta: “private data, untrusted content, and external communication” in one agent, and my demo has all 3 in about 750 lines. OWASP files it under Excessive Agency: a tool that can go anywhere, for a task that needs 1 site.
The fix takes 3 changes, and none of them touches the prompt:
Log in before the run starts. Playwright can save an authenticated browser state and load it into a new context, so the agent starts signed in and never meets a login form. Playwright’s docs warn that the file “may contain sensitive cookies and headers that could be used to impersonate you”, so it’s a secret too, and it stays with the harness.
When the harness has to act mid-run, parse the URL and compare origins. Searching a string for “login” matches evil.example/login, news.ycombinator.com.evil.example/login and evil.example/?next=news.ycombinator.com/login, and a parsed URL matches none of them:
export const HN = new URL(”https://news.ycombinator.com”);
const AUTH_PATHS = new Set([”/login”, “/vote”]);
export function needsHarnessLogin(rawUrl: string): boolean {
if (!URL.canParse(rawUrl)) return false;
const url = new URL(rawUrl);
return url.origin === HN.origin && AUTH_PATHS.has(url.pathname);
}Give the model a narrower tool. The branch swaps browser_navigate(url) for hn_open(path), which resolves the path against Hacker News and then checks where it actually points, because //evil.example/login looks like a path and resolves to another site. Anthropic’s advice for this is to “poka-yoke your tools”: “Change the arguments so that it is harder to make mistakes.”
The paper on design patterns for securing LLM agents against prompt injections states the rule behind all 3 as plainly as I’ve seen it: “once an LLM agent has ingested untrusted input, it must be constrained so that it is impossible for that input to trigger any consequential actions”. Typing a password into a form is a consequential action, and so is an upvote.
The harness holds a second kind of key, too. If your agent calls an API with side effects, like issuing a refund, and your harness retries, idempotency keys are how Stripe lets you retry “without accidentally performing the same operation twice”. The harness should make that key once per task and send the same one on every attempt, because if the model makes it up, a retry can make up a new one, and the API has no way to know it’s the same refund. Hacker News has no idempotency keys, which is why the task-level snapshot from decision 1 does that job here.
Pro tip: moving a secret out of the prompt is half of it. Also pin where the harness is allowed to use it, with a check that nothing the model reads can steer.
3. Split guardrails into budgets and policies
Paul wrote earlier in this series that “the permission layer is the most important guardrail”, the thing that asks you before risky actions, and for a coding agent with you sitting next to it I agree. Plenty of agents run with nobody there to ask, like my Hacker News one, so the harness has to answer by itself, and it helps to split guardrails into 2 kinds:
Budgets (iterations, tokens, money, wall clock time) end the run, with a reason the harness can route: retry, escalate or report.
Policies (this action, with these arguments, isn’t allowed in this task) refuse 1 action and hand the refusal back to the model as the tool result, so it can pick something else.
My demo only had budgets, and when I went back to them for this post, I found one that can’t fire. The guardrails include maxMessages(50), and the loop trims the context to 20 messages right before the guardrails run, so the count that guardrail sees never gets past 20. I showed that guardrail on stage and wrote about it, and it has never once been able to stop anything. Wild. The same trimmer keeps the last 18 messages whatever they are, so it can keep a tool result and drop the assistant message that asked for it, and OpenAI’s API rejects exactly that with “messages with role ‘tool’ must be a response to a preceding message with ‘tool_calls’” (their spelling). Neither one broke the demo on stage, which finished in 6 iterations, and the branch now has a test that shows each of them. Every guardrail gets a test that drives it past its limit through the real loop, and every trimmer cuts in whole turns.
The cheapest policy I didn’t write came straight from the task: “upvote a story” allows 1 upvote, so the harness should refuse a second, and that alone would have stopped the PR #2 run before the second vote.
beforeTool(tool: string, args: Record<string, unknown>): GuardDecision {
if (policy.classify(tool, args) !== “irreversible”) return { kind: “run” };
if (irreversible >= policy.maxIrreversible) {
return {
kind: “refuse”,
tellModel: `Refused: this task allows ${policy.maxIrreversible} such action and it has been used. Check the page and report what happened.`,
};
}
irreversible++; // count the attempt, not the success
return { kind: “run” };
}It counts the attempt and not the success, because in PR #2 the click “failed” into a login page and the vote landed anyway. And it has to classify a generic browser_click by looking inside its arguments, since the same tool clicks a harmless “More” link and casts a public vote. A dedicated hn_upvote(storyId) tool would let the harness see the consequence by name, which is one more reason to give the model narrow tools.
A refusal only helps if the model can do something with it. Anthropic’s guide to writing tools for agents says error responses should “clearly communicate specific and actionable improvements, rather than opaque error codes or tracebacks”, and a refusal is an error response. For the order in which policies apply, Claude Code’s permission rules are a good model: they’re “evaluated in order: deny, then ask, then allow” and the first match wins, so a narrow “yes” can’t undo a broad “no”.
For budgets, take the number from your runs. My demo succeeded in 6 iterations on stage, and the repo caps it at 15, and the way to pick that number is to run the task a few dozen times, look at how many iterations the successful runs took, set the cap a little above the slowest one, and then watch how often it fires, because a cap that fires on runs that were about to succeed is making your agent worse.
Pro tip: save ending the run for budgets, and make every policy refusal a tool result the model can act on.
4. Find the first wrong step, then replay it
When a run fails, you have to decide what to fix, and finding the cause is harder than it looks. The Who&When study (ICML 2025) tested automated ways to find the cause of failures in logs from 127 multi-agent systems, and the best method named the responsible agent 53.5% of the time and the decisive step 14.2% of the time. Meanwhile, both sides moved results: LangChain’s jump came from the harness alone, and Paul built a benchmark for his own agent where the smaller model won. Here’s the order I’d go in:
Find the first step that went wrong, not the last. In PR #2, the last wrong step was the second upvote, and the first was my harness telling the model to “complete your upvote task” after the vote had already landed.
Look at exactly what the model saw at that step. My demo can’t do this, because it records how many messages the model saw and not the messages. The branch wraps the completion call and keeps a copy of every request, and it has to be a copy, since the loop keeps pushing into the same array after the call:
export function recording(complete: Complete, log: RecordedCall[]): Complete {
return async (model, messages, tools) => {
const reply = await complete(model, messages, tools);
log.push({ model, messages: structuredClone(messages), tools, reply });
return reply;
};
}Ask whether a careful person with that exact context would have done better. If they wouldn’t have, because something was missing, stale, trimmed away or misleading, it’s the harness. In PR #2, the model followed the harness’s instructions to the letter, so that one’s on me. On branch 0, the last tool result the model got said it was now on a /vote URL and not back on the front page, and it had tools to check, and it claimed success anyway, so the lie is the model’s, and believing it was the harness’s.
If the context was right, replay that step. The branch’s replay sends the recorded request to your model and to a stronger one, 10 or 20 times each, and counts the wrong answers. Wrong every time on every model usually means the task or the tool is confusing, which is the harness again. Wrong only on the weaker model is the model. Wrong some of the time is a distribution, and τ-bench’s pass^k is the number to watch there: it asks whether an agent succeeds on all k tries of the same task, and GPT-4o came in under 25% at k = 8 on the retail tasks, so 1 green run tells you very little.
Fix it once, then keep the run. Add the failing case to your evals so it can’t come back quietly.
Pro tip: if a failure reproduces every time with the same inputs, look at the harness first, and if it comes and goes, measure it before you blame anything.
What I still don’t know
Everything here leans on the world having a source of truth the harness can read. Hacker News has one, a database has one, and a test suite is one, but a lot of agent work doesn’t: a summary, a research answer, a plan. The usual answer there is a model grading the output, which is a model checking a model, and I don’t know yet how to make that as trustworthy as reading a database.
In the talk, I said I hope 2027 is the year of dynamic harnesses, where an agent builds the harness for a task before it starts. I still want that, and writing this made me wonder who writes the verifier in that world, since the whole point of decision 1 is that the agent can’t touch it. If you’ve got either of these working, I’d love to hear how.
Takeaways
Let the harness decide done, from the world before and after, with 4 possible answers, from somewhere the agent can’t write.
Keep the keys in the harness, and pin where they go by parsing URLs, not searching them.
Budgets end runs and policies refuse actions, and every guardrail gets a test that makes it fire.
Find the first wrong step and replay it before you decide whether to fix the harness or change the model.
If you want to go further:
Watch the talk: Harnesses in AI: A Deep Dive
Read the demo write-up: What Is an Agent Harness?
Run the code: the after-the-loop branch, then npm test
Build one live with me: a free Maven Lightning Lesson on November 18
Bring it to your team: my workshop on building agent harnesses
“Till next time
Tejas Kumar
Enjoyed the article? The most sincere compliment is to restack this for your readers.
Whenever you’re ready, here is how I can help you
Go from agent user to agent builder. Master the foundations of AI agents and turn fragile demo code into reliable, production-ready systems with my course, Agent Engineering: Building Multi-Agent Systems (made with Towards AI).
35 lessons. Pure foundations from scratch. 4 mini-projects. 2 production systems. A certificate and direct access to me & industry experts in our Discord.
Built for software and data professionals transitioning into AI engineering. Rated 5/5 with 300+ students. The first 7 lessons are free:
Not ready to commit? Start with our free Agent AI Engineering Guide, a 6-day email course on the mistakes that silently break AI agents in production.
Images & videos
If not otherwise stated, all images and videos are created by the author.





