agentleFS
EtanHeyEtanHey/brainlayer/AGENTS.md

brainlayer

AGENTS.md9 starsChanged 56 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 checking a change actually works.

    Of the AGENTS.md files we read, the 11,773 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.

The file

Show its rules and text

We split this AGENTS.md into the rules it gives an agent

17 rules. About 0 are common, 5 are distinctive, and 12 are very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈5

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 12

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Distinctive:

    Store discipline: Verify, then store. Do the thing, then store it — never store-before-work as ritual.

    line 24
  2. Distinctive:

    Treat retrieval correctness, write safety, and MCP stability as critical-path concerns.

    line 50
  3. Distinctive:

    Prefer finding regressions in search quality, lock handling, and tool contracts before style or refactor nits.

    line 51
  4. Very specific:

    Call expand_palette or set BRAINLAYER_MCP_PROFILE=full for the rest.

    line 65
  5. Very specific:

    Run pytest before claiming behavior changed safely.

    line 82
  6. Very specific:

    Every Homebrew release must run scripts/release-verify-signatures.sh <keg-path> after installation.

    line 106
  7. Very specific:

    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 …

    line 109
  8. Distinctive:

    Do not route mandatory reviews to Bugbot or Greptile.

    line 118
  9. Very specific:

    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 …

    line 230
  10. Very specific:

    All scripts and CLI use paths.py for DB path resolution

    line 246
  11. Very specific:

    Run the producer with brainlayer observability --write.

    line 253
  12. Very specific:

    Default search excludes lifecycle-managed chunks.

    line 369
  13. Very specific:

    Every BrainLayer hook runs under the keg python, /opt/homebrew/opt/brainlayer/libexec/venv/bin/python — named in the settings.json command …

    line 382
  14. Very specific:

    Run brainlayer backup auth to authorize in the browser.

    line 418
  15. Very specific:

    Checkpoint WAL: before and after: PRAGMA wal_checkpoint(FULL)

    line 435
  16. Very specific:

    Always brain_search before answering questions about project history, architecture, or past decisions

    line 439
  17. Distinctive:

    Don't rely solely on hook-injected context -- it's a hint, not comprehensive

    line 441

≈ “Common” is an estimate: at least 1 in 5 of the 16,595 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.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
AGENTS.md

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), 17 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_enrich, brain_supersede, brain_archive, brain_subscribe, brain_unsubscribe, brain_ack, brain_backup_vacuum_into, brain_maintenance_rebuild_trigram
  • brain_backup_vacuum_into is callable regardless of profile (owner-only socket is the trust boundary), but stays out of the advertised core inventory.
  • brain_resume exists only in the Python library handlers under src/brainlayer/mcp/. BrainBar does not serve it, so agents cannot call it.

Concurrency Rules

  • One write at a time.
  • Reads are safe.
  • brain_digest is write-heavy; do not run it in parallel with other MCP work.

