brain-framework 33.0.0__tar.gz → 33.1.0__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 (33) hide show
  1. {brain_framework-33.0.0 → brain_framework-33.1.0}/PKG-INFO +1 -1
  2. {brain_framework-33.0.0 → brain_framework-33.1.0}/pyproject.toml +1 -1
  3. {brain_framework-33.0.0 → brain_framework-33.1.0}/pyproject.toml.orig +1 -1
  4. {brain_framework-33.0.0 → brain_framework-33.1.0}/src/bf/__init__.py +1 -1
  5. {brain_framework-33.0.0 → brain_framework-33.1.0}/src/bf/guides/operations.md +3 -3
  6. {brain_framework-33.0.0 → brain_framework-33.1.0}/src/bf/guides/reference.md +1 -1
  7. {brain_framework-33.0.0 → brain_framework-33.1.0}/src/bf/guides/retrieval.md +1 -1
  8. {brain_framework-33.0.0 → brain_framework-33.1.0}/src/bf/proc.py +6 -0
  9. {brain_framework-33.0.0 → brain_framework-33.1.0}/src/bf/query.py +2 -6
  10. {brain_framework-33.0.0 → brain_framework-33.1.0}/src/bf/records.py +2 -19
  11. {brain_framework-33.0.0 → brain_framework-33.1.0}/src/bf/status.py +52 -2
  12. {brain_framework-33.0.0 → brain_framework-33.1.0}/src/bf/storage.py +56 -13
  13. {brain_framework-33.0.0 → brain_framework-33.1.0}/src/bf/watch.py +32 -9
  14. {brain_framework-33.0.0 → brain_framework-33.1.0}/LICENSE +0 -0
  15. {brain_framework-33.0.0 → brain_framework-33.1.0}/README.md +0 -0
  16. {brain_framework-33.0.0 → brain_framework-33.1.0}/THIRD_PARTY_NOTICES.md +0 -0
  17. {brain_framework-33.0.0 → brain_framework-33.1.0}/src/bf/__main__.py +0 -0
  18. {brain_framework-33.0.0 → brain_framework-33.1.0}/src/bf/cli.py +0 -0
  19. {brain_framework-33.0.0 → brain_framework-33.1.0}/src/bf/config.py +0 -0
  20. {brain_framework-33.0.0 → brain_framework-33.1.0}/src/bf/engine.py +0 -0
  21. {brain_framework-33.0.0 → brain_framework-33.1.0}/src/bf/guides/authoring.md +0 -0
  22. {brain_framework-33.0.0 → brain_framework-33.1.0}/src/bf/guides/getting-started.md +0 -0
  23. {brain_framework-33.0.0 → brain_framework-33.1.0}/src/bf/guides/index.md +0 -0
  24. {brain_framework-33.0.0 → brain_framework-33.1.0}/src/bf/loops.py +0 -0
  25. {brain_framework-33.0.0 → brain_framework-33.1.0}/src/bf/markdown.py +0 -0
  26. {brain_framework-33.0.0 → brain_framework-33.1.0}/src/bf/models.py +0 -0
  27. {brain_framework-33.0.0 → brain_framework-33.1.0}/src/bf/py.typed +0 -0
  28. {brain_framework-33.0.0 → brain_framework-33.1.0}/src/bf/schemas.py +0 -0
  29. {brain_framework-33.0.0 → brain_framework-33.1.0}/src/bf/skills/bf/SKILL.md +0 -0
  30. {brain_framework-33.0.0 → brain_framework-33.1.0}/src/bf/starter/AGENTS.md +0 -0
  31. {brain_framework-33.0.0 → brain_framework-33.1.0}/src/bf/starter/concepts/welcome.md +0 -0
  32. {brain_framework-33.0.0 → brain_framework-33.1.0}/src/bf/starter/evals/smoke.py +0 -0
  33. {brain_framework-33.0.0 → brain_framework-33.1.0}/src/bf/starter/gitignore +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: brain-framework
