Skip to main content

🧠 BrainOS

The Human Brain as a Software Architecture

A complete knowledge repository that maps neuroscience to engineering —
from neurons to production-ready AI memory systems.

License: MIT PRs Welcome PyPI Docs Tests Stars


"The brain is not a filing cabinet. It's a living, rewiring, pattern-matching network."


Explore the Architecture · Install via CLI · Browse Plugins · Learn a Technique · Understand the Flows


🧠➡️⚙️ BrainOS v2 — Cognitive Runtime

BrainOS is a cognitive runtime for long-lived AI agents, inspired by computational principles of human memory.

Beyond the knowledge base and plugins below, BrainOS now ships a runtime (brainos_runtime/) that coordinates memory, retrieval, working memory, learning and safety behind one small API — so an agent can remember better, reason better, learn from experience, use less context, recover from mistakes, and stay safe over long periods. Each component's contribution is measured by an ablation study, and the neuroscience mappings now carry explicit epistemic status.

from brainos_runtime import BrainOS

brain = BrainOS(actor_id="alex")
brain.observe("The production database is PostgreSQL 16")
brain.recall("what database do we use?")   # -> ["The production database is PostgreSQL 16"]

Start here: v2 Overview · Quickstart · Cognitive Runtime · Memory Model · Retrieval · Learning · Security · Evaluation


🚦 Getting Started (Step by Step)

New here? Pick the path that matches your goal. All three run offline with no API keys.

Prerequisites

  • Python 3.10+ (3.10–3.12 are CI-tested; 3.13 works locally).
  • git, pip, and optionally make (the Makefile just wraps the commands below).

Check your version:

python --version    # should be 3.10 or newer

Step 1 — Get the repo

git clone https://github.com/niravvaghasiya/BrainOS.git
cd BrainOS

Step 2 — Choose your path

Path A — Use the v2 Cognitive Runtime (build a long-lived agent)

The runtime lives in brainos_runtime/ and is pure-Python. From the repo root:

# 1. install the package (ships the runtime + the plugin CLI), then optionally
#    generate the plugins the runtime prefers (it falls back to built-in
#    equivalents if you skip `brainos add all`).
pip install -e . && brainos add all

# 2. verify your environment is healthy
python -m brainos_runtime.cli doctor

# 3. run your first agent turns in a Python shell
python
from brainos_runtime import BrainOS

brain = BrainOS(actor_id="alex")
brain.observe("The production database is PostgreSQL 16")
brain.observe("Deploys happen on Fridays at 5pm")

brain.recall("what database do we use?")
# -> ["The production database is PostgreSQL 16"]

# It knows what it doesn't know:
brain.decide("what is the on-call rotation?")   # -> "ask"

# Explain its reasoning:
brain.why("when do deploys happen?")             # per-signal retrieval breakdown
print(brain.trace(formatted=True))               # step-by-step cognitive trace

Next: the Quickstart (temporal memory, learning, storage backends, LangGraph/MCP adapters) and the v2 docs.

Path B — Install plugins into your own project (pip)
pip install brainos-cli        # from PyPI
brainos list                   # see all 12 plugins
brainos init                   # scaffold brainos_plugins/, config/, tests/
brainos add hippocampal-index --with-config --with-tests
brainos add all                # or add everything at once
brainos info hippocampal-index # details on any plugin

Each plugin generates a working Python class you can import from brainos_plugins. See Plugins and the Integration Guide.

Path C — Just read the knowledge base (zero dependencies)

Every folder is plain markdown. Start with a brain region and follow the files:

01_sensory_buffer/README.md → mechanisms.md → examples.md → failures.md

See How to Navigate for guided reading orders.

Step 3 — Verify everything works

make install     # pip install -e .  + brainos add all
make test        # run the full test suite (316 tests)
make demo        # interactive memory-agent chat (Ctrl+C to exit)
make benchmark   # reproduce the token-savings numbers
make lint        # ruff

No make? Run the equivalents directly, e.g. python -m pytest tests/ -q, python -m brainos_runtime.cli eval.

Step 4 — Go deeper

You want to… Go to
Build an agent with memory v2 Quickstart
Understand the runtime internals Cognitive Runtime
See measured evidence per component Evaluation & Ablation
Embed in LangGraph / MCP v2 Overview → Adapters
Drop plugins into an existing app Integration Guide

