FMTechnical notes
Portfolio
Back to the blog

AI & Agents · Advanced · Agentic

Practical Guide to Agentic Harnesses: Orchestrating Subagents with TDD Without Burning Context

If your main agent read forty files to change a twenty-line function, you already lost. Context isn't free: every token spent re-reading what you already mapped is a token not spent on the actual problem.

After reading this
  • Understand why a fat agent burns context and tokens
  • Design subagents with disjoint edit surfaces
  • Apply TDD as a trust contract in orchestration
01 / 07

The problem: burned context

The failure mode is always the same: the main agent reads the codebase, then reads more code to answer each sub-question, and halfway through the feature it has three files open and is arguing with itself about a detail in a file it will never touch. The ~150k token window fills with context it already held and discarded.

Once the agent shifts from solving the problem to coordinating its own diff, the focus is broken. It's not a model problem, it's a topology problem: a single context doesn't scale to be explorer, writer, and verifier at once.

02 / 07

Solution: thin orchestrator + bounded subagents

The orchestrator delegates well-defined work units. Each subagent has a role (explore, work, verify) and disjoint edit surfaces. This way, the main context stays focused.

Here's a real example of how to derive allowed edit surfaces based on task type:

ts
// Real types for edit surfaces and tasks
type EditSurface = string[]; // Repo-relative globs
type Handoff = { files: string[]; notes: string };

interface Task {
  id: string;
  feature: string;
  type: "implementation" | "refactor" | "fix";
}

// Real function to derive allowed surfaces
function deriveEditSurface(task: Task): EditSurface {
  switch (task.type) {
    case "implementation":
      return [`src/features/${task.feature}/**/*`];
    case "refactor":
      return [`src/features/${task.feature}/**/*`, "src/shared/**/*"];
    case "fix":
      return [`src/**/*`]; // Wider surface for urgent fixes
    default:
      return [];
  }
}

// Verification that a path is within a surface
function assertWithinSurface(path: string, surface: EditSurface) {
  const normalizedPath = path.replace(/\\/g, "/");
  const allowed = surface.some((pattern) => {
    const normalizedPattern = pattern.replace(/\\/g, "/");
    // Simplification: in production use micromatch or similar
    return normalizedPath.includes(
      normalizedPattern.replace("/**/*", "")
    );
  });
  if (!allowed) throw new Error(`Access denied: ${path} outside surface`);
}
03 / 07

TDD as a trust contract

Before writing code, the subagent writes a failing test (RED). Then implements the minimal code to pass it (GREEN). Finally, it verifies nothing existing was broken (PRESERVE). This cycle is the contract the parent can audit.

Here's a real example using Vitest to test the blog's getRecommendations function:

ts
import { describe, it, expect } from "vitest";
import { getRecommendations } from "../src/blog-data/blog-registry";

describe("getRecommendations", () => {
  it("should return N recommended posts different from current", () => {
    // Arrange
    const currentSlug = "clean-architecture-react-19";
    const amount = 3;
    
    // Act
    const recommendations = getRecommendations(currentSlug, amount);
    
    // Assert
    expect(recommendations).toHaveLength(amount);
    expect(recommendations.every(post => post.slug !== currentSlug)).toBe(true);
    expect(new Set(recommendations.map(p => p.slug)).size).toBe(amount);
  });
});
04 / 07

Allowed edit surfaces

The orchestrator derives and explicitly passes the paths a subagent can edit. If a worker tries to touch a file outside its surface, the system rejects it. This prevents accidental overwrites.

Here's a complete example of an orchestrator with real edit surfaces:

ts
// Real orchestrator with edit surfaces
export async function orchestrateTask(task: Task): Promise<void> {
  const surfaces = deriveEditSurface(task);
  console.log(`Allowed surfaces for task ${task.id}:`, surfaces);
  
  // Parent never re-reads full files (context preservation rule)
  const handoff = await workerAgent(task, surfaces);
  console.log("Handoff received:", handoff);
  
  const verified = await verifyAgent(task, handoff);
  if (!verified) throw new Error("Verification failed");
  
  console.log("Task completed successfully");
}

// Worker agent simulation
async function workerAgent(task: Task, surfaces: EditSurface): Promise<Handoff> {
  // In a real implementation, this worker would have its own context
  // and make changes within the allowed surfaces
  
  // Example: add a new file
  const newFilePath = `src/features/${task.feature}/new-component.tsx`;
  assertWithinSurface(newFilePath, surfaces);
  
  return {
    files: [newFilePath],
    notes: `Initial component for ${task.feature} created`
  };
}
05 / 07

Context preservation

The parent never re-reads full files. Workers return short handoffs (path:line). The ~150k token backstop acts as an auto-pause: when it fills, the next bounded unit is delegated. The parent stays a coordinator, not an executor.

This rule can be explicitly coded in the orchestrator:

ts
// Context preservation rule: parent never re-reads full files
// This line in the orchestrator ensures mapped files are never read again
// const fileContents = await readFile(handoff.files[0]); // ❌ Forbidden
console.log("Handoff received:", handoff); // ✅ Metadata only
06 / 07

Honest testability

Not everything is tested with RED-GREEN. Visual changes (DOM, GSAP, CSS) require build + no-regression. Recognizing when TDD doesn't apply is as important as knowing when it does.

In this repository, visual changes are verified with:

  • `npm run build` to ensure there are no compilation errors
  • Manual verification in staging for critical components
  • Visual regression tests for key UI elements
07 / 07

Tradeoffs and coordination cost

Delegation has a cost: latency, synchronization, and extra verification. But the benefit is preserving the parent's focus. Delegate when real work justifies complexity, not size alone.

If the unit is ~100 lines, writing it costs less than spawning a worker that spends two minutes reading first - delegate for a named reason or stay inline.

Component tree● interactive

Layout-level composition. Owns the document structure and orchestrates which features render.

Practice

Design your own harness

Pick a feature (e.g. shopping cart) and define: 1) allowed edit surfaces, 2) a RED test that fails before implementing, 3) the high-risk item that can't be tested automatically.

Show a hint

Look at existing code. Which parts would change? What side effect could break?