AI

From Prompts to Harnesses: AI Concepts a Web Developer Should Know

· 35 min read

From Prompts to Harnesses: AI Concepts a Web Developer Should Know
Contents

I’ve been working with Claude Code for a while now, and writing new features is a smaller part of it than you might expect. A lot of it is documentation. Some of that is for people: an onboarding guide that needed restructuring, deployment and troubleshooting guides, plus the usual README and CHANGELOG updates and release notes. Some is for Claude itself. On one project about fifteen documents, a bit over 3,000 lines, describe the architecture, the API, the user flows and even what we would do differently next time, and that’s the context Claude works from there. Then there are reports: incident write-ups, a memory leak analysis and an asset inventory for people outside engineering.

QA gets its share too. After a deploy or a framework upgrade I ask for a note on what QA should focus on (the longest so far ran to 237 lines). Claude writes tests as well. It did e2e gap analyses for two sites and a Playwright visual comparison of a local build against the live site. On one project there’s now a skill that writes a regression spec named after the ticket, so it fails before the fix and passes after. Another time it built stress fixtures with the longest user IDs and with CJK and Russian names, then screenshotted the UI in every language.

For audits I give it a role first, something like “act as a principal engineer”, “as an SEO expert” or “think like a senior QA engineer”. That’s how I got a security audit, a list of the top 20 improvements and a 12-month roadmap.

At first all of this was one-off prompts. The things I kept retyping went into a project instructions file that grew and grew, and later some of them turned into custom skills. That “think like a senior QA engineer” prompt, for example, used to sit in a notes file I copied it from. Now it’s a skill Claude picks up whenever I ask for a regression checklist.

Right now I’m on a project at work where the model has to keep a lot in mind at once: a third-party API, a style guide, the limits of the UI runtime we target and the company rules for submitting code. Getting further there takes knowledge I don’t have yet, so I went looking.

As it turned out, every step I took has a name, and the industry walked the same path: prompt engineering, context engineering, RAG, agentic RAG, agents and harness engineering. Each of them appeared because the one before it hit a limit. Plenty of developers are nervous about where this is going. My take is that most of it is plumbing you already write every day: HTTP requests, search, loops and middleware. Some of these names will probably change again, so don’t get attached to the terms. The ideas underneath them will still be useful.

