brain-framework 21.2.0__tar.gz → 21.3.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.2.0 → brain_framework-21.3.0}/PKG-INFO +1 -1
  2. {brain_framework-21.2.0 → brain_framework-21.3.0}/THIRD_PARTY_NOTICES.md +3 -3
  3. {brain_framework-21.2.0 → brain_framework-21.3.0}/pyproject.toml +1 -1
  4. {brain_framework-21.2.0 → brain_framework-21.3.0}/pyproject.toml.orig +1 -1
  5. {brain_framework-21.2.0 → brain_framework-21.3.0}/src/bf/__init__.py +1 -1
  6. {brain_framework-21.2.0 → brain_framework-21.3.0}/src/bf/assistants.py +88 -67
  7. {brain_framework-21.2.0 → brain_framework-21.3.0}/src/bf/channels.py +14 -24
  8. {brain_framework-21.2.0 → brain_framework-21.3.0}/src/bf/cli.py +30 -7
  9. {brain_framework-21.2.0 → brain_framework-21.3.0}/src/bf/collect.py +134 -42
  10. {brain_framework-21.2.0 → brain_framework-21.3.0}/src/bf/graph.py +2 -2
  11. {brain_framework-21.2.0 → brain_framework-21.3.0}/src/bf/health.py +8 -5
  12. {brain_framework-21.2.0 → brain_framework-21.3.0}/src/bf/history.py +1 -1
  13. {brain_framework-21.2.0 → brain_framework-21.3.0}/src/bf/index.py +23 -9
  14. {brain_framework-21.2.0 → brain_framework-21.3.0}/src/bf/models.py +52 -24
  15. {brain_framework-21.2.0 → brain_framework-21.3.0}/src/bf/pages.py +29 -14
  16. {brain_framework-21.2.0 → brain_framework-21.3.0}/src/bf/records.py +4 -4
  17. {brain_framework-21.2.0 → brain_framework-21.3.0}/src/bf/replies.py +5 -1
  18. {brain_framework-21.2.0 → brain_framework-21.3.0}/src/bf/retrieve.py +91 -31
  19. {brain_framework-21.2.0 → brain_framework-21.3.0}/src/bf/runtime.py +0 -12
  20. {brain_framework-21.2.0 → brain_framework-21.3.0}/src/bf/skills/bf-maintain/SKILL.md +1 -1
  21. {brain_framework-21.2.0 → brain_framework-21.3.0}/src/bf/skills/bf-maintain/references/integrations.md +3 -3
  22. {brain_framework-21.2.0 → brain_framework-21.3.0}/src/bf/skills/bf-use/references/learn.md +1 -1
  23. {brain_framework-21.2.0 → brain_framework-21.3.0}/src/bf/skills/bf-use/references/retrieval.md +1 -1
  24. {brain_framework-21.2.0 → brain_framework-21.3.0}/src/bf/storage.py +8 -0
  25. {brain_framework-21.2.0 → brain_framework-21.3.0}/src/bf/update.py +18 -14
  26. {brain_framework-21.2.0 → brain_framework-21.3.0}/src/bf/validate.py +12 -9
  27. {brain_framework-21.2.0 → brain_framework-21.3.0}/LICENSE +0 -0
  28. {brain_framework-21.2.0 → brain_framework-21.3.0}/README.md +0 -0
  29. {brain_framework-21.2.0 → brain_framework-21.3.0}/src/bf/__main__.py +0 -0
  30. {brain_framework-21.2.0 → brain_framework-21.3.0}/src/bf/config.py +0 -0
  31. {brain_framework-21.2.0 → brain_framework-21.3.0}/src/bf/evaluate.py +0 -0
  32. {brain_framework-21.2.0 → brain_framework-21.3.0}/src/bf/install.py +0 -0
  33. {brain_framework-21.2.0 → brain_framework-21.3.0}/src/bf/links.py +0 -0
  34. {brain_framework-21.2.0 → brain_framework-21.3.0}/src/bf/markdown.py +0 -0
  35. {brain_framework-21.2.0 → brain_framework-21.3.0}/src/bf/mcp.py +0 -0
  36. {brain_framework-21.2.0 → brain_framework-21.3.0}/src/bf/messages.py +0 -0
  37. {brain_framework-21.2.0 → brain_framework-21.3.0}/src/bf/ontology.py +0 -0
  38. {brain_framework-21.2.0 → brain_framework-21.3.0}/src/bf/py.typed +0 -0
  39. {brain_framework-21.2.0 → brain_framework-21.3.0}/src/bf/schemas.py +0 -0
  40. {brain_framework-21.2.0 → brain_framework-21.3.0}/src/bf/skills/README.md +0 -0
  41. {brain_framework-21.2.0 → brain_framework-21.3.0}/src/bf/skills/bf-action/SKILL.md +0 -0
  42. {brain_framework-21.2.0 → brain_framework-21.3.0}/src/bf/skills/bf-action/references/actions.md +0 -0
  43. {brain_framework-21.2.0 → brain_framework-21.3.0}/src/bf/skills/bf-action/references/context.md +0 -0
  44. {brain_framework-21.2.0 → brain_framework-21.3.0}/src/bf/skills/bf-action/references/handoff.md +0 -0
  45. {brain_framework-21.2.0 → brain_framework-21.3.0}/src/bf/skills/bf-action/scripts/check-handoff.py +0 -0
  46. {brain_framework-21.2.0 → brain_framework-21.3.0}/src/bf/skills/bf-action/scripts/new-action.py +0 -0
  47. {brain_framework-21.2.0 → brain_framework-21.3.0}/src/bf/skills/bf-action/templates/action.md +0 -0
  48. {brain_framework-21.2.0 → brain_framework-21.3.0}/src/bf/skills/bf-maintain/references/conflicts.md +0 -0
  49. {brain_framework-21.2.0 → brain_framework-21.3.0}/src/bf/skills/bf-maintain/references/operations.md +0 -0
  50. {brain_framework-21.2.0 → brain_framework-21.3.0}/src/bf/skills/bf-setup/SKILL.md +0 -0
  51. {brain_framework-21.2.0 → brain_framework-21.3.0}/src/bf/skills/bf-setup/references/discovery.md +0 -0
  52. {brain_framework-21.2.0 → brain_framework-21.3.0}/src/bf/skills/bf-setup/references/import.md +0 -0
  53. {brain_framework-21.2.0 → brain_framework-21.3.0}/src/bf/skills/bf-setup/references/scan.md +0 -0
  54. {brain_framework-21.2.0 → brain_framework-21.3.0}/src/bf/skills/bf-setup/scripts/inventory.py +0 -0
  55. {brain_framework-21.2.0 → brain_framework-21.3.0}/src/bf/skills/bf-use/SKILL.md +0 -0
  56. {brain_framework-21.2.0 → brain_framework-21.3.0}/src/bf/skills/bf-use/references/consolidate.md +0 -0
  57. {brain_framework-21.2.0 → brain_framework-21.3.0}/src/bf/skills/bf-use/references/decisions.md +0 -0
  58. {brain_framework-21.2.0 → brain_framework-21.3.0}/src/bf/skills/bf-use/references/evidence.md +0 -0
  59. {brain_framework-21.2.0 → brain_framework-21.3.0}/src/bf/skills/bf-use/references/links.md +0 -0
  60. {brain_framework-21.2.0 → brain_framework-21.3.0}/src/bf/skills/bf-use/references/review.md +0 -0
  61. {brain_framework-21.2.0 → brain_framework-21.3.0}/src/bf/skills/bf-use/references/share.md +0 -0
  62. {brain_framework-21.2.0 → brain_framework-21.3.0}/src/bf/skills/bf-use/scripts/evidence.py +0 -0
  63. {brain_framework-21.2.0 → brain_framework-21.3.0}/src/bf/skills/bf-use/scripts/guarded-write.py +0 -0
  64. {brain_framework-21.2.0 → brain_framework-21.3.0}/src/bf/skills/bf-use/templates/concept.md +0 -0
  65. {brain_framework-21.2.0 → brain_framework-21.3.0}/src/bf/skills/bf-use/templates/project.md +0 -0
  66. {brain_framework-21.2.0 → brain_framework-21.3.0}/src/bf/starter/AGENTS.md +0 -0
  67. {brain_framework-21.2.0 → brain_framework-21.3.0}/src/bf/starter/concepts/index.md +0 -0
  68. {brain_framework-21.2.0 → brain_framework-21.3.0}/src/bf/starter/concepts/welcome.md +0 -0
  69. {brain_framework-21.2.0 → brain_framework-21.3.0}/src/bf/starter/evals/retrieval.yaml +0 -0
  70. {brain_framework-21.2.0 → brain_framework-21.3.0}/src/bf/starter/gitignore +0 -0
  71. {brain_framework-21.2.0 → brain_framework-21.3.0}/src/bf/usage.py +0 -0
  72. {brain_framework-21.2.0 → brain_framework-21.3.0}/src/bf/watch.py +0 -0
  73. {brain_framework-21.2.0 → brain_framework-21.3.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.2.0
3
+ Version: 21.3.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
@@ -1635,15 +1635,15 @@ ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
1635
1635
  OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
1636
1636
  ```
1637
1637
 
1638
- ## sse-starlette 3.6.0
1638
+ ## sse-starlette 3.7.0
1639
1639
 
1640
1640
  Source: <https://github.com/sysid/sse-starlette>
1641
1641
 
1642
1642
  License: `BSD-3-Clause`
1643
1643
 
1644
- Evidence: `sse_starlette-3.6.0.dist-info/licenses/LICENSE`
1644
+ Evidence: `sse_starlette-3.7.0.dist-info/licenses/LICENSE`
1645
1645
 
1646
- ### sse_starlette-3.6.0.dist-info/licenses/LICENSE
1646
+ ### sse_starlette-3.7.0.dist-info/licenses/LICENSE
1647
1647
 
1648
1648
  ```text
1649
1649
  Copyright © 2020, [sysid](https://sysid.github.io/).
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "brain-framework"
3
- version = "21.2.0"
3
+ version = "21.3.0"
4
4
  description = "🧠 Brain Framework: from information to informed actions."
5
5
  readme = "README.md"
6
6
  requires-python = ">=3.14"
@@ -1,7 +1,7 @@
1
1
  # https://packaging.python.org/en/latest/specifications/pyproject-toml/
2
2
  [project]
3
3
  name = "brain-framework"
4
- version = "21.2.0"
4
+ version = "21.3.0"
5
5
  description = "🧠 Brain Framework: from information to informed actions."
6
6
  readme = "README.md"
7
7
  requires-python = ">=3.14"
@@ -2,7 +2,7 @@
2
2
 
3
3
  import os
4
4
 
5
- __version__ = "21.2.0"
5
+ __version__ = "21.3.0"
6
6
 
7
7
 
8
8
  def main() -> None:
@@ -48,6 +48,7 @@ from bf.models import (
48
48
  decode,
49
49
  digest,
50
50
  encode,
51
+ reason,
51
52
  retried,
52
53
  timestamp,
53
54
  )
@@ -84,10 +85,6 @@ class StreamStoppedError(Error):
84
85
  """A stream worker ended outside shutdown: its input would silently stop being accepted, so watch stops."""
85
86
 
86
87
 
87
- def _reason(error: BaseException, fallback: str = "assistant files are inaccessible") -> str:
88
- return str(error) if isinstance(error, Error) else fallback
89
-
90
-
91
88
  def prepare(
92
89
  store: Store,
93
90
  name: str,
@@ -143,8 +140,8 @@ def prepare(
143
140
 
144
141
  def read_failure(channel: str, error: BaseException) -> str:
145
142
  """A failed read poll, worded alike by bf update and watch, naming the channel's read log."""
146
- reason = _reason(error, "its files are inaccessible").removeprefix(f"channel {channel}: ")
147
- return f"channel {channel}: read failed: {reason}; see {log_path(f'channel.{channel}.read')}"
143
+ cause = reason(error, "its files are inaccessible").removeprefix(f"channel {channel}: ")
144
+ return f"channel {channel}: read failed: {cause}; see {log_path(f'channel.{channel}.read')}"
148
145
 
149
146
 
150
147
  def _oversized(store: Store, work: Work) -> str:
@@ -291,11 +288,62 @@ def _exposed(work: Work) -> AbstractContextManager[None]:
291
288
  return exposing(BF_TRIGGER=work.kind, BF_SCHEDULE=_schedule(work), BF_START=work.start, BF_END=work.end)
292
289
 
293
290
 
291
+ def _recorded(
292
+ work: Work, reply: str, wake: Requested | None, metadata: dict[str, JsonValue]
293
+ ) -> tuple[Record, list[Outgoing]]:
294
+ """The record and deliveries an answer makes. The error never quotes the output."""
295
+ try:
296
+ record = Record(
297
+ id=datetime.fromisoformat(work.end).astimezone(UTC).strftime("%Y%m%dT%H%M%SZ") + "-" + work.id[-8:],
298
+ title=reply_title(work.assistant, reply),
299
+ text=reply,
300
+ time=work.end,
301
+ attributes={
302
+ "observed": work.end,
303
+ "trigger": work.kind,
304
+ "job": work.id,
305
+ "window": {"start": work.start, "end": work.end},
306
+ **({"input": work.text} if work.text else {}),
307
+ **({"output": metadata} if metadata else {}),
308
+ **({"wake": wake.model_dump()} if wake else {}),
309
+ **(
310
+ {
311
+ "channel": work.origin.channel,
312
+ "sender": work.origin.message.sender,
313
+ "conversation": work.origin.message.conversation,
314
+ }
315
+ if work.origin
316
+ else {}
317
+ ),
318
+ },
319
+ )
320
+ replies = (
321
+ [
322
+ Outgoing(
323
+ id=digest(f"{work.id}:{route.channel}:{route.conversation}".encode())[:32],
324
+ text=reply,
325
+ conversation=route.conversation,
326
+ reply_to=route.reply_to,
327
+ )
328
+ for route in work.routes
329
+ ]
330
+ if reply.strip()
331
+ else []
332
+ )
333
+ except ValidationError:
334
+ # Pydantic's message quotes the invalid input: report the cause, never the content.
335
+ raise Error(
336
+ "assistant output cannot become a record: it holds invalid Unicode or more than 2 MiB outside its "
337
+ f"message; see {log_path(work.assistant)}"
338
+ ) from None
339
+ return record, replies
340
+
341
+
294
342
  def _attempt(store: Store, work: Work, runner: Runner, argv: list[str], stdin: bytes) -> bytes:
295
- """Run the harness once, telling it why it runs; an answer that does not parse fails the attempt."""
343
+ """Run the harness once, telling it why it runs; an answer that cannot be parsed or recorded fails the attempt."""
296
344
  with _exposed(work):
297
345
  raw = runner(argv, work.settings, store, work.assistant, stdin)
298
- _answer(raw, work)
346
+ _recorded(work, *_answer(raw, work))
299
347
  return raw
300
348
 
301
349
 
@@ -318,8 +366,8 @@ def _gate(store: Store, work: Work, runner: Runner) -> list[JsonValue] | None:
318
366
  f"see {log_path(name)}"
319
367
  ) from None
320
368
  except (Error, OSError, UnicodeError) as error:
321
- reason = str(error) if isinstance(error, Error) else f"gate of schedule {schedule} failed; see {log_path(name)}"
322
- raise GateError(reason) from error
369
+ cause = reason(error, f"gate of schedule {schedule} failed; see {log_path(name)}")
370
+ raise GateError(cause) from error
323
371
  events: list[JsonValue] = [event.model_dump(exclude_defaults=True) for event in reply.events]
324
372
  if len(encode(events)) > GATE_EVENT_BYTES:
325
373
  # Saved events are reused on every retry: an oversized set would fail each prompt the same way.
@@ -401,7 +449,6 @@ def _execute(store: Store, key: str, runner: Runner) -> dict[str, object]:
401
449
  argv, stdin = expanded(store, work, queue)
402
450
  if not queue.claim(key):
403
451
  raise Error("assistant job is no longer pending; inspect bf queue")
404
- queue.lifecycle("assistant.started", work.assistant, {"job": key, "kind": work.kind})
405
452
  queue.answer(key, _attempt(store, work, runner, argv, stdin))
406
453
  row = queue.get(key)
407
454
  if row["state"] == "answered":
@@ -410,43 +457,7 @@ def _execute(store: Store, key: str, runner: Runner) -> dict[str, object]:
410
457
  raise Error("assistant returned no response to an incoming message; inspect the saved answer")
411
458
  if work.kind in {"schedule", "wake"} and not reply and not metadata:
412
459
  return _quiet(store, queue, work, key, wake)
413
- record = Record(
414
- id=datetime.fromisoformat(work.end).astimezone(UTC).strftime("%Y%m%dT%H%M%SZ") + "-" + work.id[-8:],
415
- title=reply_title(work.assistant, reply),
416
- text=reply,
417
- time=work.end,
418
- attributes={
419
- "observed": work.end,
420
- "trigger": work.kind,
421
- "job": key,
422
- "window": {"start": work.start, "end": work.end},
423
- **({"input": work.text} if work.text else {}),
424
- **({"output": metadata} if metadata else {}),
425
- **({"wake": wake.model_dump()} if wake else {}),
426
- **(
427
- {
428
- "channel": work.origin.channel,
429
- "sender": work.origin.message.sender,
430
- "conversation": work.origin.message.conversation,
431
- }
432
- if work.origin
433
- else {}
434
- ),
435
- },
436
- )
437
- replies = (
438
- [
439
- Outgoing(
440
- id=digest(f"{key}:{route.channel}:{route.conversation}".encode())[:32],
441
- text=reply,
442
- conversation=route.conversation,
443
- reply_to=route.reply_to,
444
- )
445
- for route in work.routes
446
- ]
447
- if reply.strip()
448
- else []
449
- )
460
+ record, replies = _recorded(work, reply, wake, metadata)
450
461
  queue.prepare(work, record, replies, wake)
451
462
  row = queue.get(key)
452
463
  saved = Prepared.model_validate_json(str(row["prepared"]))
@@ -553,16 +564,18 @@ def deliver(
553
564
  receipt = channels.send(store, name, command, message, runner=runner)
554
565
  queue.delivered(key, name, message, receipt)
555
566
  except (Error, OSError, UnicodeError) as error:
556
- reason = str(error) if isinstance(error, Error) else "channel send failed; inspect its local log"
567
+ cause = reason(error, "channel send failed; inspect its local log")
557
568
  attempts = int(str(delivery["attempts"])) + 1
558
- # A send command that never started sent nothing, so it retries like an idempotent one.
559
- outcome, reason, due = retry_policy(
560
- command.idempotent or isinstance(error, NotStartedError),
569
+ # A send command that never started sent nothing, so it retries like an idempotent one. A misrouted
570
+ # send may have posted elsewhere: it waits for inspection even on an idempotent channel.
571
+ outcome, cause, due = retry_policy(
572
+ (command.idempotent and not isinstance(error, channels.MisroutedError))
573
+ or isinstance(error, NotStartedError),
561
574
  delivery["job"] is not None,
562
575
  attempts,
563
- reason,
576
+ cause,
564
577
  )
565
- queue.delivery_failed(key, reason, outcome=outcome, due=due)
578
+ queue.delivery_failed(key, cause, outcome=outcome, due=due)
566
579
  except BaseException:
567
580
  # Ctrl-C or SIGTERM ends this process: record the send now, not at the next recovery pass.
568
581
  with suppress(Error, OSError):
@@ -636,9 +649,7 @@ def manual(
636
649
  raise Error("answer saved but delivery is unresolved; inspect bf queue before retrying")
637
650
  result["status"] = "ran"
638
651
  except (Error, OSError, UnicodeError) as error:
639
- result.update(
640
- status="failed", error=str(error) if isinstance(error, Error) else "assistant files are inaccessible"
641
- )
652
+ result.update(status="failed", error=reason(error, "assistant files are inaccessible"))
642
653
  return {"ok": result["status"] == "ran", "dry_run": dry_run, "assistants": [result]}
643
654
 
644
655
 
@@ -707,7 +718,7 @@ def schedule(
707
718
  "assistant": name,
708
719
  "schedule": slot.removeprefix("schedule:"),
709
720
  "status": "failed",
710
- "error": _reason(error),
721
+ "error": reason(error, "assistant files are inaccessible"),
711
722
  }
712
723
  )
713
724
  return keys, failures
@@ -828,7 +839,12 @@ def _cycle(store: Store, names: set[str], at: datetime, runner: Runner) -> list[
828
839
  )
829
840
  except (Error, OSError, UnicodeError, ValueError) as error:
830
841
  results.append(
831
- {"assistant": queue.get(key)["assistant"], "job": key, "status": "failed", "error": _reason(error)}
842
+ {
843
+ "assistant": queue.get(key)["assistant"],
844
+ "job": key,
845
+ "status": "failed",
846
+ "error": reason(error, "assistant files are inaccessible"),
847
+ }
832
848
  )
833
849
  failed: set[str] = set()
834
850
  while (delivery := queue.delivery(names=names, skip=tried)) is not None:
@@ -841,7 +857,12 @@ def _cycle(store: Store, names: set[str], at: datetime, runner: Runner) -> list[
841
857
  except (Error, OSError, UnicodeError, ValueError) as error:
842
858
  failed.add(key)
843
859
  results.append(
844
- {"assistant": delivery["assistant"], "delivery": key, "status": "failed", "error": _reason(error)}
860
+ {
861
+ "assistant": delivery["assistant"],
862
+ "delivery": key,
863
+ "status": "failed",
864
+ "error": reason(error, "assistant files are inaccessible"),
865
+ }
845
866
  )
846
867
  results.extend(
847
868
  {
@@ -893,8 +914,8 @@ def cycle(
893
914
  ]
894
915
  return _cycle(store, names, at, runner)
895
916
  except (Error, OSError, UnicodeError, ValueError) as error:
896
- reason = _reason(error, "the assistant queue or brain files are inaccessible")
897
- return [{"assistant": name, "status": "failed", "error": reason} for name in sorted(names)]
917
+ cause = reason(error, "the assistant queue or brain files are inaccessible")
918
+ return [{"assistant": name, "status": "failed", "error": cause} for name in sorted(names)]
898
919
 
899
920
 
900
921
  class Dispatcher:
@@ -1028,9 +1049,9 @@ class Dispatcher:
1028
1049
  connected=connected,
1029
1050
  )
1030
1051
  except (Error, OSError, UnicodeError) as error:
1031
- reason = str(error) if isinstance(error, Error) else "stream transport failed; inspect its local log"
1052
+ cause = reason(error, "stream transport failed; inspect its local log")
1032
1053
  with suppress(Error, OSError):
1033
- self.queue.set_progress(f"health:channel:{channel}", {"error": reason, "at": now()})
1054
+ self.queue.set_progress(f"health:channel:{channel}", {"error": cause, "at": now()})
1034
1055
  if self.stopped.wait(delay):
1035
1056
  break
1036
1057
  delay = min(delay * 2, 60)
@@ -1061,7 +1082,7 @@ class Dispatcher:
1061
1082
  config = load(self.store)
1062
1083
  except (Error, OSError, UnicodeError) as error:
1063
1084
  # Running work continues; nothing new starts until bf.yaml loads again.
1064
- self._record("dispatcher", _reason(error, "bf.yaml is inaccessible"))
1085
+ self._record("dispatcher", reason(error, "bf.yaml is inaccessible"))
1065
1086
  return
1066
1087
  errors = []
1067
1088
  # Each section fails on its own: a full queue refusing a schedule never keeps queued work from draining.
@@ -1069,7 +1090,7 @@ class Dispatcher:
1069
1090
  try:
1070
1091
  section()
1071
1092
  except (Error, OSError, UnicodeError, ValueError) as error:
1072
- errors.append(_reason(error, "assistant queue inaccessible"))
1093
+ errors.append(reason(error, "assistant queue inaccessible"))
1073
1094
  self._record("dispatcher", "; ".join(errors))
1074
1095
 
1075
1096
  def _harvest(self) -> None:
@@ -1094,7 +1115,7 @@ class Dispatcher:
1094
1115
  # Worded as bf update words it, so bf status reads the same whichever ran the poll.
1095
1116
  self._record(name, read_failure(name.split(":")[2], error))
1096
1117
  else:
1097
- self._record(name, _reason(error, "runtime worker failed"))
1118
+ self._record(name, reason(error, "runtime worker failed"))
1098
1119
 
1099
1120
  def _jobs(self) -> None:
1100
1121
  waiting = self._waiting()
@@ -4,21 +4,19 @@ from __future__ import annotations
4
4
 
5
5
  import os
6
6
  import selectors
7
- import signal
8
7
  import subprocess
9
8
  import time
10
9
  from collections.abc import Callable
11
10
  from contextlib import suppress
12
- from datetime import UTC, datetime
13
11
  from threading import Event
14
12
 
15
13
  from pydantic import ValidationError
16
14
 
17
- from bf.collect import PROGRAM_ENV, Runner, arguments, executable, run, starting
15
+ from bf.collect import Runner, _now, arguments, ended, executable, program_env, run, starting, stop
18
16
  from bf.config import load
19
- from bf.history import append_log, environment
17
+ from bf.history import append_log
20
18
  from bf.messages import Batch, Message, Outgoing, Receipt
21
- from bf.models import Command, Error, Send, Stream, decode, encode, explain, local, timestamp
19
+ from bf.models import Command, Error, Send, Stream, decode, encode, explain, timestamp
22
20
  from bf.storage import Store
23
21
 
24
22
  # Envelope keys a validation error may name; a provider's output controls any other key.
@@ -33,6 +31,10 @@ class BatchOverflowError(Error):
33
31
  """A read window holds more messages than one batch carries; a shorter window may fit."""
34
32
 
35
33
 
34
+ class MisroutedError(Error):
35
+ """A send receipt names another conversation: the message may have reached the wrong place, so never retry it."""
36
+
37
+
36
38
  def _invalid(error: Error | ValidationError) -> str:
37
39
  """Which envelope field failed and why, never its value."""
38
40
  return f": {explain(error, _FIELDS)}" if isinstance(error, ValidationError) else ""
@@ -83,7 +85,9 @@ def send(store: Store, name: str, command: Send, message: Outgoing, *, runner: R
83
85
  except (Error, ValidationError) as error:
84
86
  raise Error(f"channel {name}: send must return a JSON id and conversation receipt") from error
85
87
  if message.conversation and receipt.conversation != message.conversation:
86
- raise Error(f"channel {name}: send receipt names a different conversation; inspect delivery before retrying")
88
+ raise MisroutedError(
89
+ f"channel {name}: send receipt names a different conversation; inspect delivery before retrying"
90
+ )
87
91
  return receipt
88
92
 
89
93
 
@@ -104,9 +108,7 @@ def stream(
104
108
  `connected` runs once, when BF wrote the resume frame and the adapter still runs ESTABLISHED seconds after starting.
105
109
  Every run ends with one timed log entry naming its outcome and, when the adapter exited on its own, its status.
106
110
  """
107
- # Like `run`: inherited values of the variables BF sets never reach an adapter.
108
- env = {key: value for key, value in environment().items() if key not in PROGRAM_ENV}
109
- env["BF_BRAIN"] = str(store.root)
111
+ env = program_env(store)
110
112
  argv = arguments(store, command, resume.get("since", ""), "")
111
113
  argv[0] = executable(store, argv[0], env)
112
114
  child: subprocess.Popen[bytes] | None = None
@@ -213,28 +215,16 @@ def stream(
213
215
  break
214
216
  errors.extend(chunk)
215
217
  del errors[:-_STDERR]
216
- with suppress(ProcessLookupError):
217
- os.killpg(child.pid, signal.SIGKILL)
218
- child.wait()
218
+ stop(child)
219
219
  for pipe in (child.stdin, child.stdout, child.stderr):
220
220
  if pipe is not None:
221
221
  pipe.close()
222
222
  if code is not None:
223
- outcome += f"; adapter {_ended(code)}"
223
+ outcome += f"; adapter {ended(code)}"
224
224
  with suppress(Error, OSError):
225
225
  append_log(
226
226
  store,
227
227
  f"channel.{name}.stream",
228
- f"{local(timestamp(datetime.now(UTC).isoformat()))} {outcome} after {time.monotonic() - started:.1f}s",
228
+ f"{_now()} {outcome} after {time.monotonic() - started:.1f}s",
229
229
  bytes(errors),
230
230
  )
231
-
232
-
233
- def _ended(code: int) -> str:
234
- if code >= 0:
235
- return f"exited with status {code}"
236
- try:
237
- return f"was killed by {signal.Signals(-code).name}"
238
- except ValueError:
239
- # Real-time signals between SIGRTMIN and SIGRTMAX have no name.
240
- return f"was killed by signal {-code}"
@@ -57,7 +57,7 @@ from bf.retrieve import edges, identities, items, read, search
57
57
  from bf.runtime import Queue
58
58
  from bf.schemas import Kind, document
59
59
  from bf.storage import Store, expand, relative, writer
60
- from bf.update import KINDS, ProgramKind, run_assistant, run_routines, update
60
+ from bf.update import KINDS, ProgramKind, run_assistant, run_routines, runnable, update
61
61
  from bf.validate import validate
62
62
 
63
63
 
@@ -540,16 +540,31 @@ def export(
540
540
  ),
541
541
  ] = "edges",
542
542
  brain: BrainOption = "",
543
+ scope: Annotated[
544
+ str,
545
+ typer.Option(
546
+ help="Export only the items bf search --scope would search, such as memories/gmail, memories/gmail/7d, "
547
+ "projects or 2026-09; edges keep the claims those items assert."
548
+ ),
549
+ ] = "",
543
550
  ) -> None:
544
551
  """Print the graph of the selected brains as JSON Lines from their caches; exit 1 when evidence was skipped."""
552
+ # Invalid input fails before any brain is read, as for search.
553
+ bounds = pages.bounds(scope)
545
554
  with ExitStack() as stack:
546
- stream, extra = {"edges": edges, "identities": identities, "items": items}[kind](select(brain), stack)
555
+ stream, extra = {"edges": edges, "identities": identities, "items": items}[kind](select(brain), stack, bounds)
547
556
  for row in stream:
548
557
  _write(terminal(present(row)), flush=False)
549
558
  _write(b"")
550
559
  # The lines hold only claims: completeness goes to stderr, like other diagnostics, and to the exit code.
551
560
  for name in cast("list[str]", extra.get("stale", [])):
552
561
  _diagnose(f"{name}: a writer kept the cache from refreshing; retry for newer claims")
562
+ # Like stale, an omitted text leaves the export incomplete, yet every line it printed stays true.
563
+ for item in cast("list[dict[str, object]]", extra.get("omitted", [])):
564
+ _diagnose(
565
+ f"{item['brain']}: {item['file']}: text omitted: the file changed or became unreadable since the cache "
566
+ "refreshed; run bf build"
567
+ )
553
568
  problems = cast("list[dict[str, object]]", extra.get("problems", []))
554
569
  for problem in problems:
555
570
  # A referenced brain's directory and file names are its own: _diagnose escapes them.
@@ -561,7 +576,11 @@ def export(
561
576
  @app.command("collect", rich_help_panel="Collect and automate")
562
577
  def capture(
563
578
  sensor: Annotated[
564
- str, typer.Argument(metavar="SENSOR", help="An enabled sensor name from bf.yaml; runs even with refresh: 0.")
579
+ str,
580
+ typer.Argument(
581
+ metavar="SENSOR",
582
+ help="A sensor name from bf.yaml; it must be enabled unless --input is given; runs even with refresh: 0.",
583
+ ),
565
584
  ],
566
585
  brain: RunOption = "",
567
586
  since: Annotated[str, typer.Option(help="Window start: 7d, yesterday, YYYY-MM-DD or ISO 8601.")] = "",
@@ -736,7 +755,9 @@ def perform(
736
755
  _finish(result, failed=not result["ok"])
737
756
  return
738
757
  # Git closes a hook's input; an agent's shell can hold its own open, so a direct run reads it only on request,
739
- # and a hook only for the routines it runs: a hook that no routine lists succeeds at once.
758
+ # and a hook only for the routines it runs: a hook that no routine lists succeeds at once. A mistyped or disabled
759
+ # name fails first, instead of after waiting for input.
760
+ runnable(config, names)
740
761
  stdin = _input() if forward or (hook and hooked(config, hook)) else b""
741
762
  result = run_routines(store, names=names, hook=hook, args=args, stdin=stdin, dry_run=dry_run)
742
763
  _finish(result, failed=not result["ok"])
@@ -779,8 +800,10 @@ def channel_command(
779
800
  command = channels.operation(store, name, "send")
780
801
  if not isinstance(command, Send):
781
802
  raise Error("channel requires a send operation")
803
+ # Oversized or unending input keeps its own diagnostic, as for bf run, instead of reading as invalid JSON.
804
+ data = _input()
782
805
  try:
783
- value = decode(_input())
806
+ value = decode(data)
784
807
  if not isinstance(value, dict):
785
808
  raise Error("send input must be a JSON object containing text")
786
809
  message = Outgoing.model_validate({"id": uuid4().hex, **value})
@@ -1040,7 +1063,7 @@ def _input() -> bytes:
1040
1063
  remaining = deadline - time.monotonic()
1041
1064
  if remaining <= 0:
1042
1065
  raise Error(
1043
- "piped input did not end within 10 seconds; close it, or run bf run from a terminal"
1066
+ "piped input did not end within 10 seconds; close it, or run the command from a terminal"
1044
1067
  )
1045
1068
  if not selector.select(remaining):
1046
1069
  continue
@@ -1064,7 +1087,7 @@ _GIVEN = {
1064
1087
  "--reproject": "give a sensor name; an empty value would rebuild the cache instead",
1065
1088
  "--routine": "give a routine name; an empty value names none",
1066
1089
  "--sensor": "give a sensor name; an empty value names none",
1067
- "--since": "give a start time; an empty value would collect the default window",
1090
+ "--since": "give a start time; an empty value names none",
1068
1091
  "DIR": "give a directory; an empty value would name the working directory",
1069
1092
  "PATH": "give a directory; an empty value would name the working directory",
1070
1093
  "SENSOR": "give a sensor name from bf.yaml",