Design / Inside the brain
Brain map → Research paper
TerranSoul // Brain & Memory · the design story

Inside the brain: how an LLM gets memory, recall & skill

A language model is brilliant in the moment and forgets everything between turns. TerranSoul wraps that model in the regions of a real brain — focus, memory, recall, association, feeling and skill — so it can remember, learn from outcomes, and grow more useful over time. This is the what and the why, in plain language.

How the brain works together

Brain Architecture Design

Client request a question arrives Connecting nerve shared access channel Focus & triage what matters now Hybrid recall fuse signals, rerank to a short grounded context Language model core answers from context (local or cloud) Three-tier memory recent, durable, archived + knowledge graph Outcome observed what actually happened Self-improvement loop classify outcome, reinforce or quarantine, update memory Brain’s sources connectors repo brains peers over the nerve need context pull grounded context answer observe write back feed

Many specialised parts, one coherent loop.

01 · The metaphor

An LLM core, wrapped in brain regions

Picture the model as the brain's thinking surface — the part that reasons, in the moment, about whatever is in front of it. On its own it has no memory of its own and no past. TerranSoul grafts on the other regions of a brain, each a small module that gives the core something it lacks.

LLM core · reasons now Focus Memory Graph Recall Affect Skills MCP · the one nerve
One core, six regions, one nerve — everything any client reaches the brain through is the same MCP connection.
FOCUS · the executiveFocus

Not every message deserves deep thought. Focus sizes each turn and routes it — trivial ones skip the heavy machinery, hard ones get the full treatment. It keeps the brain fast and cheap when it can be.

MEMORY · the memory-makerMemory

Forms new memories from what happens and files them for later. Memories flow through tiers and fade unless they're used again — much like human reinforcement and forgetting.

GRAPH · the connectorKnowledge graph

Stores facts as a web of links, not a flat list. By chaining links the brain can reach an answer that no single memory ever spelled out — connecting people, places and ideas across many small facts.

RECALL · perceptionHybrid recall

Surfaces the memories worth seeing for the question at hand. Several different search methods each weigh in, and their verdicts are merged into one trustworthy short list.

AFFECT · feelingAffect

Reads the emotional tone of the brain's own reply, so a companion avatar can show the matching expression. Feeling is part of how it presents, not just what it says.

SKILLS · practised know-howSkills

Learned how-to procedures that build confidence as they succeed and get benched when they keep failing — the brain getting better at the things it does often.

Inside these six regions, finer faculties live. The brain's design names twenty-one cognitive faculties (BCF-01…21) — confidence calibration, drives, a goal-stack, attention, motivation, insight, creativity, cognitive control, governed self-evolving memory and more — each anchored to a real anatomical region of these six, and all implemented today. See the faculty layer below →
02 · Three-tier memory

How a fleeting moment becomes a lasting memory

Human memory isn't one bucket — a phone number you hold for ten seconds is different from a skill you keep for life. The brain uses three tiers, and memories graduate upward only when they earn it.

SHORT-TERM the immediate conversation — the last little while, then gone WORKING what matters for this session — the active working set LONG-TERM durable knowledge that persists — but gently fades if never used used again = promoted
Memories graduate upward when they prove useful, and fade when they're ignored — so the store stays relevant instead of just growing.
Short-term

Holds the immediate flow of conversation. It's there so the brain stays coherent turn to turn, and it's allowed to disappear — most of what's said doesn't need to outlive the chat.

Working

The session's active picture — the facts, threads and goals that matter right now. A staging area where things that keep coming up start to look worth keeping.

Long-term

Durable memory that survives across sessions. Crucially it isn't frozen: unused memories slowly decay, so the brain forgets the trivial and keeps the meaningful — like a person would.

Why it matters: graduation and decay are what keep the brain's memory useful rather than just large. Important things settle in; noise washes out.
03 · Cognitive memory axes

Four kinds of knowing — because not all memory is the same

A tier says how long a memory lives. But memories also differ in what kind of knowing they are — and the right one to surface depends on the question. The brain recognises four cognitive axes, drawn straight from how cognitive science describes human memory.

Axis · episodic

Episodic

