# When Agent MEMORY.md Goes Stale: Freshness Gates, Skeletons & Evolution (10 Benchmarks)

> 💡 **AI Labo Benchmark Cluster Synthesis — Experiments `E65, E66, E73, E76, E78, E80, E82, E83, E84, E88` (Memory & Evolution)**
>
> Synthesizing 10 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)**

In our v1 study [`E20`](https://tappers.hashnode.dev/e20-episodic-gotchas-memory), injecting a curated 5-item `MEMORY.md` cut input tokens by `-95.5%`. Naturally, teams ask the next question: *"If 5 rules help, why not let the agent automatically append lessons after every run, auto-evolve its harness, strip comments from code skeletons to save more tokens, and inject refactoring hints everywhere?"*

Across **10 multi-wave and brownfield Proxmox benchmarks (`E65`, `E66`, `E73`, `E76`, `E78`, `E80`, `E82`, `E83`, `E84`, `E88`)**, we discovered the dark side of unguarded memory and over-eager compression. Append-only logs accumulate **poisoned stale rules (`E78`, `E84`)** and **flaky environment noise (`E88`)**, stripping docstrings and constant comments breaks subtle edge cases (`E83`), and verbose refactoring diagnostics backfire on small explicit tasks (`E80`). Memory and harness evolution only pay off when wrapped in **freshness gates, backward revision, modular anchor tests, and concise syntax/value hints**.

---

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

* **1. Unchecked `MEMORY.md` Decays Into a Stale Tax—Freshness Gates & Backward Revision Fix It (`E78`, `E84`, `E88`):** Letting stale policy linger in `MEMORY.md` forced the agent to double-check `CURRENT_POLICY.py` anyway, yielding zero turn savings (`6.0 vs. 6.0`) and **`+5.0%` higher effective cached cost (`E84`)**. Conversely, backward-revising obsolete entries across a 3-wave spec shift (`ReHarness`, `E78`) deleted stale rules (`2 -> 0`), compressed `MEMORY.md` (`9 -> 6` lines), and **cut effective cost `-14.9%` (`$0.0338` ➔ `$0.0288`)**. Filtering transient timeouts/locale errors (`ENV_TRANSIENT` in `E88`) slashed uncached input SD by **`-95.6%`** and cost SD by **`-60.0%`**.
* **2. Guarded Evolution Slashes Variance Without Full Rewrites (`E65`, `E66`, `E73`, `E76`):** Cross-wave Self-Improvement Memory (`SIM`, `E65`) stopped a `10,643`-token Wave-2 thinking runaway and cut cost SD `-73.4%`. Semantic block-level checkpointing (`E66`) cut effective cost `-5.9%` and cost SD `-75.9%`. Anchoring continual harness updates against 6 regression tasks (`E73`) hit `0` regressions (`+9.84pt` cache hit) for a `+$0.0037` insurance fee, while 4-component modular updates (`E76`) beat monolithic rewrites (`-40.3%` time, `-91.3%` time SD).
* **3. Keep Docstrings in Skeletons (`E83`) and Scope Refactoring Diagnostics to Legacy Scale (`E80` vs. `E82`):** Stripping comments/docstrings from dependency skeletons cut Turn-0 chars `-66.6%` (`E83`) yet caused a missing floor-constant failure (`skl83_31`), `+1` extra turn, lower cache reuse (`51.0% -> 42.8%`), and **`+8.7%` higher cost**. Similarly, verbose refactoring hints hurt explicit 3-module codebases (**`+24.4%` cost in `E80`**), while cutting **median cost `-20.4%` (`$0.1161` ➔ `$0.0924`)** on massive `2,036`-AST undisclosed legacy codebases (`E82`).

| Exp | Harness Contrast (Mode A vs. Mode B, `N=3`) | Hidden Suite | Stability / Efficiency Impact | Effective Cached Cost (A ➔ B) |
| :--- | :--- | :---: | :--- | :---: |
| **`E65`** | Harness-Only vs. SIM 2-Wave Memory (`VM270`) | `28.00` ➔ `28.33/32` | Killed `10,643`-tok runaway, cost SD `-73.4%` | `` `$0.0906` `` ➔ **`` `$0.0864` `` (`-4.6%`)** |
| **`E66`** | Whole-Script vs. Semantic Block Ckpt (`VM271`) | `31.00/32` parity | Calls `10 -> 9`, cache `+5.88pt`, SD `-75.9%` | `` `$0.0384` `` ➔ **`` `$0.0361` `` (`-5.9%`)** |
| **`E73`** | Greedy Evo vs. 6-Anchor Guarded Evo (`VM278`) | `32/32` (`0` regr.) | Cache `+9.84pt`, token SD `-89.5%`, SD `-61.9%` | `` `$0.0232` `` ➔ `` `$0.0269` `` (`+$0.0037` ins.) |
| **`E76`** | Full Rewrite vs. 4-Comp Modular Evo (`VM281`) | `32/32` parity | Tool stdout `-78.3%`, time `-40.3%`, SD `-91.3%` | `` `$0.0263` `` ➔ **`` `$0.0258` `` (`-1.7%`)** |
| **`E78`** | Append-Only vs. Backward-Revision (`VM283`) | `31.00` vs. `30.67/32` | Stale rules `2 -> 0`, tokens `-18.8%`, time `-15.5%` | `` `$0.0338` `` ➔ **`` `$0.0288` `` (`-14.9%`)** |
| **`E80`** | Syntax Hints vs. Refactor Diags Small (`VM285`) | `32/32` tie | Extra reads spiked total tokens `+51.1%` | `` `$0.0239` `` ➔ `` `$0.0298` `` (**`+24.4%`**) |
| **`E82`** | Syntax Hints vs. Refactor Diags `2,036` AST (`VM287`) | `32/32` tie | **Median `-20.4%`** (`` `$0.1161` `` ➔ `` `$0.0924` ``), T3 outlier mean `+7.9%` | `` `$0.1255` `` ➔ `` `$0.1354` `` (mean) |
| **`E83`** | Docstring Skeleton vs. Stripped Sig (`VM288`) | `31.67` vs. `31.33/32` | Missing `#` floor constant (`+1` turn, cache `-8.2pt`) | `` `$0.0318` `` ➔ `` `$0.0346` `` (**`+8.7%`**) |
| **`E84`** | Cold-Start Source vs. Stale `MEMORY.md` (`VM289`) | `32/32` tie | Zero turn win (`6 vs 6`), input `+8.3%`, time `+15.6%` | `` `$0.0197` `` ➔ `` `$0.0207` `` (**`+5.0%`**) |
| **`E88`** | Raw Lesson Log vs. `ENV_TRANSIENT` Reset (`VM293`) | `32/32` parity | `100%` flaky filter, uncached SD `-95.6%`, SD `-60.0%` | `` `$0.0183` `` ➔ **`` `$0.0181` `` (`-1.0%`)** |

---

## 1. The Memory Lifecycle & Diagnostic Thresholds

```text
+-------------------------------------------------------------------------+
| Freshness-Gated Memory & Skeleton Design Criteria (E65..E88)            |
|                                                                         |
|  [Error / Spec Shift]                                                   |
|     |-- Flaky timeout / locale / disk noise? --> DROP (ENV_TRANSIENT)   |
|     '-- Code invariant verified against file SHA-256?                   |
|           |-- Contradicts older rule? --> OVERWRITE / RETIRE (E78)      |
|           '-- Verified & concise?     --> PIN in <=15-line MEMORY.md    |
|                                                                         |
|  [Pre-Turn Source Injection]                                            |
|     |-- Check recorded source_sha256 == live file SHA-256 (E84 gate)    |
|     |-- Keep docstrings + domain constants in AST skeletons (E83)       |
|     '-- Gate verbose refactor hints strictly to legacy AST >500 nodes   |
+-------------------------------------------------------------------------+
```

Three design lessons stand out when comparing these 10 studies alongside [`E21`](https://tappers.hashnode.dev/e21-treesitter-skeleton-context) and [`E50`](https://tappers.hashnode.dev/e50-observability-driven-automatic-harness):

1. **Untrusted Cache in Prose Form (`E78`, `E84`, `E88`):** `MEMORY.md` is a lossy secondary index over source code. When `E84` seeded a stale policy claim, models still verified `CURRENT_POLICY.py` before trusting it—so stale entries gave *zero* turn speedup while inflating prompt overhead `+5.0%`. Binding every memory line to a primary file hash (`sha256_prefix`) and resetting transient `ENV_TRANSIENT` errors automatically prunes rot.
2. **Never Over-Strip Semantic Anchors (`E83`):** Tree-sitter skeletons win when they strip *implementation bodies* (`E21`), not when they delete `#`-comments containing business constants (`skl83_31` floor values) or behavioral docstrings. Always retain signatures, types, docstrings, and constant definitions.
3. **Diagnostic Scope Calibration (`E80` vs. `E82`):** Verbose architectural/refactoring diagnostics backfire (`+24.4%` cost) on clean 3-file specs where the agent already sees the full picture (`E80`), yet cut median effective spend **`-20.4%`** when orienting inside a sprawling `2,036`-AST legacy repository (`E82`).

---

## 2. Drop-In Implementation Recipe: Freshness-Gated `MEMORY.md` Store (`E78` + `E84` + `E88`)

```python
import hashlib
import json
import re
from dataclasses import asdict, dataclass
from pathlib import Path

TRANSIENT_PATTERNS = (
    re.compile(r"(timed out|ETIMEDOUT|temporary failure|locale\.Error|BrokenPipeError)", re.I),
)


@dataclass
class MemoryEntry:
    rule_id: str
    rule_text: str
    source_path: str
    source_sha256: str


class FreshnessGatedMemoryStore:
    """Bounded (<=15 rules), SHA-validated, transient-filtered MEMORY store [E78/E84/E88]."""

    def __init__(self, repo_root: Path, store_path: Path, max_rules: int = 15) -> None:
        self.repo_root = repo_root
        self.store_path = store_path
        self.max_rules = max_rules

    def _file_sha(self, rel_path: str) -> str:
        target = self.repo_root / rel_path
        return hashlib.sha256(target.read_bytes()).hexdigest()[:16] if target.exists() else "MISSING"

    def _load(self) -> list[MemoryEntry]:
        if not self.store_path.exists():
            return []
        return [MemoryEntry(**item) for item in json.loads(self.store_path.read_text(encoding="utf-8"))]

    def record_lesson(self, rule_id: str, rule_text: str, source_path: str, raw_err: str = "") -> bool:
        """Reject flaky ENV_TRANSIENT lessons [E88]; overwrite stale rule_id in place [E78]."""
        if any(pat.search(raw_err) for pat in TRANSIENT_PATTERNS):
            return False  # Do not pollute durable memory with flaky environment noise
        sha = self._file_sha(source_path)
        entries = [e for e in self._load() if e.rule_id != rule_id]
        entries.append(MemoryEntry(rule_id=rule_id, rule_text=rule_text.strip(), source_path=source_path, source_sha256=sha))
        self.store_path.write_text(
            json.dumps([asdict(e) for e in entries[-self.max_rules :]], indent=2), encoding="utf-8"
        )
        return True

    def render_fresh_memory(self) -> str:
        """Evict rules whose backing source file changed since capture [E84]."""
        fresh: list[MemoryEntry] = []
        for entry in self._load():
            if self._file_sha(entry.source_path) == entry.source_sha256:
                fresh.append(entry)
        if len(fresh) != len(self._load()):
            self.store_path.write_text(json.dumps([asdict(e) for e in fresh], indent=2), encoding="utf-8")
        return "\n".join(f"- [{e.rule_id}] ({e.source_path}@{e.source_sha256[:8]}) {e.rule_text}" for e in fresh)
```

---

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

1. **Cross-Wave Synthetic Shifts vs. Multi-Month Production Drift:** `E65`, `E73`, and `E78` tested 2–3 sequential waves inside a controlled Proxmox fixture (`32` hidden assertions). Multi-month human repositories modify unrelated lines in `source_path` frequently, which can trigger conservative hash evictions (`E84`); binding hashes at the AST-function level (`file.py::Symbol`) rather than whole-file SHA reduces unnecessary invalidation.
2. **Outlier Risk on Complex Legacy Diagnoses (`E82`):** Even though refactoring diagnostics cut **median** cost by `-20.4%` (`$0.0924` vs. `$0.1161`), one `T3` trial spiraled to 18 turns, shifting the mean up `+7.9%`. Always combine heavy diagnostics with a turn-count circuit breaker or early-stop gate from **[Cluster 2: Zero-Cost Brownfield Guards](https://tappers.hashnode.dev/e68-e94-brownfield-zero-cost-defense-cluster)**.
3. **From Single-Agent Memory to Multi-Agent Coordination:** When multiple workers read or rewrite shared modules concurrently, memory alone cannot stop overwrite conflicts—see **[Cluster 4: Multi-Agent Coding Without Merge Chaos](https://tappers.hashnode.dev/e64-e90-multi-agent-contract-coordination-cluster)** for contract locking and adaptive team collapse.

<details>
<summary>📋 Experiment Metadata & Reproducibility (E65, E66, E73, E76, E78, E80, E82, E83, E84, E88)</summary>

* **Experiment Cluster:** `E65` (`VM270`), `E66` (`VM271`), `E73` (`VM278`), `E76` (`VM281`), `E78` (`VM283`), `E80` (`VM285`), `E82` (`VM287`), `E83` (`VM288`), `E84` (`VM289`), `E88` (`VM293`)
* **Protocol:** Benchmark v2.1 (`N=3` counterbalanced `AB/BA` trials per experiment, `temperature=0.7`)
* **Sandbox:** Zero-NIC Debian Proxmox VMs (`PrivateNetwork=yes`, 3-UID isolation)
* **Model & Pricing:** `gemini-3.8-flash` (`thinkingLevel="LOW"`, `max_output_tokens=32768`), reporting 90% prefix-cached effective cost (`effective_cached_usd`).

</details>

---

**Discussion:** How do you prevent stale hints in `CLAUDE.md` / `AGENTS.md` / `MEMORY.md` from silently contradicting refactored code over multi-week sprints?

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

* 🔍 **[Interactive Trial Explorer (CLUSTER3)](https://tappers-labo.github.io/ai-labo-benchmark-data/#cluster=CLUSTER3)** — 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 2 (`E68`–`E94`):** [Zero-Cost Brownfield Agent Guards: Full-Dir Locks, AST Hooks & Early Stop](https://tappers.hashnode.dev/e68-e94-brownfield-zero-cost-defense-cluster)
* 🤝 **Cluster 4 (`E64`–`E90`):** [Multi-Agent Coding Without Merge Chaos: Contract Locks & Adaptive Teams](https://tappers.hashnode.dev/e64-e90-multi-agent-contract-coordination-cluster)
* 🔗 **Foundational Gotchas Study (`E20`):** [Cold-Start Exploration vs. a 5-Item `MEMORY.md`](https://tappers.hashnode.dev/e20-episodic-gotchas-memory)
* 🔗 **Foundational Skeleton Study (`E21`):** [Full Source vs. Tree-sitter Interface Skeletons](https://tappers.hashnode.dev/e21-treesitter-skeleton-context)
