Building a Self-Evolving AI on My Mac - Circuit Breakers, Dream Mode, and a Pet Goose

!Cover Image

Building a Self-Evolving AI on My Mac

*This is Part 3. Part 1 covers the foundation. Part 2 covers email defense, task management, and dashboards.*

---

The numbers keep growing:

**1,052 sessions tracked. 730+ implicit ratings. 24 refined instincts. 116 auto-captured memories. 39 specialized agents. A companion goose with an opinion about everything.**

But the real story of Part 3 is about what happens when you get access to the blueprints of the system you're building on top of.

---

The Source Code That Changed Everything

In late March 2026, Anthropic accidentally leaked the full source code of Claude Code. Over 500,000 lines of TypeScript. The internal architecture of the tool I had built my entire AI framework on top of.

When you build a system on another system, you are working blind. You see behaviour, you guess at internals, you hope your assumptions are close enough. The leak removed the guesswork. I deployed 6 research agents in parallel, each covering a different domain:

| Agent | Focus | |-------|-------| | **Core Architecture** | Bootstrap, message pipeline, tool system | | **Agents and Teams** | Subagent spawning, coordination, mailbox protocol | | **Hooks and Skills** | 25 hook event types, skill matching, plugins | | **Memory and Context** | Auto-memory, compaction, CLAUDE.md loading | | **Buddy and Voice** | Companion system, voice gating, IDE bridge | | **Security and Advanced** | Permissions, sandbox, 55+ feature flags |

The result: 12 linked Obsidian notes, 30+ improvement tasks, and a deep understanding of how Claude Code actually manages context, memory, and agent coordination.

---

What I Built: The 7-Layer Context Defense

The single most important discovery from the source: Claude Code doesn't just "summarize and continue" when your context window fills up. It has a **7-layer progressive defense system**, each layer cheaper than the next.

!The 7-layer context defense

1. **Tool Result Budget** -- Cap output per tool (50K chars) and per message (200K). Overflow goes to disk with a 2KB preview. 2. **Snip Compact** -- Delete old messages. Zero API calls. Free. 3. **Microcompact** -- Three paths: time-based cleanup (exploit cache TTL expiry), server-side cache editing, API-native context management. 4. **Context Collapse** -- CQRS pattern: maintain a commit log of collapses, project a compressed view per query. Full history stays intact for recovery. 5. **Auto-Compact** -- LLM summarization with a **circuit breaker**: 3 consecutive failures and it stops trying for the session. 6. **Blocking Limit** -- Hard stop. 7. **Reactive Compact** -- Emergency recovery after 413 errors.

Before reading the source, EMMI-AI had one compaction strategy: "ask Claude to summarize." Now it has three of these layers implemented, with more planned.

---

What I Built: Memory Freshness Warnings

One of the hardest problems in persistent AI systems: **stale memories treated as current facts**.

EMMI-AI now tags every memory and instinct with freshness indicators at load time:

- **Under 7 days**: fresh, used as-is - **7-30 days**: flagged as *"may be outdated"* - **Over 30 days**: flagged as *"likely outdated, verify before acting"*

This sounds simple. It prevents real damage. Before this, EMMI-AI could confidently recommend a function that was renamed two weeks ago, or follow a workflow that I had since changed. The freshness tags make the AI aware that its knowledge might have drifted.

---

What I Built: Circuit Breaker for Compaction

When auto-compact fails 3 times in a row, EMMI-AI stops trying for the rest of the session. This pattern came directly from Claude Code's production data: 1,279 sessions had been trapped in infinite compact-fail-retry loops, burning 250K API calls per day.

The circuit breaker tracks state across compaction events:

``` consecutiveFailures: 0 | 1 | 2 | 3 (TRIPPED) ```

Once tripped, the system outputs a warning and blocks further compaction attempts. This preserves remaining context for actual work instead of wasting it on retries that will keep failing.

---

What I Built: Token Budget Tracking

A new PostToolUse hook estimates token consumption per tool call **without any API calls**:

- JSON content: ~2 bytes per token - Text content: ~4 bytes per token

It tracks cumulative usage, detects **diminishing returns** (3+ continuations with less than 500 tokens of progress each), and signals when to stop. You can set budgets with natural language: `"budget: 500k"` or `"+1m"`.

