# Test Your Agent Harness: Self-Evals Cut Guardrail Build Cost by 36.5% (N=3)

> 💡 **AI Labo Benchmark Series — Experiment `E53` (Executable Harness Self-Testing & Evals)**
>
> Part of our controlled benchmark series testing AI coding agent harnesses inside network-isolated Proxmox VMs (`N=3` counterbalanced `AB`/`BA`/`AB` trials, `temperature=0.7`, 3-UID grading, 90% prefix-cache cost accounting).
> * 🚀 **[Master Benchmark Hub & All Pattern Rankings](https://tappers.hashnode.dev/ai-agent-harness-patterns-benchmark)**
> * 🛡️ **[Anti-Cheating Proxmox & systemd Sandbox Architecture](https://tappers.hashnode.dev/air-gapped-proxmox-systemd-agent-sandbox)**

Marmelab's 2026 field study found that `60%` of testable agent harnesses lack self-tests—leaving teams blind to false-positive guardrail blocks. Intuitively, adding a suite of self-evals to a harness-building step sounds like extra work.

We tested **Executable Harness Self-Testing** (`Stage 1` builds an AST guardrail + `Stage 2` implements a 4-module clinical trial pipeline under it) on `models/gemini-4-carbon` (`thinkingLevel="MEDIUM"`, `N=3`). Surprisingly, omitting self-evals triggered **Epistemic Starvation**: the untested agent hit `MAX_TOKENS` in `3/3` trials and double-saved its already-perfect code, costing **`+57.4%` more** in Stage 1.

---

## TL;DR — Key Empirical Findings

* **1. Untested Harnesses Suffer "Epistemic Starvation & Double-Save Tax":** Both `Baseline (Untested Fragile Scaffolding)` and `Candidate (Executable Self-Evals)` finished at **`32.0 ± 0.0 / 32` (`100.0%`)** (`12` calibration + `20` clinical app tests). Post-hoc replay showed `Baseline`'s very first `save_harness_guard` already passed `14/14`! Yet with `self_evals_run: 0`, the model doubted itself—hitting `MAX_TOKENS (24,576)` truncation on `s1_harness_t2` in **`3/3` trials** (vs. `1/3` in Candidate) and rewriting the entire `500`-line guard twice (`stage1_saves`: `2.00 ± 0.00` vs. `1.33 ± 0.58`).
* **2. `-36.48%` Stage 1 Cost & `-23.33%` Overall Effective Cost:** Deterministic `14/14` feedback gave `Candidate` an **Epistemic Stopping Proof**, cutting Stage 1 thoughts by **`-38.75%`**, Stage 1 output by **`-39.25%`**, Stage 1 cost from `` `$0.6152` `` to `` `$0.3908` `` (**`-36.48%`**), and total effective cached cost from `` `$0.8859 ± $0.0090` `` to `` `$0.6792 ± $0.0847` `` (**`-23.33%`**, cheaper in `3/3` trials).
* **3. Catching Naive Regex Hooks Before Stage 2 (`verify_e53_local.py`):** When simulating brittle substring hooks (e.g., `"SELECT" in src and 'f"' in src`, `"exec" in src`), `Baseline` accepted them on syntax alone, whereas `Candidate`'s paired True-Positive / False-Positive probes (`st_tp_r1..r6` + `st_fp_r1..r6`) rejected `100%` of false-positive traps before Stage 2 began.

| Metric (`N=3` Trials, `Mean ± SD`) | Baseline: `Untested Scaffolding` (`0` Evals) | Candidate: `Executable Self-Evals` (`14` Probes) | Delta / Effect |
| :--- | :---: | :---: | :--- |
| **Hidden Grading Suite (`32` Cases)** | **`32.0 ± 0.0`** (`100.0%`) | **`32.0 ± 0.0`** (`100.0%`) | `100%` parity (`12` heval + `20` app) |
| **Total LLM Calls (`s1 + s2`)** | `8.33 ± 0.58` (`[8–9]`) | **`6.67 ± 0.58` (`[6–7]`)** | **`-20.00%`** (`-1.67` calls) |
| **Stage 1 Saves (`stage1_saves`)** | `2.00 ± 0.00` (`3/3` double-save) | **`1.33 ± 0.58`** (`[1–2]`) | **`-33.34%`** (no blind rewrites) |
| **`MAX_TOKENS` Truncation (`t2`)** | `3 / 3` trials (`100%`) | **`1 / 3` trials (`33.3%`)** | **`-66.7 pt` drop in runaways** |
| **Stage 1 Thinking / Output** | `30,266.0` / `15,378.7` | **`18,537.0` / `9,343.0`** | **`-38.75%` / `-39.25%`** |
| **Total Tokens (`total_tokens`)** | `193,302.7 ± 11,536.4` | **`146,482.7 ± 26,923.3`** | **`-24.22%`** (`-46,820.0`) |
| **Stage 1 Effective Cost** | `` `$0.6152 ± $0.0274` `` | **`` `$0.3908 ± $0.1077` ``** | **`-36.48%`** (`` `-$0.2244` ``) |
| **Elapsed Time (`elapsed_seconds`)** | **`1,077.74s ± 268.23s`** | `1,233.82s ± 614.95s` | `+14.48%` (`2.61x` faster in T2 `BA`) |
| **Effective Cached Cost (90% OFF)** | `` `$0.8859 ± $0.0090` `` | **`` `$0.6792 ± $0.0847` ``** | **`-23.33%`** (`` `-$0.2067` ``, `3/3` wins) |
| **List-Price Upper Bound (No Cache)** | `` `$1.0031 ± $0.0299` `` | **`` `$0.7464 ± $0.1018` ``** | **`-25.59%`** (`` `-$0.2567` ``) |

---

## 1. Experiment Design & Architecture

```text
+-----------------------------------------------------------------------+
| Proxmox VM257 (0 NICs, gemini-4-carbon MEDIUM, temp=0.7, N=3 AB/BA)   |
| Task: Stage 1 AST Guardrail (R1..R6) -> Stage 2 Clinical App (32 Tests)|
|                                                                       |
| Baseline (Untested Scaffolding, self_evals_run = 0):                  |
|   save_harness_guard (syntax only) -> model doubts correctness        |
|   -> MAX_TOKENS (3/3) + blind full rewrite (3/3) -> $0.8859 eff.      |
|                                                                       |
| Candidate (Executable Harness Self-Evals, 14 disjoint TP+FP probes):  |
|   eval_and_save_harness_guard -> runs 6 TP + 6 FP + 2 Sensor probes   |
|   -> deterministic 14/14 PASS -> immediate submit -> $0.6792 eff.     |
+-----------------------------------------------------------------------+
```

Each forbidden rule (`R1`–`R6`) was paired with a realistic false-positive trap in the spec and self-evals—for example, forbidding SQL `f"SELECT ..."` while allowing constant `?` SQL alongside `ValueError(f"...")`, or forbidding `exec()` while allowing identifiers like `exec_escalation_id`.

---

## 2. Drop-In Implementation Recipe: Paired TP + FP Harness Self-Evals

Never ship a `PreToolUse` or AST hook without a paired True-Positive / False-Positive calibration suite that runs at save time:

```python
PAIRED_HARNESS_PROBES = [
    {
        "id": "st_tp_r2_sql_fstring",
        "expect_violation": True,
        "module": "query_cohort_filter.py",
        "code": 'def q(conn, s): return conn.execute(f"SELECT * FROM p WHERE s={s}")',
    },
    {
        "id": "st_fp_r2_const_sql_with_error_fstring",
        "expect_violation": False,
        "module": "query_cohort_filter.py",
        "code": (
            'SQL = "SELECT id FROM p WHERE site = ?"\n'
            'def q(conn, site):\n'
            '    if not site: raise ValueError(f"invalid site: {site}")\n'
            '    return conn.execute(SQL, (site,))'
        ),
    },
    {
        "id": "st_fp_r6_exec_identifier",
        "expect_violation": False,
        "module": "ae_sla_monitor.py",
        "code": 'def record(exec_escalation_id: str) -> str: return exec_escalation_id',
    },
]


def eval_and_save_harness_guard(check_fn, probes: list[dict] = PAIRED_HARNESS_PROBES) -> dict:
    """Provides deterministic stopping proof and blocks brittle regex false positives."""
    failures = []
    for p in probes:
        hits = check_fn(p["module"], p["code"])
        violated = bool(hits)
        if violated != p["expect_violation"]:
            failures.append({"probe": p["id"], "expected": p["expect_violation"], "got": hits})
    return {
        "self_evals_passed": len(failures) == 0,
        "passed": len(probes) - len(failures),
        "total": len(probes),
        "failures": failures,
    }
```

* **Why this works:** Paired TP/FP probes eliminate false-positive workflow deadlocks while giving coding models the concrete pass signal they need to stop overthinking and avoid redundant full-file rewrites.

---

## 3. Threats to Validity & When NOT to Use This

1. **Detailed `HARNESS_SPEC.md` Ceiling Effect:** Because both modes received clear `ast`-parsing instructions in `HARNESS_SPEC.md`, `Baseline` did not commit Stage-2 FP blocks on `gemini-4-carbon (MEDIUM)`. On weaker models or underspecified prompts, brittle string-matching hooks fail Stage 2 as well.
2. **Sample Size (`N=3`) & `MAX_TOKENS` Variance:** While Candidate won on cost in all `3/3` trials (`T1 -16.3%`, `T2 -34.1%`, `T3 -19.6%`) and avoided `t4` double-saves `3/3` times, `s1_harness_t2` hit `MAX_TOKENS (24,576)` once in Candidate (`1/3`) due to natural thinking-token stochasticity, and T1/T3 elapsed times reflected upstream API SSE wait jitter.
3. **Scope of Rules:** These `14` self-evals covered single-file Python AST rules (`R1`–`R6`); multi-file type checking or dynamic taint hooks require fixture-level integration evals.

<details>
<summary>📋 Experiment Metadata & Reproducibility</summary>

* **Experiment ID:** `E53` (`C049` / Marmelab *State of AI Harness Engineering 2026* / Benchmark v2.1)
* **Run ID:** `e53-20261119-vm257-01` (`N=3` trials: `AB` ➔ `BA` ➔ `AB`, `temperature=0.7`)
* **Sandbox Environment:** Proxmox Isolated VM `VM257` (0 NICs, `PrivateNetwork=yes`, 3-UID isolation: `labexp53` / `labrunner53` / `labjudge53`)
* **Model & Thinking Level:** `models/gemini-4-carbon` (`thinkingLevel="MEDIUM"`, `max_output_tokens=24576`)
* **Cost Accounting:** Google 90% implicit prefix-cache discount (`effective_cached_micro_usd`) as primary metric; list-price upper bound reported alongside.

</details>

---

**Discussion:** Do you unit-test your `PreToolUse` hooks and custom linters with explicit false-positive edge cases—or only verify that they catch violations?

### 🔗 Continue Reading the Series
* 🚀 **Master Benchmark Hub:** [AI Agent Harness Patterns Benchmark](https://tappers.hashnode.dev/ai-agent-harness-patterns-benchmark)
* 🛡️ **Methodology & Sandbox Architecture:** [How to Benchmark AI Agents Without Eval Cheating or API Key Leaks: Designing a Proxmox & systemd Sandbox](https://tappers.hashnode.dev/air-gapped-proxmox-systemd-agent-sandbox)
* ⬅️ **Previous Post (`E52`):** [Cutting Multi-Agent Costs by 54.6%: Adaptive Routing + Filesystem Bypass (N=3)](https://tappers.hashnode.dev/e52-complexity-adaptive-orchestrator-filesystem)
* ➡️ **Next Post (`E54`):** [Runtime Code Contracts Cut Agent Thinking by 14.4% at 32/32 Parity (N=3)](https://tappers.hashnode.dev/e54-design-by-contract-runtime)
* 🛡️ **Related AST Hooks (`E11`):** [Why Long System Prompts Can't Enforce Code Architecture: Prompt Rules vs. Deterministic Pre-Commit AST Hooks](https://tappers.hashnode.dev/e11-architecture-guardrail-hooks)
* 🧭 **Related Guides & Sensors (`E39`):** [Thoughtworks' Guides-and-Sensors Pattern in Action: Bare Errors vs. Feedforward Guides + Remediation Sensors (-95.1% Tokens)](https://tappers.hashnode.dev/e39-guides-and-sensors-remediation)