A rising curve with six milestones: prompt engineering (how you ask), context engineering (what it sees), RAG (your code searches), agentic RAG (the model searches), agents (the model acts) and harness engineering (what it's allowed to do). The vertical axis is how much the model decides on its own. Brackets underneath group them: your code picks what it sees, the model picks what to do, your code sets the limits.
Not a timeline. Each step starts where the previous one hits a limit.

Prompt engineering: a ticket for a contractor#

If you ever typed a question into ChatGPT, got a vague answer and rephrased it, you’ve done prompt engineering already. Doing it on purpose mostly comes down to writing a good ticket.

Most of us have a coding assistant in the editor by now. VS Code comes with GitHub Copilot, which has a free plan. Some of you use Claude Code, and OpenAI’s Codex can be tried for free as well. The prompts below work in any of them. I ran them in Claude Code (Opus 5.5), and your answers will differ a bit, even between two runs of the same prompt.

The project is getup, a small tray app of mine that gets you up from the desk every 30 to 45 minutes. It also notices when you’ve walked away on your own and counts that as a break. Say the timer kept resetting while I was reading a long pull request without touching the mouse. So I raise the idle threshold from 3 to 5 minutes and stage the change:

src/tracker.js

-const IDLE_BREAK = 3 * MIN;        // 3+ minutes without mouse or keyboard: must have stood up
+const IDLE_BREAK = 5 * MIN;        // 5+ minutes without mouse or keyboard: must have stood up

Now the lazy way, the way I’d normally ask:

write a commit message for my staged changes

Output:

fix: count a break only after 5 minutes idle instead of 3

Being away from the mouse and keyboard for 3 minutes was too short to
mean the user actually stood up. Short pauses like reading or a phone
call were counted as breaks.

Not bad, is it? I didn’t paste anything. It ran git diff --staged by itself (that part comes back in the agents section) and read the comment next to the constant. It even matched the fix: prefix of my recent commits without ever running git log. How it knew that is the next section. Around the message it added a note: the second paragraph is a guess, edit it if the reason was different.

The guess even happens to be close. But I ran the same prompt once more:

fix: raise idle break threshold from 3 to 5 minutes

3 minutes without input was too short to count as a real break.

A reason again, and no warning this time. In git history that’s worse than no reason at all, because the next person who reads it will believe it. And it’s the same prompt, so you can’t tell in advance which of the two answers you’ll get.

Let’s write it the way we’d write a ticket for a contractor who has never met our team: who reads the result, the house rules, what done looks like, one example, and what to do when something isn’t clear.

Write a commit message for my staged changes.
It goes into the shared git history, other developers will read it months from now.
Follow Conventional Commits: type(scope): subject.
Subject in imperative mood, at most 60 characters, no trailing period.
Add a body only when the diff alone doesn't explain the change.
Never guess why a change was made. If the reason isn't in the code, end with the line "Why: TODO".
Reply with the commit message only.

Example:
fix(tray): restore the icon after the PC wakes up

Two runs again:

chore(tracker): raise idle break threshold to 5 minutes

Why: TODO
feat(tracker): raise idle break threshold to 5 minutes

Why: TODO

Both kept to the format, took the scope from the file name and left the reason open. No chatter around the message either. The type flipped between chore and feat. Without knowing why the change was made, neither is wrong. If your team has a rule for that, it’s one more line in the prompt.

For me the line that matters is “Never guess why”. The rest is formatting. By the way, the “act as a principal engineer” openers I mentioned at the start are the same trick from another angle. A role tells the model what kind of answer you expect before you even ask.

So is it worth learning? An afternoon, yes. A course, I doubt it. Current models follow plain instructions well, so the exact wording is the smallest lever you have. What matters is what makes any ticket good: who it’s for, what the rules are and what done looks like. Anthropic’s prompt engineering guide and OpenAI’s prompting guide cover the rest. If you read the Browser AI article, the triage there worked the same way: rules in the prompt, plus a JSON Schema for the shape of the answer.

Copilot users have a shortcut for all of this. The sparkle button in the Source Control panel writes the message for you, and that button is just a prompt somebody else wrote. You can add your own rules to it with the github.copilot.chat.commitMessageGeneration.instructions setting. But once rules apply to every request, they’re closer to context than to a prompt.

Now look at what the commit message still can’t say. The code shows the threshold went from 3 to 5 minutes, and the comment explains what the number means. It doesn’t show that the timer kept resetting while I was reading pull requests. That lives in my head, or in an issue at best. No wording fixes that. The information just isn’t anywhere the model can look.

Context engineering: what the model actually sees#

So how did Claude Code know my commits start with fix:, if it never ran git log? I asked it to quote what it had been told about the repo:

Current branch: demo/idle-break-5min

Main branch (you will usually use this for PRs): main

Git user: Dmitry Sheiko

Status:
M  src/tracker.js

Recent commits:
d82e73d fix: when timer reaches 30 min the timer proceeds but wiht red circle
3c1c135 build: optimize SEO
3f88ac5 first commit

Claude Code takes this snapshot when a session starts and puts it into the request next to your prompt. You never see it, and the model never had to ask for it. That’s context engineering in one picture: everything the model gets along with your question, and who decides what goes in.

How much is “everything”? My lazy prompt was ten words. The request that went out carried about 26,400 tokens (a token is roughly three quarters of a word). The rest was Claude Code’s own system prompt, the descriptions of its tools (read a file, run a command, search), the git snapshot and the project’s instructions file, if there is one. The careful ticket-style prompt from the previous section added about 165 tokens. That’s well under one percent of what the model read. Your numbers will differ, since they depend on the tool and its settings. In Claude Code, /context shows the split.

What is “the request”, though? Under every chat box there’s an HTTP call. Here’s one in plain JavaScript:

ask.js

export async function ask( prompt, system ) {
  const res = await fetch( "https://api.anthropic.com/v1/messages", {
    method: "POST",
    headers: {
      "content-type": "application/json",
      "x-api-key": process.env.ANTHROPIC_API_KEY,
      "anthropic-version": "2026-10-21"
    },
    body: JSON.stringify({
      model: "claude-opus-5-5",
      max_tokens: 16000,
      system,
      messages: [{ role: "user", content: prompt }]
    })
  });
  if ( !res.ok ) {
    throw new Error( `${ res.status } ${ await res.text() }` );
  }
  const { content } = await res.json();
  return content.find( ( block ) => block.type === "text" )?.text;
}

A POST with a JSON body and the key in a header. system is where tools like Claude Code put their own instructions, messages is the conversation. The response has one catch: content is an array, and the first block isn’t necessarily the answer. This model thinks before it replies, and the thinking comes back as a block of its own, so we pick the one with type: "text". For a real project I’d take the official SDK (@anthropic-ai/sdk), it handles retries and types for you. Here fetch shows there’s nothing behind it but HTTP.

That JSON body is all the model gets. The API is stateless and doesn’t remember the previous call. When a chat seems to remember, the client simply sends the whole history again:

messages: [
  { role: "user", content: "write a commit message for my staged changes" },
  { role: "assistant", content: "fix: raise idle break threshold from 3 to 5 minutes\n\n..." },
  { role: "user", content: "make it shorter" }
]

It shows in the numbers too. After Claude Code ran git diff, it called the model a second time, and that request carried about 30,200 tokens: all of the first one again, plus the tool call and the diff it returned. Most of it came from the prompt cache, so you don’t pay full price twice, but it still travels with every request.

The payload has a size limit, the context window. For the model I used it’s a million tokens, which sounds like plenty. But every token costs money and time, and models get worse at using what’s in there as it grows. In July 2025 Chroma tested 18 models and found that performance dropped as the input got longer, in every experiment and even on simple tasks. They called it context rot. So stuffing the window doesn’t help. What helps is picking the few things that matter.

That’s also where the missing reason from the previous section goes. It was never a prompt problem. Say I had filed an issue about the timer in the tracker. I take the ticket-style prompt from above, word for word, and add the title and text of the issue at the end:

Write a commit message for my staged changes.
(... the rest of the ticket-style prompt, unchanged ...)

The reason is in this issue:

Break counted while I'm reading
When I read a long pull request, I don't touch the mouse for 3 or 4 minutes. Getup decides I stood up, logs a break and restarts the timer. The next reminder comes 30 minutes later, so by then I've been sitting for over half an hour.

Output:

fix(tracker): raise idle break threshold to 5 minutes

Reading a long pull request can mean 3 or 4 minutes without touching
the mouse or keyboard. With a 3 minute threshold, that counted as a
break and restarted the timer. The next reminder then arrived 30 minutes
later, after the user had been sitting for more than half an hour.

The instructions are the same as before. The only new thing is the issue. A second run came out almost word for word the same. The reason now comes from the issue instead of a guess, and the type stopped flipping between chore and feat. With the issue in view it’s a fix, because the issue describes a bug.

Pasting works when you know which issue it is. Claude Code could also fetch it on its own, with gh issue view or through an MCP connection to your tracker. That’s a tool doing the work, though, and tools come a bit later.

Rules that should hold for every request belong in the context too, not in your prompt. That’s what the Copilot setting from the previous section does, and that’s what instructions files are for: CLAUDE.md in Claude Code, AGENTS.md in Codex, .github/copilot-instructions.md in Copilot. The project instructions file from the intro, the one that kept growing, was context engineering before I knew the word. Skills are the next step of the same idea. The instructions stay on disk, and only a one-line description sits in the context until a task needs the rest.

The term itself is fairly new. In June 2025 Shopify’s CEO Tobi Lütke wrote that he preferred “context engineering” to prompt engineering, calling it “the art of providing all the context for the task to be plausibly solvable by the LLM”. A week later Andrej Karpathy backed it, and it stuck. Anthropic’s post on context engineering for agents is a good next read.

If I had to choose between a better prompt and better context, I’d take the context. The prompt was one percent of what the model read, and the reason for the change only showed up once the issue was in there.

Picking by hand works as long as you know what’s relevant. I knew which issue explained the change. But what if the answer sits somewhere in two thousand help center articles, or in three years of tickets? You can’t paste them all, and context rot says you shouldn’t. Something has to find the right pieces first.

RAG: search, then ask#

Remember Acme, the electronics store from the Browser AI article? Say it has a help center, and we want a box where customers ask in their own words and get an answer from those articles. I wrote thirteen short ones for the demo: passwords, returns, refunds, shipping and so on.

You’ve built half of this before. A site search finds the matching pages and renders a list of results. Here the results go into a prompt template instead, and the model writes the answer from them. That’s RAG, retrieval-augmented generation: search, paste, generate. The name comes from a 2020 paper by researchers at Facebook AI, though what we build here is a lot simpler than what they did.

What kind of search, though? A customer types “I can’t log in”. Our help center says “sign in” everywhere, and “log in” doesn’t appear once. A LIKE query or a plain full-text index finds nothing. So we search by meaning, with embeddings. An embedding model turns a piece of text into an array of numbers, 384 of them for the one I used. Texts that mean similar things get arrays that point in a similar direction, and how similar is one line of code (cosine similarity).

The embedding model runs locally with transformers.js. That’s a JavaScript library from Hugging Face, the site where open models are usually published, and it runs those models in Node or right in the browser. So there’s no key and no bill. The model downloads about 90 MB on the first run.

embed.js

import { pipeline } from "@huggingface/transformers";

const extractor = await pipeline( "feature-extraction", "Xenova/all-MiniLM-L6-v2" );

export async function embed( text ) {
  const output = await extractor( text, { pooling: "mean", normalize: true });
  return Array.from( output.data );
}

First we index. Every article is split into paragraphs (chunks), every chunk gets its vector, and it all goes into a JSON file. That’s our whole vector database:

index-docs.js

import { readdir, readFile, writeFile } from "node:fs/promises";
import { embed } from "./embed.js";

const chunks = [];

for ( const file of await readdir( "help" ) ) {
  const md = await readFile( `help/${ file }`, "utf8" );
  const [ heading, ...paragraphs ] = md.trim().split( /\n\s*\n/ );
  const title = heading.replace( /^# /, "" );

  for ( const text of paragraphs ) {
    chunks.push({ title, text, vector: await embed( `${ title }\n${ text }` ) });
  }
}

await writeFile( "index.json", JSON.stringify( chunks ) );
console.info( `${ chunks.length } chunks` ); // 26 chunks

The title goes in front of each paragraph before embedding. A paragraph cut out of its article often doesn’t say what it’s about, and the title does. Keep that in mind, it comes back in a minute.

Now the question. Embed it the same way, rank the chunks, put the top three into the prompt:

ask-docs.js

import { readFile } from "node:fs/promises";
import { embed } from "./embed.js";
import { ask } from "../ask.js";

const chunks = JSON.parse( await readFile( "index.json", "utf8" ) );

// the vectors are normalized, so the dot product is the cosine similarity
const similarity = ( a, b ) => a.reduce( ( sum, x, i ) => sum + x * b[ i ], 0 );

async function search( question, limit = 3 ) {
  const vector = await embed( question );
  return chunks
    .map( ( chunk ) => ({ ...chunk, score: similarity( vector, chunk.vector ) }) )
    .sort( ( a, b ) => b.score - a.score )
    .slice( 0, limit );
}

const question = process.argv[ 2 ];
const sources = await search( question );

const prompt = `Answer the customer's question using only the help articles below.
Name the article each part of your answer comes from.
If the articles don't answer the question, say so and suggest contacting support.

${ sources.map( ( s ) => `<article title="${ s.title }">\n${ s.text }\n</article>` ).join( "\n\n" ) }

Question: ${ question }`;

console.info( await ask( prompt, "You answer questions from customers of Acme, an online store for home electronics." ) );

ask() is the helper from the previous section. For “I can’t log in” the search returns:

await search( "I can't log in" );
// 0.41 Reset your password: "After five wrong passwords in a row, your account is locked..."
// 0.35 Reset your password: "If you forgot your password, click "Forgot password?" on the sign-in page..."
// 0.31 Reset your password: "If the email doesn't arrive within a few minutes, check your spam folder..."

All three come from the right article, and none of them says “log in”. The model gets these three paragraphs and nothing else from the help center:

$ node ask-docs.js "I can't log in"
Sorry you're having trouble signing in. All of the following comes from the **"Reset your password"** help article:

- **If you've forgotten your password:** Click **"Forgot password?"** on the sign-in page and enter the email address of your Acme account. We'll send you a reset link that is valid for **30 minutes**.
- **If your account is locked:** After five wrong passwords in a row, your account is locked for **15 minutes**. You can wait, or reset your password to unlock it right away.
- **If the reset email doesn't arrive:** Check your spam folder if it hasn't arrived within a few minutes. If you request another reset email, links in older ones stop working, so use the most recent email.

If none of these fit your situation, for example if you get an error message or no longer have access to the email address on your account, the help articles don't cover it. Please contact Acme support.

It comes back as Markdown, ready for a chat widget. It names the article, as the prompt asked, and sends whatever the articles don’t cover to support. For “do you ship to Canada?” it answered with a plain “No” and quoted “within the European Union only” from the shipping article.

On a real site the JSON file becomes a table. Postgres has pgvector, SQLite has sqlite-vec. If you already run Elasticsearch or Algolia, both do vector search these days, and even a decent keyword search is better than none. The model doesn’t care where the chunks came from.

Of all six concepts, this is the one I’d expect a web developer to ship first. It’s a search, a template and one API call. Most “chat with our docs” widgets you’ve seen are this with a nicer UI.

The catch is that the model only knows what the search handed it. For “my headphones stopped working after two months” the search returned the paragraph about returning opened headphones, the “Report a problem” paragraph from the warranty article and, for some reason, the spam folder paragraph from the password reset. The paragraph that says “two-year warranty” didn’t make the top three. So the answer said: “The help articles don’t say how long the warranty lasts, so I can’t confirm whether two months is covered.” They do, one paragraph above. Worse, it told the customer they could still return the headphones, because the 30-day limit sat in another paragraph that wasn’t picked. The model followed every rule in the prompt and still got it wrong.

Two topics in one question fail differently. “I want to send back the speaker and I need the money back on my card” matched on “card” and brought back the gift card balance, declined payments and gift card refunds. The answer: our help articles “don’t fully cover returning an item”. There’s an article called “Return an item”. And a plain “hi” runs a search too. It pulled two password paragraphs and one about deleting your account, and the model offered those as “the topics our help articles cover”.

You can tune a lot here: bigger chunks, more results, a better embedding model, keyword and vector search combined. Anthropic’s post on contextual retrieval is about the headphones problem exactly, chunks that lose their meaning once cut out of the article. My title prefix is a tiny version of what they do. But the shape stays the same: one search with the customer’s raw words, whether searching makes sense or not. A person would look at the results, notice the warranty isn’t there and search again. What if the model could do that?

Agentic RAG: let the model do the searching#

So let’s give the search to the model. Instead of searching first and pasting the results into the prompt, we tell the model there’s a search it can use. It decides whether to search, what for and how many times. That’s agentic RAG, and it’s what you do yourself with an unfamiliar error: google it, skim the results, change the query, open another tab.

How does a model use a search, though? It can’t run anything. We describe our tools in the request: a name, a description and a JSON Schema for the input, the same kind of schema the Browser AI article used for the triage answer. When the model wants a tool, it stops and replies with a request instead of an answer, a tool_use block that says “call search_help with { "query": "warranty" }”. Our code runs the search and sends the result back with the next request, and the model carries on. It never touches our server or our database. It can only ask, and our code decides what to do about it. This is called tool calling (OpenAI says function calling), and the last two sections build on it.

agent.js

import { search, readArticle } from "./help.js";
import { send } from "../send.js";

const tools = [
  {
    name: "search_help",
    description: "Search the Acme help center. Returns the three paragraphs that match the query best, with their article titles.",
    input_schema: { type: "object", properties: { query: { type: "string" } }, required: [ "query" ] }
  },
  {
    name: "read_article",
    description: "Return the full text of a help article by its exact title.",
    input_schema: { type: "object", properties: { title: { type: "string" } }, required: [ "title" ] }
  }
];

const run = {
  search_help: async ({ query }) => ( await search( query ) )
    .map( ( s ) => `<article title="${ s.title }">\n${ s.text }\n</article>` ).join( "\n\n" ),
  read_article: async ({ title }) => readArticle( title )
};

const system = `You answer questions from customers of Acme, an online store for home electronics.
Answer only from the help center, and search it as often as you need.
Name the article each part of your answer comes from.
If the help center doesn't answer the question, say so and suggest contacting support.`;

const messages = [{ role: "user", content: process.argv[ 2 ] }];

while ( true ) {
  const response = await send({ system, tools, messages });
  messages.push({ role: "assistant", content: response.content });

  if ( response.stop_reason !== "tool_use" ) {
    console.info( response.content.find( ( block ) => block.type === "text" )?.text );
    break;
  }

  const results = [];
  for ( const call of response.content.filter( ( block ) => block.type === "tool_use" ) ) {
    console.info( `> ${ call.name } ${ JSON.stringify( call.input ) }` );
    results.push({ type: "tool_result", tool_use_id: call.id, content: await run[ call.name ]( call.input ) });
  }
  messages.push({ role: "user", content: results });
}

search() is the one from the previous section, moved to help.js next to a readArticle() that glues an article’s paragraphs back together. send() is the fetch from ask(), except it passes the body through and returns the whole response, because now we need stop_reason and the tool_use blocks. The loop keeps going until the model answers without asking for a tool. Both sides of every round go into messages, so the model sees its earlier searches. That’s the stateless API from the context section again.

The headphones question that went wrong last time:

$ node agent.js "my headphones stopped working after two months"
> search_help {"query":"headphones stopped working warranty"}
> search_help {"query":"defective product repair replacement"}
> read_article {"title":"Warranty and repairs"}
> read_article {"title":"Return an item"}
Your headphones should still be under warranty, so you can file a claim.

**You're covered** (from *Warranty and repairs*)
Every product has a two-year warranty that starts on the delivery date. Two months is well inside that. [...]

**Why a regular return won't work** (from *Return an item*)
Most items can only be returned within 30 days of delivery, and two months is past that. [...]

The index and the search function are the same as before. The model added “warranty” to the query on its own, and then it opened both articles in full instead of trusting three paragraphs. The 30-day limit came back with the article, so this time the answer explains why a regular return won’t work. A second run took a slightly different path, three searches and one article, and ended with the same answer.

The speaker question got two searches in the first round, “return a product” and “refund to credit card”, and then both articles. The answer opens with “You can return the speaker, and if you paid by card the money goes back to that card.” And “hi” got no search at all, just a greeting.

All that searching takes time. Plain RAG answered in 3 to 4 seconds with one call. The agent needed three or four calls and 11 to 14 seconds, and since every call resends the whole conversation, it read six to nine times as many input tokens. “hi” was the exception, one call in under two seconds. And nothing in that loop stops a model that keeps searching. With a read-only help center that only costs money. We’ll come back to it in the harness section.

If plain RAG answers your users’ questions, keep it. I’d switch when the questions are vague or mix topics, or when the answer is spread across sources, say the docs, the ticket history and the changelog. Each source becomes one more tool, and the model picks. Anthropic’s tool use docs and OpenAI’s function calling guide show the full request and response format.

It can still only read, though. The answer told the customer to open Account > Orders and start the return. The model knows exactly how. Why not give it a start_return tool? Technically that’s one more entry in tools and one more function in run. But a search that goes wrong costs a few cents, and a return started for the wrong order is a real mess. A model that changes things is what people call an agent.

Agents: a while loop with tools#

Simon Willison spent years calling “agent” a hopelessly ambiguous word. In September 2025 he settled on a definition: “An LLM agent runs tools in a loop to achieve a goal.” By that definition we built one in the previous section already. It just couldn’t change anything. When people say “agent” or “agentic AI” today, they usually mean the same loop with tools that write files and run commands. Claude Code, Cursor and Copilot’s agent mode are this loop with a lot of engineering around it.

Let’s build a small one and give it a real job. Most blogs and shops turn a title into the URL part, the slug, so “From Prompts to Harnesses” becomes from-prompts-to-harnesses. Our project is just that function, slugify(), plus four tests that say what a good slug looks like. Two of them fail: extra spaces turn into extra dashes, and German letters like “ö” and “ß” disappear. The goal is to get all four green by fixing slugify(), the way you’d hand a bug to a colleague:

$ node --test
✔ lowercases and joins words with dashes
✔ drops punctuation
✖ collapses spaces
✖ transliterates German letters

The agent gets three tools:

coding-agent.js

import { readFile, writeFile } from "node:fs/promises";
import { execSync } from "node:child_process";
import { send } from "../send.js";

const tools = [
  {
    name: "read_file",
    description: "Read a file of the project.",
    input_schema: { type: "object", properties: { path: { type: "string" } }, required: [ "path" ] }
  },
  {
    name: "write_file",
    description: "Write a file of the project, replacing its content.",
    input_schema: {
      type: "object",
      properties: { path: { type: "string" }, content: { type: "string" } },
      required: [ "path", "content" ]
    }
  },
  {
    name: "run_command",
    description: "Run a shell command in the project directory and return its output.",
    input_schema: { type: "object", properties: { command: { type: "string" } }, required: [ "command" ] }
  }
];

const run = {
  read_file: ({ path }) => readFile( path, "utf8" ),
  write_file: async ({ path, content }) => {
    await writeFile( path, content );
    return `Wrote ${ path }`;
  },
  run_command: async ({ command }) => {
    try {
      return execSync( command, { encoding: "utf8", stdio: "pipe" } );
    } catch ( err ) {
      return err.stdout + err.stderr;
    }
  }
};

const system = "You are a coding agent. You work on a small Node.js project in the current directory. "
  + "You can read and write its files and run its tests with node --test.";

const messages = [{ role: "user", content: process.argv[ 2 ] }];

// the loop from agent.js, unchanged

Below that comment goes the while loop from the help center agent, character for character. Only the tools are new. I ran it from the project folder:

$ node ../coding-agent.js "The tests in slugify.test.js fail. Make them pass."
> run_command {"command":"ls -la && cat *.js package.json 2>/dev/null; node --test 2>&1 | tail -40"}
> write_file {"path":"slugify.js","content":"const GERMAN = { \"ä\": \"ae\", ..."}
> run_command {"command":"node --test 2>&1 | tail -9"}
All 4 tests in `slugify.test.js` now pass. I only changed `slugify.js`, not the tests.
[...]

The new slugify.js:

const GERMAN = { "ä": "ae", "ö": "oe", "ü": "ue", "ß": "ss" };

export function slugify( title ) {
  return title
    .toLowerCase()
    .replace( /[äöüß]/g, ch => GERMAN[ ch ] )
    .replace( /[^a-z0-9 ]/g, "" )
    .trim()
    .replace( / +/g, "-" );
}

That took three steps and about nine seconds: look around, write the fix, check it. The loop was the easy part, twenty lines that haven’t changed since the help center.

I wrote read_file for reading files, and the model never called it. Its first call used the shell to list the folder, print every file and run the tests, all in one command. In the second run it skipped write_file too and wrote the fix with a heredoc through run_command. With a shell in the list, the other two tools turned out to be optional.

And run_command passes whatever it gets to execSync. rm -rf ~ would run just as well, and so would a curl that posts your .env somewhere. write_file takes any path, ../../.ssh/config included. while ( true ) has no step limit, so a model that can’t fix a test can keep trying on your API bill. Tool output goes straight into the context too. This time the model piped the tests through tail -40 on its own. The full output for just two failing tests is 61 lines with stack traces. A real suite with dozens of failures prints thousands, and every round resends all of it.

Both runs changed only slugify.js, and both said so without being asked. Nothing in the loop checked that claim, though. The model could have changed the test to make it pass, and the loop would have printed the same success message. Solomon Hykes put it shorter: “An AI agent is an LLM wrecking its environment in a loop.” (Simon Willison quotes it in Designing agentic loops.)

Do you need an agent at all? Anthropic’s Building effective agents recommends the simplest thing that works, and sometimes that means no agent at all. For a lot of tasks a fixed sequence of calls in your own code does the job and is easier to test.

When you do need one, something around the loop has to say no. That’s the last concept.

Harness engineering: everything around the loop#

In February 2026 Mitchell Hashimoto, who created Terraform, described a habit: whenever an agent makes a mistake, take the time to change things so it never makes that mistake again. He wrote that he’d “grown to calling this ‘harness engineering’”. Six days later OpenAI used the same name for how one of its teams builds with Codex, and Birgitta Böckeler on Martin Fowler’s site boiled it down to Agent = Model + Harness. The harness is everything except the model: which tools exist, what they may touch, how many rounds the loop gets, what goes back into the context and what gets logged.

If you’ve written an Express app, you know the shape. A route handler doesn’t touch the database before auth and validation middleware have looked at the request, and the request gets logged on the way. A tool call is a request too, from a client you don’t fully trust. So it goes through middleware.

The code below is that middleware for the coding agent from the previous section. guard() sits between the model’s request and the real tool, and checks the call against a few rules first: only node --test may run, writes stay inside the project and test files are read-only. A call that breaks a rule never reaches the tool, and the model gets a refusal back instead. Calls that pass run as usual, with the output clipped to 2,000 characters, and every call goes into a log:

harness.js

import { appendFile } from "node:fs/promises";
import path from "node:path";

const ROOT = process.cwd();
const COMMANDS = [ "node --test" ];
const READ_ONLY = /\.test\.js$/;
const MAX_OUTPUT = 2000;
const LOG = new URL( "agent.log", import.meta.url );

function check( name, input ) {
  if ( input.path ) {
    const file = path.resolve( ROOT, input.path );
    if ( !file.startsWith( ROOT + path.sep ) ) {
      return `${ input.path } is outside the project`;
    }
    if ( name === "write_file" && READ_ONLY.test( file ) ) {
      return `${ input.path } is read-only, fix the code instead`;
    }
  }
  if ( name === "run_command" && !COMMANDS.includes( input.command ) ) {
    return `only these commands may run: ${ COMMANDS.join( ", " ) }`;
  }
  return null;
}

function clip( text ) {
  return text.length > MAX_OUTPUT
    ? `[${ text.length - MAX_OUTPUT } characters cut]\n${ text.slice( -MAX_OUTPUT ) }`
    : text;
}

export async function guard( name, input, tool ) {
  const refusal = check( name, input );
  const output = refusal ? `Refused: ${ refusal }` : clip( String( await tool( input ) ) );
  await appendFile( LOG, JSON.stringify({ time: new Date().toISOString(), name, input, output }) + "\n" );
  return output;
}

The agent changes in two places, a step limit and the guard around every tool call:

+import { guard } from "./harness.js";
 ...
-// the loop from agent.js, unchanged
+const MAX_STEPS = 10;
+let steps = 0;
+
 while ( true ) {
+  if ( ++steps > MAX_STEPS ) {
+    console.error( `Stopped after ${ MAX_STEPS } steps` );
+    break;
+  }
+
   const response = await send({ system, tools, messages });
 ...
-    results.push({ type: "tool_result", tool_use_id: call.id, content: await run[ call.name ]( call.input ) });
+    results.push({ type: "tool_result", tool_use_id: call.id, content: await guard( call.name, call.input, run[ call.name ] ) });

What does the guard make of the calls from the previous section, and of a few worse ones?

await guard( "run_command", { command: "ls -la && cat *.js package.json 2>/dev/null; node --test 2>&1 | tail -40" }, run.run_command );
// "Refused: only these commands may run: node --test"
await guard( "run_command", { command: "rm -rf ~" }, run.run_command );
// "Refused: only these commands may run: node --test"
await guard( "write_file", { path: "../../.ssh/config", content: "..." }, run.write_file );
// "Refused: ../../.ssh/config is outside the project"
await guard( "write_file", { path: "slugify.test.js", content: "..." }, run.write_file );
// "Refused: slugify.test.js is read-only, fix the code instead"
await guard( "run_command", { command: "node --test" }, run.run_command );
// "[211 characters cut]" followed by the last 2,000 characters of the test output

Every call also lands in agent.log with its input and what came back. Remember how the model said it only changed slugify.js and nothing checked? Now the test file can’t change, and the log shows what the model actually did, whatever it reports at the end.

A refusal goes back to the model as a tool result, like any other output. How does a model take a “no”? I ran the same task in Claude Code with the same rules written as permission settings:

{
  "permissions": {
    "allow": [ "Read", "Write", "Bash(node --test)" ],
    "deny": [ "Write(./*.test.js)", "Edit(./*.test.js)" ]
  }
}

In dontAsk mode Claude Code refuses anything that isn’t on the allow list. The model opened with the familiar ls -la and cat combo, this time with a cd to a wrong path in front, and it was refused. So it read the test file and slugify.js one by one and wrote practically the same fix as before. Then it stopped:

I fixed `slugify.js`, but I couldn't run the tests because shell access was denied. I checked each of the four test cases by hand and they should all pass now. Please run `node --test` to confirm.

node --test was allowed the whole time. The refusal said “Permission to use Bash has been denied”, and the model took that to mean all of Bash. That’s why my guard’s refusal names the commands that are allowed. Whatever the harness says goes into the context like everything else, so a vague refusal works like a vague prompt. A second run sent the same combo without the cd. That one got through, and the run finished normally. The deny rule held as well: when I asked for a new test, the write to slugify.test.js was refused.

Claude Code is a harness you can configure, and much of what it does has a counterpart in harness.js. Permission modes range from asking before every edit and command to approving on its own whatever looks safe. Hooks are your own scripts that run before or after a tool call, and they can block it. The instructions file and skills are context engineering living inside the harness. Böckeler calls them guides, because they steer the model before it acts. Tests and hooks are sensors, since they catch what went wrong afterwards.

That’s also where the project from the intro stands. Its rules for submitting code are written down in the instructions file. A rule in that file is a request, though. The model reads it and usually follows it. A hook that checks the submit and blocks it when a rule is broken is enforcement, and Hashimoto’s habit says where to start: every rule the model has broken once is a candidate. Writing those hooks is what I’m learning now.

The six side by side#

What did each step add, and where did it stop?

What it is Where it stopped
Prompt engineering The request written like a ticket for a contractor who has never met the team The reason for the change wasn’t in the code, and no wording could put it there
Context engineering Choosing what goes into the request next to your prompt, which was under 1% of it Picking by hand works for one issue, not for two thousand help articles
RAG Your code searches by meaning and pastes the top matches into the prompt One search with the customer’s own words. The warranty paragraph didn’t make the top three
Agentic RAG Search becomes a tool. The model decides whether to search, what for and how often 3 to 4 times slower, 6 to 9 times the input tokens, and it can only read
Agent The same loop with tools that write files and run commands, about twenty lines run_command runs anything, while ( true ) has no step limit, and nothing checks that the tests weren’t edited
Harness engineering Code around the loop: allowed commands and paths, a step limit, clipped output, a log A vague refusal works like a vague prompt. Claude Code’s Bash refusal made the first run skip node --test

None of the six needed anything exotic, just the plumbing from the intro. The hard part every time was deciding what the model gets to see and what it may do, and that is still our job.

If you try one thing after this, write the agent loop yourself. It’s a fetch and a while. Give it a shell in a throwaway folder, ask for something small, watch which tools it calls, then try to break it. That’s when the rest starts to make sense.