What happened, and when. The story of past events and conversations — "last time we tried this," "what we decided yesterday."

Axis · semantic

Semantic

Facts and meanings that hold regardless of when you learned them — definitions, properties, "what is this thing."

Axis · procedural

Procedural

How to do something — the steps of a task. "How do I deploy this," recalled as a procedure rather than a fact.

Axis · judgment

Judgment

Durable rules, heuristics and lessons — the hard-won "do it this way" wisdom that should outrank a one-off anecdote.

The reason this matters is recall quality. A "how do I…" question should reach for procedures first; "what did we decide…" wants the episode; "what is…" wants the fact; and a settled rule should win over a passing remark. By understanding which kind of knowing a question is really asking for, the brain surfaces answers that feel right rather than merely related.

What we're sharing here is the idea, not the machinery. The value is recognising that memory has kinds and that the right kind should lead — how the brain decides which is which stays under the hood.
04 · Hybrid recall

One answer, many points of view

No single way of searching memory is trustworthy on its own. Keyword search nails exact terms but misses meaning; meaning-based search catches paraphrases but fumbles precise identifiers; following links between facts reaches things neither would find alone. So instead of betting on one, the brain asks several — then fuses their answers.

Lexical match Meaning / vector Knowledge graph Freshness Activation FUSE + rerank most relevant memory next best …a clean short list several independent signals → one fused, reranked answer — so no single method can dominate
Hybrid recall fuses several independent rankings, then reranks the result — the breadth of viewpoints is the point.

The signals it fuses

Their separate rankings are blended into one, then a final pass reorders the survivors for genuine relevance. The result reads as a single, confident answer — but it's a consensus of several independent opinions, which is exactly why it's hard to fool.

There is one more pass after the rerank: a set-level bias audit (the BCF-15 faculty) inspects the whole short list for statistical skew — one source over-represented, everything clustered in a single recent window, near-duplicate dominance, or members that contradict each other — and gently down-weights a skewed set before it ever reaches the model. Hybrid recall checks not just which memories surfaced, but whether the set as a whole is balanced.

For research and agent turns, this recall also feeds an optional deep-research answer-mode that loops — critiquing its own coverage and following the knowledge graph — to assemble thoroughly-cited answers. It widens answer coverage, not retrieval: at production cutoffs its candidate set is the same one this single pass already returns.

The value proposition, not the recipe. The strength is the fusion of multiple signals, plus a final fairness check on the set. We name the signals on purpose and stop there — the exact way they're weighed and combined is deliberately not part of this page.
05 · Brain modes

Same brain, your choice of mind

The LLM at the core is pluggable. You can run a private model on your own machine, or reach for a frontier model in the cloud — and everything around it stays the same. Memory, recall, the graph, the skills: identical surface, swappable core.

THE BRAIN memory · recall · graph · skills Local modelprivate · offline · on-device Cloud frontier modelmost capable · via your key pick one — or fall back from one to the other same surface, pluggable core
Local for privacy and offline use, cloud for raw capability — the surrounding brain doesn't change, and one can stand in for the other.
Local mode

A model running entirely on your own device. Private by default, works offline, nothing leaves the machine — the brain's memory and skills wrapped around a mind that's wholly yours.

Cloud mode

A frontier model reached over the network for maximum capability when you want it. Because the surface is identical, the brain can lean on the cloud and still fall back to local — so it keeps working even if the cloud blinks.

06 · Adaptive thinking modes

The right gear for every turn

Choosing the mind is one axis; choosing how hard it should think is another. A greeting should answer instantly; a multi-step build deserves an agent loop; an open-ended question may need a full evidence sweep. TerranSoul has seven real thinking modes, and on every turn the brain reads the message and shifts into the one that fits — automatically, unless you pin a mode yourself.

this turn + recent chat pick Chat — grounded, instant Think — extended reasoning Research — agentic search Max — verify everything one mode wins, setting depth + harness
Every turn is sized and routed into the mode that fits — light when it can be, heavyweight only when the work demands it.

Each mode sets two dials at once — how much the model deliberates, and which behavioural harness wraps the reply:

