# Zero-Cost Brownfield Agent Guards: Full-Dir Locks, AST Hooks & Early Stop (8 Benchmarks)

> 💡 **AI Labo Benchmark Cluster Synthesis — Experiments `E68, E85, E86, E89, E91, E92, E93, E94` (Brownfield Guardrails)**
>
> Synthesizing 8 controlled A/B experiments (`N=3` counterbalanced `AB/BA` trials per study, `temperature=0.7`, 3-UID isolation, `gemini-3.8-flash LOW`) executed inside zero-NIC Debian Proxmox sandboxes with 90% implicit prefix-cache cost accounting.
> * 🚀 **[Master Benchmark Hub & Pattern Index](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)**

When coding agents work inside brownfield repositories, most teams try to make them safer by adding **more LLM calls**—extra reflection turns, supervisor reviews, or prompt warnings telling the model not to weaken existing tests. Those LLM-based checks add latency, inflate effective API bills, and still fail deterministically when an agent touches `conftest.py`, leaves workspace residue, or keeps refactoring after tests already pass.

Across **8 Proxmox benchmarks (`E68`, `E85`, `E86`, `E89`, `E91`, `E92`, `E93`, `E94`)**, we replaced LLM nagging with **deterministic, 0-LLM-token boundary contracts, cryptographic full-directory locks, AST assertion guards, clean-room graders, and early-stop gates**. Rather than costing extra money, these deterministic guardrails routinely **cut effective cached costs by `-8.2%` to `-27.3%`** while blocking `100%` of runner bypasses and eval exploits.

---

## TL;DR — Key Empirical Findings Across 8 Benchmarks

* **1. Early-Stop + Task-Scoped Boundaries Cut Real Spend by Up to `-27.3%` (`E68`, `E89`, `E91`):** Stopping redundant post-green turns with a Same-Patch / 0-Token Static Audit Early-Stop Gate (`E89`) eliminated `3.0 -> 0.0` post-test calls, reduced total calls (`8 -> 5`, `-37.5%`), cut tokens `-43.7%`, and lowered effective cached cost **`-27.3%` (`$0.0224` ➔ `$0.0163`)**. Scoping files (`Editable/Inspect/Required/Protected` in `E68`) and guides (`E91`) cut effective cost `-8.7%` and `-8.2%` with `0` scope violations.
* **2. File-Path SHA-256 Locks Are Not Enough—Lock the Whole Runner & Inspect ASTs (`E85`, `E92`, `E93`, `E94`):** Locking only pinned test paths left `conftest.py` and `pytest.ini` exposed; switching to a Full-Directory & Config Lock (`E92`) blocked `100%` of runner bypasses while cutting cost `-13.9%`. An AST Assertion Lock (`E93`) killed `8/8` mutants without blocking legitimate new brownfield tests (`+$0.0008` / `+1.2%`), Clean-Room Patch Grading (`E85`) blocked `6/6` (`100%` vs. `0%`) residue cheats (`sitecustomize.py`, `decimal.py` shadow, `.pyc`, symlinks) in `0.66ms`, and Diff-Triggered Shallow-Copy Mutation Probes (`E94`) caught `100%` of reference leaks at `0.0ms` clean overhead (`-8.6%` cost).
* **3. Fix Reservation Budget Accounting Before Agents Halt Mid-Edit (`E86`):** Charging an agent's budget cap using `maxOutputTokens` reservations halted `3/3` baseline runs prematurely on Turn 4 at just `1.46%` real token usage (`26.00/32`, `81.25%`); billing by actual usage restored **`32.00/32` (`100%`, `+18.75pt`)**.