🤔 What Is This?

BrainOS treats the human brain as a software system and documents it like one:

If you're a... You'll use this for...
🤖 AI/ML Engineer Brain-inspired memory architecture plugins for your agents
🧑‍🎓 Student Evidence-based study techniques grounded in neuroscience
🧠 Neuroscience Learner Structured, code-like understanding of brain systems
🏗️ Systems Architect Bio-inspired patterns for retrieval, caching, and orchestration

No paywall. No fluff. 116 markdown files of structured knowledge — plus a working cognitive runtime (brainos_runtime/) you can drop into an agent today.


Demo

An AI agent using sensory-gate + hippocampal-index + working-memory + forgetting-engine — retrieving conversation context from 20 turns ago in under 200ms. Run it yourself with make demo (see Try It Live below).


⚡ Install

Via pip (live on PyPI)

pip install brainos-cli
# See all 12 plugins
brainos list

# Initialize project structure
brainos init

# Add a specific plugin (generates working Python class + config + tests)
brainos add sensory-gate --with-config --with-tests

# Add all plugins at once
brainos add all

# Get details about any plugin
brainos info hippocampal-index

Or just clone the knowledge base

Clone and explore — zero dependencies, pure markdown:

git clone https://github.com/niravvaghasiya/BrainOS.git
cd BrainOS

Each plugin in _plugins/ is a complete architecture spec. The CLI generates starter code from these specs into your project.


🚀 Try It Live

Runnable, dependency-light examples that use the generated plugins end to end:

Example What it shows Run it
Memory Agent A chat agent with sensory-gate + working-memory + hippocampal-index + forgetting-engine, recalling context from earlier turns make demo
Token Benchmark Measured token savings vs a naive full-history agent (offline, no API key) make benchmark
Cognitive Runtime A full conversation flowing through the v2 BrainOS runtime (observe → recall → plan → learn) python examples/03_cognitive_runtime/runtime_demo.py
Adapters The same memory driven through vanilla, LangGraph, and MCP adapters python examples/04_adapters/adapters_demo.py

More resources:

Common tasks are wrapped in a Makefile: make install, make test, make lint, make demo, make benchmark.


📐 Architecture

The brain's information storage system, mapped as 8 numbered modules + 4 support systems:

brainos/
│
├── 01_sensory_buffer/          → Input preprocessing (200ms–3s buffer)
├── 02_working_memory/          → Active workspace (4±1 slots, 15–30s)
├── 03_hippocampus/             → Indexer & Consolidation Router
├── 04_long_term_memory/        → Permanent distributed storage (~2.5 PB)
│   ├── explicit_declarative/   → Conscious recall (episodic + semantic)
│   └── implicit_nondeclarative/→ Unconscious (procedural + priming + conditioning)
├── 05_emotional_tagging/       → Priority scoring (amygdala)
├── 06_motor_memory/            → Cerebellum (body autopilot)
├── 07_language_networks/       → Broca + Wernicke (speech/comprehension)
├── 08_default_mode_network/    → Background processing (creativity, simulation)
│
├── _system/                    → Infrastructure (neurotransmitters, sleep, plasticity)
├── _flows/                     → Information pathways between systems
├── _techniques/                → Evidence-based learning methods
├── _plugins/                   → Brain-inspired AI/Agent component specs
│
├── brainos_runtime/            → 🆕 v2 Cognitive Runtime (the product)
│   ├── core/                   → kernel: events, cycle, state, BrainOS facade
│   ├── memory/                 → canonical schema + temporal memory
│   ├── retrieval/              → multi-signal retrieval engine + metrics
│   ├── cognition/              → typed working memory + metacognition
│   ├── learning/               → consolidation, forgetting, beliefs, outcomes
│   ├── security/               → trust, tenant isolation, injection defense
│   ├── storage/                → InMemory / SQLite / Postgres backends
│   ├── observability/          → session tracing + why() explanations
│   ├── adapters/               → vanilla / LangGraph / MCP
│   ├── evidence/               → neuroscience epistemic-status layer
│   └── cli.py                  → runtime CLI (python -m brainos_runtime.cli)
├── brainos_eval/               → 🆕 evaluation suite + ablation + long-running
│
├── cli/                        → pip-installable plugin CLI (brainos add <plugin>)
├── examples/                   → Runnable demos (memory agent, benchmark, runtime, adapters)
├── tests/                      → pytest suite (316 tests: plugins + runtime + eval)
└── docs/                       → v2 docs, integration guide, diagrams, baseline

