Skip to content
Nirav Vaghasiya

Cognitive runtime for AI agents

BrainOS

A neuroscience-inspired cognitive runtime that gives long-lived agents typed memory, budget-aware retrieval, working memory, consolidation and safety behind one small Python API.

  • Memory systems
  • Retrieval
  • Continual learning
  • Agent safety
Status
Published on PyPI · runtime in alpha
Started
2026
Stack
Python · SQLite / Postgres · LangGraph & MCP adapters · PyPI
Package
brainos-cli 1.2.0
Runtime core
Pure standard library
Memory types
8
Storage
In-memory · SQLite · Postgres
Adapters
Vanilla · LangGraph · MCP
Contribution
A small kernel runs a fixed cognitive cycle over a canonical memory store. Retrieval happens before storage so recall can surface prior context, and every mechanism can be switched off for ablation.
Best evidence
424,361 → 79,381
Author-reported simulated conversation; counted with tiktoken (cl100k_base).
Main limitation
Default retrieval is lexical (token Jaccard) unless embeddings are supplied; salience and incubation are keyword and temporal heuristics.
Verification basis
Repository source, v2 documentation, evaluation fixtures and PyPI metadata inspected.
01

Overview

BrainOS is a cognitive runtime for long-lived AI agents. Instead of pushing the full conversation into every prompt, an agent observes events into a typed memory store, recalls a budgeted set of relevant memories, and lets the runtime handle supersession, consolidation, forgetting and trust. The design borrows computational principles from human memory, and every brain-to-software mapping is labelled by evidence level rather than asserted as fact.

02

Problem

Agents that keep the full history pay a token cost that grows quadratically over a conversation, and still lose track of what mattered. Bolt-on memory has different failure modes: facts get silently overwritten, arbitrary tool output becomes trusted long-term memory, and the vector index quietly becomes the only source of truth.

03

Motivation

The project began as a knowledge base mapping neuroscience to engineering: eight brain regions, twelve plugin specifications and ten study techniques. The v2 runtime came from deliberately changing the success metric. The question stopped being “how many brain-inspired plugins does BrainOS have?” and became whether a small cognitive kernel coordinating memory, retrieval, working memory, learning and safety measurably helps an agent remember better, use less context and stay safe over long periods.

04

Architecture

A small kernel runs a fixed cognitive cycle over a canonical memory store. Retrieval happens before storage so recall can surface prior context, and every mechanism can be switched off for ablation.

Architecture · cognitive runtime
Cycle
Observeevent in
Filtersensory gate
Attendworking memory · 6 slots
Retrievebudgeted recall
Reasonmetacognition
Storetyped memory

↺ consolidate · forget every N turns

Memory
Store8 types · provenance · lifecycle
Retrieval enginemulti-signal score → greedy under token budget
Working memorytyped slots · TTL · dependency-aware
Learning
Beliefscontradictions supersede, never delete
Consolidationdedupe · derive facts · weaken inferences
Forgettingcomposite strength · max-active cap
Safety
Trust policytenant · source · content · verification
Quarantinesuspicious input isolated
Promotion policyinferred ≠ durable fact
Storage
Backends
In-memory
SQLite
Postgres
Adapters
Vanilla
LangGraph
MCP
  • source of truth
  • budgeted step
  • ablatable via feature flag
Retrieval runs before storage so recall can surface prior context. The relational store is authoritative; indexes are derived from it. Every mechanism on the learning and safety lanes can be disabled for ablation.
Cognitive cycle
Observe → filter (sensory gate) → attend (working memory) → retrieve → reason (metacognition) → store, with consolidation and forgetting running every N turns.
Memory model
Eight memory types — episodic, semantic, procedural, preference, goal, constraint, reflection and belief — each carrying provenance (observed, inferred or derived) and a lifecycle: candidate → validated → active → superseded, expired, archived or quarantined.
Retrieval engine
A multi-signal score combines semantic similarity (or a lexical fallback), task and temporal relevance, salience, confidence, recency decay and utility, minus redundancy and token cost. Selection is greedy under a token budget after an O(n) prefilter; superseded and stale memories are excluded by default.
Working memory
Typed slots (six by default) with TTL expiry, value-based eviction and dependency preservation. Biological capacity is treated as inspiration, not as an engineering requirement.
Learning loop
A belief manager resolves contradictions by recency, source reliability, explicitness, confidence, repetition and temporal validity; the loser is superseded and kept with a bidirectional contradicts link. Consolidation dedupes, derives semantic facts from repeated episodics and weakens low-evidence inferences. A forgetting policy archives or deletes by composite strength under a max-active cap.
Safety layer
Every memory carries tenant, source-trust, content-trust and verification fields. A trust policy classifies content at ingestion and quarantines suspicious input; a promotion policy never auto-promotes inferred hypotheses into durable facts.
Storage
A MemoryStore interface with in-memory, SQLite and Postgres backends. The relational store is authoritative; vector, graph and temporal indexes are derived from it.
05

