brain-framework 21.1.0__tar.gz → 21.2.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 (73) hide show
  1. {brain_framework-21.1.0 → brain_framework-21.2.0}/PKG-INFO +2 -2
  2. {brain_framework-21.1.0 → brain_framework-21.2.0}/README.md +1 -1
  3. {brain_framework-21.1.0 → brain_framework-21.2.0}/THIRD_PARTY_NOTICES.md +24 -24
  4. {brain_framework-21.1.0 → brain_framework-21.2.0}/pyproject.toml +2 -2
  5. {brain_framework-21.1.0 → brain_framework-21.2.0}/pyproject.toml.orig +2 -2
  6. {brain_framework-21.1.0 → brain_framework-21.2.0}/src/bf/__init__.py +1 -1
  7. {brain_framework-21.1.0 → brain_framework-21.2.0}/src/bf/assistants.py +10 -4
  8. {brain_framework-21.1.0 → brain_framework-21.2.0}/src/bf/cli.py +29 -33
  9. {brain_framework-21.1.0 → brain_framework-21.2.0}/src/bf/collect.py +1 -2
  10. {brain_framework-21.1.0 → brain_framework-21.2.0}/src/bf/health.py +6 -6
  11. {brain_framework-21.1.0 → brain_framework-21.2.0}/src/bf/index.py +6 -4
  12. {brain_framework-21.1.0 → brain_framework-21.2.0}/src/bf/markdown.py +2 -1
  13. {brain_framework-21.1.0 → brain_framework-21.2.0}/src/bf/pages.py +19 -36
  14. {brain_framework-21.1.0 → brain_framework-21.2.0}/src/bf/records.py +24 -5
  15. {brain_framework-21.1.0 → brain_framework-21.2.0}/src/bf/runtime.py +6 -6
  16. {brain_framework-21.1.0 → brain_framework-21.2.0}/src/bf/skills/bf-maintain/references/integrations.md +1 -3
  17. {brain_framework-21.1.0 → brain_framework-21.2.0}/src/bf/skills/bf-use/SKILL.md +1 -1
  18. {brain_framework-21.1.0 → brain_framework-21.2.0}/src/bf/skills/bf-use/references/evidence.md +6 -19
  19. {brain_framework-21.1.0 → brain_framework-21.2.0}/src/bf/skills/bf-use/references/links.md +4 -4
  20. {brain_framework-21.1.0 → brain_framework-21.2.0}/src/bf/skills/bf-use/references/retrieval.md +1 -1
  21. {brain_framework-21.1.0 → brain_framework-21.2.0}/src/bf/skills/bf-use/scripts/evidence.py +48 -6
  22. {brain_framework-21.1.0 → brain_framework-21.2.0}/src/bf/skills/bf-use/templates/concept.md +1 -1
  23. {brain_framework-21.1.0 → brain_framework-21.2.0}/src/bf/starter/evals/retrieval.yaml +4 -1
  24. {brain_framework-21.1.0 → brain_framework-21.2.0}/src/bf/storage.py +8 -0
  25. {brain_framework-21.1.0 → brain_framework-21.2.0}/src/bf/update.py +16 -3
  26. {brain_framework-21.1.0 → brain_framework-21.2.0}/src/bf/validate.py +3 -2
  27. {brain_framework-21.1.0 → brain_framework-21.2.0}/LICENSE +0 -0
  28. {brain_framework-21.1.0 → brain_framework-21.2.0}/src/bf/__main__.py +0 -0
  29. {brain_framework-21.1.0 → brain_framework-21.2.0}/src/bf/channels.py +0 -0
  30. {brain_framework-21.1.0 → brain_framework-21.2.0}/src/bf/config.py +0 -0
  31. {brain_framework-21.1.0 → brain_framework-21.2.0}/src/bf/evaluate.py +0 -0
  32. {brain_framework-21.1.0 → brain_framework-21.2.0}/src/bf/graph.py +0 -0
  33. {brain_framework-21.1.0 → brain_framework-21.2.0}/src/bf/history.py +0 -0
  34. {brain_framework-21.1.0 → brain_framework-21.2.0}/src/bf/install.py +0 -0
  35. {brain_framework-21.1.0 → brain_framework-21.2.0}/src/bf/links.py +0 -0
  36. {brain_framework-21.1.0 → brain_framework-21.2.0}/src/bf/mcp.py +0 -0
  37. {brain_framework-21.1.0 → brain_framework-21.2.0}/src/bf/messages.py +0 -0
  38. {brain_framework-21.1.0 → brain_framework-21.2.0}/src/bf/models.py +0 -0
  39. {brain_framework-21.1.0 → brain_framework-21.2.0}/src/bf/ontology.py +0 -0
  40. {brain_framework-21.1.0 → brain_framework-21.2.0}/src/bf/py.typed +0 -0
  41. {brain_framework-21.1.0 → brain_framework-21.2.0}/src/bf/replies.py +0 -0
  42. {brain_framework-21.1.0 → brain_framework-21.2.0}/src/bf/retrieve.py +0 -0
  43. {brain_framework-21.1.0 → brain_framework-21.2.0}/src/bf/schemas.py +0 -0
  44. {brain_framework-21.1.0 → brain_framework-21.2.0}/src/bf/skills/README.md +0 -0
  45. {brain_framework-21.1.0 → brain_framework-21.2.0}/src/bf/skills/bf-action/SKILL.md +0 -0
  46. {brain_framework-21.1.0 → brain_framework-21.2.0}/src/bf/skills/bf-action/references/actions.md +0 -0
  47. {brain_framework-21.1.0 → brain_framework-21.2.0}/src/bf/skills/bf-action/references/context.md +0 -0
  48. {brain_framework-21.1.0 → brain_framework-21.2.0}/src/bf/skills/bf-action/references/handoff.md +0 -0
  49. {brain_framework-21.1.0 → brain_framework-21.2.0}/src/bf/skills/bf-action/scripts/check-handoff.py +0 -0
  50. {brain_framework-21.1.0 → brain_framework-21.2.0}/src/bf/skills/bf-action/scripts/new-action.py +0 -0
  51. {brain_framework-21.1.0 → brain_framework-21.2.0}/src/bf/skills/bf-action/templates/action.md +0 -0
  52. {brain_framework-21.1.0 → brain_framework-21.2.0}/src/bf/skills/bf-maintain/SKILL.md +0 -0
  53. {brain_framework-21.1.0 → brain_framework-21.2.0}/src/bf/skills/bf-maintain/references/conflicts.md +0 -0
  54. {brain_framework-21.1.0 → brain_framework-21.2.0}/src/bf/skills/bf-maintain/references/operations.md +0 -0
  55. {brain_framework-21.1.0 → brain_framework-21.2.0}/src/bf/skills/bf-setup/SKILL.md +0 -0
  56. {brain_framework-21.1.0 → brain_framework-21.2.0}/src/bf/skills/bf-setup/references/discovery.md +0 -0
  57. {brain_framework-21.1.0 → brain_framework-21.2.0}/src/bf/skills/bf-setup/references/import.md +0 -0
  58. {brain_framework-21.1.0 → brain_framework-21.2.0}/src/bf/skills/bf-setup/references/scan.md +0 -0
  59. {brain_framework-21.1.0 → brain_framework-21.2.0}/src/bf/skills/bf-setup/scripts/inventory.py +0 -0
  60. {brain_framework-21.1.0 → brain_framework-21.2.0}/src/bf/skills/bf-use/references/consolidate.md +0 -0
  61. {brain_framework-21.1.0 → brain_framework-21.2.0}/src/bf/skills/bf-use/references/decisions.md +0 -0
  62. {brain_framework-21.1.0 → brain_framework-21.2.0}/src/bf/skills/bf-use/references/learn.md +0 -0
  63. {brain_framework-21.1.0 → brain_framework-21.2.0}/src/bf/skills/bf-use/references/review.md +0 -0
  64. {brain_framework-21.1.0 → brain_framework-21.2.0}/src/bf/skills/bf-use/references/share.md +0 -0
  65. {brain_framework-21.1.0 → brain_framework-21.2.0}/src/bf/skills/bf-use/scripts/guarded-write.py +0 -0
  66. {brain_framework-21.1.0 → brain_framework-21.2.0}/src/bf/skills/bf-use/templates/project.md +0 -0
  67. {brain_framework-21.1.0 → brain_framework-21.2.0}/src/bf/starter/AGENTS.md +0 -0
  68. {brain_framework-21.1.0 → brain_framework-21.2.0}/src/bf/starter/concepts/index.md +0 -0
  69. {brain_framework-21.1.0 → brain_framework-21.2.0}/src/bf/starter/concepts/welcome.md +0 -0
  70. {brain_framework-21.1.0 → brain_framework-21.2.0}/src/bf/starter/gitignore +0 -0
  71. {brain_framework-21.1.0 → brain_framework-21.2.0}/src/bf/usage.py +0 -0
  72. {brain_framework-21.1.0 → brain_framework-21.2.0}/src/bf/watch.py +0 -0
  73. {brain_framework-21.1.0 → brain_framework-21.2.0}/src/bf/watch_settings.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: brain-framework
