brain-framework 27.0.0__tar.gz → 29.0.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-27.0.0 → brain_framework-29.0.0}/PKG-INFO +4 -4
  2. {brain_framework-27.0.0 → brain_framework-29.0.0}/README.md +2 -2
  3. {brain_framework-27.0.0 → brain_framework-29.0.0}/pyproject.toml +2 -2
  4. {brain_framework-27.0.0 → brain_framework-29.0.0}/pyproject.toml.orig +2 -2
  5. {brain_framework-27.0.0 → brain_framework-29.0.0}/src/bf/__init__.py +1 -1
  6. {brain_framework-27.0.0 → brain_framework-29.0.0}/src/bf/cli.py +5 -6
  7. {brain_framework-27.0.0 → brain_framework-29.0.0}/src/bf/config.py +43 -59
  8. {brain_framework-27.0.0 → brain_framework-29.0.0}/src/bf/engine.py +120 -105
  9. {brain_framework-27.0.0 → brain_framework-29.0.0}/src/bf/guides/authoring.md +2 -2
  10. {brain_framework-27.0.0 → brain_framework-29.0.0}/src/bf/guides/getting-started.md +1 -1
  11. {brain_framework-27.0.0 → brain_framework-29.0.0}/src/bf/guides/index.md +4 -4
  12. {brain_framework-27.0.0 → brain_framework-29.0.0}/src/bf/guides/operations.md +12 -20
  13. {brain_framework-27.0.0 → brain_framework-29.0.0}/src/bf/guides/reference.md +10 -11
  14. {brain_framework-27.0.0 → brain_framework-29.0.0}/src/bf/guides/retrieval.md +3 -3
  15. {brain_framework-27.0.0 → brain_framework-29.0.0}/src/bf/jobs.py +189 -223
  16. {brain_framework-27.0.0 → brain_framework-29.0.0}/src/bf/markdown.py +150 -79
  17. {brain_framework-27.0.0 → brain_framework-29.0.0}/src/bf/mcp.py +38 -55
  18. {brain_framework-27.0.0 → brain_framework-29.0.0}/src/bf/models.py +10 -21
  19. {brain_framework-27.0.0 → brain_framework-29.0.0}/src/bf/query.py +115 -160
  20. {brain_framework-27.0.0 → brain_framework-29.0.0}/src/bf/records.py +130 -89
  21. {brain_framework-27.0.0 → brain_framework-29.0.0}/src/bf/schemas.py +51 -57
  22. {brain_framework-27.0.0 → brain_framework-29.0.0}/src/bf/skills/bf/SKILL.md +7 -7
  23. {brain_framework-27.0.0 → brain_framework-29.0.0}/src/bf/starter/AGENTS.md +2 -2
  24. {brain_framework-27.0.0 → brain_framework-29.0.0}/src/bf/starter/evals/smoke.yaml +1 -1
  25. {brain_framework-27.0.0 → brain_framework-29.0.0}/src/bf/storage.py +63 -80
  26. {brain_framework-27.0.0 → brain_framework-29.0.0}/src/bf/watch.py +163 -157
  27. {brain_framework-27.0.0 → brain_framework-29.0.0}/LICENSE +0 -0
  28. {brain_framework-27.0.0 → brain_framework-29.0.0}/THIRD_PARTY_NOTICES.md +0 -0
  29. {brain_framework-27.0.0 → brain_framework-29.0.0}/src/bf/__main__.py +0 -0
  30. {brain_framework-27.0.0 → brain_framework-29.0.0}/src/bf/py.typed +0 -0
  31. {brain_framework-27.0.0 → brain_framework-29.0.0}/src/bf/starter/concepts/welcome.md +0 -0
  32. {brain_framework-27.0.0 → brain_framework-29.0.0}/src/bf/starter/docs/index.md +0 -0
  33. {brain_framework-27.0.0 → brain_framework-29.0.0}/src/bf/starter/gitignore +0 -0