Every module contains:

  • README.md — What it does and how it works
  • mechanisms.md — Biological machinery (molecular → circuit level)
  • examples.md — Real-world demonstrations and experiments
  • failures.md — Disorders, decay, and what breaks

Architecture Overview


🔌 Plugins: Brain-Inspired AI Components

The killer feature. Each brain system is translated into an installable architecture component for AI agents.

Plugin Brain Analog What It Does Token Savings
sensory-gate Thalamic Filter Pre-filter raw tool/API outputs 50-80%
attention-filter Selective Attention Score & rank context by relevance 40-70%
working-memory Prefrontal WM 4-6 slot active state scratchpad 25-45%
hippocampal-index Hippocampus Embed + bind + pattern-complete retrieval 20-40%
consolidator Sleep Consolidation Offline summarize, dedupe, extract patterns 60-80% storage
episodic-store Episodic Memory Event memory (WHO/WHAT/WHEN/WHERE) —
semantic-store Knowledge Graph Persistent facts + relationships —
procedural-cache Basal Ganglia Cache action sequences, skip re-reasoning 30-50%
salience-tagger Amygdala Priority-score memories at storage time 20-40%
forgetting-engine Active Forgetting TTL, decay, pruning (bounded growth) ∞ (prevents bloat)
dmn-incubator Default Mode Network Background insight generation —
metacognition Prefrontal Monitor Self-eval + strategy selection Compounds

Benchmarked Results

Measured on a simulated 50-turn agent conversation (see examples/02_token_benchmark/), counted with tiktoken cl100k_base:

Configuration Total Tokens vs Naive Peak Context
Naive (full history) 424,361 — 16,540
+ Sensory Gate 278,627 -34% 10,820
+ Attention Filter 162,236 -62% 3,997 (budget)
+ Forgetting Engine 138,690 -67% 5,567
Full BrainOS Stack 79,381 -81% 3,114 (budget)

Real, reproducible numbers from examples/02_token_benchmark/. Run it yourself: make benchmark. The naive baseline grows tokens O(n²) (each call resends all history); the full stack keeps it O(n) by bounding context.

Quick Start: Which plugins solve your problem?

Context window overflows?     → sensory-gate + attention-filter + forgetting-engine
Agent forgets conversations?  → episodic-store + consolidator
Redundant tool calls?         → procedural-cache + working-memory
Can't find relevant context?  → hippocampal-index + salience-tagger
No self-improvement?          → metacognition + dmn-incubator

Each plugin includes a Python interface, implementation patterns, YAML config, and integration examples.


🛠️ Techniques: Evidence-Based Methods

For humans who want to learn better — backed by the neuroscience in this repo.

# Technique Effectiveness Key Insight
01 Spaced Repetition ★★★★★ Intervene at the point of forgetting
02 Active Recall ★★★★★ Testing > re-reading by 2x
03 Method of Loci ★★★★☆ Hijack hippocampal spatial indexing
04 Chunking ★★★★☆ Compress items to fit WM slots
05 Elaborative Encoding ★★★★☆ Depth of processing = durability
06 Sleep Optimization ★★★★☆ Study before sleep, not after waking
07 Interleaving ★★★★☆ Mix topics for better discrimination
08 Dual Coding ★★★☆☆ Words + images = 2x encoding
09 Exercise & Memory ★★★★☆ 30 min aerobic = BDNF → hippocampal growth
10 Meta-Learning ★★★★★ Learning how to learn (the master skill)

🔀 Flows: Information Pathways

How data moves BETWEEN systems — from first contact to permanent storage to recall.

Flow What It Maps Key Timing
Encoding World → Sensory → Attention → WM → Hippocampus 0 → 500ms
Consolidation Hippocampus → Sleep replay → Cortical permanence Hours → Years
Retrieval Cue → Pattern completion → Reconstruction 200ms → 2s
Emotional Modulation Amygdala amplifies/blocks at every stage 12ms (fast path)
Motor Learning Cortex → Basal Ganglia → Cerebellum → Auto Days → Permanent
Language Pipeline Sound → Phonemes → Words → Syntax → Meaning 0 → 400ms
Forgetting Decay, interference, pruning, suppression Hours → Years
Cross-System Full communication matrix + real-time walkthrough Parallel

