DEV Community

Cover image for Harness Engineering: Inner Loops in Practice
Darren "Dazbo" Lester for Google Developer Experts

Posted on Edited on

Harness Engineering: Inner Loops in Practice

Part 4 of the series "Beyond Vibe Coding: The Engineering Blueprint for Reliable AI Agents"

🗺️ The Series Roadmap: Beyond Vibe Coding

Agentic software development is drowning in fragmented buzzwords: Harness Engineering, Context Engineering, Loop Engineering, Spec-Driven Development, Inner Loops, and Outer Meta-Loops. Are they competing frameworks? Redundant prompt techniques? Or interlocking parts of a single machine?

This five-part series unifies these concepts into one cohesive architectural blueprint for building production software with AI without writing code manually:

  • Part 1: From Vibing Chaos to Reliable Agents: The What, Why, and How of Harness Engineering We diagnose the hangover of vibe coding, unpack the paradigm shift of shifting developer interventions left, establish our bedrock formula (Agent = Model + Harness), explore the motorsport analogy, and deconstruct the deterministic components that make up a production developer environment.
  • Part 2: Loop Engineering in the Harness: Autonomous, Self-Correcting Systems We fire up the dynamic runtime engine of the harness: deconstructing the core loop components, establishing hybrid evaluation rubrics (deterministic tests + LLM goal fidelity + tool trajectory verification), and applying the Ratchet Principle.
  • Part 3: Spec-Driven Development For-the-Win: Disposable Code, Living Blueprints, and Building Like a Boss We explore Spec-Driven Development (where code is disposable and specifications are the single source of truth), master Google Antigravity's unified harness and interactive slash commands (/grill-me, /plan, /goal, /boost, /learn), and combine formal specs on disk with autonomous tactical workflows in your session.
  • Part 4: Inner Loops in Practice: Fresh Contexts, Output Discipline, and Day-1 Loops (This Article) We go under the hood of an inner execution loop to see why looping actually runs faster and cheaper than single-pass vibing (fresh subagent contexts, LIVING_MEMORY.md, and strict output discipline), then wire day-one loops into any repository — ordered by setup effort — using Antigravity slash commands, loopy, and declarative Markdown with tiered rubrics.
  • Part 5: *Completing the AI Harness: Headless CI Loops, ADK Graphs, and Self-Improving Harnesses (Coming Soon)* We scale up to unattended headless execution (Antigravity CLI, Python SDK, Remote Agent) and custom Google ADK LoopAgent / ADK 2.0 Workflow graphs, close the outer meta-loop with self-improving harnesses (EXPERIENCE.md), and tie every concept together in a Monday-morning repo checklist.

Introduction: Turning Loop Theory Into Day-One Practice

Howdy friends, and welcome back to our Beyond Vibe Coding series!

In Part 1, we engineered the deterministic race car chassis around the model (Agent = Model + Harness). In Part 2, we fired up the powertrain — the autonomous execution loop backed by binary rubrics, tool trajectory checks, and the Ratchet Principle. And in Part 3, we decoupled what we are building from how we build it with Spec-Driven Development (SDD), making living Markdown specifications our permanent intellectual property and treating generated code as disposable.

After seeing our side-by-side Cosmic Conquest workbench in Part 2, two very practical questions always come up next:

  1. Why wasn't our Part 2 loop slower and more expensive than a single vibe prompt — and how do we stop multi-turn loops from going off the rails?
  2. How do we wire inner execution loops into any existing repository today without building a bespoke web workbench every time?

One of the greatest strengths of harness engineering is that loop engineering is an architectural pattern, not a rigid implementation. In this post, we'll look inside a single iteration of an inner execution loop (the tactical cycle that iterates to converge application code for your current task), and then walk through the interactive, day-one mechanisms you can drop into any repo in under ten minutes. (In Part 5, we'll step up to headless CI/CD pipelines, Google ADK graphs, and outer meta-loops that evolve the harness itself.)

Let's dive in.

Inside Every Iteration: Why Looping Beats Single-Pass Vibing

Before we look at the tooling options, let's solve a paradox that surprises many when they see my benchmark for the first time.

When people hear "multi-turn autonomous loop with a 14-point rubric", they naturally assume it must be slower and burn far more tokens than a single prompt. Yet in our Part 2 Cosmic Conquest head-to-head benchmark, the exact opposite happened: the harnessed loop ran 3–4x faster, consumed ~80% fewer total tokens (with ~15x fewer output tokens), cost ~85% less, and was the only track that produced a playable game!

