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.
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, throughcreateNoteand the write-batch kernel) emits onenote-writelog event carrying a write id, the operation, the target path, the content hash before and after, the byte sizes, the caller-assertedagentand the server-derivedorigin_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 underBrain/.state/write-images/. A reader (listNoteWrites) pluso2b brain writesand MCPbrain_writesexpose the record;brain_agent_query/brain_agent_diffgain thenotecontribution kind. - Task B (t_1814b9bf) - the shard grammar, listing, sync-conflict exclusion and device-id resolution move out of
log-jsonl.tsinto oneledger-shards.ts, and the continuity store, idempotency ledger, preference audit, metrics and session-lineage ledger write<base>.<deviceId>.jsonland merge every shard at read. The doctor reports sync-conflict copies under every ledger directory, not only the log. - Task C (t_109fa94d) - a
frozenmarker atBrain/.state/frozen.json, carried by Syncthing to every device, refused by name at the one guard every content writer already passes (assertVaultIdentityForWrite), witho2b brain freeze [--reason]/o2b brain unfreezeas the operator verbs,freeze/unfreeze/write-refusedlog events, and the frozen state reported byo2b brain status,brain_statusandbrain_doctor. - Task D (t_924129c5) -
o2b brain writes revertandbrain_writesactionplan_revert: a plan over thenote-writeevents matching an agent, device or path selector and a time window; each target resolves torestore(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 underwithDestructiveSnapshot, and records each restore as anote-writeevent of operationrevert, 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,nullat genesis) andh(its own chain hash);verifyLogChainwalks every shard, treats lines withouthas legacy genesis-class, and reports the first broken link per shard by shard path and line number;o2b brain log verifyand alog-chain-brokendoctor 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
AppendOnlyLedgerabstraction 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).
agentstays a caller-asserted claim, assrc/core/write-binding/index.ts:11-25states; 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.
deleteapplies only when the earliest selected write on that target is acreatewith no earlier writer of record. - A
session_id/turn_idon 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.auditskips the freeze check and is passed by exactly two callers: the Brain log appender (throughbrainDirsForWrite), so thatfreeze,unfreezeandwrite-refusedevents 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
VaultFrozenErrorto a structured refusal (code: "vault_frozen",frozen_at,by,reason,next_command: "o2b brain unfreeze") and appends onewrite-refusedevent 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 (oneexistsSync+ parse on the hot path; cached per process by inode the waycurrentVaultIdis). 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.unfreezeremoves the file; the removal is a destructive-site entry whose recovery story is "the marker's whole content was its existence and theunfreezelog event records who removed it". - Rollback while frozen is refused.
restoreSnapshotpasses the guard once and is refused like every other content writer; the refusal nameso2b brain unfreezeas 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 literalabsentwhen the target did not exist),hash_after,bytes_before,bytes_after.agentcomes fromresolveAgentName()(the same resolution the write-binding docblock names; caller-asserted by construction),origin_channelfrom the appender, the device from the shard. Values are strings because the log payload contract isRecord<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 | nulland, 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](defaultWRITE_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 aSTATE_SURFACESrow. - Shard grammar extraction is byte-preserving.
ledger-shards.tsexports the grammar (<base>[.<shardId>].<ext>, shard id slug[a-z0-9-]{1,32}),parseShardedName,listShardedFiles,isSyncConflictName, andresolveAppendShardIdcarrying the documented legacy fallback fromAppendLogEventOptions.deviceIdverbatim.log-jsonl.tsre-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
createdAtthen shard id. Idempotency:lookupKeyscans all shards (a key remembered on one device is honoured on another once synced);rememberKeyre-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,seqper shard,readLineageLedgermerges byatthen shard id,verifyLineageLedgerverifies every shard and reports per shard path, the gaps sidecar shards the same way. - Doctor covers every ledger directory. The existing
sync-conflict-logsignal keeps its code and widens its sweep to the continuity, idempotency, preference-audit, metrics and.statedirectories; its detail names the directory. One exit, one meaning: "a sync conflict copy exists that no reader merges". - Chain shape.
renderJsonlLinegainsprevandhafterpayload:h = sha256Hex(canonicalJson({ prev, ts, kind, payload })),prev= thehof the last line in the shard that carries one (the appender already holds the shard text under the lock).readJsonlignores both keys, so no reader changes. Lines withouthare legacy: the verifier counts them asunchained-legacy, never as broken, and a chained line whoseprevisnullafter legacy lines is the genesis of that shard's chain. A line whosehdoes not recompute, or whoseprevis not the previous chained line'sh, 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_afterof the newest selected write on that target, elsedrift; no unselected write may sit between the oldest and newest selected write on that target, elseinterleaved; arestoreneeds the before-image of the oldest selected write, elseimage-missing.deleteapplies only when the oldest selected write is acreateand 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 besideappliedandrefused:failednames 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 mapsnote-writeevents to contributions of kindnotewithpath = targetandtitle = <op> <target>, sobrain_agent_query/brain_agent_diffanswer "which notes did this agent touch" with no new reader. - Snapshot reason
note-revertjoinsBRAIN_SNAPSHOT_REASON; the revert apply takes it throughwithDestructiveSnapshot, and the restore writes go through the same note-write record as any write, taggedop: revert. - No new MCP tool for freeze. Agents receive the refusal by name and
brain_statusreports the frozen state; unfreezing is an operator action and stays CLI-only. Revert apply is CLI-only for the same reason;brain_writesofferslistandplan_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
existsSyncper guarded write, ninety-eight sites. Cached per process by marker inode likecurrentVaultId; 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
seqand per-shard compaction keep the invariant "one chain per file" that the verifier already assumes; the merge order across shards isatthen 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.