3
- Version: 21.1.0
3
+ Version: 21.2.0
4
4
  Summary: 🧠 Brain Framework: from information to informed actions.
5
5
  Keywords: ai,ai-agents,agent-memory,context-engineering,knowledge-management,local-first,mcp,model-context-protocol,python,second-brain
6
6
  Author: Médéric Hurier
@@ -218,7 +218,7 @@ Use the brain with [Claude Code](https://code.claude.com/docs/en/overview), [Cod
218
218
 
219
219
  > Use the bf CLI. Find why we chose a single product page. Read the source, cite its ref and tell me the project's next action.
220
220
 
221
- It should cite `projects/new-website.md#decision` and name “Draft the product page.” For ongoing use, install the packaged skills into your host's skills folder, such as `~/.claude/skills` for Claude Code:
221
+ It should cite `projects/new-website.md#decision` and name “Draft the product page.” For ongoing use, install the packaged skills into the folder your host discovers (`~/.agents/skills` below; Claude Code uses `~/.claude/skills`):
222
222
 
223
223
  ```bash
224
224
  bf skills ~/.agents/skills
@@ -188,7 +188,7 @@ Use the brain with [Claude Code](https://code.claude.com/docs/en/overview), [Cod
188
188
 
189
189
  > Use the bf CLI. Find why we chose a single product page. Read the source, cite its ref and tell me the project's next action.
190
190
 
191
- It should cite `projects/new-website.md#decision` and name “Draft the product page.” For ongoing use, install the packaged skills into your host's skills folder, such as `~/.claude/skills` for Claude Code:
191
+ It should cite `projects/new-website.md#decision` and name “Draft the product page.” For ongoing use, install the packaged skills into the folder your host discovers (`~/.agents/skills` below; Claude Code uses `~/.claude/skills`):
192
192
 
193
193
  ```bash
194
194
  bf skills ~/.agents/skills
@@ -72,15 +72,15 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
72
72
  SOFTWARE.
73
73
  ```
74
74
 
75
- ## anyio 4.15.1
75
+ ## anyio 4.16.0
76
76
 
77
77
  Source: <https://github.com/agronholm/anyio>
78
78
 
79
79
  License: `MIT`
80
80
 
81
- Evidence: `anyio-4.15.1.dist-info/licenses/LICENSE`
81
+ Evidence: `anyio-4.16.0.dist-info/licenses/LICENSE`
82
82
 
83
- ### anyio-4.15.1.dist-info/licenses/LICENSE
83
+ ### anyio-4.16.0.dist-info/licenses/LICENSE
84
84
 
85
85
  ```text
86
86
  The MIT License (MIT)
@@ -173,15 +173,15 @@ documentation is licensed as follows:
173
173
  DEALINGS IN THE SOFTWARE.
174
174
  ```
175
175
 
176
- ## click 8.5.0
176
+ ## click 8.5.1
177
177
 
178
178
  Source: <https://github.com/pallets/click/>
179
179
 
180
180
  License: `BSD-3-Clause`
181
181
 
182
- Evidence: `click-8.5.0.dist-info/licenses/LICENSE.txt`
182
+ Evidence: `click-8.5.1.dist-info/licenses/LICENSE.txt`
183
183
 
184
- ### click-8.5.0.dist-info/licenses/LICENSE.txt
184
+ ### click-8.5.1.dist-info/licenses/LICENSE.txt
185
185
 
186
186
  ```text
187
187
  Copyright 2014 Pallets
@@ -872,15 +872,15 @@ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
872
872
  IN THE SOFTWARE.
873
873
  ```
874
874
 
875
- ## opentelemetry-api 1.45.1
875
+ ## opentelemetry-api 1.45.2
876
876
 
877
877
  Source: <https://github.com/open-telemetry/opentelemetry-python>
878
878
 
879
879
  License: `Apache-2.0`
880
880
 
881
- Evidence: `opentelemetry_api-1.45.1.dist-info/licenses/LICENSE`
881
+ Evidence: `opentelemetry_api-1.45.2.dist-info/licenses/LICENSE`
882
882
 
883
- ### opentelemetry_api-1.45.1.dist-info/licenses/LICENSE
883
+ ### opentelemetry_api-1.45.2.dist-info/licenses/LICENSE
884
884
 
885
885
  ```text
886
886
  Apache License
@@ -1126,15 +1126,15 @@ LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
1126
1126
  OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
1127
1127
  ```
1128
1128
 
1129
- ## pydantic 2.14.1
1129
+ ## pydantic 2.14.3
1130
1130
 
1131
1131
  Source: <https://github.com/pydantic/pydantic>
1132
1132
 
1133
1133
  License: `MIT`
1134
1134
 
1135
- Evidence: `pydantic-2.14.1.dist-info/licenses/LICENSE`
1135
+ Evidence: `pydantic-2.14.3.dist-info/licenses/LICENSE`
1136
1136
 
1137
- ### pydantic-2.14.1.dist-info/licenses/LICENSE
1137
+ ### pydantic-2.14.3.dist-info/licenses/LICENSE
1138
1138
 
1139
1139
  ```text
1140
1140
  The MIT License (MIT)
@@ -1160,15 +1160,15 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
1160
1160
  SOFTWARE.
1161
1161
  ```
1162
1162
 
1163
- ## pydantic-core 2.50.1
1163
+ ## pydantic-core 2.50.4
1164
1164
 
1165
1165
  Source: <https://github.com/pydantic/pydantic/tree/main/pydantic-core>
1166
1166
 
1167
1167
  License: `MIT`
1168
1168
 
1169
- Evidence: `pydantic_core-2.50.1.dist-info/licenses/LICENSE`
1169
+ Evidence: `pydantic_core-2.50.4.dist-info/licenses/LICENSE`
1170
1170
 
1171
- ### pydantic_core-2.50.1.dist-info/licenses/LICENSE
1171
+ ### pydantic_core-2.50.4.dist-info/licenses/LICENSE
1172
1172
 
1173
1173
  ```text
1174
1174
  The MIT License (MIT)
@@ -1266,15 +1266,15 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
1266
1266
  SOFTWARE.
1267
1267
  ```
1268
1268
 
1269
- ## python-multipart 0.0.32
1269
+ ## python-multipart 0.0.33
1270
1270
 
1271
1271
  Source: <https://github.com/Kludex/python-multipart>
1272
1272
 
1273
1273
  License: `Apache-2.0`
1274
1274
 
1275
- Evidence: `python_multipart-0.0.32.dist-info/licenses/LICENSE.txt`
1275
+ Evidence: `python_multipart-0.0.33.dist-info/licenses/LICENSE.txt`
1276
1276
 
1277
- ### python_multipart-0.0.32.dist-info/licenses/LICENSE.txt
1277
+ ### python_multipart-0.0.33.dist-info/licenses/LICENSE.txt
1278
1278
 
1279
1279
  ```text
1280
1280
  Apache License
@@ -1749,7 +1749,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
1749
1749
  THE SOFTWARE.
1750
1750
  ```
1751
1751
 
1752
- ## typer 0.27.3
1752
+ ## typer 0.28.0
1753
1753
 
1754
1754
  Source: <https://github.com/fastapi/typer>
1755
1755
 
@@ -1757,9 +1757,9 @@ License: `MIT`
1757
1757
 
1758
1758
  The distribution vendors code adapted from Click in `typer/_click/`; its bundled `BSD-3-Clause` license is included below.
1759
1759
 
1760
- Evidence: `typer-0.27.3.dist-info/licenses/LICENSE`
1760
+ Evidence: `typer-0.28.0.dist-info/licenses/LICENSE`
1761
1761
 
1762
- ### typer-0.27.3.dist-info/licenses/LICENSE
1762
+ ### typer-0.28.0.dist-info/licenses/LICENSE
1763
1763
 
1764
1764
  ```text
1765
1765
  The MIT License (MIT)
@@ -2112,15 +2112,15 @@ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
2112
2112
  PERFORMANCE OF THIS SOFTWARE.
2113
2113
  ```
2114
2114
 
2115
- ## typing-inspection 0.4.4
2115
+ ## typing-inspection 0.4.5
2116
2116
 
2117
2117
  Source: <https://github.com/pydantic/typing-inspection>
2118
2118
 
2119
2119
  License: `MIT`
2120
2120
 
2121
- Evidence: `typing_inspection-0.4.4.dist-info/licenses/LICENSE`
2121
+ Evidence: `typing_inspection-0.4.5.dist-info/licenses/LICENSE`
2122
2122
 
2123
- ### typing_inspection-0.4.4.dist-info/licenses/LICENSE
2123
+ ### typing_inspection-0.4.5.dist-info/licenses/LICENSE
2124
2124
 
2125
2125
  ```text
2126
2126
  MIT License
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "brain-framework"
3
- version = "21.1.0"
3
+ version = "21.2.0"
4
4
  description = "🧠 Brain Framework: from information to informed actions."
5
5
  readme = "README.md"
6
6
  requires-python = ">=3.14"
@@ -170,5 +170,5 @@ dev = [
170
170
  "ruff>=0.16.6",
171
171
  "ty>=0.0.70,<0.1",
172
172
  "validate-pyproject[all]>=0.25",
173
- "zensical>=0.0.59,<0.1",
173
+ "zensical>=0.1.0,<0.2",
174
174
  ]
@@ -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 = "21.1.0"
4
+ version = "21.2.0"
5
5
  description = "🧠 Brain Framework: from information to informed actions."
6
6
  readme = "README.md"
7
7
  requires-python = ">=3.14"
@@ -74,7 +74,7 @@ dev = [
74
74
  "ty>=0.0.70,<0.1",
75
75
  # The extra validates classifiers offline instead of downloading them or skipping the check.
76
76
  "validate-pyproject[all]>=0.25",
77
- "zensical>=0.0.59,<0.1",
77
+ "zensical>=0.1.0,<0.2",
78
78
  ]
79
79
 
80
80
  [tool.ruff]
@@ -2,7 +2,7 @@
2
2
 
3
3
  import os
4
4
 
5
- __version__ = "21.1.0"
5
+ __version__ = "21.2.0"
6
6
 
7
7
 
8
8
  def main() -> None:
@@ -486,14 +486,16 @@ def _execute(store: Store, key: str, runner: Runner) -> dict[str, object]:
486
486
  else "assistant execution or saved reply failed; inspect its local log"
487
487
  )
488
488
  if current["state"] not in {"complete", "cancelled"}:
489
- # A harness that never started cannot have acted: its job fails plainly instead of uncertainly. A
490
- # failed gate retries by itself: no harness ran.
489
+ # A harness that never started cannot have acted: its job fails plainly instead of uncertainly, and
490
+ # retries like a failed attempt when the run is idempotent. A failed gate retries by itself: no
491
+ # harness ran.
492
+ idempotent = retried(work.settings.idempotent, work.kind)
491
493
  queue.fail(
492
494
  key,
493
495
  message,
494
496
  uncertain=current["state"] == "running" and not isinstance(error, NotStartedError),
495
- idempotent=retried(work.settings.idempotent, work.kind),
496
- retry=isinstance(error, GateError),
497
+ idempotent=idempotent,
498
+ retry=isinstance(error, GateError) or (idempotent and isinstance(error, NotStartedError)),
497
499
  )
498
500
  with suppress(Error, OSError):
499
501
  append_log(store, work.assistant, message)
@@ -526,6 +528,10 @@ def deliver(
526
528
  key, name = str(delivery["id"]), str(delivery["channel"])
527
529
  lock = f".delivery-{digest(key.encode())}"
528
530
  with collecting(store, lock):
531
+ # Read it again under the lock: another process may have sent, failed or rescheduled it meanwhile.
532
+ delivery = queue.delivery(job=job, key=key, names=names)
533
+ if delivery is None:
534
+ return False
529
535
  try:
530
536
  try:
531
537
  command = Send.model_validate_json(str(delivery["command"]))
@@ -190,6 +190,13 @@ def emit(value: object, *, reply: bool = True) -> None:
190
190
  _write(terminal(present(value) if reply else value))
191
191
 
192
192
 
193
+ def _finish(value: object, *, failed: bool) -> None:
194
+ """Print a reply, then exit 1 when it reports a failed operation: the reply says what failed."""
195
+ emit(value)
196
+ if failed:
197
+ raise typer.Exit(1)
198
+
199
+
193
200
  def _write(data: bytes, *, flush: bool = True) -> None:
194
201
  """Write reply bytes; standard output that cannot take them, such as a full disk, fails the command."""
195
202
  try:
@@ -275,7 +282,7 @@ _PEOPLE = {
275
282
  "author": "Account explicitly credited as author; authorship is not ownership.",
276
283
  "owner": "Account or organization the provider declares responsible for the item.",
277
284
  "assignee": "Account assigned responsibility for the item.",
278
- "participant": "Any account in a message, event or meeting; the specific roles list here too.",
285
+ "participant": "Any account in a message, event or meeting; its narrower relations, such as sender, list here too.",
279
286
  }
280
287
  _ROLES = {
281
288
  "sender": "Account that sent the message.",
@@ -459,9 +466,7 @@ def install(
459
466
  from bf.install import skills
460
467
 
461
468
  result = skills(destination, check=check, force=force)
462
- emit(result)
463
- if not result["ok"]:
464
- raise typer.Exit(1)
469
+ _finish(result, failed=not result["ok"])
465
470
 
466
471
 
467
472
  @app.command("schema", rich_help_panel="Set up")
@@ -645,6 +650,9 @@ def forget_records(
645
650
  """Remove collected records and keep their sensors from storing them again; Git history keeps old copies."""
646
651
  targets: dict[str, dict[str, str]] = {}
647
652
  for ref in refs:
653
+ # The UTF-8 check of single values skips arguments that take several, as `run` passes Git's arguments as given.
654
+ if _surrogates(ref):
655
+ raise typer.BadParameter("expected UTF-8 text", param_hint="REF")
648
656
  try:
649
657
  source, entry = records.target(ref)
650
658
  except Error as error:
@@ -664,7 +672,8 @@ def forget_records(
664
672
  result: dict[str, object] = {"ok": True, "dry_run": dry_run, "records": removed}
665
673
  if not dry_run:
666
674
  result["index"] = index.refresh(store, recover=True)
667
- emit(result)
675
+ # Like build and update: a skipped file hides evidence, and bf validate names it.
676
+ _finish(result, failed=bool(cast("dict[str, int]", result.get("index", {})).get("skipped")))
668
677
 
669
678
 
670
679
  @app.command("run", rich_help_panel="Collect and automate")
@@ -724,22 +733,20 @@ def perform(
724
733
  except UnicodeError as error:
725
734
  raise Error("assistant input must be UTF-8 text") from error
726
735
  result = run_assistant(store, names[0], text=text, dry_run=dry_run)
727
- emit(result)
728
- if not result["ok"]:
729
- raise typer.Exit(1)
736
+ _finish(result, failed=not result["ok"])
730
737
  return
731
738
  # Git closes a hook's input; an agent's shell can hold its own open, so a direct run reads it only on request,
732
739
  # and a hook only for the routines it runs: a hook that no routine lists succeeds at once.
733
740
  stdin = _input() if forward or (hook and hooked(config, hook)) else b""
734
741
  result = run_routines(store, names=names, hook=hook, args=args, stdin=stdin, dry_run=dry_run)
735
- emit(result)
736
- if not result["ok"]:
737
- raise typer.Exit(1)
742
+ _finish(result, failed=not result["ok"])
738
743
 
739
744
 
740
745
  @app.command("channel", rich_help_panel="Collect and automate")
741
746
  def channel_command(
742
- action: Annotated[Literal["read", "send"], typer.Argument(help="Read a bounded batch or send one message.")],
747
+ action: Annotated[
748
+ Literal["read", "send"], typer.Argument(metavar="ACTION", help="Read a bounded batch or send one message.")
749
+ ],
743
750
  name: Annotated[str, typer.Argument(metavar="CHANNEL", help="A configured channel name.")],
744
751
  brain: RunOption = "",
745
752
  since: Annotated[str, typer.Option(help="Required start of a read window.")] = "",
@@ -791,9 +798,7 @@ def channel_command(
791
798
  )
792
799
  if saved["receipt"]:
793
800
  saved["receipt"] = decode(saved["receipt"])
794
- emit(saved)
795
- if saved["state"] != "delivered":
796
- raise typer.Exit(1)
801
+ _finish(saved, failed=saved["state"] != "delivered")
797
802
 
798
803
 
799
804
  @app.command("queue", rich_help_panel="Collect and automate")
@@ -818,9 +823,9 @@ def queue_command(
818
823
  if retry and "channel" in saved:
819
824
  assistants.deliver(queue.brain, key=key)
820
825
  saved = queue.inspect(key)
821
- emit({"id": key, "status": saved["state"]})
822
- if retry and "channel" in saved and saved["state"] != "delivered":
823
- raise typer.Exit(1)
826
+ _finish(
827
+ {"id": key, "status": saved["state"]}, failed=retry and "channel" in saved and saved["state"] != "delivered"
828
+ )
824
829
  elif key:
825
830
  row = queue.inspect(key)
826
831
  for name in ("payload", "prepared", "command", "receipt"):
@@ -857,9 +862,7 @@ def refresh(
857
862
  assistants=tuple(assistant or ()),
858
863
  kinds=kinds,
859
864
  )
860
- emit(result)
861
- if not result["ok"]:
862
- raise typer.Exit(1)
865
+ _finish(result, failed=not result["ok"])
863
866
 
864
867
 
865
868
  def _kinds(values: list[str]) -> frozenset[ProgramKind]:
@@ -941,18 +944,14 @@ def report(
941
944
  observe(one(brain), observe=True)
942
945
  return
943
946
  result = health.report(select(brain))
944
- emit(result)
945
- if check and not result["healthy"]:
946
- raise typer.Exit(1)
947
+ _finish(result, failed=check and not result["healthy"])
947
948
 
948
949
 
949
950
  @app.command("validate", rich_help_panel="Check and repair")
950
951
  def check(brain: OneBrainOption = "") -> None:
951
952
  """Check OKF projects, concepts and ACTION.md notes, links, record files and program files; exit 1 on problems."""
952
953
  result = validate(one(brain))
953
- emit(result)
954
- if not result["valid"]:
955
- raise typer.Exit(1)
954
+ _finish(result, failed=not result["valid"])
956
955
 
957
956
 
958
957
  @app.command("eval", rich_help_panel="Check and repair")
@@ -972,9 +971,7 @@ def acceptance(
972
971
  _option("--path", relative, path)
973
972
  previous = _option("--baseline", load_baseline, str(baseline)) if baseline else None
974
973
  result = evaluate(one(brain), path, previous)
975
- emit(result)
976
- if not result["passed"]:
977
- raise typer.Exit(1)
974
+ _finish(result, failed=not result["passed"])
978
975
 
979
976
 
980
977
  @app.command("build", rich_help_panel="Check and repair")
@@ -1002,9 +999,7 @@ def rebuild(
1002
999
  result = remap(store, reproject, dry_run=dry_run)
1003
1000
  if not dry_run:
1004
1001
  result["index"] = index.refresh(store, recover=True)
1005
- emit(result)
1006
- if result["failed"] or cast("dict[str, int]", result.get("index", {})).get("skipped"):
1007
- raise typer.Exit(1)
1002
+ _finish(result, failed=bool(result["failed"] or cast("dict[str, int]", result.get("index", {})).get("skipped")))
1008
1003
  return
1009
1004
  result = index.refresh(store, full=True)
1010
1005
  emit(result)
@@ -1064,6 +1059,7 @@ def _input() -> bytes:
1064
1059
  _GIVEN = {
1065
1060
  "--brain": "give a brain name or path; an empty value would select another brain",
1066
1061
  "--hook": "give an event name; an empty value would run the first argument as a routine",
1062
+ "--input": "give a file, or - for stdin; an empty value would run the sensor",
1067
1063
  "--assistant": "give an assistant name; an empty value names none",
1068
1064
  "--reproject": "give a sensor name; an empty value would rebuild the cache instead",
1069
1065
  "--routine": "give a routine name; an empty value names none",
@@ -518,8 +518,7 @@ def collect(
518
518
  # Forgotten and expired records leave on purpose: only other removals need --allow-removal.
519
519
  if snapshot and not allow_removal and (refusal := _shrink(store, name, kept)):
520
520
  raise Error(refusal)
521
- records.remove(store, name, kept.removals)
522
- result.update(records.upsert(store, name, kept.kept, snapshot=snapshot))
521
+ result.update(records.upsert(store, name, kept.kept, snapshot=snapshot, removals=kept.removals))
523
522
  result.update(records=len(kept.kept), **_retention(kept))
524
523
  committed = True
525
524
  result["elapsed_seconds"] = round(time.monotonic() - measured, 6)
@@ -14,8 +14,8 @@ from bf import __version__, index, usage
14
14
  from bf.config import Selection, brain_name, load, related
15
15
  from bf.history import ASSISTANTS, ROUTINES, log_path, state
16
16
  from bf.models import CACHE, Assistant, Config, Error, Program, Sensor, decode, timestamp
17
- from bf.runtime import DATABASE, Queue, check_schema, check_version
18
- from bf.storage import Store
17
+ from bf.runtime import Queue, check_schema, check_version
18
+ from bf.storage import QUEUE, Store
19
19
 
20
20
  # Counters of the last committed collection, reported apart from indexed totals.
21
21
  _COUNTERS = (
@@ -163,20 +163,20 @@ class _Reader(Queue):
163
163
  def exists(self) -> bool:
164
164
  # Execution creates the file, then commits its schema: until then the queue holds nothing.
165
165
  try:
166
- return self.store.lstat(DATABASE).st_size > 0
166
+ return self.store.lstat(QUEUE).st_size > 0
167
167
  except FileNotFoundError:
168
168
  return False
169
169
 
170
170
  @contextmanager
171
171
  def connect(self) -> Generator[sqlite3.Connection]:
172
- info = self.store.lstat(DATABASE)
172
+ info = self.store.lstat(QUEUE)
173
173
  if info.st_uid != os.getuid() or info.st_mode & 0o077:
174
174
  raise Error("assistant queue must be a private regular file owned by you")
175
175
  for suffix in ("-wal", "-shm", "-journal"):
176
176
  with suppress(FileNotFoundError):
177
- self.store.lstat(DATABASE + suffix)
177
+ self.store.lstat(QUEUE + suffix)
178
178
  try:
179
- uri = (self.store.root / DATABASE).as_uri() + "?mode=ro"
179
+ uri = (self.store.root / QUEUE).as_uri() + "?mode=ro"
180
180
  connection = sqlite3.connect(uri, uri=True, timeout=10, isolation_level=None)
181
181
  try:
182
182
  connection.row_factory = sqlite3.Row
@@ -881,7 +881,7 @@ def _replace(store: Store) -> None:
881
881
  live.execute("PRAGMA journal_mode=DELETE")
882
882
  break
883
883
  except sqlite3.OperationalError as error:
884
- if error.sqlite_errorcode not in {sqlite3.SQLITE_BUSY, sqlite3.SQLITE_LOCKED}:
884
+ if error.sqlite_errorcode & 0xFF not in {sqlite3.SQLITE_BUSY, sqlite3.SQLITE_LOCKED}:
885
885
  raise
886
886
  if time.monotonic() >= deadline:
887
887
  raise BusyError("readers kept the search cache open; retry bf build") from error
@@ -1168,9 +1168,10 @@ _ROW = f"{_FIELDS},'' AS fragment,i.title,i.lead AS excerpt,i.tasks_open,i.tasks
1168
1168
  def within(column: str, note: str) -> str:
1169
1169
  """Fixed SQL: whether `column` names a section of `note`, a note path or BF address, as `note#fragment` does.
1170
1170
 
1171
- A range over the column's index: `$` follows `#`, so every `note#...` sorts between them.
1171
+ A range over the column's index: `$` follows `#`, so every `note#...` sorts between them. A fragment never ends
1172
+ in `.md`, so a path such as `a.md#x.md` names another note, not a section of `a.md`.
1172
1173
  """
1173
- return f"{column}>{note}||'#' AND {column}<{note}||'$'"
1174
+ return f"{column}>{note}||'#' AND {column}<{note}||'$' AND substr({column},-3)!='.md'"
1174
1175
 
1175
1176
 
1176
1177
  # Fixed SQL: each name of the JSON array :names that exactly one item holds, with that item. A name that several
@@ -1775,7 +1776,8 @@ def status(store: Store) -> dict[str, object]:
1775
1776
  sizes = dict(
1776
1777
  connection.execute(
1777
1778
  "SELECT substr(path,10,instr(substr(path,10),'/')-1),sum(size) FROM files "
1778
- "WHERE path GLOB 'memories/?*/*' GROUP BY 1"
1779
+ # A size of -1 marks a file a transient error left unstated.
1780
+ "WHERE path GLOB 'memories/?*/*' AND size>=0 GROUP BY 1"
1779
1781
  ).fetchall()
1780
1782
  )
1781
1783
  for source, entry in counts.items():
@@ -647,7 +647,8 @@ def validate_okf(path: str, data: bytes | Markdown) -> None:
647
647
  return
648
648
  if not isinstance(attributes.get("type"), str) or not str(attributes["type"]).strip():
649
649
  raise Error(f"{path}: OKF documents require a nonempty type in YAML frontmatter")
650
- if attributes.get("status", "stable") not in {"draft", "stable", "deprecated"}:
650
+ status = attributes.get("status", "stable")
651
+ if not isinstance(status, str) or status not in {"draft", "stable", "deprecated"}:
651
652
  raise Error(f"{path}: OKF status must be draft, stable or deprecated")
652
653
  aliases = attributes.get("aliases", [])
653
654
  if not isinstance(aliases, list) or not all(isinstance(v, str) and re.fullmatch(IDENTITY, v) for v in aliases):
@@ -831,48 +831,31 @@ def memories(
831
831
  return None
832
832
  return {"sources": [{"source": source, **count, **source_health(store, {source: count}, now=now)[source]}]}
833
833
 
834
+ window = None
834
835
  if len(parts) == 2:
835
836
  # A record's time is its stored instant: ordering by the column walks items_kind_source_time.
836
- reply, found = _listing(
837
- stores,
838
- "i.kind='record' AND i.source=:source",
839
- {"source": source},
840
- "i.time DESC,i.ref DESC",
841
- _time_key,
842
- SECTION,
843
- offset,
844
- counted=counted,
845
- kind="source",
846
- summary=coverage,
847
- )
848
- if not found:
849
- # An unknown source is a missing page, never an empty answer.
850
- raise absent(reply, _MISSING + suggest(source, known, prefix="memories/"))
851
- return {"page": "/".join(parts), "sources": _gather(found, "sources"), **reply}
852
- name = parts[2]
853
- window = None if name.endswith(".json") else period(name, now)
854
- if window:
855
- where = f"i.kind='record' AND i.source=:source AND {index.PERIOD_WITHIN}"
856
- params = {"source": source, "since": window.since, "until": window.until}
857
- elif name == "undated":
858
- where, params = "i.kind='record' AND i.source=:source AND i.time=''", {"source": source}
859
- elif re.fullmatch(r"[0-9a-f]{64}\.json", name):
860
- where, params = "i.kind='record' AND i.path=:path", {"path": f"memories/{source}/{name}"}
837
+ where, params = "i.kind='record' AND i.source=:source", {"source": source}
838
+ order, key, budget, kind = "i.time DESC,i.ref DESC", _time_key, SECTION, "source"
861
839
  else:
862
- raise NotFoundError(_MISSING)
840
+ name = parts[2]
841
+ window = None if name.endswith(".json") else period(name, now)
842
+ if window:
843
+ where = f"i.kind='record' AND i.source=:source AND {index.PERIOD_WITHIN}"
844
+ params = {"source": source, "since": window.since, "until": window.until}
845
+ elif name == "undated":
846
+ where, params = "i.kind='record' AND i.source=:source AND i.time=''", {"source": source}
847
+ elif re.fullmatch(r"[0-9a-f]{64}\.json", name):
848
+ where, params = "i.kind='record' AND i.path=:path", {"path": f"memories/{source}/{name}"}
849
+ else:
850
+ raise NotFoundError(_MISSING)
851
+ order = f"({index.PERIOD_TIME}) DESC,i.ref DESC" if window else "i.time DESC,i.ref DESC"
852
+ key, budget = (_period_key if window else _time_key), PAGE
853
+ kind = "source-period" if window or name == "undated" else "record"
863
854
  reply, found = _listing(
864
- stores,
865
- where,
866
- params,
867
- f"({index.PERIOD_TIME}) DESC,i.ref DESC" if window else "i.time DESC,i.ref DESC",
868
- _period_key if window else _time_key,
869
- PAGE,
870
- offset,
871
- counted=counted,
872
- kind="source-period" if window or name == "undated" else "record",
873
- summary=coverage,
855
+ stores, where, params, order, key, budget, offset, counted=counted, kind=kind, summary=coverage
874
856
  )
875
857
  if not found:
858
+ # An unknown source is a missing page, never an empty answer.
876
859
  raise absent(reply, _MISSING + suggest(source, known, prefix="memories/"))
877
860
  return {
878
861
  "page": "/".join(parts),
@@ -348,9 +348,14 @@ def source_of(name: str) -> str:
348
348
  return parts[1]
349
349
 
350
350
 
351
- def upsert(store: Store, source: str, incoming: list[Record], *, snapshot: bool) -> dict[str, int]:
351
+ def upsert(
352
+ store: Store, source: str, incoming: list[Record], *, snapshot: bool, removals: list[str] | None = None
353
+ ) -> dict[str, int]:
352
354
  """Update independent record files; snapshot removal and all replacements remain transactional.
353
355
 
356
+ `removals`, such as forgotten and expired files, leave in the same transaction without counting as removed, so a
357
+ failed collection never removes them alone.
358
+
354
359
  Only files a change replaces or removes are parsed, and each must hold its own id: collection never
355
360
  overwrites or deletes misnamed evidence, while a file with its own id that breaks the current record
356
361
  rules is replaced like any update. `bf validate` and the search cache check every other file.
@@ -361,6 +366,11 @@ def upsert(store: Store, source: str, incoming: list[Record], *, snapshot: bool)
361
366
  # Only writers holding the brain lock write records: a temporary file there belongs to a killed write.
362
367
  store.sweep(f"memories/{source}")
363
368
  counts, replacements = plan(store, source, incoming, snapshot=snapshot)
369
+ for name in removals or ():
370
+ if name in replacements:
371
+ # A snapshot already planned to remove this file, unwanted, and counted it.
372
+ counts["removed"] -= 1
373
+ replacements[name] = None
364
374
  _commit(store, source, replacements)
365
375
  return counts
366
376
 
@@ -577,7 +587,8 @@ def forget(store: Store, source: str, targets: dict[str, str], *, dry_run: bool
577
587
  if not re.fullmatch(NAME, source):
578
588
  raise Error("invalid record source")
579
589
  recover(store)
580
- hidden = forgotten(store, source)
590
+ known = forgotten(store, source)
591
+ hidden = set(known)
581
592
  result, present = [], []
582
593
  for ref, entry in targets.items():
583
594
  name = f"memories/{source}/{entry}.json"
@@ -592,11 +603,19 @@ def forget(store: Store, source: str, targets: dict[str, str], *, dry_run: bool
592
603
  hidden.add(entry)
593
604
  if dry_run:
594
605
  return result
595
- listed = "".join(f"{entry}\n" for entry in sorted(hidden)).encode()
606
+ # Append, so the owner's comments and order stay as written.
607
+ listing = f"memories/{source}/{FORGOTTEN}"
608
+ try:
609
+ listed = store.read(listing, _FORGOTTEN_LIMIT)
610
+ except FileNotFoundError:
611
+ listed = b""
612
+ if listed and not listed.endswith(b"\n"):
613
+ listed += b"\n"
614
+ listed += "".join(f"{entry}\n" for entry in sorted(hidden - known)).encode()
596
615
  if len(listed) > _FORGOTTEN_LIMIT:
597
- raise Error(f"memories/{source}/{FORGOTTEN} would exceed {_FORGOTTEN_LIMIT:,} bytes; split the source")
616
+ raise Error(f"{listing} would exceed {_FORGOTTEN_LIMIT:,} bytes; split the source")
598
617
  # The list first: a crash before the removal leaves a listed record that the next collection removes.
599
- store.write(f"memories/{source}/{FORGOTTEN}", listed)
618
+ store.write(listing, listed)
600
619
  remove(store, source, present)
601
620
  return result
602
621
 
@@ -33,7 +33,6 @@ from bf.models import (
33
33
  )
34
34
  from bf.storage import QUEUE, BusyError, Store, collecting, lock_file, runtime_store
35
35
 
36
- DATABASE = QUEUE
37
36
  # The queue format this release reads and writes; any other is preserved, never adapted.
38
37
  VERSION = 2
39
38
  MAX_PENDING = 10_000
@@ -205,7 +204,7 @@ class Queue:
205
204
 
206
205
  def exists(self) -> bool:
207
206
  try:
208
- self.store.fingerprint(DATABASE)
207
+ self.store.fingerprint(QUEUE)
209
208
  except FileNotFoundError:
210
209
  return False
211
210
  return True
@@ -216,7 +215,7 @@ class Queue:
216
215
  try:
217
216
  # Never open/close a live SQLite inode ourselves: POSIX close drops this process's locks,
218
217
  # including another thread's transaction. Serialize creation before SQLite can see the file.
219
- with _CREATE, self.store.parent(DATABASE) as (parent, name):
218
+ with _CREATE, self.store.parent(QUEUE) as (parent, name):
220
219
  try:
221
220
  info = os.stat(name, dir_fd=parent, follow_symlinks=False)
222
221
  except FileNotFoundError:
@@ -232,8 +231,8 @@ class Queue:
232
231
  raise Error("assistant queue must be a private regular file owned by you")
233
232
  for suffix in ("-wal", "-shm", "-journal"):
234
233
  with suppress(FileNotFoundError):
235
- self.store.fingerprint(DATABASE + suffix)
236
- connection = sqlite3.connect(self.store.root / DATABASE, timeout=10, isolation_level=None)
234
+ self.store.fingerprint(QUEUE + suffix)
235
+ connection = sqlite3.connect(self.store.root / QUEUE, timeout=10, isolation_level=None)
237
236
  try:
238
237
  connection.row_factory = sqlite3.Row
239
238
  connection.execute("PRAGMA foreign_keys=ON")
@@ -466,7 +465,8 @@ class Queue:
466
465
  accepted.add(message.id)
467
466
  if previous is None:
468
467
  self.reserve(db, 0, 2 * (len(encode(payload)) + len(message.text.encode())))
469
- self.event(db, f"input:{key}", "channel.received", name, payload, message.time)
468
+ # Retention counts from admission: an old backlog message keeps its marker like a new one.
469
+ self.event(db, f"input:{key}", "channel.received", name, payload, now())
470
470
  db.execute(
471
471
  "INSERT OR IGNORE INTO messages VALUES (?,?,?,?,?,?)",
472
472
  (key, name, message.conversation, "user", message.time, message.text),
@@ -8,9 +8,6 @@ Start from a reviewed [sensor example](https://github.com/fmind/brain-framework/
8
8
 
9
9
  ```yaml
10
10
  # https://fmind.github.io/brain-framework/docs/sensors/
11
- fields:
12
- # Beside the existing entries, such as depends-on: bf.yaml has one fields: key.
13
- kind: { description: Common kind of source item., type: string, cardinality: one }
14
11
  sensors:
15
12
  docs:
16
13
  command: [sensors/local-documents.py, team, "{{home}}/Documents/team"]
@@ -23,6 +20,7 @@ sensors:
23
20
  - `command` is direct argv without a shell; arguments accept `{{brain}}`, `{{home}}`, `{{start}}` and `{{end}}`.
24
21
  - `mode: window` (the default) collects a time window each run; `mode: snapshot` returns the whole catalog, and records it no longer returns are removed. Know how the provider reports changes, pagination, partial content and deletions.
25
22
  - `priority: low` quiets a high-volume feed on period and home pages.
23
+ - `kind` is a standard field `bf init` declares; add a field it lacks to the existing top-level `fields:` mapping, since a duplicate key or a second `fields:` breaks every command.
26
24
 
27
25
  A sensor's `fields:` maps each shared field, declared once under the top-level `fields:` of `bf.yaml`, from a JSON pointer into its output (`path`, such as `/attributes/repository_refs`) or a constant (`value`); the sensor prints `attributes`, never `fields`. Emit explicit namespaced identities only (`person:email/address`, `repo:github.com/owner/name`, lowercase as the reviewed examples write them); `links` and `url` take identities or URLs. Keep the upstream modification time in `attributes.updated`, which flags linking notes for review, and mark incomplete text with `attributes.partial`. See [good records](https://fmind.github.io/brain-framework/docs/sensors/#good-records) and the [limits](https://fmind.github.io/brain-framework/docs/limits/).
28
26
 
@@ -28,7 +28,7 @@ A brain is a folder of plain files: `projects/` and `concepts/` hold authored no
28
28
  - `bf read 'REF' --rel RELATION` lists every backlink of a relation beyond the 5 previewed.
29
29
  1. **Qualify** before concluding.
30
30
  - Exit 2 names the invalid argument: fix it.
31
- - `problems` (skipped files) and `stale` (a busy cache) make a result incomplete: retry. An incomplete or empty result never proves absence.
31
+ - `stale` (a busy cache): retry shortly. `problems` (skipped files, identities or brains): report them; `bf validate` names files and `bf-maintain` repairs them. Either makes a result incomplete, and an incomplete or empty result never proves absence.
32
32
  - A source `overdue`, `never` collected, `failed` or `silent` may lack evidence; collecting it needs `bf-maintain` and the user's authority.
33
33
  1. **Answer** with the conclusion, its refs and the remaining uncertainty; distinguish what the brain records from what is true now.
34
34
 
@@ -13,33 +13,20 @@ Read the exact note section or record with `bf read`. In a dated decision note,
13
13
  - A record of a source Git ignores, as `bf init` ignores `memories/`, goes in the ignored `originals/` folder; cite its path in a code span, since a link fails `bf validate` in clones that lack the file.
14
14
  - An authored note, or a record Git versions, goes in the owning action's `inputs/`, otherwise in `assets/`.
15
15
 
16
- The [evidence helper](../scripts/evidence.py) never contacts a network. `read REF --brain PATH` prints the whole exact reply of the offline `bf read`. `capture` keeps one exact read's text or record, source metadata, local capture time and a content digest, and refuses listing pages, lone text pages and incomplete or `stale` reads: a local observation, not proof of truth or live provider state. `capture` and `compare` read at most 19 MiB of standard input per reply or capture; beyond that, capture a note section or a smaller record.
16
+ The [evidence helper](../scripts/evidence.py) never contacts a network. `read REF --brain PATH` prints the whole exact reply of the offline `bf read`. `capture` keeps one exact read's text or record, source metadata, local capture time and a content digest, and refuses listing pages, lone text pages and incomplete or `stale` reads: a local observation, not proof of truth or live provider state. A capture or saved reply may hold at most 19 MiB; beyond that, capture a note section or a smaller record.
17
17
 
18
- Below, `$evidence_ref` is the exact ref (with several brains, its `uri`), `$new_capture` an unused `.json` path and `$saved_capture` an earlier capture. This subshell writes an owner-only capture, never replaces an earlier one and removes only a capture it failed to write:
18
+ Capture the exact ref (with several brains, its `uri`) into `NEW.json`, an unused path in an existing folder chosen as above:
19
19
 
20
20
  ```bash
21
- (
22
- set -o pipefail -o noclobber
23
- umask 077
24
- mkdir -p -- "$(dirname -- "$new_capture")" || exit 1
25
- exec 3> "$new_capture" || exit 1
26
- python3 "$SKILL_DIR/scripts/evidence.py" read "$evidence_ref" --brain "$brain_path" |
27
- python3 "$SKILL_DIR/scripts/evidence.py" capture >&3 || { rm -f -- "$new_capture"; exit 1; }
28
- )
21
+ python3 SKILL_DIR/scripts/evidence.py capture 'REF' --brain PATH --output NEW.json
29
22
  ```
30
23
 
31
- Captures may hold private or external text: give them the original's audience, and check the brain's ignore rules before committing action inputs or assets.
24
+ It replies `{"captured":"NEW.json"}` and writes an owner-only file, never replaces an existing one and keeps nothing when the read fails or is incomplete. Captures may hold private or external text: give them the original's audience, and check the brain's ignore rules before committing action inputs or assets.
32
25
 
33
- To compare, supply the saved capture followed by a new exact read:
26
+ To compare, pass the saved capture (`SAVED.json`), then the same ref:
34
27
 
35
28
  ```bash
36
- (
37
- set -o pipefail
38
- {
39
- cat "$saved_capture"
40
- python3 "$SKILL_DIR/scripts/evidence.py" read "$evidence_ref" --brain "$brain_path"
41
- } | python3 "$SKILL_DIR/scripts/evidence.py" compare
42
- )
29
+ python3 SKILL_DIR/scripts/evidence.py compare SAVED.json 'REF' --brain PATH
43
30
  ```
44
31
 
45
32
  Only this compact comparison reaches the model. `state` is `changed`, `unchanged` or `unknown`; `content_changed` compares stored content even when freshness is unknown.
@@ -13,14 +13,14 @@ A typed link states a relation: `[Decision](bf://NAME/projects/new-website.md?re
13
13
  - The link's section is the claim's `origin`: keep the supporting observation beside it.
14
14
  - In a `bf://` link to a record, percent-encode a `#` or `?` of its id as `%23` or `%3F`.
15
15
 
16
- Declare each relation once under `fields:` in `bf.yaml`: `bf init` declares `author`, `owner`, `depends-on` and `related-to`, and `cites`, `links` and `tagged-with` are reserved. `bf validate` names an undeclared relation, whose links stay untyped. Merge a new relation into the existing mapping, since a second `fields:` key is invalid:
16
+ Declare each relation once under `fields:` in `bf.yaml`: `bf init` declares the [standard vocabulary](https://fmind.github.io/brain-framework/docs/schema/#standard-vocabulary), including `owner`, `depends-on`, `related-to` and `supersedes`, and `cites`, `links` and `tagged-with` are reserved. Check `bf.yaml` before adding one: a name it already lists is a duplicate key that breaks every command. `bf validate` names an undeclared relation, whose links stay untyped. Merge a new relation into the existing mapping, since a second `fields:` key is invalid:
17
17
 
18
18
  ```yaml
19
19
  # https://fmind.github.io/brain-framework/docs/schema/
20
20
  fields:
21
- # Keep the existing relations, such as depends-on.
22
- supersedes:
23
- description: This authored decision explicitly replaces the target decision.
21
+ # Keep the existing entries, such as depends-on.
22
+ verifies:
23
+ description: This authored check explicitly verifies the target claim.
24
24
  type: identity
25
25
  cardinality: many
26
26
  relation: true
@@ -6,7 +6,7 @@ Use when a reply is paged, a graph claim matters or an answer must be complete;
6
6
 
7
7
  Keep the query or ref, scope, limit and brain selection unchanged and pass each `next_offset` to `--offset` until it is absent; restart when evidence or the selected brains change meanwhile. A page or preview is never the complete result.
8
8
 
9
- An exact read above 32 KiB returns its text in pages; the first carries the backlinks, claims and, when headings divide the read, an `outline`: read a section it lists when that answers the question. To assemble the whole text, run `python3 "$SKILL_DIR/scripts/evidence.py" read REF --brain PATH`: it follows every page, checks that each names the same file `sha256` and keeps every page's `problems` and `stale`. It prints the whole reply at once, past the 32 KiB page budget: redirect it to an owner-only file outside the brain, or pipe it as the [evidence guide](evidence.md#retain-a-revision) does.
9
+ An exact read above 32 KiB returns its text in pages; the first carries the backlinks, claims and, when headings divide the read, an `outline`: read a section it lists when that answers the question. To assemble the whole text, run `python3 SKILL_DIR/scripts/evidence.py read 'REF' --brain PATH`: it follows every page, checks that each names the same file `sha256` and keeps every page's `problems` and `stale`. It prints the whole reply at once, past the 32 KiB page budget: to keep it, [capture it](evidence.md#retain-a-revision) to an owner-only file instead.
10
10
 
11
11
  ## Write refs exactly
12
12
 
@@ -1,17 +1,21 @@
1
1
  #!/usr/bin/env python3
2
2
  """Read one exact bf reply whole, capture it, or compare a retained capture with a new read.
3
3
 
4
- `read` runs the offline `bf read` and assembles text pages; `capture` and `compare` use stdin only.
4
+ `read` runs the offline `bf read` and assembles text pages. `capture` and `compare` read stdin, or, given a ref and
5
+ `--brain`, run that read themselves: `capture REF --brain BRAIN --output NEW` writes an owner-only file that must not
6
+ exist yet, and `compare SAVED REF --brain BRAIN` compares a saved capture with a new read, without shell pipes.
5
7
  """
6
8
 
7
9
  from __future__ import annotations
8
10
 
9
11
  import hashlib
10
12
  import json
13
+ import os
11
14
  import re
12
15
  import subprocess
13
16
  import sys
14
17
  from datetime import UTC, datetime
18
+ from pathlib import Path
15
19
  from typing import TypeAlias, cast
16
20
 
17
21
  # Agents run this helper with whatever python3 is on PATH: keep it compatible with Python 3.11.
@@ -250,23 +254,61 @@ def compare(before: dict[str, JSON], after: dict[str, JSON]) -> dict[str, JSON]:
250
254
  }
251
255
 
252
256
 
257
+ def saved(path: str) -> dict[str, JSON]:
258
+ """A capture file, bounded like standard input."""
259
+ with Path(path).open("rb") as stream:
260
+ data = stream.read(MAX_INPUT + 1)
261
+ if len(data) > MAX_INPUT:
262
+ raise ValueError("capture exceeds the input limit")
263
+ return object_value(json.loads(data, object_pairs_hook=unique))
264
+
265
+
266
+ def save(path: str, data: bytes) -> None:
267
+ """Create `path` exclusively, owner-only, never through a symbolic link; remove it if writing fails."""
268
+ descriptor = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o600)
269
+ try:
270
+ with os.fdopen(descriptor, "wb") as stream:
271
+ stream.write(data)
272
+ except BaseException:
273
+ Path(path).unlink(missing_ok=True)
274
+ raise
275
+
276
+
253
277
  def main() -> int:
254
278
  arguments = sys.argv[1:]
255
- if arguments[:1] == ["read"] and len(arguments) == 4 and arguments[2] == "--brain":
256
- ref, brain = arguments[1], arguments[3]
279
+ mode, rest = (arguments[0], arguments[1:]) if arguments else ("", [])
280
+ # A literal command: capture REF --brain BRAIN --output NEW, compare SAVED REF --brain BRAIN or read REF --brain BRAIN.
281
+ shapes = {"read": (0, 3, ""), "capture": (0, 5, "--output"), "compare": (1, 4, "")}
282
+ first, size, option = shapes.get(mode, (0, -1, ""))
283
+ if len(rest) == size and rest[first + 1] == "--brain" and (not option or rest[first + 3] == option):
284
+ ref, brain = rest[first], rest[first + 2]
257
285
  # bf would parse a leading hyphen as an option; the brain is always an option value.
258
286
  if not ref or ref.startswith("-") or len(ref) > 8192 or any(ord(c) < 32 for c in ref) or not brain:
259
287
  sys.stderr.write("evidence: expected an exact ref and a brain name or path\n")
260
288
  return 2
261
289
  try:
262
- output = terminal(exact(ref, brain))
290
+ before = saved(rest[0]) if mode == "compare" else {}
291
+ reply = exact(ref, brain)
292
+ output = terminal(
293
+ reply if mode == "read" else capture(reply) if mode == "capture" else compare(before, reply)
294
+ )
263
295
  except (OSError, subprocess.TimeoutExpired, ValueError, TypeError, RecursionError):
264
- sys.stderr.write("evidence: bf read failed or changed while reading; inspect the exact read and retry\n")
296
+ sys.stderr.write("evidence: a read or capture failed, changed or is incomplete; inspect it and retry\n")
265
297
  return 1
298
+ if mode == "capture":
299
+ try:
300
+ save(rest[4], output + b"\n")
301
+ except OSError:
302
+ sys.stderr.write("evidence: --output must be a new file in an existing folder; nothing was kept\n")
303
+ return 1
304
+ output = terminal({"captured": rest[4]})
266
305
  sys.stdout.buffer.write(output + b"\n")
267
306
  return 0
268
307
  if len(arguments) != 1 or arguments[0] not in {"capture", "compare"}:
269
- sys.stderr.write("usage: evidence.py read REF --brain BRAIN | evidence.py capture|compare < JSON\n")
308
+ sys.stderr.write(
309
+ "usage: evidence.py read REF --brain BRAIN | capture REF --brain BRAIN --output NEW"
310
+ " | compare SAVED REF --brain BRAIN | capture|compare < JSON\n"
311
+ )
270
312
  return 2
271
313
  count = 1 if arguments[0] == "capture" else 2
272
314
  limit = count * MAX_INPUT
@@ -13,4 +13,4 @@ State the useful knowledge and its limits. Add `sources` mappings with a `resour
13
13
 
14
14
  ## Related knowledge
15
15
 
16
- Use ordinary relative links for navigation, such as `[Other](/other.md)` for `concepts/other.md`, or a declared typed BF link for a relation: `[Related](bf://NAME/concepts/OTHER.md?rel=related-to)`. Replace placeholders with verified identities. `bf init` declares `author`, `owner`, `depends-on` and `related-to`; declare any other relation under `fields:` in `bf.yaml` first. Use `entity` only when this note explicitly owns that identity, `aliases` only for namespaced identities such as `repo:github.com/owner/name` (lowercase, as the example sensors write it) and `resource` for the URI of the asset this note describes.
16
+ Use ordinary relative links for navigation, such as `[Other](/other.md)` for `concepts/other.md`, or a declared typed BF link for a relation: `[Related](bf://NAME/concepts/OTHER.md?rel=related-to)`. Replace placeholders with verified identities. `bf init` declares the standard relations, such as `owner`, `depends-on`, `related-to` and `supersedes`; declare any other relation under `fields:` in `bf.yaml` first. Use `entity` only when this note explicitly owns that identity, `aliases` only for namespaced identities such as `repo:github.com/owner/name` (lowercase, as the example sensors write it) and `resource` for the URI of the asset this note describes.
@@ -11,7 +11,10 @@ cases:
11
11
  # A qualified address still resolves once a related brain also holds concepts/welcome.md.
12
12
  read: bf://$name/concepts/welcome.md
13
13
  expect: [concepts/welcome.md]
14
- text: [Write one note per project in projects/, reusable knowledge in concepts/]
14
+ # Two fragments, each found in the note.
15
+ text:
16
+ - Write one note per project in projects/
17
+ - reusable knowledge in concepts/
15
18
  - name: absent-starter-topic
16
19
  query: bfabsentevidence9c4f2a7d
17
20
  empty: true
@@ -311,6 +311,14 @@ class Store:
311
311
  raise
312
312
  skipped[f"{prefix}/{shown}" if shown is not None else path] = stamp
313
313
  continue
314
+ except OSError as error:
315
+ # A folder replaced by a link or a file after listing: report it as the next scan sees it.
316
+ if error.errno not in {errno.ELOOP, errno.ENOTDIR}:
317
+ raise
318
+ if skipped is None:
319
+ raise Error(f"{path}: symlinks and special files are forbidden") from error
320
+ skipped[path] = stamp
321
+ continue
314
322
  if shown is not None:
315
323
  if skipped is None:
316
324
  raise Error(f"{prefix}/{shown}: {UNNAMED}")
@@ -6,6 +6,8 @@ from collections.abc import Generator
6
6
  from concurrent.futures import ThreadPoolExecutor
7
7
  from contextlib import ExitStack, contextmanager, nullcontext
8
8
  from datetime import UTC, datetime
9
+ from functools import partial
10
+ from threading import Event
9
11
  from typing import Literal
10
12
 
11
13
  from bf import assistants as assistant_runtime
@@ -140,7 +142,9 @@ def update(
140
142
  windows = [item for item in due(store, now) if item[0] in selected_sensors]
141
143
  routine_windows = [item for item in due_routines(store, now) if item[0] in selected_routines]
142
144
 
143
- def _collect_sensor(item: tuple[str, str, str, bool]) -> tuple[dict[str, object], bool]:
145
+ def _collect_sensor(
146
+ item: tuple[str, str, str, bool], runner: Runner = runner
147
+ ) -> tuple[dict[str, object], bool]:
144
148
  sensor, start, end, reconcile = item
145
149
  result: dict[str, object] = {"sensor": sensor, "start": start, "end": end, "reconcile": reconcile}
146
150
  if dry_run:
@@ -160,8 +164,17 @@ def update(
160
164
  return result, True
161
165
 
162
166
  if len(windows) > 1 and not dry_run:
163
- with ThreadPoolExecutor(max_workers=min(WORKERS, len(windows))) as pool:
164
- outcomes = list(pool.map(_collect_sensor, windows))
167
+ # Signals reach only the main thread: on cancellation, stop the workers' programs instead of waiting for them.
168
+ stop = Event()
169
+ parallel = partial(run, cancelled=stop.is_set) if runner is run else runner
170
+ pool = ThreadPoolExecutor(max_workers=min(WORKERS, len(windows)))
171
+ try:
172
+ outcomes = list(pool.map(partial(_collect_sensor, runner=parallel), windows))
173
+ except BaseException:
174
+ stop.set()
175
+ raise
176
+ finally:
177
+ pool.shutdown(wait=True, cancel_futures=True)
165
178
  else:
166
179
  outcomes = [_collect_sensor(item) for item in windows]
167
180
  for result, item_failed in outcomes:
@@ -275,9 +275,10 @@ class _Validation:
275
275
 
276
276
  def evidence(self) -> None:
277
277
  store, config = self.store, self.config
278
+ listed = store.files("memories", skipped=self.skipped, split=True)
278
279
  evidence = [
279
280
  name
280
- for name in store.files("memories", skipped=self.skipped, split=True)
281
+ for name in listed
281
282
  # Check every file collection and search read as a record, even a hidden AppleDouble `._<sha>.json`,
282
283
  # and report other visible files; ignore other hidden files, such as .DS_Store, and the pending
283
284
  # transaction.
@@ -286,7 +287,7 @@ class _Validation:
286
287
  ]
287
288
  self.stored = set(evidence)
288
289
  # A forgotten list collection could not parse would fail every run of its source.
289
- for name in store.files("memories", skipped=self.skipped, split=True):
290
+ for name in listed:
290
291
  parts = name.split("/")
291
292
  if len(parts) == 3 and parts[2] == records.FORGOTTEN:
292
293
  try: