brain-framework 33.1.0__tar.gz → 33.2.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (34) hide show
  1. {brain_framework-33.1.0 → brain_framework-33.2.1}/PKG-INFO +2 -2
  2. {brain_framework-33.1.0 → brain_framework-33.2.1}/README.md +1 -1
  3. {brain_framework-33.1.0 → brain_framework-33.2.1}/pyproject.toml +1 -1
  4. {brain_framework-33.1.0 → brain_framework-33.2.1}/pyproject.toml.orig +1 -1
  5. {brain_framework-33.1.0 → brain_framework-33.2.1}/src/bf/__init__.py +1 -1
  6. {brain_framework-33.1.0 → brain_framework-33.2.1}/src/bf/cli.py +72 -126
  7. {brain_framework-33.1.0 → brain_framework-33.2.1}/src/bf/config.py +36 -30
  8. {brain_framework-33.1.0 → brain_framework-33.2.1}/src/bf/engine.py +12 -35
  9. {brain_framework-33.1.0 → brain_framework-33.2.1}/src/bf/guides/operations.md +1 -1
  10. {brain_framework-33.1.0 → brain_framework-33.2.1}/src/bf/guides/reference.md +1 -1
  11. {brain_framework-33.1.0 → brain_framework-33.2.1}/src/bf/loops.py +4 -2
  12. {brain_framework-33.1.0 → brain_framework-33.2.1}/src/bf/models.py +2 -18
  13. {brain_framework-33.1.0 → brain_framework-33.2.1}/src/bf/proc.py +8 -11
  14. {brain_framework-33.1.0 → brain_framework-33.2.1}/src/bf/query.py +7 -26
  15. {brain_framework-33.1.0 → brain_framework-33.2.1}/src/bf/records.py +5 -17
  16. {brain_framework-33.1.0 → brain_framework-33.2.1}/src/bf/schemas.py +27 -32
  17. brain_framework-33.2.1/src/bf/status.py +425 -0
  18. {brain_framework-33.1.0 → brain_framework-33.2.1}/src/bf/watch.py +209 -143
  19. brain_framework-33.1.0/src/bf/status.py +0 -313
  20. {brain_framework-33.1.0 → brain_framework-33.2.1}/LICENSE +0 -0
  21. {brain_framework-33.1.0 → brain_framework-33.2.1}/THIRD_PARTY_NOTICES.md +0 -0
  22. {brain_framework-33.1.0 → brain_framework-33.2.1}/src/bf/__main__.py +0 -0
  23. {brain_framework-33.1.0 → brain_framework-33.2.1}/src/bf/guides/authoring.md +0 -0
  24. {brain_framework-33.1.0 → brain_framework-33.2.1}/src/bf/guides/getting-started.md +0 -0
  25. {brain_framework-33.1.0 → brain_framework-33.2.1}/src/bf/guides/index.md +0 -0
  26. {brain_framework-33.1.0 → brain_framework-33.2.1}/src/bf/guides/retrieval.md +0 -0
  27. {brain_framework-33.1.0 → brain_framework-33.2.1}/src/bf/markdown.py +0 -0
  28. {brain_framework-33.1.0 → brain_framework-33.2.1}/src/bf/py.typed +0 -0
  29. {brain_framework-33.1.0 → brain_framework-33.2.1}/src/bf/skills/bf/SKILL.md +0 -0
  30. {brain_framework-33.1.0 → brain_framework-33.2.1}/src/bf/starter/AGENTS.md +0 -0
  31. {brain_framework-33.1.0 → brain_framework-33.2.1}/src/bf/starter/concepts/welcome.md +0 -0
  32. {brain_framework-33.1.0 → brain_framework-33.2.1}/src/bf/starter/evals/smoke.py +0 -0
  33. {brain_framework-33.1.0 → brain_framework-33.2.1}/src/bf/starter/gitignore +0 -0
  34. {brain_framework-33.1.0 → brain_framework-33.2.1}/src/bf/storage.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: brain-framework
3
- Version: 33.1.0
3
+ Version: 33.2.1
4
4
  Summary: Brain Framework is a local-first brain for you and your AI agents. It compiles OKF Markdown notes into JSONL records, enforces required per-source JSON Schemas, orchestrates convention loops, and queries offline with rg, jq, and DuckDB.
5
5
  Keywords: ai,ai-agents,agent-memory,agent-skills,agents-md,context-engineering,json,json-schema,knowledge-graph,knowledge-management,local-first,personal-knowledge-management,python,second-brain
6
6
  Author: Médéric Hurier