Auto by default, yours to pin. Left on auto, a per-turn router reads the request and the recent conversation and resolves the mode — so effort and harness scale with the task instead of being fixed. Choose any mode by hand and it stays put. This is the same executive sizing the brain map shows in the Focus region, now choosing not just how much to think but how.
07 · Deep research mode

Exhaustive, fully-cited answers

Most turns are well served by a single recall pass and a short, confident answer. For research and agent work, the research and deep modes can instead engage an optional deep-research answer-mode: it loops — retrieve, ask a completeness critic what the answer still hasn't covered, follow knowledge-graph edges, re-query — then spend its deepest thinking on a thoroughly-cited synthesis. The point is coverage and answer quality, not more recall.

RETRIEVEexhaustively CRITICwhat did Imiss? EXPANDalong edges re-query the gaps — loop until coverage is saturated cited synthesis · [1][2][3]
Retrieve, critique coverage, expand along the graph, re-query — and only once nothing relevant is left unseen, synthesise a cited answer.
An answer-mode, not a recall benchmark. This tier trades latency for coverage and citation quality on research and agent turns. It is not a retrieval-recall improvement: because critic and edge hits are appended after the first round's citations without re-ranking, at the production recall depth (50) and a typical top-k (≤20) its candidate set is identical to the single-shot path — it can only change results at ranks beyond that depth, a regime production never reads. Reach for it when you need thorough, fully-cited answers, not to surface memories ordinary recall would miss.
08 · The self-improvement loop

A brain that learns from its own outcomes

The point of giving a model memory isn't just to look things up — it's to get better. TerranSoul closes the loop: what the brain does, how it turns out, and what it remembers all feed back into what it recalls next time. The cycle is simply write → manage → read.

WRITErecord what MANAGEtidy & link READrecall next time outcomes shape what gets recalled next — the brain tunes itself
Write what was learned, manage it into something durable and connected, read it back when it's relevant — and let how things turned out steer future recall.
Write

As the brain works, it records lessons, facts and the results of what it tried — turning experience into memory rather than letting it evaporate.

Manage

New memories are tidied, linked to related ones, and consolidated so the store stays coherent. Skills that keep succeeding gain standing; ones that keep failing are set aside.

Read

On future turns the brain recalls what's relevant — and because outcomes fed back in, what surfaces is shaped by what actually worked before.

Why it matters: this is the difference between a tool you re-teach every session and a companion that compounds — one whose recall quietly improves the more you use it.
09 · The MCP nerve

One brain, reached and fed through one connection

Every region connects to the world through a single nerve: the Model Context Protocol. That means any client can query the same brain — and the brain, in turn, keeps itself current by pulling from its own sources. Knowledge written by one client is legible to the next.

QUERIED BY PULLS FROM Claude Code Codex apps & companions peer TerranSoul + any MCP client MCP brain one shared memory source connectors per-repo brains peer TerranSoul one brain — consumed by any client, fed by its own sources
The same brain is queried by coding agents, apps and even peer instances — and it keeps itself current by pulling from connectors, repo brains and peers.
Queried by anything

Coding assistants like Claude Code and Codex, desktop and mobile apps, and even another TerranSoul — all reach the same brain over one protocol. Whatever one client learns, the next can read.

Fed by its own sources

The flow runs both ways. The brain also pulls in fresh material from connectors, from per-project repo brains, and from peer instances — so its memory stays current without you feeding it by hand.

10 · Cognitive faculties

Twenty-one named faculties, each in a real brain region

The six regions are the coarse map. Inside them the brain is growing a layer of finer cognitive faculties — BCF-01 through BCF-21 — drawn from cognitive neuroscience and each anchored to the part of a human brain that does the same job. The roster was completed against a four-angle research sweep (cognitive-neuroscience taxonomy, the cognitive-architecture canon, LLM-agent architectures, and deep dives on insight, creativity, metacognition and curiosity), which added three faculties the literature treats as core — insight, creativity, and cognitive control. All twenty-one are now implemented (v1) — the complete roster, each anchored to its matching region on the interactive brain map.