📊 Key Principles

# Principle Implication
1 Distributed Storage No single neuron holds a memory — patterns across networks
2 Associative Indexing Memories link by meaning, not by address
3 Reconstruction ≠ Playback Recall rebuilds from fragments + context + inference
4 Use-It-or-Lose-It Synapses weaken without reactivation (forgetting = feature)
5 Emotional Priority Amygdala tags "important" → fast-tracked consolidation
6 Sleep = Save Consolidation happens offline during deep sleep & REM
7 Capacity Limits = Features 4-slot WM forces prioritization → better decisions

📈 By the Numbers

Metric Value
Markdown docs 116 files
CLI installable pip install brainos-cli
Brain regions covered 8 primary + 4 support systems
Information flow pathways 8
Practical techniques 10
Installable AI plugins 12 (all with working code + tests)
v2 runtime subsystems 10 (core, memory, retrieval, cognition, learning, security, storage, observability, adapters, evidence)
Agent adapters 3 (vanilla, LangGraph, MCP)
Storage backends 3 (InMemory, SQLite, Postgres)
Runnable examples 4 (memory agent, token benchmark, cognitive runtime, adapters)
Test suite 316 tests (43 baseline plugin tests + 273 runtime/eval), CI on Python 3.10–3.12
Disorders/failures documented 50+
Research citations 100+

🧭 How to Navigate

I want to understand a brain region:

01_sensory_buffer/README.md → mechanisms.md → examples.md → failures.md

I want to build better AI memory:

_plugins/README.md → Pick your problem → Install the plugin(s)

I want to study more effectively:

_techniques/README.md → Pick by effectiveness rating → Follow the protocol

I want to understand information flow:

_flows/README.md → Follow the numbered pathway → See cross-system interactions

I want to build an agent with the v2 runtime:

docs/v2/QUICKSTART.md → python -m brainos_runtime.cli doctor → from brainos_runtime import BrainOS

I want to run the code:

make install → make demo (chat agent) → make benchmark (token savings) → make test

🤝 Contributing

Contributions welcome! See CONTRIBUTING.md for guidelines.

Areas especially open for contribution:

  • 🔬 Additional research citations and experiment descriptions
  • 🧪 More framework integrations and example apps (LlamaIndex, Autogen, ...)
  • 📊 Diagrams and visualizations of pathways
  • 🌍 Translations
  • 🧑‍⚕️ Clinical case studies for the failures.md files

📄 License

MIT License — see LICENSE. Use freely, build on it, credit appreciated.


⭐ Star History

If this helped you understand brains, build better AI, or study more effectively — consider starring the repo.


Built by Nirav Vaghasiya

Neuroscience × Software Architecture × AI Memory Systems

Metadata

Release files for brainos-cli 1.2.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for brainos-cli 1.2.0
File Size Uploaded Provenance Actions
brainos_cli-1.2.0.tar.gz 138.4 kB Without provenance Details for brainos_cli-1.2.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for brainos-cli 1.2.0
File Interpreter ABI Platform Actions
brainos_cli-1.2.0-py3-none-any.whl Python 3 none any Details for brainos_cli-1.2.0-py3-none-any.whl

Total release size: 262.4 kB

Release files / brainos_cli-1.2.0.tar.gz

Download URL brainos_cli-1.2.0.tar.gz
Size 138.4 kB
Tags Source
SHA-256 checksum
How to use checksums
7f9a059a4216dd41366947516aa51309fb9bfa20ccea505e7318b9f408eb6914
BLAKE2b-256 checksum
How to use checksums
f7a13c279a289f6a0246a5dfecb27f732e3b9af57e7f8eec04d61610a517f96a
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.13.2

Release files / brainos_cli-1.2.0-py3-none-any.whl

Download URL brainos_cli-1.2.0-py3-none-any.whl
Size 124.0 kB
Tags Python 3
SHA-256 checksum
How to use checksums
d1c7f785f8a01dc418bc504fab8f85994147b433137c63e40facd31f050103e0
BLAKE2b-256 checksum
How to use checksums
2aecf525799321b1cbc7526b66b0d1c4a3f23fa029a7f683c8851b902018b231
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.13.2

Security for brainos-cli 1.2.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page