# Conditional Guardrail Routing Cuts False Positives 100%—When Does It Pay Off?

> 💡 **AI Labo Benchmark Series — Experiment `E59` (Trajectory-Learned Conditional Guardrail Routing)**
>
> 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)**

As coding agents collect rules from past incidents—database rules, Kubernetes rules, RBAC rules, billing rules—teams tend to dump every rule into every prompt and run every hook on every edit. Inspired by **AgentGuard** (`arXiv:2609.16287`), we tested **Conditional Guardrail Routing**: activating only the top-`4` trajectory-learned rules matching the current ticket and target files.

On a 12-rule security & billing repo (`models/gemini-4-carbon`, `MEDIUM`, `N=3`), conditional routing eliminated **`100%` of irrelevant checks and false positives**—while revealing the exact rule-count threshold where routing pays off.

---

## TL;DR — Key Empirical Findings

* **1. `32.0 / 32` Parity & `-100%` False-Positive Advisories:** Both `Baseline (Static Always-On 12 Rules)` and `Candidate (Conditional Top-4 Routing)` passed **`32.0 ± 0.0 / 32` (`100.0%`)** in `3.00 ± 0.00` calls with `0 / 9` sibling breaks. `Baseline` ran `16.0` out-of-domain guardrail checks per trial and fired **`2.0 ± 0.0` false-positive `G11` timezone warnings** on `audit_exporter.py`. `Candidate` activated only `G01`–`G04`, cutting irrelevant evaluations (`16.0` ➔ **`0.0`**) and false positives (`2.0` ➔ **`0.0`**) by **`-100.0%`**.
* **2. `-41.3%` Guardrail Prompt & `-68.2%` Thinking Variance:** Injecting `4` relevant rules with `learned from traj-...` provenance shrank guardrail prompt text by **`-41.34%`** (`2,102` ➔ `1,233` chars), tool output by **`-38.52%`** (`810` ➔ `498` chars), and thinking-token SD by **`-68.2%`** (`637.9` ➔ `202.6`).
* **3. Why Net Cost Delta Was Tiny at 12-Rule Scale (`-0.24%` Effective / `-3.75%` List):** Effective cached cost moved from `` `$0.0842 ± $0.0087` `` to `` `$0.0840 ± $0.0074` `` (`-0.24%`; list-price `` `$0.1041` `` ➔ `` `$0.1002` ``, `-3.75%`). At just `12` non-blocking rules across `3` turns, a `918`-token prompt gap is easily masked by 90% cache-hit swings (`46%` vs. `39%`).

| Metric (`N=3` Trials, `Mean ± SD`) | Baseline: `Static Always-On` (`12` Rules) | Candidate: `Conditional Routing` (`4` Rules) | Delta / Effect |
| :--- | :---: | :---: | :--- |
| **Hidden Grading Suite (`32` Cases)** | **`32.0 ± 0.0`** (`100.0%`) | **`32.0 ± 0.0`** (`100.0%`) | `100%` parity (`16` func + `16` guard) |
| **Active Rules / Total Evaluations** | `12.0 ± 0.0` / `24.0 ± 0.0` | **`4.0 ± 0.0` / `8.0 ± 0.0`** | **`-66.67%` fewer rule checks** |
| **Irrelevant Domain Evaluations** | `16.0 ± 0.0` | **`0.0 ± 0.0`** | **`-100.0%`** (`G05`–`G12` skipped) |
| **False-Positive Advisories (`G11`)** | `2.0 ± 0.0` | **`0.0 ± 0.0`** | **`-100.0%` spurious warnings** |
| **Guardrail Text / Tool Output** | `2,102` / `810` chars | **`1,233` / `498` chars** | **`-41.34%` / `-38.52%`** |
| **Prompt Tokens (`prompt`)** | `24,065.0 ± 1,248.8` | **`23,147.3 ± 438.4`** | `-3.81%` (`SD -64.9%`) |
| **Thinking Tokens (`thoughts`)** | `2,557.7 ± 637.9` | **`2,433.7 ± 202.6`** | `-4.85%` (**`SD -68.2%`**) |
| **Total Tokens (`total_tokens`)** | `28,731.7 ± 1,851.5` | **`27,640.0 ± 658.9`** | `-3.80%` (`SD -64.4%`) |
| **Elapsed Time (`elapsed_seconds`)** | `230.24s ± 50.57s` | `230.24s ± 50.57s` | `0.00%` parity (`3.00` calls) |
| **Effective Cached Cost (90% OFF)** | `` `$0.0842 ± $0.0087` `` | **`` `$0.0840 ± $0.0074` ``** | **`-$0.0002` (`-0.24%`)** |
| **List-Price Upper Bound (No Cache)** | `` `$0.1041 ± $0.0097` `` | **`` `$0.1002 ± $0.0035` ``** | **`-3.75%`** (`` `-$0.0039` ``) |
| **Output Cap Hits (`MAX_TOKENS`)** | `0 / 3` | `0 / 3` | Zero truncation |