Tests

  • Run pytest before claiming behavior changed safely.
  • Current suite size: 4,386 Python tests (pytest tests/ --collect-only -q) + 890 Swift tests in brain-bar/Tests/.
  • Suite hygiene is enforced for unmarked tests. tests/conftest.py guards 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 on sqlite3.connect/apsw.Connection against ~/.local/share/brainlayer. It also redirects BrainBar socket resolution to a nonexistent path and refuses connects to /tmp/brainbar.sock in-process and in Python subprocesses that inherit PYTHONPATH and site initialization. The five Python BrainBar connector sites also check BRAINLAYER_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_model for a test that really needs a real model (deselected by scripts/run_tests.sh, still run in CI, which warms the HF cache on purpose), or integration/live for a deliberate production-DB or BrainBar socket check.
  • The guard's one contract: in tests/, reach an embedding model through brainlayer.embeddings or a module attribute — never from 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_directly fails on that shape.
  • BRAINLAYER_PREPUSH_SCOPE=changed-only never 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 *.so or *.dylib blocks release/deploy; never restart services until the gate passes.
  • A Casks/brainbar.rb version lower than the package version is allowed only when BRAINLAYER_VERSION_CHECK_CASK_LAG_REASON="no BrainBar release for <ver>" is set for scripts/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.15 was 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; a ModuleNotFoundError there 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

  • DB locking during enrichment.
  • 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_store outcomes (#725): STORED|DUPLICATE|MERGED|DEFERRED are all success — do NOT re-store; DEFERRED is queued and will be persisted. REJECTED|ERROR stored nothing and return no status and no chunk_id. A committed write can never answer REJECTED or ERROR.
  • Descriptions survive the wire (#727): oversized tools/list responses compact as a ladder — annotations and inputSchema prose go first; only then are descriptions shortened (marked …[truncated], with a result._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/, Textual TUI + Next.js dashboard -->

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 under mcp/
  • The FastAPI daemon was removed (fix(arch): remove FastAPI daemon, 692839cc) — there is no HTTP API
  • Textual TUI (dashboard/) and Next.js dashboard
  • 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 doctor detects this from the keg; dev runs explicitly skip the check.
  • ~/Gits/brainlayer is a real checkout kept at origin/main, and ~22 worktrees hang off it. It was repaired on 2026-09-06 (core.bare true→false, HEAD 5bd8d818→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 the python3 that Claude Code hooks resolve to — Framework 3.13, first on PATH (/usr/local/bin/python3 is a symlink to that same binary). Its /Library/Frameworks/Python.framework/Versions/3.13/lib/python3.13/site-packages/_brainlayer.pth contains exactly /Users/etanheyman/Gits/brainlayer/src, so a bare python3 -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 .pth at all and fail import brainlayer outright. 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 switch a branch at the root, and never edit files there. Work only in your own worktree, cut from origin/main. Give git worktree add an 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 commit 123da9b4 was not an ancestor of it, so everything importing through the .pth ran 09-02 library code: #782 was merged but not live. The same root-is-live-code path is what let a checkout's install.sh point 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/*.py shebang names /opt/homebrew/opt/brainlayer/libexec/venv/bin/python (the opt/ symlink, so a rendered command outlives the keg it was rendered against), src/brainlayer/hook_python.py resolves that interpreter and refuses a silent PATH fallback, and python -m brainlayer.hook_python ~/.claude/settings.json lints a settings file for bare python3. That venv does not see the .pth — it resolves to the keg. A hook can no longer be re-aimed by a git checkout at 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 bare python3 -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/*.py are real files, not symlinks into this repo, so #790's shebang change does not reach them by merging: measured 2026-09-06, the deployed brainlayer-prompt-search.py, brainlayer-session-start.py and session-cleanup.py still begin #!/usr/bin/env python3. They are safe today only because ~/.claude/settings.json names the keg interpreter ahead of the script path. Run the hook_python lint 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"
brainlayer enrich
  • Lint/format: ruff check src/ tests/ && ruff format src/ tests/
  • Pre-push: suites are queued via golems' heavy-suite lock; GOLEMS_HEAVY_FORCE=1 is the human override. .githooks/pre-push runs scripts/run_tests.sh with BRAINLAYER_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> via BRAINLAYER_CHANGED_FILES_RANGE, naming the tag in BRAINLAYER_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-only explicit 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, when BRAINLAYER_CHANGED_FILES/_RANGE is 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_TAG is set and the range is empty or maps no pytest target, scripts/run_tests.sh runs 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 push to 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.py or tests/test_engine.py; run them only as deliberate production-DB checks.

Pipeline Overview

  • Extract -> Classify -> Chunk -> Embed -> Index
  • Post-processing: Enrichment, Brain Graph, Obsidian export
  • 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.py for DB path resolution
  • Concurrency: retry on SQLITE_BUSY; each worker uses its own connection

Observability surface

  • The Python producer writes observability.json beside the resolved DB; BRAINLAYER_OBSERVABILITY_PATH overrides that path.
  • The frozen contract is tests/fixtures/observability/observability-schema.v1.json (schema_version: 1).
  • stores, emitters, author_unknown, and backups fail closed: every section carries state, reason, and inputs[]; measured sections use an empty reason, while unmeasurable sections require a non-silent one and no numeric output.
  • Run the producer with brainlayer observability --write; check fixture drift with python3 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-worker sub-agents, and session-miner / weave workflow 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_DENYLIST remains 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_DENYLIST is now () — the wf_* blanket is gone, and exclusion is decided by class from each transcript's own attributionAgent (MEMORY_READER_ATTRIBUTIONS = {brain-worker, session-miner, weave}). Ordinary workflow agents ingest. Landed by 5c0dfc52 and follow-ups. Path shape is not fully gone: memory_reader_attribution still walks the path components under subagents/ 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-miner and weave are not detectable today, and the code cannot invent them. A census of 2,793 real agent-*.meta.json sidecars under ~/.claude/projects (2026-09-05) found brain-worker 60 times and session-miner/weave zero times: every workflow agent is written as the generic workflow-subagent (2,288) or general-purpose (8), and no transcript field carries the workflow agent's own role. Both names stay in MEMORY_READER_ATTRIBUTIONS so the ruling holds the moment a harness ever labels them; until then only brain-worker actually fires. Matching on task text is not a substitute and is forbidden — a lead session discussing session-miner is ordinary memory.
  • ⚠️ BRAINLAYER_INGEST_DENYLIST REPLACES the class rule; it does not add to it. is_denylisted skips the whole attribution branch whenever the variable is present at all (BRAINLAYER_INGEST_DENYLIST_ENV not in os.environ and ...). So any override — even a project-scoped one naming a single repo — turns OFF brain-worker/session-miner/weave exclusion, and those transcripts start ingesting. Verified by execution 2026-09-05: with the deployed matchmat-shaped override set, a brain-worker transcript returns is_denylisted == False. A quiet setup therefore means "no over-exclusion", never "the class rule is intact".
  • brainlayer setup reads 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 against os.environ alone would have stayed silent on the very defect it exists to catch. env_file_denylist_patterns() parses the resolved file (including --env-file), and setup reports each source separately: that the override replaces 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.py from src/brainlayer/watcher_bridge.py before chunk persistence. Provider-prefixed and labeled high-entropy secrets are redacted; unlabeled high-entropy tokens are recorded in quarantine metadata.
  • Scrub before any cloud LLM, and scrub what comes back. src/brainlayer/pipeline/cloud_scrub.py is the one chokepoint: every remote-LLM send passes scrub_for_cloud (Gemini realtime/batch, Groq enrichment/NER, digest, eval senders), and every LLM output field passes scrub_llm_output before it is persisted (parse_enrichment, update_enrichment, the queue drain, session enrichments). Both fail closed: a scrub that raises means nothing is sent or written. A new cloud caller that skips it is a leak — the PII Sanitizer does not look for credentials.
  • MCP search uses a fixed-size readonly WAL VectorStore pool in src/brainlayer/mcp/_shared.py. BRAINLAYER_READ_POOL_SIZE defaults to 8, or 4 on detected Apple M1; M1 machines can keep the lower override explicitly. Checkout beyond the fixed pool blocks up to BRAINLAYER_READ_BUSY_TIMEOUT_MS, and startup rejects pool_size * BRAINLAYER_READ_CACHE_KB above 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: enrichment_controller.enrich_realtime uses Gemini only; BRAINLAYER_ENRICH_BACKEND selects the separate pipeline/enrichment.py backend -->

Enrichment

  • enrichment_controller.enrich_realtime uses Gemini 2.5 Flash-Lite through _get_gemini_client; it does not read BRAINLAYER_ENRICH_BACKEND or fall back to Groq/Ollama. enrich_single also uses Gemini.
  • The separate pipeline/enrichment.py backend selection reads BRAINLAYER_ENRICH_BACKEND; do not infer that it changes the realtime path.
  • Realtime rate is configurable via BRAINLAYER_ENRICH_RATE (default 5.0 req/s = 300 RPM; see enrichment_controller.py:RATE_LIMITS).
  • Operational state at the 2026-09-23 P0 handoff: enrichment is deliberately paused. This release metadata change does not resume it.
  • Adds 15 metadata fields (summary, key_facts, tags, importance, intent, primary_symbols, resolved_queries, epistemic_level, version_scope, debt_impact, external_deps, entities, sentiment_label, sentiment_score, sentiment_signals); session enrichment captures decisions/corrections
<!-- MCP-SERVERS: agent MCP is BrainBar on /tmp/brainbar.sock (brainlayer-mcp-stdio-bridge, or socat STDIO UNIX-CONNECT); brainlayer-mcp Python entrypoint DELETED; no HTTP daemon API; library handlers live under mcp/; 17 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/items routes were removed. Anything still calling them is calling a surface that is gone.
  • MCP tools: 17, defined in brain-bar/Sources/BrainBar/MCPRouter.swift — see MCP Tools above for the core/gated split. Legacy brainlayer_* names are still handled by the Python library handlers under src/brainlayer/mcp/, but BrainBar does not serve them.
  • brain_expand and brain_tags are deprecated in the Python MCP path and return errors there; the BrainBar path serves both normally.
  • MCP server: BrainBar on /tmp/brainbar.sock only. Preferred wiring is {"command":"brainlayer-mcp-stdio-bridge"} (ships with the package, reconnects across BrainBar restarts, needs nothing else on PATH); {"command":"socat","args":["STDIO","UNIX-CONNECT:/tmp/brainbar.sock"]} also works. The Python brainlayer-mcp entrypoint is deleted. brainlayer setup --migrate-mcp rewrites owned legacy configs to the socat form and leaves existing bridge entries in place.
<!-- COMMANDS: `brainlayer brain-export` → graph JSON for dashboard | `brainlayer export-obsidian` → Markdown vault with backlinks + tags -->

Exports

  • brainlayer brain-export -> graph JSON for dashboard
  • brainlayer 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-watcher dataset
  • Liveness: read watcher-health.json, not a log stream. It is the canonical surface, it is JSON, and both poll_count and updated_at advance on every poll — which is what a sampler needs. Its path is database-relative (watcher-health.json beside the resolved DB), so with BRAINLAYER_DB set it is NOT under ~/.local/share/brainlayer — ~/.local/share/brainlayer/watcher-health.json is only the canonical-DB default. The startup banner prints the path it actually used; BRAINLAYER_WATCHER_HEALTH_PATH overrides 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 the Watcher alive: … heartbeat: brainlayer watch calls logging.basicConfig(stream=sys.stderr) (#759). The poll clamp appears in both — enforce_min_poll_interval() logs it at WARNING to stderr and the command also rprints it to stdout. So grepping watch.out.log for "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::TestWatcherLivenessSurface pins all three halves.
  • 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_at on chunks table
  • Default search excludes lifecycle-managed chunks; include_archived=True shows history
  • brain_supersede: safety gate for personal data (journals, notes, health/finance)
  • brain_archive: soft-delete with timestamp
  • brain_store gains supersedes param 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 the settings.json command AND in the script's shebang. BRAINLAYER_HOOK_PYTHON is the only override, and it must exist.
  • Why: bare python3 on the M4 fronts the framework python, whose site-packages/_brainlayer.pth injects ~/Gits/brainlayer/src — a live checkout any agent can move with one git 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.py resolves it and refuses a silent PATH fallback (same fail-closed stance as scripts/launchd/install.sh). Lint a settings file by hand with python -m brainlayer.hook_python ~/.claude/settings.json; tests/test_hook_python.py fails on any bare python3/env python3 shebang 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 whose site-packages is where a global .pth lives (/usr/bin, /usr/local/bin, /opt/homebrew/bin, any Python.framework) — naming the framework python absolutely closes the PATH hazard and leaves the .pth hazard open, so it is still not an acceptable pin. is_pinned_interpreter = the gate both feed.
  • BRAINLAYER_HOOK_PYTHON is 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> from settings.json, which overrides the shebang entirely; the shebang only decides what happens when a script is run directly (today only hooks/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 is render_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/brainlayer.sock | lock=/tmp/brainlayer-enrichment.lock -->

Data & Locks

  • Backups use the BrainLayer-owned ~/.config/brainlayer/drive-tokens.json (0600); the Google Drive MCP token is a one-time copy source only.
  • Run brainlayer backup auth to authorize in the browser; BrainBar uses brainlayer backup auth --status --json and brainlayer backup auth --json.
  • BRAINLAYER_DRIVE_TOKEN_PATH and BRAINLAYER_DRIVE_CLIENT_PATH override 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.log with backup_log_provenance=real; pytest sets BRAINLAYER_BACKUP_LOG_PATH and BRAINLAYER_BACKUP_LOG_PROVENANCE=pytest so 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} by 3dca26a2, 2026-05-18; the old files are frozen at that date and are NOT a health signal)
  • Socket: /tmp/brainlayer.sock
  • Enrichment lock: /tmp/brainlayer-enrichment.lock
  • Session dedup: /tmp/brainlayer_session_*.json
<!-- ANTI-PATTERNS: never run bulk ops while enrichment is writing; never delete from chunks while FTS trigger active on large datasets; always stop workers + checkpoint WAL first -->

Bulk DB Operations (SAFETY)

  1. Stop enrichment workers first — never run bulk ops while enrichment is writing (causes WAL bloat + potential freeze)
  2. Checkpoint WAL before and after: PRAGMA wal_checkpoint(FULL)
  3. Batch deletes in 5-10K chunks, checkpoint every 3 batches

Memory Tools

  • Always brain_search before answering questions about project history, architecture, or past decisions
  • brain_store after 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: project is 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.)

Download now (ZIP)

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
What did you use it for? e.g. Reviewing pull requests in a Rails app

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.