Skip to content

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 enclosing bf.yaml -> ~/brain (zero global config; --brain and --no-color work before or after any subcommand except --brain on init and schema).
  • Output streams: Commands write one compact UTF-8 JSON object containing "ok" to stdout (except --version, --help, schema, --format text|jsonl|raw, status --watch, and live watch) and single-line bf: ... diagnostics to stderr.

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, and no remain strings. Dates accept calendar YYYY-MM-DD or 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]) populate tasks[] ({text, done, section, meta}) and ignore inline code spans. Links normalize to {to, kind, anchor, meta} across note, record, brain, and url.
  • 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-brain bf://<host>/... links stay confined to configured notes: folders without dotfiles. Record IDs forbid #, non-URL ?, and whitespace; schemes with :// other than https, http, or bf are rejected.
  • bf read envelopes: Single target returns {"ok": true, "brain", "kind", "ref", "path", ...} with record (kind: "note"|"memory"), anchor/heading/text plus parent status/updated/created (kind: "section"), text (kind: "file" for bundle attachments under notes:), or headings with per-section lines/bytes plus links_count/open_tasks (--outline, kind: "outline"). Multiple targets (up to 100, deduplicated in order; --format raw rejected) return {"ok", "brain", "count", "found", "missing", "results"} with per-item single-read envelopes or {"ok": false, "target", "error"} (exit 1 when any target is missing) and ----separated --format text. Default JSON omits compiled headings, links, tasks, and sha256 arrays on notes (pass --full for the complete compiled record; memory records stay intact). --format text renders a compact metadata header and sanitized Markdown body on notes and #anchor sections (preserving links, tables, headings, and domain fields on memories), and --format raw strips unsafe control/bidi/Tag sequences; --max-bytes shrinks heavy fields without dropping the record key (ANSI-safe on colored --format text, applied per target in batch reads; warns on stderr with --format raw|text).
  • Operational JSON envelopes: bf check returns "scope" ("all", "config", "loops", "notes", or "memories") with null in skipped counts (warning on unused schemas/*.json, unused top-level search.exclude, retired summary: frontmatter without description:, hub notes declaring entity: and non-identity aliases: without review_aliases:, and loose permissions on memories/, .bf/ including top-level .bf/*.lock, and logs/); bf query returns compact "excluded_count" (omitted when zero) and note "bytes", appends [status, YYYY-MM-DD] (plus ~size on unanchored notes) in --format text, and restricts emitted #anchor hints to level >= 2 headings; bf review --ref REF restricts evaluation to the specified compiled note ref(s) in O(1) via SQLite (including "refs" in JSON and failing closed with exit 1 if missing); bf status omits healthy loops in both JSON and --format text unless --loops is passed, appends (outside) in text mode when inside_brain is false, and with --loops returns per-loop "mode", optional "ingest_mode", "last_change", last_run capped at 4 KiB, and ordered "reasons" omitted when healthy, paused, or disabled; bf run --dry-run includes "window", redacted "env_keys", and optional "missing_env_from"; bf emit returns "mode": "event" (with "event") or "mode": "timer" (with "timer").
  • Read-only search cache: .bf/cache/index.sqlite3 is an offset-indexed stdlib SQLite FTS5 cache (unicode61 accent-folded, 2.5x note boost, hydrated via os.pread). Read commands open it strictly mode=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 PATH segments stripped, LANG/LC_ALL pinned to C.UTF-8, TLS CA/proxy vars, XDG_* dirs) < bf.yaml env: < loops.<name>.env: < loops.<name>.env_from: (host < 0600 .env) < protected BF_*. Setting a key to "" in env: unsets an inherited variable.
  • Blocked environment prefixes (rejected in bf.yaml env:, env_from:, and .env): BF_*, LD_*, DYLD_*, PYTHON* (except PYTHONDONTWRITEBYTECODE), 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 bf for internal subcommands). Managed files open through O_NOFOLLOW descriptors (symlinks rejected), and private directories enforce geteuid() ownership.
  • Status and watch bounds: bf status --watch [SECONDS] defaults to 2 (range 0.5..3600, incompatible with --check and --format json); bf watch --format auto uses a zero-termios live table on non-dumb TTYs and jsonl when piped or TERM=dumb, emits watch.recover on success-triggered recovery sweeps (300s cooldown) or SIGUSR1 (POSIX), and exits 143 cleanly on SIGTERM.

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.yaml configuration schema (notes, brains, search.exclude, concurrency, env, and loops).
  • record.schema.json: Canonical record schema for memories/_notes.jsonl and memories/<source>.jsonl.