Metadata-Version: 2.4
Name: brainos-cli
Version: 1.2.0
Summary: Brain-inspired memory plugins + a cognitive runtime for long-lived AI agents.
Author: Nirav Vaghasiya
License: MIT
Project-URL: Homepage, https://github.com/niravvaghasiya/BrainOS
Project-URL: Repository, https://github.com/niravvaghasiya/BrainOS
Keywords: ai,memory,agents,rag,llm,cognitive-architecture,cognitive-runtime
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Requires-Python: >=3.9
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: click>=8.0
Requires-Dist: rich>=13.0
Provides-Extra: all
Requires-Dist: numpy>=1.24; extra == "all"
Requires-Dist: sentence-transformers>=2.2; extra == "all"
Requires-Dist: chromadb>=0.4; extra == "all"
Requires-Dist: networkx>=3.0; extra == "all"
Provides-Extra: postgres
Requires-Dist: psycopg[binary]>=3.1; extra == "postgres"
Provides-Extra: dev
Requires-Dist: pytest>=7.0; extra == "dev"
Requires-Dist: pytest-cov>=4.0; extra == "dev"
Requires-Dist: ruff>=0.1.0; extra == "dev"
Requires-Dist: build>=1.0; extra == "dev"
Requires-Dist: twine>=4.0; extra == "dev"
Dynamic: license-file

<div align="center">

# 🧠 BrainOS

### The Human Brain as a Software Architecture

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