@@ -73,7 +73,7 @@ Explore the [four-tool walkthrough](https://github.com/fmind/brain-framework/blo
73
73
  </a>
74
74
 
75
75
  - **Uniform notes, `index.md` bundles, & required schemas ([Authoring](https://fmind.github.io/brain-framework/authoring/)):** Organize Markdown across `concepts/`, `projects/`, `actions/` (or custom `notes:` dirs) using flat `<slug>.md` files or universal `<slug>/index.md` bundles, enforce bundled `record` + `schemas/<source>.json` / `schemas/usages.json`, attach `#id` heading anchors and `{rel=...}` link metadata, and link across notes, records (`source:id`), or declared sibling brains (`bf://`).
76
- - **Convention `loops:` (`sensors/`, `routines/`, `agents/`), two-stream JSONL, & `bf watch` ([Operations](https://fmind.github.io/brain-framework/operations/)):** Drop shell (`.sh`), Python (`.py`), or executable scripts in `sensors/` (auto-implies `ingest: upsert`), `routines/`, or `agents/` (15m default timeout), stream structured JSONL logs on `stderr` into `logs/<loop>.jsonl`, coordinate over `logs/events.jsonl`, and supervise with `bf watch` (bird's-eye status + live text or `--format jsonl`).
76
+ - **Convention `loops:` (`sensors/`, `routines/`, `agents/`), two-stream JSONL, & `bf watch` ([Operations](https://fmind.github.io/brain-framework/operations/)):** Drop shell (`.sh`), Python (`.py`), or executable scripts in `sensors/` (auto-implies `ingest: upsert`), `routines/`, or `agents/` (15m default timeout), stream structured JSONL logs on `stderr` into `logs/<loop>.jsonl`, coordinate over `logs/events.jsonl`, and supervise with `bf watch` (interactive zero-dep ANSI dashboard on TTY, `--format text`, or `--format jsonl`).
77
77
  - **Strictly read-only retrieval & FinOps separation ([Retrieval](https://fmind.github.io/brain-framework/retrieval/)):** Resolve notes, `#anchor` sections, `source:id` records, or `bf://` URIs uniformly with `bf read`, search `memories/*.jsonl` or `usages/*.jsonl` via `bf query` (`rg`/`jq`) or DuckDB, and inspect live health with `bf status --format text`.
78
78
  - **Integrity, freshness, & schemas ([Reference](https://fmind.github.io/brain-framework/reference/)):** `bf check` validates `bf.yaml`, schemas, compiled-note sync, `memories/` & `usages/`, enabled `loops:`, links, `#anchor` headings, and declared cross-brain `bf://` refs; `bf review` surfaces `newer_evidence`, overdue `stale_after` notes, and open tasks; `bf schema` prints the 2 bundled Draft 2020-12 JSON Schemas (`bf`, `record`).
79
79
 
@@ -41,7 +41,7 @@ Explore the [four-tool walkthrough](https://github.com/fmind/brain-framework/blo
41
41
  </a>
42
42
 
43
43
  - **Uniform notes, `index.md` bundles, & required schemas ([Authoring](https://fmind.github.io/brain-framework/authoring/)):** Organize Markdown across `concepts/`, `projects/`, `actions/` (or custom `notes:` dirs) using flat `<slug>.md` files or universal `<slug>/index.md` bundles, enforce bundled `record` + `schemas/<source>.json` / `schemas/usages.json`, attach `#id` heading anchors and `{rel=...}` link metadata, and link across notes, records (`source:id`), or declared sibling brains (`bf://`).
44
- - **Convention `loops:` (`sensors/`, `routines/`, `agents/`), two-stream JSONL, & `bf watch` ([Operations](https://fmind.github.io/brain-framework/operations/)):** Drop shell (`.sh`), Python (`.py`), or executable scripts in `sensors/` (auto-implies `ingest: upsert`), `routines/`, or `agents/` (15m default timeout), stream structured JSONL logs on `stderr` into `logs/<loop>.jsonl`, coordinate over `logs/events.jsonl`, and supervise with `bf watch` (bird's-eye status + live text or `--format jsonl`).
44
+ - **Convention `loops:` (`sensors/`, `routines/`, `agents/`), two-stream JSONL, & `bf watch` ([Operations](https://fmind.github.io/brain-framework/operations/)):** Drop shell (`.sh`), Python (`.py`), or executable scripts in `sensors/` (auto-implies `ingest: upsert`), `routines/`, or `agents/` (15m default timeout), stream structured JSONL logs on `stderr` into `logs/<loop>.jsonl`, coordinate over `logs/events.jsonl`, and supervise with `bf watch` (interactive zero-dep ANSI dashboard on TTY, `--format text`, or `--format jsonl`).
45
45
  - **Strictly read-only retrieval & FinOps separation ([Retrieval](https://fmind.github.io/brain-framework/retrieval/)):** Resolve notes, `#anchor` sections, `source:id` records, or `bf://` URIs uniformly with `bf read`, search `memories/*.jsonl` or `usages/*.jsonl` via `bf query` (`rg`/`jq`) or DuckDB, and inspect live health with `bf status --format text`.
46
46
  - **Integrity, freshness, & schemas ([Reference](https://fmind.github.io/brain-framework/reference/)):** `bf check` validates `bf.yaml`, schemas, compiled-note sync, `memories/` & `usages/`, enabled `loops:`, links, `#anchor` headings, and declared cross-brain `bf://` refs; `bf review` surfaces `newer_evidence`, overdue `stale_after` notes, and open tasks; `bf schema` prints the 2 bundled Draft 2020-12 JSON Schemas (`bf`, `record`).
47
47
 
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "brain-framework"
3
- version = "33.1.0"
3
+ version = "33.2.1"
4
4
  description = "Brain Framework is a local-first brain for you and your AI agents. It compiles OKF Markdown notes into JSONL records, enforces required per-source JSON Schemas, orchestrates convention loops, and queries offline with rg, jq, and DuckDB."
5
5
  readme = "README.md"
6
6
  requires-python = ">=3.14"
@@ -1,7 +1,7 @@
1
1
  # https://packaging.python.org/en/latest/specifications/pyproject-toml/
2
2
  [project]
3
3
  name = "brain-framework"
4
- version = "33.1.0"
4
+ version = "33.2.1"
5
5
  description = "Brain Framework is a local-first brain for you and your AI agents. It compiles OKF Markdown notes into JSONL records, enforces required per-source JSON Schemas, orchestrates convention loops, and queries offline with rg, jq, and DuckDB."
6
6
  readme = "README.md"
7
7
  requires-python = ">=3.14"
@@ -3,7 +3,7 @@
3
3
  import os
4
4
  import sys
5
5
 
6
- __version__ = "33.1.0"
6
+ __version__ = "33.2.1"
7
7
 
8
8
 
9
9
  def main() -> None:
@@ -61,112 +61,72 @@ def _build_parser() -> _Parser:
61
61
  sp.add_argument("path", type=Path, help="Target directory (new or empty).")
62
62
  sp.add_argument("--name", default=None, help="Brain identifier (lowercase letters, digits, hyphens).")
63
63
  sp.add_argument("--description", default="", help="Short brain description written to bf.yaml.")
64
-
65
64
  cmd("build", "Compile Markdown notes into memories/<dir>.jsonl.")
66
-
67
- sp = cmd(
68
- "ingest",
69
- "Validate and save JSON/JSONL records into memories/<source>.jsonl or usages/<source>.jsonl.",
70
- epilog="Example: sensors/github.sh | bf ingest github-issues --mode upsert",
71
- )
72
- sp.add_argument("source", help="Source name (requires schemas/<source>.json or schemas/usages.json).")
73
- sp.add_argument(
74
- "--to", dest="target", choices=("memories", "usages"), default="memories", help="Target record dir."
75
- )
76
- sp.add_argument("--input", default="-", metavar="FILE", help="Input JSON/JSONL file path or '-' for stdin.")
77
- sp.add_argument("--mode", choices=("upsert", "snapshot"), default="upsert", help="Write mode (default: upsert).")
78
- sp.add_argument("--allow-removal", action="store_true", help="Allow snapshot to empty/drop >50%% of 10+ records.")
79
- sp.add_argument("--dry-run", action="store_true", help="Validate and preview counts without writing files.")
80
-
81
- sp = cmd(
82
- "read",
83
- "Read a note, #anchor section, source:id record, alias, or bf:// URI (read-only).",
84
- epilog="Example: bf read concepts/welcome.md#conventions",
85
- )
86
- sp.add_argument("target", help="Note path, note#anchor, source:id, alias, or bf:// URI.")
87
- sp.add_argument("--raw", action="store_true", help="Return raw Markdown or file text wrapped in JSON .text.")
88
- sp.add_argument("--max-bytes", type=int, default=None, metavar="N", help="Maximum UTF-8 JSON response size.")
89
-
90
- sp = cmd(
91
- "query",
92
- "Search and filter memories/*.jsonl (or usages/*.jsonl) via rg and jq (read-only).",
93
- epilog="Example: bf query 'retention' --kind note --format jsonl",
94
- )
95
- sp.add_argument("pattern", nargs="?", default=None, help="ripgrep regex pattern (optional with --jq or filters).")
96
- sp.add_argument("--jq", default=None, metavar="EXPR", help="Isolated jq filter expression.")
97
- sp.add_argument("--kind", choices=("note", "memory", "usage"), default="", help="Filter by record kind.")
98
- sp.add_argument(
99
- "-s", "--scope", default="", metavar="PATH", help="Restrict to a note, source, memories/, or usages/."
100
- )
101
- sp.add_argument("-n", "--limit", type=int, default=20, metavar="N", help="Max results (1..5000, default: 20).")
102
- sp.add_argument("--format", choices=("json", "jsonl"), default="json", help="Output format (default: json).")
65
+ ing_h = "Validate and save JSON/JSONL records into memories/<source>.jsonl or usages/<source>.jsonl."
66
+ sp = cmd("ingest", ing_h, epilog="Example: sensors/github.sh | bf ingest github-issues --mode upsert")
67
+ a = sp.add_argument
68
+ a("source", help="Source name (requires schemas/<source>.json or schemas/usages.json).")
69
+ a("--to", dest="target", choices=("memories", "usages"), default="memories", help="Target record dir.")
70
+ a("--input", default="-", metavar="FILE", help="Input JSON/JSONL file path or '-' for stdin.")
71
+ a("--mode", choices=("upsert", "snapshot"), default="upsert", help="Write mode (default: upsert).")
72
+ a("--allow-removal", action="store_true", help="Allow snapshot to empty/drop >50%% of 10+ records.")
73
+ a("--dry-run", action="store_true", help="Validate and preview counts without writing files.")
74
+ read_h = "Read a note, #anchor section, source:id record, alias, or bf:// URI (read-only)."
75
+ sp = cmd("read", read_h, epilog="Example: bf read concepts/welcome.md#conventions")
76
+ a = sp.add_argument
77
+ a("target", help="Note path, note#anchor, source:id, alias, or bf:// URI.")
78
+ a("--raw", action="store_true", help="Return raw Markdown or file text wrapped in JSON .text.")
79
+ a("--max-bytes", type=int, default=None, metavar="N", help="Maximum UTF-8 JSON response size.")
80
+ q_h = "Search and filter memories/*.jsonl (or usages/*.jsonl) via rg and jq (read-only)."
81
+ sp = cmd("query", q_h, epilog="Example: bf query 'retention' --kind note --format jsonl")
82
+ a = sp.add_argument
83
+ a("pattern", nargs="?", default=None, help="ripgrep regex pattern (optional with --jq or filters).")
84
+ a("--jq", default=None, metavar="EXPR", help="Isolated jq filter expression.")
85
+ a("--kind", choices=("note", "memory", "usage"), default="", help="Filter by record kind.")
86
+ a("-s", "--scope", default="", metavar="PATH", help="Restrict to a note, source, memories/, or usages/.")
87
+ a("-n", "--limit", type=int, default=20, metavar="N", help="Max results (1..5000, default: 20).")
88
+ a("--format", choices=("json", "jsonl"), default="json", help="Output format (default: json).")
89
+
90
+ def add_lim(sp: _Parser, dest: str, default_n: int, what: str) -> None:
91
+ grp = sp.add_mutually_exclusive_group()
92
+ grp.add_argument("-n", "--limit", type=int, default=None, metavar="N", help=f"Max {what} ({default_n}).")
93
+ grp.add_argument("--all", dest=dest, action="store_true", help=f"Return all {what}.")
103
94
 
104
95
  sp = cmd("review", "Review stale notes, newer linked evidence, and open tasks (read-only).")
105
- rv_lim = sp.add_mutually_exclusive_group()
106
- rv_lim.add_argument("-n", "--limit", type=int, default=None, metavar="N", help="Max stale items (default: 20).")
107
- rv_lim.add_argument("--all", dest="all_items", action="store_true", help="Return all stale notes.")
108
- sp.add_argument(
109
- "--format", choices=("json", "jsonl", "text"), default="json", help="Output format (default: json)."
110
- )
111
-
96
+ add_lim(sp, "all_items", 20, "stale items")
97
+ sp.add_argument("--format", choices=("json", "jsonl", "text"), default="json", help="Output format.")
112
98
  sp = cmd("check", "Validate bf.yaml, schemas, notes, JSONL records, loops, and links (read-only).")
113
- ck_lim = sp.add_mutually_exclusive_group()
114
- ck_lim.add_argument("-n", "--limit", type=int, default=None, metavar="N", help="Max problems (default: 50).")
115
- ck_lim.add_argument(
116
- "--all", dest="all_problems", action="store_true", help="Return all problems without truncation."
117
- )
118
- sp.add_argument(
119
- "--notes",
120
- action="store_true",
121
- help="Validate config, schemas, loops, notes, and note links without validating sensor/usage JSONL.",
122
- )
123
- sp.add_argument(
124
- "--strict", action="store_true", help="Fail validation on warnings (snapshot or forgotten targets)."
125
- )
126
- sp.add_argument("--format", choices=("json", "text"), default="json", help="Output format (default: json).")
127
-
99
+ add_lim(sp, "all_problems", 50, "problems")
100
+ a = sp.add_argument
101
+ a("--notes", action="store_true", help="Validate config, schemas, loops, notes, and note links only.")
102
+ a("--strict", action="store_true", help="Fail validation on warnings (snapshot or forgotten targets).")
103
+ a("--format", choices=("json", "text"), default="json", help="Output format (default: json).")
128
104
  sp = cmd("schema", "Print bundled Draft 2020-12 JSON Schemas.", with_brain=False)
129
105
  sp.add_argument("name", nargs="?", default=None, help="Schema name: bf or record.")
130
-
131
- sp = cmd(
132
- "run",
133
- "Execute named/glob, --all, or --due loops, reset loop state, or prune orphaned .bf/ state.",
134
- epilog="Pass extra args to one loop with `--`: bf run my-loop -- --verbose",
135
- )
136
- sp.add_argument("loops", nargs="*", help="Loop names or glob patterns to run sequentially (or reset with --reset).")
106
+ run_h = "Execute named/glob, --all, or --due loops, reset loop state, or prune orphaned .bf/ state."
107
+ sp = cmd("run", run_h, epilog="Pass extra args to one loop with `--`: bf run my-loop -- --verbose")
108
+ sp.add_argument("loops", nargs="*", help="Loop names or glob patterns to run sequentially (or reset).")
137
109
  rgrp = sp.add_mutually_exclusive_group()
138
110
  rgrp.add_argument("--due", action="store_true", help="Rebuild notes and run scheduled/event-triggered loops.")
139
111
  rgrp.add_argument("--all", dest="all_loops", action="store_true", help="Run all enabled cycle loops.")
140
112
  rgrp.add_argument("--reset", action="store_true", help="Reset .bf/<loop>.json state for named loops to idle.")
141
113
  rgrp.add_argument("--prune", action="store_true", help="Remove orphaned .bf/<loop>.json state files.")
142
- sp.add_argument(
143
- "--dry-run", action="store_true", help="Validate and preview actions without executing or deleting."
144
- )
145
-
146
- sp = cmd(
147
- "emit",
148
- "Append a custom event to logs/events.jsonl.",
149
- epilog='Example: echo \'{"id":"1"}\' | bf emit task.ready --data -',
150
- )
151
- sp.add_argument("kind", help="Event kind identifier (e.g. task.ready).")
152
- sp.add_argument("--source", default="bf", help="Event source name (default: bf).")
153
- sp.add_argument("--data", default="", metavar="JSON", help="Optional JSON object payload, or '-' to read stdin.")
154
- sp.add_argument("--dedupe", action="store_true", help="Deduplicate on kind, source, and data.id.")
155
-
114
+ sp.add_argument("--dry-run", action="store_true", help="Validate and preview actions without writing.")
115
+ emit_e = 'Example: echo \'{"id":"1"}\' | bf emit task.ready --data -'
116
+ sp = cmd("emit", "Append a custom event to logs/events.jsonl.", epilog=emit_e)
117
+ a = sp.add_argument
118
+ a("kind", help="Event kind identifier (e.g. task.ready).")
119
+ a("--source", default="bf", help="Event source name (default: bf).")
120
+ a("--data", default="", metavar="JSON", help="Optional JSON object payload, or '-' to read stdin.")
121
+ a("--dedupe", action="store_true", help="Deduplicate on kind, source, and data.id.")
156
122
  sp = cmd("status", "Inspect brain counts, failing loop attention, and loop health (read-only).")
157
- sp.add_argument("--all", dest="all_units", action="store_true", help="Include full per-loop status map.")
158
- sp.add_argument(
159
- "--format", choices=("json", "text"), default="json", help="Output format (json or bird's-eye text)."
160
- )
161
- sp.add_argument("--check", action="store_true", help="Exit 1 when any enabled loop requires attention.")
162
-
123
+ a = sp.add_argument
124
+ a("--all", dest="all_units", action="store_true", help="Include full per-loop status map.")
125
+ a("--format", choices=("json", "text"), default="json", help="Output format (json or bird's-eye text).")
126
+ a("--check", action="store_true", help="Exit 1 when any enabled loop requires attention.")
163
127
  sp = cmd("watch", "Supervise daemon loops, note rebuilds, and concurrent cycle loops.")
164
- sp.add_argument(
165
- "--format",
166
- choices=("auto", "text", "jsonl"),
167
- default="auto",
168
- help="Output mode: auto (text on TTY, jsonl on pipe), text, or jsonl.",
169
- )
128
+ w_h = "Output mode: auto (interactive TUI on TTY, jsonl on pipe), tui, text (scrolling log), or jsonl."
129
+ sp.add_argument("--format", choices=("auto", "tui", "text", "jsonl"), default="auto", help=w_h)
170
130
  return p
171
131
 
172
132
 
@@ -237,8 +197,7 @@ def _resolve_brain_arg(args: argparse.Namespace) -> str:
237
197
 
238
198
 
239
199
  def _dispatch(args: argparse.Namespace, extra: list[str]) -> int:
240
- cmd = args.command
241
- brain_arg = _resolve_brain_arg(args)
200
+ cmd, brain_arg = args.command, _resolve_brain_arg(args)
242
201
  if cmd == "schema":
243
202
  from bf import schemas
244
203
 
@@ -251,7 +210,6 @@ def _dispatch(args: argparse.Namespace, extra: list[str]) -> int:
251
210
  raise InputError("--name must be nonempty")
252
211
  _emit(engine.init_brain(args.path, name=args.name or "", description=args.description))
253
212
  return 0
254
-
255
213
  from bf import config
256
214
 
257
215
  store = config.select(brain_arg)
@@ -263,10 +221,7 @@ def _dispatch(args: argparse.Namespace, extra: list[str]) -> int:
263
221
  from bf import status
264
222
 
265
223
  res = status.status_summary(store, all_units=args.all_units or args.format == "text")
266
- if args.format == "text":
267
- _write_text(status.format_status_text(res, color=_use_color()))
268
- else:
269
- _emit(res)
224
+ _write_text(status.format_status_text(res, color=_use_color())) if args.format == "text" else _emit(res)
270
225
  return 0 if (not args.check or res.get("ok", True)) else 1
271
226
  if cmd == "emit":
272
227
  from bf import models, records
@@ -276,12 +231,9 @@ def _dispatch(args: argparse.Namespace, extra: list[str]) -> int:
276
231
  raise InputError("event kind must match ^[a-z][a-z0-9._-]{0,127}$")
277
232
  if not models.NAME_RE.fullmatch(args.source):
278
233
  raise InputError("event source must use lowercase letters, digits, and hyphens")
279
- if args.data == "-":
280
- if sys.stdin.isatty():
281
- raise InputError("stdin is a terminal; pipe JSON object or pass --data JSON")
282
- raw_in: bytes | str = _read_in("-")
283
- else:
284
- raw_in = args.data or ""
234
+ if args.data == "-" and sys.stdin.isatty():
235
+ raise InputError("stdin is a terminal; pipe JSON object or pass --data JSON")
236
+ raw_in: bytes | str = _read_in("-") if args.data == "-" else (args.data or "")
285
237
  try:
286
238
  raw_data = models.decode(raw_in, "--data") if raw_in.strip() else {}
287
239
  except Error as err:
@@ -294,17 +246,13 @@ def _dispatch(args: argparse.Namespace, extra: list[str]) -> int:
294
246
  if cmd == "check":
295
247
  from bf import engine, status
296
248
 
249
+ lim = 50 if args.limit is None else args.limit
297
250
  res = engine.validate(
298
- store,
299
- limit=50 if args.limit is None else args.limit,
300
- all_problems=args.all_problems,
301
- strict=args.strict,
302
- notes_only=args.notes,
251
+ store, limit=lim, all_problems=args.all_problems, strict=args.strict, notes_only=args.notes
303
252
  )
304
- if args.format == "text":
305
- _write_text(status.format_check_text(res, color=_use_color(), notes_only=args.notes))
306
- else:
307
- _emit(res)
253
+ _write_text(
254
+ status.format_check_text(res, color=_use_color(), notes_only=args.notes)
255
+ ) if args.format == "text" else _emit(res)
308
256
  return 0 if res["ok"] else 1
309
257
  if cmd == "run":
310
258
  from bf import loops
@@ -329,17 +277,16 @@ def _dispatch(args: argparse.Namespace, extra: list[str]) -> int:
329
277
 
330
278
  if args.input == "-" and sys.stdin.isatty():
331
279
  raise InputError("stdin is a terminal; pipe JSON records or pass --input FILE")
332
- _emit(
333
- records.ingest(
334
- store,
335
- args.source,
336
- _read_in(args.input),
337
- target=args.target,
338
- mode=args.mode,
339
- allow_removal=args.allow_removal,
340
- dry_run=args.dry_run,
341
- )
280
+ res = records.ingest(
281
+ store,
282
+ args.source,
283
+ _read_in(args.input),
284
+ target=args.target,
285
+ mode=args.mode,
286
+ allow_removal=args.allow_removal,
287
+ dry_run=args.dry_run,
342
288
  )
289
+ _emit(res)
343
290
  return 0
344
291
  if cmd == "read":
345
292
  from bf import query
@@ -360,7 +307,6 @@ def _dispatch(args: argparse.Namespace, extra: list[str]) -> int:
360
307
  res = engine.build(store)
361
308
  _emit(res)
362
309
  return 0 if res["ok"] else 1
363
-
364
310
  from bf import engine, status
365
311
 
366
312
  res = engine.review(store, limit=20 if args.limit is None else args.limit, all_items=args.all_items)
@@ -424,26 +424,31 @@ def _parse_loop(
424
424
  def_win = dw if isinstance(dw := defaults.get("window"), dict) else {}
425
425
  own_win = rw if isinstance(rw := raw.get("window"), dict) else {}
426
426
  win = {**def_win, **own_win}
427
- explicit_timeout = "timeout" in raw
428
- timeout_val = raw["timeout"] if "timeout" in raw else defaults.get("timeout", 300)
427
+ bf_s = models.parse_duration(win.get("backfill", 86400), f"{label}.window.backfill")
428
+ ov_s = models.parse_duration(win.get("overlap", 0), f"{label}.window.overlap", allow_zero=True)
429
+ to_s = models.parse_duration(
430
+ raw["timeout"] if "timeout" in raw else defaults.get("timeout", 300), f"{label}.timeout", maximum=86_400
431
+ )
432
+ desc = models.clean_text(str(raw.get("description") or ""), f"{label}.description")
433
+ env_m = _parse_env_map(raw.get("env"), f"{label}.env")
429
434
  return LoopSpec(
430
- name=name,
431
- run=run,
432
- description=models.clean_text(str(raw.get("description") or ""), f"{label}.description"),
433
- daemon=daemon,
434
- ingest=ingest,
435
- target=target,
436
- mode=mode,
437
- explicit_ingest=explicit_ingest,
438
- emit=emit,
439
- schedules=schedules,
440
- events=events,
441
- backfill=models.parse_duration(win.get("backfill", 86400), f"{label}.window.backfill"),
442
- overlap=models.parse_duration(win.get("overlap", 0), f"{label}.window.overlap", allow_zero=True),
443
- timeout=models.parse_duration(timeout_val, f"{label}.timeout", maximum=86_400),
444
- explicit_timeout=explicit_timeout,
445
- enabled=bool(raw.get("enabled", True)),
446
- env=_parse_env_map(raw.get("env"), f"{label}.env"),
435
+ name,
436
+ run,
437
+ desc,
438
+ daemon,
439
+ ingest,
440
+ target,
441
+ mode,
442
+ explicit_ingest,
443
+ emit,
444
+ schedules,
445
+ events,
446
+ bf_s,
447
+ ov_s,
448
+ to_s,
449
+ "timeout" in raw,
450
+ bool(raw.get("enabled", True)),
451
+ env_m,
447
452
  )
448
453
 
449
454
 
@@ -518,20 +523,23 @@ def _open_brain(chosen: str) -> Store:
518
523
  return store
519
524
 
520
525
 
526
+ def _owned_brain(path: Path, owner: int) -> bool:
527
+ ds, ys = path.stat(), (path / "bf.yaml").lstat()
528
+ return stat.S_ISDIR(ds.st_mode) and ds.st_uid == owner and stat.S_ISREG(ys.st_mode) and ys.st_uid == owner
529
+
530
+
521
531
  def select(value: str = "") -> Store:
522
532
  """Resolve `--brain PATH` -> enclosing `bf.yaml` -> `BF_BRAIN` -> `BRAIN_LOCATION` -> `~/brain`."""
523
- if value.strip():
524
- return _open_brain(value.strip())
533
+ if chosen := value.strip():
534
+ return _open_brain(chosen)
525
535
  if nearest := inside_brain():
526
536
  return nearest
527
- if env_brain := os.environ.get("BF_BRAIN", "").strip():
528
- return _open_brain(env_brain)
529
- if location := os.environ.get("BRAIN_LOCATION", "").strip():
530
- return _open_brain(location)
537
+ for env_key in ("BF_BRAIN", "BRAIN_LOCATION"):
538
+ if chosen := os.environ.get(env_key, "").strip():
539
+ return _open_brain(chosen)
531
540
  with suppress(RuntimeError, OSError):
532
541
  default_dir = Path.home() / "brain"
533
- info = (default_dir / "bf.yaml").lstat()
534
- if stat.S_ISREG(info.st_mode) and info.st_uid == os.geteuid() and default_dir.stat().st_uid == os.geteuid():
542
+ if _owned_brain(default_dir, os.geteuid()):
535
543
  return Store(default_dir)
536
544
  raise Error("no brain selected; pass --brain PATH, set BRAIN_LOCATION, run inside a brain, or run bf init ~/brain")
537
545
 
@@ -544,11 +552,9 @@ def resolve_brain(current: Store, cfg: Config, host: str) -> Store:
544
552
  raise InputError(f"brain {host!r} is not declared in bf.yaml brains:")
545
553
  raw_t = expand(Path(cfg.brains[host]))
546
554
  cand = raw_t if raw_t.is_absolute() else (current.root / raw_t)
547
- owner = os.geteuid()
548
555
  with suppress(OSError, ValueError):
549
556
  res = cand.resolve(strict=True)
550
- ds, ys = res.stat(), (res / "bf.yaml").lstat()
551
- if stat.S_ISDIR(ds.st_mode) and ds.st_uid == owner and stat.S_ISREG(ys.st_mode) and ys.st_uid == owner:
557
+ if _owned_brain(res, os.geteuid()):
552
558
  target = Store(res)
553
559
  load(target)
554
560
  return target
@@ -159,13 +159,14 @@ def build(store: Store, *, now: datetime | None = None) -> dict[str, Any]:
159
159
  ev = {"notes": note_count, "written": written, "removed": removed}
160
160
  records.append_event(store, "notes.built", "bf", ev, locked=True, now=now)
161
161
 
162
+ out_pat = f"memories/{{{','.join(cfg.notes)}}}.jsonl"
162
163
  return {
163
164
  "ok": not problems,
164
165
  "brain": cfg.name,
165
166
  "notes": note_count,
166
167
  "written": written,
167
168
  "removed": removed,
168
- "output": f"memories/{{{','.join(cfg.notes)}}}.jsonl",
169
+ "output": out_pat,
169
170
  "problems": problems,
170
171
  }
171
172
 
@@ -204,17 +205,8 @@ def validate(
204
205
  cfg = config.load(store)
205
206
  except Error as err:
206
207
  sm = {"errors": 1, "warnings": 0, "truncated": False, "by_kind": {"config": 1}}
207
- return {
208
- "ok": False,
209
- "brain": store.root.name,
210
- "notes": 0,
211
- "records": 0,
212
- "usages": 0,
213
- "errors_count": 1,
214
- "warnings_count": 0,
215
- "summary": sm,
216
- "problems": [str(err)],
217
- }
208
+ base = {"ok": False, "brain": store.root.name, "notes": 0, "records": 0, "usages": 0}
209
+ return {**base, "errors_count": 1, "warnings_count": 0, "summary": sm, "problems": [str(err)]}
218
210
  try:
219
211
  config.load_dotenv(store)
220
212
  except Error as err:
@@ -465,23 +457,16 @@ def validate(
465
457
  check_anchor(store, "", to, anc, origin)
466
458
 
467
459
  msgs, err_n, warn_n = [*errors, *warnings], len(errors), len(warnings)
468
- summary = {
469
- "errors": err_n,
470
- "warnings": warn_n,
471
- "truncated": not all_problems and len(msgs) > limit,
472
- "by_kind": by_kind,
473
- }
474
- ok_all = err_n == 0 and (not strict or warn_n == 0)
475
- shown = msgs if all_problems else msgs[:limit]
460
+ sm = {"errors": err_n, "warnings": warn_n, "truncated": not all_problems and len(msgs) > limit, "by_kind": by_kind}
461
+ ok_all, shown = err_n == 0 and (not strict or warn_n == 0), msgs if all_problems else msgs[:limit]
462
+ cnt = {"notes": len(authored_list), "records": rec_count, "usages": usage_count}
476
463
  return {
477
464
  "ok": ok_all,
478
465
  "brain": cfg.name,
479
- "notes": len(authored_list),
480
- "records": rec_count,
481
- "usages": usage_count,
466
+ **cnt,
482
467
  "errors_count": err_n,
483
468
  "warnings_count": warn_n,
484
- "summary": summary,
469
+ "summary": sm,
485
470
  "problems": shown,
486
471
  }
487
472
 
@@ -619,14 +604,6 @@ def review(store: Store, *, now: datetime | None = None, limit: int = 20, all_it
619
604
  stale.append({"ref": ref, "title": str(entry.get("title") or ""), "reasons": reasons, **newer_d})
620
605
 
621
606
  stale.sort(key=lambda x: (-len(x["reasons"]), -int(x.get("newer_count") or len(x.get("newer", ()))), x["ref"]))
622
- stale_out = stale if all_items else stale[:limit]
623
- truncated = (not all_items) and len(stale) > limit
624
- return {
625
- "ok": not problems,
626
- "brain": cfg.name,
627
- "total_stale": len(stale),
628
- "total_tasks_open": tasks_open,
629
- "stale": stale_out,
630
- "truncated": truncated,
631
- "problems": list(dict.fromkeys(problems)),
632
- }
607
+ stale_out, truncated = (stale if all_items else stale[:limit]), (not all_items) and len(stale) > limit
608
+ head = {"ok": not problems, "brain": cfg.name, "total_stale": len(stale), "total_tasks_open": tasks_open}
609
+ return {**head, "stale": stale_out, "truncated": truncated, "problems": list(dict.fromkeys(problems))}
@@ -59,7 +59,7 @@ loops:
59
59
  - **`stderr` (observability plane)**: structured JSONL (`structlog` / JSON lines with `time`/`timestamp`, `severity`/`level`, `message`/`event`, plus extra fields) or plain text, secret-redacted and appended live via `O_APPEND` with amortized compaction to `logs/<loop>.jsonl` for both cycle loops and daemons (including on graceful stop).
60
60
  - **Uniform `when:` triggers with per-trigger windows**: set `when: daemon` for continuous supervision, omit `when:` for manual loops, or pass a trigger or list of triggers (`1h`, `@daily`, `30 7 * * 1`, `{every, backfill?, overlap?}`, `{cron, backfill?, overlap?}`, `{event}`). Self-sourced `loop.succeeded`/`loop.failed` events are suppressed unless `source:` explicitly names the loop, and `bf watch` applies a per-loop event rate guard (`10`/min) against runaway cycles.
61
61
  - **Single event bus (`logs/events.jsonl`)**: `emit: <kind>`, `bf emit KIND [--data JSON|-]`, `bf build` (`notes.built`), `bf ingest` (`records.ingested`), and triggered loops (`loop.succeeded` / `loop.failed`) append deduplicated events to `logs/events.jsonl` (`0600` private, compacted at `1000` lines / `8 MiB`).
62
- - **Supervision & bird's-eye visibility (`bf watch` & `bf status --format text`)**: `bf watch` holds `.bf/watch.lock`, prints a bird's-eye status table on startup in TTY mode followed by clean live event lines (zero TUI cursor hijacking), and automatically emits structured JSONL when piped or given `--format jsonl` (ready for `systemd --user` / `journald` 24/7 hosting). Live config reload reconciles daemon loops automatically on `bf.yaml`, `.env`, and daemon script edits. Run `bf status --format text` anytime (or `tail -f` / `tail -F logs/<loop>.jsonl`) to check live health.
62
+ - **Supervision & live visibility (`bf watch` & `bf status --format text`)**: `bf watch` holds `.bf/watch.lock` and renders a zero-dependency scrollable ANSI dashboard on a TTY (`--format auto`/`tui`) showing brain health, cached corpus counts, all loops with 1-line errors and `+added ~updated -removed` diffs, and recent activity. Use `↑`/`↓` (`j`/`k`) or mouse wheel to scroll, `PgUp`/`PgDn`/`Space` to page, `g`/`G` for top/end, `f` to filter active/failing/changed loops, `s` to toggle recent vs name sort, `e` to inspect wrapped error details, `r` to refresh, and `q`/`Ctrl+C` to quit. Pass `--format text` for a plain scrolling stream, or pipe / pass `--format jsonl` for `systemd --user` and `journald`. Live config reload reconciles daemon loops automatically on `bf.yaml`, `.env`, and daemon script edits. Run `bf status --format text` anytime (or `tail -f` / `tail -F logs/<loop>.jsonl`) to check live health.
63
63
  - **Flat `env:` precedence**: `host allowlist < bf.yaml env: < loops.<name>.env: < optional 0600 .env < protected BF_*`.
64
64
  - **JSONL storage, `.forgotten`, & snapshot guard**: `bf ingest [--to memories|usages] SOURCE` writes `<target>/<source>.jsonl` atomically (deleting empty files for DuckDB compatibility), honors `<target>/<source>.forgotten`, skips snapshot pruning when `incomplete` is set, and refuses to empty a non-empty source or drop >50% of 10+ records without `--allow-removal`.
65
65
 
@@ -23,7 +23,7 @@ Every command writes one compact UTF-8 JSON object with `"ok"` to `stdout` (exce
23
23
  - `bf ingest SOURCE [--to memories|usages] [--input FILE] [--mode upsert|snapshot] [--allow-removal] [--dry-run] [--brain PATH]`: validate records against bundled `record` + required `schemas/<source>.json` (or `schemas/usages.json`), write `<target>/<source>.jsonl`, and emit `records.ingested`.
24
24
  - `bf run [LOOP ...] [--all | --due | --reset | --prune] [--dry-run] [--brain PATH] [-- EXTRA_ARGS...]`: execute named/glob, `--all`, or `--due` cycle loops, reset `.bf/<loop>.json` state (`--reset`), or prune orphaned `.bf/<loop>.json` files (`--prune`; `--dry-run` works across all modes).
25
25
  - `bf emit KIND [--source NAME] [--data JSON|-] [--dedupe] [--brain PATH]`: append a custom event to `logs/events.jsonl` (`--data -` reads JSON from non-TTY stdin).
26
- - `bf watch [--format auto|text|jsonl] [--brain PATH]`: supervise daemon loops, note rebuilds, and concurrent cycle loops; prints bird's-eye status + live text lines on TTY, or structured JSONL when piped / `--format jsonl`.
26
+ - `bf watch [--format auto|tui|text|jsonl] [--brain PATH]`: supervise daemon loops, note rebuilds, and concurrent cycle loops; renders an interactive scrollable ANSI dashboard on TTY (`auto`/`tui`), plain scrolling log (`text`), or structured JSONL when piped / `--format jsonl`.
27
27
 
28
28
  Brain selection resolves `--brain PATH` -> nearest enclosing `bf.yaml` -> `BF_BRAIN` -> `$BRAIN_LOCATION` -> `~/brain` (zero global config).
29
29
 
@@ -351,6 +351,7 @@ def execute_one_loop(
351
351
  argv, recorded = [*argv, *extra_args], False
352
352
  mark_unit_state(store, loop.name, status="running", updated=started_iso, last_start=started_iso)
353
353
  try:
354
+ err_cb = records.make_stderr_logger(store, loop.name, run_id)
354
355
  code, out_bytes, err_txt = proc.exec_argv(
355
356
  argv,
356
357
  cwd=store.root,
@@ -358,7 +359,7 @@ def execute_one_loop(
358
359
  timeout=timeout,
359
360
  stdin_data=ctx_bytes,
360
361
  stop_event=stop_event,
361
- on_stderr_line=records.make_stderr_logger(store, loop.name, run_id),
362
+ on_stderr_line=err_cb,
362
363
  )
363
364
  if stop_event is not None and stop_event.is_set() and code == 130:
364
365
  dur_ms = max(0, int((time.monotonic() - t0) * 1000))
@@ -383,6 +384,7 @@ def execute_one_loop(
383
384
  code, err_msg = 1, (models.redact_secrets(models.failure(error) or "failed")[-1024:] or "failed")
384
385
 
385
386
  ended, dur_ms = (datetime.now(UTC) if now is None else instant), max(0, int((time.monotonic() - t0) * 1000))
387
+ s_key = schedule.raw if schedule else ""
386
388
  record_run(
387
389
  store,
388
390
  loop.name,
@@ -397,7 +399,7 @@ def execute_one_loop(
397
399
  cursor_seq=cursor_target_seq,
398
400
  emit_loop_event=True,
399
401
  trigger=trigger,
400
- schedule_key=schedule.raw if schedule else "",
402
+ schedule_key=s_key,
401
403
  )
402
404
  recorded = True
403
405
  finally:
@@ -12,24 +12,8 @@ FORMAT = 18
12
12
  DEFAULT_NOTES = ("concepts", "projects", "actions")
13
13
  RECORD_DIRS = ("memories", "usages")
14
14
  RESERVED_SOURCES = frozenset(
15
- (
16
- "memories",
17
- "usages",
18
- "notes",
19
- "record",
20
- "logs",
21
- "evals",
22
- "schemas",
23
- "skills",
24
- "bf",
25
- "loops",
26
- "sensors",
27
- "routines",
28
- "agents",
29
- "clients",
30
- "prompts",
31
- )
32
- )
15
+ {"memories", "usages", "notes", "record", "logs", "evals", "schemas", "skills"}
16
+ ) | frozenset({"bf", "loops", "sensors", "routines", "agents", "clients", "prompts"})
33
17
  MAX_FILE = 256 << 20
34
18
  MAX_BATCH = 16 << 20
35
19
  MAX_NOTE = 4 << 20