@@ -1,7 +1,7 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: brain-framework
3
- Version: 27.0.0
4
- Summary: Brain Framework is a local-first brain for you and your AI agents. It compiles OKF Markdown notes into JSON records, validates notes, records, and evals against JSON Schemas, orchestrates jobs, channels, and services, and queries offline with rg and jq.
3
+ Version: 29.0.0
4
+ Summary: Brain Framework is a local-first brain for you and your AI agents. It compiles OKF Markdown notes into JSON records, validates notes, records, and evals against JSON Schemas, orchestrates jobs and services, and queries offline with rg and jq.
5
5
  Keywords: ai,ai-agents,agent-memory,agent-skills,agents-md,context-engineering,json,json-schema,knowledge-graph,knowledge-management,local-first,mcp,model-context-protocol,personal-knowledge-management,python,second-brain
6
6
  Author: Médéric Hurier
7
7
  License-Expression: MIT
@@ -45,7 +45,7 @@ Brain Framework (`bf`) turns a flat folder of human-authored Markdown notes and
45
45
 
46
46
  - **Three formats, one job each.** **YAML for config** (`bf.yaml`, `evals/*.yaml`, note frontmatter), **JSON for records** (`memories/**/*.json`, enforced by `schemas/*.json`, plus `structlog` JSON lines in `logs/*.log`), and **Markdown for humans** (`projects/`, `concepts/`, and `actions/` parsed with [Python-Markdown](https://python-markdown.github.io/) `attr_list` metadata, plus plain Markdown inputs under `prompts/`).
47
47
  - **Agents always query JSON.** `bf build` compiles Markdown notes, headings, keyed `attr_list` metadata (`attrs`), links, and open tasks into `memories/{concepts,projects,actions}/*.json`; `bf ingest` writes validated sensor records into `memories/<source>/*.json`.
48
- - **Minimal, standard-driven core.** Under 4,500 lines of Python delegating retrieval to `rg` and `jq`, cross-references to relative Markdown paths and standard `bf://` URLs, and orchestration (`timezone`, `env`, `jobs`, `channels`, `services`, `watch`) to `bf.yaml` — with zero custom databases, built-in LLMs, or provider SDKs.
48
+ - **Minimal, standard-driven core.** Under 4,500 lines of Python delegating retrieval to `rg` and `jq`, cross-references to relative Markdown paths and standard `bf://` URLs, and orchestration (`timezone`, `env`, `jobs`, `services`, `watch`) to `bf.yaml` — with zero custom databases, built-in LLMs, or provider SDKs.
49
49
 
50
50
  [![CI](https://github.com/fmind/brain-framework/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/fmind/brain-framework/actions/workflows/ci.yml) [![PyPI](https://img.shields.io/pypi/v/brain-framework?color=174EA6)](https://pypi.org/project/brain-framework/) [![Python](https://img.shields.io/pypi/pyversions/brain-framework)](https://pypi.org/project/brain-framework/) [![License: MIT](https://img.shields.io/badge/license-MIT-174EA6)](https://github.com/fmind/brain-framework/blob/main/LICENSE)
51
51
 
@@ -76,7 +76,7 @@ Explore the [four-tool walkthrough](https://github.com/fmind/brain-framework/blo
76
76
  </a>
77
77
 
78
78
  - **Notes, `attr_list`, & `bf://` URLs ([Authoring](https://fmind.github.io/brain-framework/authoring/)):** Separate volatile TODOs (`projects/`), durable knowledge (`concepts/`), and dated workspaces (`actions/*/ACTION.md`). Attach metadata on headings (`## MCP {#mcp creator=Anthropic}`) and blocks (`{: #summary confidence=high}`), and cross-reference notes or sibling brains with `bf://` URLs.
79
- - **User schemas, jobs, & live watch ([Operations](https://fmind.github.io/brain-framework/operations/)):** Ship user-owned JSON Schemas in `schemas/`, copy stdlib sensors from [examples/sensors](https://github.com/fmind/brain-framework/tree/main/examples/sensors), and orchestrate cron/duration schedules, `structlog` JSON logs, event triggers, channels, services, and Rich TUI monitoring via `bf.yaml` (`jobs`, `channels`, `services`, `watch`).
79
+ - **User schemas, jobs, & live watch ([Operations](https://fmind.github.io/brain-framework/operations/)):** Ship user-owned JSON Schemas in `schemas/`, copy stdlib sensors from [examples/sensors](https://github.com/fmind/brain-framework/tree/main/examples/sensors), and orchestrate cron/duration schedules, `structlog` JSON logs, event triggers, services, and Rich TUI monitoring via `bf.yaml` (`jobs`, `services`, `watch`).
80
80
  - **Standard JSON retrieval & MCP ([Retrieval](https://fmind.github.io/brain-framework/retrieval/)):** Resolve `bf://` URLs and `#anchor` sections with `bf read`, search and filter `memories/**/*.json` via `bf query` (`rg`, `jq`), run deterministic `bf eval` checks, or expose read-only tools via `bf mcp`.
81
81
  - **Integrity & freshness ([Reference](https://fmind.github.io/brain-framework/reference/)):** `bf validate` checks every schema, compiled-note sync, link, `#anchor`, and cross-brain `bf://` reference; `bf review` surfaces `newer_evidence`, overdue `stale_after` notes, and open `draft` actions.
82
82
 
@@ -10,7 +10,7 @@ Brain Framework (`bf`) turns a flat folder of human-authored Markdown notes and
10
10
 
11
11
  - **Three formats, one job each.** **YAML for config** (`bf.yaml`, `evals/*.yaml`, note frontmatter), **JSON for records** (`memories/**/*.json`, enforced by `schemas/*.json`, plus `structlog` JSON lines in `logs/*.log`), and **Markdown for humans** (`projects/`, `concepts/`, and `actions/` parsed with [Python-Markdown](https://python-markdown.github.io/) `attr_list` metadata, plus plain Markdown inputs under `prompts/`).
12
12
  - **Agents always query JSON.** `bf build` compiles Markdown notes, headings, keyed `attr_list` metadata (`attrs`), links, and open tasks into `memories/{concepts,projects,actions}/*.json`; `bf ingest` writes validated sensor records into `memories/<source>/*.json`.
13
- - **Minimal, standard-driven core.** Under 4,500 lines of Python delegating retrieval to `rg` and `jq`, cross-references to relative Markdown paths and standard `bf://` URLs, and orchestration (`timezone`, `env`, `jobs`, `channels`, `services`, `watch`) to `bf.yaml` — with zero custom databases, built-in LLMs, or provider SDKs.
13
+ - **Minimal, standard-driven core.** Under 4,500 lines of Python delegating retrieval to `rg` and `jq`, cross-references to relative Markdown paths and standard `bf://` URLs, and orchestration (`timezone`, `env`, `jobs`, `services`, `watch`) to `bf.yaml` — with zero custom databases, built-in LLMs, or provider SDKs.
14
14
 
15
15
  [![CI](https://github.com/fmind/brain-framework/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/fmind/brain-framework/actions/workflows/ci.yml) [![PyPI](https://img.shields.io/pypi/v/brain-framework?color=174EA6)](https://pypi.org/project/brain-framework/) [![Python](https://img.shields.io/pypi/pyversions/brain-framework)](https://pypi.org/project/brain-framework/) [![License: MIT](https://img.shields.io/badge/license-MIT-174EA6)](https://github.com/fmind/brain-framework/blob/main/LICENSE)
16
16
 
@@ -41,7 +41,7 @@ Explore the [four-tool walkthrough](https://github.com/fmind/brain-framework/blo
41
41
  </a>
42
42
 
43
43
  - **Notes, `attr_list`, & `bf://` URLs ([Authoring](https://fmind.github.io/brain-framework/authoring/)):** Separate volatile TODOs (`projects/`), durable knowledge (`concepts/`), and dated workspaces (`actions/*/ACTION.md`). Attach metadata on headings (`## MCP {#mcp creator=Anthropic}`) and blocks (`{: #summary confidence=high}`), and cross-reference notes or sibling brains with `bf://` URLs.
44
- - **User schemas, jobs, & live watch ([Operations](https://fmind.github.io/brain-framework/operations/)):** Ship user-owned JSON Schemas in `schemas/`, copy stdlib sensors from [examples/sensors](https://github.com/fmind/brain-framework/tree/main/examples/sensors), and orchestrate cron/duration schedules, `structlog` JSON logs, event triggers, channels, services, and Rich TUI monitoring via `bf.yaml` (`jobs`, `channels`, `services`, `watch`).
44
+ - **User schemas, jobs, & live watch ([Operations](https://fmind.github.io/brain-framework/operations/)):** Ship user-owned JSON Schemas in `schemas/`, copy stdlib sensors from [examples/sensors](https://github.com/fmind/brain-framework/tree/main/examples/sensors), and orchestrate cron/duration schedules, `structlog` JSON logs, event triggers, services, and Rich TUI monitoring via `bf.yaml` (`jobs`, `services`, `watch`).
45
45
  - **Standard JSON retrieval & MCP ([Retrieval](https://fmind.github.io/brain-framework/retrieval/)):** Resolve `bf://` URLs and `#anchor` sections with `bf read`, search and filter `memories/**/*.json` via `bf query` (`rg`, `jq`), run deterministic `bf eval` checks, or expose read-only tools via `bf mcp`.
46
46
  - **Integrity & freshness ([Reference](https://fmind.github.io/brain-framework/reference/)):** `bf validate` checks every schema, compiled-note sync, link, `#anchor`, and cross-brain `bf://` reference; `bf review` surfaces `newer_evidence`, overdue `stale_after` notes, and open `draft` actions.
47
47
 
@@ -1,7 +1,7 @@
1
1
  [project]
2
2
  name = "brain-framework"
3
- version = "27.0.0"
4
- description = "Brain Framework is a local-first brain for you and your AI agents. It compiles OKF Markdown notes into JSON records, validates notes, records, and evals against JSON Schemas, orchestrates jobs, channels, and services, and queries offline with rg and jq."
3
+ version = "29.0.0"
4
+ description = "Brain Framework is a local-first brain for you and your AI agents. It compiles OKF Markdown notes into JSON records, validates notes, records, and evals against JSON Schemas, orchestrates jobs and services, and queries offline with rg and jq."
5
5
  readme = "README.md"
6
6
  requires-python = ">=3.14"
7
7
  license = "MIT"
@@ -1,8 +1,8 @@
1
1
  # https://packaging.python.org/en/latest/specifications/pyproject-toml/
2
2
  [project]
3
3
  name = "brain-framework"
4
- version = "27.0.0"
5
- description = "Brain Framework is a local-first brain for you and your AI agents. It compiles OKF Markdown notes into JSON records, validates notes, records, and evals against JSON Schemas, orchestrates jobs, channels, and services, and queries offline with rg and jq."
4
+ version = "29.0.0"
5
+ description = "Brain Framework is a local-first brain for you and your AI agents. It compiles OKF Markdown notes into JSON records, validates notes, records, and evals against JSON Schemas, orchestrates jobs and services, and queries offline with rg and jq."
6
6
  readme = "README.md"
7
7
  requires-python = ">=3.14"
8
8
  license = "MIT"
@@ -3,7 +3,7 @@
3
3
  import os
4
4
  import sys
5
5
 
6
- __version__ = "27.0.0"
6
+ __version__ = "29.0.0"
7
7
 
8
8
 
9
9
  def main() -> None:
@@ -53,7 +53,8 @@ def _build_parser() -> _Parser:
53
53
  p_query.add_argument("pattern", nargs="?", default=None, metavar="QUERY", help="Lexical pattern for rg.")
54
54
  p_query.add_argument("--jq", default=None, metavar="FILTER", help="jq filter expression over JSON memories.")
55
55
  p_query.add_argument("-s", "--scope", default="", metavar="SCOPE", help="Optional folder or source name.")
56
- p_query.add_argument("-n", "--limit", type=int, default=20, metavar="N", help="Max items returned (default 20).")
56
+ lim_help = "Max items returned (default 20; 1..500 rg, 1..5000 jq)."
57
+ p_query.add_argument("-n", "--limit", type=int, default=20, metavar="N", help=lim_help)
57
58
 
58
59
  _sub(sub, "validate", "Validate bf.yaml, schemas/, OKF notes, JSON memories, evals, and links.")
59
60
  _sub(sub, "review", "List stale notes, newer linked evidence, draft actions, and open tasks.")
@@ -61,7 +62,7 @@ def _build_parser() -> _Parser:
61
62
  p_eval = _sub(sub, "eval", "Run deterministic evaluations in evals/.")
62
63
  p_eval.add_argument("target", nargs="?", default="", metavar="SUITE", help="Optional eval file path or stem.")
63
64
 
64
- p_run = _sub(sub, "run", "Execute jobs declared in bf.yaml (named, due, or Git hooks).")
65
+ p_run = _sub(sub, "run", "Execute jobs declared in bf.yaml (use -- EXTRA_ARGS... for one job or --hook).")
65
66
  p_run.add_argument("jobs", nargs="*", metavar="JOB", help="Specific job names to execute.")
66
67
  sel = p_run.add_mutually_exclusive_group()
67
68
  sel.add_argument("--due", action="store_true", help="Rebuild dirty notes and run due scheduled/event jobs.")
@@ -74,9 +75,7 @@ def _build_parser() -> _Parser:
74
75
  p_watch = _sub(sub, "watch", "Supervise constant services, file changes, events, and scheduled jobs.")
75
76
  p_watch.add_argument("--json", dest="json_stream", action="store_true", help="Emit compact JSON lines.")
76
77
 
77
- p_mcp = _sub(sub, "mcp", "Run the read-only Model Context Protocol server.")
78
- p_mcp.add_argument("--transport", choices=("stdio", "http"), default="stdio", help="MCP transport (default stdio).")
79
- p_mcp.add_argument("--port", type=int, default=None, help="Localhost port for HTTP transport (default 8765).")
78
+ _sub(sub, "mcp", "Run the read-only Model Context Protocol server over stdio.")
80
79
  return parser
81
80
 
82
81
 
@@ -143,7 +142,7 @@ def run(argv: Sequence[str] | None = None) -> int:
143
142
  if args.command == "mcp":
144
143
  from bf import mcp
145
144
 
146
- mcp.serve(brain_arg, transport=args.transport, port=args.port)
145
+ mcp.serve(brain_arg)
147
146
  return 0
148
147
  from bf import config
149
148
 
@@ -10,7 +10,7 @@ from dataclasses import dataclass, field
10
10
  from datetime import UTC, datetime
11
11
  from functools import cache
12
12
  from pathlib import Path
13
- from typing import Literal, cast
13
+ from typing import Any, Literal, cast
14
14
  from urllib.parse import unquote
15
15
  from zoneinfo import ZoneInfo, ZoneInfoNotFoundError
16
16
 
@@ -29,12 +29,9 @@ LIBYAML = (
29
29
  "uv tool install --reinstall --python 3.14 brain-framework"
30
30
  )
31
31
  _FLOAT_RE = r"^(?:[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)(?:[eE][-+]?[0-9]+)?|[-+]?\.(?:inf|Inf|INF)|\.(?:nan|NaN|NAN))$"
32
- _CORE = (
33
- ("null", r"^(?:~|null|Null|NULL|)$", ["~", "n", "N", ""]),
34
- ("bool", r"^(?:true|True|TRUE|false|False|FALSE)$", list("tTfF")),
35
- ("int", r"^(?:[-+]?[0-9]+|0o[0-7]+|0x[0-9a-fA-F]+)$", list("-+0123456789")),
36
- ("float", _FLOAT_RE, list("-+.0123456789")),
37
- )
32
+ _NULL_BOOL = (("null", r"^(?:~|null|Null|NULL|)$", ["~", "n", "N", ""]), ("bool", r"^(?i:true|false)$", list("tTfF")))
33
+ _INT_SPEC = ("int", r"^(?:[-+]?[0-9]+|0o[0-7]+|0x[0-9a-fA-F]+)$", list("-+0123456789"))
34
+ _CORE = (*_NULL_BOOL, _INT_SPEC, ("float", _FLOAT_RE, list("-+.0123456789")))
38
35
  _ENV_KEY_RE = re.compile(r"^[A-Z_][A-Z0-9_]*$")
39
36
  _PROTECTED_ENV = frozenset({"BF_BRAIN", "BF_STATE_DIR", "BF_START", "BF_END", "BF_TRIGGER", "LC_ALL", "LANG"})
40
37
 
@@ -55,7 +52,6 @@ class JobSpec:
55
52
  mode: Literal["upsert", "snapshot"] = "upsert"
56
53
  allow_removal: bool = False
57
54
  action_keep: int = 0
58
- channel: str = ""
59
55
  schedule: str = ""
60
56
  every: int | None = None
61
57
  cron: str = ""
@@ -69,22 +65,11 @@ class JobSpec:
69
65
  env: dict[str, str] = field(default_factory=dict)
70
66
 
71
67
 
72
- @dataclass(frozen=True)
73
- class ChannelSpec:
74
- name: str
75
- listen: tuple[str, ...] = ()
76
- send: tuple[str, ...] = ()
77
- timeout: int = 60
78
- enabled: bool = True
79
- requires: tuple[str, ...] = ()
80
- env: dict[str, str] = field(default_factory=dict)
81
-
82
-
83
68
  @dataclass(frozen=True)
84
69
  class ServiceSpec:
85
70
  name: str
86
71
  run: tuple[str, ...] = ()
87
- emit: str = "none"
72
+ emit: Literal["none", "events", "messages"] = "none"
88
73
  enabled: bool = True
89
74
  requires: tuple[str, ...] = ()
90
75
  env: dict[str, str] = field(default_factory=dict)
@@ -103,7 +88,6 @@ class Config:
103
88
  timezone: str = "UTC"
104
89
  env: dict[str, str] = field(default_factory=dict)
105
90
  jobs: dict[str, JobSpec] = field(default_factory=dict)
106
- channels: dict[str, ChannelSpec] = field(default_factory=dict)
107
91
  services: dict[str, ServiceSpec] = field(default_factory=dict)
108
92
  watch: WatchSpec = WatchSpec()
109
93
 
@@ -207,13 +191,8 @@ def _check_tz(tz: str, label: str) -> str:
207
191
 
208
192
 
209
193
  def _parse_events(raw: object) -> tuple[EventMatch, ...]:
210
- if not isinstance(raw, list):
211
- return ()
212
- return tuple(
213
- EventMatch(str(x.get("kind", "")), str(x.get("source", "")), str(x.get("filter", "")))
214
- for x in raw
215
- if isinstance(x, dict)
216
- )
194
+ items = (x for x in raw if isinstance(x, dict)) if isinstance(raw, list) else ()
195
+ return tuple(EventMatch(str(x.get("kind", "")), str(x.get("source", "")), str(x.get("filter", ""))) for x in items)
217
196
 
218
197
 
219
198
  def _str_tuple(raw: object) -> tuple[str, ...]:
@@ -286,20 +265,17 @@ def _parse_schedule(raw_sched: object, label: str) -> tuple[str, int | None, str
286
265
  if raw_sched is None:
287
266
  return "", None, ""
288
267
  sched = models.clean(str(raw_sched).strip(), label) if isinstance(raw_sched, str) else str(raw_sched).strip()
289
- if isinstance(raw_sched, (int, float)) or (isinstance(raw_sched, str) and models.DURATION_RE.fullmatch(sched)):
268
+ is_dur = type(raw_sched) is int or (isinstance(raw_sched, str) and bool(models.DURATION_RE.fullmatch(sched)))
269
+ if is_dur:
290
270
  return sched, models.parse_duration(raw_sched, label), ""
291
271
  if ((sched.startswith("@") and len(sched.split()) == 1) or len(sched.split()) == 5) and croniter.is_valid(sched):
292
- try:
272
+ with suppress(ValueError, KeyError, TypeError):
293
273
  croniter(sched, datetime(2026, 1, 1, tzinfo=UTC)).get_prev(datetime)
294
274
  return sched, None, sched
295
- except ValueError, KeyError, TypeError:
296
- pass
297
- raise Error(f"{label}: must be a duration (e.g. 1h, 1d) or 5-field cron expression")
275
+ raise Error(f"{label}: must be a duration (e.g. 1h, 1d), @macro, or 5-field cron expression")
298
276
 
299
277
 
300
- def _unit_meta(
301
- raw: dict[str, object], kind: str, name: str, base_env: dict[str, str]
302
- ) -> tuple[bool, tuple[str, ...], dict[str, str]]:
278
+ def _unit_meta(raw: dict[str, object], kind: str, name: str, base_env: dict[str, str]):
303
279
  env = {**base_env, **_parse_env_map(raw.get("env"), f"bf.yaml {kind}s.{name}.env")}
304
280
  return bool(raw.get("enabled", True)), _str_tuple(raw.get("requires")), env
305
281
 
@@ -326,20 +302,19 @@ def _parse_job(name: str, raw: dict[str, object], base_env: dict[str, str]) -> J
326
302
  lb = models.parse_duration(raw.get("lookback", 86400), f"bf.yaml jobs.{name}.lookback")
327
303
  ov = models.parse_duration(raw.get("overlap", 0), f"bf.yaml jobs.{name}.overlap", allow_zero=True)
328
304
  to = models.parse_duration(raw.get("timeout", 300), f"bf.yaml jobs.{name}.timeout", maximum=86_400)
329
- head = (name, run, inp, ingest, mode, allow_removal, action_keep, str(raw.get("channel") or ""), sched, every, cron)
330
- tail = (_parse_events(raw.get("events")), hooks, lb, ov, to, *_unit_meta(raw, "job", name, base_env))
331
- return JobSpec(*head, *tail)
332
-
333
-
334
- def _parse_channel(name: str, raw: dict[str, object], base_env: dict[str, str]) -> ChannelSpec:
335
- listen, send = _str_tuple(raw.get("listen")), _str_tuple(raw.get("send"))
336
- to = models.parse_duration(raw.get("timeout", 60), f"bf.yaml channels.{name}.timeout", maximum=86_400)
337
- return ChannelSpec(name, listen, send, to, *_unit_meta(raw, "channel", name, base_env))
305
+ io_kw: dict[str, Any] = {"input": inp, "ingest": ingest, "mode": mode, "allow_removal": allow_removal}
306
+ evs = _parse_events(raw.get("events"))
307
+ trig_kw: dict[str, Any] = {"schedule": sched, "every": every, "cron": cron, "events": evs, "hooks": hooks}
308
+ lim_kw: dict[str, Any] = {"lookback": lb, "overlap": ov, "timeout": to}
309
+ en, req, env = _unit_meta(raw, "job", name, base_env)
310
+ return JobSpec(
311
+ name=name, run=run, **io_kw, action_keep=action_keep, **trig_kw, **lim_kw, enabled=en, requires=req, env=env
312
+ )
338
313
 
339
314
 
340
315
  def _parse_service(name: str, raw: dict[str, object], base_env: dict[str, str]) -> ServiceSpec:
341
- run, emit = _str_tuple(raw.get("run")), str(raw.get("emit", "none"))
342
- return ServiceSpec(name, run, emit, *_unit_meta(raw, "service", name, base_env))
316
+ emit = cast("Literal['none', 'events', 'messages']", str(raw.get("emit", "none")))
317
+ return ServiceSpec(name, _str_tuple(raw.get("run")), emit, *_unit_meta(raw, "service", name, base_env))
343
318
 
344
319
 
345
320
  def load(store: Store) -> Config:
@@ -355,9 +330,9 @@ def load(store: Store) -> Config:
355
330
  if problems := validate_instance(_brain_validator(), raw, "bf.yaml"):
356
331
  raise Error("; ".join(problems))
357
332
  rb = raw.get("brains")
358
- brains = (
359
- {str(a): models.clean(str(t), f"bf.yaml brains.{a}") for a, t in rb.items()} if isinstance(rb, dict) else {}
360
- )
333
+ brains = {
334
+ str(a): models.clean(str(t), f"bf.yaml brains.{a}") for a, t in (rb.items() if isinstance(rb, dict) else ())
335
+ }
361
336
  tz = _check_tz(str(raw.get("timezone") or "UTC"), "bf.yaml timezone")
362
337
  base_env = _parse_env_map(raw.get("env"), "bf.yaml env")
363
338
 
@@ -365,21 +340,17 @@ def load(store: Store) -> Config:
365
340
  return cast("dict[str, dict[str, object]]", raw[k]) if isinstance(raw.get(k), dict) else {}
366
341
 
367
342
  jobs = {str(k): _parse_job(str(k), v, base_env) for k, v in sec("jobs").items()}
368
- channels = {str(k): _parse_channel(str(k), v, base_env) for k, v in sec("channels").items()}
369
343
  services = {str(k): _parse_service(str(k), v, base_env) for k, v in sec("services").items()}
370
- all_names = (*jobs, *channels, *services)
344
+ all_names = (*jobs, *services)
371
345
  if "events" in all_names:
372
346
  raise Error("bf.yaml: unit name 'events' is reserved")
373
347
  if len(set(all_names)) != len(all_names):
374
348
  dup = next(u for i, u in enumerate(all_names) if u in all_names[:i])
375
349
  raise Error(f"bf.yaml: unit name {dup!r} is declared in multiple sections")
376
- for job in jobs.values():
377
- if job.channel and (job.channel not in channels or not channels[job.channel].send):
378
- raise Error(f"bf.yaml jobs.{job.name}.channel: channel {job.channel!r} has no send command")
379
350
  w_spec = _parse_watch(cast("dict[str, object]", rw) if isinstance(rw := raw.get("watch"), dict) else {})
380
351
  if len(_LOADED) >= 64:
381
352
  _LOADED.clear()
382
- _LOADED[key] = cfg = Config(str(raw["name"]), brains, tz, base_env, jobs, channels, services, w_spec)
353
+ _LOADED[key] = cfg = Config(str(raw["name"]), brains, tz, base_env, jobs, services, w_spec)
383
354
  return cfg
384
355
 
385
356
 
@@ -411,8 +382,19 @@ def _open_brain(chosen: str) -> Store:
411
382
 
412
383
  def select(value: str = "") -> Store:
413
384
  """Resolve `--brain PATH` -> `BF_BRAIN` -> enclosing `bf.yaml` -> `DEFAULT_BRAIN_PATH`."""
414
- if chosen := (value or os.environ.get("BF_BRAIN", "")).strip():
415
- return _open_brain(chosen)
385
+ if value.strip():
386
+ return _open_brain(value.strip())
387
+ if env_brain := os.environ.get("BF_BRAIN", "").strip():
388
+ try:
389
+ return _open_brain(env_brain)
390
+ except Error:
391
+ if models.NAME_RE.fullmatch(env_brain) and (nearest := inside_brain()) is not None:
392
+ with suppress(Error):
393
+ if env_brain == load(nearest).name:
394
+ return nearest
395
+ if env_brain == nearest.root.name:
396
+ return nearest
397
+ raise
416
398
  if nearest := inside_brain():
417
399
  return nearest
418
400
  if fallback := os.environ.get("DEFAULT_BRAIN_PATH", "").strip():
@@ -420,10 +402,12 @@ def select(value: str = "") -> Store:
420
402
  raise Error("no brain selected; pass --brain PATH, set BF_BRAIN or DEFAULT_BRAIN_PATH, or run inside a brain")
421
403
 
422
404
 
423
- def resolve_brain(current: Store, cfg: Config, host: str) -> Store:
405
+ def resolve_brain(current: Store, cfg: Config, host: str, *, declared_only: bool = False) -> Store:
424
406
  """Resolve a `bf://<host>/...` brain target confined to user-owned brain directories."""
425
407
  if host in {"", cfg.name}:
426
408
  return current
409
+ if declared_only and host not in cfg.brains:
410
+ raise models.InputError(f"brain {host!r} is not declared in bf.yaml brains:")
427
411
  owner = os.geteuid()
428
412
  candidates: list[Path] = []
429
413
  if host in cfg.brains: