braindrain
This server does not currently have a deployable release on Glama. Follow the repository's setup instructions to install and configure it for your MCP client, including any required credentials and local dependencies.
braindrain
Version: V1.0.3
Last Updated: 2026-06-11
An MCP server that keeps AI agents lean. It stops context windows bloating with redundant tool definitions, large raw outputs, and repeated environment discovery — and gives agents the right information at the right time instead.
Built on FastMCP. Works with Cursor, Zed, Windsurf, OpenCode, Antigravity, Codex, and any MCP-compatible client.
The problem it solves
Every AI session starts with the same waste:
The agent loads tool definitions it will never use — each one costs tokens before a single line of code is written
Large tool outputs get dumped raw into context — a 10,000-token blob when you needed 200 words
The agent probes the environment from scratch —
which python3,uname,ls ~/.config— questions it has asked a hundred times before
braindrain eliminates all three.
Related MCP server: SuperBased Observer
How it works
braindrain runs as a local MCP server alongside your AI client. It exposes a small set of always-loaded (HOT) tools and a larger set of deferred tools that are only described to the agent when it searches for them. The agent stays lean by default and pulls in capability on demand.
Large outputs are routed through a local FTS5 index (context-mode) instead of being dumped into the context window. The agent gets a handle and a set of suggested queries — it retrieves only the relevant chunks.
OS environment data is probed once, cached locally, and served instantly on every subsequent call. The agent never has to discover Python versions, IDE configs, or running services again.
Tools
Environment
Tool | When to use |
| Call this first in any session. Returns a cached snapshot of the machine: Python interpreters, package managers, installed IDEs and their MCP configs, running LLM servers, browsers, VM tools, GUI tools, CLI tools, and agent behaviour hints. Zero cost after the first probe. |
| After installing new tools, switching machines, or any time the cached data feels stale. Re-runs the full probe (~5s) and updates the cache. |
Tool discovery
Tool | When to use |
| Before loading any external MCP tool. Searches the configured tool registry by capability. Returns lightweight references — not full definitions. Prevents loading 26K-token tool schemas unnecessarily. |
| Lists all configured tools and whether they are HOT (always loaded) or deferred (loaded on demand). |
| Writes |
Output routing
Tool | When to use |
| When a tool returns a large blob. Indexes it into a local FTS5 store and returns a handle + suggested queries. The raw text never enters the context window. |
| Retrieve relevant chunks from a previously routed output. Uses context-mode FTS5 — no embedding API required. Optional |
Search, embeddings, and rerank (P2)
No Mixedbread or cloud API is required for normal search:
Path | Engine | API keys |
| context-mode | None |
| BM25 over | None |
Optional rerank on | Off by default ( | Only if you enable cloud or |
Optional rerank (config/hub_config.yaml → modules.tool_gate):
| Behavior |
| No rerank pass |
| Offline token overlap — no network |
| Cloud |
| Mixedbread when key is set, else |
Enable only after benchmarking: set rerank_on_search: true and choose a provider. Per-call override: search_index(query, rerank=True).
Embeddings (embeddings in hub_config.yaml) are for future semantic workflows — not used by default search_index. Local-first providers (priority order):
Provider | Kind | Endpoint |
|
|
|
|
|
|
Cloud fallbacks |
| Google AI Studio, Hugging Face, Mixedbread |
Set embeddings.default_provider (default: lmstudio_local). Programmatic helper: braindrain.embeddings_client.embed_texts().
Token-efficient workflows (also in hub_config.yaml):
ingest_codebase— runsai_distillerfirst only when repo file count exceedsoptions.distiller_when_file_count_gt(default 200).refactor_prep_token_light—filescope+text_editorbeforerepo_mapper/jcodemunchwhentoken_budget< 2000.
Benchmark harness (machine-local report under .braindrain/plan-reports/):
# Tracked CLI (also mirrored in .scriptlib/ when scriptlib is enabled)
python3 scripts/benchmark_token_savings_brain_mcp_hub_v1.py --repo-root . --fail-on-regression
# Pytest marker (used by nightly token-benchmark workflow)
uv run pytest -m token_benchmarkReplays deterministic fixtures in tests/fixtures/token_benchmark/ through hub-on paths (route_output, search_tools, cached get_env_context, session compaction) vs a hub-off naive full-context baseline. Metrics align with braindrain/telemetry.py (estimated_raw_tokens / actual_context_tokens / saved_tokens). Minimum savings floor defaults to 25% (TOKEN_BENCHMARK_MIN_SAVINGS_PCT). Nightly CI uploads the markdown report as a workflow artifact (not committed).
Workflows
Tool | When to use |
| See what multi-step workflows are available. |
| Prime a project for AI agent use. Parameters include |
| Initialize project memory artifacts only ( |
| Hard-opt-in project or global scriptlib. Project enable can immediately harvest reusable workspace scripts into |
| Recursively copy script-like files from the workspace into the local project scriptlib catalog, honoring ignore rules. |
| Search local and shared scriptlib entries before writing a new reusable helper script. Returns a `reuse |
| Inspect metadata, scope, score, run mode, provenance, and pin/update status for one scriptlib entry. |
| Execute a script through scriptlib with restored source context when paths are sensitive. |
| Fork an existing scriptlib entry into a new version for safe edits. |
| Promote a validated project-local script into the shared personal scriptlib catalog. Requires approval. |
| List pinned shared script artifacts with available updates for the current workspace. |
| Pin or upgrade a shared script artifact for the current workspace. Requires approval. |
| Refresh indexes, surface duplicates/promotions/updates, and optionally persist new ignore dirs. |
| Summarize project/shared roots, shared pins, promotion candidates, and update state. |
| Update success score, mistakes, and validation state. |
| Rebuild project/global scriptlib indexes and generated catalogs. |
| Generate a markdown execution plan and review it before committing to a run. Use before any destructive or long-running workflow. |
| Execute a workflow. Intermediate output is routed through the sandbox — only the final summary returns to the agent. |
list_workflows() includes init_project_memory and prime_cursor_orchestration (calls prime_workspace with bundle=cursor-orchestration — deploys agents, hooks, skills, scripts/daily_plan_audit.py, and scripts/plan_build_guard.py). Consumer slash commands (from config/templates/cursor/commands/, installed by prime_workspace into .cursor/commands/):
Command | When to use |
| Onboard or refresh Cursor orchestration (rules, hooks, skills, auditor scripts). |
| End of chat — finalize L1 session compaction, token checkpoint, optional L2 wiki-brain promotion, L3 dream guidance, and reminders to update |
| Manual planning close-out ( |
| Split a |
Plan Build: run python3 scripts/plan_build_guard.py --plan <path> before edits (see Ruler RULES.md). Meta plans are blocked (meta_plan_no_build) — close out with /metaplan-closeout first.
Telemetry
Tool | When to use |
| Quick snapshot of estimated tokens saved vs raw in this session. |
| Full breakdown: per-tool savings, cache hits, cost avoided. |
| Append schema |
Async MCP tools record observer tool_call rows via asyncio.to_thread so SQLite writes do not block the event loop.
MCP Apps (inline dashboards)
Cursor and other MCP App hosts can render interactive ui:// HTML from braindrain without loading a separate frontend stack.
Tool | When to use |
| Inline token savings snapshot (JSON via |
| Interactive plan task board from |
| Operational topology graph (session, tools, hooks, plans, external MCP peers). |
| App-only — refresh board and all plan-board write actions from the iframe (audit, sync, archive, disposition, masterplan). |
| App-only — refresh SIGINT map graph from the iframe (8s auto-poll). |
Plan board UI: filters, per-plan disposition dropdown, Recheck/Apply sync, archive/cancel, timestamp tags, and open-in-editor flow. Full reference: braindrain/mcp_apps/PLAN_BOARD_UI.md.
SIGINT map UI: SVG force graph of active-session ops intelligence from observer events + project config. Full reference: braindrain/mcp_apps/SIGINT_MAP_UI.md.
Restart the braindrain MCP server after braindrain/mcp_apps/ or registration changes.
Token Checkpoint Protocol
Use this cadence for consistent token observability:
Trigger | Required | Call |
Task start | Yes |
|
Before high-cost operation | Yes |
|
After high-cost operation | Yes |
|
Milestone or phase close | Yes |
|
Task end | Yes |
|
Trivial/no-op action | Optional skip | none |
High-cost operations include broad searches, large-output reads, subagent batches, and long-running commands.
For large outputs, always use:
route_output() -> search_index()
Bad vs good large-output handling:
Bad: paste a long tool dump directly into chat and then ask for analysis.
Good: call
route_output()on the dump, then query targeted chunks withsearch_index().
Token Metrics Contract (schema 1.0)
Use <workspace>/.braindrain/token-metrics.jsonl as an optional machine-local checkpoint stream for checkpoint records (pass workspace root via record_token_checkpoint(..., path=".") or export_mcp_catalog(path=".")). Required fields per line:
schema_version(1.0)timestamp(ISO-8601 UTC)taskphase(start|pre_high_cost|post_high_cost|milestone_close|end)tool(get_token_dashboard|get_token_stats)totals.estimated_raw_tokenstotals.actual_context_tokenstotals.saved_tokenscontext_tags(string array)note
Example line:
{"schema_version":"1.0","timestamp":"2026-04-06T12:00:00Z","task":"token-stats-rule-system","phase":"post_high_cost","tool":"get_token_dashboard","totals":{"estimated_raw_tokens":6400,"actual_context_tokens":2100,"saved_tokens":4300},"context_tags":["docs","search"],"note":"Captured after cross-file wording audit."}
Validation gates:
PASS only if checkpoint cadence is consistent across
RULES.md,AGENTS.md.template, and.cursor/rules/agent-system.mdc.PASS only if
route_output() -> search_index()appears as the large-output path.FAIL if
schema_versionis omitted in JSONL examples.FAIL if
.braindrain/token-metrics.jsonlis treated as runtime telemetry source-of-truth.
Utility
Tool | When to use |
| Health check — confirms the server is running and responding. |
Installation
Quickstart (one command)
git clone https://github.com/recwebtek/braindrain.git
cd braindrain
./install.shinstall.sh now does a full guided setup:
Validates Python 3.11-3.14 (fails fast on unsupported runtimes like 3.15+)
Creates
.env.devearly (before dependency steps) so env setup never gets skippedInstalls full dependencies with visible progress, retries, and install logging to
.braindrain/install-logs/Default install is torch-free (
pyproject.tomlis canonical); optional in-process embeddings viapip install -e ".[embeddings]"Runs fresh
get_env_context()probe and regeneratesAGENTS.mdCreates
.braindrain/(gitignored, machine-local — never committed)Runs an interactive MCP target checklist (Cursor, Windsurf, Zed, OpenCode, Antigravity, Codex, etc.), previews diffs, creates backups, then applies on confirmation
Runs
ruler apply --local-only --no-gitignore --agents cursor,codex(project-scoped;.gitignorepolicy is not owned by Ruler — useprime_workspacefor the BRAINDRAIN block)Performs MCP handshake self-test and prints a structured final status summary + next steps
Manual setup (if you prefer)
With uv (recommended for contributors — lockfile-backed):
uv sync --group dev
uv run pytestClassic pip (still supported):
python3 -m venv .venv
. .venv/bin/activate
pip install -e .
# optional in-process embeddings (pulls torch):
pip install -e ".[embeddings]"requirements.txt is a thin compat shim (-e .) pointing at pyproject.toml.
Contributing (lint + hooks)
uv sync --group dev
uv run ruff check
uv run ruff format --check
uv run pytest -m "not local_only"
pre-commit install # once per clone
pre-commit run --all-filesCI runs the same checks on Python 3.11 / 3.12 / 3.14 across Ubuntu and macOS. Tests marked local_only (machine-local services, launchd, LM Studio, etc.) are skipped in CI. The token benchmark suite (pytest -m token_benchmark) runs on a separate nightly schedule via .github/workflows/token-benchmark.yml.
MCP tool schema snapshot (tests/test_mcp_tool_schemas.py): CI fails if native tool definitions drift from tests/fixtures/mcp_tool_schemas_snapshot.json. After you intentionally change @mcp.tool() signatures, descriptions, or outputSchema, regenerate and commit the fixture:
uv run python scripts/regenerate_mcp_tool_schemas_snapshot.py
uv run pytest tests/test_mcp_tool_schemas.py -qInstaller options
PYTHON=python3.14 ./install.sh # force interpreter
SKIP_TEST=1 ./install.sh # skip MCP initialize handshakeInstall logs are written to .braindrain/install-logs/install-<timestamp>.log.
Requirements
Python 3.11–3.14
Node.js (for
context-modeoutput routing)An MCP-compatible AI client
Arch / Linux dev machines
On Arch/rolling-release distros where python3 often points at Python 3.14:
The installer supports Python 3.11–3.14 and prefers
python3.14when available.Make sure system
python/python3andpipare installed via your package manager (e.g.pacman -S python python-pip).For first-time runs, a simple:
git clone https://github.com/recwebtek/braindrain.git
cd braindrain
./install.shis expected to succeed; if it doesn’t, capture the full log from .braindrain/install-logs/ and append a new section to QA-Logs/bdqadebug.md (debug log) before iterating.
IDE / Agent configuration
Replace /path/to/braindrain with the absolute path to your clone. install.sh prints this for you.
Important: Always point your IDE config at
config/braindraindirectly — not atpython3. If pyenv or system Python resolves to a different version than your venv (a common trap on macOS), the server crashes silently before producing any output.
Cursor
.cursor/mcp.json (project) or **~/.cursor/mcp.json** (global) via Settings › Features › MCP:
{
"mcpServers": {
"braindrain": {
"command": "/path/to/braindrain/config/braindrain",
"args": [],
"env": {},
"serverName": "braindrain"
}
}
}If the MCP log shows **[MCP Allowlist] No serverName provided for adapter**, either add **"serverName": "braindrain"** on that server object in **~/.cursor/mcp.json**, or run **prime_workspace(..., patch_user_cursor_mcp=true)** once so braindrain patches the global file. install.sh / configure_mcp.py and project-level prime_workspace set this for generated configs; UI-created entries may omit it.
Remote transport (non-stdio)
braindrain now uses FastMCP
streamable-httpfor remote mode withstateless_http=true.Legacy SSE remote transport has been removed.
MCP protocol headers (including
MCP-Protocol-Version) are validated by FastMCP's Streamable HTTP transport stack.
Large prime_workspace results: the MCP tool defaults to **compact_mcp_response=true** (smaller JSON) to avoid ClosedResourceError / connection closed while returning the tool result. Set **compact_mcp_response=false** only if you need the full templates.deployed map and untruncated Ruler logs.
Multi-agent loop (Cursor)
This repo includes a 4-tier multi-agent system under .cursor/. Run:
/intake(once per project) to generateproject-context.json/architectto generatePRD.md,TASK-GRAPH.md, andCOORDINATOR-BRIEF.md/coordinateto execute stages (Tier 3coordinatorusescomposer-2)
Windsurf
~/.codeium/windsurf/mcp_config.json:
{
"mcpServers": {
"braindrain": {
"command": "/path/to/braindrain/config/braindrain",
"args": [],
"env": {}
}
}
}Zed
~/.config/zed/settings.json — use the context_servers key (not mcp_servers):
{
"context_servers": {
"braindrain": {
"command": "/path/to/braindrain/config/braindrain",
"args": [],
"env": {}
}
}
}After saving, reload via the command palette: **agent: reload context servers**. braindrain will appear in the Agent panel's MCP section.
OpenCode
~/.config/opencode/opencode.jsonc:
{
"mcp": {
"braindrain": {
"type": "local",
"command": ["/path/to/braindrain/config/braindrain"]
}
}
}Antigravity
~/.gemini/antigravity/mcp_config.json:
{
"mcpServers": {
"braindrain": {
"command": "/path/to/braindrain/config/braindrain",
"args": [],
"env": {},
"disabledTools": []
}
}
}Claude Desktop / Codex and others
Any client that uses the standard mcpServers format:
{
"mcpServers": {
"braindrain": {
"command": "/path/to/braindrain/config/braindrain",
"args": [],
"env": {}
}
}
}New device setup
git clone https://github.com/recwebtek/braindrain.git
cd braindrain
./install.shEach device runs its own environment probe and gets its own env_context — correct Python paths, correct IDE config locations, correct installed tools for that machine. No shared state between devices.
Updating
Repo-clone installs can check and apply updates without hosting braindrain online:
# Check only (exit 10 when updates are available)
./scripts/update_braindrain.sh check
# Fast-forward pull when the clone is clean (ff-only)
./scripts/update_braindrain.sh applyFrom an agent session you can also call check_hub_update() (notify-only fetch) or apply_hub_update() (pull + dependency sync). After apply, reconnect or restart the braindrain MCP connection in your IDE so the host loads new code and tool schemas.
The launcher (config/braindrain) runs a throttled background check at most once per 24h and prints a stderr nudge when .braindrain/update-state.json shows commits behind origin/main. Automatic paths never pull without an explicit apply.
Manual fallback:
cd braindrain && git pull --ff-only && (command -v uv >/dev/null && uv sync || .venv/bin/pip install -r requirements.txt)Configuration
Main config: config/hub_config.yaml
Startup validation (Pydantic v2) — braindrain/config_schema.py validates the YAML at server load via braindrain/config.py:
Invalid types or missing required fields (e.g.
mcp_tools[].name) fail fast with dotted field paths.Unknown top-level keys log a warning and are ignored (forward-compat).
The legacy
livingdash:block is not validated; if present it is ignored (superseded by MCP Apps dashboard work).Restart the braindrain MCP server after config or schema changes.
Memory stack (L0–L3) — explicit sections in hub_config.yaml (defaults match server fallbacks):
observer— episodic tool-call ring buffer (~/.braindrain/events.db)sessions— session store + inactivity compaction (~/.braindrain/sessions.db)wiki_brain— durable recall/forgetting weights (~/.braindrain/wiki-brain/brain.db)lessons/memory_learning— promotion guardrails for facts and playbooksdreaming— consolidation policy (quiet_minutes, scan limits,storage.base_dir,weights,triggers.macos_host_idle)provider_context— strategy for vendor-native vs Braindrain durable memory (provider-native-first)
Restart the braindrain MCP server after changing these blocks. Machine-local ops detail: .braindrain/OPS.md (memory stack table).
Host-idle dream (macOS, manual opt-in)
Two-step enablement (config alone does not install or start a watcher):
Install watcher for this workspace (once per repo):
./scripts/install_dream_watch_launchd.shEnable in this workspace config:
dreaming.triggers.macos_host_idle.enabled: trueinconfig/hub_config.yaml
The watcher polls HID keyboard/mouse idle time (IOHIDSystem). When idle exceeds idle_threshold_seconds, it runs consolidation using mode (default full). Shared memory DBs stay under ~/.braindrain/; per-workspace state lives under ~/.braindrain/dreaming/workspaces/<workspace_hash>/.
Knob | Default | Purpose |
| 300 | Host idle before dream is considered |
| 120 | launchd poll interval (install script reads this) |
| 60 | Minimum gap between host-idle dream runs |
| true | When true, host idle can dream even if a Cursor session was active recently |
| full | Dream mode passed to |
Manual one-shot (no launchd): ./scripts/macos_dream_watch.sh
Legacy cron path still works: scripts/run_dream_cron.sh
Environment variables (copy .env.example to .env.dev to start):
Variable | Purpose |
| Override config file path |
| Absolute path to the |
| Enables the deferred GitHub MCP tool |
| LM Studio OpenAI-compatible API (default: |
| Embedding model name for LM Studio (see |
| Ollama API base (default: |
| Ollama embed model (default: |
| Optional — cloud rerank/embeddings only when explicitly enabled in config |
| Optional — cloud embeddings / semantic search |
| Set to |
The server auto-loads .env.dev → .env.prod → .env (first found, non-overriding of existing env vars).
Model provenance toggles
config/hub_config.yaml now includes a provenance block used by planning/report tooling:
provenance.chat_footer.enabledandprovenance.chat_footer.scope(all_agents,planning_only,off)provenance.plan_metadata.enabledprovenance.subagent_trace.enabledprovenance.subagent_trace.path(default:.braindrain/plan-reports/model-trace.jsonl)provenance.date_format(default:%Y-%m-%d)
The planning auditor writes model metadata into report frontmatter:
created_by_model, created_at, last_modified_by_model, last_modified_at, cursor_mode, and subagent_models_used.
To force explicit provenance values during audit runs:
python3 scripts/daily_plan_audit.py \
--repo-root . \
--report-date "$(date +%Y-%m-%d)" \
--model-name "Codex 5.3" \
--cursor-mode autoRepo structure
braindrain/
├── braindrain/
│ ├── server.py # FastMCP server entrypoint + tool registration
│ ├── tools/ # Tool-domain implementations (tokens, memory, workflows, etc.)
│ ├── primer/ # Workspace primer submodules (detect/deploy/apply/memory/prime)
│ ├── workspace_primer.py # compatibility exports for legacy primer imports
│ ├── env_probe.py # OS fingerprint probe, synthesis, and cache
│ ├── config.py # YAML config loader
│ ├── context_mode_client.py # context-mode stdio client (output routing)
│ ├── mcp_stdio_client.py # generic stdio MCP client (workflow engine)
│ ├── output_router.py # route large outputs → FTS5 index
│ ├── scriptlib.py # opt-in script library, harvesting, indexing, run wrapper
│ ├── telemetry.py # token telemetry + JSONL logging
│ ├── workflow_engine.py # multi-step workflow execution + sandbox
│ ├── tool_registry.py # BM25 search + defer_loading
│ ├── rerank.py # optional search_index rerank (lexical / mixedbread / auto)
│ ├── embeddings_client.py # local-first embeddings (LM Studio, Ollama, cloud)
│ ├── embeddings_router.py # provider priority + quota backoff
│ ├── mcp_apps/ # MCP Apps ui:// dashboards (token, plan board, SIGINT map)
│ ├── repo_stats.py # file-count gating for workflows
│ └── types.py
├── config/
│ ├── bundles/ # bundle manifests (`core`, `comms`, …) for prime_workspace
│ ├── templates/
│ │ ├── ruler/ # Ruler sources (RULES.md, ruler.toml) for prime_workspace
│ │ ├── agents/ # `.cursor/agents/*.md` subagent templates
│ │ └── cursor/ # Cursor hooks: `hooks.json`, `hooks/*.sh`
│ ├── hub_config.yaml # tools, workflows, model tiers, embeddings
│ ├── braindrain # launcher script (self-detecting, venv-pinned)
│ ├── opencode_mcp.jsonc # OpenCode reference config
│ ├── com.braindrain.mcp.plist # macOS launchd service template
│ └── com.braindrain.dream-watch.plist # macOS host-idle dream watcher template
├── AGENTS.md # agent protocol — generated per device by install.sh
├── AGENTS.md.template # template used to generate AGENTS.md
├── VERSION # semver for releases (kept in sync with this README)
├── CHANGELOG.md # release history
├── ROADMAP.md # public product direction (local scratch: `.devdocs/`, gitignored)
├── TODOS.md # public release-aligned checklist (never commit `.devdocs/`)
├── install.sh # new device setup script
├── requirements.txt
└── pyproject.tomlRule generation (AGENTS.md vs Ruler)
**AGENTS.md**: generated locally by./install.shfromAGENTS.md.template(and includes a machine-specific env block between<!-- ENV_CONTEXT_START -->/<!-- ENV_CONTEXT_END -->).Ruler-generated dotfiles:
./install.sh(and theprime_workspace()tool) deploysconfig/templates/ruler/→.ruler/and runsnpx @intellectronica/ruler applyto generate project-local agent rule files like.cursor/rules/braindrain.mdc,.mcp.json,CLAUDE.md,.agent/rules/ruler.md, etc.Source-of-truth for those generated rule files is
config/templates/ruler/RULES.md(and.ruler/ruler.toml).Important: files like
CLAUDE.mdare generated artifacts (gitignored) and should be treated as disposable. Edit the templates instead, then re-run Ruler.If a project already has older
.ruler/*files, callprime_workspace(..., sync_templates=true)to refresh those templates safely and propagate new guidance without manual cleanup.
Cursor slash commands: when Cursor is in scope,
prime_workspace()copiesconfig/templates/cursor/commands/*.md→.cursor/commands/(create-only by default;sync_templates=truerefreshes with backups). Shipped commands include/prime-braindrain,/brainlog, and/build-plan(see table under Workflows).Cursor hooks (not Ruler): when the resolved agent set includes Cursor,
prime_workspace()copiesconfig/templates/cursor/hooks.jsonandconfig/templates/cursor/hooks/*.shinto.cursor/(create-only by default;sync_templates=trueoverwrites with timestamped backups). Hook templates currently include:.cursor/hooks/on-stop-observe.sh(lightweight stop-event observation).cursor/hooks/on-stop-gitops.sh(TASK-GRAPH branch queueing).cursor/hooks/on-stop-daily-plan-audit.sh(daily-gated planning audit report).cursor/hooks/on-after-file-edit-plan-provenance.sh(stamps*.plan.mdfrontmatter with model provenance from hook payload).cursor/hooks/on-stop-plan-provenance.sh(refreshes.braindrain/active-model.jsonfor audit/report pickup)Hook output contract: stop-hook scripts should be silent unless they intentionally emit valid JSON. Plain text output can cause Cursor hook-response JSON parse failures. Edit templates under
config/templates/cursor/in this repo, then re-prime consumer projects to roll out hook changes.
Subagent templates: canonical source is
config/templates/agents/*.md.prime_workspace()copies that tree to:.cursor/agents/when Cursor is in the resolved agent set, and.codex/agents/when Codex is in the resolved agent set (same files; IDE-specific layout only). Skills deploy fromconfig/templates/cursor-skills/<id>/→.cursor/skills/<id>/for each id in the active bundleskills:list (e.g.cursor-orchestration: coordinator, gitops, scriptlib-librarian). Seedocs/skill-braindrain-hub-pr.md. Operational scripts (daily_plan_audit,plan_build_guard,plan_provenance_stamp,plan_branch_utils) copy from hubscripts/→ projectscripts/per bundleoperational_scripts. Re-prime upgrades them when the hub revision changes (content-hash marker), so plan branch/PR reconciliation reaches consumer workspaces without tracking*.plan.mdin git. Existing files are create-only by default; setsync_subagents=trueto update with backups..cursor/is gitignored at repo root; do not commit generated agent/skill files—edit templates and re-runprime_workspace.
Codex config merge:
prime_workspace()appends/updates a managedBRAINDRAIN SUBAGENTSblock in.codex/config.tomlonly when allowed by policy (sync_subagents=truefor existing files). Existing MCP server entries remain intact.Project memory artifacts: initialized by
prime_workspace()(orinit_project_memory()) and kept separate from generated protocol files:.braindrain/AGENT_MEMORY.md,.braindrain/OPS.md, and.braindrain/SESSION_PROGRESS.mdare create-only on prime/re-prime (existing content is preserved).cursor/hooks/state/continual-learning-index.jsonfor incremental transcript indexingprime now snapshots protected memory files into
.braindrain/rollback/<ts>/memory/and records metadata in.braindrain/primed.json(schema_version: 2.0) plus.braindrain/primed-history.jsonluse
list_prime_snapshots(path=".")andrestore_prime_snapshot(path=".", snapshot_id=None, restore_memory=true, restore_cursor=true)to recover from rollback snapshotsAGENTS.mdremains generator-owned protocol text and should not be used as memory storage
Scriptlib: disabled by default. When enabled for a workspace, braindrain seeds project-local
.scriptlib/, harvests reusable scripts recursively, and injects librarian-first guidance into generated agent rule surfaces for that workspace only.Shared personal scriptlib: promoted scripts can also live in
~/.braindrain/scriptlibas a curated machine-level catalog. Project-local harvest never auto-publishes into the shared catalog.Pins and updates: workspaces can pin approved shared artifacts and receive upgrade suggestions later without silent mutation.
Docs ownership map (token observability)
File/path | Ownership | Purpose |
| Source-of-truth template | Canonical protocol language and trigger matrix |
| Source template | Generated |
| Generated artifact | Do not edit directly |
| Cursor local enforcement | Immediate IDE-specific guardrails |
| Machine-local telemetry | Runtime token telemetry source-of-truth |
| Optional machine-local artifact | Local checkpoint stream using schema |
Memory layer status and roadmap
Roadmap and release TODOs ship from the repo root as **ROADMAP.md** and **TODOS.md**. Use **.devdocs/** only on your machine for private drafts (that path is gitignored and must not be committed).
Implemented now (runtime behavior in this repo):
L1 (session and episodic grounding):
ObserverStore(braindrain/observer.py) captures bounded event traces.SessionStore+EpisodeRecord(braindrain/session.py) track lifecycle, grounded evidence, and promotion-ready episode units.
L2 (durable memory store):
WikiBrain(braindrain/wiki_brain.py) stores semantic/procedural/lesson records with FTS recall, supersession, decay/forgetting, and metrics.
L3/L4 (dream consolidation and operational automation):
DreamEngine(braindrain/dream.py) runs Light/REM/Deep consolidation and writesConsolidationPlanartifacts plusDREAMS.md.MCP tools include
run_dream,get_dream_status, and related memory/episode/recall endpoints inbraindrain/server.py.Automation hooks and scheduler helpers are wired:
.cursor/hooks/on-stop-observe.sh.cursor/hooks/on-stop-gitops.sh.cursor/hooks/on-stop-daily-plan-audit.sh.cursor/hooks/on-after-file-edit-plan-provenance.sh.cursor/hooks/on-stop-plan-provenance.shscripts/run_dream_cron.shscripts/macos_dream_watch.sh+scripts/install_dream_watch_launchd.sh(macOS host-idle, opt-in)
Memory artifacts and paths:
Durable project memory path:
.braindrain/AGENT_MEMORY.md(machine-local, gitignored).Incremental transcript index path:
.cursor/hooks/state/continual-learning-index.json.Daily planning audit hook state path:
.cursor/hooks/state/daily-plan-audit.json.Daily planning audit reports path:
.braindrain/plan-reports/plan-audit-YYYY-MM-DD.md(full report, now plan-centric cards grouped by IDE -> disposition).braindrain/plan-reports/latest.md(latest mirror).braindrain/plan-reports/plan-task-board.md(active item board with Seq / Plan columns, sorted by_master.plan.mdexecution order then item status).braindrain/plan-reports/master-plan.md(generated master mirror + Implementation sequence build queue + drift detection + Branch and PR columns).braindrain/plan-reports/overlap-relations.md(plan-level overlap pairs and clusters snapshot).braindrain/plan-reports/next-actions.md(verb queue:MERGE,FIX,REPLAN,RESEARCH,IMPLEMENT,BACKLOG, READY_TO_ARCHIVE)
Planning overseer (/masterplan)
The daily auditor (scripts/daily_plan_audit.py, Cursor /masterplan) treats frontmatter todos as the status source when present, orders the build queue from _master.plan.md (execution_order: or ## active link order), and adds overseer sections to master-plan.md:
Implementation sequence — numbered build queue (excludes archived / implemented / merge-ready)
Overlap clusters — shared paths, token Jaccard, identical branches, declared
supersedesGoal alignment — scores active plans against goals from
.cursor/PRD.md,.cursor/TASK-GRAPH.md,.cursor/project-context.json, and_master.plan.mdgoalposts:
Run read-only by default. Human-confirmed write-back uses explicit CLI flags (never the daily-gated stop hook):
python3 scripts/daily_plan_audit.py --repo-root . --trigger "manual-masterplan-command"
python3 scripts/daily_plan_audit.py --repo-root . --trigger "manual-masterplan-command" \
--apply-disposition-sync --apply-archive
python3 scripts/daily_plan_audit.py --repo-root . --trigger "manual-masterplan-command" \
--apply-overlap-relations
python3 scripts/daily_plan_audit.py --repo-root . --trigger "manual-masterplan-command" \
--apply-goal-tagsOptional defaults in config/hub_config.yaml under planning_auditor: (overlap_jaccard_threshold, apply_overlap_relations, apply_goal_tags, goal_alignment_min_score). CLI threshold and --apply-* flags override YAML for one-off runs. Machine-local run paths: .braindrain/OPS.md.
Primary plan discovery now scans known IDE plan dirs (
.cursor/plans,.codex/plans,.kiro/plans,.windsurf/plans, etc.), and each plan/action is tagged with its IDE source.Branch resolution for each plan is hybrid by precedence: frontmatter
branch:->.cursor/.gitops-queue.json(planSourceexact match, then fuzzy) ->.cursor/.gitops-memory.jsonl-> local git branch slug match (git_local) ->—.PR column:
gh pr list --head <branch> --state allwhenghis available (noneif no PR;—if gh unavailable).When a branch is resolved from gitops queue/history and the plan lacks
branch:, the auditor writesbranch:into that plan's frontmatter during the audit run.Optional
--bootstrap-branchespersists high-confidencegit_localmatches intobranch:foractive/merge-readyplans only.Ownership defaults to
@<current username>fromget_env_context()whenowner:/dri:are absent. Explicit item-level owner markers (@name,owner:,assignee:,dri:) still work and override inherited ownership.
Plan execution branch invariant (coordinator/gitops contract):
For every plan execution/build path, enforce:
check branch -> checkout correct branch -> proceed.If a selected plan has no associated branch, run
branch-setupfirst, then continue execution on that branch.Cursor Plan Build runs in the current workspace on the current git HEAD unless agents follow the plan implementation guardrail in Ruler
RULES.md/.cursor/rules/braindrain.mdc.Stop hook
.cursor/hooks/on-stop-gitops-plans.shqueuesbranch-setupfor recently edited*.plan.mdfiles withplanSourcelinkage.Dream artifacts path:
~/.braindrain/dreaming/(plans/,daily/,DREAMS.md,last_status.json).init_project_memory(path, dry_run)bootstraps memory artifacts and is idempotent.prime_workspace()includes memory initialization in onboarding.
Next-phase roadmap (optional expansion, not missing core restoration):
Cross-project memory governance and retrieval policy for optional global memory.
Additional lesson-quality scoring and promotion analytics dashboards.
Extended provider-boundary metrics for long-run token ROI tracking.
Operational notes:
Public telemetry source-of-truth remains
~/.braindrain/costs/session.jsonl..braindrain/token-metrics.jsonlremains an optional checkpoint stream only.
License
This project is licensed under the GNU Affero General Public License v3.0 (AGPL-3.0).
Braindrain is a community-first, research-driven orchestration layer focused on token-usage reduction and practical MCP workflows. Contributions and forks are welcome under the AGPL terms.
What this means in practice
You can use, study, modify, and redistribute this project.
If you run a modified version for users over a network, you must make the corresponding source code available under AGPL-3.0.
Derivative works must keep the same license terms.
Commercial use and naming
Commercial use is permitted under AGPL-3.0. However, the Braindrain name, branding, and project identity are governed separately by project trademark policy. Forks, research reuse, and community improvements are welcome; just avoid presenting modified or hosted versions as the official Braindrain project unless explicitly authorized.
For full terms, see the [LICENSE](LICENSE) file and naming guidance in [TRADEMARKS.md](TRADEMARKS.md).
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
This server cannot be deployed
Maintenance
Related MCP Connectors
Shared memory MCP server for Claude Code, Codex, Gemini CLI and Cursor. Cited, editable.
MCP server for your apps' tools and custom tools, plus hosted AI agents and approval-gated workflows
Persistent memory, knowledge graph, task management and more for AI agents via MCP.
A second brain for your AI agent. Shared memory for your team's AI agents, plus public and private knowledge bases — works with ChatGPT, Claude, Cursor and any MCP client.
Related MCP Servers
- AlicenseAqualityCmaintenanceLocal-first MCP server that gives any AI coding agent per-project memory, workflow intelligence, and always-on, lossless token & context optimization.378 npm6MIT
- FlicenseNot gradedqualityAmaintenanceLocal MCP server that lets your AI coding agent query its own cross-tool project history - file/command freshness, past test failures, cost & token spend, cache status, and session handoff - over stdio, 100% local, no telemetry.63-
- AlicenseNot gradedqualityBmaintenanceLocal-first code intelligence MCP server that enables coding agents to search code, inspect structure, read exact ranges, and explore Git history with explicit token budgets.179Apache 2.0
- AlicenseBqualityBmaintenanceEnables AI coding agents and local LLMs to store and recall project memory, compact verbose logs, look up code symbols, create and rewind workspace snapshots, detect risky commands and loops, pack context optimally, and draft tokens through MCP tools.102Apache 2.0