How is an iterative loop faster and cheaper than single-pass vibing? Because of what happens inside each iteration. If you simply let an agent loop endlessly inside one sprawling chat thread, your token usage explodes, the model loses focus, and an unconstrained command can trash your workspace. Keeping an inner execution loop fast, cheap, and reliable comes down to four mechanics:

1. Sandboxed Execution (Blast Radius Control)

Generated code runs inside an isolated sandbox so a bad edit or test command cannot touch files outside your workspace, break local services, or push unapproved changes.

2. Fresh Contexts per Pass (Clean Subagents)

In a single-thread chat loop, every failed code draft, lint warning, and 200-line stack trace stays bolted onto the conversation history. Input tokens grow quadratically, and as failed attempts pile up, the model's attention degrades into familiar failure modes:

Fergus buried under single-thread chat bloat

  • Going in Circles: By Turn 4, the model retries a fix that failed on Turn 1 because the original error is buried under thousands of tokens of log noise.
  • Broken Edits & Syntax Regression: The model confuses old code drafts in the chat transcript with the actual files on disk.
  • Instruction Drift: Your standing rules, coding standards, and acceptance criteria get drowned out by pages of raw terminal output.

The fix is simple: give every iteration a clean slate. Delegate each loop pass to a fresh, short-lived subagent with a clean context window containing only three things:

Delegating each loop iteration to a clean-slate subagent

  • The Target Spec Slice: The specific requirement and acceptance criteria from SPEC.md or tasks/plan.md.
  • The Current Workspace Files on Disk: The actual source files right now, with zero stale drafts from earlier turns.
  • The Latest Failure Receipt: A compact summary of what broke on the previous pass.

The subagent makes its edit, runs the checks, records a short receipt, and exits. Its chat history is discarded immediately, leaving the parent orchestrator completely clean to check the result and decide whether to finish or spin up the next pass.

3. LIVING_MEMORY.md (Keep the Signal, Drop the Noise)

If each subagent starts with a clean slate, how does Turn 3 avoid repeating Turn 1's mistake? By reading a compact structured ledger on disk — LIVING_MEMORY.md — instead of 20,000 tokens of raw tracebacks.

Each failed turn appends roughly 200 tokens of distilled signal: what changed, what failed, the root cause, an explicit "Do NOT Repeat" guardrail, and the next hypothesis:

# Living Memory: Iteration Ledger

## Turn 1: UserSchema Migration (FAILED)

- **Changes Made:** `app/schemas/user.py` (lines 12–48) — replaced `class Config` with `model_config = ConfigDict(from_attributes=True)`.
- **Verifier Output:**
  - `uv run pytest tests/test_user.py`: 16 passed, 2 failed.
  - **Error:** `PydanticUserError: '@validator' is deprecated and no longer supports 'each_item=True' in v2 (app/schemas/user.py:34)`.
- **Root Cause:** Left legacy Pydantic v1 `@validator('roles', each_item=True)` decorator in place.
- **Do NOT Repeat:** Do not use `@validator` in Pydantic v2 models.

## Turn 2: UserSchema Migration (FAILED)

- **Changes Made:** `app/schemas/user.py` (lines 34–58) — migrated validators to `@field_validator('email', 'roles')`.
- **Verifier Output:**
  - `uv run pytest tests/test_user.py`: 17 passed, 1 failed (`tests/test_user.py::test_invalid_email_error_code`).
  - **Error:** `AssertionError: assert 'value_error' == 'invalid_email_format' (where 'value_error' = exc_info.value.errors()[0]['type'])`.
  - `uv run ruff check .`: 0 errors.
- **Rubric Delta:** 13 / 14 checks passed (Failed Check 1.2: custom validation errors must preserve API error code `invalid_email_format`).
- **Root Cause:** Raising plain `ValueError("Invalid email")` in Pydantic v2 sets error `type` to `'value_error'`, breaking the v1 API contract expected by `test_invalid_email_error_code`.
- **Next Hypothesis (Turn 3):** Raise `PydanticCustomError('invalid_email_format', 'Invalid email address')` from `pydantic_core` inside `validate_email`.
Enter fullscreen mode Exit fullscreen mode

When Turn 3 boots up, it reads twenty lines of crisp root-cause signal, fixes the exact bug, and moves on. Token usage stays flat across five or more iterations.

4. Strict Output Discipline (~15–20x Output Token Reduction)

