brainlayer
AGENTS.md10 starsChanged 29 days agoApache-2.0View on GitHub
Ratified row-by-row by voice, 2026-08-07. Record: docs.local/GRILL-RATIFIED-2026-08-06.md. BrainLayer is the fleet's memory — both sides of it. My prompts, intent, and corrections on one side; what you all tried, what worked, what eroded and why on the other — the fleet's accumulated experience, so agents learn from each other's experience instead of re-deriving what the fleet already paid to learn. More than storage: it should give agents the understanding of WHY to go one way and not the other. Everything…
- Reads credentials
- Installs packages
- Commits and pushes
Where files are headingNew AGENTS.md files have more rules about keeping secrets out of the code, and fewer about code style.
Of the AGENTS.md files we read, the 33,398 first seen in the last six months, against the older ones: the kind of rule that gained most share, and the kind that lost most. About files like this in general, not this one, and an estimate, since a kind is a pattern in the words.
In this repository3 other files it gives its agents.
- site/AGENTS.mdAGENTS.md
- CLAUDE.mdCLAUDE.md
- site/CLAUDE.mdCLAUDE.md
The file
Show its rules and text
We split this AGENTS.md into the rules it gives an agent
19 rules. About 0 are common, 6 are distinctive, and 13 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈6
Distinctive · estimate
This author's own choices. Worth a look.
13
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Distinctive: line 24
Store discipline: Verify, then store. Do the thing, then store it — never store-before-work as ritual.
- Distinctive: line 50
Treat retrieval correctness, write safety, and MCP stability as critical-path concerns.
- Distinctive: line 51
Prefer finding regressions in search quality, lock handling, and tool contracts before style or refactor nits.
- Very specific: line 65
Call expand_palette or set BRAINLAYER_MCP_PROFILE=full for the rest.
- Very specific: line 83
Run pytest before claiming behavior changed safely.
- Very specific: line 107
Every Homebrew release must run scripts/release-verify-signatures.sh <keg-path> after installation.
- Very specific: line 110
Every release receipt must include the table from scripts/release_tag_contains.py <tag> <PRs/SHAs>, and a deploy brief may only name a fix …
- Distinctive: line 119
Do not route mandatory reviews to Bugbot or Greptile.
- Very specific: line 230
A release gate never skips: When BRAINLAYER_PREPUSH_TAG is set and the range is empty or maps no pytest target, scripts/run_tests.sh runs …
- Very specific: line 246
All scripts and CLI use paths.py for DB path resolution
- Very specific: line 253
Run the producer with brainlayer observability --write.
- Very specific: line 376
Stop-hook source='realtime' rows exist for every session and never count.
- Very specific: line 401
Default search excludes lifecycle-managed chunks.
- Very specific: line 414
Every BrainLayer hook runs under the keg python, /opt/homebrew/opt/brainlayer/libexec/venv/bin/python — named in the settings.json command …
- Very specific: line 455
Run brainlayer backup auth to authorize in the browser.
- Distinctive: line 468
Read that before tailing anything.
- Very specific: line 488
Checkpoint WAL: before and after: PRAGMA wal_checkpoint(FULL)
- Very specific: line 492
Always brain_search before answering questions about project history, architecture, or past decisions
- Distinctive: line 494
Don't rely solely on hook-injected context -- it's a hint, not comprehensive
≈ “Common” is an estimate: at least 1 in 5 of the 43,423 AGENTS.md files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
BrainLayer — a letter from Etan
Ratified row-by-row by voice, 2026-08-07. Record:
docs.local/GRILL-RATIFIED-2026-08-06.md.
BrainLayer is the fleet's memory — both sides of it. My prompts, intent, and corrections on one side; what you all tried, what worked, what eroded and why on the other — the fleet's accumulated experience, so agents learn from each other's experience instead of re-deriving what the fleet already paid to learn. More than storage: it should give agents the understanding of WHY to go one way and not the other.
Everything traces to its origin. From any memory you can walk back to the conversation it came from. Prefer pointers to the source of truth over hoarding copies.
Every indexed source carries its class. CLI coding agents (Claude Code, Codex, antigravity),
desktop apps (Claude Desktop, Gemini, ChatGPT), and subagents — normal subagents versus
brain-workers. The class is labeled at ingest and decides default-search visibility and importance.
Desktop apps: indexed, hidden from default search, opt-in only — and the opt-in switch stays
unadvertised so benchmark lanes can't trip it. Normal subagents: indexed, labeled, expandable as a
subagent thread. Brain-workers: always saved, never in default searches, never demoting other
results — [OPEN] whether they index at all, and they should ship with BrainLayer itself. All
transcripts get saved, so every memory can trace back. A new source enters only by deliberate
wiring; nothing is auto-detected.
Store discipline. Verify, then store. Do the thing, then store it — never store-before-work as
ritual. When something you stored turns out wrong, UPDATE it, don't store again beside it. If it's
my intent you corrected, come back and ask me if you got it right — and make sure your question
actually reached me: a question buried under recon output was never asked. Standing rules carry
their date and expiry — a stale truth must not masquerade as current. [NOT A FEATURE YET — this is where I'm driving this]
Eventually BrainLayer should be able to sleep like a human brain does: during the night or
hibernation periods it runs local or large-context models to figure out what the current truths
still are, and learns. That's what a brain does when it sleeps.
Never silently degrade. Never auto-delete personal data. Transcripts move to the archive only after they're embedded, and only if the usage readers still see everything. Test data changes against a copy of the real database before merging. Merged is not deployed — verify the thing that executes. Never ship my database inside a package.
This letter is for agents building BrainLayer. The rules for agents USING it live in the tool descriptions — keep those true.
— Etan
BrainLayer Agent Notes (operational)
BrainLayer is the memory layer for the entire ecosystem. If it breaks, every golem degrades into a vanilla LLM with no durable recall.
Review Guidelines
- Treat retrieval correctness, write safety, and MCP stability as critical-path concerns.
- Prefer finding regressions in search quality, lock handling, and tool contracts before style or refactor nits.
- Flag risky DB or concurrency changes explicitly. Do not hand-wave lock behavior.
Key Paths
src/brainlayer/scripts/tests/
Database
- Canonical DB:
~/.local/share/brainlayer/brainlayer.db
MCP Tools
Served by BrainBar (MCPRouter.toolDefinitions), 16 total. A session boots into the core
palette — brain_search, brain_store, brain_recall, brain_expand, plus expand_palette.
Call expand_palette or set BRAINLAYER_MCP_PROFILE=full for the rest.
- Core:
brain_search,brain_store,brain_recall,brain_expand - Gated:
brain_entity,brain_get_person,brain_tags,brain_digest,brain_update,brain_supersede,brain_archive,brain_subscribe,brain_unsubscribe,brain_ack,brain_backup_vacuum_into,brain_maintenance_rebuild_trigram brain_backup_vacuum_intois callable regardless of profile (owner-only socket is the trust boundary), but stays out of the advertised core inventory.brain_resumeexists only in the Python library handlers undersrc/brainlayer/mcp/. BrainBar does not serve it, so agents cannot call it.
Concurrency Rules
- One write at a time.
- Reads are safe.
brain_digestis write-heavy; do not run it in parallel with other MCP work.
Tests
- Bulky local build, extract, QA and pytest output lives inside
<repo-or-worktree>/.build.noindex/(pytest underpytest/) and dies with the worktree;docs.local/holds only small text receipts (version, SHA, cdhash, logs), never app bundles or binaries of any size, including archives. Temporary fake Applications roots may use*.noindex; GitHub release runners retaindist/BrainBar.appand$RUNNER_TEMP. Worktree archiving must exclude.build.noindex/,*.appand binaries over 1 MiB. - Run
pytestbefore claiming behavior changed safely. - Suite size measured 2026-11-11: 12,620 Python tests (
pytest tests/ --collect-only -q) + 1,609 Swiftfunc testdeclarations inbrain-bar/Tests/. - Suite hygiene is enforced for unmarked tests.
tests/conftest.pyguards embedding model loads, canonical DB opens, and production BrainBar socket connects —BRAINLAYER_FORBID_EMBEDDING_MODEL=1(checked at every model-load site, and inherited by subprocesses) and a refusal onsqlite3.connect/apsw.Connectionagainst~/.local/share/brainlayer. It also redirects BrainBar socket resolution to a nonexistent path and refuses connects to/tmp/brainbar.sockin-process and in Python subprocesses that inherit PYTHONPATH and site initialization. The five Python BrainBar connector sites also checkBRAINLAYER_FORBID_BRAINBAR_SOCKET, including when a child replaces PYTHONPATH but keeps the guard flag. A clean environment or non-Python socket client does not inherit that guard. The only escape is a declared marker:@pytest.mark.embedding_modelfor a test that really needs a real model (deselected byscripts/run_tests.sh, still run in CI, which warms the HF cache on purpose), orintegration/livefor a deliberate production-DB or BrainBar socket check. - The guard's one contract: in
tests/, reach an embedding model throughbrainlayer.embeddingsor a module attribute — neverfrom sentence_transformers import X. A direct alias binds the real class at import time, before any fixture, and reaches neither the module patch nor the env check (which lives at BrainLayer's load sites, not inside a third-party constructor).test_no_test_module_binds_an_embedding_model_class_directlyfails on that shape. BRAINLAYER_PREPUSH_SCOPE=changed-onlynever escalates to the full suite on an empty change set; it skips loudly and says nothing was measured.
Release safety
- Every Homebrew release must run
scripts/release-verify-signatures.sh <keg-path>after installation. - Any invalid
*.soor*.dylibblocks release/deploy; never restart services until the gate passes. - A
Casks/brainbar.rbversion lower than the package version is allowed only whenBRAINLAYER_VERSION_CHECK_CASK_LAG_REASON="no BrainBar release for <ver>"is set forscripts/brainlayer-version-check.sh; a cask ahead of the package still fails hard. - Every release receipt must include the table from
scripts/release_tag_contains.py <tag> <PRs/SHAs>, and a deploy brief may only name a fix that passed that gate —v1.5.15was tagged 22 minutes before #778 merged, and a whole M1 deploy was cut for a fix the release did not contain. --assert-module <importable>checks the same claim from the other end, against the INSTALLED keg's python; aModuleNotFoundErrorthere blocks the deploy exactly as an invalid signature does.
PR Workflow
- Review = Codex↔Claude pair + CodeRabbit (+ at most one bot); never write the Codex bot's at-mention token.
- Request a lead-routed Claude pair review through the active collab lane.
- Do not route mandatory reviews to Bugbot or Greptile.
Known Issues
- Historical enrichment writer contention is retired; keep SQLite write/lock safety.
- WAL can grow to 4.7GB.
<!-- IDENTITY: brainlayer, owner=EtanHey, purpose=the fleet's memory — see the letter at the top of this file -->BrainBar Native Tools
BrainBar is the only agent MCP transport. The authoritative tool list, descriptions, schemas, and
ToolAnnotations live in brain-bar/Sources/BrainBar/MCPRouter.swift (toolDefinitions) — read that,
not a copy here. Two contracts an agent must know:
brain_storeoutcomes (#725):STORED|DUPLICATE|MERGED|DEFERREDare all success — do NOT re-store;DEFERREDis queued and will be persisted.REJECTED|ERRORstored nothing and return nostatusand nochunk_id. A committed write can never answerREJECTEDorERROR.- Descriptions survive the wire (#727): oversized
tools/listresponses compact as a ladder — annotations and inputSchema prose go first; only then are descriptions shortened (marked…[truncated], with aresult._meta["brainlayer/descriptionsTruncated"]notice naming each one). Descriptions are never removed; below the floor the response ships over-limit with its contract intact and logs why.
<!-- ARCHITECTURE: Python/Typer CLI, sqlite-vec storage via APSW, bge-large embeddings, BrainBar Swift MCP daemon over /tmp/brainbar.sock, library MCP handlers under mcp/, Rich TUI + Next.js site -->Stack (WHAT)
- Python package + Typer CLI in
src/brainlayer/ - sqlite-vec storage via APSW (
vector_store.py) - bge-large-en-v1.5 embeddings (
embeddings.py) - BrainBar (Swift) owns the MCP daemon and
/tmp/brainbar.sock; Python keeps library handlers undermcp/ - The FastAPI daemon was removed (
fix(arch): remove FastAPI daemon, 692839cc) — there is no HTTP API - Rich TUI (
src/brainlayer/dashboard/) and Next.js site (site/) - Source data: JSONL in
~/.claude/projects/
Checkouts and worktrees — never work at the repo root
- An old editable-install console script can shadow the keg CLI on PATH and run root code.
brainlayer doctordetects this from the keg; dev runs explicitly skip the check. ~/Gits/brainlayeris a real checkout kept atorigin/main, and ~22 worktrees hang off it. It was repaired on 2026-09-06 (core.baretrue→false, HEAD5bd8d818→da325b8d) after its working tree sat frozen at the 09-02 snapshot for days. It is not self-stabilising.- The root's
src/is on the interpreter path of thepython3that Claude Code hooks resolve to — Framework 3.13, first on PATH (/usr/local/bin/python3is a symlink to that same binary). Its/Library/Frameworks/Python.framework/Versions/3.13/lib/python3.13/site-packages/_brainlayer.pthcontains exactly/Users/etanheyman/Gits/brainlayer/src, so a barepython3 -c "import brainlayer"resolves to<root>/src/brainlayer/__init__.py— a live working tree, not an installed package. Checking out a branch, or leaving a dirty tree, at the ROOT therefore changes what that interpreter imports — for every session, in every lane, immediately. - It is not every
python3, and testing with the wrong one proves nothing./opt/homebrew/bin/python3(3.14), Framework 3.10, and/usr/bin/python3(3.9) do not see the.pthat all and failimport brainlayeroutright. The exposure is real and load-bearing for the default interpreter only — which is the one that matters, because it is the one the hooks get. Law: never
git checkout/git switcha branch at the root, and never edit files there. Work only in your own worktree, cut fromorigin/main. Givegit worktree addan absolute target: it resolves a relative path against your cwd, so a seat that is already inside a worktree — which, under this rule, is every seat — would turn.worktrees/<name>into a nested checkout at.worktrees/<current>/.worktrees/<name>. The absolute form is copy-paste safe from anywhere, and is also what the machine's worktree-location guard accepts:git worktree add ~/Gits/brainlayer/.worktrees/<name> -b wt/<name> origin/main- The evidence. While the root sat at
5bd8d818(2026-09-04), #782's commit123da9b4was not an ancestor of it, so everything importing through the.pthran 09-02 library code: #782 was merged but not live. The same root-is-live-code path is what let a checkout'sinstall.shpoint every LaunchAgent at the wrong version on 09-05. - #790 pinned the hooks, so for HOOKS this rule is now defence in depth. Every
hooks/*.pyshebang names/opt/homebrew/opt/brainlayer/libexec/venv/bin/python(theopt/symlink, so a rendered command outlives the keg it was rendered against),src/brainlayer/hook_python.pyresolves that interpreter and refuses a silent PATH fallback, andpython -m brainlayer.hook_python ~/.claude/settings.jsonlints a settings file for barepython3. That venv does not see the.pth— it resolves to the keg. A hook can no longer be re-aimed by agit checkoutat the root. - For everything else the rule is still primary — #790 did not remove the
.pth. Verified 2026-09-06 after #790 merged: the file is still there and barepython3 -c "import brainlayer"still resolves to<root>/src/brainlayer/__init__.py. Any script,python3 -c, editable install, or non-BrainLayer hook running under the default interpreter still reads the root's working tree. The pin closed the worst consumer, not the mechanism. - ⚠️ Merged is not deployed, and this is the live example.
~/.claude/hooks/*.pyare real files, not symlinks into this repo, so #790's shebang change does not reach them by merging: measured 2026-09-06, the deployedbrainlayer-prompt-search.py,brainlayer-session-start.pyandsession-cleanup.pystill begin#!/usr/bin/env python3. They are safe today only because~/.claude/settings.jsonnames the keg interpreter ahead of the script path. Run thehook_pythonlint against the real settings file before believing the pin is live on a machine.
<!-- COMMANDS: `python3 -m venv .venv && source .venv/bin/activate && pip install -e ".[dev]"` | test: `pytest` | lint: `ruff check src/ tests/ && ruff format src/ tests/` | run: `brainlayer index && brainlayer setup` -->Workflow (HOW)
python3 -m venv .venv && source .venv/bin/activate
pip install -e ".[dev]"
brainlayer index
brainlayer setup
brainlayer search "how did I implement authentication"- Lint/format:
ruff check src/ tests/ && ruff format src/ tests/ - Pre-push: suites are queued via golems' heavy-suite lock;
GOLEMS_HEAVY_FORCE=1is the human override..githooks/pre-pushrunsscripts/run_tests.shwithBRAINLAYER_PREPUSH=1; full runs are deduped by git tree hash in.git/brainlayer-prepush-cache. - A tag push has no branch to diff against, so the hook reads the pushed refs off its stdin and
scopes the run to
<previous release tag>..<tag>viaBRAINLAYER_CHANGED_FILES_RANGE, naming the tag inBRAINLAYER_PREPUSH_TAG. The predecessor must be a full release: resolved with--match 'v*' --exclude '*-*', so neither a non-release tag (nightly,archive/*) nor a pre-release (v1.2.3-rc1) can start the range short and leave real commits unmapped. Over-scoping from the last full release is safe; under-scoping a gate is not. - An explicit scope picks the MODE; the range is the DATA. Under
BRAINLAYER_PREPUSH_SCOPE=changed-only— the normal worker path below — a tag push still gets its range. Only a non-changed-onlyexplicit scope (full, or anything else) stops the hook entirely. The hook otherwise refuses to narrow — printing the reason in the push output — when a branch rides along, whenBRAINLAYER_CHANGED_FILES/_RANGEis already set, when more than one tag is pushed at once, or when the tag has no full-release predecessor. None of those are silent. - A release gate never skips. When
BRAINLAYER_PREPUSH_TAGis set and the range is empty or maps no pytest target,scripts/run_tests.shruns the full suite and says why, instead of taking the measured-empty / no-mapped-target skip. That skip stays correct for every other caller; for a tag it would mean a release gating nothing at all. - Scoped worker pushes: use
BRAINLAYER_PREPUSH_SCOPE=changed-only git pushto map changed files to focused pytest targets while keeping the lightweight registration, isolated, bun, and shell gates. - Worker pre-push must not run real-DB files
tests/test_vector_store.pyortests/test_engine.py; run them only as deliberate production-DB checks.
Pipeline Overview
- Extract -> Classify -> Chunk -> Embed -> Index
- Post-processing: local Brain Graph and Obsidian export; historical enrichment metadata remains readable
- Storage:
~/.local/share/brainlayer/brainlayer.db(canonical path; measured 2026-09-06 at 16.5 GB / 817,238 chunks — it grows, so re-measure rather than quoting this figure back) - DB path resolved by
paths.py:get_db_path()— env var override or canonical path - All scripts and CLI use
paths.pyfor DB path resolution - Concurrency: retry on
SQLITE_BUSY; each worker uses its own connection
Observability surface
- The Python producer writes
observability.jsonbeside the resolved DB;BRAINLAYER_OBSERVABILITY_PATHoverrides that path. - The frozen contract is
tests/fixtures/observability/observability-schema.v1.json(schema_version: 1). stores,emitters,author_unknown, andbackupsfail closed: every section carriesstate,reason, andinputs[]; measured sections use an empty reason, whileunmeasurablesections require a non-silent one and no numeric output.- Run the producer with
brainlayer observability --write; check fixture drift withpython3 scripts/check_observability_golden_inputs.py --split dev.
P1 Pipeline Contracts
- BL-10 source denylist is implemented in
src/brainlayer/ingest_denylist.py. By default, provider sessions and ordinary Claude subagents ingest. Exclusion is scoped to agents whose job is to READ OTHER AGENTS' MEMORY OR JSONLs —brain-workersub-agents, andsession-miner/weaveworkflow agents. It is NOT all workflows. Etan, 2026-08-03: "That's very specific. It's not all workflows. I don't know why y'all keep thinking it's all workflows." and "the Weaver's workflow is built of session miners." - brain-worker and miner sessions are KEPT but NOT INDEXED. Exclusion never deletes the source
JSONL — it means exclusion from the index only.
BRAINLAYER_INGEST_DENYLISTremains an explicit deployment override. - brain-worker ≠ brainlayer worker (Etan, ratified by voice 2026-08-08): a brain-worker is the ingest-excluded SUBAGENT type (Claude Agent-tool type today; other harnesses hopefully later) — its transcript stays out of the index BY CLASS, which is its entire point. A brainlayer worker is a cmux pane of a brainlayerGolem and ingests normally. Never substitute a visible pane when ingest-exclusion is the goal; to "paste" to a subagent, paste to the lead, who relays.
- Code drift CLOSED.
DEFAULT_INGEST_DENYLISTis now()— thewf_*blanket is gone, and exclusion is decided by class from each transcript's ownattributionAgent(MEMORY_READER_ATTRIBUTIONS = {brain-worker, session-miner, weave}). Ordinary workflow agents ingest. Landed by5c0dfc52and follow-ups. Path shape is not fully gone:memory_reader_attributionstill walks the path components undersubagents/and returns a role when one of them literally names a memory reader, before it reads the JSONL. That is a narrow exact-segment match, never task text — but do not read "by class" as "path is never consulted". - ⚠️
session-minerandweaveare not detectable today, and the code cannot invent them. A census of 2,793 realagent-*.meta.jsonsidecars under~/.claude/projects(2026-09-05) foundbrain-worker60 times andsession-miner/weavezero times: every workflow agent is written as the genericworkflow-subagent(2,288) orgeneral-purpose(8), and no transcript field carries the workflow agent's own role. Both names stay inMEMORY_READER_ATTRIBUTIONSso the ruling holds the moment a harness ever labels them; until then onlybrain-workeractually fires. Matching on task text is not a substitute and is forbidden — a lead session discussing session-miner is ordinary memory. BRAINLAYER_INGEST_DENYLISTadds path exclusions to the class rule. Empty and deployment-scoped overrides preserve memory-reader attribution exclusion and the default fail-closed policy for unknown Claude subagents. Narrowing a Codex blanket must retain unrelated project exclusions; a configured path may still exclude otherwise ordinary sessions.brainlayer setupreads the env FILE it resolved, not just the process environment. The blanket lived in~/.config/brainlayer/brainlayer.env, which is not in a fresh shell's environ, so a check againstos.environalone would have stayed silent on the very defect it exists to catch.env_file_denylist_patterns()parses the resolved file (including--env-file), andsetupreports each source separately: that the override preserves the class rule, and then any pattern broader than it. Deployment-scoped patterns naming one project or repo are not reported as overreach. Etan rules on that env file; agents do not edit it.- Go-forward secret scrubbing runs in
src/brainlayer/pipeline/secret_scrub.pyfromsrc/brainlayer/watcher_bridge.pybefore chunk persistence. Provider-prefixed and labeled high-entropy secrets are redacted; unlabeled high-entropy tokens are recorded in quarantine metadata. - LLM enrichment producers are retired. Existing parsed metadata, local replay, and output
scrubbing remain compatibility contracts. Keep fail-closed credential/output scrubbing and
the public local PII
Sanitizer; do not add a model sender or route around retirement. History: enrichment retirement. - MCP search uses a fixed-size readonly WAL
VectorStorepool insrc/brainlayer/mcp/_shared.py.BRAINLAYER_READ_POOL_SIZEdefaults to 8, or 4 on detected Apple M1; M1 machines can keep the lower override explicitly. Checkout beyond the fixed pool blocks up toBRAINLAYER_READ_BUSY_TIMEOUT_MS, and startup rejectspool_size * BRAINLAYER_READ_CACHE_KBabove about 768MB.
<!-- ARCHITECTURE: classification preserves ai_code/stack_trace/user_message verbatim; skips noise; AST-aware chunking via tree-sitter; never split stack traces -->Classification & Chunking Rules
- Preserve verbatim:
ai_code,stack_trace,user_message - Skip/summarize:
noise(skip),build_log(summarize),dir_listing(structure only) - Chunking: AST-aware (tree-sitter); never split stack traces; mask large tool output
<!-- ARCHITECTURE: LLM enrichment retired; historical metadata and local KG retained -->Enrichment (retired)
- LLM chunk/session enrichment and provider activation are retired.
- Existing metadata and session analysis remain readable. Local indexing, search, digest, KG, offline prompt emission/collection, and checkpoint replay remain available.
- History: enrichment retirement.
- Release gate: retain
GOOGLE_API_KEY,BRAINLAYER_REQUIRE_GOOGLE_API_KEY, and env-run's exit-78 compatibility gate until the release re-renders installed hotlane plists. Preserve its documentation in Configuration. Do not resume retired jobs.
<!-- MCP-SERVERS: agent MCP is BrainBar on /tmp/brainbar.sock (brainlayer-mcp-stdio-bridge; raw socat loses transport on restart); brainlayer-mcp Python entrypoint DELETED; no HTTP daemon API; library handlers live under mcp/; 16 tools in MCPRouter.toolDefinitions, core palette = brain_search/brain_store/brain_recall/brain_expand + expand_palette -->Interfaces
- There is no HTTP API. The FastAPI daemon and its
/health,/stats,/search,/brain/graph,/backlog/itemsroutes were removed. Anything still calling them is calling a surface that is gone. - MCP tools: 16, defined in
brain-bar/Sources/BrainBar/MCPRouter.swift— see MCP Tools above for the core/gated split. Legacybrainlayer_*names are still handled by the Python library handlers undersrc/brainlayer/mcp/, but BrainBar does not serve them. brain_expandandbrain_tagsare deprecated in the Python MCP path and return errors there; the BrainBar path serves both normally.- MCP server: BrainBar on
/tmp/brainbar.sockonly. Preferred wiring is{"command":"/opt/homebrew/opt/brainlayer/bin/brainlayer-mcp-stdio-bridge"}(ships with the package, reconnects across BrainBar restarts, uses a stable opt path). Rawsocat STDIO UNIX-CONNECT:/tmp/brainbar.sockexits on a BrainBar restart and leaves persistent clients with a closed transport;brainlayer doctorreports that risk with the config path. The Pythonbrainlayer-mcpentrypoint is deleted.brainlayer setup --migrate-mcpbacks up and rewrites owned legacy and raw-socat entries to the absolute opt-path bridge, verifies that same path, preserves unrelated servers/settings, and leaves existing pinned bridge entries in place. Doctor flags bare or foreign bridge targets. Converted socat entries dropMCPLAYER_BRAINLAYER_FRONT(retained in the backup) to keep their direct route; existing bridge entries keep their env. Doctor notes proxy routes as info. Project.mcp.jsoncan override a healthy base Codex config; migrate those owned files too.
<!-- COMMANDS: `brainlayer brain-export` → graph JSON for dashboard | `brainlayer export-obsidian` → Markdown vault with backlinks + tags -->Exports
brainlayer brain-export-> graph JSON for dashboardbrainlayer export-obsidian-> Markdown vault (backlinks + tags)
<!-- ARCHITECTURE: real-time watcher via LaunchAgent (com.brainlayer.watch.plist), 4-layer content filters, offset persistence, rewind detection, Axiom telemetry -->Real-time JSONL Watcher
brainlayer watch— persistent watcher for~/.claude/projects/*.jsonl- LaunchAgent:
com.brainlayer.watch.plist(KeepAlive, Nice=10) - 4-layer content filters: entry type whitelist → classify → chunk min-length → system-reminder strip
- Offset persistence:
~/.local/share/brainlayer/offsets.json(survives restarts) - Rewind detection: file shrink = checkpoint restore → soft-archives reverted chunks
- Axiom telemetry: startup, flush, error, heartbeat (60s threshold, but it is checked once per poll, so at the 30s poll default the real spacing is ~60-95s — measured 91s; do not alert on a 60s cadence) to
brainlayer-watcherdataset - Liveness: read
watcher-health.json, not a log stream. It is the canonical surface, it is JSON, and bothpoll_countandupdated_atadvance on every poll — which is what a sampler needs. Its path is database-relative (watcher-health.jsonbeside the resolved DB), so withBRAINLAYER_DBset it is NOT under~/.local/share/brainlayer—~/.local/share/brainlayer/watcher-health.jsonis only the canonical-DB default. The startup banner prints the path it actually used;BRAINLAYER_WATCHER_HEALTH_PATHoverrides it outright. - The two streams are split on purpose, and neither is the liveness surface.
stdout(watch.out.log) carries the one-shot startup banner and rewind notices — rich markup, for a human.stderr(watch.err.log) carries timestamped logging, including theWatcher alive: …heartbeat:brainlayer watchcallslogging.basicConfig(stream=sys.stderr)(#759). The poll clamp appears in both —enforce_min_poll_interval()logs it at WARNING to stderr and the command alsorprints it to stdout. So greppingwatch.out.logfor "Watcher alive" returns nothing — that is the split, not a dead watcher. The heartbeat is deliberately NOT duplicated onto stdout: one signal, one writer.tests/test_jsonl_watcher.py::TestWatcherLivenessSurfacepins all three halves. - A forked Claude chat starts at its fork point. Claude Code writes a fork (/side, a resumed
fork) as the parent's entries copied under the fork's sessionId, each carrying
forkedFrom={sessionId: <immediate parent>, messageUuid}, then the fork's own entries without it. The tailer consumes a copy without emitting it only when ALL hold:<fork dir>/<parent>.jsonlwas discovered this poll and is not denylisted; it is still the file the registry has been reading and is FULLY READ (rewind generation 0, same inode as this poll's stat, confirmed offset == current size; a partly read parent ingests the copies and dedupe merges them); AND the parent has rows the WATCHER wrote (source='realtime_watcher'or asource_end_offset; read-only, cached per poll, fail-closed). Stop-hooksource='realtime'rows exist for every session and never count. Otherwise the copies ingest as before. Skipped copies are neutral lines and do not count towardmax_lines_per_file(up to 25,000 per read). Health:fork_copies_skipped_total,fork_copy_files(with the parent's confirmed offset and size). Only Claude has a per-entry fork marker; Codex's is header-level. - A T3 session T3 never links is held for a bounded window, then indexed. A T3-origin Codex
session (
originator: "T3 Code") that the T3 projection does not link is held unconfirmed only while its own UUIDv7 start is withinBRAINLAYER_T3_LINKAGE_HOLD_S(default 24 h). Past it, the flush indexes it withprovenance_class = 't3-unlinked'and confirms it normally. Evidence for the window (2026-11-19): 0 of 87 M4 sessions that ever raisedt3_runtime_linkage_pendingwere linked later, and no linked session ever raised it. Inside the window, the READ held bytes arecatch_up.held_for_linkage {files, bytes, oldest_age_s, window_s}inwatcher-health.json, never lag. Unread bytes and holds past the window stay lag (offset_lag, red as before). A late link: new entries aret3-app-sessionat once; already-indexed rows are relabelled in place byscripts/retag_t3_app_provenance.py --apply(reversible, lead-run).tests/test_t3_linkage_hold.py. - A finished file's no-entry tail is confirmed once the entries before it are. Bytes after a
file's last message (tool output, token counts) are confirmed as discarded progress only when
nothing of the file is buffered. If its last entries were still buffered (or held), the
frontier is remembered and
_retry_discarded_progressconfirms it after the poll's flush, never past the read end. Before this, such a tail stayed unconfirmed forever at EOF and counted as lag (9 of 15 real held sessions, 19 Nov). - Source:
watcher.py(tailer + indexer),watcher_bridge.py(pipeline integration)
<!-- ARCHITECTURE: chunk lifecycle columns superseded_by/aggregated_into/archived_at; brain_supersede has safety gate for personal data; brain_archive is soft-delete -->Chunk Lifecycle
- Columns:
superseded_by,aggregated_into,archived_aton chunks table - Default search excludes lifecycle-managed chunks;
include_archived=Trueshows history brain_supersede: safety gate for personal data (journals, notes, health/finance)brain_archive: soft-delete with timestampbrain_storegainssupersedesparam for atomic store-and-replace
<!-- HOOKS: SessionStart writes injected chunk_ids to /tmp/brainlayer_session_{id}.json; UserPromptSubmit skips already-injected; module: hooks/dedup_coordination.py -->Session Dedup Coordination
/tmp/brainlayer_session_{id}.json— shared between SessionStart and UserPromptSubmit hooks- SessionStart writes injected chunk_ids; UserPromptSubmit skips already-injected
- Handoff detection: prompts with "handoff", "session-handoff" skip auto-search
- Module:
hooks/dedup_coordination.py
Hook Interpreter (pinned, never PATH)
- Every BrainLayer hook runs under the keg python,
/opt/homebrew/opt/brainlayer/libexec/venv/bin/python— named in thesettings.jsoncommand AND in the script's shebang.BRAINLAYER_HOOK_PYTHONis the only override, and it must exist. - Why: bare
python3on the M4 fronts the framework python, whosesite-packages/_brainlayer.pthinjects~/Gits/brainlayer/src— a live checkout any agent can move with onegit checkout. When it held a 09-02 snapshot, hooks executed weeks-old library code under a 1.5.15 CLI, silently: no import error, no version mismatch, no log line. src/brainlayer/hook_python.pyresolves it and refuses a silent PATH fallback (same fail-closed stance asscripts/launchd/install.sh). Lint a settings file by hand withpython -m brainlayer.hook_python ~/.claude/settings.json;tests/test_hook_python.pyfails on any barepython3/env python3shebang or command.- The gate is affirmative, not a blacklist: anything it cannot vouch for is REPORTED. An empty
interpreter token, the Stop shim's
--with the pin dropped,uv run, a cwd-relative path — all are findings, each carrying the reason. A lint that answers "fine" to a command shape it does not understand is not a gate, and this one guards every future BrainLayer hook. - Three separate questions, deliberately not one.
is_bare_python3= does PATH decide.is_system_python= is this a site-wide interpreter, i.e. one whosesite-packagesis where a global.pthlives (/usr/bin,/usr/local/bin,/opt/homebrew/bin, anyPython.framework) — naming the framework python absolutely closes the PATH hazard and leaves the.pthhazard open, so it is still not an acceptable pin.is_pinned_interpreter= the gate both feed. BRAINLAYER_HOOK_PYTHONis refused, loudly, three ways: relative, site-wide, or set-but-missing. A set-but-missing override never falls through to the keg — setting it is a deliberate choice, and silently substituting a different interpreter for a typo'd one is the same failure the pin exists to prevent. An absolute venv python outside a keg IS accepted, and the linter accepts it too; the contract is "explicitly named", not "Homebrew-shaped".- The shebangs name the ARM Homebrew prefix, so they are machine-specific on purpose. The four
hooks that matter are invoked as
<python> <script>fromsettings.json, which overrides the shebang entirely; the shebang only decides what happens when a script is run directly (today onlyhooks/post-commit.py, which nothing in this repo installs as a git hook). On an Intel prefix that shebang fails loudly with "bad interpreter" — which is the intended failure, not a silent run against the wrong library. Rendering per-machine isrender_hook_command()'s job; there is no hook installer yet to call it.
<!-- PATHS: DB=~/.local/share/brainlayer/brainlayer.db | offsets=~/.local/share/brainlayer/offsets.json | logs=~/Library/Logs/brainlayer/watch.{out,err}.log | socket=/tmp/brainbar.sock | lock=/tmp/brainlayer-enrichment.lock -->Data & Locks
- Disk-space truth: use only
brainlayer disk --json(--path Pselects a volume). On macOS,dffree is NOT Available: Available includes purgeable capacity; backup allocation still requires measured free-now bytes and preserves the 2 GiB raw floor. Probe fallback is explicit insource; non-macOS reports Available = free now and purgeable = 0. - Backups use the BrainLayer-owned
~/.config/brainlayer/drive-tokens.json(0600); the Google Drive MCP token is a one-time copy source only. - Database backup retention and its configuration are defined in Backup Strategy; keep the policy numbers there.
- Run
brainlayer backup authto authorize in the browser; BrainBar usesbrainlayer backup auth --status --jsonandbrainlayer backup auth --json. BRAINLAYER_DRIVE_TOKEN_PATHandBRAINLAYER_DRIVE_CLIENT_PATHoverride the token and read-only OAuth client paths; never delete a token after refresh failure.- Backup log: real runs append JSONL to
~/.local/share/brainlayer/logs/backup-daily.logwithbackup_log_provenance=real; pytest setsBRAINLAYER_BACKUP_LOG_PATHandBRAINLAYER_BACKUP_LOG_PROVENANCE=pytestso tests cannot refresh the production heartbeat log. - Watcher offsets:
~/.local/share/brainlayer/offsets.json - Prompts cache:
~/.local/share/brainlayer/prompts/ - Watcher logs:
~/Library/Logs/brainlayer/watch.{out,err}.log(moved from~/.local/share/brainlayer/logs/watch.{log,err}by3dca26a2, 2026-05-18; the old files are frozen at that date and are NOT a health signal — #732: an agent read them as a live lock storm). Those paths are only what the shipped plist sets. The running watcher is the authority on where it writes: itsJSONL watcher started:line andwatcher-health.json→log_destinationsname the stdout/stderr targets read from the kernel. Read that before tailing anything. Agents never delete or archive the old files; Etan decides. - A vanished JSONL is not a parse failure:
vanished_source_count_totalinwatcher-health.jsoncounts confirmed deletions (lstat ENOENT), which never raisewatcher_file_ingestion_failed. A path that reappears under the same inode is resumed only if the 256 bytes before its offset AND a digest of its first 4 KiB still match; otherwise it is re-ingested from 0 (#732). A tail alone is not enough: the #1656 DB-copy rehearsal lost two records to a rewrite whose records lined up with the old offset and shared a long suffix. - A stored offset is never trusted on its own word. Each
offsets.jsonentry carries afingerprint(offset + head digest + tail) of the bytes before it. A restarted watcher, or one handed copied offsets, re-checks it before resuming and re-reads from 0 on a mismatch (idempotent: content-hash chunk ids + dedupe). Entries written before fingerprints existed resume only if the file's mtime is no later than the checkpoint's confirm time, so an upgrade does not re-read untouched files from 0; any appended or rewritten file is re-read from 0. - Socket:
/tmp/brainbar.sock - Historical enrichment lock:
/tmp/brainlayer-enrichment.lock(legacy cleanup/safety only) - Session dedup:
/tmp/brainlayer_session_*.json
<!-- ANTI-PATTERNS: quiesce writers before bulk ops; preserve legacy enrichment stop checks; checkpoint WAL first -->Bulk DB Operations (SAFETY)
- Quiesce all writers first — preserve checks for older installed enrichment jobs, but never resume the retired service. Concurrent bulk writes can cause WAL bloat or freezes.
- Checkpoint WAL before and after:
PRAGMA wal_checkpoint(FULL) - Batch deletes in 5-10K chunks, checkpoint every 3 batches
Memory Tools
- Always
brain_searchbefore answering questions about project history, architecture, or past decisions brain_storeafter making decisions, hitting bugs, or receiving corrections- Don't rely solely on hook-injected context -- it's a hint, not comprehensive
Naming
- BrainLayer (זיכרון) = "memory"
Rulings that bind every agent here (ratified by voice 2026-08-02)
- Worktrees:
projectis always the REPO (canonical); the branch is a separate field. A branch name is never a project. - Rules ride in instruction files (this file +
CLAUDE.md), deterministically. BrainLayer injects CONTEXT only — it is not a source of law, and no third curated instruction source gets created. - Agent-authored chunks are the normal case — "rules cite no source" is a non-finding; never report it.
- Pre-merge live-check against a DB copy is required before any change that touches stored data. (Etan's addition at ratification, 2026-08-02.)
Local JSONL retention
- Each sweep adds at most one reporting row:
local_retention_summary, with akeptlist of archives held past the retention period (name,bytes,first_reason, nullableeligible_at) and totals for held/young bytes and the next age-eligible bytes/date. Reporting rows have no run-result fields orerror, preserving BrainBar's 200-line history and last-run selection. Dates forecast only the age gate; live Drive, hashes, exact receipt and newest protection still govern deletion. Reconciliation starts a new full 14-day verification clock; never backdate it. - Local deletion defaults on via
BRAINLAYER_JSONL_BACKUP_LOCAL_RETENTION;0/falsedisables it. Require both mtime and verified-at ages >=14 days, exact verified receipt plus local/Drive MD5 match and live Drive presence; never newest across release siblings. Drive-onlyBRAINLAYER_JSONL_BACKUP_RETENTIONremains opt-in, latest 30. Scratch proof:formal/jsonl-retention/check.sh,tests/test_jsonl_local_retention.py,tests/test_jsonl_retention_r2.py.
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