3
- Version: 33.0.0
3
+ Version: 33.1.0
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
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "brain-framework"
3
- version = "33.0.0"
3
+ version = "33.1.0"
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.0.0"
4
+ version = "33.1.0"
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.0.0"
6
+ __version__ = "33.1.0"
7
7
 
8
8
 
9
9
  def main() -> None:
@@ -56,10 +56,10 @@ loops:
56
56
  - **UNIX two-stream contract + `BF_*` env & `stdin`**:
57
57
  - **`env`, `{{...}}` placeholders, & `stdin`**: every loop receives `BF_BRAIN`, `BF_LOOP`, `BF_STATE` (`<brain>/.bf/<loop>`), `BF_START`, `BF_END`, `BF_TRIGGER`, and `BF_RUN`, and `run:` argv tokens expand the matching allowlisted placeholders (`{{brain}}`, `{{loop}}`, `{{state}}`, `{{start}}`, `{{end}}`, `{{trigger}}`, `{{run}}`; unknown `{{...}}` tokens fail closed at config load). Cycle loops also receive one compact JSON context object on `stdin` (`{"run", "trigger", "loop", "start", "end", "events"}`); daemons receive `/dev/null`.
58
58
  - **`stdout` (data plane)**: JSONL records for `ingest:` or JSONL events for `emit:`.
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 to `logs/<loop>.jsonl` for both cycle loops and daemons (including on graceful stop).
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`. Run `bf status --format text` anytime (or `tail -f logs/<loop>.jsonl`) to check live health.
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.
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
 
@@ -71,4 +71,4 @@ loops:
71
71
  ## Privacy and security boundaries {#privacy-and-security-boundaries}
72
72
 
73
73
  - **No built-in LLM or provider SDK**: `bf` never calls model APIs directly; `run` commands execute with literal `argv` (`shell=False`), allowlisted environments, dedicated process groups, and JSON context on `stdin`. `jq` queries and event filters run from `/` with module imports and `$ENV` disabled.
74
- - **Private `.bf/` & `logs/`**: `.bf/` (`0700`, disposable locks `write.lock`/`watch.lock` and per-loop state `<loop>.json`/`<loop>/`) and `logs/` (`0700`, `0600` JSONL `logs/<loop>.jsonl` and `logs/events.jsonl`, excluded from `bf read`, `bf query`, and note links) enforce `geteuid()` ownership, and diagnostics redact common secrets and strip control characters.
74
+ - **Private `.bf/` & `logs/`**: `.bf/` (`0700`, disposable locks `write.lock`/`watch.lock`/`logs.lock` and per-loop state `<loop>.json`/`<loop>/`) and `logs/` (`0700`, `0600` JSONL `logs/<loop>.jsonl` and `logs/events.jsonl`, excluded from `bf read`, `bf query`, and note links) enforce `geteuid()` ownership, and diagnostics redact common secrets and strip control characters.
@@ -39,7 +39,7 @@ Brain selection resolves `--brain PATH` -> nearest enclosing `bf.yaml` -> `BF_BR
39
39
  - **Notes (`notes:`):** `concepts/`, `projects/`, `actions/` (flat `<slug>.md` or `<slug>/index.md` bundles).
40
40
  - **Loops (`loops:`):** `sensors/` (auto-ingested collectors), `routines/` (maintenance/reports/daemons), `agents/` (LLM/harness tasks).
41
41
  - **Records (JSONL):** `memories/` (`<source>.jsonl` + `.forgotten`), `usages/` (`<source>.jsonl` + `.forgotten`), `logs/` (`0700` private: `0600` `logs/<loop>.jsonl` + `logs/events.jsonl`).
42
- - **Supporting & runtime:** `schemas/` (`<source>.json`, `usages.json`), `evals/` (user Python/pytest evals), optional `clients/` & `prompts/` (convention-only), optional gitignored `0600` `.env`, and disposable `0700` `.bf/` (`write.lock`, `watch.lock`, `<loop>.json`, `<loop>/`).
42
+ - **Supporting & runtime:** `schemas/` (`<source>.json`, `usages.json`), `evals/` (user Python/pytest evals), optional `clients/` & `prompts/` (convention-only), optional gitignored `0600` `.env`, and disposable `0700` `.bf/` (`write.lock`, `watch.lock`, `logs.lock`, `<loop>.json`, `<loop>/`).
43
43
 