Keeping input context slim is only half the story. Output tokens are the biggest driver of both how long a loop takes and how much it costs.

Strict Output Discipline: keeping code on disk and returning concise turn receipts

I learned this the hard way while tuning our Part 2 evaluation workbench. Without explicit formatting rules, the agent defaulted to pasting entire source files back into the chat on every single turn — burning ~16,000 output tokens on one run! Adding strict Output Discipline rules to the harness slashed output tokens by nearly 20x:

  • Keep Code in Files, Not in Chat: Write all source and test files directly to disk via workspace tools. Explicitly forbid dumping full source files into chat replies.
  • Cap Turn Summaries at 150–250 Words: Require every pass to reply with a brief summary covering what it tackled, the root cause of any failure, and which files and tests it updated.
  • Read & Fix Only What Failed: Because the code lives on disk, the next subagent never needs old chat transcripts to see what changed — it reads LIVING_MEMORY.md, inspects only the affected files, and fixes them.

Day-One Interactive Loop Mechanisms

With those iteration mechanics in place, let's look at the interactive ways to wire an inner execution loop into any new or existing repository today — ordered from lowest setup time and effort to highest, with zero custom Python plumbing required. Each mechanism works cleanly on its own, and because they operate at different layers, you can combine them whenever it helps.

Mechanism 1: Native Harness Slash Commands & Orchestrator Mode (0 mins — Built-in)

Best for: Immediate interactive high-velocity feature development, deep adversarial review, and parallel multi-file engineering inside Google Antigravity.