Refreshed against the 2026 frontier. A freshest-2026 sweep (June-2026 agent-memory preprints, the DeepMind cognitive-AGI framework, and the 2026 cognitive-neuroscience literature) re-checked the roster. It mostly confirmed the set — and added one genuinely-distinct faculty, governed self-evolving memory (BCF-21): the write-time safety gate that guards the brain's own autonomous memory against drift, poisoning and unbounded growth. The rest of the frontier landed as dated refinements to existing faculties (memory-aware test-time scaling, latent world-model rollout, conservative consolidation, learned retrieval policies).

Four faculties, up close

BCF-01 · frontal lobe / prefrontalMetacognitive confidence calibration

A second-order monitor that estimates a calibrated confidence in the brain's own answer before it is spoken, and routes the turn to one of four honest choices — answer, deliberate, seek more evidence, or abstain. It reads only structural signals (top score, margin, retrieval quality, agreement across samples, supporting links) and learns its own calibration curve from logged outcomes, so a small local model can decline to bluff rather than hallucinate confidently.

BCF-02 · hypothalamus · drivesMotivation, drives & homeostasis

Endogenous "what should I do now" for an always-on resident. A set of homeostatic drives — coverage (curiosity), competence (mastery), integrity (coherence), upkeep (tidiness) and bond (connection) — each measured from real store metrics. Deviation from a setpoint becomes a need signal, and closing a gap or tidying the store is intrinsic reward. The highest-need drive surfaces as an intent for the goal-stack to act on; drive weights are learned from whether pursuing them tends to succeed.

BCF-03 · dorsolateral PFC · executiveExecutive function & goal-stack

The agenda that turns a fleeting drive into sustained pursuit. A prioritised stack of goals that persists across sessions, with arbitration (priority × drive-weight × due-ness, plus a commitment bonus), a suspend / resume / done / abandon lifecycle, progress tracking that auto-closes finished goals, and commitments with optional deadlines. Stale goals decay so neglected ones sink. This is the difference between a reactive chatbot and an agent that follows through.

BCF-15 · post-retrieval · set auditSystematic retrieval-bias detection

A fairness check on the whole retrieved set, run after rerank but before the model sees it. Four structural metrics — source concentration, recency skew, single-cluster dominance and contradiction density, each normalised to a 0–1 score with no domain word-lists — flag a skewed set and down-weight it. It judges the set, where the per-document quality check judges each row, and its thresholds self-tune from their own flag-rate history.

How they stay honest: every threshold, weight and setpoint above lives in the brain's own seeded configuration, not as a number hardcoded in source — so the brain can re-tune itself, and a fresh store with no seed simply has the faculty switched off. Each faculty writes only its own rows through the one MCP gateway; there are no private caches.

The full faculty roster & its brain-region map

Each faculty sits beside the anatomical region that performs the matching function in a human brain — consistent with the placements on the interactive brain map. Every faculty below is implemented (v1) today — the full twenty-one-faculty roster, complete.

BCF-01
Confidence calibration shipped
Frontal lobe · prefrontal · metacognition

Knows when it doesn't know — calibrated self-confidence that gates answer vs. abstain vs. seek-more.

BCF-02
Drives & homeostasis shipped
Hypothalamus · motivation

Setpoint need-variables plus intrinsic reward from learning-progress — the source of self-directed activity.

BCF-03
Executive · goal-stack shipped
Dorsolateral PFC · executive

A durable, arbitrated goal stack with suspend/resume and commitment tracking that persists across sessions.

BCF-04
Affect · appraisal · mood shipped
Limbic · amygdala

Appraises events against goals into a stored mood that decays — and modulates what becomes salient.

BCF-05
Attention · workspace gate shipped
Thalamo-cortical · broadcast

A winner-take-all bottleneck arbitrating memories, drives, intentions, affect and surprise for the one context window.

BCF-06
Theory of mind · user-model shipped
Temporoparietal · mentalizing

An explicit model of what the user knows, wants and feels, held apart from the agent's own.

BCF-07
Prospective memory shipped
Rostral PFC · intentions

A "do Y when X happens / at time T" store that fires an intention when its cue is met — follow-through beyond the turn.

BCF-08
Test-time-compute allocator shipped
PFC · System-1 / System-2

