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.
Design
Context
See proposal.md for the motivation and brainstorm.md for the chosen approach. Facts from the code and a live install (2026-11-06) that shape the design:
- Catalogue.
src/core/state/surfaces.ts(STATE_SURFACES, about 60 rows) already lists every state location the product keeps in the vault, with its tier and reason. It is the migration manifest. - Sharding.
src/core/brain/ledger-shards.tsalready shards append-only ledgers per device (<base>.<deviceId>.jsonl) and merges them on read in order (key, shard id, line). The new store generalises this pattern. - Device id. It lives in device-local config and is never synced (
src/core/config.ts). Nothing that every machine must agree on can live there. - Writes today.
- Signals are one Markdown file each (6.6k live).
- The log append (
log.ts) takes a directory lock, re-reads the whole day file and rewrites it atomically for every event, about 5k events a day per device. pinned.mdis written read-modify-write with no lock.- Preferences are Markdown files under per-file locks.
- Index.
brain.sqlitecan already be relocated (search_db_path). It holds vault-relative paths, and 6,655 of its 7,928 documents are signals. - Defects the move must fix rather than carry over:
.state/anticipatory/is never pruned (3,647 files, 305 MB).- Upgrade snapshots bypass retention (911 files, 1.7 GB).
- The dream pass has not run on the live install since 2026-05-24, which is why 6.6k signals sit unprocessed.
- Vault assumptions. Obsidian is required only by
.basefiles and by wikilinks used as record identifiers. Note tools (brain_create_noteand related) already refuseBrain/paths. - Outside readers. Skills (
skills/brain-memory,skills/open-second-brainand theplugins/codexmirrors), the MCP instruction segments, hook messages and the MCP resourcesosb://log/{date},osb://preference/{id}andosb://topic/{slug}hard-codeBrain/paths or the old meaning of "topic". The Python Hermes shim delegates to the CLI and needs no path logic.
Goals / Non-Goals
Goals:
- No Open Second Brain machine file in the vault after migration.
- One store folder (two with the
privatepartition) for the user to sync. - Same folded state on every machine.
- Reads that see a neighbour's record as soon as file sync delivers it.
- Context injection bounded by budgets.
- A brain that works with no vault at all.
Non-Goals:
- A server, relay or real-time channel.
- Encryption at rest. It is documented as the sync or disk layer's job.
- Changing the CLI or MCP tool contracts beyond new verbs and new optional fields.
- Rewriting in Rust. Formats must simply be easy to port.
- Changing how user notes are written.
- Multi-user brains: one user, several machines.
Decisions
D1. Store layout
<store>/
FORMAT.md format document (versioned, shipped)
shared/ partition, synced to every working machine
events/<device>/<YYYY-MM>.jsonl signals, evidence, notes, feedback
log/<device>/<YYYY-MM>.jsonl operational log, lifecycle, continuity
ledgers/<name>/<device>/<YYYY-MM>.jsonl idempotency, audit, metrics, receipts, lineage
topics/<device>/<YYYY-MM>.jsonl topic events
settings/<device>/<YYYY-MM>.jsonl shared settings (view writer, thresholds, migration records)
digests/<device>/<YYYY-MM>.jsonl state digests
blobs/<sha256[0:2]>/<sha256> large bodies, immutable
private/ same shape, for private-visibility records
shared/ and private/ are synced as separate folders;
the store root itself is never a sync folder
<device-local state dir>/ never synced: index, locks, caches, hook state,
snapshots, maintenance lease, freshen state
The device-local directory comes from the platform data directory (src/core/platform-dirs.ts), keyed by store id.
Alternatives:
- One shard per writer process, as the author first proposed. Rejected: process ids churn, so the shard count grows without bound.
- One shard per device per day. Rejected: about 30 times more files than monthly shards, with no gain.
D2. Appends
A record is one JSON line written with a single append (O_APPEND) call, under a device-local advisory lock on the shard. The lock is held only for the write and is never synced. Lines stay under a size cap; larger bodies go to blobs/. This replaces the full-file rewrite in log.ts.
On Windows the append opens with FILE_APPEND_DATA inside the same local lock.
Alternative: lock-free O_APPEND. Rejected because Windows append atomicity is not guaranteed for every size, and the local lock is cheap.
D3. Envelope and clock
Every record has this shape:
{ "v": 1, "id": <ulid>, "hlc": "<physical_ms>.<counter>", "device": <id>,
"agent": <name>, "kind": <kind>, "scope": <scope>, "topic": <topic id|null>,
"sum": <sha256 of body>, "body": { ... } }
- Fold order is (hlc, device, id).
- Clock rules. Standard HLC.
- Send: the physical part is the larger of the wall clock and the local clock; the counter increments on a tie.
- Receive: every catch-up raises the local clock to the largest clock it ingested.
- So a record written in reply to a remote record always folds after it, even when the replying machine's wall clock is behind. Skew of seconds is harmless at sync latency.
- As built (phase 2): reading is receiving. Every shard read raises an in-process floor for its store, and the next stamp for that store takes the receive rule over the floor first, so a write that replaces, removes or raises a record the operation read (a replacement, a tombstone, a privacy raise) folds after that record even when its device stamped it minutes ahead of this machine's wall clock. A stamp more than a day ahead is still not adopted.
- Readers skip an incomplete or checksum-failing last line and retry it on the next pass. A failing middle line is reported by doctor.
- Unknown
v: the record is skipped and doctor reports it.
D4. Folds of mutable entities
Preferences, pinned context, topic fields, assignments and settings are folds over records with precedence human > agent > decision model, then the later clock wins within an authority. Removal is a tombstone record.
- Preference counters (applied, violated) are derived in the fold, not written back. This removes the stale-counter class of bugs.
- The existing preference audit trail (
pref-audit.ts) becomes these records.
D5. Index
brain.sqlite moves to device-local state and gains three things:
- A watermark table per shard: path, file identity (inode or Windows file id), size, mtime, byte offset and a hash of the verified prefix. A changed identity, a size below the offset, or a prefix hash mismatch resets that shard to offset 0. The re-read is idempotent by record id.
- A
recordstable (id, stream, kind, scope, topic, hlc, device, agent) beside the existing documents and chunks. - A source column that separates brain records from user notes.
Catch-up runs before reads: stat each shard, then read only from the stored offset. Stats are throttled to once per second per process, and a directory listing is cached by directory mtime. The phase 1 benchmark (500 shards, nothing changed) must stay under 20 ms. The change probe ("what is new since W") is an index query, not a file read.
A full rebuild uses the existing brain.sqlite.new and swap path.
D6. State digests
Digests are computed per partition over an explicit cut. A cut is a vector of (shard, record count, last record id) for every shard the machine holds in that partition, excluding the digests stream itself, so publishing a digest never changes the cut being compared.
After catch-up, a machine writes a digest record carrying the cut and a hash of each fold computed from exactly those records. Doctor compares only digests whose cuts are identical, so idle devices, offline devices and machines without a partition never produce a false alarm or a stall.
Roster: the devices with records in the partition during the last 30 days, minus devices retired by a device-retire human record. Doctor reports a roster device that has published no digest for 7 days.
D7. Human view: one configured writer
One writer. The human view and topic-creating dream steps have exactly one writer device, the view writer. It is named by a view-writer human settings record in the shared partition, so every machine agrees on it.
- The first machine that migrates or initialises the store records itself as the view writer.
o2b view writer --heremoves the role in two steps:- It records a
view-writer-request. - The current writer sees it at its next catch-up, finishes any render in progress, and records
view-writer-released. - The new device renders only after it has caught up on that release record.
- It records a
--forceskips the release when the old writer is unreachable, with a warning that a still-running old writer may write pages once more before it catches up. The old writer always catches up before rendering, so it stops at its first render after the change reaches it.- When two machines initialise a store at the same time, the claim with the lowest (clock, device) wins once both claims sync. The loser has written no pages, because a fresh writer waits one full catch-up after its claim before its first render.
- Another device never writes view pages, even when the writer is offline. Pages then go stale, but no data is lost.
- Doctor on every machine reports a view writer that has published nothing for 3 days, and names the command to move the role.
Alternative: an expiring lease that passes the role on automatically, as the partner first proposed. Rejected by the review: delayed file sync cannot make a lease exclusive, so two holders could render different record sets into conflicting copies of one page.
Render protocol on the writer:
- Catch up.
- For every page, compare the file on disk with the checksum in the last render record.
- A mismatch is a human edit. Three-way merge it with the base (the last rendered text, kept as a blob referenced from the render record), the file on disk and the new render. Store the user's changes as human records before rendering.
- Render to a temporary file and check the page checksum once more right before the rename; if it changed, go back to step 3.
- Write a render record (page, checksum, base blob).
No silent loss. A phone edit that lands between the last check and the rename could be overwritten, and not every sync tool makes a conflict copy. To keep that edit recoverable:
- Before every rename the writer stores the on-disk bytes it replaces as a blob, kept for 30 days.
- After the rename it re-reads the page. If the replaced bytes differed from the base, it ingests them as a human edit and renders again.
- A sync-conflict copy of a page, when the tool makes one, is ingested the same way and then removed.
o2b view recover <page>lists the replaced versions.
Promise to users: an edit is never silently lost. An edit that races a render may arrive one render later.
Pages. about-me.md (the profile page), history/<YYYY>-W<ww>.md, decisions.md, reports/<slug>.md, sources/<slug>.md and topics/<date>-<slug>/topic.md.
- Each page has one HTML comment line with its store id.
- There is no frontmatter and there are no Obsidian-only links.
- Generated prose uses
view.language(a shared setting); quoted text stays in its original language.
D8. Topics
A topic is a record family with an immutable topic_id (ULID). Topic events:
topic-create,topic-rename,topic-status,topic-goaldecision,open-question,question-resolvedlog-entry,milestone,milestone-doneassign,unassign,merge,split,link,undo
Page schema: title, one-line description, status, goal, milestones, decisions, open questions, log (newest first), related. Decisions use one plain list with "serves" links where they help. The office prior art's four groups (Need, Surface, Internals, Method) are left out of version 1 because they fit engineering topics but not personal matters.
Code naming:
- The new entity owns
topicin code, the CLI and MCP. - The existing preference slug becomes
ruleTopic/rule_topicin code; the persistedtopicfield on signals keeps its name for compatibility and is read asrule_topic. - The resource
osb://topic/{slug}becomesosb://rule-topic/{slug}. The old name is kept as an alias for one minor version, and the newosb://topic/{id}serves topics.
D9. Automatic and requested topic actions
Only the view writer runs the topic-planning step of dream, under a device-local exclusive lock, so neither two machines nor two processes on the writer create the same topic twice. Dream assigns unassigned events to topics and creates a topic when at least N related unassigned events (default 5) from at least two sessions fall in one scope. Assigns and creates apply at once; each is listed in the dream report and can be undone with one command. Merges and splits are only proposed, in briefs and the digest, until the user confirms.
A topic created by request on another machine gets a fresh id there. If the planner later sees a near-identical topic, it proposes a merge (topic_same) and never merges silently.
Requested actions come through MCP tools (brain_topic, with actions create, assign, rename, status, merge, split, archive, undo) and the matching CLI verbs. A CLI verb is recorded as a human record (the user runs it), except o2b topic record, which writes an agent record unless --as-human. brain_topic writes agent records unless the caller names human on the user's explicit request, which is refused below local reach (D18 item 5).
D10. Decision-model uses
All uses plug into src/core/decision-model/ with modes off, shadow and enforce; every use is off by default.
| Use | Question | Deterministic fallback | Where it runs |
|---|---|---|---|
topic_route |
which active topic, or none | scope match plus lexical similarity over topic heads | writer, at record time |
event_kind |
decision, open question, log-worthy or routine | the kind the agent passed; otherwise routine | writer |
human_readable |
belongs in history or not | only records the agent flagged significant | renderer |
topic_new |
does this cluster deserve its own topic | count and session threshold | dream |
topic_same |
are two topics one topic | none (no proposal) | dream, reuses pair-verdict |
question_resolved |
does this record answer q{n}, and which one | none | dream |
milestone_done |
does the milestone look done | none | dream (proposal only) |
head_select |
which topic heads to inject | recency and scope ranking | session start (reuses recall_inject) |
neighbour_relevant |
does a neighbour's record matter to this task | same topic id and kind decision | before a turn |
- Verdicts stored once. A verdict is stored in the record it decides, with model id, version, mode and confidence. Folds read the stored verdict and never call a model, so machines converge.
- Private data stays local. Uses that read
privaterecords refuse a hosted provider unless the user opts in per use.
D11. Migration
The command is o2b brain migrate-store [--dry-run] [--resume] [--rollback]. o2b upgrade offers it, and doctor and status report it. It never runs without consent.
Order of work on the first machine:
- Preflight. Config, free disk, no other migration running, store root outside the vault, and the device roster of the legacy tree. The roster is every device id found in legacy shard names during the last 30 days; the report lists them.
- Quiesce this machine through a device-local migration gate, not the synced fleet freeze marker (
freeze-marker.tsis shared across machines).- Every writer takes a shared lock on the gate file in the device-local directory for the length of each write.
- The migration takes the exclusive lock. It waits until in-flight writes drain, then holds the lock to the end.
- Writers that find the gate held refuse with a "migration in progress" message.
- The phase 2 test runs several writer processes against one migration.
- As built (phase 2): the gate is one device-local file, checked by the vault write guard every content writer passes, so a write that starts while the gate is held is refused. A write already past the guard when the gate closes is not waited for by a lock: a settle period after closing the gate lets it finish, the final delta pass imports what it left, and the transition import (D11a) picks up anything that lands later. No per-write shared lock is taken.
- Back up.
- Take a snapshot of
Brain/through the existing snapshot path. - Make an explicit backup of every non-rebuildable
.open-second-brain/surface.STATE_SURFACESmarks secrets, keys, attestations, ingest and import checkpoints and lockfiles; the snapshot path excludes them today (path-constants.ts:188). - Each backup is verified by a restore into a temporary directory.
- Take a snapshot of
- Map. Walk
STATE_SURFACES. Each surface maps to a stream, a blob, device-local state, or "drop" (derived caches only). An unmapped surface fails the dry run. - Convert.
- Signals become
eventsrecords, using their originalcreated_atas the clock's physical part. - Log JSONL lines keep their hash chain inside the body.
- Preferences become seed records plus their audit history.
- The journal is per item, and per line for append-only files: (device, source path, line or item, checksum, record id). Matching uses the whole key, never the checksum alone, so two distinct legacy records with identical content stay two records.
- Signals become
- Final delta pass. Re-scan every source and import whatever changed or grew since its journal row. Repeat until a pass imports nothing.
- Verify every journal row against the store.
- Render the minimal human view (see D13 phase 2).
- Switch. Record
migration-donein the shared partition, carrying the per-partition cut of what was imported. Lift the freeze; writers now use the store only. - Leave the legacy tree in place, read-only to this machine, until every roster device has switched (D11a).
D11a. Mixed versions.
- Upgraded machines import late writes. A machine still on the old release keeps writing into the legacy tree, and sync delivers those files to upgraded machines. Upgraded machines import them line by line through the journal: new or grown lines only.
- When the legacy tree leaves the vault. At preflight the first machine records a durable migration cohort: every device id found anywhere in the legacy tree, with no age window. The tree leaves the vault only after every cohort device has written
migration-doneordevice-switched, or has been retired by a human record, or the user passes--force(the report names the devices that will stop receiving data). A device that stays offline for months keeps the tree in place until one of these happens. Then the tree moves to a dated archive in the device-local state directory. It is never deleted automatically. - Until then doctor on every machine lists the devices still on the legacy layout.
Later machines.
- A later machine waits until its catch-up holds every record of the
migration-donecut for the partitions it holds, which protects against the record arriving before its data. A partition it does not hold is skipped and named in its report. - It then runs the same pipeline over its own legacy files, because they may hold records the first machine never saw. The journal skips anything already in the store by checksum.
- It backs up and moves its own device-local surfaces, then writes
device-switched.
Rollback (--rollback, per machine, until the legacy tree leaves the vault):
- Freeze this machine.
- Restore the snapshot and the explicit backups.
- Replay into the legacy layout every store record whose stable identity (record id, or the legacy key for imported records) is absent from the restored tree. That includes remote records that arrived after the snapshot. Replay runs in fold order through legacy exporters for signals, log events, preferences, pinned context and notes, is idempotent, and can be resumed through its own journal.
- Record kinds with no legacy form (topics, view renders, digests) stay in the store and are listed in the report.
- Switch config back to the legacy layout and lift the freeze.
- As built (phase 2): a rollback is per migrated vault. The backup records the vault it was taken of (identity marker, else the real path), and a rollback for any other vault is refused before any file is touched. A vault a switched machine only imported through the transition (D11a) has no backup of its own and needs none: the transition never writes into its legacy tree. The transition binds such a vault only when nothing was held back and its operator settings,
_permissions.yamlincluded, were imported without a conflict with the stored document. - As built (phase 2): the same held-back rule gates the removal of the legacy tree (D11a). While the transition import holds an item back for a partition this machine does not hold, the removal refuses, names the count and the partition, and
--forcedoes not override it, because a rollback is refused once the tree has left the vault. A migration killed after its switch record is finished only for the vault it migrated (compared as a rollback compares it); a vault configured since stays unbound and goes through the transition's own checks. - As built (phase 2): the journal keys every import by the vault it came from as well (identity marker, else the real path, compared as a rollback compares them; the store holds only a hash of the path), so an identical item at the same path of a second vault gets its own record. Rows and records written before carry no vault and count for the first vault this machine migrated, never for another. The migration, and the transition that binds a vault, record the automatic import's legacy-file watermark from the stamps taken before their final delta pass; with no watermark the automatic import runs and the journal decides what it still lacks.
- As built (phase 2): a dual-written copy stands in only for an item of the vault it was dual-written from. The content match leaves the vault out, so the pool checks it: a copy whose
vault_idnames a marker counts only for the vault with that marker, and a copy with none counts only on the device that wrote it, for the vault that device migrated. An identical item of another vault, or one whose unmarked copy another device wrote, gets a record of its own: a duplicate, never a merge. - As built (phase 2): a path is device-local, so the migration (first and later machine) gives a vault without an identity marker its marker before it writes any journal mark, and the marker reaches the other machines by sync. A mark from another device proves a vault only by its marker id; a mark that names a path alone, or no vault, counts only on the device that wrote it and only for the vault at that path. A later machine whose vault has no marker, while another device's migration named its vault by one, waits for the marker to arrive instead of minting a second one; for a vault that is a different one,
o2b brain initgives it its own. The transition on a switched machine writes nothing into a vault's legacy tree (item 1 of D14), so it creates no marker: a vault it imports without one gets path-only marks, and another device imports its own copy of those items rather than merge them with another vault's. - As built (phase 2): a data path that ends in a step a later run cannot take back reads the store completely or not at all. While any held shard (the
digestsstream aside) is unreadable, gone since this machine read it, or read only in part, the rollback refuses before it touches anything and again before its restore, names the shards, and keeps the switch; the removal of the legacy tree refuses (a partial shard only without--force, as for asettingsshard); the transition imports a vault configured after the switch but does not bind it and names the shards; and the migration refuses in its preflight and again before its switch steps, so the machine stays on the legacy layout. - As built (phase 2): the rollback matches what the restored tree already holds per vault, by the journal's rule: a
migratedmark counts as restored only when it names this vault, and a dual-written copy stamped with another vault's marker is never matched by content. Another vault's occurrence of an identical item is written back beside this vault's. A copy that names no vault keeps the content match, so a peer's dual write from before the marker is not written back twice.
Doctor reports legacy directories that reappear after the tree left the vault, with the writer when known.
D12. Path discovery
o2b store path (JSON: store root, partitions, device state dir, view target) and an MCP field in second_brain_status replace hard-coded paths. Skills are rewritten to name tools and commands only, and plugins/codex mirrors are regenerated with bun run sync-plugin-mirrors.
D13. Phasing
The change ships in four releases, each one PR carrying its own version bump, CHANGELOG entry and docs:
- Store core: layout, envelope, appends, folds, digests, index catch-up. Writes go to both the store and the legacy tree behind a flag that is off by default. The defect fixes (cache prune, snapshot retention, log append, pinned lock) ship here.
- Migration, the vault-free mode and the minimal human view: the view writer, the render protocol and the pages
about-me.md,history/anddecisions.md, so the preferences that leave the vault have a readable replacement on the same day. - Topics, plus reports and sources pages.
- Decision-model uses and agent-context budgets.
D14. Store-only mode: answers the phase 2 inventory raised
The inventory for task 2.10 (316 modules reach the legacy tree) raised questions the decisions above did not settle. They are settled here so the work can split into parallel packages.
- Switch. A machine is store-only once it holds its own
device-switchedrecord (D11, D11a); a fresh install with no legacy tree is store-only from the first write, ando2b initrunso2b store init. In store-only mode a store failure fails the operation with the reason and the remedy; nothing is skipped silently. Hooks and other fail-open paths log the failure to the device-local hook audit and continue. As built (phase 2): the switch is sticky per machine. The migration and the fresh-install switch record it in a device-local marker as they switch the device, and from then on the marker alone answers switched: asettingsshard that is absent or unreadable while sync delivers it never sends the machine back into the legacy tree, and every check of whether this device switched (the migration's preflight, the rollback, the automatic import, the status block, doctor) reads the same marker. Only a rollback clears it. The removal of the legacy tree refuses while anysettingsshard ofsharedcannot be read, since a cohort record or a peer's switch in it would be missed. - Record lanes with no record kind (decisions, obligations, pledges, theses, tensions, gap tasks, attention flows, entities, procedures, procedural memory, skill proposals and benchmarks, captures, clusters, bridge proposals, triggers, handoffs, dead-ends, personas, write sessions, foresight, dream staging, architect projects, the profile page, report snapshots): one generic kind,
lane-entry, with the lane name, a stable entry id, the structured fields the page carried in frontmatter and the Markdown body. Entries fold by id under D4. Their tools read the fold and work with no vault. Pages for people come from the view (phase 2decisions.md, later phases for the rest), never from these records' old files. - Settings. Each
_brain.yamlkey is classified once: keys about one machine belong in device config; keys every machine must agree on become shared settings records (D1,fold-settings). Migration imports the changed shared keys of_brain.yamlas records and writes the changed device keys into the machine config as<key>: <JSON value>lines, never over a key the config already sets (the user's value stays), and reports what it wrote and what it kept, so a device key does not fall back to its default on the switched machine. A single reader returns the folded settings with defaults; the 39 readers call it._permissions.yamlis a shared setting too:permissions.documentholds its text, only the operator (human authority) sets it, the migration imports the file, and every gate reads the setting first and falls back to the file only on an unswitched machine where the setting is unset; doctor warns (permissions-legacy-only) when deny rules sit in a legacy file no gate reads. - Standing rules are human-authored:
lane-entryrecords in lanestanding-rulewith authorityhuman. A view page for them comes in a later phase; until then the CLI and MCP tools edit them. - Signal lifecycle. Moves between inbox folders become
signal-stateevents (consumed, archived, retired, expired, staged, approved, rejected) keyed by signal id; the signal fold gives the current state. - Backup-class surfaces (secrets, signing keys, checkpoints, lockfiles) live in the device-local state after migration and are never synced; migration backs them up explicitly (D11). Attestation records are shared records; the keys that sign them stay device-local.
- Digests.
active.mdandlessons.mdare rendered on demand for hooks and MCP resources, with a cache in the device-local state. They are not view pages. - Vault adapter. One module, active only when a vault is configured, owns everything Obsidian-specific:
.basefiles for user notes, wikilink audits and the note tools' vault requirement. No.basefile queries store data; view pages carry no frontmatter for one to query. - Snapshots after migration cover the device-local state. The store needs none: shards are append-only with per-record sums and partition digests (D6). The migration snapshot (D11) covers the legacy tree until removal.
- Integrity. Legacy day-file hash chains stay verifiable by the legacy reader. Store integrity is the record sums plus partition digests over cuts; there is no per-record chain.
- Derived ledgers (rollup ladder, cross-topic) are device-local and recomputable; machines need not agree on them.
- Exports (
export, knowledge pack, OKF, bundle) read the folds and may keep the legacy layout as an interchange format. They are exporter modules for the 2.10 grep. - Write guard. In store-only mode the vault identity guard is replaced by the store identity check (store id and device id bound in the device-local state); the freeze marker is device-local and still holds every content write (lane pages, settings, schema applies), with or without a vault; a migration gate left naming the vault is a leftover of the migration that switched the machine and refuses nothing. Note tools keep the vault identity guard through the adapter.
- Vault filtering. Store reads do not filter by
vault_id(one brain across vaults, D1);vault_idstays as provenance. The search index lives in the store's device-local state, one per vault (keyed by a hash of the vault's real path), and is keyed by the store id when no vault is configured. - MCP tokens move from per-vault files to device config, so a server with no vault still enforces them; migration copies them. As built in 2.10 only the read side has moved: the transport reads
mcp-tokens.jsonbeside the machine config when it exists (with or without a vault) and otherwise the per-vault file (src/mcp/token-source.ts). The migration copies the per-vault file there (never over a device copy already present), and a rollback removes that copy again (or sets it aside when it changed since), so the per-vault file is the token map once more. On a switched machine minting, rotation and revocation write the device-config copy too (starting from the per-vault map when no copy exists yet), with the custody audit in the store, so a token minted after the switch authenticates with or without a vault. - The 2.10 checks. The test preload configures no vault; tests that need one create it. The grep is an architecture test with an allowlist and a reason per entry, covering the
Brain/literal and"Brain"path segments in code, not comments; comments are updated by the package that owns the file. - Note-tool walls that refuse
Brain/paths stay until the legacy tree is removed (D11a) and count as legacy modules. - Privacy judge. Once switched, reference privacy reads the preference and signal folds, not legacy pages; a reference the folds cannot resolve still counts as private (fail closed).
As built (phase 2): a write that replaces an existing store-backed entry (a lane page or file, a tension transition, an entity merge or label prune, an exact-state aspect) keeps the strictest partition of the entry it replaces: an entry that lives in
private, or whose fields reserve it, stays private whatever the new content says. No agent overwrite lowers a partition; an entry becomes shared only by removing it and writing it anew. As built (phase 2): a tombstone carries no content, so it goes to the partition of the entry it removes whatever the rest of its operation is, and no enclosing verdict raises it; this is the one exception to one partition per operation. A folder move or removal places each entry and its tombstone in that entry's own partition (a moved entry can still be raised, never lowered), so a device that holds onlysharedsees a shared entry leave a mixed folder. A write that raises a shared entry toprivate(a lane page or file, an exact-state aspect) writes the entry's shared tombstone first in the same store write, so a device that holds onlysharedsees the entry go and a device that holds both reads the private value. As built (phase 2): a store read whose answer decides a protection fails closed when it cannot see a shard it should consider. A shard counts as unseen when it cannot be read, or when this machine read it before and it is gone now: every stream listing records the shards it saw in a device-local ledger per store (seen-shards-<root hash>.json), and a shard the ledger names that the listing no longer finds is reported as unreadable, unless acompactedrecord replaced it or a human retired the device that wrote it. On an unseen shard a lane or exact-state write is judged private (refused on a machine withoutprivate), an exported lane entry counts as private, the capture boundary captures nothing, the permissions gates refuse, an agent settings write is refused (settings_unreadable), a signal removal refuses, the brain settings readers throw instead of answering defaults, and the decision ledger throws instead of answering "never gated". Doctor reports each unseen shard by its path (store-shard-unreadable). A shard read only in part counts as unseen too: one that holds a record whose body blob has not arrived, or a bad line in the middle (a checksum or envelope that does not verify, a record of a newer format). Its readable records are still read, and no fold cache keeps a read over an unseen shard, so the fold is read again once the blob arrives even though the shard did not change. Two cases are not gaps: the last line held back while an append is still arriving (the existing reading rule), and a line torn by a crash and closed by the next append, recognised as a JSON object cut short and never a record any machine read. The removal of the legacy tree refuses on asettingsshard read only in part unless--force, since such a line may never read again; doctor's shard check does not report a partial read as an unreadable shard. On a machine the sticky marker names switched, a store that cannot be opened (store.jsonmissing or corrupt) or that no longer shows itssharedpartition is unseen as a whole, never "no store, no rules": the permissions gates refuse, the brain settings readers throw and capture closes, an agent settings write is refused (settings_unreadable), lane and exact-state privacy is judged private, a signal removal refuses, and the decision ledger and the attestations refuse to read as empty. A machine that never switched still reads "no store" as nothing stored. The partitions a machine holds are sticky the same way: opening a store for writing ando2b store initrecord, in a device-local list per store root, every partition this machine holds, and a listed partition whosestore.jsonis now missing makes the store unopenable by name. On every store-only machine (switched, or with no legacy tree) every protection reader then fails closed as for an unopenable store, so a private lane entry is never read as shared because its partition's identity file went away; every store write refuses, and doctor names the partition (store-partition-lost, an error). A machine that never held a partition (set up with--partitions shared) keeps working with the partitions it has. No command takes a partition off the list: the remedy is to restore itsstore.jsonfrom sync or a backup.
D15. Phase 3 store follow-ups (tasks 3.9, 3.10, 3.11, 3.18, 3.21)
- Lane entry ids (3.9). The path rule of
store/lane-paths.tsis a bijection on the paths it accepts: a path names an entry only when that entry turns back into the same path, and every other name is refused with its reason. A page whose name without.mdreads as a kept file (x.json.md) keeps its whole name, so it no longer takes the id ofx.json. A user's top folder spelled otherwise than its lane name (My Notes/,project_x/: case, spaces, other separators) is not refused by the migration: its pages are imported under the normalized lane, with the original path in themigratedmark, which is where a rollback writes them back; two folders that take one lane are refused, both but the one spelled as the lane, and doctor names such folders before a migration (lane-folder-unimportable). Refused are a file with another extension or none, a top folder that is not a lane name or is the lane name of another folder (exact-state,brain), and the place of a root file with a lane. A store-only write of such a name refuses, and the migration lists it as an item it could not convert (archived with the other unparseable items) instead of filing it under an id that names another path. Refusal was chosen over an escaped encoding for these names: none of them is written by a writer of this tool, and an encoding would change the ids of entries already in stores. An earlier release did file a migrated pagex.json.mdunderx.json: a store-only dream pass runs a repair (store-migration/lane-id-repair.ts) that moves such a record, recognised by the legacy path in itsmigratedmark, to the id its path maps to now, and gives the old id back the latest record that is not the page's (the filex.json), with at least the authority of the page record it replaces, or removes it. The page is written under its new id only when that id has no history at all, so a page removed after its repair stays removed. Every moved or restored record keeps the body it copies, itsmigratedmark included. The repair runs only on a machine that holdsprivate(one without it cannot see a file's own record there and would remove the file's id over it), and once per store on a machine: a device-local marker records a finished pass that read every shard in full, with a stamp, taken before the read, of theeventsshards other devices write, so a later pass reads the stream again only once another machine's records arrived, a late import of a machine still on the earlier release included, and never for this machine's own writes. A pass that met an unreadable shard, one gone since it was read, or a pending blob writes nothing at all (it may have missed the file beside a page, or a removal) and runs again. The page's value and the old id's own value are each resolved as the register resolves them (authority, then fold order), never taken from the latest record. Each record lands in the partition of the record it copies; a file restored inprivateover a page that lives insharedalso removes the page fromshared, and a removal the move into an id replaces is kept when the move lands in another partition, so a machine that holds only one partition never keeps a stale page. The plan is written only once a read right before the write finds the same lane records, and made again from that read otherwise. The old id's own state counts its removals: a file removed before a page was filed over it stays removed. A page whose own id holds only a page filed there from the id after it (x.json.md.mdunderx.json.md) takes that id in the same pass, which moves the other page on. On a store where no machine holdsprivatethe repair never runs, so doctor reports mis-filed ids on every machine (lane-id-misfiled; it names only the repairs of pages the caller may read, below local reach only those no record of theprivatepartition takes part in, with one remedy whatever the machine holds, and the legacy-folder check states its finding by name only, with no names or counts), naming them and the remedy: a dream pass on a machine that holdsprivate, or adding the partition on one witho2b store init --partitions shared,privatefirst. The old id's tombstone or restore is appended before the page's new record, and the rollback exporter writes an entry back to the legacy path of amigratedmark only when that path names the entry under the current rule (or names no entry the rule maps, a blob lane's file or a respelled folder), else to the entry's own path, so a rollback after a repair leaves both files at their own paths, and a lone page the snapshot restores is never removed by its old id's tombstone. - Procedural counters (3.10). The usage counters of procedural memory (
usage.jsonl: uses, last use, successes, failures), the procedural graph and the recall hints are machine state, at their vault-relative paths on an unswitched machine and in the device-local state once switched, like the claim graph and the rollup ledger (D14 item 11). A use or an outcome rewrites only the usage file, so a usage tick appends no store record. Every read-modify-write of the usage file (a tick, an outcome, the reconcile that moves an index's counters into it) runs under the file's write lock and reads the file again inside it, so a reconcile in one process never drops a tick another process counted. A reconcile moves the counters an older index carries into the usage file before it rewrites the index without them, so a rebuild that fails afterwards leaves them in the usage file. A first adoption of the stored usage record is written under the same lock, only while the file is still absent. The index stays a sharedlane-entryand is written with its counters at rest; a reader takes the counters from the usage file and falls back to those an older index still carries, and the next reconcile writes them into the usage file. The migration movesusage.jsonlinto the device-local state (adevice-localsurface) and drops the graph and hints, which each machine recomputes. Counters are per machine from then on: they rank procedures for the machine that uses them, and machines need not agree on them. A machine switched before this change holds the three files aslane-entryrecords only: a reader with no machine-state copy yet reads that record and adopts it into the machine state on the first read, writing no store record, so the graph, the hints and the counters answer before the next reconcile. The records stay until the legacy tree leaves the vault, because a rollback replays post-switch records into the legacy tree and a tombstone would remove the legacy file they came from; the removal of the legacy tree, after which no rollback can run, adopts them on its own machine and then tombstones each one whose copy this machine now holds (store-migration/retire-adopted.ts); one it could not adopt (its device-local folder refused the write) or whose tombstone could not be written stays live, the one copy there is. A rollback before that loses only the counter ticks counted after the switch, which live in the device-local state; the legacy files come back from the snapshot. A machine that never read the records before their tombstone arrives rebuilds the graph and hints on its next reconcile and starts its counters from those its index carries. - Schema apply attestation (3.11). Of the two options, the audit row moves: a store-only apply writes it to
shared, the partition of thebrain.schema.*settings records it attests, so a machine that holds onlysharedfinds the digest the pack must match and reports another device's apply as attested. The other option, accepting the newest settings records as attested, was rejected because it would accept any settings write to a schema field as an audited apply, which is exactly what the integrity check exists to tell apart. Thereasondoes not belong on the shared row: it is free text an operator wrote, and audit rows have always stayed inprivateon a machine that holds it. So the shared row carries what attests the pack (actor, time, target, count, digest) and the mutation list, which the sharedbrain.schema.*records hold anyway, and the whole row, reason included, goes toprivateas every audit row does when this machine holds it; on a machine that does not, the shared row keeps the reason, the exposure such a machine always had. One privacy verdict covers the batch and the reason: a private page named (the rule every audit row is judged by) or a<private>region; when it holds, the shared row keeps only the attestation and says the mutations were withheld, so an apply whose reason the store would move toprivateis still attested inshared. - Private evidence (3.18). A private
apply-evidenceevent never changes a shared preference's status, confidence, evidence timestamps or evidence sections, which dream writes tosharedfor every machine and remote caller; it counts toward a preference that is itself private. Every number derived from evidence that lands insharedfollows the same rule: a merge copies each private evidence record of the drop as a private record (each copy keeps its source's partition), and its sums count a private use whenever the keep it lands on is private, and the shared and the private copies are written as two store writes, one per partition, since one write lands in one; the merge's log event and audit trail carry the sums of the shared evidence for a shared preference; dream compares a preference's counters against the ones the scan would count, so a shared preference with private uses settles instead of being rewritten every pass. Apreference-evidencerecord inprivateno longer makes its preference private (before, the first private use moved the whole preference intoprivateon this machine, where every later write followed it). The counters fold the partitions a machine holds, so a local caller on a machine that holdsprivatesees its own private uses counted: that is the local view the event may affect, and it is never written back. A caller below local reach is shown the counters a machine that holds onlysharedfolds: each preference of the store fold carries both, and the MCP server runs every tool call and resource read of a remote transport in an ambient scope (store/caller-reach.ts) that the preference facades and the rebuilt preference pages read, so the MCP tools, thebrain_contextdigest, the operator snapshot and the review candidates all answer with the shared counters there. The device-local digest cache is always rendered with nothing withheld, since only local readers are served it; a remote caller gets its own render. - Seen-shards ledger (3.21). Every read-modify-write of the ledger runs under the device-local lock of the ledger file and re-reads it inside the lock, so a tracking read and a partition leave in two processes never undo each other. The lock guards the ledger alone and takes no other lock inside it, so a reader that holds a store lock may take it; a tracking update waits at most half a second and then skips, which only delays tracking to the next read, a skipped change stays queued in the process, counts as seen in its next listings (so a shard it names is still reported once gone) and is written with its next update, which a listing with nothing new also tries (a change for a partition the machine no longer holds is dropped then, and a partition leave drops its own process's queue for that partition), so a skip delays tracking, it does not drop it; and after a skip behind a lock one holder has kept the whole wait and longer (a crashed process's) the process leaves the ledger alone for ten seconds without waiting, so such a lock costs a hook one wait, not one per listing, while a lock other processes take and release in turn backs nothing off, whatever its directory's stat says (a released lock directory can linger with its old stat on Windows); the leave waits the full lock budget and refuses as before.
D16. Topics as built (phase 3, tasks 3.1 to 3.3)
Details the specs leave open, settled for the first part of phase 3:
- Identity and envelope. The topic id is a ULID minted by the writer of the
topic-create, carried in the envelopetopicof every topic record (all in thetopicsstream); the first create in fold order fixes the scope (personalorproject:<project>, also the envelopescope) and the creation time, and a second create of the same id only offers its title, description and goal to their registers. A non-topic record belongs to the topic itsassignnames, else to the topic its envelope names (topicOfRecord). - Items. Decisions, open questions, log entries and milestones are list items keyed by an
itemid (the creating record's id when it names none). Each item, its owner topic, a milestone's completion and a question's resolution are registers;removed: trueis an item's tombstone. A record that names an existing item with another kind is rejected. A log entry carries aclass; onlyroutinestays off the page, andnoteis a line the user wrote into the log section. - Undo. An
undovoids the record it names when its authority is at least that record's, and can itself be undone; an undo cycle (only a forged one) is cut where the walk in canonical record order meets it again, so its outcome is deterministic on every machine. An undo of anassignand anunassign, by the user or an agent (not by a decision model), record a blocked route, which the dream planning of task 3.4 reads so it never routes that record to that topic again. - Proposals. A goal offer that comes after the winning goal and loses to it is a proposal, rendered as an open question attributed to its agent (spec "User rewrites the goal"). A
milestone-donecounts from the user, or from an agent withevidence; one from a decision model or from an agent without evidence is a "looks done, confirm" proposal. A modelquestion-resolvedis a "looks answered" proposal. - Merges and splits. A merge resolves the merged topic to its target (
canonical), applied in fold order of the winning merge records, skipping one that would close a cycle or names a topic that does not exist; the target's page carries both topics' items and names the merged one in its related section, and the merged topic's page is removed. A split moves the listed items (their owner register) and record assignments. Both are written only on the user's confirmation (D9), so they carryhumanauthority in practice; the fold applies them by the usual precedence. - Partitions. A write is one store operation in one partition (
topics/write.ts):privatewhen asked, when atopic-createin it has the personal scope and the caller did not ask forshared(spec brain-store "personal-scope topics SHALL default to private"), or when any topic it names lives inprivate, so a private topic's events never land inshared. The writer judges this from every partition the machine holds whatever the caller's reach, and refuses when a topics shard cannot be read in full. A topic is private when its firsttopic-createsits inprivate; an item is private when any of its records does. A caller below local reach foldssharedalone (topics/read.ts). - Private topics stay off the view. The view renders from
sharedrecords only (phase 2), so a private topic, an item created inprivate, any record written toprivateand a shared record that carries a<private>region never reach a page. An item created insharedkeeps its shared text on the page after a later edit of it lands inprivate: that edit is not shown, so nothing private is published, but the item does not leave the view; taking it out would be a separate decision. This keeps the phase 2 promise that a phone that syncs only the view sees nothing private, and it means a personal topic is not in the view by default. The spec scenario "User asks for a topic" for a personal matter therefore holds for a personal topic the user asks to keep inshared; whether the view should show private topics on a writer that holdsprivate(with an opt-in shared setting and private ingestion of their edits) is left to the owner. - Page layout.
topics/<YYYY-MM-DD>-<slug>/topic.md: the topic's creation day (UTC) and a slug of its current title (letters and digits of any script, joined by hyphens, at most 48 code points,topicwhen empty); a second topic that takes the same folder gets the last six characters of its id appended. The id comment line also names the topic (topic=<id>). Required sections are the title, the description (a generated placeholder when none), the status line and the related section (which names at least the scope); the goal, milestones, decisions, open questions and log are left out when empty. Decisions and the log are newest first; open milestones come first in the order recorded, then done ones newest first; goal proposals follow the open questions. - Page budget. Per section: at most 10 done milestones, 25 decisions and 15 log entries stay on
topic.md; the oldest over that, and every resolved question, move toarchive.mdin the same folder, linked from the related section. Open milestones and open questions never move, so a topic with more of those than fits is the one case where the page is longer than its budget. - Retiring pages. A page in
topics/,reports/orsources/that has a render record but is no longer rendered (a rename, a merge, an undone create, a removed report) is removed by the view writer at the start of its pass: an edit it carries and its conflict copies are ingested first, the page leaves its name by one atomic rename (so a racing edit is captured), and the user's companion files of a renamed topic's folder move to the new folder. An edit that renames the topic (its title line) moves the page on the next pass. - Edits of topic pages. A changed line of a topic page or its archive maps to the topic record that says the same thing, with
humanauthority (view/topic-edits.ts): the title, description, status, goal, an item's text (decorations stripped in every view language), a ticked milestone, a deleted item (its tombstone), a deleted goal proposal (an undo of the agent's goal record) and a line added in an item section (a new item). A line this mapping does not own takes the generic phase 2 correction of the view. A done milestone's line key names the record that completed it, so unticking it on the page writes a humanundoof that record and the milestone is open again. - Reports and sources.
reports/<entry>.mdandsources/<entry>.mdrender from thelane-entryrecords of the lanesreportsandsourcesinshared, leaving out removed entries, entries whose fields reserve them as private, records with a<private>region and entry ids that are not plain file names. A body line's key is a hash of its text and occurrence, so a correction follows the line while the report keeps it. - Note-tool refusal. The note tools' view-folder guard (phase 2) names the topic event tool (
brain_topic,o2b topic) for a path in the view'stopicsfolder, and the report and source tools forreportsandsources; at the vault root the guard also owns those three folder names. - Digests. The state digests (D6) hash a fourth fold,
topics(topicsFingerprint: every topic, the assignments, blocked routes, voided records and rejected ids). The hash is optional in a digest, so a digest an earlier release of format version 1 published still parses, and two digests are compared on a fold only when both carry it; the format version does not change.
D17. Topic planning, the topic tool and the CLI as built (phase 3, tasks 3.4 to 3.6)
- What planning reads. The candidates are
signalrecords and the log events a person reads (note,decision-record,decision-resolved), with their text, project and session (topics/candidates.ts). The project is the record'sprojectfield (a signal's frontmatter, a log event's body), normalised as every scope key is. The session is the record'ssession, else itssession_ref, else the device, agent and UTC day that wrote it, so one agent's records of one day on one machine count as one session. A signal asignal-removedrecord forgot is not a candidate. - Deterministic fallbacks only. Until the decision-model uses of phase 4, routing and grouping use subject words (letters and digits of any script, four or more code points, a short list of common English words dropped). A record routes to the active topic of its scope whose head (title, description, goal and item texts) shares the most words with it, at least two and a fifth of the record's; a route the user took back is never taken. A record with no project routes only to a personal topic and never makes a topic: personal topics are made on request. A group is grown greedily in record order (a record joins the first group it shares two words with); one of at least
topics.new_min_recordsrecords from at leasttopics.new_min_sessionssessions becomes a topic titled by its three most frequent words (a tie goes to the word its first record says first) with its first record's text as the drafted goal. A record anyassign,unassignorsplitever named (touched, voided ones included) is routed but never grouped again, so a topic the user undid is not recreated from the same records. - Who and how. Planning runs on the view writer only (the same view-writer records as the render), under a device-local lock, and reads every held partition inside the lock and refuses on a partial read; the second of two passes therefore sees the first one's topics and assignments and creates nothing twice. Its records are
agentrecords of the dreaming agent. A create and its assigns land inprivatewhen any member is private; a route lands inprivatewhen the record or the topic is; a private record on a machine without the partition is skipped and counted. The dream pass runs it before the render (brain/dream-tail.ts), so the new topic's page is written in the same pass. - Proposals and prompts. Two active topics of one scope whose heads (title, description, goal) share half their words (Jaccard) are proposed for a merge; a topic whose own records group into two groups that would each make a topic is proposed for a split; an active topic with no record for
topics.quiet_days(a new shared setting, default 30) is offered for a status decision. Nothing is written for them: the dream report lists all three, and the markdown digest gains a## Topicssection with the merges and quiet topics and the command for each, rendered at the caller's reach and absent when there is nothing to ask, so a digest without topics is byte-identical. - Undo.
o2b topic undo <record>(andbrain_topicundo) writes a humanundonaming a topic record the caller can see; the dream report prints that command for every create and route. - The topic tool.
brain_topicando2b topicshare one implementation (topics/actions.ts).o2b topicwrites human records and itsrecordverb agent ones;brain_topicwrites agent records by default, and the caller can namehumanwithauthorityexcept below local reach (D18 item 5). Below local reach the fold holdssharedonly, and every write first resolves the topics it names in that fold, so a private topic answers "no topic with id" exactly as an unknown id does.showrenders the topic's page with private items for a local caller (topicPageswithincludePrivate), never for the view.osb://topic/{id}answers the same page and the absent-topic error below local reach. - Rule topics. The preference-slug internals of the query and resource layers are named
ruleTopic(queryByRuleTopic,readRuleTopicand their renderers); the resource isosb://rule-topic/{slug}, andosb://topic/<value>serves a topic when the value is a ULID and the rule topic otherwise, as the alias for one minor version. Thebrain_querytool'stopicargument and the persistedtopicfield of signals keep their names (design D8).
D18. Topics: review fixes (phase 3)
Paths from records. The view writer acts on a page path from a record only when it has exactly a shape the renderer writes (
topics/<YYYY-MM-DD>-<slug>/(topic|archive).md,reports/<entry>.md,sources/<entry>.md: forward slashes, no.., no\, no empty segment) and resolves strictly inside the view folder (view/page-path.ts). No folder below the view folder, nor the page itself, may be a symbolic link, and the real path of the page's folder must lie inside the real view folder; this check also guards live page writes and both folders of a companion move. Any other path in aview-renderrecord is ignored: a device that syncssharedcan write any record. A Windows device name (con,nul, ...) is never a retiring page, and a retiring page that is a live page's file under another case (a case-insensitive file system) is not retired.Folder slots. Retiring happens in
view/retire.ts. A live topic page whose last render record names another topic (the id line on disk decides only for a page rendered before render records named their topic, since a user's edit or a sync merge can change it) is retired first (its edit ingested, its folder's companion files moved to that topic's current folder), then the pages no longer rendered.view-renderrecords name the topic of a topic page, so the companions of a page already gone still follow their topic.Planning and the writer protocol. Planning uses the render's gate: the writer releases on a pending request, a writer by its own fresh claim waits until the render settled the claim (
claimSeen, read only, so the render's own wait is not spent), and the gate is asked again under the planning lock. The lock waits at least 30 seconds, and a pass whose topic records changed between its read and its writes (a lock taken over from a holder that looked stale) writes nothing (raced).Items per topic. An item id is its topic's own: the fold keys an item by the topic that first recorded it and the id, and a topic an item was split into finds it by its current owner. A
recordthat names an item (an edit, a completion, a resolution) must name an item of that topic of the right kind; below local reach arecordmay not pick a new item id. Unknownrecordfields are refused.Authority.
brain_topicwritesagentrecords unless the caller nameshuman, which is refused below local reach;o2b topicwriteshumanrecords (the user runs it), and itsrecordverbagentones unless--as-human. The agent's goal therefore stays a proposal under the user's. A request that reachesbrain_topicover a remote transport is recorded as anagentrecord: the transport cannot prove the user is behind it. Taking a route back blocks it whoever writes the undo or unassign, the user or an agent; only a decision model's leaves the route open, so an undo throughbrain_topicstops re-routing aso2b topic undodoes.Privacy and delivery. A shared record that carries a
<private>region makes its cluster's topic private and is withheld from remote reads of topics; the topic pageshowandosb://topic/{id}return is fenced below local reach; an unreadable-shard refusal names no shard below local reach; topic titles and descriptions are one line; review answers and the digest's topic section are empty over a partial read.Resources and the view at the vault root.
osb://topic/<value>falls back to the rule-topic reader when no topic the caller sees has that id. With the view at the vault root, the note tools refuse only the view's own pages (and their conflict copies and temp files) intopics/,reports/andsources/, and the folders that hold them as containers; a user's own note in those folders stays writable. Report and source ids that differ only in case render one page, and Windows device names none.PR review follow-ups. A topic starts
activewithout the create claiming the status register, so the firsttopic-statusof any authority applies (a later human one still wins). The planner cuts a drafted title to the record limit and checks every create as the fold does before it writes anything of the group. Below local reach every topic text oflistandshowis fenced, not only the page. After a merge an item id two owners share is refused as ambiguous untilrecordnames theowner. An undo of an undo is checked by the record it names, so an undone create can be taken back. A line the user adds to a topic page gets an item id derived from its topic, section and text, so the same line in a page and its conflict copy is one item. A private item's words never route a shared record. The view writer never reads a page name that became a symbolic link (it checks each name it reads or captures), moves a companion file only onto no name (a link, then an unlink), honours the pass's time budget while retiring, and takes a retiring page's owner from its last render record before its id line. The dream pass forwards its config path to topic planning and the view render, counts topic writes as a change, and skips planning once its deadline has passed. The folder of a topic never repeats another topic's, whatever a title ends in.Re-review follow-ups. An undo is private when the record it names sits in
private(an undone private create takes its topic out of the fold, so the topic alone cannot tell), so neither a private topic id nor a private record id reachesshared. The fold reports, per head field (title, description, goal), whether its winning record is private, and only shared head text and shared items route a shared record. Arecordwith anownernames an existing item of that owner, and the owner must be the topic or one merged into it; otherwise it is refused as an absent item is. The planner cuts a drafted title in UTF-16 code units, the unit of the record check, after capitalizing and never inside a surrogate pair. Below local reach the scope oflistandshowis fenced like the other topic text. A name that is not a regular file (a folder) at a live topic page reports that page as refused and the rest of the pass renders: the disk is read for an owner only when no render record names one. A page is read throughO_NOFOLLOWand a check of the opened descriptor where the platform has them. A companion move leaves a file in exactly one folder: when the old name holds another version by the time it would be unlinked (a sync tool delivered a newer one), or cannot be unlinked (Windows reports a file another program holds asEPERM, the code it also gives for "no hard links"), the new name is taken back.Second re-review follow-ups. Planning checks the view writer again from the catch-up read it plans from, so a move that arrives after the gate under the lock read the settings still stops the pass (
not-writer). The dream pass asks its deadline again under the planning lock, after the read and before the first write, and a pass past it writes nothing (deferred). A write that fails after others landed reportserrorwith the topics created and records routed before it, each with its undo command, and the dream summary counts them as a change. Asplitrequest takes only items the topic shows and writes the split of an item of a merged topic under that topic, the item's owner (the fold looks up a split's items by the topic it names); an id two merged owners share needsowner. An item id is refused for a new item of a topic only when a split moved that topic's item of the id to another topic: the fold still resolves the id to the moved item. A removed item stays its topic's, so its id can be recorded again. Adecisionrecord that leavesservesout keeps the links the item has, so a decision reworded on its page keeps the milestones it serves, and"serves": []clears them. When topics exchange folders, each retiring page moves only the companion names its folder held before any move of the pass. A companion move never unlinks a live name: the source and, when a move is taken back, the new name are each renamed to a temp name first and removed only when they are the version this move checked or placed, so a version a sync tool delivers under either name meanwhile is put back. A conflict-copy name that is not a regular file (a folder, a symbolic link) is refused where it is, and a capture that meets one puts it back under its name without replacing a name that exists. A conflict copy is taken out of its name before it is read, in a render and while retiring, so a copy written again after that read stays for the next pass. A private record routes by the private head text of a topic too, since its assign lands inprivate, and so does any record routed to a private topic; a shared route still uses shared text only. An edit, completion or resolution of an item that has a record inprivateis written toprivate, whatever the caller asks.o2b topic splittakes--ownerasbrain_topicdoes; a split whose named topic moves no item of its own carries only its records.brain_topicrefuses aprivateorremovedthat is not a boolean instead of dropping it. A dream pass plans on its own clock when it has one, and its undo commands name the config it ran with. A topic's activity time includes the records of topics merged into it and a split that hands it items or records. An item's privacy counts its completions and resolutions, whose evidence and answer are its text, so a later one written without the flag stays private. A route taken back from a topic is also blocked for the topic it merged into. Companion moves resolve each path once and use path-based calls: the runtime has no descriptor-relative rename or link, so a folder swapped for a symbolic link between the check and the call is not caught. That needs a process with write access to the view folder at that instant, which can already change the user's files directly.
D19. Schema field lists, personas and the shared namespace (task 3.12)
Three questions the store left open after phase 2, settled by the option that fits the store already built (append-only records, order-independent folds, human over agent over model, shared and private partitions) with the least new machinery.
- Schema field lists merge per entry. A schema field (
brain.schema.<field>) was one settings register over the whole list, so two devices that each added an entry before they synced kept only the later list (a whole-list last writer wins). A schema apply now writes onesetting-entryrecord ({ authority, key, entry, present }) per entry it adds or removes, never the list. A settings key that holds such a record folds per entry (store/fold-setting-lists.ts): each entry is one register under D4, keyed by its slot, the entry in the normalised form the pack parser reads (NFC, quotes stripped, trimmed, lower case, each side of aname=valueline on its own and each side of a->pair too), or for the keyed lists (prefixes,expert_routing,attributes,frontmatter_tiers, whosename=valuelines hold one value per name) the normalised name, a compoundtype.fieldname ofattributesandfrontmatter_tierssplit at its first.with each half normalised on its own (the split function is the parser's own,splitCompoundSchemaKey, sopaper . yearis never a second slot besidepaper.yearand never repaired away as a dangling entry), so a changed value replaces the old entry and a variant spelling of one token is the same slot, never a second one. Only the keysbrain.schema.<field>take entry records; the fold rejects an entry record for any other key, so a key that holds one value (a humanpermissions.document, a boolean, an object) stays on the plain register and no entry record can turn it into a removed list. The other way round too: asetting-setof abrain.schema.<field>key whose value is no list of one-line scalars (a string, a number, an object, an element with a line break) is rejected by the fold, so it can neither win the plain register and hide the stored list from the pack reader and the attestation, nor remove every entry of a key folded per entry, nor read as several pack lines; the settings writer already refuses such a value. An add on one device and a remove of the same entry on another resolve as every register does: the stronger authority, then the later clock. A whole-listsetting-set(the migration's import,o2b brain settings set) offers every entry the key ever named, its own as present and the rest as removed, and asetting-unsetoffers all as removed, so whole-list histories resolve exactly as the register did; a key with no entry record folds as the plain register. The list is ordered by the fold order of each entry's deciding record. Rejected: keeping the whole-list register and asking the user to re-apply after a conflict (silent loss is the defect the task names); a three-way list merge against a base the record would have to carry (more machinery, and it needs the base both devices saw, which delayed sync does not guarantee); add-wins or remove-wins as a special rule for lists (a second precedence rule beside D4 for no gain). 1.1 Authority per entry. The writers refuse an agent change the fold would ignore. An apply's entry change is refused when its slot is decided by a stronger authority; a slot no record named yet is decided by the whole-list records alone (the strongestsetting-setorsetting-unsetof the key), never by the newest entry record of another slot. For a key folded per entry, an agent's whole-listo2b brain settings setorunset(MCPbrain_settings) is refused when any slot it would add, remove or respell is decided by a stronger authority, and an accepted write reports the folded value, not the requested one. A key not yet folded per entry keeps the key-level refusal. 1.2 References across fields are repaired on read. The fold merges per field, so aremove_typeon one device and anadd_aliasoradd_prefixfor that type on another meet in a pack no apply could produce. The fold cannot refuse a record that arrives later, so the rule is enforced on the read side: the pack built from the store drops every reference to an undeclared token (aliases, prefixes, extractable entries, expert routes and attributes of a token the vocabulary does not hold, a link constraint pair whose source or target the vocabulary does not hold, and the constraints of an undeclared link type or of one left with no pair), the cascaderemove_typeandremove_link_typeapply (remove_link_typedrops the pairs of other link types that name it as an endpoint unless a vocabulary type of the same token keeps it declared). A pair is dropped rather than kept as inert: the indexer reads a page's type from its frontmattertype:, which removing the type from the vocabulary does not rewrite, so a kept pair would still allow or refuse typed edges of such pages, and an apply refuses a pair with an undeclared endpoint, so a machine that reads_brain.yamlnever holds one either. The drop is deterministic, so every machine reads one consistent pack and a later apply never fails on a dangling reference. The next apply writes the drop as entry removals, so the records converge too; a removal the applying authority may not write (an agent, an operator's entry) is skipped, since every reader drops it anyway. 1.3 What an audit row attests. A pack merged from two applies is no single apply's output, so its digest matches no audit row. Each apply's row also names records (decided): the records this apply wrote, plus the deciding records that rows this machine has seen already attest. A row names each record as<id>:<sha256>of the record's canonical JSON, never by id alone: a record's checksum covers its body, not its id, so another version under an attested id would otherwise pass as attested. An apply reads the store's schema records once, under its lock (readStoreSchemaPackinbrain/schema-pack.ts): the pack in force, the records deciding it and the stored field lists a repair compares against all come from that one fold of the shared settings stream, so the race is impossible rather than unlikely. A record that syncs in while the apply runs is neither part of the pack it builds on without being among the records it checks, nor attested by its row, nor removed as a repair: a repair removes only an entry the pack in force dropped on read from the same field lists (item 1.2), never one the read did not hold. A repair removal also names the record that decided the entry's slot in that read, and the settings writer skips it when another record decides the slot by the time it is written (a replacement another device wrote meanwhile). Sync delivers a peer's record at any time and no lock orders it against this machine's append, so a write-time check alone still loses a replacement written before the repair and delivered after it, whose clock is lower. The repair is therefore written as a conditional removal (if_decided_by, the record it judged): the fold applies it only while that record decides the slot among the key's unconditional records, and ignores it otherwise, whatever its clock and the delivery order. So a repair never removes what it did not judge; skipping or ignoring it is always safe, since every reader drops the dangling entry anyway. Rejected: re-checking the slot under the shard lock right before the append (it narrows the window and closes it only against writers on this machine, not against sync).if_decided_bybelongs tosetting-entryalone: on asetting-setorsetting-unsetit is no field of the kind and is ignored, as the format ignores every field a kind does not define, while on an addition, or empty, it is a malformedsetting-entryand the record is rejected. A key whose records name no entry at all once the inapplicable conditional removals are dropped (an empty whole list, an unset) is a removed key, won by its strongest, then latest, record as the whole-list register would win it; the list fold never throws on any record set, which a seeded property test over small random record sets pins together with order independence. The integrity read takes the pack's digest and the records it checks from one read the same way. Never every record that happens to decide the pack: one apply would then attest, on every machine, a record no apply wrote. A store-only pack that differs from the newest digest is stillok(merged) when every record deciding it is named by some row. A deciding record no row attests under an apply is a finding: the apply refuses withunattested_schema_records, naming the records, and the integrity read reports the pack asmodified, naming the same records (fielddecided), even when the pack digests as the newest row recorded (a record that sets an entry the pack already held changes no digest but still decides the entry), and even when the records leave no pack at all (an unattested removal of the last entry of the only schema field): the check for unattested records runs before the pack-absent answer, which staysunverified(config-absent) only when every deciding record is attested. Only a store whose rows all predatedecidedkeeps the digest comparison alone. The operator may adopt them witho2b brain schema apply --adopt-unattested(human authority only; MCP has no such option), with or without mutations (on its own it is an empty batch, and only on a store-only machine), and the row records them asadoptedwith the operator asadopted_by. Adoption alone writes no entry record, not even the repair of a dangling entry: it attests, it does not edit. The migration's import writes a baseline row (schema_import_baseline, no digest) attesting the schema records it wrote. A store whose rows all predatedecidedkeeps the digest comparison: there an apply counts the records deciding the pack as attested only when the pack in force is exactly the newest apply's output. The attestation reads the same pack fields the pack reader does, the field names the pack parser reads and nothing else, so a record underbrain.schema.that is no pack field (a name the parser does not read, a dotted key, a value that is no list) changes nothing attested. 1.4 Versioning. No released version of Open Second Brain contains the brain store; the store ships for the first time in the release that also carriessetting-entry. So no earlier release can meet the kind, and format version 1 includes it from the start. From that first release on, the versioning rule of the format (store/FORMAT.md, Versioning) applies unchanged: a later change that a reader of the released format would misread raises the format version, so that reader skips and reports the newer records instead of folding a different value. - Personas are records. D14 item 2 already folds personas as
lane-entryrecords of the lanepersonas, and the panel read them from the fold, but nothing could write one on a store-only machine, where there is noBrain/personas/folder to edit. The lane page layer now writes and removes them througho2b brain panel persona-set <slug> [--lens L] [--file F]andpersona-remove <slug>(personaslists them), with human authority from the CLI: a note on an unswitched machine, a record on a store-only one, with or without a vault. A persona curated on one machine is the lens on every machine of the store, and two devices editing one persona resolve by D4. The verbs run the lane write guard first, as every lane write: a frozen machine refuses them in both modes, and a running migration refuses them on a machine that has not switched; on a store-only machine the guard checks the store identity in place of the vault marker (D14 item 13) and keeps the freeze, as the store-mode settings writer and the store-only schema apply do, while a migration gate left naming the vault refuses nothing there. The verbs then refuse a page of another kind at the persona's path, refuse to replace a persona that lives inprivate(the lane writer keeps a replaced entry in its partition and never lowers its privacy, so the operator removes it and sets it again), and refuse a private persona by name: a lens or prompt with a<private>region or naming a private page would be stored inprivate, which machines that do not hold it never read. A prompt holds at most 16 KB (every panel step carries it, and the record syncs to every machine), a lens at most 200 characters on one line, Unicode line separators included. On an unswitched machine with the phase 1 dual write on,persona-setalso writes the entry to the store, sopersona-removethere dual-writes the stored entry's tombstone, and a persona removed before the switch is not back after it; this is the lane page layer's removal and move (store/lane-dual-moves.ts), so every lane's removed or moved page (a pledge, a staged folder, an archived dead end) leaves its stored entry the same way. A page that never reached the store is removed as a file alone. The records of one removal or move, a folder's included, are one store operation built from one fold of the lane entries, so an entry's value and its partition come from the same read. A move is the write of the destination page plus the removal of the source, judged as those two writes would be judged, in both modes and for a page and a folder alike; one table-driven test checks it over every state a move can start from (tests/core/lanes/lane-move-table.test.ts). A moved entry is built from the page as it is on disk after the rename (a legacy-only edit the store never saw included; when nothing the store would import is there, the move removes the source entry and the destination entry the rename overwrote, and writes nothing else), lives where the old entry lived, or inprivatewhen the page is private by its own content, the fold may miss a record, or the destination it replaces is private (its stored entry lives inprivateor its fields reserve it, or, on an unswitched machine, the legacy page the rename replaced was private by its frontmatter): the rule of a write over that page, since nothing lowers an entry's partition, and a move is a write at its destination. A move that replaces a shared destination entry with a private one writes that entry's shared tombstone first (D14 item 18), the store-only move too. A page the store never saw, renamed over a path whose entry the store holds (a single page, or a file of a folder moved onto stored entries), is dual-written as the write of that page alone (there is no source entry to remove): the page as it now is on disk, judged as a fresh write would be (the replaced entry or legacy page private keeps it private, its own content, a fold that may miss a record), the replaced shared entry's tombstone first when the new value leavesshared; when no page the store would import is there, the stored entry's tombstone alone. A folder's stored entries are paired from the entry ids below the source and the destination folders, never from the disk, so a link where an entry's file was does not hide that entry. Each moved entry is placed by itself (D14 item 18), so a private page of a folder does not raise the others, and the lane's private-when-held rule does not apply to a move (no caller moves a page into such a lane). So the destination's stored entry never stays live with content the tree no longer has. A move whose source is a lane entry and whose destination is none (outsideBrain/, or not in a lane folder) is refused before anything moves, in both modes: an unswitched machine used to rename it and write the tombstones, while a store-only machine has no file to leave there and its tombstones alone would lose the page. A store-only move of a single page onto itself (the same path, or one that normalises to it, a trailing slash included) writes nothing, like every same-identity move. A dual-written move builds the new entry from the legacy file even when the store holds a newer value from a switched peer: the legacy write wins during the trial (D11), so a peer's newer value of a page this machine moves is replaced by the file's; no staleness guard is added, since the trial's rule is that the legacy tree is the truth until the switch. The page at the new path is never read through a symbolic link, at its own name or at a folder belowBrain/, nor when it is a special file (openRegularFileForRead, the rule of the migration's legacy scan, which never imports such a page): it writes the tombstones of the old entry and of the destination entry the rename overwrote, so a link moved as a lane page cannot carry a file from outside the vault intoshared. A folder is never moved into its own subfolder nor into a folder that holds it, refused in both modes before anything moves: the rename refuses both (a folder cannot move into itself, and the folder that holds the source is never empty), and on a store-only machine one entry's destination can be another entry's source in the same batch (s1moved to its parent, holdings1/z.mdands1/s1/z.md), whose tombstone, written after it, would remove the entry the batch just wrote there. Refusal was chosen over writing every tombstone of the batch before every new entry: that order keeps every entry, but it accepts moves the rename refuses, so the two modes would end in different states, and a move into an ancestor would merge the folder's entries into the ancestor's own. With overlapping folders refused, the only destination that is also a source is the folder moved onto itself, which writes nothing. A fold that may miss a record is one with aneventsshard it could not see or read only in part, or a record inprivatewhose body blob has not arrived, quarantined on this machine or not (a quarantine lets the shard read as whole, yet the record is still left out, and it may be the newer private value of the entry that moves): one predicate (laneFoldIncomplete) answers it for every lane write, move and privacy read, so a quarantined blob inprivateno longer lets a lane page intosharedwhile the record waits. A record insharedwhose blob has not arrived does not count: every writer judges a value's fields before it places the record, so a record insharednever carries a value that makes an entry private, and leaving one record out changes an entry's winner only when it is that winner (the register keeps the last record of the strongest authority), so the fold without it is at least as private as the fold with it. Counting it would block every lane write on a machine that holds onlyshareduntil the lost blob arrives, which is what a quarantine is there to end. The table test crosses both with the move states. A move onto the entry it moves (the same path, or one that normalises to it) writes nothing; a case-only rename names two entries in the store, whose entry ids keep their case, so it moves the entry like any rename. Rejected: personas as files in the view folder, ingested by the view writer (a second edit path, and the view is rendered fromsharedonly and written by one device, so a machine that is not the writer could not curate); personas as device-local files (machines would disagree on the panel's lenses). - The shared namespace gets no store of its own. The
shared_namespacemirror wrote remember-writes into a second vault. A write to a vault that is store-only on this machine lands in this machine's brain store, which every store-only agent of every machine of the store reads: a store-only namespace is that store. So the mirror writes there when the origin record is not in it already (the origin vault still writes the legacy layout and dual writes are off), attributed byorigin_vaultas before, and refuses before any I/O when it is (a switched machine, a store-only origin vault, dual writes on), naming the reason, and when the machine has no store at all. Every check reads the machine config the caller names, the one its origin write used. A namespace path that is no directory (unmounted, missing, a file) is reportedfailedbefore any write, never taken for a store-only namespace. A second store would need its own store identity, clock floor, held partitions, seen-shards ledger, digest roster and index per machine for a fact every agent of the brain already shares; a namespace shared with a different brain stays a legacy-vault feature. Rejected: ashared_namespace_storeroot opened beside the machine's own store (all of that machinery, and one brain across vaults, D14 item 14, already covers one user's agents); keeping the blanket refusal (it also refused the case where the mirror is the only way the record reaches the store).
D20. Decision-model uses and agent context as built (phase 4, tasks 4.1 to 4.5)
Registry. The nine uses are appended to
DECISION_MODEL_USESin contract order afterrecall_inject; each isoffunlessdecision_model_usesnames it. Question texts, thresholds (route_min0.6,kind_min0.7,hide_below0.3,veto_below0.3,same_min0.7,resolved_min0.7,done_min0.8,drop_below0.1,inject_min0.5), per-use question versions (1 at first; 2 for the eight uses whose questions now name their own masked field -records.R<k>,topics.T<k>,milestones.M<k>,pairs.A<i>andpairs.B<i>- as the original uses do;topic_newstays 1) and the shared limits (records per pass 50, per request 10, topic options 20, record clip 900, head field 300, pairs 20, groups 10, members 10 at 300, history notes 50, heads per request 40, neighbour candidates 20) live inquestions-topics.ts, re-exported fromquestions.ts. The shippedjev-1.13baseline was measured on the eight original uses only (BASELINE_TUNED_USES): a new use runsenforceonly with a thresholds-store entry for the answering model or a measured mark, and otherwise runsshadow, named inshadowOnlyUses. The nine uses compare each answer against the stored value for the model that answered (use-thresholds.tsappliedThreshold: the vault's override, else the global entry, else the built-in default; a stored value outside 0..1, which only a hand edit or a damaged file can produce, is ignored for the built-in one): a run result names the chain entry that answered (answeredBy), the resolved config carries the store path (thresholdsPath), and a stored verdict names the answering provider.topic_sameacts only on pairs whose answering entry heldenforce(the pair-verdict runner reports the answering entry per pair), so a shadow fallback never acts, and it hands the runner its share of the pass budget (until), so no batch starts once the share is spent; the planner trusts the pass's threshold instead of re-checking the built-in one.PairVerdictSpec.usewidened to includetopic_same; the nine new uses have no per-use report yet (USE_REPORTSentriesnull; the generic summary covers them).The private-data guard.
egress-guard.tsholdsisLoopbackUrlandwithoutUserinfo(moved out ofconfig.ts, which imports them back) andmayShareRecord(cfg, use, isPrivate): a private record leaves the machine only when every chain entry's base URL is loopback, or when the operator opted the use in through the new machine-config keydecision_model_private_uses(a comma list of the nine new uses only, unknown use invalid, environmentOPEN_SECOND_BRAIN_DECISION_MODEL_PRIVATE_USES, resolved intoprivateHostedUseson the config; the vault can only narrow the feature, never set this key). A mixed local/hosted chain counts as hosted. Every new use builds candidates withvisibility: []or[REMOTE_DENY_VISIBILITY_TOKEN]andprivateRegions: privateRegionTexts(text), so the shared state builder withholds private records and always strips<private>regions (also from the side texts a request carries beside its candidates: head fields, question and milestone texts, the drafted title of a new topic, the neighbour candidate's topic title); a request whose every candidate is withheld is not sent and writes nodecision_model_callrecord. A private subject id in record details reads(withheld). The planner's finer privacy holds for what a use sends beside its candidates: a head field whose winning record is private (a shared topic with a private rename, description or goal) is sent blank unless private records of the use may leave (shareableHeadFields, used by the topic uses andhead_select), and an open question or milestone that is private, or belongs to a private topic, is neither offered nor asked about under the same rule.Verdict shape and storage. A record a dream-time use wrote or let through in
enforcecarriesverdict: { use, model, provider, version, mode: "enforce", confidence }(built bytopics/verdicts.tsverdictBody;versionis the use's question version).shadowanswers are recorded indecision_model_callonly. Folds never call a model: the field is informational. Documented inFORMAT.mdwith thesourcefield and thehistory-verdictkind. The provider chain readerresolvedProviderEntriesmoved toprovider-entries.tsso the guard can read the chain without importing the resolver - the one import edge that would have closed a cycle betweenconfig.tsandegress-guard.ts.The decide pass.
dream()stays synchronous. The asynchronous front doors (CLI dream verb, MCPbrain_dream, the maintenance lane's dream task) awaitprepareTopicVerdicts(decide-auto.ts, fail-open toundefined) and hand the verdicts in asDreamOptions.topicVerdicts; synchronous callers, dry runs and previews get the deterministic result. The front doors pass the decide pass the same config path and run date (runAt, the dream'snow) the dream plans with: the writer gate, the store read, the plan and the history window follow the run date, as planning does under the lock, while the pass budget stays on the wall clock. The pass (decide.tsorchestratingdecide-route.ts,decide-same.ts,decide-items.ts,decide-history.tsoverdecide-shared.ts) runs only on the view writer (the same gate planning runs), outside the planning lock, with a 20-second pass budget andcfg.timeoutMsper request; each use gets an even share of what is left of the budget when it starts (time it does not spend rolls over), so a long queue of one use never starves the later ones. The record uses ask about candidates from the last eight ISO weeks, newest first (milestones by their newest held record), so a per-pass cap takes the newest and a new record never waits behind old routine ones; a record dated after the run (a device with a fast clock) comes after every present one. An answer oftopic_route,event_kind,question_resolvedormilestone_donethat writes nothing (shadow, below its threshold, a routine kind, anoneresolution, a milestone not done) goes into a device-local asked set (decide-asked.ts,decide-asked.jsonin the store's device-local directory, beside the other device-local state; the stored format is unchanged), keyed by use, subject (the record; the record and the questions offered; the milestone and its evidence), question version, answering model and mode, and pruned to the eight-week window; the next pass skips those subjects, so the records behind them get their turn, a new question version or another model asks again, and an answer given inshadowis asked again once the use is inenforce. An answer that acts is not entered: its record settles the subject, and a write that did not land is asked again. The one acting answer without a record, an enforcenoneroute, is entered with its verdict, and later passes apply it without asking. The set is saved when the pass ends, a pass that fails after answers arrived included, and is best-effort: an unreadable file is an empty set, a failed save repeats questions. It returns onlyenforceanswers, keyed by subject.planTopics(fold, candidates, settings, nowMs, verdicts?)stays pure and applies a verdict only where its subject still matches the fold read under the lock (record still unassigned, topic still active and of the scope, route not blocked, group members unchanged); anything stale is ignored. The writes stay inplanUnderLockbehind the fence (verdict-writes.ts): model routes writeassignrecords withauthority: "model"and the verdict; approvals ride thetopic-create(which keepsagentauthority); derived items,question-resolvedandmilestone-doneproposals are written withauthority: "model", neverevidence, a proposal under the item's owner (an item a merged topic shows is still written to the topic that owns it, where the fold finds it) and inprivatewhen the item is private (a completion or resolution counts for the item's privacy);history-verdictrecords go to thelogstream ofshared(the innerappendgained a stream argument), one withkeep: falseper hidden note and one withkeep: trueper kept note, so a judged note is settled and never asked about again; under the lock a note that already has a stored verdict (another front door's pass applied first) gets no second one. The report carriesderived,resolutions,completions,hiddenandkeptcounts, grown as each record lands so a failed write still reports what landed before it, and a pass that wrote any of them reportschangedlike one that created or routed, anddescribeTopicPlanningappends ", N decided by a decision model" and the model-judged merge count with confidences. The topic-route option ranking is exported (rankedRouteTopics);topic_samepairs come fromtopicPairsForSame(best score first, Jaccard 0.2, at most 20).Session start digest.
hooks/active-inject.tsbuilds two more blocks between the scoped rules and the memory body, both charged against the injection budget (memoryBudget = injectBudgetChars - scopedBlock.length - headsBlock.length - pinnedBlock.length, floor 0) and metered asLANE_BUDGETEDsourcestopic-headsandpinned-context. The heads block (pure modulesrc/core/agent-context/heads.ts): candidate topics of scopeproject:<P>with statuses active, waiting and blocked, not merged, never personal, nothing without a project; one line per head- <title> [<status>] (<id>): <description>. Goal: <goal>, description and goal omitted when null, goal cut to 160, line cut to 300, each part neutralised; cut whole, lowest-ranked first, never mid-line; the cut line (src/core/agent-context/budget-line.ts, task 4.4's shared helper) names every candidate not shown and both listing commands; the block rides the untrusted fence with origintopic-heads; the whole fenced block - heading, fence and cut line included - fitstopic_heads_max_chars, heads cut lowest-ranked first.topicScopeMatchesProjectnormalises both sides throughscopedRuleKey- the adapter for the two normalisations the store's scope keys and the workspace key use (section 3.7 item 2). The pinned block (pinned-block.ts):readPinnedContextcontent, neutralised, fenced with originpinned-contextas stored, agent-authored text, the whole fenced block (heading and cut line included) withinpinned_max_chars(default 1200), its cut line namingbrain_pinned_context. Heads and pinned together take at most half of what the injection budget leaves after the scoped rules: when the two caps together exceed that half, both shrink in proportion, so the confirmed preferences keep the other half and, when cut, carry their usual truncation notice (at the default budget of 8000 characters both caps stay as configured while the scoped rules block is at most 2400 characters; a larger scoped block shrinks them). A heads block always shows at least one head: when none fits beside the full cut line a short one without the listing commands is tried, and when none fits beside that there is no block. New_brain.yamlkeystopic_heads_max(12),topic_heads_max_chars(1600),pinned_max_chars(1200) inKNOWN_KEYS,BrainActiveConfig, the parser and the config template.head_select(head-select.ts) runs undermin(hookBudgetMs, remaining), enforced again around the call, where the remaining time ends at half the hook's process ceiling (decisionWaitMsinhooks/lib/process-ceiling.ts), so a provider that never answers leaves the digest time to be emitted;shadowsends and records,enforceorders by p(yes) descending (fallback order on ties) and drops heads belowdrop_below, counted in the cut line; a head without a valid answer keeps its fallback place after the scored ones. With no store, no project topics and no pinned context the digest is byte-identical to before.Neighbour updates.
hooks/neighbour-updates.ts(UserPromptSubmit, registered afterrecall-injectinhooks/hooks.jsonand every mirror) runs whenever a brain store is in use, on every host (the OpenCode prompt relay gained a default-on form for it); the machine-config keyneighbour_updates_enabledset tofalseor0, the boolean rule every setting follows (environmentOPEN_SECOND_BRAIN_NEIGHBOUR_UPDATES_ENABLED, resolver insrc/core/agent-context/config.ts), turns it off. Per turn: read the per-session state (neighbour_watermark,neighbour_topics, one-day expiry, device-local) and ask the index directly (brain-store/neighbour-probe.tsprobeNeighbours, after the usual catch-up): the head watermark, this device and agent's newest 500 own records, and - with a usable watermark - the candidate rows after it up to the head (streamtopics, the six kinds, never this device and agent), the newest 2000 of them, counting the older ones. Never paging over every record, a turn that follows a large import of other records still sees the update on its topic. With no watermark (the first prompt, or a state that expired after a day without a prompt) or a watermark from a rebuilt index, store the head watermark and inject nothing: a session resumed after more than a day does not replay what its neighbours wrote meanwhile, an accepted limit. The topics this session works on are those the earlier turns stored plus the envelope topics of its newest own records, asked from the index each turn (and the topics the fold assigns those records), so an own record older than any page still counts. Keep the candidates whose topic is one this session works on or whose scope normalises to the session's project - before any cap - read the fold only then, drop routine log entries and model-derived items whosesourcerecord this device and agent wrote (the rest are named model-derived), and take the newest 20 candidates of the six kinds, counting what the cap removed in the cut line; each candidate carries its privacy (record partition, topic, item, and the title's winning record) to the egress guard, a withheld id is written as(withheld), gate deterministically (topic this session works on and kinddecision) refined byneighbour_relevant(neighbour-relevant.ts: onenoulper candidate, the prompt's<private>regions stripped and cut to 2000, record text cut to 300,inject_min0.5); underenforcea candidate the model did not judge (withheld as private, cut to fit the state budget, an invalid answer) keeps the deterministic gate, ashead_selectkeeps an unjudged head in place, so turning the use on never hides a private decision on the session's topic. Render at most 5 update lines and 800 characters inside theneighbour-updatesfence (the 800 hold the cut line too: an update line that would push the block past it is cut and counted), one line per record with thebrain_topic showpointer, end with the cut line naming the old watermark when candidates were cut (the cut line alone when no update line is shown and the caps or the candidate cap cut any, since the watermark moves past them), and, when the 2000-row limit left candidates out, add one line naming how many (counted over every topic and project, before the session's filter) and thebrain_changescall since the old watermark, which lists them among every record written since then (alone in the fence when nothing else is shown). The change probe'stailoption the first version used is gone. The new watermark is stored after stdout, always. The lane has 1500 ms, and its decision wait also ends by half the process ceiling, so a provider that never answers gives way to the deterministic gate while the hook can still emit; any error exits 0 with no output and leaves the watermark unchanged.Budget cut lines.
budgetCutLine(task 4.4) rides the heads block, the pinned block and the neighbour block.activeTruncationNoticenow states the dropped-section count and the rule lines the headline tier cut ("Dropped 2 sections (Quarantine, Recently retired); 14 rule lines cut."), and the tier-alone notice and the kept-headlines clause carry the count too; the existing tests' expected strings were updated, nothing else changed.recall-injectnames the notes the budget left out inside the brief (_N more recalled notes are not shown. Search for them withbrain_searchand this prompt._), counting every fresh candidate not shown; a note gives way when the line would not fit, the count is recomputed after each eviction, the last note is never evicted (the line stays out instead), a brief that shows no note carries no cut line, and an evicted note of the sliced brief leaves the injected set. A note the decision filter judged unhelpful is not a budget cut and is not named. The shared line takes a singular form for a count of one. The active-preferences tier notice carries its cut count only when it still fits the budget.log-catchup's "N older not shown" now names the surface that carries the rest ("the log pages carry the rest"; there is no log-listing command, and the agent-text census forbids a legacy path in agent-facing text, so the pointer names the pages - recorded here as the one deviation from "names a command"). Audit of the remaining context hooks:nav-injecthas no budget cut (structural tier);counterparty-brief's item limit is the lane's shape and per-item clips carry an ellipsis;gap-agendareports rather than drops;backlog-nudgeis one count line;hygiene-digestemits counts per detector;subagent-injectridesbudgetActiveBody(announced) and marks truncated prefixes;reground-deliverdelivers parts that carry their own notices. None cut silently.Where each verdict is stored.
topic_routeon the assign;topic_newon the create;event_kind,question_resolved,milestone_done,human_readableon the records they write;topic_same,head_select,neighbour_relevantin thedecision_model_callrecord only.shadowalways records indecision_model_callonly.Authority. Routes, derived items, question resolutions, milestone completions and history verdicts carry
authority: "model"; a topic create the model let through keepsagentauthority and carries the verdict. A model record never beats an agent's or the user's, and no use ever deletes, merges, splits, closes or completes anything on its own.After the first pull-request review.
topic_newsends the drafted title only when every member of the group may leave the machine, the members pastgroupMembersShownincluded (a member the pass cannot resolve counts as one that may not). The record-item uses (event_kind,question_resolved,milestone_done) take a record's holding topic from the routetopic_routeaccepted earlier in the same pass before the deterministic plan, and an enforcenonekeeps the record free.event_kindtreats an item id a split moved to another topic (fold.movedAway) as taken, in the decide pass and under the lock.topicPairsForSameranks by score before its cap. The maintenance lane hands itsconfigPathtoprepareTopicVerdicts; the MCP dream tool gives the decide pass what is left of the call's safeguard, at mostDECIDE_PASS_BUDGET_MS(decideBudgetWithin), and skips it when nothing is left. The planning report carrieskeptbesidehidden, andwithTopicPasssetschangedfor any verdict record written. The heads glue keeps the deterministic order whenhead_selectfails. The neighbour block's 800 characters hold its cut line. The kept-headlines clause counts only the sections it names (linesCutByKey); the drop notice keeps the total. The recall hint is derived from the notes the brief finally shows, after the cut line's evictions, in both renderers, and a rerender after the enforce filter keeps counting the notes the budget left out. Rejected: the digest blocks stay on every context event the hook is registered for (SessionStart and PostCompact; a compact drops the earlier digest), and no(device, agent, seq)index forownRecordsTail, which would need a schema version for a scan measured at about 27 ms over 200,000 rows with no own record.After the second pull-request review.
topicCandidatestakes each record's text with its<private>regions cut out (no placeholder left; a record whose text is all region is no candidate), so grouping, routing, the drafted title and goal,event_kinditem texts and every request read only text outside the regions; the record still counts as private. The maintenance lane hands itsconfigPathtodreamas well, so the topic and view passes plan in the store its caller's config names; the livedreamcallers (CLI verb, MCP tool, lane) all forward it, and the dry-run callers never reach the store tail. The heads block reads its topics fromconfiguredStore(configPath), the config its decision settings come from. Each decide request getsmin(decision_model_timeout_ms, until - now)(requestTimeoutMs;runPairVerdictsthe same when givenuntil).question_resolvedandmilestone_donebuild the question and milestone texts inside the state frame, somaxStateTokenscounts them.applySameVerdictsadds or annotates a model-only pair only while both topics are active in one scope in the fold read under the lock. The write-time holding topic reads an explicit none as the decide pass does and then takes the plan's route.writeVerdictRecordswrites at most onequestion-resolvedper question in a batch.After the third pull-request review. The maintenance lane's dream task starts its one deadline before the decide pass and hands it
decideBudgetWithin(timeoutMs, 0)(no decide pass when that is 0), then gives the same guard todream, as the MCP tool shares its call's.historyNoteCandidatesputs a note dated after the run behind every present one before the per-pass cap, asaskableCandidatesdoes for records.event_kindsends each record's topic title as afieldsentry of the candidate, sobuildCandidateStatemeasures it againstmaxStateTokens. An item id is a topic's own and a merged topic shows the items of the topics merged into it, soquestion_resolvedandmilestone_donecarry the item's owner beside its id: in the options, in the asked-set subject (owner/id) and in the verdict, andwriteVerdictRecordsmatches the item on both. When no neighbour update line is shown, the cut line alone names what the caps or the candidate cap removed, also when no candidate passed the gate.After the fourth pull-request review. Partition of a written record. A record a use writes is private when any input it was derived from is private: by partition, as a private topic or head field, or by a
<private>region (a record with a region counts as private, and the region's text never leaves). An input the egress rule keeps home never reaches the question and does not count; a hosted provider still gets the shared text around a stripped region, so a region counts there too. The verdict carries the inputs other than the subject and its topic asprivateInput, set in the decide pass, and the writer ORs it into the partition; no field of a shared record carries text from a private input.Record written (use) Inputs Private when assign(topic_route)the record, the chosen topic, and every record and every topic with its head fields of the same request (a request batches records and offers them one shared topics state) the record, the chosen topic, or any record, topic or sent head field (region included) of the request is private derived item ( event_kind)the record, its holding topic, and every record of the same request with its topic title the record, the topic, or any record or sent title of the request is private question-resolved(question_resolved)the record, the topic and title, every offered question the record, the topic, the title, the chosen question or any offered question is private milestone-done(milestone_done)the milestone, the topic, every evidence record sent the milestone, the topic or any sent evidence record is private history-verdict(human_readable)the note never: only sharednotes without a region are asked, and the verdict goes tosharedtopic-create(topic_new)the group members, the drafted title any member is private (the planner's rule); the title is drafted only from text outside regions and sent only when every member may leave merge proposal ( topic_same),head_select,neighbour_relevanttopic pairs, heads, neighbour records no store record is written; a private subject is (withheld)indecision_model_callA private head field the egress rule withholds is never sent and does not count, even when its text carries a region. The table test
decide-privacy-matrix.test.tsholds every row (74 cells: kind, which input is private, may leave or hosted; the inputs include another subject of the same batched request, that subject's own topic, and a withheld private field). Filter before cap. Every per-pass or per-request cap counts only what may leave: records (event_kind,topic_route,question_resolved), offered topics (topic_route), shown evidence (milestone_done), groups and shown members (topic_new), pairs (topic_same) and heads per request (head_select); what the egress rule keeps home is left out first, so shareable subjects behind it are still asked and a private subject is not even named as(withheld)in the call record.neighbour_relevantkeeps its order (the hook caps before it, and a withheld candidate keeps the deterministic gate). Minimum request time. No request starts with less thanMIN_REQUEST_MS(250 ms,request-floor.ts) of its use's share left (mayStartRequest, checked where the pass checkeduntiland inrunPairVerdicts) or of the hook budget (head_select,neighbour_relevant), and none whose own timeout is below it: the floor holds for the time the request really gets, the smaller of the configured request timeout (decision_model_timeout_ms,decision_model_hook_budget_msfor the hook uses) and what is left; it counts as a budget skip, and the deterministic result stands for what was not asked. The floor is enforced inrunDecision(requestFloor, which every topic, pair and hook request sets): the request's time runs from the call's start, so preparing the state counts and the floor is checked again before the first attempt; and it holds for each attempt of a provider chain (attemptTimeoutMs): the chain splits the request's time evenly, an entry whose share would fall below the floor is not attempted, and its time goes to the entries before it. A floor skip inrunDecisionsends and records nothing. The callers' checks before a request stay as the cheap early stop that spares preparing a request that cannot start. The value is the floor skill attachment already keeps before its second request (SKILLS_STAGE2_MIN_REMAINING_MS), a twelfth of the default 3 s request timeout: a hosted round trip rarely answers in less, and a request that cannot finish may still be billed.After the fifth pull-request review. One order for every subject queue. Records, a milestone's evidence and history notes are taken newest first, an item dated after the run behind every present one (
newestPresentFirst,decide-shared.ts): a milestone's evidence keeps the order of the pass's candidates, so five future-dated records can no longer push the present evidence out of the request, and a milestone with only future-dated evidence is asked last.
Risks / Trade-offs
- [A fold bug makes machines diverge silently] β state digests with doctor alerts (D6), property tests that shuffle delivery order and duplicate lines, and a rebuild command.
- [Clock skew orders two concurrent edits against the user's intent] β authority precedence decides most conflicts before the clock does, and the losing edit stays in history.
- [The view writer is offline for a long time] β pages go stale but no data is lost; doctor on every machine reports it after 3 days and names
o2b view writer --here. - [A phone edit races a render] β re-check before the rename, and ingestion of the resulting sync-conflict copy as a human edit (D7).
- [Legacy writers on other machines keep writing during migration] β per-line journal, final delta pass, imports during the transition, and the legacy tree stays until every roster device has switched (D11, D11a).
- [Rollback after new writes] β replay into the legacy layout through exporters (D11).
- [Skills still tell agents to use
Brain/paths] β skills rewritten in phase 2 and legacy-tree detection in doctor (D11, D12). - [Large migration on a slow disk is interrupted] β per-item journal,
--resume, and no source removal before verification. - [Users sync the device-local directory by mistake] β it lives outside the store root by default, and doctor reports another device's id inside it.
- [A cloud-drive sync tool changes whole files under a writer] β one writer device per file; doctor reports conflict copies and torn middle lines.
- [The private partition is missing on a server agent's machine] β writes of private records refuse with a clear message; reads work on what is present.
- [Phase 1 dual writes double disk use for a release] β the flag is off by default and documented as a trial.
Migration Plan
D11 is the plan, including rollback. The transition window ends per install when the legacy tree leaves the vault (D11a). Code for legacy reads and rollback stays for two minor releases after the release that ships the migration.
Open Questions
- The roster window (30 days), the digest silence alert (7 days) and the view-writer silence alert (3 days) are to be tuned with real multi-machine data. They do not change the specs.
- The weekly history page budget (lines per week) is to be tuned once the
human_readableuse has shadow data.