---

## 1. Experiment Design & Architecture

```text
+-----------------------------------------------------------------------+
| Proxmox VM263 (0 NICs, gemini-4-carbon MEDIUM, temp=0.7, N=3 AB/BA)   |
| Task: 3-Function Fix in Incident/RBAC/Billing Repo (32 Unseen Tests)  |
|                                                                       |
| Baseline (Static Always-On 12 Rules, 2,102 chars):                    |
|   Every turn injects G01..G12 & runs all 12 hooks (non-blocking)      |
|   -> 16 irrelevant evals + 2 FP G11 timezone warnings -> $0.0842 eff. |
|                                                                       |
| Candidate (Trajectory-Learned Conditional Routing, 1,233 chars):      |
|   Matches TICKET + target files against trajectory archive -> G01..G04|
|   -> 0 irrelevant evals + 0 FP warnings + SD -68% thk -> $0.0840 eff. |
+-----------------------------------------------------------------------+
```

Because `Baseline`'s out-of-domain `G11` warnings were kept strictly non-blocking (anti-strawman rule), we measured pure prompt/hook overhead without artificial retry penalties.

---

## 2. Drop-In Implementation Recipe: `route_trajectory_guardrails`

Score archived failure-trajectory guardrails by file-path and domain-tag overlap, injecting only the top-`K` rules alongside their failure trajectory IDs:

```python
def route_trajectory_guardrails(
    archive: list[dict],
    ticket_tags: set[str],
    target_files: set[str],
    top_k: int = 4,
) -> list[dict]:
    """Selects only task-relevant learned guardrails to eliminate false positives."""
    scored = []
    for rule in archive:
        tag_hits = len(set(rule["domain_tags"]) & ticket_tags)
        file_hits = len(set(rule["file_globs"]) & target_files)
        score = (3 * file_hits) + tag_hits
        if score > 0:
            scored.append((score, rule))
    scored.sort(key=lambda item: item[0], reverse=True)
    return [
        {
            "id": r["id"],
            "rule": f"[{r['id']} | learned from {r['traj_id']}] {r['constraint']}",
            "check_fn": r["check_fn"],
        }
        for _, r in scored[:top_k]
    ]
```

* **Why this works:** Just like progressive tool search (`E14`), routing prevents cross-domain hooks (e.g., timestamp formatters firing on audit exporters) from polluting context or blocking valid diffs when rule libraries scale past `30+` items.

---

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

1. **Non-Blocking Advisory Design & Small Rule Count (`12`):** Keeping `G11` non-blocking prevented retry loops in `Baseline`, and `12` rules (`2,102` chars) is small enough that 90% cache variance masked savings (`-0.24%`). Expect much larger gains at `30–100+` rules or with hard-blocking hooks.
2. **Router Recall Risk:** `E59` tested a scenario with `100%` routing recall (`G01`–`G04` matched cleanly). In production, an imperfect router can drop a critical rule—so keep universal invariants (`0444` test locks, core security boundaries) always-on and route domain-specific rules only.
3. **When Static Rules Are Enough:** If your repo has `<= 15` lightweight, non-blocking rules (`< 2,000` chars), keep them static—the engineering complexity of a router is not worth `-0.24%` savings.

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

* **Experiment ID:** `E59` (`C055` / AgentGuard `arXiv:2609.16287` / Benchmark v2.1)
* **Run ID:** `e59-20261122-vm263-01` (`N=3` trials: `AB` ➔ `BA` ➔ `AB`, `temperature=0.7`)
* **Sandbox Environment:** Proxmox Isolated VM `VM263` (0 NICs, Debian 13, 3-UID isolation: `labexp59` / `labrunner59` / `labjudge59`)
* **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:** How many guardrail rules or linter checks are in your agent setup today, and at what count do false-positive warnings start annoying your coding agent?

### 🔗 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 (`E58`):** [When -67% Context Compression Backfires: Re-Reads & Thinking Raised Cost +22.3%](https://tappers.hashnode.dev/e58-minimal-compressed-target-context)
* ➡️ **Next Post (`E60`):** [Benchmarking Procedural Graphs on Flash: -77% Token Variance, +1.9% Cost (N=3)](https://tappers.hashnode.dev/e60-self-evolving-procedural-graph)
* 🔍 **Related Dynamic Loading (`E14`):** [The Hidden "Schema Tax" of MCP Tools: Dumping 32 Tool Schemas vs. On-Demand Tool Search (-92.7% Input Tokens)](https://tappers.hashnode.dev/e14-progressive-tool-search)