[![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE)
[![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg)](CONTRIBUTING.md)
[![PyPI](https://img.shields.io/pypi/v/brainos-cli?color=orange&label=pip%20install%20brainos-cli)](https://pypi.org/project/brainos-cli/)
[![Docs](https://img.shields.io/badge/docs-116%20markdown-purple.svg)](#-architecture)
[![Tests](https://img.shields.io/badge/tests-316%20passing-brightgreen.svg)](#-getting-started-step-by-step)
[![Stars](https://img.shields.io/github/stars/niravvaghasiya/brainos?style=social)](https://github.com/niravvaghasiya/brainos)

<br>

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

<br>

[Explore the Architecture](#-architecture) · [Install via CLI](#-install) · [Browse Plugins](#-plugins-brain-inspired-ai-components) · [Learn a Technique](#-techniques-evidence-based-methods) · [Understand the Flows](#-flows-information-pathways)

</div>

---

## 🧠➡️⚙️ 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](docs/v2/EVALUATION.md#ablation), and the neuroscience mappings now
carry explicit [epistemic status](docs/NEUROSCIENCE_EVIDENCE.md).

```python
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](docs/v2/README.md) · [Quickstart](docs/v2/QUICKSTART.md) ·
[Cognitive Runtime](docs/v2/COGNITIVE_RUNTIME.md) · [Memory Model](docs/v2/MEMORY_MODEL.md) ·
[Retrieval](docs/v2/RETRIEVAL.md) · [Learning](docs/v2/LEARNING.md) ·
[Security](docs/v2/SECURITY.md) · [Evaluation](docs/v2/EVALUATION.md)

---

## 🚦 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:

```bash
python --version    # should be 3.10 or newer
```

### Step 1 — Get the repo

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

### Step 2 — Choose your path

<details open>
<summary><b>Path A — Use the v2 Cognitive Runtime (build a long-lived agent)</b></summary>

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

```bash
# 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
```

```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](docs/v2/QUICKSTART.md) (temporal memory, learning,
storage backends, LangGraph/MCP adapters) and the [v2 docs](docs/v2/README.md).

</details>

<details>
<summary><b>Path B — Install plugins into your own project (pip)</b></summary>

```bash
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](#-plugins-brain-inspired-ai-components) and the
[Integration Guide](docs/INTEGRATION_GUIDE.md).

</details>

<details>
<summary><b>Path C — Just read the knowledge base (zero dependencies)</b></summary>

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](#-how-to-navigate) for guided reading orders.

</details>

### Step 3 — Verify everything works

```bash
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](docs/v2/QUICKSTART.md) |
| Understand the runtime internals | [Cognitive Runtime](docs/v2/COGNITIVE_RUNTIME.md) |
| See measured evidence per component | [Evaluation & Ablation](docs/v2/EVALUATION.md) |
| Embed in LangGraph / MCP | [v2 Overview → Adapters](docs/v2/README.md) |
| Drop plugins into an existing app | [Integration Guide](docs/INTEGRATION_GUIDE.md) |

---

## 🤔 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](#-try-it-live) below).

---

## ⚡ Install

### Via pip (live on PyPI)

```bash
pip install brainos-cli
```

```bash
# 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:

```bash
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](examples/01_memory_agent/) | A chat agent with sensory-gate + working-memory + hippocampal-index + forgetting-engine, recalling context from earlier turns | `make demo` |
| [Token Benchmark](examples/02_token_benchmark/) | Measured token savings vs a naive full-history agent (offline, no API key) | `make benchmark` |
| [Cognitive Runtime](examples/03_cognitive_runtime/) | A full conversation flowing through the v2 `BrainOS` runtime (observe → recall → plan → learn) | `python examples/03_cognitive_runtime/runtime_demo.py` |
| [Adapters](examples/04_adapters/) | The same memory driven through vanilla, LangGraph, and MCP adapters | `python examples/04_adapters/adapters_demo.py` |

More resources:

- **[Integration Guide](docs/INTEGRATION_GUIDE.md)** — wire BrainOS plugins into LangChain, LangGraph, CrewAI, or vanilla Python.
- **Diagrams** — [architecture overview](docs/assets/architecture_overview.svg), [information flow](docs/assets/information_flow.svg), [brain vs. AI](docs/assets/brain_vs_ai.svg).

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](docs/assets/architecture_overview.svg)

---

## 🔌 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`](_plugins/01_sensory_gate.md) | Thalamic Filter | Pre-filter raw tool/API outputs | 50-80% |
| [`attention-filter`](_plugins/02_attention_filter.md) | Selective Attention | Score & rank context by relevance | 40-70% |
| [`working-memory`](_plugins/03_working_memory_manager.md) | Prefrontal WM | 4-6 slot active state scratchpad | 25-45% |
| [`hippocampal-index`](_plugins/04_hippocampal_index.md) | Hippocampus | Embed + bind + pattern-complete retrieval | 20-40% |
| [`consolidator`](_plugins/05_consolidator.md) | Sleep Consolidation | Offline summarize, dedupe, extract patterns | 60-80% storage |
| [`episodic-store`](_plugins/06_episodic_store.md) | Episodic Memory | Event memory (WHO/WHAT/WHEN/WHERE) | — |
| [`semantic-store`](_plugins/07_semantic_store.md) | Knowledge Graph | Persistent facts + relationships | — |
| [`procedural-cache`](_plugins/08_procedural_cache.md) | Basal Ganglia | Cache action sequences, skip re-reasoning | 30-50% |
| [`salience-tagger`](_plugins/09_salience_tagger.md) | Amygdala | Priority-score memories at storage time | 20-40% |
| [`forgetting-engine`](_plugins/10_forgetting_engine.md) | Active Forgetting | TTL, decay, pruning (bounded growth) | ∞ (prevents bloat) |
| [`dmn-incubator`](_plugins/11_dmn_incubator.md) | Default Mode Network | Background insight generation | — |
| [`metacognition`](_plugins/12_metacognition_monitor.md) | Prefrontal Monitor | Self-eval + strategy selection | Compounds |

### Benchmarked Results

Measured on a simulated 50-turn agent conversation (see [`examples/02_token_benchmark/`](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](_techniques/01_spaced_repetition.md) | ★★★★★ | Intervene at the point of forgetting |
| 02 | [Active Recall](_techniques/02_active_recall.md) | ★★★★★ | Testing > re-reading by 2x |
| 03 | [Method of Loci](_techniques/03_method_of_loci.md) | ★★★★☆ | Hijack hippocampal spatial indexing |
| 04 | [Chunking](_techniques/04_chunking_strategies.md) | ★★★★☆ | Compress items to fit WM slots |
| 05 | [Elaborative Encoding](_techniques/05_elaborative_encoding.md) | ★★★★☆ | Depth of processing = durability |
| 06 | [Sleep Optimization](_techniques/06_sleep_optimization.md) | ★★★★☆ | Study before sleep, not after waking |
| 07 | [Interleaving](_techniques/07_interleaving.md) | ★★★★☆ | Mix topics for better discrimination |
| 08 | [Dual Coding](_techniques/08_dual_coding.md) | ★★★☆☆ | Words + images = 2x encoding |
| 09 | [Exercise & Memory](_techniques/09_exercise_and_memory.md) | ★★★★☆ | 30 min aerobic = BDNF → hippocampal growth |
| 10 | [Meta-Learning](_techniques/10_meta_learning.md) | ★★★★★ | 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](_flows/01_encoding_pathway.md) | World → Sensory → Attention → WM → Hippocampus | 0 → 500ms |
| [Consolidation](_flows/02_consolidation_pathway.md) | Hippocampus → Sleep replay → Cortical permanence | Hours → Years |
| [Retrieval](_flows/03_retrieval_pathway.md) | Cue → Pattern completion → Reconstruction | 200ms → 2s |
| [Emotional Modulation](_flows/04_emotional_modulation.md) | Amygdala amplifies/blocks at every stage | 12ms (fast path) |
| [Motor Learning](_flows/05_motor_learning_pathway.md) | Cortex → Basal Ganglia → Cerebellum → Auto | Days → Permanent |
| [Language Pipeline](_flows/06_language_processing_pipeline.md) | Sound → Phonemes → Words → Syntax → Meaning | 0 → 400ms |
| [Forgetting](_flows/07_forgetting_pathway.md) | Decay, interference, pruning, suppression | Hours → Years |
| [Cross-System](_flows/08_cross_system_interactions.md) | 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`](https://pypi.org/project/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](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](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.

---

<div align="center">

**Built by [Nirav Vaghasiya](https://linkedin.com/in/niravrvaghasiya)**

*Neuroscience × Software Architecture × AI Memory Systems*

</div>
