Skip to content
Press / to search

SecondBrain — Reference Implementation

Evidence-based mapping from ContextOS primitives to the open-source SecondBrain runtime, including known conformance gaps.

ReferenceLast reviewed: Edit on GitHub
At a glance

SecondBrain is an open-source, local-first agent operating system that implements many ContextOS patterns in running code: governed tool execution, durable sessions, promotion-aware memory, bounded improvement, and a Memory API exposed through HTTP and MCP. It is a reference implementation and research input, not proof that every current ContextOS schema or conformance test is implemented end-to-end.

If you want to read the spec, start at Foundations. If you want to run the spec on your laptop and inspect every layer, start at SecondBrain.

Websitesb.chat
Repogithub.com/contextosai/SecondBrain-collab
LicenseMIT
Primary languagePython (with a Swift Mac shell and a Vite/React operator UI)
PostureLocal-first; one-command Docker quickstart
Surfacessb CLI, FastAPI Memory API, MCP server, A2A capability plane, brain.sdk

Why this matters for ContextOS

ContextOS is the portable specification. SecondBrain is one implementation-shaped source of evidence:

  • Many foundation primitives have inspectable code paths and tests.
  • Its contracts can be compared against ContextOS schemas to find alignment and gaps.
  • Its operational experience supplies evidence for which harness patterns work in practice; it does not automatically promote a SecondBrain-specific type into the normative ContextOS surface.

The Memory API ships a published quality scorecard (synthetic seed: nDCG@10 = 0.94, MRR = 0.94; dogfood: 2.1× better recall and 3.5× better precision than grep) and a GET /v1/cognitive/uplift route that exposes per-layer contribution counters. The self-improvement claim is auditable, not marketing.

ContextOS primitive → SecondBrain module

The mapping below is a navigation table from spec to source. Every right-hand path is a real directory or file in the repo as of main.

Intelligence plane

ContextOS primitiveSecondBrain location
Memory Model — promotion-aware tiers (working / episodic / semantic / durable) with review queue and contradiction handlingbrain/memory/ — working, episodic, long-term separation; sleep-time synthesis writes to a review queue, not directly
Knowledge Graph — evidence-bound graph with GraphRAG retrievalbrain/retrieval/ — hybrid retrieval; promoted-knowledge-first
Ontology — versioned, governed canonical schemaontology/ + contracts/
Identity Layer — CEIDs, SIDs, agent workload identityper-workspace tokens behind SB_MULTI_TENANT=1; historical design at docs/archive/planning/multi_tenancy_design.md

Context plane

ContextOS primitiveSecondBrain location
Context Pack — eight-stage compilation into a CompiledContextbrain/context_packs/
CompiledContext — bounded per-request statesb context explain <run_id> and sb context doctor produce the per-run view
Agentic Context Engineering — bucket scoring, provenance, dynamic injectionbrain/context/ + retrieval rank hints from sb context doctor --write-rank-hints

Decision plane

ContextOS primitiveSecondBrain location
Cognitive loop - perception -> attention -> identity -> goals -> judgment -> policy gate -> action -> consolidation -> reflectionbrain/antahkarana/chitta, manas, buddhi, viveka, atman, ahamkara modules
Orchestration — bounded Planner / Executor / Critic + durable background sessionsbrain/agent_runtime/ + brain/background_sessions/
RunContext, RunBudget, RunTracebrain/agent_harness/contracts.py — task runs, context budgets, permission decisions, checkpoints, verification plans, run traces
DecisionRecord — typed per-turn recordAgentRunTrace receipts in brain/agent_harness/turn_traces.py; persisted by trace_store.py; inspect via sb traces list / sb traces show <id>

Action plane

ContextOS primitiveSecondBrain location
Tool Gateway — only path to external effectbrain/orchestrator/action_gateway.py
ApprovalMode v1 compatibilitybrain/policies/approval_mode.py plus local aliases. This is implementation evidence for the compatibility projection, not evidence that native multidimensional ActionRisk is complete.
Adapter mesh — MCP / A2A / OpenAPI / custombrain/adapters/ + brain/a2a/
Skillsbrain/skills/ — discovery, loader, registry, router, runtime