Implementation

  • Runtime package brainos_runtime with a pure-standard-library core that runs offline with no API keys; shipped on PyPI as brainos-cli 1.2.0 alongside the plugin-scaffold CLI and the brainos_eval suite.
  • Facade API: observe, recall, remember(subject=…), decide, why, trace, consolidate, forget and explain, plus temporal queries such as current() and as_of().
  • Two CLIs: plugin scaffolding (list, init, add, info) and runtime tooling (doctor, memory search / inspect, explain, trace, eval, benchmark).
  • Adapters for vanilla Python, LangGraph and MCP.
  • Feature flags for security, temporal supersession, stale exclusion, consolidation and forgetting so each mechanism can be ablated independently.
  • CI on Python 3.10–3.12 with ruff and pytest; the README reports 316 tests across plugin and runtime suites.
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"] brain.decide("what is the on-call rotation?")# -> "ask"   (nothing known, so the policy asks instead of guessing) print(brain.trace(formatted=True))
From the README — observe, recall, decide, and ask the runtime to explain itself.
06

Key technical decisions

  1. 01

    Supersede, never overwrite

    Conflicting memories are marked superseded and retained with provenance, so as_of() and state_of() can answer what was believed at any point in time.

  2. 02

    The relational store is the source of truth

    Vector, graph and temporal indexes are rebuilt from the canonical store — not the other way round — so a corrupted or swapped index never loses data.

  3. 03

    Small kernel, optional modules

    No brain-inspired module is mandatory. Generated plugins load when present and fall back to inline equivalents otherwise, so BrainOS() always runs.

  4. 04

    Evidence-graded neuroscience

    Each mapping is split into four layers — established neuroscience, computational abstraction, BrainOS hypothesis and implementation choice — generated from a single mappings module so the documentation cannot drift from the code.

  5. 05

    Recall is not an observation

    Querying memory is traced but never stored, so asking questions does not pollute long-term memory.

07

Evaluation & results

Prompt tokens, 50-turn simulated conversation
424,361 → 79,381
Naive full history versus full BrainOS stack, counted with tiktoken (cl100k_base); an 81% reduction, with peak prompt size falling from 16,540 to 3,114 tokens.
Ablation ladder
baseline → +temporal → +stale exclusion → +security → +consolidation → full stack
Each rung is measured for stale suppression, injection blocking, absence of hallucinated facts and active-memory count after consolidation.
Evaluation suite
Recall@K · Precision@K · MRR · temporal accuracy · contradiction resolution · provenance
Compared against full-history and lexical-RAG baselines.
Long-run validation
3 workloads
Coding agent, personal assistant and research agent, checked for bounded growth, stable salient recall, stale suppression, contradiction resolution, p95 latency and quarantined injections.

Figures are the author's own measurements published in the repository. The token benchmark runs on a simulated conversation and the RAG baseline is lexical-only.

08

Challenges

  • Redundancy-aware retrieval is quadratic in the number of candidates; it only scales because a single linear scoring pass shortlists candidates first.
  • Consolidation order matters. Stable facts have to be derived before near-duplicates are merged, otherwise repeated episodics disappear before they can be abstracted.
  • Inferred memories must remain beliefs. A tempting mapping shortcut would have let infer() mint durable semantic facts, violating the no-auto-promote rule.
  • Periodic consolidation legitimately spikes a single cycle, so long-run latency is judged at p95 rather than at the maximum.
09

Limitations

  • Default retrieval is lexical (token Jaccard) unless embeddings are supplied; salience and incubation are keyword and temporal heuristics.
  • The token benchmark measures the inline implementations on a simulated conversation, and the RAG baseline does not use embeddings.
  • The runtime is versioned 2.0.0-alpha; the CLI's memory, explain and trace commands run against a seeded in-process demo brain rather than persisted state.
  • Python 3.13 is untested in CI.
10

What I learned

  • Integration and validation move a memory system forward more than adding conceptual modules.
  • Provenance and lifecycle are what make memory debuggable — why() and trace() only work because every memory remembers where it came from.
  • Separating what neuroscience establishes from what the runtime hypothesises keeps biological inspiration honest.