Reference¶
Contract lookup for Brain Framework (bf), bf.yaml (version: 20), CLI commands, exit codes, runtime layout, and published JSON Schemas. Run bf <command> --help for full option descriptions on any command.
- Brain discovery:
--brain PATH->BF_BRAIN-> nearest enclosingbf.yaml->~/brain(zero global config;--brainand--no-colorwork before or after any subcommand except--brainoninitandschema). - Output streams: Commands write one compact UTF-8 JSON object containing
"ok"tostdout(except--version,--help,schema,--format text|jsonl|raw,status --watch, and livewatch) and single-linebf: ...diagnostics tostderr.
CLI commands¶
Read-only commands (never mutate disk)¶
| Command | Purpose | Key flags |
|---|---|---|
bf --version |
Print installed package version | |
bf status |
Health overview, counts, unbuilt notes, orphans, and attention loops | --loops, --check, --watch [SECONDS], --format json\|text |
bf review |
Stale notes (newer_evidence, due, future_updated) and open task count |
--ref REF (repeatable), -n/--limit N (20), --all, --format json\|jsonl\|text |
bf query [QUERY] |
Ranked BM25 search, structured filters, and backlinks | --kind, -s/--scope, --type, --status, --tag, --since, --links-to, --exclude, --all-sources, -n/--limit, --all, --format json\|jsonl\|text |
bf read TARGET [TARGET ...] |
Read one or more notes, #anchor sections, source:id, aliases, bundle files, or bf:// |
--format json\|raw\|text, --outline, --full, --max-bytes N |
bf check |
Validate bf.yaml, .env, schemas, note sync, memories/, loops, and links |
--only config\|loops\|notes\|memories, -n/--limit N (50), --all, --strict, --format json\|text |
bf events |
Inspect .bf/state/events.jsonl or pending delayed timers |
--since SEQ, --timers, --kind, --source, -n/--limit N (20), --all, --format json\|jsonl\|text |
bf state show LOOP |
Inspect one loop's .bf/state/<loop>.json checkpoint in O(1) (safe mid-run) |
--brain PATH |
bf schema [bf\|record] |
Print bundled Draft 2020-12 JSON Schemas (no brain required) |
Write and execution commands¶
| Command | Purpose | Key flags |
|---|---|---|
bf init PATH |
Scaffold a version: 20 brain, starter note schemas, evals/smoke.py, and cache |
--name NAME, --description TEXT |
bf build |
Incrementally compile Markdown notes into memories/_notes.jsonl and sync cache |
--dry-run |
bf ingest SOURCE |
Validate and atomically write memories/<source>.jsonl, sync cache, emit records.ingested |
--input FILE, --mode upsert\|snapshot, --schema NAME, --allow-removal, --dry-run |
bf run [LOOP ...] |
Execute named/glob, --all, --due, or --failed cycle loops under per-loop locks |
--all, --due, --failed, --dry-run, -- EXTRA_ARGS... |
bf watch |
Supervise daemons, delayed timers, note rebuilds, and pooled cycle loops | --format auto\|live\|text\|jsonl |
bf pause [LOOP ...] |
Mute cycle or daemon loops without editing bf.yaml |
--all, --for DURATION, --dry-run |
bf resume [LOOP ...] |
Unmute paused loops | --all, --dry-run |
bf emit KIND |
Append a custom event or schedule a delayed timer | --source NAME, --data JSON\|-, --in DURATION, --at ISO, --dedupe, --dry-run |
bf state reset [LOOP ...] |
Reset loop state to idle anchored at current event_seq |
--all, --dry-run |
bf state prune |
Delete orphaned .bf/state/, unlocked locks, and logs/ for removed loops |
--dry-run |
Exit codes¶
| Code | Meaning |
|---|---|
0 |
Success ("ok": true, or readable bf status without --check) |
1 |
Validation failure, bf status --check attention, failed loop, missing/corrupt files, schema error, or lock contention |
2 |
Invalid flags, conflicting selectors, running a mode: daemon loop via bf run, TTY stdin on ingest/emit --data -, undeclared bf:// host, or malformed syntax |
130 / 143 |
Interrupted by SIGINT (130) or SIGTERM (143) |
Brain layout¶
| Path | Purpose | Notes |
|---|---|---|
bf.yaml |
Declarative config (version: 20) |
Tracked in Git; 1 MiB limit |
concepts/, projects/, actions/ |
Authored Markdown notes (<slug>.md or <slug>/index.md bundles) |
Configured by notes:; tracked in Git |
sensors/, routines/, agents/ |
Loop scripts (<dir>/<name>{,.sh,.py} zero-arg convention) |
Tracked in Git |
schemas/ |
Optional per-source domain JSON Schemas (<source>.json) |
schemas/record.json is reserved and rejected |
evals/ |
User-owned Python/pytest retrieval and contract checks |
Tracked in Git |
clients/, prompts/ |
Convention-only supporting scripts and prompt templates | Tracked in Git |
memories/ |
Canonical JSONL (_notes.jsonl, <source>.jsonl, <source>.forgotten) |
Gitignored (*.forgotten trackable); created 0700 with 0600 JSONL writes; queryable with rg/jq/DuckDB |
logs/ |
Redacted JSONL loop logs (<loop>.jsonl) |
Private 0700 dir, 0600 files; gitignored; excluded from search/links |
.env |
Optional local secret source for env_from: |
Private 0600 file; gitignored; 64 KiB limit |
.bf/ |
Private 0700 runtime (cache/index.sqlite3, state/<loop>.json, state/<loop>/, state/events.jsonl, state/timers.jsonl, watch.lock, write.lock, logs.lock, corpus.lock, locks/loop-*.lock, locks/source-*.lock) |
Gitignored; only .bf/cache/ is disposable |
Authoring and retrieval contracts¶
- YAML 1.2 frontmatter: Anchors and aliases are rejected;
on,off, andnoremain strings. Dates accept calendarYYYY-MM-DDor ISO 8601 timestamps with timezone. Computed keys (id,ref,source,kind,text,headings,tasks,sha256,ingested_at) are rejected in frontmatter. - Headings, tasks, and links: Both ATX and Setext headings use one exact CommonMark AST line map (blockquotes are ignored). Checklist items (
- [ ],- [x]) populatetasks[]({text, done, section, meta}) and ignore inline code spans. Links normalize to{to, kind, anchor, meta}acrossnote,record,brain, andurl. - Link confinement: Same-brain authored notes may reference tracked non-private brain files outside
logs/,memories/,usages/, and private dotfiles (.bf,.git,.env/.env.*other than.env.{example,sample,template},.private*,*.local*, secret/key files);bf read, ingested records, and cross-brainbf://<host>/...links stay confined to configurednotes:folders without dotfiles. Record IDs forbid#, non-URL?, and whitespace; schemes with://other thanhttps,http, orbfare rejected. bf readenvelopes: Single target returns{"ok": true, "brain", "kind", "ref", "path", ...}withrecord(kind: "note"|"memory"),anchor/heading/textplus parentstatus/updated/created(kind: "section"),text(kind: "file"for bundle attachments undernotes:), orheadingswith per-sectionlines/bytespluslinks_count/open_tasks(--outline,kind: "outline"). Multiple targets (up to100, deduplicated in order;--format rawrejected) return{"ok", "brain", "count", "found", "missing", "results"}with per-item single-read envelopes or{"ok": false, "target", "error"}(exit1when any target is missing) and----separated--format text. Default JSON omits compiledheadings,links,tasks, andsha256arrays on notes (pass--fullfor the complete compiled record; memory records stay intact).--format textrenders a compact metadata header and sanitized Markdown body on notes and#anchorsections (preserving links, tables, headings, and domain fields on memories), and--format rawstrips unsafe control/bidi/Tag sequences;--max-bytesshrinks heavy fields without dropping therecordkey (ANSI-safe on colored--format text, applied per target in batch reads; warns onstderrwith--format raw|text).- Operational JSON envelopes:
bf checkreturns"scope"("all","config","loops","notes", or"memories") withnullin skippedcounts(warning on unusedschemas/*.json, unused top-levelsearch.exclude, retiredsummary:frontmatter withoutdescription:, hub notes declaringentity:and non-identityaliases:withoutreview_aliases:, and loose permissions onmemories/,.bf/including top-level.bf/*.lock, andlogs/);bf queryreturns compact"excluded_count"(omitted when zero) and note"bytes", appends[status, YYYY-MM-DD](plus~sizeon unanchored notes) in--format text, and restricts emitted#anchorhints tolevel >= 2headings;bf review --ref REFrestricts evaluation to the specified compiled note ref(s) in O(1) via SQLite (including"refs"in JSON and failing closed with exit1if missing);bf statusomits healthy loops in both JSON and--format textunless--loopsis passed, appends(outside)in text mode wheninside_brainisfalse, and with--loopsreturns per-loop"mode", optional"ingest_mode","last_change",last_runcapped at4 KiB, and ordered"reasons"omitted when healthy, paused, or disabled;bf run --dry-runincludes"window", redacted"env_keys", and optional"missing_env_from";bf emitreturns"mode": "event"(with"event") or"mode": "timer"(with"timer"). - Read-only search cache:
.bf/cache/index.sqlite3is an offset-indexed stdlib SQLite FTS5 cache (unicode61accent-folded,2.5xnote boost, hydrated viaos.pread). Read commands open it strictlymode=ro(refusing WAL headers, sidecars, and triggers/views) with automatic per-source JSONL fallback.
Loop environment, placeholders, and event predicates¶
| Env var | Placeholder | Value |
|---|---|---|
BF_BRAIN |
{{brain}} |
Absolute brain root path |
BF_LOOP |
{{loop}} |
Loop name from bf.yaml |
BF_STATE |
{{state}} |
Loop state directory (<brain>/.bf/state/<loop>) |
BF_START |
{{start}} |
Inclusive UTC window start ISO timestamp |
BF_END |
{{end}} |
Exclusive UTC window end ISO timestamp |
BF_TRIGGER |
{{trigger}} |
Trigger kind (manual, schedule, event, daemon) |
BF_RUN |
{{run}} |
Unique run ID (<loop>-<epoch>-<hex>) |
BF_EVENTS_MISSED |
None | Set only when compacted events were skipped while lagging |
| Event feature | Contract |
|---|---|
where: operators |
Dot-path keys evaluated in pure Python: exact scalar (data.direct: true), {in: [...]}, {exists: true\|false}, {prefix: "..."} |
| Built-in events | notes.built (bf build), records.ingested (bf ingest, with bounded added_refs/updated_refs), loop.failed (always emitted), loop.succeeded (emitted only when an enabled loop subscribes to it; every run is still logged to logs/<loop>.jsonl) |
| Event bus | .bf/state/events.jsonl (0600, compacted at 10,000 lines / 16 MiB); new or reset loops anchor at current event_seq; non-matching cursor flushes amortize on a 2,000-event / 4 MiB stride unless a compaction gap or reset occurs |
| Retries and dead-lettering | Event triggers retry 3 times on short backoff before dead-lettering (dead_lettered) without blocking schedules |
| Loop guards | Self-sourced loop.succeeded/loop.failed are suppressed unless source: names the loop; bf watch caps runaway event loops at 10/min |
| Loop execution defaults | Default mode: is cycle, timeout: is 5m, and concurrency: mapping implicitly includes default: 4 when omitted; window: defaults to backfill: 1d, overlap: 0s; ingest: is explicit (ingest.search: include\|exclude) and mutually exclusive with emit: and mode: daemon (which also forbids when:, window:, timeout:, pool:); debounce: supports 1s..1h (max wait 4x); durations require units (30s, 5m, 1h, 7d, 1w; 0/0s valid only on overlap:) |
| Ingestion guards | bf ingest accepts JSONL (with optional {"incomplete": true \| {"missed": N}} trailer; explicit null is rejected), JSON arrays, or {"records": [...], "incomplete": ...} envelopes, honors memories/<source>.forgotten (bare <id> or <source>:<id> per line, ignoring # comments), holds watermarks when incomplete is set (degraded with incomplete_missed in bf status), and blocks emptying a source or dropping >50% of 10+ records without --allow-removal |
Security and runtime rules¶
- Environment precedence: Minimal host allowlist (shell with empty/relative
PATHsegments stripped,LANG/LC_ALLpinned toC.UTF-8, TLS CA/proxy vars,XDG_*dirs) <bf.yamlenv:<loops.<name>.env:<loops.<name>.env_from:(host <0600.env) < protectedBF_*. Setting a key to""inenv:unsets an inherited variable. - Blocked environment prefixes (rejected in
bf.yamlenv:,env_from:, and.env):BF_*,LD_*,DYLD_*,PYTHON*(exceptPYTHONDONTWRITEBYTECODE),UV_*,PIP_*,GIT_*,XDG_*,NPM_CONFIG_*,OPENSSL_*. - Blocked environment keys: shell and locale (
PATH,HOME,SHELL,LANG,LC_ALL,ENV,FPATH,IFS,BASH_ENV,BASHOPTS,SHELLOPTS,PS4,PROMPT_COMMAND,ZDOTDIR), TLS and proxies (SSL_CERT_FILE,SSL_CERT_DIR,SSLKEYLOGFILE,REQUESTS_CA_BUNDLE,CURL_CA_BUNDLE,CURL_HOME,AWS_CA_BUNDLE,GRPC_DEFAULT_SSL_ROOTS_FILE_PATH,NODE_EXTRA_CA_CERTS,NODE_TLS_REJECT_UNAUTHORIZED,HTTP_PROXY,HTTPS_PROXY,ALL_PROXY,NO_PROXY, plus lowercase variants), runtimes (NODE_OPTIONS,NODE_PATH,PERL5OPT,PERL5LIB,PERLLIB,RUBYOPT,RUBYLIB,JAVA_TOOL_OPTIONS,_JAVA_OPTIONS,JDK_JAVA_OPTIONS,CLASSPATH), and loader or askpass (SSH_ASKPASS,SUDO_ASKPASS,GCONV_PATH,GLIBC_TUNABLES). - Process and filesystem isolation: Loops run via literal
argv(shell=False) in isolated process groups (python -P -E -m bffor internal subcommands). Managed files open throughO_NOFOLLOWdescriptors (symlinks rejected), and private directories enforcegeteuid()ownership. - Status and watch bounds:
bf status --watch [SECONDS]defaults to2(range0.5..3600, incompatible with--checkand--format json);bf watch --format autouses a zero-termioslive table on non-dumb TTYs andjsonlwhen piped orTERM=dumb, emitswatch.recoveron success-triggered recovery sweeps (300scooldown) orSIGUSR1(POSIX), and exits143cleanly onSIGTERM.
bf.yaml schema¶
Published at bf.schema.json:
# yaml-language-server: $schema=https://fmind.github.io/brain-framework/bf.schema.json
version: 20
name: my-brain
description: Short description for humans and AI agents.
notes: [concepts, projects, actions]
brains:
team-brain: ../team-brain
search:
exclude: []
timezone: UTC
concurrency: 4
env: {}
loops: {}
Published JSON Schemas¶
bf.schema.json:bf.yamlconfiguration schema (notes,brains,search.exclude,concurrency,env, andloops).record.schema.json: Canonical record schema formemories/_notes.jsonlandmemories/<source>.jsonl.