This prevents runaway sessions where the AI keeps working but producing minimal incremental value.

---

What I Built: Cross-Model Auditing

After extracting everything useful from the source code, I had an idea: what if I used a completely different AI to review my framework?

!Two AI models independently auditing the same codebase

I deployed two models independently: - **Claude Sonnet** -- Found data flow bugs, traced shell script issues, identified unused hook event types - **A separate coding model** -- Found latency concerns, monolith patterns, security patterns that Claude had normalized

**The key insight:** An AI reviewing its own work has systematic blind spots for patterns it considers "normal." A different model does not share those assumptions. If you are building AI systems, get a second opinion from a different model family.

---

What I Built: Auto-Dream Mode

EMMI-AI can dream.

When enabled, the auto-dream system runs a scheduled consolidation cycle. It reads all memories, cross-references signals, and synthesizes patterns that individual sessions miss. Think of it as the AI equivalent of sleep consolidation -- the process where your brain strengthens memories and finds connections during rest.

The dream mode runs via `auto-dream.sh`, scoped with strict permissions: only Read, Write, Edit, Grep, and Glob. No Bash execution, no web access, no agent spawning. It updates the KAIROS scheduler's `last_run` timestamp and writes synthesis files that the next session inherits.

This means EMMI-AI can improve between sessions, not just during them.

---

What I Built: The ENGRAM Observer

The observer is a macOS launchd agent that runs every 10 minutes. It watches every tool call, every user correction, every error recovery. When it detects high-signal events (corrections, errors), it runs a Haiku-class model to extract behavioral instincts.

These instincts are atomic:

```yaml id: perplexity-paired-research-queries trigger: "when conducting research" action: "always pair with Perplexity MCP for gap-filling" confidence: 0.99 ```

They start at confidence 0.5 and earn their way up through repeated validation. Currently 24 active instincts with confidence ranging from 0.70 to 0.99, refined from an initial 58 (the rest were mechanical artifacts like "consecutive reads happen in clusters" -- that is just how parallel execution works, not a behavioral pattern).

---

What I Built: Bristle, the Companion Goose

This one was inspired by Claude Code's built-in buddy system. Claude Code has a `/buddy` command that spawns a companion creature with stats, a personality, and speech bubbles that react to your code changes in real time. After reading how they implemented companion evolution tied to session metrics, I built my own version on top of ENGRAM.

Here is Claude Code's built-in buddy, which adopted the name Bristle because our system injects the personality context at session start:

!Claude Code's built-in /buddy command showing Bristle with its own stat tracking

Our custom Bristle lives in the PULSE HUD and evolves based on real ENGRAM data:

- **Debugging**: +1 for each error-then-recovery sequence - **Patience**: +1 for long sessions (40+ observations), -1 for very short ones - **Chaos**: +1 per build failure, +2 per force push - **Wisdom**: +N for synthesis files created that day - **Snark**: Always 75. It is a goose.

XP accumulates from sessions (+10 base, +50 for high-rated sessions, up to +300 for instinct evolutions). Mood shifts based on average session ratings: delighted, content, curious, grumpy, or chaotic.

!The PULSE HUD showing Bristle's stats alongside system metrics

Our Bristle lives in the PULSE HUD, showing level, XP progress, mood, and all five stats in real time. So there are technically two Bristles: Claude Code's built-in one (with its own stat tracking and speech bubbles) and ours (driven by ENGRAM, visible in the HUD).

The Claude Code Bristle has strong opinions about the arrangement:

!Claude Code's Bristle reacting to our custom evolution system

*"\*HONKS OFFENDEDLY\* Wait -- Wisdom went UP? That's a GLITCH! I'm supposed to stay STUPID and CHAOTIC! Fix it NOW!"*

The goose disapproves of self-improvement. The goose always disapproves.

---

What I Built: Scoped Autonomous Permissions

The background observer and dream mode need to run without a human present. But instead of leaving full permissions wide open, they run with:

```bash --allowedTools "Read,Write,Edit,Grep,Glob" --add-dir "$HOME/.claude/MEMORY" ```

No Bash execution. No web access. No agent spawning. Scoped to the MEMORY directory only. Least privilege in practice.

---

What I Built: The PULSE HUD

The entire system state is visible in a single terminal display. PULSE (Performance, Usage, Learning, Status, Environment) renders in 4 responsive modes depending on terminal width:

