# Self-Evolving Agent Harnesses Cut Variance by 59%—But Cost +17% More (N=3)

> 💡 **AI Labo Benchmark Series — Experiment `E50` (Observability-Driven Automatic Harness Evolution)**
>
> 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)**

Instead of hand-tuning AST rules and gotcha files forever, can an agent inspect its own execution trace after Ticket 1 and **automatically evolve** a better harness for Ticket 2?

We benchmarked Observability-Driven Automatic Harness Evolution (AHE, inspired by `arXiv:2604.25850`) against a fair static harness across sequential 2-ticket billing tasks on `models/gemini-4-carbon` (`thinkingLevel="MEDIUM"`, `N=3`). AHE evolved reliably (`3/3` zero-rollback) and crushed variance—yet uncovered an **"Evolution + Memory Thinking Tax"** and a subtle OpenAPI schema stripping bug.

---

## TL;DR — Key Empirical Findings

* **1. `100%` Safe Self-Evolution & `-58.8%` Cost Variance Reduction (`32/32` Parity):** Both `Baseline (Static Hand-Tuned Harness v0)` and `Candidate (AHE v1)` scored **`32.0 ± 0.0 / 32` (`100.0%`)** with `0` decoy reads. `Candidate`'s Meta-Evolver succeeded in `3/3` trials (`0` rollbacks, `0` false positives), promoting `7.0 ± 0.0` scoped AST guards, `4.0 ± 0.0` runtime probes, `compact_failures_only` (`-79.0%` verify log size: `837` ➔ `176` chars), and `4.67 ± 0.58` memory items—locking Task 2 to **`3.00 ± 0.00` calls** and cutting total cost SD by **`-58.8%`** (`` `$0.0417` `` ➔ `` `$0.0172` ``).
* **2. Why Break-Even `K*` Never Arrives (`+16.99%` Total Cost, `+$0.0010` Even on Task 2):** Although Task 2 prompt tokens fell **`-12.4%`** (`48,666.7` ➔ `42,623.7`), reading denser evolved rules made the model spend **`+10.1%` more thinking tokens** and **`+5.7%` more output tokens**. Because output/thoughts are billed at **`60x`** cached input (`` `$12.00/1M` `` vs. `` `$0.20/1M` ``), Task 2 alone rose from `` `$0.1935` `` to `` `$0.1945` `` (and `` `$0.0560` `` upfront Meta-Evolver cost yielded `` `$0.3399` `` vs. `` `$0.3976` `` total, **`+16.99%`**).
* **3. Silent OpenAPI Schema Stripping Bug Caught by Telemetry:** Declaring AST guard `params` as a bare `{"type": "OBJECT"}` without nested `properties` caused Gemini Function Calling to strip all child keys to `"params": {}` across `3/3` trials, silently turning `require_module_imports` into a no-op.

| Metric (`N=3` Trials, `Mean ± SD`) | Baseline: `Static Harness v0` | Candidate: `AHE v1` (Meta-Evolver) | Delta / Effect |
| :--- | :---: | :---: | :--- |
| **Hidden Grading Suite (`32` Cases)** | **`32.0 ± 0.0`** (`100.0%`) | **`32.0 ± 0.0`** (`100.0%`) | `100%` parity (`T1:14 + Core:10 + Inv:8`) |
| **Meta-Evolver Acceptance Rate** | — (`0` calls) | **`3 / 3` (`0` rollbacks, `0` FP)** | `7` AST guards + `4` probes + memory |
| **Task 2 Calls (`model_calls`)** | `3.67 ± 0.58` | **`3.00 ± 0.00`** | **SD=`0.00` deterministic convergence** |
| **Task 2 Verify Log Length** | `837` chars | **`176` chars** | **`-79.0%`** (`compact_failures_only`) |
| **Task 2 Prompt Tokens** | `48,666.7` | **`42,623.7`** | **`-12.4%`** |
| **Total Thinking Tokens (`thoughts`)** | **`12,547.3 ± 1,828.3`** | `15,850.0 ± 1,910.5` | `+26.32%` (Meta-Evolver + Memory Tax) |
| **Total Tokens (`total_tokens`)** | `104,609.0 ± 22,752.7` | **`101,867.7 ± 6,966.3`** | `-2.62%` (**SD `-69.4%`**) |
| **Elapsed Time (`elapsed_seconds`)** | **`289.46s ± 73.40s`** | `327.92s ± 27.95s` | `+13.28%` (SD `-61.9%`) |
| **Effective Cached Cost (90% OFF)** | **`` `$0.3399 ± $0.0417` ``** | `` `$0.3976 ± $0.0172` `` | **`+$0.0577` (`+16.99%`), SD `-58.8%`** |
| **List-Price Upper Bound (No Cache)** | **`` `$0.4078 ± $0.0604` ``** | `` `$0.4518 ± $0.0149` `` | `+10.79%`, SD `-75.3%` |
| **Output Cap Hits (`capped_termination`)** | `0 / 3` | `0 / 3` | Zero truncation |

---

## 1. Experiment Design & Architecture