| Exp | Harness Contrast (Mode A vs. Mode B, `N=3`) | Hidden Suite | Deterministic Defense Impact | Effective Cached Cost (A ➔ B) |
| :--- | :--- | :---: | :--- | :---: |
| **`E68`** | Open Scope vs. Boundary Contracts (`VM273`) | `32/32` vs. `32/32` | `0` boundary violations, elapsed `-26.9%` | `` `$0.0416` `` ➔ **`` `$0.0380` `` (`-8.7%`)** |
| **`E85`** | In-Place UID vs. Clean-Room Patch Grader (`VM290`) | `32.0` vs. `31.7/32` | Blocked `6/6` (`100%` vs `0%`) residue cheats in `0.66ms` | `` `$0.0204` `` vs. `` `$0.0206` `` (`+1.1%`) |
| **`E86`** | `maxOutputTokens` Reserve vs. Actual Usage (`VM291`) | `26.00` ➔ **`32.00/32`** | Fixed `3/3` Turn-4 premature halts (`+18.75pt`) | `` `$0.0113` `` ➔ `` `$0.0190` `` (full 7 turns) |
| **`E89`** | Unbounded Post-Green vs. Early-Stop Gate (`VM294`) | `32/32` vs. `32/32` | Calls `8 -> 5` (`-37.5%`), tokens `-43.7%`, time `-33.3%` | `` `$0.0224` `` ➔ **`` `$0.0163` `` (`-27.3%`)** |
| **`E91`** | Monolithic vs. Task-Scoped Guides (`VM296`) | `28/28` vs. `28/28` | Input tokens `-31.1%`, elapsed `-25.9%` | `` `$0.0286` `` ➔ **`` `$0.0263` `` (`-8.2%`)** |
| **`E92`** | Pinned-Path Lock vs. Full-Dir & Config Lock (`VM297`) | `28/28` vs. `28/28` | `100%` `conftest`/`pytest.ini` bypass block, `0` FP | `` `$0.0676` `` ➔ **`` `$0.0582` `` (`-13.9%`)** |
| **`E93`** | Prompt Rules vs. Hook AST Assertion Lock (`VM298`) | `28/28` (`8/8` mut.) | `0` false blocks on new brownfield `test_*` files | `` `$0.0611` `` ➔ `` `$0.0619` `` (`+1.2%`) |
| **`E94`** | Static Diff vs. Shallow-Copy Probe (`VM299`) | `28/28` vs. `28/28` | `100%` shallow-leak catch, `0.0ms` when clean | `` `$0.0250` `` ➔ **`` `$0.0229` `` (`-8.6%`)** |

---

## 1. Defense-in-Depth Architecture for Brownfield Coding Loops

```text
+-------------------------------------------------------------------------+
| Zero-Token Brownfield Defense Pipeline (E68, E85, E86, E89, E91-E94)    |
|                                                                         |
|  1. Pre-Turn Scope & Actual Budget Gate (E68 + E86 + E91)               |
|     - Inject Task-Scoped Guides + Editable/Protected paths only         |
|     - Bill budget on actual usage (never maxOutputTokens reservation)   |
|  2. Pre-Commit Test & Runner Integrity Hooks (E92 + E93 + E94)          |
|     - Full-dir SHA-256 lock on tests/**, conftest.py, pytest.ini        |
|     - AST parity check: existing assert nodes untouched; new tests OK   |
|     - Diff-triggered shallow-copy mutation probe when copying dicts/obj |
|  3. Early-Stop Gate & Clean-Room Grader (E85 + E89)                     |
|     - On green + zero AST violations + repeated diff SHA -> STOP (E89)  |
|     - Evaluate via clean-room git patch apply (drops residue cheats)    |
+-------------------------------------------------------------------------+
```