44
44
  ## `bf.yaml` schema {#bf-yaml-schema}
45
45
 
@@ -10,7 +10,7 @@ bf status --all
10
10
  bf review --limit 10
11
11
  ```
12
12
 
13
- - `bf status` returns compact `counts` (`notes`, `records`, `usages`, `sources`, `loops`), `"inside_brain"` (true only when CWD is inside the selected brain), `events_seq`, failing `attention` loops, `orphaned_states`, and `unbuilt_notes` (authored folders missing compiled `memories/<dir>.jsonl`). Pass `--format text` for a calm bird's-eye table (or `watch -n 2 bf status --format text`), `--all` for full JSON loop details, or `--check` to exit `1` on failures.
13
+ - `bf status` returns compact `counts` (`notes`, `records`, `usages`, `sources`, `loops`), `"inside_brain"` (true only when CWD is inside the selected brain), `events_seq`, failing `attention` loops, `orphaned_states`, and `unbuilt_notes` (authored folders whose `memories/<dir>.jsonl` is missing or out of sync with Markdown edits). Pass `--format text` for a calm bird's-eye table (or `watch -n 2 bf status --format text`), `--all` for full JSON loop details, or `--check` to exit `1` on failures.
14
14
  - `bf review` streams `memories/*.jsonl` directly to report bounded `stale` notes (`newer_evidence` capped to 5 items per note with `newer_count`, `due`, `future_updated`) and `total_tasks_open` (`--limit 20` default, `--all`, `--format json|jsonl|text`).
15
15
 
16
16
  ## 2. Read uniformly (`bf read`)
@@ -338,6 +338,12 @@ def prepare_unit(
338
338
  if not store.exists(cleaned):
339
339
  raise Error(f"{name}: command {argv[0]} does not exist inside brain")
340
340
  argv[0] = str(store.root.joinpath(*parts))
341
+ for tok in argv[1:]:
342
+ cleaned = tok.removeprefix(f"{store.root}/")
343
+ while cleaned.startswith("./"):
344
+ cleaned = cleaned[2:]
345
+ if cleaned.startswith(("sensors/", "routines/", "agents/")) and not store.exists(cleaned):
346
+ raise Error(f"{name}: script {cleaned} must be a regular file inside brain")
341
347
 
342
348
  env: dict[str, str] = {key: val for key in _ENV_ALLOWLIST if (val := os.environ.get(key))}
343
349
  env |= dict(base_env or {}) | dict(unit_env or {}) | config.load_dotenv(store)
@@ -358,7 +358,7 @@ def query(
358
358
 
359
359
  unbuilt: list[str] = []
360
360
  if kind in {"", "note"}:
361
- from bf import markdown as md
361
+ from bf.status import unbuilt_note_dirs
362
362
 
363
363
  sc = scope.strip().rstrip("/")
364
364
  if not sc or sc == "memories":
@@ -372,11 +372,7 @@ def query(
372
372
  else:
373
373
  head = sc.split("/", 1)[0]
374
374
  cand_dirs = [head] if head in cfg.notes else []
375
- missing_dirs = [f for f in cand_dirs if not store.exists(records.memory_file(f))]
376
- if missing_dirs:
377
- with suppress(Error):
378
- found_dirs = {p.split("/", 1)[0] for p in md.authored_notes(store, missing_dirs, skipped=[])}
379
- unbuilt = sorted(f for f in missing_dirs if f in found_dirs)
375
+ unbuilt = unbuilt_note_dirs(store, cand_dirs)
380
376
  return {
381
377
  "ok": True,
382
378
  "brain": cfg.name,
@@ -4,7 +4,6 @@ from __future__ import annotations
4
4
 
5
5
  import os
6
6
  import re
7
- import stat
8
7
  from collections.abc import Generator, Iterable
9
8
  from contextlib import nullcontext, suppress
10
9
  from datetime import datetime
@@ -12,7 +11,7 @@ from typing import Any, Literal
12
11
 
13
12
  from bf import models
14
13
  from bf.models import DEFAULT_NOTES, RESERVED_SOURCES, Error, InputError, clean, decode, encode, now_utc
15
- from bf.storage import Store, open_regular, private_dir, tail_lines, writer
14
+ from bf.storage import Store, append_regular, private_dir, tail_lines, writer
16
15
 
17
16
  Target = Literal["memories", "usages"]
18
17
  Mode = Literal["upsert", "snapshot"]
@@ -248,23 +247,7 @@ def append_event(
248
247
  raw_line = encode(event)
249
248
  if len(raw_line) > MAX_EVENT_LINE:
250
249
  raise Error(f"logs/events.jsonl: event exceeds {MAX_EVENT_LINE} bytes")
251
- with logs_dir.parent("events.jsonl", create=True) as (parent, leaf):
252
- fd = open_regular(parent, leaf, "logs/events.jsonl", os.O_WRONLY | os.O_CREAT | os.O_APPEND, 0o600)
253
- with os.fdopen(fd, "wb", buffering=0) as stream:
254
- if not stat.S_ISREG((info := os.fstat(stream.fileno())).st_mode):
255
- raise Error("logs/events.jsonl: expected a regular file")
256
- os.fchmod(stream.fileno(), 0o600)
257
- view = memoryview(raw_line)
258
- try:
259
- while view:
260
- if not (written := stream.write(view)):
261
- raise Error("logs/events.jsonl: short write")
262
- view = view[written:]
263
- except BaseException:
264
- with suppress(OSError):
265
- os.ftruncate(stream.fileno(), info.st_size)
266
- raise
267
- size_after = info.st_size + len(raw_line)
250
+ size_after = append_regular(logs_dir, "events.jsonl", raw_line, mode=0o600, label="logs/events.jsonl")
268
251
  if size_after > COMPACT_BYTES or (seq > MAX_EVENTS and seq % 200 == 0):
269
252
  all_lines = logs_dir.read("events.jsonl", 32 << 20).splitlines(keepends=True)
270
253
  if len(all_lines) > MAX_EVENTS or size_after > COMPACT_BYTES:
@@ -2,6 +2,7 @@
2
2
 
3
3
  from __future__ import annotations
4
4
 
5
+ from collections.abc import Iterable
5
6
  from contextlib import suppress
6
7
  from datetime import UTC, datetime
7
8
  from typing import Any
@@ -42,6 +43,54 @@ def _loop_trigger_label(loop: LoopSpec) -> str:
42
43
  return " · ".join(parts) or "manual"
43
44
 
44
45
 
46
+ def unbuilt_note_dirs(store: Store, folders: Iterable[str], authored: Iterable[str] | None = None) -> list[str]:
47
+ """Return sorted note folders whose `memories/<dir>.jsonl` is missing or out of sync with Markdown files."""
48
+ dirs = tuple(dict.fromkeys(folders))
49
+ if not dirs:
50
+ return []
51
+ by_dir: dict[str, list[str]] = {d: [] for d in dirs}
52
+ if authored is not None:
53
+ for path in authored:
54
+ if (d := path.split("/", 1)[0]) in by_dir:
55
+ by_dir[d].append(path)
56
+ out: list[str] = []
57
+ for folder in dirs:
58
+ if authored is None:
59
+ try:
60
+ notes = markdown.authored_notes(store, (folder,), skipped=[])
61
+ except Error:
62
+ out.append(folder)
63
+ continue
64
+ else:
65
+ notes = by_dir[folder]
66
+ mem_file = records.memory_file(folder)
67
+ has_mem = store.exists(mem_file)
68
+ if not notes:
69
+ if has_mem:
70
+ out.append(folder)
71
+ continue
72
+ if not has_mem:
73
+ out.append(folder)
74
+ continue
75
+ try:
76
+ built: dict[str, str] = {}
77
+ bad = False
78
+ for _, obj in records.iter_jsonl(store, mem_file):
79
+ if not isinstance(ref := obj.get("ref"), str) or ref in built:
80
+ bad = True
81
+ break
82
+ built[ref] = str(obj.get("sha256") or "")
83
+ if (
84
+ bad
85
+ or set(built) != set(notes)
86
+ or any(models.digest(store.read(p, models.MAX_NOTE)) != built[p] for p in notes)
87
+ ):
88
+ out.append(folder)
89
+ except Error, OSError:
90
+ out.append(folder)
91
+ return sorted(out)
92
+
93
+
45
94
  def status_summary(store: Store, *, all_units: bool = False) -> dict[str, Any]:
46
95
  """Strictly read-only brain counts, failing attention loops, orphaned `.bf/` states, and optional `loops`."""
47
96
  cfg, problems, attention, loops_out = config.load(store), [], [], {}
@@ -83,7 +132,7 @@ def status_summary(store: Store, *, all_units: bool = False) -> dict[str, Any]:
83
132
  notes_set = frozenset(cfg.notes)
84
133
  authored_list = markdown.authored_notes(store, cfg.notes)
85
134
  notes_total = len(authored_list)
86
- unbuilt_notes = sorted({d for p in authored_list if not store.exists(records.memory_file(d := p.split("/", 1)[0]))})
135
+ unbuilt_notes = unbuilt_note_dirs(store, cfg.notes, authored_list)
87
136
  rec_total = usage_total = 0
88
137
  rec_sources: set[str] = set()
89
138
  for bucket in models.RECORD_DIRS:
@@ -194,8 +243,9 @@ def format_status_text(summary: dict[str, Any], *, color: bool = False, now: dat
194
243
  ts = str(d.get("last_start" if st == "running" else "last_end") or d.get("last_success") or "")
195
244
  when = _fmt_age(ts, instant, live=st == "running")
196
245
  trig = printable(str(d.get("trigger") or d.get("mode") or ""))
246
+ st_disp = printable(st)[:16]
197
247
  lines.append(
198
- f" {printable(name):<{w_n}} {trig:<{w_t}} {st_c}{st:<8}{c_rst} {when:<8} {_fmt_detail(d)}"
248
+ f" {printable(name):<{w_n}} {trig:<{w_t}} {st_c}{st_disp:<8}{c_rst} {when:<8} {_fmt_detail(d)}"
199
249
  )
200
250
  disabled = sum(1 for d in loops_map.values() if not d.get("enabled", True))
201
251
  if disabled:
@@ -22,6 +22,7 @@ UNNAMED = "file name is not valid UTF-8 or contains a backslash; rename it"
22
22
  LINKED = "symlinks are not followed; replace the link with the file or folder itself"
23
23
  _WRITE_BUSY = "another writer is active for this brain; retry after it finishes"
24
24
  _LOG_LOCK = threading.Lock()
25
+ _LOG_APPENDS: dict[tuple[Path, str], int] = {}
25
26
 
26
27
 
27
28
  def _shown(name: str) -> str | None:
@@ -52,6 +53,28 @@ def open_regular(dir_fd: int, leaf: str, name: str, flags: int = os.O_RDONLY, mo
52
53
  raise
53
54
 
54
55
 
56
+ def append_regular(store: Store, name: str, data: bytes, *, mode: int = 0o600, label: str = "") -> int:
57
+ """Atomically append `data` to a regular file via `O_APPEND | O_NOFOLLOW`, rolling back on write errors."""
58
+ tag = label or name
59
+ with store.parent(name, create=True) as (parent, leaf):
60
+ fd = open_regular(parent, leaf, tag, os.O_WRONLY | os.O_CREAT | os.O_APPEND, mode)
61
+ with os.fdopen(fd, "wb", buffering=0) as stream:
62
+ if not stat.S_ISREG((info := os.fstat(stream.fileno())).st_mode):
63
+ raise Error(f"{tag}: expected a regular file")
64
+ os.fchmod(stream.fileno(), mode)
65
+ view = memoryview(data)
66
+ try:
67
+ while view:
68
+ if not (written := stream.write(view)):
69
+ raise Error(f"{tag}: short write")
70
+ view = view[written:]
71
+ except BaseException:
72
+ with suppress(OSError):
73
+ os.ftruncate(stream.fileno(), info.st_size)
74
+ raise
75
+ return info.st_size + len(data)
76
+
77
+
55
78
  def tail_lines(lines: list[bytes], max_lines: int, budget: int) -> list[bytes]:
56
79
  """Return the newest suffix of `lines` fitting within `max_lines` and `budget` bytes."""
57
80
  kept: list[bytes] = []
@@ -93,7 +116,10 @@ def _atomic_replace(parent: int, temporary: str, leaf: str, name: str, *, durabl
93
116
  class Store:
94
117
  """Confined directory store opening every descendant through `O_NOFOLLOW` descriptors."""
95
118
 
96
- def __init__(self, root: Path) -> None:
119
+ def __init__(self, root: Path, *, _base: Path | None = None, _private: tuple[str, ...] = ()) -> None:
120
+ if _base is not None:
121
+ self._base, self._private, self.root = _base, _private, _base.joinpath(*_private)
122
+ return
97
123
  try:
98
124
  self.root = root.resolve(strict=True)
99
125
  info = self.root.stat()
@@ -101,12 +127,15 @@ class Store:
101
127
  raise Error("brain directory does not exist; pass an existing --brain or BRAIN_LOCATION") from error
102
128
  if not stat.S_ISDIR(info.st_mode):
103
129
  raise Error("brain must be a directory")
130
+ self._base, self._private = self.root, ()
104
131
 
105
132
  def _open_dir(self, parts: tuple[str, ...], *, create: bool = False) -> int:
106
- fd = os.open(self.root, _DIR)
133
+ fd = os.open(self._base, _DIR)
134
+ all_parts = (*self._private, *parts)
135
+ priv_n = len(self._private)
107
136
  try:
108
- for number, part in enumerate(parts, 1):
109
- if create:
137
+ for number, part in enumerate(all_parts, 1):
138
+ if create and number > priv_n:
110
139
  with suppress(FileExistsError):
111
140
  os.mkdir(part, 0o755, dir_fd=fd)
112
141
  os.fsync(fd)
@@ -115,12 +144,16 @@ class Store:
115
144
  except OSError as error:
116
145
  if error.errno not in {errno.ELOOP, errno.ENOTDIR}:
117
146
  raise
118
- loc = "/".join(parts[:number])
147
+ if number <= priv_n:
148
+ raise Error("state directory must be a real directory without symlinks") from error
149
+ loc = "/".join(parts[: number - priv_n])
119
150
  if stat.S_ISREG(os.stat(part, dir_fd=fd, follow_symlinks=False).st_mode):
120
151
  raise Error(f"{loc}: expected a directory, found a file") from error
121
152
  raise Error(f"{loc}: expected a directory; symlinks and special files are not followed") from error
122
153
  os.close(fd)
123
154
  fd = child
155
+ if number <= priv_n and ((pinfo := os.fstat(fd)).st_uid != os.geteuid() or pinfo.st_mode & 0o077):
156
+ raise Error(f"state directory {'/'.join(self._private)} must be owned by you with mode 700")
124
157
  return fd
125
158
  except BaseException:
126
159
  os.close(fd)
@@ -328,18 +361,28 @@ class Store:
328
361
  return (tail.split(b"\n", 1)[1] if b"\n" in tail else b"") if off else tail, off
329
362
 
330
363
  def append_log(self, name: str, line: bytes, *, max_lines: int = 500, max_bytes: int = 2 << 20) -> None:
331
- """Append one private (`0600`) JSONL line to `logs/<name>.jsonl`, retaining up to `max_lines` / `max_bytes`."""
364
+ """Append one private (`0600`) JSONL line to `logs/<name>.jsonl` via `O_APPEND` with amortized compaction."""
332
365
  leaf_name, path = f"{name}.jsonl", f"logs/{name}.jsonl"
333
366
  entry = line if line.endswith(b"\n") else line + b"\n"
334
367
  if len(entry) > max_bytes:
335
368
  raise Error(f"{path}: log entry exceeds {max_bytes} bytes")
336
- logs_store, kept = private_dir(self, "logs"), []
369
+ key = (self.root, leaf_name)
337
370
  with _LOG_LOCK, writer(self, name="logs.lock"):
338
- if max_lines > 1:
339
- with suppress(FileNotFoundError):
340
- tail, _ = logs_store.read_tail(leaf_name, max_bytes, label=path)
341
- kept = tail_lines(tail.splitlines(keepends=True), max_lines - 1, max_bytes - len(entry))
342
- logs_store.write(leaf_name, b"".join([*kept, entry]), mode=0o600, durable=False)
371
+ logs_store = private_dir(self, "logs")
372
+ size_after = append_regular(logs_store, leaf_name, entry, mode=0o600, label=path)
373
+ if key not in _LOG_APPENDS and len(_LOG_APPENDS) >= 256:
374
+ _LOG_APPENDS.pop(next(iter(_LOG_APPENDS)))
375
+ count = _LOG_APPENDS.get(key, 0) + 1
376
+ _LOG_APPENDS[key] = count
377
+ stride = max(1, max_lines // 4)
378
+ limit = max_lines if max_lines <= 16 else max_lines + stride
379
+ check_lines = max_lines <= 16 or count == 1 or count % stride == 0
380
+ if size_after > max_bytes or check_lines:
381
+ tail, off = logs_store.read_tail(leaf_name, max_bytes + 1, label=path)
382
+ raw_lines = tail.splitlines(keepends=True)
383
+ if off > 0 or size_after > max_bytes or len(raw_lines) > limit:
384
+ kept = tail_lines(raw_lines, max_lines, max_bytes) or ([entry] if max_lines > 0 else [])
385
+ logs_store.write(leaf_name, b"".join(kept), mode=0o600, durable=False)
343
386
 
344
387
 
345
388
  def expand(path: Path) -> Path:
@@ -378,7 +421,7 @@ def private_dir(store: Store, *parts: str, create: bool = True) -> Store:
378
421
  raise Error(f"state directory {'/'.join(target)} must be owned by you with mode 700")
379
422
  finally:
380
423
  os.close(fd)
381
- return Store(store.root.joinpath(*target))
424
+ return Store(store.root, _base=store.root, _private=tuple(target))
382
425
 
383
426
 
384
427
  @contextmanager
@@ -59,11 +59,14 @@ def format_watch_line(event: str, payload: dict[str, Any], *, color: bool = Fals
59
59
  if isinstance(sm := payload.get("summary"), dict):
60
60
  if "records" in sm:
61
61
  diffs = " ".join(
62
- f"{s}{v}" for s, k in (("+", "added"), ("~", "updated"), ("-", "removed")) if (v := sm.get(k))
62
+ f"{s}{printable(str(v))[:16]}"
63
+ for s, k in (("+", "added"), ("~", "updated"), ("-", "removed"))
64
+ if (v := sm.get(k))
63
65
  )
64
- detail = f"{diffs} · {sm['records']} records" if diffs else f"{sm['records']} unchanged"
66
+ recs = printable(str(sm["records"]))[:16]
67
+ detail = f"{diffs} · {recs} records" if diffs else f"{recs} unchanged"
65
68
  elif "emitted" in sm:
66
- detail = f"{sm['emitted']} emitted"
69
+ detail = f"{printable(str(sm['emitted']))[:16]} emitted"
67
70
  return f"{c_dim}{ts}{c_rst} {c_ok}ok {c_rst} {name} {detail} {c_dim}{dur}{c_rst}\n"
68
71
  err = printable(str(payload.get("error") or st))
69
72
  return f"{c_dim}{ts}{c_rst} {c_err}fail {c_rst} {name} {err} {c_dim}{dur}{c_rst}\n"
@@ -352,32 +355,52 @@ def _serve_locked(
352
355
  q.append(now_m)
353
356
  return True
354
357
 
358
+ def _daemon_sig(unit: LoopSpec, base_env: Mapping[str, str], dotenv_sig: str) -> object:
359
+ resolved_argv: tuple[str, ...] = ()
360
+ scripts: list[tuple[str, str]] = []
361
+ with suppress(Error, OSError):
362
+ resolved_argv, _, _, _, _ = loops.resolve_loop(store, unit)
363
+ for tok in resolved_argv:
364
+ cleaned = tok.removeprefix("{{brain}}/").removeprefix(f"{store.root}/")
365
+ while cleaned.startswith("./"):
366
+ cleaned = cleaned[2:]
367
+ if cleaned.startswith(("sensors/", "routines/", "agents/")):
368
+ sig = models.digest(store.read(cleaned, models.MAX_NOTE)) if store.exists(cleaned) else "invalid"
369
+ scripts.append((cleaned, sig))
370
+ return (unit, models.digest(models.encode(dict(base_env))), dotenv_sig, resolved_argv, tuple(scripts))
371
+
355
372
  def reconcile_config() -> None:
356
373
  nonlocal cfg
357
374
  prev_key = (cfg.name, cfg.notes)
358
375
  try:
359
376
  new_cfg = config.load(store)
377
+ dotenv_sig = models.digest(models.encode(config.load_dotenv(store)))
360
378
  except models.FAILURES as err:
361
379
  emit_event("watch.error", {"ok": False, "error": printable(failure(err))})
362
380
  return
363
381
  if (new_cfg.name, new_cfg.notes) != prev_key:
364
382
  note_dirty.set()
365
- desired = {u.name: (u, new_cfg.env) for u in new_cfg.loops.values() if u.enabled and u.daemon}
383
+ desired = {
384
+ u.name: (_daemon_sig(u, new_cfg.env, dotenv_sig), u, new_cfg.env)
385
+ for u in new_cfg.loops.values()
386
+ if u.enabled and u.daemon
387
+ }
366
388
  with reconcile_lock:
367
389
  cfg = new_cfg
368
390
  stale = (
369
- [] if stop_ev.is_set() else [daemons.pop(k) for k in list(daemons) if desired.get(k) != daemons[k][0]]
391
+ []
392
+ if stop_ev.is_set()
393
+ else [daemons.pop(k) for k in list(daemons) if k not in desired or desired[k][0] != daemons[k][0]]
370
394
  )
371
395
  for _, u_stop, d_stream in stale:
372
396
  u_stop.set()
373
397
  d_stream.terminate()
374
398
  with reconcile_lock:
375
- for key, spec_pair in () if stop_ev.is_set() else desired.items():
399
+ for key, (sig, unit, base_env) in () if stop_ev.is_set() else desired.items():
376
400
  if key not in daemons:
377
- unit, base_env = spec_pair
378
401
  u_stop = threading.Event()
379
402
  stream = DaemonStream(store, unit, u_stop, wake_event, base_env=base_env, on_event=emit_event)
380
- daemons[key] = (spec_pair, u_stop, stream)
403
+ daemons[key] = (sig, u_stop, stream)
381
404
  stream.start()
382
405
 
383
406
  def _classify(raw_path: str) -> str:
@@ -390,7 +413,7 @@ def _serve_locked(
390
413
  return ""
391
414
  if (parts[0] in cfg.notes and rel.endswith(".md")) or (parts[0] == "schemas" and rel.endswith(".json")):
392
415
  return "note"
393
- if rel == "bf.yaml":
416
+ if rel in {"bf.yaml", ".env"} or parts[0] in {"sensors", "routines", "agents"}:
394
417
  return "config"
395
418
  if rel == "logs/events.jsonl":
396
419
  return "wake"