Conversational agents are conditioned to be polite: they finish one subtask, pause, and ask "Would you like me to continue with the next step?" As we introduced in Part 3, Antigravity's native slash commands remove that friction right out of the box while giving you distinct execution topologies on demand:

  • /goal (Hands-Off Autonomous Execution Loop): Prefixing a task — or a saved loop recipe — with /goal puts Antigravity into persistent loop mode, iterating across edits and test runs without stopping after every step to ask permission. It still respects your sandbox and approval boundaries: any unsandboxed command you haven't authorised pauses cleanly for your sign-off.
  • /boost (Going Deeper on One Hard Problem): Invoking /boost routes a tricky feature or bug through Antigravity's deep-reasoning pipeline — automatically exploring multiple perspectives, stress-testing edge cases, and running adversarial verification checks to defeat the Sycophantic Yes-Agent before returning.
  • /swarm (Going Wider Across Big Multi-File Work): Where /boost goes deeper on one hard problem, /swarm goes wider. It spins up a coordinator, parallel worker agents operating inside isolated Git worktrees (so they never step on each other's edits), and dedicated verifiers collaborating peer-to-peer via live @mention channels.
  • Orchestrator Mode (Model Routing Inside the Harness): Remember a fundamental harness principle: a model cannot swap itself out! Model routing lives in the harness. Toggling Antigravity's Orchestrator mode dynamically pairs frontier reasoning (Gemini 4 Carbon or Gemini 4 Neon) for planning and architecture review with fast, low-cost execution (Gemini 4 Hydrogen) for parallel slices inside a single workflow.
/boost implement the OAuth2 token refresh flow from specs/auth.md and verify it against RUBRIC.md
Enter fullscreen mode Exit fullscreen mode

Mechanism 2: Off-the-Shelf Skill Loops (loopy + LOOPS.md · 1–2 mins)

Best for: Standardising repeatable engineering and maintenance tasks, auditing loop safety before you run, pulling ready-made loops from a community catalogue, and building a shared LOOPS.md for your team.

What if you want specialised loops — cleaning up tech debt, speeding up a sluggish test suite, verifying a fresh git clone, or running a Devil's Advocate critique — without hand-crafting the loop rules yourself?

Install the open-source loopy skill directly into your harness:

npx skills add https://github.com/Forward-Future/loopy --skill loopy -g -y
Enter fullscreen mode Exit fullscreen mode

Once installed, loopy covers the full loop lifecycle:

  • Pull & Adapt from The Loop Library: Ask your agent: "Use loopy to find a loop for speeding up our pytest suite and adapt it to our repo." It fetches the nearest published pattern from The Loop Library and tailors the verification command to your pyproject.toml.
  • Craft a Custom Loop via Short Q&A: Tell your agent: "I want a loop that migrates our legacy endpoints to Pydantic v2. Use loopy to help me design it." loopy interviews you one question at a time — what "done" looks like, what files are in or out of scope, what test verifies each pass, and when to stop or escalate — and generates a ready-to-run loop recipe.
  • Run Loop Doctor Before You Launch: loopy includes a pre-flight Loop Doctor audit that reviews any loop definition for weak verification checks, missing stopping conditions, or overly broad permissions before you unleash it on your repository.
  • Run Debrief After a Run: Once a loop finishes, loopy's Debrief workflow inspects the completed evidence receipts to diagnose where turns were wasted — feeding directly into our Loop Bug vs Harness Bug diagnostics in Part 5.
  • Save Team Loops in LOOPS.md: Once a loop works cleanly, ask loopy to save it into a version-controlled LOOPS.md catalogue in your repo root:
# Project Loops (LOOPS.md)

## Endpoint Pydantic v2 Migration Loop

Migrates one legacy FastAPI route per pass to strict Pydantic v2 models until all routes are converted or progress stalls.

Prompt:
> Inspect `app/routers/` and select one unconverted endpoint. Replace raw dict payloads with strict Pydantic v2 `BaseModel` schemas. After each change, run `uv run pytest`, `uv run ruff check .`, and `uv run pyright`. Keep the change only if all checks pass; otherwise revert and record the blocker in `LIVING_MEMORY.md`. Stop when all routers use `BaseModel`, after 10 endpoints, or if 2 consecutive passes fail to convert a route. Ask before altering public URL paths.

## Test Suite Speedup Loop

Profiles and optimises the slowest pytest tests one at a time without reducing coverage.

Prompt:
> Run `uv run pytest --durations=5` and pick the slowest test not yet listed in `LIVING_MEMORY.md`. Refactor fixture scope or mock expensive I/O to reduce runtime. Keep the change only if `uv run pytest` passes with identical coverage and wall-clock time improves by at least 15%; otherwise revert and log the attempt. Stop when no test exceeds 200ms, after 5 passes, or after 2 consecutive stalls.
Enter fullscreen mode Exit fullscreen mode

Any engineer on your team can now trigger a saved loop simply by asking: "Loopy, run the Endpoint Pydantic v2 Migration Loop" — or even without the skill installed, "Run the Endpoint Pydantic v2 Migration Loop from LOOPS.md."

Mechanism 3: Pure Declarative Markdown & Tiered Verification (GEMINI.md, RUBRIC.md, LIVING_MEMORY.md · 5–10 mins)

Best for: Full tool-agnostic control in any AI coding tool (e.g. Google Antigravity, Claude Code, Cursor, GitHub Copilot) with custom standing loop protocols and tiered verification gates.

You don't need to install a single package to create an autonomous loop. Because modern coding agents natively read workspace context files and have access to sandboxed terminal tools, you can wire a complete Observe → Act → Verify → Record loop using pure Markdown.

You simply drop a standing Autonomous Loop Protocol into your project's root rule file — GEMINI.md or AGENTS.md. You can either include your binary pass/fail checks inline or, as a clean best practice for larger projects, keep them in a separate RUBRIC.md file so your main loop file stays lean.

Notice one subtle production detail in step 4 below: we run codespell, ruff, and pyright via uv run from the project environment rather than uvx ...@latest. Running against your locked local environment keeps the entire static gate 100% offline inside the sandbox without triggering surprise network lookups or breaking command approval prompts:

# Autonomous Execution Loop Protocol (in GEMINI.md / AGENTS.md)

Whenever asked to implement a feature or fix a bug from `specs/` or `tasks/plan.md`, you MUST execute in a strict self-correcting loop:

1. **Fresh Context per Iteration:** If you can spawn subagents, delegate each loop iteration to a new, short-lived subagent so every pass starts with a clean context window.
2. **Observe & Restate Goal:** Read the target task and restate the exact acceptance criteria at the start of the turn to prevent goal drift. Read `LIVING_MEMORY.md` (if present) to see what failed in prior attempts.
3. **Act (TDD First):** Write or update the failing unit test in `tests/` first, then implement the minimal modular code change.
4. **Verify (Offline Deterministic Gate + Binary Rubric):**
   - Run `uv run pytest`
   - Run `uv run codespell -s`, `uv run ruff check --fix .`, and `uv run pyright`
   - Score the output against every binary check in `RUBRIC.md` using an independent clean-slate Critic.
5. **Record & Iterate:**
   - If ANY test, static check, or rubric assertion fails, append the turn number, failed check IDs, root cause, "Do NOT Repeat" note, and next hypothesis to `LIVING_MEMORY.md`.
   - Do NOT ask the human for permission to fix test or lint failures — immediately spin up the next iteration and remediate.
6. **Output Discipline (No Inline Code Dumps):**
   - Write all source and test files directly to the workspace. Never dump full source files into chat replies.
   - Reply on every pass with a 150–250 word summary covering what was tackled, the root cause of any failure, and which files and tests were updated.
7. **Circuit Breakers (Stop / Escalate):**
   - **Clean Exit:** Stop and present a concise summary ONLY when `pytest`, `codespell`, `ruff`, `pyright`, and 100% of `RUBRIC.md` checks pass.
   - **Stall / Cap Escalation:** If the rubric score fails to improve for 3 consecutive attempts, or if you reach 5 iterations, HALT immediately and escalate to the human with your diagnostic log.
Enter fullscreen mode Exit fullscreen mode

Even in tools without subagent spawning, persisting each failed turn to LIVING_MEMORY.md lets you clear or /compact your chat thread mid-run without losing working memory.

Scaling Your Rubric Into a Tiered Verification Funnel:

In Part 2, we split validation into two halves: fast deterministic checks (pytest, ruff) followed by a clean-slate semantic Critic agent. In day-to-day production, waking a heavyweight Critic subagent on every minor check can still feel sluggish.

You can scale that exact RUBRIC.md pattern into a tiered verification funnel using my open-source tiered-rubric-loop skill:

  • Tier 1 — Mechanical Gate (Zero Token Cost): pytest, codespell, ruff, and pyright run offline in seconds. If anything fails here, the loop short-circuits immediately without spending a single model token on semantic review.
  • Tier 1.5 — Fast Calibrated Screening (Gemini Decisions API): Once Tier 1 passes, straightforward semantic assertions (e.g. "Does every new public function include a docstring?" or "Are all error messages actionable?") are screened in milliseconds by gemini-decision-1 — Google's calibrated Decisions API, which outputs a pass/fail probability with zero output tokens.
  • Tier 2 — Clean-Slate Critic Subagent (Exceptions & Critical Architecture Only): A full, independent Critic subagent wakes only for borderline grey-zone scores from Tier 1.5 or critical architectural invariants like security boundaries and concurrency. (We'll unpack the engineering and live benchmarks behind this funnel in an upcoming companion post, Using the Gemini Decisions API to Speed Up Our Evaluation Rubric.)

💡 Is a Single Rubric Pass Enough?
After Part 2, several readers rightly asked whether passing a rubric once is enough. It depends on what you are testing:

  • Deterministic code gates (pytest, ruff, pyright): One pass is definitive — code either passes the test suite or it doesn't.
  • Semantic LLM-as-a-Judge checks (RUBRIC.md): Never let the Builder mark its own homework (the Sycophantic Yes-Agent), and never use fuzzy 1-to-5 scores — force strict binary assertions graded by an independent, clean-slate Critic.
  • When the system you are building is itself an agent, prompt, or skill: One lucky pass tells you almost nothing because the system under test is non-deterministic. Require multi-trial consecutive passes (e.g. 3 out of 3 runs) before declaring victory.

Wrapping Up Part 4: Ready for Unattended Scale

With fresh subagent contexts, LIVING_MEMORY.md, strict output discipline, and these interactive loop mechanisms in place, you can wire reliable, self-correcting inner loops into any repository in ten minutes flat — without writing a single line of bespoke orchestration code.

But what happens when nobody is sitting at the IDE? How do you run that exact same workspace harness headlessly in CI/CD, enforce deterministic Python stop hooks with the Antigravity SDK, build custom multi-agent harnesses in Google ADK 2.0, and close the outer meta-loop so your harness upgrades itself across tasks?

👉 Continue to *Part 5: Completing the AI Harness: Headless CI Loops, ADK Graphs, and Self-Improving Harnesses (Coming Soon)*

Before You Go

  • Please share 📢 this with anyone that you think will be interested. It might help them, and it really helps me!
  • Please drop some reactions ❤️ 🦄 🔥 (you can pick more than one!) and bookmark 🔖 this post!
  • Please leave a comment 💬. Interaction is good!
  • Add a star ⭐ on my repos!
  • Follow 👉 me here on Dev.to, so you don’t miss my content.

References and Useful Links

Practical Inner Loop Tooling

Dazbo's Related Articles

Dazbo Links

Top comments (0)