agentleFS
EtanHeyEtanHey/brainlayer/AGENTS.md

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.

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
  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 83
  6. Very specific:

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

    line 107
  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 110
  8. Distinctive:

    Do not route mandatory reviews to Bugbot or Greptile.

    line 119
  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:

    Stop-hook source='realtime' rows exist for every session and never count.

    line 376
  13. Very specific:

    Default search excludes lifecycle-managed chunks.

    line 401
  14. 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 414
  15. Very specific:

    Run brainlayer backup auth to authorize in the browser.

    line 455
  16. Distinctive:

    Read that before tailing anything.

    line 468
  17. Very specific:

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

    line 488
  18. Very specific:

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

    line 492
  19. Distinctive:

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

    line 494

≈ “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.

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), 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_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

  • Bulky local build, extract, QA and pytest output lives inside <repo-or-worktree>/.build.noindex/ (pytest under pytest/) 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 retain dist/BrainBar.app and $RUNNER_TEMP. Worktree archiving must exclude .build.noindex/, *.app and binaries over 1 MiB.
  • Run pytest before claiming behavior changed safely.
  • Suite size measured 2026-11-11: 12,620 Python tests (pytest tests/ --collect-only -q) + 1,609 Swift func test declarations 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

  • 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_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/, 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 under mcp/
  • 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 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"
  • 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: 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.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 adds 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 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 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.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.
  • 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 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: 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/items routes 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. 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":"/opt/homebrew/opt/brainlayer/bin/brainlayer-mcp-stdio-bridge"} (ships with the package, reconnects across BrainBar restarts, uses a stable opt path). Raw socat STDIO UNIX-CONNECT:/tmp/brainbar.sock exits on a BrainBar restart and leaves persistent clients with a closed transport; brainlayer doctor reports that risk with the config path. The Python brainlayer-mcp entrypoint is deleted. brainlayer setup --migrate-mcp backs 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 drop MCPLAYER_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.json can 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 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.
  • 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>.jsonl was 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 a source_end_offset; read-only, cached per poll, fail-closed). Stop-hook source='realtime' rows exist for every session and never count. Otherwise the copies ingest as before. Skipped copies are neutral lines and do not count toward max_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 within BRAINLAYER_T3_LINKAGE_HOLD_S (default 24 h). Past it, the flush indexes it with provenance_class = 't3-unlinked' and confirms it normally. Evidence for the window (2026-11-19): 0 of 87 M4 sessions that ever raised t3_runtime_linkage_pending were linked later, and no linked session ever raised it. Inside the window, the READ held bytes are catch_up.held_for_linkage {files, bytes, oldest_age_s, window_s} in watcher-health.json, never lag. Unread bytes and holds past the window stay lag (offset_lag, red as before). A late link: new entries are t3-app-session at once; already-indexed rows are relabelled in place by scripts/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_progress confirms 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_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/brainbar.sock | lock=/tmp/brainlayer-enrichment.lock -->

Data & Locks

  • Disk-space truth: use only brainlayer disk --json (--path P selects a volume). On macOS, df free 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 in source; 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 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 — #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: its JSONL watcher started: line and watcher-health.json → log_destinations name 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_total in watcher-health.json counts confirmed deletions (lstat ENOENT), which never raise watcher_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.json entry carries a fingerprint (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)

  1. 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.
  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.)

Local JSONL retention

  • Each sweep adds at most one reporting row: local_retention_summary, with a kept list of archives held past the retention period (name, bytes, first_reason, nullable eligible_at) and totals for held/young bytes and the next age-eligible bytes/date. Reporting rows have no run-result fields or error, 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/false disables 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-only BRAINLAYER_JSONL_BACKUP_RETENTION remains opt-in, latest 30. Scratch proof: formal/jsonl-retention/check.sh, tests/test_jsonl_local_retention.py, tests/test_jsonl_retention_r2.py.

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.