brain-framework 28.0.0__tar.gz → 29.0.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.
- {brain_framework-28.0.0 → brain_framework-29.0.1}/PKG-INFO +4 -4
- {brain_framework-28.0.0 → brain_framework-29.0.1}/README.md +2 -2
- {brain_framework-28.0.0 → brain_framework-29.0.1}/pyproject.toml +2 -2
- {brain_framework-28.0.0 → brain_framework-29.0.1}/pyproject.toml.orig +2 -2
- {brain_framework-28.0.0 → brain_framework-29.0.1}/src/bf/__init__.py +1 -1
- {brain_framework-28.0.0 → brain_framework-29.0.1}/src/bf/cli.py +17 -39
- {brain_framework-28.0.0 → brain_framework-29.0.1}/src/bf/config.py +35 -70
- {brain_framework-28.0.0 → brain_framework-29.0.1}/src/bf/engine.py +190 -182
- {brain_framework-28.0.0 → brain_framework-29.0.1}/src/bf/guides/authoring.md +3 -3
- {brain_framework-28.0.0 → brain_framework-29.0.1}/src/bf/guides/getting-started.md +1 -1
- {brain_framework-28.0.0 → brain_framework-29.0.1}/src/bf/guides/index.md +3 -3
- brain_framework-29.0.1/src/bf/guides/operations.md +65 -0
- {brain_framework-28.0.0 → brain_framework-29.0.1}/src/bf/guides/reference.md +10 -11
- {brain_framework-28.0.0 → brain_framework-29.0.1}/src/bf/guides/retrieval.md +3 -3
- brain_framework-29.0.1/src/bf/jobs.py +517 -0
- {brain_framework-28.0.0 → brain_framework-29.0.1}/src/bf/markdown.py +161 -91
- {brain_framework-28.0.0 → brain_framework-29.0.1}/src/bf/mcp.py +71 -70
- {brain_framework-28.0.0 → brain_framework-29.0.1}/src/bf/models.py +14 -21
- brain_framework-29.0.1/src/bf/query.py +471 -0
- {brain_framework-28.0.0 → brain_framework-29.0.1}/src/bf/records.py +147 -138
- {brain_framework-28.0.0 → brain_framework-29.0.1}/src/bf/schemas.py +53 -78
- {brain_framework-28.0.0 → brain_framework-29.0.1}/src/bf/skills/bf/SKILL.md +7 -7
- {brain_framework-28.0.0 → brain_framework-29.0.1}/src/bf/starter/AGENTS.md +1 -1
- {brain_framework-28.0.0 → brain_framework-29.0.1}/src/bf/starter/evals/smoke.yaml +1 -1
- {brain_framework-28.0.0 → brain_framework-29.0.1}/src/bf/storage.py +113 -109
- {brain_framework-28.0.0 → brain_framework-29.0.1}/src/bf/watch.py +162 -170
- brain_framework-28.0.0/src/bf/guides/operations.md +0 -73
- brain_framework-28.0.0/src/bf/jobs.py +0 -519
- brain_framework-28.0.0/src/bf/query.py +0 -459
- {brain_framework-28.0.0 → brain_framework-29.0.1}/LICENSE +0 -0
- {brain_framework-28.0.0 → brain_framework-29.0.1}/THIRD_PARTY_NOTICES.md +0 -0
- {brain_framework-28.0.0 → brain_framework-29.0.1}/src/bf/__main__.py +0 -0
- {brain_framework-28.0.0 → brain_framework-29.0.1}/src/bf/py.typed +0 -0
- {brain_framework-28.0.0 → brain_framework-29.0.1}/src/bf/starter/concepts/welcome.md +0 -0
- {brain_framework-28.0.0 → brain_framework-29.0.1}/src/bf/starter/docs/index.md +0 -0
- {brain_framework-28.0.0 → brain_framework-29.0.1}/src/bf/starter/gitignore +0 -0
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: brain-framework
|
|
3
|
-
Version:
|
|
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
|
|
3
|
+
Version: 29.0.1
|
|
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`, `
|
|
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
|
[](https://github.com/fmind/brain-framework/actions/workflows/ci.yml) [](https://pypi.org/project/brain-framework/) [](https://pypi.org/project/brain-framework/) [](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,
|
|
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`, `
|
|
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
|
[](https://github.com/fmind/brain-framework/actions/workflows/ci.yml) [](https://pypi.org/project/brain-framework/) [](https://pypi.org/project/brain-framework/) [](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,
|
|
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 = "
|
|
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
|
|
3
|
+
version = "29.0.1"
|
|
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 = "
|
|
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
|
|
4
|
+
version = "29.0.1"
|
|
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"
|
|
@@ -38,45 +38,36 @@ def _build_parser() -> _Parser:
|
|
|
38
38
|
p_init.add_argument("path", type=Path, metavar="PATH", help="New or empty directory for the brain.")
|
|
39
39
|
p_init.add_argument("--name", default="", help="Explicit brain name (defaults to directory slug).")
|
|
40
40
|
_sub(sub, "build", "Compile OKF Markdown notes into memories/{concepts,projects,actions}/*.json.")
|
|
41
|
-
|
|
42
41
|
p_ingest = _sub(sub, "ingest", "Validate and save JSON records into memories/<source>/<sha256>.json.")
|
|
43
42
|
p_ingest.add_argument("source", metavar="SOURCE", help="Lowercase source name for memories/<source>/.")
|
|
44
43
|
p_ingest.add_argument("--input", default="-", metavar="FILE", help="Input JSON/JSONL file path, or '-' for stdin.")
|
|
45
44
|
p_ingest.add_argument("--mode", choices=("upsert", "snapshot"), default="upsert", help="Merge or snapshot mode.")
|
|
46
|
-
|
|
45
|
+
rm_help = "Allow snapshot to drop >50%% of >=10 records or empty a source."
|
|
46
|
+
p_ingest.add_argument("--allow-removal", action="store_true", help=rm_help)
|
|
47
47
|
p_ingest.add_argument("--dry-run", action="store_true", help="Validate and report counts without writing files.")
|
|
48
|
-
|
|
49
48
|
p_read = _sub(sub, "read", "Read an OKF note, note#anchor section, source:id record, JSON memory, or bf:// URI.")
|
|
50
49
|
p_read.add_argument("target", metavar="TARGET", help="Note path, source:id, JSON memory path, or bf:// URI.")
|
|
51
|
-
|
|
52
50
|
p_query = _sub(sub, "query", "Query pure JSON memories via rg or jq.")
|
|
53
51
|
p_query.add_argument("pattern", nargs="?", default=None, metavar="QUERY", help="Lexical pattern for rg.")
|
|
54
52
|
p_query.add_argument("--jq", default=None, metavar="FILTER", help="jq filter expression over JSON memories.")
|
|
55
53
|
p_query.add_argument("-s", "--scope", default="", metavar="SCOPE", help="Optional folder or source name.")
|
|
56
|
-
|
|
57
|
-
|
|
54
|
+
lim_help = "Max items returned (default 20; 1..500 rg, 1..5000 jq)."
|
|
55
|
+
p_query.add_argument("-n", "--limit", type=int, default=20, metavar="N", help=lim_help)
|
|
58
56
|
_sub(sub, "validate", "Validate bf.yaml, schemas/, OKF notes, JSON memories, evals, and links.")
|
|
59
57
|
_sub(sub, "review", "List stale notes, newer linked evidence, draft actions, and open tasks.")
|
|
60
|
-
|
|
61
58
|
p_eval = _sub(sub, "eval", "Run deterministic evaluations in evals/.")
|
|
62
59
|
p_eval.add_argument("target", nargs="?", default="", metavar="SUITE", help="Optional eval file path or stem.")
|
|
63
|
-
|
|
64
|
-
p_run = _sub(sub, "run", "Execute jobs declared in bf.yaml (named, due, or Git hooks).")
|
|
60
|
+
p_run = _sub(sub, "run", "Execute jobs declared in bf.yaml (use -- EXTRA_ARGS... for one job or --hook).")
|
|
65
61
|
p_run.add_argument("jobs", nargs="*", metavar="JOB", help="Specific job names to execute.")
|
|
66
62
|
sel = p_run.add_mutually_exclusive_group()
|
|
67
63
|
sel.add_argument("--due", action="store_true", help="Rebuild dirty notes and run due scheduled/event jobs.")
|
|
68
64
|
sel.add_argument("--hook", choices=("pre-commit", "pre-push"), default="", help="Run jobs matching Git hook.")
|
|
69
65
|
p_run.add_argument("--dry-run", action="store_true", help="Validate job selection without executing commands.")
|
|
70
|
-
|
|
71
66
|
p_status = _sub(sub, "status", "Inspect folder counts, attention, unit states, and event sequence.")
|
|
72
67
|
p_status.add_argument("--check", action="store_true", help="Exit 1 if required binaries fail or a unit failed.")
|
|
73
|
-
|
|
74
68
|
p_watch = _sub(sub, "watch", "Supervise constant services, file changes, events, and scheduled jobs.")
|
|
75
69
|
p_watch.add_argument("--json", dest="json_stream", action="store_true", help="Emit compact JSON lines.")
|
|
76
|
-
|
|
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).")
|
|
70
|
+
_sub(sub, "mcp", "Run the read-only Model Context Protocol server over stdio.")
|
|
80
71
|
return parser
|
|
81
72
|
|
|
82
73
|
|
|
@@ -135,37 +126,29 @@ def run(argv: Sequence[str] | None = None) -> int:
|
|
|
135
126
|
head_argv, extra = _split_run_passthrough(items)
|
|
136
127
|
args = parser.parse_args(head_argv)
|
|
137
128
|
brain_arg = _resolve_brain_arg(args)
|
|
138
|
-
if args.command == "init":
|
|
139
|
-
from bf import engine
|
|
140
|
-
|
|
141
|
-
_emit(engine.init_brain(args.path, name=args.name))
|
|
142
|
-
return 0
|
|
143
129
|
if args.command == "mcp":
|
|
144
130
|
from bf import mcp
|
|
145
131
|
|
|
146
|
-
mcp.serve(brain_arg
|
|
132
|
+
mcp.serve(brain_arg)
|
|
147
133
|
return 0
|
|
148
|
-
from bf import config
|
|
134
|
+
from bf import config, engine, jobs, query, records
|
|
149
135
|
|
|
136
|
+
if args.command == "init":
|
|
137
|
+
_emit(engine.init_brain(args.path, name=args.name))
|
|
138
|
+
return 0
|
|
150
139
|
store, c = config.select(brain_arg), args.command
|
|
151
140
|
if c == "watch":
|
|
152
141
|
from bf import watch
|
|
153
142
|
|
|
154
143
|
return 0 if watch.serve(store, json_stream=args.json_stream)["ok"] else 1
|
|
155
144
|
if c in {"build", "validate", "review"}:
|
|
156
|
-
from bf import engine
|
|
157
|
-
|
|
158
145
|
res = {"build": engine.build, "validate": engine.validate, "review": engine.review}[c](store)
|
|
159
146
|
elif c == "ingest":
|
|
160
|
-
from bf import records
|
|
161
|
-
|
|
162
147
|
if args.input == "-" and sys.stdin.isatty():
|
|
163
148
|
raise InputError("stdin is a terminal; pipe JSON records or pass --input FILE")
|
|
164
149
|
kw_in: dict[str, Any] = {"mode": args.mode, "allow_removal": args.allow_removal, "dry_run": args.dry_run}
|
|
165
150
|
res = records.ingest(store, args.source, _read_input(args.input), **kw_in)
|
|
166
151
|
elif c in {"read", "query", "eval"}:
|
|
167
|
-
from bf import query
|
|
168
|
-
|
|
169
152
|
if c == "read":
|
|
170
153
|
res = query.read_target(store, args.target)
|
|
171
154
|
elif c == "eval":
|
|
@@ -173,19 +156,14 @@ def run(argv: Sequence[str] | None = None) -> int:
|
|
|
173
156
|
elif (args.jq is not None) == (args.pattern is not None):
|
|
174
157
|
raise InputError("pass either positional QUERY (rg) or --jq FILTER")
|
|
175
158
|
else:
|
|
176
|
-
qkw: dict[str, Any] = {"scope": args.scope, "limit": args.limit}
|
|
177
159
|
fn = query.query_jq if args.jq is not None else query.search_rg
|
|
178
|
-
res = fn(store, args.jq if args.jq is not None else args.pattern,
|
|
160
|
+
res = fn(store, args.jq if args.jq is not None else args.pattern, scope=args.scope, limit=args.limit)
|
|
161
|
+
elif c == "run":
|
|
162
|
+
b = _read_input("-") if (args.hook == "pre-push" and not args.dry_run and not sys.stdin.isatty()) else b""
|
|
163
|
+
ro: jobs.RunOpts = {"extra_args": extra, "stdin_bytes": b, "dry_run": args.dry_run}
|
|
164
|
+
res = jobs.run_jobs(store, args.jobs, due_only=args.due, hook=args.hook, **ro)
|
|
179
165
|
else:
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
if c == "run":
|
|
183
|
-
is_push = args.hook == "pre-push" and not args.dry_run and not sys.stdin.isatty()
|
|
184
|
-
kw_run: dict[str, Any] = {"due_only": args.due, "hook": args.hook, "extra_args": extra}
|
|
185
|
-
kw_run["stdin_bytes"] = _read_input("-") if is_push else b""
|
|
186
|
-
res = jobs.run_jobs(store, args.jobs, **kw_run, dry_run=args.dry_run)
|
|
187
|
-
else:
|
|
188
|
-
res = jobs.status_summary(store, check=args.check)
|
|
166
|
+
res = jobs.status_summary(store, check=args.check)
|
|
189
167
|
_emit(res)
|
|
190
168
|
return 0 if (c in {"ingest", "read", "query"} or (c == "status" and not args.check) or res["ok"]) else 1
|
|
191
169
|
except KeyboardInterrupt:
|
|
@@ -29,12 +29,12 @@ 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
|
-
|
|
32
|
+
_NULL_BOOL = (
|
|
33
33
|
("null", r"^(?:~|null|Null|NULL|)$", ["~", "n", "N", ""]),
|
|
34
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
35
|
)
|
|
36
|
+
_INT_SPEC = ("int", r"^(?:[-+]?[0-9]+|0o[0-7]+|0x[0-9a-fA-F]+)$", list("-+0123456789"))
|
|
37
|
+
_CORE = (*_NULL_BOOL, _INT_SPEC, ("float", _FLOAT_RE, list("-+.0123456789")))
|
|
38
38
|
_ENV_KEY_RE = re.compile(r"^[A-Z_][A-Z0-9_]*$")
|
|
39
39
|
_PROTECTED_ENV = frozenset({"BF_BRAIN", "BF_STATE_DIR", "BF_START", "BF_END", "BF_TRIGGER", "LC_ALL", "LANG"})
|
|
40
40
|
|
|
@@ -55,7 +55,6 @@ class JobSpec:
|
|
|
55
55
|
mode: Literal["upsert", "snapshot"] = "upsert"
|
|
56
56
|
allow_removal: bool = False
|
|
57
57
|
action_keep: int = 0
|
|
58
|
-
channel: str = ""
|
|
59
58
|
schedule: str = ""
|
|
60
59
|
every: int | None = None
|
|
61
60
|
cron: str = ""
|
|
@@ -69,22 +68,11 @@ class JobSpec:
|
|
|
69
68
|
env: dict[str, str] = field(default_factory=dict)
|
|
70
69
|
|
|
71
70
|
|
|
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
71
|
@dataclass(frozen=True)
|
|
84
72
|
class ServiceSpec:
|
|
85
73
|
name: str
|
|
86
74
|
run: tuple[str, ...] = ()
|
|
87
|
-
emit:
|
|
75
|
+
emit: Literal["none", "events", "messages"] = "none"
|
|
88
76
|
enabled: bool = True
|
|
89
77
|
requires: tuple[str, ...] = ()
|
|
90
78
|
env: dict[str, str] = field(default_factory=dict)
|
|
@@ -103,7 +91,6 @@ class Config:
|
|
|
103
91
|
timezone: str = "UTC"
|
|
104
92
|
env: dict[str, str] = field(default_factory=dict)
|
|
105
93
|
jobs: dict[str, JobSpec] = field(default_factory=dict)
|
|
106
|
-
channels: dict[str, ChannelSpec] = field(default_factory=dict)
|
|
107
94
|
services: dict[str, ServiceSpec] = field(default_factory=dict)
|
|
108
95
|
watch: WatchSpec = WatchSpec()
|
|
109
96
|
|
|
@@ -207,13 +194,8 @@ def _check_tz(tz: str, label: str) -> str:
|
|
|
207
194
|
|
|
208
195
|
|
|
209
196
|
def _parse_events(raw: object) -> tuple[EventMatch, ...]:
|
|
210
|
-
if
|
|
211
|
-
|
|
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
|
-
)
|
|
197
|
+
items = (x for x in raw if isinstance(x, dict)) if isinstance(raw, list) else ()
|
|
198
|
+
return tuple(EventMatch(str(x.get("kind", "")), str(x.get("source", "")), str(x.get("filter", ""))) for x in items)
|
|
217
199
|
|
|
218
200
|
|
|
219
201
|
def _str_tuple(raw: object) -> tuple[str, ...]:
|
|
@@ -286,20 +268,17 @@ def _parse_schedule(raw_sched: object, label: str) -> tuple[str, int | None, str
|
|
|
286
268
|
if raw_sched is None:
|
|
287
269
|
return "", None, ""
|
|
288
270
|
sched = models.clean(str(raw_sched).strip(), label) if isinstance(raw_sched, str) else str(raw_sched).strip()
|
|
289
|
-
|
|
271
|
+
is_dur = type(raw_sched) is int or (isinstance(raw_sched, str) and bool(models.DURATION_RE.fullmatch(sched)))
|
|
272
|
+
if is_dur:
|
|
290
273
|
return sched, models.parse_duration(raw_sched, label), ""
|
|
291
274
|
if ((sched.startswith("@") and len(sched.split()) == 1) or len(sched.split()) == 5) and croniter.is_valid(sched):
|
|
292
|
-
|
|
275
|
+
with suppress(ValueError, KeyError, TypeError):
|
|
293
276
|
croniter(sched, datetime(2026, 1, 1, tzinfo=UTC)).get_prev(datetime)
|
|
294
277
|
return sched, None, sched
|
|
295
|
-
|
|
296
|
-
pass
|
|
297
|
-
raise Error(f"{label}: must be a duration (e.g. 1h, 1d) or 5-field cron expression")
|
|
278
|
+
raise Error(f"{label}: must be a duration (e.g. 1h, 1d), @macro, or 5-field cron expression")
|
|
298
279
|
|
|
299
280
|
|
|
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]]:
|
|
281
|
+
def _unit_meta(raw: dict[str, object], kind: str, name: str, base_env: dict[str, str]):
|
|
303
282
|
env = {**base_env, **_parse_env_map(raw.get("env"), f"bf.yaml {kind}s.{name}.env")}
|
|
304
283
|
return bool(raw.get("enabled", True)), _str_tuple(raw.get("requires")), env
|
|
305
284
|
|
|
@@ -309,37 +288,29 @@ def _parse_job(name: str, raw: dict[str, object], base_env: dict[str, str]) -> J
|
|
|
309
288
|
if inp:
|
|
310
289
|
relative(inp)
|
|
311
290
|
raw_ing = raw.get("ingest")
|
|
312
|
-
mode: Literal["upsert", "snapshot"] = "upsert"
|
|
313
291
|
if isinstance(raw_ing, dict):
|
|
314
292
|
ingest = str(raw_ing["source"])
|
|
315
|
-
if raw_ing.get("mode") == "snapshot"
|
|
316
|
-
mode = "snapshot"
|
|
293
|
+
mode: Literal["upsert", "snapshot"] = "snapshot" if raw_ing.get("mode") == "snapshot" else "upsert"
|
|
317
294
|
allow_removal = bool(raw_ing.get("allow_removal", False))
|
|
318
295
|
else:
|
|
319
|
-
ingest, allow_removal = str(raw_ing or ""), False
|
|
296
|
+
ingest, mode, allow_removal = str(raw_ing or ""), "upsert", False
|
|
320
297
|
if ingest in models.RESERVED_SOURCES:
|
|
321
298
|
raise Error(f"bf.yaml jobs.{name}.ingest: source {ingest!r} is reserved")
|
|
322
|
-
|
|
323
|
-
action_keep = int(cast("int", raw_act["keep"])) if isinstance(raw_act, dict) else 0
|
|
299
|
+
action_keep = int(cast("int", raw_act["keep"])) if isinstance(raw_act := raw.get("action"), dict) else 0
|
|
324
300
|
sched, every, cron = _parse_schedule(raw.get("schedule"), f"bf.yaml jobs.{name}.schedule")
|
|
325
301
|
hooks = (str(raw["hook"]),) if isinstance(raw.get("hook"), str) else _str_tuple(raw.get("hook"))
|
|
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
|
-
|
|
330
|
-
|
|
331
|
-
|
|
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
|
+
en, req, env = _unit_meta(raw, "job", name, base_env)
|
|
306
|
+
ev = _parse_events(raw.get("events"))
|
|
307
|
+
a = (name, run, inp, ingest, mode, allow_removal, action_keep, sched, every, cron, ev, hooks, lb, ov, to, en, req)
|
|
308
|
+
return JobSpec(*a, env)
|
|
338
309
|
|
|
339
310
|
|
|
340
311
|
def _parse_service(name: str, raw: dict[str, object], base_env: dict[str, str]) -> ServiceSpec:
|
|
341
|
-
|
|
342
|
-
return ServiceSpec(name, run, emit, *_unit_meta(raw, "service", name, base_env))
|
|
312
|
+
emit = cast("Literal['none', 'events', 'messages']", str(raw.get("emit", "none")))
|
|
313
|
+
return ServiceSpec(name, _str_tuple(raw.get("run")), emit, *_unit_meta(raw, "service", name, base_env))
|
|
343
314
|
|
|
344
315
|
|
|
345
316
|
def load(store: Store) -> Config:
|
|
@@ -354,32 +325,24 @@ def load(store: Store) -> Config:
|
|
|
354
325
|
models.check_version(raw, "bf.yaml")
|
|
355
326
|
if problems := validate_instance(_brain_validator(), raw, "bf.yaml"):
|
|
356
327
|
raise Error("; ".join(problems))
|
|
357
|
-
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
|
-
)
|
|
328
|
+
rb = raw.get("brains") if isinstance(raw.get("brains"), dict) else {}
|
|
329
|
+
brains = {str(a): models.clean(str(t), f"bf.yaml brains.{a}") for a, t in cast("dict[str, object]", rb).items()}
|
|
361
330
|
tz = _check_tz(str(raw.get("timezone") or "UTC"), "bf.yaml timezone")
|
|
362
331
|
base_env = _parse_env_map(raw.get("env"), "bf.yaml env")
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
channels = {str(k): _parse_channel(str(k), v, base_env) for k, v in sec("channels").items()}
|
|
369
|
-
services = {str(k): _parse_service(str(k), v, base_env) for k, v in sec("services").items()}
|
|
370
|
-
all_names = (*jobs, *channels, *services)
|
|
332
|
+
raw_jobs = cast("dict[str, dict[str, object]]", raw["jobs"]) if isinstance(raw.get("jobs"), dict) else {}
|
|
333
|
+
raw_svcs = cast("dict[str, dict[str, object]]", raw["services"]) if isinstance(raw.get("services"), dict) else {}
|
|
334
|
+
jobs = {str(k): _parse_job(str(k), v, base_env) for k, v in raw_jobs.items()}
|
|
335
|
+
services = {str(k): _parse_service(str(k), v, base_env) for k, v in raw_svcs.items()}
|
|
336
|
+
all_names = (*jobs, *services)
|
|
371
337
|
if "events" in all_names:
|
|
372
338
|
raise Error("bf.yaml: unit name 'events' is reserved")
|
|
373
339
|
if len(set(all_names)) != len(all_names):
|
|
374
340
|
dup = next(u for i, u in enumerate(all_names) if u in all_names[:i])
|
|
375
341
|
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
342
|
w_spec = _parse_watch(cast("dict[str, object]", rw) if isinstance(rw := raw.get("watch"), dict) else {})
|
|
380
343
|
if len(_LOADED) >= 64:
|
|
381
|
-
_LOADED.
|
|
382
|
-
_LOADED[key] = cfg = Config(str(raw["name"]), brains, tz, base_env, jobs,
|
|
344
|
+
_LOADED.pop(next(iter(_LOADED)))
|
|
345
|
+
_LOADED[key] = cfg = Config(str(raw["name"]), brains, tz, base_env, jobs, services, w_spec)
|
|
383
346
|
return cfg
|
|
384
347
|
|
|
385
348
|
|
|
@@ -418,10 +381,10 @@ def select(value: str = "") -> Store:
|
|
|
418
381
|
return _open_brain(env_brain)
|
|
419
382
|
except Error:
|
|
420
383
|
if models.NAME_RE.fullmatch(env_brain) and (nearest := inside_brain()) is not None:
|
|
384
|
+
near_name = ""
|
|
421
385
|
with suppress(Error):
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
if env_brain == nearest.root.name:
|
|
386
|
+
near_name = load(nearest).name
|
|
387
|
+
if env_brain in {near_name, nearest.root.name}:
|
|
425
388
|
return nearest
|
|
426
389
|
raise
|
|
427
390
|
if nearest := inside_brain():
|
|
@@ -431,10 +394,12 @@ def select(value: str = "") -> Store:
|
|
|
431
394
|
raise Error("no brain selected; pass --brain PATH, set BF_BRAIN or DEFAULT_BRAIN_PATH, or run inside a brain")
|
|
432
395
|
|
|
433
396
|
|
|
434
|
-
def resolve_brain(current: Store, cfg: Config, host: str) -> Store:
|
|
397
|
+
def resolve_brain(current: Store, cfg: Config, host: str, *, declared_only: bool = False) -> Store:
|
|
435
398
|
"""Resolve a `bf://<host>/...` brain target confined to user-owned brain directories."""
|
|
436
399
|
if host in {"", cfg.name}:
|
|
437
400
|
return current
|
|
401
|
+
if declared_only and host not in cfg.brains:
|
|
402
|
+
raise models.InputError(f"brain {host!r} is not declared in bf.yaml brains:")
|
|
438
403
|
owner = os.geteuid()
|
|
439
404
|
candidates: list[Path] = []
|
|
440
405
|
if host in cfg.brains:
|