- **Skills, workflows, hooks, agents** -- counted and displayed - **Context window** -- real-time percentage with visual buckets - **Memory stats** -- work files, ratings, sessions, research - **Learning sparklines** -- 15-minute to 1-month rating trends - **Bristle companion** -- level, XP bar, mood, stats - **Git status** -- branch, age, modifications - **Inspirational quotes** -- refreshed every 30 seconds

Everything runs locally on my Mac. No cloud dependency for the HUD, the observer, dream mode, or Bristle evolution.

---

The Current System At a Glance

| Component | Status | What It Does | |-----------|--------|-------------| | **ENGRAM Observer** | Active (every 10 min) | Watches tool calls, creates instincts from patterns | | **Auto-Dream** | Enabled | Memory consolidation between sessions | | **Circuit Breaker** | Active | Stops runaway compaction after 3 failures | | **Token Budget** | Active | Tracks usage, detects diminishing returns | | **Memory Freshness** | Active | Flags stale memories at load time | | **Bristle** | Level 1, 190 XP | Companion goose evolving from session data | | **PULSE HUD** | 4 modes | Real-time system dashboard | | **Security Validator** | Active | Conservative defaults on all operations | | **Voice System** | Active | TTS announcements on session events | | **Cross-Model Audit** | On-demand | Deploy multiple AI models for independent review |

---

What's Next

The roadmap from the source analysis includes 30+ documented improvements. Here is what is coming:

Prompt Cache Stability

Claude Code sorts its tool pool alphabetically to maximize prompt cache hit rates. Every token before a cache boundary is wasted on re-encoding. EMMI-AI will implement frozen/fresh context partitions: stable system context at the top (high cache hits), dynamic session context at the bottom.

CQRS Context Collapse

Instead of destructive summarization, maintain a commit log of context events and project compressed views on demand. Full history stays intact for recovery. This is the pattern Claude Code uses internally.

Voice Gating

Gate certain dangerous operations behind voice confirmation. Instead of typing "yes" to confirm a force push, the system would ask aloud and listen for voice confirmation. This ties into the voice input system already running.

IDE Bridge

Connect EMMI-AI's hooks, Bristle, and PULSE to IDE extensions. Claude Code already has this bridge between its CLI and VS Code/JetBrains. For EMMI-AI, it would mean seeing companion status, memory stats, and instinct activity inside the IDE rather than only in the terminal.

KAIROS Daemon

An always-on background daemon that handles scheduled tasks: heartbeat checks, signal pruning, memory consolidation, proactive briefings. Currently experimental, waiting for stability validation before enabling.

Bristle Evolution

The companion system will grow: level milestones at 5, 10, 25, 50, 100. Cosmetic unlocks (hats, eye styles) tied to achievements. Rarity-based stat scaling. The bones are built; the progression just needs sessions to accumulate.

---

What I Learned

1. Reading your tool's source code is transformative

Before the leak, I was building on assumptions. After reading the implementation, I could make informed architectural decisions. The 7-layer context defense alone changed how I think about context management.

2. Cross-model review catches what single-model review never will

An AI reviewing its own work has blind spots for patterns it considers normal. A different model does not share those assumptions. This is now a standard practice in my workflow.

3. Local-first AI is possible and powerful

Everything in this article runs on a single Mac. No cloud servers for the observer, dream mode, or companion evolution. The only cloud dependency is the Claude API itself. This matters for privacy, cost, and the ability to experiment freely.

4. Pruning is as important as growing

Going from 58 instincts to 24 was not a loss. The 34 removed were mechanical artifacts. The remaining 24 are real behavioral patterns with earned confidence scores. Quality over quantity in AI learning systems.

5. Give your AI a personality and it works harder

Half-joking, half-serious. Since adding Bristle, the system feels more alive. The goose reacts to code changes, gains wisdom from synthesis work, and loudly protests any attempt to reduce its chaos stat. It makes the development experience more engaging -- and that matters for solo builders who spend hours in a terminal.

---

*The full source code, including all features and the Bristle companion system, is on GitHub. If you are building your own AI infrastructure inside Claude Code, the codebase documents every pattern I extracted from the source code with implementation details.*

*Part 4 will cover KAIROS daemon activation, prompt cache optimization, and what happens when Bristle reaches Level 5.*