> ## Documentation Index
> Fetch the complete documentation index at: https://docs.wolffi.sh/llms.txt
> Use this file to discover all available pages before exploring further.

# Brain Modules

> Detailed reference for all 15 runtime modules

# The 15 Runtime Modules

## How the Brain Works

Wolffish models its runtime after the human brain — not as a metaphor, but as an architecture pattern. Each module handles exactly one cognitive function, and they communicate through a shared event bus (the corpus callosum) rather than calling each other directly.

When a message arrives, it flows through the modules like a neural signal:

1. **Input arrives** — the channel adapter (Desktop, Telegram, or WhatsApp) emits an `input.received` event on the corpus
2. **Context is built** — the prefrontal cortex reads your identity files, queries the hippocampus for relevant memories, asks the cerebellum which capabilities are available, and passes everything through the RAS attention filter to fit within the token budget
3. **The LLM thinks** — the thalamus sends the assembled prompt to the one Brain model you selected (`config.llm.brain`) and streams the response back; there's no cascade between providers
4. **Response is parsed** — Wernicke's area extracts tool calls and text from the stream, normalizing across all nine cloud provider formats
5. **Safety is checked** — if tool calls are present, the amygdala checks them against danger patterns and either approves, requests confirmation, or blocks
6. **Tools execute** — the motor cortex runs approved tools, logging every step to task files with retry logic
7. **Response is delivered** — Broca's area streams the final text back to the user through the channel
8. **Memory is saved** — the hippocampus appends the conversation to today's episode file
9. **Learning happens** — the basal ganglia records whether tool calls succeeded or failed, building a feedback history

All of this happens in a deterministic 17-step pipeline. The brainstem runs background processes (file watching, scheduled tasks, nightly memory consolidation), the hypothalamus monitors system health, and the insula provides self-awareness so the agent can report on its own state.

The key insight: because every module communicates through events and writes its state to markdown files, the entire brain is observable and editable at every layer.

***

## Module Reference

Wolffish has 15 runtime modules, each handling one specific function. They all live in `src/main/runtime/` and communicate exclusively via the event bus (`corpus`).

## corpus.ts — Event Bus

Maps to the **corpus callosum**. The nervous system connecting all modules.

Built on `mitt` with 30+ typed events. A wildcard handler logs every event to daily markdown files at `brain/corpus/YYYY-MM-DD.log.md` with a 2-second buffer flush. Old logs are cleaned up after 7 days. Initialized first and passed as a singleton to all other modules.

## thalamus.ts — Model Gateway

Maps to the **thalamus** (sensory gateway). Manages nine cloud LLM providers plus Ollama via pure `fetch()`.

Resolves the one Brain model you selected (`config.llm.brain`) and streams from it — there's no cascade or automatic substitution between providers. Uses `net.isOnline()` for instant offline detection. On a transient error it retries the **same** Brain on a backoff schedule; health tracking with exponential backoff feeds that same-model retry and diagnostics, not provider switching. Exposes a unified `async *stream()` generator yielding `StreamChunk` types.

## prefrontal.ts — Context Builder

Maps to the **prefrontal cortex** (executive function). The most important module.

Reads workspace markdown files, calls cerebellum for tool definitions, calls cortex for memory search, passes candidates through RAS for scoring, and assembles the final system prompt with XML tags. Writes debug snapshots to `brain/prefrontal/.debug/`. Excludes `brain/cerebellum/` and `brain/corpus/` from memory candidates.

## ras.ts — Attention Filter

Maps to the **Reticular Activating System**. Decides what's relevant.

Keyword-based relevance scoring with a 0.25 minimum threshold. Token budget allocation: 15% identity, 10% prefrontal, 30% memory, 20% skills, 25% history. Uses \~4 chars per token estimation.

## cortex.ts — Search Index

Maps to the **cerebral cortex**. Fast retrieval via SQLite.

WAL mode, FTS5 virtual table, BM25 ranking. Fully disposable — delete `cortex.db` and it rebuilds from markdown. Supports single-file index/remove for the brainstem file watcher.

## hippocampus.ts — Memory

Maps to the **hippocampus**. Three-tier memory system.

* **Episodes** (`episodes/YYYY-MM-DD.md`): Daily conversation logs, appended every turn with no LLM call
* **Consolidated** (`consolidated/YYYY-WNN.md`): Weekly summaries generated by brainstem's nightly compaction
* **Knowledge** (`knowledge/`): Permanent topic files promoted from episodes

## cerebellum.ts — Capability Loader

Maps to the **cerebellum** (motor coordination). Discovers and loads capabilities.

Scans `brain/cerebellum/` for capability folders, parses SKILL.md frontmatter (YAML), dynamic-imports plugins, registers tools and danger patterns. Passes `PluginContext` (pluginDir + workspaceRoot) to plugins on init.

## wernicke.ts — Response Parser

Maps to **Wernicke's area** (language comprehension). Understands LLM output.

Parses streaming chunks, extracts tool calls, normalizes across three provider formats into a single `ToolCall` type. Handles partial JSON and thinking blocks.

## broca.ts — Response Assembler

Maps to **Broca's area** (language production). Produces the final response.

Streams tokens to renderer via IPC, formats tool results, manages line breaks between text segments from different LLM turns.

## amygdala.ts — Safety Gate

Maps to the **amygdala** (threat detection). Zero hardcoded patterns — all loaded from SKILL.md via cerebellum.

Matches against `toolName + " " + JSON.stringify(args)`. Three classification levels: `safe` (proceed), `confirm` (show approval dialog), `block` (deny). IPC approval flow with Promise-based bridge.

## motor.ts — Task Executor

Maps to the **motor cortex**. Runs tool calls with full logging.

Creates task markdown files at `brain/motor/tasks/TASK-{id}.md`. Per-step logging with args, output, duration, and attempt count. 3x retry with 2s/6s/18s exponential backoff. AbortController for stop support.

## basalganglia.ts — Feedback Loop

Maps to the **basal ganglia** (reward/learning). Learns from outcomes.

Daily feedback files with full args and output snippet (\~200 char truncation). Records four outcome types: success, failure, denial, approval.

## hypothalamus.ts — System Monitor

Maps to the **hypothalamus** (homeostasis). Watches system health.

60-second `setInterval` monitoring RAM, disk, CPU, and context window usage. Emits `health.warning` and `health.critical` events on corpus when thresholds are exceeded.

## brainstem.ts — Background Processes

Maps to the **brainstem** (autonomic functions). Runs without user interaction.

`chokidar` file watcher with 500ms debounce triggers cortex reindexing on file changes. `node-cron` scheduler reads schedules from `brainstem/heartbeat.md`. Nightly LLM-powered compaction consolidates episodes into weekly summaries (cloud-first for quality). All in-process — no system-level daemons.

## insula.ts — Self-Awareness

Maps to the **insula** (interoception). Knows its own state.

Exposed via the `introspect` capability with three tools: `wolffish_status`, `wolffish_performance`, `wolffish_memory`. Reads workspace files directly for stats. Ask Wolffish "how are you doing?" and it reads its own logs to answer.
