Designing a Four-Layer Memory Garden and 40K-Char Auto Epoch Rotation for Local Multi-Agent Bots
Most local AI agents start strong on day one and quietly degrade by week two.
The failure mode is rarely the underlying language model. It is memory hygiene. If you keep appending every tool output, retry trace, and status update into a single infinite chat thread, latency climbs, instruction adherence softens, and the agent eventually forgets the constraints you wrote on day one. Conversely, if you wipe the session clean every morning, you spend half your time re-explaining project state, active IDs, and operational boundaries.
When we rebuilt our local multi-agent workbench, we skipped vector-database bloat and designed a plain-file Four-Layer Memory Garden paired with 40K-Character Auto Epoch Rotation. Every layer lives in inspectable Markdown or append-only JSONL, every mutation is snapshot-protected, and every bot stays fast across weeks of continuous operation.
Why Flat Transcripts and Naive RAG Both Fall Short
Before landing on a layered design, we tested two common approaches:
- Infinite single-thread sessions: Easy to bootstrap, terrible after 30–50 tool calls. Even models with massive context windows suffer from attention dilution when old stack traces sit right next to current operational rules.
- Embedding-only RAG over raw chat logs: Great for semantic recall, weak for hard invariants. A top-k vector lookup might retrieve an outdated draft or miss a single one-line safety rule that must apply on every turn.
Specialized operational bots do not treat all information equally. Hard identity boundaries, durable procedures, active run state, and historical transcripts have completely different lifecycles and size budgets. Mixing them into one bucket guarantees drift.
The Four-Layer Memory Garden
Instead of one undifferentiated memory store, each bot in our workbench reads and writes across four distinct layers with strict size caps:
| Layer | File / Store | Lifecycle | Hard Budget | Purpose |
|---|---|---|---|---|
| L1 · Identity & Boundaries | SOUL.md | Rarely edited (human-owned) | Small, fixed | Non-negotiable safety rules, isolation contracts, tone |
| L2 · Durable Playbook | CORE.md | Updated on lessons learned | <= 4,000 chars | Stable CLI recipes, routing rules, anti-footgun invariants |
| L3 · Topic Knowledge | topics/<slug>.md | On-demand modular docs | Per-topic cap | Deep platform rules, style guides, domain checklists |
| L4 · Rolling Working State | BRIEF.md + transcript archive | Updated every milestone / epoch | <= 2,500 chars | Active IDs, lock windows, next actions; full logs indexed separately |
A few architectural trade-offs make this layout unusually resilient:
- Strict character budgets prevent silent bloat. Because
CORE.mdis capped at 4,000 characters andBRIEF.mdat 2,500 characters, a bot cannot dump raw logs into its standing prompt. Every update forces compression into high-signal facts. - Snapshots before every overwrite. Before modifying
CORE.md,BRIEF.md, or any topic file, the memory tool writes a timestamped backup into.history/. If a bot ever writes a noisy summary, rolling back is a single deterministic call. - Secret-rejection gate on write. Memory writes pass through a fail-closed secret scanner. Credentials, tokens, and sensitive identifiers are rejected before they ever touch disk, so secrets never leak into long-term context.
- Cold history stays cold. Full transcripts are rotated out of the active prompt window and queried on demand via full-text history search only when an agent genuinely needs an older detail.
40K-Character Auto Epoch Rotation
The four layers define where knowledge lives; Auto Epoch Rotation defines when the active session resets.
In our kernel, every active conversation tracks the cumulative character count of its current epoch. Once the running window crosses 40,000 characters (roughly 10K–15K tokens depending on code and language mix), the runtime schedules a clean epoch boundary:
- Flush working state: The bot distills active task IDs, external URLs, lock dates, and pending next steps into
BRIEF.md(<= 2,500chars). - Promote durable lessons: Any newly discovered edge case or workflow invariant gets promoted into
CORE.md(<= 4,000chars) or a dedicatedtopics/<slug>.md. - Archive and rotate: The completed epoch transcript is sealed into the searchable log store, and the next turn starts a fresh epoch seeded only with
SOUL.md,CORE.md, andBRIEF.md.
Why 40,000 characters instead of waiting for a 200K-token ceiling? Because operational quality degrades long before a hard token limit is hit. Rotating early keeps every turn snappy, predictable, and tightly anchored to the bot's actual rules.
Reference Implementation in Python
Here is a self-contained, zero-dependency reference implementation showing the budget enforcement, atomic snapshot rotation, and 40K-character epoch trigger we use in practice:
from dataclasses import dataclass from datetime import datetime, timezone from pathlib import Path import re import shutil EPOCH_CHAR_LIMIT = 40_000 BRIEF_CHAR_LIMIT = 2_500 CORE_CHAR_LIMIT = 4_000 SECRET_PATTERNS = ( re.compile(r"\b(?:sk-|ghp_|AIza|AKIA)[A-Za-z0-9_\-]{12,}\b"), re.compile(r"\b(?:api[_-]?key|secret[_-]?token)\s*[:=]\s*\S{12,}\b", re.IGNORECASE), ) class MemoryGuardError(ValueError): """Raised when a memory write violates size or secret hygiene rules.""" @dataclass class EpochState: epoch_id: int accumulated_chars: int = 0 def record_turn(self, text: str) -> bool: """Add turn length and return True when epoch rotation is required.""" self.accumulated_chars += len(text) return self.accumulated_chars >= EPOCH_CHAR_LIMIT def safe_write_layer(target: Path, content: str, max_chars: int) -> Path: """Validate budget and secrets, snapshot prior version, then atomically write.""" text = content.strip() + "\n" if len(text) > max_chars: raise MemoryGuardError( f"{target.name} exceeds budget ({len(text)} > {max_chars} chars)" ) for pattern in SECRET_PATTERNS: if pattern.search(text): raise MemoryGuardError(f"Blocked potential secret in {target.name}") target.parent.mkdir(parents=True, exist_ok=True) if target.exists(): history_dir = target.parent / ".history" history_dir.mkdir(exist_ok=True) stamp = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H-%M-%SZ") shutil.copy2(target, history_dir / f"{stamp}__{target.name}.bak") tmp_path = target.with_suffix(target.suffix + ".tmp") tmp_path.write_text(text, encoding="utf-8") tmp_path.replace(target) return target if __name__ == "__main__": epoch = EpochState(epoch_id=1) assert not epoch.record_turn("x" * 15_000) assert epoch.record_turn("y" * 26_000) print("Epoch rotation trigger verified at 40K chars.") Offline Verification Checklist
Before trusting a memory garden in unattended daily runs, verify these five invariants offline:
- Budget enforcement: Attempting to write a
2,600-characterBRIEF.mdfails closed withMemoryGuardError. - Snapshot integrity: Overwriting
CORE.mdtwice produces two timestamped.bakfiles in.history/and leaves the latest file intact via atomic rename. - Secret rejection: Injecting a synthetic credential string into any memory write aborts before disk mutation.
- Epoch handoff continuity: After forcing a rotation at
40,000characters, the fresh epoch still knows active IDs, lock windows, and pending tasks purely fromSOUL.md + CORE.md + BRIEF.md. - Cold recall: Historical details intentionally omitted from
BRIEF.mdremain retrievable via on-demand history search without bloating every turn.
Structured plain-text layers and early epoch rotation are not glamorous, but they solve the exact failure modes that break real multi-agent systems in week two. Keep the active window small, force explicit state compression, and let cold logs stay cold.