Skip to content

Local-first 🧠 memory for Hermes Agent that lives in your Obsidian vault and remembers project context. Nightly 😴 dream passes turn repeat corrections into confirmed preferences with measurable confidence. Adapters ship for Claude Code, Codex, and OpenClaw, with an MCP server for anything else.

TypeScript

feat: who wrote what, and how to take it back (v1.55.0) (#184)

Sol Aitken5f415267e182
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json
index 9c572444..250ab1c6 100644
--- a/.claude-plugin/plugin.json
+++ b/.claude-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "1.54.0",
+ "version": "1.55.0",
"description": "Plugin-first second brain package for AI agents and humans.",
"author": {
"name": "Open Second Brain contributors"
diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.json
index 86896b94..7583cd23 100644
--- a/.codex-plugin/plugin.json
+++ b/.codex-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "1.54.0",
+ "version": "1.55.0",
"description": "Plugin-first second brain package for Codex, Hermes, Claude Code, OpenClaw, and other agent runtimes.",
"skills": "./skills",
"hooks": "./hooks/hooks.json",
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 61059d80..0fbe5b34 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,6 +5,36 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
+## [1.55.0] - 2026-09-10
+
+Open Second Brain has known who wrote a signal or a preference since the log shipped, has taken a snapshot before every destructive pass since 0.10, and has sharded the Brain log per device since 0.10.8 so that two machines syncing one vault never fight over one file. What it could not say was who wrote a note. A `brain_create_note`, an `update_note`, an `append_note` or a `write_batch` left no event in the log and no row in any roster, and the bulk of what an agent produces was therefore invisible to attribution, to `brain_event_trace`, and to any rollback finer than the whole `Brain/` tree at a snapshot instant. This release closes that, and the four things that follow from closing it. Every note write now emits one `note-write` event carrying a write id, the operation, the target, the content hash and byte size on both sides, the caller-asserted agent and the server-derived origin channel, with the device riding on the shard name as it does for every event, and the bytes the write replaced kept in a content-addressed store so that a revert has something to restore from. A revert is a plan over those events for one agent, device or path in a window - restore, delete, or a refusal by name when another writer sits on top - sealed by a digest, applied only as the exact plan the operator read, under a snapshot, and recorded as a write of its own so that a revert is itself attributable and revertible. A freeze marker at `Brain/.state/frozen.json`, carried by Syncthing to every device, is refused by name at the one guard every content writer already passes, while the Brain log keeps recording so the refusals are auditable; `o2b brain freeze` and `o2b brain unfreeze` are the operator verbs and `o2b brain status`, `brain_status` and `brain_doctor` all say so. The shard rule the log has followed for a year is now the rule for every append-only ledger in the vault - continuity, idempotency, preference audit, metrics and session lineage each write `<base>.<device-id>.jsonl` and merge every shard at read, and the doctor names a sync-conflict copy under any of those directories, not only the log. And because the log is now the attribution record for every write, every JSONL line it appends carries a per-shard hash chain: a line that was edited, removed or stripped after it was written has a file and a line number, reported by `o2b brain log verify` and the doctor and never used to gate a read.
+
+The wave was scoped from a comparison against a published control-model checklist for agents with delegated authority whose fleet layer - a kill path, a causal log attributable per agent and per machine, and rollback - is described in prose and not shipped. The comparison found that Open Second Brain already had most of the described log and none of the described stop, and that its own log discipline had not been applied to its own other ledgers; the five kanban cards behind this release are those findings, each verified against the live source before anything was designed.
+
+### Added
+
+- **Every note write is an event.** `createNote` and the write-batch kernel's `update_note` and `append_note` commits each append exactly one `note-write` log event after the bytes land: `write_id` (`nw_<14 timestamp digits>_<16 hex>`, derived from the event body so two devices that record the same write agree on its id), `op`, `target`, `hash_before` (the literal `absent` when the target did not exist, deliberately not the hash of zero bytes), `hash_after`, `bytes_before`, `bytes_after`, and `agent`. The bytes an update or append replaced are kept at `Brain/.state/write-images/<sha256>`, written before the atomic write and skipped when an image of that content already exists, so a note toggled between two states costs two files and not two per write. A log failure never fails a write that has already landed; the result and the MCP receipt carry `write_id: null` and an `audit_reason` instead, and a create that skipped an occupied target records nothing because it authored nothing.
+- **`o2b brain writes` and `brain_writes`.** The record read back: filter by agent, device, path, window and operation, newest first, with the device reported as the shard the event came from. `brain_agent_query` and `brain_agent_diff` gain the `note` contribution kind off the same events, so "which notes did this agent touch" has an answer with no new reader. `o2b brain writes prune-images [--older-than-days N] [--dry-run]` bounds the image store by file age, default 30 days; an image is a copy of note content the snapshot region already archives, so removing one loses no content and only narrows how far back a revert can reach, which a revert plan then reports by name.
+- **`o2b brain writes revert` and `brain_writes action=plan_revert`.** A selector - at least one of agent, device or path, with an optional window - resolves every target the selected writes touched to one action: `restore` to the bytes the oldest selected write replaced, `delete` when the oldest selected write created the note and nothing preceded it, or a refusal by name: `drift` when the note on disk is not what the newest selected write left, `interleaved` when an unselected write sits between the selected ones, `image-missing` when the before-image was pruned, `already-reverted` when the target already holds the bytes the plan would restore, `unrecorded` when the target cannot be read at all. A plan carries the log's parse warnings beside its entries, outside the digest, because an operator deciding what to undo has to be told when the history is incomplete. The plan is sealed by a digest over the selector and every entry, refusals included; `--apply <digest>` re-plans, refuses before any byte when the digests differ, runs under a `note-revert` snapshot, and records each restore and delete as a `note-write` of operation `revert`. Apply is CLI-only; the MCP tool plans and does not apply.
+- **A fleet freeze.** `o2b brain freeze [--reason]` writes `Brain/.state/frozen.json` and `o2b brain unfreeze` removes it; the marker records who set it, from which device, when and why. `assertVaultIdentityForWrite` - the guard every content writer in the tree already calls before its first byte, ninety-eight call sites across sixty modules - refuses the content lane by name while the marker exists, with `frozen_at`, `by`, `reason` and the next command. The guard gains a write lane: the Brain log appender and the marker writer ask for the audit lane and are the only two that do, pinned by a source scan, so `freeze`, `unfreeze` and `write-refused` events are recorded while the freeze is in force. A malformed marker is a freeze, not an absence. The MCP boundary maps the refusal to a structured error and appends one `write-refused` event naming the tool. `o2b brain rollback` on a frozen vault is refused like every other writer; the recovering operator is exactly the operator who should decide the freeze is over.
+- **Per-device shards for every ledger.** The shard grammar, listing, sync-conflict exclusion and device-id resolution move out of the log reader into `ledger-shards.ts`, byte-preserving for the log, and the continuity store, idempotency ledger, preference audit, metrics and session-lineage ledger write `<base>.<device-id>.jsonl` and merge every shard at read in a deterministic order. The preference audit is the one ledger that changes shape: a flat `<pref-id>.<device-id>.jsonl` is a name another valid preference id could own, because a preference id may itself contain a dot, so new audit lines land in one directory per preference, `Brain/log/pref-audit/<pref-id>/device[.<device-id>].jsonl`, the legacy flat trail stays readable, and a row whose `pref_id` is not the one asked for is dropped with a warning naming both. The bare name is the shard with the empty id everywhere, so no file is renamed and a device with an id never appends to a bare file again. The lineage ledger keeps one hash chain and one sequence per shard, compacts per shard, shards its gap sidecar the same way, and its verifier reports per shard path. The doctor's `sync-conflict-log` finding sweeps every ledger directory and names the one the copy sits in.
+- **The log chain.** Every JSONL row appended from this release on carries `h`, the sha-256 of the canonical JSON of `{ prev, ts, kind, payload }`, and `prev`, the `h` of the previous chained line in the same shard or `null` at that shard's genesis. Editing any earlier line changes every later hash, so a tampered history cannot be re-linked without rewriting the shard from the edit forward. One chain per shard, because two machines append to two files that Syncthing delivers in whatever order it likes. Rows written before the chain are legacy and clean while they precede it; the same shape after a chained line is a stripped line and is reported, and a first chained line naming a predecessor means the head was cut off. `o2b brain log verify [--json]` reports the first break per shard as `hash-mismatch`, `prev-mismatch` or `malformed` with the line number; `brain_doctor` emits one `log-chain-broken` warning per broken shard. Report-only: `readLogDay` reads `ts`, `kind` and `payload` and nothing else, so a broken shard still yields every event it holds. The markdown twin is a derived rendering and is not chained.
+
+### Changed
+
+- **`readLogDay` reports the shard beside each entry.** `entryShardIds` is a parallel array at the same index as `entries`, the empty string being the legacy un-sharded pair. A parallel array rather than a payload field, because the shard is a fact about the file and not a claim the writer made.
+- **`createNote`, `applyWriteBatch` and `scaffoldStub` accept a `configPath`.** Without it the note-write record resolved the agent against no config and attributed every MCP write to the unconfigured default instead of the identity the server's own config names. Attribution is the deliverable, so the three signatures grew one optional field.
+- **The state-surface catalogue has 44 rows,** up from 42: the freeze marker and the before-image store, each with a written recovery story. The write-site census admits the two new writers as shared-helper rows.
+
+### Notes
+
+- The `agent` on a note-write event is a caller-asserted claim, exactly as `src/core/write-binding/index.ts` has stated since 1.52.0; `origin_channel` and the device shard are the facts. No gate in this release keys on the agent name, and the freeze keys on the vault, not on who is asking. A policy layer over who may write remains a separate card.
+- The chain is the one place this release changes bytes for a vault that enables nothing: two keys on every new log line. Legacy lines read exactly as before.
+- Revert refuses on doubt and never merges. A target another writer touched after the selected writes is reported, not reconciled; the plan digest covers the refusals, so the operator who applies a digest applies the plan they read, refusals and all.
+- The lineage state-surface row still derives the bare file name, which on a device with an id does not exist; the row's reason says so. Deriving a shard name there touches the inventory contract and is left for a later card, as is re-pointing the two ledgers that already carried their own copy of the shard grammar (`truth/store.ts`, `decisions/receipts.ts`) at the shared module.
+- An independent review of the finished branch returned three blocking findings and six non-blocking ones, all applied: the before-image prune threw on any foreign file name in its directory and now reports such names as `skipped`; the preference-audit shard grammar let one preference read another's trail, closed by the per-preference directory above; the idempotency ledger and the continuity store had started swallowing every shard read error where the unsharded reader propagated it, so a permission fault read as "key never seen" - both now rethrow anything but a missing file; a crafted `target` on a note-write event aborted the whole revert plan with an unnamed error and is now the per-target refusal `target-invalid`; one throwing entry in a revert apply aborted the rest after the snapshot and is now a named `failed` bucket the others continue past; and the audit-lane pin reads both spellings of the lane.
+- Note-write events carry no session or turn id: the MCP server context does not hold them today, and inventing one at the seam would be a claim with nothing behind it.
+
## [1.54.0] - 2026-08-27
Open Second Brain has shipped a `visibility:` frontmatter field, a predicate that reads it, and a filter that applies it - and until this release the field was decorative. The filter was wired into exactly one call site, and the scope it filtered against came from the caller, so a remote caller that asked for the private scope was handed it. Of the 71 callable surfaces the project's own visibility census enumerated, 3 consulted the field and 68 did not. The previous wave measured that rather than closing it: 1.52.0 shipped the census, the registry behind it, and an `o2b search check` finding that stated in the operator's own diagnostics that this boundary did not exist. This release is the enforcement that census was built as the coverage map for. One reserved token is denied by default at remote reach and enforced at the three roots every read surface reaches page content through - the ranked search pipeline, the page walker, and the by-path and by-chunk-id read primitives - and a new sweep proves mechanically that there is no fourth root. The reach that decides is minted by the transport and refused by name when a caller supplies it, because a trust claim echoed back from the request is not a trust claim. A vault that never wrote the token sees no change at all, and the schema-12 backfill is what guarantees that rather than an assumption.
@@ -7428,6 +7458,7 @@ plugin config (vault field)`, and exits with a clear
- Sandbox vault and plugin manifest fixtures for tests.
- GitHub release workflow for tag-based and manually dispatched releases.
+[1.55.0]: https://github.com/itechmeat/open-second-brain/compare/v1.54.0...v1.55.0
[1.54.0]: https://github.com/itechmeat/open-second-brain/compare/v1.53.1...v1.54.0
[1.53.1]: https://github.com/itechmeat/open-second-brain/compare/v1.53.0...v1.53.1
[1.53.0]: https://github.com/itechmeat/open-second-brain/compare/v1.52.1...v1.53.0
diff --git a/README.md b/README.md
index b88999e5..89e85556 100644
--- a/README.md
+++ b/README.md
@@ -118,6 +118,7 @@ Each non-Hermes target writes a sidecar manifest under `<vault>/.open-second-bra
- **Memory that learns, and forgets, on its own.** A nightly `dream` pass turns repeated corrections into rules and retires the ones nothing uses any more. Deterministic by design: counters and atomic file moves, no LLM guessing inside your memory.
- **One brain, every agent.** Teach a rule in one agent and the next one already knows it - Hermes, Claude Code, Codex, Cursor, and the rest read and write the same vault.
- **You stay in control.** Pin, merge, retire, or roll back any rule from the `o2b` CLI. Every Brain mutation takes a verified snapshot first, so a bad change is one `o2b brain rollback` away.
+- **Who wrote what, and how to take it back.** Every note write is a log event with a write id, the agent, the device, and the content hash before and after, and the bytes it replaced are kept. `o2b brain writes` reads the record; `o2b brain writes revert --agent <name>` plans a restore of exactly that agent's writes, refuses by name where another writer sits on top, and applies only the plan you read. `o2b brain freeze` stops every content writer on every device that syncs the vault until you say otherwise, and the log carries a per-shard hash chain so a line that was edited or removed after the fact has a file and a line number.
- **Search that explains itself.** Keyword plus an optional semantic layer over your vault, with results that show why they surfaced and what was missing - not a black box. Opt into a structured per-result score breakdown (`explain`), inline trust metadata (age, superseded, conflict), a relevance threshold that returns nothing rather than weak noise, and reinforcement that lifts memories you have marked useful. Track retrieval quality over time with `brain_eval` and the recall benchmark (hit@k, MRR, answer-containment@k).
- **Conversations survive compaction.** When the host compresses context and rotates the session id, capture and recall stitch the segments back into one conversation - any segment id returns the whole lineage.
- **Memory that cleans itself, on your terms.** `o2b brain hygiene scan` surfaces contested facts, near-duplicate rules, stale derived pages, and never-recalled memories; `apply` executes only the findings you select, and stale pages recompile from their recorded sources with a dry-run preview.
diff --git a/docs/architecture.md b/docs/architecture.md
index 734d57bd..7b647731 100644
--- a/docs/architecture.md
+++ b/docs/architecture.md
@@ -198,7 +198,7 @@ Recommended behavior:
What "the vault" contains is enumerated rather than assumed.
`src/core/state/surfaces.ts` declares every durable location this build
-keeps INSIDE a vault β€” 42 of them β€” each with the layer that can move it
+keeps INSIDE a vault β€” 44 of them β€” each with the layer that can move it
and what its loss costs, split into `derived` (rebuildable, so deleting it
costs time) and `vault-content` (the memory itself, permanent without a
backup). `o2b state status` measures that catalogue against one vault and
@@ -379,13 +379,13 @@ disclosure, so `warn`'s observability here is the `owner:` stamp appearing on
new files, not a count in any response.
The enforcement lives in `tests/mcp/agent-scope-matrix.test.ts`, and its shape
-is the point rather than its size. Ninety-nine classified tools carry 226 call
+is the point rather than its size. One hundred classified tools carry 229 call
recipes - one per mode, view or operation, because one executed view is not an
executed classification. Every recipe runs TWICE against the same two-owner
fixture, once with the gate closed and once with it open, and the classification
decides what the open run must show: the 32 recipes classified as reaching
owner-taggable content must surface the marker with the gate off, which is what
-stops the closed run from passing vacuously. The other 194 carry a claim of
+stops the closed run from passing vacuously. The other 197 carry a claim of
unreachability, and that claim is executed directly - the marker must be absent
even where nothing is hidden. The first version of this probe asserted only the
closed half, and 81 of its entries were driven against arguments that named
diff --git a/docs/brainstorm/who-wrote-what/cli-output/claude.md b/docs/brainstorm/who-wrote-what/cli-output/claude.md
new file mode 100644
index 00000000..36efb072
--- /dev/null
+++ b/docs/brainstorm/who-wrote-what/cli-output/claude.md
@@ -0,0 +1,43 @@
+### Variant 1: Seam-first, thin shared primitives
+
+- **Approach**: Add one note-write seam (`src/core/brain/notes/write-seam.ts`) that every note mutation passes through: it checks the freeze marker, hashes the target before and after, runs the atomic write, and emits one `note_write` log event through `appendLogEvent` in `src/core/brain/log.ts` with the pref-audit field shape (`agent`, `hash_before/after`, `origin_channel` stamped server-side at `log.ts:335`). Extract only the shard grammar, listing and merge from `src/core/brain/log-jsonl.ts:52-62` into a small `ledger-shards.ts` and re-point the five unsharded writers at it; put the per-shard `prev` chain inside the log appender only; build revert as plan-seal-apply over `note_write` events with the before-image resolved from a content-addressed image store written by the seam. Landing order: B (shards) β†’ A (seam + event) β†’ C (freeze at the seam) β†’ E (chain in appender + doctor) β†’ D (revert).
+- **Trade-offs**:
+ - Pro: A and C share one chokepoint, and the write-site census (`tests/core/architecture/write-site-census.test.ts`) can pin "every note writer routes through the seam" the same way it pins direct-fs exclusions. Internal callers (dream apply, dedup merge, write-session commit in `write-session/engine.ts:414`, `write-batch.ts:236`) are covered because the seam sits below the MCP layer.
+ - Pro: the shard extraction is mechanical; `continuity/store.ts:98`, `idempotency-ledger.ts:126`, `pref-audit.ts`, `metrics.ts:69` and `lineage/ledger.ts` each swap one path function and one reader loop. The bare file name already means "empty shard id" (`log-jsonl.ts:6`), so no rename migration is needed, only a doctor lint that reports leftover bare files being appended to by a second device.
+ - Pro: content-addressed before-images (`Brain/.state/write-images/<sha256>`) dedupe naturally, and the log event only carries the hash. The snapshot gate (`snapshot-gate.ts`) covers `Brain/` top-level entries, so the image store is inside the recovery region.
+ - Pro: revert reuses `sealManifest` and the `destination_occupied`-style drift refusal from `src/core/state/migrate.ts:186,724`; the only new semantics are "refuse on drift", the simplest of the three options the task leaves open.
+ - Con: the lineage ledger carries its own `seq` and chain plus in-place compaction; sharding it per device means the verifier in `lineage/verify.ts` must iterate shards, which is a real change, not a path swap.
+ - Con: the image store grows with every edit until pruned; it needs a retention rule tied to the snapshot policy in `policy.ts` or it becomes a second unbounded ledger.
+ - Con: the chain lives in `log.ts`, so other ledgers stay unchained. Acceptable per Task E scope, but a second chain later will want the primitive Variant 2 builds now.
+ - Con: new `prev` on every log line changes log bytes for every vault. Mitigation: legacy lines without `prev` are treated as chain genesis, and the verifier names them `unchained-legacy` rather than broken.
+- **Complexity**: medium
+- **Risk**: low
+
+### Variant 2: One append-only ledger abstraction carrying shards and chain
+
+- **Approach**: Build `src/core/brain/ledger/` as a typed `AppendOnlyLedger` that owns shard naming, the device id from `resolveDeviceId()`, the sync writer lock, sync-conflict exclusion, deterministic merge, and an optional per-shard hash chain. Move Brain/log, continuity, idempotency, pref-audit, metrics and lineage onto it, so Task B and Task E are one change; Task A's `note_write` event and Task C's freeze refusal event are records on the same log ledger; Task D reads the ledger's typed cursor and stores the before-image inline in the event. Landing order: ledger primitive β†’ migrate six writers β†’ seam + freeze β†’ revert.
+- **Trade-offs**:
+ - Pro: sharding, locking and chaining are written once and every current and future ledger inherits them; the census for "did we miss one" becomes a type check rather than a grep over `src/core/state/surfaces.ts`.
+ - Pro: Task E's "which files are chained" question has one answer: any ledger with `chain: true`, verified by one doctor check with one finding code.
+ - Con: Brain/log has a markdown twin, a directory-level lock and a byte-exact idempotent append contract (`log.ts:335-380`); folding it into a generic ledger risks changing bytes for vaults that enable nothing, which the constraints forbid.
+ - Con: the lineage ledger's compaction, gap sidecar and `seq` allocation (`lineage/ledger.ts:100-180`) do not fit a generic append-only shape without either a leaky escape hatch or a second abstraction.
+ - Con: inline before-images make the log the largest file family in the vault and put note bodies into a file `o2b brain protect` and Obsidian expose; redaction rules from `continuity/redaction.ts` would have to apply to the log too.
+ - Con: file count and review surface exceed the 50-70 file budget once six readers, six writers, their tests, and the pinned state-surface count are all touched in one PR.
+- **Complexity**: large
+- **Risk**: high
+
+### Variant 3: Boundary middleware, core untouched
+
+- **Approach**: Enforce freeze and emit write events at the MCP and CLI boundary: a `withWriteGuard` wrapper over `ToolDefinition` in `src/mcp/` (next to `reach-refusal.ts`) and a matching CLI verb decorator, keyed on a tool allow-list of mutating verbs. Shards are done per ledger by copying the `LOG_FILE_RE` grammar into each writer; the chain goes into `log.ts`; revert resolves before-images from the nearest snapshot manifest (`manifest.ts` `diffManifests`) and refuses when none covers the write. Landing order: C β†’ A β†’ B β†’ E β†’ D.
+- **Trade-offs**:
+ - Pro: smallest diff, and the refusal shape is already the house style for boundary refusals (`src/mcp/reach-refusal.ts`).
+ - Pro: no change to core write functions, so bit-identical behaviour for unchanged vaults is trivially true.
+ - Con: the boundary is not the write seam. Dream apply, hygiene, lifecycle, page-dedup merge and the write-session engine mutate `Brain/` from inside core and would bypass both the freeze and the event, which is exactly the `o2b brain protect` failure the task cites. The census cannot pin a wrapper applied by list.
+ - Con: `hash_before` must be computed before the core write and `hash_after` after it, but the handler does not know the resolved target path until `resolveNoteTarget` runs inside `createNote`; the wrapper ends up re-implementing target resolution or recording the caller's unresolved path.
+ - Con: snapshots are opt-in and pruned, so most revert plans would refuse for lack of a before-image, making Task D mostly a report rather than an apply path.
+ - Con: five copies of the shard grammar drift the day one changes; the project's own DRY brief forbids this.
+- **Complexity**: small
+- **Risk**: high
+
+### Recommended: Variant 1
+**Rationale**: The seam is the only position that satisfies both Task A and Task C for the internal writers the tasks explicitly list, and it is the position the existing censuses and the vault-identity guard (`vault-identity.ts`, "check before any byte") already occupy, so the architecture test can pin it. Extracting just the shard grammar keeps `log.ts` byte-stable for vaults that change nothing while still putting `resolveDeviceId()` behind one function, and the content-addressed image store gives Task D a real apply path without either bloating the log or depending on opt-in snapshots. Variant 2 is the right long-term shape but does not fit one wave under the bit-identical constraint, and Variant 3 repeats the bypassed-boundary failure the epic exists to fix.
diff --git a/docs/brainstorm/who-wrote-what/cli-output/prompt.md b/docs/brainstorm/who-wrote-what/cli-output/prompt.md
new file mode 100644
index 00000000..45859b12
--- /dev/null
+++ b/docs/brainstorm/who-wrote-what/cli-output/prompt.md
@@ -0,0 +1,194 @@
+You are brainstorming architectural variants for the following task. Do not write code. Do not write a final design. Only produce variants and a recommendation. You are running inside the project repository and MAY read files to ground your variants; cite file paths you relied on.
+
+# Task
+
+This is an EPIC of five related kanban tasks that ship as ONE feature branch, ONE pull request and ONE release of Open Second Brain. Produce variants for the architecture of the whole suite (how the five pieces share primitives, in what order they land, where the seams are), not five separate mini-designs.
+
+## Task A (t_662f4e82, priority 4): Every note write emits an attributable log event
+
+**Source**: https://github.com/tonydzi/agent-leash (README "fleet layer": Replay - "a causal log attributable per agent and per machine"; docs/leash-8.md Domain 1 Identity, Domain 7 Observability)
+**Repo**: tonydzi/agent-leash (2β˜…, MIT, prose-only: 721 lines of Markdown, no code)
+**Released**: v0.1.2 (2026-09-05)
+
+## What
+Every action an agent takes lands in an append-only log outside the agent's own write scope, stamped with agent, machine and task, so an operator can replay what happened and attribute each write. agent-leash publishes the requirement, not the format.
+
+For Open Second Brain: every note write emits one attributable log event. Today `brain_create_note` / `update_note` / `append_note` / `write_batch` emit no log event at all (CHANGELOG 1.52.0: "caller-named note writes emit no log event"; `docs/observability.md`: "brain_create_note file creation emits no telemetry event today and is not counted"), and `origin_channel` is stamped on note creation only (`src/core/brain/notes/create-note.ts:495-505`). The event carries: write id, `agent` (caller-asserted, marked as such), `origin_channel` (server-derived), device id, session/turn ids when present, target path, content hash before and after, and the write kind. The per-preference audit line (`src/core/brain/pref-audit.ts`: `agent`, `reason`, `revision_before/after`, `hash_before/after`) is the shape to generalise; the write-session engine already emits one log event per terminal transition with `target` (`src/core/brain/write-session/engine.ts:414-428`).
+
+## Why useful for Open Second Brain
+`brain_agent_query` / `brain_agent_diff` attribute only `signal | preference | log` (`src/core/brain/agent-source/types.ts:1`); note bodies, the bulk of what agents write, are invisible to attribution. Without a per-write record with before/after hashes there is nothing for a per-agent revert to act on (see t_924129c5), `brain_event_trace` cannot join a note change to the session that made it, and the only history is git, which is absent on non-repo vaults (`brain_note_history` returns `available: false`).
+
+## Status in Open Second Brain
+- **Verdict**: present_weaker
+- **Codegraph hints**: unstamped writers `src/core/brain/notes/create-note.ts`, `src/core/brain/write-batch.ts` (:20-26 documents the no-rollback contract), append/update verbs in `src/mcp/brain/*-tools.ts`; log appender `src/core/brain/log.ts:335` (`origin_channel` stamp site); event kinds `src/core/brain/types.ts` (`BRAIN_LOG_EVENT_KIND`); the write-site census `tests/core/architecture/write-site-census.test.ts` is the standing list of the unstamped remainder and must shrink to zero for note writes.
+
+## Notes
+Priority 4 by the triage rubric: internal, every target file named, the event shape already exists for preferences and write-sessions. Keep the caller-asserted nature of `agent` explicit in the record (the write-binding docblock `src/core/write-binding/index.ts:11-25` is the standing rule: identity is a claim, `origin_channel` is the fact). A hash-chained log (tamper evidence) is a separate follow-up task, not part of this one.
+
+## Task B (t_1814b9bf, priority 4): Per-device shards for every append-only ledger, not only Brain/log
+
+**Source**: https://github.com/tonydzi/agent-leash (README "fleet layer", templates/approval-design-checklist.md Β§7)
+**Repo**: tonydzi/agent-leash (2β˜…, MIT, prose-only: 721 lines of Markdown, no code)
+**Released**: v0.1.2 (2026-09-05)
+
+## What
+agent-leash reports, from a 6-machine live operation, the failure that a single synced file holding shared counters was overwritten by two machines "inside an hour" (checklist Β§7). The recommendation is that every append-only ledger an agent writes must be sharded per machine so peers never contend for one file, with the merged view computed at read time.
+
+Open Second Brain already does exactly this for `Brain/log/<date>.<deviceId>.jsonl|.md` (`src/core/brain/log-jsonl.ts:1-62`: per-device shard suffix, deterministic merge by `(timestamp, shardId, line)`, `*.sync-conflict-*` copies excluded, doctor lint `sync-conflict-log` at `src/core/brain/diagnostics.ts:239`). Every other append-only ledger in the vault is still one synced file per period or per key:
+
+- continuity store `Brain/log/continuity/<YYYY-MM>.jsonl` (`src/core/brain/continuity/store.ts:98`)
+- idempotency ledger `Brain/logs/idempotency/<YYYY-MM>.jsonl` (`src/core/brain/idempotency-ledger.ts:126`)
+- preference audit `Brain/log/pref-audit/<pref-id>.jsonl` (`src/core/brain/pref-audit.ts:6`)
+- metrics `Brain/metrics/<surface>.jsonl` (`src/core/brain/metrics.ts:69`)
+- session lineage `Brain/.state/session-lineage.jsonl` + gaps file (`src/core/brain/lineage/ledger.ts:122-123`) - this one carries sequence numbers and a hash chain, so two devices appending concurrently produce a fork the verifier can only report
+
+Extend the shard discipline to all of them: `<name>.<deviceId>.jsonl` written, merged at read, sync-conflict copies excluded and reported by `brain_doctor`, `resolveDeviceId()` (`src/core/config.ts:425-570`) as the only shard-id source, a one-shot migration that renames the existing unsharded file into the empty-shard slot (the log reader already treats the bare name as "shard with the empty id", `log-jsonl.ts:6`).
+
+## Why useful for Open Second Brain
+The vault is replicated with Syncthing across devices. Two machines appending to the same monthly continuity or idempotency file in the same sync window yield a `.sync-conflict-*` copy that no reader merges, so context receipts, idempotency decisions and preference audit lines silently split across two files. The log layer solved this in v0.10.8; the remaining ledgers inherited the bug the log fixed.
+
+## Status in Open Second Brain
+- **Verdict**: present_weaker
+- **Codegraph hints**: shard pattern to reuse `src/core/brain/log-jsonl.ts:52-62` (`LOG_FILE_RE`, `SYNC_CONFLICT_SHARD_PREFIX`); device id `src/core/config.ts:425-570`; unsharded writers listed above; surfaces catalogue `src/core/state/surfaces.ts` (42 durable locations) is the checklist for "did we miss one".
+
+## Notes
+The upstream repo ships no code for this; the pattern to copy is the project's own `log-jsonl.ts`. Priority 4 by the triage rubric: internal, every target file named, no open design question (the shard-name grammar and merge rule already exist). Coordinate with t_25afa1ba (timestamp-aware bundle import) only if bundle export enumerates ledger files by exact name.
+
+## Task C (t_109fa94d, priority 4): Fleet kill switch: a synced frozen write mode honoured at the write seam by every MCP tool and CLI verb
+
+**Source**: https://github.com/tonydzi/agent-leash (README "fleet layer": Kill / Cap / Replay; docs/leash-8.md Domain 8 Incident response)
+**Repo**: tonydzi/agent-leash (2β˜…, MIT, prose-only: 721 lines of Markdown, no code)
+**Released**: v0.1.2 (2026-09-05)
+
+## What
+A fleet-wide kill switch for agent writes: one operator action stops every agent on every machine from mutating the memory, with a measured time-to-disable, an "autonomy downgrade" mode (reads and proposals continue, writes hold), and scheduled drills that prove the path still works. agent-leash describes it as the first of three fleet controls (Kill, Cap, Replay) and publishes only the description.
+
+For Open Second Brain: a `frozen` write mode that lives in the vault so Syncthing carries it to every device, is honoured at the write seam by every MCP tool and CLI verb that mutates `Brain/` (create/update/append note, write_batch, write-session commit, delete_by_source, dream/hygiene/lifecycle apply, page-dedup merge), refuses with a named reason and a log event, leaves reads and dry-runs untouched, and is reported by `brain_doctor` / `brain_status`. `o2b brain freeze [--reason] / unfreeze` as the operator verbs, plus an env override for the case where the vault itself is unreachable.
+
+## Why useful for Open Second Brain
+Today there is no single stop. `o2b brain protect` (`src/core/brain/protect.ts`) patches two runtimes' own permission files and is bypassed by MCP tools, which are the actual write path. `write_approval.enabled` (`src/core/brain/pending.ts:37-38`) stages extracted signals only, not note writes. A write binding with no prefixes (`src/core/write-binding/index.ts`) is inert, not deny-all. `grep kill.switch src/core` hits only search-index toggles. An operator who sees a runaway agent on one of several machines has to find and stop each process.
+
+## Status in Open Second Brain
+- **Verdict**: not_in_osb_useful
+- **Codegraph hints**: chokepoint inventory already exists as the destructive-site census `src/core/brain/destructive-sites.ts` + `tests/core/architecture/destructive-site-census.test.ts` and the write-site census `tests/core/architecture/write-site-census.test.ts`; policy block to extend `src/core/brain/policy/blocks/write-binding.ts`; refusal shape to reuse `src/mcp/reach-refusal.ts` (named-reason refusals, v1.54.0); vault-identity guard `src/core/brain/vault-identity.ts` (`assertVaultIdentityForWrite`) is the same "check before any byte" position.
+
+## Notes
+Priority 4 by the triage rubric: internal, the seam and the census that enumerates every write site exist, and the only design choice (marker file under `Brain/.state/` vs a `_brain.yaml` key) is small; a marker file is recommended because `_brain.yaml` is operator-authored config and a freeze is runtime state. "Cap" (spend/capability budgets) from the same upstream section is deliberately not filed: t_0bed79f3 already covers cost caps for the one metered path.
+
+## Task D (t_924129c5, priority 3): Per-agent / per-session revert: plan-seal-apply over the per-write log
+
+**Source**: https://github.com/tonydzi/agent-leash (README "fleet layer": Replay; docs/plan-vs-authorize.md reversibility tiers)
+**Repo**: tonydzi/agent-leash (2β˜…, MIT, prose-only: 721 lines of Markdown, no code)
+**Released**: v0.1.2 (2026-09-05)
+
+## What
+"Who wrote what, and how to take it back": revert the writes of one agent (or one session, or one device) without restoring the whole vault. agent-leash frames rollback as the operator-side half of an attributable causal log; it publishes no mechanism.
+
+For Open Second Brain: an apply path over the per-write log from the parent task. `o2b brain agent-revert <agent|session|device> [--since]` and the matching MCP verb produce a plan (dry-run default) listing each write, its target, the hash the file has now versus the `hash_after` recorded for that write, and the action: restore `hash_before` content from the nearest snapshot or from an inline before-image, delete a file the agent created, or refuse when a later write by someone else sits on top (drift). Apply runs only the reviewed plan, sealed by digest, under `withDestructiveSnapshot()` so the revert itself is revertible.
+
+## Why useful for Open Second Brain
+Rollback granularity today is the whole `Brain/` tree at a snapshot instant (`src/core/brain/snapshot.ts`, `src/cli/brain/verbs/rollback.ts`). Targeted removal keys on a source file (`src/core/brain/source-cleanup.ts`: `deleteBySource`) or a note's derivations, never on writer identity. `brain_agent_diff` can show an agent's contributions but there is no apply path anywhere in `src/core/brain/agent-source/`. A misbehaving sub-agent that touched forty notes over two days forces a choice between losing two days of everyone else's work and hand-editing forty files.
+
+## Status in Open Second Brain
+- **Verdict**: not_in_osb_useful
+- **Codegraph hints**: snapshot gate `src/core/brain/snapshot-gate.ts:1-40` (`withDestructiveSnapshot`, `RecoverabilityVerdict`); manifest diff `src/core/brain/manifest.ts` (`diffManifests`, SHA-256 inventory); plan-seal-apply-exact discipline already implemented for state relocation in `src/core/state/migrate.ts` (`planStateMigration` :250, `sealManifest` :186, digest verify :740-746, `destination_occupied` drift refusal :724-730); dry-run-only `ForgetPlan` `src/core/brain/governance/forget-plan.ts`.
+
+## Notes
+Depends on the per-write log task t_662f4e82 (linked parent). Priority 3, not 4, by the triage rubric: two design decisions are open before this is actionable. (1) Where the before-image comes from: inline in the log event (vault grows with every edit) or resolved from the nearest snapshot (snapshots are opt-in and pruned). (2) Semantics when a later write by another agent overlaps the same file: refuse, three-way merge, or revert-to-before-both. The plan/approve-by-digest/apply-exact shape from `state/migrate.ts` and t_18fda844 is the recommended container for the answer.
+
+## Task E (t_8a7bf39a, priority 3): Per-shard hash chain on the Brain log with report-only doctor verification
+
+**Source**: https://github.com/tonydzi/agent-leash (docs/leash-8.md Domain 7 Observability: "append-only action log outside the agent's write scope")
+**Repo**: tonydzi/agent-leash (2β˜…, MIT, prose-only: 721 lines of Markdown, no code)
+**Released**: v0.1.2 (2026-09-05)
+
+## What
+The action log must be tamper-evident with respect to the agents that write to it: an agent that can delete or edit a line of its own history defeats attribution. agent-leash states the requirement; it publishes no format.
+
+For Open Second Brain: a per-shard hash chain on `Brain/log/<date>.<deviceId>.jsonl`, each line carrying `prev` (hash of the previous line in the same shard) so a removed or edited line breaks the chain from that point; `brain_doctor` verifies every shard and reports the first broken link as a named finding; verification is report-only, never a read gate. Per-shard chains, not a global one, because devices append concurrently and a global ordinal would need the merge story the project deliberately does not have.
+
+## Why useful for Open Second Brain
+The Brain log JSONL is unchained: a deleted or edited line is undetectable. The one hash chain in the codebase, `src/core/brain/lineage/ledger.ts` with `lineage/verify.ts`, covers session lineage only, and its docblock (:26-35) sets the policy this task should keep: "integrity here is an audit property, not a gate". `o2b brain protect` denies runtime writes to `Brain/log` but only for two runtimes and not for MCP tools. With the per-write note events landing in the same log (t_662f4e82), the log becomes the attribution record for every write; it should carry evidence that it was not edited after the fact.
+
+## Status in Open Second Brain
+- **Verdict**: present_weaker
+- **Codegraph hints**: chain + verifier to reuse `src/core/brain/lineage/ledger.ts`, `src/core/brain/lineage/verify.ts` (`verifyLineageLedger`, sequence + hash chain, report-only); appender `src/core/brain/log.ts` (lock + atomic write); reader `src/core/brain/log-jsonl.ts` (per-shard iteration is already the unit); doctor finding shape `src/core/brain/diagnostics.ts:239` (`sync-conflict-log`).
+
+## Notes
+Priority 3 by the triage rubric: internal and the pieces exist, but one design decision is open - whether the `.md` human-readable twin of each shard is chained too or declared a derived rendering of the JSONL (recommended: derived, one source of truth). Depends on the per-device ledger sharding task t_1814b9bf only in the sense that chaining a file two devices append to is meaningless; the log is already sharded, so this can start independently.
+
+# Project context
+
+Open Second Brain (TypeScript, Bun runtime, CLI `o2b` + MCP server, an agent-owned `Brain/` directory inside an Obsidian-compatible Markdown vault replicated between devices by Syncthing). Version on main: 1.54.0; this wave ships 1.55.0.
+
+Recent commits:
+dc552590 feat: private is not a suggestion (v1.54.0) (#183)
+23e6b81e fix(brain): merged pages leave the dedup pool, and the write seam refuses cycles (v1.53.1) (#182)
+c2e13f9d fix(hermes): make prefetch recall query-aware (#181)
+5102f142 fix(hermes): record context-pack receipts and explicit outcomes (#179)
+323e2f09 feat: nothing writes silently, nothing degrades silently (v1.52.0) (#178)
+6d3e8b23 feat: what earns its keep (v1.51.0) (#177)
+86544b9b fix(hermes): the bridge child inherits a PATH that can find Bun (v1.50.3) (#176)
+ba1a9678 fix(hermes): preserve context-pack recall (v1.50.2) (#172)
+4ba335d4 ci: adopt Bun 1.4.0 - pin the toolchain and rebuild the bundle it gates (#175)
+1e8792cb fix: a provider the host cannot read is not an unconfigured one (v1.50.1) (#171)
+962228ae fix(mcp): the pairing one tool declared and the other only enforced (v1.50.0) (#169)
+aa73af4b feat: what the machine already has (v1.50.0) (#168)
+b49af81e feat: a label is not a boundary (v1.49.0) (#166)
+280469d2 feat: nothing runs unwatched (v1.48.0) (#165)
+aa818084 feat: wiring what exists (v1.47.0) (#164)
+a6d10dab feat: evidence at the boundary (v1.46.0) (#162)
+29ea0099 fix: the flush that never landed (v1.45.1) (#158)
+8d05a62a feat: silence is not an answer (v1.45.0) (#159)
+34f96b84 fix: reuse and reap Hermes MCP bridges (v1.44.1) (#156)
+3ee1963a feat: what the index already knew (v1.44.0) (#157)
+
+Related files (verified to exist):
+- Brain log appender + parser: src/core/brain/log.ts (appendLogEvent(vault, BrainLogEntry, {deviceId}); every event carries `agent` (caller-asserted) and `origin_channel` (server-derived, src/core/origin-channel.ts); event kinds in src/core/brain/types.ts BRAIN_LOG_EVENT_KIND)
+- Per-device log shards + deterministic merge + sync-conflict exclusion: src/core/brain/log-jsonl.ts (LOG_FILE_RE, SYNC_CONFLICT_SHARD_PREFIX, readLogDay, listLogShardFiles)
+- Device id: src/core/config.ts resolveDeviceId (device-local, never synced)
+- Unsharded ledgers: src/core/brain/continuity/store.ts (Brain/log/continuity/<YYYY-MM>.jsonl, appendContinuityRecord, listContinuityRecords), src/core/brain/idempotency-ledger.ts (Brain/logs/idempotency/<YYYY-MM>.jsonl, rememberKey/lookupKey), src/core/brain/pref-audit.ts (Brain/log/pref-audit/<pref-id>.jsonl), src/core/brain/metrics.ts (Brain/metrics/<surface>.jsonl), src/core/brain/lineage/ledger.ts + lineage/verify.ts (Brain/.state/session-lineage.jsonl, sequence numbers + hash chain, report-only verifier)
+- Note write paths that emit no log event today: src/core/brain/notes/create-note.ts createNote (origin_channel stamped in frontmatter on create only, :495-505), src/mcp/brain/notes-tools.ts (brain_create_note / brain_update_note / brain_append_note handlers at :232/:317/:348), src/core/brain/write-batch.ts applyWriteBatch (:236; docblock :20-26 says mid-commit rollback is not attempted)
+- Write-session engine emits one log event per terminal transition with target: src/core/brain/write-session/engine.ts auditTerminal (:414-428)
+- Preference audit shape to generalise: src/core/brain/pref-audit.ts (agent, reason, revision_before/after, hash_before/after)
+- Agent attribution readers: src/core/brain/agent-source/{types,registry,vault-provider,query,diff,summary}.ts (AgentSourceContributionKind = signal | preference | log), CLI src/cli/brain/verbs/agent-query.ts, agent-diff.ts, MCP src/mcp/brain/query-tools.ts
+- Snapshot + rollback: src/core/brain/snapshot.ts, snapshot-gate.ts (withDestructiveSnapshot, RecoverabilityVerdict), manifest.ts (SHA-256 inventory, diffManifests), src/cli/brain/verbs/rollback.ts
+- Plan/seal/apply-exact discipline already implemented for state relocation: src/core/state/migrate.ts (planStateMigration, sealManifest, digest verify, destination_occupied drift refusal, unwind)
+- Source-keyed targeted removal: src/core/brain/source-cleanup.ts (deleteBySource, dry-run default, confirm + expect count guard)
+- Write policy surfaces: src/core/write-binding/index.ts (+ docblock :11-25 stating identity is a caller claim), src/core/brain/policy/blocks/write-binding.ts, src/core/brain/pending.ts (write_approval), src/core/brain/protect.ts, src/core/brain/vault-identity.ts (assertVaultIdentityForWrite), src/mcp/reach-refusal.ts (named-reason refusals)
+- Censuses that pin architecture: tests/core/architecture/write-site-census.test.ts, destructive-site-census.test.ts (+ src/core/brain/destructive-sites.ts), origin-channel-census.test.ts; state surfaces catalogue src/core/state/surfaces.ts (42 durable locations, test-pinned)
+- Doctor findings: src/core/brain/diagnostics.ts (sync-conflict-log at :239), src/core/brain/doctor/
+- Docs: docs/observability.md (event kinds table, continuity record kinds), docs/architecture.md, docs/cli-reference.md, docs/mcp.md
+
+Conventions:
+- Append-only files + byte-identical idempotent writes; Syncthing peers converge by construction, conflict copies are excluded and reported, never merged.
+- Integrity is an audit property, not a gate (lineage/ledger.ts docblock): verifiers report by name, never refuse reads.
+- Nothing writes silently, nothing degrades silently (1.52.0): every refusal has a named reason; fail-soft paths report the reason.
+- `agent` is a caller-asserted claim; `origin_channel` and transport reach are server-derived facts; no fence may key on the agent name alone.
+- Every destructive mutation runs behind withDestructiveSnapshot or has a written recovery story in destructive-sites.ts.
+- Test pins: MCP tool counts, write-site census rows, state-surface count, docs prose counts are all pinned and must be updated deliberately.
+- Standing engineering brief: SOLID, KISS, DRY, repeated values hoisted into named constants; no silent fallbacks, no stubs; everything in English.
+
+Constraints:
+- No new external dependencies.
+- No change to existing public CLI/MCP argument shapes; additive only.
+- A vault that never enables any of the new behaviour must read and write bit-identically (except that note writes now emit log events, which is the point of Task A).
+- Task D depends on Task A. Task E must not need a cross-device global ordinal.
+- The whole suite must be implementable by a small team in one wave (roughly 50-70 changed files).
+
+# Required output format
+
+Produce exactly 3 distinct architectural variants. For each variant:
+
+### Variant N: <short name>
+- **Approach**: 2-3 sentences describing the variant.
+- **Trade-offs**: bullet list of pros and cons.
+- **Complexity**: small | medium | large
+- **Risk**: low | medium | high
+
+After the three variants, add exactly one recommendation:
+
+### Recommended: Variant N
+**Rationale**: 2-3 sentences explaining why this variant over the others, considering the project context and constraints above.
+
+Output nothing outside of these sections.
diff --git a/docs/brainstorm/who-wrote-what/design.md b/docs/brainstorm/who-wrote-what/design.md
new file mode 100644
index 00000000..0f11df5c
--- /dev/null
+++ b/docs/brainstorm/who-wrote-what/design.md
@@ -0,0 +1,70 @@
+# Who wrote what, and how to take it back - attributable note writes, per-agent revert, fleet freeze, per-device ledgers, chained log
+
+**Status:** draft
+**Author:** claude-dev-agent (via feature-release-playbook)
+**Audience:** implementation
+
+## Problem statement
+
+Open Second Brain already records who wrote a signal or a preference, takes a snapshot before every destructive pass, and shards the Brain log per device so Syncthing peers never contend for one file. Four gaps remain, and they are the four an operator running several agents on several machines hits first: note writes (the bulk of what agents produce) emit no log event and are invisible to attribution; the only rollback is the whole `Brain/` tree at a snapshot instant; there is no single stop that every writer on every device honours; and every ledger except the log is still one synced file per period that two devices overwrite. A fifth, smaller gap follows from closing the first: once the log is the attribution record for every write, a deleted or edited log line must be detectable.
+
+## Scope
+
+- **Task A (t_662f4e82)** - every note write (`create_note`, `update_note`, `append_note`, through `createNote` and the write-batch kernel) emits one `note-write` log event carrying a write id, the operation, the target path, the content hash before and after, the byte sizes, the caller-asserted `agent` and the server-derived `origin_channel` (device id rides on the shard name as it does for every log event). The bytes a write replaces are kept as a content-addressed before-image under `Brain/.state/write-images/`. A reader (`listNoteWrites`) plus `o2b brain writes` and MCP `brain_writes` expose the record; `brain_agent_query` / `brain_agent_diff` gain the `note` contribution kind.
+- **Task B (t_1814b9bf)** - the shard grammar, listing, sync-conflict exclusion and device-id resolution move out of `log-jsonl.ts` into one `ledger-shards.ts`, and the continuity store, idempotency ledger, preference audit, metrics and session-lineage ledger write `<base>.<deviceId>.jsonl` and merge every shard at read. The doctor reports sync-conflict copies under every ledger directory, not only the log.
+- **Task C (t_109fa94d)** - a `frozen` marker at `Brain/.state/frozen.json`, carried by Syncthing to every device, refused by name at the one guard every content writer already passes (`assertVaultIdentityForWrite`), with `o2b brain freeze [--reason]` / `o2b brain unfreeze` as the operator verbs, `freeze` / `unfreeze` / `write-refused` log events, and the frozen state reported by `o2b brain status`, `brain_status` and `brain_doctor`.
+- **Task D (t_924129c5)** - `o2b brain writes revert` and `brain_writes` action `plan_revert`: a plan over the `note-write` events matching an agent, device or path selector and a time window; each target resolves to `restore` (from the before-image), `delete` (the selected writes created it) or a named refusal (`drift`, `interleaved`, `image-missing`); the plan is sealed by a digest and `--apply <digest>` re-plans, refuses on mismatch, runs under `withDestructiveSnapshot`, and records each restore as a `note-write` event of operation `revert`, so a revert is itself attributable and revertible.
+- **Task E (t_8a7bf39a)** - every JSONL log line carries `prev` (the chain hash of the previous line in the same shard, `null` at genesis) and `h` (its own chain hash); `verifyLogChain` walks every shard, treats lines without `h` as legacy genesis-class, and reports the first broken link per shard by shard path and line number; `o2b brain log verify` and a `log-chain-broken` doctor finding expose it. Report-only, never a read gate.
+- CLI verbs, MCP tool, tests, docs, CHANGELOG `[1.55.0]`, version bump, for each capability.
+
+## Out of scope
+
+- A generic `AppendOnlyLedger` abstraction that would fold the Brain log's markdown twin, lock and idempotent append into one type (consultant Variant 2). The shard grammar is shared; the writers keep their own append contracts.
+- Boundary-only enforcement of freeze or write events at the MCP/CLI layer (consultant Variant 3). Internal writers (dream, hygiene, page-dedup, write-session) are the ones the epic exists to cover.
+- A policy engine keyed to agent identity (allow/ask/deny per agent). `agent` stays a caller-asserted claim, as `src/core/write-binding/index.ts:11-25` states; the freeze keys on the vault, not on who is asking. t_29798f41 tracks the policy layer.
+- Spend or capability budgets ("Cap"). t_0bed79f3 covers the one metered path.
+- Chaining any ledger other than the Brain log. The lineage ledger keeps its own chain; the other ledgers stay unchained.
+- Three-way merge on revert. A target touched by another writer after the selected write is refused by name, never merged.
+- Deleting a note through the revert path when the note was created outside the selected writes. `delete` applies only when the earliest selected write on that target is a `create` with no earlier writer of record.
+- A `session_id` / `turn_id` on note-write events. The MCP server context does not carry them today; adding them is a separate change to the transport layer.
+
+## Chosen approach
+
+Consultant Variant 1 (seam-first, thin shared primitives), accepted with two overrides recorded below. Every note mutation already funnels through two functions - `createNote` and the three `commit` closures of `applyWriteBatch` - and every content writer in the tree already calls `assertVaultIdentityForWrite` before its first byte. Those two positions are the seams: the note-write record hooks the first, the freeze hooks the second. The shard grammar is extracted from the log reader unchanged so the log stays byte-stable, and the other ledgers re-point their path function and their reader loop at it. The chain lives inside the log appender, which already re-reads the shard under a lock before every append, so the previous line's hash costs nothing extra. Revert is plan-seal-apply over the note-write events with the before-image resolved from the content-addressed store, the same shape `src/core/state/migrate.ts` uses for state relocation.
+
+Landing order: B (shards) and C (freeze) and A (note-write record) are independent and land first; E (chain) and D (revert) land second, E on top of the extracted shard module and D on top of the note-write record.
+
+## Design decisions
+
+- **Override 1 - the freeze guard is the vault-identity guard, not the note seam.** The consultant put the freeze at the note-write seam. That seam covers note writers only; the dream pass, hygiene, page-dedup, the write-session engine and forty other modules write preferences, signals and state without touching a note. All of them call `assertVaultIdentityForWrite` (98 call sites in 60 modules, verified by grep), so the freeze check is added to that guard. The guard gains a third parameter, `lane: WriteLane = WRITE_LANE.content`; `WRITE_LANE.audit` skips the freeze check and is passed by exactly two callers: the Brain log appender (through `brainDirsForWrite`), so that `freeze`, `unfreeze` and `write-refused` events can be recorded while frozen, and the freeze marker writer itself. A test pins that the audit lane is requested from those two modules and no other.
+- **Override 2 - refusal events are recorded at the MCP tool boundary.** The guard cannot append a log event without importing the log module, which imports the paths module, which imports the guard - a cycle. The MCP dispatch already has one error boundary; it maps `VaultFrozenError` to a structured refusal (`code: "vault_frozen"`, `frozen_at`, `by`, `reason`, `next_command: "o2b brain unfreeze"`) and appends one `write-refused` event naming the tool. CLI refusals print the same fields on stderr and exit non-zero; internal writers propagate the error by name. The event is the agent-facing audit trail, which is the trail the freeze exists for.
+- **Freeze marker shape.** `Brain/.state/frozen.json`: `{ schema: 1, frozen_at, by, device_id, reason }`, written atomically, read on every guarded write (one `existsSync` + parse on the hot path; cached per process by inode the way `currentVaultId` is). A malformed marker is a freeze, not an absence: an operator who wrote a broken marker meant to stop writes, and a parse error must never silently reopen the vault. `unfreeze` removes the file; the removal is a destructive-site entry whose recovery story is "the marker's whole content was its existence and the `unfreeze` log event records who removed it".
+- **Rollback while frozen is refused.** `restoreSnapshot` passes the guard once and is refused like every other content writer; the refusal names `o2b brain unfreeze` as the next command. Simpler than an exemption, and an operator recovering a vault is exactly the operator who should decide the freeze is over.
+- **Note-write event fields.** `write_id` (`nw_<compact-stamp>_<sha16>` over the canonical event body, the continuity id shape), `op` (`create | update | append | revert`), `target` (vault-relative path), `hash_before` (sha256 of the raw bytes replaced, or the literal `absent` when the target did not exist), `hash_after`, `bytes_before`, `bytes_after`. `agent` comes from `resolveAgentName()` (the same resolution the write-binding docblock names; caller-asserted by construction), `origin_channel` from the appender, the device from the shard. Values are strings because the log payload contract is `Record<string, string | string[]>`.
+- **Event after bytes, receipt names the gap.** The file is written first and the event appended second. If the append throws, the write has landed and the caller is told: the note-write result gains `write_id: string | null` and, when null, `audit_reason`. The MCP receipt carries both. This is the snapshot-event precedent (a log failure never fails the load-bearing write) with the silence removed.
+- **Before-image store.** `Brain/.state/write-images/<sha256>` holds the raw bytes a write replaced, written before the atomic write, skipped when the hash already exists. Content-addressed, so repeated edits of the same content cost one file. It is inside the snapshot region. Retention: `o2b brain writes prune-images [--older-than-days N]` (default `WRITE_IMAGE_RETENTION_DAYS = 30`) removes images by mtime; the removal is a destructive-site entry with the recovery story that an image is a copy of note content the snapshot region already archives and its absence only narrows revert reach, which revert reports by name. The store is a `STATE_SURFACES` row.
+- **Shard grammar extraction is byte-preserving.** `ledger-shards.ts` exports the grammar (`<base>[.<shardId>].<ext>`, shard id slug `[a-z0-9-]{1,32}`), `parseShardedName`, `listShardedFiles`, `isSyncConflictName`, and `resolveAppendShardId` carrying the documented legacy fallback from `AppendLogEventOptions.deviceId` verbatim. `log-jsonl.ts` re-exports what it exported before and its tests do not change. The bare `<base>.<ext>` name is the shard with the empty id everywhere, so no migration renames a file; a device with an id never appends to a bare file again.
+- **Per-ledger merge rules.** Continuity: merge all shards of a month, keep the month range-skip on the parsed base, sort by `createdAt` then shard id. Idempotency: `lookupKey` scans all shards (a key remembered on one device is honoured on another once synced); `rememberKey` re-reads only its own shard under the lock, which is the same guarantee as today because the key it guards against is the one this device is about to write. Preference audit: merge per preference, sort by timestamp then shard id. Metrics: merge per surface. Lineage: one chain per shard, `seq` per shard, `readLineageLedger` merges by `at` then shard id, `verifyLineageLedger` verifies every shard and reports per shard path, the gaps sidecar shards the same way.
+- **Doctor covers every ledger directory.** The existing `sync-conflict-log` signal keeps its code and widens its sweep to the continuity, idempotency, preference-audit, metrics and `.state` directories; its detail names the directory. One exit, one meaning: "a sync conflict copy exists that no reader merges".
+- **Chain shape.** `renderJsonlLine` gains `prev` and `h` after `payload`: `h = sha256Hex(canonicalJson({ prev, ts, kind, payload }))`, `prev` = the `h` of the last line in the shard that carries one (the appender already holds the shard text under the lock). `readJsonl` ignores both keys, so no reader changes. Lines without `h` are legacy: the verifier counts them as `unchained-legacy`, never as broken, and a chained line whose `prev` is `null` after legacy lines is the genesis of that shard's chain. A line whose `h` does not recompute, or whose `prev` is not the previous chained line's `h`, breaks the chain at that line; the verifier reports the first break per shard and keeps counting. The markdown twin is declared a derived rendering and is not chained.
+- **Revert semantics are refuse-on-doubt.** For each target touched by the selected writes: the disk hash must equal the `hash_after` of the newest selected write on that target, else `drift`; no unselected write may sit between the oldest and newest selected write on that target, else `interleaved`; a `restore` needs the before-image of the oldest selected write, else `image-missing`. `delete` applies only when the oldest selected write is a `create` and no earlier note-write event exists for that target. Three more refusals ship beyond those three, each a fact about the vault rather than a failure of the module: `unrecorded` - the current bytes of the target cannot be read at all, so no verdict about drift is possible and "I could not tell" must never resolve to "revert it"; `already-reverted` - the target already holds exactly what this revert would produce, which is not the same answer as a restore that rewrites identical bytes and logs a write; `target-invalid` - the recorded target is not a path inside this vault (a corrupt, hand-appended or crafted log line), which costs that target and not the verdict on every other target in the plan. Refused targets are reported, never skipped silently, and the plan digest covers them too, so an operator applying a digest applies the plan they read. The apply adds a third bucket beside `applied` and `refused`: `failed` names any entry the apply reached and could not carry out for a reason no plan could predict (an unwritable directory, an I/O error), so one throwing entry costs that entry and not the entries after it.
+- **Attribution kind `note`.** The vault provider maps `note-write` events to contributions of kind `note` with `path = target` and `title = <op> <target>`, so `brain_agent_query` / `brain_agent_diff` answer "which notes did this agent touch" with no new reader.
+- **Snapshot reason `note-revert`** joins `BRAIN_SNAPSHOT_REASON`; the revert apply takes it through `withDestructiveSnapshot`, and the restore writes go through the same note-write record as any write, tagged `op: revert`.
+- **No new MCP tool for freeze.** Agents receive the refusal by name and `brain_status` reports the frozen state; unfreezing is an operator action and stays CLI-only. Revert apply is CLI-only for the same reason; `brain_writes` offers `list` and `plan_revert`.
+
+## File changes
+
+New core: `src/core/brain/ledger-shards.ts`, `src/core/brain/freeze-marker.ts` (read, assert, `VaultFrozenError`, `WRITE_LANE`), `src/core/brain/freeze.ts` (freeze/unfreeze with log events), `src/core/brain/notes/write-record.ts` (hashing, before-image store, event append, `NOTE_WRITE_OP`), `src/core/brain/notes/write-log.ts` (`listNoteWrites`), `src/core/brain/notes/revert.ts` (`planNoteRevert`, `applyNoteRevert`, plan digest), `src/core/brain/log-chain.ts` (`verifyLogChain`), doctor checks under `src/core/brain/doctor/` for the frozen marker and the log chain.
+Extended core: `src/core/brain/log.ts` (chain fields, audit lane), `src/core/brain/log-jsonl.ts` (re-point at `ledger-shards.ts`), `src/core/brain/paths.ts` (`brainDirsForWrite` lane, new path helpers), `src/core/brain/vault-identity.ts` (lane parameter, freeze check), `src/core/brain/continuity/store.ts`, `src/core/brain/idempotency-ledger.ts`, `src/core/brain/pref-audit.ts`, `src/core/brain/metrics.ts`, `src/core/brain/lineage/{ledger,verify}.ts`, `src/core/brain/notes/create-note.ts`, `src/core/brain/write-batch.ts`, `src/core/brain/agent-source/{types,vault-provider}.ts`, `src/core/brain/types.ts` (event kinds `note-write`, `freeze`, `unfreeze`, `write-refused`; snapshot reason `note-revert`), `src/core/brain/diagnostics.ts`, `src/core/brain/doctor.ts`, `src/core/brain/status.ts`, `src/core/brain/destructive-sites.ts`, `src/core/state/surfaces.ts`, `src/mcp/brain/health-tools.ts` (`brain_status` frozen field), MCP error boundary (`VaultFrozenError` mapping + `write-refused` event).
+New CLI verbs: `freeze`, `unfreeze`, `writes` (`list` default, `revert`, `prune-images`), `log` (`verify`); registered in the six standard places (handler, barrel, dispatcher switch, help text summary + `VERB_HELP`, command manifest, `docs/cli-reference.md`).
+New MCP tool: `brain_writes` (`action: list | plan_revert`) in `src/mcp/brain/query-tools.ts` with a preview budget; pins in `tests/mcp/mcp.test.ts`, `brain-tools-parity.test.ts`, `agent-scope-matrix.test.ts`, `tests/helpers/tool-probe-catalogue.ts`, `tests/core/install/tool-ceiling.test.ts`.
+Tests: per-module suites for every new module, shard suites per ledger, guard-lane pin, census updates (write-site, destructive-site, state-surface, doctor-exit), CLI and MCP suites.
+Docs: README (one paragraph under the control section), `docs/observability.md` (event kinds, ledger table, chain), `docs/cli-reference.md`, `docs/mcp.md`, `docs/architecture.md` (state-surface count), CHANGELOG `[1.55.0]`.
+
+## Risks and open questions
+
+- **Hot-path cost of the freeze check.** One `existsSync` per guarded write, ninety-eight sites. Cached per process by marker inode like `currentVaultId`; measured in the freeze module's test with a counter on the stat call.
+- **Log bytes change for every vault.** Task E adds two keys to every new JSONL line. Legacy lines are read exactly as before; the markdown twin is unchanged. This is the one place the "bit-identical for a vault that enables nothing" rule is deliberately not met, and the CHANGELOG says so.
+- **Lineage sharding touches a chain with compaction.** Per-shard `seq` and per-shard compaction keep the invariant "one chain per file" that the verifier already assumes; the merge order across shards is `at` then shard id. If the implementation finds the gaps sidecar cannot shard cleanly, the sidecar stays single-file and the design records why.
+- **Image store growth.** Bounded by the prune verb and the retention default; the doctor reports the store size so an operator sees it before it matters.
+- **Pin reconciliation across parallel implementation.** Every wave agent bumps the same count pins from the same base; the merge resolves each to the measured value by running the pin suites, per the standing note in the project memory.
diff --git a/docs/brainstorm/who-wrote-what/plan.md b/docs/brainstorm/who-wrote-what/plan.md
new file mode 100644
index 00000000..cd21165b
--- /dev/null
+++ b/docs/brainstorm/who-wrote-what/plan.md
@@ -0,0 +1,39 @@
+# Who wrote what, and how to take it back - implementation plan
+
+Feature branch: `feat/who-wrote-what`. TDD per task, one atomic conventional commit per task, `bun run fmt` + `bun run lint` green before every commit. Tasks 1-3 are independent and run in parallel in separate worktrees; tasks 4-5 run after them. Task 6 is the reconciliation the orchestrator does on the feature branch.
+
+Registration checklist for a new `o2b brain` verb (six places): handler `src/cli/brain/verbs/<verb>.ts`; barrel `src/cli/brain/verbs/index.ts`; dispatcher import + `case` in `src/cli/brain.ts` (the `switch` stays terminated by `default:`); `src/cli/brain/help-text.ts` summary line in `BRAIN_HELP` AND a `VERB_HELP` key; `src/cli/command-manifest.ts` brain group; `docs/cli-reference.md`. Pinned by `tests/cli/manifest-completeness.test.ts` and `tests/cli/help-surface-parity.test.ts`.
+
+Registration checklist for a new MCP tool: `ToolDefinition` in a domain array (model `brain_agent_diff`, `src/mcp/brain/query-tools.ts:713-751`); description <= 300 chars, property descriptions <= 160; `previewBudget` or a >= 10-char exemption reason in `src/mcp/registry-guard.ts` `PREVIEW_BUDGET_EXEMPT`; pins: `tests/mcp/mcp.test.ts:765` (113 -> 114), `tests/mcp/brain-tools-parity.test.ts` `FROZEN_BRAIN_TOOL_NAMES`, `tests/mcp/agent-scope-matrix.test.ts:214` (113 -> 114) plus a `SCOPED_SURFACES` / `PROBE_ENTRIES` classification, `tests/helpers/tool-probe-catalogue.ts:274-276` (`PROBE_ENTRY_COUNT` 99, `PROBE_RECIPE_COUNT` 226, `PROBE_TWO_SIDED_COUNT` 32 - measured after adding the probe), `tests/core/install/tool-ceiling.test.ts:343` (`available_tool_count` 113 -> 114), `docs/mcp.md` prose counts. A tool that reads page content needs a `src/core/search/visibility-surface-registry.ts` row (`tests/core/architecture/visibility-surface-census.test.ts:452`, `MCP_TOOL_POPULATION_SIZE` 48).
+
+## Tasks
+
+### Task 1: Per-device shards for every append-only ledger (t_1814b9bf)
+- **Files**: new `src/core/brain/ledger-shards.ts`; `src/core/brain/log-jsonl.ts` (re-point, keep exports and bytes); `src/core/brain/log.ts` (`resolveAppendShardId` replaces the inline fallback, behaviour unchanged); `src/core/brain/continuity/store.ts`; `src/core/brain/idempotency-ledger.ts`; `src/core/brain/pref-audit.ts` (+ `prefAuditPath` in `paths.ts`); `src/core/brain/metrics.ts`; `src/core/brain/lineage/ledger.ts`, `lineage/verify.ts`; `src/core/brain/diagnostics.ts` + the doctor check that emits `sync-conflict-log` (widen the sweep, keep the code); `src/core/state/surfaces.ts` (row labels/patterns; count stays 42 unless a new directory appears); `docs/observability.md` ledger table; tests: new `tests/core/brain/ledger-shards.test.ts`, shard cases added to `continuity-store.test.ts`, `idempotency-ledger.test.ts`, `pref-audit.test.ts`, `metrics.test.ts`, `lineage-ledger-integrity.test.ts`, doctor test for a conflict copy under each directory.
+- **Acceptance**: each writer with `device_id: "testdev1"` in config writes `<base>.testdev1.jsonl` and never the bare file; a reader given a bare file plus two device shards plus a `*.sync-conflict-*` copy returns the union of the first three in deterministic order and the doctor names the fourth with its directory; `log-shards.read.test.ts` and `log-shards.write.test.ts` pass unmodified; lineage verify reports per shard; the state-surface census and `tests/core/state/surfaces.test.ts` pass.
+- **Depends on**: none
+
+### Task 2: Fleet freeze (t_109fa94d)
+- **Files**: new `src/core/brain/freeze-marker.ts` (`FROZEN_MARKER_FILE`, `readFreezeMarker`, `assertVaultNotFrozen`, `VaultFrozenError`, `WRITE_LANE`, per-process inode cache); new `src/core/brain/freeze.ts` (`freezeVault`, `unfreezeVault`, log events `freeze` / `unfreeze`); `src/core/brain/vault-identity.ts` (third parameter `lane`, freeze check first for the content lane); `src/core/brain/paths.ts` (`brainDirsForWrite(vault, notices?, lane?)`, `frozenMarkerPath`); `src/core/brain/log.ts` (passes `WRITE_LANE.audit`); `src/core/brain/types.ts` (three event kinds); `src/core/brain/status.ts` + `src/cli/brain/verbs/status.ts` + `src/mcp/brain/health-tools.ts` (`frozen` field); new doctor check `src/core/brain/doctor/frozen-check.ts` + `DIAGNOSTIC_SIGNALS` entry `vault-frozen` (`nextCommand: "o2b brain unfreeze"`); MCP error boundary in `src/mcp/tools.ts` (map `VaultFrozenError` -> structured refusal, append `write-refused` naming the tool); `src/core/brain/destructive-sites.ts` (marker removal); `src/core/state/surfaces.ts` (marker row, 42 -> 43, `DECLARED_SURFACE_COUNT` in `tests/core/architecture/state-surface-census.test.ts:83`); new CLI verbs `freeze`, `unfreeze` (six places); `docs/cli-reference.md`, `docs/observability.md`, `docs/mcp.md` (refusal shape); tests: `tests/core/brain/freeze-marker.test.ts`, `freeze.test.ts`, a lane pin test asserting `WRITE_LANE.audit` is referenced only from `log.ts` and `freeze-marker.ts`/`freeze.ts`, `tests/core/brain/vault-identity*.test.ts` extension, CLI test `tests/cli/brain-freeze.test.ts`, MCP test that `brain_create_note` on a frozen vault returns the structured refusal and a `write-refused` event lands in the log, `doctor-exit-census` passes.
+- **Acceptance**: with the marker present every guarded content write throws `VaultFrozenError` naming `frozen_at`, `by`, `reason` and the next command; `appendLogEvent` still works; `o2b brain freeze --reason x` writes the marker and one `freeze` event, `unfreeze` removes it and writes one `unfreeze` event; a malformed marker freezes; `o2b brain status` and `brain_status` show `frozen`; `o2b brain rollback` on a frozen vault is refused by name.
+- **Depends on**: none
+
+### Task 3: Attributable note writes (t_662f4e82)
+- **Files**: new `src/core/brain/notes/write-record.ts` (`NOTE_WRITE_OP`, `NOTE_WRITE_NO_PRIOR = "absent"`, `noteWriteId`, `storeBeforeImage`, `recordNoteWrite`, `writeImagePath`, `WRITE_IMAGE_RETENTION_DAYS`, `pruneWriteImages`); new `src/core/brain/notes/write-log.ts` (`listNoteWrites(vault, {agent, device, path, since, until, op})` over `readLogDay`); `src/core/brain/notes/create-note.ts` (record after the exclusive write, `write_id` / `audit_reason` on the result); `src/core/brain/write-batch.ts` (update/append commits: hash raw bytes before, store image, write, record; results gain `write_id`); `src/mcp/brain/notes-tools.ts` + `write-batch-tools.ts` (receipts carry `write_id`); `src/core/brain/types.ts` (event kind `note-write`); `src/core/brain/agent-source/types.ts` + `vault-provider.ts` (kind `note`); `src/core/brain/destructive-sites.ts` (image prune); `src/core/state/surfaces.ts` (write-images row, count +1); new CLI verb `writes` (`list` default with `--agent --device --path --since --until --op --json`, `prune-images [--older-than-days N] [--dry-run]`); new MCP tool `brain_writes` (`action: list`; `plan_revert` arrives in Task 5 - declare the enum with both members now and refuse `plan_revert` by name until Task 5 lands, or leave the enum single-valued; pick the first so the pins move once); `docs/observability.md`, `docs/cli-reference.md`, `docs/mcp.md`, README; tests: `tests/core/brain/notes/write-record.test.ts`, `write-log.test.ts`, extensions of `tests/core/brain/write-batch.test.ts` and the create-note suite, agent-source test for kind `note`, CLI and MCP tests, write-site census pins (`tests/core/architecture/write-site-census.test.ts`: new shared-helper rows), destructive-site and state-surface census, MCP pins listed above.
+- **Acceptance**: creating, updating and appending a note through MCP and through the kernel each append exactly one `note-write` JSONL line with the fields in the design; the before-image file exists with sha256 = `hash_before` after an update; a second update to the same content does not write a second image; `listNoteWrites` filters by agent and path; `brain_agent_query` lists the note under kind `note`; a log-append failure (simulated) leaves the note written and the result with `write_id: null` and an `audit_reason`; `prune-images --dry-run` lists and `--older-than-days 0` removes.
+- **Depends on**: none
+
+### Task 4: Per-shard hash chain on the Brain log (t_8a7bf39a)
+- **Files**: `src/core/brain/log.ts` (`renderJsonlLine` gains `prev` + `h`; the appender computes them from the shard text it already holds under the lock; `LOG_CHAIN_FIELDS` constant); `src/core/brain/log-jsonl.ts` (`readJsonl` ignores the two keys; export a raw-line scanner for the verifier); new `src/core/brain/log-chain.ts` (`logChainHash`, `verifyLogChain(vault) -> { shards: [{ path, chained, legacy, firstBreak?: { line, reason } }], ok }`); new doctor check + `DIAGNOSTIC_SIGNALS` entry `log-chain-broken` (`nextCommand: "o2b brain log verify"`); new CLI verb `log` with `verify [--json]`; `docs/observability.md` (chain paragraph, markdown twin declared derived); tests: `tests/core/brain/log-chain.test.ts` (genesis, legacy prefix, edited line, deleted line, appended-by-hand line, two shards independent), existing log tests still pass byte-for-byte on the markdown side, CLI test, doctor-exit census.
+- **Acceptance**: three appends produce three lines whose `prev` links match; editing the middle line's payload makes verify report line 2 `hash-mismatch`; deleting it reports line 3 `prev-mismatch`; a file of legacy lines followed by chained lines verifies clean with `legacy = N`; the doctor emits `log-chain-broken` only on a break.
+- **Depends on**: Task 1 (shard listing lives in `ledger-shards.ts`)
+
+### Task 5: Per-agent revert (t_924129c5)
+- **Files**: new `src/core/brain/notes/revert.ts` (`planNoteRevert(vault, selector) -> NoteRevertPlan { entries: [{ target, action: restore|delete|refuse, reason?, writes: [write_id], hash_now, hash_to }], digest }`, `applyNoteRevert(vault, digest) -> { snapshot, applied, refused }`, `NOTE_REVERT_REFUSAL = { drift, interleaved, imageMissing }`); `src/core/brain/types.ts` (`BRAIN_SNAPSHOT_REASON.noteRevert`); `src/core/brain/notes/write-record.ts` (op `revert`); CLI `writes revert --agent A | --device D [--path P] [--since --until] [--apply <digest>] [--json]`; MCP `brain_writes` action `plan_revert` (same selector, no apply); `docs/cli-reference.md`, `docs/mcp.md`, README; tests: `tests/core/brain/notes/revert.test.ts` (restore, delete, drift, interleaved, image-missing, digest mismatch, revert-of-revert), CLI test, MCP test, snapshot-reason test.
+- **Acceptance**: after agent A updates a note twice and agent B never touches it, `revert --agent A` plans one `restore` to the pre-A bytes and `--apply <digest>` restores them, takes a `note-revert` snapshot, and appends a `note-write` event with `op: revert`; if B updated in between the plan refuses `interleaved`; if the note changed after A's last write the plan refuses `drift`; a note A created is planned `delete`; applying a stale digest is refused before any byte moves.
+- **Depends on**: Task 3
+
+### Task 6: Reconciliation, docs, version
+- **Files**: every count pin touched by more than one task (`tests/mcp/*`, `tests/helpers/tool-probe-catalogue.ts`, state-surface and write-site censuses, `docs/architecture.md` surface count prose near line 201); `CHANGELOG.md` `[1.55.0]` + link reference; `package.json` 1.55.0 + `bun run scripts/sync-version.ts`; README paragraph; `docs/observability.md` final pass.
+- **Acceptance**: `bun run typecheck`, `bun run lint`, `bun run fmt:check`, `bun run test`, `bun run sync-version:check`, `python -m unittest discover -s tests/python` all green on the merged branch.
+- **Depends on**: Tasks 1-5
diff --git a/docs/brainstorm/who-wrote-what/variants.md b/docs/brainstorm/who-wrote-what/variants.md
new file mode 100644
index 00000000..065916e5
--- /dev/null
+++ b/docs/brainstorm/who-wrote-what/variants.md
@@ -0,0 +1,60 @@
+# Who wrote what, and how to take it back - brainstorm audit trail
+
+Consultant: Claude Code (`claude -p`), prompt at `cli-output/prompt.md`, verbatim output at `cli-output/claude.md`. Fallback consultant not needed (three parseable variants returned).
+
+## Variants as returned
+
+### Variant 1: Seam-first, thin shared primitives
+
+- **Approach**: Add one note-write seam (`src/core/brain/notes/write-seam.ts`) that every note mutation passes through: it checks the freeze marker, hashes the target before and after, runs the atomic write, and emits one `note_write` log event through `appendLogEvent` in `src/core/brain/log.ts` with the pref-audit field shape (`agent`, `hash_before/after`, `origin_channel` stamped server-side at `log.ts:335`). Extract only the shard grammar, listing and merge from `src/core/brain/log-jsonl.ts:52-62` into a small `ledger-shards.ts` and re-point the five unsharded writers at it; put the per-shard `prev` chain inside the log appender only; build revert as plan-seal-apply over `note_write` events with the before-image resolved from a content-addressed image store written by the seam. Landing order: B (shards) β†’ A (seam + event) β†’ C (freeze at the seam) β†’ E (chain in appender + doctor) β†’ D (revert).
+- **Trade-offs**:
+ - Pro: A and C share one chokepoint, and the write-site census (`tests/core/architecture/write-site-census.test.ts`) can pin "every note writer routes through the seam" the same way it pins direct-fs exclusions. Internal callers (dream apply, dedup merge, write-session commit in `write-session/engine.ts:414`, `write-batch.ts:236`) are covered because the seam sits below the MCP layer.
+ - Pro: the shard extraction is mechanical; `continuity/store.ts:98`, `idempotency-ledger.ts:126`, `pref-audit.ts`, `metrics.ts:69` and `lineage/ledger.ts` each swap one path function and one reader loop. The bare file name already means "empty shard id" (`log-jsonl.ts:6`), so no rename migration is needed, only a doctor lint that reports leftover bare files being appended to by a second device.
+ - Pro: content-addressed before-images (`Brain/.state/write-images/<sha256>`) dedupe naturally, and the log event only carries the hash. The snapshot gate (`snapshot-gate.ts`) covers `Brain/` top-level entries, so the image store is inside the recovery region.
+ - Pro: revert reuses `sealManifest` and the `destination_occupied`-style drift refusal from `src/core/state/migrate.ts:186,724`; the only new semantics are "refuse on drift", the simplest of the three options the task leaves open.
+ - Con: the lineage ledger carries its own `seq` and chain plus in-place compaction; sharding it per device means the verifier in `lineage/verify.ts` must iterate shards, which is a real change, not a path swap.
+ - Con: the image store grows with every edit until pruned; it needs a retention rule tied to the snapshot policy in `policy.ts` or it becomes a second unbounded ledger.
+ - Con: the chain lives in `log.ts`, so other ledgers stay unchained. Acceptable per Task E scope, but a second chain later will want the primitive Variant 2 builds now.
+ - Con: new `prev` on every log line changes log bytes for every vault. Mitigation: legacy lines without `prev` are treated as chain genesis, and the verifier names them `unchained-legacy` rather than broken.
+- **Complexity**: medium
+- **Risk**: low
+
+### Variant 2: One append-only ledger abstraction carrying shards and chain
+
+- **Approach**: Build `src/core/brain/ledger/` as a typed `AppendOnlyLedger` that owns shard naming, the device id from `resolveDeviceId()`, the sync writer lock, sync-conflict exclusion, deterministic merge, and an optional per-shard hash chain. Move Brain/log, continuity, idempotency, pref-audit, metrics and lineage onto it, so Task B and Task E are one change; Task A's `note_write` event and Task C's freeze refusal event are records on the same log ledger; Task D reads the ledger's typed cursor and stores the before-image inline in the event. Landing order: ledger primitive β†’ migrate six writers β†’ seam + freeze β†’ revert.
+- **Trade-offs**:
+ - Pro: sharding, locking and chaining are written once and every current and future ledger inherits them; the census for "did we miss one" becomes a type check rather than a grep over `src/core/state/surfaces.ts`.
+ - Pro: Task E's "which files are chained" question has one answer: any ledger with `chain: true`, verified by one doctor check with one finding code.
+ - Con: Brain/log has a markdown twin, a directory-level lock and a byte-exact idempotent append contract (`log.ts:335-380`); folding it into a generic ledger risks changing bytes for vaults that enable nothing, which the constraints forbid.
+ - Con: the lineage ledger's compaction, gap sidecar and `seq` allocation (`lineage/ledger.ts:100-180`) do not fit a generic append-only shape without either a leaky escape hatch or a second abstraction.
+ - Con: inline before-images make the log the largest file family in the vault and put note bodies into a file `o2b brain protect` and Obsidian expose; redaction rules from `continuity/redaction.ts` would have to apply to the log too.
+ - Con: file count and review surface exceed the 50-70 file budget once six readers, six writers, their tests, and the pinned state-surface count are all touched in one PR.
+- **Complexity**: large
+- **Risk**: high
+
+### Variant 3: Boundary middleware, core untouched
+
+- **Approach**: Enforce freeze and emit write events at the MCP and CLI boundary: a `withWriteGuard` wrapper over `ToolDefinition` in `src/mcp/` (next to `reach-refusal.ts`) and a matching CLI verb decorator, keyed on a tool allow-list of mutating verbs. Shards are done per ledger by copying the `LOG_FILE_RE` grammar into each writer; the chain goes into `log.ts`; revert resolves before-images from the nearest snapshot manifest (`manifest.ts` `diffManifests`) and refuses when none covers the write. Landing order: C β†’ A β†’ B β†’ E β†’ D.
+- **Trade-offs**:
+ - Pro: smallest diff, and the refusal shape is already the house style for boundary refusals (`src/mcp/reach-refusal.ts`).
+ - Pro: no change to core write functions, so bit-identical behaviour for unchanged vaults is trivially true.
+ - Con: the boundary is not the write seam. Dream apply, hygiene, lifecycle, page-dedup merge and the write-session engine mutate `Brain/` from inside core and would bypass both the freeze and the event, which is exactly the `o2b brain protect` failure the task cites. The census cannot pin a wrapper applied by list.
+ - Con: `hash_before` must be computed before the core write and `hash_after` after it, but the handler does not know the resolved target path until `resolveNoteTarget` runs inside `createNote`; the wrapper ends up re-implementing target resolution or recording the caller's unresolved path.
+ - Con: snapshots are opt-in and pruned, so most revert plans would refuse for lack of a before-image, making Task D mostly a report rather than an apply path.
+ - Con: five copies of the shard grammar drift the day one changes; the project's own DRY brief forbids this.
+- **Complexity**: small
+- **Risk**: high
+
+
+## Consultant recommendation
+
+Variant 1 (seam-first, thin shared primitives). Rationale as returned: the seam is the only position that covers the internal writers, the censuses can pin it, the shard extraction keeps `log.ts` byte-stable, the content-addressed image store gives revert a real apply path; Variant 2 does not fit one wave under the bit-identical constraint; Variant 3 repeats the bypassed-boundary failure the epic exists to fix.
+
+## Orchestrator decision
+
+Variant 1 accepted, with two overrides grounded in the reconnaissance the consultant did not have:
+
+1. The freeze guard hooks `assertVaultIdentityForWrite`, not the note-write seam. The note seam covers note writers only; the identity guard is called at 98 sites across 60 modules and is the position "check before any byte" already occupies. A `lane` parameter exempts the Brain log appender and the marker writer so the freeze can be recorded while in force.
+2. Refusal events are recorded at the MCP tool boundary, not inside the guard, because the guard cannot import the log module without an import cycle (log -> paths -> vault-identity). The boundary is where the agent-facing refusal is produced anyway.
+
+Variant 2 was rejected for the reasons the consultant gave and one more: the lineage ledger's compaction and gap sidecar would need a leaky escape hatch in any generic ledger type. Variant 3 was rejected because `dream`, `hygiene`, `page-dedup` and the write-session engine write from inside core and would bypass both the freeze and the event, which is the `o2b brain protect` failure the epic cites.
diff --git a/docs/cli-reference.md b/docs/cli-reference.md
index e535f5a2..d7357e8e 100644
--- a/docs/cli-reference.md
+++ b/docs/cli-reference.md
@@ -315,9 +315,15 @@ o2b brain monthly Month-level Brain synthesis over timeline events,
o2b brain query Read helper: by preference, by topic, or by log timestamp; --topic adds point-in-time recall over the expiration filter: --at <ISO|YYYY-MM-DD> evaluates expiration_date as of that instant (default now, unparseable is refused with exit 2, never coerced) and --show-expired keeps lapsed memories. Both apply to --topic only and are refused elsewhere; omitting both leaves the output byte-identical
o2b brain agent-query Read source-agent provenance; filters by --agent, --topic, --query, --kind, --limit; --json mirrors brain_agent_query
o2b brain agent-diff Compare source-agent coverage in browse/search/diff/map modes; --json mirrors brain_agent_diff
+o2b brain writes Recorded note writes, newest first: timestamp, operation, agent, device, target, and the content digest on each side; filters by --agent, --device, --path, --since, --until, --op; --json mirrors brain_writes action=list. The device comes off the log shard, so a legacy un-sharded log prints '-' rather than a guess
+o2b brain writes revert (CLI-only) Undo the recorded note writes a selector names: `(--agent A | --device D | --path P)` plus optional `--since` / `--until`, and `--apply <digest>` to run it. A selector naming none of agent, device or path is refused by name (`unbounded_selector`) - a time window alone is a vault rollback, which is `o2b brain rollback`. Without `--apply` it PLANS: each target resolves to `restore` (put the before-image of the oldest selected write back), `delete` (the selected writes created the note and nothing wrote it before) or a refusal naming `drift` (the bytes on disk are not the ones the newest selected write left), `interleaved` (an unselected write sits between the oldest and newest selected write in the merged `(timestamp, shard id, line)` order; line order inside one shard is append order, so a same-second write on the SAME shard is ordered rather than refused, while a same-second write from another device shard is refused on doubt), `image-missing` (the before-image is not in the store), `unrecorded` (the current bytes cannot be read at all) or `already-reverted` (the target already holds what the revert would produce). The plan prints its `digest:` on its own line followed by the exact `--apply` invocation, and exits 0 even when every target is refused - a plan that refuses everything is a report. `--apply` re-plans and refuses `digest_mismatch` before any byte moves, refuses `nothing_to_apply` when no entry is actionable, then runs every restore and delete inside one `note-revert` snapshot and records each as a note write of operation `revert`, so a revert is itself attributable and revertible. A frozen vault refuses it by name before anything is read
+o2b brain writes prune-images (CLI-only) Remove note-write before-images older than --older-than-days (default 30); --dry-run lists what would go and removes nothing; --json
o2b brain reject (CLI-only) Retire a preference; requires --reason "<text>". Subsequent signals on the same topic are suppressed.
o2b brain merge (CLI-only) Fold one confirmed/quarantine pref into another (<keep> <drop>); --dry-run / --force; drop retires with reason 'merged-into'
o2b brain pin / unpin (CLI-only) Toggle pinned: true on a preference (exempt from auto-retire)
+o2b brain freeze (CLI-only) Write Brain/.state/frozen.json and stop every content write in this vault (--reason "<text>", --json). Syncthing carries the marker, so the stop holds on every device that shares the vault, not only this one. The Brain log keeps recording: `freeze` names who set it, and each refused MCP call appends `write-refused`. Idempotent - a second freeze reports the first one's timestamp, agent and reason rather than replacing them. A marker that is present and unparseable freezes too: an operator who wrote a broken one meant to stop writes
+o2b brain unfreeze (CLI-only) Remove the freeze marker and reopen the content lane (--json). The `unfreeze` log event records who lifted it plus what the marker said, which is the only place those survive the file. Idempotent. `o2b brain rollback` is refused while frozen like every other content write, with no exemption for recovery: an operator restoring a frozen vault is the operator who should decide the freeze is over
+o2b brain log verify Walk every JSONL shard of the Brain log and report where each one stops linking up (--json). Each appended row carries `prev` and `h`: `h = sha256(canonical JSON of { prev, ts, kind, payload })`, `prev` the previous chained line's `h` or null at the shard's genesis, so an edited or deleted line is detectable. Output names the shard path, the line number, and the break - `hash-mismatch` (the line was edited), `prev-mismatch` (a line was removed or reordered), `malformed` (a line carries no chain link where the chain had already started). Rows written before the chain shipped carry no `h` and are counted as legacy: clean while they precede the chain, a break after it. The markdown twin is a derived rendering and is not chained. Reports only - nothing rewrites a log to make it verify and the read path never consults the chain - and exits 1 when any shard does not link up
o2b brain set-primary (CLI-only) Declare or clear primary_agent in Brain/_brain.yaml (--clear)
o2b brain protect (CLI-only) Emit / apply native deny rules for Brain/ (--target {claudecode|codex} [--apply])
o2b brain unprotect (CLI-only) Remove the Open-Second-Brain-managed deny rules for the chosen target
diff --git a/docs/how-it-works.md b/docs/how-it-works.md
index 26f517d4..16c61d06 100644
--- a/docs/how-it-works.md
+++ b/docs/how-it-works.md
@@ -697,7 +697,8 @@ event to the archive that would undo it.
Every snapshot now carries a typed reason from one closed vocabulary
(`BRAIN_SNAPSHOT_REASON`): `dream`, `upgrade`, `import-claude-memory`,
-`delete-by-source`, `entity-prune`, `note-delete` for the six destructive
+`delete-by-source`, `entity-prune`, `note-delete`, `note-revert` for the
+seven destructive
call sites, plus `manual` for the recovery point a rollback takes of the
live tree it is about to discard (`restoreSnapshotWithRecoveryPoint` in
`snapshot-gate.ts`, reached from `o2b brain rollback`). Three members have
diff --git a/docs/mcp.md b/docs/mcp.md
index cc20e1f0..74b37d1e 100644
--- a/docs/mcp.md
+++ b/docs/mcp.md
@@ -194,6 +194,7 @@ flags for a narrower per-process full server.
| `brain_codegraph_report` | Read-only codegraph partner report: in-scope code project, index state (`no_project`/`absent`/`not_indexed`/`indexed` with counts/`error`), and structural `Cargo.toml` workspace members. When indexed, attaches a non-blocking `index.health` graph-health gate (`empty-graph`, `collapsed-edges`, `dangling-references`, `self-loops`, `cache-root-mismatch`) surfaced before labeling/import/recall trust the graph. Never installs, extracts, or mutates; non-Rust projects report `cargo_workspace: null` with a reason. | β€” |
| `brain_agent_query` | Read-only source-agent retrieval over Brain provenance. Filters by agents, topic, free-text query, contribution kind, and limit. | β€” |
| `brain_agent_diff` | Read-only comparison between source agents using browse/search/diff/map modes over the same provenance foundation. | β€” |
+| `brain_writes` | Read-only listing of recorded note writes (create / update / append / revert), newest first, with the agent, the device the log shard names, the target path and the content digest on each side. Filters by agent, device, path, op and time window. `action: plan_revert` returns the sealed plan for undoing a selection of those writes - one entry per target with its action, refusal reason and both digests - and never applies it; applying is CLI-only. | β€” |
| `brain_audit` | Read-only per-preference mutation trail (create / promote / update / retire / merge) with agent, reason, revision + content-hash before/after. | `pref_id` |
| `brain_brief` | Read-only Brain summary for any window: `view: morning \| daily \| weekly \| monthly \| operator \| digest`. | `view` |
| `brain_analytics` | Read-only Brain analytics for any lens: `view: timeline \| attention_flows \| belief_evolution \| concept_synthesis \| dedup`. `view=dedup` summarises the persisted exact-hash ingest dedup records into a trend plus a per-source re-ingest ranking; every count is an exact sha-256 drop, never a semantic figure (the semantic detectors nominate merge candidates and never drop). | `view` |
@@ -251,7 +252,29 @@ alias-to-replacement table lives in `docs/updating.md`.
`brain_agent_query` accepts `agents` (string array), `topic`, `query`, `kind`
(`signal`, `preference`, `log`), and `limit` (1-500, default 50).
`brain_agent_diff` accepts the same filters plus `mode` (`browse`, `search`,
-`diff`, `map`). Omitting `agents` means all known source agents.
+`diff`, `map`). Omitting `agents` means all known source agents. Both accept
+`kind: note`, which lists the notes an agent wrote: the vault provider maps
+every `note-write` log event to a contribution whose `path` is the note and
+whose title is the operation.
+`brain_writes` accepts `action` (`list`, default; `plan_revert`), `agent`,
+`device`, `path`, `op` (`create`,
+`update`, `append`, `revert`), `since` / `until` (a bare `YYYY-MM-DD` or an
+ISO-8601 UTC timestamp; a bare `until` date covers the whole day it names), and
+`limit` (1-500, default 50). It answers with `total_matched` beside `returned`,
+so a capped list is legible as one, and each row carries `write_id`, both
+content digests, both byte counts and the device the log shard names - the
+empty string being the legacy un-sharded log rather than an unknown machine.
+`action: plan_revert` takes the same selector (`agent`, `device`, `path`,
+`since`, `until`) and returns the sealed plan for undoing the writes it names:
+one entry per target with `action` (`restore`, `delete`, `refuse`), `reason`
+when refused (`drift`, `interleaved`, `image-missing`, `unrecorded`,
+`already-reverted`), the selected `writes` oldest first, and `hash_now` /
+`hash_to`; plus the `digest` that seals it and `next_command`. A selector
+naming none of `agent`, `device` or `path` is refused with `INVALID_PARAMS`
+carrying `unbounded_selector` - a time window alone is a vault rollback. There
+is no apply here: applying moves bytes on targets the caller may never have
+written, so `o2b brain writes revert --apply <digest>` is where a human types
+the digest.
`brain_search` accepts `query_document` with line-oriented `intent:`, `lex:`,
`vec:`, and `hyde:` lanes; `focus_query` / `focus_path_prefix` to steer a
single call; `since` / `until` time ranges (ISO date/datetime, `today`,
@@ -1298,6 +1321,21 @@ log line is machine-composed rather than authored.
`transport-reach` are one argument rather than three. `disclosure` is
deliberately not reserved - it is the unrelated result-depth mode on the
recall surfaces.
+- Since v1.55.0 a write attempted while the vault is FROZEN
+ (`o2b brain freeze`, marker `Brain/.state/frozen.json`) is refused with
+ `-32602`, the refusal token `vault_frozen`, and structured `data`:
+ `code`, `tool`, `frozen_at`, `by`, `reason`, and
+ `next_command: "o2b brain unfreeze"`. The refusal is raised by the vault
+ write guard, so it covers every tool that puts bytes in the vault -
+ including the internal writers a tool composes - rather than a list of
+ write tools somebody maintained. Each refused call also appends one
+ `write-refused` event to the Brain log naming the tool, the caller and
+ the marker's reason; when that append itself fails, the payload carries
+ an `audit_reason` saying why rather than reporting a record that does
+ not exist. No MCP tool sets or clears the freeze: lifting one is an
+ operator decision about a fleet an agent cannot see, so `freeze` and
+ `unfreeze` are CLI-only. `brain_status` reports the state as
+ `frozen: null | { frozen_at, by, device_id, reason }`.
- Since v1.54.0 a withheld page is reported exactly as an absent one. On
the key-addressed reads - a chunk id, a preference id, the templated
`osb://` readers - the message is byte-identical to the one an absent
@@ -1308,3 +1346,17 @@ log line is machine-composed rather than authored.
It does NOT prove operator intent: a remote host can spawn a stdio
subprocess. The alternative - no bypass at all - would take an operator's
own reserved notes away from the operator's own shell.
+- Since v1.55.0 every note write is attributable. `brain_create_note`,
+ `brain_update_note`, `brain_append_note` and the note operations of
+ `brain_write_batch` each append exactly ONE `note-write` log event carrying
+ a write id, the operation, the target path, the content hash and byte size on
+ both sides, and the agent the server's own config names; the bytes an update
+ or append replaced are kept content-addressed under
+ `Brain/.state/write-images/<sha256>` so a recorded write can be undone from
+ what it displaced. The bytes land BEFORE the event is appended, which is the
+ ordering that keeps a log failure from failing a write - and the receipts say
+ so rather than staying silent: every note-write receipt carries `write_id`,
+ and `write_id: null` arrives with an `audit_reason` naming what went wrong. A
+ skipped create (`if_exists: "skip"`) authored no bytes, so it carries no
+ `write_id` at all. `brain_writes` reads the record back. One new tool - the
+ surface moves from 113 to 114.
diff --git a/docs/metrics.md b/docs/metrics.md
index 5aa0e8f7..f8abd695 100644
--- a/docs/metrics.md
+++ b/docs/metrics.md
@@ -8,22 +8,35 @@ read metrics without importing Open Second Brain internals.
## Layout
-One append-only JSONL file per surface:
+One append-only JSONL file per surface PER DEVICE, named
+`<surface>[.<device-id>].jsonl`:
```
Brain/metrics/
-β”œβ”€β”€ index.jsonl
-β”œβ”€β”€ bridge_discovery.jsonl
-β”œβ”€β”€ communities.jsonl
-β”œβ”€β”€ recall_benchmark.jsonl
-β”œβ”€β”€ self_tuning.jsonl
-β”œβ”€β”€ self_heal_reindex.jsonl
-└── dream_stage.jsonl
+β”œβ”€β”€ index.jsonl # the shard with the empty device id
+β”œβ”€β”€ index.a1b2c3d4.jsonl # one machine's shard
+β”œβ”€β”€ index.e5f6a7b8.jsonl # another machine's shard
+β”œβ”€β”€ bridge_discovery.a1b2c3d4.jsonl
+β”œβ”€β”€ communities.a1b2c3d4.jsonl
+β”œβ”€β”€ recall_benchmark.a1b2c3d4.jsonl
+β”œβ”€β”€ self_tuning.a1b2c3d4.jsonl
+β”œβ”€β”€ self_heal_reindex.a1b2c3d4.jsonl
+└── dream_stage.a1b2c3d4.jsonl
```
Surface names are lowercase snake_case (`[a-z][a-z0-9_]*`, max 64
-chars). A consumer reads only the files it renders; unknown files in
-the directory must be ignored.
+chars); device ids are lowercase slugs (`[a-z0-9-]`, max 32 chars). The
+vault is Syncthing-replicated, so a device only ever appends to the file
+its own id names - see "The per-device shard rule" in
+`docs/observability.md`. A file with no device suffix is the shard with
+the empty device id and is read exactly like any other.
+
+**A consumer must therefore group by surface, not by file name**: strip
+an optional trailing `.<device-id>` segment before the `.jsonl`
+extension to get the surface, and read every file that maps to the
+surface it renders. Two names are never metric shards: a
+`*.sync-conflict-*` copy (Syncthing leftover; `o2b brain doctor` reports
+it) and any other unknown file in the directory, which must be ignored.
## Record envelope
@@ -41,7 +54,8 @@ Every line is one JSON object:
- `schema` - envelope version. Evolution rule mirrors continuity
records: additive optional payload fields do NOT bump the version;
renames, removals, or semantic changes bump to `o2b.metrics.v2`.
-- `surface` - matches the file name.
+- `surface` - matches the file name with any `.<device-id>` shard
+ suffix removed.
- `run_at` - ISO-8601 UTC timestamp of the run the record describes.
- `payload` - surface-specific object (fields below).
diff --git a/docs/observability.md b/docs/observability.md
index 43f5a107..214d41ac 100644
--- a/docs/observability.md
+++ b/docs/observability.md
@@ -6,11 +6,26 @@ Open Second Brain records what it did - learning events, recall decisions, serve
| Surface | Location | Writer | Format |
|---|---|---|---|
-| Brain log | `Brain/log/<date>.md` + JSONL sidecar | `appendLogEvent()` in `src/core/brain/log.ts` | Markdown line + JSONL row per event |
-| Continuity store | `Brain/log/continuity/<month>.jsonl` | `appendContinuityRecord()` in `src/core/brain/continuity/store.ts` | one JSON record per line |
+| Brain log | `Brain/log/<date>[.<device-id>].md` + JSONL sidecar | `appendLogEvent()` in `src/core/brain/log.ts` | Markdown line + JSONL row per event |
+| Continuity store | `Brain/log/continuity/<month>[.<device-id>].jsonl` | `appendContinuityRecord()` in `src/core/brain/continuity/store.ts` | one JSON record per line |
+| Idempotency ledger | `Brain/logs/idempotency/<month>[.<device-id>].jsonl` | `rememberKey()` in `src/core/brain/idempotency-ledger.ts` | one `key -> content hash` record per line |
+| Preference mutation audit | `Brain/log/pref-audit/<pref-id>/device[.<device-id>].jsonl` (legacy flat `Brain/log/pref-audit/<pref-id>[.<device-id>].jsonl` still read) | `appendPrefAudit()` in `src/core/brain/pref-audit.ts` | one JSON record per line |
+| Session lineage ledger | `Brain/.state/session-lineage[.<device-id>].jsonl` (+ `session-lineage-gaps[.<device-id>].jsonl`) | `recordLineageObservation()` in `src/core/brain/lineage/ledger.ts` | one JSON record per line, sequence-numbered and hash-chained per file |
| Session lifecycle audit | `Brain/log/session-lifecycle/` | `captureSessionLifecycleEvent()` in `src/core/brain/session-lifecycle.ts` | JSONL audit rows |
| Bench runs | `<runs-dir>/<run-id>/` (default `.open-second-brain/bench-runs/`, gitignored) | `runMemoryBench()` in `src/core/bench/phases.ts` | `checkpoint.json`, per-question results, `report.json` |
-| Metrics | `Brain/metrics/<surface>.jsonl` | `appendMetric()` in `src/core/brain/metrics.ts` | one run-level JSON record per line (see `docs/metrics.md`) |
+| Metrics | `Brain/metrics/<surface>[.<device-id>].jsonl` | `appendMetric()` in `src/core/brain/metrics.ts` | one run-level JSON record per line (see `docs/metrics.md`) |
+
+### The per-device shard rule
+
+Every append-only ledger above is one file per period (or per key, or per surface) PER DEVICE. The vault is replicated with Syncthing, and two machines appending to one file inside a single sync window produce a `.sync-conflict-*` copy that no reader merges β€” so the rows split silently across two files. The shard suffix removes the contention instead of resolving it after the fact: a device only ever appends to the file its own id names.
+
+The grammar is `<base>[.<device-id>].<ext>`, and it lives in exactly one place, `src/core/brain/ledger-shards.ts`. The device id is the lowercase slug `resolveDeviceId()` produces (`src/core/config.ts`), which is device-local config and never synced. **A file with no device suffix is the shard with the EMPTY id**: legacy history stays readable, no migration renames anything, and a vault whose device id resolves empty (`O2B_DEVICE_ID=""`, or a config that cannot be read) keeps writing exactly the bytes it always did.
+
+Every reader merges every shard it finds, in the one order all devices agree on: **the ledger's own sort key, then the shard id, then position within the shard**. The shard id is the tie-break rather than the arrival order because arrival order is precisely what differs between two Syncthing peers β€” so two machines reading the same set of shards return the same sequence. The continuity store adds its content-hash record id as a last resort after the shard id, which is what keeps a single-shard vault reading back in exactly the order it did before sharding existed.
+
+Two names are never shards. A `*.sync-conflict-*` copy is excluded from every listing even when its middle segment fits the shard-id shape (the `sync-conflict` prefix is reserved in the device-id validator for the same reason), and `o2b brain doctor` reports any leftover copy under any ledger directory as `sync-conflict-log`, naming the directory so the union+dedup merge has an address. A name whose base does not match the ledger's own layout is not that ledger's file at all β€” bases go into the grammar as patterns, or as escaped literals where the base is a value (a preference id may legitimately contain a dot).
+
+The session lineage ledger is the one with an extra invariant: its sequence numbers and hash chain are per FILE, so a per-device shard is a per-device chain, compaction is per shard, and `verifyLineageLedger` verifies each shard separately and reports each finding under that shard's own path. A break in one machine's ledger says nothing about another's.
The `prompt_prefix` metric surface measures STRUCTURAL prompt-prefix stability (whether the kernel handed the agent a byte-stable, cache-eligible preamble across a generation pass), never a provider's cache-hit rate the kernel cannot observe. It stores only the SHA-256 hash and length of the prefix, never the raw prompt - the same payload-safety rule as `generation_report`. See `docs/metrics.md`.
@@ -23,10 +38,64 @@ The `prompt_prefix` metric surface measures STRUCTURAL prompt-prefix stability (
| `dream`, `promote`, `retire`, `noted-redundant`, `signal-suppressed`, `skip-corrupted-frontmatter`, `reconcile` | the deterministic learning pass runs |
| `feedback`, `apply-evidence`, `force-confirmed`, `reject` | a taste signal or evidence event is recorded |
| `pin`, `unpin`, `rollback`, `merge`, `upgrade` | operator-facing vault maintenance |
+| `freeze`, `unfreeze` | an operator stopped or reopened the content lane for every device that syncs the vault (`o2b brain freeze` / `o2b brain unfreeze`). One event per real transition only - a second freeze, or an unfreeze on an open vault, writes nothing. `freeze` carries the `reason` and the `device_id` it was set from; `unfreeze` carries the `frozen_at`, `by` and `reason` read off the marker before it was removed, which is the only place they survive the file |
+| `write-refused` | a write was refused because the vault is frozen. Appended at the MCP tool boundary - the guard that refuses sits below the log module and cannot append without closing an import cycle - one per refused call, carrying the `tool`, the `agent` and the marker's `reason`. The Brain log itself keeps writing while frozen (the audit write lane, `WRITE_LANE.audit` in `src/core/brain/freeze-marker.ts`), because a freeze that silenced the log would erase the record of itself |
| `scan-inline`, `import-session`, `import-claude-memory` | capture and import operations |
| `note` | a narrative milestone is recorded (`brain_note`) |
+| `note-write` | a vault note is created, updated, appended to, or reverted |
| `session-lifecycle` | a captured lifecycle event also produced Brain writes |
+### Note writes
+
+Every note mutation funnels through two seams - `createNote` and the write-batch kernel - and each one appends exactly ONE `note-write` event. The payload is all strings, because the log payload contract admits `string | string[]` and nothing else:
+
+| Field | What it holds |
+|---|---|
+| `write_id` | `nw_<14 timestamp digits>_<16 hex>`, derived from the event body, so two devices that record the same write agree on its id |
+| `op` | `create`, `update`, `append`, or `revert` (`NOTE_WRITE_OP`) |
+| `target` | vault-relative POSIX path of the note |
+| `hash_before` | sha-256 of the bytes replaced, or the literal `absent` when the target did not exist - deliberately not the sha-256 of zero bytes, which an empty FILE would also produce |
+| `hash_after` | sha-256 of the bytes now on disk, or the same literal `absent` when the write left no file - which only a `revert` that removes a note the selected writes created produces, paired with `bytes_after: 0` |
+| `bytes_before` / `bytes_after` | byte sizes, rendered as decimal strings |
+| `agent` | `resolveAgentName()` against the config the writing surface runs under; caller-asserted by construction, as `src/core/write-binding/index.ts` states |
+
+The device is NOT a payload field: it rides on the log shard name exactly as it does for every other event, and `origin_channel` is stamped by the appender. `listNoteWrites` (`src/core/brain/notes/write-log.ts`) reads the record back and reports the shard as the `device`, the empty string being the legacy un-sharded log rather than an unknown machine. `o2b brain writes` and the `brain_writes` MCP tool are the two surfaces over it, and `brain_agent_query --kind note` answers "which notes did this agent touch" off the same events.
+
+**Order, and the gap the receipt names.** The bytes are written FIRST and the event appended second, so a log failure never fails a write that has already landed - the snapshot-event precedent, with the silence removed. `recordNoteWrite` never throws: it returns `write_id: null` with an `audit_reason`, and every note-write result and MCP receipt carries both. A skipped create (`if_exists: "skip"`) authored no bytes, so it records nothing and carries no `write_id` at all.
+
+**Before-image store.** The bytes an update or append replaced are kept at `Brain/.state/write-images/<sha256>`, written before the atomic write and skipped when an image of that content already exists - so a note toggled between two states costs two files, not two per write. The store is a `STATE_SURFACES` row inside the snapshot region; `o2b brain writes prune-images [--older-than-days N] [--dry-run]` bounds it by file age, default 30 days (`WRITE_IMAGE_RETENTION_DAYS`). An image is a copy of note content the snapshot region already archives, so removing one loses no content - it only narrows how far back a revert can reach, which a revert plan reports by name.
+
+**Revert.** `o2b brain writes revert (--agent A | --device D | --path P) [--since --until]` reads the same events back and plans what undoing them would do; `brain_writes` action `plan_revert` returns the same plan and never applies it. A selector naming none of agent, device or path is refused by name (`unbounded_selector`): a time window alone selects every write by every agent on every machine, which is a vault rollback and has its own verb. Per target, over the selected writes S (oldest..newest) and every recorded write A on that target:
+
+| Verdict | When |
+|---|---|
+| `refuse` / `unrecorded` | the current bytes cannot be read at all, so no drift verdict is possible |
+| `refuse` / `drift` | sha-256 of the bytes on disk is not the `hash_after` of the newest write in S - including the target being gone when it should be there |
+| `refuse` / `interleaved` | a write in `A \ S` sits between the oldest and newest write in S **in the merged total order** - `(timestamp, shard id, line)`, the order `readLogDay` already yields. Timestamps are second-precision, so "between" is a position and not a clock comparison: line order inside one shard IS append order, and three writes in one second on one device are perfectly ordered. The one tie that is not evidence is a same-second tie ACROSS shards, where the merge falls back to the shard id - a name, not a clock - and two devices could have written in either order. So a non-selected write sharing a second with a selected write is trusted only when it shares that write's shard; a cross-shard tie is `interleaved` on doubt |
+| `refuse` / `already-reverted` | the target already holds exactly what the revert would produce |
+| `refuse` / `image-missing` | a restore's before-image is not in the store, or no longer hashes to its own name |
+| `delete` | the oldest write in S has `hash_before: absent` AND no write in A precedes it - the selection brought the note into existence |
+| `restore` | otherwise: put back the before-image of the oldest write in S |
+
+A refused target is reported, never skipped, and the plan's digest - `sha256(canonical JSON of { selector, entries })`, deliberately NOT covering `planned_at` - covers refusals too, so an operator who applies a digest applies the plan they read. `--apply <digest>` re-plans from scratch and refuses `digest_mismatch` before any byte moves when the vault changed in between; a plan with no actionable entry is refused `nothing_to_apply`; a frozen vault refuses the whole apply by name before anything is read. Everything that does run goes inside ONE `withDestructiveSnapshot` under the `note-revert` reason, so a revert that half-succeeds still has one recovery point covering the state before all of it. Each restored or deleted target keeps a before-image of the bytes it replaced and is recorded through `recordNoteWrite` with `op: revert` - a delete as `hash_after: absent`, `bytes_after: 0` - which is what makes a revert attributable and itself revertible: reverting the reverting agent puts the bytes back.
+
+### The log chain
+
+Once the log is the attribution record for every write, a line someone deleted or edited has to be detectable. Every JSONL row appended from v1.55.0 on carries two extra keys after `payload`:
+
+- `h` β€” `sha256(canonical JSON of { prev, ts, kind, payload })`, this row's chain hash;
+- `prev` β€” the `h` of the previous chained line **in the same shard**, or `null` at that shard's genesis.
+
+`prev` is inside the hash rather than beside it, which is what makes the structure a chain: editing any earlier line changes every later hash, so a tampered history cannot be re-linked without rewriting the whole shard from the edit forward. The appender computes the link from the shard text it already holds under the directory lock, which is also what makes the link correct β€” two appenders reading the same head would otherwise write two lines claiming the same predecessor.
+
+**One chain per shard.** Two machines append to two files that Syncthing delivers in whatever order it likes, so there is no total order to chain across; the chain's unit is one file and a break in one device's shard says nothing about another's. **The markdown twin is a derived rendering and is NOT chained** β€” a human-editable view is the wrong thing to hold to a hash, and the JSONL sidecar is the machine-primary surface every reader already prefers.
+
+**Report-only.** `readLogDay` reads `ts`, `kind` and `payload` and nothing else, so a broken shard still yields every event it holds. A log that refused to be read because someone edited it would be a worse outcome than the edit. What the chain buys is that the edit has a name, a file and a line number.
+
+`o2b brain log verify [--json]` walks every shard and reports the first break in each, by path and line: `hash-mismatch` (the line was edited after it was written), `prev-mismatch` (a line between it and its predecessor was removed or reordered), `malformed` (the line carries no usable chain link where the chain had already started). It exits 1 when any shard does not link up. `o2b brain doctor` emits one `log-chain-broken` warning per broken shard with the same next command. Neither repairs anything: the only way to make a broken chain verify is to rewrite the history it records, which is the act the chain exists to detect.
+
+Rows written before the chain shipped carry no `h`. They are counted as **legacy** and are clean while they precede the chain β€” the first chained line after them anchors the shard with `prev: null`. The same shape *after* a chained line is not history but a line whose links were stripped, and it is reported. The head of a shard is not exempt either: the Brain log never compacts, so a first chained line naming a predecessor means the head of the file was cut off. Sync-conflict copies are excluded from verification β€” they are the doctor's separate `sync-conflict-log` finding, and their chain never held by construction.
+
## Continuity record kinds
Every continuity record shares one envelope, and exactly these eight fields in this order: `schema`, `id`, `kind`, `createdAt`, `sourceRefs`, `payload`, `private`, `redacted`. The table marks how each kind is gated - this is the always-on vs opt-in matrix, verified against the call sites named in the right column.
diff --git a/docs/stability.md b/docs/stability.md
index 6f4f1c85..9824f2dd 100644
--- a/docs/stability.md
+++ b/docs/stability.md
@@ -53,7 +53,7 @@ major cycle after N+1 ships:
| Schema string | File | Since |
| --- | --- | --- |
-| `o2b.metrics.v1` | `Brain/metrics/<surface>.jsonl` | 0.45.0 |
+| `o2b.metrics.v1` | `Brain/metrics/<surface>[.<device-id>].jsonl` | 0.45.0 |
| `o2b.tuning.v1` | `Brain/search/tuning.json` | 0.45.0 |
| `o2b.dream-stage.v1` | `Brain/dream/staged/<run-id>/manifest.json` | 1.0.0 |
| `o2b.report-snapshot.v1` | `Brain/reports/<surface>/<date>.json` | 1.0.0 |
diff --git a/openclaw.plugin.json b/openclaw.plugin.json
index 300cdbc5..9349416a 100644
--- a/openclaw.plugin.json
+++ b/openclaw.plugin.json
@@ -2,7 +2,7 @@
"id": "open-second-brain",
"name": "Open Second Brain",
"description": "Second brain for AI agents using Obsidian-compatible Markdown vaults.",
- "version": "1.54.0",
+ "version": "1.55.0",
"activation": { "onStartup": true },
"skills": ["./skills"],
"contracts": {
diff --git a/openclaw/index.js b/openclaw/index.js
index 53c7b8b5..d3a1bae6 100644
--- a/openclaw/index.js
+++ b/openclaw/index.js
@@ -3074,7 +3074,9 @@ var DEGRADATION_CODE = Object.freeze({
lineageObservationDropped: "lineage-observation-dropped",
lineageChainBroken: "lineage-chain-broken",
vaultMarkerAbsent: "vault-marker-absent",
- vaultMarkerMismatch: "vault-marker-mismatch"
+ vaultMarkerMismatch: "vault-marker-mismatch",
+ vaultFrozen: "vault-frozen",
+ logChainBroken: "log-chain-broken"
});
class DegradationNoticeError extends Error {
diff --git a/package.json b/package.json
index 1d4626fb..5951d4bf 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "1.54.0",
+ "version": "1.55.0",
"private": false,
"description": "Second brain for AI agents using Obsidian-compatible Markdown vaults. Works with Hermes, Claude Code, Codex, and OpenClaw.",
"keywords": [
diff --git a/plugin.yaml b/plugin.yaml
index 15e65a3d..17b91b9a 100644
--- a/plugin.yaml
+++ b/plugin.yaml
@@ -1,5 +1,5 @@
name: open-second-brain
-version: "1.54.0"
+version: "1.55.0"
description: "Open Second Brain - native Hermes memory provider backed by an Obsidian-compatible Markdown vault."
author: "Open Second Brain contributors"
memory_provider: true
diff --git a/plugins/codex/.codex-plugin/plugin.json b/plugins/codex/.codex-plugin/plugin.json
index c4d3bf57..dbad9936 100644
--- a/plugins/codex/.codex-plugin/plugin.json
+++ b/plugins/codex/.codex-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "1.54.0",
+ "version": "1.55.0",
"description": "Plugin-first second brain package for Codex, Hermes, Claude Code, OpenClaw, and other agent runtimes.",
"author": {
"name": "Open Second Brain contributors",
diff --git a/plugins/hermes/plugin.yaml b/plugins/hermes/plugin.yaml
index 15e65a3d..17b91b9a 100644
--- a/plugins/hermes/plugin.yaml
+++ b/plugins/hermes/plugin.yaml
@@ -1,5 +1,5 @@
name: open-second-brain
-version: "1.54.0"
+version: "1.55.0"
description: "Open Second Brain - native Hermes memory provider backed by an Obsidian-compatible Markdown vault."
author: "Open Second Brain contributors"
memory_provider: true
diff --git a/pyproject.toml b/pyproject.toml
index c36bdf99..180be371 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -10,7 +10,7 @@ build-backend = "setuptools.build_meta"
# CLI entry points (those moved to `package.json` `bin`).
[project]
name = "open-second-brain"
-version = "1.54.0"
+version = "1.55.0"
description = "Hermes Python shim for Open Second Brain. Most of the project (CLI, MCP server, OpenClaw plugin) is TypeScript on Bun; see package.json."
readme = "README.md"
requires-python = ">=3.11"
diff --git a/src/cli/brain.ts b/src/cli/brain.ts
index 11623a62..b86af801 100644
--- a/src/cli/brain.ts
+++ b/src/cli/brain.ts
@@ -27,8 +27,12 @@ import {
cmdBrainQuery,
cmdBrainAgentQuery,
cmdBrainAgentDiff,
+ cmdBrainWrites,
cmdBrainReject,
+ cmdBrainFreeze,
cmdBrainPin,
+ cmdBrainUnfreeze,
+ handleBrainLogSubcommand,
cmdBrainUnpin,
cmdBrainState,
cmdBrainSetPrimary,
@@ -250,8 +254,16 @@ export async function handleBrainSubcommand(argv: ReadonlyArray<string>): Promis
return await cmdBrainAgentQuery(rest);
case "agent-diff":
return await cmdBrainAgentDiff(rest);
+ case "writes":
+ return await cmdBrainWrites(rest);
case "reject":
return await cmdBrainReject(rest);
+ case "freeze":
+ return await cmdBrainFreeze(rest);
+ case "unfreeze":
+ return await cmdBrainUnfreeze(rest);
+ case "log":
+ return await handleBrainLogSubcommand(rest);
case "pin":
return await cmdBrainPin(rest);
case "unpin":
diff --git a/src/cli/brain/help-text.ts b/src/cli/brain/help-text.ts
index b7b9ddd5..00267570 100644
--- a/src/cli/brain/help-text.ts
+++ b/src/cli/brain/help-text.ts
@@ -50,7 +50,11 @@ Brain verbs (observing memory):
query Read by --preference, --topic, or --since
agent-query Read Brain provenance by source agent (--agent; --json)
agent-diff Compare source-agent coverage (browse/search/diff/map)
+ writes Recorded note writes: list (default), revert, prune-images
reject Move a preference to retired (user-rejected); --yes if pinned
+ freeze Stop every content write on every device (--reason <text>)
+ unfreeze Lift the freeze and reopen the content lane
+ log Inspect Brain/log itself: verify (per-shard hash chain)
pin Mark a preference exempt from automatic retire (idempotent)
unpin Clear the pinned flag (idempotent)
state Overwrite-only exact-state lane (set/get/list/clear --aspect)
@@ -327,18 +331,48 @@ export const VERB_HELP: Record<string, string> = {
"--show-expired keeps lapsed memories; both apply to --topic only.\n",
"agent-query":
"usage: o2b brain agent-query [--agent <id>...] [--topic <slug>] [--query <text>]\n" +
- " [--kind signal|preference|log] [--limit <n>]\n" +
+ " [--kind signal|preference|log|note] [--limit <n>]\n" +
" [--vault <path>] [--json]\n" +
"Read-only source-agent retrieval over Brain provenance. Omit --agent to query all known agents.\n",
+ writes:
+ "usage: o2b brain writes [list] [--agent <id>] [--device <id>] [--path <note>]\n" +
+ " [--since <date>] [--until <date>] [--op create|update|append|revert]\n" +
+ " [--vault <path>] [--json]\n" +
+ " o2b brain writes revert (--agent <id> | --device <id> | --path <note>)\n" +
+ " [--since <date>] [--until <date>] [--apply <digest>]\n" +
+ " [--vault <path>] [--json]\n" +
+ " o2b brain writes prune-images [--older-than-days <n>] [--dry-run]\n" +
+ " [--vault <path>] [--json]\n" +
+ "Read-only listing of every recorded note write, newest first: timestamp, operation,\n" +
+ "agent, device, target, and the content digest on each side of the write. The device\n" +
+ "comes off the log shard, so a legacy un-sharded log prints '-' rather than a guess.\n" +
+ "revert plans what undoing the selected writes would do: each target resolves to\n" +
+ "restore, delete or a named refusal (drift, interleaved, image-missing, unrecorded,\n" +
+ "already-reverted), and the plan is sealed by a digest printed with the exact --apply\n" +
+ "line that runs it. A selector naming no agent, device or path is refused - a time\n" +
+ "window alone is a vault rollback, which is o2b brain rollback. --apply re-plans,\n" +
+ "refuses a digest that no longer describes the vault before any byte moves, takes a\n" +
+ "note-revert snapshot, and records each restored or deleted target as a note write of\n" +
+ "operation revert, so a revert is itself attributable and revertible.\n" +
+ "prune-images bounds the before-image store by file age; the default window is 30 days.\n",
"agent-diff":
"usage: o2b brain agent-diff [--mode browse|search|diff|map] [--agent <id>...]\n" +
" [--topic <slug>] [--query <text>]\n" +
- " [--kind signal|preference|log] [--limit <n>]\n" +
+ " [--kind signal|preference|log|note] [--limit <n>]\n" +
" [--vault <path>] [--json]\n" +
"Compare source-agent coverage using the same provenance foundation as agent-query.\n",
reject:
"usage: o2b brain reject --id <pref-id> --reason <text> [--yes] [--vault <path>] [--json]\n" +
"Move a preference to retired/ with reason 'user-rejected'. --yes required when pinned.\n",
+ freeze:
+ "usage: o2b brain freeze [--reason <text>] [--vault <path>] [--json]\n" +
+ "Write Brain/.state/frozen.json. While it exists every content write in this vault is refused - on this device and, once Syncthing has carried the marker, on every device that shares it. The Brain log keeps recording, so the freeze and the writes it refuses stay auditable. Idempotent: a second freeze keeps the first one's reason.\n",
+ log:
+ "usage: o2b brain log verify [--vault <path>] [--json]\n" +
+ "Walk every JSONL shard of the Brain log and report where each one stops linking up. Each appended row carries prev and h, a sha256 over the previous line's hash plus the row's own ts, kind and payload, so an edited or deleted line is detectable. Output names the shard path, the line number, and whether the line was edited (hash-mismatch), removed or reordered (prev-mismatch), or stripped of its chain fields (malformed). Rows written before the chain shipped carry no h; they are counted as legacy and are clean while they precede the chain. Reports only: nothing here rewrites a log to make it verify, and the read path never consults the chain. Exits 1 when any shard does not link up.\n",
+ unfreeze:
+ "usage: o2b brain unfreeze [--vault <path>] [--json]\n" +
+ "Remove the freeze marker and reopen the content lane. The unfreeze log event records who lifted it and what the marker said, which is the only place that survives the file. Idempotent.\n",
pin:
"usage: o2b brain pin --id <pref-id> [--vault <path>] [--json]\n" +
"Set pinned: true. Idempotent. Exempts the preference from automatic retire.\n",
diff --git a/src/cli/brain/helpers.ts b/src/cli/brain/helpers.ts
index 98ef554d..cf35a7f5 100644
--- a/src/cli/brain/helpers.ts
+++ b/src/cli/brain/helpers.ts
@@ -95,7 +95,7 @@ export function parse(
// ── Re-exports (the barrel that verb handlers import from) ──────────────────
export { CliError } from "../argparse.ts";
-export { describeErrorChain, fail, failWith, info, ok, okJson } from "../output.ts";
+export { describeErrorChain, fail, failWith, info, ok, okJson, writeJson } from "../output.ts";
/**
* Usage / argument error: plain message to stderr, exit code 2. Distinct
diff --git a/src/cli/brain/verbs/agent-diff.ts b/src/cli/brain/verbs/agent-diff.ts
index 9dc16109..517c3d4f 100644
--- a/src/cli/brain/verbs/agent-diff.ts
+++ b/src/cli/brain/verbs/agent-diff.ts
@@ -3,7 +3,11 @@ import {
type AgentSourceDiffMode,
type AgentSourceDiffResult,
} from "../../../core/brain/agent-source/diff.ts";
-import type { AgentSourceContributionKind } from "../../../core/brain/agent-source/types.ts";
+import {
+ AGENT_SOURCE_CONTRIBUTION_KINDS,
+ isAgentSourceContributionKind,
+ type AgentSourceContributionKind,
+} from "../../../core/brain/agent-source/types.ts";
import { brainVerbContext, fail, parse } from "../helpers.ts";
export async function cmdBrainAgentDiff(argv: string[]): Promise<number> {
@@ -76,8 +80,8 @@ function parseKind(raw: string | undefined): {
readonly error?: string;
} {
if (raw === undefined) return {};
- if (raw === "signal" || raw === "preference" || raw === "log") return { value: raw };
- return { error: "--kind must be one of signal|preference|log" };
+ if (isAgentSourceContributionKind(raw)) return { value: raw };
+ return { error: `--kind must be one of ${AGENT_SOURCE_CONTRIBUTION_KINDS.join("|")}` };
}
function parseLimit(raw: string | undefined): {
diff --git a/src/cli/brain/verbs/agent-query.ts b/src/cli/brain/verbs/agent-query.ts
index 4ef1ef72..42438d42 100644
--- a/src/cli/brain/verbs/agent-query.ts
+++ b/src/cli/brain/verbs/agent-query.ts
@@ -2,7 +2,11 @@ import {
queryAgentSources,
type AgentSourceQueryResult,
} from "../../../core/brain/agent-source/query.ts";
-import type { AgentSourceContributionKind } from "../../../core/brain/agent-source/types.ts";
+import {
+ AGENT_SOURCE_CONTRIBUTION_KINDS,
+ isAgentSourceContributionKind,
+ type AgentSourceContributionKind,
+} from "../../../core/brain/agent-source/types.ts";
import { brainVerbContext, fail, parse } from "../helpers.ts";
export async function cmdBrainAgentQuery(argv: string[]): Promise<number> {
@@ -59,8 +63,8 @@ function parseKind(raw: string | undefined): {
readonly error?: string;
} {
if (raw === undefined) return {};
- if (raw === "signal" || raw === "preference" || raw === "log") return { value: raw };
- return { error: "--kind must be one of signal|preference|log" };
+ if (isAgentSourceContributionKind(raw)) return { value: raw };
+ return { error: `--kind must be one of ${AGENT_SOURCE_CONTRIBUTION_KINDS.join("|")}` };
}
function parseLimit(raw: string | undefined): {
diff --git a/src/cli/brain/verbs/freeze.ts b/src/cli/brain/verbs/freeze.ts
new file mode 100644
index 00000000..941ad69f
--- /dev/null
+++ b/src/cli/brain/verbs/freeze.ts
@@ -0,0 +1,104 @@
+import { freezeVault, unfreezeVault } from "../../../core/brain/freeze.ts";
+import { resolveAgentName } from "../../../core/config.ts";
+import { brainVerbContext, fail, normalizeFlagString, ok, okJson, parse } from "../helpers.ts";
+import { emitNextStep, type AdvisoryStream } from "../../advisory-rail.ts";
+
+/**
+ * `o2b brain freeze` / `o2b brain unfreeze` (who-wrote-what, Task C) -
+ * the operator's stop for every content writer on every device that
+ * syncs this vault.
+ *
+ * CLI-only by design. Agents receive the refusal by name and can read the
+ * frozen state off `brain_status`, but lifting a freeze is an act of
+ * judgement about a fleet an agent cannot see, so no MCP tool sets or
+ * clears the marker.
+ *
+ * Both verbs are idempotent and say which of the two things happened: a
+ * second `freeze` reports the freeze already standing (and whose it is,
+ * because the first operator's reason is the one that holds), and an
+ * `unfreeze` on an open vault reports that it was already open. Neither
+ * is an error - the operator asked for a state and got it - so both exit
+ * zero.
+ */
+export async function cmdBrainFreeze(argv: string[]): Promise<number> {
+ const { flags } = parse(argv, {
+ vault: { type: "string" },
+ reason: { type: "string" },
+ json: { type: "boolean" },
+ });
+ const { config, vault } = brainVerbContext(flags);
+ const reason = normalizeFlagString(flags["reason"]);
+ const agent = resolveAgentName(config);
+
+ try {
+ const out = freezeVault(vault, {
+ agent,
+ ...(reason !== null ? { reason } : {}),
+ });
+ if (flags["json"]) {
+ okJson({
+ changed: out.changed,
+ frozen: true,
+ frozen_at: out.marker.frozen_at,
+ by: out.marker.by,
+ device_id: out.marker.device_id,
+ reason: out.marker.reason,
+ marker: out.path,
+ });
+ } else if (out.changed) {
+ ok(`frozen: ${describe(out.marker.frozen_at, out.marker.by, out.marker.reason)}`);
+ ok("every content write is refused until the freeze is lifted");
+ // The lift is a forward pointer, and forward pointers ride the rail:
+ // the `vault-frozen` signal already names the command, so the verb
+ // does not spell it a second time.
+ const stream: AdvisoryStream = { command: "brain", argv, jsonRequested: false };
+ emitNextStep("vault-frozen", stream);
+ } else {
+ ok(`already frozen: ${describe(out.marker.frozen_at, out.marker.by, out.marker.reason)}`);
+ }
+ return 0;
+ } catch (exc) {
+ return fail(`freeze failed: ${(exc as Error).message ?? exc}`);
+ }
+}
+
+export async function cmdBrainUnfreeze(argv: string[]): Promise<number> {
+ const { flags } = parse(argv, {
+ vault: { type: "string" },
+ json: { type: "boolean" },
+ });
+ const { config, vault } = brainVerbContext(flags);
+ const agent = resolveAgentName(config);
+
+ try {
+ const out = unfreezeVault(vault, { agent });
+ if (flags["json"]) {
+ okJson({
+ changed: out.changed,
+ frozen: false,
+ frozen_at: out.marker?.frozen_at ?? null,
+ by: out.marker?.by ?? null,
+ reason: out.marker?.reason ?? null,
+ });
+ } else if (out.changed) {
+ // The marker is gone, so this line is the last place its contents
+ // are shown to a human; the `unfreeze` log event is where they last.
+ ok(
+ `unfrozen: ${describe(out.marker?.frozen_at ?? "", out.marker?.by ?? "", out.marker?.reason ?? "")}`,
+ );
+ } else {
+ ok("not frozen: nothing to lift");
+ }
+ return 0;
+ } catch (exc) {
+ return fail(`unfreeze failed: ${(exc as Error).message ?? exc}`);
+ }
+}
+
+/** One line naming when the freeze was set, by whom, and why. */
+function describe(frozenAt: string, by: string, reason: string): string {
+ const who = by === "" ? "an unnamed agent" : by;
+ const when = frozenAt === "" ? "an unrecorded time" : frozenAt;
+ const why = reason === "" ? "no reason given" : reason;
+ return `set at ${when} by ${who} (${why})`;
+}
diff --git a/src/cli/brain/verbs/index.ts b/src/cli/brain/verbs/index.ts
index 971bc079..c2b47976 100644
--- a/src/cli/brain/verbs/index.ts
+++ b/src/cli/brain/verbs/index.ts
@@ -16,7 +16,10 @@ export { cmdBrainMonthly } from "./monthly.ts";
export { cmdBrainQuery } from "./query.ts";
export { cmdBrainAgentQuery } from "./agent-query.ts";
export { cmdBrainAgentDiff } from "./agent-diff.ts";
+export { cmdBrainWrites } from "./writes.ts";
export { cmdBrainReject } from "./reject.ts";
+export { cmdBrainFreeze, cmdBrainUnfreeze } from "./freeze.ts";
+export { cmdBrainLogVerify, handleBrainLogSubcommand } from "./log.ts";
export { cmdBrainPin, cmdBrainUnpin } from "./pin.ts";
export { cmdBrainState } from "./state.ts";
export { cmdBrainSetPrimary } from "./set-primary.ts";
diff --git a/src/cli/brain/verbs/log.ts b/src/cli/brain/verbs/log.ts
new file mode 100644
index 00000000..b7e0a637
--- /dev/null
+++ b/src/cli/brain/verbs/log.ts
@@ -0,0 +1,135 @@
+import { breakDetail, verifyLogChain } from "../../../core/brain/log-chain.ts";
+import { brainDirs } from "../../../core/brain/paths.ts";
+import { brainVerbContext, fail, info, parse, writeJson } from "../helpers.ts";
+
+/**
+ * `o2b brain log <verb>` (who-wrote-what, Task E) - the operator surface
+ * over `Brain/log/` itself, as opposed to over what it records.
+ *
+ * `verify` is the only verb today and the reason the namespace exists:
+ * the per-shard hash chain is report-only, so nothing surfaces a shard
+ * that stopped linking up until someone asks. The doctor asks on every
+ * run; this is the surface for an operator who suspects something and
+ * wants the whole picture, shard by shard.
+ *
+ * The name is RESERVED rather than collapsed into a single `log-verify`
+ * verb: the log is a subsystem with more than one question worth asking
+ * of it, and an unknown subcommand is refused by name here rather than
+ * being read as a flag or silently ignored.
+ */
+const LOG_VERBS = Object.freeze({ verify: "verify" } as const);
+
+/** Printed for `o2b brain log` with no verb, and for `--help`. */
+const LOG_USAGE =
+ "usage: o2b brain log <verb> [args...]\n" +
+ "Verbs:\n" +
+ " verify [--json] Walk every JSONL shard of the Brain log and report\n" +
+ " where each one stops linking up: shard path, line\n" +
+ " number, and whether the line was edited, removed or\n" +
+ " stripped of its chain fields. Reports only - nothing\n" +
+ " here rewrites a log to make it verify.\n";
+
+export async function handleBrainLogSubcommand(argv: ReadonlyArray<string>): Promise<number> {
+ if (argv.length === 0 || argv[0] === "-h" || argv[0] === "--help") {
+ process.stdout.write(LOG_USAGE);
+ return argv.length === 0 ? 2 : 0;
+ }
+ const sub = argv[0]!;
+ const rest = argv.slice(1);
+ switch (sub) {
+ case LOG_VERBS.verify:
+ return await cmdBrainLogVerify([...rest]);
+ default:
+ process.stderr.write(
+ `unknown brain log verb: ${sub}; supported: ${Object.values(LOG_VERBS).join(", ")}\n`,
+ );
+ return 2;
+ }
+}
+
+/**
+ * Walk every chained shard and print the verdict.
+ *
+ * Exit 1 when the log does not verify. A check whose failure looks like
+ * its success is not a check, and this one is meant to be runnable from
+ * a cron entry that only reports when something is wrong. Exit 0 with an
+ * explicit line for a vault with no chained shard at all: "there is
+ * nothing to verify" is an answer, and printing nothing would make it
+ * indistinguishable from "everything verified".
+ */
+export async function cmdBrainLogVerify(argv: string[]): Promise<number> {
+ const { flags } = parse(argv, {
+ vault: { type: "string" },
+ json: { type: "boolean" },
+ });
+ const { vault } = brainVerbContext(flags);
+
+ let result;
+ try {
+ result = verifyLogChain(vault);
+ } catch (exc) {
+ return fail(`log verify failed: ${(exc as Error).message ?? exc}`);
+ }
+
+ if (flags["json"]) {
+ writeJson({
+ ok: result.ok,
+ shards: result.shards.map((shard) => ({
+ path: shard.path,
+ date: shard.date,
+ shard_id: shard.shardId,
+ chained: shard.chained,
+ legacy: shard.legacy,
+ unparsed: shard.unparsed,
+ first_break:
+ shard.firstBreak === null
+ ? null
+ : { line: shard.firstBreak.line, reason: shard.firstBreak.reason },
+ })),
+ notices: result.notices.map((notice) => ({
+ code: notice.code,
+ site: notice.site,
+ ...(notice.path !== undefined ? { path: notice.path } : {}),
+ detail: notice.detail,
+ })),
+ });
+ return result.ok ? 0 : 1;
+ }
+
+ if (result.shards.length === 0) {
+ info(`no chained log shard under ${brainDirs(vault).log}: nothing to verify`);
+ // Still a finding when the directory itself could not be listed.
+ for (const notice of result.notices) info(` ${notice.detail}`);
+ return result.ok ? 0 : 1;
+ }
+
+ const chained = result.shards.reduce((sum, shard) => sum + shard.chained, 0);
+ const legacy = result.shards.reduce((sum, shard) => sum + shard.legacy, 0);
+ const broken = result.shards.filter((shard) => shard.firstBreak !== null);
+ info(
+ `${plural(result.shards.length, "shard")}, ${chained} chained ` +
+ `${plural(chained, "line", false)}, ${legacy} legacy`,
+ );
+
+ for (const shard of broken) {
+ const found = shard.firstBreak!;
+ info(`${shard.path}: line ${found.line} (${found.reason}) - it ${breakDetail(found.reason)}`);
+ }
+ if (broken.length === 0) {
+ info("every shard links up");
+ return 0;
+ }
+ info(
+ `${plural(broken.length, "shard")} of ${result.shards.length} did not link up. ` +
+ "Nothing here rewrites a log to make it verify: the line named above was edited, " +
+ "removed, or stripped of its chain fields after it was written, and that is what " +
+ "the chain exists to say. Every event in those shards still reads.",
+ );
+ return 1;
+}
+
+/** `1 shard` / `2 shards`, with the count kept in front for scanning. */
+function plural(count: number, noun: string, withCount = true): string {
+ const word = count === 1 ? noun : `${noun}s`;
+ return withCount ? `${count} ${word}` : word;
+}
diff --git a/src/cli/brain/verbs/writes.ts b/src/cli/brain/verbs/writes.ts
new file mode 100644
index 00000000..cf6da2f2
--- /dev/null
+++ b/src/cli/brain/verbs/writes.ts
@@ -0,0 +1,332 @@
+import {
+ NOTE_REVERT_ACTION,
+ NoteRevertError,
+ applyNoteRevert,
+ planNoteRevert,
+ type NoteRevertEntry,
+ type NoteRevertSelector,
+} from "../../../core/brain/notes/revert.ts";
+import { listNoteWrites, type NoteWriteRecord } from "../../../core/brain/notes/write-log.ts";
+import {
+ NOTE_WRITE_OP,
+ WRITE_IMAGE_RETENTION_DAYS,
+ isNoteWriteOp,
+ pruneWriteImages,
+ type NoteWriteOp,
+} from "../../../core/brain/notes/write-record.ts";
+import {
+ brainVerbContext,
+ fail,
+ normalizeFlagString,
+ ok,
+ okJson,
+ parse,
+ usageError,
+} from "../helpers.ts";
+
+/**
+ * `o2b brain writes` - the operator's view of who wrote what
+ * (who-wrote-what, Task A / t_662f4e82).
+ *
+ * Subcommands:
+ * list (default) recorded note writes, newest first
+ * revert plan, and with --apply run, a per-agent undo
+ * prune-images bound the before-image store by age
+ *
+ * `list` is the default because the question that brings an operator
+ * here is "what has been written to my vault", and making them type the
+ * subcommand to ask it would be a road sign pointing at itself.
+ */
+export async function cmdBrainWrites(argv: string[]): Promise<number> {
+ const sub = argv[0];
+ const rest = sub === undefined || sub.startsWith("--") ? argv : argv.slice(1);
+ const { flags } = parse(rest, {
+ vault: { type: "string" },
+ agent: { type: "string" },
+ device: { type: "string" },
+ path: { type: "string" },
+ since: { type: "string" },
+ until: { type: "string" },
+ op: { type: "string" },
+ "older-than-days": { type: "string" },
+ "dry-run": { type: "boolean" },
+ apply: { type: "string" },
+ json: { type: "boolean" },
+ });
+ const json = flags["json"] === true;
+
+ if (sub === undefined || sub.startsWith("--") || sub === "list") {
+ return listWrites(flags, json);
+ }
+ if (sub === "revert") {
+ return revert(flags, json);
+ }
+ if (sub === "prune-images") {
+ return pruneImages(flags, json);
+ }
+ return usageError(
+ `unknown brain writes subcommand '${sub}' - expected list, revert or prune-images`,
+ );
+}
+
+/** Hex characters of each digest shown in the plain table. */
+const DIGEST_PREVIEW_LENGTH = 8;
+
+/** What the table prints where a fact is absent rather than empty. */
+const ABSENT_COLUMN = "-";
+
+function listWrites(
+ flags: Record<string, string | boolean | string[] | undefined>,
+ json: boolean,
+): number {
+ const rawOp = normalizeFlagString(flags["op"]);
+ if (rawOp !== null && !isNoteWriteOp(rawOp)) {
+ return usageError(
+ `--op must be one of ${Object.values(NOTE_WRITE_OP).join("|")}, got '${rawOp}'`,
+ );
+ }
+ const op: NoteWriteOp | null = rawOp;
+ const { vault } = brainVerbContext(flags);
+ const agent = normalizeFlagString(flags["agent"]);
+ const device = normalizeFlagString(flags["device"]);
+ const path = normalizeFlagString(flags["path"]);
+ const since = normalizeFlagString(flags["since"]);
+ const until = normalizeFlagString(flags["until"]);
+
+ const result = listNoteWrites(vault, {
+ ...(agent !== null ? { agent } : {}),
+ ...(device !== null ? { device } : {}),
+ ...(path !== null ? { path } : {}),
+ ...(since !== null ? { since } : {}),
+ ...(until !== null ? { until } : {}),
+ ...(op !== null ? { op } : {}),
+ });
+
+ if (json) {
+ okJson({
+ writes: result.writes.map((w) => ({ ...w })),
+ count: result.writes.length,
+ warnings: result.warnings.map((w) => ({
+ path: w.path,
+ line: w.lineNumber,
+ message: w.message,
+ })),
+ });
+ return 0;
+ }
+
+ if (result.writes.length === 0) {
+ ok("no recorded note writes");
+ } else {
+ for (const write of result.writes) ok(renderRow(write));
+ }
+ // Warnings after the rows and never instead of them: a day whose log
+ // lost a line still has the writes it kept, and hiding them would make
+ // an incomplete list read as a complete one.
+ for (const warning of result.warnings) {
+ ok(`warning: ${warning.path}:${warning.lineNumber}: ${warning.message}`);
+ }
+ return 0;
+}
+
+/** One row: when, what, who, where, and the two ends of the content. */
+function renderRow(write: NoteWriteRecord): string {
+ const device = write.device === "" ? ABSENT_COLUMN : write.device;
+ const before = write.hash_before.slice(0, DIGEST_PREVIEW_LENGTH);
+ const after = write.hash_after.slice(0, DIGEST_PREVIEW_LENGTH);
+ return [
+ write.timestamp,
+ write.op,
+ write.agent === "" ? ABSENT_COLUMN : write.agent,
+ device,
+ write.target,
+ `${before} -> ${after}`,
+ ].join(" ");
+}
+
+function pruneImages(
+ flags: Record<string, string | boolean | string[] | undefined>,
+ json: boolean,
+): number {
+ const raw = normalizeFlagString(flags["older-than-days"]);
+ let olderThanDays = WRITE_IMAGE_RETENTION_DAYS;
+ if (raw !== null) {
+ const parsed = Number.parseInt(raw, 10);
+ if (!Number.isInteger(parsed) || String(parsed) !== raw || parsed < 0) {
+ return usageError(`--older-than-days must be a non-negative integer, got '${raw}'`);
+ }
+ olderThanDays = parsed;
+ }
+ const dryRun = flags["dry-run"] === true;
+ const { vault } = brainVerbContext(flags);
+ const result = pruneWriteImages(vault, { olderThanDays, dryRun });
+
+ if (json) {
+ okJson({
+ removed: [...result.removed],
+ removed_count: result.removed.length,
+ kept: result.kept,
+ skipped: [...result.skipped],
+ skipped_count: result.skipped.length,
+ dry_run: result.dry_run,
+ older_than_days: olderThanDays,
+ });
+ return 0;
+ }
+ // The verb says what it DID, not what it was asked to do: a dry run
+ // that printed "removed 3" would be the one sentence an operator would
+ // act on and the one that was not true.
+ const verb = result.dry_run ? "would remove" : "removed";
+ ok(`${verb} ${result.removed.length} before-image(s) older than ${olderThanDays} day(s)`);
+ ok(`kept ${result.kept}`);
+ for (const sha of result.removed) ok(`- ${sha}`);
+ // A name this store did not write is left where it is, and the only
+ // pass anybody makes over the store is the one that has to say so -
+ // otherwise a conflict copy sits there unbounded and unmentioned.
+ if (result.skipped.length > 0) {
+ ok(`skipped ${result.skipped.length} name(s) that are not before-images`);
+ for (const name of result.skipped) ok(`? ${name}`);
+ }
+ return 0;
+}
+
+/**
+ * `revert` - plan what undoing a selection of writes would do, and with
+ * `--apply <digest>` do it.
+ *
+ * Two invocations rather than a confirmation prompt, because the digest
+ * is what makes the second one refer to the first: an operator applies
+ * the plan they read, and a vault that moved in between is refused
+ * rather than re-planned silently. The plan itself is a REPORT and exits
+ * 0 even when every target is refused - a revert that finds nothing safe
+ * to undo answered the question it was asked. Only a selector this verb
+ * will not accept, and an apply that cannot run, exit non-zero.
+ */
+function revert(
+ flags: Record<string, string | boolean | string[] | undefined>,
+ json: boolean,
+): number {
+ const selector: NoteRevertSelector = {
+ ...selectorField(flags, "agent"),
+ ...selectorField(flags, "device"),
+ ...selectorField(flags, "path"),
+ ...selectorField(flags, "since"),
+ ...selectorField(flags, "until"),
+ };
+ const digest = normalizeFlagString(flags["apply"]);
+ const { vault } = brainVerbContext(flags);
+
+ try {
+ return digest === null
+ ? printPlan(vault, selector, json)
+ : printApply(vault, selector, digest, json);
+ } catch (err) {
+ // The code first, then the sentence: an operator scripting around
+ // this reads one token, and the rest of the line is for the human.
+ if (err instanceof NoteRevertError) return fail(`${err.code}: ${err.message}`);
+ throw err;
+ }
+}
+
+/** One selector field, present only when the flag carried a value. */
+function selectorField(
+ flags: Record<string, string | boolean | string[] | undefined>,
+ key: "agent" | "device" | "path" | "since" | "until",
+): Partial<Record<typeof key, string>> {
+ const value = normalizeFlagString(flags[key]);
+ return value === null ? {} : { [key]: value };
+}
+
+/** The plan's own `--apply` line, so the digest never has to be retyped. */
+function applyInvocation(selector: NoteRevertSelector, digest: string): string {
+ const parts = ["o2b", "brain", "writes", "revert"];
+ for (const [key, value] of Object.entries(selector)) parts.push(`--${key}`, String(value));
+ parts.push("--apply", digest);
+ return parts.join(" ");
+}
+
+/** One planned target: what, where, why not, how many writes, both digests. */
+function renderEntry(entry: NoteRevertEntry): string {
+ const now = entry.hash_now.slice(0, DIGEST_PREVIEW_LENGTH);
+ const to = entry.hash_to.slice(0, DIGEST_PREVIEW_LENGTH);
+ return [
+ entry.action,
+ entry.target,
+ entry.reason ?? ABSENT_COLUMN,
+ String(entry.writes.length),
+ `${now} -> ${to}`,
+ ].join(" ");
+}
+
+function printPlan(vault: string, selector: NoteRevertSelector, json: boolean): number {
+ const plan = planNoteRevert(vault, selector);
+ if (json) {
+ okJson({
+ selector: { ...plan.selector },
+ entries: plan.entries.map((e) => ({ ...e })),
+ digest: plan.digest,
+ planned_at: plan.planned_at,
+ warnings: plan.warnings.map((w) => ({
+ path: w.path,
+ line: w.lineNumber,
+ message: w.message,
+ })),
+ });
+ return 0;
+ }
+
+ if (plan.entries.length === 0) ok("no recorded note writes match this selector");
+ for (const entry of plan.entries) ok(renderEntry(entry));
+ // Warnings before the digest, because a day whose log lost a line is a
+ // day whose write history is incomplete, and the digest below seals
+ // exactly the plan that incomplete history produced.
+ for (const warning of plan.warnings) {
+ ok(`warning: ${warning.path}:${warning.lineNumber}: ${warning.message}`);
+ }
+ ok(`digest: ${plan.digest}`);
+ ok(applyInvocation(plan.selector, plan.digest));
+ return 0;
+}
+
+function printApply(
+ vault: string,
+ selector: NoteRevertSelector,
+ digest: string,
+ json: boolean,
+): number {
+ const result = applyNoteRevert(vault, selector, digest);
+ if (json) {
+ okJson({
+ snapshot: { ...result.snapshot },
+ applied: result.applied.map((e) => ({ ...e })),
+ refused: result.refused.map((e) => ({ ...e })),
+ failed: result.failed.map((f) => ({ ...f })),
+ recorded: result.recorded.map((r) => ({ ...r })),
+ recoverability: {
+ state: result.recoverability.state,
+ coverage: [...result.recoverability.coverage],
+ blockers: [...result.recoverability.blockers],
+ },
+ });
+ return 0;
+ }
+
+ ok(`snapshot: ${result.snapshot.run_id}`);
+ for (const entry of result.applied) ok(`${entry.action} ${entry.target}`);
+ for (const entry of result.refused) {
+ ok(`${NOTE_REVERT_ACTION.refuse} ${entry.target} ${entry.reason ?? ABSENT_COLUMN}`);
+ }
+ // A target the apply could not carry out is neither applied nor
+ // refused, and a plan whose entry appears nowhere reads as a plan that
+ // never contained it.
+ for (const failure of result.failed) {
+ ok(`failed ${failure.target} ${failure.reason}`);
+ }
+ // An unrecorded revert is a fact the operator is told, not one they
+ // have to infer from a missing line in a later listing.
+ for (const row of result.recorded) {
+ if (row.write_id === null) ok(`warning: ${row.target}: ${row.audit_reason}`);
+ }
+ ok(`recoverability: ${result.recoverability.state}`);
+ return 0;
+}
diff --git a/src/cli/command-manifest.ts b/src/cli/command-manifest.ts
index 2aef3c04..5653807b 100644
--- a/src/cli/command-manifest.ts
+++ b/src/cli/command-manifest.ts
@@ -173,8 +173,71 @@ export const CLI_COMMAND_MANIFEST: CliRootManifest = Object.freeze({
]),
command("agent-query", "Read source-agent provenance"),
command("agent-diff", "Compare source-agent coverage"),
+ command(
+ "writes",
+ "Recorded note writes: list (default), revert, prune-images",
+ [
+ flag("vault", "string"),
+ flag("agent", "string"),
+ flag("device", "string"),
+ flag("path", "string"),
+ flag("since", "string"),
+ flag("until", "string"),
+ flag("op", "string"),
+ flag("apply", "string"),
+ flag("json", "boolean"),
+ ],
+ [
+ command("list", "Recorded note writes, newest first", [
+ flag("vault", "string"),
+ flag("agent", "string"),
+ flag("device", "string"),
+ flag("path", "string"),
+ flag("since", "string"),
+ flag("until", "string"),
+ flag("op", "string"),
+ flag("json", "boolean"),
+ ]),
+ command("revert", "Plan, and with --apply run, a per-agent undo of note writes", [
+ flag("vault", "string"),
+ flag("agent", "string"),
+ flag("device", "string"),
+ flag("path", "string"),
+ flag("since", "string"),
+ flag("until", "string"),
+ flag("apply", "string"),
+ flag("json", "boolean"),
+ ]),
+ command("prune-images", "Remove before-images past a retention window", [
+ flag("vault", "string"),
+ flag("older-than-days", "string"),
+ flag("dry-run", "boolean"),
+ flag("json", "boolean"),
+ ]),
+ ],
+ ),
command("reject", "Retire a preference"),
command("merge", "Merge duplicate preferences"),
+ command("freeze", "Stop every content write on every device", [
+ flag("vault", "string"),
+ flag("reason", "string"),
+ flag("json", "boolean"),
+ ]),
+ command("unfreeze", "Lift the freeze and reopen the content lane", [
+ flag("vault", "string"),
+ flag("json", "boolean"),
+ ]),
+ command(
+ "log",
+ "Inspect Brain/log itself: verify (per-shard hash chain)",
+ [],
+ [
+ command("verify", "Report where each log shard stops linking up", [
+ flag("vault", "string"),
+ flag("json", "boolean"),
+ ]),
+ ],
+ ),
command("pin", "Pin a preference"),
command("unpin", "Unpin a preference"),
command("set-primary", "Set primary Brain agent"),
diff --git a/src/core/brain/agent-source/types.ts b/src/core/brain/agent-source/types.ts
index 632f059e..1028ea2c 100644
--- a/src/core/brain/agent-source/types.ts
+++ b/src/core/brain/agent-source/types.ts
@@ -1,4 +1,28 @@
-export type AgentSourceContributionKind = "signal" | "preference" | "log";
+/**
+ * What a contribution IS, as the roster and the diff group them.
+ *
+ * `note` joined the three originals with the note-write record
+ * (who-wrote-what, Task A / t_662f4e82). It is deliberately its own kind
+ * rather than a `log` contribution that happens to carry a path: "which
+ * notes did this agent touch" is the question the epic exists to answer,
+ * and folding it into `log` would make that question a substring search
+ * over event payloads.
+ */
+export type AgentSourceContributionKind = "signal" | "preference" | "log" | "note";
+
+/** The kinds, in the order the surfaces list them. */
+export const AGENT_SOURCE_CONTRIBUTION_KINDS: ReadonlyArray<AgentSourceContributionKind> =
+ Object.freeze(["signal", "preference", "log", "note"]);
+
+/** True when `value` is a member of {@link AGENT_SOURCE_CONTRIBUTION_KINDS}. */
+export function isAgentSourceContributionKind(
+ value: unknown,
+): value is AgentSourceContributionKind {
+ return (
+ typeof value === "string" &&
+ (AGENT_SOURCE_CONTRIBUTION_KINDS as ReadonlyArray<string>).includes(value)
+ );
+}
export interface AgentSourceContribution {
readonly provider_id: string;
diff --git a/src/core/brain/agent-source/vault-provider.ts b/src/core/brain/agent-source/vault-provider.ts
index 46b301a3..ad652d5d 100644
--- a/src/core/brain/agent-source/vault-provider.ts
+++ b/src/core/brain/agent-source/vault-provider.ts
@@ -7,7 +7,12 @@ import { brainDirs } from "../paths.ts";
import { preferenceOwner } from "../owner-scoped-facts.ts";
import { parsePreference, parseRetired } from "../preference.ts";
import { parseSignal } from "../signal.ts";
-import type { BrainPreference, BrainRetired, BrainSignal } from "../types.ts";
+import {
+ BRAIN_LOG_EVENT_KIND,
+ type BrainPreference,
+ type BrainRetired,
+ type BrainSignal,
+} from "../types.ts";
import { normaliseWikilinkTarget } from "../wikilink.ts";
import { deepFreeze } from "./freeze.ts";
import type { AgentSourceContribution, AgentSourceProvider } from "./types.ts";
@@ -172,6 +177,8 @@ function preferenceContribution(
function logContribution(entry: BrainLogEntry): AgentSourceContribution | null {
const agents = entry.agent ? [entry.agent] : [];
if (agents.length === 0) return null;
+ const note = noteWriteContribution(entry, agents);
+ if (note !== null) return note;
return deepFreeze({
provider_id: PROVIDER_ID,
kind: "log",
@@ -188,6 +195,46 @@ function logContribution(entry: BrainLogEntry): AgentSourceContribution | null {
});
}
+/**
+ * A `note-write` event as a contribution of kind `note`
+ * (who-wrote-what, Task A / t_662f4e82).
+ *
+ * The whole point of the kind is that the ANSWER is the page: `path`
+ * carries the note the write touched, so `brain_agent_query --kind note`
+ * lists the notes an agent produced with no new reader and no second
+ * index. `title` is the operation and the target together, because a
+ * roster row that read only "note-write" would name the event kind and
+ * not the work.
+ *
+ * A line missing its target is left to fall through to the generic log
+ * contribution rather than being projected as a note with no page: a
+ * pathless `note` row is one an operator could select and never open.
+ */
+function noteWriteContribution(
+ entry: BrainLogEntry,
+ agents: ReadonlyArray<string>,
+): AgentSourceContribution | null {
+ if (entry.eventType !== BRAIN_LOG_EVENT_KIND.noteWrite) return null;
+ const target = entry.body["target"];
+ const op = entry.body["op"];
+ if (typeof target !== "string" || typeof op !== "string") return null;
+ const writeId = entry.body["write_id"];
+ return deepFreeze({
+ provider_id: PROVIDER_ID,
+ kind: "note",
+ id: typeof writeId === "string" ? writeId : `${entry.timestamp}:${entry.eventType}`,
+ agents: Object.freeze([...agents]),
+ timestamp: entry.timestamp,
+ title: `${op} ${target}`,
+ text: logText(entry),
+ path: target,
+ data: {
+ event_type: entry.eventType,
+ body: cloneLogBody(entry.body),
+ },
+ });
+}
+
function logTopic(entry: BrainLogEntry): string | undefined {
const topic = entry.body["topic"];
return typeof topic === "string" && topic.trim().length > 0 ? topic : undefined;
diff --git a/src/core/brain/continuity/store.ts b/src/core/brain/continuity/store.ts
index 09cccf58..674b6778 100644
--- a/src/core/brain/continuity/store.ts
+++ b/src/core/brain/continuity/store.ts
@@ -1,8 +1,16 @@
import { createHash } from "node:crypto";
-import { existsSync, mkdirSync, readFileSync, readdirSync, statSync, writeFileSync } from "node:fs";
+import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import { originChannelStamp } from "../../origin-channel.ts";
+import {
+ listShardedFiles,
+ mergeShardedRows,
+ resolveAppendShardId,
+ shardedFileName,
+ type LedgerShardGrammar,
+ type ShardedRow,
+} from "../ledger-shards.ts";
import { BRAIN_LOG_REL, ensureInsideVault } from "../paths.ts";
import { acquireLockSync } from "../sync-lockfile.ts";
import { assertVaultIdentityForWrite } from "../vault-identity.ts";
@@ -41,6 +49,20 @@ export interface ContinuityPaginationOptions extends ContinuityRecordFilter {
const CONTINUITY_REL = `${BRAIN_LOG_REL}/continuity`;
const CURSOR_PREFIX = "offset:";
+/** Shard base: one file per UTC month. */
+const MONTH_RE = /^\d{4}-\d{2}$/;
+const CONTINUITY_EXT = "jsonl";
+
+/**
+ * The ledger's file-name layout, handed to the shared shard grammar.
+ * The base is the month, so a sharded name still yields the month the
+ * `since`/`until` range-skip below tests without re-parsing the name.
+ */
+const CONTINUITY_GRAMMAR: LedgerShardGrammar = Object.freeze({
+ base: "\\d{4}-\\d{2}",
+ extensions: Object.freeze([CONTINUITY_EXT]),
+});
+
/**
* Canonical UTC ISO-8601 shape: `YYYY-MM-DDTHH:MM:SS[.sss]Z`. A trailing
* `Z` is mandatory β€” a numeric offset (`+03:00`) is rejected so every
@@ -93,9 +115,34 @@ export function assertCanonicalCreatedAt(createdAt: unknown): string {
return createdAt;
}
-export function continuityLogPath(vault: string, month: string): string {
- if (!/^\d{4}-\d{2}$/.test(month)) throw new Error(`invalid continuity month: ${month}`);
- return ensureInsideVault(join(vault, CONTINUITY_REL, `${month}.jsonl`), vault);
+/**
+ * The directory every continuity shard lives in. Exported so the sweep
+ * that reports Syncthing conflict copies names this ledger's directory
+ * through the module that owns it, rather than re-deriving the path.
+ */
+export function continuityLogDir(vault: string): string {
+ return ensureInsideVault(join(vault, CONTINUITY_REL), vault);
+}
+
+/**
+ * One month's shard for one device: `<month>[.<shardId>].jsonl`.
+ *
+ * `shardId` defaults to this device's id, so an append lands in a file no
+ * other device writes and Syncthing never has two versions of one month
+ * to reconcile. The empty shard id is the legacy un-sharded name, which
+ * every reader still merges and no migration renames - a vault whose
+ * device id resolves empty keeps writing exactly the file it always did.
+ */
+export function continuityLogPath(
+ vault: string,
+ month: string,
+ shardId: string = resolveAppendShardId(),
+): string {
+ if (!MONTH_RE.test(month)) throw new Error(`invalid continuity month: ${month}`);
+ return ensureInsideVault(
+ join(vault, CONTINUITY_REL, shardedFileName(month, shardId, CONTINUITY_EXT)),
+ vault,
+ );
}
export function appendContinuityRecord(
@@ -308,54 +355,63 @@ function appendRecord(vault: string, record: ContinuityRecord): ContinuityRecord
}
/**
- * Read every stored record, optionally skipping whole month shards that
- * a `since`/`until` filter proves cannot contribute a matching record.
+ * Read every stored record across every device shard, optionally skipping
+ * whole months that a `since`/`until` filter proves cannot contribute a
+ * matching record.
+ *
+ * Shards are named `<month>[.<deviceId>].jsonl`, and the shared grammar
+ * hands back the month as the parsed base - so the range-skip below tests
+ * the month whether or not a device suffix is present. A month whose
+ * shards sort strictly before `since`'s month can only hold records with
+ * `createdAt < since` (rejected by {@link matches}); one strictly after
+ * `until`'s month can only hold `createdAt > until`. Both are skipped
+ * without opening the file. The boundary months are still read in full,
+ * so the returned set is identical to reading everything and letting
+ * `matches` filter - this only avoids reading files that would contribute
+ * nothing. Grows the read cost with the queried window, not the whole
+ * history.
*
- * Shards are named `YYYY-MM.jsonl`, so the shard month is a 7-char prefix
- * of every record's `createdAt` inside it. A shard whose month sorts
- * strictly before `since`'s month can only hold records with
- * `createdAt < since` (rejected by {@link matches}); one whose month sorts
- * strictly after `until`'s month can only hold `createdAt > until`. Both
- * are skipped without opening the file. The boundary months (equal to
- * `since`/`until`'s month) are still read in full, so the returned set is
- * byte-identical to reading everything and letting `matches` filter -
- * this only avoids reading shards that would contribute nothing. Grows
- * the read cost with the queried window, not the whole log history.
+ * Order is (`createdAt`, shard id, `id`). The shard id is the tie-break
+ * every device agrees on regardless of Syncthing arrival order; `id` is
+ * the last resort, and because it is a content hash a single-shard vault
+ * reads back in exactly the order it always did.
*/
function readAllRecords(vault: string, filter: ContinuityRecordFilter = {}): ContinuityRecord[] {
- const dir = ensureInsideVault(join(vault, CONTINUITY_REL), vault);
- if (!existsSync(dir)) return [];
+ const dir = continuityLogDir(vault);
const sinceMonth = filter.since ? filter.since.slice(0, 7) : undefined;
const untilMonth = filter.until ? filter.until.slice(0, 7) : undefined;
- const records: ContinuityRecord[] = [];
- for (const name of readdirSync(dir).toSorted()) {
- if (!name.endsWith(".jsonl")) continue;
- const month = name.slice(0, -".jsonl".length);
- // Only a canonical YYYY-MM shard has a month prefix we can range-skip
- // on; any other name is read in full to stay byte-identical.
- if (/^\d{4}-\d{2}$/.test(month)) {
- if (sinceMonth !== undefined && month < sinceMonth) continue;
- if (untilMonth !== undefined && month > untilMonth) continue;
- }
- const path = ensureInsideVault(join(dir, name), vault);
- let st;
+ const rows: Array<ShardedRow<ContinuityRecord>> = [];
+ for (const shard of listShardedFiles(dir, CONTINUITY_GRAMMAR)) {
+ if (sinceMonth !== undefined && shard.base < sinceMonth) continue;
+ if (untilMonth !== undefined && shard.base > untilMonth) continue;
+ let text: string;
try {
- st = statSync(path);
- } catch {
+ text = readFileSync(ensureInsideVault(shard.path, vault), "utf8");
+ } catch (err) {
+ // A shard listed a moment ago and gone now (a concurrent prune, a
+ // sync delete) contributes nothing and is skipped. Anything else -
+ // EACCES, EIO - propagates: a shard silently dropped shortens the
+ // history without saying so, and a caller cannot tell a short
+ // history from a complete one.
+ if ((err as NodeJS.ErrnoException).code !== "ENOENT") throw err;
continue;
}
- if (!st.isFile()) continue;
- for (const line of readFileSync(path, "utf8").split("\n")) {
- if (!line.trim()) continue;
+ let line = 0;
+ for (const raw of text.split("\n")) {
+ if (!raw.trim()) continue;
try {
- records.push(JSON.parse(line) as ContinuityRecord);
+ rows.push({ value: JSON.parse(raw) as ContinuityRecord, shardId: shard.shardId, line });
} catch {
continue;
}
+ line++;
}
}
- records.sort((a, b) => a.createdAt.localeCompare(b.createdAt) || a.id.localeCompare(b.id));
- return records;
+ return mergeShardedRows(
+ rows,
+ (record) => record.createdAt,
+ (record) => record.id,
+ );
}
function matches(record: ContinuityRecord, filter: ContinuityRecordFilter): boolean {
diff --git a/src/core/brain/destructive-sites.ts b/src/core/brain/destructive-sites.ts
index 0ff23127..697cac12 100644
--- a/src/core/brain/destructive-sites.ts
+++ b/src/core/brain/destructive-sites.ts
@@ -335,6 +335,16 @@ export const DESTRUCTIVE_SITES: Readonly<Record<string, DestructiveSiteDeclarati
},
// --- Rewrites through a temp file ------------------------------------
+ "src/core/brain/freeze.ts": {
+ calls: ["unlinkSync"],
+ recovery: UNARCHIVED_BRAIN,
+ reason:
+ "removes the freeze marker, whose whole content was its existence: the file carries " +
+ "no memory, `o2b brain freeze` writes an identical one in a single command, and the " +
+ "`unfreeze` log event records who lifted the freeze plus what the marker said before " +
+ "it went. Archiving it would preserve a fact the log already holds.",
+ },
+
"src/core/brain/maintenance/journal.ts": {
calls: ["renameSync"],
recovery: UNARCHIVED_BRAIN,
@@ -394,6 +404,18 @@ export const DESTRUCTIVE_SITES: Readonly<Record<string, DestructiveSiteDeclarati
"PARTIAL rather than covered because `--include-originals` removes the imported file " +
"outside `Brain/`, which no archive has ever held.",
},
+ "src/core/brain/notes/write-record.ts": {
+ calls: ["unlinkSync"],
+ recovery: UNARCHIVED_BRAIN,
+ reason:
+ "prunes before-images past a retention window measured from each file's own mtime, " +
+ "and an image whose age cannot be measured at all is kept rather than removed. Every " +
+ "image is a COPY of note content that still exists somewhere the snapshot region " +
+ "archives - either on disk as the note's current body or inside an earlier archive - " +
+ "so removing one loses no content; it only narrows how far back a revert can reach, " +
+ "and a revert that cannot reach its before-image refuses that target by name rather " +
+ "than discovering the absence silently.",
+ },
"src/core/brain/notes/lifecycle.ts": {
calls: ["renameSync", "unlinkSync"],
recovery: UNARCHIVED_OUTSIDE,
diff --git a/src/core/brain/diagnostics.ts b/src/core/brain/diagnostics.ts
index 6e34a174..1fddaee2 100644
--- a/src/core/brain/diagnostics.ts
+++ b/src/core/brain/diagnostics.ts
@@ -471,6 +471,40 @@ export const DIAGNOSTIC_SIGNALS: ReadonlyMap<string, DiagnosticSignal> = new Map
// doctor check would make the census follow the import back and
// read every registry entry below as a doctor code. Same reason
// `recall-channel-silent` is a literal here.
+ // The vault carries a freeze marker. Spelled as a literal for
+ // the same reason `recovery-point-stale` below is: importing a
+ // `*_CODE` identifier from this module into a doctor check would
+ // make the exit census follow the import back and read every
+ // registry entry here as a doctor code.
+ //
+ // `autoRepairable: false` is load-bearing rather than a default.
+ // A freeze is an instruction, not a defect, and a repair pass
+ // that lifted one would be overruling the operator who set it
+ // from a machine they may not be sitting at.
+ code: "vault-frozen",
+ issueClass: "vault frozen: every content write is refused",
+ nextCommand: "o2b brain unfreeze",
+ autoRepairable: false,
+ },
+ {
+ // A shard of the Brain log stopped linking up. Spelled as a
+ // literal for the same reason `vault-frozen` above is: importing
+ // a `*_CODE` identifier from this module into a doctor check
+ // would make the exit census follow the import back and read
+ // every registry entry here as a doctor code.
+ //
+ // The exit is the verifier rather than a repair, and
+ // `autoRepairable: false` is the whole point rather than a
+ // default: the only way to make a broken chain verify is to
+ // rewrite the history it records, which is precisely the act the
+ // chain exists to detect. What an operator can do is SEE the
+ // damage across every shard, which is what the verb prints.
+ code: "log-chain-broken",
+ issueClass: "Brain log shard whose hash chain does not hold",
+ nextCommand: "o2b brain log verify",
+ autoRepairable: false,
+ },
+ {
code: "recovery-point-stale",
issueClass: "newest recovery point older than the liveness window",
nextCommand: "o2b brain snapshot log",
diff --git a/src/core/brain/doctor.ts b/src/core/brain/doctor.ts
index 7569afb7..55085f58 100644
--- a/src/core/brain/doctor.ts
+++ b/src/core/brain/doctor.ts
@@ -75,6 +75,8 @@ import { recoveryPointLivenessCheck } from "./doctor/recovery-point-liveness.ts"
import { removedToolReferenceCheck } from "./doctor/removed-tool-checks.ts";
import { makeStaleDependencyCheck } from "./doctor/stale-dependency-check.ts";
import { auditStaleDependencies } from "./stale-dependency.ts";
+import { frozenVaultCheck } from "./doctor/frozen-check.ts";
+import { logChainCheck } from "./doctor/log-chain-check.ts";
import { checkSemanticHealth } from "./doctor/semantic-health-check.ts";
import {
danglingWorkrunCheck,
@@ -159,6 +161,8 @@ const DOCTOR_CHECKS: ReadonlyArray<DoctorCheck> = Object.freeze([
entityRegistryCheck,
capturePatternCheck,
syncConflictLogCheck,
+ frozenVaultCheck,
+ logChainCheck,
symlinkEscapeCheck,
frontmatterUncertaintyProbe,
lineageLedgerProbe,
diff --git a/src/core/brain/doctor/frozen-check.ts b/src/core/brain/doctor/frozen-check.ts
new file mode 100644
index 00000000..48f75126
--- /dev/null
+++ b/src/core/brain/doctor/frozen-check.ts
@@ -0,0 +1,52 @@
+/**
+ * Is this vault frozen? (who-wrote-what, Task C)
+ *
+ * The freeze refuses every content write on every device that syncs the
+ * vault, which makes it the condition that explains the widest range of
+ * other symptoms: a dream pass that recorded nothing, a note write that
+ * came back as an error, an agent that keeps reporting it cannot save.
+ * An operator chasing any of those runs the doctor, so the doctor has to
+ * say it first.
+ *
+ * ## A warning, not an error, and never in `uncertain`
+ *
+ * The three streams mean different things and this finding belongs to
+ * exactly one of them. It is not an ERROR: nothing is broken, and an
+ * operator asked for this state deliberately. It is not UNCERTAIN: the
+ * marker was read and the answer is known. It is a WARNING - a standing
+ * condition worth stating every time until it is lifted - and it carries
+ * `o2b brain unfreeze` as its exit, so the finding is never a dead end
+ * for whoever is reading it, including the operator who set it and has
+ * since forgotten.
+ *
+ * A marker nobody can parse reports here exactly as a well-formed one
+ * does, because it freezes the vault exactly as a well-formed one does.
+ * The reason field says which it was.
+ */
+
+import { readFreezeMarker, FREEZE_NEXT_COMMAND, frozenMarkerPath } from "../freeze-marker.ts";
+import type { DoctorIssue } from "../types.ts";
+import type { DoctorCheck, DoctorCheckContext, DoctorFindings } from "./check.ts";
+
+/** The vault carries a freeze marker, so every content write is refused. */
+export const VAULT_FROZEN_CODE = "vault-frozen";
+
+export const frozenVaultCheck: DoctorCheck = {
+ failSoft: true,
+ run(ctx: DoctorCheckContext, out: DoctorFindings): void {
+ const marker = readFreezeMarker(ctx.vault);
+ if (marker === null) return;
+ const who = marker.by === "" ? "an unnamed agent" : marker.by;
+ const when = marker.frozen_at === "" ? "an unrecorded time" : marker.frozen_at;
+ const why = marker.reason === "" ? "no reason given" : marker.reason;
+ out.issues.push({
+ severity: "warning",
+ code: VAULT_FROZEN_CODE,
+ path: frozenMarkerPath(ctx.vault),
+ message:
+ `this vault is frozen: set at ${when} by ${who} (${why}). Every content write is ` +
+ "refused here and on every device that syncs this vault; the Brain log keeps " +
+ `recording, so the refusals are auditable. Run \`${FREEZE_NEXT_COMMAND}\` to lift it`,
+ } satisfies DoctorIssue);
+ },
+};
diff --git a/src/core/brain/doctor/log-chain-check.ts b/src/core/brain/doctor/log-chain-check.ts
new file mode 100644
index 00000000..e23ac28b
--- /dev/null
+++ b/src/core/brain/doctor/log-chain-check.ts
@@ -0,0 +1,59 @@
+/**
+ * Does the Brain log still link up? (who-wrote-what, Task E)
+ *
+ * The per-shard hash chain is report-only: nothing in the read path
+ * consults it, so a shard that stopped linking up is invisible until
+ * something looks. `o2b brain log verify` is the surface for an operator
+ * who suspects something; this check is the surface for the operator who
+ * does not, and it is the one they already run.
+ *
+ * ## A warning, and one finding per shard
+ *
+ * Not an ERROR: nothing is broken. Every event the shard holds still
+ * reads, every pass still runs, and the store is exactly as usable as it
+ * was - what changed is that its history can no longer be vouched for. A
+ * warning is the severity for a standing condition worth stating rather
+ * than for a store that cannot be used.
+ *
+ * Not UNCERTAIN either: the shard was read and the answer is known. The
+ * lineage ledger's equivalent reaches `uncertain` because its finding is
+ * often "the ledger could not be read at all"; here the common case is a
+ * definite break at a definite line, so it belongs in the stream an
+ * operator reads as findings.
+ *
+ * One finding per SHARD, because the chain's unit is one file: a break
+ * in one device's day says nothing about another's, and an operator who
+ * has to open two files should be told about two files. The message
+ * names the path and the line so the finding is never a dead end.
+ */
+
+import { breakDetail, verifyLogChain } from "../log-chain.ts";
+import type { DoctorIssue } from "../types.ts";
+import type { DoctorCheck, DoctorCheckContext, DoctorFindings } from "./check.ts";
+
+/** A shard of the Brain log does not link up: a line was edited or removed. */
+export const LOG_CHAIN_BROKEN_CODE = "log-chain-broken";
+
+/** Named once: the finding and its registered next command spell the same verb. */
+const LOG_VERIFY_COMMAND = "o2b brain log verify";
+
+export const logChainCheck: DoctorCheck = {
+ failSoft: true,
+ run(ctx: DoctorCheckContext, out: DoctorFindings): void {
+ const result = verifyLogChain(ctx.vault);
+ for (const shard of result.shards) {
+ const found = shard.firstBreak;
+ if (found === null) continue;
+ out.issues.push({
+ severity: "warning",
+ code: LOG_CHAIN_BROKEN_CODE,
+ path: shard.path,
+ message:
+ `the Brain log shard ${shard.path} stops linking up at line ${found.line}: it ` +
+ `${breakDetail(found.reason)}. ${shard.chained} of its lines still carry a chain ` +
+ "hash and every event in it still reads - the chain is an audit surface, never a " +
+ `read gate. Run \`${LOG_VERIFY_COMMAND}\` for the whole picture across every shard`,
+ } satisfies DoctorIssue);
+ }
+ },
+};
diff --git a/src/core/brain/doctor/store-integrity.ts b/src/core/brain/doctor/store-integrity.ts
index 5daa5d8a..eca04cf3 100644
--- a/src/core/brain/doctor/store-integrity.ts
+++ b/src/core/brain/doctor/store-integrity.ts
@@ -11,10 +11,14 @@
import { join } from "node:path";
import { realpathInsideVault, vaultRelative } from "../../path-safety.ts";
+import { continuityLogDir } from "../continuity/store.ts";
import { scanDanglingWorkruns } from "../dream-workrun.ts";
import { readTierDriftCount } from "../frontmatter-tiers.ts";
-import { listLogSyncConflicts } from "../log-jsonl.ts";
-import { brainDirs } from "../paths.ts";
+import { idempotencyLogDir } from "../idempotency-ledger.ts";
+import { listSyncConflictFiles } from "../ledger-shards.ts";
+import { brainStateDirPath } from "../lineage/ledger.ts";
+import { metricsDir } from "../metrics.ts";
+import { brainDirs, prefAuditDir } from "../paths.ts";
import type { DoctorCheck } from "./check.ts";
import type { DoctorUncertainEntry } from "./report.ts";
import {
@@ -73,23 +77,88 @@ export const danglingWorkrunCheck: DoctorCheck = {
};
/**
- * Memory Integrity Suite: leftover Syncthing conflict copies under
- * Brain/log/. The per-device shard layout prevents new ones; old
- * copies need a manual union+dedup merge into the day's log.
+ * Every append-only ledger directory in the vault, each named by the
+ * module that owns it rather than by a path spelled a second time here.
+ *
+ * All six shard per device (who-wrote-what, Task B), which is what makes
+ * one finding cover all of them: the shard layout prevents NEW conflicts
+ * everywhere, so a `*.sync-conflict-*` copy under any of these means the
+ * same thing - a file that exists and that no reader merges.
+ */
+const LEDGER_DIRS: ReadonlyArray<(vault: string, uncertain: DoctorUncertainEntry[]) => string[]> =
+ Object.freeze([
+ (vault: string) => [brainDirs(vault).log],
+ (vault: string) => [continuityLogDir(vault)],
+ (vault: string) => [idempotencyLogDir(vault)],
+ prefAuditSweepDirs,
+ (vault: string) => [metricsDir(vault)],
+ (vault: string) => [brainStateDirPath(vault)],
+ ]);
+
+/**
+ * The preference audit keeps one DIRECTORY per preference
+ * (`pref-audit/<pref-id>/`), so its shards - and therefore any conflict
+ * copy of one - live a level below the others. Sweeping only the parent
+ * would report a clean ledger while a copy nobody merges sat inside it.
+ *
+ * A parent that cannot be listed is reported by name through the shared
+ * swept-path reporter rather than read as "no preferences": the whole
+ * point of this check is to keep "nothing found" and "nothing looked at"
+ * apart.
+ */
+function prefAuditSweepDirs(vault: string, uncertain: DoctorUncertainEntry[]): string[] {
+ const parent = prefAuditDir(vault);
+ const entries = readSweptDir(
+ parent,
+ {
+ site: SYNC_CONFLICT_SITE,
+ consequence:
+ "its per-preference subdirectories were not listed for Syncthing conflict copies, so a " +
+ "leftover copy waiting to be merged is missing from this report",
+ uncertain,
+ },
+ SWEEP_ORIGIN.root,
+ );
+ if (entries === null) return [parent];
+ return [parent, ...entries.filter((e) => e.isDirectory()).map((e) => join(parent, e.name))];
+}
+
+/**
+ * Memory Integrity Suite: leftover Syncthing conflict copies under any
+ * append-only ledger directory. The per-device shard layout prevents new
+ * ones; old copies need a manual union+dedup merge into the shard they
+ * were split from.
+ *
+ * One exit, one meaning - "a sync conflict copy exists that no reader
+ * merges" - so the code stays `sync-conflict-log` and the DETAIL names
+ * the directory the copy was found in.
*/
export const syncConflictLogCheck: DoctorCheck = {
failSoft: true,
run({ vault }, { issues, uncertain }) {
- const conflicts = listSyncConflicts(vault, uncertain);
- for (const path of conflicts) {
- issues.push({
- severity: "warning",
- code: "sync-conflict-log",
- path,
- message:
- `Syncthing sync-conflict copy under Brain/log/: ${path}. ` +
- "Merge its rows into the day's log (union + dedup by ts and content), then delete it.",
- });
+ for (const resolve of LEDGER_DIRS) {
+ let ledgerDirs: string[];
+ try {
+ ledgerDirs = resolve(vault, uncertain);
+ } catch {
+ // A directory whose own resolver refuses (a vault path that
+ // escapes its root) is not a directory this sweep can visit;
+ // the resolver's caller is where that refusal belongs.
+ continue;
+ }
+ for (const ledgerDir of ledgerDirs) {
+ for (const path of listSyncConflicts(ledgerDir, uncertain)) {
+ issues.push({
+ severity: "warning",
+ code: "sync-conflict-log",
+ path,
+ message:
+ `Syncthing sync-conflict copy under ${vaultRelative(ledgerDir, vault)}/: ${path}. ` +
+ "Merge its rows into the shard it was split from (union + dedup by timestamp and " +
+ "content), then delete it.",
+ });
+ }
+ }
}
},
};
@@ -98,19 +167,21 @@ export const syncConflictLogCheck: DoctorCheck = {
const SYNC_CONFLICT_SITE = "brain.doctor.syncConflictLog";
/**
- * The conflict copies under `Brain/log/`, or none plus a named reason.
+ * The conflict copies under one ledger directory, or none plus a named
+ * reason.
*
* The listing is behind a shared helper, so the failure arrives here as
* a throw. Swallowed by the pass's fail-soft arm it produced no finding
* at all, which reads as "no conflict copies" - the answer this check
- * exists to distinguish from "the directory was not read".
+ * exists to distinguish from "the directory was not read". Reported per
+ * directory, so one unreadable ledger does not silence the other five.
*/
-function listSyncConflicts(vault: string, uncertain: DoctorUncertainEntry[]): string[] {
+function listSyncConflicts(dir: string, uncertain: DoctorUncertainEntry[]): string[] {
try {
- return listLogSyncConflicts(vault);
+ return listSyncConflictFiles(dir);
} catch (err) {
reportSweptFailure(
- brainDirs(vault).log,
+ dir,
"sync-conflict listing failed",
err,
{
diff --git a/src/core/brain/event-trace.ts b/src/core/brain/event-trace.ts
index fbbbf190..49c7db19 100644
--- a/src/core/brain/event-trace.ts
+++ b/src/core/brain/event-trace.ts
@@ -1,9 +1,10 @@
/**
* Event β†’ context-trace join reader.
*
- * The Brain log (`Brain/log/<date>.md` + JSONL sidecar) records WHAT
- * happened; the continuity store (`Brain/log/continuity/<month>.jsonl`)
- * records WHICH CONTEXT was supplied to those operations. The two
+ * The Brain log (`Brain/log/<date>[.<device-id>].md` + JSONL sidecar)
+ * records WHAT happened; the continuity store
+ * (`Brain/log/continuity/<month>[.<device-id>].jsonl`) records WHICH
+ * CONTEXT was supplied to those operations. The two
* surfaces are written independently and, until now, were read
* independently β€” an operator asking "why did the agent do this?" had
* to query the log, copy a correlation id, and then query each
diff --git a/src/core/brain/freeze-marker.ts b/src/core/brain/freeze-marker.ts
new file mode 100644
index 00000000..c2db74ef
--- /dev/null
+++ b/src/core/brain/freeze-marker.ts
@@ -0,0 +1,309 @@
+/**
+ * The fleet freeze, read side: one marker file, honoured by every writer
+ * on every device (who-wrote-what, Task C).
+ *
+ * An operator running several agents on several machines has no single
+ * stop. Killing one process stops one process; a Syncthing peer that was
+ * mid-pass keeps writing, and the vault the operator is trying to hold
+ * still moves under them. The stop this module supplies is a FILE -
+ * `Brain/.state/frozen.json` - because a file is the only thing every
+ * device already agrees about: it rides the same sync channel the vault
+ * does, so freezing on the laptop freezes the desktop as soon as the two
+ * have talked, with nothing to install and no daemon to reach.
+ *
+ * ## Why this module imports almost nothing
+ *
+ * The freeze check runs inside `assertVaultIdentityForWrite`, which is
+ * imported by `paths.ts`, which is imported by `log.ts`. So this module
+ * must not reach any of the three: an edge back would close a cycle whose
+ * cost is paid at module-initialisation time by every consumer in the
+ * tree (`tests/core/architecture/import-cycles.test.ts` is the ratchet).
+ * It therefore builds its own path from the leaf constants, exactly as
+ * `vault-identity.ts` builds the identity marker's path, and the
+ * `paths.ts` re-export is a convenience for callers rather than the
+ * definition.
+ *
+ * ## An unreadable marker is a freeze
+ *
+ * The asymmetry with {@link readVaultIdentity} is deliberate and is the
+ * one judgement in this module. An absent identity marker collapses to
+ * "unknown" because a fresh vault and a wrong root look identical. A
+ * marker that is PRESENT and does not parse carries no such ambiguity of
+ * intent: somebody put a file called `frozen.json` in the state directory,
+ * and the only reading under which a parse error should reopen the vault
+ * is one where a truncated sync is allowed to cancel an operator's stop.
+ * So a marker that cannot be read freezes, and the refusal names
+ * {@link FREEZE_MARKER_UNREADABLE_REASON} rather than inventing a reason
+ * it did not read.
+ *
+ * ## The two lanes
+ *
+ * The freeze cannot cover literally every write, because the events that
+ * record the freeze - `freeze`, `unfreeze`, `write-refused` - are
+ * themselves writes into `Brain/log/`. A freeze that silenced its own
+ * audit trail would make the one state an operator most needs to
+ * reconstruct the least recorded. {@link WRITE_LANE} names that split
+ * once: `content` is everything the freeze holds, `audit` is the log
+ * appender and this feature's own marker writer. A source-scan test pins
+ * that `audit` is requested from those modules and nowhere else, so the
+ * exemption cannot spread by being convenient.
+ */
+
+import { existsSync, readFileSync, statSync } from "node:fs";
+import { join, resolve } from "node:path";
+
+import { ensureInsideVault } from "../path-safety.ts";
+import {
+ DEGRADATION_CODE,
+ degradationNotice,
+ formatDegradationNotice,
+ type DegradationNotice,
+} from "../integrity/degradation.ts";
+import { BRAIN_INTERNAL_STATE_REL } from "./path-constants.ts";
+
+/** Marker schema version. Bumped only on an incompatible field change. */
+export const FREEZE_MARKER_SCHEMA_VERSION = 1;
+
+/** Marker filename inside `Brain/.state/`. */
+export const FROZEN_MARKER_FILE = "frozen.json";
+
+/** Site name carried by every notice this module emits. */
+const SITE = "brain.freeze";
+
+/**
+ * The one command that ends a freeze, spelled once.
+ *
+ * Every refusal carries it - the thrown error, the MCP refusal payload,
+ * the doctor finding - because a stop with no named way out is a dead end
+ * for whoever hits it, including the operator who set it.
+ */
+export const FREEZE_NEXT_COMMAND = "o2b brain unfreeze";
+
+/**
+ * The reason reported when the marker is present and could not be read.
+ * See the module docblock for why that is a freeze and not an absence.
+ */
+export const FREEZE_MARKER_UNREADABLE_REASON = "marker-unreadable";
+
+/**
+ * Which half of the write surface a caller belongs to.
+ *
+ * `content` is everything the freeze exists to hold: notes, preferences,
+ * signals, state, snapshots - every byte an agent or a pass produces.
+ * `audit` is the record of what happened, which has to keep working while
+ * the vault is frozen or the freeze erases its own evidence.
+ */
+export const WRITE_LANE = Object.freeze({
+ content: "content",
+ audit: "audit",
+} as const);
+
+export type WriteLane = (typeof WRITE_LANE)[keyof typeof WRITE_LANE];
+
+/**
+ * The durable freeze record. Like the identity marker it carries nothing
+ * machine-local except `device_id`, which names the device that SET the
+ * freeze rather than a path - so the file is byte-identical on every peer
+ * and means the same thing on each of them.
+ */
+export interface FreezeMarker {
+ readonly schema: number;
+ /** When the freeze was set, ISO-8601 UTC. */
+ readonly frozen_at: string;
+ /** Agent identity that set it, as `resolveAgentName` reports it. */
+ readonly by: string;
+ /** Device that set it, or the empty string when unresolvable. */
+ readonly device_id: string;
+ /** Operator-supplied reason, or the empty string when none was given. */
+ readonly reason: string;
+}
+
+/** Path of the freeze marker: `<vault>/Brain/.state/frozen.json`. */
+export function frozenMarkerPath(vault: string): string {
+ return ensureInsideVault(join(vault, BRAIN_INTERNAL_STATE_REL, FROZEN_MARKER_FILE), vault);
+}
+
+/**
+ * A write was attempted against a frozen vault.
+ *
+ * Carries the marker's fields beside the structured notice so a caller -
+ * the MCP boundary, a CLI verb, an internal writer - reports the evidence
+ * rather than re-parsing the message. The shape mirrors
+ * `VaultIdentityMismatchError`, which is the other refusal this guard can
+ * raise, so both are handled the same way at a call site.
+ */
+export class VaultFrozenError extends Error {
+ readonly notice: DegradationNotice;
+ readonly frozen_at: string;
+ readonly by: string;
+ readonly reason: string;
+ readonly next_command: string;
+
+ constructor(notice: DegradationNotice, marker: FreezeMarker) {
+ super(formatDegradationNotice(notice));
+ this.name = "VaultFrozenError";
+ this.notice = notice;
+ this.frozen_at = marker.frozen_at;
+ this.by = marker.by;
+ this.reason = marker.reason;
+ this.next_command = FREEZE_NEXT_COMMAND;
+ }
+}
+
+/** The marker every present-but-unparseable file collapses to. */
+const UNREADABLE_MARKER: FreezeMarker = Object.freeze({
+ schema: FREEZE_MARKER_SCHEMA_VERSION,
+ frozen_at: "",
+ by: "",
+ device_id: "",
+ reason: FREEZE_MARKER_UNREADABLE_REASON,
+});
+
+/**
+ * Inode identity of the marker the last read parsed, per resolved root.
+ *
+ * The check sits in front of every content write - the same
+ * append-heavy loops `vault-identity.ts` measures - so the steady-state
+ * cost has to be one syscall rather than an open-read-parse. The marker
+ * is written through `atomicWriteFileSync` (temp file plus rename), so a
+ * replaced marker always arrives with a new inode; matching on
+ * (inode, size, mtime) therefore proves the bytes are the ones already
+ * parsed.
+ */
+interface MarkerStamp {
+ readonly ino: number;
+ readonly size: number;
+ readonly mtimeMs: number;
+ readonly marker: FreezeMarker;
+}
+const MARKER_STAMPS = new Map<string, MarkerStamp>();
+
+/** Resolved marker path per root; the containment walk is paid once. */
+const MARKER_PATHS = new Map<string, string>();
+
+/**
+ * How many times the marker's BYTES have been read and parsed, process
+ * wide.
+ *
+ * Exported for the cache test, which is the only place the hot-path claim
+ * in the docblock above is actually measured. A counter rather than a
+ * spy: the alternative is monkey-patching `node:fs` in a test, which
+ * pins the implementation instead of the property.
+ */
+let reloadCount = 0;
+
+export function freezeMarkerReloadCount(): number {
+ return reloadCount;
+}
+
+/**
+ * Drop every cached marker. Exported for tests, which run many vaults in
+ * one process; production code has no reason to call it.
+ */
+export function resetFreezeMarkerCache(): void {
+ MARKER_STAMPS.clear();
+ MARKER_PATHS.clear();
+}
+
+/** Parse the marker's bytes, or report the unreadable collapse. */
+function parseMarker(path: string): FreezeMarker {
+ reloadCount += 1;
+ let parsed: Partial<FreezeMarker>;
+ try {
+ parsed = JSON.parse(readFileSync(path, "utf8")) as Partial<FreezeMarker>;
+ } catch {
+ return UNREADABLE_MARKER;
+ }
+ if (parsed === null || typeof parsed !== "object") return UNREADABLE_MARKER;
+ // `frozen_at` is the one field a freeze cannot be reconstructed without:
+ // a refusal that cannot say WHEN the vault was stopped is not a record,
+ // it is a wall. Its absence therefore reads as unreadable rather than as
+ // a freeze with an empty timestamp.
+ if (typeof parsed.frozen_at !== "string" || parsed.frozen_at === "") return UNREADABLE_MARKER;
+ return Object.freeze({
+ schema: typeof parsed.schema === "number" ? parsed.schema : FREEZE_MARKER_SCHEMA_VERSION,
+ frozen_at: parsed.frozen_at,
+ by: typeof parsed.by === "string" ? parsed.by : "",
+ device_id: typeof parsed.device_id === "string" ? parsed.device_id : "",
+ reason: typeof parsed.reason === "string" ? parsed.reason : "",
+ });
+}
+
+/**
+ * The freeze marker for `vault`, or `null` when the vault is not frozen.
+ *
+ * A present-but-unparseable marker returns {@link UNREADABLE_MARKER} -
+ * that is, a freeze - never `null`.
+ */
+export function readFreezeMarker(vault: string): FreezeMarker | null {
+ const root = resolve(vault);
+ let path = MARKER_PATHS.get(root);
+ if (path === undefined) {
+ path = frozenMarkerPath(root);
+ MARKER_PATHS.set(root, path);
+ }
+ // `throwIfNoEntry: false` for the same reason `currentVaultId` uses it:
+ // an absent marker is the steady state, and the throwing form built and
+ // discarded one Error, with its stack, per guarded write. The `catch`
+ // stays because the option suppresses ENOENT only and every other stat
+ // failure (EACCES, ELOOP) must not propagate out of a write guard.
+ let stat;
+ try {
+ stat = statSync(path, { throwIfNoEntry: false });
+ } catch {
+ stat = undefined;
+ }
+ if (stat === undefined) {
+ MARKER_STAMPS.delete(root);
+ return null;
+ }
+ const cached = MARKER_STAMPS.get(root);
+ if (
+ cached !== undefined &&
+ cached.ino === stat.ino &&
+ cached.size === stat.size &&
+ cached.mtimeMs === stat.mtimeMs
+ ) {
+ return cached.marker;
+ }
+ const marker = parseMarker(path);
+ MARKER_STAMPS.set(root, {
+ ino: stat.ino,
+ size: stat.size,
+ mtimeMs: stat.mtimeMs,
+ marker,
+ });
+ return marker;
+}
+
+/** Whether the marker file exists at all, uncached. For the writer only. */
+export function freezeMarkerExists(vault: string): boolean {
+ return existsSync(frozenMarkerPath(vault));
+}
+
+/** The `vault-frozen` notice for `marker`, worded once. */
+export function vaultFrozenNotice(vault: string, marker: FreezeMarker): DegradationNotice {
+ const why = marker.reason === "" ? "no reason given" : marker.reason;
+ return degradationNotice({
+ code: DEGRADATION_CODE.vaultFrozen,
+ site: SITE,
+ path: resolve(vault),
+ detail:
+ `refusing to write: this vault was frozen at ${marker.frozen_at} by ` +
+ `${marker.by === "" ? "an unnamed agent" : marker.by} (${why}). ` +
+ `Run \`${FREEZE_NEXT_COMMAND}\` to lift it`,
+ });
+}
+
+/**
+ * Assert that the content lane may write to `vault`.
+ *
+ * Throws {@link VaultFrozenError} while the marker is present, including
+ * when it is present and unreadable. Returns silently otherwise; it never
+ * writes, creates, or repairs anything.
+ */
+export function assertVaultNotFrozen(vault: string): void {
+ const marker = readFreezeMarker(vault);
+ if (marker === null) return;
+ throw new VaultFrozenError(vaultFrozenNotice(vault, marker), marker);
+}
diff --git a/src/core/brain/freeze.ts b/src/core/brain/freeze.ts
new file mode 100644
index 00000000..b34484e2
--- /dev/null
+++ b/src/core/brain/freeze.ts
@@ -0,0 +1,171 @@
+/**
+ * The fleet freeze, write side: the two operator actions that set and
+ * lift it (who-wrote-what, Task C).
+ *
+ * `freeze-marker.ts` is the leaf every guarded write reads. This module
+ * is the pair of verbs behind `o2b brain freeze` / `o2b brain unfreeze`,
+ * and it is deliberately separate: the reader must import nothing from
+ * the log (which imports the paths module, which imports the guard), and
+ * these two writers must import the log, because the events they emit
+ * are the only durable record either action leaves.
+ *
+ * ## Why the marker's removal is not a data-loss event
+ *
+ * The marker carries no memory. Its whole content is its existence plus
+ * the five fields that say who stopped the vault and why, and the
+ * `unfreeze` event copies all five before the file goes. So the
+ * `unlinkSync` here is declared in `destructive-sites.ts` with exactly
+ * that story rather than routed through the snapshot gate: archiving a
+ * file whose replacement costs one command would be ceremony, and the
+ * fact worth keeping is kept in the log.
+ *
+ * ## Both verbs take the audit lane
+ *
+ * The vault-identity assertion still runs - a marker landing in the
+ * wrong store is as wrong as a note landing there - but the freeze check
+ * does not, because `unfreeze` must work on a vault that is frozen. That
+ * is the whole point of it. `freeze` takes the same lane for symmetry
+ * and because its own idempotence check, not the guard, is what makes a
+ * second freeze a no-op.
+ */
+
+import { unlinkSync } from "node:fs";
+
+import { resolveAgentName, resolveDeviceId } from "../config.ts";
+import { atomicWriteFileSync } from "../fs-atomic.ts";
+import {
+ FREEZE_MARKER_SCHEMA_VERSION,
+ WRITE_LANE,
+ freezeMarkerExists,
+ frozenMarkerPath,
+ readFreezeMarker,
+ type FreezeMarker,
+} from "./freeze-marker.ts";
+import { appendLogEvent, type BrainLogEntry } from "./log.ts";
+import { isoSecond } from "./time.ts";
+import { BRAIN_LOG_EVENT_KIND } from "./types.ts";
+import { assertVaultIdentityForWrite } from "./vault-identity.ts";
+
+export interface FreezeVaultOptions {
+ /** Agent recorded as having set the freeze. Defaults to the config identity. */
+ readonly agent?: string;
+ /** Operator's reason. Absent is recorded as the empty string, never guessed. */
+ readonly reason?: string;
+ /** Wall clock for `frozen_at`; injected so a test can pin the stamp. */
+ readonly now?: Date;
+}
+
+export interface FreezeVaultResult {
+ /**
+ * `true` when this call wrote the marker. `false` when the vault was
+ * already frozen - in which case {@link marker} is the EXISTING
+ * freeze, not the one this call would have written.
+ */
+ readonly changed: boolean;
+ readonly marker: FreezeMarker;
+ readonly path: string;
+}
+
+export interface UnfreezeVaultOptions {
+ /** Agent recorded as having lifted the freeze. Defaults to the config identity. */
+ readonly agent?: string;
+ /** Wall clock for the log event's timestamp. */
+ readonly now?: Date;
+}
+
+export interface UnfreezeVaultResult {
+ /** `true` when this call removed a marker; `false` when there was none. */
+ readonly changed: boolean;
+ /** What the marker said before it went, or `null` when there was none. */
+ readonly marker: FreezeMarker | null;
+}
+
+/**
+ * The device this machine appends under, or the empty string when it
+ * cannot be resolved.
+ *
+ * The same absorption `appendLogEvent` performs for the same reason, and
+ * the empty string is the documented shape rather than a value invented
+ * to look healthy: a device id that cannot be read must not turn an
+ * operator's stop into a failed command, and the field it fills is
+ * descriptive - it names which machine set the freeze, and the freeze
+ * itself is honoured on every machine regardless.
+ */
+function deviceIdOrEmpty(configPath?: string): string {
+ try {
+ return resolveDeviceId(configPath);
+ } catch {
+ return "";
+ }
+}
+
+/**
+ * Stop every content writer on every device that syncs this vault.
+ *
+ * Idempotent: a vault that is already frozen keeps the freeze it has and
+ * this call reports `changed: false` without rewriting the marker. That
+ * direction is the safe one - re-freezing would overwrite the record of
+ * who stopped the vault first, and a second operator's reason is not
+ * more true than the first's.
+ */
+export function freezeVault(vault: string, opts: FreezeVaultOptions = {}): FreezeVaultResult {
+ assertVaultIdentityForWrite(vault, undefined, WRITE_LANE.audit);
+ const path = frozenMarkerPath(vault);
+ const existing = readFreezeMarker(vault);
+ if (existing !== null) return { changed: false, marker: existing, path };
+
+ const agent = opts.agent ?? resolveAgentName();
+ const marker: FreezeMarker = Object.freeze({
+ schema: FREEZE_MARKER_SCHEMA_VERSION,
+ frozen_at: isoSecond(opts.now ?? new Date()),
+ by: agent,
+ device_id: deviceIdOrEmpty(),
+ reason: opts.reason ?? "",
+ });
+ atomicWriteFileSync(path, `${JSON.stringify(marker, null, 2)}\n`);
+
+ const entry: BrainLogEntry = {
+ timestamp: marker.frozen_at,
+ eventType: BRAIN_LOG_EVENT_KIND.freeze,
+ body: {
+ reason: marker.reason,
+ device_id: marker.device_id,
+ agent,
+ },
+ };
+ appendLogEvent(vault, entry);
+ return { changed: true, marker, path };
+}
+
+/**
+ * Lift the freeze.
+ *
+ * Removes the marker whatever state it is in - including a marker nobody
+ * could parse, which freezes the vault exactly as a well-formed one does
+ * and would otherwise be unliftable by any command. The event carries
+ * what the marker said, so the record of the freeze outlives the file.
+ */
+export function unfreezeVault(vault: string, opts: UnfreezeVaultOptions = {}): UnfreezeVaultResult {
+ assertVaultIdentityForWrite(vault, undefined, WRITE_LANE.audit);
+ // `readFreezeMarker` collapses an unreadable marker onto a freeze, so
+ // presence is asked of the filesystem rather than of the parse: the
+ // two answers agree everywhere except on a file this call must still
+ // be able to remove.
+ if (!freezeMarkerExists(vault)) return { changed: false, marker: null };
+ const marker = readFreezeMarker(vault);
+ unlinkSync(frozenMarkerPath(vault));
+
+ const agent = opts.agent ?? resolveAgentName();
+ const entry: BrainLogEntry = {
+ timestamp: isoSecond(opts.now ?? new Date()),
+ eventType: BRAIN_LOG_EVENT_KIND.unfreeze,
+ body: {
+ frozen_at: marker?.frozen_at ?? "",
+ by: marker?.by ?? "",
+ reason: marker?.reason ?? "",
+ agent,
+ },
+ };
+ appendLogEvent(vault, entry);
+ return { changed: true, marker };
+}
diff --git a/src/core/brain/idempotency-ledger.ts b/src/core/brain/idempotency-ledger.ts
index 8fc58362..99e2c431 100644
--- a/src/core/brain/idempotency-ledger.ts
+++ b/src/core/brain/idempotency-ledger.ts
@@ -15,27 +15,37 @@
* - {@link lookupKey} reads the stored record for a key (audit / C6 /
* the pre-write dedupe consult the writers perform).
*
- * Storage mirrors the continuity store's append/list model: month-sharded
- * JSONL under `<vault>/Brain/logs/idempotency/<YYYY-MM>.jsonl`, appended
- * under a per-shard lock. Reads scan every shard because a retry may land
- * in a later month than the original write.
+ * Storage mirrors the continuity store's append/list model: JSONL under
+ * `<vault>/Brain/logs/idempotency/<YYYY-MM>[.<deviceId>].jsonl`, one file
+ * per month per device, appended under a per-file lock. Reads scan every
+ * file because a retry may land in a later month than the original write,
+ * and because a key remembered on one device has to be honoured on
+ * another once Syncthing has delivered its shard.
*
* Concurrency boundary (inherited from the continuity model): the
* check-and-append is atomic within a single shard under its lock. Two
* genuinely-concurrent FIRST writers of the same key can both observe
* "absent" and both proceed β€” a rare race the append-only store does not
- * guard. The primary target β€” a SEQUENTIAL retry after a crash / double
- * delivery β€” is fully deduped because the prior write is already durable
- * on disk before the retry runs.
+ * guard, and one the per-device layout does not widen: the lock this
+ * device takes is on the only file this device writes. The primary
+ * target β€” a SEQUENTIAL retry after a crash / double delivery β€” is fully
+ * deduped because the prior write is already durable on disk before the
+ * retry runs.
*
* The kernel stays deterministic: no LLM, no wall-clock beyond the
* caller-supplied (or defaulted) `createdAt`.
*/
-import { existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync } from "node:fs";
+import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import { canonicalJson, sha256Hex } from "../integrity/digest.ts";
+import {
+ listShardedFiles,
+ resolveAppendShardId,
+ shardedFileName,
+ type LedgerShardGrammar,
+} from "./ledger-shards.ts";
import { BRAIN_ROOT_REL, ensureInsideVault } from "./paths.ts";
import { acquireLockSync } from "./sync-lockfile.ts";
import { isoSecond } from "./time.ts";
@@ -44,6 +54,16 @@ import { assertVaultIdentityForWrite } from "./vault-identity.ts";
/** Month-sharded JSONL root, distinct from `Brain/log/` (the human trail). */
const IDEMPOTENCY_REL = `${BRAIN_ROOT_REL}/logs/idempotency`;
+/** Shard base: one file per UTC month, per device. */
+const MONTH_RE = /^\d{4}-\d{2}$/;
+const IDEMPOTENCY_EXT = "jsonl";
+
+/** The ledger's file-name layout, handed to the shared shard grammar. */
+const IDEMPOTENCY_GRAMMAR: LedgerShardGrammar = Object.freeze({
+ base: "\\d{4}-\\d{2}",
+ extensions: Object.freeze([IDEMPOTENCY_EXT]),
+});
+
/** Hard cap on a client key. Long enough for `<session-id>:<slug>` joins. */
const KEY_MAX_LEN = 256;
@@ -121,15 +141,43 @@ export function computePayloadHash(fields: Readonly<Record<string, unknown>>): s
return sha256Hex(canonicalJson(fields));
}
-export function idempotencyLogPath(vault: string, month: string): string {
- if (!/^\d{4}-\d{2}$/.test(month)) throw new Error(`invalid idempotency month: ${month}`);
- return ensureInsideVault(join(vault, IDEMPOTENCY_REL, `${month}.jsonl`), vault);
+/**
+ * The directory every idempotency shard lives in. Exported so the sweep
+ * that reports Syncthing conflict copies names this ledger's directory
+ * through the module that owns it, rather than re-deriving the path.
+ */
+export function idempotencyLogDir(vault: string): string {
+ return ensureInsideVault(join(vault, IDEMPOTENCY_REL), vault);
}
/**
- * Look up the stored record for a client key across all month shards.
- * Returns the first-written record for the key (shards read in ascending
- * month order, lines in append order) or `null` when the key is unseen.
+ * One month's shard for one device: `<month>[.<shardId>].jsonl`.
+ *
+ * `shardId` defaults to this device's id, so an append lands in a file no
+ * other device writes. The empty shard id is the legacy un-sharded name,
+ * still read by every lookup and never renamed.
+ */
+export function idempotencyLogPath(
+ vault: string,
+ month: string,
+ shardId: string = resolveAppendShardId(),
+): string {
+ if (!MONTH_RE.test(month)) throw new Error(`invalid idempotency month: ${month}`);
+ return ensureInsideVault(
+ join(vault, IDEMPOTENCY_REL, shardedFileName(month, shardId, IDEMPOTENCY_EXT)),
+ vault,
+ );
+}
+
+/**
+ * Look up the stored record for a client key across EVERY shard of every
+ * month. Returns the first-written record for the key (shards read in
+ * ascending file-name order, lines in append order) or `null` when the
+ * key is unseen.
+ *
+ * The scan spans devices on purpose: a key remembered on one machine has
+ * to be honoured on another once Syncthing has delivered its shard, or
+ * the retry this ledger exists to dedupe would go through twice.
*/
export function lookupKey(vault: string, key: string): IdempotencyRecord | null {
const normalised = normaliseKey(key);
@@ -157,6 +205,9 @@ export function rememberKey(vault: string, input: RememberKeyInput): RememberKey
const handle = acquireLockSync(shardPath);
try {
// Re-scan under the lock so a same-shard concurrent insert is caught.
+ // The lock is on THIS device's shard - the only file this call can
+ // append to - while the scan still spans every shard, so a key a
+ // synced peer already remembered is honoured here too.
const existing = lookupKey(vault, key);
if (existing) {
return {
@@ -211,13 +262,23 @@ function monthOf(createdAt: string): string {
}
function readAllRecords(vault: string): IdempotencyRecord[] {
- const dir = ensureInsideVault(join(vault, IDEMPOTENCY_REL), vault);
- if (!existsSync(dir)) return [];
+ const dir = idempotencyLogDir(vault);
const records: IdempotencyRecord[] = [];
- for (const name of readdirSync(dir).toSorted()) {
- if (!name.endsWith(".jsonl")) continue;
- const path = ensureInsideVault(join(dir, name), vault);
- for (const line of readFileSync(path, "utf8").split("\n")) {
+ for (const shard of listShardedFiles(dir, IDEMPOTENCY_GRAMMAR)) {
+ let text: string;
+ try {
+ text = readFileSync(ensureInsideVault(shard.path, vault), "utf8");
+ } catch (err) {
+ // A shard that is not there has nothing to say and is skipped.
+ // Anything else - EACCES, EIO, a directory where a file belongs -
+ // propagates: an unreadable shard read as an empty one makes
+ // `lookupKey` answer "never seen", and a retried write then lands
+ // as a first write. That is the one outcome this ledger exists to
+ // prevent, so "I could not tell" must never resolve to "no".
+ if ((err as NodeJS.ErrnoException).code !== "ENOENT") throw err;
+ continue;
+ }
+ for (const line of text.split("\n")) {
if (!line.trim()) continue;
try {
records.push(JSON.parse(line) as IdempotencyRecord);
diff --git a/src/core/brain/ledger-shards.ts b/src/core/brain/ledger-shards.ts
new file mode 100644
index 00000000..6cd10aa1
--- /dev/null
+++ b/src/core/brain/ledger-shards.ts
@@ -0,0 +1,272 @@
+/**
+ * Per-device shard grammar for every append-only ledger in the vault.
+ *
+ * The vault is replicated with Syncthing. Two machines appending to the
+ * same file inside one sync window produce a `.sync-conflict-*` copy that
+ * no reader merges, so rows silently split across two files. `Brain/log/`
+ * solved that in v0.10.8 by giving each device its own file and merging
+ * every file at read; this module is that solution with the log-specific
+ * parts removed, so the continuity store, the idempotency ledger, the
+ * preference audit, the metrics sink and the session-lineage ledger share
+ * ONE answer instead of five copies of it.
+ *
+ * The grammar is `<base>[.<shardId>].<ext>`:
+ *
+ * - `<base>` is whatever the ledger already named its file after (a
+ * date, a month, a preference id, a metric surface, a fixed stem).
+ * Callers hand in the pattern, so a name outside their own layout is
+ * never mistaken for one of their shards;
+ * - `<shardId>` is the device id ({@link LEDGER_SHARD_ID_RE}, the same
+ * slug `resolveDeviceId` produces). ABSENT means the shard with the
+ * empty id - the legacy un-sharded file, which stays readable and
+ * never needs renaming;
+ * - `<ext>` is one of the extensions the ledger declares.
+ *
+ * Two rules hold everywhere:
+ *
+ * - a `*.sync-conflict-*` copy is NEVER a shard, even when its middle
+ * segment happens to fit the shard-id shape. It is reported by the
+ * doctor and merged by hand;
+ * - a merged read is ordered by (ledger sort key, shard id, line), so
+ * every device sees the same sequence regardless of the order
+ * Syncthing delivered the files in.
+ */
+
+import { existsSync, readdirSync } from "node:fs";
+import { join } from "node:path";
+
+import { resolveDeviceId } from "../config.ts";
+
+/**
+ * The shard-id shape: the lowercase slug `resolveDeviceId` produces,
+ * bounded so a shard id can never dominate a file name. Kept in sync
+ * with `DEVICE_ID_RE` in `src/core/config.ts` by construction - the only
+ * values that ever reach a shard name come from that resolver - and
+ * deliberately not shared with it: this one also has to admit the
+ * segment as it appears MID-NAME, where the config regex's anchoring on
+ * a leading alphanumeric is not what a reader of a file name checks.
+ */
+export const LEDGER_SHARD_ID_RE = /^[a-z0-9-]{1,32}$/;
+
+/** Source form of {@link LEDGER_SHARD_ID_RE}, for composing name regexes. */
+const SHARD_ID_PATTERN = "[a-z0-9-]{1,32}";
+
+/**
+ * A Syncthing conflict copy is named `<stem>.sync-conflict-<stamp>.<ext>`,
+ * so its middle segment can pass the shard-id shape. Named once because
+ * both the recogniser that must REJECT it and the leftover reporter that
+ * must FIND it key on the same marker.
+ */
+export const SYNC_CONFLICT_SHARD_PREFIX = "sync-conflict";
+
+/** The marker as it appears inside a file name, dot included. */
+const SYNC_CONFLICT_MARKER = `.${SYNC_CONFLICT_SHARD_PREFIX}-`;
+
+/**
+ * One ledger's file-name layout: the base-name pattern (regex SOURCE,
+ * anchored here) and the extensions it writes.
+ *
+ * The base is a pattern rather than a literal because most ledgers name
+ * their files after a shape (`\d{4}-\d{2}` for a month) rather than a
+ * fixed string. A ledger whose base is a caller-supplied value passes it
+ * through {@link literalBase} instead, which is what keeps a preference
+ * id containing a dot from being read as `<base>.<shardId>`.
+ */
+export interface LedgerShardGrammar {
+ /** Regex source matching the base name, WITHOUT anchors. */
+ readonly base: string;
+ /** Extensions, without the leading dot. */
+ readonly extensions: ReadonlyArray<string>;
+}
+
+/** The shape of one recognised ledger file name. */
+export interface ParsedShardedName {
+ readonly base: string;
+ /** Empty string for the legacy un-sharded file. */
+ readonly shardId: string;
+ readonly ext: string;
+}
+
+/** A parsed name together with where it was found. */
+export interface ShardedFile extends ParsedShardedName {
+ readonly path: string;
+ readonly name: string;
+}
+
+/**
+ * Escape `value` so it matches itself and nothing else inside a grammar
+ * base. The dot is the character that matters: a preference id is only
+ * bounded by {@link import('./paths.ts').validateSlug}, which permits
+ * one, and an unescaped `pref-a.b` would let `pref-a.b.jsonl` parse as
+ * the `b` shard of `pref-a`.
+ */
+export function literalBase(value: string): string {
+ return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
+}
+
+/**
+ * Compiled name regexes, keyed by grammar. Every listing call parses one
+ * name per directory entry, so compiling the pattern per call would make
+ * a directory scan quadratic in the regex engine rather than in the
+ * files. The key is the grammar's full content, so two grammars that
+ * differ anywhere never share a pattern.
+ */
+const NAME_RE_CACHE = new Map<string, RegExp>();
+
+function nameRe(grammar: LedgerShardGrammar): RegExp {
+ // JSON rather than a joined string: it needs no separator character,
+ // so two grammars whose parts differ can never collide by having those
+ // parts run together.
+ const key = JSON.stringify([grammar.base, grammar.extensions]);
+ const cached = NAME_RE_CACHE.get(key);
+ if (cached !== undefined) return cached;
+ const exts = grammar.extensions.map(literalBase).join("|");
+ const re = new RegExp(`^(${grammar.base})(?:\\.(${SHARD_ID_PATTERN}))?\\.(${exts})$`);
+ NAME_RE_CACHE.set(key, re);
+ return re;
+}
+
+/**
+ * Decide whether `name` is a file of the ledger `grammar` describes, and
+ * which shard of it.
+ *
+ * Returns `null` for anything else, INCLUDING a hand-renamed Syncthing
+ * conflict copy whose middle segment fits the shard-id shape.
+ */
+export function parseShardedName(
+ name: string,
+ grammar: LedgerShardGrammar,
+): ParsedShardedName | null {
+ const m = nameRe(grammar).exec(name);
+ if (m === null) return null;
+ const shardId = m[2] ?? "";
+ if (shardId.startsWith(SYNC_CONFLICT_SHARD_PREFIX)) return null;
+ return { base: m[1]!, shardId, ext: m[3]! };
+}
+
+/**
+ * The file name a writer on shard `shardId` appends to. The empty shard
+ * id yields the bare `<base>.<ext>`, which is exactly the legacy name -
+ * so a vault whose device id resolves empty writes the same bytes to the
+ * same file it always did, and no migration renames anything.
+ */
+export function shardedFileName(base: string, shardId: string, ext: string): string {
+ if (shardId !== "" && !LEDGER_SHARD_ID_RE.test(shardId)) {
+ throw new Error(
+ `invalid ledger shard id ${JSON.stringify(shardId)} - ` +
+ "expected a lowercase slug matching the device_id config shape",
+ );
+ }
+ return shardId === "" ? `${base}.${ext}` : `${base}.${shardId}.${ext}`;
+}
+
+/** True for a name Syncthing wrote as a conflict copy. */
+export function isSyncConflictName(name: string): boolean {
+ return name.includes(SYNC_CONFLICT_MARKER);
+}
+
+/**
+ * Every file under `dir` that `grammar` recognises, sorted by name.
+ *
+ * An absent directory lists nothing. A directory that exists but cannot
+ * be READ throws: the callers that must distinguish "no shards" from
+ * "not looked at" (the doctor's conflict sweep) rely on the throw, and
+ * absorbing it here would hand them the one answer they cannot act on.
+ */
+export function listShardedFiles(dir: string, grammar: LedgerShardGrammar): ShardedFile[] {
+ if (!existsSync(dir)) return [];
+ const out: ShardedFile[] = [];
+ for (const entry of readdirSync(dir, { withFileTypes: true }).toSorted((a, b) =>
+ a.name.localeCompare(b.name),
+ )) {
+ if (!entry.isFile()) continue;
+ const parsed = parseShardedName(entry.name, grammar);
+ if (parsed === null) continue;
+ out.push({ ...parsed, path: join(dir, entry.name), name: entry.name });
+ }
+ return out;
+}
+
+/**
+ * `*.sync-conflict-*` copies left behind by Syncthing under `dir`. The
+ * shard layout prevents NEW conflicts; doctor surfaces any leftovers for
+ * a manual union+dedup merge. Absent directory: none. Unreadable
+ * directory: throws, for the reason {@link listShardedFiles} gives.
+ */
+export function listSyncConflictFiles(dir: string): string[] {
+ if (!existsSync(dir)) return [];
+ return readdirSync(dir, { withFileTypes: true })
+ .filter((e) => e.isFile() && isSyncConflictName(e.name))
+ .map((e) => join(dir, e.name))
+ .toSorted();
+}
+
+/** One row read out of one shard, tagged with where it came from. */
+export interface ShardedRow<T> {
+ readonly value: T;
+ readonly shardId: string;
+ /** 0-based position within its own shard. */
+ readonly line: number;
+}
+
+/**
+ * Merge rows drawn from several shards into the one order every device
+ * agrees on: the ledger's own sort key first, then the shard id, then
+ * either the ledger's own last-resort key or the line's position inside
+ * its shard.
+ *
+ * The shard id is the tie-break rather than the arrival order because
+ * arrival order is precisely what differs between two Syncthing peers.
+ *
+ * `withinShard` is for a ledger whose rows carry an identity of their own
+ * that is independent of which device wrote them - the continuity
+ * record's content-hash id, say. Supplying it keeps a single-shard vault
+ * reading back in exactly the order it did before sharding existed;
+ * omitting it falls back to append order, which is the only ordering the
+ * file itself asserts.
+ */
+export function mergeShardedRows<T>(
+ rows: ReadonlyArray<ShardedRow<T>>,
+ sortKey: (value: T) => string,
+ withinShard?: (value: T) => string,
+): T[] {
+ return rows
+ .map((row) => ({ row, key: sortKey(row.value) }))
+ .toSorted((a, b) => {
+ if (a.key !== b.key) return a.key < b.key ? -1 : 1;
+ if (a.row.shardId !== b.row.shardId) return a.row.shardId < b.row.shardId ? -1 : 1;
+ if (withinShard === undefined) return a.row.line - b.row.line;
+ const left = withinShard(a.row.value);
+ const right = withinShard(b.row.value);
+ return left === right ? a.row.line - b.row.line : left < right ? -1 : 1;
+ })
+ .map((entry) => entry.row.value);
+}
+
+/**
+ * The shard id THIS device appends under.
+ *
+ * Defaults to `resolveDeviceId()` from the device-local config; the empty
+ * string selects the legacy un-sharded file.
+ *
+ * ANY resolution failure falls back to the legacy file - a missing HOME,
+ * an unwritable config home, or a config file that is present but cannot
+ * be read (`ConfigReadError`). The append paths are the ones that absorb
+ * that error, and it is deliberate rather than an oversight: appending is
+ * the always-on write path behind every hook and every session-capture
+ * event, so failing it turns one bad file mode into a dead session. The
+ * fallback is also not a neutral value invented to look healthy - it is
+ * the documented shard shape the `O2B_DEVICE_ID=""` opt-out selects, it
+ * loses no data, and the per-file lock still orders concurrent writers.
+ * The condition itself is not swallowed anywhere: every OTHER caller of
+ * `resolveDeviceId` propagates it, and the CLI reports it by name.
+ */
+export function resolveAppendShardId(): string {
+ try {
+ return resolveDeviceId();
+ } catch {
+ // Legacy un-sharded file. See the docblock above for why the append
+ // paths absorb what every other caller propagates.
+ return "";
+ }
+}
diff --git a/src/core/brain/lineage/ledger.ts b/src/core/brain/lineage/ledger.ts
index 71b9648e..c0343eb9 100644
--- a/src/core/brain/lineage/ledger.ts
+++ b/src/core/brain/lineage/ledger.ts
@@ -75,6 +75,14 @@ import {
} from "../../integrity/degradation.ts";
import type { GitWorkspaceIdentity } from "../git/reader.ts";
import { computePayloadHash } from "../idempotency-ledger.ts";
+import {
+ listShardedFiles,
+ literalBase,
+ mergeShardedRows,
+ resolveAppendShardId,
+ shardedFileName,
+ type ShardedRow,
+} from "../ledger-shards.ts";
import { BRAIN_ROOT_REL, ensureInsideVault } from "../paths.ts";
import { acquireLockSync, type LockHandle } from "../sync-lockfile.ts";
import { assertVaultIdentityForWrite, VaultIdentityMismatchError } from "../vault-identity.ts";
@@ -119,8 +127,15 @@ const GAP_RETENTION_MS = 7 * 24 * 60 * 60 * 1000;
const GAP_LOCK_STALE_MS = 60_000;
const STATE_DIR_REL = posix.join(BRAIN_ROOT_REL, ".state");
-const LEDGER_FILE = "session-lineage.jsonl";
-const GAPS_FILE = "session-lineage-gaps.jsonl";
+/**
+ * Shard bases. The two are distinct stems rather than one stem with a
+ * suffix, so `session-lineage-gaps.jsonl` can never parse as a shard of
+ * `session-lineage`: the grammar splits on a dot, and `-gaps` is part of
+ * the base.
+ */
+const LEDGER_BASE = "session-lineage";
+const GAPS_BASE = "session-lineage-gaps";
+const LINEAGE_EXT = "jsonl";
/** Site recorded on every notice this module emits. */
const LEDGER_SITE = "brain.lineage.ledger";
@@ -248,17 +263,81 @@ export function brainStateDirPath(vault: string): string {
return ensureInsideVault(join(vault, STATE_DIR_REL), vault);
}
-export function sessionLineageLedgerPath(vault: string): string {
- return ensureInsideVault(join(vault, STATE_DIR_REL, LEDGER_FILE), vault);
+/**
+ * This device's ledger shard: `session-lineage[.<deviceId>].jsonl`.
+ *
+ * One chain and one sequence per FILE, so a per-device shard is a
+ * per-device chain (who-wrote-what, Task B) and two machines syncing one
+ * vault never rewrite each other's compaction. The empty shard id is the
+ * legacy un-sharded name, still merged by every read and never renamed.
+ */
+export function sessionLineageLedgerPath(
+ vault: string,
+ shardId: string = resolveAppendShardId(),
+): string {
+ return ensureInsideVault(
+ join(vault, STATE_DIR_REL, shardedFileName(LEDGER_BASE, shardId, LINEAGE_EXT)),
+ vault,
+ );
}
/**
* Sidecar holding observations that were never appended. Lives beside
* the ledger under the same dot-directory, which is excluded from vault
* walking and search indexing - a diagnostic must not become a note.
+ *
+ * Shards with the ledger: each device bounds and ages its OWN sidecar,
+ * carrying its own discard accumulator, and the report sums them. The
+ * sidecar's trim lock therefore never crosses a device boundary either.
+ */
+export function sessionLineageGapsPath(
+ vault: string,
+ shardId: string = resolveAppendShardId(),
+): string {
+ return ensureInsideVault(
+ join(vault, STATE_DIR_REL, shardedFileName(GAPS_BASE, shardId, LINEAGE_EXT)),
+ vault,
+ );
+}
+
+/** One shard of the ledger (or of its gap sidecar) as found on disk. */
+export interface LineageShardFile {
+ /** Empty string for the legacy un-sharded file. */
+ readonly shardId: string;
+ readonly path: string;
+}
+
+/**
+ * Every ledger shard under `Brain/.state/`, ordered by shard id so the
+ * legacy file leads and two devices agree on the sequence whatever order
+ * Syncthing delivered their files in. Fail-soft: a state directory that
+ * cannot be listed yields no shards, matching every other read here.
*/
-export function sessionLineageGapsPath(vault: string): string {
- return ensureInsideVault(join(vault, STATE_DIR_REL, GAPS_FILE), vault);
+export function listSessionLineageShards(vault: string): LineageShardFile[] {
+ return listLineageShards(vault, LEDGER_BASE);
+}
+
+/** The gap sidecar's shards. See {@link listSessionLineageShards}. */
+export function listSessionLineageGapShards(vault: string): LineageShardFile[] {
+ return listLineageShards(vault, GAPS_BASE);
+}
+
+function listLineageShards(vault: string, base: string): LineageShardFile[] {
+ let dir: string;
+ try {
+ dir = brainStateDirPath(vault);
+ } catch {
+ return [];
+ }
+ let files;
+ try {
+ files = listShardedFiles(dir, { base: literalBase(base), extensions: [LINEAGE_EXT] });
+ } catch {
+ return [];
+ }
+ return files
+ .map((file) => ({ shardId: file.shardId, path: file.path }))
+ .toSorted((a, b) => (a.shardId < b.shardId ? -1 : a.shardId > b.shardId ? 1 : 0));
}
export interface LedgerLine {
@@ -473,20 +552,30 @@ export interface LineageLedgerScan {
* needs line order and the chain fields that per-session state folds
* away.
*/
-export function scanLineageLedger(vault: string): LineageLedgerScan {
- const absent = Object.freeze({
+export function scanLineageLedger(
+ vault: string,
+ shardId: string = resolveAppendShardId(),
+): LineageLedgerScan {
+ let path: string;
+ try {
+ path = sessionLineageLedgerPath(vault, shardId);
+ } catch {
+ return absentScan();
+ }
+ return scanLineageShard(path);
+}
+
+function absentScan(): LineageLedgerScan {
+ return Object.freeze({
exists: false,
readable: false,
lines: Object.freeze([]),
skippedLineNumbers: Object.freeze([]),
});
- let path: string;
- try {
- path = sessionLineageLedgerPath(vault);
- } catch {
- return absent;
- }
- if (!existsSync(path)) return absent;
+}
+
+function scanLineageShard(path: string): LineageLedgerScan {
+ if (!existsSync(path)) return absentScan();
let raw: string;
try {
raw = readFileSync(path, "utf8");
@@ -507,6 +596,22 @@ export function scanLineageLedger(vault: string): LineageLedgerScan {
});
}
+/** One shard's scan, together with which shard it was. */
+export interface LineageLedgerShardScan extends LineageLedgerScan, LineageShardFile {}
+
+/**
+ * Scan EVERY ledger shard, in shard-id order. The unit of the chain is
+ * one file, so the verifier walks these one at a time and reports each
+ * by its own path; a break in one device's shard says nothing about
+ * another's.
+ */
+export function scanLineageLedgerShards(vault: string): LineageLedgerShardScan[] {
+ return listSessionLineageShards(vault).map((shard) => ({
+ ...shard,
+ ...scanLineageShard(shard.path),
+ }));
+}
+
/** The sidecar as a whole: what it still lists, and what it no longer can. */
export interface LineageGapReport {
/** The sidecar file exists on disk. */
@@ -624,28 +729,42 @@ export function readLineageGapReport(
opts: ReadLineageGapsOptions = {},
): LineageGapReport {
const nowMs = opts.nowMs ?? Date.now();
- const empty = Object.freeze({
- exists: false,
- records: Object.freeze([]),
- discarded: 0,
- truncated: false,
- total: 0,
- });
- let raw: string;
- try {
- const path = sessionLineageGapsPath(vault);
- if (!existsSync(path)) return empty;
- raw = readFileSync(path, "utf8");
- } catch {
- return empty;
+ const rows: Array<ShardedRow<LineageGapRecord>> = [];
+ let exists = false;
+ let discarded = 0;
+ // One sidecar per device, each with its own bound and its own discard
+ // accumulator; the report is their union and the sum of what each
+ // device's trim threw away.
+ for (const shard of listSessionLineageGapShards(vault)) {
+ let raw: string;
+ try {
+ raw = readFileSync(shard.path, "utf8");
+ } catch {
+ continue;
+ }
+ exists = true;
+ const parsed = parseGapFile(raw, nowMs);
+ discarded += parsed.discarded;
+ parsed.records.forEach((value, index) =>
+ rows.push({ value, shardId: shard.shardId, line: index }),
+ );
+ }
+ if (!exists) {
+ return Object.freeze({
+ exists: false,
+ records: Object.freeze([]),
+ discarded: 0,
+ truncated: false,
+ total: 0,
+ });
}
- const parsed = parseGapFile(raw, nowMs);
+ const records = mergeShardedRows(rows, (record) => record.at);
return Object.freeze({
exists: true,
- records: Object.freeze(parsed.records),
- discarded: parsed.discarded,
- truncated: parsed.discarded > 0,
- total: parsed.records.length + parsed.discarded,
+ records: Object.freeze(records),
+ discarded,
+ truncated: discarded > 0,
+ total: records.length + discarded,
});
}
@@ -721,7 +840,16 @@ function buildState(lines: ReadonlyArray<LedgerLine>): Map<string, LineageLedger
* belong to `verify.ts`, which reports them to the doctor.
*/
export function readLineageLedger(vault: string): LineageLedgerState {
- return buildState(scanLineageLedger(vault).lines.map((entry) => entry.line));
+ const rows: Array<ShardedRow<LedgerLine>> = [];
+ for (const shard of scanLineageLedgerShards(vault)) {
+ shard.lines.forEach((entry, index) =>
+ rows.push({ value: entry.line, shardId: shard.shardId, line: index }),
+ );
+ }
+ // (at, shard id, line): every device folds the same observations in the
+ // same order, so per-session state does not depend on which machine is
+ // asking or on when Syncthing delivered the other machine's shard.
+ return buildState(mergeShardedRows(rows, (line) => line.at));
}
/**
diff --git a/src/core/brain/lineage/verify.ts b/src/core/brain/lineage/verify.ts
index 1662aa11..defa40e1 100644
--- a/src/core/brain/lineage/verify.ts
+++ b/src/core/brain/lineage/verify.ts
@@ -59,9 +59,10 @@ import {
import {
isChainedLine,
type LedgerLine,
+ type LineageLedgerScan,
lineageChainHash,
readLineageGapReport,
- scanLineageLedger,
+ scanLineageLedgerShards,
sessionLineageLedgerPath,
} from "./ledger.ts";
@@ -80,14 +81,45 @@ const VERIFY_SITE = "brain.lineage.verify";
*/
const MAX_ITEMIZED_FINDINGS = 20;
+/**
+ * One shard's verdict. The chain's unit is one FILE, so a break in one
+ * device's shard says nothing about another's and every count here is
+ * that shard's alone.
+ */
+export interface LineageLedgerShardVerification {
+ /** Empty string for the legacy un-sharded ledger. */
+ readonly shardId: string;
+ /** The shard that was verified. */
+ readonly path: string;
+ /** The shard file is on disk. */
+ readonly exists: boolean;
+ /** The file's bytes were obtained. False for an unreadable shard. */
+ readonly readable: boolean;
+ /** Parseable lines found in this shard. */
+ readonly lines: number;
+ /** Non-blank lines of this shard that could not be read as a record. */
+ readonly skipped: number;
+ /** Lines of this shard carrying a sequence number and a chain hash. */
+ readonly chained: number;
+ /** Lines of this shard carrying no chain fields. */
+ readonly legacy: number;
+ /** This shard's findings, in file order. */
+ readonly notices: ReadonlyArray<DegradationNotice>;
+ /** True when this shard produced no finding. */
+ readonly ok: boolean;
+}
+
export interface LineageLedgerVerification {
- /** The ledger that was verified, whether or not it exists. */
+ /**
+ * The ledger this device would append to, whether or not it exists.
+ * {@link shards} names every ledger that WAS verified.
+ */
readonly path: string;
- /** The ledger file is on disk. Distinguishes "no ledger" from "empty ledger". */
+ /** At least one ledger shard is on disk. Distinguishes "no ledger" from "empty ledger". */
readonly exists: boolean;
- /** The file's bytes were obtained. False for an absent OR unreadable ledger. */
+ /** Every shard on disk had its bytes obtained. False when one could not be read. */
readonly readable: boolean;
- /** Parseable lines found. */
+ /** Parseable lines found, across every shard. */
readonly lines: number;
/** Non-blank lines that could not be read as a record. Each is a finding. */
readonly skipped: number;
@@ -95,11 +127,13 @@ export interface LineageLedgerVerification {
readonly chained: number;
/** Lines carrying no chain fields. A finding only AFTER a chained line. */
readonly legacy: number;
+ /** Per-shard verdicts, in shard-id order. Empty when no shard exists. */
+ readonly shards: ReadonlyArray<LineageLedgerShardVerification>;
/** Observations recorded as never-appended gaps, listed plus discarded. */
readonly droppedObservations: number;
/** True when the gap sidecar's bound discarded records it can no longer list. */
readonly gapsTruncated: boolean;
- /** Every finding, in file order. Empty on a clean ledger. */
+ /** Every finding, shard by shard then in file order. Empty on a clean ledger. */
readonly notices: ReadonlyArray<DegradationNotice>;
/** True when nothing was found. */
readonly ok: boolean;
@@ -128,10 +162,73 @@ export function verifyLineageLedger(
): LineageLedgerVerification {
const notices: DegradationNotice[] = [];
const path = safeLedgerPath(vault);
+
+ // One shard, one chain. Every shard is verified in full and reports
+ // under its OWN path, so an operator holding a finding knows which
+ // machine's ledger to look at.
+ const shards: LineageLedgerShardVerification[] = [];
+ for (const scan of scanLineageLedgerShards(vault)) {
+ shards.push(verifyShard(scan.shardId, scan.path, scan));
+ }
+ for (const shard of shards) notices.push(...shard.notices);
+
+ const lines = shards.reduce((sum, shard) => sum + shard.lines, 0);
+ const skippedTotal = shards.reduce((sum, shard) => sum + shard.skipped, 0);
+ const chained = shards.reduce((sum, shard) => sum + shard.chained, 0);
+ const legacy = shards.reduce((sum, shard) => sum + shard.legacy, 0);
+
+ const gaps = readLineageGapReport(vault, opts.nowMs !== undefined ? { nowMs: opts.nowMs } : {});
+ for (const gap of gaps.records.slice(0, MAX_ITEMIZED_FINDINGS)) {
+ emitDegradationNotice(notices, {
+ code: DEGRADATION_CODE.lineageObservationDropped,
+ site: VERIFY_SITE,
+ detail:
+ `observation for session ${gap.sessionId} (event ${gap.event}) ` +
+ `was never appended: ${gap.reason}`,
+ });
+ }
+ const unlisted = gaps.total - Math.min(gaps.records.length, MAX_ITEMIZED_FINDINGS);
+ if (unlisted > 0) {
+ emitDegradationNotice(notices, {
+ code: DEGRADATION_CODE.lineageObservationDropped,
+ site: VERIFY_SITE,
+ detail:
+ `${unlisted} further observations were never appended and are not itemized` +
+ (gaps.truncated ? ` (${gaps.discarded} beyond the sidecar's retained records)` : ""),
+ });
+ }
+
+ return Object.freeze({
+ path,
+ exists: shards.some((shard) => shard.exists),
+ readable: shards.length > 0 && shards.every((shard) => shard.readable),
+ lines,
+ skipped: skippedTotal,
+ chained,
+ legacy,
+ shards: Object.freeze(shards),
+ droppedObservations: gaps.total,
+ gapsTruncated: gaps.truncated,
+ notices: Object.freeze(notices),
+ ok: notices.length === 0,
+ });
+}
+
+/**
+ * Verify one shard's chain. Extracted from the whole-ledger pass with no
+ * change to what it checks: the conditions in this module's docblock all
+ * concern lines that are ADJACENT IN ONE FILE, and a shard is exactly
+ * that file.
+ */
+function verifyShard(
+ shardId: string,
+ path: string,
+ scan: LineageLedgerScan,
+): LineageLedgerShardVerification {
+ const notices: DegradationNotice[] = [];
let chained = 0;
let legacy = 0;
- const scan = scanLineageLedger(vault);
if (scan.exists && !scan.readable) {
emitDegradationNotice(notices, {
code: DEGRADATION_CODE.lineageChainBroken,
@@ -195,32 +292,12 @@ export function verifyLineageLedger(
}
chained++;
sawChained = true;
- checkChainedLine(line, previous, notices);
+ checkChainedLine(line, previous, notices, path);
previous = line;
}
- const gaps = readLineageGapReport(vault, opts.nowMs !== undefined ? { nowMs: opts.nowMs } : {});
- for (const gap of gaps.records.slice(0, MAX_ITEMIZED_FINDINGS)) {
- emitDegradationNotice(notices, {
- code: DEGRADATION_CODE.lineageObservationDropped,
- site: VERIFY_SITE,
- detail:
- `observation for session ${gap.sessionId} (event ${gap.event}) ` +
- `was never appended: ${gap.reason}`,
- });
- }
- const unlisted = gaps.total - Math.min(gaps.records.length, MAX_ITEMIZED_FINDINGS);
- if (unlisted > 0) {
- emitDegradationNotice(notices, {
- code: DEGRADATION_CODE.lineageObservationDropped,
- site: VERIFY_SITE,
- detail:
- `${unlisted} further observations were never appended and are not itemized` +
- (gaps.truncated ? ` (${gaps.discarded} beyond the sidecar's retained records)` : ""),
- });
- }
-
return Object.freeze({
+ shardId,
path,
exists: scan.exists,
readable: scan.readable,
@@ -228,8 +305,6 @@ export function verifyLineageLedger(
skipped: skipped.length,
chained,
legacy,
- droppedObservations: gaps.total,
- gapsTruncated: gaps.truncated,
notices: Object.freeze(notices),
ok: notices.length === 0,
});
@@ -244,12 +319,14 @@ function checkChainedLine(
line: LedgerLine,
previous: LedgerLine | undefined,
notices: DegradationNotice[],
+ path: string,
): void {
const seq = line.seq!;
if (lineageChainHash(line) !== line.h) {
emitDegradationNotice(notices, {
code: DEGRADATION_CODE.lineageChainBroken,
site: VERIFY_SITE,
+ path,
detail:
`sequence ${seq} (session ${line.sid}): content does not match its ` +
"recorded hash - the line was edited after it was written",
@@ -261,6 +338,7 @@ function checkChainedLine(
emitDegradationNotice(notices, {
code: DEGRADATION_CODE.lineageChainBroken,
site: VERIFY_SITE,
+ path,
detail:
`sequence ${seq} (session ${line.sid}): does not link to sequence ` +
`${previous.seq} - a line between them was removed or reordered`,
@@ -271,6 +349,7 @@ function checkChainedLine(
emitDegradationNotice(notices, {
code: DEGRADATION_CODE.lineageChainBroken,
site: VERIFY_SITE,
+ path,
detail: `sequence ${seq} (session ${line.sid}): follows sequence ${previous.seq}`,
});
}
diff --git a/src/core/brain/log-chain.ts b/src/core/brain/log-chain.ts
new file mode 100644
index 00000000..d692e675
--- /dev/null
+++ b/src/core/brain/log-chain.ts
@@ -0,0 +1,384 @@
+/**
+ * Brain log chain verification (who-wrote-what, Task E).
+ *
+ * Every note write, every freeze and every refusal is now recorded as a
+ * Brain log event, which makes the log the attribution record for the
+ * vault. A record only carries weight if a line someone deleted or
+ * edited is DETECTABLE, so every JSONL row appended from this release on
+ * carries `prev` and `h` ({@link LOG_CHAIN_FIELDS}) and this module is
+ * the pass that walks them.
+ *
+ * ## One chain per shard, and only per shard
+ *
+ * The log is sharded per device and per day, and two machines append to
+ * two files that Syncthing later delivers in whatever order it likes.
+ * There is therefore no total order to chain across, and pretending
+ * otherwise would report every peer's normal history as a break. The
+ * chain's unit is one FILE: a break in one device's shard says nothing
+ * about another's, and every count here is that shard's alone.
+ *
+ * The markdown twin is not chained. It is a derived rendering of the
+ * same events for human eyes in Obsidian, it is meant to be readable and
+ * therefore editable, and the JSONL sidecar is the machine-primary
+ * surface every reader already prefers.
+ *
+ * ## Report-only, exactly like the lineage ledger's chain
+ *
+ * Nothing in the read path consults this. `readLogDay` returns every
+ * event it can parse whether the shard links up or not, because a log
+ * that refused to be read because someone edited it would be a worse
+ * outcome than the edit. What the chain buys is that the edit has a
+ * name, a file and a line number.
+ *
+ * ## What counts as a break, and what does not
+ *
+ * A line with no `h` is LEGACY: written before the chain shipped, or by
+ * a peer still on an older build. Legacy lines are counted and never
+ * reported - but only while they precede the chain. The first chained
+ * line in a shard anchors it with `prev: null`, and once a shard has a
+ * chained line, a line without one is not history: it is a line whose
+ * links were stripped, so it is reported as `malformed` at its own line.
+ * That asymmetry is the whole reason a stripped middle line cannot pass.
+ *
+ * The head of a shard is NOT exempt. `lineage/verify.ts` exempts its
+ * first line because that ledger compacts and its head legitimately
+ * names a predecessor that no longer exists; the Brain log never
+ * compacts, so a first chained line carrying a non-null `prev` means the
+ * head of the file was cut off - and reporting that is the point.
+ *
+ * Three break reasons, first one per shard reported ({@link
+ * LOG_CHAIN_BREAK_REASON}). The walk continues past a break so the
+ * counts describe the whole file rather than its head.
+ */
+
+import {
+ DEGRADATION_CODE,
+ type DegradationNotice,
+ emitDegradationNotice,
+} from "../integrity/degradation.ts";
+import { LOG_CHAIN_FIELDS, logChainHash } from "./log.ts";
+import { listLogShardFiles, scanJsonlRows, type LogShardFile } from "./log-jsonl.ts";
+import { brainDirs } from "./paths.ts";
+
+export { LOG_CHAIN_FIELDS, logChainHash } from "./log.ts";
+
+/** Site recorded on every notice this module emits. */
+const VERIFY_SITE = "brain.log.chain.verify";
+
+/**
+ * Broken shards listed individually before the rest are folded into one
+ * counted notice.
+ *
+ * A vault that has been running for a year holds hundreds of shards, and
+ * a bulk edit (a botched merge of a conflict copy, say) can break most
+ * of them at once. Pouring all of those into the doctor's report buries
+ * every other finding beside them. The remainder is never dropped: it is
+ * reported as an explicit count, so a capped listing is never mistaken
+ * for the whole finding. Same bound and same reasoning as
+ * `MAX_ITEMIZED_FINDINGS` in `lineage/verify.ts`.
+ */
+const MAX_ITEMIZED_SHARDS = 20;
+
+/** Only the machine-primary sidecar is chained; the markdown twin is derived. */
+const CHAINED_EXTENSION = "jsonl";
+
+/** Why one shard's chain does not hold. */
+export const LOG_CHAIN_BREAK_REASON = Object.freeze({
+ /** The line's recorded `h` is not what its content hashes to: it was edited. */
+ hashMismatch: "hash-mismatch",
+ /** The line's `prev` is not the preceding chained line's `h`: a line was removed or reordered. */
+ prevMismatch: "prev-mismatch",
+ /** The line is not a chainable row where the chain had already started. */
+ malformed: "malformed",
+} as const);
+
+export type LogChainBreakReason =
+ (typeof LOG_CHAIN_BREAK_REASON)[keyof typeof LOG_CHAIN_BREAK_REASON];
+
+/** Where a shard's chain stops holding, and why. */
+export interface LogChainBreak {
+ /** 1-based line number inside the shard file - the number an editor shows. */
+ readonly line: number;
+ readonly reason: LogChainBreakReason;
+}
+
+/** One shard's verdict. */
+export interface LogChainShardVerification {
+ /** The shard file that was verified. */
+ readonly path: string;
+ /** The UTC day this shard records. */
+ readonly date: string;
+ /** Empty string for the legacy un-sharded pair. */
+ readonly shardId: string;
+ /** Lines of this shard carrying a chain hash. */
+ readonly chained: number;
+ /**
+ * Lines of this shard carrying no chain hash. Legitimate history when
+ * they precede the chain; one appearing after it is also reported as
+ * {@link LOG_CHAIN_BREAK_REASON.malformed}.
+ */
+ readonly legacy: number;
+ /**
+ * Lines that are neither: not JSON, not an object, or a chained row
+ * whose own projection cannot be hashed. Reported, never silently
+ * counted as clean.
+ */
+ readonly unparsed: number;
+ /** The first place the chain stops holding, or `null` on a clean shard. */
+ readonly firstBreak: LogChainBreak | null;
+}
+
+export interface LogChainVerification {
+ /** Per-shard verdicts, in file-name order. Empty when the log holds no shard. */
+ readonly shards: ReadonlyArray<LogChainShardVerification>;
+ /** Every finding. Empty on a clean log. */
+ readonly notices: ReadonlyArray<DegradationNotice>;
+ /** True when nothing was found. */
+ readonly ok: boolean;
+}
+
+/**
+ * Walk every JSONL shard of the Brain log and report where each one
+ * stops linking up.
+ *
+ * Never throws. A log directory that cannot be listed, and a shard whose
+ * bytes cannot be read, are both findings rather than silence - "not
+ * verified" is not "verified clean", and the caller here is the doctor,
+ * which must not report a store it could not open as healthy.
+ *
+ * Syncthing conflict copies are excluded, because they are not shards:
+ * the shard recogniser rejects them by name and the doctor reports them
+ * under its own `sync-conflict-log` finding. Verifying them here would
+ * report one condition twice, and the copy's rows were split off from a
+ * shard rather than appended to it, so its chain never held by
+ * construction.
+ */
+export function verifyLogChain(vault: string): LogChainVerification {
+ const notices: DegradationNotice[] = [];
+ let files: ReadonlyArray<LogShardFile>;
+ try {
+ files = listLogShardFiles(vault);
+ } catch (err) {
+ emitDegradationNotice(notices, {
+ code: DEGRADATION_CODE.logChainBroken,
+ site: VERIFY_SITE,
+ path: safeLogDir(vault),
+ detail:
+ "the Brain log directory could not be listed, so no shard in it was verified: " +
+ `${(err as NodeJS.ErrnoException).message ?? String(err)}`,
+ });
+ return Object.freeze({ shards: Object.freeze([]), notices: Object.freeze(notices), ok: false });
+ }
+
+ const shards = files
+ .filter((file) => file.ext === CHAINED_EXTENSION)
+ .map((file) => verifyShard(file, notices));
+
+ let reported = 0;
+ let unreported = 0;
+ for (const shard of shards) {
+ if (shard.firstBreak === null) continue;
+ if (reported >= MAX_ITEMIZED_SHARDS) {
+ unreported++;
+ continue;
+ }
+ reported++;
+ emitDegradationNotice(notices, {
+ code: DEGRADATION_CODE.logChainBroken,
+ site: VERIFY_SITE,
+ path: shard.path,
+ detail: `line ${shard.firstBreak.line} ${breakDetail(shard.firstBreak.reason)}`,
+ });
+ }
+ if (unreported > 0) {
+ emitDegradationNotice(notices, {
+ code: DEGRADATION_CODE.logChainBroken,
+ site: VERIFY_SITE,
+ path: safeLogDir(vault),
+ detail:
+ `${unreported} further log shards do not link up and are not itemized ` +
+ `(${reported + unreported} broken of ${shards.length} verified)`,
+ });
+ }
+
+ return Object.freeze({
+ shards: Object.freeze(shards),
+ notices: Object.freeze(notices),
+ ok: notices.length === 0,
+ });
+}
+
+/** English for one break reason, for the notice and the CLI alike. */
+export function breakDetail(reason: LogChainBreakReason): string {
+ switch (reason) {
+ case LOG_CHAIN_BREAK_REASON.hashMismatch:
+ return "carries a hash its content does not match - the line was edited after it was written";
+ case LOG_CHAIN_BREAK_REASON.prevMismatch:
+ return "does not link to the line before it - a line between them was removed or reordered";
+ case LOG_CHAIN_BREAK_REASON.malformed:
+ return (
+ "is not a chainable row where the chain had already started - its links were stripped, " +
+ "and the next line's is no longer checkable"
+ );
+ }
+}
+
+/**
+ * Verify one shard's chain, in file order.
+ *
+ * At most one break is RECORDED per shard - the first - but the walk
+ * runs to the end so `chained`, `legacy` and `unparsed` describe the
+ * whole file. An operator deciding whether a shard is worth recovering
+ * needs both halves: where it broke, and how much of it is intact.
+ */
+function verifyShard(file: LogShardFile, notices: DegradationNotice[]): LogChainShardVerification {
+ const scan = scanJsonlRows(file.path);
+ if (!scan.readable) {
+ emitDegradationNotice(notices, {
+ code: DEGRADATION_CODE.logChainBroken,
+ site: VERIFY_SITE,
+ path: file.path,
+ detail:
+ `the shard exists but could not be read (${scan.failure ?? "no reason reported"}), ` +
+ "so no line in it was verified - an unverifiable history is not a clean one",
+ });
+ }
+
+ let chained = 0;
+ let legacy = 0;
+ let unparsed = 0;
+ let firstBreak: LogChainBreak | null = null;
+ /**
+ * What the next chained line's `prev` must be: the previous chained
+ * line's `h`, `null` at genesis, or `undefined` when the line before
+ * it was already reported and its successor's link is unknowable.
+ *
+ * `null` rather than `undefined` at the START of the shard is the
+ * difference between this chain and the lineage ledger's. That ledger
+ * compacts, so its first line legitimately names a predecessor that no
+ * longer exists and its head is exempt. The Brain log never compacts -
+ * a shard begins at its genesis line - so a first chained line naming a
+ * predecessor means the head of the file was cut off, which is exactly
+ * the tampering worth catching.
+ */
+ let previous: string | null | undefined = null;
+ let sawChained = false;
+
+ const breakAt = (line: number, reason: LogChainBreakReason): void => {
+ if (firstBreak === null) firstBreak = { line, reason };
+ };
+
+ for (const entry of scan.lines) {
+ const row = entry.row;
+ if (row === null) {
+ unparsed++;
+ breakAt(entry.lineNumber, LOG_CHAIN_BREAK_REASON.malformed);
+ // A line the parser cannot read breaks the adjacency the `prev`
+ // check relies on; the next chained line's link is unknowable
+ // rather than wrong, so it is not reported a second time.
+ previous = undefined;
+ continue;
+ }
+
+ const h = row[LOG_CHAIN_FIELDS.h];
+ if (typeof h !== "string" || h === "") {
+ legacy++;
+ // Legitimate history at the HEAD of a shard, a stripped line
+ // anywhere after it. See this module's docblock.
+ if (sawChained) breakAt(entry.lineNumber, LOG_CHAIN_BREAK_REASON.malformed);
+ previous = undefined;
+ continue;
+ }
+
+ const projection = chainableProjection(row);
+ if (projection === null) {
+ unparsed++;
+ breakAt(entry.lineNumber, LOG_CHAIN_BREAK_REASON.malformed);
+ previous = undefined;
+ continue;
+ }
+
+ chained++;
+ sawChained = true;
+ const recomputed = logChainHash(
+ projection.prev,
+ projection.ts,
+ projection.kind,
+ projection.payload,
+ );
+ if (recomputed !== h) {
+ // At most ONE finding per line: a tampered line would otherwise
+ // also fail its successor's `prev` check and report the same
+ // damage twice. `previous` still takes the stored hash, which is
+ // what the next line actually links to.
+ breakAt(entry.lineNumber, LOG_CHAIN_BREAK_REASON.hashMismatch);
+ } else if (previous !== undefined && projection.prev !== previous) {
+ breakAt(entry.lineNumber, LOG_CHAIN_BREAK_REASON.prevMismatch);
+ }
+ previous = h;
+ }
+
+ return Object.freeze({
+ path: file.path,
+ date: file.date,
+ shardId: file.shardId,
+ chained,
+ legacy,
+ unparsed,
+ firstBreak,
+ });
+}
+
+/** The four values a chain hash is computed over, or `null` when the row lacks them. */
+interface ChainableProjection {
+ readonly prev: string | null;
+ readonly ts: string;
+ readonly kind: string;
+ readonly payload: Readonly<Record<string, string | ReadonlyArray<string>>>;
+}
+
+/**
+ * Re-read a stored row as the exact value {@link logChainHash} was given
+ * when the row was written, or `null` when it is not that shape.
+ *
+ * Strict on purpose: `prev` must be present and be a string or `null`,
+ * and every payload value must be a string or an array of strings, which
+ * is the whole of what `renderJsonlLine` can emit. A row outside that
+ * shape cannot be rehashed, so reporting it as a hash MISMATCH would
+ * name the wrong condition - it is malformed, and the caller says so.
+ */
+function chainableProjection(row: Readonly<Record<string, unknown>>): ChainableProjection | null {
+ const prev = row[LOG_CHAIN_FIELDS.prev];
+ if (prev !== null && typeof prev !== "string") return null;
+ const ts = row["ts"];
+ const kind = row["kind"];
+ const payload = row["payload"];
+ if (typeof ts !== "string" || typeof kind !== "string") return null;
+ if (payload === null || typeof payload !== "object" || Array.isArray(payload)) return null;
+ const projected: Record<string, string | ReadonlyArray<string>> = {};
+ for (const [key, value] of Object.entries(payload as Record<string, unknown>)) {
+ if (typeof value === "string") {
+ projected[key] = value;
+ continue;
+ }
+ if (Array.isArray(value) && value.every((item) => typeof item === "string")) {
+ projected[key] = value as string[];
+ continue;
+ }
+ return null;
+ }
+ return { prev, ts, kind, payload: projected };
+}
+
+/**
+ * The log directory, or the vault root when the path builder refuses.
+ * A notice must name SOMETHING an operator can look at, and a builder
+ * that refuses has already been reported by its own caller.
+ */
+function safeLogDir(vault: string): string {
+ try {
+ return brainDirs(vault).log;
+ } catch {
+ return vault;
+ }
+}
diff --git a/src/core/brain/log-jsonl.ts b/src/core/brain/log-jsonl.ts
index 1665085d..a636e5f3 100644
--- a/src/core/brain/log-jsonl.ts
+++ b/src/core/brain/log-jsonl.ts
@@ -17,17 +17,43 @@
* lives in exactly one module. Malformed JSONL lines surface as
* `warnings` instead of aborting the read, matching `parseLogDay`'s
* tolerance contract.
+ *
+ * The per-shard hash chain (who-wrote-what, Task E) is invisible here by
+ * design: `coerceEntry` reads `ts`, `kind` and `payload` and nothing
+ * else, so a row's `prev` and `h` never reach a reader and a broken
+ * chain never withholds an event. Verification is a separate pass over
+ * the same files ({@link scanJsonlRows}, consumed by `log-chain.ts`).
*/
-import { existsSync, readdirSync, readFileSync } from "node:fs";
-import { join } from "node:path";
+import { readFileSync } from "node:fs";
+import {
+ listShardedFiles,
+ listSyncConflictFiles,
+ mergeShardedRows,
+ parseShardedName,
+ type LedgerShardGrammar,
+ type ShardedRow,
+} from "./ledger-shards.ts";
import { brainDirs, validateIsoDate } from "./paths.ts";
import { parseLogDayFile, type BrainLogEntry, type BrainLogParseWarning } from "./log.ts";
import { BRAIN_LOG_EVENT_KIND_SET, type BrainLogEventKind } from "./types.ts";
export interface ReadLogDayResult {
readonly entries: ReadonlyArray<BrainLogEntry>;
+ /**
+ * The shard id each entry in {@link entries} came from, at the same
+ * index; the empty string for the legacy un-sharded pair.
+ *
+ * A parallel array rather than a field on the entry, because
+ * `BrainLogEntry` is the shape the markdown parser, the JSONL parser
+ * and every writer already agree on, and a key that only one of the
+ * three could fill would be absent exactly where a reader needs it.
+ * The shard id IS the device id (see `logShardPath`), which is how the
+ * note-write reader answers "which machine wrote this" without a field
+ * in the payload.
+ */
+ readonly entryShardIds: ReadonlyArray<string>;
readonly source: "jsonl" | "markdown-fallback";
readonly warnings: ReadonlyArray<BrainLogParseWarning>;
}
@@ -47,19 +73,17 @@ export interface ReadLogDayResult {
// break the contract of the other surface.
const ISO_UTC_TS_RE = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z$/;
-// One log file name: `<date>.jsonl`, `<date>.md`, or the sharded
-// `<date>.<deviceId>.jsonl` / `.md`. Device ids are lowercase slugs
-// (see `resolveDeviceId`); Syncthing conflict copies and anything else
-// that does not match are NOT log shards.
-const LOG_FILE_RE = /^(\d{4}-\d{2}-\d{2})(?:\.([a-z0-9-]{1,32}))?\.(jsonl|md)$/;
-
/**
- * A Syncthing conflict copy is named `<stem>.sync-conflict-<stamp>.<ext>`,
- * so its middle segment can pass the shard-id shape. Named once because
- * both the recogniser that must REJECT it and the leftover reporter that
- * must FIND it key on the same marker.
+ * One log file name: `<date>.jsonl`, `<date>.md`, or the sharded
+ * `<date>.<deviceId>.jsonl` / `.md`. The grammar itself, the device-id
+ * slug and the sync-conflict exclusion live in `ledger-shards.ts`, which
+ * every append-only ledger in the vault now shares; this declaration is
+ * the log's own base and extensions and nothing more.
*/
-const SYNC_CONFLICT_SHARD_PREFIX = "sync-conflict";
+const LOG_GRAMMAR: LedgerShardGrammar = Object.freeze({
+ base: "\\d{4}-\\d{2}-\\d{2}",
+ extensions: Object.freeze(["jsonl", "md"]),
+});
/** The shape of one recognised `Brain/log/` daily file name. */
export interface ParsedLogFileName {
@@ -87,13 +111,9 @@ export interface ParsedLogFileName {
* the layout, rather than a third copy of the pattern.
*/
export function parseLogFileName(name: string): ParsedLogFileName | null {
- const m = LOG_FILE_RE.exec(name);
- if (m === null) return null;
- const shardId = m[2] ?? "";
- // Defensive: a hand-renamed Syncthing conflict copy could match the
- // shard-id shape; conflict copies are never log shards.
- if (shardId.startsWith(SYNC_CONFLICT_SHARD_PREFIX)) return null;
- return { date: m[1]!, shardId, ext: m[3] as "jsonl" | "md" };
+ const parsed = parseShardedName(name, LOG_GRAMMAR);
+ if (parsed === null) return null;
+ return { date: parsed.base, shardId: parsed.shardId, ext: parsed.ext as "jsonl" | "md" };
}
export interface LogShardFile extends ParsedLogFileName {
@@ -108,18 +128,13 @@ export interface LogShardFile extends ParsedLogFileName {
* of paying one `readdirSync` + sort per date.
*/
export function listLogShardFiles(vault: string): LogShardFile[] {
- const dir = brainDirs(vault).log;
- if (!existsSync(dir)) return [];
- const out: LogShardFile[] = [];
- for (const entry of readdirSync(dir, { withFileTypes: true }).toSorted((a, b) =>
- a.name.localeCompare(b.name),
- )) {
- if (!entry.isFile()) continue;
- const parsed = parseLogFileName(entry.name);
- if (parsed === null) continue;
- out.push({ ...parsed, path: join(dir, entry.name), name: entry.name });
- }
- return out;
+ return listShardedFiles(brainDirs(vault).log, LOG_GRAMMAR).map((file) => ({
+ date: file.base,
+ shardId: file.shardId,
+ ext: file.ext as "jsonl" | "md",
+ path: file.path,
+ name: file.name,
+ }));
}
/**
@@ -139,12 +154,7 @@ export function listLogDates(vault: string): string[] {
* for a manual union+dedup merge.
*/
export function listLogSyncConflicts(vault: string): string[] {
- const dir = brainDirs(vault).log;
- if (!existsSync(dir)) return [];
- return readdirSync(dir, { withFileTypes: true })
- .filter((e) => e.isFile() && e.name.includes(`.${SYNC_CONFLICT_SHARD_PREFIX}-`))
- .map((e) => join(dir, e.name))
- .toSorted();
+ return listSyncConflictFiles(brainDirs(vault).log);
}
/** Markdown log files (legacy + shards) for doctor's per-file lint. */
@@ -173,7 +183,9 @@ export function readLogDay(
): ReadLogDayResult {
const validDate = validateIsoDate(date);
const shards = (preloadedShards ?? listLogShardFiles(vault)).filter((f) => f.date === validDate);
- if (shards.length === 0) return { entries: [], source: "jsonl", warnings: [] };
+ if (shards.length === 0) {
+ return { entries: [], entryShardIds: [], source: "jsonl", warnings: [] };
+ }
// Group by shard id; per shard prefer .jsonl over .md.
const byShard = new Map<string, { jsonl?: LogShardFile; md?: LogShardFile }>();
@@ -183,12 +195,7 @@ export function readLogDay(
byShard.set(f.shardId, slot);
}
- interface Tagged {
- readonly entry: BrainLogEntry;
- readonly shardId: string;
- readonly line: number;
- }
- const tagged: Tagged[] = [];
+ const tagged: Array<ShardedRow<BrainLogEntry>> = [];
const warnings: BrainLogParseWarning[] = [];
let usedMarkdown = false;
@@ -196,33 +203,97 @@ export function readLogDay(
const slot = byShard.get(shardId)!;
if (slot.jsonl) {
const r = readJsonl(slot.jsonl.path);
- r.entries.forEach((entry, i) => tagged.push({ entry, shardId, line: i }));
+ r.entries.forEach((entry, i) => tagged.push({ value: entry, shardId, line: i }));
warnings.push(...r.warnings);
continue;
}
if (slot.md) {
usedMarkdown = true;
const r = parseLogDayFile(vault, validDate, slot.md.path);
- r.entries.forEach((entry, i) => tagged.push({ entry, shardId, line: i }));
+ r.entries.forEach((entry, i) => tagged.push({ value: entry, shardId, line: i }));
warnings.push(...r.warnings);
}
}
- tagged.sort((a, b) => {
- if (a.entry.timestamp !== b.entry.timestamp) {
- return a.entry.timestamp < b.entry.timestamp ? -1 : 1;
- }
- if (a.shardId !== b.shardId) return a.shardId < b.shardId ? -1 : 1;
- return a.line - b.line;
- });
-
+ // The merge orders by (timestamp, shard id, line) and returns values
+ // only, so the shard id rides inside the value to come out beside its
+ // entry at the same index.
+ const merged = mergeShardedRows(
+ tagged.map((row) => ({ ...row, value: { entry: row.value, shardId: row.shardId } })),
+ (row) => row.entry.timestamp,
+ );
return {
- entries: tagged.map((t) => t.entry),
+ entries: merged.map((row) => row.entry),
+ entryShardIds: merged.map((row) => row.shardId),
source: usedMarkdown ? "markdown-fallback" : "jsonl",
warnings,
};
}
+/**
+ * One non-blank line of a JSONL shard as the chain verifier sees it:
+ * where it sits in the file and what it parsed to, with `row: null` for
+ * a line that is not a JSON object.
+ *
+ * `lineNumber` is 1-based, because the number an operator needs is the
+ * one their editor shows them.
+ */
+export interface RawJsonlLine {
+ readonly lineNumber: number;
+ readonly row: Readonly<Record<string, unknown>> | null;
+}
+
+/** Every non-blank line of one shard, plus whether the bytes were obtained. */
+export interface RawJsonlScan {
+ /** False when the file could not be read; `lines` is then empty. */
+ readonly readable: boolean;
+ /** The read failure, verbatim, when there was one. */
+ readonly failure: string | null;
+ readonly lines: ReadonlyArray<RawJsonlLine>;
+}
+
+/**
+ * Read one JSONL shard WITHOUT coercing its rows into log entries.
+ *
+ * {@link readLogDay} exists to answer "what happened", so it drops every
+ * row it cannot turn into a `BrainLogEntry` and never sees the chain
+ * fields at all. The chain verifier's question is the opposite one -
+ * "what is in this file, and does it link up" - and a row the reader
+ * discarded is exactly the row it most needs to report. So the two share
+ * the file and nothing else: this scanner parses JSON and stops there.
+ *
+ * Never throws. An unreadable shard reports `readable: false` with the
+ * reason, because "not verified" is not "verified clean".
+ */
+export function scanJsonlRows(path: string): RawJsonlScan {
+ let text: string;
+ try {
+ text = readFileSync(path, "utf8");
+ } catch (err) {
+ const message = (err as NodeJS.ErrnoException).message ?? String(err);
+ return { readable: false, failure: message, lines: [] };
+ }
+ const lines: RawJsonlLine[] = [];
+ const raw = text.split(/\r?\n/);
+ for (let i = 0; i < raw.length; i++) {
+ const line = raw[i]!;
+ if (line.trim() === "") continue;
+ let parsed: unknown;
+ try {
+ parsed = JSON.parse(line);
+ } catch {
+ lines.push({ lineNumber: i + 1, row: null });
+ continue;
+ }
+ const isObject = parsed !== null && typeof parsed === "object" && !Array.isArray(parsed);
+ lines.push({
+ lineNumber: i + 1,
+ row: isObject ? (parsed as Record<string, unknown>) : null,
+ });
+ }
+ return { readable: true, failure: null, lines };
+}
+
interface ReadJsonlResult {
readonly entries: ReadonlyArray<BrainLogEntry>;
readonly warnings: ReadonlyArray<BrainLogParseWarning>;
diff --git a/src/core/brain/log.ts b/src/core/brain/log.ts
index ad4b5cee..fbe296fa 100644
--- a/src/core/brain/log.ts
+++ b/src/core/brain/log.ts
@@ -28,6 +28,14 @@
* `agent` one: the server-derived channel of the process that wrote it
* (`src/core/origin-channel.ts`). Events written before that shipped
* carry no such bullet and are never rewritten to add one.
+ *
+ * Every appended JSONL row also carries a per-shard hash chain
+ * ({@link LOG_CHAIN_FIELDS}, who-wrote-what Task E): once the log is the
+ * attribution record for every write, a line someone deleted or edited
+ * has to be detectable. The markdown twin is a derived rendering of the
+ * same events and is deliberately NOT chained - a human-editable view is
+ * the wrong thing to hold to a hash, and the JSONL sidecar is the
+ * machine-primary surface every reader already prefers.
*/
import { existsSync, mkdirSync, readFileSync } from "node:fs";
@@ -35,6 +43,7 @@ import { existsSync, mkdirSync, readFileSync } from "node:fs";
import lockfile from "proper-lockfile";
import { atomicWriteFileSync } from "../fs-atomic.ts";
+import { canonicalJson, sha256Hex } from "../integrity/digest.ts";
import {
brainDirsForWrite,
logPath,
@@ -42,7 +51,9 @@ import {
logShardPath,
validateIsoDate,
} from "./paths.ts";
-import { isValidDeviceId, resolveDeviceId } from "../config.ts";
+import { WRITE_LANE } from "./freeze-marker.ts";
+import { isValidDeviceId } from "../config.ts";
+import { resolveAppendShardId } from "./ledger-shards.ts";
import { ORIGIN_CHANNEL_FIELD, originChannelStamp } from "../origin-channel.ts";
import { BRAIN_LOG_EVENT_KIND, BRAIN_LOG_EVENT_KIND_SET, type BrainLogEventKind } from "./types.ts";
@@ -260,20 +271,13 @@ function acquireLogLock(logDir: string): () => void {
export interface AppendLogEventOptions {
/**
* Per-device shard id (Memory Integrity Suite). Defaults to
- * `resolveDeviceId()` from the device-local config; the empty string
- * forces the legacy un-sharded `<date>.jsonl` / `<date>.md` pair.
+ * {@link resolveAppendShardId}, which reads the device-local config and
+ * falls back to the empty string - the legacy un-sharded
+ * `<date>.jsonl` / `<date>.md` pair - when the config cannot be
+ * resolved. That fallback and the reasoning behind it now live in
+ * `ledger-shards.ts`, shared with every other append-only ledger.
*
- * ANY resolution failure falls back to the legacy pair - a missing HOME,
- * an unwritable config home, or a config file that is present but cannot
- * be read (`ConfigReadError`). This caller is the one that absorbs that
- * error, and it is deliberate rather than an oversight: appending is the
- * always-on write path behind every hook and every session-capture
- * event, so failing it turns one bad file mode into a dead session. The
- * fallback is also not a neutral value invented to look healthy - it is
- * the documented shard shape the `O2B_DEVICE_ID=""` opt-out selects, it
- * loses no data, and the log-dir lock still orders concurrent writers.
- * The condition itself is not swallowed anywhere: every OTHER caller of
- * `resolveDeviceId` propagates it, and the CLI reports it by name.
+ * Passing the empty string here forces the legacy pair explicitly.
*/
readonly deviceId?: string;
}
@@ -300,13 +304,7 @@ export function appendLogEvent(
}
deviceId = opts.deviceId;
} else {
- try {
- deviceId = resolveDeviceId();
- } catch {
- // Legacy un-sharded pair. See AppendLogEventOptions.deviceId for why
- // this one caller absorbs what every other caller propagates.
- deviceId = "";
- }
+ deviceId = resolveAppendShardId();
}
// Parse the timestamp once to extract date + HHMMSS deterministically.
// We deliberately do not accept Date objects: the caller controls the
@@ -315,7 +313,14 @@ export function appendLogEvent(
const ts = parseIsoUtc(event.timestamp);
const path = logShardPath(vault, ts.date, deviceId);
const jsonlPath = logShardJsonlPath(vault, ts.date, deviceId);
- const logDir = brainDirsForWrite(vault).log;
+ // The AUDIT lane (who-wrote-what, Task C). This appender is one of the
+ // two callers that skip the freeze check, and it is the reason the lane
+ // exists at all: `freeze`, `unfreeze` and `write-refused` are events
+ // about a frozen vault, so a freeze that silenced the log would erase
+ // the record of itself and of every write it refused. The identity
+ // assertion still runs - a log line landing in the wrong store is as
+ // wrong as a note landing there.
+ const logDir = brainDirsForWrite(vault, undefined, WRITE_LANE.audit).log;
const topLevelAgent = (event as { agent?: unknown }).agent;
const withAgent =
typeof topLevelAgent === "string" && typeof event.body["agent"] !== "string"
@@ -354,8 +359,14 @@ export function appendLogEvent(
// One row per event. The row is a deterministic projection of the
// markdown body so the markdown and JSONL representations describe
// the same event byte-for-byte after JSON.parse.
+ // The chain (Task E) costs nothing extra here: the shard's bytes are
+ // already in hand under the directory lock, so the link to the
+ // previous line is one backward scan of text this append had to read
+ // anyway. Holding the lock is also what makes the link CORRECT - two
+ // appenders reading the same head would otherwise write two lines
+ // claiming the same predecessor.
const existingJsonl = existsSync(jsonlPath) ? readFileSync(jsonlPath, "utf8") : "";
- const line = renderJsonlLine(diskEvent);
+ const line = renderJsonlLine(diskEvent, lastChainHash(existingJsonl));
const nextJsonl =
existingJsonl === "" ? `${line}\n` : `${existingJsonl.replace(/\s+$/, "")}\n${line}\n`;
atomicWriteFileSync(jsonlPath, nextJsonl);
@@ -426,24 +437,108 @@ function renderEventBlock(event: BrainLogEntry, hms: string): string {
}
/**
- * Render the JSONL projection of an event (Β§23, v0.10.8). The row
- * shape is `{ ts, kind, payload }` where `payload` is a one-to-one map
+ * Render the JSONL projection of an event (Β§23, v0.10.8; chained by
+ * who-wrote-what Task E). The row shape is
+ * `{ ts, kind, payload, prev, h }` where `payload` is a one-to-one map
* of the markdown body bullets. Array bullets become JSON arrays;
* scalar bullets become JSON strings. The function never sorts keys,
- * so byte-identical inputs produce byte-identical rows.
+ * so byte-identical inputs plus a byte-identical `prev` produce
+ * byte-identical rows.
+ *
+ * The chain fields come LAST so the projection the readers have always
+ * consumed still reads as the head of the row, and `readJsonl` ignores
+ * them entirely - the chain is an audit surface, never a read gate.
*/
-function renderJsonlLine(event: BrainLogEntry): string {
+function renderJsonlLine(event: BrainLogEntry, prev: string | null): string {
const payload: Record<string, string | ReadonlyArray<string>> = {};
for (const [key, value] of Object.entries(event.body)) {
payload[key] = value;
}
+ const ts = event.timestamp;
+ const kind: string = event.eventType;
return JSON.stringify({
- ts: event.timestamp,
- kind: event.eventType,
+ ts,
+ kind,
payload,
+ [LOG_CHAIN_FIELDS.prev]: prev,
+ [LOG_CHAIN_FIELDS.h]: logChainHash(prev, ts, kind, payload),
});
}
+// ----- The per-shard hash chain ---------------------------------------------
+
+/**
+ * The two chain-carrying keys of a JSONL log row, named once because
+ * three surfaces spell them: the renderer above, the head scanner
+ * below, and the verifier in `log-chain.ts`.
+ *
+ * They are the ONLY keys the chain adds. Everything else a row carries
+ * is hashed, so a field a future writer adds to the projection is
+ * covered by the chain automatically.
+ */
+export const LOG_CHAIN_FIELDS = Object.freeze({
+ /** The preceding chained line's {@link LOG_CHAIN_FIELDS.h}, `null` at genesis. */
+ prev: "prev",
+ /** This line's chain hash. */
+ h: "h",
+} as const);
+
+/**
+ * The chain hash a row carries: sha256 over the canonical JSON of its
+ * link plus its whole projection.
+ *
+ * `prev` is inside the hash rather than beside it, which is what makes
+ * the structure a chain: editing any earlier line changes every later
+ * hash, so a tampered history cannot be re-linked without rewriting the
+ * whole shard from the edit forward.
+ *
+ * Defined here rather than in `log-chain.ts` even though the verifier is
+ * that module's subject: the appender needs it, `log-chain.ts` needs the
+ * shard listing from `log-jsonl.ts`, and `log-jsonl.ts` needs this
+ * module's parser - so a hash living with the verifier would close an
+ * import cycle. `log-chain.ts` re-exports it, so callers reading about
+ * the chain find it where the design puts it.
+ */
+export function logChainHash(
+ prev: string | null,
+ ts: string,
+ kind: string,
+ payload: Readonly<Record<string, string | ReadonlyArray<string>>>,
+): string {
+ return sha256Hex(canonicalJson({ prev, ts, kind, payload }));
+}
+
+/**
+ * The chain head of a shard already read into memory: the `h` of the
+ * LAST line that carries one, or `null` when no line does.
+ *
+ * Scanned from the end and stopped at the first hit, so an append costs
+ * one JSON parse rather than one per line of the day. Lines that carry
+ * no `h` are the pre-chain history of a vault that upgraded mid-day;
+ * they are skipped rather than treated as a break, and the first chained
+ * line written after them anchors the shard's chain with `prev: null`.
+ * A line that will not parse is skipped for the same reason - the
+ * appender's job is to link to the newest link that exists, and naming
+ * the damage is the verifier's.
+ */
+function lastChainHash(jsonl: string): string | null {
+ const lines = jsonl.split(/\r?\n/);
+ for (let i = lines.length - 1; i >= 0; i--) {
+ const line = lines[i]!;
+ if (line.trim() === "") continue;
+ let parsed: unknown;
+ try {
+ parsed = JSON.parse(line);
+ } catch {
+ continue;
+ }
+ if (parsed === null || typeof parsed !== "object") continue;
+ const h = (parsed as Record<string, unknown>)[LOG_CHAIN_FIELDS.h];
+ if (typeof h === "string" && h !== "") return h;
+ }
+ return null;
+}
+
// ----- Bullet block parser --------------------------------------------------
interface ParseBulletResult {
diff --git a/src/core/brain/metrics.ts b/src/core/brain/metrics.ts
index 86178e61..dce09039 100644
--- a/src/core/brain/metrics.ts
+++ b/src/core/brain/metrics.ts
@@ -1,9 +1,12 @@
/**
* Dashboard-ready metrics sink (link-recall-intelligence, Task 1).
*
- * One append-only JSONL file per surface under `Brain/metrics/` -
- * the stable on-disk contract the upcoming dashboard plugin reads
- * without importing OSB internals. Every record is one line:
+ * One append-only JSONL file per surface per device under
+ * `Brain/metrics/<surface>[.<deviceId>].jsonl` - the stable on-disk
+ * contract the upcoming dashboard plugin reads without importing Open
+ * Second Brain internals. A reader merges every device's shard of a
+ * surface (who-wrote-what, Task B); the bare name is the shard with the
+ * empty id. Every record is one line:
*
* {"schema":"o2b.metrics.v1","surface":"...","run_at":"...","payload":{...}}
*
@@ -19,8 +22,15 @@
* consumers in `docs/metrics.md`.
*/
-import { appendFileSync, existsSync, mkdirSync, readdirSync, readFileSync } from "node:fs";
+import { appendFileSync, mkdirSync, readFileSync } from "node:fs";
import { dirname, join } from "node:path";
+import {
+ listShardedFiles,
+ literalBase,
+ resolveAppendShardId,
+ shardedFileName,
+ type LedgerShardGrammar,
+} from "./ledger-shards.ts";
import { assertVaultIdentityForWrite } from "./vault-identity.ts";
/** On-disk schema version stamped on every metric record. */
@@ -29,6 +39,9 @@ export const METRICS_SCHEMA_VERSION = "o2b.metrics.v1";
/** Surface names: lowercase snake_case, max 64 chars. */
const SURFACE_RE = /^[a-z][a-z0-9_]{0,63}$/;
+/** Extension of every metric shard. */
+const METRICS_EXT = "jsonl";
+
/** ISO-8601 UTC timestamp shape (second or millisecond precision). */
const ISO_RE = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,3})?Z$/;
@@ -61,14 +74,44 @@ export interface ListMetricsFilter {
readonly limit?: number;
}
-function metricsDir(vault: string): string {
+/**
+ * The directory every metric shard lives in. Exported so the sweep that
+ * reports Syncthing conflict copies names this ledger's directory through
+ * the module that owns it, rather than re-deriving the path.
+ */
+export function metricsDir(vault: string): string {
return join(vault, "Brain", "metrics");
}
-function surfacePath(vault: string, surface: string): string {
- return join(metricsDir(vault), `${surface}.jsonl`);
+/**
+ * This device's shard for one surface: `<surface>[.<deviceId>].jsonl`.
+ * The empty shard id is the legacy un-sharded name, which every read
+ * still merges and no migration renames.
+ */
+function surfacePath(
+ vault: string,
+ surface: string,
+ shardId: string = resolveAppendShardId(),
+): string {
+ return join(metricsDir(vault), shardedFileName(surface, shardId, METRICS_EXT));
+}
+
+/**
+ * The name layout of ONE surface's shards. Surface names are validated
+ * `[a-z][a-z0-9_]*` and so carry no dot, but they go in as a literal all
+ * the same: the base is a value, not a shape, and escaping it is what
+ * keeps `index_v2.jsonl` from ever parsing as a shard of `index`.
+ */
+function surfaceGrammar(surface: string): LedgerShardGrammar {
+ return { base: literalBase(surface), extensions: [METRICS_EXT] };
}
+/** The layout of the whole directory, for discovering surfaces. */
+const ANY_SURFACE_GRAMMAR: LedgerShardGrammar = Object.freeze({
+ base: "[a-z][a-z0-9_]{0,63}",
+ extensions: Object.freeze([METRICS_EXT]),
+});
+
function assertSurface(surface: string): void {
if (!SURFACE_RE.test(surface)) {
throw new MetricSurfaceError(
@@ -112,13 +155,12 @@ export function listMetrics(vault: string, filter: ListMetricsFilter = {}): Metr
assertSurface(filter.surface);
surfaces = [filter.surface];
} else {
- const dir = metricsDir(vault);
- if (!existsSync(dir)) return [];
- surfaces = readdirSync(dir)
- .filter((f) => f.endsWith(".jsonl"))
- .map((f) => f.slice(0, -".jsonl".length))
- .filter((s) => SURFACE_RE.test(s))
- .toSorted();
+ // Every surface that has at least one shard, sharded or not. The
+ // grammar strips a device suffix, so one surface written by three
+ // devices is discovered once.
+ surfaces = [
+ ...new Set(listShardedFiles(metricsDir(vault), ANY_SURFACE_GRAMMAR).map((f) => f.base)),
+ ].toSorted();
}
const out: Array<{ record: MetricRecord; seq: number }> = [];
@@ -141,29 +183,46 @@ export function listMetrics(vault: string, filter: ListMetricsFilter = {}): Metr
return filter.limit !== undefined ? records.slice(0, Math.max(0, filter.limit)) : records;
}
+/**
+ * One surface's records across every device shard, in (shard id, line)
+ * order. The shard id orders the merge rather than the file name, so the
+ * legacy un-sharded file - the shard with the empty id - always leads,
+ * and two devices agree on the sequence whatever order Syncthing
+ * delivered their files in.
+ */
function readSurface(vault: string, surface: string): MetricRecord[] {
- const path = surfacePath(vault, surface);
- if (!existsSync(path)) return [];
+ const shards = listShardedFiles(metricsDir(vault), surfaceGrammar(surface)).toSorted((a, b) =>
+ a.shardId < b.shardId ? -1 : a.shardId > b.shardId ? 1 : 0,
+ );
const out: MetricRecord[] = [];
- for (const line of readFileSync(path, "utf8").split("\n")) {
- if (line.trim().length === 0) continue;
+ for (const shard of shards) {
+ let text: string;
try {
- const parsed: unknown = JSON.parse(line);
- if (
- parsed !== null &&
- typeof parsed === "object" &&
- !Array.isArray(parsed) &&
- typeof (parsed as { schema?: unknown }).schema === "string" &&
- typeof (parsed as { surface?: unknown }).surface === "string" &&
- typeof (parsed as { run_at?: unknown }).run_at === "string" &&
- (parsed as { payload?: unknown }).payload !== null &&
- typeof (parsed as { payload?: unknown }).payload === "object" &&
- !Array.isArray((parsed as { payload?: unknown }).payload)
- ) {
- out.push(parsed as MetricRecord);
- }
+ text = readFileSync(shard.path, "utf8");
} catch {
- // Fail-soft: a torn line never breaks the metrics read.
+ // Fail-soft: an unreadable shard never breaks the metrics read.
+ continue;
+ }
+ for (const line of text.split("\n")) {
+ if (line.trim().length === 0) continue;
+ try {
+ const parsed: unknown = JSON.parse(line);
+ if (
+ parsed !== null &&
+ typeof parsed === "object" &&
+ !Array.isArray(parsed) &&
+ typeof (parsed as { schema?: unknown }).schema === "string" &&
+ typeof (parsed as { surface?: unknown }).surface === "string" &&
+ typeof (parsed as { run_at?: unknown }).run_at === "string" &&
+ (parsed as { payload?: unknown }).payload !== null &&
+ typeof (parsed as { payload?: unknown }).payload === "object" &&
+ !Array.isArray((parsed as { payload?: unknown }).payload)
+ ) {
+ out.push(parsed as MetricRecord);
+ }
+ } catch {
+ // Fail-soft: a torn line never breaks the metrics read.
+ }
}
}
return out;
diff --git a/src/core/brain/notes/create-note.ts b/src/core/brain/notes/create-note.ts
index 6fc56357..bfa5793e 100644
--- a/src/core/brain/notes/create-note.ts
+++ b/src/core/brain/notes/create-note.ts
@@ -74,6 +74,7 @@ import {
renderNoteTemplate,
type NoteTemplateVariables,
} from "./note-template.ts";
+import { NOTE_WRITE_OP, recordNoteWrite } from "./write-record.ts";
/** Machine-readable reason a {@link createNote} call was refused. */
export type CreateNoteErrorCode =
@@ -137,6 +138,14 @@ export interface CreateNoteInput {
readonly template?: string;
/** Variables the template may reference; requires `template`. */
readonly templateVariables?: NoteTemplateVariables;
+ /**
+ * Config file that names the writing agent, for the note-write record
+ * (who-wrote-what, Task A). Absent falls back to the same discovery
+ * every other Brain writer uses; a caller that KNOWS which config it
+ * is running under passes it, so the record names the agent the caller
+ * is, not the one the machine default happens to name.
+ */
+ readonly configPath?: string;
}
/** What a {@link createNote} call actually did. */
@@ -148,9 +157,30 @@ export interface CreatedNoteResult {
readonly path: string;
readonly outcome: "created";
readonly created: true;
+ /**
+ * Id of the `note-write` event that attributes this write, or null when
+ * the event could not be appended (who-wrote-what, Task A).
+ *
+ * The bytes land first and the event is appended second, so a log
+ * failure costs the audit line and never the note. `null` is therefore
+ * a real state a caller has to be able to see, and it never arrives
+ * alone: {@link audit_reason} names what went wrong.
+ */
+ readonly write_id: string | null;
+ /** Why {@link write_id} is null. Absent when it is not. */
+ readonly audit_reason?: string;
}
-/** An occupied target left exactly as it was, under `ifExists: "skip"`. */
+/**
+ * An occupied target left exactly as it was, under `ifExists: "skip"`.
+ *
+ * Deliberately WITHOUT a `write_id`: a skip authored no bytes, so there
+ * is no write to attribute and nothing a revert could undo. Carrying
+ * `write_id: null` here would spell "the audit line was lost" for a call
+ * that never had one to lose - the same conflation between "nothing
+ * happened" and "something failed" the `outcome` discriminant exists to
+ * prevent.
+ */
export interface SkippedNoteResult {
/** Vault-relative POSIX path of the note that was left alone. */
readonly path: string;
@@ -533,5 +563,17 @@ export function createNote(vault: string, input: CreateNoteInput): CreateNoteRes
throw err;
}
- return { path: relPath, outcome: "created", created: true };
+ // The bytes are on disk. Record the write LAST and never let the
+ // recording fail it: `recordNoteWrite` returns its failure instead of
+ // throwing, and the reason rides out on the result rather than being
+ // swallowed here (who-wrote-what, Task A). A create replaces nothing,
+ // so there is no before-image to store and `hash_before` is `absent`.
+ const receipt = recordNoteWrite(vault, {
+ op: NOTE_WRITE_OP.create,
+ target: relPath,
+ before: null,
+ after: { bytes: formatFrontmatter(frontmatter, body) },
+ ...(input.configPath !== undefined ? { configPath: input.configPath } : {}),
+ });
+ return { path: relPath, outcome: "created", created: true, ...receipt };
}
diff --git a/src/core/brain/notes/revert.ts b/src/core/brain/notes/revert.ts
new file mode 100644
index 00000000..97feb011
--- /dev/null
+++ b/src/core/brain/notes/revert.ts
@@ -0,0 +1,755 @@
+/**
+ * Per-agent / per-session note revert (who-wrote-what, Task D /
+ * t_924129c5).
+ *
+ * The note-write record answers "who wrote that, and what did it say
+ * before". This module is the other half: taking it back. It is
+ * plan-seal-apply over the `note-write` events, the same shape
+ * `src/core/state/migrate.ts` uses for state relocation, because the
+ * operator has to be able to READ what a revert is about to do before it
+ * does it.
+ *
+ * ## Refuse on doubt
+ *
+ * A revert reaches into files other writers share, and there is no
+ * three-way merge here by design (`docs/brainstorm/who-wrote-what/
+ * design.md`, out of scope). So every target the selected writes touched
+ * resolves to exactly one of three things and is REPORTED either way:
+ *
+ * - `restore` - put back the before-image of the oldest selected write;
+ * - `delete` - the selected writes brought the note into existence and
+ * nothing wrote it before, so undoing them removes it;
+ * - `refuse` - with a named reason from {@link NOTE_REVERT_REFUSAL}.
+ *
+ * A refused target is never touched and never dropped from the plan: the
+ * digest covers refusals too, so an operator who applies a digest applies
+ * the plan they read, including the parts of it that will not run.
+ *
+ * ## The seal
+ *
+ * {@link planNoteRevert} returns a `digest` over the selector and the
+ * entries - NOT over `planned_at`, so the same vault in the same state
+ * plans to the same digest twice and an operator can re-read a plan
+ * before applying it. {@link applyNoteRevert} re-plans from scratch and
+ * refuses `digest_mismatch` before any byte moves when the vault changed
+ * under the operator. That is the whole concurrency story: nothing is
+ * locked between the two calls, and the digest is what notices.
+ *
+ * ## Why the apply is one gated block
+ *
+ * Every restored and deleted target runs inside one
+ * {@link withDestructiveSnapshot} call, so a revert that half-succeeds
+ * still has ONE recovery point covering the state before all of it. The
+ * removal lives lexically inside the gate's argument list, which is also
+ * what the destructive-site census reads.
+ */
+
+import { existsSync, mkdirSync, readFileSync, unlinkSync } from "node:fs";
+import { dirname, join } from "node:path";
+
+import { atomicWriteFileSync } from "../../fs-atomic.ts";
+import { canonicalJson, sha256Hex } from "../../integrity/digest.ts";
+import type { RecoverabilityVerdict } from "../gates/recoverability.ts";
+import type { BrainLogParseWarning } from "../log.ts";
+import { BRAIN_ROOT_REL, ensureInsideVault, writeImagePath } from "../paths.ts";
+import { withDestructiveSnapshot } from "../snapshot-gate.ts";
+import { isoSecond } from "../time.ts";
+import { BRAIN_SNAPSHOT_REASON } from "../types.ts";
+import { assertVaultIdentityForWrite } from "../vault-identity.ts";
+import { listNoteWrites, type NoteWriteRecord } from "./write-log.ts";
+import {
+ NOTE_WRITE_NO_PRIOR,
+ NOTE_WRITE_OP,
+ recordNoteWrite,
+ storeBeforeImage,
+ type NoteWriteReceipt,
+} from "./write-record.ts";
+
+/** What a plan says will happen to one target. */
+export const NOTE_REVERT_ACTION = Object.freeze({
+ /** Put the before-image of the oldest selected write back. */
+ restore: "restore",
+ /** Remove the note the selected writes created. */
+ delete: "delete",
+ /** Touch nothing, and say why through {@link NOTE_REVERT_REFUSAL}. */
+ refuse: "refuse",
+} as const);
+
+export type NoteRevertAction = (typeof NOTE_REVERT_ACTION)[keyof typeof NOTE_REVERT_ACTION];
+
+/**
+ * Why one target is refused. Closed, and every member is a fact about
+ * the vault rather than a failure of this module.
+ */
+export const NOTE_REVERT_REFUSAL = Object.freeze({
+ /**
+ * The bytes on disk are not the ones the newest selected write left -
+ * somebody wrote the target afterwards, or it is gone when it should
+ * be there. Reverting would destroy that unrecorded work.
+ */
+ drift: "drift",
+ /**
+ * A write this selector did NOT select sits between the oldest and the
+ * newest selected write on this target, in the merged total order
+ * (timestamp, shard id, line) the reader already yields. Undoing the
+ * outer pair would silently undo the middle one too.
+ *
+ * Same-second ties are decided by that order too, because line order
+ * inside one shard IS append order. Only a tie ACROSS shards is
+ * interleaved on doubt: there the merge falls back to the shard id,
+ * which is a name and not a clock. See {@link interleaves}.
+ */
+ interleaved: "interleaved",
+ /**
+ * The bytes a restore needs are not in the before-image store - pruned
+ * by retention, or never written. The hash proves the write happened;
+ * only the image can undo it.
+ */
+ imageMissing: "image-missing",
+ /**
+ * The current bytes of the target cannot be read at all, so no verdict
+ * about drift is possible. "I could not tell" must never resolve to
+ * "revert it".
+ */
+ unrecorded: "unrecorded",
+ /**
+ * The target already holds exactly what this revert would produce -
+ * the selected writes put it back themselves, or a previous revert
+ * already ran. Nothing to take back, and saying so is not the same
+ * answer as a restore that rewrites identical bytes and logs a write.
+ */
+ alreadyReverted: "already-reverted",
+ /**
+ * The recorded target is not a path inside this vault: a corrupt log
+ * line, a hand-appended one, a crafted one. Distinct from
+ * `unrecorded`, which is a fact about BYTES that could not be read at
+ * a path this vault owns; this is a fact about the log, and no revert
+ * of such a target could ever be safe.
+ */
+ targetInvalid: "target-invalid",
+} as const);
+
+export type NoteRevertRefusal = (typeof NOTE_REVERT_REFUSAL)[keyof typeof NOTE_REVERT_REFUSAL];
+
+/** Membership list, in declaration order. */
+export const NOTE_REVERT_REFUSALS: ReadonlyArray<NoteRevertRefusal> = Object.freeze(
+ Object.values(NOTE_REVERT_REFUSAL),
+);
+
+/**
+ * Why a whole revert call is refused, as opposed to one target of it.
+ * Each is thrown as a {@link NoteRevertError} carrying the code, so a CLI
+ * or MCP surface reports the reason by name rather than by message text.
+ */
+export const NOTE_REVERT_ERROR = Object.freeze({
+ /** No `agent`, `device` or `path`: a time window alone selects the vault. */
+ unboundedSelector: "unbounded_selector",
+ /** The sealed plan no longer describes the vault. */
+ digestMismatch: "digest_mismatch",
+ /** Every entry is a refusal; there is nothing an apply could do. */
+ nothingToApply: "nothing_to_apply",
+} as const);
+
+export type NoteRevertErrorCode = (typeof NOTE_REVERT_ERROR)[keyof typeof NOTE_REVERT_ERROR];
+
+/** A revert refused as a whole, with the code a caller narrows on. */
+export class NoteRevertError extends Error {
+ readonly code: NoteRevertErrorCode;
+ /** The digest the caller supplied, on a `digest_mismatch` only. */
+ readonly expected?: string;
+ /** The digest the re-plan produced, on a `digest_mismatch` only. */
+ readonly actual?: string;
+
+ constructor(
+ code: NoteRevertErrorCode,
+ message: string,
+ digests?: { readonly expected: string; readonly actual: string },
+ ) {
+ super(message);
+ this.name = "NoteRevertError";
+ this.code = code;
+ if (digests !== undefined) {
+ this.expected = digests.expected;
+ this.actual = digests.actual;
+ }
+ }
+}
+
+/**
+ * Which recorded writes a revert is about.
+ *
+ * At least one of `agent`, `device` or `path` is required: a selector
+ * that only bounds TIME selects every write every agent on every machine
+ * made in a window, which is a rollback of the vault wearing a revert's
+ * clothes. `o2b brain rollback` is the verb for that, and it takes a
+ * snapshot the operator chose.
+ */
+export interface NoteRevertSelector {
+ /** Exact agent identity that recorded the write. */
+ readonly agent?: string;
+ /** Exact device id; the empty string is the legacy un-sharded log. */
+ readonly device?: string;
+ /** Exact vault-relative target path. */
+ readonly path?: string;
+ /** Inclusive lower bound: an ISO date or an ISO-8601 UTC timestamp. */
+ readonly since?: string;
+ /** Inclusive upper bound, same two spellings. */
+ readonly until?: string;
+}
+
+/** What the plan says about one target. */
+export interface NoteRevertEntry {
+ /** Vault-relative POSIX path of the note. */
+ readonly target: string;
+ readonly action: NoteRevertAction;
+ /** Present exactly when {@link action} is `refuse`. */
+ readonly reason?: NoteRevertRefusal;
+ /** The selected write ids on this target, oldest first. */
+ readonly writes: ReadonlyArray<string>;
+ /**
+ * sha256 of the bytes on disk now, or {@link NOTE_WRITE_NO_PRIOR} when
+ * there is no file, or {@link NOTE_REVERT_HASH_UNREADABLE} when the
+ * bytes could not be read at all.
+ */
+ readonly hash_now: string;
+ /**
+ * sha256 the target would hold after the revert, or
+ * {@link NOTE_WRITE_NO_PRIOR} when the revert removes it.
+ */
+ readonly hash_to: string;
+}
+
+/**
+ * What `hash_now` says when the target exists in some form and its bytes
+ * cannot be read.
+ *
+ * A third literal rather than reusing {@link NOTE_WRITE_NO_PRIOR},
+ * because "there is no file here" and "there is something here I could
+ * not read" are different facts, and reporting the second as the first
+ * is exactly the misleading silence the refusal beside it exists to
+ * prevent.
+ */
+export const NOTE_REVERT_HASH_UNREADABLE = "unreadable";
+
+/** A sealed revert plan. */
+export interface NoteRevertPlan {
+ /** The selector as it was applied, with absent fields omitted. */
+ readonly selector: NoteRevertSelector;
+ /** One entry per target the selected writes touched, sorted by target. */
+ readonly entries: ReadonlyArray<NoteRevertEntry>;
+ /** `sha256Hex(canonicalJson({ selector, entries }))`. */
+ readonly digest: string;
+ /** ISO-8601 UTC second the plan was made. NOT covered by the digest. */
+ readonly planned_at: string;
+ /**
+ * Every parse warning the log days behind this plan reported. A day
+ * whose JSONL lost a line is a day whose write history is incomplete,
+ * and an operator deciding what to revert has to be told that.
+ */
+ readonly warnings: ReadonlyArray<BrainLogParseWarning>;
+}
+
+/** How one applied target was recorded back into the write ledger. */
+export interface NoteRevertRecorded {
+ readonly target: string;
+ /** The `note-write` id of the revert, or null when it was not recorded. */
+ readonly write_id: string | null;
+ /** Present exactly when {@link write_id} is null. */
+ readonly audit_reason?: string;
+}
+
+/** What one apply did. */
+/** One target the apply reached and could not complete, and why. */
+export interface NoteRevertFailure {
+ /** Vault-relative POSIX path of the note. */
+ readonly target: string;
+ /** The error's own message; a machine code here would be an invention. */
+ readonly reason: string;
+}
+
+export interface NoteRevertApplyResult {
+ /** The recovery point the whole apply ran behind. */
+ readonly snapshot: { readonly run_id: string; readonly path: string };
+ /** Entries whose bytes moved, in plan order. */
+ readonly applied: ReadonlyArray<NoteRevertEntry>;
+ /**
+ * Entries nothing touched: the plan's own refusals, plus any target
+ * whose before-image failed verification at apply time.
+ */
+ readonly refused: ReadonlyArray<NoteRevertEntry>;
+ /** One row per applied target, naming its `revert` write id. */
+ readonly recorded: ReadonlyArray<NoteRevertRecorded>;
+ /**
+ * Entries the apply reached and could not carry out, for a reason no
+ * plan could have predicted - an unwritable directory, an I/O error, a
+ * target replaced under the apply. A third bucket rather than a
+ * refusal, because a refusal is a fact about the vault the plan
+ * already knew and this is a failure of this run; and a bucket rather
+ * than a throw, because one failing entry must not lose the entries
+ * after it, which would then appear in neither `applied` nor
+ * `refused`.
+ */
+ readonly failed: ReadonlyArray<NoteRevertFailure>;
+ /**
+ * What the recovery point is worth for what this apply reached. A
+ * note under `Brain/` and a note outside it are covered differently,
+ * and reporting the archive path with no verdict beside it reads as
+ * full coverage to every caller.
+ */
+ readonly recoverability: RecoverabilityVerdict;
+}
+
+/** Injected clock, shared by both entry points. */
+export interface PlanNoteRevertOptions {
+ readonly now?: Date;
+}
+
+/** How an apply attributes the `revert` writes it records. */
+export interface ApplyNoteRevertOptions extends PlanNoteRevertOptions {
+ /** Caller-asserted identity; defaults to the resolved agent name. */
+ readonly agent?: string;
+ /** Config file that names the writing agent, threaded to the record. */
+ readonly configPath?: string;
+}
+
+/** The selector fields that bound a revert to something smaller than the vault. */
+const BOUNDING_FIELDS = Object.freeze(["agent", "device", "path"] as const);
+
+/** Prefix that puts a target inside the Brain tree. */
+const BRAIN_TREE_PREFIX = `${BRAIN_ROOT_REL}/`;
+
+/** The bytes at a target, or the named reason there are none to hash. */
+type CurrentBytes =
+ | { readonly kind: "bytes"; readonly bytes: string }
+ | { readonly kind: "absent" }
+ | { readonly kind: "unreadable" };
+
+/**
+ * Read the target as it is now.
+ *
+ * `ENOENT` is the one error that means "no file here"; every other
+ * failure - a directory at the path, a permission wall, an I/O error -
+ * is `unreadable`, because a plan that cannot see the bytes cannot judge
+ * whether reverting them destroys somebody's work.
+ */
+function readCurrent(abs: string): CurrentBytes {
+ try {
+ return { kind: "bytes", bytes: readFileSync(abs, "utf8") };
+ } catch (err) {
+ return (err as NodeJS.ErrnoException).code === "ENOENT"
+ ? { kind: "absent" }
+ : { kind: "unreadable" };
+ }
+}
+
+/** The digest of what is on disk now, in the entry's vocabulary. */
+function hashOf(current: CurrentBytes): string {
+ if (current.kind === "bytes") return sha256Hex(current.bytes);
+ return current.kind === "absent" ? NOTE_WRITE_NO_PRIOR : NOTE_REVERT_HASH_UNREADABLE;
+}
+
+/** The selector with absent fields dropped, so the digest is stable. */
+function normaliseSelector(selector: NoteRevertSelector): NoteRevertSelector {
+ return {
+ ...(selector.agent !== undefined ? { agent: selector.agent } : {}),
+ ...(selector.device !== undefined ? { device: selector.device } : {}),
+ ...(selector.path !== undefined ? { path: selector.path } : {}),
+ ...(selector.since !== undefined ? { since: selector.since } : {}),
+ ...(selector.until !== undefined ? { until: selector.until } : {}),
+ };
+}
+
+/** Refuse a selector that names nobody and nothing. */
+function assertBounded(selector: NoteRevertSelector): void {
+ if (BOUNDING_FIELDS.some((field) => selector[field] !== undefined)) return;
+ throw new NoteRevertError(
+ NOTE_REVERT_ERROR.unboundedSelector,
+ `a revert selector must name at least one of ${BOUNDING_FIELDS.join(", ")}; a time window ` +
+ "alone selects every write by every agent on every device, which is a vault rollback - " +
+ "use o2b brain rollback for that",
+ );
+}
+
+/** One refusal entry, so the four call sites cannot spell it differently. */
+function refuse(
+ target: string,
+ writes: ReadonlyArray<string>,
+ reason: NoteRevertRefusal,
+ hashNow: string,
+ hashTo: string,
+): NoteRevertEntry {
+ return {
+ target,
+ action: NOTE_REVERT_ACTION.refuse,
+ reason,
+ writes,
+ hash_now: hashNow,
+ hash_to: hashTo,
+ };
+}
+
+/**
+ * Whether the store holds the image a restore needs.
+ *
+ * `writeImagePath` validates the digest shape, because it reaches this
+ * module from a log payload an operator may have hand-edited; a digest
+ * it rejects is an image this vault does not have, which is the same
+ * answer as a missing file.
+ */
+function imageAvailable(vault: string, sha256: string): boolean {
+ try {
+ return existsSync(writeImagePath(vault, sha256));
+ } catch {
+ return false;
+ }
+}
+
+/**
+ * Whether a write nobody selected sits inside the selected window.
+ *
+ * The window is measured in the MERGED TOTAL ORDER `listNoteWrites`
+ * already yields - `readLogDay` orders by (timestamp, shard id, line),
+ * and line order inside one shard IS the order the appends landed - so
+ * "between" is a position, not a timestamp comparison. That matters
+ * because timestamps are second-precision: three writes in one second
+ * are indistinguishable by clock and perfectly ordered by line.
+ *
+ * The one place the position is NOT evidence is a same-second tie across
+ * shards. There the merge falls back to the shard id, which is a name
+ * and not a clock: two devices that wrote in the same second could have
+ * written in either order, and the order shown is alphabetical. So a
+ * non-selected write that shares a second with a selected write is
+ * trusted only when it shares that write's SHARD; otherwise it is
+ * interleaved, which is the refuse-on-doubt half of the rule.
+ *
+ * This is deliberately narrower than "any same-second write is
+ * interleaved", which is what this rule used to say. That reading
+ * refused a create and an update a second apart on one machine - an
+ * order the log proves - and an operator whose whole vault lives on one
+ * device could never revert anything two writes had touched inside a
+ * second.
+ */
+function interleaves(
+ selected: ReadonlyArray<NoteWriteRecord>,
+ universe: ReadonlyArray<NoteWriteRecord>,
+): boolean {
+ const oldest = selected[0]!;
+ const newest = selected[selected.length - 1]!;
+ const selectedIds = new Set(selected.map((w) => w.write_id));
+ const first = universe.findIndex((w) => w.write_id === oldest.write_id);
+ const last = universe.findIndex((w) => w.write_id === newest.write_id);
+
+ return universe.some((w, index) => {
+ if (selectedIds.has(w.write_id)) return false;
+ // Strictly between the two ends in the merged order. A write with a
+ // timestamp strictly inside the window lands here too, because the
+ // merge sorts on the timestamp first.
+ if (index > first && index < last) return true;
+ if (w.timestamp < oldest.timestamp || w.timestamp > newest.timestamp) return false;
+ // Outside the positional window but inside the same second as one of
+ // its ends: trust the position only if the tie is within one shard.
+ // A tie against nothing cannot happen (a strictly-interior timestamp
+ // is already positionally interior), and if it ever does, doubt wins.
+ const tied = selected.filter((s) => s.timestamp === w.timestamp);
+ return tied.length === 0 || tied.some((s) => s.device !== w.device);
+ });
+}
+
+/**
+ * Resolve one target, applying the design's rules in the order they are
+ * stated: what cannot be judged, then what would destroy unrecorded
+ * work, then what would undo somebody else's write, then what is already
+ * done, and only then the two actions.
+ */
+function planTarget(
+ vault: string,
+ target: string,
+ selected: ReadonlyArray<NoteWriteRecord>,
+ universe: ReadonlyArray<NoteWriteRecord>,
+): NoteRevertEntry {
+ const oldest = selected[0]!;
+ const newest = selected[selected.length - 1]!;
+ const writes = selected.map((w) => w.write_id);
+ // The plan is a report over every target the selection touched, so a
+ // target this vault would never have written costs that target and
+ // not the plan: one crafted log line must not take the verdict on
+ // every other note with it.
+ let abs: string;
+ try {
+ abs = ensureInsideVault(join(vault, target), vault);
+ } catch {
+ return refuse(
+ target,
+ writes,
+ NOTE_REVERT_REFUSAL.targetInvalid,
+ NOTE_REVERT_HASH_UNREADABLE,
+ oldest.hash_before,
+ );
+ }
+ const current = readCurrent(abs);
+ const hashNow = hashOf(current);
+
+ if (current.kind === "unreadable") {
+ return refuse(target, writes, NOTE_REVERT_REFUSAL.unrecorded, hashNow, oldest.hash_before);
+ }
+ if (hashNow !== newest.hash_after) {
+ return refuse(target, writes, NOTE_REVERT_REFUSAL.drift, hashNow, oldest.hash_before);
+ }
+
+ if (interleaves(selected, universe)) {
+ return refuse(target, writes, NOTE_REVERT_REFUSAL.interleaved, hashNow, oldest.hash_before);
+ }
+
+ // `delete` applies only when the selected writes brought the note into
+ // existence: the oldest one replaced nothing AND nothing on record
+ // wrote this target before it. A note created outside the selection is
+ // never deleted through this path (design.md, out of scope).
+ const createdBySelection =
+ oldest.hash_before === NOTE_WRITE_NO_PRIOR &&
+ universe.findIndex((w) => w.write_id === oldest.write_id) === 0;
+ const hashTo = createdBySelection ? NOTE_WRITE_NO_PRIOR : oldest.hash_before;
+
+ if (hashNow === hashTo) {
+ return refuse(target, writes, NOTE_REVERT_REFUSAL.alreadyReverted, hashNow, hashTo);
+ }
+ if (createdBySelection) {
+ return {
+ target,
+ action: NOTE_REVERT_ACTION.delete,
+ writes,
+ hash_now: hashNow,
+ hash_to: hashTo,
+ };
+ }
+ // A restore to `absent` would be a delete the delete rule declined to
+ // authorise - the oldest selected write replaced nothing, but an
+ // earlier write of record exists, so this note had a life before the
+ // selection. There is no image of nothing to restore, and the store is
+ // where the plan says so.
+ if (hashTo === NOTE_WRITE_NO_PRIOR || !imageAvailable(vault, hashTo)) {
+ return refuse(target, writes, NOTE_REVERT_REFUSAL.imageMissing, hashNow, hashTo);
+ }
+ return { target, action: NOTE_REVERT_ACTION.restore, writes, hash_now: hashNow, hash_to: hashTo };
+}
+
+/**
+ * Plan what reverting the selected writes would do, and seal it.
+ *
+ * Two reads of the ledger rather than one: the SELECTED writes narrow by
+ * the whole selector, and the UNIVERSE of writes on the same targets
+ * narrows by path alone, because the interleaving and creation rules ask
+ * about writes the selector deliberately excluded.
+ */
+export function planNoteRevert(
+ vault: string,
+ selector: NoteRevertSelector,
+ opts: PlanNoteRevertOptions = {},
+): NoteRevertPlan {
+ assertBounded(selector);
+ const normalised = normaliseSelector(selector);
+ // `listNoteWrites` returns newest-first; every rule here reads the
+ // history forwards, so both lists are reversed once, here.
+ const selectedRead = listNoteWrites(vault, normalised);
+ const universeRead = listNoteWrites(
+ vault,
+ normalised.path !== undefined ? { path: normalised.path } : {},
+ );
+ const selected = selectedRead.writes.toReversed();
+ const universe = universeRead.writes.toReversed();
+
+ const byTarget = new Map<string, NoteWriteRecord[]>();
+ for (const write of selected) {
+ const bucket = byTarget.get(write.target);
+ if (bucket === undefined) byTarget.set(write.target, [write]);
+ else bucket.push(write);
+ }
+
+ const entries = [...byTarget.keys()]
+ .toSorted((a, b) => a.localeCompare(b))
+ .map((target) =>
+ planTarget(
+ vault,
+ target,
+ byTarget.get(target)!,
+ universe.filter((w) => w.target === target),
+ ),
+ );
+
+ return {
+ selector: normalised,
+ entries,
+ digest: sha256Hex(canonicalJson({ selector: normalised, entries })),
+ planned_at: isoSecond(opts.now ?? new Date()),
+ warnings: universeRead.warnings,
+ };
+}
+
+/** The regions this apply reaches, declared from the targets themselves. */
+function blastRadiusOf(entries: ReadonlyArray<NoteRevertEntry>): {
+ readonly brainTopLevel?: boolean;
+ readonly outsideBrainRoot?: boolean;
+} {
+ const inBrain = entries.some((e) => e.target.startsWith(BRAIN_TREE_PREFIX));
+ const outside = entries.some((e) => !e.target.startsWith(BRAIN_TREE_PREFIX));
+ return {
+ ...(inBrain ? { brainTopLevel: true } : {}),
+ ...(outside ? { outsideBrainRoot: true } : {}),
+ };
+}
+
+/** The recorded row for one applied target, discriminated on the receipt. */
+function recordedRow(target: string, receipt: NoteWriteReceipt): NoteRevertRecorded {
+ return receipt.write_id === null
+ ? { target, write_id: null, audit_reason: receipt.audit_reason }
+ : { target, write_id: receipt.write_id };
+}
+
+/**
+ * Apply a plan the caller has already read, identified by its digest.
+ *
+ * Order is the contract. The vault-identity guard runs FIRST, so a
+ * frozen vault refuses a revert by name before anything is read; then
+ * the plan is rebuilt from scratch and compared to the digest, so a
+ * vault that moved under the operator is refused before any byte; and
+ * only then does the destructive gate take the one recovery point the
+ * whole apply runs behind.
+ */
+export function applyNoteRevert(
+ vault: string,
+ selector: NoteRevertSelector,
+ digest: string,
+ opts: ApplyNoteRevertOptions = {},
+): NoteRevertApplyResult {
+ assertVaultIdentityForWrite(vault);
+ const plan = planNoteRevert(vault, selector, opts);
+ if (plan.digest !== digest) {
+ throw new NoteRevertError(
+ NOTE_REVERT_ERROR.digestMismatch,
+ `this plan no longer describes the vault: the sealed digest was ${digest} and re-planning ` +
+ `the same selector now yields ${plan.digest}. Nothing has been touched - plan again and ` +
+ "read what changed",
+ { expected: digest, actual: plan.digest },
+ );
+ }
+
+ const actionable = plan.entries.filter((e) => e.action !== NOTE_REVERT_ACTION.refuse);
+ if (actionable.length === 0) {
+ throw new NoteRevertError(
+ NOTE_REVERT_ERROR.nothingToApply,
+ `every one of the ${plan.entries.length} target(s) in this plan is refused, so there is ` +
+ "nothing to apply; the plan names the reason for each",
+ );
+ }
+
+ const timestamp = isoSecond(opts.now ?? new Date());
+ const applied: NoteRevertEntry[] = [];
+ const refused: NoteRevertEntry[] = plan.entries.filter(
+ (e) => e.action === NOTE_REVERT_ACTION.refuse,
+ );
+ const recorded: NoteRevertRecorded[] = [];
+ const failed: NoteRevertFailure[] = [];
+ const record = (entry: NoteRevertEntry, before: string | null, after: string | null): void => {
+ applied.push(entry);
+ recorded.push(
+ recordedRow(
+ entry.target,
+ recordNoteWrite(vault, {
+ op: NOTE_WRITE_OP.revert,
+ target: entry.target,
+ before: before === null ? null : { bytes: before },
+ after: after === null ? null : { bytes: after },
+ timestamp,
+ ...(opts.agent !== undefined ? { agent: opts.agent } : {}),
+ ...(opts.configPath !== undefined ? { configPath: opts.configPath } : {}),
+ }),
+ ),
+ );
+ };
+
+ const gated = withDestructiveSnapshot(
+ vault,
+ BRAIN_SNAPSHOT_REASON.noteRevert,
+ () => {
+ for (const entry of actionable) {
+ // Per-entry boundary. Every step below can throw on a condition
+ // the plan could not see, and the recovery point is already
+ // taken - so an escaping throw would abandon every entry after
+ // this one inside a half-applied gate, and those entries would
+ // appear in neither `applied` nor `refused`. Named in `failed`,
+ // the operator reads what did not happen instead of inferring it
+ // from what is missing.
+ //
+ // Inline rather than behind a helper on purpose: the removal
+ // below has to stay lexically inside this gate's argument list,
+ // which is what the destructive-site census reads.
+ try {
+ const abs = ensureInsideVault(join(vault, entry.target), vault);
+ const current = readCurrent(abs);
+ if (entry.action === NOTE_REVERT_ACTION.delete) {
+ // The plan proved the bytes are the ones the newest selected
+ // write left, so `current` is those bytes; keeping an image
+ // of them is what makes this delete itself revertible.
+ if (current.kind !== "bytes") {
+ refused.push({
+ ...entry,
+ action: NOTE_REVERT_ACTION.refuse,
+ reason: NOTE_REVERT_REFUSAL.unrecorded,
+ });
+ continue;
+ }
+ storeBeforeImage(vault, current.bytes);
+ unlinkSync(abs);
+ record(entry, current.bytes, null);
+ continue;
+ }
+ // A restore verifies the image against the digest the plan
+ // sealed BEFORE it writes: restoring bytes that are not the
+ // ones recorded is the one failure a revert must never have,
+ // and a corrupt or vanished image is the same answer the plan
+ // gives.
+ const bytes = readImage(vault, entry.hash_to);
+ if (bytes === null) {
+ refused.push({
+ ...entry,
+ action: NOTE_REVERT_ACTION.refuse,
+ reason: NOTE_REVERT_REFUSAL.imageMissing,
+ });
+ continue;
+ }
+ if (current.kind === "bytes") storeBeforeImage(vault, current.bytes);
+ mkdirSync(dirname(abs), { recursive: true });
+ atomicWriteFileSync(abs, bytes);
+ record(entry, current.kind === "bytes" ? current.bytes : null, bytes);
+ } catch (err) {
+ failed.push({
+ target: entry.target,
+ reason: err instanceof Error ? err.message : String(err),
+ });
+ }
+ }
+ },
+ {
+ blastRadius: blastRadiusOf(actionable),
+ ...(opts.now !== undefined ? { now: opts.now } : {}),
+ },
+ );
+
+ return {
+ snapshot: { run_id: gated.snapshot.runId, path: gated.snapshot.path },
+ applied,
+ refused,
+ failed,
+ recorded,
+ recoverability: gated.recoverability,
+ };
+}
+
+/** The image's bytes, or null when it is missing or no longer hashes to its name. */
+function readImage(vault: string, sha256: string): string | null {
+ try {
+ const bytes = readFileSync(writeImagePath(vault, sha256), "utf8");
+ return sha256Hex(bytes) === sha256 ? bytes : null;
+ } catch {
+ return null;
+ }
+}
diff --git a/src/core/brain/notes/scaffold-stub.ts b/src/core/brain/notes/scaffold-stub.ts
index a6d31f69..6073353e 100644
--- a/src/core/brain/notes/scaffold-stub.ts
+++ b/src/core/brain/notes/scaffold-stub.ts
@@ -335,6 +335,12 @@ export interface ScaffoldStubInput {
readonly ifExists?: CreateNoteIfExists;
/** False (the default) resolves and plans, writing nothing. */
readonly apply?: boolean;
+ /**
+ * Config file that names the writing agent, forwarded to `createNote`
+ * for the note-write record (who-wrote-what, Task A). A stub is a note
+ * like any other and is attributed like one.
+ */
+ readonly configPath?: string;
}
export interface ScaffoldStubResult {
@@ -484,6 +490,7 @@ export function scaffoldStub(vault: string, input: ScaffoldStubInput): ScaffoldS
frontmatter,
content: body,
...(input.ifExists !== undefined ? { ifExists: input.ifExists } : {}),
+ ...(input.configPath !== undefined ? { configPath: input.configPath } : {}),
});
return Object.freeze({
target,
diff --git a/src/core/brain/notes/write-log.ts b/src/core/brain/notes/write-log.ts
new file mode 100644
index 00000000..a7efbe97
--- /dev/null
+++ b/src/core/brain/notes/write-log.ts
@@ -0,0 +1,209 @@
+/**
+ * The note-write reader (who-wrote-what, Task A / t_662f4e82).
+ *
+ * `recordNoteWrite` appends one `note-write` event per write; this is the
+ * only module that reads them back, and it exists so that `o2b brain
+ * writes`, the `brain_writes` MCP tool and the per-agent revert
+ * (t_924129c5) all answer from one projection rather than three parsers
+ * of the same payload.
+ *
+ * It reads through {@link readLogDay}, which merges every device shard of
+ * a day in a deterministic order and reports malformed lines as warnings
+ * instead of aborting. Two consequences the callers rely on:
+ *
+ * - the DEVICE comes off the shard the entry was read from, not off the
+ * payload. No writer stamps its device id into a note-write body, and
+ * one that did would be asserting a fact the file name already
+ * records - a caller naming its own provenance, which is the shape
+ * the origin-channel stamp exists not to be.
+ * - a warning is carried out rather than swallowed. A day whose JSONL
+ * lost a line is a day whose write history is incomplete, and an
+ * operator deciding what to revert has to be told that.
+ *
+ * Order is newest-first, because every surface over this reader answers
+ * "what just happened" before it answers "what happened once".
+ */
+
+import { listLogDates, listLogShardFiles, readLogDay, type LogShardFile } from "../log-jsonl.ts";
+import type { BrainLogEntry, BrainLogParseWarning } from "../log.ts";
+import { BRAIN_LOG_EVENT_KIND } from "../types.ts";
+import { ORIGIN_CHANNEL_FIELD } from "../../origin-channel.ts";
+import { isNoteWriteOp, type NoteWriteOp } from "./write-record.ts";
+
+/** One recorded note write, projected from its log event. */
+export interface NoteWriteRecord {
+ readonly write_id: string;
+ /** ISO-8601 UTC second the event carries. */
+ readonly timestamp: string;
+ readonly op: NoteWriteOp;
+ /** Vault-relative POSIX path of the note. */
+ readonly target: string;
+ /** sha256 of the replaced bytes, or `absent` when there were none. */
+ readonly hash_before: string;
+ readonly hash_after: string;
+ readonly bytes_before: number;
+ readonly bytes_after: number;
+ readonly agent: string;
+ /**
+ * Device that recorded the write, read off the log shard. The empty
+ * string is the legacy un-sharded pair, which is a real answer ("the
+ * machine that wrote this had no device id configured") and not a
+ * missing one.
+ */
+ readonly device: string;
+ /** Channel the appender stamped, or null on a line written before it. */
+ readonly origin_channel: string | null;
+}
+
+/** How a caller narrows {@link listNoteWrites}. */
+export interface ListNoteWritesFilter {
+ /** Exact agent identity. */
+ readonly agent?: string;
+ /** Exact device id; the empty string selects the legacy un-sharded pair. */
+ readonly device?: string;
+ /** Exact vault-relative target path. */
+ readonly path?: string;
+ /** Inclusive lower bound: an ISO date or an ISO-8601 UTC timestamp. */
+ readonly since?: string;
+ /** Inclusive upper bound, same two spellings. */
+ readonly until?: string;
+ readonly op?: NoteWriteOp;
+}
+
+export interface ListNoteWritesResult {
+ /** Matching writes, newest first. */
+ readonly writes: ReadonlyArray<NoteWriteRecord>;
+ /** Every parse warning the underlying log days reported. */
+ readonly warnings: ReadonlyArray<BrainLogParseWarning>;
+}
+
+/** Characters of an ISO-8601 timestamp that spell its date. */
+const DATE_LENGTH = 10;
+
+/** A bare `YYYY-MM-DD`, which both bounds accept as shorthand for a day. */
+const ISO_DATE_ONLY_RE = /^\d{4}-\d{2}-\d{2}$/;
+
+/** How a bare date is completed at each end of the window. */
+const DAY_START_SUFFIX = "T00:00:00Z";
+const DAY_END_SUFFIX = "T23:59:59Z";
+
+/**
+ * Complete a bound to a comparable timestamp.
+ *
+ * A bare `--until 2026-03-04` means "through the end of the fourth", not
+ * "up to midnight starting it" - the second reading would return nothing
+ * for the very day an operator just named, which is the kind of empty
+ * that reads as "no writes" rather than as "wrong bound".
+ */
+function completeBound(value: string, suffix: string): string {
+ return ISO_DATE_ONLY_RE.test(value) ? `${value}${suffix}` : value;
+}
+
+/** Payload value as a string, or null when the key is absent or a list. */
+function stringField(
+ body: Readonly<Record<string, string | ReadonlyArray<string>>>,
+ key: string,
+): string | null {
+ const value = body[key];
+ return typeof value === "string" ? value : null;
+}
+
+/**
+ * A byte count as recorded. The payload contract carries strings only, so
+ * the count is rendered on the way in and parsed back here; a value that
+ * is not a non-negative integer is reported as `-1` rather than silently
+ * becoming zero, because a zero-length note and an unreadable count are
+ * different facts.
+ */
+const UNREADABLE_BYTE_COUNT = -1;
+
+function byteField(
+ body: Readonly<Record<string, string | ReadonlyArray<string>>>,
+ key: string,
+): number {
+ const raw = stringField(body, key);
+ if (raw === null) return UNREADABLE_BYTE_COUNT;
+ const value = Number.parseInt(raw, 10);
+ return Number.isInteger(value) && value >= 0 && String(value) === raw
+ ? value
+ : UNREADABLE_BYTE_COUNT;
+}
+
+/**
+ * Project one log entry into a record, or null when it is not a
+ * note-write event this build can read.
+ *
+ * A `note-write` line missing its `write_id`, `target` or `op` is not
+ * projected: those three are what every surface over this reader keys on,
+ * and a record with a blank one would be a row an operator could select
+ * and never act on.
+ */
+function projectRecord(entry: BrainLogEntry, device: string): NoteWriteRecord | null {
+ if (entry.eventType !== BRAIN_LOG_EVENT_KIND.noteWrite) return null;
+ const writeId = stringField(entry.body, "write_id");
+ const target = stringField(entry.body, "target");
+ const op = stringField(entry.body, "op");
+ if (writeId === null || target === null || op === null || !isNoteWriteOp(op)) return null;
+ return {
+ write_id: writeId,
+ timestamp: entry.timestamp,
+ op,
+ target,
+ hash_before: stringField(entry.body, "hash_before") ?? "",
+ hash_after: stringField(entry.body, "hash_after") ?? "",
+ bytes_before: byteField(entry.body, "bytes_before"),
+ bytes_after: byteField(entry.body, "bytes_after"),
+ agent: stringField(entry.body, "agent") ?? "",
+ device,
+ origin_channel: stringField(entry.body, ORIGIN_CHANNEL_FIELD),
+ };
+}
+
+/**
+ * Every recorded note write matching the filter, newest first.
+ *
+ * The date range narrows which log days are opened at all, so a filter
+ * with both bounds does not pay for the whole history; the remaining
+ * predicates run per record because they key on payload fields the file
+ * layout cannot answer.
+ */
+export function listNoteWrites(
+ vault: string,
+ filter: ListNoteWritesFilter = {},
+): ListNoteWritesResult {
+ const since = filter.since === undefined ? null : completeBound(filter.since, DAY_START_SUFFIX);
+ const until = filter.until === undefined ? null : completeBound(filter.until, DAY_END_SUFFIX);
+ const shards: ReadonlyArray<LogShardFile> = listLogShardFiles(vault);
+ const warnings: BrainLogParseWarning[] = [];
+ const writes: NoteWriteRecord[] = [];
+
+ for (const date of listLogDates(vault)) {
+ if (since !== null && date < since.slice(0, DATE_LENGTH)) continue;
+ if (until !== null && date > until.slice(0, DATE_LENGTH)) continue;
+ const day = readLogDay(vault, date, shards);
+ warnings.push(...day.warnings);
+ day.entries.forEach((entry, index) => {
+ const record = projectRecord(entry, day.entryShardIds[index] ?? "");
+ if (record === null) return;
+ if (filter.agent !== undefined && record.agent !== filter.agent) return;
+ if (filter.device !== undefined && record.device !== filter.device) return;
+ if (filter.path !== undefined && record.target !== filter.path) return;
+ if (filter.op !== undefined && record.op !== filter.op) return;
+ if (since !== null && record.timestamp < since) return;
+ if (until !== null && record.timestamp > until) return;
+ writes.push(record);
+ });
+ }
+
+ // Newest first, by REVERSING the order the log already merged rather
+ // than re-sorting on the timestamp. Timestamps are second-precision, so
+ // a sort would tie for every pair of writes made inside one second and
+ // any tiebreak invented here - the write id, the path - would order
+ // them by something that is not when they happened. `readLogDay`
+ // already merges shards by (timestamp, shard id, line), and line order
+ // inside a shard IS the order the appends landed, so reversing keeps
+ // the causal order within a second and stays deterministic across
+ // devices reading one synced vault.
+ writes.reverse();
+ return { writes, warnings };
+}
diff --git a/src/core/brain/notes/write-record.ts b/src/core/brain/notes/write-record.ts
new file mode 100644
index 00000000..4b4dfa70
--- /dev/null
+++ b/src/core/brain/notes/write-record.ts
@@ -0,0 +1,384 @@
+/**
+ * The note-write record (who-wrote-what, Task A / t_662f4e82).
+ *
+ * Signals and preferences have carried an `agent:` since they shipped,
+ * and note writes - the bulk of what a connected agent actually produces
+ * - carried nothing at all. A note rewritten by one of four agents on one
+ * of three machines left an mtime and no answer to "who did that, and
+ * what did it say before". This module is that answer, and it is
+ * deliberately two artifacts rather than one:
+ *
+ * - ONE `note-write` log event per write, carrying the write id, the
+ * operation, the target, the content hash and byte size on both
+ * sides, and the caller-asserted agent. The appender stamps the
+ * origin channel and shards per device, so the device rides on the
+ * shard name exactly as it does for every other event.
+ * - the bytes the write REPLACED, kept content-addressed under
+ * `Brain/.state/write-images/<sha256>`. A hash proves a write
+ * happened; only the bytes let it be undone.
+ *
+ * ## Order, and why the receipt can say `null`
+ *
+ * The caller stores the image, writes the file, and records last. The
+ * file is the load-bearing artifact and the event is the audit trail, so
+ * a log failure must never abort a write that has already landed - that
+ * is the precedent the snapshot event set. What this module does NOT
+ * inherit is the silence: {@link recordNoteWrite} never throws, and when
+ * the append fails it returns `write_id: null` with an `audit_reason`
+ * naming the failure, which every note-write result and MCP receipt
+ * carries through to the caller. A write nobody can attribute is a fact
+ * the caller is told, not one it has to infer.
+ *
+ * ## Why content-addressed
+ *
+ * An agent that toggles a note between two states costs two images, not
+ * two per write, and two writers that replace identical content share
+ * one file. The store is inside `Brain/`, so the snapshot region already
+ * archives it; {@link pruneWriteImages} bounds its growth by mtime.
+ */
+
+import { existsSync, mkdirSync, readdirSync, unlinkSync } from "node:fs";
+import { dirname, isAbsolute, join } from "node:path";
+
+import { atomicWriteFileSync } from "../../fs-atomic.ts";
+import { resolveAgentName } from "../../config.ts";
+import { canonicalJson, sha256Hex } from "../../integrity/digest.ts";
+import { appendLogEvent } from "../log.ts";
+import {
+ SHA256_HEX_RE,
+ ensureInsideVault,
+ vaultRelative,
+ writeImagePath,
+ writeImagesDir,
+} from "../paths.ts";
+import { fileAgeMs, isoSecond, msToWholeDays } from "../time.ts";
+import { assertVaultIdentityForWrite } from "../vault-identity.ts";
+import { BRAIN_LOG_EVENT_KIND } from "../types.ts";
+
+/**
+ * What a recorded write did to its target. Closed vocabulary: the three
+ * mutations the note seams perform, plus `revert`, which the per-agent
+ * revert (t_924129c5) writes when it restores a before-image. `revert` is
+ * declared HERE rather than added later on purpose - a restore is a write
+ * like any other and must be attributable and itself revertible, so the
+ * vocabulary that admits it is the vocabulary the reader already knows.
+ */
+export const NOTE_WRITE_OP = Object.freeze({
+ create: "create",
+ update: "update",
+ append: "append",
+ revert: "revert",
+} as const);
+
+export type NoteWriteOp = (typeof NOTE_WRITE_OP)[keyof typeof NOTE_WRITE_OP];
+
+/** The operations, in declaration order; the membership half of the trio. */
+export const NOTE_WRITE_OPS: ReadonlyArray<NoteWriteOp> = Object.freeze(
+ Object.values(NOTE_WRITE_OP),
+);
+
+/** True when `value` is a member of {@link NOTE_WRITE_OP}. */
+export function isNoteWriteOp(value: unknown): value is NoteWriteOp {
+ return typeof value === "string" && (NOTE_WRITE_OPS as ReadonlyArray<string>).includes(value);
+}
+
+/**
+ * What `hash_before` says when the target did not exist - and what
+ * `hash_after` says when the write left it not existing.
+ *
+ * A literal rather than an empty string or a missing key: the payload
+ * contract admits only strings, an absent key would be indistinguishable
+ * from a legacy line, and the sha256 of zero bytes is a real digest that
+ * an empty FILE would also produce. "There was nothing here" and "there
+ * was an empty file here" are different facts and a revert reads them
+ * differently.
+ *
+ * ONE literal for both sides rather than two, because it names one fact -
+ * no file at this path - and a reader comparing the two sides of a write
+ * would otherwise have to know two spellings of it. The `revert` that
+ * removes a note the selected writes created is the only producer of the
+ * `hash_after` half today (`notes/revert.ts`), and it pairs the literal
+ * with `bytes_after: "0"`.
+ */
+export const NOTE_WRITE_NO_PRIOR = "absent";
+
+/**
+ * Default age, in whole days, past which {@link pruneWriteImages} removes
+ * a before-image. Thirty days is the window in which an operator notices
+ * an agent wrote something it should not have; past it the snapshot
+ * region is the recovery story and the image only narrows revert reach.
+ */
+export const WRITE_IMAGE_RETENTION_DAYS = 30;
+
+/** Prefix of every write id, mirroring the continuity record id shape. */
+const NOTE_WRITE_ID_PREFIX = "nw_";
+/** Digits of the event timestamp carried in the id, most significant first. */
+const NOTE_WRITE_ID_STAMP_LENGTH = 14;
+/** Hex characters of the body digest carried in the id. */
+const NOTE_WRITE_ID_HASH_LENGTH = 16;
+
+/** The facts a write id is derived from. */
+export interface NoteWriteIdInput {
+ /** ISO-8601 UTC second the event carries. */
+ readonly timestamp: string;
+ readonly op: NoteWriteOp;
+ /** Vault-relative POSIX path of the note. */
+ readonly target: string;
+ /** sha256 of the replaced bytes, or {@link NOTE_WRITE_NO_PRIOR}. */
+ readonly hash_before: string;
+ /** sha256 of the bytes now on disk. */
+ readonly hash_after: string;
+ readonly agent: string;
+}
+
+/**
+ * The id of one recorded write: `nw_<14 timestamp digits>_<16 hex>`.
+ *
+ * Sortable by its stamp and unique by its digest, the shape
+ * `continuity/store.ts` already uses for the same reason. Derived from
+ * the event body rather than from a counter or a random value, so two
+ * devices that record the same write of the same bytes at the same
+ * second agree on its id and a merged log deduplicates rather than
+ * double-counts.
+ */
+export function noteWriteId(body: NoteWriteIdInput): string {
+ const stamp = body.timestamp.replace(/\D/g, "").slice(0, NOTE_WRITE_ID_STAMP_LENGTH);
+ const hash = sha256Hex(canonicalJson(body)).slice(0, NOTE_WRITE_ID_HASH_LENGTH);
+ return `${NOTE_WRITE_ID_PREFIX}${stamp}_${hash}`;
+}
+
+/** Where one before-image ended up, and whether this call put it there. */
+export interface StoredBeforeImage {
+ /** sha256 of the stored bytes; the file's own name. */
+ readonly sha256: string;
+ /** Absolute path of the image file. */
+ readonly path: string;
+ /** False when an image of the same content already existed. */
+ readonly stored: boolean;
+}
+
+/**
+ * Keep the bytes a write is about to replace, keyed by their digest.
+ *
+ * Content-addressed and therefore idempotent: a second call with the same
+ * bytes writes nothing and reports `stored: false`, which is what keeps a
+ * note edited a hundred times between two states at two images.
+ */
+export function storeBeforeImage(vault: string, bytes: string): StoredBeforeImage {
+ const sha256 = sha256Hex(bytes);
+ const path = writeImagePath(vault, sha256);
+ if (existsSync(path)) return { sha256, path, stored: false };
+ mkdirSync(dirname(path), { recursive: true });
+ atomicWriteFileSync(path, bytes);
+ return { sha256, path, stored: true };
+}
+
+/** One side of a write, as the bytes that were or are on disk. */
+export interface NoteWriteBytes {
+ readonly bytes: string;
+}
+
+/** What {@link recordNoteWrite} needs to describe one write. */
+export interface RecordNoteWriteInput {
+ readonly op: NoteWriteOp;
+ /** Vault-relative POSIX path, or an absolute path inside the vault. */
+ readonly target: string;
+ /** The replaced bytes, or null when the target did not exist. */
+ readonly before: NoteWriteBytes | null;
+ /**
+ * The bytes now on disk, or null when the write left NO file at the
+ * target. Only the revert path produces the null side today: undoing
+ * the writes that created a note removes it, and a removal that could
+ * not be recorded would be the one write in this ledger with no line.
+ */
+ readonly after: NoteWriteBytes | null;
+ /** ISO-8601 UTC second; defaults to now. */
+ readonly timestamp?: string;
+ /** Caller-asserted identity; defaults to {@link resolveAgentName}. */
+ readonly agent?: string;
+ /**
+ * Config file that names the writing agent, when the caller knows
+ * which one it is running under.
+ *
+ * Threaded rather than left to the default discovery because the whole
+ * point of this record is WHO wrote the note: a server started against
+ * an explicit config and a record resolved against the machine default
+ * would attribute the same write to two different agents, and the one
+ * on disk would be the wrong one.
+ */
+ readonly configPath?: string;
+}
+
+/**
+ * The audit half of a note-write result.
+ *
+ * Discriminated on `write_id` so a caller cannot read an unrecorded write
+ * as a recorded one: either there is an id, or there is a reason there is
+ * not. Both halves ride on every note-write result and MCP receipt.
+ */
+export type NoteWriteReceipt =
+ | { readonly write_id: string; readonly audit_reason?: undefined }
+ | { readonly write_id: null; readonly audit_reason: string };
+
+/**
+ * Append the one `note-write` event for a write whose bytes have ALREADY
+ * landed, and never throw.
+ *
+ * The ordering is the contract: this runs after the atomic write, so a
+ * failure here costs the audit line and not the note. Every failure mode
+ * - an unresolvable agent identity, a locked log directory, a full disk -
+ * returns `write_id: null` with the reason, because the alternative shapes
+ * are both worse: throwing would undo nothing and report a failure for a
+ * write that succeeded, and swallowing would leave the caller believing an
+ * event exists.
+ */
+export function recordNoteWrite(vault: string, input: RecordNoteWriteInput): NoteWriteReceipt {
+ try {
+ const timestamp = input.timestamp ?? isoSecond();
+ const agent = input.agent ?? resolveAgentName(input.configPath);
+ // The seams hand this a vault-relative POSIX path they already
+ // judged; an absolute one is admitted too, and both go back through
+ // containment rather than being trusted, so a target outside the
+ // vault becomes a named audit reason instead of a log line pointing
+ // out of the tree.
+ const abs = ensureInsideVault(
+ isAbsolute(input.target) ? input.target : join(vault, input.target),
+ vault,
+ );
+ const target = vaultRelative(abs, vault);
+ const hashBefore = input.before === null ? NOTE_WRITE_NO_PRIOR : sha256Hex(input.before.bytes);
+ const bytesBefore = input.before === null ? 0 : Buffer.byteLength(input.before.bytes, "utf8");
+ const hashAfter = input.after === null ? NOTE_WRITE_NO_PRIOR : sha256Hex(input.after.bytes);
+ const bytesAfter = input.after === null ? 0 : Buffer.byteLength(input.after.bytes, "utf8");
+ const idInput: NoteWriteIdInput = {
+ timestamp,
+ op: input.op,
+ target,
+ hash_before: hashBefore,
+ hash_after: hashAfter,
+ agent,
+ };
+ // Every value is a string: `BrainLogEntryPayload` admits `string |
+ // string[]` and nothing else, so the byte counts are rendered rather
+ // than carried as numbers a reader would have to coerce back.
+ const writeId = noteWriteId(idInput);
+ appendLogEvent(vault, {
+ timestamp,
+ eventType: BRAIN_LOG_EVENT_KIND.noteWrite,
+ agent,
+ body: {
+ write_id: writeId,
+ op: idInput.op,
+ target: idInput.target,
+ hash_before: idInput.hash_before,
+ hash_after: idInput.hash_after,
+ bytes_before: String(bytesBefore),
+ bytes_after: String(bytesAfter),
+ agent,
+ },
+ });
+ return { write_id: writeId };
+ } catch (err) {
+ return {
+ write_id: null,
+ audit_reason: `note-write event not recorded: ${err instanceof Error ? err.message : String(err)}`,
+ };
+ }
+}
+
+/** How {@link pruneWriteImages} was asked to run. */
+export interface PruneWriteImagesOptions {
+ /** Whole days of age past which an image is removed. Default 30. */
+ readonly olderThanDays?: number;
+ /** Report what would go and remove nothing. */
+ readonly dryRun?: boolean;
+ /** Instant the ages are measured against; defaults to now. */
+ readonly now?: Date;
+}
+
+/** What one prune pass found and did. */
+export interface PruneWriteImagesResult {
+ /** sha256 names removed (or, under `dryRun`, that would be), sorted. */
+ readonly removed: ReadonlyArray<string>;
+ /** Images left in the store. */
+ readonly kept: number;
+ /**
+ * Names in the store that are not before-images, in directory order:
+ * a Syncthing `*.sync-conflict-*` copy, a `.DS_Store`, an editor temp
+ * file. The prune neither removes them nor counts them as kept - it
+ * does not own them - but it names them, because this verb is the
+ * only pass an operator makes over the store and a file nothing will
+ * ever remove is exactly what they need told.
+ */
+ readonly skipped: ReadonlyArray<string>;
+ /** True when nothing was actually unlinked. */
+ readonly dry_run: boolean;
+}
+
+/**
+ * Remove before-images older than a retention window.
+ *
+ * The store is not self-limiting - every distinct prior content of every
+ * note stays until something removes it - so this is the bound. An image
+ * is a copy of note content the snapshot region already archives, and its
+ * absence only narrows how far back a revert can reach, which the revert
+ * plan reports by name rather than discovering silently.
+ */
+export function pruneWriteImages(
+ vault: string,
+ opts: PruneWriteImagesOptions = {},
+): PruneWriteImagesResult {
+ // The one entry point in this module a caller reaches on its own: the
+ // store and the record are written from inside the note seams, which
+ // are guarded before their first byte, and this removes vault bytes
+ // from an operator verb that passes through nothing else.
+ assertVaultIdentityForWrite(vault);
+ const olderThanDays = opts.olderThanDays ?? WRITE_IMAGE_RETENTION_DAYS;
+ if (!Number.isInteger(olderThanDays) || olderThanDays < 0) {
+ throw new Error(
+ `pruneWriteImages: olderThanDays must be a non-negative integer, got ${String(olderThanDays)}`,
+ );
+ }
+ const dryRun = opts.dryRun === true;
+ const dir = writeImagesDir(vault);
+ if (!existsSync(dir)) return { removed: [], kept: 0, skipped: [], dry_run: dryRun };
+ const nowMs = (opts.now ?? new Date()).getTime();
+ const removed: string[] = [];
+ const skipped: string[] = [];
+ let kept = 0;
+ for (const entry of readdirSync(dir, { withFileTypes: true }).toSorted((a, b) =>
+ a.name.localeCompare(b.name),
+ )) {
+ if (!entry.isFile()) continue;
+ // A name this store did not write is not this prune's to remove, and
+ // it is not a reason to abandon the pass either: the store is a
+ // directory on a synced filesystem, so one conflict copy would
+ // otherwise leave every real image unbounded forever.
+ if (!isWriteImageName(entry.name)) {
+ skipped.push(entry.name);
+ continue;
+ }
+ const path = writeImagePath(vault, entry.name);
+ // An unmeasurable age is not an old age: a file whose mtime this
+ // process cannot read is kept, because "I could not tell" must never
+ // resolve to "remove it".
+ const ageMs = fileAgeMs(path, nowMs);
+ if (ageMs === null || msToWholeDays(ageMs) < olderThanDays) {
+ kept += 1;
+ continue;
+ }
+ if (!dryRun) unlinkSync(path);
+ removed.push(entry.name);
+ }
+ return { removed, kept, skipped, dry_run: dryRun };
+}
+
+/**
+ * True when `name` is a name {@link storeBeforeImage} could have
+ * written. Asked before {@link writeImagePath}, which throws on anything
+ * else - the throw is right for a caller naming a digest and wrong for a
+ * loop reading a directory.
+ */
+function isWriteImageName(name: string): boolean {
+ return SHA256_HEX_RE.test(name);
+}
diff --git a/src/core/brain/operator-snapshot.ts b/src/core/brain/operator-snapshot.ts
index b33a08fe..b8266c5b 100644
--- a/src/core/brain/operator-snapshot.ts
+++ b/src/core/brain/operator-snapshot.ts
@@ -18,6 +18,7 @@
import { existsSync, readdirSync, statSync } from "node:fs";
import { resolveSearchConfig } from "../search/index.ts";
+import { FREEZE_NEXT_COMMAND, readFreezeMarker, type FreezeMarker } from "./freeze-marker.ts";
import { runDoctor } from "./doctor.ts";
import { resolveSignal } from "./diagnostics.ts";
import { runHygieneScan } from "./hygiene/scan.ts";
@@ -65,6 +66,19 @@ export interface OperatorSnapshot {
readonly problems: ReadonlyArray<SnapshotProblem>;
/** True when there are no problem lines. */
readonly healthy: boolean;
+ /**
+ * The fleet freeze, or `null` when the vault is open (who-wrote-what,
+ * Task C).
+ *
+ * Reported here rather than only as a doctor finding because "why is
+ * nothing writing" is the first question a freeze raises, and the
+ * operator snapshot is the surface that answers first questions. It is
+ * NOT folded into {@link healthy}: a freeze is a state an operator
+ * asked for, and calling it a problem would report an instruction as a
+ * fault. The doctor names it as a warning, which is where a standing
+ * condition belongs.
+ */
+ readonly frozen: FreezeMarker | null;
}
export interface BuildOperatorSnapshotOptions {
@@ -188,6 +202,7 @@ export async function buildOperatorSnapshot(
healthVerdict,
problems: Object.freeze(problems),
healthy: problems.length === 0,
+ frozen: readFreezeMarker(vault),
});
}
@@ -213,6 +228,17 @@ export function renderOperatorSnapshot(snap: OperatorSnapshot): string {
`search index ${snap.stateFiles.searchIndex ? "present" : "absent"}`,
);
out.push(` health: ${snap.healthVerdict}`);
+ // Printed on BOTH branches, and that is the point: "no line" would be
+ // indistinguishable from a renderer that forgot to ask, and the state
+ // an operator most needs stated is the one where nothing is writing.
+ out.push(
+ snap.frozen === null
+ ? " frozen: no"
+ : ` frozen: yes - set at ${snap.frozen.frozen_at} by ` +
+ `${snap.frozen.by === "" ? "an unnamed agent" : snap.frozen.by} ` +
+ `(${snap.frozen.reason === "" ? "no reason given" : snap.frozen.reason}); ` +
+ `lift with \`${FREEZE_NEXT_COMMAND}\``,
+ );
if (!snap.healthy) {
out.push("");
diff --git a/src/core/brain/path-constants.ts b/src/core/brain/path-constants.ts
index fcd080c3..e5414d55 100644
--- a/src/core/brain/path-constants.ts
+++ b/src/core/brain/path-constants.ts
@@ -78,6 +78,18 @@ export const BRAIN_ENTITIES_REL = posix.join(BRAIN_ROOT_REL, "entities");
* value can never resurface through semantic recall.
*/
export const BRAIN_STATE_REL = posix.join(BRAIN_ROOT_REL, "state");
+/**
+ * Internal machinery lane: `Brain/.state/`. Distinct from
+ * {@link BRAIN_STATE_REL} above despite the near-identical name, and the
+ * two are not interchangeable: `Brain/state/` is OPERATOR-facing memory
+ * content (one page per aspect, readable in Obsidian), while this
+ * dot-directory holds the ledgers and markers this tool keeps for itself
+ * - the session-lineage ledger, the anticipatory cache, the freeze
+ * marker. Dot-prefixed so the vault walker excludes it from search and
+ * indexing exactly as it excludes `.snapshots`.
+ */
+export const BRAIN_INTERNAL_STATE_DIR = ".state";
+export const BRAIN_INTERNAL_STATE_REL = posix.join(BRAIN_ROOT_REL, BRAIN_INTERNAL_STATE_DIR);
/** Obsidian Bases view definitions: `Brain/bases/<view>.base` (v1.15.0). */
export const BRAIN_BASES_REL = posix.join(BRAIN_ROOT_REL, "bases");
/** Ingested source summary pages: `Brain/sources/src-<slug>.md` (v1.7.0). */
@@ -97,6 +109,15 @@ export const BRAIN_SNAPSHOTS_REL = posix.join(BRAIN_ROOT_REL, BRAIN_SNAPSHOTS_DI
export const BRAIN_ARTIFACTS_DIR = ".artifacts";
export const BRAIN_ARTIFACTS_REL = posix.join(BRAIN_ROOT_REL, BRAIN_ARTIFACTS_DIR);
+/**
+ * Content-addressed store of the bytes a note write replaced:
+ * `Brain/.state/write-images/<sha256>` (who-wrote-what, Task A). One file
+ * per distinct prior content, so repeated edits between two states cost
+ * one file rather than one per write.
+ */
+export const BRAIN_WRITE_IMAGES_DIR = "write-images";
+export const BRAIN_WRITE_IMAGES_REL = posix.join(BRAIN_INTERNAL_STATE_REL, BRAIN_WRITE_IMAGES_DIR);
+
/**
* The top-level `Brain/` entries the snapshot family never touches:
* never archived, never hashed into a manifest, and never removed by a
diff --git a/src/core/brain/paths.ts b/src/core/brain/paths.ts
index 91f12174..8fcbba6d 100644
--- a/src/core/brain/paths.ts
+++ b/src/core/brain/paths.ts
@@ -29,6 +29,7 @@ import { join } from "node:path";
import { isFileAlreadyExists } from "../fs-atomic.ts";
import { ensureInsideVault, vaultRelative } from "../path-safety.ts";
import type { DegradationNotice } from "../integrity/degradation.ts";
+import { resolveAppendShardId, shardedFileName } from "./ledger-shards.ts";
import {
BRAIN_ARTIFACTS_REL,
BRAIN_ACTIVE_FILE,
@@ -67,13 +68,25 @@ import {
BRAIN_STATE_REL,
BRAIN_TENSIONS_REL,
BRAIN_THESES_REL,
+ BRAIN_WRITE_IMAGES_REL,
DERIVED_STORE_DIR,
HOOK_AUDIT_DIR,
} from "./path-constants.ts";
import { assertVaultIdentityForWrite } from "./vault-identity.ts";
+import type { WriteLane } from "./freeze-marker.ts";
export { ensureInsideVault, vaultRelative } from "../path-safety.ts";
+/**
+ * The freeze marker's location, re-exported so callers reach every Brain
+ * path through this module. It is DEFINED in `freeze-marker.ts` because
+ * the guard that reads it sits below this module in the import graph -
+ * see that module's docblock for the cycle the split avoids.
+ */
+export { frozenMarkerPath } from "./freeze-marker.ts";
+/** Shape of a sha256 digest as {@link writeImagePath} spells its file names. */
+export const SHA256_HEX_RE = /^[0-9a-f]{64}$/;
+
// The canonical vault-relative names live in their own leaf module so
// `vault-identity.ts` can locate the marker without importing the
// builders that guard on it. Re-exported wholesale: every constant this
@@ -186,9 +199,19 @@ export function brainDirs(vault: string): BrainDirs {
* through one of them is guarded at its own entry point, not here.
* Those writers call `assertVaultIdentityForWrite` directly; see
* its docblock for the two call surfaces and why they differ.
+ *
+ * `lane` selects which half of the write surface the caller belongs to
+ * and is forwarded verbatim to the guard; see its docblock for the
+ * freeze the content lane carries. Exactly one caller passes anything
+ * but the default: the Brain log appender, whose events have to keep
+ * landing while the vault is frozen.
*/
-export function brainDirsForWrite(vault: string, notices?: DegradationNotice[]): BrainDirs {
- assertVaultIdentityForWrite(vault, notices);
+export function brainDirsForWrite(
+ vault: string,
+ notices?: DegradationNotice[],
+ lane?: WriteLane,
+): BrainDirs {
+ assertVaultIdentityForWrite(vault, notices, lane);
return brainDirs(vault);
}
@@ -248,6 +271,36 @@ export function brainStateDir(vault: string): string {
return ensureInsideVault(join(vault, BRAIN_STATE_REL), vault);
}
+/**
+ * Content-addressed before-image store: `Brain/.state/write-images/`
+ * (who-wrote-what, Task A).
+ *
+ * Holds the raw bytes each note write replaced, keyed by their sha256, so
+ * a recorded write can be undone from the content it displaced rather
+ * than from a whole-tree archive. Inside `Brain/`, so the snapshot region
+ * already covers it.
+ */
+export function writeImagesDir(vault: string): string {
+ return ensureInsideVault(join(vault, BRAIN_WRITE_IMAGES_REL), vault);
+}
+
+/**
+ * One before-image: `Brain/.state/write-images/<sha256>`.
+ *
+ * The digest is validated rather than trusted, because it reaches this
+ * builder from a log payload an operator may have hand-edited and a
+ * separator smuggled through it would be a traversal out of the store.
+ */
+export function writeImagePath(vault: string, sha256: string): string {
+ if (!SHA256_HEX_RE.test(sha256)) {
+ throw new Error(
+ `writeImagePath: invalid before-image digest ${JSON.stringify(sha256)} - ` +
+ "expected 64 lowercase hexadecimal characters",
+ );
+ }
+ return ensureInsideVault(join(writeImagesDir(vault), sha256), vault);
+}
+
/** A single exact-state aspect page: `Brain/state/<aspect>.md` (t_b0c9d0a3). */
export function exactStatePath(vault: string, aspect: string): string {
const s = validateSlug(aspect);
@@ -553,16 +606,60 @@ export function prefAuditDir(vault: string): string {
}
/**
- * Brain lifecycle suite (Feature 1). Append-only audit JSONL for a
- * single preference: `Brain/log/pref-audit/<pref-id>.jsonl`. The pref
+ * Brain lifecycle suite (Feature 1). The directory holding ONE
+ * preference's audit shards: `Brain/log/pref-audit/<pref-id>/`. The pref
* id (`pref-<slug>` / `ret-<slug>`) is validated through
* {@link validateSlug} so it cannot escape the canonical directory.
+ *
+ * A directory rather than a name prefix because {@link validateSlug}
+ * permits a dot inside a preference id: flat, `pref-a.b.jsonl` is both
+ * `pref-a.b`'s trail and `pref-a`'s shard on a device called `b`, and no
+ * separator built out of characters `validateSlug` accepts can tell them
+ * apart. One path segment per preference can never be another
+ * preference's segment. See the module docblock of
+ * `src/core/brain/pref-audit.ts` for the whole decision.
*/
-export function prefAuditPath(vault: string, prefId: string): string {
- const id = validateSlug(prefId);
- return ensureInsideVault(join(prefAuditDir(vault), `${id}.jsonl`), vault);
+export function prefAuditPrefDir(vault: string, prefId: string): string {
+ return ensureInsideVault(join(prefAuditDir(vault), validateSlug(prefId)), vault);
}
+/**
+ * Brain lifecycle suite (Feature 1). Append-only audit JSONL for a
+ * single preference on a single device:
+ * `Brain/log/pref-audit/<pref-id>/device[.<deviceId>].jsonl`.
+ *
+ * `shardId` defaults to this device's id (who-wrote-what, Task B), so two
+ * machines editing one preference never append to the same file. The
+ * empty shard id is the un-sharded name inside that directory.
+ *
+ * The stem is fixed rather than the device id alone so the empty shard id
+ * still has a name, and so the shared shard grammar names this file the
+ * same way it names every other ledger's.
+ */
+export function prefAuditPath(
+ vault: string,
+ prefId: string,
+ shardId: string = resolveAppendShardId(),
+): string {
+ return ensureInsideVault(
+ join(
+ prefAuditPrefDir(vault, prefId),
+ shardedFileName(PREF_AUDIT_STEM, shardId, PREF_AUDIT_EXT),
+ ),
+ vault,
+ );
+}
+
+/** Extension of every preference-audit shard. */
+export const PREF_AUDIT_EXT = "jsonl";
+
+/**
+ * Fixed base name of every preference-audit shard inside its
+ * per-preference directory. A stem rather than the bare device id so the
+ * legacy empty shard id still yields a name.
+ */
+export const PREF_AUDIT_STEM = "device";
+
/** Snapshots directory: `Brain/.snapshots/`. */
export function snapshotsDir(vault: string): string {
return brainDirs(vault).snapshots;
diff --git a/src/core/brain/pref-audit.ts b/src/core/brain/pref-audit.ts
index f54b2833..3fccaa37 100644
--- a/src/core/brain/pref-audit.ts
+++ b/src/core/brain/pref-audit.ts
@@ -3,11 +3,39 @@
*
* Every mutation to a preference is captured at the mutation chokepoint
* (`writePreferenceTxn`, `moveToRetired`, `mergePreferences`) as one
- * append-only JSONL line under `Brain/log/pref-audit/<pref-id>.jsonl`.
- * Because the trail is written where the content hash is computed, it is
+ * append-only JSONL line under
+ * `Brain/log/pref-audit/<pref-id>/device[.<deviceId>].jsonl` - one file
+ * per preference per device (who-wrote-what, Task B), so two machines
+ * editing the same preference never contend for one synced file. Because
+ * the trail is written where the content hash is computed, it is
* authoritative (true before/after) and also catches manual edits routed
* through the same primitives.
*
+ * ## Why a directory per preference
+ *
+ * The trail was flat - `<pref-id>[.<deviceId>].jsonl` - and that name is
+ * ambiguous, because {@link import('./paths.ts').validateSlug} permits a
+ * dot inside a preference id. `pref-a.b.jsonl` is BOTH the legacy trail
+ * of the preference `pref-a.b` and `pref-a`'s shard on a device called
+ * `b`: reading `pref-a` returned the neighbour's records, and appending
+ * for `pref-a` on device `b` wrote into the neighbour's file.
+ *
+ * No separator fixes it. Every character `validateSlug` accepts can also
+ * appear inside a preference id, so any flat name built from
+ * `(prefId, deviceId)` is a name some other valid preference id could
+ * own. One path SEGMENT per preference can not be another preference's
+ * segment, so the directory is the layout that makes the collision
+ * impossible rather than unlikely. Inside it the file is named by a fixed
+ * stem plus the shard id, which is the same grammar every other ledger
+ * uses and which gives the empty (legacy) shard id a name.
+ *
+ * Legacy flat files stay readable and are never renamed: a read merges
+ * `<pref-id>[.<deviceId>].jsonl` from the parent directory with the
+ * per-preference directory. Because a flat name can be ambiguous, every
+ * record read is checked against the id that was asked for; a record
+ * carrying a different `pref_id` is DROPPED and reported as a warning,
+ * never silently mixed in.
+ *
* No-op contract: for an `update` op, {@link appendPrefAudit} writes
* nothing and returns `false` when `hash_before === hash_after` (both
* present and equal), i.e. the write did not change the preference
@@ -23,10 +51,24 @@
* (kept as the raw string), matching the log-reader tolerance contract.
*/
-import { appendFileSync, existsSync, mkdirSync, readFileSync } from "node:fs";
+import { appendFileSync, mkdirSync, readFileSync } from "node:fs";
import { dirname } from "node:path";
-import { prefAuditPath } from "./paths.ts";
+import {
+ listShardedFiles,
+ literalBase,
+ mergeShardedRows,
+ type LedgerShardGrammar,
+ type ShardedRow,
+} from "./ledger-shards.ts";
+import {
+ PREF_AUDIT_EXT,
+ PREF_AUDIT_STEM,
+ prefAuditDir,
+ prefAuditPath,
+ prefAuditPrefDir,
+ validateSlug,
+} from "./paths.ts";
import { assertVaultIdentityForWrite } from "./vault-identity.ts";
import { isoSecond } from "./time.ts";
import { PREF_AUDIT_OP, type PrefAuditOp, type PrefAuditRecord } from "./types.ts";
@@ -134,47 +176,95 @@ export function appendPrefAudit(
}
/**
- * Read the full mutation history for one preference id, oldest first.
- * Returns empty records (no warnings) when the file does not exist.
- * Malformed lines and rows missing required fields become warnings;
- * unknown op kinds are preserved verbatim.
+ * Read the full mutation history for one preference id, oldest first,
+ * merged across every device shard.
+ *
+ * Two places hold shards: the per-preference directory every current
+ * write lands in, and the legacy flat names beside it. Both are read; the
+ * legacy ones first, so a same-timestamp tie between the two layouts
+ * resolves the same way on every device. The merge order is (`ts`, shard
+ * id, line), so two machines show the same history whatever order
+ * Syncthing delivered the files in. Returns empty records (no warnings)
+ * when no shard exists. Malformed lines and rows missing required fields
+ * become warnings naming the shard they came from; unknown op kinds are
+ * preserved verbatim.
+ *
+ * A record whose `pref_id` is not the one asked for is DROPPED with a
+ * warning rather than returned: a legacy flat name is ambiguous (see the
+ * module docblock), and answering with the neighbour's history is the one
+ * answer a caller cannot detect.
*/
export function readPrefAudit(vault: string, prefId: string): ReadPrefAuditResult {
- const path = prefAuditPath(vault, prefId);
- if (!existsSync(path)) return { records: [], warnings: [] };
-
- let text: string;
- try {
- text = readFileSync(path, "utf8");
- } catch (err) {
- const message = (err as NodeJS.ErrnoException).message ?? String(err);
- return {
- records: [],
- warnings: [{ path, lineNumber: 0, message: `failed to read audit file: ${message}` }],
- };
- }
-
- const records: PrefAuditRecord[] = [];
+ const wanted = validateSlug(prefId);
+ const rows: Array<ShardedRow<PrefAuditRecord>> = [];
const warnings: PrefAuditParseWarning[] = [];
- const lines = text.split(/\r?\n/);
- for (let i = 0; i < lines.length; i++) {
- const line = lines[i]!;
- if (line.trim() === "") continue;
- let parsed: unknown;
+ const shards = [
+ ...listShardedFiles(prefAuditDir(vault), legacyPrefAuditGrammar(wanted)),
+ ...listShardedFiles(prefAuditPrefDir(vault, wanted), PREF_AUDIT_GRAMMAR),
+ ];
+ for (const shard of shards) {
+ const path = shard.path;
+ let text: string;
try {
- parsed = JSON.parse(line);
- } catch {
- warnings.push({
- path,
- lineNumber: i + 1,
- message: `malformed JSONL line: ${line.slice(0, 80)}`,
- });
+ text = readFileSync(path, "utf8");
+ } catch (err) {
+ const message = (err as NodeJS.ErrnoException).message ?? String(err);
+ warnings.push({ path, lineNumber: 0, message: `failed to read audit file: ${message}` });
continue;
}
- const rec = coerceRecord(parsed, path, i + 1, warnings);
- if (rec !== null) records.push(rec);
+ const lines = text.split(/\r?\n/);
+ let index = 0;
+ for (let i = 0; i < lines.length; i++) {
+ const line = lines[i]!;
+ if (line.trim() === "") continue;
+ let parsed: unknown;
+ try {
+ parsed = JSON.parse(line);
+ } catch {
+ warnings.push({
+ path,
+ lineNumber: i + 1,
+ message: `malformed JSONL line: ${line.slice(0, 80)}`,
+ });
+ continue;
+ }
+ const rec = coerceRecord(parsed, path, i + 1, warnings);
+ if (rec === null) continue;
+ if (rec.pref_id !== wanted) {
+ warnings.push({
+ path,
+ lineNumber: i + 1,
+ message:
+ `audit row belongs to ${rec.pref_id}, not ${wanted} - the legacy flat file name is ` +
+ "ambiguous when a preference id contains a dot; this row was not merged",
+ });
+ continue;
+ }
+ rows.push({ value: rec, shardId: shard.shardId, line: index++ });
+ }
}
- return { records, warnings };
+ return { records: mergeShardedRows(rows, (record) => record.ts), warnings };
+}
+
+/**
+ * The name layout of one preference's shards INSIDE its own directory.
+ * The base is the fixed stem, so the directory alone decides which
+ * preference a file belongs to and no id can be mistaken for a shard.
+ */
+const PREF_AUDIT_GRAMMAR: LedgerShardGrammar = Object.freeze({
+ base: literalBase(PREF_AUDIT_STEM),
+ extensions: Object.freeze([PREF_AUDIT_EXT]),
+});
+
+/**
+ * The legacy flat layout: `<pref-id>[.<deviceId>].jsonl` beside the
+ * per-preference directories. Still read, never written, never renamed.
+ * The pref id goes in as a literal so an unescaped dot cannot widen the
+ * pattern - but the name remains ambiguous in the other direction, which
+ * is why every row it yields is checked against `pref_id`.
+ */
+function legacyPrefAuditGrammar(prefId: string): LedgerShardGrammar {
+ return { base: literalBase(prefId), extensions: [PREF_AUDIT_EXT] };
}
/**
diff --git a/src/core/brain/types.ts b/src/core/brain/types.ts
index 17acb78f..093b7500 100644
--- a/src/core/brain/types.ts
+++ b/src/core/brain/types.ts
@@ -493,6 +493,46 @@ export const BRAIN_LOG_EVENT_KIND = {
* no event, so the log records changes and not calls.
*/
expirationSet: "expiration-set",
+ /**
+ * `freeze` (who-wrote-what, Task C) - an operator stopped every content
+ * writer on every device by writing `Brain/.state/frozen.json`. Payload
+ * carries the `reason` (or the empty string when none was given), the
+ * `device_id` the freeze was set from, and the `agent`. Emitted only on
+ * a real transition: freezing an already-frozen vault changes nothing
+ * and writes nothing, so the log records the stop and not the attempt.
+ */
+ freeze: "freeze",
+ /**
+ * `unfreeze` (who-wrote-what, Task C) - the freeze marker was removed
+ * and the content lane reopened. Payload carries the `frozen_at`,
+ * `by` and `reason` read off the marker before it went, plus the
+ * `agent` lifting it: the marker's whole content was its existence, so
+ * this event is the only place that record survives.
+ */
+ unfreeze: "unfreeze",
+ /**
+ * `write-refused` (who-wrote-what, Task C) - a write was refused
+ * because the vault is frozen. Recorded at the MCP tool boundary, which
+ * is the one seam that knows both the refusal and the caller: the guard
+ * itself cannot append (it sits below the log module). Payload carries
+ * the `tool`, the `agent`, and the `reason` the marker gave.
+ */
+ writeRefused: "write-refused",
+ /**
+ * `note-write` (who-wrote-what, Task A / t_662f4e82) - one vault note
+ * was created, updated, appended to, or reverted. This is the event
+ * that makes the bulk of what an agent produces attributable at all:
+ * before it, a note write left no trace in the log and no row in any
+ * roster, so "which notes did this agent touch" had no answer. Payload
+ * carries the `write_id`, the `op` ({@link NOTE_WRITE_OP}), the
+ * vault-relative `target`, the content hash and byte size on both sides
+ * of the write (`hash_before` spelled `absent` when the target did not
+ * exist), and the `agent`; the device rides on the shard name and the
+ * `origin_channel` is stamped by the appender. One event per write,
+ * appended AFTER the bytes land - a create that skipped an occupied
+ * target wrote nothing and records nothing.
+ */
+ noteWrite: "note-write",
} as const;
export type BrainLogEventKind = (typeof BRAIN_LOG_EVENT_KIND)[keyof typeof BRAIN_LOG_EVENT_KIND];
@@ -612,6 +652,13 @@ export const BRAIN_SNAPSHOT_REASON = Object.freeze({
* archive's filename prefix.
*/
noteDelete: "note-delete",
+ /**
+ * Pre-apply point taken before `o2b brain writes revert --apply`
+ * restores before-images or removes the notes its selected writes
+ * created (who-wrote-what, Task D). Kebab-case like its siblings
+ * because the value doubles as the archive's filename prefix.
+ */
+ noteRevert: "note-revert",
/** Deferred: a session boundary. No producer in this release. */
sessionBoundary: "session-boundary",
/** Deferred: a plan boundary. No producer in this release. */
@@ -663,7 +710,8 @@ export type PrefAuditOp = (typeof PREF_AUDIT_OP)[keyof typeof PREF_AUDIT_OP];
/**
* One append-only audit line for a single preference mutation. Stored
- * as JSONL under `Brain/log/pref-audit/<pref-id>.jsonl`. `op` is widened
+ * as JSONL under `Brain/log/pref-audit/<pref-id>[.<device-id>].jsonl`,
+ * one file per preference per device. `op` is widened
* to `string` on read so an unknown future op kind round-trips without
* loss. Revision/hash before-after are `null` where not applicable
* (e.g. `hash_before` is `null` on a `create`).
diff --git a/src/core/brain/vault-identity.ts b/src/core/brain/vault-identity.ts
index 1040baba..c9d073af 100644
--- a/src/core/brain/vault-identity.ts
+++ b/src/core/brain/vault-identity.ts
@@ -88,6 +88,7 @@ import {
type DegradationNotice,
} from "../integrity/degradation.ts";
import { compareStamps, formatStampMismatch, type StampMismatch } from "../integrity/stamp.ts";
+import { assertVaultNotFrozen, WRITE_LANE, type WriteLane } from "./freeze-marker.ts";
import { BRAIN_ROOT_REL } from "./path-constants.ts";
/** Marker schema version. Bumped only on an incompatible field change. */
@@ -350,9 +351,30 @@ export function vaultMarkerAbsentNotice(vault: string): DegradationNotice | null
* reads. The assertion therefore belongs to the writer, and it belongs
* BEFORE the writer's first byte - a refusal that arrives after the page
* is on disk has already materialized the wrong store.
+ *
+ * ## The freeze rides here, and why here rather than at the note seam
+ *
+ * `lane` selects which half of the write surface the caller belongs to
+ * (who-wrote-what, Task C). The default, {@link WRITE_LANE.content},
+ * refuses while `Brain/.state/frozen.json` exists - and it is checked
+ * FIRST, ahead of the identity comparison, because a frozen vault is a
+ * decision an operator made and an identity mismatch is a condition they
+ * have not seen yet; reporting the second while the first holds would
+ * answer a question nobody asked.
+ *
+ * This guard is the freeze's seam because it is the only position every
+ * content writer already passes. Hooking the note-write seam instead
+ * would have left the dream pass, hygiene, page-dedup and the
+ * write-session engine writing preferences, signals and state straight
+ * through a freeze.
*/
-export function assertVaultIdentityForWrite(vault: string, sink?: DegradationNotice[]): void {
+export function assertVaultIdentityForWrite(
+ vault: string,
+ sink?: DegradationNotice[],
+ lane: WriteLane = WRITE_LANE.content,
+): void {
const root = resolve(vault);
+ if (lane === WRITE_LANE.content) assertVaultNotFrozen(root);
const vaultId = currentVaultId(root);
if (vaultId === null) {
if (sink !== undefined) {
diff --git a/src/core/brain/write-batch.ts b/src/core/brain/write-batch.ts
index 9acfb893..2b3e7b16 100644
--- a/src/core/brain/write-batch.ts
+++ b/src/core/brain/write-batch.ts
@@ -26,13 +26,19 @@
* (temp file + rename), so no single target is ever left half-written.
*/
-import { existsSync, mkdirSync } from "node:fs";
+import { existsSync, mkdirSync, readFileSync } from "node:fs";
import { dirname } from "node:path";
import type { FrontmatterMap } from "../types.ts";
import { atomicWriteFileSync } from "../fs-atomic.ts";
import { CreateNoteError, createNote, resolveNoteTarget } from "./notes/create-note.ts";
import { refuseBlankOverwrite } from "./notes/blank-overwrite-guard.ts";
+import {
+ NOTE_WRITE_OP,
+ recordNoteWrite,
+ storeBeforeImage,
+ type NoteWriteOp,
+} from "./notes/write-record.ts";
import { formatFrontmatter, parseFrontmatterWithNotices } from "../vault.ts";
import { DEGRADATION_CODE } from "../integrity/degradation.ts";
import {
@@ -205,11 +211,37 @@ export class WriteBatchError extends Error {
}
}
+/**
+ * The audit half every note-write result carries (who-wrote-what, Task A).
+ *
+ * `write_id` names the `note-write` event that attributes the write; it is
+ * null when the bytes landed and the event could not be appended, and in
+ * that case - and only that case - `audit_reason` says why. The two travel
+ * together so a caller can never read an unrecorded write as a recorded
+ * one.
+ */
+export interface NoteWriteAudit {
+ readonly write_id: string | null;
+ readonly audit_reason?: string;
+}
+
/** Per-operation outcome, discriminated by `kind`. */
export type WriteBatchOpResult =
- | { readonly kind: "create_note"; readonly path: string; readonly created: true }
- | { readonly kind: "update_note"; readonly path: string; readonly updated: true }
- | { readonly kind: "append_note"; readonly path: string; readonly appended: true }
+ | ({
+ readonly kind: "create_note";
+ readonly path: string;
+ readonly created: true;
+ } & NoteWriteAudit)
+ | ({
+ readonly kind: "update_note";
+ readonly path: string;
+ readonly updated: true;
+ } & NoteWriteAudit)
+ | ({
+ readonly kind: "append_note";
+ readonly path: string;
+ readonly appended: true;
+ } & NoteWriteAudit)
| { readonly kind: "apply_evidence"; readonly logged_at: string; readonly log_path: string }
| { readonly kind: "append_log_line"; readonly logged_at: string; readonly log_path: string };
@@ -227,6 +259,17 @@ interface PlannedOperation {
readonly commit: () => WriteBatchOpResult;
}
+/** Facts the kernel needs that are not part of any single operation. */
+export interface ApplyWriteBatchOptions {
+ /**
+ * Config file that names the writing agent, for the note-write record
+ * (who-wrote-what, Task A). Absent falls back to the shared discovery;
+ * a caller that knows which config it runs under passes it so the
+ * record names the agent the caller is.
+ */
+ readonly configPath?: string;
+}
+
/**
* Apply an ordered batch of write operations atomically. Validates and
* projects every operation in memory first; only if all pass does it
@@ -236,6 +279,7 @@ interface PlannedOperation {
export function applyWriteBatch(
vault: string,
operations: ReadonlyArray<WriteOperation>,
+ opts: ApplyWriteBatchOptions = {},
): WriteBatchResult {
// Vault-identity write guard (context-integrity-gates, Unit J).
assertVaultIdentityForWrite(vault);
@@ -256,7 +300,7 @@ export function applyWriteBatch(
// would silently clobber the first at commit time. Refuse it loudly.
const noteTargets = new Set<string>();
const planned: PlannedOperation[] = operations.map((operation, index) =>
- projectOperation(vault, operation, index, noteTargets),
+ projectOperation(vault, operation, index, noteTargets, opts),
);
const results = planned.map((p) => p.commit());
@@ -268,15 +312,16 @@ function projectOperation(
operation: WriteOperation,
index: number,
noteTargets: Set<string>,
+ opts: ApplyWriteBatchOptions,
): PlannedOperation {
const kind = (operation as { readonly kind?: unknown } | null | undefined)?.kind;
switch (kind) {
case "create_note":
- return projectCreateNote(vault, operation as CreateNoteOperation, index, noteTargets);
+ return projectCreateNote(vault, operation as CreateNoteOperation, index, noteTargets, opts);
case "update_note":
- return projectUpdateNote(vault, operation as UpdateNoteOperation, index, noteTargets);
+ return projectUpdateNote(vault, operation as UpdateNoteOperation, index, noteTargets, opts);
case "append_note":
- return projectAppendNote(vault, operation as AppendNoteOperation, index, noteTargets);
+ return projectAppendNote(vault, operation as AppendNoteOperation, index, noteTargets, opts);
case "apply_evidence":
return projectApplyEvidence(vault, operation as ApplyEvidenceOperation, index);
case "append_log_line":
@@ -338,6 +383,7 @@ function projectCreateNote(
op: CreateNoteOperation,
index: number,
noteTargets: Set<string>,
+ opts: ApplyWriteBatchOptions,
): PlannedOperation {
const target = reserveNoteTarget(vault, op.path, index, noteTargets);
// Pre-check existence so a clobber aborts the batch before any commit.
@@ -358,8 +404,30 @@ function projectCreateNote(
path: op.path,
...(op.frontmatter !== undefined ? { frontmatter: op.frontmatter } : {}),
...(op.content !== undefined ? { content: op.content } : {}),
+ ...(opts.configPath !== undefined ? { configPath: opts.configPath } : {}),
});
- return { kind: "create_note", path: res.path, created: true };
+ if (res.outcome !== "created") {
+ // Unreachable by construction: the batch exposes none of the
+ // authoring modes, so `ifExists` is never sent and an occupied
+ // target is a refusal rather than a skip. Named rather than
+ // cast, because a cast would report `created: true` for a call
+ // that created nothing.
+ throw new WriteBatchError(
+ "exists",
+ index,
+ `operation ${index}: note already exists: ${res.path}`,
+ { path: res.path },
+ );
+ }
+ // The create writer records its own event, so the batch carries
+ // its receipt through rather than appending a second one.
+ return {
+ kind: "create_note",
+ path: res.path,
+ created: true,
+ write_id: res.write_id,
+ ...(res.audit_reason !== undefined ? { audit_reason: res.audit_reason } : {}),
+ };
} catch (err) {
throw envelopeError(err, index);
}
@@ -372,6 +440,7 @@ function projectUpdateNote(
op: UpdateNoteOperation,
index: number,
noteTargets: Set<string>,
+ opts: ApplyWriteBatchOptions,
): PlannedOperation {
if (op.frontmatter === undefined && op.body === undefined) {
throw new WriteBatchError(
@@ -407,9 +476,15 @@ function projectUpdateNote(
const contents = formatFrontmatter(frontmatter, body);
return {
commit: () => {
- mkdirSync(dirname(target.abs), { recursive: true });
- atomicWriteFileSync(target.abs, contents);
- return { kind: "update_note", path: target.relPath, updated: true };
+ const audit = commitNoteRewrite(
+ vault,
+ target,
+ state.raw,
+ contents,
+ NOTE_WRITE_OP.update,
+ opts,
+ );
+ return { kind: "update_note", path: target.relPath, updated: true, ...audit };
},
};
}
@@ -419,6 +494,7 @@ function projectAppendNote(
op: AppendNoteOperation,
index: number,
noteTargets: Set<string>,
+ opts: ApplyWriteBatchOptions,
): PlannedOperation {
if (typeof op.content !== "string" || op.content.trim().length === 0) {
throw new WriteBatchError(
@@ -434,13 +510,49 @@ function projectAppendNote(
const contents = formatFrontmatter(state.frontmatter, body);
return {
commit: () => {
- mkdirSync(dirname(target.abs), { recursive: true });
- atomicWriteFileSync(target.abs, contents);
- return { kind: "append_note", path: target.relPath, appended: true };
+ const audit = commitNoteRewrite(
+ vault,
+ target,
+ state.raw,
+ contents,
+ NOTE_WRITE_OP.append,
+ opts,
+ );
+ return { kind: "append_note", path: target.relPath, appended: true, ...audit };
},
};
}
+/**
+ * Commit one note rewrite and attribute it, in the order the design
+ * fixes: keep the bytes this write replaces, write, record.
+ *
+ * The image goes FIRST because it is the only copy of the prior content
+ * that survives the rename - a process that dies between the rename and
+ * the record loses the audit line, which is recoverable, rather than the
+ * bytes, which are not. The record goes LAST and cannot fail the write:
+ * `recordNoteWrite` returns its failure, and this returns it too.
+ */
+function commitNoteRewrite(
+ vault: string,
+ target: { readonly relPath: string; readonly abs: string },
+ before: string,
+ contents: string,
+ op: NoteWriteOp,
+ opts: ApplyWriteBatchOptions,
+): NoteWriteAudit {
+ mkdirSync(dirname(target.abs), { recursive: true });
+ storeBeforeImage(vault, before);
+ atomicWriteFileSync(target.abs, contents);
+ return recordNoteWrite(vault, {
+ op,
+ target: target.relPath,
+ before: { bytes: before },
+ after: { bytes: contents },
+ ...(opts.configPath !== undefined ? { configPath: opts.configPath } : {}),
+ });
+}
+
/** Accepted apply-evidence result values, for phase-1 validation. */
const APPLY_RESULTS: ReadonlySet<string> = new Set([
BRAIN_APPLY_RESULT.applied,
@@ -559,6 +671,17 @@ function projectAppendLogLine(
interface ExistingNote {
readonly frontmatter: FrontmatterMap;
readonly body: string;
+ /**
+ * The target's bytes exactly as they sit on disk (who-wrote-what,
+ * Task A).
+ *
+ * Not `formatFrontmatter(frontmatter, body)`: the before-image and the
+ * `hash_before` have to describe what a revert would put BACK, and a
+ * re-serialisation of the parsed halves is what this build would have
+ * written, not what the previous writer did. Key order, spacing and a
+ * hand-edited block all survive here and would not survive there.
+ */
+ readonly raw: string;
}
/** Attribution for the frontmatter notices this reader inspects. */
@@ -620,5 +743,8 @@ function readExistingNote(abs: string, relPath: string, index: number): Existing
{ path: relPath, reason },
);
}
- return { frontmatter: { ...frontmatter }, body };
+ // Read after the parse rather than before it: the two notices above
+ // are the named ways this file can be unavailable, and a raw read that
+ // ran first would have to invent a third.
+ return { frontmatter: { ...frontmatter }, body, raw: readFileSync(abs, "utf8") };
}
diff --git a/src/core/integrity/degradation.ts b/src/core/integrity/degradation.ts
index bcac8388..6353d1c0 100644
--- a/src/core/integrity/degradation.ts
+++ b/src/core/integrity/degradation.ts
@@ -95,6 +95,28 @@ export const DEGRADATION_CODE = Object.freeze({
* write path rather than a warning.
*/
vaultMarkerMismatch: "vault-marker-mismatch",
+ /**
+ * Task C. An operator froze this vault, so the content lane refuses
+ * every write until the marker is removed. Unlike the two above this is
+ * an INTENDED state rather than a defect: the notice exists so the
+ * refusal names when the freeze was set, who set it, why, and the one
+ * command that lifts it.
+ */
+ vaultFrozen: "vault-frozen",
+ /**
+ * Task E. A shard of the Brain log does not link up: a line's hash does
+ * not recompute, its `prev` does not name the line before it, or a line
+ * carries no chain fields where the chain had already started. Distinct
+ * from {@link DEGRADATION_CODE.lineageChainBroken} because it names a
+ * different file with a different chain shape - one shard per device
+ * per day rather than one ledger - and an operator holding the finding
+ * has to know which of the two to open.
+ *
+ * Report-only, exactly like its lineage sibling: the log's read path
+ * never consults the chain, so a broken shard still yields every event
+ * it holds.
+ */
+ logChainBroken: "log-chain-broken",
} as const);
/**
diff --git a/src/core/search/visibility-surface-registry.ts b/src/core/search/visibility-surface-registry.ts
index 9675cd2e..23d26f7d 100644
--- a/src/core/search/visibility-surface-registry.ts
+++ b/src/core/search/visibility-surface-registry.ts
@@ -352,6 +352,18 @@ export const VISIBILITY_SURFACE_REGISTRY: ReadonlyArray<VisibilitySurfaceEntry>
"comment, 'contribution rows - ids, topics and the record text' from the provenance fold, " +
"gated by an explicit agent_scope argument only - never by visibility.",
},
+ {
+ surface: "brain_writes",
+ kind: K.mcpTool,
+ category: C.excluded,
+ reason:
+ "listNoteWrites (core/brain/notes/write-log.ts) projects `note-write` events out of the " +
+ "Brain log and never opens the notes they name, so no `visibility:` is on the path to be " +
+ "consulted. It returns a target PATH and two content digests rather than any note body - " +
+ "which bounds the exposure to the existence of a page and its name, not its prose - but " +
+ "the path of a note marked private is still reported, so this is excluded rather than " +
+ "covered.",
+ },
{
surface: "brain_agent_diff",
kind: K.mcpTool,
diff --git a/src/core/state/surfaces.ts b/src/core/state/surfaces.ts
index c7f4a149..d197bb8d 100644
--- a/src/core/state/surfaces.ts
+++ b/src/core/state/surfaces.ts
@@ -126,6 +126,8 @@ export const STATE_SURFACE_ID = Object.freeze({
captureDecisionLog: "capture_decision_log",
decisionReceipts: "decision_receipts",
lineageLedger: "lineage_ledger",
+ freezeMarker: "freeze_marker",
+ writeImages: "write_images",
anticipatoryCache: "anticipatory_cache",
exactState: "exact_state",
searchFeedback: "search_feedback",
@@ -279,6 +281,8 @@ const PROPOSAL_WATERMARK_FILE = "proposal-watermark.json";
const TRUTH_DIR = "truth";
const BRAIN_INTERNAL_STATE_DIR = ".state";
const LINEAGE_LEDGER_FILE = "session-lineage.jsonl";
+const FROZEN_MARKER_FILE = "frozen.json";
+const WRITE_IMAGES_DIR = "write-images";
const ANTICIPATORY_DIR = "anticipatory";
const SEARCH_STATE_DIR = "search";
const SEARCH_FEEDBACK_DIR = "feedback";
@@ -614,12 +618,13 @@ export const STATE_SURFACES: ReadonlyArray<StateSurface> = Object.freeze([
label: "continuity ledger",
tier: STATE_TIER.vaultContent,
derive: brainLog(CONTINUITY_DIR),
- override_env: null,
- override_config_key: null,
+ override_env: DEVICE_ID_ENV,
+ override_config_key: DEVICE_ID_CONFIG_KEY,
carries_memory: true,
reason:
- "One JSONL shard per month recording session handovers, so a new session can pick up what " +
- "the previous one left unfinished. Nothing recomputes a handover that was never written.",
+ "One JSONL file per month per device (`<month>.<device-id>.jsonl`) recording session " +
+ "handovers, so a new session can pick up what the previous one left unfinished and two " +
+ "machines never write one file. Nothing recomputes a handover that was never written.",
sources: ["src/core/brain/continuity/store.ts"],
},
{
@@ -640,11 +645,13 @@ export const STATE_SURFACES: ReadonlyArray<StateSurface> = Object.freeze([
label: "preference mutation audit",
tier: STATE_TIER.vaultContent,
derive: brainLog(PREF_AUDIT_DIR),
- override_env: null,
- override_config_key: null,
+ override_env: DEVICE_ID_ENV,
+ override_config_key: DEVICE_ID_CONFIG_KEY,
carries_memory: true,
reason:
- "One append-only JSONL per preference recording every promotion, edit and retirement. It " +
+ "One append-only JSONL per preference per device (`<pref-id>/device.<device-id>.jsonl`) " +
+ "recording every promotion, edit and retirement. A directory per preference because a " +
+ "preference id may contain a dot, which a flat name cannot tell from a device suffix. It " +
"is the provenance behind a rule the agents follow, and it cannot be reconstructed from " +
"the preference file it describes.",
sources: ["src/core/brain/paths.ts"],
@@ -710,15 +717,47 @@ export const STATE_SURFACES: ReadonlyArray<StateSurface> = Object.freeze([
label: "session lineage ledger",
tier: STATE_TIER.vaultContent,
derive: brainTree(BRAIN_INTERNAL_STATE_DIR, LINEAGE_LEDGER_FILE),
- override_env: null,
- override_config_key: null,
+ override_env: DEVICE_ID_ENV,
+ override_config_key: DEVICE_ID_CONFIG_KEY,
carries_memory: false,
reason:
"Which session followed which, plus a companion gap file naming the observations that " +
"never reached it. It is how a broken chain is detectable at all, so deleting it hides " +
- "gaps rather than closing them.",
+ "gaps rather than closing them. The name above is the shard with the EMPTY device id; " +
+ "a machine with a device id writes `session-lineage.<device-id>.jsonl` beside it, one " +
+ "hash chain per file, and a reader merges every shard it finds.",
sources: ["src/core/brain/lineage/ledger.ts"],
},
+ {
+ id: STATE_SURFACE_ID.freezeMarker,
+ label: "fleet freeze marker",
+ tier: STATE_TIER.vaultContent,
+ derive: brainTree(BRAIN_INTERNAL_STATE_DIR, FROZEN_MARKER_FILE),
+ override_env: null,
+ override_config_key: null,
+ carries_memory: false,
+ reason:
+ "While this file exists every content writer on every device that syncs the vault " +
+ "refuses, which is exactly what an operator asked for when they wrote it. Deleting it " +
+ "by hand is the same act as `o2b brain unfreeze` minus the log event that would have " +
+ "recorded who lifted the stop.",
+ sources: ["src/core/brain/freeze-marker.ts"],
+ },
+ {
+ id: STATE_SURFACE_ID.writeImages,
+ label: "note-write before-images",
+ tier: STATE_TIER.vaultContent,
+ derive: brainTree(BRAIN_INTERNAL_STATE_DIR, WRITE_IMAGES_DIR),
+ override_env: null,
+ override_config_key: null,
+ carries_memory: true,
+ reason:
+ "The bytes each recorded note write replaced, one file per distinct prior content. It is " +
+ "what lets a write be undone from what it displaced rather than from a whole-tree " +
+ "archive, so deleting it narrows how far back a revert can reach - which the revert plan " +
+ "then reports by name. It holds note prose, so it is a copy of your vault text.",
+ sources: ["src/core/brain/notes/write-record.ts", "src/core/brain/paths.ts"],
+ },
{
id: STATE_SURFACE_ID.anticipatoryCache,
label: "anticipatory context cache",
@@ -832,12 +871,13 @@ export const STATE_SURFACES: ReadonlyArray<StateSurface> = Object.freeze([
label: "per-surface metrics",
tier: STATE_TIER.vaultContent,
derive: brainTree(METRICS_DIR),
- override_env: null,
- override_config_key: null,
+ override_env: DEVICE_ID_ENV,
+ override_config_key: DEVICE_ID_CONFIG_KEY,
carries_memory: false,
reason:
- "One append-only JSONL per instrumented surface, timestamped per run. They are " +
- "observations of runs that already finished, so nothing regenerates them.",
+ "One append-only JSONL per instrumented surface per device " +
+ "(`<surface>.<device-id>.jsonl`), timestamped per run and merged across devices at read. " +
+ "They are observations of runs that already finished, so nothing regenerates them.",
sources: ["src/core/brain/metrics.ts"],
},
{
@@ -1128,12 +1168,15 @@ export function inventoryStateSurfaces(input: StateInventoryInput): StateInvento
/**
* Whether the override value is a PATH the derivation should use.
*
- * The device-id override selects a shard filename inside a directory this
- * inventory reports at directory granularity, so feeding it to the
- * derivation would build `<vault>/Brain/<device-id>`. The origin is still
- * reported, because "your log shard is named by an environment variable"
- * is exactly the provenance an operator looking for their own writes
- * needs; only the path substitution is withheld.
+ * The device-id override selects a shard FILENAME, not a location, so
+ * feeding it to the derivation would build `<vault>/Brain/<device-id>`.
+ * Most rows it applies to are reported at directory granularity, which
+ * already contains every shard; the one row that names a single file
+ * (the session lineage ledger) says in its own `reason` that the name
+ * shown is the empty-shard one. The origin is still reported either way,
+ * because "your shard is named by an environment variable" is exactly the
+ * provenance an operator looking for their own writes needs; only the
+ * path substitution is withheld.
*/
function movesPath(surface: StateSurface): boolean {
return surface.override_env !== DEVICE_ID_ENV;
diff --git a/src/mcp/brain/lifecycle-file-tools.ts b/src/mcp/brain/lifecycle-file-tools.ts
index 11dd7e1e..1b07b0b4 100644
--- a/src/mcp/brain/lifecycle-file-tools.ts
+++ b/src/mcp/brain/lifecycle-file-tools.ts
@@ -311,6 +311,7 @@ async function toolBrainScaffoldStub(
sources: coerceStringArray(args, "sources"),
...(ifExists !== undefined ? { ifExists: ifExists as CreateNoteIfExists } : {}),
...(apply !== undefined ? { apply } : {}),
+ ...(ctx.configPath !== null ? { configPath: ctx.configPath } : {}),
});
return {
action,
diff --git a/src/mcp/brain/notes-tools.ts b/src/mcp/brain/notes-tools.ts
index 56a5483e..77633701 100644
--- a/src/mcp/brain/notes-tools.ts
+++ b/src/mcp/brain/notes-tools.ts
@@ -37,12 +37,14 @@ import {
WriteBatchError,
type AppendNoteOperation,
type UpdateNoteOperation,
+ type NoteWriteAudit,
type WriteBatchOpResult,
} from "../../core/brain/write-batch.ts";
import { nextCommandField } from "../../core/brain/next-step.ts";
import { lintWrittenPages, pageLintField, type PageLintField } from "../../core/brain/page-lint.ts";
import { WRITE_BINDING_REFUSED_CODE } from "../../core/write-binding/index.ts";
import { isFrontmatterKey } from "../../core/vault.ts";
+import { rethrowVaultFrozen } from "../frozen-refusal.ts";
import { INTERNAL_ERROR, INVALID_PARAMS, MCPError } from "../protocol.ts";
import type { ServerContext, ToolDefinition } from "../tool-contract.ts";
import { coerceBoolOptional, coerceStr, coerceStringOptional } from "../coerce.ts";
@@ -199,6 +201,7 @@ export function parseFrontmatterArg(
* than an opaque throw.
*/
export function writeBatchErrorToMcp(err: unknown, tool: string): MCPError {
+ rethrowVaultFrozen(err);
if (err instanceof WriteBatchError) {
return new MCPError(rpcCodeFor(err.code), `${tool}: ${err.message}`, {
code: err.code,
@@ -255,6 +258,10 @@ async function toolBrainCreateNote(
...(strict !== undefined ? { strict } : {}),
...(template !== undefined ? { template } : {}),
...(templateVariables !== undefined ? { templateVariables } : {}),
+ // The note-write record names the agent this server runs as, which
+ // is the one THIS config declares - not the one a machine-default
+ // discovery would find (who-wrote-what, Task A).
+ ...(ctx.configPath !== null ? { configPath: ctx.configPath } : {}),
});
// `outcome` is the discriminant; `created` is the boolean this tool
// has always returned and stays in lockstep with it, so a skip can
@@ -264,6 +271,11 @@ async function toolBrainCreateNote(
created: res.created,
outcome: res.outcome,
path: res.path,
+ // The audit half rides on the receipt for a create and NOT for a
+ // skip (who-wrote-what, Task A): a skip authored no bytes, so it
+ // has no write to attribute and no null that could be mistaken for
+ // a lost one.
+ ...(res.outcome === "created" ? auditFields(res) : {}),
});
} catch (err) {
// Almost every CreateNoteError is a client-input fault (bad path,
@@ -281,6 +293,7 @@ async function toolBrainCreateNote(
...(err.violations.length > 0 ? { violations: err.violations } : {}),
});
}
+ rethrowVaultFrozen(err);
throw new MCPError(INTERNAL_ERROR, err instanceof Error ? err.message : String(err));
}
}
@@ -338,7 +351,11 @@ async function toolBrainUpdateNote(
const result = runSingleWrite(ctx, op, "brain_update_note");
// The flag comes off the kernel result rather than being restated here:
// one fact, one source.
- return noteWriteResult(ctx, [result.path], { updated: result.updated, path: result.path });
+ return noteWriteResult(ctx, [result.path], {
+ updated: result.updated,
+ path: result.path,
+ ...auditFields(result),
+ });
}
/**
@@ -353,7 +370,28 @@ async function toolBrainAppendNote(
const content = coerceStr(args, "content", true)!;
const op: AppendNoteOperation = { kind: "append_note", path, content };
const result = runSingleWrite(ctx, op, "brain_append_note");
- return noteWriteResult(ctx, [result.path], { appended: result.appended, path: result.path });
+ return noteWriteResult(ctx, [result.path], {
+ appended: result.appended,
+ path: result.path,
+ ...auditFields(result),
+ });
+}
+
+/**
+ * The `write_id` (and, when it is null, the `audit_reason`) of one note
+ * write, as receipt fields.
+ *
+ * The bytes land before the event is appended, so `write_id: null` is a
+ * state the caller has to be able to see: the note exists and nothing
+ * attributes it. Both keys are always spelled together - the receipt
+ * never carries a bare null - so an agent reading the reply learns which
+ * of the two happened rather than inferring it from an absence.
+ */
+function auditFields(audit: NoteWriteAudit): Record<string, unknown> {
+ return {
+ write_id: audit.write_id,
+ ...(audit.audit_reason !== undefined ? { audit_reason: audit.audit_reason } : {}),
+ };
}
/** The kernel results that name a note file: exactly the three note ops. */
@@ -381,7 +419,11 @@ function runSingleWrite<K extends SingleNoteOperation["kind"]>(
): Extract<NoteOpResult, { readonly kind: K }> {
let batch;
try {
- batch = applyWriteBatch(ctx.vault, [op]);
+ batch = applyWriteBatch(
+ ctx.vault,
+ [op],
+ ctx.configPath !== null ? { configPath: ctx.configPath } : {},
+ );
} catch (err) {
throw writeBatchErrorToMcp(err, tool);
}
diff --git a/src/mcp/brain/query-tools.ts b/src/mcp/brain/query-tools.ts
index 99cbbd5a..e18793e1 100644
--- a/src/mcp/brain/query-tools.ts
+++ b/src/mcp/brain/query-tools.ts
@@ -21,7 +21,22 @@ import {
import { parseIsoUtc } from "../../core/brain/health/iso-time.ts";
import { diffAgentSources, type AgentSourceDiffMode } from "../../core/brain/agent-source/diff.ts";
import { queryAgentSources } from "../../core/brain/agent-source/query.ts";
-import type { AgentSourceContributionKind } from "../../core/brain/agent-source/types.ts";
+import {
+ NoteRevertError,
+ planNoteRevert,
+ type NoteRevertSelector,
+} from "../../core/brain/notes/revert.ts";
+import { listNoteWrites } from "../../core/brain/notes/write-log.ts";
+import {
+ NOTE_WRITE_OP,
+ NOTE_WRITE_OPS,
+ isNoteWriteOp,
+} from "../../core/brain/notes/write-record.ts";
+import {
+ AGENT_SOURCE_CONTRIBUTION_KINDS,
+ isAgentSourceContributionKind,
+ type AgentSourceContributionKind,
+} from "../../core/brain/agent-source/types.ts";
import {
type BrainPreference,
type BrainRetired,
@@ -282,6 +297,134 @@ async function toolBrainAgentQuery(
}) as unknown as Record<string, unknown>;
}
+/**
+ * The two actions `brain_writes` offers.
+ *
+ * `plan_revert` READS: it returns the plan an operator would apply and
+ * carries no apply path of its own. Applying a revert moves bytes an
+ * agent did not ask for on targets it may not have written, and the
+ * design puts that decision at the CLI where a human types the digest
+ * (`docs/brainstorm/who-wrote-what/design.md`, "No new MCP tool for
+ * freeze"). The plan is the half an agent can act on: it names, per
+ * target, what would happen and why not.
+ */
+const BRAIN_WRITES_ACTION = Object.freeze({
+ list: "list",
+ planRevert: "plan_revert",
+} as const);
+
+const BRAIN_WRITES_ACTIONS: ReadonlyArray<string> = Object.freeze(
+ Object.values(BRAIN_WRITES_ACTION),
+);
+
+/** Default and maximum rows one `brain_writes` list returns. */
+const BRAIN_WRITES_DEFAULT_LIMIT = 50;
+const BRAIN_WRITES_MAX_LIMIT = 500;
+
+async function toolBrainWrites(
+ ctx: ServerContext,
+ args: Record<string, unknown>,
+): Promise<Record<string, unknown>> {
+ const action = coerceStr(args, "action", false) ?? BRAIN_WRITES_ACTION.list;
+ if (action === BRAIN_WRITES_ACTION.planRevert) {
+ return planRevert(ctx, args);
+ }
+ if (action !== BRAIN_WRITES_ACTION.list) {
+ throw new MCPError(
+ INVALID_PARAMS,
+ `brain_writes: 'action' must be one of ${BRAIN_WRITES_ACTIONS.join(", ")}`,
+ );
+ }
+ const rawOp = coerceStr(args, "op", false);
+ if (rawOp !== null && !isNoteWriteOp(rawOp)) {
+ throw new MCPError(
+ INVALID_PARAMS,
+ `brain_writes: 'op' must be one of ${Object.values(NOTE_WRITE_OP).join(", ")}`,
+ );
+ }
+ const agent = coerceStr(args, "agent", false);
+ const device = coerceStr(args, "device", false);
+ const path = coerceStr(args, "path", false);
+ const since = coerceStr(args, "since", false);
+ const until = coerceStr(args, "until", false);
+ const limit = coerceInt(args, "limit", BRAIN_WRITES_DEFAULT_LIMIT, 1, BRAIN_WRITES_MAX_LIMIT);
+
+ const result = listNoteWrites(ctx.vault, {
+ ...(agent !== null ? { agent } : {}),
+ ...(device !== null ? { device } : {}),
+ ...(path !== null ? { path } : {}),
+ ...(since !== null ? { since } : {}),
+ ...(until !== null ? { until } : {}),
+ ...(rawOp !== null ? { op: rawOp } : {}),
+ });
+ // `total_matched` beside `returned` so a truncated answer is legible as
+ // one: a list capped at the limit and a list that IS the whole history
+ // are otherwise the same shape.
+ return {
+ action: BRAIN_WRITES_ACTION.list,
+ total_matched: result.writes.length,
+ returned: Math.min(result.writes.length, limit),
+ writes: result.writes.slice(0, limit).map((w) => ({ ...w })),
+ warnings: result.warnings.map((w) => ({
+ path: w.path,
+ line: w.lineNumber,
+ message: w.message,
+ })),
+ };
+}
+
+/**
+ * The read-only half of the per-agent revert: what undoing the selected
+ * writes WOULD do, sealed by the digest `o2b brain writes revert --apply`
+ * takes.
+ *
+ * Every refusal the planner raises for the whole call - the unbounded
+ * selector, today the only one - comes back as `INVALID_PARAMS` carrying
+ * the CODE, so an agent narrows on a token rather than on a sentence.
+ * Nothing here writes; the digest is the only thing that crosses to the
+ * operator's terminal.
+ */
+function planRevert(ctx: ServerContext, args: Record<string, unknown>): Record<string, unknown> {
+ const selector: NoteRevertSelector = {
+ ...selectorArg(args, "agent"),
+ ...selectorArg(args, "device"),
+ ...selectorArg(args, "path"),
+ ...selectorArg(args, "since"),
+ ...selectorArg(args, "until"),
+ };
+ let plan;
+ try {
+ plan = planNoteRevert(ctx.vault, selector);
+ } catch (err) {
+ if (err instanceof NoteRevertError) {
+ throw new MCPError(INVALID_PARAMS, `brain_writes: ${err.code}: ${err.message}`);
+ }
+ throw err;
+ }
+ return {
+ action: BRAIN_WRITES_ACTION.planRevert,
+ selector: { ...plan.selector },
+ entries: plan.entries.map((entry) => ({ ...entry })),
+ digest: plan.digest,
+ planned_at: plan.planned_at,
+ next_command: `o2b brain writes revert --apply ${plan.digest}`,
+ warnings: plan.warnings.map((w) => ({
+ path: w.path,
+ line: w.lineNumber,
+ message: w.message,
+ })),
+ };
+}
+
+/** One selector field, present only when the caller supplied it. */
+function selectorArg(
+ args: Record<string, unknown>,
+ key: "agent" | "device" | "path" | "since" | "until",
+): Partial<Record<typeof key, string>> {
+ const value = coerceStr(args, key, false);
+ return value === null ? {} : { [key]: value };
+}
+
async function toolBrainAgentDiff(
ctx: ServerContext,
args: Record<string, unknown>,
@@ -314,10 +457,10 @@ function coerceAgentContributionKind(
): AgentSourceContributionKind | null {
const raw = coerceStr(args, key, false);
if (raw === null) return null;
- if (raw !== "signal" && raw !== "preference" && raw !== "log") {
+ if (!isAgentSourceContributionKind(raw)) {
throw new MCPError(
INVALID_PARAMS,
- `argument '${key}' must be 'signal', 'preference', or 'log'`,
+ `argument '${key}' must be one of ${AGENT_SOURCE_CONTRIBUTION_KINDS.join(", ")}`,
);
}
return raw;
@@ -690,7 +833,7 @@ export const QUERY_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([
},
kind: {
type: "string",
- enum: ["signal", "preference", "log"],
+ enum: [...AGENT_SOURCE_CONTRIBUTION_KINDS],
description: "Contribution kind filter.",
},
limit: {
@@ -709,6 +852,56 @@ export const QUERY_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([
},
handler: toolBrainAgentQuery,
},
+ {
+ name: "brain_writes",
+ previewBudget: MCP_PREVIEW_BUDGET,
+ description:
+ "List recorded note writes (create, update, append, revert), newest first, with the agent, the device the log shard names, the target path and the content digest on each side. Filters by agent, device, path, op and time window. plan_revert returns the sealed plan for undoing them. Read-only.",
+ inputSchema: {
+ type: "object",
+ properties: {
+ action: {
+ type: "string",
+ enum: [...BRAIN_WRITES_ACTIONS],
+ description:
+ "list returns recorded writes. plan_revert returns the sealed undo plan; applying it is CLI-only.",
+ },
+ agent: {
+ type: "string",
+ description: "Exact agent identity that recorded the write.",
+ },
+ device: {
+ type: "string",
+ description: "Exact device id; the empty string is the legacy un-sharded log.",
+ },
+ path: {
+ type: "string",
+ description: "Exact vault-relative target path of the note.",
+ },
+ since: {
+ type: "string",
+ description: "Inclusive lower bound: YYYY-MM-DD or an ISO-8601 UTC timestamp.",
+ },
+ until: {
+ type: "string",
+ description: "Inclusive upper bound, same two spellings; a bare date covers its day.",
+ },
+ op: {
+ type: "string",
+ enum: [...NOTE_WRITE_OPS],
+ description: "Operation filter.",
+ },
+ limit: {
+ type: "integer",
+ minimum: 1,
+ maximum: 500,
+ description: "Maximum writes returned. Defaults to 50.",
+ },
+ },
+ additionalProperties: false,
+ },
+ handler: toolBrainWrites,
+ },
{
name: "brain_agent_diff",
description:
@@ -738,7 +931,7 @@ export const QUERY_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([
},
kind: {
type: "string",
- enum: ["signal", "preference", "log"],
+ enum: [...AGENT_SOURCE_CONTRIBUTION_KINDS],
description: "Contribution kind filter.",
},
limit: {
diff --git a/src/mcp/brain/write-batch-tools.ts b/src/mcp/brain/write-batch-tools.ts
index 798e49b6..32d62a3f 100644
--- a/src/mcp/brain/write-batch-tools.ts
+++ b/src/mcp/brain/write-batch-tools.ts
@@ -180,7 +180,11 @@ async function toolBrainWriteBatch(
let batch: WriteBatchResult;
try {
- batch = applyWriteBatch(ctx.vault, operations);
+ batch = applyWriteBatch(
+ ctx.vault,
+ operations,
+ ctx.configPath !== null ? { configPath: ctx.configPath } : {},
+ );
} catch (err) {
throw writeBatchErrorToMcp(err, "brain_write_batch");
}
diff --git a/src/mcp/frozen-refusal.ts b/src/mcp/frozen-refusal.ts
new file mode 100644
index 00000000..63619015
--- /dev/null
+++ b/src/mcp/frozen-refusal.ts
@@ -0,0 +1,146 @@
+/**
+ * What a caller is told when the vault is frozen, and where the refusal
+ * is recorded (who-wrote-what, Task C, Override 2).
+ *
+ * The freeze itself lives in `assertVaultIdentityForWrite`, below the
+ * Brain log module in the import graph. That guard therefore cannot
+ * append the event that says a write was refused - the edge back would
+ * close a cycle paid for by every consumer in the tree. So the record is
+ * made at the one seam that already knows both the refusal and who
+ * caused it: the MCP tool-dispatch boundary, which sees the thrown
+ * `VaultFrozenError`, the tool name, and the resolved agent identity.
+ *
+ * That is the right place for a second reason as well. The event is the
+ * AGENT-facing audit trail, and the agent side is the side a fleet
+ * freeze exists to hold: an operator lifting a freeze wants to know what
+ * kept trying to write while it was on.
+ *
+ * ## The refusal is structured, not prose
+ *
+ * A caller that can only regex a sentence cannot act on it. The `data`
+ * payload carries the four facts an agent needs - when the freeze was
+ * set, by whom, why, and the one command that lifts it - in the same
+ * shape `./reach-refusal.ts` uses for the boundary it guards.
+ *
+ * ## Recording never fails the refusal
+ *
+ * The write was already refused; the event is the record of it. A log
+ * append that throws must not turn a clean refusal into an internal
+ * error, so the append is best-effort and its failure is reported to the
+ * caller as an `audit_reason` on the same payload rather than swallowed.
+ * The refusal itself is the load-bearing answer.
+ */
+
+import { appendLogEvent } from "../core/brain/log.ts";
+import { BRAIN_LOG_EVENT_KIND } from "../core/brain/types.ts";
+import { isoSecond } from "../core/brain/time.ts";
+import { VaultFrozenError } from "../core/brain/freeze-marker.ts";
+import { INVALID_PARAMS, MCPError } from "./protocol.ts";
+
+/** The refusal token, named in the message and carried in `data`. */
+export const VAULT_FROZEN_REFUSAL = "vault_frozen";
+
+/** The structured payload attached to the refusal, for machine callers. */
+export interface VaultFrozenData {
+ readonly code: typeof VAULT_FROZEN_REFUSAL;
+ readonly tool: string;
+ readonly frozen_at: string;
+ readonly by: string;
+ readonly reason: string;
+ readonly next_command: string;
+ /** Why the refusal reached no `write-refused` event, when it did not. */
+ readonly audit_reason?: string;
+}
+
+/**
+ * Record one `write-refused` event, and report why when it could not be
+ * recorded.
+ *
+ * Returns `null` on success and the reason on failure; see the module
+ * docblock for why a failure here is reported rather than raised.
+ */
+function recordRefusal(
+ vault: string,
+ tool: string,
+ agent: string,
+ err: VaultFrozenError,
+): string | null {
+ try {
+ appendLogEvent(vault, {
+ timestamp: isoSecond(new Date()),
+ eventType: BRAIN_LOG_EVENT_KIND.writeRefused,
+ body: {
+ tool,
+ agent,
+ reason: err.reason,
+ frozen_at: err.frozen_at,
+ },
+ });
+ return null;
+ } catch (exc) {
+ return exc instanceof Error ? exc.message : String(exc);
+ }
+}
+
+/**
+ * Re-raise a frozen-vault refusal ahead of any generic error mapping.
+ *
+ * The tool handlers wrap an unrecognised throw in an `INTERNAL_ERROR`
+ * MCPError, which is right for an I/O fault and wrong for this: a freeze
+ * is a state an operator asked for, and a caller told "internal error"
+ * learns neither that nor the command that lifts it. A converter calls
+ * this first so the typed refusal reaches the dispatch seam, which is
+ * where it becomes the structured refusal and the `write-refused` event.
+ *
+ * A no-op for every other error, so a call site pays one `instanceof`.
+ */
+export function rethrowVaultFrozen(err: unknown): void {
+ if (err instanceof VaultFrozenError) throw err;
+}
+
+/**
+ * Turn a {@link VaultFrozenError} into the refusal a caller receives,
+ * recording it on the way through.
+ *
+ * The caller's identity is passed as a THUNK because resolving it can
+ * itself throw on an unreadable config, and a broken config must not
+ * replace the freeze refusal with a different error - the freeze is what
+ * actually stopped the write. An unresolvable identity is recorded under
+ * {@link UNRESOLVED_AGENT}, which is a named absence rather than a guess.
+ */
+export function vaultFrozenRefusal(
+ vault: string,
+ tool: string,
+ err: VaultFrozenError,
+ resolveAgent: () => string,
+): MCPError {
+ let agent: string;
+ try {
+ agent = resolveAgent();
+ } catch {
+ agent = UNRESOLVED_AGENT;
+ }
+ const auditReason = recordRefusal(vault, tool, agent, err);
+ const message =
+ `${tool}: refused (${VAULT_FROZEN_REFUSAL}). ${err.notice.detail}. ` +
+ "Every content write in this vault is refused until the freeze is lifted; " +
+ "this refusal was recorded in the Brain log.";
+ const data: VaultFrozenData = Object.freeze({
+ code: VAULT_FROZEN_REFUSAL,
+ tool,
+ frozen_at: err.frozen_at,
+ by: err.by,
+ reason: err.reason,
+ next_command: err.next_command,
+ ...(auditReason !== null ? { audit_reason: auditReason } : {}),
+ });
+ return new MCPError(INVALID_PARAMS, message, data);
+}
+
+/**
+ * Recorded as the caller when the server's own identity resolution
+ * fails. A token, not a plausible name: an agent field that reads like a
+ * real identity but was invented is worse than one that says it is
+ * missing.
+ */
+export const UNRESOLVED_AGENT = "unresolved";
diff --git a/src/mcp/server.ts b/src/mcp/server.ts
index 64b57865..a97861d9 100644
--- a/src/mcp/server.ts
+++ b/src/mcp/server.ts
@@ -11,6 +11,8 @@ import {
} from "../core/config.ts";
import { emitMcpRouteLatency, type McpRouteStatus } from "../core/brain/mcp-route-metrics.ts";
import { assertKnownArguments } from "./argument-guard.ts";
+import { VaultFrozenError } from "../core/brain/freeze-marker.ts";
+import { UNRESOLVED_AGENT, vaultFrozenRefusal } from "./frozen-refusal.ts";
import { assertNoCallerSuppliedReach } from "./reach-refusal.ts";
import { buildInstructions } from "./instructions.ts";
import {
@@ -233,14 +235,20 @@ export class MCPServer {
// cannot see.
assertNoCallerSuppliedReach(tool, args);
assertKnownArguments(tool, args);
- if (!this.routeMetricsEnabled) return tool.handler(this.context, args, onProgress);
+ if (!this.routeMetricsEnabled) {
+ try {
+ return await tool.handler(this.context, args, onProgress);
+ } catch (exc) {
+ throw this.mapFrozen(tool, exc);
+ }
+ }
const start = performance.now();
let status: McpRouteStatus = "ok";
try {
return await tool.handler(this.context, args, onProgress);
} catch (exc) {
status = "error";
- throw exc;
+ throw this.mapFrozen(tool, exc);
} finally {
emitMcpRouteLatency(
this.vault,
@@ -256,6 +264,29 @@ export class MCPServer {
}
}
+ /**
+ * Map a frozen-vault refusal onto the structured error a caller can
+ * act on, recording one `write-refused` event on the way through.
+ *
+ * Here rather than in each write tool because the freeze is enforced
+ * at the vault guard, so ANY handler can raise it - including the
+ * internal writers a tool composes - and a per-tool `catch` would
+ * cover the ones somebody remembered. Every other exception passes
+ * through untouched.
+ */
+ private mapFrozen(tool: ToolDefinition, exc: unknown): unknown {
+ if (!(exc instanceof VaultFrozenError)) return exc;
+ // `agentName` is optional on the context - a transport may supply
+ // none - so an absent identity is recorded as the named absence
+ // rather than as a plausible-looking name nobody claimed.
+ return vaultFrozenRefusal(
+ this.vault,
+ tool.name,
+ exc,
+ () => this.context.agentName ?? UNRESOLVED_AGENT,
+ );
+ }
+
/** Process one JSON-RPC request or notification. Returns null for notifications. */
async handleRequest(request: JsonRpcRequest): Promise<JsonRpcResponse | null> {
if (typeof request !== "object" || request === null) {
diff --git a/tests/cli/brain-freeze.test.ts b/tests/cli/brain-freeze.test.ts
new file mode 100644
index 00000000..8a9ffb5f
--- /dev/null
+++ b/tests/cli/brain-freeze.test.ts
@@ -0,0 +1,139 @@
+/**
+ * `o2b brain freeze` / `o2b brain unfreeze` (who-wrote-what, Task C).
+ *
+ * The operator surface of the fleet freeze. Freezing is not a status
+ * flag: between the two commands every content write in the vault is
+ * refused, on this device and on every device that syncs it - so these
+ * tests drive a real write in between and hold the refusal to naming the
+ * way out.
+ */
+
+import { afterEach, beforeEach, expect, test } from "bun:test";
+import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { createSnapshot } from "../../src/core/brain/snapshot.ts";
+import { BRAIN_SNAPSHOT_REASON } from "../../src/core/brain/types.ts";
+import { runCli } from "../helpers/run-cli.ts";
+
+let tmp: string;
+let vault: string;
+let marker: string;
+
+beforeEach(() => {
+ tmp = mkdtempSync(join(tmpdir(), "o2b-cli-freeze-"));
+ vault = join(tmp, "vault");
+ mkdirSync(join(vault, "Brain"), { recursive: true });
+ // A Brain tree with something in it: the snapshot archiver refuses an
+ // empty one, and an operator's vault is never empty either.
+ writeFileSync(join(vault, "Brain", "_brain.yaml"), "schema_version: 1\n", "utf8");
+ marker = join(vault, "Brain", ".state", "frozen.json");
+});
+
+afterEach(() => {
+ rmSync(tmp, { recursive: true, force: true });
+});
+
+test("freeze writes the marker, unfreeze removes it, and both are idempotent", async () => {
+ const first = await runCli(["brain", "freeze", "--vault", vault, "--reason", "migrating"]);
+ expect(first.returncode).toBe(0);
+ expect(first.stdout).toContain("frozen");
+ expect(first.stdout).toContain("migrating");
+ expect(existsSync(marker)).toBe(true);
+
+ const again = await runCli(["brain", "freeze", "--vault", vault, "--reason", "second"]);
+ expect(again.returncode).toBe(0);
+ expect(again.stdout).toContain("already frozen");
+
+ const lifted = await runCli(["brain", "unfreeze", "--vault", vault]);
+ expect(lifted.returncode).toBe(0);
+ expect(existsSync(marker)).toBe(false);
+
+ const noop = await runCli(["brain", "unfreeze", "--vault", vault]);
+ expect(noop.returncode).toBe(0);
+ expect(noop.stdout).toContain("not frozen");
+});
+
+test("--json reports the transition and the marker fields", async () => {
+ const frozen = await runCli(["brain", "freeze", "--vault", vault, "--reason", "x", "--json"]);
+ expect(frozen.returncode).toBe(0);
+ const payload = JSON.parse(frozen.stdout) as Record<string, unknown>;
+ expect(payload["ok"]).toBe(true);
+ expect(payload["changed"]).toBe(true);
+ expect(payload["reason"]).toBe("x");
+ expect(typeof payload["frozen_at"]).toBe("string");
+
+ const lifted = await runCli(["brain", "unfreeze", "--vault", vault, "--json"]);
+ const liftedPayload = JSON.parse(lifted.stdout) as Record<string, unknown>;
+ expect(liftedPayload["changed"]).toBe(true);
+ expect(liftedPayload["reason"]).toBe("x");
+});
+
+test("a content write is refused while frozen, naming the way out", async () => {
+ await runCli(["brain", "freeze", "--vault", vault, "--reason", "migrating"]);
+ const set = await runCli([
+ "brain",
+ "state",
+ "set",
+ "--vault",
+ vault,
+ "--aspect",
+ "branch",
+ "--value",
+ "feat/x",
+ ]);
+ expect(set.returncode).not.toBe(0);
+ const said = `${set.stdout}${set.stderr}`;
+ expect(said).toContain("frozen");
+ expect(said).toContain("o2b brain unfreeze");
+});
+
+test("rollback is refused by name while frozen, with no exemption for recovery", async () => {
+ // A real recovery point, so the refusal below is the freeze rather
+ // than a missing run id. An operator recovering a frozen vault is
+ // exactly the operator who should decide the freeze is over, so there
+ // is no exemption for the restore path - and no code implementing one:
+ // `restoreSnapshot` passes the same guard every other writer does.
+ const runId = "dream-2026-09-10-080000";
+ createSnapshot(vault, runId, { reason: BRAIN_SNAPSHOT_REASON.dream });
+ await runCli(["brain", "freeze", "--vault", vault, "--reason", "migrating"]);
+
+ // `--force-rollback` clears the drift confirmation the freeze itself
+ // caused (the marker and the log lines are new since the archive), so
+ // the only thing left to refuse the restore is the freeze.
+ const back = await runCli([
+ "brain",
+ "rollback",
+ runId,
+ "--vault",
+ vault,
+ "--yes",
+ "--force-rollback",
+ ]);
+ expect(back.returncode).not.toBe(0);
+ expect(`${back.stdout}${back.stderr}`).toContain("o2b brain unfreeze");
+});
+
+test("status reports the freeze, and stops reporting it once lifted", async () => {
+ await runCli(["brain", "freeze", "--vault", vault, "--reason", "migrating"]);
+ const frozen = await runCli(["brain", "status", "--vault", vault, "--json"]);
+ expect(frozen.returncode).toBe(0);
+ const snapshot = JSON.parse(frozen.stdout) as { frozen: Record<string, unknown> | null };
+ expect(snapshot.frozen).not.toBeNull();
+ expect(snapshot.frozen!["reason"]).toBe("migrating");
+
+ await runCli(["brain", "unfreeze", "--vault", vault]);
+ const thawed = await runCli(["brain", "status", "--vault", vault, "--json"]);
+ expect((JSON.parse(thawed.stdout) as { frozen: unknown }).frozen).toBeNull();
+});
+
+test("the text status prints a frozen line either way", async () => {
+ const clear = await runCli(["brain", "status", "--vault", vault]);
+ expect(clear.stdout).toContain("frozen: no");
+
+ await runCli(["brain", "freeze", "--vault", vault, "--reason", "migrating"]);
+ const frozen = await runCli(["brain", "status", "--vault", vault]);
+ expect(frozen.stdout).toContain("frozen: yes");
+ expect(frozen.stdout).toContain("migrating");
+});
diff --git a/tests/cli/brain-log-verify.test.ts b/tests/cli/brain-log-verify.test.ts
new file mode 100644
index 00000000..58439d75
--- /dev/null
+++ b/tests/cli/brain-log-verify.test.ts
@@ -0,0 +1,116 @@
+/**
+ * `o2b brain log verify` (who-wrote-what, Task E).
+ *
+ * The operator surface of the per-shard hash chain. The verb reports and
+ * never repairs, so what these tests hold it to is that it says which
+ * shard, which line, and what the break means - and that it exits
+ * non-zero when the log does not verify, because a check whose failure
+ * looks like its success is not a check.
+ */
+
+import { afterEach, beforeEach, expect, test } from "bun:test";
+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { appendLogEvent } from "../../src/core/brain/log.ts";
+import { logJsonlPath, logShardJsonlPath } from "../../src/core/brain/paths.ts";
+import { runCli } from "../helpers/run-cli.ts";
+
+const DATE = "2026-06-03";
+
+let tmp: string;
+let vault: string;
+
+beforeEach(() => {
+ tmp = mkdtempSync(join(tmpdir(), "o2b-cli-log-verify-"));
+ vault = join(tmp, "vault");
+ mkdirSync(join(vault, "Brain", "log"), { recursive: true });
+ writeFileSync(join(vault, "Brain", "_brain.yaml"), "schema_version: 1\n", "utf8");
+});
+
+afterEach(() => {
+ rmSync(tmp, { recursive: true, force: true });
+});
+
+function appendMany(count: number, shardId = ""): void {
+ for (let i = 0; i < count; i++) {
+ appendLogEvent(
+ vault,
+ {
+ timestamp: `${DATE}T10:00:0${i}Z`,
+ eventType: "note",
+ body: { text: `event ${i}`, agent: "@tester" },
+ },
+ { deviceId: shardId },
+ );
+ }
+}
+
+function dropLine(path: string, line: number): void {
+ const rows = readFileSync(path, "utf8").trim().split("\n");
+ rows.splice(line - 1, 1);
+ writeFileSync(path, rows.join("\n") + "\n", "utf8");
+}
+
+test("an intact log verifies clean and exits zero", async () => {
+ appendMany(3);
+ const res = await runCli(["brain", "log", "verify", "--vault", vault]);
+ expect(res.returncode).toBe(0);
+ expect(res.stdout).toContain("1 shard");
+ expect(res.stdout).toContain("3 chained");
+});
+
+test("a vault with no log at all is reported as such, not as clean silence", async () => {
+ const res = await runCli(["brain", "log", "verify", "--vault", vault]);
+ expect(res.returncode).toBe(0);
+ expect(res.stdout).toContain("no chained log shard");
+});
+
+test("a broken shard is named with its line and the verb exits non-zero", async () => {
+ appendMany(3);
+ dropLine(logJsonlPath(vault, DATE), 2);
+
+ const res = await runCli(["brain", "log", "verify", "--vault", vault]);
+ expect(res.returncode).toBe(1);
+ expect(res.stdout).toContain(logJsonlPath(vault, DATE));
+ expect(res.stdout).toContain("line 2");
+ expect(res.stdout).toContain("prev-mismatch");
+});
+
+test("--json carries every shard, broken or not", async () => {
+ appendMany(3, "devalpha");
+ appendMany(2, "devbeta");
+ dropLine(logShardJsonlPath(vault, DATE, "devalpha"), 2);
+
+ const res = await runCli(["brain", "log", "verify", "--vault", vault, "--json"]);
+ expect(res.returncode).toBe(1);
+ const payload = JSON.parse(res.stdout) as {
+ ok: boolean;
+ shards: Array<Record<string, unknown>>;
+ notices: Array<Record<string, unknown>>;
+ };
+ expect(payload.ok).toBe(false);
+ expect(payload.shards).toHaveLength(2);
+ const alpha = payload.shards.find((s) => s["shard_id"] === "devalpha")!;
+ expect(alpha["first_break"]).toEqual({ line: 2, reason: "prev-mismatch" });
+ const beta = payload.shards.find((s) => s["shard_id"] === "devbeta")!;
+ expect(beta["first_break"]).toBeNull();
+ expect(beta["chained"]).toBe(2);
+ expect(payload.notices).toHaveLength(1);
+});
+
+test("the verb name is reserved: an unknown subcommand is refused by name", async () => {
+ const res = await runCli(["brain", "log", "compact", "--vault", vault]);
+ expect(res.returncode).toBe(2);
+ expect(res.stderr).toContain("compact");
+ expect(res.stderr).toContain("verify");
+});
+
+test("no subcommand prints the usage rather than guessing one", async () => {
+ const res = await runCli(["brain", "log"]);
+ expect(res.returncode).toBe(2);
+ const text = res.stdout + res.stderr;
+ expect(text).toContain("usage: o2b brain log <verb>");
+ expect(text).toContain("verify");
+});
diff --git a/tests/cli/brain-writes.test.ts b/tests/cli/brain-writes.test.ts
new file mode 100644
index 00000000..821b18b5
--- /dev/null
+++ b/tests/cli/brain-writes.test.ts
@@ -0,0 +1,337 @@
+/**
+ * `o2b brain writes` (who-wrote-what, Task A / t_662f4e82).
+ *
+ * The operator surface over the note-write record: the default listing,
+ * the filters, and the image prune with its dry run - which is the one
+ * place a wrong verb in the output would cost real bytes.
+ */
+
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { dirname, join } from "node:path";
+
+import { bootstrapBrain } from "../../src/core/brain/init.ts";
+import { appendLogEvent } from "../../src/core/brain/log.ts";
+import { recordNoteWrite, storeBeforeImage } from "../../src/core/brain/notes/write-record.ts";
+import { writeImagePath } from "../../src/core/brain/paths.ts";
+import { BRAIN_LOG_EVENT_KIND } from "../../src/core/brain/types.ts";
+import { runCli } from "../helpers/run-cli.ts";
+
+let tmp: string;
+let vault: string;
+let configPath: string;
+
+beforeEach(() => {
+ tmp = mkdtempSync(join(tmpdir(), "o2b-brain-writes-cli-"));
+ vault = join(tmp, "vault");
+ configPath = join(tmp, "config.yaml");
+ writeFileSync(configPath, `vault: ${vault}\nagent_name: test\n`);
+ bootstrapBrain(vault, { configPath });
+});
+
+afterEach(() => {
+ rmSync(tmp, { recursive: true, force: true });
+});
+
+const env = () => ({ OPEN_SECOND_BRAIN_CONFIG: configPath });
+
+function seedWrite(opts: {
+ readonly timestamp: string;
+ readonly agent: string;
+ readonly target: string;
+ readonly op: string;
+ readonly deviceId?: string;
+}): void {
+ appendLogEvent(
+ vault,
+ {
+ timestamp: opts.timestamp,
+ eventType: BRAIN_LOG_EVENT_KIND.noteWrite,
+ agent: opts.agent,
+ body: {
+ write_id: `nw_${opts.timestamp.replace(/\D/g, "")}_${"0".repeat(16)}`,
+ op: opts.op,
+ target: opts.target,
+ hash_before: "a".repeat(64),
+ hash_after: "b".repeat(64),
+ bytes_before: "10",
+ bytes_after: "20",
+ agent: opts.agent,
+ },
+ },
+ { deviceId: opts.deviceId ?? "" },
+ );
+}
+
+describe("o2b brain writes", () => {
+ test("lists every recorded write newest first, with no subcommand typed", async () => {
+ seedWrite({ timestamp: "2026-03-04T01:00:00Z", agent: "claude", target: "A.md", op: "create" });
+ seedWrite({ timestamp: "2026-03-04T02:00:00Z", agent: "codex", target: "B.md", op: "update" });
+
+ const res = await runCli(["brain", "writes"], { env: env() });
+ expect(res.returncode).toBe(0);
+ const lines = res.stdout.trim().split("\n");
+ expect(lines[0]).toContain("B.md");
+ expect(lines[1]).toContain("A.md");
+ // Every column of the row: when, what, who, where, and both digests.
+ expect(lines[0]).toContain("2026-03-04T02:00:00Z");
+ expect(lines[0]).toContain("update");
+ expect(lines[0]).toContain("codex");
+ expect(lines[0]).toContain("aaaaaaaa -> bbbbbbbb");
+ });
+
+ test("a legacy un-sharded log prints an absent device, not an invented one", async () => {
+ seedWrite({ timestamp: "2026-03-04T01:00:00Z", agent: "claude", target: "A.md", op: "create" });
+ const res = await runCli(["brain", "writes", "list"], { env: env() });
+ expect(res.returncode).toBe(0);
+ expect(res.stdout).toContain(" - ");
+ });
+
+ test("--json carries the full record, the count and the device", async () => {
+ seedWrite({
+ timestamp: "2026-03-04T01:00:00Z",
+ agent: "claude",
+ target: "A.md",
+ op: "append",
+ deviceId: "laptop",
+ });
+ const res = await runCli(["brain", "writes", "--json"], { env: env() });
+ expect(res.returncode).toBe(0);
+ const payload = JSON.parse(res.stdout) as {
+ count: number;
+ writes: Array<Record<string, unknown>>;
+ };
+ expect(payload.count).toBe(1);
+ expect(payload.writes[0]).toMatchObject({
+ op: "append",
+ target: "A.md",
+ agent: "claude",
+ device: "laptop",
+ bytes_before: 10,
+ bytes_after: 20,
+ });
+ });
+
+ test("filters by agent, path and op", async () => {
+ seedWrite({ timestamp: "2026-03-04T01:00:00Z", agent: "claude", target: "A.md", op: "create" });
+ seedWrite({ timestamp: "2026-03-04T02:00:00Z", agent: "codex", target: "B.md", op: "update" });
+
+ const byAgent = await runCli(["brain", "writes", "--agent", "codex"], { env: env() });
+ expect(byAgent.stdout).toContain("B.md");
+ expect(byAgent.stdout).not.toContain("A.md");
+
+ const byPath = await runCli(["brain", "writes", "--path", "A.md"], { env: env() });
+ expect(byPath.stdout).toContain("A.md");
+ expect(byPath.stdout).not.toContain("B.md");
+
+ const byOp = await runCli(["brain", "writes", "--op", "create"], { env: env() });
+ expect(byOp.stdout).toContain("A.md");
+ expect(byOp.stdout).not.toContain("B.md");
+ });
+
+ test("an empty history says so rather than printing nothing", async () => {
+ const res = await runCli(["brain", "writes"], { env: env() });
+ expect(res.returncode).toBe(0);
+ expect(res.stdout).toContain("no recorded note writes");
+ });
+
+ test("an unknown --op is refused by name and lists the vocabulary", async () => {
+ const res = await runCli(["brain", "writes", "--op", "delete"], { env: env() });
+ expect(res.returncode).toBe(2);
+ expect(res.stderr).toContain("--op must be one of create|update|append|revert");
+ });
+
+ test("an unknown subcommand names the three that exist", async () => {
+ const res = await runCli(["brain", "writes", "purge"], { env: env() });
+ expect(res.returncode).toBe(2);
+ expect(res.stderr).toContain("expected list, revert or prune-images");
+ });
+});
+
+describe("o2b brain writes prune-images", () => {
+ test("--dry-run lists what would go and removes nothing", async () => {
+ const image = storeBeforeImage(vault, "prior bytes");
+ const res = await runCli(
+ ["brain", "writes", "prune-images", "--older-than-days", "0", "--dry-run"],
+ { env: env() },
+ );
+ expect(res.returncode).toBe(0);
+ expect(res.stdout).toContain("would remove 1");
+ expect(res.stdout).toContain(image.sha256);
+ expect(existsSync(writeImagePath(vault, image.sha256))).toBe(true);
+ });
+
+ test("--older-than-days 0 removes them", async () => {
+ const image = storeBeforeImage(vault, "prior bytes");
+ const res = await runCli(["brain", "writes", "prune-images", "--older-than-days", "0"], {
+ env: env(),
+ });
+ expect(res.returncode).toBe(0);
+ expect(res.stdout).toContain("removed 1");
+ expect(existsSync(writeImagePath(vault, image.sha256))).toBe(false);
+ });
+
+ test("the default window keeps a fresh image, and --json reports it", async () => {
+ storeBeforeImage(vault, "prior bytes");
+ const res = await runCli(["brain", "writes", "prune-images", "--json"], { env: env() });
+ expect(res.returncode).toBe(0);
+ expect(JSON.parse(res.stdout)).toMatchObject({
+ removed: [],
+ removed_count: 0,
+ kept: 1,
+ dry_run: false,
+ older_than_days: 30,
+ });
+ });
+
+ test("a negative window is refused by name before anything is read", async () => {
+ const res = await runCli(["brain", "writes", "prune-images", "--older-than-days", "-1"], {
+ env: env(),
+ });
+ expect(res.returncode).toBe(2);
+ expect(res.stderr).toContain("--older-than-days must be a non-negative integer");
+ });
+
+ test("a name the store did not write is named, not removed and not fatal", async () => {
+ const image = storeBeforeImage(vault, "prior bytes");
+ const stray = join(dirname(writeImagePath(vault, image.sha256)), "readme.txt");
+ writeFileSync(stray, "not an image", "utf8");
+
+ const res = await runCli(["brain", "writes", "prune-images", "--older-than-days", "0"], {
+ env: env(),
+ });
+ expect(res.returncode).toBe(0);
+ expect(res.stdout).toContain("removed 1");
+ expect(res.stdout).toContain("skipped 1 name(s) that are not before-images");
+ expect(res.stdout).toContain("readme.txt");
+ expect(existsSync(writeImagePath(vault, image.sha256))).toBe(false);
+ expect(existsSync(stray)).toBe(true);
+ });
+});
+
+describe("o2b brain writes revert", () => {
+ /** Do what the write seams do, so the plan reads a real history. */
+ function seedNote(opts: {
+ readonly target: string;
+ readonly bytes: string;
+ readonly agent: string;
+ readonly at: string;
+ }): void {
+ const abs = join(vault, opts.target);
+ const before = existsSync(abs) ? readFileSync(abs, "utf8") : null;
+ mkdirSync(dirname(abs), { recursive: true });
+ if (before !== null) storeBeforeImage(vault, before);
+ writeFileSync(abs, opts.bytes);
+ recordNoteWrite(vault, {
+ op: before === null ? "create" : "update",
+ target: opts.target,
+ before: before === null ? null : { bytes: before },
+ after: { bytes: opts.bytes },
+ timestamp: opts.at,
+ agent: opts.agent,
+ });
+ }
+
+ const TARGET = "notes/A.md";
+
+ function seedTwoUpdatesByA(): void {
+ seedNote({ target: TARGET, bytes: "v0", agent: "seed", at: "2026-03-04T01:00:00Z" });
+ seedNote({ target: TARGET, bytes: "v1", agent: "claude", at: "2026-03-04T02:00:00Z" });
+ seedNote({ target: TARGET, bytes: "v2", agent: "claude", at: "2026-03-04T03:00:00Z" });
+ }
+
+ test("prints the plan, the digest and the exact --apply invocation", async () => {
+ seedTwoUpdatesByA();
+ const res = await runCli(["brain", "writes", "revert", "--agent", "claude"], { env: env() });
+ expect(res.returncode).toBe(0);
+ expect(res.stdout).toContain(TARGET);
+ expect(res.stdout).toContain("restore");
+ expect(res.stdout).toMatch(/digest: [0-9a-f]{64}/);
+ const digest = res.stdout
+ .split("\n")
+ .find((l) => l.startsWith("digest:"))!
+ .slice("digest:".length)
+ .trim();
+ expect(res.stdout).toContain(`o2b brain writes revert --agent claude --apply ${digest}`);
+ // A plan is a report: nothing moved.
+ expect(readFileSync(join(vault, TARGET), "utf8")).toBe("v2");
+ });
+
+ test("a selector naming nobody and nothing is refused, and exits 1", async () => {
+ const res = await runCli(["brain", "writes", "revert", "--since", "2026-03-04"], {
+ env: env(),
+ });
+ expect(res.returncode).toBe(1);
+ expect(res.stderr).toContain("unbounded_selector");
+ });
+
+ test("a plan that refuses every target is a report, not a failure", async () => {
+ seedTwoUpdatesByA();
+ writeFileSync(join(vault, TARGET), "drifted");
+ const res = await runCli(["brain", "writes", "revert", "--agent", "claude"], { env: env() });
+ expect(res.returncode).toBe(0);
+ expect(res.stdout).toContain("drift");
+ });
+
+ test("--apply restores the bytes and names the snapshot it took", async () => {
+ seedTwoUpdatesByA();
+ const plan = await runCli(["brain", "writes", "revert", "--agent", "claude", "--json"], {
+ env: env(),
+ });
+ const digest = (JSON.parse(plan.stdout) as { digest: string }).digest;
+
+ const res = await runCli(
+ ["brain", "writes", "revert", "--agent", "claude", "--apply", digest],
+ { env: env() },
+ );
+ expect(res.returncode).toBe(0);
+ expect(res.stdout).toContain("note-revert-");
+ expect(res.stdout).toContain(`restore ${TARGET}`);
+ expect(readFileSync(join(vault, TARGET), "utf8")).toBe("v0");
+ });
+
+ test("a stale digest is refused by name and exits 1", async () => {
+ seedTwoUpdatesByA();
+ const res = await runCli(
+ ["brain", "writes", "revert", "--agent", "claude", "--apply", "f".repeat(64)],
+ { env: env() },
+ );
+ expect(res.returncode).toBe(1);
+ expect(res.stderr).toContain("digest_mismatch");
+ expect(readFileSync(join(vault, TARGET), "utf8")).toBe("v2");
+ });
+
+ test("a plan with nothing to apply is refused by name and exits 1", async () => {
+ seedTwoUpdatesByA();
+ writeFileSync(join(vault, TARGET), "drifted");
+ const plan = await runCli(["brain", "writes", "revert", "--agent", "claude", "--json"], {
+ env: env(),
+ });
+ const digest = (JSON.parse(plan.stdout) as { digest: string }).digest;
+ const res = await runCli(
+ ["brain", "writes", "revert", "--agent", "claude", "--apply", digest],
+ { env: env() },
+ );
+ expect(res.returncode).toBe(1);
+ expect(res.stderr).toContain("nothing_to_apply");
+ });
+
+ test("--json carries the entries and the digest", async () => {
+ seedTwoUpdatesByA();
+ const res = await runCli(["brain", "writes", "revert", "--path", TARGET, "--json"], {
+ env: env(),
+ });
+ expect(res.returncode).toBe(0);
+ const payload = JSON.parse(res.stdout) as {
+ digest: string;
+ entries: ReadonlyArray<Record<string, unknown>>;
+ selector: Record<string, unknown>;
+ };
+ expect(payload.selector).toEqual({ path: TARGET });
+ expect(payload.entries).toHaveLength(1);
+ // A path with no agent selects EVERY write on that note, including
+ // the one that created it, so undoing them all removes the note.
+ expect(payload.entries[0]!["action"]).toBe("delete");
+ });
+});
diff --git a/tests/core/architecture/origin-channel-census.test.ts b/tests/core/architecture/origin-channel-census.test.ts
index c69ce0cb..067a3fb4 100644
--- a/tests/core/architecture/origin-channel-census.test.ts
+++ b/tests/core/architecture/origin-channel-census.test.ts
@@ -197,8 +197,14 @@ describe("the unverifiable surface this rule exists for", () => {
* equality fails in both directions; when it does, recount with the
* regex below, update this constant, and say in the commit which
* schemas moved it.
+ *
+ * 25 -> 26: `brain_writes` (who-wrote-what, Task A). It is the one
+ * `agent:` property in the set that is not a writer's claim at all -
+ * the tool is read-only and the argument selects which recorded writes
+ * to list. It still counts, because the regex measures the SURFACE a
+ * caller can spell and not the use each schema makes of it.
*/
- const CALLER_SUPPLIED_AGENT_PROPERTIES = 25;
+ const CALLER_SUPPLIED_AGENT_PROPERTIES = 26;
test("is exactly what the rule was argued from, in both directions", () => {
let count = 0;
diff --git a/tests/core/architecture/state-surface-census.test.ts b/tests/core/architecture/state-surface-census.test.ts
index 2fea0ce1..8a156abb 100644
--- a/tests/core/architecture/state-surface-census.test.ts
+++ b/tests/core/architecture/state-surface-census.test.ts
@@ -80,7 +80,7 @@ const STORE_DIR_IDENTIFIER = "DERIVED_STORE_DIR";
const SWEPT_POPULATION_SIZE = 21;
/** Declared surfaces today. Pinned for the same reason. */
-const DECLARED_SURFACE_COUNT = 42;
+const DECLARED_SURFACE_COUNT = 44;
/** An exclusion reason has to be an argument, not a label. */
const MIN_REASON_LENGTH = 80;
diff --git a/tests/core/architecture/verdict-vocabulary-census.test.ts b/tests/core/architecture/verdict-vocabulary-census.test.ts
index 2977cc87..3e87b142 100644
--- a/tests/core/architecture/verdict-vocabulary-census.test.ts
+++ b/tests/core/architecture/verdict-vocabulary-census.test.ts
@@ -401,6 +401,11 @@ import {
ORIGIN_CHANNEL,
ORIGIN_CHANNELS,
} from "../../../src/core/origin-channel.ts";
+import {
+ isNoteWriteOp,
+ NOTE_WRITE_OP,
+ NOTE_WRITE_OPS,
+} from "../../../src/core/brain/notes/write-record.ts";
import { lexCode } from "../../helpers/source-lexer.ts";
import {
TRANSPORT_REACH,
@@ -1253,6 +1258,17 @@ const CENSUS: ReadonlyArray<VocabularyUnderCensus> = Object.freeze([
members: ORIGIN_CHANNELS,
guard: isOriginChannel,
},
+ {
+ // who-wrote-what, Task A. What a recorded note write DID to its
+ // target. `revert` is a member from the start rather than added when
+ // the revert task lands, because a restore is a write like any other
+ // and a reader that could not name it would have to fall back to a
+ // string comparison the moment the first one was recorded.
+ name: "NOTE_WRITE_OP",
+ values: NOTE_WRITE_OP,
+ members: NOTE_WRITE_OPS,
+ guard: isNoteWriteOp,
+ },
]);
// ---------------------------------------------------------------------------
@@ -1517,7 +1533,7 @@ const SCANNED = scanVocabularies(SOURCE_TREE);
* How many four-piece vocabularies `src/` currently holds. Measured, and
* kept as an equality rather than a floor - see the population test.
*/
-const VOCABULARY_POPULATION = 74;
+const VOCABULARY_POPULATION = 75;
const REGISTERED = new Map(CENSUS.map((entry) => [entry.name, entry] as const));
describe("verdict vocabulary census", () => {
diff --git a/tests/core/architecture/visibility-surface-census.test.ts b/tests/core/architecture/visibility-surface-census.test.ts
index 8a45ae06..c620ce65 100644
--- a/tests/core/architecture/visibility-surface-census.test.ts
+++ b/tests/core/architecture/visibility-surface-census.test.ts
@@ -449,7 +449,7 @@ function reasonProblems(entries: ReadonlyArray<VisibilitySurfaceEntry>): {
* both leaking, plus the three tools that share `procedure-tools.ts` with
* the second of them and come in on the file-level rule.
*/
-const MCP_TOOL_POPULATION_SIZE = 48;
+const MCP_TOOL_POPULATION_SIZE = 49;
/** Measured: MCP resources + templates, all excluded. */
const MCP_RESOURCE_POPULATION_SIZE = 8;
/** Measured: hand-enumerated CLI verb mirrors. */
diff --git a/tests/core/architecture/write-site-census.test.ts b/tests/core/architecture/write-site-census.test.ts
index 843e1a66..f00f9430 100644
--- a/tests/core/architecture/write-site-census.test.ts
+++ b/tests/core/architecture/write-site-census.test.ts
@@ -414,6 +414,15 @@ const DIRECT_WRITE_EXCLUSIONS: Readonly<Record<string, WriteExclusion>> = Object
"appending. The `unlinkSync` breaks a lock proven stale by its own mtime, with " +
"exactly one retry.",
},
+ "src/core/brain/freeze.ts": {
+ categories: [C.lockPrimitive, C.retentionDelete],
+ calls: ["unlinkSync"],
+ reason:
+ "the freeze marker is a concurrency primitive over the whole vault rather than a " +
+ "note: its entire content is its existence, `unfreeze` is the one command that " +
+ "removes it, and the `unfreeze` log event records who did so and what the marker " +
+ "said. There is nothing for a shared note writer to write.",
+ },
"src/core/brain/maintenance/journal.ts": {
categories: [C.appendOnlyLedger],
calls: ["appendFileSync", "renameSync", "writeFileSync"],
@@ -628,6 +637,27 @@ const DIRECT_WRITE_EXCLUSIONS: Readonly<Record<string, WriteExclusion>> = Object
"removes generated cluster notes the current run no longer expects, and only " +
"those whose own frontmatter declares the generated kind.",
},
+ "src/core/brain/notes/revert.ts": {
+ categories: [C.retentionDelete],
+ calls: ["unlinkSync"],
+ reason:
+ "removes a note the selected writes created, when undoing them means the note should " +
+ "not exist at all. There is nothing for a shared writer to author on the way out, and " +
+ "the restore half of the same module writes the recorded before-image through " +
+ "`atomicWriteFileSync`. The unlink runs inside `withDestructiveSnapshot`, so the " +
+ "destructive-site census holds it rather than an exclusion of its own, and the bytes it " +
+ "removes are kept as a before-image first, which is what makes the delete revertible.",
+ },
+ "src/core/brain/notes/write-record.ts": {
+ categories: [C.retentionDelete],
+ calls: ["unlinkSync"],
+ reason:
+ "prunes note-write before-images past a retention window read from each file's own mtime, " +
+ "and keeps any image whose age cannot be measured. The store is content-addressed, so a " +
+ "file's NAME is the digest of its bytes: there is nothing for a shared writer to author on " +
+ "the way out, and the write half of the same module already goes through " +
+ "`atomicWriteFileSync`.",
+ },
"src/core/brain/skill-accept-journal.ts": {
categories: [C.retentionDelete],
calls: ["rmSync"],
@@ -1078,8 +1108,16 @@ const DIRECT_ROWS = ROWS.filter((row) => row.directCalls.length > 0);
* `src/core/bench/fixture.ts` (fixture materialisation into a
* vault-shaped disposable directory). Each is now carrying a written
* exclusion above.
+ *
+ * 68 -> 69: `src/core/brain/notes/write-record.ts` prunes before-images
+ * past their retention window; its write half routes through
+ * `atomicWriteFileSync`, so only the unlink is a direct call.
+ *
+ * 70 -> 71: `src/core/brain/notes/revert.ts` unlinks the note a reverted
+ * create brought into existence; its restore half writes the recorded
+ * before-image through `atomicWriteFileSync`.
*/
-const DIRECT_WRITE_ROWS = 68;
+const DIRECT_WRITE_ROWS = 71;
/**
* Measured modules reaching a write through a shared helper. An equality.
@@ -1105,8 +1143,19 @@ const DIRECT_WRITE_ROWS = 68;
* multi-artifact commit through `atomicWriteFileSync`, and removes
* nothing - deleting the only evidence of a partial write is exactly what
* that module declines to do - so it too arrives with no exclusion owed.
+ *
+ * 100 -> 101: `src/core/brain/notes/write-record.ts` writes each note
+ * before-image through `atomicWriteFileSync`. It is in BOTH classes, not
+ * only this one - the retention prune it also owns unlinks directly - so
+ * it is the rare module that arrives in the shared class and still owes
+ * a written exclusion for the other half.
+ *
+ * 102 -> 103: `src/core/brain/notes/revert.ts` restores a before-image
+ * through `atomicWriteFileSync` and, like the record module beside it,
+ * sits in both classes - the delete arm unlinks directly and carries its
+ * own written exclusion.
*/
-const SHARED_HELPER_ROWS = 100;
+const SHARED_HELPER_ROWS = 103;
// ----- Origin-channel coverage boundary (Unit C) ----------------------------
@@ -1172,7 +1221,7 @@ const STAMPED_PATHS: ReadonlySet<string> = new Set(
* ledger, which appends its own record shape and carries the channel on
* the record rather than in frontmatter.
*/
-const UNSTAMPED_DIRECT_ROWS = 67;
+const UNSTAMPED_DIRECT_ROWS = 70;
/**
* Shared-helper write sites the stamp does not reach, measured the same
@@ -1180,7 +1229,7 @@ const UNSTAMPED_DIRECT_ROWS = 67;
* the log pair through `atomicWriteFileSync`, signals and notes through
* `writeFrontmatterAtomic` - are the ones missing from this count.
*/
-const UNSTAMPED_SHARED_ROWS = 97;
+const UNSTAMPED_SHARED_ROWS = 100;
describe("in-vault write-site census", () => {
test("every direct-fs write site carries a written exclusion", () => {
diff --git a/tests/core/brain.agent-source.provider.test.ts b/tests/core/brain.agent-source.provider.test.ts
index 2ea87d5f..21605fce 100644
--- a/tests/core/brain.agent-source.provider.test.ts
+++ b/tests/core/brain.agent-source.provider.test.ts
@@ -128,3 +128,72 @@ describe("vault agent-source provider", () => {
expect(readdirSync(brainDirs(tmp).inbox).toSorted()).toEqual(beforeInbox);
});
});
+
+/**
+ * The `note` contribution kind (who-wrote-what, Task A / t_662f4e82).
+ *
+ * A `note-write` event is not a `log` contribution that happens to name a
+ * path: it IS the answer to "which notes did this agent touch", so it
+ * gets its own kind, its own `path`, and a title that names the operation
+ * rather than the event kind.
+ */
+describe("note-write events as contributions of kind note", () => {
+ function seedNoteWrite(overrides: Record<string, string> = {}): void {
+ appendLogEvent(
+ tmp,
+ {
+ timestamp: "2026-05-24T10:00:00Z",
+ eventType: "note-write",
+ agent: "claude",
+ body: {
+ write_id: "nw_20260524100000_0123456789abcdef",
+ op: "update",
+ target: "Notes/Design.md",
+ hash_before: "a".repeat(64),
+ hash_after: "b".repeat(64),
+ bytes_before: "10",
+ bytes_after: "20",
+ agent: "claude",
+ ...overrides,
+ },
+ },
+ { deviceId: "" },
+ );
+ }
+
+ test("the write becomes a note contribution keyed by its write id", () => {
+ seedNoteWrite();
+ const note = collectAgentSourceContributions(tmp).find((c) => c.kind === "note");
+ expect(note).toBeDefined();
+ expect(note!.id).toBe("nw_20260524100000_0123456789abcdef");
+ expect(note!.agents).toEqual(["claude"]);
+ // The page IS the answer, so it rides on `path`.
+ expect(note!.path).toBe("Notes/Design.md");
+ // The title names the work, not the event kind.
+ expect(note!.title).toBe("update Notes/Design.md");
+ });
+
+ test("the roster reports the kind, so an agent's notes are one filter away", () => {
+ seedNoteWrite();
+ const claude = listAgentSources(tmp).find((a) => a.id === "claude");
+ expect(claude?.kinds).toContain("note");
+ });
+
+ test("a note-write line with no target stays a log contribution, never a pathless note", () => {
+ // Projecting it as a `note` would put a row in the roster an operator
+ // could select and never open.
+ appendLogEvent(
+ tmp,
+ {
+ timestamp: "2026-05-24T11:00:00Z",
+ eventType: "note-write",
+ agent: "claude",
+ body: { write_id: "nw_20260524110000_ffffffffffffffff", op: "update" },
+ },
+ { deviceId: "" },
+ );
+ const kinds = collectAgentSourceContributions(tmp).map((c) => c.kind);
+ expect(kinds).toContain("log");
+ expect(kinds).not.toContain("note");
+ });
+});
diff --git a/tests/core/brain.log.test.ts b/tests/core/brain.log.test.ts
index 7ccd303b..5185a69e 100644
--- a/tests/core/brain.log.test.ts
+++ b/tests/core/brain.log.test.ts
@@ -3,7 +3,12 @@ import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync
import { tmpdir } from "node:os";
import { join } from "node:path";
-import { appendLogEvent, parseLogDay, type BrainLogEntry } from "../../src/core/brain/log.ts";
+import {
+ appendLogEvent,
+ logChainHash,
+ parseLogDay,
+ type BrainLogEntry,
+} from "../../src/core/brain/log.ts";
import { brainDirs, logJsonlPath, logPath } from "../../src/core/brain/paths.ts";
let tmp: string;
@@ -253,7 +258,14 @@ describe("appendLogEvent β€” JSONL sidecar (Β§23, v0.10.8)", () => {
// stay one-to-one. `unset` because a test harness is not one of the
// entry points that claims a channel - the explicit literal for that,
// never a guessed `cli`.
- expect(parsed).toEqual({
+ //
+ // `prev` and `h` are the per-shard hash chain (who-wrote-what, Task
+ // E). This is the first line of the shard, so it anchors the chain
+ // with `prev: null`; `h` is asserted against the recomputation
+ // rather than a literal, because a hard-coded digest here would
+ // re-key silently the day the projection gains a field.
+ const { h, ...withoutHash } = parsed as Record<string, unknown>;
+ expect(withoutHash).toEqual({
ts: "2026-05-19T10:00:00Z",
kind: "feedback",
payload: {
@@ -262,7 +274,16 @@ describe("appendLogEvent β€” JSONL sidecar (Β§23, v0.10.8)", () => {
sign: "positive",
origin_channel: "unset",
},
+ prev: null,
});
+ expect(h).toBe(
+ logChainHash(null, "2026-05-19T10:00:00Z", "feedback", {
+ signal: "[[sig-x]]",
+ topic: "x",
+ sign: "positive",
+ origin_channel: "unset",
+ }),
+ );
});
test("appends a second event to both files", () => {
diff --git a/tests/core/brain.types.test.ts b/tests/core/brain.types.test.ts
index 26a506f0..712ec1e2 100644
--- a/tests/core/brain.types.test.ts
+++ b/tests/core/brain.types.test.ts
@@ -134,6 +134,15 @@ describe("BRAIN_* const enums", () => {
// salience-lifecycle-enrichment unit 3c (t_5e338af1) expiration set,
// changed or explicitly cleared after the artifact was written
"expiration-set",
+ // who-wrote-what Task C (t_109fa94d) fleet freeze: the two operator
+ // transitions and the refusal each frozen write is recorded as
+ "freeze",
+ "unfreeze",
+ "write-refused",
+ // who-wrote-what Task A (t_662f4e82) one vault note created, updated,
+ // appended to or reverted - the event that makes the bulk of what an
+ // agent produces attributable at all
+ "note-write",
]);
const actual = new Set<string>(Object.values(BRAIN_LOG_EVENT_KIND));
expect(actual).toEqual(expected);
@@ -166,6 +175,13 @@ describe("BRAIN_SNAPSHOT_REASON", () => {
expect(BRAIN_SNAPSHOT_REASON.entityPrune).toBe("entity-prune");
});
+ test("the two note-file reasons name the verbs that take them", () => {
+ // Both double as archive filename prefixes, so a rename here would
+ // orphan the archives already in `.snapshots/`.
+ expect(BRAIN_SNAPSHOT_REASON.noteDelete).toBe("note-delete");
+ expect(BRAIN_SNAPSHOT_REASON.noteRevert).toBe("note-revert");
+ });
+
test("the three deferred boundary reasons and the manual one are readable", () => {
// Nothing WRITES these yet (taking snapshots at those boundaries is
// deferred), and the manifest must still be able to read a reason a
diff --git a/tests/core/brain/continuity-store.test.ts b/tests/core/brain/continuity-store.test.ts
index 4e848548..9df6257a 100644
--- a/tests/core/brain/continuity-store.test.ts
+++ b/tests/core/brain/continuity-store.test.ts
@@ -1,13 +1,22 @@
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
-import { existsSync, mkdtempSync, readFileSync, rmSync } from "node:fs";
+import {
+ chmodSync,
+ existsSync,
+ mkdirSync,
+ mkdtempSync,
+ readFileSync,
+ rmSync,
+ writeFileSync,
+} from "node:fs";
import { tmpdir } from "node:os";
-import { join } from "node:path";
+import { dirname, join } from "node:path";
import { acquireLockSync } from "../../../src/core/brain/sync-lockfile.ts";
import {
appendContinuityRecord,
appendContinuityRecords,
appendContinuitySourceInvalidation,
+ buildContinuityRecord,
continuityLogPath,
isCanonicalUtcTimestamp,
listContinuityRecords,
@@ -290,3 +299,120 @@ describe("createdAt validation at the store boundary", () => {
expect(listContinuityRecords(vault, {})).toHaveLength(0);
});
});
+
+/**
+ * Per-device shards (who-wrote-what, Task B / t_1814b9bf). Two devices
+ * syncing one vault must not append to the same month file, and a reader
+ * on either device must see the same merged sequence.
+ */
+describe("continuity per-device shards", () => {
+ const savedEnv: Record<string, string | undefined> = {};
+ let configHome: string;
+
+ beforeEach(() => {
+ configHome = mkdtempSync(join(tmpdir(), "o2b-continuity-shard-cfg-"));
+ const configPath = join(configHome, "config.yaml");
+ savedEnv["OPEN_SECOND_BRAIN_CONFIG"] = process.env["OPEN_SECOND_BRAIN_CONFIG"];
+ savedEnv["O2B_DEVICE_ID"] = process.env["O2B_DEVICE_ID"];
+ process.env["OPEN_SECOND_BRAIN_CONFIG"] = configPath;
+ delete process.env["O2B_DEVICE_ID"];
+ writeFileSync(configPath, `vault: ${vault}\ndevice_id: "testdev1"\n`, "utf8");
+ });
+
+ afterEach(() => {
+ rmSync(configHome, { recursive: true, force: true });
+ for (const key of ["OPEN_SECOND_BRAIN_CONFIG", "O2B_DEVICE_ID"]) {
+ const value = savedEnv[key];
+ if (value === undefined) delete process.env[key];
+ else process.env[key] = value;
+ }
+ });
+
+ function record(createdAt: string, snippet: string) {
+ return buildContinuityRecord({
+ kind: "session_turn",
+ createdAt,
+ sourceRefs: [{ id: snippet }],
+ payload: { snippet },
+ });
+ }
+
+ /** Write a shard directly, standing in for a file Syncthing delivered. */
+ function writeShard(month: string, shardId: string, snippets: ReadonlyArray<string>): void {
+ const path = continuityLogPath(vault, month, shardId);
+ mkdirSync(dirname(path), { recursive: true });
+ writeFileSync(
+ path,
+ snippets.map((s) => `${JSON.stringify(record(`${month}-01T10:00:0${s[0]}Z`, s))}\n`).join(""),
+ "utf8",
+ );
+ }
+
+ test("a device with an id writes its own shard and never the bare file", () => {
+ appendContinuityRecord(vault, {
+ kind: "session_turn",
+ createdAt: "2026-06-01T10:00:00Z",
+ payload: { snippet: "one" },
+ });
+ expect(existsSync(continuityLogPath(vault, "2026-06", "testdev1"))).toBe(true);
+ expect(existsSync(continuityLogPath(vault, "2026-06", ""))).toBe(false);
+ });
+
+ test("a batch append lands in the device shard too", () => {
+ appendContinuityRecords(vault, [
+ { kind: "session_turn", createdAt: "2026-06-01T10:00:00Z", payload: { snippet: "a" } },
+ { kind: "session_turn", createdAt: "2026-06-01T10:00:01Z", payload: { snippet: "b" } },
+ ]);
+ const raw = readFileSync(continuityLogPath(vault, "2026-06", "testdev1"), "utf8");
+ expect(raw.trim().split("\n")).toHaveLength(2);
+ expect(existsSync(continuityLogPath(vault, "2026-06", ""))).toBe(false);
+ });
+
+ test("the reader merges the bare file and every device shard in one order", () => {
+ writeShard("2026-06", "", ["0-legacy"]);
+ writeShard("2026-06", "devb", ["2-otherdev"]);
+ writeShard("2026-06", "testdev1", ["1-mine"]);
+ expect(listContinuityRecords(vault, {}).map((r) => r.payload["snippet"])).toEqual([
+ "0-legacy",
+ "1-mine",
+ "2-otherdev",
+ ]);
+ });
+
+ test("a sync-conflict copy is not a shard and is never merged", () => {
+ writeShard("2026-06", "testdev1", ["1-mine"]);
+ const dir = dirname(continuityLogPath(vault, "2026-06", ""));
+ writeFileSync(
+ join(dir, "2026-06.sync-conflict-20260601-120000-ABCDEFG.jsonl"),
+ `${JSON.stringify(record("2026-06-01T09:00:00Z", "conflict"))}\n`,
+ "utf8",
+ );
+ expect(listContinuityRecords(vault, {}).map((r) => r.payload["snippet"])).toEqual(["1-mine"]);
+ });
+
+ test("the month range-skip reads the parsed base of a sharded name", () => {
+ writeShard("2026-06", "testdev1", ["1-mine"]);
+ writeShard("2026-05", "testdev1", ["0-may"]);
+ const listed = listContinuityRecords(vault, { since: "2026-06-01T00:00:00Z" });
+ expect(listed.map((r) => r.payload["snippet"])).toEqual(["1-mine"]);
+ });
+
+ /**
+ * A shard this process cannot read is not an empty shard: a listing
+ * that silently drops it reports a shorter history as if it were the
+ * whole one.
+ */
+ test.skipIf(process.getuid?.() === 0)(
+ "an unreadable shard is refused, not listed as absent",
+ () => {
+ writeShard("2026-06", "testdev1", ["1-mine"]);
+ const path = continuityLogPath(vault, "2026-06", "testdev1");
+ chmodSync(path, 0o000);
+ try {
+ expect(() => listContinuityRecords(vault, {})).toThrow(/EACCES|EPERM/);
+ } finally {
+ chmodSync(path, 0o600);
+ }
+ },
+ );
+});
diff --git a/tests/core/brain/doctor-exit-census.test.ts b/tests/core/brain/doctor-exit-census.test.ts
index 614d265b..b721e9ad 100644
--- a/tests/core/brain/doctor-exit-census.test.ts
+++ b/tests/core/brain/doctor-exit-census.test.ts
@@ -187,6 +187,7 @@ const DOCTOR_REGISTERED_CODES: ReadonlyArray<string> = [
"embedding-model-sunset-announced",
"entity-label-malformed",
"entity-quote-variant-collision",
+ "log-chain-broken",
"low-evidence-confirmed",
"orphan-evidence",
"principle-corrupted",
@@ -198,6 +199,7 @@ const DOCTOR_REGISTERED_CODES: ReadonlyArray<string> = [
"sync-conflict-log",
"tier-drift",
"topic-key-collision",
+ "vault-frozen",
"vault-walk-entry-skipped",
];
diff --git a/tests/core/brain/doctor-frozen.test.ts b/tests/core/brain/doctor-frozen.test.ts
new file mode 100644
index 00000000..d70cc9aa
--- /dev/null
+++ b/tests/core/brain/doctor-frozen.test.ts
@@ -0,0 +1,83 @@
+/**
+ * The doctor names a frozen vault (who-wrote-what, Task C).
+ *
+ * A freeze is a standing condition rather than a fault, and it is the
+ * condition that explains every other symptom an operator might chase:
+ * writes that vanish, a pass that reports nothing, an agent that keeps
+ * apologising. So it is a WARNING with an exact next command, never an
+ * error and never silence.
+ */
+
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { DIAGNOSTIC_SIGNALS } from "../../../src/core/brain/diagnostics.ts";
+import { runDoctor } from "../../../src/core/brain/doctor.ts";
+import { VAULT_FROZEN_CODE } from "../../../src/core/brain/doctor/frozen-check.ts";
+import { freezeVault, unfreezeVault } from "../../../src/core/brain/freeze.ts";
+import { frozenMarkerPath, resetFreezeMarkerCache } from "../../../src/core/brain/freeze-marker.ts";
+import { resetVaultIdentityPins } from "../../../src/core/brain/vault-identity.ts";
+
+let tmp: string;
+let vault: string;
+
+beforeEach(() => {
+ tmp = mkdtempSync(join(tmpdir(), "o2b-doctor-frozen-"));
+ vault = join(tmp, "vault");
+ for (const d of ["preferences", "retired", "inbox", "processed", "log"]) {
+ mkdirSync(join(vault, "Brain", d), { recursive: true });
+ }
+ writeFileSync(join(vault, "Brain", "_brain.yaml"), "schema_version: 1\n");
+ resetFreezeMarkerCache();
+ resetVaultIdentityPins();
+});
+
+afterEach(() => {
+ rmSync(tmp, { recursive: true, force: true });
+ resetFreezeMarkerCache();
+ resetVaultIdentityPins();
+});
+
+describe("the frozen-vault check", () => {
+ test("says nothing about a vault nobody froze", async () => {
+ const report = await runDoctor(vault);
+ expect(report.warnings.filter((i) => i.code === VAULT_FROZEN_CODE)).toHaveLength(0);
+ });
+
+ test("warns while the marker stands, naming who froze it and why", async () => {
+ freezeVault(vault, { agent: "@operator", reason: "migrating" });
+ const report = await runDoctor(vault);
+ const found = report.warnings.filter((i) => i.code === VAULT_FROZEN_CODE);
+ expect(found).toHaveLength(1);
+ expect(found[0]!.severity).toBe("warning");
+ expect(found[0]!.message).toContain("@operator");
+ expect(found[0]!.message).toContain("migrating");
+ expect(found[0]!.path).toBe(frozenMarkerPath(vault));
+ });
+
+ test("stops warning once the freeze is lifted", async () => {
+ freezeVault(vault, { agent: "@operator", reason: "migrating" });
+ unfreezeVault(vault, { agent: "@operator" });
+ const report = await runDoctor(vault);
+ expect(report.warnings.filter((i) => i.code === VAULT_FROZEN_CODE)).toHaveLength(0);
+ });
+
+ test("warns about a marker nobody can parse, which freezes just the same", async () => {
+ mkdirSync(join(vault, "Brain", ".state"), { recursive: true });
+ writeFileSync(frozenMarkerPath(vault), "{ not json", "utf8");
+ const report = await runDoctor(vault);
+ expect(report.warnings.filter((i) => i.code === VAULT_FROZEN_CODE)).toHaveLength(1);
+ });
+});
+
+describe("the exit", () => {
+ test("the finding carries the one command that lifts it", () => {
+ const signal = DIAGNOSTIC_SIGNALS.get(VAULT_FROZEN_CODE);
+ expect(signal).toBeDefined();
+ expect(signal!.nextCommand).toBe("o2b brain unfreeze");
+ // A freeze is an operator's decision; no repair pass may undo one.
+ expect(signal!.autoRepairable).toBe(false);
+ });
+});
diff --git a/tests/core/brain/doctor-log-chain.test.ts b/tests/core/brain/doctor-log-chain.test.ts
new file mode 100644
index 00000000..0fc0099d
--- /dev/null
+++ b/tests/core/brain/doctor-log-chain.test.ts
@@ -0,0 +1,129 @@
+/**
+ * The doctor names a Brain log shard that stopped linking up
+ * (who-wrote-what, Task E).
+ *
+ * The chain is report-only, so the doctor is the surface an operator who
+ * is not looking for it reaches it through. One finding per broken
+ * shard, naming the file and the line, because "the log was edited" with
+ * no file to open is a dead end.
+ */
+
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { DIAGNOSTIC_SIGNALS } from "../../../src/core/brain/diagnostics.ts";
+import { runDoctor } from "../../../src/core/brain/doctor.ts";
+import { LOG_CHAIN_BROKEN_CODE } from "../../../src/core/brain/doctor/log-chain-check.ts";
+import { appendLogEvent } from "../../../src/core/brain/log.ts";
+import { logJsonlPath, logShardJsonlPath } from "../../../src/core/brain/paths.ts";
+
+const DATE = "2026-06-02";
+
+let tmp: string;
+let vault: string;
+
+beforeEach(() => {
+ tmp = mkdtempSync(join(tmpdir(), "o2b-doctor-log-chain-"));
+ vault = join(tmp, "vault");
+ for (const d of ["preferences", "retired", "inbox", "processed", "log"]) {
+ mkdirSync(join(vault, "Brain", d), { recursive: true });
+ }
+ writeFileSync(join(vault, "Brain", "_brain.yaml"), "schema_version: 1\n");
+});
+
+afterEach(() => {
+ rmSync(tmp, { recursive: true, force: true });
+});
+
+function appendMany(count: number, shardId = ""): void {
+ for (let i = 0; i < count; i++) {
+ appendLogEvent(
+ vault,
+ {
+ timestamp: `${DATE}T10:00:0${i}Z`,
+ eventType: "note",
+ body: { text: `event ${i}`, agent: "@tester" },
+ },
+ { deviceId: shardId },
+ );
+ }
+}
+
+/** Remove the `line`th (1-based) row of a shard, breaking its chain. */
+function dropLine(path: string, line: number): void {
+ const rows = readFileSync(path, "utf8").trim().split("\n");
+ rows.splice(line - 1, 1);
+ writeFileSync(path, rows.join("\n") + "\n", "utf8");
+}
+
+describe("the log-chain check", () => {
+ test("says nothing about a log nobody edited", async () => {
+ appendMany(3);
+ const report = await runDoctor(vault);
+ expect(report.warnings.filter((i) => i.code === LOG_CHAIN_BROKEN_CODE)).toHaveLength(0);
+ expect(report.errors.filter((i) => i.code === LOG_CHAIN_BROKEN_CODE)).toHaveLength(0);
+ });
+
+ test("says nothing about a vault whose log holds only pre-chain lines", async () => {
+ writeFileSync(
+ logJsonlPath(vault, DATE),
+ JSON.stringify({ ts: `${DATE}T09:00:00Z`, kind: "note", payload: { text: "legacy" } }) + "\n",
+ "utf8",
+ );
+ const report = await runDoctor(vault);
+ expect(report.warnings.filter((i) => i.code === LOG_CHAIN_BROKEN_CODE)).toHaveLength(0);
+ });
+
+ test("warns once per broken shard, naming the shard and the line", async () => {
+ appendMany(3);
+ dropLine(logJsonlPath(vault, DATE), 2);
+
+ const report = await runDoctor(vault);
+ const found = report.warnings.filter((i) => i.code === LOG_CHAIN_BROKEN_CODE);
+ expect(found).toHaveLength(1);
+ expect(found[0]!.severity).toBe("warning");
+ expect(found[0]!.path).toBe(logJsonlPath(vault, DATE));
+ expect(found[0]!.message).toContain("line 2");
+ expect(found[0]!.message).toContain("removed or reordered");
+ });
+
+ test("reports two broken shards as two findings", async () => {
+ appendMany(3, "devalpha");
+ appendMany(3, "devbeta");
+ dropLine(logShardJsonlPath(vault, DATE, "devalpha"), 2);
+ dropLine(logShardJsonlPath(vault, DATE, "devbeta"), 2);
+
+ const report = await runDoctor(vault);
+ const found = report.warnings.filter((i) => i.code === LOG_CHAIN_BROKEN_CODE);
+ expect(found).toHaveLength(2);
+ expect(found.map((i) => i.path).toSorted()).toEqual(
+ [
+ logShardJsonlPath(vault, DATE, "devalpha"),
+ logShardJsonlPath(vault, DATE, "devbeta"),
+ ].toSorted(),
+ );
+ });
+
+ test("a break in one shard leaves the other shard unreported", async () => {
+ appendMany(3, "devalpha");
+ appendMany(3, "devbeta");
+ dropLine(logShardJsonlPath(vault, DATE, "devalpha"), 2);
+
+ const report = await runDoctor(vault);
+ const found = report.warnings.filter((i) => i.code === LOG_CHAIN_BROKEN_CODE);
+ expect(found).toHaveLength(1);
+ expect(found[0]!.path).toBe(logShardJsonlPath(vault, DATE, "devalpha"));
+ });
+});
+
+describe("the exit", () => {
+ test("the finding carries the command that shows the whole picture", () => {
+ const signal = DIAGNOSTIC_SIGNALS.get(LOG_CHAIN_BROKEN_CODE);
+ expect(signal).toBeDefined();
+ expect(signal!.nextCommand).toBe("o2b brain log verify");
+ // Nothing may rewrite an audit trail to make it verify.
+ expect(signal!.autoRepairable).toBe(false);
+ });
+});
diff --git a/tests/core/brain/doctor-sync-conflict-ledgers.test.ts b/tests/core/brain/doctor-sync-conflict-ledgers.test.ts
new file mode 100644
index 00000000..3a19f391
--- /dev/null
+++ b/tests/core/brain/doctor-sync-conflict-ledgers.test.ts
@@ -0,0 +1,102 @@
+/**
+ * `sync-conflict-log` covers every ledger directory (who-wrote-what,
+ * Task B / t_1814b9bf).
+ *
+ * The per-device shard layout means no reader merges a Syncthing
+ * conflict copy - not under `Brain/log/`, and not under any of the five
+ * other append-only ledger directories that now shard the same way. One
+ * exit, one meaning: "a sync conflict copy exists that no reader
+ * merges", with the directory named in the detail so an operator knows
+ * where to do the union+dedup merge.
+ */
+
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { continuityLogDir } from "../../../src/core/brain/continuity/store.ts";
+import { runDoctor } from "../../../src/core/brain/doctor.ts";
+import { idempotencyLogDir } from "../../../src/core/brain/idempotency-ledger.ts";
+import { bootstrapBrain } from "../../../src/core/brain/init.ts";
+import { brainStateDirPath } from "../../../src/core/brain/lineage/ledger.ts";
+import { metricsDir } from "../../../src/core/brain/metrics.ts";
+import { brainDirs, prefAuditDir } from "../../../src/core/brain/paths.ts";
+import { atomicWriteFileSync } from "../../../src/core/fs-atomic.ts";
+
+let vault: string;
+let configHome: string;
+
+beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "o2b-conflict-sweep-"));
+ configHome = mkdtempSync(join(tmpdir(), "o2b-conflict-sweep-cfg-"));
+ const configPath = join(configHome, "config.yaml");
+ atomicWriteFileSync(configPath, `vault: ${vault}\n`);
+ bootstrapBrain(vault, { configPath });
+});
+
+afterEach(() => {
+ rmSync(vault, { recursive: true, force: true });
+ rmSync(configHome, { recursive: true, force: true });
+});
+
+/** The conflict-copy name Syncthing writes, for an arbitrary stem. */
+function conflictName(stem: string): string {
+ return `${stem}.sync-conflict-20260610-120000-ABCDEFG.jsonl`;
+}
+
+function plant(dir: string, stem: string): string {
+ mkdirSync(dir, { recursive: true });
+ const path = join(dir, conflictName(stem));
+ writeFileSync(path, "{}\n", "utf8");
+ return path;
+}
+
+function conflictFindings(): ReadonlyArray<{ message: string; path?: string }> {
+ return runDoctor(vault).warnings.filter((i) => i.code === "sync-conflict-log");
+}
+
+describe("sync-conflict sweep across every ledger directory", () => {
+ const LEDGERS: ReadonlyArray<readonly [string, (v: string) => string, string]> = [
+ ["Brain log", (v) => brainDirs(v).log, "2026-06-10"],
+ ["continuity", continuityLogDir, "2026-06"],
+ ["idempotency", idempotencyLogDir, "2026-06"],
+ ["preference audit", prefAuditDir, "pref-alpha"],
+ ["metrics", metricsDir, "index"],
+ ["Brain state", brainStateDirPath, "session-lineage"],
+ ];
+
+ test.each(LEDGERS)("%s: a conflict copy is reported with its directory", (_label, dir, stem) => {
+ const path = plant(dir(vault), stem);
+ const findings = conflictFindings();
+ expect(findings).toHaveLength(1);
+ expect(findings[0]!.path).toBe(path);
+ expect(findings[0]!.message).toContain("sync-conflict");
+ });
+
+ test("a clean vault reports nothing", () => {
+ expect(conflictFindings()).toHaveLength(0);
+ });
+
+ test("every ledger directory is swept in one pass", () => {
+ for (const [, dir, stem] of LEDGERS) plant(dir(vault), stem);
+ expect(conflictFindings()).toHaveLength(LEDGERS.length);
+ });
+
+ test("the six directories are distinct, so no one of them is swept twice", () => {
+ const dirs = LEDGERS.map(([, dir]) => dir(vault));
+ expect(new Set(dirs).size).toBe(LEDGERS.length);
+ });
+
+ /**
+ * The preference audit is the one ledger whose shards live a level
+ * down - one directory per preference - so sweeping only its parent
+ * would report a clean ledger while a copy nobody merges sat inside.
+ */
+ test("a conflict copy inside a per-preference directory is reported too", () => {
+ const path = plant(join(prefAuditDir(vault), "pref-alpha"), "device");
+ const findings = conflictFindings();
+ expect(findings).toHaveLength(1);
+ expect(findings[0]!.path).toBe(path);
+ });
+});
diff --git a/tests/core/brain/dream-checkpoints.test.ts b/tests/core/brain/dream-checkpoints.test.ts
index 2cfe17af..18143258 100644
--- a/tests/core/brain/dream-checkpoints.test.ts
+++ b/tests/core/brain/dream-checkpoints.test.ts
@@ -46,6 +46,7 @@ import {
import { writeSignal } from "../../../src/core/brain/signal.ts";
import { bootstrapBrain } from "../../../src/core/brain/init.ts";
import { atomicWriteFileSync } from "../../../src/core/fs-atomic.ts";
+import { maskLogChainDigests } from "../../helpers/vault-digest.ts";
let vault: string;
let configHome: string;
@@ -166,7 +167,12 @@ function treeDigest(root: string): string {
continue;
}
const content = rel.startsWith(`${NORMALISED_SUBTREE}/`)
- ? readFileSync(full, "utf8").replaceAll(ARCHIVE_SIZE_RE, "$1<archive-size>")
+ ? // The chain hash covers `size_bytes`, so the field this
+ // comparison cannot ask to be reproducible propagates into
+ // every row's `h` - see `maskLogChainDigests`.
+ maskLogChainDigests(
+ readFileSync(full, "utf8").replaceAll(ARCHIVE_SIZE_RE, "$1<archive-size>"),
+ )
: readFileSync(full);
lines.push(`${rel}:${createHash("sha256").update(content).digest("hex")}`);
}
diff --git a/tests/core/brain/freeze-marker.test.ts b/tests/core/brain/freeze-marker.test.ts
new file mode 100644
index 00000000..2c44cb0c
--- /dev/null
+++ b/tests/core/brain/freeze-marker.test.ts
@@ -0,0 +1,147 @@
+/**
+ * Fleet freeze, read side (who-wrote-what, Task C).
+ *
+ * The marker is the whole mechanism: a file every device sees through
+ * Syncthing, read in front of every content write. These tests pin the
+ * four states it can be in - absent, present, unreadable, replaced - and
+ * the one asymmetry that makes the freeze trustworthy: a marker nobody
+ * can parse freezes the vault rather than reopening it.
+ */
+
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { atomicWriteFileSync } from "../../../src/core/fs-atomic.ts";
+import {
+ FREEZE_MARKER_SCHEMA_VERSION,
+ FREEZE_MARKER_UNREADABLE_REASON,
+ FREEZE_NEXT_COMMAND,
+ VaultFrozenError,
+ WRITE_LANE,
+ assertVaultNotFrozen,
+ freezeMarkerReloadCount,
+ frozenMarkerPath,
+ readFreezeMarker,
+ resetFreezeMarkerCache,
+} from "../../../src/core/brain/freeze-marker.ts";
+
+let vault: string;
+
+beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "o2b-freeze-marker-"));
+ mkdirSync(join(vault, "Brain"), { recursive: true });
+ resetFreezeMarkerCache();
+});
+
+afterEach(() => {
+ rmSync(vault, { recursive: true, force: true });
+ resetFreezeMarkerCache();
+});
+
+/** Write a well-formed marker the way `freezeVault` does. */
+function writeMarker(reason: string): void {
+ atomicWriteFileSync(
+ frozenMarkerPath(vault),
+ `${JSON.stringify(
+ {
+ schema: FREEZE_MARKER_SCHEMA_VERSION,
+ frozen_at: "2026-09-10T08:00:00Z",
+ by: "@operator",
+ device_id: "laptop",
+ reason,
+ },
+ null,
+ 2,
+ )}\n`,
+ );
+}
+
+describe("the freeze marker's location", () => {
+ test("sits in the internal state directory, inside the vault", () => {
+ expect(frozenMarkerPath(vault)).toBe(join(vault, "Brain", ".state", "frozen.json"));
+ });
+});
+
+describe("reading the marker", () => {
+ test("an absent marker is an absence, and nothing is refused", () => {
+ expect(readFreezeMarker(vault)).toBeNull();
+ expect(() => assertVaultNotFrozen(vault)).not.toThrow();
+ });
+
+ test("a present marker is read field for field", () => {
+ writeMarker("migrating the laptop");
+ const marker = readFreezeMarker(vault);
+ expect(marker).not.toBeNull();
+ expect(marker!.frozen_at).toBe("2026-09-10T08:00:00Z");
+ expect(marker!.by).toBe("@operator");
+ expect(marker!.device_id).toBe("laptop");
+ expect(marker!.reason).toBe("migrating the laptop");
+ });
+
+ test("a malformed marker IS a freeze, named as unreadable rather than absent", () => {
+ mkdirSync(join(vault, "Brain", ".state"), { recursive: true });
+ writeFileSync(frozenMarkerPath(vault), "{ not json", "utf8");
+ const marker = readFreezeMarker(vault);
+ expect(marker).not.toBeNull();
+ expect(marker!.reason).toBe(FREEZE_MARKER_UNREADABLE_REASON);
+ expect(() => assertVaultNotFrozen(vault)).toThrow(VaultFrozenError);
+ });
+
+ test("a marker missing its timestamp is unreadable too, never a half-freeze", () => {
+ mkdirSync(join(vault, "Brain", ".state"), { recursive: true });
+ writeFileSync(frozenMarkerPath(vault), JSON.stringify({ schema: 1, by: "@x" }), "utf8");
+ expect(readFreezeMarker(vault)!.reason).toBe(FREEZE_MARKER_UNREADABLE_REASON);
+ });
+});
+
+describe("the refusal", () => {
+ test("names when, who, why, and the way out", () => {
+ writeMarker("migrating the laptop");
+ let raised: unknown;
+ try {
+ assertVaultNotFrozen(vault);
+ } catch (exc) {
+ raised = exc;
+ }
+ expect(raised).toBeInstanceOf(VaultFrozenError);
+ const err = raised as VaultFrozenError;
+ expect(err.frozen_at).toBe("2026-09-10T08:00:00Z");
+ expect(err.by).toBe("@operator");
+ expect(err.reason).toBe("migrating the laptop");
+ expect(err.next_command).toBe(FREEZE_NEXT_COMMAND);
+ expect(err.notice.code).toBe("vault-frozen");
+ expect(err.message).toContain(FREEZE_NEXT_COMMAND);
+ });
+});
+
+describe("the per-process cache", () => {
+ test("re-reads only when the file on disk is not the one already parsed", () => {
+ writeMarker("first");
+ expect(readFreezeMarker(vault)!.reason).toBe("first");
+ const afterFirst = freezeMarkerReloadCount();
+ // Same bytes, same inode: the cached parse answers.
+ expect(readFreezeMarker(vault)!.reason).toBe("first");
+ expect(freezeMarkerReloadCount()).toBe(afterFirst);
+
+ // `atomicWriteFileSync` renames a temp file into place, so a replaced
+ // marker always arrives with a new inode.
+ writeMarker("second");
+ expect(readFreezeMarker(vault)!.reason).toBe("second");
+ expect(freezeMarkerReloadCount()).toBe(afterFirst + 1);
+ });
+
+ test("an unfreeze is visible to a process that had the freeze cached", () => {
+ writeMarker("first");
+ expect(readFreezeMarker(vault)).not.toBeNull();
+ rmSync(frozenMarkerPath(vault));
+ expect(readFreezeMarker(vault)).toBeNull();
+ });
+});
+
+describe("the write lanes", () => {
+ test("are a closed pair, so a third lane cannot be invented at a call site", () => {
+ expect(Object.values(WRITE_LANE).toSorted()).toEqual(["audit", "content"]);
+ });
+});
diff --git a/tests/core/brain/freeze-write-lane.test.ts b/tests/core/brain/freeze-write-lane.test.ts
new file mode 100644
index 00000000..c04052b1
--- /dev/null
+++ b/tests/core/brain/freeze-write-lane.test.ts
@@ -0,0 +1,200 @@
+/**
+ * What a freeze actually holds, and the one thing it deliberately does
+ * not (who-wrote-what, Task C).
+ *
+ * The freeze lives inside `assertVaultIdentityForWrite`, which every
+ * content writer in `src/core/brain/` already passes. These tests drive
+ * the real writers rather than the guard, because "the guard throws" is
+ * a property of one function and "a frozen vault refuses note writes" is
+ * the property the feature claims. The audit lane is asserted the same
+ * way: `appendLogEvent` must still land, or the freeze erases the record
+ * of itself.
+ */
+
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join, relative } from "node:path";
+
+import { freezeVault } from "../../../src/core/brain/freeze.ts";
+import {
+ VaultFrozenError,
+ WRITE_LANE,
+ resetFreezeMarkerCache,
+} from "../../../src/core/brain/freeze-marker.ts";
+import { appendLogEvent } from "../../../src/core/brain/log.ts";
+import { createNote } from "../../../src/core/brain/notes/create-note.ts";
+import { brainDirs, brainDirsForWrite } from "../../../src/core/brain/paths.ts";
+import { appendPrefAudit } from "../../../src/core/brain/pref-audit.ts";
+import { restoreSnapshot } from "../../../src/core/brain/snapshot.ts";
+import { applyWriteBatch } from "../../../src/core/brain/write-batch.ts";
+import { resetVaultIdentityPins } from "../../../src/core/brain/vault-identity.ts";
+
+const REPO_ROOT = join(import.meta.dir, "..", "..", "..");
+
+let vault: string;
+
+beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "o2b-freeze-lane-"));
+ mkdirSync(join(vault, "Brain"), { recursive: true });
+ resetFreezeMarkerCache();
+ resetVaultIdentityPins();
+});
+
+afterEach(() => {
+ rmSync(vault, { recursive: true, force: true });
+ resetFreezeMarkerCache();
+ resetVaultIdentityPins();
+});
+
+function freeze(): void {
+ freezeVault(vault, { agent: "@operator", reason: "migrating the fleet" });
+}
+
+describe("the content lane while frozen", () => {
+ test("brainDirsForWrite refuses, naming the freeze and the way out", () => {
+ freeze();
+ let raised: unknown;
+ try {
+ brainDirsForWrite(vault);
+ } catch (exc) {
+ raised = exc;
+ }
+ expect(raised).toBeInstanceOf(VaultFrozenError);
+ const err = raised as VaultFrozenError;
+ expect(err.reason).toBe("migrating the fleet");
+ expect(err.by).toBe("@operator");
+ expect(err.frozen_at).not.toBe("");
+ expect(err.next_command).toBe("o2b brain unfreeze");
+ });
+
+ test("createNote refuses and leaves no file behind", () => {
+ freeze();
+ expect(() => createNote(vault, { path: "notes/frozen.md", content: "body" })).toThrow(
+ VaultFrozenError,
+ );
+ expect(existsSync(join(vault, "notes", "frozen.md"))).toBe(false);
+ });
+
+ test("applyWriteBatch refuses before it reads its operations", () => {
+ freeze();
+ expect(() =>
+ applyWriteBatch(vault, [{ kind: "create_note", path: "notes/batch.md", content: "body" }]),
+ ).toThrow(VaultFrozenError);
+ expect(existsSync(join(vault, "notes", "batch.md"))).toBe(false);
+ });
+
+ test("appendPrefAudit refuses", () => {
+ freeze();
+ expect(() =>
+ appendPrefAudit(vault, {
+ pref_id: "pref-frozen",
+ op: "create",
+ agent: "@agent",
+ revision_before: null,
+ revision_after: 1,
+ hash_before: null,
+ hash_after: "abc",
+ }),
+ ).toThrow(VaultFrozenError);
+ });
+
+ test("restoreSnapshot refuses by name, before it looks the run id up", () => {
+ freeze();
+ // The run id does not exist. A vault that was NOT frozen would fail
+ // with a missing-snapshot error; the freeze has to win, or an
+ // operator recovering a frozen vault would silently move bytes.
+ let raised: unknown;
+ try {
+ restoreSnapshot(vault, "20260101T000000Z-abcdef");
+ } catch (exc) {
+ raised = exc;
+ }
+ expect(raised).toBeInstanceOf(VaultFrozenError);
+ });
+
+ test("the refusal lifts the moment the marker goes", () => {
+ freeze();
+ expect(() => brainDirsForWrite(vault)).toThrow(VaultFrozenError);
+ rmSync(join(vault, "Brain", ".state", "frozen.json"));
+ expect(brainDirsForWrite(vault)).toEqual(brainDirs(vault));
+ });
+});
+
+describe("the audit lane while frozen", () => {
+ test("appendLogEvent still lands, so the freeze does not erase its own record", () => {
+ freeze();
+ const result = appendLogEvent(
+ vault,
+ {
+ timestamp: "2026-09-10T09:00:00Z",
+ eventType: "write-refused",
+ body: { tool: "brain_create_note", agent: "@agent" },
+ },
+ { deviceId: "" },
+ );
+ expect(existsSync(result.logPath)).toBe(true);
+ expect(readFileSync(result.logPath, "utf8")).toContain("write-refused");
+ });
+});
+
+/**
+ * The audit lane is an exemption from the freeze, and an exemption
+ * spreads by being convenient. This is the bound: two modules ask for it,
+ * both of them are the record-keeping the freeze cannot silence, and a
+ * third asking is a decision somebody has to make in front of this test.
+ */
+describe("the audit lane's blast radius", () => {
+ const ALLOWED = new Set(["src/core/brain/log.ts", "src/core/brain/freeze.ts"]);
+
+ function sourceFiles(dir: string): string[] {
+ const out: string[] = [];
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
+ const abs = join(dir, entry.name);
+ if (entry.isDirectory()) out.push(...sourceFiles(abs));
+ else if (entry.name.endsWith(".ts")) out.push(abs);
+ }
+ return out;
+ }
+
+ /**
+ * Two spellings reach the same lane. `WRITE_LANE.audit` is the one the
+ * exemption is written in; the bare literal `"audit"` passed as the
+ * third argument to either guard is the same request wearing different
+ * clothes, and a pin that greps only the constant would let it in.
+ */
+ const LANE_SPELLINGS: ReadonlyArray<RegExp> = Object.freeze([
+ /WRITE_LANE\.audit\b/,
+ // `fn(vault, <anything but a comma or paren>, "audit")` across lines.
+ /\b(?:assertVaultIdentityForWrite|brainDirsForWrite)\s*\(\s*[^,()]*,[^,()]*,\s*["'`]audit["'`]/s,
+ ]);
+
+ test("WRITE_LANE.audit is requested from the record-keeping modules and nowhere else", () => {
+ const requesting = sourceFiles(join(REPO_ROOT, "src"))
+ .filter((abs) => {
+ const text = readFileSync(abs, "utf8");
+ return LANE_SPELLINGS.some((re) => re.test(text));
+ })
+ .map((abs) => relative(REPO_ROOT, abs).split("\\").join("/"));
+ expect(requesting.toSorted()).toEqual([...ALLOWED].toSorted());
+ });
+
+ test("the literal spelling of the lane is caught, not only the constant", () => {
+ const literalCall = 'assertVaultIdentityForWrite(vault, undefined, "audit");';
+ expect(LANE_SPELLINGS.some((re) => re.test(literalCall))).toBe(true);
+ expect(
+ LANE_SPELLINGS.some((re) => re.test('brainDirsForWrite(v, undefined, "audit").log')),
+ ).toBe(true);
+ // The content lane, spelled either way, is not the audit lane.
+ expect(LANE_SPELLINGS.some((re) => re.test("assertVaultIdentityForWrite(vault);"))).toBe(false);
+ expect(
+ LANE_SPELLINGS.some((re) =>
+ re.test('assertVaultIdentityForWrite(vault, undefined, "content")'),
+ ),
+ ).toBe(false);
+ });
+
+ test("the lane vocabulary is what the pin is written against", () => {
+ expect(WRITE_LANE.audit).toBe("audit");
+ });
+});
diff --git a/tests/core/brain/freeze.test.ts b/tests/core/brain/freeze.test.ts
new file mode 100644
index 00000000..ca2c50bb
--- /dev/null
+++ b/tests/core/brain/freeze.test.ts
@@ -0,0 +1,120 @@
+/**
+ * Setting and lifting the fleet freeze (who-wrote-what, Task C).
+ *
+ * The marker's whole content is its existence, so the two log events are
+ * the only durable record of who stopped the vault and who started it
+ * again. These tests hold both ends to that: one event per real
+ * transition, none for a call that changed nothing, and an `unfreeze`
+ * that still carries what the marker said before it was removed.
+ */
+
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { freezeVault, unfreezeVault } from "../../../src/core/brain/freeze.ts";
+import {
+ FREEZE_MARKER_SCHEMA_VERSION,
+ FREEZE_MARKER_UNREADABLE_REASON,
+ frozenMarkerPath,
+ readFreezeMarker,
+ resetFreezeMarkerCache,
+} from "../../../src/core/brain/freeze-marker.ts";
+import { readLogDay } from "../../../src/core/brain/log-jsonl.ts";
+import { resetVaultIdentityPins } from "../../../src/core/brain/vault-identity.ts";
+
+let vault: string;
+
+const AT = new Date("2026-09-10T08:00:00Z");
+
+beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "o2b-freeze-"));
+ mkdirSync(join(vault, "Brain"), { recursive: true });
+ resetFreezeMarkerCache();
+ resetVaultIdentityPins();
+});
+
+afterEach(() => {
+ rmSync(vault, { recursive: true, force: true });
+ resetFreezeMarkerCache();
+ resetVaultIdentityPins();
+});
+
+/** Every event of `kind` recorded on the day the test's clock names. */
+function events(kind: string): ReadonlyArray<Record<string, unknown>> {
+ const day = readLogDay(vault, "2026-09-10");
+ return day.entries.filter((e) => e.eventType === kind).map((e) => e.body);
+}
+
+describe("freezing", () => {
+ test("writes the marker and records exactly one freeze event", () => {
+ const out = freezeVault(vault, { agent: "@operator", reason: "migrating", now: AT });
+ expect(out.changed).toBe(true);
+ expect(out.marker.frozen_at).toBe("2026-09-10T08:00:00Z");
+ expect(out.marker.by).toBe("@operator");
+ expect(out.marker.reason).toBe("migrating");
+
+ const onDisk = JSON.parse(readFileSync(frozenMarkerPath(vault), "utf8")) as Record<
+ string,
+ unknown
+ >;
+ expect(onDisk["schema"]).toBe(FREEZE_MARKER_SCHEMA_VERSION);
+ expect(onDisk["reason"]).toBe("migrating");
+
+ const recorded = events("freeze");
+ expect(recorded).toHaveLength(1);
+ expect(recorded[0]!["reason"]).toBe("migrating");
+ expect(recorded[0]!["agent"]).toBe("@operator");
+ });
+
+ test("a reason is optional and its absence is recorded as such, never invented", () => {
+ const out = freezeVault(vault, { agent: "@operator", now: AT });
+ expect(out.marker.reason).toBe("");
+ expect(events("freeze")[0]!["reason"]).toBe("");
+ });
+
+ test("freezing an already frozen vault changes nothing and logs nothing", () => {
+ freezeVault(vault, { agent: "@operator", reason: "first", now: AT });
+ const again = freezeVault(vault, { agent: "@other", reason: "second", now: AT });
+ expect(again.changed).toBe(false);
+ // The first freeze stands: a second call must not overwrite who
+ // stopped the vault or why.
+ expect(again.marker.by).toBe("@operator");
+ expect(again.marker.reason).toBe("first");
+ expect(readFreezeMarker(vault)!.reason).toBe("first");
+ expect(events("freeze")).toHaveLength(1);
+ });
+});
+
+describe("unfreezing", () => {
+ test("removes the marker and records what it said before it went", () => {
+ freezeVault(vault, { agent: "@operator", reason: "migrating", now: AT });
+ const out = unfreezeVault(vault, { agent: "@operator", now: AT });
+ expect(out.changed).toBe(true);
+ expect(existsSync(frozenMarkerPath(vault))).toBe(false);
+ expect(readFreezeMarker(vault)).toBeNull();
+
+ const recorded = events("unfreeze");
+ expect(recorded).toHaveLength(1);
+ expect(recorded[0]!["frozen_at"]).toBe("2026-09-10T08:00:00Z");
+ expect(recorded[0]!["by"]).toBe("@operator");
+ expect(recorded[0]!["reason"]).toBe("migrating");
+ });
+
+ test("unfreezing an unfrozen vault changes nothing and logs nothing", () => {
+ const out = unfreezeVault(vault, { agent: "@operator", now: AT });
+ expect(out.changed).toBe(false);
+ expect(out.marker).toBeNull();
+ expect(events("unfreeze")).toHaveLength(0);
+ });
+
+ test("lifts a marker nobody could parse, and says so in the event", () => {
+ mkdirSync(join(vault, "Brain", ".state"), { recursive: true });
+ writeFileSync(frozenMarkerPath(vault), "{ not json", "utf8");
+ const out = unfreezeVault(vault, { agent: "@operator", now: AT });
+ expect(out.changed).toBe(true);
+ expect(existsSync(frozenMarkerPath(vault))).toBe(false);
+ expect(events("unfreeze")[0]!["reason"]).toBe(FREEZE_MARKER_UNREADABLE_REASON);
+ });
+});
diff --git a/tests/core/brain/idempotency-ledger.test.ts b/tests/core/brain/idempotency-ledger.test.ts
index 5cd64ff3..d0ed928a 100644
--- a/tests/core/brain/idempotency-ledger.test.ts
+++ b/tests/core/brain/idempotency-ledger.test.ts
@@ -10,10 +10,19 @@
*/
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
-import { existsSync, mkdtempSync, readFileSync, rmSync } from "node:fs";
+import {
+ chmodSync,
+ existsSync,
+ mkdirSync,
+ mkdtempSync,
+ readFileSync,
+ rmSync,
+ writeFileSync,
+} from "node:fs";
import { tmpdir } from "node:os";
-import { join } from "node:path";
+import { dirname, join } from "node:path";
+import { acquireLockSync } from "../../../src/core/brain/sync-lockfile.ts";
import {
computePayloadHash,
idempotencyLogPath,
@@ -119,3 +128,111 @@ describe("idempotency ledger", () => {
expect(c).not.toBe(a);
});
});
+
+/**
+ * Per-device shards (who-wrote-what, Task B / t_1814b9bf). A key
+ * remembered on one device must be honoured on another once Syncthing
+ * has delivered its shard - and neither device may write the other's
+ * file.
+ */
+describe("idempotency per-device shards", () => {
+ const savedEnv: Record<string, string | undefined> = {};
+ let configHome: string;
+
+ beforeEach(() => {
+ configHome = mkdtempSync(join(tmpdir(), "o2b-idempotency-cfg-"));
+ const configPath = join(configHome, "config.yaml");
+ savedEnv["OPEN_SECOND_BRAIN_CONFIG"] = process.env["OPEN_SECOND_BRAIN_CONFIG"];
+ savedEnv["O2B_DEVICE_ID"] = process.env["O2B_DEVICE_ID"];
+ process.env["OPEN_SECOND_BRAIN_CONFIG"] = configPath;
+ delete process.env["O2B_DEVICE_ID"];
+ writeFileSync(configPath, `vault: ${vault}\ndevice_id: "testdev1"\n`, "utf8");
+ });
+
+ afterEach(() => {
+ rmSync(configHome, { recursive: true, force: true });
+ for (const key of ["OPEN_SECOND_BRAIN_CONFIG", "O2B_DEVICE_ID"]) {
+ const value = savedEnv[key];
+ if (value === undefined) delete process.env[key];
+ else process.env[key] = value;
+ }
+ });
+
+ test("a device with an id writes its own shard and never the bare file", () => {
+ rememberKey(vault, { key: "k", contentHash: "hash-a", createdAt: "2026-05-14T10:00:00Z" });
+ expect(existsSync(idempotencyLogPath(vault, "2026-05", "testdev1"))).toBe(true);
+ expect(existsSync(idempotencyLogPath(vault, "2026-05", ""))).toBe(false);
+ });
+
+ test("lookupKey finds a key another device remembered", () => {
+ const path = idempotencyLogPath(vault, "2026-05", "devb");
+ mkdirSync(dirname(path), { recursive: true });
+ writeFileSync(
+ path,
+ `${JSON.stringify({ key: "remote", contentHash: "hash-r", createdAt: "2026-05-14T09:00:00Z" })}\n`,
+ "utf8",
+ );
+ expect(lookupKey(vault, "remote")?.contentHash).toBe("hash-r");
+ });
+
+ test("a key another device remembered dedupes this device's write", () => {
+ const path = idempotencyLogPath(vault, "2026-05", "devb");
+ mkdirSync(dirname(path), { recursive: true });
+ writeFileSync(
+ path,
+ `${JSON.stringify({ key: "shared", contentHash: "hash-a", createdAt: "2026-05-14T09:00:00Z" })}\n`,
+ "utf8",
+ );
+ const r = rememberKey(vault, {
+ key: "shared",
+ contentHash: "hash-a",
+ createdAt: "2026-05-14T10:00:00Z",
+ });
+ expect(r.status).toBe(REMEMBER_KEY_STATUS.duplicate_match);
+ expect(existsSync(idempotencyLogPath(vault, "2026-05", "testdev1"))).toBe(false);
+ });
+
+ test("a sync-conflict copy is not a shard and is never read", () => {
+ const dir = dirname(idempotencyLogPath(vault, "2026-05", ""));
+ mkdirSync(dir, { recursive: true });
+ writeFileSync(
+ join(dir, "2026-05.sync-conflict-20260514-120000-ABCDEFG.jsonl"),
+ `${JSON.stringify({ key: "conflict", contentHash: "hash-c", createdAt: "2026-05-14T09:00:00Z" })}\n`,
+ "utf8",
+ );
+ expect(lookupKey(vault, "conflict")).toBeNull();
+ });
+
+ /**
+ * A shard this process cannot read is not an empty shard. Answering
+ * "never seen" for one turns a retried write into a first write, which
+ * is the one outcome this ledger exists to prevent.
+ */
+ test.skipIf(process.getuid?.() === 0)("an unreadable shard is refused, not read as empty", () => {
+ const path = idempotencyLogPath(vault, "2026-05", "testdev1");
+ mkdirSync(dirname(path), { recursive: true });
+ writeFileSync(
+ path,
+ `${JSON.stringify({ key: "k", contentHash: "hash-a", createdAt: "2026-05-14T09:00:00Z" })}\n`,
+ "utf8",
+ );
+ chmodSync(path, 0o000);
+ try {
+ expect(() => lookupKey(vault, "k")).toThrow(/EACCES|EPERM/);
+ } finally {
+ chmodSync(path, 0o600);
+ }
+ });
+
+ test("the lock this device takes is on its own shard", () => {
+ const own = idempotencyLogPath(vault, "2026-05", "testdev1");
+ const handle = acquireLockSync(own);
+ try {
+ expect(() =>
+ rememberKey(vault, { key: "k", contentHash: "hash-a", createdAt: "2026-05-14T10:00:00Z" }),
+ ).toThrow("lock busy");
+ } finally {
+ handle.release();
+ }
+ });
+});
diff --git a/tests/core/brain/ledger-shards.test.ts b/tests/core/brain/ledger-shards.test.ts
new file mode 100644
index 00000000..c33361ec
--- /dev/null
+++ b/tests/core/brain/ledger-shards.test.ts
@@ -0,0 +1,264 @@
+/**
+ * The shard grammar every append-only ledger shares (who-wrote-what,
+ * Task B / t_1814b9bf).
+ *
+ * `Brain/log/` proved the layout: `<base>[.<shardId>].<ext>`, the bare
+ * name being the shard with the empty id, Syncthing conflict copies
+ * excluded from every listing and reported separately. This suite pins
+ * the extracted grammar itself, so the five ledgers that now share it
+ * cannot each drift their own copy of the answer.
+ */
+
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import {
+ isSyncConflictName,
+ LEDGER_SHARD_ID_RE,
+ listShardedFiles,
+ listSyncConflictFiles,
+ literalBase,
+ mergeShardedRows,
+ parseShardedName,
+ resolveAppendShardId,
+ shardedFileName,
+ type LedgerShardGrammar,
+} from "../../../src/core/brain/ledger-shards.ts";
+
+const MONTH_GRAMMAR: LedgerShardGrammar = Object.freeze({
+ base: "\\d{4}-\\d{2}",
+ extensions: Object.freeze(["jsonl"]),
+});
+
+const DAY_GRAMMAR: LedgerShardGrammar = Object.freeze({
+ base: "\\d{4}-\\d{2}-\\d{2}",
+ extensions: Object.freeze(["jsonl", "md"]),
+});
+
+let dir: string;
+
+beforeEach(() => {
+ dir = mkdtempSync(join(tmpdir(), "o2b-ledger-shards-"));
+});
+
+afterEach(() => {
+ rmSync(dir, { recursive: true, force: true });
+});
+
+function touch(name: string): void {
+ writeFileSync(join(dir, name), "", "utf8");
+}
+
+describe("parseShardedName", () => {
+ test("the bare name is the shard with the empty id", () => {
+ expect(parseShardedName("2026-08.jsonl", MONTH_GRAMMAR)).toEqual({
+ base: "2026-08",
+ shardId: "",
+ ext: "jsonl",
+ });
+ });
+
+ test("a device suffix is the shard id", () => {
+ expect(parseShardedName("2026-08.testdev1.jsonl", MONTH_GRAMMAR)).toEqual({
+ base: "2026-08",
+ shardId: "testdev1",
+ ext: "jsonl",
+ });
+ });
+
+ test("every declared extension is recognised", () => {
+ expect(parseShardedName("2026-06-01.dev.md", DAY_GRAMMAR)?.ext).toBe("md");
+ expect(parseShardedName("2026-06-01.dev.jsonl", DAY_GRAMMAR)?.ext).toBe("jsonl");
+ });
+
+ test("a name whose base does not match the grammar is not a shard", () => {
+ expect(parseShardedName("notes.jsonl", MONTH_GRAMMAR)).toBeNull();
+ expect(parseShardedName("2026-08.txt", MONTH_GRAMMAR)).toBeNull();
+ expect(parseShardedName("2026-08.jsonl.bak", MONTH_GRAMMAR)).toBeNull();
+ });
+
+ test("a shard id outside the slug shape is not a shard", () => {
+ expect(parseShardedName("2026-08.NOTASLUG.jsonl", MONTH_GRAMMAR)).toBeNull();
+ expect(parseShardedName(`2026-08.${"a".repeat(33)}.jsonl`, MONTH_GRAMMAR)).toBeNull();
+ });
+
+ test("a hand-renamed sync-conflict copy never passes as a shard", () => {
+ expect(
+ parseShardedName("2026-08.sync-conflict-20260801-120000.jsonl", MONTH_GRAMMAR),
+ ).toBeNull();
+ });
+
+ test("a literal base admits the dots inside it", () => {
+ const grammar: LedgerShardGrammar = {
+ base: literalBase("pref-a.b"),
+ extensions: ["jsonl"],
+ };
+ expect(parseShardedName("pref-a.b.jsonl", grammar)).toEqual({
+ base: "pref-a.b",
+ shardId: "",
+ ext: "jsonl",
+ });
+ expect(parseShardedName("pref-a.b.dev1.jsonl", grammar)?.shardId).toBe("dev1");
+ expect(parseShardedName("pref-ax.jsonl", grammar)).toBeNull();
+ });
+
+ test("round-trips whatever the name builder produced", () => {
+ for (const shardId of ["", "testdev1", "a-b-c"]) {
+ const name = shardedFileName("2026-08", shardId, "jsonl");
+ expect(parseShardedName(name, MONTH_GRAMMAR)).toEqual({
+ base: "2026-08",
+ shardId,
+ ext: "jsonl",
+ });
+ }
+ });
+
+ test("the builder refuses a shard id outside the slug shape", () => {
+ expect(() => shardedFileName("2026-08", "BAD/ID", "jsonl")).toThrow(/shard id/i);
+ });
+});
+
+describe("listShardedFiles", () => {
+ test("an absent directory lists nothing", () => {
+ expect(listShardedFiles(join(dir, "missing"), MONTH_GRAMMAR)).toEqual([]);
+ });
+
+ test("lists every shard sorted by name and excludes conflict copies", () => {
+ touch("2026-08.jsonl");
+ touch("2026-08.devb.jsonl");
+ touch("2026-08.deva.jsonl");
+ touch("2026-08.sync-conflict-20260801-120000-ABCDEFG.jsonl");
+ touch("README.md");
+ mkdirSync(join(dir, "2026-09.jsonl"));
+ const shards = listShardedFiles(dir, MONTH_GRAMMAR);
+ expect(shards.map((s) => s.name)).toEqual([
+ "2026-08.deva.jsonl",
+ "2026-08.devb.jsonl",
+ "2026-08.jsonl",
+ ]);
+ expect(shards.map((s) => s.shardId)).toEqual(["deva", "devb", ""]);
+ expect(shards[0]!.path).toBe(join(dir, "2026-08.deva.jsonl"));
+ });
+});
+
+describe("sync-conflict recognition", () => {
+ test("names the marker Syncthing writes and nothing else", () => {
+ expect(isSyncConflictName("2026-08.sync-conflict-20260801-120000-ABCDEFG.jsonl")).toBe(true);
+ expect(isSyncConflictName("2026-08.jsonl")).toBe(false);
+ expect(isSyncConflictName("sync-conflict.jsonl")).toBe(false);
+ });
+
+ test("lists conflict copies under a directory, sorted", () => {
+ touch("2026-08.jsonl");
+ touch("b.sync-conflict-20260801-120000-ABCDEFG.jsonl");
+ touch("a.sync-conflict-20260801-120000-ABCDEFG.jsonl");
+ expect(listSyncConflictFiles(dir)).toEqual([
+ join(dir, "a.sync-conflict-20260801-120000-ABCDEFG.jsonl"),
+ join(dir, "b.sync-conflict-20260801-120000-ABCDEFG.jsonl"),
+ ]);
+ });
+
+ test("an absent directory holds no conflict copies", () => {
+ expect(listSyncConflictFiles(join(dir, "missing"))).toEqual([]);
+ });
+});
+
+describe("mergeShardedRows", () => {
+ test("orders by sort key, then shard id, then line", () => {
+ const rows = [
+ { value: { at: "2026-08-02", tag: "b-late" }, shardId: "b", line: 1 },
+ { value: { at: "2026-08-01", tag: "b-1" }, shardId: "b", line: 0 },
+ { value: { at: "2026-08-01", tag: "a-1" }, shardId: "a", line: 0 },
+ { value: { at: "2026-08-01", tag: "a-2" }, shardId: "a", line: 1 },
+ { value: { at: "2026-08-01", tag: "bare" }, shardId: "", line: 0 },
+ ];
+ expect(mergeShardedRows(rows, (v) => v.at).map((v) => v.tag)).toEqual([
+ "bare",
+ "a-1",
+ "a-2",
+ "b-1",
+ "b-late",
+ ]);
+ });
+
+ test("a ledger's own last-resort key replaces line order when supplied", () => {
+ const rows = [
+ { value: { at: "2026-08-01", tag: "z" }, shardId: "a", line: 0 },
+ { value: { at: "2026-08-01", tag: "a" }, shardId: "a", line: 1 },
+ ];
+ expect(
+ mergeShardedRows(
+ rows,
+ (v) => v.at,
+ (v) => v.tag,
+ ).map((v) => v.tag),
+ ).toEqual(["a", "z"]);
+ expect(mergeShardedRows(rows, (v) => v.at).map((v) => v.tag)).toEqual(["z", "a"]);
+ });
+
+ test("the order does not depend on the order the shards arrived in", () => {
+ const rows = [
+ { value: { at: "2026-08-01", tag: "a" }, shardId: "a", line: 0 },
+ { value: { at: "2026-08-01", tag: "b" }, shardId: "b", line: 0 },
+ ];
+ const forward = mergeShardedRows(rows, (v) => v.at).map((v) => v.tag);
+ const reversed = mergeShardedRows(rows.toReversed(), (v) => v.at).map((v) => v.tag);
+ expect(forward).toEqual(reversed);
+ expect(forward).toEqual(["a", "b"]);
+ });
+});
+
+describe("resolveAppendShardId", () => {
+ const saved: Record<string, string | undefined> = {};
+
+ beforeEach(() => {
+ saved["O2B_DEVICE_ID"] = process.env["O2B_DEVICE_ID"];
+ saved["OPEN_SECOND_BRAIN_CONFIG"] = process.env["OPEN_SECOND_BRAIN_CONFIG"];
+ });
+
+ afterEach(() => {
+ for (const key of ["O2B_DEVICE_ID", "OPEN_SECOND_BRAIN_CONFIG"]) {
+ const value = saved[key];
+ if (value === undefined) delete process.env[key];
+ else process.env[key] = value;
+ }
+ });
+
+ test("returns the resolved device id", () => {
+ process.env["O2B_DEVICE_ID"] = "testdev1";
+ expect(resolveAppendShardId()).toBe("testdev1");
+ });
+
+ test("the empty opt-out selects the legacy un-sharded name", () => {
+ process.env["O2B_DEVICE_ID"] = "";
+ expect(resolveAppendShardId()).toBe("");
+ expect(shardedFileName("2026-08", resolveAppendShardId(), "jsonl")).toBe("2026-08.jsonl");
+ });
+
+ test("a config that cannot be read falls back to the legacy shard, never throws", () => {
+ delete process.env["O2B_DEVICE_ID"];
+ // A directory where the config file is expected: every read of it
+ // raises EISDIR, which is the ConfigReadError the appenders absorb.
+ const configHome = mkdtempSync(join(tmpdir(), "o2b-ledger-shards-cfg-"));
+ const configPath = join(configHome, "config.yaml");
+ mkdirSync(configPath, { recursive: true });
+ process.env["OPEN_SECOND_BRAIN_CONFIG"] = configPath;
+ try {
+ expect(resolveAppendShardId()).toBe("");
+ } finally {
+ rmSync(configHome, { recursive: true, force: true });
+ }
+ });
+});
+
+describe("the shard id shape", () => {
+ test("is the device-id slug the config resolver produces", () => {
+ expect(LEDGER_SHARD_ID_RE.test("testdev1")).toBe(true);
+ expect(LEDGER_SHARD_ID_RE.test("a-b-c")).toBe(true);
+ expect(LEDGER_SHARD_ID_RE.test("")).toBe(false);
+ expect(LEDGER_SHARD_ID_RE.test("Bad")).toBe(false);
+ expect(LEDGER_SHARD_ID_RE.test("a".repeat(33))).toBe(false);
+ });
+});
diff --git a/tests/core/brain/lineage-ledger-integrity.test.ts b/tests/core/brain/lineage-ledger-integrity.test.ts
index 11a3df83..2b22e001 100644
--- a/tests/core/brain/lineage-ledger-integrity.test.ts
+++ b/tests/core/brain/lineage-ledger-integrity.test.ts
@@ -23,6 +23,7 @@ import { afterEach, beforeEach, describe, expect, test } from "bun:test";
import {
appendFileSync,
chmodSync,
+ existsSync,
mkdirSync,
mkdtempSync,
readFileSync,
@@ -561,3 +562,127 @@ describe("recordLineageObservation β€” genuinely concurrent writers", () => {
expect(landed).toBe(appended);
}, 30_000);
});
+
+// ----- per-device shards ----------------------------------------------------
+
+/**
+ * Per-device shards (who-wrote-what, Task B / t_1814b9bf). The chain and
+ * its sequence are per FILE, so each device keeps its own chain; the
+ * reader merges every shard and the verifier reports per shard path.
+ */
+describe("session lineage per-device shards", () => {
+ const savedEnv: Record<string, string | undefined> = {};
+ let configHome: string;
+
+ beforeEach(() => {
+ configHome = mkdtempSync(join(tmpdir(), "o2b-ledger-cfg-"));
+ const configPath = join(configHome, "config.yaml");
+ savedEnv["OPEN_SECOND_BRAIN_CONFIG"] = process.env["OPEN_SECOND_BRAIN_CONFIG"];
+ savedEnv["O2B_DEVICE_ID"] = process.env["O2B_DEVICE_ID"];
+ process.env["OPEN_SECOND_BRAIN_CONFIG"] = configPath;
+ delete process.env["O2B_DEVICE_ID"];
+ writeFileSync(configPath, `vault: ${tmp}\ndevice_id: "testdev1"\n`, "utf8");
+ });
+
+ afterEach(() => {
+ rmSync(configHome, { recursive: true, force: true });
+ for (const key of ["OPEN_SECOND_BRAIN_CONFIG", "O2B_DEVICE_ID"]) {
+ const value = savedEnv[key];
+ if (value === undefined) delete process.env[key];
+ else process.env[key] = value;
+ }
+ });
+
+ test("a device with an id writes its own shard and never the bare file", () => {
+ record("s-1", T0);
+ expect(readFileSync(sessionLineageLedgerPath(tmp, "testdev1"), "utf8")).toContain("s-1");
+ expect(existsSync(sessionLineageLedgerPath(tmp, ""))).toBe(false);
+ });
+
+ test("each shard carries its own chain, starting at sequence 1", () => {
+ record("s-1", T0);
+ record("s-2", T0 + 1_000);
+ // A second device's shard, arrived through Syncthing: its own chain.
+ const other = sessionLineageLedgerPath(tmp, "devb");
+ writeFileSync(
+ other,
+ `${JSON.stringify({ sid: "s-3", at: new Date(T0 + 2_000).toISOString(), event: "Stop" })}\n`,
+ "utf8",
+ );
+ const mine = readFileSync(sessionLineageLedgerPath(tmp, "testdev1"), "utf8")
+ .split("\n")
+ .filter((l) => l.trim().length > 0)
+ .map((l) => JSON.parse(l) as RawLine);
+ expect(mine.map((l) => l.seq)).toEqual([1, 2]);
+ expect(mine[0]!.prev).toBeNull();
+ });
+
+ test("the reader merges every shard by observation time", () => {
+ record("mine", T0 + 1_000);
+ writeFileSync(
+ sessionLineageLedgerPath(tmp, "devb"),
+ `${JSON.stringify({ sid: "theirs", at: new Date(T0).toISOString(), event: "Stop" })}\n`,
+ "utf8",
+ );
+ const state = readLineageLedger(tmp);
+ expect([...state.keys()].toSorted()).toEqual(["mine", "theirs"]);
+ });
+
+ test("a sync-conflict copy is neither merged nor verified", () => {
+ record("mine", T0);
+ writeFileSync(
+ join(
+ dirname(sessionLineageLedgerPath(tmp, "")),
+ "session-lineage.sync-conflict-20260610-080000-ABCDEFG.jsonl",
+ ),
+ "{ not a ledger line\n",
+ "utf8",
+ );
+ expect([...readLineageLedger(tmp).keys()]).toEqual(["mine"]);
+ expect(verifyLineageLedger(tmp).ok).toBe(true);
+ });
+
+ test("verify reports every shard by its own path and names the broken one", () => {
+ record("mine", T0);
+ const other = sessionLineageLedgerPath(tmp, "devb");
+ writeFileSync(
+ other,
+ `${JSON.stringify({ sid: "theirs", at: new Date(T0).toISOString(), event: "Stop", seq: 1, prev: null, h: "0".repeat(64) })}\n`,
+ "utf8",
+ );
+ const report = verifyLineageLedger(tmp);
+ expect(report.shards.map((s) => s.shardId).toSorted()).toEqual(["devb", "testdev1"]);
+ expect(report.ok).toBe(false);
+ expect(report.notices.every((n) => n.path === other)).toBe(true);
+ expect(report.shards.find((s) => s.shardId === "testdev1")!.ok).toBe(true);
+ expect(report.shards.find((s) => s.shardId === "devb")!.ok).toBe(false);
+ });
+
+ test("a vault with no shard at all still reports absence, not a finding", () => {
+ const report = verifyLineageLedger(join(tmp, "elsewhere"));
+ expect(report.exists).toBe(false);
+ expect(report.shards).toHaveLength(0);
+ expect(report.ok).toBe(true);
+ });
+
+ test("the gap sidecar shards with the ledger and the report merges both", () => {
+ const handle = acquireLockSync(sessionLineageLedgerPath(tmp, "testdev1"));
+ try {
+ expect(record("dropped-here", T0).status).toBe(LINEAGE_RECORD_STATUS.dropped);
+ } finally {
+ handle.release();
+ }
+ expect(existsSync(sessionLineageGapsPath(tmp, "testdev1"))).toBe(true);
+ expect(existsSync(sessionLineageGapsPath(tmp, ""))).toBe(false);
+ writeFileSync(
+ sessionLineageGapsPath(tmp, "devb"),
+ `${JSON.stringify({ sid: "dropped-there", at: new Date(T0).toISOString(), rat: new Date(T0).toISOString(), event: "Stop", reason: "lock-busy" })}\n`,
+ "utf8",
+ );
+ const report = readLineageGapReport(tmp, { nowMs: T0 + 1_000 });
+ expect(report.records.map((r) => r.sessionId).toSorted()).toEqual([
+ "dropped-here",
+ "dropped-there",
+ ]);
+ });
+});
diff --git a/tests/core/brain/log-chain.test.ts b/tests/core/brain/log-chain.test.ts
new file mode 100644
index 00000000..d12ef517
--- /dev/null
+++ b/tests/core/brain/log-chain.test.ts
@@ -0,0 +1,275 @@
+/**
+ * Per-shard hash chain on the Brain log (who-wrote-what, Task E).
+ *
+ * Once the log is the attribution record for every write, a deleted or
+ * edited line has to be DETECTABLE. These tests hold the chain to that
+ * one property and to nothing more: they tamper with a shard the way a
+ * text editor would - rewrite a payload, remove a line, paste a line in
+ * by hand - and require the verifier to name the shard and the line.
+ *
+ * Report-only by construction, so every case also asserts that the READ
+ * path is untouched: `readLogDay` returns the same entries whether the
+ * chain is intact or broken, because a log that refused to be read
+ * because someone edited it would be a worse outcome than the edit.
+ */
+
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import {
+ LOG_CHAIN_BREAK_REASON,
+ logChainHash,
+ verifyLogChain,
+} from "../../../src/core/brain/log-chain.ts";
+import { appendLogEvent, LOG_CHAIN_FIELDS } from "../../../src/core/brain/log.ts";
+import { readLogDay } from "../../../src/core/brain/log-jsonl.ts";
+import { brainDirs, logJsonlPath, logShardJsonlPath } from "../../../src/core/brain/paths.ts";
+import { DEGRADATION_CODE } from "../../../src/core/integrity/degradation.ts";
+
+const DATE = "2026-06-01";
+
+let tmp: string;
+
+beforeEach(() => {
+ tmp = mkdtempSync(join(tmpdir(), "o2b-log-chain-"));
+ mkdirSync(join(tmp, "Brain"), { recursive: true });
+});
+
+afterEach(() => {
+ rmSync(tmp, { recursive: true, force: true });
+});
+
+/** Append `count` events to `shardId`, one second apart. */
+function appendMany(count: number, shardId = ""): void {
+ for (let i = 0; i < count; i++) {
+ appendLogEvent(
+ tmp,
+ {
+ timestamp: `${DATE}T10:00:0${i}Z`,
+ eventType: "note",
+ body: { text: `event ${i}`, agent: "@tester" },
+ },
+ { deviceId: shardId },
+ );
+ }
+}
+
+function readRows(path: string): Array<Record<string, unknown>> {
+ return readFileSync(path, "utf8")
+ .trim()
+ .split("\n")
+ .map((line) => JSON.parse(line) as Record<string, unknown>);
+}
+
+function writeRows(path: string, rows: ReadonlyArray<Record<string, unknown>>): void {
+ writeFileSync(path, rows.map((row) => JSON.stringify(row)).join("\n") + "\n", "utf8");
+}
+
+describe("chain links", () => {
+ test("three appends produce three lines whose prev links match", () => {
+ appendMany(3);
+ const rows = readRows(logJsonlPath(tmp, DATE));
+ expect(rows).toHaveLength(3);
+
+ expect(rows[0]![LOG_CHAIN_FIELDS.prev]).toBeNull();
+ expect(rows[1]![LOG_CHAIN_FIELDS.prev]).toBe(rows[0]![LOG_CHAIN_FIELDS.h]);
+ expect(rows[2]![LOG_CHAIN_FIELDS.prev]).toBe(rows[1]![LOG_CHAIN_FIELDS.h]);
+
+ for (const row of rows) {
+ const expected = logChainHash(
+ row[LOG_CHAIN_FIELDS.prev] as string | null,
+ row["ts"] as string,
+ row["kind"] as string,
+ row["payload"] as Record<string, string>,
+ );
+ expect(row[LOG_CHAIN_FIELDS.h]).toBe(expected);
+ }
+
+ const result = verifyLogChain(tmp);
+ expect(result.ok).toBe(true);
+ expect(result.notices).toHaveLength(0);
+ expect(result.shards).toHaveLength(1);
+ expect(result.shards[0]).toMatchObject({
+ date: DATE,
+ shardId: "",
+ chained: 3,
+ legacy: 0,
+ firstBreak: null,
+ });
+ });
+
+ test("the row keeps its ts/kind/payload projection beside the chain fields", () => {
+ appendMany(1);
+ const row = readRows(logJsonlPath(tmp, DATE))[0]!;
+ expect(Object.keys(row)).toEqual(["ts", "kind", "payload", "prev", "h"]);
+ });
+});
+
+describe("tamper detection", () => {
+ test("editing the middle line's payload reports line 2 hash-mismatch", () => {
+ appendMany(3);
+ const path = logJsonlPath(tmp, DATE);
+ const rows = readRows(path);
+ rows[1] = { ...rows[1]!, payload: { ...(rows[1]!["payload"] as object), text: "tampered" } };
+ writeRows(path, rows);
+
+ const result = verifyLogChain(tmp);
+ expect(result.ok).toBe(false);
+ expect(result.shards[0]!.firstBreak).toEqual({
+ line: 2,
+ reason: LOG_CHAIN_BREAK_REASON.hashMismatch,
+ });
+ expect(result.notices).toHaveLength(1);
+ expect(result.notices[0]!.code).toBe(DEGRADATION_CODE.logChainBroken);
+ expect(result.notices[0]!.path).toBe(path);
+ expect(result.notices[0]!.detail).toContain("line 2");
+
+ // Report-only: the read path still returns every line.
+ expect(readLogDay(tmp, DATE).entries).toHaveLength(3);
+ });
+
+ test("deleting the middle line reports the survivor's line as prev-mismatch", () => {
+ appendMany(3);
+ const path = logJsonlPath(tmp, DATE);
+ const rows = readRows(path);
+ writeRows(path, [rows[0]!, rows[2]!]);
+
+ const result = verifyLogChain(tmp);
+ expect(result.ok).toBe(false);
+ expect(result.shards[0]!.firstBreak).toEqual({
+ line: 2,
+ reason: LOG_CHAIN_BREAK_REASON.prevMismatch,
+ });
+ expect(result.shards[0]!.chained).toBe(2);
+ expect(readLogDay(tmp, DATE).entries).toHaveLength(2);
+ });
+
+ test("deleting the third of four lines reports line 3 prev-mismatch", () => {
+ appendMany(4);
+ const path = logJsonlPath(tmp, DATE);
+ const rows = readRows(path);
+ writeRows(path, [rows[0]!, rows[1]!, rows[3]!]);
+
+ const result = verifyLogChain(tmp);
+ expect(result.shards[0]!.firstBreak).toEqual({
+ line: 3,
+ reason: LOG_CHAIN_BREAK_REASON.prevMismatch,
+ });
+ });
+
+ test("cutting the head off a shard reports line 1 prev-mismatch", () => {
+ // The Brain log never compacts, so a shard begins at its genesis
+ // line and the first chained line must carry `prev: null`. One that
+ // names a predecessor means the head of the file was removed - the
+ // one tampering a compaction-exempt anchor would let through.
+ appendMany(3);
+ const path = logJsonlPath(tmp, DATE);
+ const rows = readRows(path);
+ writeRows(path, [rows[1]!, rows[2]!]);
+
+ const result = verifyLogChain(tmp);
+ expect(result.ok).toBe(false);
+ expect(result.shards[0]!.firstBreak).toEqual({
+ line: 1,
+ reason: LOG_CHAIN_BREAK_REASON.prevMismatch,
+ });
+ });
+
+ test("a line that is not JSON at all is malformed at its own line", () => {
+ appendMany(2);
+ const path = logJsonlPath(tmp, DATE);
+ writeFileSync(path, readFileSync(path, "utf8") + "{not json\n", "utf8");
+
+ const result = verifyLogChain(tmp);
+ expect(result.ok).toBe(false);
+ expect(result.shards[0]!.firstBreak).toEqual({
+ line: 3,
+ reason: LOG_CHAIN_BREAK_REASON.malformed,
+ });
+ });
+});
+
+describe("legacy lines", () => {
+ test("a legacy prefix followed by chained lines verifies clean", () => {
+ const dir = brainDirs(tmp).log;
+ mkdirSync(dir, { recursive: true });
+ const path = logJsonlPath(tmp, DATE);
+ writeRows(path, [
+ { ts: `${DATE}T09:00:00Z`, kind: "note", payload: { text: "before the chain" } },
+ { ts: `${DATE}T09:00:01Z`, kind: "note", payload: { text: "also before" } },
+ ]);
+ appendMany(2);
+
+ const result = verifyLogChain(tmp);
+ expect(result.ok).toBe(true);
+ expect(result.shards[0]).toMatchObject({ chained: 2, legacy: 2, firstBreak: null });
+
+ // The first chained line after a legacy prefix is a genesis anchor.
+ const rows = readRows(path);
+ expect(rows[2]![LOG_CHAIN_FIELDS.prev]).toBeNull();
+ expect(readLogDay(tmp, DATE).entries).toHaveLength(4);
+ });
+
+ test("an unchained line pasted in AFTER chained ones is malformed, not legacy", () => {
+ appendMany(2);
+ const path = logJsonlPath(tmp, DATE);
+ const rows = readRows(path);
+ writeRows(path, [
+ ...rows,
+ { ts: `${DATE}T11:00:00Z`, kind: "note", payload: { text: "pasted by hand" } },
+ ]);
+
+ const result = verifyLogChain(tmp);
+ expect(result.ok).toBe(false);
+ expect(result.shards[0]!.firstBreak).toEqual({
+ line: 3,
+ reason: LOG_CHAIN_BREAK_REASON.malformed,
+ });
+ expect(result.shards[0]!.legacy).toBe(1);
+ });
+});
+
+describe("shard isolation", () => {
+ test("two device shards each carry their own chain", () => {
+ appendMany(2, "devalpha");
+ appendMany(2, "devbeta");
+
+ const clean = verifyLogChain(tmp);
+ expect(clean.ok).toBe(true);
+ expect(clean.shards.map((s) => s.shardId)).toEqual(["devalpha", "devbeta"]);
+
+ const alpha = logShardJsonlPath(tmp, DATE, "devalpha");
+ const rows = readRows(alpha);
+ writeRows(alpha, [rows[1]!]);
+
+ const broken = verifyLogChain(tmp);
+ expect(broken.ok).toBe(false);
+ const byShard = new Map(broken.shards.map((s) => [s.shardId, s]));
+ expect(byShard.get("devalpha")!.firstBreak).not.toBeNull();
+ expect(byShard.get("devbeta")!.firstBreak).toBeNull();
+ expect(broken.notices).toHaveLength(1);
+ expect(broken.notices[0]!.path).toBe(alpha);
+ });
+
+ test("a Syncthing conflict copy is never verified", () => {
+ appendMany(2);
+ const dir = brainDirs(tmp).log;
+ // A conflict copy is the doctor's OTHER finding (`sync-conflict-log`);
+ // verifying it here would report one condition as two.
+ writeFileSync(join(dir, `${DATE}.sync-conflict-20260601-120000-ABCDEF.jsonl`), "{broken\n");
+
+ const result = verifyLogChain(tmp);
+ expect(result.ok).toBe(true);
+ expect(result.shards).toHaveLength(1);
+ expect(result.shards[0]!.path).toBe(logJsonlPath(tmp, DATE));
+ });
+
+ test("a vault with no log at all verifies clean with no shards", () => {
+ const result = verifyLogChain(tmp);
+ expect(result.ok).toBe(true);
+ expect(result.shards).toHaveLength(0);
+ expect(result.notices).toHaveLength(0);
+ });
+});
diff --git a/tests/core/brain/metrics.test.ts b/tests/core/brain/metrics.test.ts
index 39e5e74c..cd0bb047 100644
--- a/tests/core/brain/metrics.test.ts
+++ b/tests/core/brain/metrics.test.ts
@@ -8,7 +8,7 @@
*/
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
-import { mkdtempSync, readFileSync, rmSync, writeFileSync, mkdirSync } from "node:fs";
+import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync, mkdirSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
@@ -123,3 +123,68 @@ describe("listMetrics", () => {
expect(listMetrics(vault)).toHaveLength(1);
});
});
+
+/**
+ * Per-device shards (who-wrote-what, Task B / t_1814b9bf). Two machines
+ * running the same instrumented pass must not append to one surface file.
+ */
+describe("metrics per-device shards", () => {
+ const savedEnv: Record<string, string | undefined> = {};
+ let configHome: string;
+
+ function metricsPath(name: string): string {
+ return join(vault, "Brain", "metrics", name);
+ }
+
+ beforeEach(() => {
+ configHome = mkdtempSync(join(tmpdir(), "o2b-metrics-cfg-"));
+ const configPath = join(configHome, "config.yaml");
+ savedEnv["OPEN_SECOND_BRAIN_CONFIG"] = process.env["OPEN_SECOND_BRAIN_CONFIG"];
+ savedEnv["O2B_DEVICE_ID"] = process.env["O2B_DEVICE_ID"];
+ process.env["OPEN_SECOND_BRAIN_CONFIG"] = configPath;
+ delete process.env["O2B_DEVICE_ID"];
+ writeFileSync(configPath, `vault: ${vault}\ndevice_id: "testdev1"\n`, "utf8");
+ });
+
+ afterEach(() => {
+ rmSync(configHome, { recursive: true, force: true });
+ for (const key of ["OPEN_SECOND_BRAIN_CONFIG", "O2B_DEVICE_ID"]) {
+ const value = savedEnv[key];
+ if (value === undefined) delete process.env[key];
+ else process.env[key] = value;
+ }
+ });
+
+ function line(runAt: string, n: number): string {
+ return `${JSON.stringify({ schema: METRICS_SCHEMA_VERSION, surface: "index", run_at: runAt, payload: { n } })}\n`;
+ }
+
+ test("a device with an id writes its own shard and never the bare file", () => {
+ appendMetric(vault, { surface: "index", runAt: NOW, payload: { n: 1 } });
+ expect(existsSync(metricsPath("index.testdev1.jsonl"))).toBe(true);
+ expect(existsSync(metricsPath("index.jsonl"))).toBe(false);
+ });
+
+ test("the reader merges the bare file and every device shard, newest first", () => {
+ mkdirSync(join(vault, "Brain", "metrics"), { recursive: true });
+ writeFileSync(metricsPath("index.jsonl"), line("2026-06-05T10:00:00Z", 1));
+ writeFileSync(metricsPath("index.devb.jsonl"), line("2026-06-05T10:00:02Z", 3));
+ writeFileSync(metricsPath("index.testdev1.jsonl"), line("2026-06-05T10:00:01Z", 2));
+ expect(listMetrics(vault, { surface: "index" }).map((r) => r.payload["n"])).toEqual([3, 2, 1]);
+ });
+
+ test("a sync-conflict copy is not a shard and is never merged", () => {
+ mkdirSync(join(vault, "Brain", "metrics"), { recursive: true });
+ writeFileSync(metricsPath("index.testdev1.jsonl"), line("2026-06-05T10:00:01Z", 2));
+ writeFileSync(
+ metricsPath("index.sync-conflict-20260605-120000-ABCDEFG.jsonl"),
+ line("2026-06-05T10:00:00Z", 99),
+ );
+ expect(listMetrics(vault, { surface: "index" }).map((r) => r.payload["n"])).toEqual([2]);
+ });
+
+ test("an unfiltered listing discovers a surface that only has device shards", () => {
+ appendMetric(vault, { surface: "bridge_discovery", runAt: NOW, payload: { n: 7 } });
+ expect(listMetrics(vault).map((r) => r.surface)).toEqual(["bridge_discovery"]);
+ });
+});
diff --git a/tests/core/brain/notes/create-note-modes.test.ts b/tests/core/brain/notes/create-note-modes.test.ts
index 5ce373b8..7ec096af 100644
--- a/tests/core/brain/notes/create-note-modes.test.ts
+++ b/tests/core/brain/notes/create-note-modes.test.ts
@@ -40,6 +40,7 @@ import {
CreateNoteError,
type CreateNoteResult,
} from "../../../../src/core/brain/notes/create-note.ts";
+import { listNoteWrites } from "../../../../src/core/brain/notes/write-log.ts";
import { applyWriteBatch, WriteBatchError } from "../../../../src/core/brain/write-batch.ts";
/**
@@ -104,8 +105,31 @@ const GOLDEN_BASELINE_FRONTMATTER_KEYS: ReadonlyArray<string> = Object.freeze([
*/
const GOLDEN_BARE_NOTE = "---\norigin_channel: unset\n---\n\njust a body\n";
-/** Result field order the MCP surface and the SDK both read. */
-const GOLDEN_RESULT_KEYS: ReadonlyArray<string> = Object.freeze(["path", "outcome", "created"]);
+/**
+ * Result field order the MCP surface and the SDK both read.
+ *
+ * `write_id` joined it with the note-write record (who-wrote-what,
+ * Task A): every created note now names the log event that attributes
+ * it, or names why there is none. A skipped result deliberately does NOT
+ * grow the field - see {@link GOLDEN_SKIPPED_RESULT_KEYS}.
+ */
+const GOLDEN_RESULT_KEYS: ReadonlyArray<string> = Object.freeze([
+ "path",
+ "outcome",
+ "created",
+ "write_id",
+]);
+
+/**
+ * A skip authored no bytes, so it has no write to attribute. Pinned
+ * separately and WITHOUT `write_id`, because a null id here would read as
+ * a lost audit line for a call that never had one.
+ */
+const GOLDEN_SKIPPED_RESULT_KEYS: ReadonlyArray<string> = Object.freeze([
+ "path",
+ "outcome",
+ "created",
+]);
let vault: string;
beforeEach(() => {
@@ -214,6 +238,11 @@ describe("createNote - the new options are byte-identical when absent", () => {
// The result envelope is the one addition this unit makes, and it is
// pinned in full so a fourth field cannot arrive unannounced.
expect(Object.keys(res)).toEqual([...GOLDEN_RESULT_KEYS]);
+ // The id is the one the note-write event carries, not a placeholder.
+ // Narrowed on the discriminant rather than cast, because only the
+ // created arm has a write to name.
+ if (res.outcome !== "created") throw new Error("expected a created result");
+ expect(res.write_id).toMatch(/^nw_\d{14}_[0-9a-f]{16}$/);
});
});
@@ -228,9 +257,19 @@ describe('createNote - ifExists: "skip"', () => {
expect(res.outcome).toBe("skipped");
expect(res.created).toBe(false);
expect(res.path).toBe("Notes/Dup.md");
+ // No `write_id`: nothing was written, so there is nothing to
+ // attribute and no null to mistake for a lost audit line.
+ expect(Object.keys(res)).toEqual([...GOLDEN_SKIPPED_RESULT_KEYS]);
expect(readFileSync(join(vault, "Notes/Dup.md"), "utf8")).toContain("original");
});
+ test("a skip appends no note-write event: the log records writes, not calls", () => {
+ createNote(vault, { path: "Notes/Dup.md", content: "original" });
+ expect(listNoteWrites(vault).writes).toHaveLength(1);
+ createNote(vault, { path: "Notes/Dup.md", content: "replacement", ifExists: "skip" });
+ expect(listNoteWrites(vault).writes).toHaveLength(1);
+ });
+
test("a skip leaves the vault tree byte-for-byte unchanged, directories included", () => {
createNote(vault, { path: "A/B/C/Deep.md", content: "original" });
const before = snapshotTree(vault);
diff --git a/tests/core/brain/notes/revert.test.ts b/tests/core/brain/notes/revert.test.ts
new file mode 100644
index 00000000..62f898bc
--- /dev/null
+++ b/tests/core/brain/notes/revert.test.ts
@@ -0,0 +1,568 @@
+/**
+ * Per-agent / per-session revert (who-wrote-what, Task D / t_924129c5).
+ *
+ * The plan half is a report an operator READS: every target the selected
+ * writes touched resolves to `restore`, `delete` or a named refusal, and
+ * nothing is ever skipped silently. The apply half is sealed by the
+ * plan's digest, runs behind `withDestructiveSnapshot`, and records each
+ * restored or deleted target as a `note-write` of operation `revert` - so
+ * a revert is attributable and itself revertible, which the last test in
+ * this file proves by reverting the reverter.
+ */
+
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import {
+ chmodSync,
+ existsSync,
+ mkdirSync,
+ mkdtempSync,
+ readFileSync,
+ rmSync,
+ unlinkSync,
+ writeFileSync,
+} from "node:fs";
+import { tmpdir } from "node:os";
+import { dirname, join } from "node:path";
+
+import { bootstrapBrain } from "../../../../src/core/brain/init.ts";
+import { freezeVault } from "../../../../src/core/brain/freeze.ts";
+import {
+ VaultFrozenError,
+ resetFreezeMarkerCache,
+} from "../../../../src/core/brain/freeze-marker.ts";
+import { appendLogEvent } from "../../../../src/core/brain/log.ts";
+import { listNoteWrites } from "../../../../src/core/brain/notes/write-log.ts";
+import {
+ NOTE_WRITE_NO_PRIOR,
+ NOTE_WRITE_OP,
+ noteWriteId,
+ recordNoteWrite,
+ storeBeforeImage,
+ type NoteWriteOp,
+} from "../../../../src/core/brain/notes/write-record.ts";
+import {
+ NOTE_REVERT_ACTION,
+ NOTE_REVERT_ERROR,
+ NOTE_REVERT_REFUSAL,
+ NOTE_REVERT_REFUSALS,
+ NoteRevertError,
+ applyNoteRevert,
+ planNoteRevert,
+} from "../../../../src/core/brain/notes/revert.ts";
+import { writeImagePath } from "../../../../src/core/brain/paths.ts";
+import { listSnapshots } from "../../../../src/core/brain/snapshot.ts";
+import { atomicWriteFileSync } from "../../../../src/core/fs-atomic.ts";
+import { sha256Hex } from "../../../../src/core/integrity/digest.ts";
+import { BRAIN_LOG_EVENT_KIND, BRAIN_SNAPSHOT_REASON } from "../../../../src/core/brain/types.ts";
+
+const SEED = "agent-seed";
+const A = "agent-a";
+const B = "agent-b";
+const REVERTER = "agent-reverter";
+const TARGET = "notes/A.md";
+
+/** One hour apart, so no two seeded writes share a second. */
+const at = (hour: number): string => `2026-03-04T${String(hour).padStart(2, "0")}:00:00Z`;
+
+let vault: string;
+let configHome: string;
+let configPath: string;
+
+beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "o2b-note-revert-vault-"));
+ configHome = mkdtempSync(join(tmpdir(), "o2b-note-revert-cfg-"));
+ configPath = join(configHome, "config.yaml");
+ atomicWriteFileSync(configPath, `vault: ${vault}\nagent_name: ${REVERTER}\n`);
+ bootstrapBrain(vault, { configPath });
+ resetFreezeMarkerCache();
+});
+
+afterEach(() => {
+ resetFreezeMarkerCache();
+ rmSync(vault, { recursive: true, force: true });
+ rmSync(configHome, { recursive: true, force: true });
+});
+
+/**
+ * Do to a note exactly what the write seams do - keep the bytes it
+ * replaces, write, record - so the plan reads a history it could have
+ * read off a real vault rather than one this file invented.
+ */
+function seedWrite(opts: {
+ readonly target?: string;
+ readonly bytes: string;
+ readonly agent: string;
+ readonly at: string;
+ readonly op?: NoteWriteOp;
+ /**
+ * Device shard the event lands on. Absent means whatever the appender
+ * resolves, which is the single-device case every other test wants;
+ * naming it is how the same-second tests put two writes on the same
+ * shard or on two, which is the whole difference between a known order
+ * and a guess.
+ */
+ readonly device?: string;
+}): string {
+ const target = opts.target ?? TARGET;
+ const abs = join(vault, target);
+ const before = existsSync(abs) ? readFileSync(abs, "utf8") : null;
+ mkdirSync(dirname(abs), { recursive: true });
+ if (before !== null) storeBeforeImage(vault, before);
+ atomicWriteFileSync(abs, opts.bytes);
+ const op = opts.op ?? (before === null ? NOTE_WRITE_OP.create : NOTE_WRITE_OP.update);
+ if (opts.device === undefined) {
+ const receipt = recordNoteWrite(vault, {
+ op,
+ target,
+ before: before === null ? null : { bytes: before },
+ after: { bytes: opts.bytes },
+ timestamp: opts.at,
+ agent: opts.agent,
+ });
+ expect(receipt.write_id).not.toBeNull();
+ return receipt.write_id!;
+ }
+ // `recordNoteWrite` does not thread a shard - the appender resolves it
+ // from config - so a test that needs two shards in one vault builds the
+ // same event body and hands the appender the device directly.
+ const body = {
+ timestamp: opts.at,
+ op,
+ target,
+ hash_before: before === null ? NOTE_WRITE_NO_PRIOR : sha256Hex(before),
+ hash_after: sha256Hex(opts.bytes),
+ agent: opts.agent,
+ } as const;
+ const writeId = noteWriteId(body);
+ appendLogEvent(
+ vault,
+ {
+ timestamp: opts.at,
+ eventType: BRAIN_LOG_EVENT_KIND.noteWrite,
+ agent: opts.agent,
+ body: {
+ write_id: writeId,
+ op: body.op,
+ target: body.target,
+ hash_before: body.hash_before,
+ hash_after: body.hash_after,
+ bytes_before: String(before === null ? 0 : Buffer.byteLength(before, "utf8")),
+ bytes_after: String(Buffer.byteLength(opts.bytes, "utf8")),
+ agent: opts.agent,
+ },
+ },
+ { deviceId: opts.device },
+ );
+ return writeId;
+}
+
+/** `seed` created it, then A edited it twice and nobody else touched it. */
+function seedTwoUpdatesByA(): void {
+ seedWrite({ bytes: "v0", agent: SEED, at: at(1) });
+ seedWrite({ bytes: "v1", agent: A, at: at(2) });
+ seedWrite({ bytes: "v2", agent: A, at: at(3) });
+}
+
+const noteBytes = (target = TARGET): string => readFileSync(join(vault, target), "utf8");
+
+describe("planNoteRevert selector", () => {
+ test("an unbounded selector is refused by name before any log is read", () => {
+ let thrown: unknown;
+ try {
+ planNoteRevert(vault, {});
+ } catch (err) {
+ thrown = err;
+ }
+ expect(thrown).toBeInstanceOf(NoteRevertError);
+ expect((thrown as NoteRevertError).code).toBe(NOTE_REVERT_ERROR.unboundedSelector);
+ });
+
+ test("a window with no agent, device or path is still unbounded", () => {
+ expect(() => planNoteRevert(vault, { since: "2026-03-04", until: "2026-03-05" })).toThrow(
+ NoteRevertError,
+ );
+ });
+
+ test("a path alone bounds it", () => {
+ seedTwoUpdatesByA();
+ expect(planNoteRevert(vault, { path: TARGET }).entries).toHaveLength(1);
+ });
+});
+
+describe("planNoteRevert restore", () => {
+ test("two updates by one agent plan one restore to the pre-agent bytes", () => {
+ seedTwoUpdatesByA();
+ const plan = planNoteRevert(vault, { agent: A });
+
+ expect(plan.entries).toHaveLength(1);
+ const entry = plan.entries[0]!;
+ expect(entry.target).toBe(TARGET);
+ expect(entry.action).toBe(NOTE_REVERT_ACTION.restore);
+ expect(entry.reason).toBeUndefined();
+ expect(entry.writes).toHaveLength(2);
+ expect(entry.hash_now).toBe(sha256Hex("v2"));
+ expect(entry.hash_to).toBe(sha256Hex("v0"));
+ expect(plan.digest).toMatch(/^[0-9a-f]{64}$/);
+ });
+
+ test("the write ids are oldest first, so an operator reads the order they landed", () => {
+ seedWrite({ bytes: "v0", agent: SEED, at: at(1) });
+ const first = seedWrite({ bytes: "v1", agent: A, at: at(2) });
+ const second = seedWrite({ bytes: "v2", agent: A, at: at(3) });
+ expect(planNoteRevert(vault, { agent: A }).entries[0]!.writes).toEqual([first, second]);
+ });
+
+ test("the digest covers the selector and the entries, and not the planning instant", () => {
+ seedTwoUpdatesByA();
+ const first = planNoteRevert(vault, { agent: A }, { now: new Date("2026-03-05T00:00:00Z") });
+ const second = planNoteRevert(vault, { agent: A }, { now: new Date("2026-03-06T00:00:00Z") });
+ expect(second.digest).toBe(first.digest);
+ expect(second.planned_at).not.toBe(first.planned_at);
+ // A different selector over the same vault is a different plan.
+ expect(planNoteRevert(vault, { path: TARGET }).digest).not.toBe(first.digest);
+ });
+});
+
+describe("planNoteRevert refusals", () => {
+ test("an unselected write inside the window refuses interleaved", () => {
+ seedWrite({ bytes: "v0", agent: SEED, at: at(1) });
+ seedWrite({ bytes: "v1", agent: A, at: at(2) });
+ seedWrite({ bytes: "vB", agent: B, at: at(3) });
+ seedWrite({ bytes: "v3", agent: A, at: at(4) });
+
+ const entry = planNoteRevert(vault, { agent: A }).entries[0]!;
+ expect(entry.action).toBe(NOTE_REVERT_ACTION.refuse);
+ expect(entry.reason).toBe(NOTE_REVERT_REFUSAL.interleaved);
+ });
+
+ test("a same-second write on the SAME shard is ordered by line, not refused", () => {
+ // One shard, one second, two writes. Line order inside a shard IS
+ // append order and `readLogDay` merges on (timestamp, shard id,
+ // line), so B's create is PROVABLY before A's update and there is
+ // nothing ambiguous to refuse over.
+ const target = "notes/two.md";
+ const ts = at(2);
+ seedWrite({ target, bytes: "b0", agent: B, at: ts, device: "deva" });
+ seedWrite({ target, bytes: "a1", agent: A, at: ts, device: "deva" });
+
+ const entry = planNoteRevert(vault, { agent: A }).entries[0]!;
+ expect(entry.action).toBe(NOTE_REVERT_ACTION.restore);
+ expect(entry.hash_to).toBe(sha256Hex("b0"));
+ });
+
+ test("a same-second write on a DIFFERENT shard is still interleaved", () => {
+ // Two devices, one second. Nothing orders them: the merge falls back
+ // to the shard id, which is a name, not a clock. Refuse on doubt.
+ const target = "notes/two.md";
+ const ts = at(2);
+ seedWrite({ target, bytes: "b0", agent: B, at: ts, device: "devb" });
+ seedWrite({ target, bytes: "a1", agent: A, at: ts, device: "deva" });
+
+ const entry = planNoteRevert(vault, { agent: A }).entries[0]!;
+ expect(entry.action).toBe(NOTE_REVERT_ACTION.refuse);
+ expect(entry.reason).toBe(NOTE_REVERT_REFUSAL.interleaved);
+ });
+
+ test("bytes changed after the newest selected write refuse drift", () => {
+ seedTwoUpdatesByA();
+ writeFileSync(join(vault, TARGET), "somebody else, unrecorded");
+
+ const entry = planNoteRevert(vault, { agent: A }).entries[0]!;
+ expect(entry.action).toBe(NOTE_REVERT_ACTION.refuse);
+ expect(entry.reason).toBe(NOTE_REVERT_REFUSAL.drift);
+ expect(entry.hash_now).toBe(sha256Hex("somebody else, unrecorded"));
+ });
+
+ test("a target that should exist and does not refuses drift", () => {
+ seedTwoUpdatesByA();
+ unlinkSync(join(vault, TARGET));
+ expect(planNoteRevert(vault, { agent: A }).entries[0]!.reason).toBe(NOTE_REVERT_REFUSAL.drift);
+ });
+
+ test("a target whose current bytes cannot be read refuses unrecorded", () => {
+ seedTwoUpdatesByA();
+ // A directory where the note was: the bytes are neither present nor
+ // absent, and "I could not tell" must never resolve to "revert it".
+ unlinkSync(join(vault, TARGET));
+ mkdirSync(join(vault, TARGET));
+
+ const entry = planNoteRevert(vault, { agent: A }).entries[0]!;
+ expect(entry.action).toBe(NOTE_REVERT_ACTION.refuse);
+ expect(entry.reason).toBe(NOTE_REVERT_REFUSAL.unrecorded);
+ });
+
+ test("a missing before-image refuses image-missing", () => {
+ seedTwoUpdatesByA();
+ unlinkSync(writeImagePath(vault, sha256Hex("v0")));
+
+ const entry = planNoteRevert(vault, { agent: A }).entries[0]!;
+ expect(entry.action).toBe(NOTE_REVERT_ACTION.refuse);
+ expect(entry.reason).toBe(NOTE_REVERT_REFUSAL.imageMissing);
+ expect(entry.hash_to).toBe(sha256Hex("v0"));
+ });
+
+ test("a target already at the state the plan would produce refuses already-reverted", () => {
+ seedWrite({ bytes: "v0", agent: SEED, at: at(1) });
+ seedWrite({ bytes: "v1", agent: A, at: at(2) });
+ // A put it back itself: the newest selected write leaves the bytes
+ // the oldest one replaced, so there is nothing left to take back.
+ seedWrite({ bytes: "v0", agent: A, at: at(3) });
+
+ const entry = planNoteRevert(vault, { agent: A }).entries[0]!;
+ expect(entry.action).toBe(NOTE_REVERT_ACTION.refuse);
+ expect(entry.reason).toBe(NOTE_REVERT_REFUSAL.alreadyReverted);
+ });
+
+ test("every touched target is reported, refused ones beside applicable ones", () => {
+ seedTwoUpdatesByA();
+ seedWrite({ target: "notes/B.md", bytes: "b1", agent: A, at: at(4) });
+ writeFileSync(join(vault, "notes/B.md"), "drifted");
+
+ const plan = planNoteRevert(vault, { agent: A });
+ expect(plan.entries.map((e) => `${e.target}:${e.action}`)).toEqual([
+ `${TARGET}:${NOTE_REVERT_ACTION.restore}`,
+ `notes/B.md:${NOTE_REVERT_ACTION.refuse}`,
+ ]);
+ });
+});
+
+describe("planNoteRevert delete", () => {
+ test("a note the selected writes created plans a delete", () => {
+ seedWrite({ target: "notes/New.md", bytes: "brand new", agent: A, at: at(2) });
+
+ const entry = planNoteRevert(vault, { agent: A }).entries[0]!;
+ expect(entry.action).toBe(NOTE_REVERT_ACTION.delete);
+ expect(entry.hash_to).toBe(NOTE_WRITE_NO_PRIOR);
+ expect(entry.hash_now).toBe(sha256Hex("brand new"));
+ });
+
+ test("a note created by somebody else is never deleted", () => {
+ seedWrite({ target: "notes/New.md", bytes: "v0", agent: SEED, at: at(1) });
+ seedWrite({ target: "notes/New.md", bytes: "v1", agent: A, at: at(2) });
+ expect(planNoteRevert(vault, { agent: A }).entries[0]!.action).toBe(NOTE_REVERT_ACTION.restore);
+ });
+});
+
+describe("applyNoteRevert", () => {
+ test("restores the pre-agent bytes behind a note-revert snapshot and records the write", () => {
+ seedTwoUpdatesByA();
+ const plan = planNoteRevert(vault, { agent: A });
+
+ const result = applyNoteRevert(vault, { agent: A }, plan.digest, {
+ now: new Date(at(9)),
+ agent: REVERTER,
+ configPath,
+ });
+
+ expect(noteBytes()).toBe("v0");
+ expect(result.applied).toHaveLength(1);
+ expect(result.refused).toHaveLength(0);
+ expect(result.snapshot.run_id).toStartWith(`${BRAIN_SNAPSHOT_REASON.noteRevert}-`);
+ expect(existsSync(result.snapshot.path)).toBe(true);
+ expect(listSnapshots(vault).snapshots.some((s) => s.run_id === result.snapshot.run_id)).toBe(
+ true,
+ );
+
+ const reverts = listNoteWrites(vault, { op: NOTE_WRITE_OP.revert }).writes;
+ expect(reverts).toHaveLength(1);
+ expect(reverts[0]!.target).toBe(TARGET);
+ expect(reverts[0]!.agent).toBe(REVERTER);
+ expect(reverts[0]!.hash_before).toBe(sha256Hex("v2"));
+ expect(reverts[0]!.hash_after).toBe(sha256Hex("v0"));
+ expect(result.recorded).toEqual([{ target: TARGET, write_id: reverts[0]!.write_id }]);
+ });
+
+ test("a delete unlinks the note and records an absent after side", () => {
+ seedWrite({ target: "notes/New.md", bytes: "brand new", agent: A, at: at(2) });
+ const plan = planNoteRevert(vault, { agent: A });
+
+ applyNoteRevert(vault, { agent: A }, plan.digest, {
+ now: new Date(at(9)),
+ agent: REVERTER,
+ configPath,
+ });
+
+ expect(existsSync(join(vault, "notes/New.md"))).toBe(false);
+ const revert = listNoteWrites(vault, { op: NOTE_WRITE_OP.revert }).writes[0]!;
+ expect(revert.hash_after).toBe(NOTE_WRITE_NO_PRIOR);
+ expect(revert.bytes_after).toBe(0);
+ // The bytes it removed are kept, so the delete is itself revertible.
+ expect(existsSync(writeImagePath(vault, sha256Hex("brand new")))).toBe(true);
+ });
+
+ test("a stale digest is refused before any byte moves", () => {
+ seedTwoUpdatesByA();
+ const stale = planNoteRevert(vault, { agent: A }).digest;
+ seedWrite({ bytes: "v3", agent: A, at: at(4) });
+
+ let thrown: unknown;
+ try {
+ applyNoteRevert(vault, { agent: A }, stale, { now: new Date(at(9)), configPath });
+ } catch (err) {
+ thrown = err;
+ }
+ expect(thrown).toBeInstanceOf(NoteRevertError);
+ expect((thrown as NoteRevertError).code).toBe(NOTE_REVERT_ERROR.digestMismatch);
+ expect(noteBytes()).toBe("v3");
+ expect(listSnapshots(vault).snapshots).toHaveLength(0);
+ expect(listNoteWrites(vault, { op: NOTE_WRITE_OP.revert }).writes).toHaveLength(0);
+ });
+
+ test("a plan whose every entry is refused cannot be applied", () => {
+ seedTwoUpdatesByA();
+ writeFileSync(join(vault, TARGET), "drifted");
+ const plan = planNoteRevert(vault, { agent: A });
+
+ let thrown: unknown;
+ try {
+ applyNoteRevert(vault, { agent: A }, plan.digest, { now: new Date(at(9)), configPath });
+ } catch (err) {
+ thrown = err;
+ }
+ expect(thrown).toBeInstanceOf(NoteRevertError);
+ expect((thrown as NoteRevertError).code).toBe(NOTE_REVERT_ERROR.nothingToApply);
+ expect(noteBytes()).toBe("drifted");
+ expect(listSnapshots(vault).snapshots).toHaveLength(0);
+ });
+
+ test("an image that no longer matches its digest refuses that target instead of writing it", () => {
+ seedTwoUpdatesByA();
+ const plan = planNoteRevert(vault, { agent: A });
+ // The plan saw the image; it is corrupt by the time the apply reads
+ // it. Restoring bytes that are not the ones recorded would be the
+ // one failure a revert must never have.
+ writeFileSync(writeImagePath(vault, sha256Hex("v0")), "not v0 any more");
+
+ const result = applyNoteRevert(vault, { agent: A }, plan.digest, {
+ now: new Date(at(9)),
+ configPath,
+ });
+ expect(result.applied).toHaveLength(0);
+ expect(result.refused[0]!.reason).toBe(NOTE_REVERT_REFUSAL.imageMissing);
+ expect(noteBytes()).toBe("v2");
+ });
+
+ test("a frozen vault refuses the revert by name, before the snapshot", () => {
+ seedTwoUpdatesByA();
+ const plan = planNoteRevert(vault, { agent: A });
+ freezeVault(vault, { agent: "operator", reason: "audit", now: new Date(at(8)) });
+ resetFreezeMarkerCache();
+
+ expect(() =>
+ applyNoteRevert(vault, { agent: A }, plan.digest, { now: new Date(at(9)), configPath }),
+ ).toThrow(VaultFrozenError);
+ expect(noteBytes()).toBe("v2");
+ expect(listSnapshots(vault).snapshots).toHaveLength(0);
+ });
+
+ test("a revert is itself revertible: reverting the reverter puts the bytes back", () => {
+ seedTwoUpdatesByA();
+ const first = planNoteRevert(vault, { agent: A });
+ applyNoteRevert(vault, { agent: A }, first.digest, {
+ now: new Date(at(9)),
+ agent: REVERTER,
+ configPath,
+ });
+ expect(noteBytes()).toBe("v0");
+
+ const second = planNoteRevert(vault, { agent: REVERTER });
+ expect(second.entries[0]!.action).toBe(NOTE_REVERT_ACTION.restore);
+ expect(second.entries[0]!.hash_to).toBe(sha256Hex("v2"));
+
+ applyNoteRevert(vault, { agent: REVERTER }, second.digest, {
+ now: new Date(at(10)),
+ agent: "agent-second-reverter",
+ configPath,
+ });
+ expect(noteBytes()).toBe("v2");
+ });
+});
+
+/**
+ * The log is a file, and a file can hold a target this vault would never
+ * have written - a corrupt line, a hand-appended one, a crafted one. The
+ * plan is a REPORT: one unusable target must cost that target and not
+ * every other target in the same plan, and the apply must not lose an
+ * entry between `applied` and `refused` because a later one threw.
+ */
+describe("a target the plan cannot resolve", () => {
+ /** Append a `note-write` event naming `target`, bypassing the seams. */
+ function seedRawWrite(target: string, agent: string, timestamp: string): void {
+ appendLogEvent(
+ vault,
+ {
+ timestamp,
+ eventType: BRAIN_LOG_EVENT_KIND.noteWrite,
+ agent,
+ body: {
+ write_id: `nw_${timestamp.replace(/[^0-9]/g, "")}_0123456789abcdef`,
+ op: NOTE_WRITE_OP.update,
+ target,
+ hash_before: sha256Hex("old"),
+ hash_after: sha256Hex("new"),
+ bytes_before: "3",
+ bytes_after: "3",
+ agent,
+ },
+ },
+ { deviceId: "" },
+ );
+ }
+
+ test("a target that escapes the vault is refused by name, not thrown", () => {
+ seedWrite({ bytes: "v0", agent: A, at: at(1) });
+ seedRawWrite("../../escape.md", A, at(2));
+
+ const plan = planNoteRevert(vault, { agent: A });
+ const escaped = plan.entries.find((e) => e.target === "../../escape.md");
+ expect(escaped?.action).toBe(NOTE_REVERT_ACTION.refuse);
+ expect(escaped?.reason).toBe(NOTE_REVERT_REFUSAL.targetInvalid);
+ // The other target in the same plan is still resolved.
+ expect(plan.entries.find((e) => e.target === TARGET)).toBeDefined();
+ });
+
+ test("the refusal is a member of the closed vocabulary", () => {
+ expect(NOTE_REVERT_REFUSAL.targetInvalid).toBe("target-invalid");
+ expect(NOTE_REVERT_REFUSALS).toContain(NOTE_REVERT_REFUSAL.targetInvalid);
+ });
+
+ /**
+ * The plan proved both targets restorable; the second one then fails
+ * on a condition no plan can see - the directory it has to write into
+ * is not writable. Without a per-entry boundary the throw escapes the
+ * gate and the second target appears in neither `applied` nor
+ * `refused`, which reads as "it was not in the plan".
+ */
+ test.skipIf(process.getuid?.() === 0)(
+ "an entry that throws mid-apply is named, and the others still run",
+ () => {
+ seedWrite({ target: "notes/one/A.md", bytes: "v0", agent: SEED, at: at(1) });
+ seedWrite({ target: "notes/one/A.md", bytes: "v1", agent: A, at: at(2) });
+ seedWrite({ target: "notes/two/B.md", bytes: "w0", agent: SEED, at: at(3) });
+ seedWrite({ target: "notes/two/B.md", bytes: "w1", agent: A, at: at(4) });
+
+ const plan = planNoteRevert(vault, { agent: A });
+ expect(plan.entries.map((e) => e.target)).toEqual(["notes/one/A.md", "notes/two/B.md"]);
+ expect(plan.entries.every((e) => e.action === NOTE_REVERT_ACTION.restore)).toBe(true);
+
+ // Readable, so the re-plan still sees the same bytes and the digest
+ // still matches; not writable, so the restore itself throws.
+ const twoDir = join(vault, "notes/two");
+ chmodSync(twoDir, 0o500);
+ let result;
+ try {
+ result = applyNoteRevert(vault, { agent: A }, plan.digest);
+ } finally {
+ chmodSync(twoDir, 0o700);
+ }
+
+ expect(result.applied.map((e) => e.target)).toEqual(["notes/one/A.md"]);
+ expect(readFileSync(join(vault, "notes/one/A.md"), "utf8")).toBe("v0");
+ expect(result.failed).toHaveLength(1);
+ expect(result.failed[0]!.target).toBe("notes/two/B.md");
+ expect(result.failed[0]!.reason).toMatch(/EACCES|EPERM|permission/i);
+ // Untouched: the failure cost this target and nothing else.
+ expect(readFileSync(join(vault, "notes/two/B.md"), "utf8")).toBe("w1");
+ },
+ );
+});
diff --git a/tests/core/brain/notes/write-log.test.ts b/tests/core/brain/notes/write-log.test.ts
new file mode 100644
index 00000000..84c9a871
--- /dev/null
+++ b/tests/core/brain/notes/write-log.test.ts
@@ -0,0 +1,171 @@
+/**
+ * The note-write reader (who-wrote-what, Task A / t_662f4e82).
+ *
+ * The filters, the newest-first order, and the one fact that cannot come
+ * from the payload: the device, which the reader takes off the log shard
+ * the entry was read from.
+ */
+
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { mkdtempSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { appendLogEvent } from "../../../../src/core/brain/log.ts";
+import { listNoteWrites } from "../../../../src/core/brain/notes/write-log.ts";
+import { NOTE_WRITE_OP } from "../../../../src/core/brain/notes/write-record.ts";
+import { BRAIN_LOG_EVENT_KIND } from "../../../../src/core/brain/types.ts";
+
+let vault: string;
+beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "o2b-write-log-"));
+});
+afterEach(() => rmSync(vault, { recursive: true, force: true }));
+
+interface SeedInput {
+ readonly timestamp: string;
+ readonly agent: string;
+ readonly target: string;
+ readonly op?: string;
+ readonly deviceId?: string;
+ readonly writeId?: string;
+}
+
+function seed(input: SeedInput): void {
+ appendLogEvent(
+ vault,
+ {
+ timestamp: input.timestamp,
+ eventType: BRAIN_LOG_EVENT_KIND.noteWrite,
+ agent: input.agent,
+ body: {
+ write_id: input.writeId ?? `nw_${input.timestamp.replace(/\D/g, "")}_${input.target}`,
+ op: input.op ?? NOTE_WRITE_OP.update,
+ target: input.target,
+ hash_before: "a".repeat(64),
+ hash_after: "b".repeat(64),
+ bytes_before: "10",
+ bytes_after: "20",
+ agent: input.agent,
+ },
+ },
+ { deviceId: input.deviceId ?? "" },
+ );
+}
+
+describe("listNoteWrites", () => {
+ test("returns every recorded write newest first", () => {
+ seed({ timestamp: "2026-03-04T01:00:00Z", agent: "a", target: "One.md" });
+ seed({ timestamp: "2026-03-05T02:00:00Z", agent: "b", target: "Two.md" });
+ seed({ timestamp: "2026-03-04T03:00:00Z", agent: "a", target: "Three.md" });
+
+ const { writes, warnings } = listNoteWrites(vault);
+ expect(warnings).toEqual([]);
+ expect(writes.map((w) => w.target)).toEqual(["Two.md", "Three.md", "One.md"]);
+ });
+
+ test("projects the recorded fields, parsing the byte counts back to numbers", () => {
+ seed({
+ timestamp: "2026-03-04T01:00:00Z",
+ agent: "agent-a",
+ target: "Notes/One.md",
+ op: NOTE_WRITE_OP.append,
+ writeId: "nw_20260304010000_0123456789abcdef",
+ });
+ const record = listNoteWrites(vault).writes[0]!;
+ expect(record.write_id).toBe("nw_20260304010000_0123456789abcdef");
+ expect(record.op).toBe(NOTE_WRITE_OP.append);
+ expect(record.target).toBe("Notes/One.md");
+ expect(record.agent).toBe("agent-a");
+ expect(record.bytes_before).toBe(10);
+ expect(record.bytes_after).toBe(20);
+ expect(record.hash_before).toBe("a".repeat(64));
+ // The appender stamps the channel; the reader carries it through.
+ expect(record.origin_channel).not.toBeNull();
+ });
+
+ test("the device comes off the shard the entry was read from", () => {
+ seed({ timestamp: "2026-03-04T01:00:00Z", agent: "a", target: "One.md", deviceId: "laptop" });
+ seed({ timestamp: "2026-03-04T02:00:00Z", agent: "a", target: "Two.md", deviceId: "desktop" });
+ seed({ timestamp: "2026-03-04T03:00:00Z", agent: "a", target: "Three.md" });
+
+ const byTarget = new Map(listNoteWrites(vault).writes.map((w) => [w.target, w.device]));
+ expect(byTarget.get("One.md")).toBe("laptop");
+ expect(byTarget.get("Two.md")).toBe("desktop");
+ // The legacy un-sharded pair is the empty device, which is an answer.
+ expect(byTarget.get("Three.md")).toBe("");
+ });
+
+ test("filters by agent, device, path and op", () => {
+ seed({ timestamp: "2026-03-04T01:00:00Z", agent: "a", target: "One.md", deviceId: "laptop" });
+ seed({ timestamp: "2026-03-04T02:00:00Z", agent: "b", target: "One.md", deviceId: "laptop" });
+ seed({
+ timestamp: "2026-03-04T03:00:00Z",
+ agent: "a",
+ target: "Two.md",
+ deviceId: "desktop",
+ op: NOTE_WRITE_OP.create,
+ });
+
+ expect(listNoteWrites(vault, { agent: "a" }).writes.map((w) => w.target)).toEqual([
+ "Two.md",
+ "One.md",
+ ]);
+ expect(listNoteWrites(vault, { device: "desktop" }).writes.map((w) => w.target)).toEqual([
+ "Two.md",
+ ]);
+ expect(listNoteWrites(vault, { path: "One.md" }).writes.map((w) => w.agent)).toEqual([
+ "b",
+ "a",
+ ]);
+ expect(listNoteWrites(vault, { op: NOTE_WRITE_OP.create }).writes).toHaveLength(1);
+ expect(listNoteWrites(vault, { agent: "a", path: "One.md" }).writes).toHaveLength(1);
+ });
+
+ test("a bare --until date covers the whole day it names", () => {
+ seed({ timestamp: "2026-03-04T23:59:00Z", agent: "a", target: "Late.md" });
+ seed({ timestamp: "2026-03-05T00:00:01Z", agent: "a", target: "Next.md" });
+
+ expect(listNoteWrites(vault, { until: "2026-03-04" }).writes.map((w) => w.target)).toEqual([
+ "Late.md",
+ ]);
+ expect(listNoteWrites(vault, { since: "2026-03-05" }).writes.map((w) => w.target)).toEqual([
+ "Next.md",
+ ]);
+ expect(
+ listNoteWrites(vault, { since: "2026-03-04T23:59:30Z" }).writes.map((w) => w.target),
+ ).toEqual(["Next.md"]);
+ });
+
+ test("events of other kinds are not note writes", () => {
+ appendLogEvent(
+ vault,
+ {
+ timestamp: "2026-03-04T01:00:00Z",
+ eventType: BRAIN_LOG_EVENT_KIND.note,
+ agent: "a",
+ body: { text: "a milestone" },
+ },
+ { deviceId: "" },
+ );
+ expect(listNoteWrites(vault).writes).toEqual([]);
+ });
+
+ test("a note-write line missing its target is not projected as a blank row", () => {
+ appendLogEvent(
+ vault,
+ {
+ timestamp: "2026-03-04T01:00:00Z",
+ eventType: BRAIN_LOG_EVENT_KIND.noteWrite,
+ agent: "a",
+ body: { write_id: "nw_1_x", op: NOTE_WRITE_OP.update },
+ },
+ { deviceId: "" },
+ );
+ expect(listNoteWrites(vault).writes).toEqual([]);
+ });
+
+ test("an empty vault reports no writes and no warnings", () => {
+ expect(listNoteWrites(vault)).toEqual({ writes: [], warnings: [] });
+ });
+});
diff --git a/tests/core/brain/notes/write-record.test.ts b/tests/core/brain/notes/write-record.test.ts
new file mode 100644
index 00000000..b2a37655
--- /dev/null
+++ b/tests/core/brain/notes/write-record.test.ts
@@ -0,0 +1,240 @@
+/**
+ * The note-write record (who-wrote-what, Task A / t_662f4e82).
+ *
+ * Covers the three artifacts the module owns - the write id, the
+ * content-addressed before-image store, and the one `note-write` log
+ * event - plus the property the whole design turns on: a log-append
+ * failure costs the audit line and NOT the write, and says so by name.
+ */
+
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import {
+ chmodSync,
+ existsSync,
+ mkdirSync,
+ mkdtempSync,
+ readFileSync,
+ rmSync,
+ writeFileSync,
+} from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import {
+ NOTE_WRITE_NO_PRIOR,
+ NOTE_WRITE_OP,
+ WRITE_IMAGE_RETENTION_DAYS,
+ isNoteWriteOp,
+ noteWriteId,
+ pruneWriteImages,
+ recordNoteWrite,
+ storeBeforeImage,
+} from "../../../../src/core/brain/notes/write-record.ts";
+import { writeImagePath, writeImagesDir } from "../../../../src/core/brain/paths.ts";
+import { readLogDay } from "../../../../src/core/brain/log-jsonl.ts";
+import { sha256Hex } from "../../../../src/core/integrity/digest.ts";
+import { BRAIN_LOG_EVENT_KIND } from "../../../../src/core/brain/types.ts";
+
+const AGENT = "agent-a";
+const TS = "2026-03-04T05:06:07Z";
+const DATE = "2026-03-04";
+
+let vault: string;
+beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "o2b-write-record-"));
+});
+afterEach(() => rmSync(vault, { recursive: true, force: true }));
+
+describe("noteWriteId", () => {
+ test("carries the timestamp digits and a 16-hex body digest", () => {
+ const id = noteWriteId({
+ timestamp: TS,
+ op: NOTE_WRITE_OP.update,
+ target: "Notes/A.md",
+ hash_before: sha256Hex("old"),
+ hash_after: sha256Hex("new"),
+ agent: AGENT,
+ });
+ expect(id).toMatch(/^nw_\d{14}_[0-9a-f]{16}$/);
+ expect(id.slice(3, 17)).toBe("20260304050607");
+ });
+
+ test("is a pure function of the body: same facts, same id", () => {
+ const body = {
+ timestamp: TS,
+ op: NOTE_WRITE_OP.create,
+ target: "Notes/A.md",
+ hash_before: NOTE_WRITE_NO_PRIOR,
+ hash_after: sha256Hex("new"),
+ agent: AGENT,
+ } as const;
+ expect(noteWriteId(body)).toBe(noteWriteId(body));
+ expect(noteWriteId({ ...body, agent: "agent-b" })).not.toBe(noteWriteId(body));
+ });
+});
+
+describe("isNoteWriteOp", () => {
+ test("admits the four declared operations and nothing else", () => {
+ for (const op of Object.values(NOTE_WRITE_OP)) expect(isNoteWriteOp(op)).toBe(true);
+ expect(isNoteWriteOp("delete")).toBe(false);
+ expect(isNoteWriteOp(null)).toBe(false);
+ });
+});
+
+describe("storeBeforeImage", () => {
+ test("writes the bytes under their sha256 and reports it stored", () => {
+ const image = storeBeforeImage(vault, "prior body");
+ expect(image.sha256).toBe(sha256Hex("prior body"));
+ expect(image.stored).toBe(true);
+ expect(image.path).toBe(writeImagePath(vault, image.sha256));
+ expect(readFileSync(image.path, "utf8")).toBe("prior body");
+ });
+
+ test("a second image of identical content writes nothing", () => {
+ const first = storeBeforeImage(vault, "same");
+ const second = storeBeforeImage(vault, "same");
+ expect(second.stored).toBe(false);
+ expect(second.path).toBe(first.path);
+ });
+
+ test("distinct content gets distinct files", () => {
+ storeBeforeImage(vault, "one");
+ storeBeforeImage(vault, "two");
+ expect(pruneWriteImages(vault, { olderThanDays: 0, dryRun: true }).removed).toHaveLength(2);
+ });
+});
+
+describe("recordNoteWrite", () => {
+ test("appends exactly one note-write event with the design's fields", () => {
+ const receipt = recordNoteWrite(vault, {
+ op: NOTE_WRITE_OP.update,
+ target: "Notes/A.md",
+ before: { bytes: "old" },
+ after: { bytes: "newer" },
+ timestamp: TS,
+ agent: AGENT,
+ });
+ const writeId = receipt.write_id;
+ expect(writeId).toMatch(/^nw_\d{14}_[0-9a-f]{16}$/);
+
+ const day = readLogDay(vault, DATE);
+ const events = day.entries.filter((e) => e.eventType === BRAIN_LOG_EVENT_KIND.noteWrite);
+ expect(events).toHaveLength(1);
+ const body = events[0]!.body;
+ expect(body["write_id"]).toBe(writeId!);
+ expect(body["op"]).toBe(NOTE_WRITE_OP.update);
+ expect(body["target"]).toBe("Notes/A.md");
+ expect(body["hash_before"]).toBe(sha256Hex("old"));
+ expect(body["hash_after"]).toBe(sha256Hex("newer"));
+ expect(body["bytes_before"]).toBe("3");
+ expect(body["bytes_after"]).toBe("5");
+ expect(body["agent"]).toBe(AGENT);
+ expect(events[0]!.agent).toBe(AGENT);
+ });
+
+ test("a null before is recorded as absent, not as the digest of nothing", () => {
+ recordNoteWrite(vault, {
+ op: NOTE_WRITE_OP.create,
+ target: "Notes/A.md",
+ before: null,
+ after: { bytes: "body" },
+ timestamp: TS,
+ agent: AGENT,
+ });
+ const body = readLogDay(vault, DATE).entries[0]!.body;
+ expect(body["hash_before"]).toBe(NOTE_WRITE_NO_PRIOR);
+ expect(body["hash_before"]).not.toBe(sha256Hex(""));
+ expect(body["bytes_before"]).toBe("0");
+ });
+
+ test("an absolute target inside the vault is recorded vault-relative", () => {
+ recordNoteWrite(vault, {
+ op: NOTE_WRITE_OP.append,
+ target: join(vault, "Notes", "A.md"),
+ before: { bytes: "a" },
+ after: { bytes: "ab" },
+ timestamp: TS,
+ agent: AGENT,
+ });
+ expect(readLogDay(vault, DATE).entries[0]!.body["target"]).toBe("Notes/A.md");
+ });
+
+ test("a log-append failure returns a named audit_reason and never throws", () => {
+ // An unwritable log directory is the shape a full disk, a permission
+ // flip and a sync-locked tree all present as. The note is already on
+ // disk by the time this runs, so a throw here would report a failure
+ // for a write that succeeded.
+ const logDir = join(vault, "Brain", "log");
+ mkdirSync(logDir, { recursive: true });
+ chmodSync(logDir, 0o500);
+ try {
+ const receipt = recordNoteWrite(vault, {
+ op: NOTE_WRITE_OP.update,
+ target: "Notes/A.md",
+ before: { bytes: "old" },
+ after: { bytes: "new" },
+ timestamp: TS,
+ agent: AGENT,
+ });
+ expect(receipt.write_id).toBeNull();
+ expect(receipt.audit_reason).toContain("note-write event not recorded");
+ } finally {
+ chmodSync(logDir, 0o700);
+ }
+ });
+});
+
+describe("pruneWriteImages", () => {
+ test("the default window is the declared retention constant", () => {
+ storeBeforeImage(vault, "fresh");
+ expect(WRITE_IMAGE_RETENTION_DAYS).toBe(30);
+ expect(pruneWriteImages(vault).removed).toEqual([]);
+ expect(pruneWriteImages(vault).kept).toBe(1);
+ });
+
+ test("--older-than-days 0 removes every image; a dry run removes none", () => {
+ const image = storeBeforeImage(vault, "gone");
+ const preview = pruneWriteImages(vault, { olderThanDays: 0, dryRun: true });
+ expect(preview.removed).toEqual([image.sha256]);
+ expect(preview.dry_run).toBe(true);
+ expect(existsSync(image.path)).toBe(true);
+
+ const applied = pruneWriteImages(vault, { olderThanDays: 0 });
+ expect(applied.removed).toEqual([image.sha256]);
+ expect(applied.kept).toBe(0);
+ expect(existsSync(image.path)).toBe(false);
+ });
+
+ test("an absent store is an empty result, not a fault", () => {
+ expect(existsSync(writeImagesDir(vault))).toBe(false);
+ expect(pruneWriteImages(vault)).toEqual({ removed: [], kept: 0, skipped: [], dry_run: false });
+ });
+
+ test("a negative window is refused by name", () => {
+ expect(() => pruneWriteImages(vault, { olderThanDays: -1 })).toThrow(/non-negative integer/);
+ });
+
+ /**
+ * The store is a directory on a synced filesystem, so a name that is
+ * not a digest arrives there without anybody putting it there. The
+ * prune is the ONLY bound on the store, so it must survive one.
+ */
+ test("a name that is not a digest is skipped and reported, not thrown on", () => {
+ const image = storeBeforeImage(vault, "gone");
+ const dir = writeImagesDir(vault);
+ writeFileSync(join(dir, "readme.txt"), "not an image", "utf8");
+ writeFileSync(join(dir, "x.sync-conflict-20260910-000000-ABCDEF"), "conflict copy", "utf8");
+
+ const result = pruneWriteImages(vault, { olderThanDays: 0 });
+ expect(result.removed).toEqual([image.sha256]);
+ expect(existsSync(image.path)).toBe(false);
+ expect(result.skipped.toSorted()).toEqual([
+ "readme.txt",
+ "x.sync-conflict-20260910-000000-ABCDEF",
+ ]);
+ expect(result.kept).toBe(0);
+ // Skipped is not kept and not removed: a foreign name is neither an
+ // image this prune spared nor one it took.
+ expect(existsSync(join(dir, "readme.txt"))).toBe(true);
+ });
+});
diff --git a/tests/core/brain/pref-audit.test.ts b/tests/core/brain/pref-audit.test.ts
index 99ed4adc..21e767ba 100644
--- a/tests/core/brain/pref-audit.test.ts
+++ b/tests/core/brain/pref-audit.test.ts
@@ -10,9 +10,9 @@
*/
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
-import { appendFileSync, existsSync, mkdirSync, mkdtempSync, rmSync } from "node:fs";
+import { appendFileSync, existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
-import { join } from "node:path";
+import { dirname, join } from "node:path";
import {
appendPrefAudit,
@@ -25,6 +25,12 @@ import { PREF_AUDIT_OP } from "../../../src/core/brain/types.ts";
let vault: string;
const now = new Date("2026-05-29T12:00:00Z");
+/** Append to a shard whose directory the writer would have created. */
+function seedShard(path: string, text: string): void {
+ mkdirSync(dirname(path), { recursive: true });
+ appendFileSync(path, text, "utf8");
+}
+
beforeEach(() => {
vault = mkdtempSync(join(tmpdir(), "o2b-pref-audit-"));
mkdirSync(join(vault, "Brain", "log"), { recursive: true });
@@ -153,7 +159,7 @@ describe("readPrefAudit", () => {
test("tolerates an unknown op kind, keeping the raw string", () => {
const path = prefAuditPath(vault, "pref-future");
- mkdirSync(join(vault, "Brain", "log", "pref-audit"), { recursive: true });
+ mkdirSync(dirname(path), { recursive: true });
appendFileSync(
path,
JSON.stringify({
@@ -176,7 +182,7 @@ describe("readPrefAudit", () => {
test("surfaces a malformed JSONL line as a warning without aborting", () => {
const path = prefAuditPath(vault, "pref-mixed");
- mkdirSync(join(vault, "Brain", "log", "pref-audit"), { recursive: true });
+ mkdirSync(dirname(path), { recursive: true });
appendFileSync(path, "{ not json\n", "utf8");
appendFileSync(
path,
@@ -197,3 +203,189 @@ describe("readPrefAudit", () => {
expect(warnings.length).toBeGreaterThanOrEqual(1);
});
});
+
+/**
+ * Per-device shards (who-wrote-what, Task B / t_1814b9bf). Two devices
+ * promoting or editing the same preference must not append to one file,
+ * and the audit trail a reader shows is the union of both.
+ */
+describe("preference audit per-device shards", () => {
+ const savedEnv: Record<string, string | undefined> = {};
+ let configHome: string;
+
+ beforeEach(() => {
+ configHome = mkdtempSync(join(tmpdir(), "o2b-pref-audit-cfg-"));
+ const configPath = join(configHome, "config.yaml");
+ savedEnv["OPEN_SECOND_BRAIN_CONFIG"] = process.env["OPEN_SECOND_BRAIN_CONFIG"];
+ savedEnv["O2B_DEVICE_ID"] = process.env["O2B_DEVICE_ID"];
+ process.env["OPEN_SECOND_BRAIN_CONFIG"] = configPath;
+ delete process.env["O2B_DEVICE_ID"];
+ writeFileSync(configPath, `vault: ${vault}\ndevice_id: "testdev1"\n`, "utf8");
+ });
+
+ afterEach(() => {
+ rmSync(configHome, { recursive: true, force: true });
+ for (const key of ["OPEN_SECOND_BRAIN_CONFIG", "O2B_DEVICE_ID"]) {
+ const value = savedEnv[key];
+ if (value === undefined) delete process.env[key];
+ else process.env[key] = value;
+ }
+ });
+
+ function line(ts: string, agent: string): string {
+ return renderPrefAuditLine({
+ ts,
+ pref_id: "pref-shared",
+ op: PREF_AUDIT_OP.update,
+ agent,
+ revision_before: 1,
+ revision_after: 2,
+ hash_before: "a",
+ hash_after: "b",
+ });
+ }
+
+ test("a device with an id writes its own shard and never the bare file", () => {
+ appendPrefAudit(
+ vault,
+ {
+ pref_id: "pref-shared",
+ op: PREF_AUDIT_OP.create,
+ agent: "dream",
+ revision_before: null,
+ revision_after: 1,
+ hash_before: null,
+ hash_after: "a",
+ },
+ { now },
+ );
+ expect(existsSync(prefAuditPath(vault, "pref-shared", "testdev1"))).toBe(true);
+ expect(existsSync(prefAuditPath(vault, "pref-shared", ""))).toBe(false);
+ });
+
+ test("the reader merges the bare file and every device shard by timestamp", () => {
+ seedShard(prefAuditPath(vault, "pref-shared", ""), line("2026-05-29T12:00:00Z", "legacy"));
+ seedShard(
+ prefAuditPath(vault, "pref-shared", "devb"),
+ line("2026-05-29T12:00:02Z", "otherdev"),
+ );
+ seedShard(
+ prefAuditPath(vault, "pref-shared", "testdev1"),
+ line("2026-05-29T12:00:01Z", "mine"),
+ );
+ expect(readPrefAudit(vault, "pref-shared").records.map((r) => r.agent)).toEqual([
+ "legacy",
+ "mine",
+ "otherdev",
+ ]);
+ });
+
+ test("the flat trail written before the per-preference directory is still merged", () => {
+ const dir = join(vault, "Brain", "log", "pref-audit");
+ seedShard(join(dir, "pref-shared.jsonl"), line("2026-05-29T12:00:00Z", "flat-legacy"));
+ seedShard(join(dir, "pref-shared.devb.jsonl"), line("2026-05-29T12:00:01Z", "flat-devb"));
+ seedShard(
+ prefAuditPath(vault, "pref-shared", "testdev1"),
+ line("2026-05-29T12:00:02Z", "mine"),
+ );
+ expect(readPrefAudit(vault, "pref-shared").records.map((r) => r.agent)).toEqual([
+ "flat-legacy",
+ "flat-devb",
+ "mine",
+ ]);
+ });
+
+ test("a sync-conflict copy is not a shard and is never merged", () => {
+ const dir = join(vault, "Brain", "log", "pref-audit");
+ const own = prefAuditPath(vault, "pref-shared", "testdev1");
+ seedShard(own, line("2026-05-29T12:00:01Z", "mine"));
+ seedShard(
+ join(dir, "pref-shared.sync-conflict-20260529-120000-ABCDEFG.jsonl"),
+ line("2026-05-29T12:00:00Z", "conflict-flat"),
+ );
+ seedShard(
+ join(dirname(own), "device.sync-conflict-20260529-120000-ABCDEFG.jsonl"),
+ line("2026-05-29T12:00:00Z", "conflict-dir"),
+ );
+ expect(readPrefAudit(vault, "pref-shared").records.map((r) => r.agent)).toEqual(["mine"]);
+ });
+
+ test("one preference's shards never pick up another preference's file", () => {
+ seedShard(
+ prefAuditPath(vault, "pref-shared", "testdev1"),
+ line("2026-05-29T12:00:01Z", "mine"),
+ );
+ seedShard(
+ prefAuditPath(vault, "pref-shared-extra", "testdev1"),
+ line("2026-05-29T12:00:00Z", "other-pref"),
+ );
+ expect(readPrefAudit(vault, "pref-shared").records.map((r) => r.agent)).toEqual(["mine"]);
+ });
+});
+
+/**
+ * `validateSlug` permits one dot inside a preference id, so `pref-a.b` is
+ * a preference in its own right AND looks exactly like `pref-a`'s shard
+ * on a device called `b`. Both ends of the trail have to hold: a read
+ * that returns the neighbour's records and a write that lands in the
+ * neighbour's file are the same defect seen from two sides.
+ */
+describe("a preference id that contains a dot", () => {
+ const savedDeviceId = process.env["O2B_DEVICE_ID"];
+ beforeEach(() => {
+ process.env["O2B_DEVICE_ID"] = "b";
+ });
+ afterEach(() => {
+ if (savedDeviceId === undefined) delete process.env["O2B_DEVICE_ID"];
+ else process.env["O2B_DEVICE_ID"] = savedDeviceId;
+ });
+
+ function legacyLine(prefId: string, ts: string, agent: string): string {
+ return renderPrefAuditLine({
+ ts,
+ pref_id: prefId,
+ op: PREF_AUDIT_OP.update,
+ agent,
+ revision_before: 1,
+ revision_after: 2,
+ hash_before: "a",
+ hash_after: "b",
+ });
+ }
+
+ test("`pref-a` does not read `pref-a.b`'s legacy trail, and says it saw it", () => {
+ const dir = join(vault, "Brain", "log", "pref-audit");
+ mkdirSync(dir, { recursive: true });
+ appendFileSync(join(dir, "pref-a.jsonl"), legacyLine("pref-a", "2026-05-29T12:00:00Z", "mine"));
+ appendFileSync(
+ join(dir, "pref-a.b.jsonl"),
+ legacyLine("pref-a.b", "2026-05-29T12:00:01Z", "neighbour"),
+ );
+
+ const read = readPrefAudit(vault, "pref-a");
+ expect(read.records.map((r) => r.agent)).toEqual(["mine"]);
+ expect(read.warnings).toHaveLength(1);
+ expect(read.warnings[0]!.message).toContain("pref-a.b");
+
+ expect(readPrefAudit(vault, "pref-a.b").records.map((r) => r.agent)).toEqual(["neighbour"]);
+ });
+
+ test("appending for `pref-a` on device `b` leaves `pref-a.b`'s trail alone", () => {
+ appendPrefAudit(
+ vault,
+ {
+ pref_id: "pref-a",
+ op: PREF_AUDIT_OP.create,
+ agent: "dream",
+ revision_before: null,
+ revision_after: 1,
+ hash_before: null,
+ hash_after: "a",
+ },
+ { now },
+ );
+ expect(readPrefAudit(vault, "pref-a").records.map((r) => r.agent)).toEqual(["dream"]);
+ expect(readPrefAudit(vault, "pref-a.b").records).toEqual([]);
+ expect(existsSync(join(vault, "Brain", "log", "pref-audit", "pref-a.b.jsonl"))).toBe(false);
+ });
+});
diff --git a/tests/core/brain/snapshot-gate-coverage.test.ts b/tests/core/brain/snapshot-gate-coverage.test.ts
index b7a43d96..0e4d0e5a 100644
--- a/tests/core/brain/snapshot-gate-coverage.test.ts
+++ b/tests/core/brain/snapshot-gate-coverage.test.ts
@@ -71,6 +71,7 @@ import {
import { brainDirs, dreamWorkrunPath } from "../../../src/core/brain/paths.ts";
import { BRAIN_SNAPSHOT_REASON } from "../../../src/core/brain/types.ts";
import { atomicWriteFileSync } from "../../../src/core/fs-atomic.ts";
+import { maskLogChainDigests } from "../../helpers/vault-digest.ts";
const NOW = new Date("2026-06-01T00:00:00Z");
@@ -144,10 +145,15 @@ function dreamOutputRows(brainRoot: string): string[] {
// rows for every other file.
if (rel === "_brain.yaml") continue;
const path = rel.replace(/^log\/(\d{4}-\d{2}-\d{2})\.[0-9a-f]{8}\./, "log/$1.");
- const text = readFileSync(abs, "utf8")
- .replace(/^vault_name: .*$/gm, "vault_name: <name>")
- .replace(/^- size_bytes: \d+$/gm, "- size_bytes: <n>")
- .replace(/"size_bytes":"\d+"/g, String.raw`"size_bytes":"<n>"`);
+ // The chain hash over each JSONL row covers `size_bytes`, so the
+ // one value normalised above propagates into every row's `h` and
+ // into the `prev` that follows it - see `maskLogChainDigests`.
+ const text = maskLogChainDigests(
+ readFileSync(abs, "utf8")
+ .replace(/^vault_name: .*$/gm, "vault_name: <name>")
+ .replace(/^- size_bytes: \d+$/gm, "- size_bytes: <n>")
+ .replace(/"size_bytes":"\d+"/g, String.raw`"size_bytes":"<n>"`),
+ );
rows.push(`${path}\t${createHash("sha256").update(text).digest("hex")}`);
}
};
@@ -231,10 +237,22 @@ describe("the dream pass runs behind the gate, not beside it", () => {
// that unit and WITHOUT the snapshot gate this file guards, taken
// the same way as the two before it, so what it still proves is the
// same claim: the gate authors none of these bytes.
+ //
+ // Re-measured a THIRD time, in who-wrote-what, and again for bytes
+ // the pass does author: every JSONL log row now carries `prev` and
+ // `h`, the per-shard hash chain (Task E). Unlike the two before it
+ // this literal was taken on the branch that adds the chain rather
+ // than on a tree without the unit, because the chain is computed
+ // inside the appender the pass calls and there is no build of it to
+ // measure the pass against. What the number still guards is that it
+ // does not move again without a named reason - and the masking in
+ // `dreamOutputRows` is what keeps it a guard rather than a coin
+ // flip: `size_bytes` is inside the hashed payload, so without the
+ // mask this digest would differ on every run.
seedSignal("tidy");
dream(vault, { now: NOW, agentName: "tester" });
expect(dreamOutputDigest(join(vault, "Brain"))).toBe(
- "345b742a592bbfd51305e16fc9e63031f88ba54371ba619e01eecff129f4103a",
+ "595e933323e01c1d2d9c15b5c1b8e1bcede298740cf9ef543c8fdc8845048bc0",
);
});
diff --git a/tests/core/brain/write-batch.test.ts b/tests/core/brain/write-batch.test.ts
index 803b0664..302222f0 100644
--- a/tests/core/brain/write-batch.test.ts
+++ b/tests/core/brain/write-batch.test.ts
@@ -40,6 +40,13 @@ import { tmpdir } from "node:os";
import { join } from "node:path";
import { applyWriteBatch, WriteBatchError } from "../../../src/core/brain/write-batch.ts";
+import { listNoteWrites, type NoteWriteRecord } from "../../../src/core/brain/notes/write-log.ts";
+import {
+ NOTE_WRITE_NO_PRIOR,
+ pruneWriteImages,
+} from "../../../src/core/brain/notes/write-record.ts";
+import { writeImagePath } from "../../../src/core/brain/paths.ts";
+import { sha256Hex } from "../../../src/core/integrity/digest.ts";
let vault: string;
@@ -404,3 +411,93 @@ describe("applyWriteBatch note operations", () => {
expect(readFileSync(abs, "utf8")).toBe(before);
});
});
+
+/**
+ * Attributable note writes (who-wrote-what, Task A / t_662f4e82).
+ *
+ * The kernel is one of the two seams every note mutation funnels through,
+ * so this is where "exactly one event per write" is pinned - along with
+ * the before-image, which is what makes a recorded write undoable rather
+ * than merely visible.
+ */
+describe("applyWriteBatch note-write attribution", () => {
+ function noteWrites(): ReadonlyArray<NoteWriteRecord> {
+ return listNoteWrites(vault).writes;
+ }
+
+ test("each of the three note operations appends exactly one event", () => {
+ seedNote("Notes/Doc.md", "original body", "title: Doc");
+ applyWriteBatch(vault, [{ kind: "create_note", path: "Notes/Fresh.md", content: "fresh" }]);
+ applyWriteBatch(vault, [{ kind: "update_note", path: "Notes/Doc.md", body: "next body" }]);
+ applyWriteBatch(vault, [{ kind: "append_note", path: "Notes/Doc.md", content: "more" }]);
+
+ const writes = noteWrites();
+ expect(writes).toHaveLength(3);
+ expect(writes.map((w) => `${w.op} ${w.target}`).toSorted()).toEqual([
+ "append Notes/Doc.md",
+ "create Notes/Fresh.md",
+ "update Notes/Doc.md",
+ ]);
+ });
+
+ test("every note result carries the id of the event that attributes it", () => {
+ seedNote("Notes/Doc.md", "original body", "title: Doc");
+ const res = applyWriteBatch(vault, [
+ { kind: "create_note", path: "Notes/Fresh.md", content: "fresh" },
+ { kind: "update_note", path: "Notes/Doc.md", body: "next body" },
+ ]);
+ const ids = res.results.map((r) => ("write_id" in r ? r.write_id : null));
+ for (const id of ids) expect(id).toMatch(/^nw_\d{14}_[0-9a-f]{16}$/);
+ expect(new Set(noteWrites().map((w) => w.write_id))).toEqual(new Set(ids as string[]));
+ // The audit half is a pair: an id present means no reason is owed.
+ for (const r of res.results) expect("audit_reason" in r).toBe(false);
+ });
+
+ test("an update records the bytes it replaced and the bytes it wrote", () => {
+ const abs = seedNote("Notes/Doc.md", "original body", "title: Doc");
+ const before = readFileSync(abs, "utf8");
+ applyWriteBatch(vault, [{ kind: "update_note", path: "Notes/Doc.md", body: "next body" }]);
+ const after = readFileSync(abs, "utf8");
+
+ const write = noteWrites()[0]!;
+ expect(write.hash_before).toBe(sha256Hex(before));
+ expect(write.hash_after).toBe(sha256Hex(after));
+ expect(write.bytes_before).toBe(Buffer.byteLength(before, "utf8"));
+ expect(write.bytes_after).toBe(Buffer.byteLength(after, "utf8"));
+ // The before-image holds the exact prior bytes, keyed by their hash.
+ expect(readFileSync(writeImagePath(vault, write.hash_before), "utf8")).toBe(before);
+ });
+
+ test("a create records no prior content and stores no image", () => {
+ applyWriteBatch(vault, [{ kind: "create_note", path: "Notes/Fresh.md", content: "fresh" }]);
+ const write = noteWrites()[0]!;
+ expect(write.hash_before).toBe(NOTE_WRITE_NO_PRIOR);
+ expect(write.bytes_before).toBe(0);
+ expect(pruneWriteImages(vault, { olderThanDays: 0, dryRun: true }).removed).toEqual([]);
+ });
+
+ test("returning a note to a former state re-uses the image already stored", () => {
+ const abs = seedNote("Notes/Doc.md", "one", "title: Doc");
+ const first = readFileSync(abs, "utf8");
+ applyWriteBatch(vault, [{ kind: "update_note", path: "Notes/Doc.md", body: "two" }]);
+ const second = readFileSync(abs, "utf8");
+ applyWriteBatch(vault, [{ kind: "update_note", path: "Notes/Doc.md", body: "one" }]);
+ applyWriteBatch(vault, [{ kind: "update_note", path: "Notes/Doc.md", body: "two" }]);
+
+ // Three rewrites, two distinct prior contents, two image files.
+ expect(noteWrites()).toHaveLength(3);
+ const stored = pruneWriteImages(vault, { olderThanDays: 0, dryRun: true }).removed;
+ expect(stored.toSorted()).toEqual([sha256Hex(first), sha256Hex(second)].toSorted());
+ });
+
+ test("a refused batch records nothing, because no bytes were written", () => {
+ seedNote("Notes/Doc.md", "original body", "title: Doc");
+ expect(() =>
+ applyWriteBatch(vault, [
+ { kind: "update_note", path: "Notes/Doc.md", body: "next body" },
+ { kind: "update_note", path: "Notes/Missing.md", body: "never" },
+ ]),
+ ).toThrow(WriteBatchError);
+ expect(noteWrites()).toEqual([]);
+ });
+});
diff --git a/tests/core/install/tool-ceiling.test.ts b/tests/core/install/tool-ceiling.test.ts
index 8790dd36..ba239b03 100644
--- a/tests/core/install/tool-ceiling.test.ts
+++ b/tests/core/install/tool-ceiling.test.ts
@@ -340,7 +340,7 @@ describe("the capability report states the ceiling it runs under", () => {
test("the advertised count is the one a host lists, not the registered one", () => {
const evaluated = report("cursor");
- expect(evaluated.available_tool_count).toBe(113);
+ expect(evaluated.available_tool_count).toBe(114);
expect(evaluated.advertised_tool_count).toBe(7);
});
});
diff --git a/tests/core/integrity/degradation.test.ts b/tests/core/integrity/degradation.test.ts
index fe230005..3b96efd8 100644
--- a/tests/core/integrity/degradation.test.ts
+++ b/tests/core/integrity/degradation.test.ts
@@ -48,6 +48,10 @@ function owningUnit(code: DegradationCode): string {
return "J";
case DEGRADATION_CODE.vaultMarkerMismatch:
return "J";
+ case DEGRADATION_CODE.vaultFrozen:
+ return "C";
+ case DEGRADATION_CODE.logChainBroken:
+ return "E";
default:
return assertNever(code);
}
diff --git a/tests/core/state/surfaces.test.ts b/tests/core/state/surfaces.test.ts
index 97d0b042..74bffa4c 100644
--- a/tests/core/state/surfaces.test.ts
+++ b/tests/core/state/surfaces.test.ts
@@ -49,6 +49,7 @@ import {
brainStateDir,
captureDecisionLogPath,
captureWatermarkPath,
+ writeImagesDir,
} from "../../../src/core/brain/paths.ts";
import { deadLetterDir } from "../../../src/core/brain/dead-letter.ts";
import { checkpointPath } from "../../../src/core/brain/ingest/checkpoint.ts";
@@ -60,6 +61,7 @@ import { manifestPath as installManifestPath } from "../../../src/core/install/m
import { receiptsDir } from "../../../src/core/brain/decisions/receipts.ts";
import { anticipatoryCachePath } from "../../../src/core/brain/anticipatory-cache.ts";
import { continuityLogPath } from "../../../src/core/brain/continuity/store.ts";
+import { frozenMarkerPath } from "../../../src/core/brain/freeze-marker.ts";
import { sessionLineageLedgerPath } from "../../../src/core/brain/lineage/ledger.ts";
import { appendJournal, MAINTENANCE_VERDICT } from "../../../src/core/brain/maintenance/journal.ts";
import { acquireLease, MAINTENANCE_LEASE_NAME } from "../../../src/core/brain/maintenance/lease.ts";
@@ -253,6 +255,8 @@ const RESOLVER_BINDINGS: ReadonlyArray<readonly [StateSurfaceId, (vault: string)
["proposal_watermark", (v) => proposalWatermarkPath(v)],
["decision_receipts", (v) => receiptsDir(v)],
["lineage_ledger", (v) => sessionLineageLedgerPath(v)],
+ ["freeze_marker", (v) => frozenMarkerPath(v)],
+ ["write_images", (v) => writeImagesDir(v)],
["anticipatory_cache", (v) => dirname(anticipatoryCachePath(v, "root-session"))],
["exact_state", (v) => brainStateDir(v)],
["search_feedback", (v) => feedbackDir(v)],
diff --git a/tests/helpers/tool-probe-catalogue.ts b/tests/helpers/tool-probe-catalogue.ts
index 7f282df2..e8e4820a 100644
--- a/tests/helpers/tool-probe-catalogue.ts
+++ b/tests/helpers/tool-probe-catalogue.ts
@@ -250,6 +250,23 @@ export const REASON = Object.freeze({
"plans a recompile of DERIVED pages whose sources moved (`Brain/sources`, `Brain/reports`). " +
"The fixture holds no derived page, so this recipe reaches no owner-taggable content; the " +
"gap is recorded rather than papered over with a recipe that cannot fail.",
+ noteWriteLedger:
+ "reads the `note-write` event ledger inside the Brain log. The rows are a write id, an " +
+ "operation, a target PATH, two content digests and the agent that recorded them - no page " +
+ "is ever opened, so there is no frontmatter for the ownership rule to read. The honest " +
+ "half: a target path names a note file that MAY carry an `owner:`, and this surface " +
+ "reports the path either way, so an owner-private note an agent wrote is discoverable by " +
+ "path here. The gap is recorded rather than closed by reading every named page, which " +
+ "would turn a log listing into a fan-out over the whole vault; the revert task is where " +
+ "the ownership question is decided, because that is where a caller acts on a target " +
+ "rather than reading that one exists.",
+ noteRevertPlan:
+ "plans what undoing the note writes a selector names WOULD do, and applies nothing - the " +
+ "apply is CLI-only by design. It is the one recipe in this entry that opens page bytes: it " +
+ "hashes each named target to decide whether the file drifted since the write it would undo. " +
+ "What it PUBLISHES is a digest, a path, an action token and a refusal reason, never a byte " +
+ "of the page, so an owner-private note reaches this surface as the same path the listing " +
+ "beside it already reports and as nothing more.",
signalAuthorship:
"groups SIGNALS by the `agent:` that wrote them. A signal carries no `owner:` anywhere in " +
"this product, so the agent column names the author of a SHARED artifact - the same fact " +
@@ -271,8 +288,8 @@ export const REASONS_REACHING_OWNER_CONTENT: ReadonlySet<string> = new Set([REAS
* `docs/mcp.md` and the release notes. Equalities, not floors - see the
* test that reads them.
*/
-export const PROBE_ENTRY_COUNT = 99;
-export const PROBE_RECIPE_COUNT = 226;
+export const PROBE_ENTRY_COUNT = 100;
+export const PROBE_RECIPE_COUNT = 229;
export const PROBE_TWO_SIDED_COUNT = 32;
/**
@@ -328,6 +345,17 @@ export function hygieneApplyArgs(vault: string): Record<string, unknown> {
* forgotten β€” this is the honest half of the matrix.
*/
export const UNSCOPED_CONTENT: ReadonlyArray<ProbeEntry> = [
+ {
+ name: "brain_writes",
+ calls: [
+ { args: { action: "list" }, reason: REASON.noteWriteLedger },
+ { args: { action: "list", op: "update" }, reason: REASON.noteWriteLedger },
+ {
+ args: { action: "plan_revert", path: "notes/shared.md" },
+ reason: REASON.noteRevertPlan,
+ },
+ ],
+ },
{ name: "brain_session_grep", calls: one({ query: QUERY }, REASON.sessionLane) },
{ name: "brain_session_expand", calls: one({ id: "sess-probe:0" }, REASON.sessionLane) },
{
diff --git a/tests/helpers/vault-digest.ts b/tests/helpers/vault-digest.ts
index c9a0d49f..644aefc6 100644
--- a/tests/helpers/vault-digest.ts
+++ b/tests/helpers/vault-digest.ts
@@ -64,3 +64,28 @@ export function changedPaths(
for (const [path, digest] of after) if (before.get(path) !== digest) changed.add(path);
return [...changed].toSorted();
}
+
+/** `"h":"<64 hex>"` / `"prev":"<64 hex>"`, capturing the key. */
+const LOG_CHAIN_DIGEST_RE = /("(?:prev|h)":)"[0-9a-f]{64}"/g;
+
+/**
+ * The Brain log's chain digests, masked (who-wrote-what, Task E).
+ *
+ * Every JSONL log row carries `h`, a sha256 over its own `{ prev, ts,
+ * kind, payload }`, and `prev`, the previous row's `h`. A byte-for-byte
+ * comparison of two independently produced vaults therefore inherits
+ * every exemption the payload already needed: the `snapshot` audit row
+ * records an archive's byte length, tar embeds per-entry mtimes, so two
+ * identically seeded vaults differ there - and once they differ there,
+ * the hash of that row and of every row after it differs too. A test
+ * that normalises the length without normalising the hash is asking the
+ * chain to be blind to a value it has just declared unreproducible.
+ *
+ * Only the 64-hex DIGEST is masked. The key names stay, and
+ * `"prev":null` is deliberately left alone, so the comparison still
+ * asserts that every row carries a hash and that exactly the same rows
+ * anchor their shard's chain in both trees.
+ */
+export function maskLogChainDigests(text: string): string {
+ return text.replaceAll(LOG_CHAIN_DIGEST_RE, '$1"<chain-digest>"');
+}
diff --git a/tests/mcp/agent-scope-matrix.test.ts b/tests/mcp/agent-scope-matrix.test.ts
index 33373eb6..40c99bb2 100644
--- a/tests/mcp/agent-scope-matrix.test.ts
+++ b/tests/mcp/agent-scope-matrix.test.ts
@@ -211,7 +211,7 @@ test("the matrix classifies every tool exactly once", () => {
});
test("the tool count is unchanged: an argument was added, never a tool", () => {
- expect(TOOLS.length).toBe(113);
+ expect(TOOLS.length).toBe(114);
});
test("every argument-scoped surface declares agent_scope in its input schema", () => {
diff --git a/tests/mcp/brain-create-note.test.ts b/tests/mcp/brain-create-note.test.ts
index 3fd69ae9..77c68f45 100644
--- a/tests/mcp/brain-create-note.test.ts
+++ b/tests/mcp/brain-create-note.test.ts
@@ -21,6 +21,13 @@ import { WRITE_BINDING_REFUSED_CODE } from "../../src/core/write-binding/index.t
import { MCPError } from "../../src/mcp/protocol.ts";
import type { ServerContext } from "../../src/mcp/tool-contract.ts";
+/**
+ * Shape of a note-write id, as `noteWriteId` spells it (who-wrote-what,
+ * Task A). Its value carries the instant of the write, so a receipt test
+ * pins the shape rather than a literal.
+ */
+const NOTE_WRITE_ID_RE = /^nw_\d{14}_[0-9a-f]{16}$/;
+
let vault: string;
let configHome: string;
let ctx: ServerContext;
@@ -246,15 +253,19 @@ describe("brain_create_note - the lint attached to the receipt", () => {
const call = async (args: Record<string, unknown>): Promise<Record<string, unknown>> =>
(await handler(ctx, args)) as Record<string, unknown>;
- test("a clean write is byte-identical to the receipt that shipped before", async () => {
+ test("a clean write carries the flags, the path and the write id", async () => {
const res = await call({
path: "Notes/Clean.md",
frontmatter: { title: "Clean" },
content: "plain prose, no links",
});
- expect(JSON.stringify(res)).toBe(
- JSON.stringify({ created: true, outcome: "created", path: "Notes/Clean.md" }),
- );
+ expect(Object.keys(res)).toEqual(["created", "outcome", "path", "write_id"]);
+ expect(res).toMatchObject({ created: true, outcome: "created", path: "Notes/Clean.md" });
+ // `write_id` joined the receipt with the note-write record
+ // (who-wrote-what, Task A); its value is derived from the instant of
+ // the write, so the shape is what can be pinned.
+ expect(res["write_id"]).toMatch(NOTE_WRITE_ID_RE);
+ expect("audit_reason" in res).toBe(false);
expect(PAGE_LINT_KEY in res).toBe(false);
});
diff --git a/tests/mcp/brain-tools-parity.test.ts b/tests/mcp/brain-tools-parity.test.ts
index 1874dd0e..57a0158a 100644
--- a/tests/mcp/brain-tools-parity.test.ts
+++ b/tests/mcp/brain-tools-parity.test.ts
@@ -166,6 +166,7 @@ const FROZEN_BRAIN_TOOL_NAMES = [
"brain_update_note",
"brain_write_batch",
"brain_write_session",
+ "brain_writes",
] as const;
describe("BRAIN_TOOLS frozen surface", () => {
diff --git a/tests/mcp/brain-update-append-note.test.ts b/tests/mcp/brain-update-append-note.test.ts
index f3df75f6..188b6476 100644
--- a/tests/mcp/brain-update-append-note.test.ts
+++ b/tests/mcp/brain-update-append-note.test.ts
@@ -28,6 +28,13 @@ import { PAGE_LINT_KEY } from "../../src/core/brain/page-lint.ts";
import { INTERNAL_ERROR, INVALID_PARAMS, MCPError } from "../../src/mcp/protocol.ts";
import type { ServerContext } from "../../src/mcp/tool-contract.ts";
+/**
+ * Shape of a note-write id, as `noteWriteId` spells it (who-wrote-what,
+ * Task A). Its value carries the instant of the write, so a receipt test
+ * pins the shape rather than a literal.
+ */
+const NOTE_WRITE_ID_RE = /^nw_\d{14}_[0-9a-f]{16}$/;
+
/** Await `result`, assert it rejected with an MCPError, and return it. */
async function rejectedMcpError(result: unknown): Promise<MCPError> {
let thrown: unknown;
@@ -272,17 +279,29 @@ describe("the lint attached to the update / append receipts", () => {
args: Record<string, unknown>,
): Promise<Record<string, unknown>> => (await tool.handler(ctx, args)) as Record<string, unknown>;
- test("a clean update is byte-identical to the receipt that shipped before", async () => {
+ test("a clean update carries the flag, the path and the write id, in that order", async () => {
seedNote("Notes/Clean.md", "old body", "title: Clean");
const res = await call(updateTool, { path: "Notes/Clean.md", content: "new body" });
- expect(JSON.stringify(res)).toBe(JSON.stringify({ updated: true, path: "Notes/Clean.md" }));
+ // The shape is pinned in full so a field cannot arrive unannounced.
+ // `write_id` joined it with the note-write record (who-wrote-what,
+ // Task A) and is the one key whose VALUE cannot be a literal: it is
+ // derived from the instant of the write.
+ expect(Object.keys(res)).toEqual(["updated", "path", "write_id"]);
+ expect(res).toMatchObject({ updated: true, path: "Notes/Clean.md" });
+ expect(res["write_id"]).toMatch(NOTE_WRITE_ID_RE);
+ // An id present means no audit reason is owed, and the lint has
+ // nothing to say about a clean page.
+ expect("audit_reason" in res).toBe(false);
expect(PAGE_LINT_KEY in res).toBe(false);
});
- test("a clean append is byte-identical to the receipt that shipped before", async () => {
+ test("a clean append carries the flag, the path and the write id, in that order", async () => {
seedNote("Notes/CleanA.md", "first", "title: CleanA");
const res = await call(appendTool, { path: "Notes/CleanA.md", content: "second" });
- expect(JSON.stringify(res)).toBe(JSON.stringify({ appended: true, path: "Notes/CleanA.md" }));
+ expect(Object.keys(res)).toEqual(["appended", "path", "write_id"]);
+ expect(res).toMatchObject({ appended: true, path: "Notes/CleanA.md" });
+ expect(res["write_id"]).toMatch(NOTE_WRITE_ID_RE);
+ expect("audit_reason" in res).toBe(false);
expect(PAGE_LINT_KEY in res).toBe(false);
});
diff --git a/tests/mcp/brain-write-batch.test.ts b/tests/mcp/brain-write-batch.test.ts
index 5fd8c73d..a5ef53bc 100644
--- a/tests/mcp/brain-write-batch.test.ts
+++ b/tests/mcp/brain-write-batch.test.ts
@@ -30,6 +30,13 @@ import { PAGE_LINT_KEY } from "../../src/core/brain/page-lint.ts";
import { MCPError } from "../../src/mcp/protocol.ts";
import type { ServerContext } from "../../src/mcp/tool-contract.ts";
+/**
+ * Shape of a note-write id, as `noteWriteId` spells it (who-wrote-what,
+ * Task A). Its value carries the instant of the write, so a receipt test
+ * pins the shape rather than a literal.
+ */
+const NOTE_WRITE_ID_RE = /^nw_\d{14}_[0-9a-f]{16}$/;
+
let vault: string;
let configHome: string;
let ctx: ServerContext;
@@ -291,7 +298,7 @@ describe("brain_write_batch", () => {
* per call rather than once per operation.
*/
describe("brain_write_batch - the lint attached to the receipt", () => {
- test("a clean batch is byte-identical to the receipt that shipped before", async () => {
+ test("a clean batch carries the counts, the results and each write id", async () => {
const res = await runBatch([
{
op: "create_note",
@@ -300,13 +307,19 @@ describe("brain_write_batch - the lint attached to the receipt", () => {
content: "prose",
},
]);
- expect(JSON.stringify(res)).toBe(
- JSON.stringify({
- applied: 1,
- results: [{ kind: "create_note", path: "Notes/CleanBatch.md", created: true }],
- done: true,
- }),
- );
+ expect(Object.keys(res)).toEqual(["applied", "results", "done"]);
+ const only = (res["results"] as ReadonlyArray<Record<string, unknown>>)[0]!;
+ expect(Object.keys(only)).toEqual(["kind", "path", "created", "write_id"]);
+ expect(only).toMatchObject({
+ kind: "create_note",
+ path: "Notes/CleanBatch.md",
+ created: true,
+ });
+ // Each note result names the event that attributes it; the batch
+ // envelope itself is unchanged (who-wrote-what, Task A).
+ expect(only["write_id"]).toMatch(NOTE_WRITE_ID_RE);
+ expect(res["applied"]).toBe(1);
+ expect(res["done"]).toBe(true);
expect(PAGE_LINT_KEY in res).toBe(false);
});
diff --git a/tests/mcp/brain-writes.test.ts b/tests/mcp/brain-writes.test.ts
new file mode 100644
index 00000000..b0c953ab
--- /dev/null
+++ b/tests/mcp/brain-writes.test.ts
@@ -0,0 +1,218 @@
+/**
+ * `brain_writes` (who-wrote-what, Task A / t_662f4e82).
+ *
+ * The agent-facing half of the note-write record: the listing, the
+ * filters, and the one action that is DECLARED and not yet reachable -
+ * `plan_revert`, which is refused by name so an agent learns the
+ * capability exists rather than reading an unknown-argument error as a
+ * typo.
+ *
+ * The end-to-end property is pinned here too: a note written through
+ * `brain_create_note` shows up under `brain_writes` with the id its own
+ * receipt named. Two surfaces, one record.
+ */
+
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { dirname, join } from "node:path";
+
+import { bootstrapBrain } from "../../src/core/brain/init.ts";
+import { recordNoteWrite, storeBeforeImage } from "../../src/core/brain/notes/write-record.ts";
+import { atomicWriteFileSync } from "../../src/core/fs-atomic.ts";
+import { BRAIN_TOOLS } from "../../src/mcp/brain-tools.ts";
+import { INVALID_PARAMS, MCPError } from "../../src/mcp/protocol.ts";
+import type { ServerContext } from "../../src/mcp/tool-contract.ts";
+
+let vault: string;
+let configHome: string;
+let ctx: ServerContext;
+
+beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "o2b-brain-writes-vault-"));
+ configHome = mkdtempSync(join(tmpdir(), "o2b-brain-writes-cfg-"));
+ const configPath = join(configHome, "config.yaml");
+ atomicWriteFileSync(configPath, `vault: ${vault}\nagent_name: claude\n`);
+ bootstrapBrain(vault, { configPath });
+ ctx = { vault, configPath, repoRoot: null };
+});
+
+afterEach(() => {
+ rmSync(vault, { recursive: true, force: true });
+ rmSync(configHome, { recursive: true, force: true });
+});
+
+const tool = (name: string) => BRAIN_TOOLS.find((t) => t.name === name)!;
+
+const call = async (name: string, args: Record<string, unknown>) =>
+ (await tool(name).handler(ctx, args)) as Record<string, unknown>;
+
+interface WritesReply {
+ readonly action: string;
+ readonly total_matched: number;
+ readonly returned: number;
+ readonly writes: ReadonlyArray<Record<string, unknown>>;
+ readonly warnings: ReadonlyArray<unknown>;
+}
+
+const listWrites = async (args: Record<string, unknown> = {}): Promise<WritesReply> =>
+ (await call("brain_writes", args)) as unknown as WritesReply;
+
+/** Await `result`, assert it rejected with an MCPError, and return it. */
+async function rejectedMcpError(result: unknown): Promise<MCPError> {
+ let thrown: unknown;
+ try {
+ await result;
+ } catch (err) {
+ thrown = err;
+ }
+ expect(thrown).toBeInstanceOf(MCPError);
+ return thrown as MCPError;
+}
+
+describe("brain_writes registration", () => {
+ test("is registered, read-only by shape, and takes no required argument", () => {
+ const def = tool("brain_writes");
+ expect(def).toBeDefined();
+ expect(def.inputSchema.required ?? []).toEqual([]);
+ expect(def.previewBudget).toBeGreaterThan(0);
+ });
+
+ test("declares both actions now, so the schema pins move once", () => {
+ const schema = tool("brain_writes").inputSchema as {
+ properties: Record<string, { enum?: ReadonlyArray<string> }>;
+ };
+ expect(schema.properties["action"]?.enum).toEqual(["list", "plan_revert"]);
+ expect(schema.properties["op"]?.enum).toEqual(["create", "update", "append", "revert"]);
+ });
+});
+
+describe("brain_writes action list", () => {
+ test("lists what the note-write tools recorded, by the id they reported", async () => {
+ const created = await call("brain_create_note", {
+ path: "Notes/One.md",
+ content: "first body",
+ });
+ await call("brain_update_note", { path: "Notes/One.md", content: "second body" });
+
+ const reply = await listWrites({});
+ expect(reply.action).toBe("list");
+ expect(reply.total_matched).toBe(2);
+ expect(reply.returned).toBe(2);
+ // Newest first, so the update leads.
+ expect(reply.writes.map((w) => w["op"])).toEqual(["update", "create"]);
+ expect(reply.writes.map((w) => w["target"])).toEqual(["Notes/One.md", "Notes/One.md"]);
+ // The very id the create receipt named: two surfaces, one record.
+ expect(reply.writes.map((w) => w["write_id"])).toContain(created["write_id"]);
+ expect(reply.writes[0]!["agent"]).toBe("claude");
+ });
+
+ test("defaults to list when no action is sent", async () => {
+ await call("brain_create_note", { path: "Notes/One.md", content: "body" });
+ expect((await listWrites({})).action).toBe("list");
+ });
+
+ test("filters by op and by path", async () => {
+ await call("brain_create_note", { path: "Notes/One.md", content: "body" });
+ await call("brain_create_note", { path: "Notes/Two.md", content: "body" });
+ await call("brain_append_note", { path: "Notes/One.md", content: "more" });
+
+ expect((await listWrites({ op: "append" })).total_matched).toBe(1);
+ expect((await listWrites({ path: "Notes/Two.md" })).total_matched).toBe(1);
+ expect((await listWrites({ agent: "nobody" })).total_matched).toBe(0);
+ });
+
+ test("limit caps the rows and total_matched still names the whole match", async () => {
+ await call("brain_create_note", { path: "Notes/One.md", content: "body" });
+ await call("brain_create_note", { path: "Notes/Two.md", content: "body" });
+
+ const reply = await listWrites({ limit: 1 });
+ expect(reply.total_matched).toBe(2);
+ expect(reply.returned).toBe(1);
+ expect(reply.writes).toHaveLength(1);
+ });
+
+ test("an empty vault answers with an empty list, not an error", async () => {
+ const reply = await listWrites({});
+ expect(reply.total_matched).toBe(0);
+ expect(reply.writes).toEqual([]);
+ expect(reply.warnings).toEqual([]);
+ });
+
+ test("an unknown op is refused by name", async () => {
+ const err = await rejectedMcpError(call("brain_writes", { op: "delete" }));
+ expect(err.code).toBe(INVALID_PARAMS);
+ expect(err.message).toContain("create, update, append, revert");
+ });
+});
+
+describe("brain_writes action plan_revert", () => {
+ /** Do what the write seams do, so the plan reads a real history. */
+ function seedNote(opts: {
+ readonly target: string;
+ readonly bytes: string;
+ readonly agent: string;
+ readonly at: string;
+ }): void {
+ const abs = join(vault, opts.target);
+ const before = existsSync(abs) ? readFileSync(abs, "utf8") : null;
+ mkdirSync(dirname(abs), { recursive: true });
+ if (before !== null) storeBeforeImage(vault, before);
+ atomicWriteFileSync(abs, opts.bytes);
+ recordNoteWrite(vault, {
+ op: before === null ? "create" : "update",
+ target: opts.target,
+ before: before === null ? null : { bytes: before },
+ after: { bytes: opts.bytes },
+ timestamp: opts.at,
+ agent: opts.agent,
+ });
+ }
+
+ const TARGET = "notes/A.md";
+
+ test("returns the entries and the digest, and no apply path", async () => {
+ seedNote({ target: TARGET, bytes: "v0", agent: "seed", at: "2026-03-04T01:00:00Z" });
+ seedNote({ target: TARGET, bytes: "v1", agent: "claude", at: "2026-03-04T02:00:00Z" });
+
+ const reply = await call("brain_writes", { action: "plan_revert", agent: "claude" });
+ expect(reply["action"]).toBe("plan_revert");
+ expect(reply["digest"]).toMatch(/^[0-9a-f]{64}$/);
+ const entries = reply["entries"] as ReadonlyArray<Record<string, unknown>>;
+ expect(entries).toHaveLength(1);
+ expect(entries[0]!["target"]).toBe(TARGET);
+ expect(entries[0]!["action"]).toBe("restore");
+ // The plan is a report: the tool has no apply and moved nothing.
+ expect(readFileSync(join(vault, TARGET), "utf8")).toBe("v1");
+ expect(Object.keys(reply)).not.toContain("applied");
+ });
+
+ test("reports a refused target by name rather than dropping it", async () => {
+ seedNote({ target: TARGET, bytes: "v0", agent: "seed", at: "2026-03-04T01:00:00Z" });
+ seedNote({ target: TARGET, bytes: "v1", agent: "claude", at: "2026-03-04T02:00:00Z" });
+ atomicWriteFileSync(join(vault, TARGET), "drifted");
+
+ const reply = await call("brain_writes", { action: "plan_revert", path: TARGET });
+ const entries = reply["entries"] as ReadonlyArray<Record<string, unknown>>;
+ expect(entries[0]!["action"]).toBe("refuse");
+ expect(entries[0]!["reason"]).toBe("drift");
+ });
+
+ test("an unbounded selector is refused with the code, not an empty plan", async () => {
+ const err = await rejectedMcpError(
+ call("brain_writes", { action: "plan_revert", since: "2026-03-04" }),
+ );
+ expect(err.code).toBe(INVALID_PARAMS);
+ expect(err.message).toContain("unbounded_selector");
+ });
+
+ test("no apply reaches this tool: an --apply-shaped argument is rejected", () => {
+ const schema = tool("brain_writes").inputSchema as {
+ properties: Record<string, unknown>;
+ additionalProperties?: boolean;
+ };
+ expect(schema.additionalProperties).toBe(false);
+ expect(Object.keys(schema.properties)).not.toContain("apply");
+ expect(Object.keys(schema.properties)).not.toContain("digest");
+ });
+});
diff --git a/tests/mcp/frozen-refusal.test.ts b/tests/mcp/frozen-refusal.test.ts
new file mode 100644
index 00000000..14804d57
--- /dev/null
+++ b/tests/mcp/frozen-refusal.test.ts
@@ -0,0 +1,137 @@
+/**
+ * What an agent is told when the vault is frozen (who-wrote-what,
+ * Task C).
+ *
+ * The guard that refuses the write sits below the log module and cannot
+ * append an event without closing an import cycle, so the MCP dispatch -
+ * the one seam that knows both the refusal and the caller - is where the
+ * refusal becomes a structured error and a `write-refused` line. That
+ * makes the freeze auditable from the agent's side, which is the side it
+ * exists to hold.
+ */
+
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { freezeVault, unfreezeVault } from "../../src/core/brain/freeze.ts";
+import { resetFreezeMarkerCache } from "../../src/core/brain/freeze-marker.ts";
+import { listLogDates, readLogDay } from "../../src/core/brain/log-jsonl.ts";
+import { resetVaultIdentityPins } from "../../src/core/brain/vault-identity.ts";
+import { VAULT_FROZEN_REFUSAL } from "../../src/mcp/frozen-refusal.ts";
+import { MCPServer } from "../../src/mcp/server.ts";
+
+let tmp: string;
+let vault: string;
+let server: MCPServer;
+
+beforeEach(() => {
+ tmp = mkdtempSync(join(tmpdir(), "o2b-mcp-frozen-"));
+ vault = join(tmp, "vault");
+ mkdirSync(join(vault, "Brain"), { recursive: true });
+ writeFileSync(join(vault, "Brain", "_brain.yaml"), "schema_version: 1\n", "utf8");
+ server = new MCPServer({ vault });
+ resetFreezeMarkerCache();
+ resetVaultIdentityPins();
+});
+
+afterEach(() => {
+ rmSync(tmp, { recursive: true, force: true });
+ resetFreezeMarkerCache();
+ resetVaultIdentityPins();
+});
+
+async function createNote(path: string) {
+ return server.handleRequest({
+ jsonrpc: "2.0",
+ id: 1,
+ method: "tools/call",
+ params: { name: "brain_create_note", arguments: { path, content: "body" } },
+ });
+}
+
+/** `brain_status`'s structured payload. */
+async function status(): Promise<Record<string, unknown>> {
+ const result = await server.callTool("brain_status", {});
+ return result["structuredContent"] as Record<string, unknown>;
+}
+
+/** Every `write-refused` payload in the log, across every day and shard. */
+function refusals(): ReadonlyArray<Record<string, unknown>> {
+ const out: Record<string, unknown>[] = [];
+ for (const date of listLogDates(vault)) {
+ for (const entry of readLogDay(vault, date).entries) {
+ if (entry.eventType === "write-refused") out.push(entry.body);
+ }
+ }
+ return out;
+}
+
+describe("a write tool called on a frozen vault", () => {
+ test("comes back as a structured refusal naming the freeze and the way out", async () => {
+ freezeVault(vault, { agent: "@operator", reason: "migrating" });
+ const response = await createNote("notes/frozen.md");
+ const error = (response as { error?: { message: string; data?: unknown } }).error;
+ expect(error).toBeDefined();
+ const data = error!.data as Record<string, unknown>;
+ expect(data["code"]).toBe(VAULT_FROZEN_REFUSAL);
+ expect(data["by"]).toBe("@operator");
+ expect(data["reason"]).toBe("migrating");
+ expect(typeof data["frozen_at"]).toBe("string");
+ expect(data["next_command"]).toBe("o2b brain unfreeze");
+ expect(data["tool"]).toBe("brain_create_note");
+ expect(error!.message).toContain("o2b brain unfreeze");
+ // The refusal has to be a refusal: nothing may have landed.
+ expect(existsSync(join(vault, "notes", "frozen.md"))).toBe(false);
+ });
+
+ test("appends exactly one write-refused event naming the tool and the caller", async () => {
+ freezeVault(vault, { agent: "@operator", reason: "migrating" });
+ await createNote("notes/frozen.md");
+ const recorded = refusals();
+ expect(recorded).toHaveLength(1);
+ expect(recorded[0]!["tool"]).toBe("brain_create_note");
+ expect(recorded[0]!["reason"]).toBe("migrating");
+ expect(typeof recorded[0]!["agent"]).toBe("string");
+ });
+
+ test("records one event per refused call, so a retry loop is visible", async () => {
+ freezeVault(vault, { agent: "@operator", reason: "migrating" });
+ await createNote("notes/a.md");
+ await createNote("notes/b.md");
+ expect(refusals()).toHaveLength(2);
+ });
+
+ test("goes back to writing once the freeze is lifted", async () => {
+ freezeVault(vault, { agent: "@operator", reason: "migrating" });
+ await createNote("notes/frozen.md");
+ unfreezeVault(vault, { agent: "@operator" });
+
+ const response = await createNote("notes/thawed.md");
+ expect((response as { error?: unknown }).error).toBeUndefined();
+ expect(existsSync(join(vault, "notes", "thawed.md"))).toBe(true);
+ });
+});
+
+describe("brain_status", () => {
+ test("reports the freeze, and reports its absence just as plainly", async () => {
+ const open = await status();
+ expect(open["frozen"]).toBeNull();
+
+ freezeVault(vault, { agent: "@operator", reason: "migrating" });
+ const marker = (await status())["frozen"] as Record<string, unknown>;
+ expect(marker["by"]).toBe("@operator");
+ expect(marker["reason"]).toBe("migrating");
+ expect(typeof marker["frozen_at"]).toBe("string");
+ expect(typeof marker["device_id"]).toBe("string");
+ });
+});
+
+describe("an open vault", () => {
+ test("records no refusal at all", async () => {
+ const response = await createNote("notes/open.md");
+ expect((response as { error?: unknown }).error).toBeUndefined();
+ expect(refusals()).toHaveLength(0);
+ });
+});
diff --git a/tests/mcp/mcp.test.ts b/tests/mcp/mcp.test.ts
index 0777b87d..4e8a5323 100644
--- a/tests/mcp/mcp.test.ts
+++ b/tests/mcp/mcp.test.ts
@@ -220,6 +220,9 @@ describe("tool listing", () => {
"brain_query",
"brain_agent_query",
"brain_agent_diff",
+ // Recorded note writes: who wrote what, and what it replaced
+ // (who-wrote-what Task A).
+ "brain_writes",
"brain_doctor",
"brain_health",
// Unified operator status snapshot (source-pipeline-integrity O3).
@@ -762,7 +765,9 @@ describe("stdio loop", () => {
// + brain_design_note (one-shot design note grounded in tension,
// decision and truth records, salience-lifecycle-enrichment
// t_c87644b4) = 113.
- expect(list.result.tools.length).toBe(113);
+ // + brain_writes (recorded note writes, who-wrote-what Task A
+ // t_662f4e82) = 114.
+ expect(list.result.tools.length).toBe(114);
});
test("returns parse error for invalid JSON", async () => {
diff --git a/tests/mcp/owner-scope-refusal.test.ts b/tests/mcp/owner-scope-refusal.test.ts
index 86e2f7a8..96d4edba 100644
--- a/tests/mcp/owner-scope-refusal.test.ts
+++ b/tests/mcp/owner-scope-refusal.test.ts
@@ -66,8 +66,14 @@ const AGENT_ARG_NAME = "agent";
* hand-written list is the defect this release is about. The count is
* pinned so a tool joining or leaving the set is a decision somebody
* makes on purpose.
+ *
+ * 24 -> 25: `brain_writes` (who-wrote-what, Task A) declares `agent` and
+ * belongs to the same minority `brain_generation_reports` already sits
+ * in - it FILTERS by the identity rather than stamping it, because the
+ * identity on a note-write record came from `resolveAgentName` at the
+ * moment of the write and no caller can supply one after the fact.
*/
-const AGENT_ARGUMENT_TOOL_COUNT = 24;
+const AGENT_ARGUMENT_TOOL_COUNT = 25;
/** Tools that accept a caller-supplied owner scope, derived the same way. */
const AGENT_SCOPE_TOOL_COUNT = 13;
diff --git a/tests/mcp/removed-tools.test.ts b/tests/mcp/removed-tools.test.ts
index e13e220b..8865acf5 100644
--- a/tests/mcp/removed-tools.test.ts
+++ b/tests/mcp/removed-tools.test.ts
@@ -191,5 +191,7 @@ test("the shadow surface is gone: no hidden tools, removed names unlisted", asyn
// + brain_design_note (one-shot design note grounded in tension,
// decision and truth records, salience-lifecycle-enrichment
// t_c87644b4) = 113.
- expect(list.result.tools.length).toBe(113);
+ // + brain_writes (recorded note writes, who-wrote-what Task A
+ // t_662f4e82) = 114.
+ expect(list.result.tools.length).toBe(114);
});