Notice the unifying principle: **every defense executes locally in `<2ms` of Python CPU time** rather than spending LLM reasoning tokens.
* In **`E92`** (suggested by reader Remy Calder) and **`E93`** (suggested by reader Anas Alkhatib), cryptographic hashing of individual test files missed subtle exploits like adding a plugin hook inside `conftest.py` or deleting `assert` nodes inside an unlocked helper test. Full-directory hashing plus AST assertion fingerprinting closed both holes without blocking agents from writing net-new regression tests.
* In **`E85`**, even strict Linux UID separation allowed workspace-level Python import shadowing (`sitecustomize.py`, `decimal.py`) and poisoned `__pycache__` `.pyc` artifacts to compromise in-place grading. Extracting only an allowlisted `diff` onto a pristine clean-room checkout eliminated `6/6` attacks.
* Similarly, scoping feedforward guides (**`E91`**, `@fgrandon`) and halting immediately after the first clean green build (**`E89`**) pairs naturally with our negative scope boundary rules in [`E57`](https://tappers.hashnode.dev/e57-negative-scope-guardrails) and SHA-256 locking in [`E38`](https://tappers.hashnode.dev/e38-cryptographic-test-tampering-lock).

---

## 2. Drop-In Implementation Recipe: 0-Token Brownfield Guard Hook (`E89` + `E92` + `E93`)

Drop this dependency-free guard into your tool executor (`write_file` / `edit_file` / `run_tests` wrapper) to lock runner configs (`E92`), permit new brownfield unit tests while freezing existing assertions via AST (`E93`), and signal an immediate clean stop once tests pass without diff churn (`E89`).

```python
import ast
import hashlib
from pathlib import Path


def snapshot_locked_configs(repo_root: Path, locked_globs: tuple[str, ...]) -> dict[str, str]:
    """Capture SHA-256 over test configs/hooks (conftest.py, pytest.ini) [E92]."""
    hashes: dict[str, str] = {}
    for pattern in locked_globs:
        for path in sorted(repo_root.glob(pattern)):
            if path.is_file():
                hashes[str(path.relative_to(repo_root))] = hashlib.sha256(path.read_bytes()).hexdigest()
    return hashes


def assert_signatures_by_func(source: str) -> dict[str, list[str]]:
    """Extract normalized AST assert statements per top-level/class test function [E93]."""
    tree = ast.parse(source)
    sigs: dict[str, list[str]] = {}
    for node in ast.walk(tree):
        if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) and node.name.startswith("test_"):
            asserts = [ast.dump(n, include_attributes=False) for n in ast.walk(node) if isinstance(n, ast.Assert)]
            sigs[node.name] = asserts
    return sigs


def validate_brownfield_guard(
    repo_root: Path,
    baseline_configs: dict[str, str],
    baseline_test_asts: dict[str, dict[str, list[str]]],
    current_diff_bytes: bytes,
    previous_green_diff_hash: str | None,
) -> tuple[bool, str, bool]:
    """Return (ok, message, should_early_stop) with zero LLM tokens [E89/E92/E93]."""
    for rel, expected_sha in baseline_configs.items():
        p = repo_root / rel
        if not p.exists() or hashlib.sha256(p.read_bytes()).hexdigest() != expected_sha:
            return False, f"BLOCKED [E92]: protected runner config '{rel}' was modified.", False

    for rel, old_sigs in baseline_test_asts.items():
        new_sigs = assert_signatures_by_func((repo_root / rel).read_text(encoding="utf-8"))
        for fn_name, old_asserts in old_sigs.items():
            if new_sigs.get(fn_name) != old_asserts:
                return False, f"BLOCKED [E93]: existing test '{rel}::{fn_name}' weakened.", False

    diff_hash = hashlib.sha256(current_diff_bytes).hexdigest()
    should_stop = previous_green_diff_hash == diff_hash  # Same-patch early-stop gate [E89]
    return True, "OK: guardrails clean" + (" (early-stop green parity)" if should_stop else ""), should_stop
```

**Why this stops reward hacking without breaking brownfield workflows:**
* **New tests remain unblocked (`E93`):** Because `validate_brownfield_guard` checks `fn_name` keys present in `baseline_test_asts`, an agent can freely append new `test_regression_*` functions while being physically prevented from altering any pre-existing `assert`.
* **Runner hijacks caught (`E92`):** Any sneaky edits to `conftest.py` fixtures or `pytest.ini` markers trigger an instant deterministic block before test execution.
* **Post-green thrashing eliminated (`E89`):** Hashing the clean `git diff` catches no-op "verification reassurance" turns and closes the loop `3` turns earlier.

---

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

1. **Legitimate Test Refactoring Tasks:** The AST Assertion Lock (`E93`) assumes pre-existing test expectations represent ground-truth invariants. If your ticket explicitly asks the agent to migrate a deprecated API whose old `assert` values *must* change, temporarily move those specific files from `baseline_test_asts` into an explicit migration allowlist (`E68`).
2. **Dynamic Non-`assert` Test Helpers:** Python AST inspection of `ast.Assert` works cleanly for `pytest`-style assertions; `unittest.TestCase` codebases using `self.assertEqual(...)` require extending the AST filter to `ast.Call` nodes matching `assert*`, and non-Python repos need tree-sitter equivalents.
3. **Cache & Memory Trade-Offs:** Even bulletproof static guards will stall if `MEMORY.md` feeds contradicting legacy rules or stripped code skeletons mislead the implementer—explore how to prevent memory decay next in **[Cluster 3: Freshness Gates, Skeletons & Evolution](https://tappers.hashnode.dev/e65-e88-freshness-gated-memory-evolution-cluster)** and verify cache safety in **[Cluster 1: Prefix-Cache Economics](https://tappers.hashnode.dev/e62-e95-prefix-cache-economics-cluster)**.

<details>
<summary>📋 Experiment Metadata & Reproducibility (E68, E85, E86, E89, E91, E92, E93, E94)</summary>

* **Experiment Cluster:** `E68` (`VM273`), `E85` (`VM290`), `E86` (`VM291`), `E89` (`VM294`), `E91` (`VM296`), `E92` (`VM297`), `E93` (`VM298`), `E94` (`VM299`)
* **Protocol:** Benchmark v2.1 (`N=3` counterbalanced `AB/BA` trials per study, `temperature=0.7`)
* **Sandbox:** Zero-NIC Debian Proxmox VMs (`PrivateNetwork=yes`, 3-UID isolation + Clean-Room patch extraction in `E85`)
* **Model & Pricing:** `gemini-3.8-flash` (`thinkingLevel="LOW"`, `max_output_tokens=32768`), reporting 90% prefix-cached effective spend (`effective_cached_usd`).
* **Community Attribution:** `E91` (`@fgrandon`), `E92` (Remy Calder), `E93` (Anas Alkhatib), and `E94` (Nexus Verify) were directly refined from reader feedback.

</details>

---

**Discussion:** Which subtle test-bypass or scope-creep failure have you seen coding agents commit in brownfield repos (`conftest.py` overrides, `pytest.ini` skips, `.pyc` residue, or endless post-green refactors)?

<!-- PUBLIC_DATASET_LINKS_START -->
### 📦 Raw Benchmark Telemetry & Interactive Trial Explorer

* 🔍 **[Interactive Trial Explorer (CLUSTER2)](https://tappers-labo.github.io/ai-labo-benchmark-data/#cluster=CLUSTER2)** — Filter all 104 benchmarks and inspect per-trial `effective_cached_usd`, token breakdowns, and hidden-test outcomes.
* 💾 **[Sanitized Open Dataset Repo](https://github.com/tappers-labo/ai-labo-benchmark-data)** — Download `experiments_master.csv/.jsonl`, Block 5 Bill of Design, plus sanitized `usage.json`, `independent-tests.json`, and `actions.json` traces.
* 🎥 **[YouTube Channel (Tappers AI Labo)](https://www.youtube.com/@tappers-labo-en)** — Plain-English Lv.1 video walkthroughs of our isolated AI benchmark lab & key findings.
<!-- PUBLIC_DATASET_LINKS_END -->

### 🔗 Continue Reading the Series
* 🚀 **Master Benchmark Hub:** [AI Agent Harness Patterns Benchmark](https://tappers.hashnode.dev/ai-agent-harness-patterns-benchmark)
* ⚡ **Cluster 1 (`E62`–`E95`):** [The 90% Prefix-Cache Trap: Why Context Pruning Often Raises Agent Costs](https://tappers.hashnode.dev/e62-e95-prefix-cache-economics-cluster)
* 🧠 **Cluster 3 (`E65`–`E88`):** [When Agent MEMORY.md Goes Stale: Freshness Gates, Skeletons & Evolution](https://tappers.hashnode.dev/e65-e88-freshness-gated-memory-evolution-cluster)
* 🔗 **Cryptographic Test Lock (`E38`):** [Prompt Rules vs. SHA-256 Test Locking](https://tappers.hashnode.dev/e38-cryptographic-test-tampering-lock)
* 🔗 **Negative Scope Guardrails (`E57`):** [Guardrails Beat Guidance: Negative AGENTS.md Rules Cut Diffs 12.7%](https://tappers.hashnode.dev/e57-negative-scope-guardrails)