```text
+-----------------------------------------------------------------------+
| Proxmox VM254 (0 NICs, gemini-4-carbon MEDIUM, temp=0.7, N=3 AB/BA)   |
| Task: 2 Sequential Billing Tickets (32 Tests: 14 T1 + 10 Core + 8 Inv)|
|                                                                       |
| Task 1 (upstream modules) --> Observability Signals (traces/failures) |
|   |-- Baseline (bypass) ----> Task 2 with Static Harness v0           |
|   |                           7.33 calls | $0.3399 eff. | 32/32 PASS  |
|   |-- Candidate (Meta-Evolver, $0.0560) --> Accept/Rollback Gate      |
|       --> Evolved Harness v1 (7 AST + 4 Probes + Filter + Memory)     |
|       --> Task 2 (locked 3.00 calls, 176c log)                        |
|           7.33 calls | $0.3976 eff. | SD -58.8% | 32/32 PASS          |
+-----------------------------------------------------------------------+
```

After Task 1, `Meta-Evolver` inspected execution traces and proposed updates to `HARNESS_CONFIG.json` and `HARNESS_MEMORY.md`. An `Accept/Rollback` gate immediately checked all proposed AST guards against Task 1's clean reference code—accepting only when false positives equaled zero.

---

## 2. Drop-In Implementation Recipe: Typed Schema + Evolution Gate

Always declare explicit child `properties` in tool schemas (preventing silent `"params": {}` stripping) and reject no-op guards before promoting evolved configs:

```python
EVOLVER_GUARD_SCHEMA = {
    "type": "OBJECT",
    "required": ["rule_id", "target_modules", "params"],
    "properties": {
        "rule_id": {"type": "STRING"},
        "target_modules": {"type": "ARRAY", "items": {"type": "STRING"}},
        "params": {
            "type": "OBJECT",
            "properties": {
                "forbidden_names": {"type": "ARRAY", "items": {"type": "STRING"}},
                "required_imports": {"type": "ARRAY", "items": {"type": "STRING"}},
            },
        },
    },
}


def accept_or_rollback_evolution(
    proposed_guards: list[dict],
    run_guard_fn,
    clean_reference_modules: dict[str, str],
) -> tuple[bool, str]:
    """Accepts evolved AST guards only if 0 false positives and non-empty params."""
    for guard in proposed_guards:
        if guard["rule_id"] == "require_module_imports" and not guard.get("params"):
            return False, f"REJECTED_EMPTY_PARAMS: {guard['rule_id']} stripped to no-op"
        for mod_name in guard.get("target_modules", []):
            hits = run_guard_fn(guard, mod_name, clean_reference_modules[mod_name])
            if hits:
                return False, f"ROLLBACK_FALSE_POSITIVE: {guard['rule_id']} flagged {mod_name}"
    return True, f"ACCEPTED_{len(proposed_guards)}_GUARDS"
```

* **Why this works:** Explicit OpenAPI `properties` preserve guard arguments end-to-end, while the clean-reference gate ensures self-evolved rules never break valid downstream work.

---

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

1. **Downstream Horizon & Ceiling Effect:** Both modes hit `32/32` because `REPO_ARCHITECTURE.md` was fairly linked in `AGENTS.md`. Over 5–10 noisy tickets or on lighter models where static specs fail, AHE's safety value grows—yet unless `HARNESS_MEMORY.md` is tightly capped to avoid the `+10.1%` thinking tax, cost amortization (`K*`) remains blocked by the `60:1` output-to-cached-input price ratio.
2. **Schema Stripping Scope:** Because bare `OBJECT` stripped `params` to `{}`, `require_module_imports` fired as a silent no-op while 4 fallback guards caught `6` Task-1 seed defects.
3. **When Baseline Is Enough:** On 1–2 well-specified tickets on frontier models, skip full Meta-Evolver loops and simply turn on `compact_failures_only` (`E16`) statically to get `-79%` log compression at zero evolution cost.

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

* **Experiment ID:** `E50` (`C046` / `arXiv:2604.25850` / Benchmark v2.1)
* **Run ID:** `e50-20261118-vm254-01` (`N=3` trials: `AB` ➔ `BA` ➔ `AB`, `temperature=0.7`)
* **Sandbox Environment:** Proxmox Isolated VM `VM254` (0 NICs, `PrivateNetwork=yes`, 3-UID isolation: `labexp50` / `labrunner50` / `labjudge50`)
* **Model & Thinking Level:** `models/gemini-4-carbon` (`thinkingLevel="MEDIUM"`)
* **Cost Accounting:** Google 90% implicit prefix-cache discount (`effective_cached_micro_usd`) as primary metric; list-price upper bound reported alongside.

</details>

---

**Discussion:** Have you ever caught your LLM's Function Calling API silently stripping nested `OBJECT` arguments to `{}` without throwing an error?

### 🔗 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 (`E49`):** [The +38% Compliance Audit Tax: Spec-Conflict Gates on Gemini 4 Carbon (N=3)](https://tappers.hashnode.dev/e49-carbon-spec-conflict-escalation)
* ➡️ **Next Post (`E51`):** [Zero Secret Exposure and -3% Cost: Capability Attenuation + Blind Proxy (N=3)](https://tappers.hashnode.dev/e51-capability-attenuated-security-harness)
* 🧠 **Related Episodic Memory (`E20`):** [Stop Your Coding Agent From Stepping on the Same Rake Twice: Cold-Start Exploration vs. a 5-Item MEMORY.md](https://tappers.hashnode.dev/e20-episodic-gotchas-memory)