Decides how much deliberation to spend, escalating only when confidence is low — System-2 on demand without retraining.

BCF-09
Curiosity · info-seeking shipped
Dopaminergic · seeking

Acts on detected gaps with curiosity-driven questions and self-directed search, rewarded for closing a gap.

BCF-10
World model · prediction shipped
Predictive cortex · forward model

Causal "if I do X then Y" transitions for forward simulation and counterfactuals — the source of prediction-error.

BCF-11
Consolidation · reconsolidation shipped
Hippocampal replay · CLS

Idle replay that distils episodes into durable generalisations and revises stale beliefs in place.

BCF-12
Verified skill library shipped
Basal ganglia · procedural

Self-verified, precondition-keyed runnable skills with an automatic curriculum — learning to act, not just recall.

BCF-13
Self · narrative identity shipped
Default-mode · narrative self

A continuous self-narrative that binds sessions into one persistent "I" — the heart of resident embodiment.

BCF-14
Context compression shipped
PFC · context manager

Progressive summarisation / virtual-context paging that keeps long sessions coherent without abrupt truncation.

BCF-15
Retrieval-bias detection shipped
Post-retrieval · occipital · set audit

Audits the retrieved set for statistical skew and down-weights it before injection.

BCF-16
Analogical reasoning shipped
Association cortex · structure-mapping

Aligns relational structure across domains to transfer a solution schema — human-like generalisation.

BCF-17
Multimodal perception shipped
Occipital · perception

A perception front-end mapping image / screen / spatial input into the same memory schema with spatial graph edges.

BCF-18
Insight · restructuring shipped
Right anterior temporal · association cortex

When analytic search stalls, it re-encodes the stuck problem and reaches a remote association — the Aha! leap, measured as a real solution jump, not a token.

BCF-19
Creativity · divergent thinking shipped
Default-mode + control · generate-evaluate

Generates many varied candidate ideas then filters them against constraints — balancing novelty against appropriateness on the four classic divergent-thinking axes.

BCF-20
Cognitive control · inhibition shipped
Anterior cingulate · right IFG · conflict/error

Inhibits a prepotent or unsafe answer, monitors conflict between candidate responses, and catches its own errors to trigger self-correction.

BCF-21
Governed self-evolving memory shipped
Hippocampal–prefrontal gate · memory governance

A write-time safety gate over the brain's own autonomous writes — guarding against belief drift, poisoned or anomalous sources, and unbounded growth, and quarantining peer-brain imports until corroborated.

Why anatomy: the mapping isn't decoration. Confidence and executive control belong to the prefrontal cortex; drives to the hypothalamus; affect to the limbic system; memory consolidation to the hippocampus; perception to the occipital cortex — so the brain-region a faculty sits in is also the clearest shorthand for what it does.
11 · Database design

One clean schema, sharded for the write storm

The memory store is being rebuilt around a single, self-contained schema instead of a long chain of in-place upgrades — and split into purpose-built shards sized for the order of a million memories, so the high-frequency writes of an always-on resident never block recall. This section is a design contract: the spec a follow-up change implements, not yet live in the store. Because TerranSoul is pre-release there is no production data to migrate, so the schema can be recreated clean.

Why redesign — three structural debts

One definition, five table groups

The canonical schema plus its version-helper chain collapse into a single schema applied once (version reset to 1). Every column exists in its CREATE TABLE from the start — no backfills, no "create indexes last" ordering hazard. The schema reads as five clearly fenced groups:

GroupPurposeHolds
G1 core memorythe knowledge base + provenancememories, versions, conflicts, sources, offload payloads
G2 embeddings & indexvector + keyword retrieval surfacesembeddings, pending-embeddings, full-text index + its sync triggers
G3 knowledge graphtyped edges + pre-aggregated statsedges, graph clusters
G4 append-only logswrite-heavy, time-ordered, retention-boundedtraces, telemetry, sync log, calibration log, safety decisions
G5 cognitive-faculty tableslearning / metacognition state on the hot pathreinforcements, trigger patterns, gaps, tool-skills, action-trust ledger, decomposition cache, paired devices