Trust plane

ContextOS primitiveSecondBrain location
Governance — policy outside agent code, JsonLogic-style bundles, guardrailsbrain/policies/engine.py, bundles.py, guardrails.py, injection.py, command_safety.py, obligations.py
Approval gatesbrain/orchestrator/approvals.py + durable approval pauses in background sessions
Evaluation and Observability — evaluators on Policy / Utility / Latency / Safety / Economics, OTEL traces, replaybrain/evals/ (graders, goldens, dogfood, replay) + brain/eval/; quality scorecard at docs/reference/quality.md
Improvement Loop — Insight Synthesizer, Strategy Compiler, Feedback Store, Autotunebrain/autotune/ — lanes, evaluators, promotion gate, ensemble acceptance, mutation safety; see OPERATING.md
Reviewer Agents — security / architecture / data / etc.contracts/registry/agent_profiles.yaml — ships security-reviewer, repo-scanner, memory-curator profiles
Durable rollback / reversalfile checkpoint create/list/diff/rewind via sb checkpoint / sb rewind; auto pre-mutation checkpoints on chat code writes, gateway write_file, vault writes
AGENTS.md — primary navigation for agents/AGENTS.md

What SecondBrain adds on top of the spec

SecondBrain is a reference, not a clone — some surfaces extend the spec rather than just implementing it. Treat these as proven patterns ContextOS may absorb upstream:

  • Antahkarana cognitive stack. A named decomposition of the cognitive loop: chitta (synthesis), manas (predictive context), buddhi (judgment), viveka (quality gate), atman (identity), ahamkara (self-model). Each layer exposes a counter at GET /v1/cognitive/uplift so the contribution is auditable.
  • Memory API v1 with citation envelopes. Every response carries a Citation envelope (chunk_hash, source_path, anchor, text_span, score, retrieved_at). 13 HTTP routes + 13 MCP tools with named parity. Contract at contracts/memory_api_v1.yaml.
  • Citation density gate. Grounded answers refuse thin-evidence responses by default — a concrete enforcement of the Trust plane’s evidence-coverage requirement.
  • Autotune as constrained optimization. Lane specs declare mutable files, evaluators, benchmark packs, and acceptance rules. Promotion gates block unsafe promotion when baselines are missing, smoke evidence failed, or judge agreement is insufficient. This is the Improvement Loop’s “harness as a search target” framing in working code.
  • Durable workspaces and checkpoints. sb tasks workspace status audits worktree health; sb tasks workspace promote is a dry-run-first, --apply --yes-guarded fast-forward path. Compensates ContextOS’s specified-but-not-shipped rollback contract with a real implementation.

Quickstart

git clone https://github.com/contextosai/SecondBrain-collab.git
cd SecondBrain-collab
make quickstart-docker

The Memory API comes up live at http://localhost:8765/v1/. Once it is running:

eval "$(uv run sb serve-token env)"
curl -H "Authorization: Bearer ${SB_SERVE_TOKEN}" \
     -H "Content-Type: application/json" \
     -d '{"query":"migration plan","top_k":5}' \
     http://localhost:8765/v1/memory/recall

Inspect a run’s DecisionRecord-equivalent receipt:

sb traces list
sb traces show <trace_id>

Inspect what a context pack is putting in front of the model:

sb context explain <run_id>
sb context doctor

Caveats

  • SecondBrain is a reference implementation, not a deployment of ContextOS as a managed product. It is local-first by design.
  • Some primitives in the spec are richer than what is yet shipped or evidenced in SecondBrain, notably native multidimensional ActionRisk, the full multi-region deployment blueprint, and exact ContextOS schema conformance for every runtime artifact. The repo’s operating guidance is in brain/autotune/OPERATING.md and its harness docs.
  • Contributions that close spec-vs-implementation gaps land upstream in this docs site and downstream in SecondBrain in lockstep — see the “files to touch together” map in this repo’s CLAUDE.md.