SecondBrain — Reference Implementation
Evidence-based mapping from ContextOS primitives to the open-source SecondBrain runtime, including known conformance gaps.
This page maps a dated SecondBrain source snapshot to ContextOS patterns: governed tools, durable sessions, promotion-aware memory, bounded improvement, and a Memory API exposed through HTTP and MCP. It is implementation research input, not proof that every current ContextOS schema, exact profile or conformance case is implemented end-to-end.
Start at Foundations to read the spec, and use this source map to investigate a concrete implementation. Before running the historical quickstart, review the pinned project’s own setup, trust-domain, credential and data requirements.
| Website | sb.chat |
| Repo | github.com/contextosai/SecondBrain-collab |
| License | MIT |
| Primary language | Python (with a Swift Mac shell and a Vite/React operator UI) |
| Posture | Local-first; one-command Docker quickstart |
| Surfaces | sb 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 pinned quality scorecard reports synthetic nDCG@10/MRR of 0.94 on 30 golden queries using hash-mode embeddings. Its 25-query dogfood test uses a simplified token-overlap retriever, generous substring relevance and a bounded ripgrep baseline; it reports recall 0.92 versus 0.44 and precision 0.33 versus 0.10. These source-reported measurements were not rerun here and do not establish live production retrieval or causal self-improvement. Per-layer contribution counters support inspection but need controlled comparisons to attribute outcome improvement.
ContextOS primitive → SecondBrain module
The mapping below preserves the original 2026-09-03 navigation review at the pinned commit. A source path or similarly named receipt is not a schema validator, observed enforcement test or current deployment attestation.
Intelligence plane
| ContextOS primitive | SecondBrain location |
|---|---|
| Memory Model — promotion-aware tiers (working / episodic / semantic / durable) with review queue and contradiction handling | brain/memory/ — working, episodic, long-term separation; sleep-time synthesis writes to a review queue, not directly |
| Knowledge Graph — evidence-bound graph with GraphRAG retrieval | brain/retrieval/ — hybrid retrieval; promoted-knowledge-first |
| Ontology — versioned, governed canonical schema | ontology/ + contracts/ |
| Identity Layer — CEIDs, SIDs, agent workload identity | per-workspace tokens behind SB_MULTI_TENANT=1; historical design at docs/archive/planning/multi_tenancy_design.md |
Context plane
| ContextOS primitive | SecondBrain location |
|---|---|
Context Pack — eight-stage compilation into a CompiledContext | brain/context_packs/ |
CompiledContext — bounded per-request state | sb context explain <run_id> and sb context doctor produce the per-run view |
| Agentic Context Engineering — bucket scoring, provenance, dynamic injection | brain/context/ + retrieval rank hints from sb context doctor --write-rank-hints |
Decision plane
| ContextOS primitive | SecondBrain location |
|---|---|
| Cognitive loop - perception -> attention -> identity -> goals -> judgment -> policy gate -> action -> consolidation -> reflection | brain/antahkarana/ — chitta, manas, buddhi, viveka, atman, ahamkara modules |
| Orchestration — bounded Planner / Executor / Critic + durable background sessions | brain/agent_runtime/ + brain/background_sessions/ |
RunContext, RunBudget, RunTrace | brain/agent_harness/contracts.py — task runs, context budgets, permission decisions, checkpoints, verification plans, run traces |
DecisionRecord — typed per-turn record | AgentRunTrace 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 primitive | SecondBrain location |
|---|---|
| Tool Gateway — only path to external effect | brain/orchestrator/action_gateway.py |
ApprovalMode v1 compatibility | brain/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 / custom | brain/adapters/ + brain/a2a/ |
| Skills | brain/skills/ — discovery, loader, registry, router, runtime |
Trust plane
| ContextOS primitive | SecondBrain location |
|---|---|
| Governance — policy outside agent code, JsonLogic-style bundles, guardrails | brain/policies/ — engine.py, bundles.py, guardrails.py, injection.py, command_safety.py, obligations.py |
| Approval gates | brain/orchestrator/approvals.py + durable approval pauses in background sessions |
| Evaluation and Observability — evaluators on Policy / Utility / Latency / Safety / Economics, OTEL traces, replay | brain/evals/ (graders, goldens, dogfood, replay) + brain/eval/; quality scorecard at docs/reference/quality.md |
| Improvement Loop — Insight Synthesizer, Strategy Compiler, Feedback Store, Autotune | brain/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 / reversal | file 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
Some surfaces extend the spec. Treat these as reported implementation patterns to evaluate before any versioned promotion into ContextOS:
- 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 atGET /v1/cognitive/upliftso the contribution is auditable. - Memory API v1 with citation envelopes. Every response carries a
Citationenvelope (chunk_hash,source_path,anchor,text_span,score,retrieved_at). 13 HTTP routes + 13 MCP tools with named parity. Contract atcontracts/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. The snapshot documents
sb tasks workspace statusand a dry-run-firstsb tasks workspace promotepath. File/worktree restoration does not prove external-effect compensation, current approval binding or fenced resume under ContextOS’s new execution attachments.
Quickstart
git clone https://github.com/contextosai/SecondBrain-collab.git
cd SecondBrain-collab
git checkout --detach acec9678c05e80e859802a4e4e18f187e35d66b5
make quickstart-dockerThe historical setup expects the Memory API at http://localhost:8765/v1/; this review did not start it. Once your verified local deployment 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/recallInspect 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 doctorWhere to read next
- In SecondBrain:
AGENTS.md— the primary navigation file for any agent operating in the repo.docs/index.md— full doc routing table.docs/harness/overview.md— SecondBrain’s harness architecture in its own words.docs/explanation/agent-harness-claude-code-learnings.md— what the project learned closing harness gaps inspired by Claude Code’s permission model.docs/reference/quality.md— the published quality scorecard, including the dogfood-vs-grep numbers.brain/autotune/OPERATING.md— running the autotune loop in practice.
- In ContextOS:
- Harness Engineering — the discipline SecondBrain implements.
- Improvement Loop — the spec’s view of the autotune-style outer loop.
- Reviewer Agents — the taxonomy SecondBrain’s
agent_profiles.yamlinstantiates.
Caveats
- SecondBrain is a reference implementation, not a deployment of ContextOS as a managed product. It is local-first by design.
- The historical source-map review did not establish complete native multidimensional
ActionRisk, multi-region operational behavior or exact ContextOS schema conformance for every artifact. This is a limit of the evidence reviewed, not a conclusion that current source lacks those capabilities. Consult the pinned operating guidance and perform a new release-specific assessment. - Contributions that close spec-vs-implementation gaps land upstream in this docs site and downstream in SecondBrain in lockstep — following the “files to touch together” map in the specification’s maintainer notes.
The new Execution Contract requires a fresh crosswalk for exact profile/feature support, complete action/stored approval binding, current grant/ancestor revocation, observed sandbox/egress/data routes, owned operation/checkpoint/budget stores and verified useful/denied/fault cases. Those runtime controls are not evaluated by this page’s review. Do not infer they are present or absent from this historical module map. Apply the conformance assessment to the actual implementation/release/environment/workflow with independently verified current evidence.