To keep the hot row narrow, the rarely-read procedural ledger (success / failure counts, activation tier, deprecation flag) moves out of the wide memories table into a keyed G5 side table — so the 90% retrieval path reads a compact row and the promoter pays a cheap join only when it needs the counters.

Sharded for high-throughput writes

The store opens one primary connection and attaches siblings — a single-process scale-out where joins still work but each file gets its own write-ahead log, checkpoint cadence, cache and lock. Routing is keyed on the two axes the memory model already encodes — tier (working vs. long) and access pattern (random-access knowledge vs. sequential logs):

durable · primarylong.db

The canonical read-heavy RAG database — core memory, embeddings and the knowledge graph. Tuned with the largest cache for fast fused recall.

session-scopedworking.db

Working-memory churn that promotes and evicts every turn, aggressively checkpointed so it never dirties the durable index.

write-heavy logslogs.db

Append-only telemetry and traces on a separate checkpoint, decoupling high-frequency log writes from retrieval latency.

On top of the shards, several mechanisms absorb the write rate of a resident that records something on nearly every turn:

What stays invariant: every read and write still flows through the one MCP gateway — sharding is entirely internal to the store, and no client ever opens a shard directly or keeps a private cache. The table groups, shard keys, retention windows and pragmas are generic infrastructure; none of them encode any task answer.
12 · Adopted from the field

Best ideas from rival agents, re-grounded as our own

TerranSoul studies competing agent systems and folds their strongest generic patterns into the brain — reimplemented on existing modules as domain-agnostic primitives. No upstream source, prompts, branded identity or schema is copied; each adoption enhances a part of the brain rather than bolting on a parallel one. Influences are credited in the project's CREDITS file.

GENesis-AGI · self-improvement primitivesSharper recall & safe consolidation

A study of GENesis-AGI contributed several generic mechanisms, each reimplemented in Rust: an activation signal as an extra recall term (how alive a memory is right now), an echo-collapse diversity pass that stops near-duplicates dominating a result set, auto-linking on write so new memories join the graph immediately, consolidation safety gates (reversible rollback, faithfulness review, a shrink guard), and outcome-classified write-back that routes a five-class session outcome to reinforce, quarantine or extract.

Hermes · autonomous skill loopMint, prove & refine new skills

Reverse-engineered from the Hermes agent (generically, nothing vendored): a closed learning loop — observe → author → validate → register → reuse → refine — that detects a recurring or workaround-successful trajectory and creates a fresh reusable skill, the one capability the brain lacked. New skills are governed by the existing confidence ledger, surfaced by description-first retrieval (names and one-liners in the prompt, bodies hydrated on match), and curated through an Active → Stale → Archived lifecycle. Design contract; not yet shipped.

Hermes · automation blueprintsRoutines it proposes, you approve

A blueprint unifies a parameterised skill and a human-friendly schedule into one typed object — no raw cron is ever written. When the brain notices a routine worth automating it adds a consent-first suggestion to a queue: it proposes, you accept or dismiss, and only an explicit accept ever schedules anything. The proposal bar is learned from how often suggestions are taken up, so it grows more or less forward over time.

OpenClaw · proactive commitmentsClosing the loops you left open

A continuously-running companion should notice the follow-ups a conversation leaves dangling — "I'll let you know when the build finishes," "check in after their interview" — without being asked. Inferred open-loops are stored as future intentions, and a gentle heartbeat surfaces the due ones through the same attention gate as everything else, held back by quiet-hours, busy-skip and don't-repeat guards so it never nags. How proactive it is, is itself learned.

The patterns it borrows — and where they land

Every borrowed knob is brain-resident. Cluster sizes, look-back windows, length caps, promotion floors and curator timings all live in the brain's seeded configuration — read at runtime, never hardcoded — so adoptions stay tunable and free of task-specific answers.
13 · In a sentence

The whole idea

One frozen LLM, one nerve (MCP), and the 21 BCF components above sitting between them — each one reads/writes its own tables, each one is reachable by the model on every turn. Nothing here retrains the model; every capability lives in the memory layer, which is why it's auditable and swappable independent of the model.

TerranSoul · brain & memory