Local-first π§ memory for Hermes Agent that lives in your Obsidian vault and remembers project context. Nightly π΄ dream passes turn repeat corrections into confirmed preferences with measurable confidence. Adapters ship for Claude Code, Codex, and OpenClaw, with an MCP server for anything else.
TypeScript
feat(store): brain store core behind a default-off dual write (#289)
Serg Eroshe67adf3f0658f
diff --git a/docs/architecture.md b/docs/architecture.mdindex 60792469..1ee52205 100644--- a/docs/architecture.md+++ b/docs/architecture.md@@ -433,8 +433,8 @@ not enter through the correction door. The predicate insurfaces differ in what they serve, never in what the rule says.The enforcement lives in `tests/mcp/agent-scope-matrix.test.ts`, and its shape-is the point rather than its size. One hundred and eight classified tools carry-251 call recipes - one per mode, view or operation, because one executed view+is the point rather than its size. One hundred and nine classified tools carry+252 call recipes - one per mode, view or operation, because one executed viewis not an executed classification. Every recipe runs TWICE against the sametwo-owner fixture, once with the gate closed and once with it open, and theclassification decides what the open run must show: the 32 recipes classifieddiff --git a/docs/cli-reference.md b/docs/cli-reference.mdindex f2fdd97b..ecae2094 100644--- a/docs/cli-reference.md+++ b/docs/cli-reference.md@@ -20,6 +20,7 @@ o2b secrets list|status Inspect $secret:NAME references without printing vo2b mcp Run the MCP tool server (stdio by default; --transport http binds loopback, and a credential - a key, --api-key or, kept out of the process list, OPEN_SECOND_BRAIN_MCP_API_KEY, or a non-empty per-agent token map from `o2b mcp token mint` - is required only for a non-loopback --host); a token-matched request authenticates as that token's agent for the request, the shared key keeps the process identity, and `mcp_tokens_required` / OPEN_SECOND_BRAIN_MCP_TOKENS_REQUIRED (default false) refuses credential-less requests while a non-empty token map exists; --scope full|writer|catalog, --tool-profile full|writer|catalog|recall|minimal (an unknown profile exits 2 rather than serving the full surface), --host-target <runtime>, --harness <id>, --probe, --allow-tool, --disable-tool, --max-toolso2b state status|migrate|rollbackInventory the state this vault holds, move it to another directory, or put it back (see "State surfaces" below)+o2b store init Create the brain store once, on the first machine: both partitions with one store id, or --partitions shared for a machine that must not hold private records; refuses an existing store (exit 1), completes a half-created one with its own store id, and refuses a partition folder that holds store files without store.json; --config, --json (see "Brain store dual writes" in how-it-works.md)o2b tool-call Invoke an MCP tool handler from the CLIo2b version Print the installed Open Second Brain version; --version is a synonymo2b help --json Print the command/flag manifest as JSON@@ -177,6 +178,23 @@ a refusal prints `{ "ok": false, "error", "run_id", "drifted" }`, where`drifted` lists the refused paths. A file that holds bytes which are notvalid UTF-8 and was not edited still upgrades.+`Brain/_BRAIN.md` carries a `template_revision:` line in its frontmatter+(a manual without it is revision 0). Devices that share one vault through+a file sync may run different releases, and an older release used to+rewrite the manual a newer release wrote back to its own template, while+the newer release upgraded it forward again on its next start, each step+behind a pre-apply snapshot. A manual whose revision is higher than the one+this release ships is now left as it is, by the automatic upgrade and by+`o2b brain upgrade --apply` alike: the plan row is a no-op, the dry run+prints `kept; written by a newer release (template revision N, this release+ships M)` (JSON: `ahead_revision` on the row), and `o2b brain status` lists+the `managed-file-from-newer-release` problem until Open Second Brain on+this device is updated. A manual from the same or an older revision is+upgraded as before. Releases from before the stamp do not know the rule,+so a device still on one of them keeps rewriting the manual until it is+updated. `_brain.yaml` needs no stamp: its merge only adds missing keys+and never rewrites or removes one, so two releases cannot undo each other.+### The codegraph partner check`o2b doctor` consults the optional [codegraph](https://github.com/colbymchenry/codegraph)@@ -2329,6 +2347,7 @@ so there is no separate lane field that could drift from it:| Code | The narrowing it reports || ------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ || `index-stale` | the index was last updated more than ten minutes ago (`detail.ageSeconds`), so notes changed since then may be missing; `detail.behindCount` is the measured number of documents the next incremental run would add, update or delete, counted live under the same gate that fires the code by a stat-only walk diffed against the index - an upper bound (a touch-only file counts as changed), a measured zero rides too, and absent means not measured, never zero. The code still does not say a refresh is running: freshen on read starts a background run when it can, and starts none when it is off, a failed run is backing off, another run or writer holds the index, the index is read-only for this reader, or the run cannot be spawned |+| `store-catch-up-failed` | the brain store catch-up before this read failed, so store records added since the last good catch-up may be missing; the failure itself is in the warning || `keyword-fts-match-empty` | the query tokenised to an empty FTS match, so the keyword lane never ran || `keyword-trigram-lane-fault` | the trigram candidate lane could not be read; `detail.fault` carries that lane's own classification || `semantic-embeddings-absent` | the index holds no compatible embedding |diff --git a/docs/how-it-works.md b/docs/how-it-works.mdindex eb6c6e6f..65987c37 100644--- a/docs/how-it-works.md+++ b/docs/how-it-works.md@@ -374,7 +374,7 @@ A `portability/` subsystem of deterministic primitives, all opt-in orno-op by default:- **Session codec.** A pure lossless `compress`/`expand` (`expand(compress(x))-=== x` for all input). Token savings come from reversibly collapsing+ === x` for all input). Token savings come from reversibly collapsingwhitespace/blank-line runs behind a Private-Use-Area marker; code andstructured tokens are preserved byte-for-byte. Opt-in on the signalstore (gated by a `_raw_codec` marker the reader keys off) and exposed as@@ -577,11 +577,11 @@ Since v1.70.0 the operator can also write rules that hold for oneproject, one harness or one machine, one file per scope value, besidethe vault-wide `Brain/standing-rules.md`:-| File | Matches when |-|---|---|-| `Brain/standing-rules/project/<key>.md` | the session runs in a project linked to the vault whose key is `<key>` |-| `Brain/standing-rules/harness/<harness id>.md` | the MCP server was launched for that harness |-| `Brain/standing-rules/host/<device id>.md` | the session runs on the device with that id |+| File | Matches when |+| ---------------------------------------------- | ---------------------------------------------------------------------- |+| `Brain/standing-rules/project/<key>.md` | the session runs in a project linked to the vault whose key is `<key>` |+| `Brain/standing-rules/harness/<harness id>.md` | the MCP server was launched for that harness |+| `Brain/standing-rules/host/<device id>.md` | the session runs on the device with that id |The scope identity is resolved by the server from facts the operatoror the packager wrote, never from anything a caller names about itself:@@ -668,39 +668,39 @@ resolving symbolic links, and nothing generates or rewrites the files.The same operations are reachable through two channels. Read columnsare mirrored in MCP; destructive operations are CLI-only by design.-| Operation | CLI verb | MCP tool | Side effect |-| -------------------------- | --------------------------------------------------- | ---------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |-| Bootstrap layer | `o2b brain init` | β | creates `Brain/` skeleton |-| Record taste signal | `o2b brain feedback` | `brain_feedback` | writes signal + log event (sanitised) |-| Consolidation pass | `o2b brain dream` | `brain_dream` | mutates preferences/retired, atomic snapshot, regenerates `Brain/active.md` |-| Record application | `o2b brain apply-evidence` | `brain_apply_evidence` | appends log event; `result β {applied, violated, outdated}`; artifact supports `[[file:120-145]]` ranges |-| Record milestone | `o2b brain note <text>` | `brain_note` | appends one `note` log event to `Brain/log/<today>.md` plus the JSONL sidecar. Multi-line collapses to one line. CLI mirror exists for cron / shell. |-| Pin current-task context | β (use MCP) | `brain_pinned_context` | writes/appends/clears `Brain/pinned.md`; transient context, not a learned preference |-| Pull active context | β (use MCP) | `brain_context` | read-only; returns `Brain/active.md` body, pinned context + counts. Always-loaded on the writer MCP server so runtimes without a `SessionStart` hook (Cursor, Aider, raw Claude API) can fetch it at session start. |-| Render summary | `o2b brain digest [--window Nd]` | `brain_digest` | read-only; includes `top_applied`, `top_referenced`, and `agent_summary` sections |-| Pre-dream intent review | `o2b brain intent-review` | `brain_intent_review` | read-only; classifies active signal clusters as ready, needing evidence, or conflicted before the next `dream` |-| Lifecycle retention review | `o2b brain retention` | `brain_retention` | read-only; recommends keep / improve / park / prune for retired preferences and processed signals; no artifact is deleted or moved |-| Monthly synthesis | `o2b brain monthly` | `brain_monthly_review` | read-only; month-level counters for events, status transitions, retirements, contradictions, and neglected areas |-| Inspect state | `o2b brain query` | `brain_query` | read-only |-| Computed backlinks | `o2b brain backlinks <id>` | `brain_backlinks` | read-only; inverted reference map across `preferences/`, `retired/`, `log/` |-| Validate invariants | `o2b brain doctor` | `brain_doctor` | read-only; structural lints + semantic-health findings; `--remediate [--dry-run]` applies auto-safe content-hash re-stamps |-| Semantic health | `o2b brain health` | `brain_health` | read-only; contradictions, concept gaps, stale claims + clean/watch/investigate verdict |-| Preference edit-history | `o2b brain history <slug>` | β (CLI-only) | read-only; one entry per content mutation (principle / scope / status before -> after) |-| Full-text search | `o2b search "<query>"` | `brain_search` | FTS5 + optional semantic; write-classified MCP tool (persists access and opt-in reinforce/telemetry ledgers under `Brain/search/`) |-| Manage search index | `o2b search index \| reindex \| status \| check` | β (CLI-only) | builds / inspects `<vault>/.open-second-brain/brain.sqlite`. `search check` ends with a `recommendations:` block on missing pieces (key, sqlite-vec, first reindex) |-| Cron template for reindex | `o2b search reindex --cron-template [--interval N]` | β (CLI-only) | prints a watchdog script, native crontab line, and `hermes cron create` recipe to stdout (writes nothing) |-| Operational snapshot | `o2b status` | `second_brain_status` | read-only; `brain.*` + `search.*` blocks |-| Retire manually | `o2b brain reject` | β (CLI-only) | requires `--reason "<text>"`; subsequent signals on the same topic are suppressed |-| Merge near-duplicate prefs | `o2b brain merge <keep> <drop>` | β (CLI-only) | folds `evidenced_by` and counters into `keep`; `drop` retires with reason `merged-into`; surfaced as candidates in `brain_digest` |-| Toggle pin | `o2b brain pin / unpin` | β (CLI-only) | flips `pinned` field; regenerates `Brain/active.md` |-| Protect Brain/ | `o2b brain protect / unprotect` | β (CLI-only) | machine-enforced deny rules for `claudecode` / `codex` runtimes; sidecar manifest at `.open-second-brain/protect.lock.json` |-| Restore snapshot | `o2b brain rollback` | β (CLI-only) | overwrites Brain/ from snapshot; from v0.10.6 aborts on drift unless `--force-rollback`, see [Snapshots and rollback](#snapshots-and-rollback) |-| Upgrade managed files | `o2b brain upgrade` | β (CLI-only) | migrates the three release-owned files (`_brain.yaml`, `_BRAIN.md`, `_OPEN_SECOND_BRAIN.md`) forward. `_brain.yaml` is text-merged additively (user values, comments, and ordering preserved); the other two are byte-compared and overwritten. `--dry-run` prints a per-file plan; `--check` exits 2 on pending updates (CI-friendly); `--apply --yes` applies the plan it showed: a file edited after the plan was read is refused before the `upgrade-<ts>` snapshot, and again at each write, instead of being overwritten. After a plugin update the MCP server and the `SessionStart` hook run the same upgrade in a detached worker, off the start-up path, and back off after a failure (see `docs/updating.md`). |-| Export active prefs | `o2b brain export --format json\|llms-txt` | β (CLI-only) | read-only dump of `confirmed \| unconfirmed \| quarantine` preferences from `Brain/preferences/`. `--out <path>` writes a file (refuses to overwrite without `--force`); default sink is stdout. Retired and signal artifacts are deliberately excluded. |-| Export a transcript corpus | `o2b brain export --format transcripts-jsonl --transcripts <file\|dir>` | β (CLI-only) | since v1.50.0: one JSON object per line, one per CONVERSATION, built from recorded session logs. Reads no vault. Messages carry role, text and the NAMES of the tools a turn called, never the tool inputs. `--runtime` filters by adapter; `--since`/`--until` select whole conversations by their start. Guarded record by record; a secret-shaped identifier refuses the whole export and writes nothing. Full contract in [`cli-reference.md`](cli-reference.md). |-| Force-directed explorer | `o2b brain explorer [--port \| --export]` | β (CLI-only) | live HTTP on `127.0.0.1` (default `:7777`) or single-file HTML at `<path>`; renders preferences + retired as a graph; zero backend. Keyboard-accessible `<ul role="listbox">` mirror of visible nodes (ArrowUp/Down/Home/End/Enter/Escape); layout + filter state persisted to `localStorage` under `osb-explorer-layout:<vault_basename>`; "Reset layout" button clears the key. |-| Import Claude memory | `o2b brain import-claude-memory` | β (CLI-only) | imports `metadata.type=feedback` entries from a Claude Code memory directory into `Brain/preferences/`. `--dry-run` prints a per-file plan; `--apply --yes` takes an `import-claude-memory-<ts>` snapshot before writing. Sidecar manifest `Brain/.imports/claude-memory.json` keys idempotency on body sha256. `UPDATE` preserves the eight evidence-related frontmatter fields. `CONFLICT` (existing pref outside the manifest) lands the safe writes and exits 2. |-| Daily discipline report | `o2b discipline {report\|install\|uninstall}` | β (CLI-only) | renders a deterministic Telegram MarkdownV2 block comparing per-agent brain-events vs runtime-agnostic activity (git/mtime/vault delta) plus a complexity-to-thinking ratio. `install` writes a Hermes cron entry (`--telegram-target` required; `--weekly` installs a Monday digest; `uninstall --weekly` removes only the weekly job). `alert` fires when taste events (`feedback`+`apply_evidence`) are zero while activity is non-zero, or when structural churn grows much faster than recorded thinking. |+| Operation | CLI verb | MCP tool | Side effect |+| -------------------------- | ----------------------------------------------------------------------- | ---------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| Bootstrap layer | `o2b brain init` | β | creates `Brain/` skeleton |+| Record taste signal | `o2b brain feedback` | `brain_feedback` | writes signal + log event (sanitised) |+| Consolidation pass | `o2b brain dream` | `brain_dream` | mutates preferences/retired, atomic snapshot, regenerates `Brain/active.md` |+| Record application | `o2b brain apply-evidence` | `brain_apply_evidence` | appends log event; `result β {applied, violated, outdated}`; artifact supports `[[file:120-145]]` ranges |+| Record milestone | `o2b brain note <text>` | `brain_note` | appends one `note` log event to `Brain/log/<today>.md` plus the JSONL sidecar. Multi-line collapses to one line. CLI mirror exists for cron / shell. |+| Pin current-task context | β (use MCP) | `brain_pinned_context` | writes/appends/clears `Brain/pinned.md`; transient context, not a learned preference |+| Pull active context | β (use MCP) | `brain_context` | read-only; returns `Brain/active.md` body, pinned context + counts. Always-loaded on the writer MCP server so runtimes without a `SessionStart` hook (Cursor, Aider, raw Claude API) can fetch it at session start. |+| Render summary | `o2b brain digest [--window Nd]` | `brain_digest` | read-only; includes `top_applied`, `top_referenced`, and `agent_summary` sections |+| Pre-dream intent review | `o2b brain intent-review` | `brain_intent_review` | read-only; classifies active signal clusters as ready, needing evidence, or conflicted before the next `dream` |+| Lifecycle retention review | `o2b brain retention` | `brain_retention` | read-only; recommends keep / improve / park / prune for retired preferences and processed signals; no artifact is deleted or moved |+| Monthly synthesis | `o2b brain monthly` | `brain_monthly_review` | read-only; month-level counters for events, status transitions, retirements, contradictions, and neglected areas |+| Inspect state | `o2b brain query` | `brain_query` | read-only |+| Computed backlinks | `o2b brain backlinks <id>` | `brain_backlinks` | read-only; inverted reference map across `preferences/`, `retired/`, `log/` |+| Validate invariants | `o2b brain doctor` | `brain_doctor` | read-only; structural lints + semantic-health findings; `--remediate [--dry-run]` applies auto-safe content-hash re-stamps |+| Semantic health | `o2b brain health` | `brain_health` | read-only; contradictions, concept gaps, stale claims + clean/watch/investigate verdict |+| Preference edit-history | `o2b brain history <slug>` | β (CLI-only) | read-only; one entry per content mutation (principle / scope / status before -> after) |+| Full-text search | `o2b search "<query>"` | `brain_search` | FTS5 + optional semantic; write-classified MCP tool (persists access and opt-in reinforce/telemetry ledgers under `Brain/search/`) |+| Manage search index | `o2b search index \| reindex \| status \| check` | β (CLI-only) | builds / inspects `<vault>/.open-second-brain/brain.sqlite`. `search check` ends with a `recommendations:` block on missing pieces (key, sqlite-vec, first reindex) |+| Cron template for reindex | `o2b search reindex --cron-template [--interval N]` | β (CLI-only) | prints a watchdog script, native crontab line, and `hermes cron create` recipe to stdout (writes nothing) |+| Operational snapshot | `o2b status` | `second_brain_status` | read-only; `brain.*` + `search.*` blocks |+| Retire manually | `o2b brain reject` | β (CLI-only) | requires `--reason "<text>"`; subsequent signals on the same topic are suppressed |+| Merge near-duplicate prefs | `o2b brain merge <keep> <drop>` | β (CLI-only) | folds `evidenced_by` and counters into `keep`; `drop` retires with reason `merged-into`; surfaced as candidates in `brain_digest` |+| Toggle pin | `o2b brain pin / unpin` | β (CLI-only) | flips `pinned` field; regenerates `Brain/active.md` |+| Protect Brain/ | `o2b brain protect / unprotect` | β (CLI-only) | machine-enforced deny rules for `claudecode` / `codex` runtimes; sidecar manifest at `.open-second-brain/protect.lock.json` |+| Restore snapshot | `o2b brain rollback` | β (CLI-only) | overwrites Brain/ from snapshot; from v0.10.6 aborts on drift unless `--force-rollback`, see [Snapshots and rollback](#snapshots-and-rollback) |+| Upgrade managed files | `o2b brain upgrade` | β (CLI-only) | migrates the three release-owned files (`_brain.yaml`, `_BRAIN.md`, `_OPEN_SECOND_BRAIN.md`) forward. `_brain.yaml` is text-merged additively (user values, comments, and ordering preserved); the other two are byte-compared and overwritten. `--dry-run` prints a per-file plan; `--check` exits 2 on pending updates (CI-friendly); `--apply --yes` applies the plan it showed: a file edited after the plan was read is refused before the `upgrade-<ts>` snapshot, and again at each write, instead of being overwritten. After a plugin update the MCP server and the `SessionStart` hook run the same upgrade in a detached worker, off the start-up path, and back off after a failure (see `docs/updating.md`). |+| Export active prefs | `o2b brain export --format json\|llms-txt` | β (CLI-only) | read-only dump of `confirmed \| unconfirmed \| quarantine` preferences from `Brain/preferences/`. `--out <path>` writes a file (refuses to overwrite without `--force`); default sink is stdout. Retired and signal artifacts are deliberately excluded. |+| Export a transcript corpus | `o2b brain export --format transcripts-jsonl --transcripts <file\|dir>` | β (CLI-only) | since v1.50.0: one JSON object per line, one per CONVERSATION, built from recorded session logs. Reads no vault. Messages carry role, text and the NAMES of the tools a turn called, never the tool inputs. `--runtime` filters by adapter; `--since`/`--until` select whole conversations by their start. Guarded record by record; a secret-shaped identifier refuses the whole export and writes nothing. Full contract in [`cli-reference.md`](cli-reference.md). |+| Force-directed explorer | `o2b brain explorer [--port \| --export]` | β (CLI-only) | live HTTP on `127.0.0.1` (default `:7777`) or single-file HTML at `<path>`; renders preferences + retired as a graph; zero backend. Keyboard-accessible `<ul role="listbox">` mirror of visible nodes (ArrowUp/Down/Home/End/Enter/Escape); layout + filter state persisted to `localStorage` under `osb-explorer-layout:<vault_basename>`; "Reset layout" button clears the key. |+| Import Claude memory | `o2b brain import-claude-memory` | β (CLI-only) | imports `metadata.type=feedback` entries from a Claude Code memory directory into `Brain/preferences/`. `--dry-run` prints a per-file plan; `--apply --yes` takes an `import-claude-memory-<ts>` snapshot before writing. Sidecar manifest `Brain/.imports/claude-memory.json` keys idempotency on body sha256. `UPDATE` preserves the eight evidence-related frontmatter fields. `CONFLICT` (existing pref outside the manifest) lands the safe writes and exits 2. |+| Daily discipline report | `o2b discipline {report\|install\|uninstall}` | β (CLI-only) | renders a deterministic Telegram MarkdownV2 block comparing per-agent brain-events vs runtime-agnostic activity (git/mtime/vault delta) plus a complexity-to-thinking ratio. `install` writes a Hermes cron entry (`--telegram-target` required; `--weekly` installs a Monday digest; `uninstall --weekly` removes only the weekly job). `alert` fires when taste events (`feedback`+`apply_evidence`) are zero while activity is non-zero, or when structural churn grows much faster than recorded thinking. |Operations that change the **protected set** (`pin`, `unpin`,`reject`, `rollback`) and the **index lifecycle** (`search index`,@@ -867,7 +867,7 @@ live tree it is about to discard (`restoreSnapshotWithRecoveryPoint` in`snapshot-gate.ts`, reached from `o2b brain rollback`). Three members have**no producer in this release** β `session-boundary`, `plan-boundary` and`decision-boundary`, for boundaries a later release may snapshot at. No-CLI verb and no MCP tool mints a recovery point *on demand*: the+CLI verb and no MCP tool mints a recovery point _on demand_: thetake-snapshot entry point is reached only by the destructive-operationgate, the rollback's own recovery point included. The reason is required by`createSnapshot`, doubles as the run-id prefix so the filename and the@@ -1210,7 +1210,7 @@ Key behaviours, all driven from `Brain/_brain.yaml`-free `search_*` /term; every boost below still applies, and `linear` is bit-identical topre-v0.36.0 ranking.- **Ranking.** `final_score = clamp01(keyword_weightΒ·norm_BM25 +-semantic_weightΒ·cosine + link_boost + recency_boost + entity_boost)`+ semantic_weightΒ·cosine + link_boost + recency_boost + entity_boost)`(linear mode; in `rrf` mode the first two terms are replaced by thefused reciprocal-rank relevance).BM25 is min-max-normalised within the candidate set; cosine is@@ -1811,6 +1811,111 @@ withheld below local reach.A Markdown or text source gets nothing new: its page is byte for bytewhat it was.+## Brain store dual writes (phase 1 trial)++Open Second Brain is moving its machine data out of the vault into the brain+store: an append-only folder outside the vault whose format is documented in+`FORMAT.md` inside the store (source: `src/core/store/FORMAT.md`). In this+phase the store is a trial. Nothing reads from it yet, and the vault tree+under `Brain/` stays the source of truth.++The store is created once, by an explicit command, on the first machine:++```+o2b store init # both partitions+o2b store init --partitions shared # a machine that must not hold private records+```++It writes one store id into every partition it creates, and the format+document into the root and each partition. Every other machine receives the+partitions through sync; sync each partition folder as its own sync folder,+never the store root. A second run refuses an existing store. A run that+finds some requested partitions already present (a first run that stopped+half way, or a machine adding `private` later) adds the missing ones with+the same store id. A partition folder that holds store files but no+`store.json` is refused by name rather than given a new id.++The `store_dual_write` setting turns the trial on. It is off by default.+Set `store_dual_write: true` in the machine config, or set the environment+variable `OPEN_SECOND_BRAIN_STORE_DUAL_WRITE=1`, which wins over the config.+While it is on, the existing writers also append the same data to the store:++| Legacy write | Store record |+| ------------------------------------------------------------ | -------------------------------------------------------- |+| A signal (feedback, inline and extracted signals) | `signal` in `events` |+| A Brain log event (notes, apply-evidence, every other event) | `log-event` in `log` |+| A preference write, retire or pin | `preference-set` in `events` |+| Apply-evidence | `preference-evidence` in `events`, besides its log event |+| Pinned context write, append, batch or clear | `pinned-set` or `pinned-clear` in `events` |+| A row of a per-device ledger | `ledger-row` in `ledgers/<name>` |++Preference and pinned records carry who decided them. An operator running+`o2b` decides as `human`; an agent calling a tool, a bulk import and the+dream pass decide as `agent` (dream is automatic even when an operator+starts it); a decision-model verdict is `model`. No legacy writer acts on a+decision-model verdict yet, so `model` appears only when a caller passes it.+Records of a page whose frontmatter reserves it as private go to the store's+`private` partition. The rule is the one search and remote reads use: a+`visibility` that includes `private`, or an informal marker such as+`access: private`, `confidentiality: secret` or `sensitivity: confidential`.+A page that exists but cannot be read counts as private. The apply-evidence+log event, the audit rows and the edit-history rows about a private+preference follow it into `private`.++Truth-claim ledger rows go to `private` when this machine holds that+partition and to `shared` when it does not, since a claim can be about a note+of any visibility. Audit rows follow the same rule: the preference audit+trail and every reliability audit trail (hygiene, secret custody, hook audit,+watchdog and the others under `Brain/log/`) go to `private` when this machine+holds it and to `shared` when it does not. An audit row about a private+preference goes to `private` only; a machine without that partition refuses+it and counts a failed dual write, the legacy row is kept.++Rules of the trial:++- With the setting off, nothing is written to the store and the legacy+ files are byte-identical to what they were before the store existed.+- A store failure never fails the legacy write. The first failure in a+ process prints one warning; every failure is counted in+ `dual-write.json` in the device-local state directory+ (`${XDG_STATE_HOME:-~/.local/state}/open-second-brain/stores/` on Linux and+ macOS, `%LOCALAPPDATA%\open-second-brain\stores\` on Windows).+- Dual writes never create the store. With no store at the root they are+ skipped, counted and warned about once; doctor says to run+ `o2b store init`.+- The store needs a real device id. With `O2B_DEVICE_ID` set to the empty+ string, or when the device id cannot be resolved (for example an+ unreadable or unwritable machine config), the dual writes are skipped,+ counted and warned about once. A missing `device_id` is generated and+ saved to the machine config on first use, as for the sharded logs.+- The store root comes from `OPEN_SECOND_BRAIN_STORE_ROOT`, then the+ `store_root` config key, then a per-user default+ (`${XDG_DATA_HOME:-~/.local/share}/open-second-brain/store`). A root inside+ the vault is refused.+- A machine that holds only the `shared` partition refuses private records;+ that counts as a failure, and the legacy write is kept.++`o2b brain doctor` has a store section. It stays silent while the store is+not in use (the setting is off and no store root is configured). When the+store is in use it reports failed or skipped dual writes, a store that has+not been created yet, a store root it cannot use, state digests that+disagree between machines over the same records, devices that stopped+publishing digests, record ids that arrived with different content, and+records whose clock is more than one day ahead of now (per device, with the+newest stamp). Such records are still folded, and they win ties on the+later clock, so the fix is the clock of the named device.++Search and `brain_changes` catch the index up with the store before they+read. To keep a burst of reads cheap, one process looks at the store at most+once per second; a record another machine adds inside that window is found+by the next read after it. The environment variable+`OPEN_SECOND_BRAIN_STORE_CATCHUP_INTERVAL_MS` sets the window in whole+milliseconds (`0` looks on every read); any other value keeps the default.++Writers that edit preference files directly rather than through the+preference writer (for example protection marks, expiration dates, the Claude memory+import and batch writes) are not covered in this phase.+## Safety propertiesThese are invariants of the system, not configuration to enable.diff --git a/docs/mcp.md b/docs/mcp.mdindex 5f1cd1f2..bec6e343 100644--- a/docs/mcp.md+++ b/docs/mcp.md@@ -403,6 +403,7 @@ flags for a narrower per-process full server.| `brain_brief` | Brain summary for any window: `view: morning \| daily \| weekly \| monthly \| operator \| digest \| today`. `view=today` embeds the operator dashboard: obligations sorted due-today and overdue first, one-off pledges, open loops, merged recent activity, totals. `view=digest` also snapshots its report under `Brain/reports/` for the run-over-run delta when report snapshots are enabled (skipped below local reach and under an enforced owner scope). | `view` || `brain_analytics` | Brain analytics for any lens: `view: timeline \| attention_flows \| belief_evolution \| concept_synthesis \| dedup`. `view=attention_flows` seeds its default flow recipe when the vault lacks one; `view=dedup` summarises the persisted exact-hash ingest dedup records into a trend plus a per-source re-ingest ranking; every count is an exact sha-256 drop, never a semantic figure (the semantic detectors nominate merge candidates and never drop). | `view` || `brain_search` | Vault search with optional structured query lanes, explicit focus hints, time ranges, evidence-pack diagnostics, a selectable recall `profile` (`fast \| balanced \| thorough`), an FTS `match_mode` (`all` \| `any`), a pushed `kind` filter (`page` \| `section`) plus SQL pushdown for the promoted `properties` keys (since v1.80.0), and since v1.82.0 an opt-in iterative recall loop (`iterative`, `iterative_token`, `iterative_payload`) whose surviving coverage gaps pause with a plan the caller answers. Write-classified: it persists activation access events by default and the opt-in reinforce, recall-telemetry and query-demand ledgers under `Brain/search/` - ranking state later searches read back. | `query` |+| `brain_changes` | Change probe over the brain store (phase 1 trial, active only when a store is in use): returns the record ids added since an optional watermark (`since`; absent starts from the first record), grouped by partition, stream, scope and topic, plus the watermark to pass next (`truncated: true` when `limit` cut the page, `reset: true` when the watermark came from a replaced index, `warnings` when a catch-up failed), so an agent or hook can see what other agents saved without running a search. Read-only; local reach only. | none (`since`, `limit` optional) || `brain_recall_feedback` | Record explicit up/down recall feedback for one search result; feeds the deterministic learned-weight fold. | `query`, `result_path`, `verdict` || `brain_recall_gate` | Read-only classifier for whether an automatic recall attempt should run; returns `retrieve` plus a stable reason. When the caller passes `scores` AND `match_quality` (the `idf_weighted_coverage` a search outcome reports - the two stand or fall together, and an incomplete pair is refused), also attaches an adequacy verdict (`sufficient` \| `weak` \| `insufficient`), a recommended action (`proceed` \| `re_recall` \| `abstain`), and an optional `escalate` flag. The LEVEL is decided by `match_quality` alone; the scores decide only the usable-result count. Thresholds via `recall_adequacy_sufficient` / `recall_adequacy_weak` / `recall_adequacy_min_results`. Since v1.82.0 a measured call also returns the shared graded surfacing key (`key`, `tier`) beside the binary decision. | `prompt` || `brain_context_pack` | Budgeted context slice; pass `lanes: true` to return directives, constraints, and consider lanes. Filtered items include `safety.reasons`. Each item carries a structural `epistemic` status (`observed` \| `derived` \| `hypothesis` \| `plan` \| `unknown`) plus `evidence_refs` derived from existing graph metadata; fields are absent when the status is `unknown`. Takes the same adequacy pair as `brain_recall_gate` under its own spelling, `recall_scores` AND `match_quality`: both or neither, an incomplete pair is refused, and the schema states it as `dependentRequired` keyed on this tool's own scores name. Since v1.91.0 an opt-in `entity_facts_context_pack` config key (default off, env `OPEN_SECOND_BRAIN_ENTITY_FACTS_CONTEXT_PACK`) adds a conditional `entity_facts` section: the canonical-scope entities anchored from the query, at most three, each listing only ids the pack already kept whose bodies anchor it; the key is absent when off, so the default pack stays byte-identical. Since v1.95.0 an opt-in `tail_trim_context_pack` config key (default off, env `OPEN_SECOND_BRAIN_TAIL_TRIM_CONTEXT_PACK`) adds a score-aware tail trim whenever the call carries a query: the top three delivered items are immune, an item whose query-term overlap nearly matches the top delivered score is kept, the rest drop whole with a `tail-trim` skip reason, and the freed budget is offered back to `over-budget` candidates in priority order; the response carries a conditional `tail_trim` block (`dropped`, `kept_by_query_terms`, `rescued`, `tokens_saved`) only when the trim ran, and with the key off the pack is byte-identical. | `max_tokens` |diff --git a/openclaw/index.js b/openclaw/index.jsindex 83a75e43..e3e04580 100644--- a/openclaw/index.js+++ b/openclaw/index.js@@ -1781,7 +1781,7 @@ var init_secret_ref = __esm(() => {// src/core/platform-dirs.tsimport { homedir } from "node:os";-import { join as join2, win32 } from "node:path";+import { join as join2, posix, win32 } from "node:path";function processDirsEnv() {return { platform: process.platform, home: homedir(), env: process.env };}@@ -1800,11 +1800,17 @@ function baseDir(kind, source) {return xdg;if (isWindows(source))return windowsLocalAppData(source);- return join2(source.home, ...POSIX_DEFAULT[kind]);+ return posix.join(source.home, ...POSIX_DEFAULT[kind]);}function configBaseDir(source = processDirsEnv()) {return baseDir("config", source);}+function dataBaseDir(source = processDirsEnv()) {+ return baseDir("data", source);+}+function stateBaseDir(source = processDirsEnv()) {+ return baseDir("state", source);+}var APP_DIR_NAME = "open-second-brain", XDG_VARIABLE, POSIX_DEFAULT;var init_platform_dirs = __esm(() => {XDG_VARIABLE = Object.freeze({@@ -2152,54 +2158,55 @@ var init_errors = __esm(() => {});// src/core/brain/path-constants.ts-import { posix } from "node:path";-var BRAIN_ROOT_REL = "Brain", BRAIN_INBOX_REL, BRAIN_PROCESSED_REL, BRAIN_ARCHIVED_SIGNALS_REL, BRAIN_PENDING_REL, BRAIN_PREFERENCES_REL, BRAIN_RETIRED_REL, BRAIN_SKILL_PROPOSALS_REL, BRAIN_SKILL_PROPOSALS_PENDING_REL, BRAIN_SKILL_PROPOSALS_ACCEPTED_REL, BRAIN_SKILL_PROPOSALS_REJECTED_REL, BRAIN_SKILL_ACCEPT_JOURNAL_REL, BRAIN_PROCEDURES_REL, BRAIN_PROCEDURAL_MEMORY_REL, BRAIN_ATTENTION_REL, BRAIN_OBLIGATIONS_REL, BRAIN_PLEDGES_REL, BRAIN_THESES_REL, BRAIN_DECISIONS_REL, BRAIN_GAP_TASKS_REL, BRAIN_TENSIONS_REL, BRAIN_LOG_DIR = "log", BRAIN_LOG_REL, BRAIN_CAPTURES_REL, BRAIN_CAPTURES_PROCESSED_REL, BRAIN_ENTITIES_REL, BRAIN_STATE_REL, BRAIN_INTERNAL_STATE_DIR = ".state", BRAIN_INTERNAL_STATE_REL, BRAIN_BASES_REL, BRAIN_SOURCES_REL, BRAIN_REPORTS_REL, BRAIN_DISTILLATIONS_REL, BRAIN_SNAPSHOTS_DIR = ".snapshots", BRAIN_SNAPSHOTS_REL, BRAIN_ARTIFACTS_DIR = ".artifacts", BRAIN_ARTIFACTS_REL, BRAIN_ARCHIVES_DIR = ".archives", BRAIN_ARCHIVES_REL, BRAIN_PAYLOADS_DIR = ".payloads", BRAIN_PAYLOADS_REL, BRAIN_WRITE_IMAGES_DIR = "write-images", BRAIN_WRITE_IMAGES_REL, BRAIN_SNAPSHOT_EXCLUDED_ENTRIES, DERIVED_STORE_DIR = ".open-second-brain", BENCH_RUNS_REL, JSONL_LEDGER_EXT = "jsonl", BRAIN_CONFIG_FILE = "_brain.yaml", BRAIN_ACTIVE_FILE = "active.md", BRAIN_LESSONS_FILE = "lessons.md", BRAIN_COMPILED_DIGEST_RELS, BRAIN_INDEX_FILE = "_INDEX.md", BRAIN_INDEX_REL, BRAIN_PAGE_LANES_REL;+import { posix as posix2 } from "node:path";+var BRAIN_ROOT_REL = "Brain", BRAIN_INBOX_REL, BRAIN_PROCESSED_REL, BRAIN_ARCHIVED_SIGNALS_REL, BRAIN_PENDING_REL, BRAIN_PREFERENCES_REL, BRAIN_RETIRED_REL, BRAIN_SKILL_PROPOSALS_REL, BRAIN_SKILL_PROPOSALS_PENDING_REL, BRAIN_SKILL_PROPOSALS_ACCEPTED_REL, BRAIN_SKILL_PROPOSALS_REJECTED_REL, BRAIN_SKILL_ACCEPT_JOURNAL_REL, BRAIN_PROCEDURES_REL, BRAIN_PROCEDURAL_MEMORY_REL, BRAIN_ATTENTION_REL, BRAIN_OBLIGATIONS_REL, BRAIN_PLEDGES_REL, BRAIN_THESES_REL, BRAIN_DECISIONS_REL, BRAIN_GAP_TASKS_REL, BRAIN_TENSIONS_REL, BRAIN_LOG_DIR = "log", BRAIN_LOG_REL, BRAIN_CAPTURES_REL, BRAIN_CAPTURES_PROCESSED_REL, BRAIN_ENTITIES_REL, BRAIN_STATE_REL, BRAIN_INTERNAL_STATE_DIR = ".state", BRAIN_INTERNAL_STATE_REL, BRAIN_ANTICIPATORY_DIR = "anticipatory", BRAIN_ANTICIPATORY_REL, BRAIN_BASES_REL, BRAIN_SOURCES_REL, BRAIN_REPORTS_REL, BRAIN_DISTILLATIONS_REL, BRAIN_SNAPSHOTS_DIR = ".snapshots", BRAIN_SNAPSHOTS_REL, BRAIN_ARTIFACTS_DIR = ".artifacts", BRAIN_ARTIFACTS_REL, BRAIN_ARCHIVES_DIR = ".archives", BRAIN_ARCHIVES_REL, BRAIN_PAYLOADS_DIR = ".payloads", BRAIN_PAYLOADS_REL, BRAIN_WRITE_IMAGES_DIR = "write-images", BRAIN_WRITE_IMAGES_REL, BRAIN_SNAPSHOT_EXCLUDED_ENTRIES, DERIVED_STORE_DIR = ".open-second-brain", BENCH_RUNS_REL, JSONL_LEDGER_EXT = "jsonl", BRAIN_CONFIG_FILE = "_brain.yaml", BRAIN_ACTIVE_FILE = "active.md", BRAIN_LESSONS_FILE = "lessons.md", BRAIN_COMPILED_DIGEST_RELS, BRAIN_INDEX_FILE = "_INDEX.md", BRAIN_INDEX_REL, BRAIN_PAGE_LANES_REL;var init_path_constants = __esm(() => {- BRAIN_INBOX_REL = posix.join(BRAIN_ROOT_REL, "inbox");- BRAIN_PROCESSED_REL = posix.join(BRAIN_INBOX_REL, "processed");- BRAIN_ARCHIVED_SIGNALS_REL = posix.join(BRAIN_INBOX_REL, "archived");- BRAIN_PENDING_REL = posix.join(BRAIN_ROOT_REL, "pending");- BRAIN_PREFERENCES_REL = posix.join(BRAIN_ROOT_REL, "preferences");- BRAIN_RETIRED_REL = posix.join(BRAIN_ROOT_REL, "retired");- BRAIN_SKILL_PROPOSALS_REL = posix.join(BRAIN_ROOT_REL, "skill-proposals");- BRAIN_SKILL_PROPOSALS_PENDING_REL = posix.join(BRAIN_SKILL_PROPOSALS_REL, "pending");- BRAIN_SKILL_PROPOSALS_ACCEPTED_REL = posix.join(BRAIN_SKILL_PROPOSALS_REL, "accepted");- BRAIN_SKILL_PROPOSALS_REJECTED_REL = posix.join(BRAIN_SKILL_PROPOSALS_REL, "rejected");- BRAIN_SKILL_ACCEPT_JOURNAL_REL = posix.join(BRAIN_SKILL_PROPOSALS_REL, "accept-journal");- BRAIN_PROCEDURES_REL = posix.join(BRAIN_ROOT_REL, "procedures");- BRAIN_PROCEDURAL_MEMORY_REL = posix.join(BRAIN_ROOT_REL, "procedural-memory");- BRAIN_ATTENTION_REL = posix.join(BRAIN_ROOT_REL, "attention");- BRAIN_OBLIGATIONS_REL = posix.join(BRAIN_ROOT_REL, "obligations");- BRAIN_PLEDGES_REL = posix.join(BRAIN_ROOT_REL, "pledges");- BRAIN_THESES_REL = posix.join(BRAIN_ROOT_REL, "theses");- BRAIN_DECISIONS_REL = posix.join(BRAIN_ROOT_REL, "decisions");- BRAIN_GAP_TASKS_REL = posix.join(BRAIN_ROOT_REL, "gap-tasks");- BRAIN_TENSIONS_REL = posix.join(BRAIN_ROOT_REL, "tensions");- BRAIN_LOG_REL = posix.join(BRAIN_ROOT_REL, BRAIN_LOG_DIR);- BRAIN_CAPTURES_REL = posix.join(BRAIN_ROOT_REL, "captures");- BRAIN_CAPTURES_PROCESSED_REL = posix.join(BRAIN_CAPTURES_REL, "processed");- BRAIN_ENTITIES_REL = posix.join(BRAIN_ROOT_REL, "entities");- BRAIN_STATE_REL = posix.join(BRAIN_ROOT_REL, "state");- BRAIN_INTERNAL_STATE_REL = posix.join(BRAIN_ROOT_REL, BRAIN_INTERNAL_STATE_DIR);- BRAIN_BASES_REL = posix.join(BRAIN_ROOT_REL, "bases");- BRAIN_SOURCES_REL = posix.join(BRAIN_ROOT_REL, "sources");- BRAIN_REPORTS_REL = posix.join(BRAIN_ROOT_REL, "reports");- BRAIN_DISTILLATIONS_REL = posix.join(BRAIN_ROOT_REL, "distillations");- BRAIN_SNAPSHOTS_REL = posix.join(BRAIN_ROOT_REL, BRAIN_SNAPSHOTS_DIR);- BRAIN_ARTIFACTS_REL = posix.join(BRAIN_ROOT_REL, BRAIN_ARTIFACTS_DIR);- BRAIN_ARCHIVES_REL = posix.join(BRAIN_ROOT_REL, BRAIN_ARCHIVES_DIR);- BRAIN_PAYLOADS_REL = posix.join(BRAIN_ROOT_REL, BRAIN_PAYLOADS_DIR);- BRAIN_WRITE_IMAGES_REL = posix.join(BRAIN_INTERNAL_STATE_REL, BRAIN_WRITE_IMAGES_DIR);+ BRAIN_INBOX_REL = posix2.join(BRAIN_ROOT_REL, "inbox");+ BRAIN_PROCESSED_REL = posix2.join(BRAIN_INBOX_REL, "processed");+ BRAIN_ARCHIVED_SIGNALS_REL = posix2.join(BRAIN_INBOX_REL, "archived");+ BRAIN_PENDING_REL = posix2.join(BRAIN_ROOT_REL, "pending");+ BRAIN_PREFERENCES_REL = posix2.join(BRAIN_ROOT_REL, "preferences");+ BRAIN_RETIRED_REL = posix2.join(BRAIN_ROOT_REL, "retired");+ BRAIN_SKILL_PROPOSALS_REL = posix2.join(BRAIN_ROOT_REL, "skill-proposals");+ BRAIN_SKILL_PROPOSALS_PENDING_REL = posix2.join(BRAIN_SKILL_PROPOSALS_REL, "pending");+ BRAIN_SKILL_PROPOSALS_ACCEPTED_REL = posix2.join(BRAIN_SKILL_PROPOSALS_REL, "accepted");+ BRAIN_SKILL_PROPOSALS_REJECTED_REL = posix2.join(BRAIN_SKILL_PROPOSALS_REL, "rejected");+ BRAIN_SKILL_ACCEPT_JOURNAL_REL = posix2.join(BRAIN_SKILL_PROPOSALS_REL, "accept-journal");+ BRAIN_PROCEDURES_REL = posix2.join(BRAIN_ROOT_REL, "procedures");+ BRAIN_PROCEDURAL_MEMORY_REL = posix2.join(BRAIN_ROOT_REL, "procedural-memory");+ BRAIN_ATTENTION_REL = posix2.join(BRAIN_ROOT_REL, "attention");+ BRAIN_OBLIGATIONS_REL = posix2.join(BRAIN_ROOT_REL, "obligations");+ BRAIN_PLEDGES_REL = posix2.join(BRAIN_ROOT_REL, "pledges");+ BRAIN_THESES_REL = posix2.join(BRAIN_ROOT_REL, "theses");+ BRAIN_DECISIONS_REL = posix2.join(BRAIN_ROOT_REL, "decisions");+ BRAIN_GAP_TASKS_REL = posix2.join(BRAIN_ROOT_REL, "gap-tasks");+ BRAIN_TENSIONS_REL = posix2.join(BRAIN_ROOT_REL, "tensions");+ BRAIN_LOG_REL = posix2.join(BRAIN_ROOT_REL, BRAIN_LOG_DIR);+ BRAIN_CAPTURES_REL = posix2.join(BRAIN_ROOT_REL, "captures");+ BRAIN_CAPTURES_PROCESSED_REL = posix2.join(BRAIN_CAPTURES_REL, "processed");+ BRAIN_ENTITIES_REL = posix2.join(BRAIN_ROOT_REL, "entities");+ BRAIN_STATE_REL = posix2.join(BRAIN_ROOT_REL, "state");+ BRAIN_INTERNAL_STATE_REL = posix2.join(BRAIN_ROOT_REL, BRAIN_INTERNAL_STATE_DIR);+ BRAIN_ANTICIPATORY_REL = posix2.join(BRAIN_INTERNAL_STATE_REL, BRAIN_ANTICIPATORY_DIR);+ BRAIN_BASES_REL = posix2.join(BRAIN_ROOT_REL, "bases");+ BRAIN_SOURCES_REL = posix2.join(BRAIN_ROOT_REL, "sources");+ BRAIN_REPORTS_REL = posix2.join(BRAIN_ROOT_REL, "reports");+ BRAIN_DISTILLATIONS_REL = posix2.join(BRAIN_ROOT_REL, "distillations");+ BRAIN_SNAPSHOTS_REL = posix2.join(BRAIN_ROOT_REL, BRAIN_SNAPSHOTS_DIR);+ BRAIN_ARTIFACTS_REL = posix2.join(BRAIN_ROOT_REL, BRAIN_ARTIFACTS_DIR);+ BRAIN_ARCHIVES_REL = posix2.join(BRAIN_ROOT_REL, BRAIN_ARCHIVES_DIR);+ BRAIN_PAYLOADS_REL = posix2.join(BRAIN_ROOT_REL, BRAIN_PAYLOADS_DIR);+ BRAIN_WRITE_IMAGES_REL = posix2.join(BRAIN_INTERNAL_STATE_REL, BRAIN_WRITE_IMAGES_DIR);BRAIN_SNAPSHOT_EXCLUDED_ENTRIES = Object.freeze([BRAIN_SNAPSHOTS_DIR,BRAIN_ARTIFACTS_DIR]);- BENCH_RUNS_REL = posix.join(DERIVED_STORE_DIR, "bench-runs");+ BENCH_RUNS_REL = posix2.join(DERIVED_STORE_DIR, "bench-runs");BRAIN_COMPILED_DIGEST_RELS = Object.freeze([- posix.join(BRAIN_ROOT_REL, BRAIN_ACTIVE_FILE),- posix.join(BRAIN_ROOT_REL, BRAIN_LESSONS_FILE)+ posix2.join(BRAIN_ROOT_REL, BRAIN_ACTIVE_FILE),+ posix2.join(BRAIN_ROOT_REL, BRAIN_LESSONS_FILE)]);- BRAIN_INDEX_REL = posix.join(BRAIN_ROOT_REL, BRAIN_INDEX_FILE);+ BRAIN_INDEX_REL = posix2.join(BRAIN_ROOT_REL, BRAIN_INDEX_FILE);BRAIN_PAGE_LANES_REL = Object.freeze([BRAIN_SOURCES_REL,BRAIN_REPORTS_REL,@@ -2208,6 +2215,21 @@ var init_path_constants = __esm(() => {});// src/core/integrity/digest.ts+import { createHash } from "node:crypto";+function sha256Hex(input) {+ return createHash(DIGEST_ALGORITHM).update(input).digest("hex");+}+function canonicalJson(value) {+ if (Array.isArray(value)) {+ return `[${value.map((item) => canonicalJson(item)).join(",")}]`;+ }+ if (value !== null && typeof value === "object") {+ const entries = Object.entries(value).filter(([, child]) => child !== undefined).toSorted(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([key, child]) => `${JSON.stringify(key)}:${canonicalJson(child)}`);+ return `{${entries.join(",")}}`;+ }+ return JSON.stringify(value) ?? "null";+}+var DIGEST_ALGORITHM = "sha256";var init_digest = () => {};// src/core/reliability/command-bridge.ts@@ -2226,12 +2248,12 @@ var init_llm_step = __esm(() => {});// src/core/brain/skill-rewrite-tasks.ts-import { posix as posix2 } from "node:path";+import { posix as posix3 } from "node:path";var SKILL_BENCHMARKS_DIR = "skill-benchmarks", SKILL_BENCHMARKS_ROOT_REL, SKILL_BENCH_TASK_KIND, SKILL_BENCH_TASK_KINDS, SKILL_BENCH_CHECK, SKILL_BENCH_CHECKS, SKILL_BENCH_VALUE_CLASS, SKILL_BENCH_VALUE_CLASSES;var init_skill_rewrite_tasks = __esm(() => {init_digest();init_path_constants();- SKILL_BENCHMARKS_ROOT_REL = posix2.join(BRAIN_ROOT_REL, SKILL_BENCHMARKS_DIR);+ SKILL_BENCHMARKS_ROOT_REL = posix3.join(BRAIN_ROOT_REL, SKILL_BENCHMARKS_DIR);SKILL_BENCH_TASK_KIND = Object.freeze({invocation_transcript: "invocation_transcript"});@@ -2322,7 +2344,46 @@ var init_skill_rewrite = __esm(() => {});// src/core/brain/wikilink.ts-var init_wikilink = () => {};+import { basename as basename2 } from "node:path";+function normaliseWikilinkTarget(value) {+ let s = value.trim();+ const wm = ANCHORED_WIKILINK_RE.exec(s);+ if (wm)+ s = wm[1].trim();+ return stripBasenameDecoration(s);+}+function stripWikilinkDecoration(body) {+ let s = body.trim();+ const pipe = s.indexOf("|");+ if (pipe >= 0)+ s = s.slice(0, pipe).trim();+ const hash = s.indexOf("#");+ if (hash >= 0)+ s = s.slice(0, hash).trim();+ return s;+}+function stripBasenameDecoration(body) {+ let s = stripWikilinkDecoration(body);+ s = basename2(s);+ if (s.endsWith(".md"))+ s = s.slice(0, -".md".length);+ return s;+}+function stripBrainIdPrefix(id) {+ return id.trim().replace(BRAIN_ID_PREFIX_RE, "").trim();+}+function parseWikilink(value) {+ const m = EXACT_WIKILINK_RE.exec(value.trim());+ if (!m)+ return null;+ return normaliseWikilinkTarget(m[1]);+}+var ANCHORED_WIKILINK_RE, EXACT_WIKILINK_RE, BRAIN_ID_PREFIX_RE;+var init_wikilink = __esm(() => {+ ANCHORED_WIKILINK_RE = /^\[\[([^\]]+)\]\]/;+ EXACT_WIKILINK_RE = /^\[\[([^\]]+)\]\]$/;+ BRAIN_ID_PREFIX_RE = /^(?:pref-|ret-)/;+});// src/core/brain/link-graph/format-wikilink.tsfunction isWikiLinkFormat(value) {@@ -2339,6 +2400,66 @@ var init_format_wikilink = __esm(() => {SUFFIX_INDEX_MEMO = new WeakMap;});+// src/core/store/constants.ts+var STORE_FORMAT_VERSION = 1, STORE_FORMAT_FILE = "FORMAT.md", STORE_IDENTITY_FILE = "store.json", STORE_PARTITIONS, STORE_STREAMS, LEDGER_STREAM = "ledgers", STORE_BLOBS_DIR = "blobs", STORE_SHARD_EXT = "jsonl", ENVELOPE_FIELDS, BLOB_REF_KEY = "$blob", BLOB_REF_BYTES_KEY = "bytes", COMPACTED_KIND = "compacted", STORE_RECORD_KINDS, STORE_LINE_CAP_BYTES, STORE_BODY_MAX_DEPTH = 64, STORE_BLOB_MAX_BYTES, STORE_ROOT_CONFIG_KEY = "store_root", STORE_ROOT_ENV = "OPEN_SECOND_BRAIN_STORE_ROOT", STORE_DEFAULT_DIR = "store", STORE_STATE_DIR = "stores", STORE_LOCKS_DIR = "locks", STORE_CLOCK_DIR = "clock", VAULT_ID_FIELD = "vault_id", AUTHORITIES, PREFERENCE_SET_KIND = "preference-set", PREFERENCE_REMOVE_KIND = "preference-remove", PREFERENCE_EVIDENCE_KIND = "preference-evidence", PINNED_SET_KIND = "pinned-set", PINNED_CLEAR_KIND = "pinned-clear", SETTING_SET_KIND = "setting-set", SETTING_UNSET_KIND = "setting-unset", DEVICE_RETIRE_KIND = "device-retire", STATE_DIGEST_KIND = "state-digest", FOLD_RECORD_KINDS, EVIDENCE_RESULTS, PREFERENCE_COUNTER_FIELDS, SETTING_VIEW_WRITER = "view.writer", SETTING_VIEW_LANGUAGE = "view.language", SETTING_TOPIC_MIN_RECORDS = "topics.new_min_records", SETTING_TOPIC_MIN_SESSIONS = "topics.new_min_sessions", SETTING_KEYS, STATE_DIGEST_FOLDS, DAY_MS, STORE_DUAL_WRITE_CONFIG_KEY = "store_dual_write", STORE_DUAL_WRITE_ENV = "OPEN_SECOND_BRAIN_STORE_DUAL_WRITE", SIGNAL_KIND = "signal", LOG_EVENT_KIND = "log-event", LEDGER_ROW_KIND = "ledger-row", DUAL_WRITE_RECORD_KINDS, DUAL_WRITE_STATUS_FILE = "dual-write.json", STORE_TMP_DIR = "tmp", BLOB_TEMP_PREFIX = ".tmp-";+var init_constants = __esm(() => {+ STORE_PARTITIONS = Object.freeze(["shared", "private"]);+ STORE_STREAMS = Object.freeze([+ "events",+ "log",+ "ledgers",+ "topics",+ "settings",+ "digests"+ ]);+ ENVELOPE_FIELDS = Object.freeze([+ "v",+ "id",+ "hlc",+ "device",+ "agent",+ "kind",+ "scope",+ "topic",+ "sum",+ "body"+ ]);+ STORE_RECORD_KINDS = Object.freeze([COMPACTED_KIND]);+ STORE_LINE_CAP_BYTES = 16 * 1024;+ STORE_BLOB_MAX_BYTES = 64 * 1024 * 1024;+ AUTHORITIES = Object.freeze(["human", "agent", "model"]);+ FOLD_RECORD_KINDS = Object.freeze([+ PREFERENCE_SET_KIND,+ PREFERENCE_REMOVE_KIND,+ PREFERENCE_EVIDENCE_KIND,+ PINNED_SET_KIND,+ PINNED_CLEAR_KIND,+ SETTING_SET_KIND,+ SETTING_UNSET_KIND,+ DEVICE_RETIRE_KIND,+ STATE_DIGEST_KIND+ ]);+ EVIDENCE_RESULTS = Object.freeze(["applied", "violated", "outdated"]);+ PREFERENCE_COUNTER_FIELDS = Object.freeze([+ "applied_count",+ "violated_count",+ "outdated_count"+ ]);+ SETTING_KEYS = Object.freeze([+ SETTING_VIEW_WRITER,+ SETTING_VIEW_LANGUAGE,+ SETTING_TOPIC_MIN_RECORDS,+ SETTING_TOPIC_MIN_SESSIONS+ ]);+ STATE_DIGEST_FOLDS = Object.freeze(["preferences", "pinned", "settings"]);+ DAY_MS = 24 * 60 * 60 * 1000;+ DUAL_WRITE_RECORD_KINDS = Object.freeze([+ SIGNAL_KIND,+ LOG_EVENT_KIND,+ LEDGER_ROW_KIND+ ]);+});+// src/core/config.tsvar exports_config = {};__export(exports_config, {@@ -2349,6 +2470,7 @@ __export(exports_config, {DECISION_RECALL_MAX_PER_SESSION_ENV_KEY: () => DECISION_RECALL_MAX_PER_SESSION_ENV_KEY,DECISION_RECALL_MIN_SPACING_TURNS_CONFIG_KEY: () => DECISION_RECALL_MIN_SPACING_TURNS_CONFIG_KEY,DECISION_RECALL_MIN_SPACING_TURNS_ENV_KEY: () => DECISION_RECALL_MIN_SPACING_TURNS_ENV_KEY,+ DEVICE_ID_ENV: () => DEVICE_ID_ENV,DEVICE_ID_RE: () => DEVICE_ID_RE,INSTALLATION_SECRET_CONFIG_KEY: () => INSTALLATION_SECRET_CONFIG_KEY,INSTALLATION_SECRET_ENV_KEY: () => INSTALLATION_SECRET_ENV_KEY,@@ -2375,9 +2497,12 @@ __export(exports_config, {installNamedSecretResolver: () => installNamedSecretResolver,isAnswerQuoteCheckMode: () => isAnswerQuoteCheckMode,isConfiguredAgentName: () => isConfiguredAgentName,+ isUsableLocalDeviceId: () => isUsableLocalDeviceId,isValidDeviceId: () => isValidDeviceId,isValidInstallationSecret: () => isValidInstallationSecret,+ isWindowsReservedDeviceId: () => isWindowsReservedDeviceId,parseSimpleYaml: () => parseSimpleYaml,+ readDeviceId: () => readDeviceId,resolveAgentName: () => resolveAgentName,resolveAnswerQuoteCheckActive: () => resolveAnswerQuoteCheckActive,resolveAnswerQuoteCheckRecall: () => resolveAnswerQuoteCheckRecall,@@ -2432,6 +2557,7 @@ __export(exports_config, {resolveSkillsAttachTriggers: () => resolveSkillsAttachTriggers,resolveSkillsAttachUsageOrdering: () => resolveSkillsAttachUsageOrdering,resolveSkillsDir: () => resolveSkillsDir,+ resolveStoreDualWrite: () => resolveStoreDualWrite,resolveTailTrimContextPack: () => resolveTailTrimContextPack,resolveTelegramBotToken: () => resolveTelegramBotToken,resolveTelegramCaptureAllowlist: () => resolveTelegramCaptureAllowlist,@@ -2601,14 +2727,29 @@ function resolveSharedNamespace(configPath) {function isValidDeviceId(value) {return DEVICE_ID_RE.test(value) && !value.startsWith("sync-conflict");}+function isWindowsReservedDeviceId(value) {+ return WINDOWS_RESERVED_DEVICE_NAME_RE.test(value);+}+function isUsableLocalDeviceId(value, platform = process.platform) {+ return isValidDeviceId(value) && !(platform === "win32" && isWindowsReservedDeviceId(value));+}+function readDeviceId(configPath) {+ const env = process.env[DEVICE_ID_ENV];+ if (env === "")+ return null;+ if (env !== undefined && isUsableLocalDeviceId(env))+ return env;+ const value = discoverConfig(configPath ?? defaultConfigPath()).data["device_id"];+ return value !== undefined && isUsableLocalDeviceId(value) ? value : null;+}function resolveDeviceId(configPath) {- const env = process.env["O2B_DEVICE_ID"];- if (env !== undefined && (env === "" || isValidDeviceId(env)))+ const env = process.env[DEVICE_ID_ENV];+ if (env !== undefined && (env === "" || isUsableLocalDeviceId(env)))return env;const resolved = configPath ?? defaultConfigPath();const read = () => {const value = discoverConfig(resolved).data["device_id"];- return value && isValidDeviceId(value) ? value : null;+ return value && isUsableLocalDeviceId(value) ? value : null;};const existing = read();if (existing !== null)@@ -2783,6 +2924,9 @@ function resolveNearDuplicateRetireSiblingsEnabled(configPath) {function resolveNearDuplicateWriteWideningEnabled(configPath) {return resolveConfigFlag("OPEN_SECOND_BRAIN_NEAR_DUPLICATE_WRITE_WIDENING_ENABLED", "near_duplicate_write_widening_enabled", configPath);}+function resolveStoreDualWrite(configPath) {+ return resolveConfigFlag(STORE_DUAL_WRITE_ENV, STORE_DUAL_WRITE_CONFIG_KEY, configPath);+}function resolveSessionHandoff(configPath) {return resolveConfigFlag("OPEN_SECOND_BRAIN_SESSION_HANDOFF", "session_handoff", configPath);}@@ -3126,7 +3270,7 @@ function expandTilde(p, platform = process.platform, home = homedir2()) {return join5(home, p.slice(2));return p;}-var import_proper_lockfile2, namedSecretResolver, CONFIG_VALUE_REJECTED_CHARS, UNSUPPORTED_CONFIG_PLATFORMS, UnsupportedPlatformError, ConfigReadError, UNCONFIGURED_AGENT_NAME = "agent", SHARED_NAMESPACE_KEY = "shared_namespace", DEVICE_ID_RE, INSTALLATION_SECRET_CONFIG_KEY = "installation_secret", INSTALLATION_SECRET_ENV_KEY = "O2B_INSTALLATION_SECRET", INSTALLATION_SECRET_RE, VAULT_STORE_REF_PREFIX = "vault://", VAULT_STORE_REF_HEX_LEN = 32, DECISION_RECALL_MAX_PER_SESSION_CONFIG_KEY = "decision_recall.max_per_session", DECISION_RECALL_MAX_PER_SESSION_ENV_KEY = "OPEN_SECOND_BRAIN_DECISION_RECALL_MAX_PER_SESSION", DECISION_RECALL_MIN_SPACING_TURNS_CONFIG_KEY = "decision_recall.min_spacing_turns", DECISION_RECALL_MIN_SPACING_TURNS_ENV_KEY = "OPEN_SECOND_BRAIN_DECISION_RECALL_MIN_SPACING_TURNS", LESSONS_PROMOTION_SCOPES_ENV_KEY = "OPEN_SECOND_BRAIN_LESSONS_PROMOTION_SCOPES", MODEL_CONTEXT_WINDOW_ENV_KEY = "OPEN_SECOND_BRAIN_MODEL_CONTEXT_WINDOW", ANSWER_QUOTE_CHECK_MODES, QUOTE_CHECK_BLOCK = "quote_check", ANSWER_QUOTE_CHECK_PHASES, QUOTE_CHECK_DEFAULT = "shadow", quoteCheckWarnedUnknownKeys, RECALL_INJECT_CAP_SPECS, REGROUND_PART_CHARS_DEFAULT = 9000, MAINTENANCE_EMBEDDINGS_ENV = "OPEN_SECOND_BRAIN_MAINTENANCE_EMBEDDINGS", MAINTENANCE_EMBEDDINGS_CONFIG_KEY = "maintenance_embeddings", MAINTENANCE_CUSTOM_TASKS_ENV = "OPEN_SECOND_BRAIN_MAINTENANCE_CUSTOM_TASKS", MAINTENANCE_CUSTOM_TASKS_CONFIG_KEY = "maintenance_custom_tasks", PARTNER_CODEGRAPH_DISABLED_ENV = "OPEN_SECOND_BRAIN_PARTNER_CODEGRAPH_DISABLED", PARTNER_CODEGRAPH_DISABLED_CONFIG_KEY = "partner_codegraph_disabled", SESSION_CAPTURE_ROLES, SKILL_REWRITE_MODE_CONFIG_KEY = "skill_rewrite.mode", SKILL_REWRITE_MODE_ENV_KEY = "OPEN_SECOND_BRAIN_SKILL_REWRITE_MODE", SKILL_REWRITE_JUDGE_CMD_CONFIG_KEY = "skill_rewrite_judge_cmd", SKILL_REWRITE_JUDGE_CMD_ENV_KEY = "OPEN_SECOND_BRAIN_SKILL_REWRITE_JUDGE_CMD";+var import_proper_lockfile2, namedSecretResolver, CONFIG_VALUE_REJECTED_CHARS, UNSUPPORTED_CONFIG_PLATFORMS, UnsupportedPlatformError, ConfigReadError, UNCONFIGURED_AGENT_NAME = "agent", SHARED_NAMESPACE_KEY = "shared_namespace", DEVICE_ID_RE, WINDOWS_RESERVED_DEVICE_NAME_RE, DEVICE_ID_ENV = "O2B_DEVICE_ID", INSTALLATION_SECRET_CONFIG_KEY = "installation_secret", INSTALLATION_SECRET_ENV_KEY = "O2B_INSTALLATION_SECRET", INSTALLATION_SECRET_RE, VAULT_STORE_REF_PREFIX = "vault://", VAULT_STORE_REF_HEX_LEN = 32, DECISION_RECALL_MAX_PER_SESSION_CONFIG_KEY = "decision_recall.max_per_session", DECISION_RECALL_MAX_PER_SESSION_ENV_KEY = "OPEN_SECOND_BRAIN_DECISION_RECALL_MAX_PER_SESSION", DECISION_RECALL_MIN_SPACING_TURNS_CONFIG_KEY = "decision_recall.min_spacing_turns", DECISION_RECALL_MIN_SPACING_TURNS_ENV_KEY = "OPEN_SECOND_BRAIN_DECISION_RECALL_MIN_SPACING_TURNS", LESSONS_PROMOTION_SCOPES_ENV_KEY = "OPEN_SECOND_BRAIN_LESSONS_PROMOTION_SCOPES", MODEL_CONTEXT_WINDOW_ENV_KEY = "OPEN_SECOND_BRAIN_MODEL_CONTEXT_WINDOW", ANSWER_QUOTE_CHECK_MODES, QUOTE_CHECK_BLOCK = "quote_check", ANSWER_QUOTE_CHECK_PHASES, QUOTE_CHECK_DEFAULT = "shadow", quoteCheckWarnedUnknownKeys, RECALL_INJECT_CAP_SPECS, REGROUND_PART_CHARS_DEFAULT = 9000, MAINTENANCE_EMBEDDINGS_ENV = "OPEN_SECOND_BRAIN_MAINTENANCE_EMBEDDINGS", MAINTENANCE_EMBEDDINGS_CONFIG_KEY = "maintenance_embeddings", MAINTENANCE_CUSTOM_TASKS_ENV = "OPEN_SECOND_BRAIN_MAINTENANCE_CUSTOM_TASKS", MAINTENANCE_CUSTOM_TASKS_CONFIG_KEY = "maintenance_custom_tasks", PARTNER_CODEGRAPH_DISABLED_ENV = "OPEN_SECOND_BRAIN_PARTNER_CODEGRAPH_DISABLED", PARTNER_CODEGRAPH_DISABLED_CONFIG_KEY = "partner_codegraph_disabled", SESSION_CAPTURE_ROLES, SKILL_REWRITE_MODE_CONFIG_KEY = "skill_rewrite.mode", SKILL_REWRITE_MODE_ENV_KEY = "OPEN_SECOND_BRAIN_SKILL_REWRITE_MODE", SKILL_REWRITE_JUDGE_CMD_CONFIG_KEY = "skill_rewrite_judge_cmd", SKILL_REWRITE_JUDGE_CMD_ENV_KEY = "OPEN_SECOND_BRAIN_SKILL_REWRITE_JUDGE_CMD";var init_config = __esm(() => {init_fs_atomic();init_secret_ref();@@ -3137,6 +3281,7 @@ var init_config = __esm(() => {init_path_constants();init_skill_rewrite();init_format_wikilink();+ init_constants();import_proper_lockfile2 = __toESM(require_proper_lockfile(), 1);CONFIG_VALUE_REJECTED_CHARS = ['"', "\\", ``, "\r"];@@ -3158,6 +3303,7 @@ var init_config = __esm(() => {}};DEVICE_ID_RE = /^[a-z0-9][a-z0-9-]{0,31}$/;+ WINDOWS_RESERVED_DEVICE_NAME_RE = /^(con|prn|aux|nul|com[1-9]|lpt[1-9])$/;INSTALLATION_SECRET_RE = /^[0-9a-f]{32}$/;ANSWER_QUOTE_CHECK_MODES = Object.freeze(["off", "shadow", "enforce"]);ANSWER_QUOTE_CHECK_PHASES = Object.freeze(["recall", "active", "subagent"]);@@ -3313,6 +3459,11 @@ function stripPrivateRegions(text) {}return output + text.slice(cursor);}+function privateRegionTexts(text) {+ if (!text)+ return [];+ return privateRegionSpans(text).map((span) => text.slice(span.start, span.end));+}function scanRawOutput(text, opts = {}) {if (!text)return { text, truncated: false };@@ -3587,65 +3738,23 @@ var init_ledger_shards = __esm(() => {NAME_RE_CACHE = new Map;});-// src/core/reliability/audit.ts-import { closeSync as closeSync2, fsyncSync as fsyncSync2, mkdirSync as mkdirSync5, openSync as openSync2, writeFileSync } from "node:fs";-import { join as join6 } from "node:path";-function appendAuditRecord(auditRoot, record) {- const timestamp = new Date(record.timestamp);- if (!Number.isFinite(timestamp.getTime())) {- throw new Error(`invalid audit timestamp: ${record.timestamp}`);- }- mkdirSync5(auditRoot, { recursive: true });- const path = join6(auditRoot, shardedFileName(isoWeekLabel(timestamp), resolveAppendShardId(), JSONL_LEDGER_EXT));- const line = redactRawOutput(JSON.stringify(record), {- maxInput: Number.POSITIVE_INFINITY- });- const fileDescriptor = openSync2(path, "a", 384);- try {- writeFileSync(fileDescriptor, line + `-`, "utf8");- fsyncSync2(fileDescriptor);- } finally {- closeSync2(fileDescriptor);- }- return path;-}-function isoWeekLabel(input) {- const date = new Date(Date.UTC(input.getUTCFullYear(), input.getUTCMonth(), input.getUTCDate()));- const dayNumber = date.getUTCDay() || 7;- date.setUTCDate(date.getUTCDate() + 4 - dayNumber);- const year = date.getUTCFullYear();- const yearStart = new Date(Date.UTC(year, 0, 1));- const week = Math.ceil(((date.getTime() - yearStart.getTime()) / 86400000 + 1) / 7);- return `${year}-W${String(week).padStart(2, "0")}`;-}-var AUDIT_WEEK_SHARD_GRAMMAR;-var init_audit = __esm(() => {- init_redactor();- init_ledger_shards();- AUDIT_WEEK_SHARD_GRAMMAR = Object.freeze({- base: "\\d{4}-W\\d{2}",- extensions: Object.freeze([JSONL_LEDGER_EXT])+// src/core/origin-channel.ts+var ORIGIN_CHANNEL, ORIGIN_CHANNELS;+var init_origin_channel = __esm(() => {+ ORIGIN_CHANNEL = Object.freeze({+ mcpTool: "mcp-tool",+ cli: "cli",+ import: "import"});-});--// src/core/brain/audit-dirs.ts-var SESSION_LIFECYCLE_AUDIT_DIR = "session-lifecycle", HYGIENE_AUDIT_DIR = "hygiene", SECRET_CUSTODY_AUDIT_DIR = "secret-custody", WATCHDOG_AUDIT_DIR = "watchdog", BRAIN_LOG_AUDIT_DIRS;-var init_audit_dirs = __esm(() => {- BRAIN_LOG_AUDIT_DIRS = Object.freeze([- SESSION_LIFECYCLE_AUDIT_DIR,- HYGIENE_AUDIT_DIR,- SECRET_CUSTODY_AUDIT_DIR,- WATCHDOG_AUDIT_DIR- ]);+ ORIGIN_CHANNELS = Object.freeze(Object.values(ORIGIN_CHANNEL));});// src/core/path-safety.tsimport { existsSync as existsSync4, realpathSync, statSync as statSync4 } from "node:fs";import {- basename as basename2,+ basename as basename3,dirname as dirname5,- join as join7,+ join as join6,posix as pathPosix,relative,resolve as resolve4,@@ -3671,6 +3780,13 @@ function realpathInsideVault(target, vault) {const realAncestor = safeRealpath(deepestExistingAncestor(resolve4(target)));return isLexicallyInsideHost(realAncestor, realVault);}+function pathIsInside(target, root) {+ return pathIsInsideOn(hostPlatform(), target, root);+}+function pathIsInsideOn(platform, target, root) {+ const pathImpl = platform === "win32" ? pathWin32 : pathPosix;+ return isLexicallyInside(platform, pathImpl.resolve(target), pathImpl.resolve(root));+}function isLexicallyInside(platform, target, root) {const fold = platform === "win32";const sepChar = fold ? pathWin32.sep : pathPosix.sep;@@ -3703,6 +3819,9 @@ function safeRealpath(p) {throw err;}}+function posixRel(p) {+ return sep2 === "/" ? p : p.replaceAll("\\", "/");+}function vaultRelative(target, vault) {const rel = relative(resolve4(vault), resolve4(target));return rel.split(/[\\/]/).filter((p) => p.length > 0).join(pathPosix.sep);@@ -3824,9 +3943,9 @@ var init_stamp = __esm(() => {// src/core/brain/freeze-marker.tsimport { existsSync as existsSync5, readFileSync as readFileSync5, statSync as statSync5 } from "node:fs";-import { join as join8, resolve as resolve5 } from "node:path";+import { join as join7, resolve as resolve5 } from "node:path";function frozenMarkerPath(vault) {- return ensureInsideVault(join8(vault, BRAIN_INTERNAL_STATE_REL, FROZEN_MARKER_FILE), vault);+ return ensureInsideVault(join7(vault, BRAIN_INTERNAL_STATE_REL, FROZEN_MARKER_FILE), vault);}function parseMarker(path) {reloadCount += 1;@@ -3931,9 +4050,9 @@ var init_freeze_marker = __esm(() => {// src/core/brain/vault-identity.tsimport { existsSync as existsSync6, readFileSync as readFileSync6, statSync as statSync6 } from "node:fs";-import { join as join9, resolve as resolve6 } from "node:path";+import { join as join8, resolve as resolve6 } from "node:path";function vaultIdentityPath(vault) {- return ensureInsideVault(join9(vault, BRAIN_ROOT_REL, VAULT_IDENTITY_FILE), vault);+ return ensureInsideVault(join8(vault, BRAIN_ROOT_REL, VAULT_IDENTITY_FILE), vault);}function readVaultIdentity(vault) {const path = vaultIdentityPath(vault);@@ -4016,7 +4135,7 @@ function assertVaultIdentityForWrite(vault, sink, lane = WRITE_LANE.content) {}if (pinned === vaultId)return;- const mismatch = compareStamps({ [VAULT_ID_FIELD]: pinned }, { [VAULT_ID_FIELD]: vaultId })[0];+ const mismatch = compareStamps({ [VAULT_ID_FIELD2]: pinned }, { [VAULT_ID_FIELD2]: vaultId })[0];const evidence = mismatch;throw new VaultIdentityMismatchError(degradationNotice({code: DEGRADATION_CODE.vaultMarkerMismatch,@@ -4025,7 +4144,7 @@ function assertVaultIdentityForWrite(vault, sink, lane = WRITE_LANE.content) {detail: `refusing to write: the store at this root is not the one this process opened (${formatStampMismatch(evidence)})`}), evidence);}-var VAULT_IDENTITY_SCHEMA_VERSION = 1, VAULT_IDENTITY_FILE = "vault-id.json", SITE2 = "vault-identity", VAULT_ID_FIELD = "vault_id", VaultIdentityMismatchError, PINNED_IDENTITIES, MARKER_STAMPS2, MARKER_PATHS2;+var VAULT_IDENTITY_SCHEMA_VERSION = 1, VAULT_IDENTITY_FILE = "vault-id.json", SITE2 = "vault-identity", VAULT_ID_FIELD2 = "vault_id", VaultIdentityMismatchError, PINNED_IDENTITIES, MARKER_STAMPS2, MARKER_PATHS2;var init_vault_identity = __esm(() => {init_fs_atomic();init_path_safety();@@ -4048,180 +4167,2130 @@ var init_vault_identity = __esm(() => {MARKER_PATHS2 = new Map;});-// src/core/brain/paths.ts-import { join as join10 } from "node:path";-function brainDirs(vault) {- const brain = ensureInsideVault(join10(vault, BRAIN_ROOT_REL), vault);- return {- brain,- inbox: ensureInsideVault(join10(vault, BRAIN_INBOX_REL), vault),- processed: ensureInsideVault(join10(vault, BRAIN_PROCESSED_REL), vault),- archived: ensureInsideVault(join10(vault, BRAIN_ARCHIVED_SIGNALS_REL), vault),- pending: ensureInsideVault(join10(vault, BRAIN_PENDING_REL), vault),- preferences: ensureInsideVault(join10(vault, BRAIN_PREFERENCES_REL), vault),- retired: ensureInsideVault(join10(vault, BRAIN_RETIRED_REL), vault),- log: ensureInsideVault(join10(vault, BRAIN_LOG_REL), vault),- entities: ensureInsideVault(join10(vault, BRAIN_ENTITIES_REL), vault),- bases: ensureInsideVault(join10(vault, BRAIN_BASES_REL), vault),- snapshots: ensureInsideVault(join10(vault, BRAIN_SNAPSHOTS_REL), vault)- };-}-function brainDirsForWrite(vault, notices, lane) {- assertVaultIdentityForWrite(vault, notices, lane);- return brainDirs(vault);+// src/core/store/hlc.ts+function formatHlc(clock) {+ return `${clock.physical}.${clock.counter}`;}-var init_paths = __esm(() => {- init_fs_atomic();- init_path_safety();- init_ledger_shards();- init_path_constants();- init_vault_identity();- init_skill_rewrite_tasks();- init_skill_rewrite();- init_path_safety();- init_freeze_marker();- init_path_constants();+function parseHlc(text) {+ const match = HLC_RE.exec(text);+ if (match === null)+ return null;+ const physical = Number(match[1]);+ const counter = Number(match[2]);+ if (!Number.isSafeInteger(physical) || !Number.isSafeInteger(counter))+ return null;+ return { physical, counter };+}+function sendHlc(local, wallMs) {+ const wall = Math.max(0, Math.floor(wallMs));+ if (wall > local.physical)+ return { physical: wall, counter: 0 };+ return { physical: local.physical, counter: local.counter + 1 };+}+var HLC_MAX_DRIFT_MS, HLC_ZERO, HLC_RE;+var init_hlc = __esm(() => {+ HLC_MAX_DRIFT_MS = 24 * 60 * 60 * 1000;+ HLC_ZERO = Object.freeze({ physical: 0, counter: 0 });+ HLC_RE = /^(0|[1-9]\d{0,15})\.(0|[1-9]\d{0,9})$/;});-// src/core/brain/time.ts-function isoSecond(d = new Date) {- return d.toISOString().replace(/\.\d{3}Z$/, "Z");+// src/core/brain/sync-lockfile.ts+import {+ closeSync as closeSync2,+ constants as fsConstants,+ fstatSync,+ lstatSync,+ readFileSync as readFileSync7,+ mkdirSync as mkdirSync5,+ openSync as openSync2,+ readdirSync,+ unlinkSync as unlinkSync2,+ writeSync as writeSync2+} from "node:fs";+function isWindowsDeletePending(e, lockPath, platform = process.platform, occupied = nameIsOccupied) {+ if (platform !== "win32" || e.code !== "EPERM" && e.code !== "EACCES")+ return false;+ return occupied(lockPath);}-var init_time = () => {};--// src/core/brain/secrets/value-cipher.ts-import { createCipheriv, createDecipheriv, randomBytes as randomBytes2 } from "node:crypto";-function encryptValue(key, plaintext, aad) {- const iv = randomBytes2(IV_BYTES);- const cipher = createCipheriv(ALGORITHM, key, iv);- if (aad !== undefined)- cipher.setAAD(Buffer.from(aad, "utf8"));- const ciphertext = Buffer.concat([cipher.update(plaintext, "utf8"), cipher.final()]);- return {- ciphertext: ciphertext.toString("base64"),- iv: iv.toString("base64"),- tag: cipher.getAuthTag().toString("base64")- };+function nameIsOccupied(path) {+ try {+ lstatSync(path);+ return true;+ } catch (err) {+ return err.code !== "ENOENT";+ }}-function decryptValue(key, encrypted, aad) {- const decipher = createDecipheriv(ALGORITHM, key, Buffer.from(encrypted.iv, "base64"));- decipher.setAuthTag(Buffer.from(encrypted.tag, "base64"));- if (aad !== undefined)- decipher.setAAD(Buffer.from(aad, "utf8"));- const plaintext = Buffer.concat([- decipher.update(Buffer.from(encrypted.ciphertext, "base64")),- decipher.final()- ]);- return plaintext.toString("utf8");+function resolveLockWaitBudgetMs(env = process.env) {+ const raw = env[LOCK_WAIT_BUDGET_ENV];+ if (raw === undefined || raw.trim() === "")+ return LOCK_WAIT_BUDGET_MS;+ const text = raw.trim();+ const parsed = /^\d+$/.test(text) ? Number(text) : Number.NaN;+ if (!Number.isSafeInteger(parsed)) {+ throw new Error(`${LOCK_WAIT_BUDGET_ENV}=${raw} is not a lock wait; set it to a whole number of ` + `milliseconds >= 0 (the default is ${LOCK_WAIT_BUDGET_MS}), or unset it`);+ }+ return parsed;}-var ALGORITHM = "aes-256-gcm", IV_BYTES = 12;-var init_value_cipher = () => {};+var heldLocks, LOCK_WAIT_BUDGET_MS = 5000, LOCK_WAIT_BUDGET_ENV = "OPEN_SECOND_BRAIN_LOCK_WAIT_MS", RETRY_SLEEP_CEILING_MS = 25, contendedReleases, HANDOFF_WINDOW_MS, AGED_WAITER_AFTER_MS, POSIX_MIN_STAMP_BYTES = 48, WIN32_MIN_STAMP_BYTES = 30, MIN_STAMP_BYTES, WAITER_MARK, MARK_OPEN_FLAGS;+var init_sync_lockfile = __esm(() => {+ init_path_constants();+ heldLocks = new Map;+ contendedReleases = new Map;+ HANDOFF_WINDOW_MS = RETRY_SLEEP_CEILING_MS * 4;+ AGED_WAITER_AFTER_MS = RETRY_SLEEP_CEILING_MS * 10;+ MIN_STAMP_BYTES = process.platform === "win32" ? WIN32_MIN_STAMP_BYTES : POSIX_MIN_STAMP_BYTES;+ WAITER_MARK = Buffer.from("w", "utf8");+ MARK_OPEN_FLAGS = fsConstants.O_RDWR | (fsConstants.O_NOFOLLOW ?? 0);+});-// src/core/brain/secrets/owner-acl.ts-import { spawnSync } from "node:child_process";-import { resolve as resolve7, win32 as win322 } from "node:path";-function system32Tool(name, env = process.env) {- const root = env["SystemRoot"] || env["windir"] || "C:\\Windows";- return win322.join(root, "System32", name);-}-function parseWhoamiUser(stdout) {- const m = /^\s*"([^"]+)","(S-1-\d+(?:-\d+)+)"\s*$/m.exec(stdout);- return m ? { name: m[1], sid: m[2] } : null;+// src/core/store/local-lock.ts+import { mkdirSync as mkdirSync6 } from "node:fs";+import { dirname as dirname6 } from "node:path";+function isLockContention(err, lockTarget, platform = process.platform) {+ const e = err;+ return e.code === "ELOCKED" || isWindowsDeletePending(e, `${lockTarget}.lock`, platform);+}+function isWindowsRefusal(err, platform = process.platform) {+ const code = err.code;+ return platform === "win32" && (code === "EPERM" || code === "EACCES");+}+function acquireDirLock(lockTarget, options) {+ const started = Date.now();+ let refusalRetried = false;+ for (let attempt = 0;; attempt++) {+ try {+ return import_proper_lockfile3.default.lockSync(lockTarget, { stale: options.staleMs, realpath: false });+ } catch (err) {+ if (!isLockContention(err, lockTarget)) {+ if (refusalRetried || !isWindowsRefusal(err))+ throw err;+ refusalRetried = true;+ continue;+ }+ if (Date.now() - started >= options.budgetMs) {+ const refused = new Error(`${options.label} busy: ${lockTarget}: still held after waiting ` + `${Date.now() - started} ms; ${options.remedy}`, { cause: err });+ refused.code = "ELOCKED";+ refused.path = lockTarget;+ throw refused;+ }+ sleepSync(1 + Math.floor(Math.random() * Math.min(RETRY_SLEEP_MAX_MS, 2 + attempt * 2)));+ }+ }}-function currentWindowsIdentity() {- if (cachedIdentity !== undefined)- return cachedIdentity;+function withLocalLock(lockTarget, fn, budgetMs) {+ mkdirSync6(dirname6(lockTarget), { recursive: true });+ const release = acquireDirLock(lockTarget, {+ staleMs: STORE_LOCK_STALE_MS,+ budgetMs: budgetMs ?? resolveLockWaitBudgetMs(),+ label: "store lock",+ remedy: "retry once the other writer finishes, or allow a longer wait with " + "OPEN_SECOND_BRAIN_LOCK_WAIT_MS=<milliseconds>"+ });try {- const proc = spawnSync(system32Tool("whoami.exe"), ["/user", "/fo", "csv", "/nh"], {- encoding: "utf8",- windowsHide: true,- timeout: TOOL_TIMEOUT_MS- });- cachedIdentity = proc.error === undefined && proc.status === 0 ? parseWhoamiUser(proc.stdout) : null;- } catch {- cachedIdentity = null;+ return fn();+ } finally {+ release();}- return cachedIdentity;}-function ownerOnlyAclArgv(path, sid, kind) {- const rights = kind === "directory" ? "(OI)(CI)F" : "F";- return [path, "/inheritance:r", "/grant:r", `*${sid}:${rights}`];+var import_proper_lockfile3, STORE_LOCK_STALE_MS = 60000, RETRY_SLEEP_MAX_MS = 20;+var init_local_lock = __esm(() => {+ init_sync_lockfile();+ init_fs_atomic();+ import_proper_lockfile3 = __toESM(require_proper_lockfile(), 1);+});++// src/core/store/clock-store.ts+import { readFileSync as readFileSync8 } from "node:fs";+import { join as join9 } from "node:path";+function clockFilePath(deviceStateDir, device) {+ return join9(deviceStateDir, STORE_CLOCK_DIR, `${device}.json`);}-function restrictToOwner(path, kind, platform = process.platform, force = false) {- if (platform !== "win32")- return true;- const key = `${kind}:${resolve7(path).toLowerCase()}`;- if (!force && restricted.has(key))- return true;- let detail;+function readClock(deviceStateDir, device) {+ let text;try {- const identity = currentWindowsIdentity();- if (identity === null) {- detail = "the current user's SID could not be read (whoami /user)";- } else {- let proc = spawnSync(system32Tool("icacls.exe"), [path, "/reset"], {- encoding: "utf8",- windowsHide: true,- timeout: TOOL_TIMEOUT_MS- });- if (proc.error === undefined && proc.status === 0) {- proc = spawnSync(system32Tool("icacls.exe"), [...ownerOnlyAclArgv(path, identity.sid, kind)], { encoding: "utf8", windowsHide: true, timeout: TOOL_TIMEOUT_MS });- }- if (proc.error === undefined && proc.status === 0) {- restricted.add(key);- return true;- }- detail = proc.error !== undefined ? proc.error.message : `icacls exited ${proc.status ?? proc.signal}: ${(proc.stderr || proc.stdout).trim()}`;- }+ text = readFileSync8(clockFilePath(deviceStateDir, device), "utf8");} catch (err) {- detail = err instanceof Error ? err.message : String(err);+ if (err.code === "ENOENT")+ return null;+ throw err;}- process.stderr.write(`warning: could not restrict secrets ${kind} to the current user, ` + `it keeps its inherited ACL: ${path}: ${detail}+ try {+ const parsed = JSON.parse(text);+ return typeof parsed.hlc === "string" ? parseHlc(parsed.hlc) : null;+ } catch {+ return null;+ }+}+function update(deviceStateDir, device, step) {+ const path = clockFilePath(deviceStateDir, device);+ return withLocalLock(path, () => {+ const next = step(readClock(deviceStateDir, device) ?? HLC_ZERO);+ atomicWriteText(path, `${JSON.stringify({ hlc: formatHlc(next) })}`);- return false;+ return next;+ });}-var TOOL_TIMEOUT_MS = 1e4, cachedIdentity, restricted;-var init_owner_acl = __esm(() => {- restricted = new Set;+function tickClock(deviceStateDir, device, now = systemWallClock) {+ return update(deviceStateDir, device, (local) => sendHlc(local, now()));+}+var systemWallClock = () => Date.now();+var init_clock_store = __esm(() => {+ init_fs_atomic();+ init_constants();+ init_hlc();+ init_local_lock();});-// src/core/brain/secrets/envelope.ts-import { randomBytes as randomBytes3, scryptSync, timingSafeEqual } from "node:crypto";-import {- chmodSync,- closeSync as closeSync3,- fsyncSync as fsyncSync3,- openSync as openSync3,- readFileSync as readFileSync7,- unlinkSync as unlinkSync2,- writeSync as writeSync2-} from "node:fs";-import { dirname as dirname6, resolve as resolve8 } from "node:path";-function kdfCostCurveRefusal(kdf) {- if (kdf.n > SCRYPT_N_MAX) {- return `kdf n ${String(kdf.n)} exceeds this build's ceiling ${String(SCRYPT_N_MAX)}`;- }- if (kdf.r > SCRYPT_R_MAX) {- return `kdf r ${String(kdf.r)} exceeds this build's ceiling ${String(SCRYPT_R_MAX)}`;- }- if (kdf.p > SCRYPT_P_MAX) {- return `kdf p ${String(kdf.p)} exceeds this build's ceiling ${String(SCRYPT_P_MAX)}`;+// src/core/store/ulid.ts+import { randomBytes as randomBytes2 } from "node:crypto";+function encodeTime(time) {+ let out = "";+ let rest = time;+ for (let i = 0;i < TIME_CHARS; i++) {+ out = ALPHABET[rest % 32] + out;+ rest = Math.floor(rest / 32);}- if (kdf.maxmem > SCRYPT_MAXMEM_MAX) {- return `kdf maxmem ${String(kdf.maxmem)} exceeds this build's ceiling ${String(SCRYPT_MAXMEM_MAX)}`;+ return out;+}+function freshRandom() {+ const bytes = randomBytes2(RANDOM_CHARS);+ return Array.from(bytes, (byte) => byte % 32);+}+function increment(digits) {+ for (let i = digits.length - 1;i >= 0; i--) {+ if (digits[i] < 31) {+ digits[i] += 1;+ return true;+ }+ digits[i] = 0;}- const needed = 128 * kdf.n * kdf.r;- if (kdf.maxmem < needed) {- return `kdf maxmem ${String(kdf.maxmem)} is below the ${String(needed)} bytes ` + `these n/r parameters need`;+ return false;+}+function newUlid(nowMs = Date.now()) {+ const time = Math.min(MAX_TIME, Math.max(0, Math.floor(nowMs)));+ if (time === lastTime) {+ if (!increment(lastRandom)) {+ lastTime += 1;+ lastRandom = freshRandom();+ }+ } else {+ lastTime = time;+ lastRandom = freshRandom();}- return null;+ return encodeTime(lastTime) + lastRandom.map((d) => ALPHABET[d]).join("");}-function holderSlot(keyPath) {- const resolved = resolve8(keyPath);- return process.platform === "win32" ? resolved.toLowerCase() : resolved;+function isUlid(value) {+ return typeof value === "string" && ULID_RE.test(value);}-function heldUnlockedKey(keyPath) {- return HELD_KEYS.get(holderSlot(keyPath)) ?? null;+var ALPHABET = "0123456789ABCDEFGHJKMNPQRSTVWXYZ", TIME_CHARS = 10, RANDOM_CHARS = 16, ULID_RE, MAX_TIME, lastTime = -1, lastRandom;+var init_ulid = __esm(() => {+ ULID_RE = /^[0-7][0-9A-HJKMNP-TV-Z]{25}$/;+ MAX_TIME = 2 ** 48 - 1;+ lastRandom = [];+});++// src/core/store/envelope.ts+function canonicalBodyText(body) {+ return canonicalJson(body);+}+function bodyChecksum(body) {+ return sha256Hex(canonicalBodyText(body));+}+function isPlainObject(value) {+ return typeof value === "object" && value !== null && !Array.isArray(value);+}+function bodyTooDeep(body) {+ const stack = [[body, 1]];+ while (stack.length > 0) {+ const [value, depth] = stack.pop();+ if (value === null || typeof value !== "object")+ continue;+ if (depth > STORE_BODY_MAX_DEPTH)+ return true;+ for (const child of Array.isArray(value) ? value : Object.values(value)) {+ if (child !== null && typeof child === "object")+ stack.push([child, depth + 1]);+ }+ }+ return false;+}+function labelProblem(value) {+ if (typeof value !== "string" || value.trim() === "" || value.length > MAX_LABEL_LENGTH) {+ return `must be a non-empty string of at most ${MAX_LABEL_LENGTH} characters`;+ }+ if (/[\r\n]/.test(value))+ return "must be one line";+ return null;+}+function isRecordLabel(value) {+ return labelProblem(value) === null;+}+function label(name, value, nullable) {+ if (value === null || value === undefined) {+ if (nullable)+ return null;+ throw new EnvelopeError(`record ${name} is required`);+ }+ const problem = labelProblem(value);+ if (problem !== null)+ throw new EnvelopeError(`record ${name} ${problem}`);+ return value;+}+function buildRecord(input) {+ if (!isValidDeviceId(input.device)) {+ throw new EnvelopeError(`record device "${input.device}" is not a valid device id (lowercase letters, digits and hyphens, not "sync-conflict")`);+ }+ if (!RECORD_KIND_RE.test(input.kind)) {+ throw new EnvelopeError(`record kind "${input.kind}" must match ${RECORD_KIND_RE}`);+ }+ const agent = label("agent", input.agent, false);+ const scope = label("scope", input.scope, true);+ const topic = input.topic ?? null;+ if (topic !== null && !isUlid(topic)) {+ throw new EnvelopeError(`record topic "${topic}" must be a topic id (ULID) or null`);+ }+ if (!isPlainObject(input.body))+ throw new EnvelopeError("record body must be a JSON object");+ if (bodyTooDeep(input.body))+ throw new EnvelopeError(`record ${BODY_TOO_DEEP_REASON}`);+ if (BLOB_REF_KEY in input.body) {+ throw new EnvelopeError(`record body must not use the reserved key "${BLOB_REF_KEY}"`);+ }+ const id = input.id ?? newUlid(input.hlc.physical);+ if (!isUlid(id))+ throw new EnvelopeError(`record id "${id}" must be a ULID`);+ const body = JSON.parse(JSON.stringify(input.body));+ return {+ v: STORE_FORMAT_VERSION,+ id,+ hlc: formatHlc(input.hlc),+ device: input.device,+ agent,+ kind: input.kind,+ scope,+ topic,+ sum: bodyChecksum(body),+ body+ };+}+var EnvelopeError, RECORD_KIND_RE, MAX_LABEL_LENGTH = 200, BODY_TOO_DEEP_REASON;+var init_envelope = __esm(() => {+ init_config();+ init_digest();+ init_constants();+ init_hlc();+ init_ulid();+ EnvelopeError = class EnvelopeError extends Error {+ constructor(message) {+ super(message);+ this.name = "EnvelopeError";+ }+ };+ RECORD_KIND_RE = /^[a-z][a-z0-9-]{0,63}$/;+ BODY_TOO_DEEP_REASON = `body nests deeper than ${STORE_BODY_MAX_DEPTH} levels`;+});++// src/core/store/safe-fs.ts+import {+ closeSync as closeSync3,+ constants,+ fstatSync as fstatSync2,+ lstatSync as lstatSync2,+ mkdirSync as mkdirSync7,+ openSync as openSync3+} from "node:fs";+import { dirname as dirname7, isAbsolute as isAbsolute2, join as join10, relative as relative2, sep as sep3 } from "node:path";+function errnoCode(err) {+ return err?.code;+}+function lstatOrNull(path) {+ try {+ return lstatSync2(path);+ } catch (err) {+ if (errnoCode(err) === "ENOENT")+ return null;+ throw err;+ }+}+function assertRealDirectory(path) {+ const stat = lstatOrNull(path);+ if (stat === null)+ return;+ if (stat.isSymbolicLink())+ throw new StoreUnsafePathError(path, "is a symbolic link");+ if (!stat.isDirectory())+ throw new StoreUnsafePathError(path, "is not a directory");+}+function ensureStoreDir(partitionRoot, dir) {+ const rel = relative2(partitionRoot, dir);+ if (rel === ".." || rel.startsWith(`..${sep3}`) || isAbsolute2(rel)) {+ throw new StoreUnsafePathError(dir, "is outside the partition folder");+ }+ mkdirSync7(partitionRoot, { recursive: true, mode: STORE_DIR_MODE });+ let current = partitionRoot;+ for (const part of rel === "" ? [] : rel.split(sep3)) {+ current = join10(current, part);+ assertRealDirectory(current);+ try {+ mkdirSync7(current, { mode: STORE_DIR_MODE });+ } catch (err) {+ if (errnoCode(err) !== "EEXIST")+ throw err;+ }+ assertRealDirectory(current);+ }+}+function isRealDirBelowPartition(partitionRoot, dir) {+ const rel = relative2(partitionRoot, dir);+ if (rel === ".." || rel.startsWith(`..${sep3}`) || isAbsolute2(rel))+ return false;+ let current = partitionRoot;+ for (const part of rel === "" ? [] : rel.split(sep3)) {+ current = join10(current, part);+ const stat = lstatOrNull(current);+ if (stat === null || stat.isSymbolicLink() || !stat.isDirectory())+ return false;+ }+ return true;+}+function openRegularFileForRead(path, partitionRoot) {+ if (!lstatSync2(path).isFile())+ return null;+ let fd;+ try {+ fd = openSync3(path, constants.O_RDONLY | NO_FOLLOW | NON_BLOCK);+ } catch (err) {+ if (errnoCode(err) === "ELOOP")+ return null;+ throw err;+ }+ let keep = false;+ try {+ const opened = fstatSync2(fd);+ keep = opened.isFile() && (NO_FOLLOW !== 0 || nameIsOpenedFile(path, opened)) && (partitionRoot === undefined || isRealDirBelowPartition(partitionRoot, dirname7(path)));+ } finally {+ if (!keep)+ closeSync3(fd);+ }+ return keep ? fd : null;+}+function nameIsOpenedFile(path, opened) {+ const now = lstatOrNull(path);+ return now !== null && !now.isSymbolicLink() && now.ino === opened.ino && now.dev === opened.dev;+}+function assertNameIsOpenedFile(path, opened) {+ const now = lstatOrNull(path);+ if (now === null)+ throw new StoreUnsafePathError(path, "was removed while it was opened");+ if (now.isSymbolicLink())+ throw new StoreUnsafePathError(path, "is a symbolic link");+ if (now.ino !== opened.ino || now.dev !== opened.dev) {+ throw new StoreUnsafePathError(path, "was replaced while it was opened");+ }+}+function openShardForAppend(path) {+ const before = lstatOrNull(path);+ if (before?.isSymbolicLink() === true)+ throw new StoreUnsafePathError(path, "is a symbolic link");+ let fd;+ try {+ fd = openSync3(path, constants.O_RDWR | constants.O_APPEND | constants.O_CREAT | NO_FOLLOW, STORE_FILE_MODE);+ } catch (err) {+ if (errnoCode(err) === "ELOOP")+ throw new StoreUnsafePathError(path, "is a symbolic link");+ throw err;+ }+ try {+ const stat = fstatSync2(fd);+ if (!stat.isFile())+ throw new StoreUnsafePathError(path, "is not a regular file");+ if (stat.nlink > 1)+ throw new StoreUnsafePathError(path, `has ${stat.nlink} hard links`);+ if (NO_FOLLOW === 0)+ assertNameIsOpenedFile(path, stat);+ } catch (err) {+ closeSync3(fd);+ throw err;+ }+ return fd;+}+var STORE_DIR_MODE = 448, STORE_FILE_MODE = 384, StoreUnsafePathError, NO_FOLLOW, NON_BLOCK;+var init_safe_fs = __esm(() => {+ StoreUnsafePathError = class StoreUnsafePathError extends Error {+ path;+ constructor(path, why) {+ super(`refusing to write through ${path} in the brain store: it ${why}. ` + "Something other than Open Second Brain put it there (a sync peer, a restore, a manual " + "edit); remove it and let the store create the path again");+ this.name = "StoreUnsafePathError";+ this.path = path;+ }+ };+ NO_FOLLOW = constants.O_NOFOLLOW ?? 0;+ NON_BLOCK = constants.O_NONBLOCK ?? 0;+});++// src/core/store/store-paths.ts+import { realpathSync as realpathSync2 } from "node:fs";+import { homedir as homedir3 } from "node:os";+import { join as join11, posix as posix4, win32 as win322 } from "node:path";+function pathsFor(platform) {+ return platform === "win32" ? win322 : posix4;+}+function expandHome(value, source) {+ const paths = pathsFor(source.platform);+ if (value === "~")+ return source.home;+ if (value.startsWith("~/") || source.platform === "win32" && value.startsWith("~\\")) {+ return paths.join(source.home, value.slice(2));+ }+ return value;+}+function resolveLinks(path, platform) {+ if (platform !== process.platform)+ return path;+ const paths = pathsFor(platform);+ let head = path;+ const tail = [];+ for (;; ) {+ try {+ return paths.join(realpathSync2(head), ...tail.toReversed());+ } catch {+ const parent = paths.dirname(head);+ if (parent === head)+ return path;+ tail.push(paths.basename(head));+ head = parent;+ }+ }+}+function isPathInside(child, parent, platform) {+ const paths = pathsFor(platform);+ const fold = (p) => CASE_INSENSITIVE_PLATFORMS.has(platform) ? p.toLowerCase() : p;+ const rel = paths.relative(fold(paths.resolve(parent)), fold(paths.resolve(child)));+ const escapes = rel === ".." || rel.startsWith(`..${paths.sep}`);+ return rel === "" || !escapes && !paths.isAbsolute(rel);+}+function isPathInsideResolved(child, parent, platform) {+ return isPathInside(child, parent, platform) || isPathInside(resolveLinks(child, platform), resolveLinks(parent, platform), platform);+}+function defaultStoreRoot(source = processDirsEnv()) {+ return pathsFor(source.platform).join(dataBaseDir(source), APP_DIR_NAME, STORE_DEFAULT_DIR);+}+function resolveStoreRoot(source) {+ const paths = pathsFor(source.platform);+ const env = source.env[STORE_ROOT_ENV]?.trim();+ const configured = source.config[STORE_ROOT_CONFIG_KEY]?.trim();+ let resolved;+ if (env) {+ resolved = { root: paths.resolve(expandHome(env, source)), origin: "env" };+ } else if (configured) {+ const expanded = expandHome(configured, source);+ const root = paths.isAbsolute(expanded) ? paths.normalize(expanded) : paths.resolve(paths.dirname(source.configPath), expanded);+ resolved = { root, origin: "config" };+ } else {+ resolved = { root: defaultStoreRoot(source), origin: "default" };+ }+ if (source.vault !== null && source.vault.trim() !== "") {+ const vault = expandHome(source.vault.trim(), source);+ if (isPathInsideResolved(resolved.root, vault, source.platform))+ throw new StoreRootInsideVaultError(resolved.root, vault, resolved.origin);+ }+ return resolved;+}+function resolveConfiguredStoreRoot(configPath) {+ const path = configPath ?? defaultConfigPath();+ return resolveStoreRoot({+ platform: process.platform,+ home: homedir3(),+ env: process.env,+ config: discoverConfig(path).data,+ configPath: path,+ vault: resolveVault(path)+ });+}+function storesStateDir(source = processDirsEnv()) {+ return pathsFor(source.platform).join(stateBaseDir(source), APP_DIR_NAME, STORE_STATE_DIR);+}+function deviceStateDirFor(storeId, source = processDirsEnv()) {+ if (!isUlid(storeId))+ throw new Error(`store id "${storeId}" is not a ULID`);+ return pathsFor(source.platform).join(storesStateDir(source), storeId);+}+function dualWriteStatusPath(source = processDirsEnv()) {+ return pathsFor(source.platform).join(storesStateDir(source), DUAL_WRITE_STATUS_FILE);+}+function partitionDir(root, partition) {+ return join11(root, partition);+}+function shardMonth(physicalMs) {+ return new Date(physicalMs).toISOString().slice(0, 7);+}+function streamSegments(ref) {+ if (ref.stream === LEDGER_STREAM) {+ if (ref.ledger === undefined || !LEDGER_NAME_RE.test(ref.ledger)) {+ throw new Error(`the ${LEDGER_STREAM} stream needs a ledger name matching ${LEDGER_NAME_RE}`);+ }+ return [ref.stream, ref.ledger];+ }+ if (ref.ledger !== undefined)+ throw new Error(`stream ${ref.stream} takes no ledger name`);+ return [ref.stream];+}+function shardRelPath(ref, device, month) {+ if (!isValidDeviceId(device))+ throw new Error(`"${device}" is not a valid device id`);+ if (!SHARD_MONTH_RE.test(month))+ throw new Error(`"${month}" is not a YYYY-MM month`);+ return posix4.join(...streamSegments(ref), device, `${month}.${STORE_SHARD_EXT}`);+}+function shardPath(root, partition, ref, device, month) {+ return join11(partitionDir(root, partition), ...shardRelPath(ref, device, month).split("/"));+}+function blobPath(partitionRoot, sha) {+ if (!SHA256_RE.test(sha))+ throw new Error(`"${sha}" is not a sha256 hex digest`);+ return join11(partitionRoot, STORE_BLOBS_DIR, sha.slice(0, 2), sha);+}+function shardLockTarget(deviceStateDir, partition, rel) {+ return join11(deviceStateDir, STORE_LOCKS_DIR, partition, ...rel.split("/"));+}+var StoreRootInsideVaultError, CASE_INSENSITIVE_PLATFORMS, LEDGER_NAME_RE, SHARD_MONTH_RE, SHA256_RE;+var init_store_paths = __esm(() => {+ init_config();+ init_platform_dirs();+ init_constants();+ init_ulid();+ StoreRootInsideVaultError = class StoreRootInsideVaultError extends Error {+ root;+ vault;+ setting;+ origin;+ constructor(root, vault, origin) {+ const setting = origin === "env" ? `the ${STORE_ROOT_ENV} environment variable` : origin === "config" ? `\`${STORE_ROOT_CONFIG_KEY}\` in the machine config` : "the default store root";+ const remedy = origin === "default" ? `set \`${STORE_ROOT_CONFIG_KEY}\` in the machine config to a directory outside the vault` : `change ${setting} to a directory outside the vault, or remove it to use the per-user default`;+ super(`the brain store root ${root} (from ${setting}) is inside the vault ${vault}; ` + `the store must live outside the vault: ${remedy}.`);+ this.name = "StoreRootInsideVaultError";+ this.root = root;+ this.vault = vault;+ this.setting = setting;+ this.origin = origin;+ }+ };+ CASE_INSENSITIVE_PLATFORMS = new Set(["win32", "darwin"]);+ LEDGER_NAME_RE = /^[a-z0-9][a-z0-9-]{0,63}$/;+ SHARD_MONTH_RE = /^\d{4}-(0[1-9]|1[0-2])$/;+ SHA256_RE = /^[0-9a-f]{64}$/;+});++// src/core/store/blobs.ts+import {+ closeSync as closeSync4,+ fstatSync as fstatSync3,+ fsyncSync as fsyncSync2,+ linkSync as linkSync2,+ mkdirSync as mkdirSync8,+ openSync as openSync4,+ readFileSync as readFileSync9,+ readSync,+ statSync as statSync7,+ unlinkSync as unlinkSync3,+ writeSync as writeSync3+} from "node:fs";+import { basename as basename4, dirname as dirname8, join as join12 } from "node:path";+function errnoCode2(err) {+ return err?.code;+}+function sameFilesystem(a, b) {+ try {+ return statSync7(a).dev === statSync7(b).dev;+ } catch {+ return false;+ }+}+function writeAll(fd, bytes) {+ let written = 0;+ while (written < bytes.length)+ written += writeSync3(fd, bytes, written, bytes.length - written);+ fsyncSync2(fd);+}+function createExclusive(path, bytes) {+ const fd = openSync4(path, "wx", STORE_FILE_MODE);+ try {+ writeAll(fd, bytes);+ } finally {+ closeSync4(fd);+ }+}+function tempPathFor(target, tempDir) {+ const unique = `${process.pid}.${Date.now()}.${Math.random().toString(16).slice(2)}`;+ const blobDir = dirname8(target);+ if (tempDir !== undefined) {+ try {+ mkdirSync8(tempDir, { recursive: true });+ if (sameFilesystem(tempDir, blobDir))+ return join12(tempDir, `${basename4(target)}.${unique}`);+ } catch {}+ }+ return join12(blobDir, `${BLOB_TEMP_PREFIX}${basename4(target)}.${unique}`);+}+function verifies(path, sha, size, attempts, sleepMs) {+ for (let attempt = 0;attempt < attempts; attempt += 1) {+ try {+ const fd = openRegularFileForRead(path);+ if (fd !== null) {+ try {+ if (fstatSync3(fd).size === size && sha256Hex(readFileSync9(fd)) === sha)+ return true;+ } finally {+ closeSync4(fd);+ }+ }+ } catch (err) {+ if (errnoCode2(err) !== "ENOENT")+ throw err;+ }+ if (attempt < attempts - 1)+ sleepSync(sleepMs);+ }+ return false;+}+function settleExisting(path, sha, bytes, options) {+ if (verifies(path, sha, bytes.length, VERIFY_ATTEMPTS, VERIFY_SLEEP_MS))+ return;+ const repair = tempPathFor(path, options.tempDir);+ try {+ createExclusive(repair, bytes);+ try {+ (options.rename ?? renameWithRetry)(repair, path);+ } catch (err) {+ const code = errnoCode2(err);+ if (code === undefined || !STILL_OPEN_CODES.has(code))+ throw err;+ if (!verifies(path, sha, bytes.length, VERIFY_ATTEMPTS, VERIFY_SLEEP_MS * 10))+ throw err;+ }+ } finally {+ try {+ unlinkSync3(repair);+ } catch {}+ }+ if (!verifies(path, sha, bytes.length, 1, 0)) {+ throw new Error(`blob ${path} does not hold the content its name promises, even after a rewrite`);+ }+}+function createFileOnce(path, bytes, options = {}) {+ const link = options.link ?? linkSync2;+ mkdirSync8(dirname8(path), { recursive: true, mode: STORE_DIR_MODE });+ const temp = tempPathFor(path, options.tempDir);+ try {+ createExclusive(temp, bytes);+ try {+ link(temp, path);+ return true;+ } catch (err) {+ const code = errnoCode2(err);+ if (code === "EEXIST")+ return false;+ if (code === undefined || !NO_LINK_CODES.has(code))+ throw err;+ }+ } finally {+ try {+ unlinkSync3(temp);+ } catch {}+ }+ try {+ createExclusive(path, bytes);+ return true;+ } catch (err) {+ if (errnoCode2(err) !== "EEXIST")+ throw err;+ return false;+ }+}+function writeBlob(partitionRoot, text, options = {}) {+ const sha = sha256Hex(text);+ const path = blobPath(partitionRoot, sha);+ const bytes = Buffer.from(text, "utf8");+ ensureStoreDir(partitionRoot, dirname8(path));+ if (createFileOnce(path, bytes, options))+ return { sha, path, created: true };+ settleExisting(path, sha, bytes, options);+ return { sha, path, created: false };+}+var NO_LINK_CODES, VERIFY_ATTEMPTS = 5, VERIFY_SLEEP_MS = 20, STILL_OPEN_CODES;+var init_blobs = __esm(() => {+ init_fs_atomic();+ init_digest();+ init_constants();+ init_safe_fs();+ init_store_paths();+ NO_LINK_CODES = new Set([+ "EPERM",+ "ENOTSUP",+ "EOPNOTSUPP",+ "ENOSYS",+ "EXDEV",+ "EMLINK"+ ]);+ STILL_OPEN_CODES = new Set(["EPERM", "EBUSY"]);+});++// src/core/store/appender.ts+import { closeSync as closeSync5, fstatSync as fstatSync4, fsyncSync as fsyncSync3, openSync as openSync5, readSync as readSync2, writeSync as writeSync4 } from "node:fs";+import { dirname as dirname9, join as join13 } from "node:path";+function lineBytes(record) {+ return Buffer.from(`${JSON.stringify(record)}+`, "utf8");+}+function fsyncDirBestEffort(dir) {+ try {+ const fd = openSync5(dir, "r");+ try {+ fsyncSync3(fd);+ } finally {+ closeSync5(fd);+ }+ } catch {}+}+function appendLine(partitionRoot, path, bytes) {+ ensureStoreDir(partitionRoot, dirname9(path));+ const fd = openShardForAppend(path);+ let created = false;+ try {+ const size = fstatSync4(fd).size;+ created = size === 0;+ let payload = bytes;+ if (size > 0) {+ const last = Buffer.alloc(1);+ readSync2(fd, last, 0, 1, size - 1);+ if (last[0] !== NEWLINE)+ payload = Buffer.concat([Buffer.from([NEWLINE]), bytes]);+ }+ let written = 0;+ while (written < payload.length) {+ written += writeSync4(fd, payload, written, payload.length - written);+ }+ fsyncSync3(fd);+ } finally {+ closeSync5(fd);+ }+ if (created)+ fsyncDirBestEffort(dirname9(path));+}+function appendRecord(store, input, options = {}) {+ if (!store.partitions.has(input.partition)) {+ throw new PartitionUnavailableError(input.partition, store.root);+ }+ const ref = input.ledger === undefined ? { stream: input.stream } : { stream: input.stream, ledger: input.ledger };+ const hlc = tickClock(store.deviceStateDir, store.device, options.now);+ const month = shardMonth(hlc.physical);+ const rel = shardRelPath(ref, store.device, month);+ const record = buildRecord({+ hlc,+ device: store.device,+ agent: input.agent,+ kind: input.kind,+ scope: input.scope ?? null,+ topic: input.topic ?? null,+ body: input.body+ });+ let bytes = lineBytes(record);+ let spilled = false;+ if (bytes.length > STORE_LINE_CAP_BYTES) {+ const text = canonicalBodyText(record.body);+ const reference = {+ [BLOB_REF_KEY]: record.sum,+ [BLOB_REF_BYTES_KEY]: Buffer.byteLength(text, "utf8")+ };+ bytes = lineBytes({ ...record, body: reference });+ if (bytes.length > STORE_LINE_CAP_BYTES)+ throw new RecordTooLargeError(bytes.length);+ writeBlob(partitionDir(store.root, input.partition), text, {+ tempDir: join13(store.deviceStateDir, STORE_TMP_DIR)+ });+ spilled = true;+ }+ const path = shardPath(store.root, input.partition, ref, store.device, month);+ withLocalLock(shardLockTarget(store.deviceStateDir, input.partition, rel), () => appendLine(partitionDir(store.root, input.partition), path, bytes));+ return { record, path, rel, spilled };+}+var PartitionUnavailableError, RecordTooLargeError, NEWLINE = 10;+var init_appender = __esm(() => {+ init_clock_store();+ init_constants();+ init_envelope();+ init_blobs();+ init_local_lock();+ init_safe_fs();+ init_store_paths();+ PartitionUnavailableError = class PartitionUnavailableError extends Error {+ partition;+ constructor(partition, root) {+ super(`this machine does not hold the ${partition} partition of the brain store at ${root}; ` + `the record was not written. Sync the ${partition} folder to this machine to write ${partition} records here.`);+ this.name = "PartitionUnavailableError";+ this.partition = partition;+ }+ };+ RecordTooLargeError = class RecordTooLargeError extends Error {+ constructor(bytes) {+ super(`a store record line is ${bytes} bytes even with its body in a blob, above the ${STORE_LINE_CAP_BYTES}-byte cap; shorten its agent, scope or kind`);+ this.name = "RecordTooLargeError";+ }+ };+});++// src/core/store/operation-scope.ts+import { AsyncLocalStorage } from "node:async_hooks";+function activeOperationPrivate() {+ return storage.getStore()?.() ?? false;+}+var storage;+var init_operation_scope = __esm(() => {+ storage = new AsyncLocalStorage;+});++// src/core/store/private-region.ts+function textCarriesPrivateRegion(text) {+ return text.includes(PRIVATE_REGION_PLACEHOLDER) || privateRegionTexts(text).length > 0;+}+function valueCarriesPrivateRegion(value) {+ const strings = rowStrings(value, new Set);+ return strings === null || strings.texts.some(textCarriesPrivateRegion);+}+function rowStrings(row, opaque) {+ const references = [];+ const texts = [];+ const stack = [[row, 0, false]];+ while (stack.length > 0) {+ const [value, depth, isOpaque] = stack.pop();+ if (typeof value === "string") {+ texts.push(value);+ if (!isOpaque)+ references.push(value);+ continue;+ }+ if (value === null || typeof value !== "object")+ continue;+ if (depth >= ROW_WALK_MAX_DEPTH)+ return null;+ if (Array.isArray(value)) {+ for (const child of value)+ stack.push([child, depth + 1, isOpaque]);+ continue;+ }+ for (const [field, child] of Object.entries(value)) {+ stack.push([child, depth + 1, isOpaque || opaque.has(field)]);+ }+ }+ return { texts, references };+}+var ROW_WALK_MAX_DEPTH = 32;+var init_private_region = __esm(() => {+ init_redactor();+});++// src/core/store/format-doc.ts+import { readFileSync as readFileSync10 } from "node:fs";+import { join as join14 } from "node:path";+import { fileURLToPath } from "node:url";+function shippedFormatDoc() {+ shipped ??= readFileSync10(join14(fileURLToPath(new URL(".", import.meta.url)), STORE_FORMAT_FILE), "utf8");+ return shipped;+}+function formatDocVersion(text) {+ const match = VERSION_MARKER_RE.exec(text);+ return match === null ? null : Number(match[1]);+}+function writeFormatDoc(dir) {+ const text = shippedFormatDoc();+ const target = join14(dir, STORE_FORMAT_FILE);+ let existing = null;+ try {+ existing = readFileSync10(target, "utf8");+ } catch {+ existing = null;+ }+ if (existing === text)+ return false;+ if (existing !== null) {+ const onDisk = formatDocVersion(existing);+ const ours = formatDocVersion(text);+ if (onDisk !== null && ours !== null && onDisk >= ours)+ return false;+ }+ return atomicWriteText(target, text, { mode: FORMAT_DOC_MODE });+}+var VERSION_MARKER_RE, FORMAT_DOC_MODE = 420, shipped;+var init_format_doc = __esm(() => {+ init_fs_atomic();+ init_constants();+ VERSION_MARKER_RE = /^<!-- open-second-brain-store-format: (\d+) -->/;+});++// src/core/store/store-open.ts+import { readFileSync as readFileSync11, statSync as statSync8 } from "node:fs";+import { join as join15 } from "node:path";+function readStoreId(dir) {+ let text;+ try {+ text = readFileSync11(join15(dir, STORE_IDENTITY_FILE), "utf8");+ } catch (err) {+ if (err.code === "ENOENT")+ return null;+ throw err;+ }+ let parsed;+ try {+ parsed = JSON.parse(text);+ } catch {+ throw new StoreIdentityError(`${join15(dir, STORE_IDENTITY_FILE)} is not valid JSON`);+ }+ if (!isUlid(parsed.store_id)) {+ throw new StoreIdentityError(`${join15(dir, STORE_IDENTITY_FILE)} carries no valid store_id`);+ }+ return parsed.store_id;+}+function heldPartitions(root) {+ if (statSync8(root, { throwIfNoEntry: false })?.isDirectory() === false) {+ throw new StoreOpenError(`the brain store root ${root} is not a directory; move the file away or point ` + "the store root at a directory");+ }+ const ids = new Map;+ for (const partition of STORE_PARTITIONS) {+ const id = readStoreId(partitionDir(root, partition));+ if (id !== null)+ ids.set(partition, id);+ }+ if (new Set(ids.values()).size > 1) {+ throw new StoreOpenError(`the partitions under ${root} belong to different stores (${[...ids].map(([p, id]) => `${p}: ${id}`).join(", ")}); keep one store per root`);+ }+ const first = ids.values().next();+ return { held: new Set(ids.keys()), storeId: first.done === true ? null : first.value };+}+function openStore(options) {+ if (!isUsableLocalDeviceId(options.device)) {+ throw new StoreOpenError(`the brain store needs a device id, got "${options.device}"; set device_id in the machine ` + `config or O2B_DEVICE_ID to lowercase letters, digits and hyphens`);+ }+ const { held, storeId } = heldPartitions(options.root);+ if (storeId === null)+ throw new NoStoreError(options.root);+ writeFormatDoc(options.root);+ for (const partition of held)+ writeFormatDoc(partitionDir(options.root, partition));+ return {+ root: options.root,+ storeId,+ device: options.device,+ deviceStateDir: deviceStateDirFor(storeId, options.dirs ?? processDirsEnv()),+ partitions: held+ };+}+var StoreOpenError, NoStoreError, StoreIdentityError;+var init_store_open = __esm(() => {+ init_platform_dirs();+ init_config();+ init_constants();+ init_format_doc();+ init_store_paths();+ init_ulid();+ StoreOpenError = class StoreOpenError extends Error {+ constructor(message) {+ super(message);+ this.name = "StoreOpenError";+ }+ };+ NoStoreError = class NoStoreError extends StoreOpenError {+ root;+ constructor(root) {+ super(`no brain store at ${root}: no partition holds ${STORE_IDENTITY_FILE}; ` + "run `o2b store init` to create one, or let sync deliver it from a machine that has it");+ this.root = root;+ this.name = "NoStoreError";+ }+ };+ StoreIdentityError = class StoreIdentityError extends StoreOpenError {+ constructor(message) {+ super(message);+ this.name = "StoreIdentityError";+ }+ };+});++// src/core/store/dual-write.ts+import { readFileSync as readFileSync12 } from "node:fs";+function isDualWriteEnabled(configPath) {+ try {+ return resolveStoreDualWrite(configPath);+ } catch {+ return false;+ }+}+function readDualWriteStatus(path = dualWriteStatusPath()) {+ try {+ const parsed = JSON.parse(readFileSync12(path, "utf8"));+ return {+ failures: typeof parsed.failures === "number" ? parsed.failures : 0,+ skipped_no_device: typeof parsed.skipped_no_device === "number" ? parsed.skipped_no_device : 0,+ skipped_no_store: typeof parsed.skipped_no_store === "number" ? parsed.skipped_no_store : 0,+ last_error: typeof parsed.last_error === "string" ? parsed.last_error : null,+ last_failure_at: typeof parsed.last_failure_at === "string" ? parsed.last_failure_at : null,+ last_skip_at: typeof parsed.last_skip_at === "string" ? parsed.last_skip_at : null+ };+ } catch {+ return EMPTY_STATUS;+ }+}+function bumpStatus(update2) {+ try {+ const path = dualWriteStatusPath();+ withLocalLock(path, () => {+ const next = update2(readDualWriteStatus(path));+ atomicWriteFileSync(path, `${JSON.stringify(next, null, 2)}+`);+ });+ } catch {}+}+function warnOnce(kind, message) {+ if (warned.has(kind))+ return;+ warned.add(kind);+ try {+ process.stderr.write(`Open Second Brain: ${message}+`);+ } catch {}+}+function recordFailure(err) {+ const message = err instanceof Error ? err.message : String(err);+ warnOnce("failure", `a brain store dual write failed (${message}); the legacy write is intact. ` + "Later failures in this process are counted, not printed; `o2b brain doctor` reports them.");+ const at = new Date().toISOString();+ bumpStatus((s) => ({+ ...s,+ failures: s.failures + 1,+ last_error: message.slice(0, 500),+ last_failure_at: at+ }));+}+function recordNoDevice() {+ warnOnce("device", "brain store dual writes are on but this machine has no device id (O2B_DEVICE_ID is empty " + "or device_id is unset); the dual writes are skipped and the legacy writes are intact.");+ const at = new Date().toISOString();+ bumpStatus((s) => ({ ...s, skipped_no_device: s.skipped_no_device + 1, last_skip_at: at }));+}+function recordNoStore(root) {+ warnOnce("store", `brain store dual writes are on but there is no store at ${root}; the dual writes are ` + "skipped and the legacy writes are intact. Run `o2b store init` to create the store.");+ const at = new Date().toISOString();+ bumpStatus((s) => ({ ...s, skipped_no_store: s.skipped_no_store + 1, last_skip_at: at }));+}+function storeFor(device, context) {+ const { root, origin } = resolveConfiguredStoreRoot(context.configPath);+ const vault = context.vault?.trim();+ if (vault !== undefined && vault !== "" && isPathInsideResolved(root, vault, process.platform)) {+ throw new StoreRootInsideVaultError(root, vault, origin);+ }+ const key = `${root}\x00${device}`;+ const cached = handles.get(key);+ if (cached !== undefined && STORE_PARTITIONS.every((p) => {+ const id = readStoreId(partitionDir(root, p));+ return cached.partitions.has(p) ? id === cached.storeId : id === null;+ })) {+ return cached;+ }+ const handle = openStore({ root, device });+ handles.set(key, handle);+ return handle;+}+function vaultIdOf(context) {+ const vault = context.vault?.trim();+ if (vault === undefined || vault === "")+ return null;+ return readVaultIdentity(vault)?.vault_id ?? null;+}+function defaultAgent() {+ try {+ return resolveAgentName();+ } catch {+ return "agent";+ }+}+function dualWrite(build, context = {}) {+ if (!isDualWriteEnabled(context.configPath))+ return;+ try {+ const device = resolveAppendShardId();+ if (device === "") {+ recordNoDevice();+ return;+ }+ const built = build();+ if (built === null)+ return;+ const records = Array.isArray(built) ? built : [built];+ if (records.length === 0)+ return;+ let store;+ try {+ store = storeFor(device, context);+ } catch (err) {+ if (!(err instanceof NoStoreError))+ throw err;+ recordNoStore(err.root);+ return;+ }+ const vaultId = vaultIdOf(context);+ for (const record of records) {+ const partition = record.private === true || activeOperationPrivate() || valueCarriesPrivateRegion(record.body) || record.privateWhenHeld === true && store.partitions.has("private") ? "private" : "shared";+ appendRecord(store, {+ partition,+ stream: record.stream,+ ...record.ledger !== undefined ? { ledger: record.ledger } : {},+ kind: record.kind,+ agent: record.agent !== undefined && record.agent.trim() !== "" ? record.agent : defaultAgent(),+ scope: record.scope ?? null,+ body: { ...record.body, [VAULT_ID_FIELD]: vaultId }+ });+ }+ } catch (err) {+ recordFailure(err);+ }+}+var EMPTY_STATUS, warned, handles;+var init_dual_write = __esm(() => {+ init_fs_atomic();+ init_config();+ init_origin_channel();+ init_ledger_shards();+ init_vault_identity();+ init_appender();+ init_constants();+ init_local_lock();+ init_operation_scope();+ init_private_region();+ init_store_open();+ init_store_paths();+ EMPTY_STATUS = Object.freeze({+ failures: 0,+ skipped_no_device: 0,+ skipped_no_store: 0,+ last_error: null,+ last_failure_at: null,+ last_skip_at: null+ });+ warned = new Set;+ handles = new Map;+});++// src/core/brain/paths.ts+import { join as join16 } from "node:path";+function brainDirs(vault) {+ const brain = ensureInsideVault(join16(vault, BRAIN_ROOT_REL), vault);+ return {+ brain,+ inbox: ensureInsideVault(join16(vault, BRAIN_INBOX_REL), vault),+ processed: ensureInsideVault(join16(vault, BRAIN_PROCESSED_REL), vault),+ archived: ensureInsideVault(join16(vault, BRAIN_ARCHIVED_SIGNALS_REL), vault),+ pending: ensureInsideVault(join16(vault, BRAIN_PENDING_REL), vault),+ preferences: ensureInsideVault(join16(vault, BRAIN_PREFERENCES_REL), vault),+ retired: ensureInsideVault(join16(vault, BRAIN_RETIRED_REL), vault),+ log: ensureInsideVault(join16(vault, BRAIN_LOG_REL), vault),+ entities: ensureInsideVault(join16(vault, BRAIN_ENTITIES_REL), vault),+ bases: ensureInsideVault(join16(vault, BRAIN_BASES_REL), vault),+ snapshots: ensureInsideVault(join16(vault, BRAIN_SNAPSHOTS_REL), vault)+ };+}+function brainDirsForWrite(vault, notices, lane) {+ assertVaultIdentityForWrite(vault, notices, lane);+ return brainDirs(vault);+}+function preferencePath(vault, slug) {+ const s = validateSlug(slug);+ return ensureInsideVault(join16(brainDirs(vault).preferences, `pref-${s}.md`), vault);+}+function retiredPath(vault, slug) {+ const s = validateSlug(slug);+ return ensureInsideVault(join16(brainDirs(vault).retired, `ret-${s}.md`), vault);+}+function validateSlug(slug) {+ const trimmed = slug.trim();+ if (!trimmed)+ throw new Error("slug must not be empty");+ if (trimmed.includes("/") || trimmed.includes("\\")) {+ throw new Error(`slug must not contain path separators: ${slug}`);+ }+ if (/[:*?"<>|\x00-\x1F]/.test(trimmed)) {+ throw new Error(`slug contains invalid character: ${JSON.stringify(slug)}`);+ }+ if (trimmed === ".." || trimmed === "." || /(?:^|[^\w])\.\.(?:$|[^\w])/.test(trimmed)) {+ throw new Error(`slug must not contain '..' traversal: ${slug}`);+ }+ if (/[. ]$/.test(trimmed)) {+ throw new Error(`slug must not end with '.' or whitespace (Windows-incompatible): ${slug}`);+ }+ if (WINDOWS_RESERVED_BASENAME_RE.test(trimmed)) {+ throw new Error(`slug uses a Windows-reserved filename: ${slug}`);+ }+ return trimmed;+}+var WINDOWS_RESERVED_BASENAME_RE;+var init_paths = __esm(() => {+ init_fs_atomic();+ init_path_safety();+ init_ledger_shards();+ init_path_constants();+ init_vault_identity();+ init_skill_rewrite_tasks();+ init_skill_rewrite();+ init_path_safety();+ init_freeze_marker();+ init_path_constants();+ WINDOWS_RESERVED_BASENAME_RE = /^(con|prn|aux|nul|com[1-9]|lpt[1-9])(\..*)?$/i;+});++// src/core/graph/transport-reach.ts+var TRANSPORT_REACH, TRANSPORT_REACHES, MAINTENANCE_LANE_REACH;+var init_transport_reach = __esm(() => {+ TRANSPORT_REACH = Object.freeze({+ local: "local",+ remote: "remote"+ });+ TRANSPORT_REACHES = Object.freeze([+ TRANSPORT_REACH.local,+ TRANSPORT_REACH.remote+ ]);+ MAINTENANCE_LANE_REACH = TRANSPORT_REACH.local;+});++// src/core/graph/visibility.ts+function normToken(raw) {+ return raw.normalize("NFC").trim().toLowerCase();+}+function pageVisibility(meta) {+ const v = meta["visibility"];+ const list = Array.isArray(v) ? v : typeof v === "string" && v.length > 0 ? [v] : [];+ return list.map((s) => normToken(String(s))).filter((s) => s.length > 0);+}+function isRemotelyReadable(pageTags, reach) {+ if (reach === TRANSPORT_REACH.local)+ return true;+ return !pageTags.includes(REMOTE_DENY_VISIBILITY_TOKEN);+}+var REMOTE_DENY_VISIBILITY_TOKEN = "private";+var init_visibility = __esm(() => {+ init_transport_reach();+});++// src/core/graph/privacy-markers.ts+function declaredValues(raw) {+ if (typeof raw === "string")+ return [raw];+ if (!Array.isArray(raw))+ return [];+ return raw.filter((v) => typeof v === "string");+}+function hasPrivacyDenyMarker(meta) {+ for (const key of Object.keys(meta)) {+ if (!PRIVACY_MARKER_KEY_TOKENS.has(normToken(key)))+ continue;+ for (const value of declaredValues(meta[key])) {+ if (PRIVACY_DENY_MARKER_VALUES.includes(normToken(value)))+ return true;+ }+ }+ return false;+}+function markerDenyTokens(meta) {+ return hasPrivacyDenyMarker(meta) ? Object.freeze([REMOTE_DENY_VISIBILITY_TOKEN]) : Object.freeze([]);+}+function remoteDenyVisibilityTokens(meta) {+ const declared = pageVisibility(meta);+ const out = [...declared];+ for (const token of markerDenyTokens(meta)) {+ if (!out.includes(token))+ out.push(token);+ }+ return Object.freeze(out);+}+var PRIVACY_MARKER_KEYS, PRIVACY_DENY_MARKER_VALUES, PRIVACY_MARKER_KEY_TOKENS;+var init_privacy_markers = __esm(() => {+ init_visibility();+ PRIVACY_MARKER_KEYS = Object.freeze([+ "access",+ "confidentiality",+ "sensitivity"+ ]);+ PRIVACY_DENY_MARKER_VALUES = Object.freeze([+ "private",+ "secret",+ "confidential"+ ]);+ PRIVACY_MARKER_KEY_TOKENS = Object.freeze(new Set(PRIVACY_MARKER_KEYS.map((key) => normToken(key))));+});++// src/core/vault.ts+import { mkdirSync as mkdirSync9, readFileSync as readFileSync13, readdirSync as readdirSync2, writeFileSync } from "node:fs";+import { dirname as dirname10, join as join17, relative as relative3 } from "node:path";+function parseFrontmatterWithNotices(path, opts = {}) {+ const site = opts.site ?? FRONTMATTER_SITE;+ let text;+ try {+ text = readFileSync13(path, "utf8");+ } catch (err) {+ const notices = [];+ emitDegradationNotice(notices, {+ code: DEGRADATION_CODE.frontmatterUnreadable,+ site,+ path,+ detail: `frontmatter read failed: ${err instanceof Error ? err.message : String(err)}`+ });+ return [{}, "", notices];+ }+ return parseFrontmatterTextWithNotices(text, { site, path });+}+function parseFrontmatterTextWithNotices(raw, opts = {}) {+ const notices = [];+ const site = opts.site ?? FRONTMATTER_SITE;+ const text = raw.charCodeAt(0) === BYTE_ORDER_MARK ? raw.slice(1) : raw;+ const match = FRONTMATTER_RE.exec(text);+ if (!match) {+ return [{}, text.trim(), notices];+ }+ const fmBlock = match[1];+ const body = text.slice(match[0].length).trim();+ const metadata = {};+ const lines = fmBlock.split(`+`);+ let blockKey = null;+ for (let i = 0;i < lines.length; i++) {+ const line = lines[i].trim();+ if (!line || line.startsWith("#"))+ continue;+ const dash = DASH_ITEM_RE.exec(line);+ if (dash && blockKey !== null) {+ const arr = metadata[blockKey] ?? [];+ arr.push(stripQuotes(dash[1] ?? ""));+ metadata[blockKey] = arr;+ continue;+ }+ blockKey = null;+ const kv = KEY_VALUE_RE.exec(line);+ if (!kv) {+ emitDegradationNotice(notices, {+ code: DEGRADATION_CODE.frontmatterLineDropped,+ site,+ ...opts.path !== undefined ? { path: opts.path } : {},+ detail: `frontmatter line ${i + 1} is not a supported key/value or list item: ${clipNoticeLine(line)}`+ });+ continue;+ }+ const key = kv[1];+ let value = kv[2].trim();+ if (value === "") {+ let j = i + 1;+ let nextMeaningful = null;+ while (j < lines.length) {+ const cand = lines[j].trim();+ if (!cand || cand.startsWith("#")) {+ j++;+ continue;+ }+ nextMeaningful = cand;+ break;+ }+ if (nextMeaningful !== null && DASH_ITEM_RE.test(nextMeaningful)) {+ metadata[key] = [];+ blockKey = key;+ } else {+ metadata[key] = "";+ }+ continue;+ }+ if (value.startsWith("[") && value.endsWith("]")) {+ const inner = value.slice(1, -1).trim();+ metadata[key] = inner ? splitInlineArray(inner) : [];+ continue;+ }+ metadata[key] = stripQuotes(value);+ }+ return [metadata, body, notices];+}+function clipNoticeLine(line) {+ return line.length <= NOTICE_LINE_MAX ? line : line.slice(0, NOTICE_LINE_MAX) + NOTICE_LINE_ELLIPSIS;+}+function listVaultPages(vaultDir, opts) {+ const skipDirs = new Set(opts.skipDirs ?? DEFAULT_SKIP_DIRS);+ const skipFiles = new Set((opts.skipFiles ?? DEFAULT_SKIP_FILES).map((f) => f.toLowerCase()));+ const walked = [];+ walk(vaultDir, vaultDir, skipDirs, skipFiles, walked, {+ sink: opts.notices,+ site: opts.site ?? LIST_VAULT_PAGES_SITE+ });+ const pages = walked.filter((w) => isRemotelyReadable(w.unreadable ? UNMEASURABLE_PAGE_VISIBILITY : remoteDenyVisibilityTokens(w.page.metadata), opts.reach)).map((w) => w.page);+ pages.sort((a, b) => COLLATOR.compare(a.title.toLowerCase(), b.title.toLowerCase()));+ return pages;+}+function walk(root, dir, skipDirs, skipFiles, out, notices) {+ let entries;+ try {+ entries = readdirSync2(dir, { withFileTypes: true });+ } catch (err) {+ if (notices.sink !== undefined) {+ emitDegradationNotice(notices.sink, {+ code: DEGRADATION_CODE.vaultWalkEntrySkipped,+ site: notices.site,+ path: dir,+ detail: `directory listing failed: ${err instanceof Error ? err.message : String(err)}`+ });+ }+ return;+ }+ for (const entry of entries) {+ const full = join17(dir, entry.name);+ if (entry.isDirectory()) {+ if (skipDirs.has(entry.name))+ continue;+ walk(root, full, skipDirs, skipFiles, out, notices);+ continue;+ }+ if (!entry.isFile())+ continue;+ if (!entry.name.toLowerCase().endsWith(".md"))+ continue;+ if (skipFiles.has(entry.name.toLowerCase()))+ continue;+ const rel = relative3(root, full);+ const parts = rel.split(/[\\/]/);+ if (parts.some((p) => skipDirs.has(p)))+ continue;+ const [meta, , pageNotices] = parseFrontmatterWithNotices(full, { site: notices.site });+ if (notices.sink !== undefined)+ notices.sink.push(...pageNotices);+ const titleVal = meta["title"];+ const title = typeof titleVal === "string" && titleVal ? titleVal : stem(entry.name);+ out.push({+ page: { title, path: full, metadata: meta },+ unreadable: pageNotices.some((n) => n.code === DEGRADATION_CODE.frontmatterUnreadable)+ });+ }+}+function stripQuotes(s) {+ if (s.length >= 2 && s.startsWith('"') && s.endsWith('"')) {+ return unescapeDoubleQuoted(s.slice(1, -1));+ }+ if (s.length >= 2 && s.startsWith("'") && s.endsWith("'")) {+ return s.slice(1, -1);+ }+ return s;+}+function unescapeDoubleQuoted(inner) {+ return inner.replace(/\\([\\"nrt])/g, (_, ch) => DOUBLE_QUOTED_ESCAPES[ch] ?? `\\${ch}`);+}+function splitInlineArray(inner) {+ const out = [];+ let current = "";+ let inQuote = false;+ let quoteChar = "";+ for (let i = 0;i < inner.length; i++) {+ const ch = inner[i];+ if (inQuote) {+ current += ch;+ if (ch === quoteChar && inner[i - 1] !== "\\") {+ inQuote = false;+ quoteChar = "";+ }+ continue;+ }+ if (ch === '"' || ch === "'") {+ inQuote = true;+ quoteChar = ch;+ current += ch;+ continue;+ }+ if (ch === ",") {+ out.push(stripQuotes(current.trim()));+ current = "";+ continue;+ }+ current += ch;+ }+ if (current.trim() !== "") {+ out.push(stripQuotes(current.trim()));+ }+ return out;+}+var FRONTMATTER_RE, BYTE_ORDER_MARK = 65279, FRONTMATTER_KEY_PATTERN = "[a-zA-Z_][a-zA-Z0-9_-]*", FRONTMATTER_KEY_RE, KEY_VALUE_RE, DASH_ITEM_RE, MEDIA_EXTENSIONS, DEFAULT_SKIP_DIRS, DEFAULT_SKIP_FILES, FRONTMATTER_SITE = "vault.parseFrontmatter", NOTICE_LINE_MAX = 120, NOTICE_LINE_ELLIPSIS = "β¦", LIST_VAULT_PAGES_SITE = "vault.listVaultPages", COLLATOR, UNMEASURABLE_PAGE_VISIBILITY, DOUBLE_QUOTED_ESCAPES;+var init_vault = __esm(() => {+ init_wikilink();+ init_fs_atomic();+ init_fs_utils();+ init_degradation();+ init_path_safety();+ init_privacy_markers();+ init_visibility();+ init_fs_utils();+ FRONTMATTER_RE = /^---[^\S\n]*\n([\s\S]*?)\n---\s*\n?/;+ FRONTMATTER_KEY_RE = new RegExp(`^${FRONTMATTER_KEY_PATTERN}$`);+ KEY_VALUE_RE = new RegExp(`^(${FRONTMATTER_KEY_PATTERN})\\s*:\\s*(.*?)\\s*$`);+ DASH_ITEM_RE = /^-(?:\s+(.*))?$/;+ MEDIA_EXTENSIONS = new Set([+ ".png",+ ".jpg",+ ".jpeg",+ ".gif",+ ".svg",+ ".webp",+ ".bmp",+ ".tiff",+ ".avif",+ ".mp4",+ ".webm",+ ".ogv",+ ".mov",+ ".mkv",+ ".avi",+ ".mp3",+ ".wav",+ ".ogg",+ ".flac",+ ".m4a",+ ".pdf"+ ]);+ DEFAULT_SKIP_DIRS = [".git", ".obsidian", ".trash", ".stversions"];+ DEFAULT_SKIP_FILES = ["index.md", "log.md"];+ COLLATOR = new Intl.Collator("en", { numeric: true });+ UNMEASURABLE_PAGE_VISIBILITY = Object.freeze([+ REMOTE_DENY_VISIBILITY_TOKEN+ ]);+ DOUBLE_QUOTED_ESCAPES = Object.freeze({+ "\\": "\\",+ '"': '"',+ n: `+`,+ r: "\r",+ t: "\t"+ });+});+// src/core/store/fold.ts+var TOMBSTONE;+var init_fold = __esm(() => {+ init_digest();+ init_constants();+ init_envelope();+ TOMBSTONE = Symbol("tombstone");+});++// src/core/store/fold-preferences.ts+var COUNTERS, KINDS;+var init_fold_preferences = __esm(() => {+ init_constants();+ init_fold();+ COUNTERS = new Set(PREFERENCE_COUNTER_FIELDS);+ KINDS = new Set([+ PREFERENCE_SET_KIND,+ PREFERENCE_REMOVE_KIND,+ PREFERENCE_EVIDENCE_KIND+ ]);+});++// src/core/store/dual-write-records.ts+function plain(value) {+ return JSON.parse(JSON.stringify(value ?? null));+}+function isPrivateFrontmatter(frontmatter) {+ return remoteDenyVisibilityTokens(frontmatter).includes(REMOTE_DENY_VISIBILITY_TOKEN);+}+function isPrivatePageFile(path) {+ const [frontmatter, , notices] = parseFrontmatterWithNotices(path);+ if (notices.some((n) => n.code === DEGRADATION_CODE.frontmatterUnreadable))+ return true;+ return isPrivateFrontmatter(frontmatter);+}+function partitionOf(partition) {+ return {+ private: partition === "private",+ ...partition === "private-when-held" ? { privateWhenHeld: true } : {}+ };+}+function ledgerRowRecord(ledger, row, partition, agent) {+ return {+ stream: "ledgers",+ ledger,+ kind: LEDGER_ROW_KIND,+ ...agent !== undefined ? { agent } : {},+ ...partitionOf(partition),+ body: { row: plain(row) }+ };+}+function auditRowRecord(ledger, row, agent, isPrivate) {+ return ledgerRowRecord(ledger, row, isPrivate ? "private" : "private-when-held", agent);+}+var COUNTERS2, DUAL_WRITE_LEDGERS;+var init_dual_write_records = __esm(() => {+ init_paths();+ init_privacy_markers();+ init_visibility();+ init_degradation();+ init_vault();+ init_constants();+ init_fold_preferences();+ COUNTERS2 = new Set(PREFERENCE_COUNTER_FIELDS);+ DUAL_WRITE_LEDGERS = Object.freeze({+ idempotency: "idempotency",+ continuity: "continuity",+ metrics: "metrics",+ lineage: "lineage",+ permissions: "permissions",+ gitCommits: "git-commits",+ reliabilityAudit: "reliability-audit",+ maintenanceJournal: "maintenance-journal",+ verifierRejections: "verifier-rejections",+ preferenceAudit: "preference-audit",+ editHistory: "edit-history",+ decisionReceipts: "decision-receipts",+ truthClaims: "truth-claims",+ queryDemand: "query-demand",+ recurrence: "recurrence"+ });+});++// src/core/brain/artifact-ref-resolve.ts+import { isAbsolute as isAbsolute3, join as join18 } from "node:path";+import { existsSync as existsSync7, statSync as statSync9 } from "node:fs";+function unbracket(ref) {+ const match = ANCHORED_WIKILINK_RE.exec(ref.trim());+ return stripWikilinkDecoration(match === null ? ref : match[1]);+}+function artifactPath(vault, id) {+ const dirs = brainDirs(vault);+ for (const dir of [+ dirs.preferences,+ dirs.retired,+ dirs.inbox,+ dirs.processed,+ dirs.archived,+ dirs.pending,+ join18(vault, BRAIN_SOURCES_REL),+ dirs.entities,+ join18(vault, BRAIN_DECISIONS_REL)+ ]) {+ const abs = join18(dir, `${id}${MARKDOWN_EXT}`);+ if (existsSync7(abs))+ return vaultRelative(abs, vault);+ }+ return null;+}+function pageCandidate(vault, bare) {+ if (isVaultFile(vault, bare))+ return bare;+ const twin = bare + MARKDOWN_EXT;+ if (isVaultFile(vault, twin))+ return twin;+ return null;+}+function isVaultFile(vault, rel) {+ if (!pathIsInside(join18(vault, rel), vault))+ return false;+ try {+ return statSync9(join18(vault, rel)).isFile();+ } catch {+ return false;+ }+}+function resolveArtifactRef(vault, ref) {+ const spelled = posixRel(unbracket(ref));+ if (spelled.length === 0)+ return null;+ const bare = isAbsolute3(spelled) ? vaultRelative(spelled, vault) : spelled;+ if (bare.length === 0)+ return null;+ if (bare.endsWith(MARKDOWN_EXT))+ return bare;+ return bare.includes("/") ? pageCandidate(vault, bare) : artifactPath(vault, bare);+}+var MARKDOWN_EXT = ".md";+var init_artifact_ref_resolve = __esm(() => {+ init_path_safety();+ init_paths();+ init_wikilink();+});++// src/core/brain/note-path.ts+var init_note_path = () => {};++// src/core/brain/types.ts+var BRAIN_SIGNAL_SOURCE_TYPE, BRAIN_SIGNAL_SOURCE_TYPES, BRAIN_MEMORY_LAYER, BRAIN_MEMORY_LAYER_VALUES, BRAIN_LOG_EVENT_KIND, BRAIN_COMMITMENT_TIER, BRAIN_COMMITMENT_TIER_VALUES, BRAIN_LOG_EVENT_KIND_SET, BRAIN_SNAPSHOT_REASON, BRAIN_SNAPSHOT_REASONS;+var init_types = __esm(() => {+ BRAIN_SIGNAL_SOURCE_TYPE = {+ live: "live",+ inline: "inline",+ session: "session",+ extracted: "extracted",+ autoExtract: "auto_extract"+ };+ BRAIN_SIGNAL_SOURCE_TYPES = Object.freeze(Object.values(BRAIN_SIGNAL_SOURCE_TYPE));+ BRAIN_MEMORY_LAYER = {+ L0: "L0",+ L1: "L1",+ L2: "L2",+ L3: "L3"+ };+ BRAIN_MEMORY_LAYER_VALUES = Object.values(BRAIN_MEMORY_LAYER);+ BRAIN_LOG_EVENT_KIND = {+ dream: "dream",+ feedback: "feedback",+ applyEvidence: "apply-evidence",+ forceConfirmed: "force-confirmed",+ reject: "reject",+ promote: "promote",+ retire: "retire",+ notedRedundant: "noted-redundant",+ skipCorruptedFrontmatter: "skip-corrupted-frontmatter",+ pin: "pin",+ unpin: "unpin",+ rollback: "rollback",+ snapshot: "snapshot",+ signalSuppressed: "signal-suppressed",+ scanInline: "scan-inline",+ importSession: "import-session",+ merge: "merge",+ upgrade: "upgrade",+ importClaudeMemory: "import-claude-memory",+ promoteHostMemory: "promote-host-memory",+ note: "note",+ sessionLifecycle: "session-lifecycle",+ reconcile: "reconcile",+ writeSession: "write-session",+ entityAnchorSkip: "entity-anchor-skip",+ attributeWrite: "attribute-write",+ durabilitySkip: "durability-skip",+ ambientWithheld: "ambient-withheld",+ writeConflictAdvisory: "write-conflict-advisory",+ captureRoutingHint: "capture-routing-hint",+ signalRetire: "signal-retire",+ tombstone: "tombstone",+ temporalReplace: "temporal-replace",+ chainDecay: "chain-decay",+ decisionRecord: "decision-record",+ decisionOutcome: "decision-outcome",+ decisionRating: "decision-rating",+ decisionChangeReceipt: "decision-change-receipt",+ decisionOpen: "decision-open",+ decisionResolved: "decision-resolved",+ decisionDiscarded: "decision-discarded",+ authoredAtBackfill: "authored-at-backfill",+ tension: "tension",+ sourceCitation: "source-citation",+ doctorRepair: "doctor-repair",+ vectorBackfill: "vector-backfill",+ eventAnchorBackfill: "event-anchor-backfill",+ expirationSet: "expiration-set",+ freeze: "freeze",+ unfreeze: "unfreeze",+ writeRefused: "write-refused",+ noteWrite: "note-write",+ lessonsApproved: "lessons-approved",+ lessonsDenied: "lessons-denied",+ lessonsPromoted: "lessons-promoted"+ };+ BRAIN_COMMITMENT_TIER = {+ exploring: "exploring",+ leaning: "leaning",+ decided: "decided",+ locked: "locked"+ };+ BRAIN_COMMITMENT_TIER_VALUES = Object.values(BRAIN_COMMITMENT_TIER);+ BRAIN_LOG_EVENT_KIND_SET = new Set(Object.values(BRAIN_LOG_EVENT_KIND));+ BRAIN_SNAPSHOT_REASON = Object.freeze({+ dream: "dream",+ upgrade: "upgrade",+ importClaudeMemory: "import-claude-memory",+ promoteHostMemory: "promote-host-memory",+ deleteBySource: "delete-by-source",+ entityPrune: "entity-prune",+ entityMerge: "entity-merge",+ noteDelete: "note-delete",+ noteRevert: "note-revert",+ knowledgePackUninstall: "knowledge-pack-uninstall",+ payloadGc: "payload-gc",+ receiptCompaction: "receipt-compaction",+ sessionBoundary: "session-boundary",+ planBoundary: "plan-boundary",+ decisionBoundary: "decision-boundary",+ manual: "manual"+ });+ BRAIN_SNAPSHOT_REASONS = Object.freeze(Object.values(BRAIN_SNAPSHOT_REASON));+});++// src/core/brain/temporal/period-common.ts+function extractId(linkOrId) {+ const stripped = linkOrId.replace(LINK_REASON_RE, "").trim();+ const target = parseWikilink(stripped) ?? stripped;+ return ID_PREFIX_RE.test(target) ? target : undefined;+}+var LINK_REASON_RE, ID_PREFIX_RE;+var init_period_common = __esm(() => {+ init_wikilink();+ init_types();+ LINK_REASON_RE = /\(([^)]+)\)\s*$/;+ ID_PREFIX_RE = /^(pref|ret)-[A-Za-z0-9-]+$/;+});++// src/core/store/reference-privacy.ts+import { existsSync as existsSync8, statSync as statSync10 } from "node:fs";+import { resolve as resolve7 } from "node:path";+function preferenceIdIsPrivate(vault, id) {+ let paths;+ try {+ const slug = stripBrainIdPrefix(id);+ paths = [preferencePath(vault, slug), retiredPath(vault, slug)].filter((p) => existsSync8(p));+ } catch {+ return true;+ }+ return paths.length === 0 || paths.some((p) => isPrivatePageFile(p));+}+function logRefsNamePrivatePage(vault, refs, guessed) {+ let guessSpared = guessed === undefined;+ for (const ref of refs) {+ if (ref === undefined || ref === "")+ continue;+ const isGuess = !guessSpared && ref === guessed;+ if (isGuess)+ guessSpared = true;+ const id = extractId(ref);+ if (id !== undefined && !isGuess && preferenceIdIsPrivate(vault, id))+ return true;+ const rel = resolveArtifactRef(vault, ref);+ if (rel === null)+ continue;+ const abs = resolve7(vault, rel);+ if (!pathIsInside(abs, vault) || existsSync8(abs) && isPrivatePageFile(abs))+ return true;+ }+ return false;+}+var init_reference_privacy = __esm(() => {+ init_artifact_ref_resolve();+ init_note_path();+ init_paths();+ init_period_common();+ init_path_safety();+ init_vault();+ init_wikilink();+ init_dual_write_records();+ init_private_region();+});++// src/core/reliability/audit.ts+import { closeSync as closeSync6, fsyncSync as fsyncSync4, mkdirSync as mkdirSync10, openSync as openSync6, writeFileSync as writeFileSync2 } from "node:fs";+import { basename as basename5, join as join19 } from "node:path";+function appendAuditRecord(auditRoot, record, vault) {+ const timestamp = new Date(record.timestamp);+ if (!Number.isFinite(timestamp.getTime())) {+ throw new Error(`invalid audit timestamp: ${record.timestamp}`);+ }+ mkdirSync10(auditRoot, { recursive: true });+ const path = join19(auditRoot, shardedFileName(isoWeekLabel(timestamp), resolveAppendShardId(), JSONL_LEDGER_EXT));+ const line = redactRawOutput(JSON.stringify(record), {+ maxInput: Number.POSITIVE_INFINITY+ });+ const fileDescriptor = openSync6(path, "a", 384);+ try {+ writeFileSync2(fileDescriptor, line + `+`, "utf8");+ fsyncSync4(fileDescriptor);+ } finally {+ closeSync6(fileDescriptor);+ }+ dualWrite(() => {+ const written = JSON.parse(line);+ return auditRowRecord(DUAL_WRITE_LEDGERS.reliabilityAudit, { audit_dir: basename5(auditRoot), record: written }, isRecordLabel(written.actor) ? written.actor : undefined, auditRowNamesPrivatePage(vault, written));+ }, vault !== undefined ? { vault } : {});+ return path;+}+function stringsIn(value, out = []) {+ if (typeof value === "string")+ out.push(value);+ else if (Array.isArray(value))+ for (const v of value)+ stringsIn(v, out);+ else if (value !== null && typeof value === "object") {+ for (const v of Object.values(value))+ stringsIn(v, out);+ }+ return out;+}+function auditRowNamesPrivatePage(vault, record) {+ if (vault === undefined)+ return true;+ return logRefsNamePrivatePage(vault, [record.target, ...stringsIn(record.details)]);+}+function isoWeekLabel(input) {+ const date = new Date(Date.UTC(input.getUTCFullYear(), input.getUTCMonth(), input.getUTCDate()));+ const dayNumber = date.getUTCDay() || 7;+ date.setUTCDate(date.getUTCDate() + 4 - dayNumber);+ const year = date.getUTCFullYear();+ const yearStart = new Date(Date.UTC(year, 0, 1));+ const week = Math.ceil(((date.getTime() - yearStart.getTime()) / 86400000 + 1) / 7);+ return `${year}-W${String(week).padStart(2, "0")}`;+}+var AUDIT_WEEK_SHARD_GRAMMAR;+var init_audit = __esm(() => {+ init_redactor();+ init_ledger_shards();+ init_dual_write();+ init_dual_write_records();+ init_envelope();+ init_reference_privacy();+ AUDIT_WEEK_SHARD_GRAMMAR = Object.freeze({+ base: "\\d{4}-W\\d{2}",+ extensions: Object.freeze([JSONL_LEDGER_EXT])+ });+});++// src/core/brain/audit-dirs.ts+var SESSION_LIFECYCLE_AUDIT_DIR = "session-lifecycle", HYGIENE_AUDIT_DIR = "hygiene", SECRET_CUSTODY_AUDIT_DIR = "secret-custody", WATCHDOG_AUDIT_DIR = "watchdog", BRAIN_LOG_AUDIT_DIRS;+var init_audit_dirs = __esm(() => {+ BRAIN_LOG_AUDIT_DIRS = Object.freeze([+ SESSION_LIFECYCLE_AUDIT_DIR,+ HYGIENE_AUDIT_DIR,+ SECRET_CUSTODY_AUDIT_DIR,+ WATCHDOG_AUDIT_DIR+ ]);+});++// src/core/brain/time.ts+function isoSecond(d = new Date) {+ return d.toISOString().replace(/\.\d{3}Z$/, "Z");+}+var init_time = () => {};++// src/core/brain/secrets/value-cipher.ts+import { createCipheriv, createDecipheriv, randomBytes as randomBytes3 } from "node:crypto";+function encryptValue(key, plaintext, aad) {+ const iv = randomBytes3(IV_BYTES);+ const cipher = createCipheriv(ALGORITHM, key, iv);+ if (aad !== undefined)+ cipher.setAAD(Buffer.from(aad, "utf8"));+ const ciphertext = Buffer.concat([cipher.update(plaintext, "utf8"), cipher.final()]);+ return {+ ciphertext: ciphertext.toString("base64"),+ iv: iv.toString("base64"),+ tag: cipher.getAuthTag().toString("base64")+ };+}+function decryptValue(key, encrypted, aad) {+ const decipher = createDecipheriv(ALGORITHM, key, Buffer.from(encrypted.iv, "base64"));+ decipher.setAuthTag(Buffer.from(encrypted.tag, "base64"));+ if (aad !== undefined)+ decipher.setAAD(Buffer.from(aad, "utf8"));+ const plaintext = Buffer.concat([+ decipher.update(Buffer.from(encrypted.ciphertext, "base64")),+ decipher.final()+ ]);+ return plaintext.toString("utf8");+}+var ALGORITHM = "aes-256-gcm", IV_BYTES = 12;+var init_value_cipher = () => {};++// src/core/brain/secrets/owner-acl.ts+import { spawnSync } from "node:child_process";+import { resolve as resolve8, win32 as win323 } from "node:path";+function system32Tool(name, env = process.env) {+ const root = env["SystemRoot"] || env["windir"] || "C:\\Windows";+ return win323.join(root, "System32", name);+}+function parseWhoamiUser(stdout) {+ const m = /^\s*"([^"]+)","(S-1-\d+(?:-\d+)+)"\s*$/m.exec(stdout);+ return m ? { name: m[1], sid: m[2] } : null;+}+function currentWindowsIdentity() {+ if (cachedIdentity !== undefined)+ return cachedIdentity;+ try {+ const proc = spawnSync(system32Tool("whoami.exe"), ["/user", "/fo", "csv", "/nh"], {+ encoding: "utf8",+ windowsHide: true,+ timeout: TOOL_TIMEOUT_MS+ });+ cachedIdentity = proc.error === undefined && proc.status === 0 ? parseWhoamiUser(proc.stdout) : null;+ } catch {+ cachedIdentity = null;+ }+ return cachedIdentity;+}+function ownerOnlyAclArgv(path, sid, kind) {+ const rights = kind === "directory" ? "(OI)(CI)F" : "F";+ return [path, "/inheritance:r", "/grant:r", `*${sid}:${rights}`];+}+function restrictToOwner(path, kind, platform = process.platform, force = false) {+ if (platform !== "win32")+ return true;+ const key = `${kind}:${resolve8(path).toLowerCase()}`;+ if (!force && restricted.has(key))+ return true;+ let detail;+ try {+ const identity = currentWindowsIdentity();+ if (identity === null) {+ detail = "the current user's SID could not be read (whoami /user)";+ } else {+ let proc = spawnSync(system32Tool("icacls.exe"), [path, "/reset"], {+ encoding: "utf8",+ windowsHide: true,+ timeout: TOOL_TIMEOUT_MS+ });+ if (proc.error === undefined && proc.status === 0) {+ proc = spawnSync(system32Tool("icacls.exe"), [...ownerOnlyAclArgv(path, identity.sid, kind)], { encoding: "utf8", windowsHide: true, timeout: TOOL_TIMEOUT_MS });+ }+ if (proc.error === undefined && proc.status === 0) {+ restricted.add(key);+ return true;+ }+ detail = proc.error !== undefined ? proc.error.message : `icacls exited ${proc.status ?? proc.signal}: ${(proc.stderr || proc.stdout).trim()}`;+ }+ } catch (err) {+ detail = err instanceof Error ? err.message : String(err);+ }+ process.stderr.write(`warning: could not restrict secrets ${kind} to the current user, ` + `it keeps its inherited ACL: ${path}: ${detail}+`);+ return false;+}+var TOOL_TIMEOUT_MS = 1e4, cachedIdentity, restricted;+var init_owner_acl = __esm(() => {+ restricted = new Set;+});++// src/core/brain/secrets/envelope.ts+import { randomBytes as randomBytes4, scryptSync, timingSafeEqual } from "node:crypto";+import {+ chmodSync,+ closeSync as closeSync7,+ fsyncSync as fsyncSync5,+ openSync as openSync7,+ readFileSync as readFileSync14,+ unlinkSync as unlinkSync4,+ writeSync as writeSync5+} from "node:fs";+import { dirname as dirname11, resolve as resolve9 } from "node:path";+function kdfCostCurveRefusal(kdf) {+ if (kdf.n > SCRYPT_N_MAX) {+ return `kdf n ${String(kdf.n)} exceeds this build's ceiling ${String(SCRYPT_N_MAX)}`;+ }+ if (kdf.r > SCRYPT_R_MAX) {+ return `kdf r ${String(kdf.r)} exceeds this build's ceiling ${String(SCRYPT_R_MAX)}`;+ }+ if (kdf.p > SCRYPT_P_MAX) {+ return `kdf p ${String(kdf.p)} exceeds this build's ceiling ${String(SCRYPT_P_MAX)}`;+ }+ if (kdf.maxmem > SCRYPT_MAXMEM_MAX) {+ return `kdf maxmem ${String(kdf.maxmem)} exceeds this build's ceiling ${String(SCRYPT_MAXMEM_MAX)}`;+ }+ const needed = 128 * kdf.n * kdf.r;+ if (kdf.maxmem < needed) {+ return `kdf maxmem ${String(kdf.maxmem)} is below the ${String(needed)} bytes ` + `these n/r parameters need`;+ }+ return null;+}+function holderSlot(keyPath) {+ const resolved = resolve9(keyPath);+ return process.platform === "win32" ? resolved.toLowerCase() : resolved;+}+function heldUnlockedKey(keyPath) {+ return HELD_KEYS.get(holderSlot(keyPath)) ?? null;}function heldKeyOrRefusal(keyPath) {const held = HELD_KEYS.get(holderSlot(keyPath));@@ -4276,7 +6345,7 @@ function hasEnvelopeShape(parsed) {function isEnvelopeFile(keyPath) {let bytes;try {- bytes = readFileSync7(keyPath);+ bytes = readFileSync14(keyPath);} catch {return false;}@@ -4292,7 +6361,7 @@ function isEnvelopeBytes(bytes) {function readEnvelope(keyPath) {let parsed;try {- parsed = JSON.parse(readFileSync7(keyPath, "utf8"));+ parsed = JSON.parse(readFileSync14(keyPath, "utf8"));} catch (err) {throw new SecretEnvelopeError(ENVELOPE_REFUSAL_CODES.malformed, keyPath, `not parseable as an envelope: ${err instanceof Error ? err.message : String(err)}`);}@@ -4317,7 +6386,7 @@ function readEnvelope(keyPath) {function freshWrapKdfParams() {return {algo: KDF_ALGO,- salt: randomBytes3(SALT_BYTES).toString("base64"),+ salt: randomBytes4(SALT_BYTES).toString("base64"),n: SCRYPT_N,r: SCRYPT_R,p: SCRYPT_P,@@ -4403,32 +6472,32 @@ function writeRawKeyfileBytes(keyPath, dek) {const tmp = `${keyPath}.raw-tmp`;let fd = null;try {- fd = openSync3(tmp, "wx", 384);+ fd = openSync7(tmp, "wx", 384);let written = 0;while (written < dek.byteLength) {- written += writeSync2(fd, dek, written, dek.byteLength - written);+ written += writeSync5(fd, dek, written, dek.byteLength - written);}- fsyncSync3(fd);- closeSync3(fd);+ fsyncSync5(fd);+ closeSync7(fd);fd = null;renameWithRetry(tmp, keyPath);} catch (err) {if (fd !== null) {try {- closeSync3(fd);+ closeSync7(fd);} catch {}}try {- unlinkSync2(tmp);+ unlinkSync4(tmp);} catch {}throw err;}try {- const dfd = openSync3(dirname6(keyPath), "r");+ const dfd = openSync7(dirname11(keyPath), "r");try {- fsyncSync3(dfd);+ fsyncSync5(dfd);} finally {- closeSync3(dfd);+ closeSync7(dfd);}} catch {}}@@ -4450,7 +6519,7 @@ function unlockKeyfile(keyPath, passphrase) {return dek;}var KEYFILE_ENVELOPE_SCHEMA_VERSION = 1, KDF_ALGO = "scrypt", WRAP_KEY_BYTES = 32, DEK_BYTES = 32, SALT_BYTES = 16, SCRYPT_N, SCRYPT_R = 8, SCRYPT_P = 1, SCRYPT_MAXMEM, SCRYPT_N_MAX, SCRYPT_R_MAX = 16, SCRYPT_P_MAX = 8, SCRYPT_MAXMEM_MAX, ENVELOPE_REFUSAL_CODES, SecretEnvelopeError, SECRET_STORE_LOCKED_CODE = "secret_store_locked", SECRET_STORE_PASSPHRASE_ENV = "OPEN_SECOND_BRAIN_SECRETS_PASSPHRASE", SecretStoreLockedError, SECRET_STORE_KEYFILE_MISSING_CODE = "secret_store_keyfile_missing", SecretStoreKeyfileMissingError, HELD_KEYS;-var init_envelope = __esm(() => {+var init_envelope2 = __esm(() => {init_fs_atomic();init_value_cipher();init_owner_acl();@@ -4497,24 +6566,24 @@ var init_envelope = __esm(() => {});// src/core/brain/secrets/crypto.ts-import { randomBytes as randomBytes4 } from "node:crypto";+import { randomBytes as randomBytes5 } from "node:crypto";import {chmodSync as chmodSync2,- closeSync as closeSync4,- existsSync as existsSync7,- mkdirSync as mkdirSync6,- openSync as openSync4,- readFileSync as readFileSync8,- writeFileSync as writeFileSync2,- writeSync as writeSync3+ closeSync as closeSync8,+ existsSync as existsSync9,+ mkdirSync as mkdirSync11,+ openSync as openSync8,+ readFileSync as readFileSync15,+ writeFileSync as writeFileSync3,+ writeSync as writeSync6} from "node:fs";-import { dirname as dirname7, join as join11 } from "node:path";+import { dirname as dirname12, join as join20 } from "node:path";function ensureSyncExclusionMarker(dir) {- const marker = join11(dir, ".gitignore");- if (existsSync7(marker))+ const marker = join20(dir, ".gitignore");+ if (existsSync9(marker))return;try {- writeFileSync2(marker, SYNC_EXCLUSION_CONTENT, { encoding: "utf8", flag: "wx", mode: 384 });+ writeFileSync3(marker, SYNC_EXCLUSION_CONTENT, { encoding: "utf8", flag: "wx", mode: 384 });} catch (err) {if (err.code !== "EEXIST") {process.stderr.write(`warning: could not write the sync-exclusion marker for the secrets directory: ` + `${marker}: ${err instanceof Error ? err.message : String(err)}@@ -4523,8 +6592,8 @@ function ensureSyncExclusionMarker(dir) {}}function loadOrCreateKey(keyPath) {- const keyDir = dirname7(keyPath);- if (existsSync7(keyPath)) {+ const keyDir = dirname12(keyPath);+ if (existsSync9(keyPath)) {restrictToOwner(keyDir, "directory");restrictToOwner(keyPath, "file");if (process.platform !== "win32") {@@ -4537,7 +6606,7 @@ function loadOrCreateKey(keyPath) {}}ensureSyncExclusionMarker(keyDir);- const key2 = readFileSync8(keyPath);+ const key2 = readFileSync15(keyPath);if (isEnvelopeBytes(key2))return heldKeyOrRefusal(keyPath);if (key2.length !== KEY_BYTES) {@@ -4545,22 +6614,22 @@ function loadOrCreateKey(keyPath) {}return key2;}- mkdirSync6(keyDir, { recursive: true, mode: 448 });+ mkdirSync11(keyDir, { recursive: true, mode: 448 });restrictToOwner(keyDir, "directory");ensureSyncExclusionMarker(keyDir);- const key = randomBytes4(KEY_BYTES);+ const key = randomBytes5(KEY_BYTES);let fd;try {- fd = openSync4(keyPath, "wx", 384);+ fd = openSync8(keyPath, "wx", 384);} catch (exc) {if (exc.code === "EEXIST")return loadOrCreateKey(keyPath);throw exc;}try {- writeSync3(fd, key);+ writeSync6(fd, key);} finally {- closeSync4(fd);+ closeSync8(fd);}restrictToOwner(keyPath, "file");return key;@@ -4569,7 +6638,7 @@ var KEY_BYTES = 32, SYNC_EXCLUSION_CONTENT = `*!.gitignore`;var init_crypto = __esm(() => {- init_envelope();+ init_envelope2();init_owner_acl();init_value_cipher();});@@ -4598,19 +6667,19 @@ __export(exports_store, {withSecretsLock: () => withSecretsLock,writeStore: () => writeStore});-import { chmodSync as chmodSync3, existsSync as existsSync8, readFileSync as readFileSync9, statSync as statSync7, writeFileSync as writeFileSync3 } from "node:fs";-import { join as join12 } from "node:path";+import { chmodSync as chmodSync3, existsSync as existsSync10, readFileSync as readFileSync16, statSync as statSync11, writeFileSync as writeFileSync4 } from "node:fs";+import { join as join21 } from "node:path";function secretsDir(vault) {- return join12(vault, ".open-second-brain", "secrets");+ return join21(vault, ".open-second-brain", "secrets");}function storePath(vault) {- return join12(secretsDir(vault), "secrets.json");+ return join21(secretsDir(vault), "secrets.json");}function keyPath(vault) {- return join12(secretsDir(vault), "keyfile");+ return join21(secretsDir(vault), "keyfile");}function tokenStorePath(vault) {- return join12(secretsDir(vault), "mcp-tokens.json");+ return join21(secretsDir(vault), "mcp-tokens.json");}function isValidSecretName(name) {return NAME_RE.test(name);@@ -4633,7 +6702,7 @@ function withSecretsLock(vault, fn) {let lastError;for (let attempt = 0;attempt < maxAttempts && release === null; attempt++) {try {- release = import_proper_lockfile3.default.lockSync(secretsDir(vault), { stale: 1e4, realpath: false });+ release = import_proper_lockfile4.default.lockSync(secretsDir(vault), { stale: 1e4, realpath: false });} catch (exc) {if (exc.code !== "ELOCKED")throw exc;@@ -4741,7 +6810,7 @@ function resolveSecretReadOnly(vault, name) {throw new Error(`unknown secret "${normalized}"`);}const kp = keyPath(vault);- if (!existsSync8(kp))+ if (!existsSync10(kp))throw new SecretStoreKeyfileMissingError(kp);const key = loadOrCreateKey(kp);return {@@ -4794,9 +6863,9 @@ function custodyTargets(vault) {[secretsDir(vault), "directory"],[keyPath(vault), "file"]];- if (existsSync8(storePath(vault)))+ if (existsSync10(storePath(vault)))targets.push([storePath(vault), "file"]);- if (existsSync8(tokenStorePath(vault)))+ if (existsSync10(tokenStorePath(vault)))targets.push([tokenStorePath(vault), "file"]);return targets;}@@ -4811,19 +6880,19 @@ function toMetadata(name, stored) {}function readStore(vault) {const path = storePath(vault);- if (!existsSync8(path))+ if (!existsSync10(path))return { version: SECRETS_SCHEMA_VERSION, secrets: {} };restrictToOwner(path, "file");if (process.platform !== "win32") {try {- if ((statSync7(path).mode & 511) !== 384)+ if ((statSync11(path).mode & 511) !== 384)chmodSync3(path, 384);} catch (err) {process.stderr.write(`warning: could not re-apply owner-only mode to the secrets store: ` + `${path}: ${err instanceof Error ? err.message : String(err)}`);}}- const parsed = JSON.parse(readFileSync9(path, "utf8"));+ const parsed = JSON.parse(readFileSync16(path, "utf8"));if (parsed === null || typeof parsed !== "object" || parsed.version !== SECRETS_SCHEMA_VERSION) {throw new Error(`secrets store is corrupt or from a newer version: ${path}`);}@@ -4840,7 +6909,7 @@ function writeStore(vault, file) {loadOrCreateKey(keyPath(vault));const path = storePath(vault);const tmp = `${path}.tmp`;- writeFileSync3(tmp, JSON.stringify(file, null, 2) + `+ writeFileSync4(tmp, JSON.stringify(file, null, 2) + ``, { mode: 384 });renameWithRetry(tmp, path);}@@ -4857,16 +6926,16 @@ function touchLastUsed(vault, name, now) {});}function audit(vault, ctx, action, name, details) {- appendAuditRecord(join12(brainDirsForWrite(vault).log, SECRET_CUSTODY_AUDIT_DIR), {+ appendAuditRecord(join21(brainDirsForWrite(vault).log, SECRET_CUSTODY_AUDIT_DIR), {timestamp: ctx.now.toISOString(),actor: ctx.agent,action,target: name,ok: true,details- });+ }, vault);}-var import_proper_lockfile3, SECRETS_SCHEMA_VERSION = 1, NAME_RE, ENV_VAR_RE;+var import_proper_lockfile4, SECRETS_SCHEMA_VERSION = 1, NAME_RE, ENV_VAR_RE;var init_store = __esm(() => {init_fs_atomic();init_audit();@@ -4875,9 +6944,9 @@ var init_store = __esm(() => {init_time();init_vault_identity();init_crypto();- init_envelope();+ init_envelope2();init_owner_acl();- import_proper_lockfile3 = __toESM(require_proper_lockfile(), 1);+ import_proper_lockfile4 = __toESM(require_proper_lockfile(), 1);NAME_RE = /^[a-z0-9][a-z0-9_-]*$/;ENV_VAR_RE = /^[A-Z_][A-Z0-9_]*$/;});@@ -5062,7 +7131,7 @@ function redactConfigMapping(data, policy = {}) {init_config();init_secret_ref();init_secret_ref();-import { existsSync as existsSync9 } from "node:fs";+import { existsSync as existsSync11 } from "node:fs";var custodyStoreModule;function custodyStore() {if (custodyStoreModule === undefined) {@@ -5113,7 +7182,7 @@ function resolvedSecretLiterals(vault) {}const heldNames = new Set(held.map((meta) => meta.name));const out = [];- if (held.length > 0 && existsSync9(store.keyPath(vault))) {+ if (held.length > 0 && existsSync11(store.keyPath(vault))) {for (const meta of held) {try {out.push(store.resolveSecretReadOnly(vault, meta.name).value);@@ -5168,21 +7237,21 @@ function probeVaultDirectory(vault) {init_config();init_fs_utils();import {- existsSync as existsSync11,- mkdirSync as mkdirSync7,- openSync as openSync5,- readFileSync as readFileSync10,+ existsSync as existsSync13,+ mkdirSync as mkdirSync12,+ openSync as openSync9,+ readFileSync as readFileSync17,rmSync as rmSync2,- writeSync as writeSync4,- closeSync as closeSync5+ writeSync as writeSync7,+ closeSync as closeSync9} from "node:fs";-import { dirname as dirname9, join as join14 } from "node:path";+import { dirname as dirname14, join as join23 } from "node:path";// src/core/partner/codegraph.tsinit_config();init_fs_utils();-import { existsSync as existsSync10, readdirSync, realpathSync as realpathSync2 } from "node:fs";-import { dirname as dirname8, join as join13, resolve as resolve9 } from "node:path";+import { existsSync as existsSync12, readdirSync as readdirSync3, realpathSync as realpathSync3 } from "node:fs";+import { dirname as dirname13, join as join22, resolve as resolve10 } from "node:path";// src/core/project-manifests.tsvar MANIFEST_ECOSYSTEM = Object.freeze({@@ -5285,11 +7354,11 @@ function codegraphInitCommand(projectPath) {}function isCodeProject(dir) {try {- if (!existsSync10(dir))+ if (!existsSync12(dir))return false;- if (!isDir(join13(dir, ".git")))+ if (!isDir(join22(dir, ".git")))return false;- return CODE_MANIFEST_FILES.some((m) => existsSync10(join13(dir, m)));+ return CODE_MANIFEST_FILES.some((m) => existsSync12(join22(dir, m)));} catch {return false;}@@ -5302,7 +7371,7 @@ function findCodeProjects(opts) {const consider = (raw) => {if (scanned >= limit)return;- const path = resolve9(raw);+ const path = resolve10(raw);if (seen.has(path))return;seen.add(path);@@ -5313,11 +7382,11 @@ function findCodeProjects(opts) {found.push(path);};consider(opts.cwd);- const vaultParent = dirname8(resolve9(opts.vault));+ const vaultParent = dirname13(resolve10(opts.vault));if (isDir(vaultParent)) {let entries = [];try {- entries = readdirSync(vaultParent);+ entries = readdirSync3(vaultParent);} catch {entries = [];}@@ -5325,7 +7394,7 @@ function findCodeProjects(opts) {for (const name of entries) {if (scanned >= limit)break;- consider(join13(vaultParent, name));+ consider(join22(vaultParent, name));}}for (const extra of opts.scanExtraPaths ?? []) {@@ -5467,7 +7536,7 @@ function codegraphDisabledResult() {};}function evaluateProjectStatus(project, deps) {- const indexDir = join13(project, ".codegraph");+ const indexDir = join22(project, ".codegraph");let indexed;try {indexed = statOrAbsent(indexDir)?.isDirectory() === true;@@ -5537,7 +7606,7 @@ function resolveRealpath(value) {if (!value)return null;try {- return realpathSync2(value);+ return realpathSync3(value);} catch {return value;}@@ -5546,7 +7615,7 @@ function resolveRealpath(value) {// src/core/doctor.tsvar MANIFEST_FIX = "o2b update";function checkVaultWriteable(vault) {- if (!existsSync11(vault)) {+ if (!existsSync13(vault)) {return {name: "vault_writeable",ok: false,@@ -5554,10 +7623,10 @@ function checkVaultWriteable(vault) {fix: `mkdir -p "${vault}"`};}- const probe = join14(vault, ".open-second-brain-doctor-test");+ const probe = join23(vault, ".open-second-brain-doctor-test");try {- const fd = openSync5(probe, "w");- closeSync5(fd);+ const fd = openSync9(probe, "w");+ closeSync9(fd);rmSync2(probe);} catch (exc) {return {@@ -5572,12 +7641,12 @@ function checkVaultWriteable(vault) {function checkConfigWriteable(config) {let createdForCheck = false;try {- mkdirSync7(dirname9(config), { recursive: true });- if (!existsSync11(config))+ mkdirSync12(dirname14(config), { recursive: true });+ if (!existsSync13(config))createdForCheck = true;- const fd = openSync5(config, "a");- writeSync4(fd, "");- closeSync5(fd);+ const fd = openSync9(config, "a");+ writeSync7(fd, "");+ closeSync9(fd);if (createdForCheck)rmSync2(config);} catch (exc) {@@ -5585,7 +7654,7 @@ function checkConfigWriteable(config) {name: "config_writeable",ok: false,message: `cannot write config ${config}: ${exc.message ?? exc}`,- fix: `mkdir -p "${dirname9(config)}" && chmod u+rwx "${dirname9(config)}"`+ fix: `mkdir -p "${dirname14(config)}" && chmod u+rwx "${dirname14(config)}"`};}return { name: "config_writeable", ok: true, message: `config writable: ${config}` };@@ -5615,7 +7684,7 @@ function loadJsonManifest(path, name) {}let data;try {- data = JSON.parse(readFileSync10(path, "utf8"));+ data = JSON.parse(readFileSync17(path, "utf8"));} catch (exc) {return {result: {@@ -5741,7 +7810,7 @@ function checkHermesManifest(path) {}let text;try {- text = readFileSync10(path, "utf8");+ text = readFileSync17(path, "utf8");} catch (exc) {return {name: "hermes_manifest",@@ -5790,7 +7859,7 @@ function checkOpenclawManifest(path) {}function checkOpenclawInstallability(repoRoot) {const results = [];- const pkgPath = join14(repoRoot, "package.json");+ const pkgPath = join23(repoRoot, "package.json");const { result, data } = loadJsonManifest(pkgPath, "openclaw_package_json");results.push(result);if (!data)@@ -5821,7 +7890,7 @@ function checkOpenclawInstallability(repoRoot) {});continue;}- const entryPath = join14(repoRoot, entry);+ const entryPath = join23(repoRoot, entry);const problem = manifestFileProblem(entryPath);if (problem === null) {results.push({@@ -5857,10 +7926,10 @@ function doctor(opts) {results.push(checkConfigWriteable(opts.config));if (opts.repoRoot) {const root = opts.repoRoot;- results.push(checkClaudeManifest(join14(root, ".claude-plugin", "plugin.json")));- results.push(checkCodexManifest(join14(root, ".codex-plugin", "plugin.json")));- results.push(checkHermesManifest(join14(root, "plugins", "hermes", "plugin.yaml")));- results.push(checkOpenclawManifest(join14(root, "openclaw.plugin.json")));+ results.push(checkClaudeManifest(join23(root, ".claude-plugin", "plugin.json")));+ results.push(checkCodexManifest(join23(root, ".codex-plugin", "plugin.json")));+ results.push(checkHermesManifest(join23(root, "plugins", "hermes", "plugin.yaml")));+ results.push(checkOpenclawManifest(join23(root, "openclaw.plugin.json")));results.push(...checkOpenclawInstallability(root));}const cg = checkCodegraph({@@ -5875,10 +7944,10 @@ function doctor(opts) {}// src/core/identity-reminder.ts-import { readFileSync as readFileSync11 } from "node:fs";-import { dirname as dirname10, resolve as resolve10 } from "node:path";-import { fileURLToPath } from "node:url";-var TEMPLATE_PATH = resolve10(dirname10(fileURLToPath(import.meta.url)), "..", "..", "templates", "identity-reminder.txt");+import { readFileSync as readFileSync18 } from "node:fs";+import { dirname as dirname15, resolve as resolve11 } from "node:path";+import { fileURLToPath as fileURLToPath2 } from "node:url";+var TEMPLATE_PATH = resolve11(dirname15(fileURLToPath2(import.meta.url)), "..", "..", "templates", "identity-reminder.txt");var RUNTIME_TARGET = Object.freeze({hermes: "hermes",openclaw: "openclaw"@@ -5895,7 +7964,7 @@ function loadReminderTemplate() {if (commonTemplateCache !== undefined)return commonTemplateCache;try {- commonTemplateCache = readFileSync11(TEMPLATE_PATH, "utf8").trimEnd();+ commonTemplateCache = readFileSync18(TEMPLATE_PATH, "utf8").trimEnd();return commonTemplateCache;} catch (err) {const message = err instanceof Error ? err.message : String(err);@@ -5904,8 +7973,8 @@ function loadReminderTemplate() {});}}-var TEMPLATES_DIR = resolve10(dirname10(fileURLToPath(import.meta.url)), "..", "..", "templates");-var PER_TARGET_PATHS = Object.freeze(Object.fromEntries(KNOWN_RUNTIME_TARGETS.map((t) => [t, resolve10(TEMPLATES_DIR, `identity-reminder.${t}.txt`)])));+var TEMPLATES_DIR = resolve11(dirname15(fileURLToPath2(import.meta.url)), "..", "..", "templates");+var PER_TARGET_PATHS = Object.freeze(Object.fromEntries(KNOWN_RUNTIME_TARGETS.map((t) => [t, resolve11(TEMPLATES_DIR, `identity-reminder.${t}.txt`)])));var TEMPLATE_CACHE = new Map;function tryReadTargetTemplate(target) {const cached = TEMPLATE_CACHE.get(target);@@ -5913,7 +7982,7 @@ function tryReadTargetTemplate(target) {return cached;let body;try {- body = readFileSync11(PER_TARGET_PATHS[target], "utf8").trimEnd();+ body = readFileSync18(PER_TARGET_PATHS[target], "utf8").trimEnd();} catch (err) {if (err.code !== "ENOENT")throw err;@@ -5946,322 +8015,9 @@ function buildReminder(agent, target) {return loadReminderTemplate().replace(/\{agent\}/g, agent);}-// src/core/vault.ts-init_wikilink();-init_fs_atomic();-init_fs_utils();-init_degradation();-init_path_safety();-import { mkdirSync as mkdirSync8, readFileSync as readFileSync12, readdirSync as readdirSync2, writeFileSync as writeFileSync4 } from "node:fs";-import { dirname as dirname11, join as join15, relative as relative2 } from "node:path";--// src/core/graph/transport-reach.ts-var TRANSPORT_REACH = Object.freeze({- local: "local",- remote: "remote"-});-var TRANSPORT_REACHES = Object.freeze([- TRANSPORT_REACH.local,- TRANSPORT_REACH.remote-]);-var MAINTENANCE_LANE_REACH = TRANSPORT_REACH.local;--// src/core/graph/visibility.ts-function normToken(raw) {- return raw.normalize("NFC").trim().toLowerCase();-}-function pageVisibility(meta) {- const v = meta["visibility"];- const list = Array.isArray(v) ? v : typeof v === "string" && v.length > 0 ? [v] : [];- return list.map((s) => normToken(String(s))).filter((s) => s.length > 0);-}-var REMOTE_DENY_VISIBILITY_TOKEN = "private";-function isRemotelyReadable(pageTags, reach) {- if (reach === TRANSPORT_REACH.local)- return true;- return !pageTags.includes(REMOTE_DENY_VISIBILITY_TOKEN);-}--// src/core/graph/privacy-markers.ts-var PRIVACY_MARKER_KEYS = Object.freeze([- "access",- "confidentiality",- "sensitivity"-]);-var PRIVACY_DENY_MARKER_VALUES = Object.freeze([- "private",- "secret",- "confidential"-]);-function declaredValues(raw) {- if (typeof raw === "string")- return [raw];- if (!Array.isArray(raw))- return [];- return raw.filter((v) => typeof v === "string");-}-var PRIVACY_MARKER_KEY_TOKENS = Object.freeze(new Set(PRIVACY_MARKER_KEYS.map((key) => normToken(key))));-function hasPrivacyDenyMarker(meta) {- for (const key of Object.keys(meta)) {- if (!PRIVACY_MARKER_KEY_TOKENS.has(normToken(key)))- continue;- for (const value of declaredValues(meta[key])) {- if (PRIVACY_DENY_MARKER_VALUES.includes(normToken(value)))- return true;- }- }- return false;-}-function markerDenyTokens(meta) {- return hasPrivacyDenyMarker(meta) ? Object.freeze([REMOTE_DENY_VISIBILITY_TOKEN]) : Object.freeze([]);-}-function remoteDenyVisibilityTokens(meta) {- const declared = pageVisibility(meta);- const out = [...declared];- for (const token of markerDenyTokens(meta)) {- if (!out.includes(token))- out.push(token);- }- return Object.freeze(out);-}--// src/core/vault.ts-init_fs_utils();-var FRONTMATTER_RE = /^---[^\S\n]*\n([\s\S]*?)\n---\s*\n?/;-var BYTE_ORDER_MARK = 65279;-var FRONTMATTER_KEY_PATTERN = "[a-zA-Z_][a-zA-Z0-9_-]*";-var FRONTMATTER_KEY_RE = new RegExp(`^${FRONTMATTER_KEY_PATTERN}$`);-var KEY_VALUE_RE = new RegExp(`^(${FRONTMATTER_KEY_PATTERN})\\s*:\\s*(.*?)\\s*$`);-var DASH_ITEM_RE = /^-(?:\s+(.*))?$/;-var MEDIA_EXTENSIONS = new Set([- ".png",- ".jpg",- ".jpeg",- ".gif",- ".svg",- ".webp",- ".bmp",- ".tiff",- ".avif",- ".mp4",- ".webm",- ".ogv",- ".mov",- ".mkv",- ".avi",- ".mp3",- ".wav",- ".ogg",- ".flac",- ".m4a",- ".pdf"-]);-var DEFAULT_SKIP_DIRS = [".git", ".obsidian", ".trash", ".stversions"];-var DEFAULT_SKIP_FILES = ["index.md", "log.md"];-var FRONTMATTER_SITE = "vault.parseFrontmatter";-var NOTICE_LINE_MAX = 120;-var NOTICE_LINE_ELLIPSIS = "β¦";-function parseFrontmatterWithNotices(path, opts = {}) {- const site = opts.site ?? FRONTMATTER_SITE;- let text;- try {- text = readFileSync12(path, "utf8");- } catch (err) {- const notices = [];- emitDegradationNotice(notices, {- code: DEGRADATION_CODE.frontmatterUnreadable,- site,- path,- detail: `frontmatter read failed: ${err instanceof Error ? err.message : String(err)}`- });- return [{}, "", notices];- }- return parseFrontmatterTextWithNotices(text, { site, path });-}-function parseFrontmatterTextWithNotices(raw, opts = {}) {- const notices = [];- const site = opts.site ?? FRONTMATTER_SITE;- const text = raw.charCodeAt(0) === BYTE_ORDER_MARK ? raw.slice(1) : raw;- const match = FRONTMATTER_RE.exec(text);- if (!match) {- return [{}, text.trim(), notices];- }- const fmBlock = match[1];- const body = text.slice(match[0].length).trim();- const metadata = {};- const lines = fmBlock.split(`-`);- let blockKey = null;- for (let i = 0;i < lines.length; i++) {- const line = lines[i].trim();- if (!line || line.startsWith("#"))- continue;- const dash = DASH_ITEM_RE.exec(line);- if (dash && blockKey !== null) {- const arr = metadata[blockKey] ?? [];- arr.push(stripQuotes(dash[1] ?? ""));- metadata[blockKey] = arr;- continue;- }- blockKey = null;- const kv = KEY_VALUE_RE.exec(line);- if (!kv) {- emitDegradationNotice(notices, {- code: DEGRADATION_CODE.frontmatterLineDropped,- site,- ...opts.path !== undefined ? { path: opts.path } : {},- detail: `frontmatter line ${i + 1} is not a supported key/value or list item: ${clipNoticeLine(line)}`- });- continue;- }- const key = kv[1];- let value = kv[2].trim();- if (value === "") {- let j = i + 1;- let nextMeaningful = null;- while (j < lines.length) {- const cand = lines[j].trim();- if (!cand || cand.startsWith("#")) {- j++;- continue;- }- nextMeaningful = cand;- break;- }- if (nextMeaningful !== null && DASH_ITEM_RE.test(nextMeaningful)) {- metadata[key] = [];- blockKey = key;- } else {- metadata[key] = "";- }- continue;- }- if (value.startsWith("[") && value.endsWith("]")) {- const inner = value.slice(1, -1).trim();- metadata[key] = inner ? splitInlineArray(inner) : [];- continue;- }- metadata[key] = stripQuotes(value);- }- return [metadata, body, notices];-}-function clipNoticeLine(line) {- return line.length <= NOTICE_LINE_MAX ? line : line.slice(0, NOTICE_LINE_MAX) + NOTICE_LINE_ELLIPSIS;-}-var LIST_VAULT_PAGES_SITE = "vault.listVaultPages";-var COLLATOR = new Intl.Collator("en", { numeric: true });-var UNMEASURABLE_PAGE_VISIBILITY = Object.freeze([- REMOTE_DENY_VISIBILITY_TOKEN-]);-function listVaultPages(vaultDir, opts) {- const skipDirs = new Set(opts.skipDirs ?? DEFAULT_SKIP_DIRS);- const skipFiles = new Set((opts.skipFiles ?? DEFAULT_SKIP_FILES).map((f) => f.toLowerCase()));- const walked = [];- walk(vaultDir, vaultDir, skipDirs, skipFiles, walked, {- sink: opts.notices,- site: opts.site ?? LIST_VAULT_PAGES_SITE- });- const pages = walked.filter((w) => isRemotelyReadable(w.unreadable ? UNMEASURABLE_PAGE_VISIBILITY : remoteDenyVisibilityTokens(w.page.metadata), opts.reach)).map((w) => w.page);- pages.sort((a, b) => COLLATOR.compare(a.title.toLowerCase(), b.title.toLowerCase()));- return pages;-}-function walk(root, dir, skipDirs, skipFiles, out, notices) {- let entries;- try {- entries = readdirSync2(dir, { withFileTypes: true });- } catch (err) {- if (notices.sink !== undefined) {- emitDegradationNotice(notices.sink, {- code: DEGRADATION_CODE.vaultWalkEntrySkipped,- site: notices.site,- path: dir,- detail: `directory listing failed: ${err instanceof Error ? err.message : String(err)}`- });- }- return;- }- for (const entry of entries) {- const full = join15(dir, entry.name);- if (entry.isDirectory()) {- if (skipDirs.has(entry.name))- continue;- walk(root, full, skipDirs, skipFiles, out, notices);- continue;- }- if (!entry.isFile())- continue;- if (!entry.name.toLowerCase().endsWith(".md"))- continue;- if (skipFiles.has(entry.name.toLowerCase()))- continue;- const rel = relative2(root, full);- const parts = rel.split(/[\\/]/);- if (parts.some((p) => skipDirs.has(p)))- continue;- const [meta, , pageNotices] = parseFrontmatterWithNotices(full, { site: notices.site });- if (notices.sink !== undefined)- notices.sink.push(...pageNotices);- const titleVal = meta["title"];- const title = typeof titleVal === "string" && titleVal ? titleVal : stem(entry.name);- out.push({- page: { title, path: full, metadata: meta },- unreadable: pageNotices.some((n) => n.code === DEGRADATION_CODE.frontmatterUnreadable)- });- }-}-function stripQuotes(s) {- if (s.length >= 2 && s.startsWith('"') && s.endsWith('"')) {- return unescapeDoubleQuoted(s.slice(1, -1));- }- if (s.length >= 2 && s.startsWith("'") && s.endsWith("'")) {- return s.slice(1, -1);- }- return s;-}-var DOUBLE_QUOTED_ESCAPES = Object.freeze({- "\\": "\\",- '"': '"',- n: `-`,- r: "\r",- t: "\t"-});-function unescapeDoubleQuoted(inner) {- return inner.replace(/\\([\\"nrt])/g, (_, ch) => DOUBLE_QUOTED_ESCAPES[ch] ?? `\\${ch}`);-}-function splitInlineArray(inner) {- const out = [];- let current = "";- let inQuote = false;- let quoteChar = "";- for (let i = 0;i < inner.length; i++) {- const ch = inner[i];- if (inQuote) {- current += ch;- if (ch === quoteChar && inner[i - 1] !== "\\") {- inQuote = false;- quoteChar = "";- }- continue;- }- if (ch === '"' || ch === "'") {- inQuote = true;- quoteChar = ch;- current += ch;- continue;- }- if (ch === ",") {- out.push(stripQuotes(current.trim()));- current = "";- continue;- }- current += ch;- }- if (current.trim() !== "") {- out.push(stripQuotes(current.trim()));- }- return out;-}+// src/openclaw/index.ts+init_vault();+init_transport_reach();// src/core/brain/entities/types.tsvar BRAIN_ENTITY_STATUS = {@@ -6350,7 +8106,7 @@ init_path_safety();// src/mcp/vault-path-field.tsinit_config();-init_envelope();+init_envelope2();init_secret_ref();var VAULT_PATH_OUTPUT_SCHEMA = Object.freeze({});var CONFIG_UNREADABLE_REASON = "the device-local config could not be read, so this reference cannot be " + "resolved; call second_brain_status for the file and the remedy";diff --git a/openspec/changes/archive/.gitkeep b/openspec/changes/archive/.gitkeepnew file mode 100644index 00000000..e69de29bdiff --git a/openspec/changes/brain-store-and-topics/.openspec.yaml b/openspec/changes/brain-store-and-topics/.openspec.yamlnew file mode 100644index 00000000..18807b93--- /dev/null+++ b/openspec/changes/brain-store-and-topics/.openspec.yaml@@ -0,0 +1,2 @@+schema: jeex+created: 2026-11-06diff --git a/openspec/changes/brain-store-and-topics/brainstorm.md b/openspec/changes/brain-store-and-topics/brainstorm.mdnew file mode 100644index 00000000..c620b7fc--- /dev/null+++ b/openspec/changes/brain-store-and-topics/brainstorm.md@@ -0,0 +1,88 @@+# Brainstorm++## Problem++Open Second Brain writes all of its machine data into the user's Obsidian vault under `Brain/`. On a real install that is about 7.7k of the roughly 8.3k files Obsidian indexes (6.6k signal files, about 800 log files, 238 preference files), plus about 2 GB of hidden snapshots and ledgers that file sync still ships to every device, including phones. Obsidian mobile chokes while indexing them. The feature must move machine data out of the vault into its own store, keep only human-readable material in a human-facing view, make Obsidian optional, and add user-facing topics, without giving up the product's values: user-owned open data readable without the tool, any agent runtime, append-only recoverable evidence, and one brain shared by several machines.++## Related work++- No OpenSpec specs exist yet in this repository; this is the first change.+- Paths are centralised in `src/core/brain/path-constants.ts` (`BRAIN_ROOT_REL` and the per-lane constants), so relocating the store is a bounded change at the path layer.+- The derived index `.open-second-brain/brain.sqlite` is already per-device and excluded from file sync.+- The decision-model framework (`src/core/decision-model/`, `docs/decision-models.md`) already provides `off`/`shadow`/`enforce` uses, a canonical deterministic fallback, a daily cost gate, local thresholds and local-model routes.+- The existing word "topic" in the dream pass (`dream-plan-topics.ts`, `topicKey`) means a preference slug. The new user-facing topic needs a different name in code.+- Prior art studied: the "office" memory setup of another project the owner uses (fixed `topic.md` schema with Goal, Milestones, Decisions, Open questions, newest-first Log, Related; one owning skill per memory folder; topic heads handed to agents for routing; a gardener pass that archives finished topics). The owner reports it works very well, especially running one area of work or one matter per topic.++## Doubts++1. Ordering and merge rules across machines: which clock orders records from different writers, and how mutable entities (preferences, pinned context, topic fields) resolve concurrent edits deterministically on every machine.+2. Several agent processes on one machine at once: one shard per writer process versus one per device with a local lock, and what happens on Windows where append atomicity differs.+3. File sync delivering a half-written last line of a growing shard; readers must skip it and pick it up later.+4. Index catch-up cost per query when many shards exist (stat every shard before each read?), and how a rebuild is triggered when the record format version changes.+5. The gardener: what happens when it is offline for days, when two devices claim it, and how a user edit to `topic.md` on a phone merges against agent events that arrived meanwhile.+6. Decision-model verdicts must be recorded once in the event; recomputing per machine would break convergence.+7. Migration of a live install without losing evidence, and readers outside the TS core (Hermes plugin, Python bits, skills that point agents at `Brain/...` paths).+8. Snapshot size: 1.7 GB of upgrade snapshots today. Should snapshots stay per device and unsynced, with retention?+9. Privacy: topic events may be personal, so the decision-model uses that read them should default to a local model.++## Approaches considered++1. **Files plus index, refactored (author).** A separate store directory synced between working machines and not to phones. Append-only JSONL shards with exactly one writer each (`events/<device>/<writer>/<YYYY-MM>.jsonl`), Markdown for documents, a per-device SQLite index that catches up from shard byte offsets, and generated human pages. Evidence: the derived index already exists and is per device; paths are centralised; Syncthing never conflicts on a file that has one writer. Cost: we own ordering, merge rules, compaction and format versioning. Risk: silent divergence if a merge rule is not deterministic; mitigated by a fixed reading order, a state digest compared across devices and property tests.+2. **DoltLite, one local database per device with per-device file remotes (research).** SQLite-compatible SQL with commit, branch, diff and merge, and vectors built in. Cost: native addon; the project is young (created 2026-03, beta since 2026-08); file remotes over Syncthing are untested; the data is not readable without its tool.+3. **SQLite session changesets as the sync log (research).** A normal local SQLite per device, with each transaction's changeset saved as an immutable file that file sync carries. Cost: binary changesets are not readable without a tool; Bun exposes sessions only through `node:sqlite` and per-OS support is unverified; we would write conflict handling across schema migrations.+4. **The owner's three candidates (TencentDB Agent Memory, HutchDB, CortexDB).** All three need a central server for several machines, and two are effectively single-author projects. See Rejected.++## Decision++Approach 1, decided by the owner after the research. Elements agreed in the discussion:++1. The store lives outside the vault, is synced between all of the user's working machines (workstations, laptops, servers) and never reaches the phone. Agents on different machines see each other's records with sync delay (seconds, sometimes minutes); the owner accepted that, so no real-time relay is needed.+2. One writer per shard, covering several concurrent agents on one machine.+3. A per-device index, never synced, caught up before reads.+4. The human view is a few generated pages plus topics, written into the vault, a plain Markdown folder or nowhere. Phones see only this view. The owner's test for what belongs there: readable by a person, not machine data that only looks readable.+5. Topics as folders with a fixed readable `topic.md`. They are created automatically during dream and on user request, and can hold any area: project, sub-project or personal matter. Agents write topic events and never the page. A single gardener device renders pages. User edits are merged back as human events and always win.+6. Context economy: agents get topic heads and budgeted rules at session start, pull detail on demand, and see neighbours' fresh events only when they matter to the current task.+7. Optional decision-model uses plug into the existing framework, off by default: route to topic, event kind, human-readable or machine, new topic, same topic, question resolved, milestone looks done, head selection, neighbour relevance. Verdicts are stored in the event once. Human events override them. Personal data goes to a local model by default.+8. Automatic and reversible actions (route an event, create a topic) apply with one-command undo and are listed in the dream report. Merges and splits are proposed and wait for the user. The author made this call because the owner's question was left open; the partner should challenge it.+9. Rust fit is a tie-breaker only. The design should port cleanly to a future Rust core, but TypeScript on Bun is the target now.++## Rejected++- TencentDB Agent Memory: an application built around a central server and an LLM proxy, not a store; devices cannot write offline and merge later.+- HutchDB: a Postgres server under AGPL plus a CLA, one developer, no releases, no vectors.+- CortexDB: a Go engine that needs a central gRPC server to share across machines; effectively one author; it competes with the product rather than serving as a layer under it.+- One SQLite file synced by file sync: a known failure that produced gigabytes of conflict copies on this install.+- cr-sqlite: no release since 2024-01.+- Turso and libSQL sync: offline writes sync only through a vendor cloud.+- ElectricSQL, PowerSync, rqlite, LiteFS: need a central primary or a quorum.+- Automerge, Loro and Yjs as the main store: they hold documents in memory and have no querying. They may still serve small mutable documents later.+- Agent-memory frameworks (mem0, Letta, Graphiti, Cognee, MemOS): built on external database servers; none merges writes from several machines without a server.++## Partner round: what changed++The partner agreed with approach 1 and pointed out that `src/core/brain/ledger-shards.ts` already implements its core. Accepted changes, each checked against the code:++1. Files per partition, stream, device and month, not per writer process. Process ids churn, so per-process shards would explode the file count. Agents on one device share the device file under a device-local lock.+2. No configured gardener. Device config is never synced (`src/core/config.ts`), so "the first device in shared config" has nowhere to live. Rendering is a pure function. The partner proposed an expiring lease; the review then showed that delayed sync cannot make a lease exclusive, so the final design uses one view writer device named by a shared human setting (design.md D7).+3. A hybrid logical clock in every record. Mutable entities fold by authority (human, agent, model), then by clock. Tombstones replace deletion.+4. Snapshots move out of the vault, stay per device and unsynced, and obey retention by manifest order. Upgrade snapshots currently bypass retention.+5. State digests and property tests become explicit requirements, not just mitigations.+6. Skills are the riskiest migration surface (`skills/brain-memory`, `skills/open-second-brain` name `Brain/` paths). Skills ask the CLI for paths, and doctor detects a regenerated legacy tree.+7. Immutable topic ids. Automatic topic creation needs recurrence across sessions. Undo is a synced human record.+8. The new entity owns the word `topic` in code. The preference slug becomes `rule_topic`.++Owner answers after the round: the owner trusts their own server with the full store, but the product is open source and other users may not. That led to the `shared` and `private` partitions and the documented threat model. The owner also asked for an explicit migration script, which is the `migrate-store` command in `specs/brain-migration`.++Calls the author made on the partner's minor questions:+- Topic pages carry no frontmatter, only one HTML id comment.+- The page set is fixed; only its target folder is configurable.+- During the transition window there are no dual writes after migration, only an import of late legacy files.+- The office prior art's four decision groups are left out of version 1 because they fit engineering topics but not personal matters.++## Open questions++None that change the specs. Tuning values are listed in design.md.++## Process++The author ran a discussion with the owner, a storage research pass (GitHub API, crates.io and web search, 2026-11-06) and a code inventory. Partner: an independent agent from another model family, one read-only round (the usual partner was out of quota).diff --git a/openspec/changes/brain-store-and-topics/design.md b/openspec/changes/brain-store-and-topics/design.mdnew file mode 100644index 00000000..8052418c--- /dev/null+++ b/openspec/changes/brain-store-and-topics/design.md@@ -0,0 +1,285 @@+# 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.ts` already 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.md` is written read-modify-write with no lock.+ - Preferences are Markdown files under per-file locks.+- **Index.** `brain.sqlite` can 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 `.base` files and by wikilinks used as record identifiers. Note tools (`brain_create_note` and related) already refuse `Brain/` paths.+- **Outside readers.** Skills (`skills/brain-memory`, `skills/open-second-brain` and the `plugins/codex` mirrors), the MCP instruction segments, hook messages and the MCP resources `osb://log/{date}`, `osb://preference/{id}` and `osb://topic/{slug}` hard-code `Brain/` 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 `private` partition) 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.+- **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:+1. 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.+2. A `records` table (id, stream, kind, scope, topic, hlc, device, agent) beside the existing documents and chunks.+3. 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 --here` moves the role in two steps:+ 1. It records a `view-writer-request`.+ 2. The current writer sees it at its next catch-up, finishes any render in progress, and records `view-writer-released`.+ 3. The new device renders only after it has caught up on that release record.+- `--force` skips 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:**++1. Catch up.+2. For every page, compare the file on disk with the checksum in the last render record.+3. 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.+4. Render to a temporary file and check the page checksum once more right before the rename; if it changed, go back to step 3.+5. 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-goal`+- `decision`, `open-question`, `question-resolved`+- `log-entry`, `milestone`, `milestone-done`+- `assign`, `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 `topic` in code, the CLI and MCP.+- The existing preference slug becomes `ruleTopic` / `rule_topic` in code; the persisted `topic` field on signals keeps its name for compatibility and is read as `rule_topic`.+- The resource `osb://topic/{slug}` becomes `osb://rule-topic/{slug}`. The old name is kept as an alias for one minor version, and the new `osb://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. Each is recorded as a human record.++### 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 `private` records 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:++1. **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.+2. **Quiesce this machine** through a device-local migration gate, not the synced fleet freeze marker (`freeze-marker.ts` is 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.+3. **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_SURFACES` marks 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.+4. **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.+5. **Convert.**+ - Signals become `events` records, using their original `created_at` as 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.+6. **Final delta pass.** Re-scan every source and import whatever changed or grew since its journal row. Repeat until a pass imports nothing.+7. **Verify** every journal row against the store.+8. **Render the minimal human view** (see D13 phase 2).+9. **Switch.** Record `migration-done` in the shared partition, carrying the per-partition cut of what was imported. Lift the freeze; writers now use the store only.+10. **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-done` or `device-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-done` cut 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):+1. Freeze this machine.+2. Restore the snapshot and the explicit backups.+3. 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.+4. Record kinds with no legacy form (topics, view renders, digests) stay in the store and are listed in the report.+5. Switch config back to the legacy layout and lift the freeze.++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:++1. **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.+2. **Migration, the vault-free mode and the minimal human view:** the view writer, the render protocol and the pages `about-me.md`, `history/` and `decisions.md`, so the preferences that leave the vault have a readable replacement on the same day.+3. **Topics, plus reports and sources pages.**+4. **Decision-model uses and agent-context budgets.**++## 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_readable` use has shadow data.diff --git a/openspec/changes/brain-store-and-topics/proposal.md b/openspec/changes/brain-store-and-topics/proposal.mdnew file mode 100644index 00000000..817dbeb2--- /dev/null+++ b/openspec/changes/brain-store-and-topics/proposal.md@@ -0,0 +1,45 @@+# Proposal: brain store outside the vault, human view and topics++## Why++Open Second Brain keeps all of its machine data inside the user's Obsidian vault. On a real install this is about 7.7k of the roughly 8.3k files Obsidian sees, plus about 2 GB of hidden snapshots and ledgers that file sync still ships to every device, phones included. Obsidian mobile chokes while indexing them. The data a person actually reads is a small fraction of that, and a lot of the rest is machine state that only looks readable because it is Markdown. The product also assumes Obsidian is installed, which it should not.++The original values stay: the user owns the data in an open, documented format that is readable without the tool; any agent runtime can take part; evidence is append-only and recoverable; one brain is shared by several machines.++## What Changes++- **New brain store outside the vault.** All machine data (signals, event log, ledgers, metrics, payloads, archives, captures, session continuity) moves to a store directory of its own, configurable, synced as a separate file-sync folder between the user's working machines (workstations, laptops, servers) and never to a phone.+- **One writer device per file.** Streams are append-only JSONL files per partition, stream, device and month (`<partition>/<stream>/<device>/<YYYY-MM>.jsonl`); agents on one device share its file. Records carry a hybrid logical clock and a checksum, mutable entities are folds (human beats agent beats model, then later clock), and machines publish state digests so divergence is detected. File sync cannot create conflict copies, and every machine converges on the same state.+- **Any sync tool, or none.** The store works on a single machine, offline, and over any whole-file sync tool; no server is required.+- **Sensitivity partitions.** Records live in `shared` and `private` partitions, so a user can keep personal material off a server or a work laptop.+- **Local derived index per machine.** The SQLite index (full text, embeddings, rerank inputs) stays per device and is never synced. Before each read it catches up on the new bytes of changed shards; it can always be rebuilt from the store.+- **Human view.** A small set of generated, human-readable Markdown pages (what the brain knows about the user, weekly history, decisions, reports, topics) is written to a configurable folder. That folder can be the Obsidian vault, any Markdown folder, or nothing.+- **Topics.** A new user-facing unit with an immutable id: a folder per initiative, project, sub-project or personal matter, with a fixed readable `topic.md` (status, goal, milestones, decisions, open questions, log, related). The dream pass groups related material into topics automatically (recurring across sessions, undoable), and the user can create, move and close topics on request. Agents never edit `topic.md` directly: they record topic events, and one view writer device, named by a shared setting and moved only by the user, renders pages as a pure function of the records. User edits to the page are merged back as human events and always win.+- **Context economy for many concurrent agents.** At session start an agent gets only the heads of the active topics of its project plus its budgeted rules. Detail is pulled on demand. Fresh events from other agents on the same topic or project are surfaced only when they matter to the current task.+- **Optional decision models.** New decision-model uses (route an event to a topic, classify an event kind, human-readable or machine, new-topic and same-topic verdicts, question resolved, milestone looks done, which topic heads to inject, which neighbour events matter) plug into the existing `off`/`shadow`/`enforce` framework. They are off by default, and the deterministic result stays canonical. A verdict is recorded in the event once, never recomputed per machine.+- **Obsidian becomes optional.** Without a vault the store and the index work on their own. Obsidian-only features (Bases, wikilink audits of the user's notes) become a vault adapter that is active only when a vault is configured.+- **Migration script.** One idempotent, resumable command (`o2b brain migrate-store`) converts an existing brain into the store: dry run, snapshot first, per-item journal, verified checksums, rollback, and import of late legacy files from machines not yet upgraded during a transition window. Skills and plugins stop hard-coding `Brain/` paths and ask the CLI for the store location.+- **Defects fixed on the way.** The prompt context cache that is never pruned, upgrade snapshots that bypass retention, the log append that rewrites the whole day file per event, and unlocked `pinned.md` writes. **BREAKING** for anything that reads `<vault>/Brain/**` directly. The CLI, MCP and skills keep their contracts.++## Capabilities++### New Capabilities++- `brain-store`: the machine-data store outside the vault. Layout, one-writer shards, record envelope, ordering, convergence across machines, retention and compaction, snapshots and rollback.+- `brain-index`: the per-device derived index. Catch-up from shards, rebuild, freshness guarantees for reads, never synced.+- `human-view`: generated human-readable pages and where they are written. Works with an Obsidian vault, a plain Markdown folder or no view at all.+- `topics`: user-facing topics. Lifecycle, page schema, topic events, automatic and requested grouping, rendering by the view writer, human edits merged back.+- `agent-context`: what an agent receives at session start and per turn across many concurrent agents and machines. Topic heads, on-demand detail, neighbour updates, budgets.+- `brain-migration`: moving an existing in-vault `Brain/` into the store and the human view, with dry run, snapshot, verification and a transition window.++### Modified Capabilities++None. The repository has no OpenSpec specs yet. Existing behaviour lives in `docs/` and is updated as part of this change.++## Impact++- **Code:** `src/core/brain/path-constants.ts` and `paths.ts` (store root separate from the vault), every writer of `Brain/**` (signals, log, ledgers, captures, payloads), the index build and search (`src/cli/search`), the dream pass (topic planning on the view writer), snapshots and rollback, doctor and health, the MCP read and write tools, the decision-model uses and thresholds, and the session-start and prompt hooks.+- **Config:** new keys for the store root, the human-view target and the topic decision-model uses; the view writer and thresholds are shared settings records, not config keys. `vault` becomes optional.+- **Integrations:** the Hermes, Codex, Claude Code and OpenClaw plugins, the skills and `plugins/codex` mirrors, and any user scripts reading `<vault>/Brain/**`.+- **Sync setup:** users add one file-sync folder for the store and stop syncing `Brain/` machine data to phones. The docs gain a setup and migration guide.+- **Dependencies:** none new. Bun's SQLite and the existing embedding and decision-model providers are reused.diff --git a/openspec/changes/brain-store-and-topics/review.md b/openspec/changes/brain-store-and-topics/review.mdnew file mode 100644index 00000000..b0c97ce9--- /dev/null+++ b/openspec/changes/brain-store-and-topics/review.md@@ -0,0 +1,68 @@+# Independent review++## Reviewer++Two independent agents that did not write the artifacts, each read-only over the repository:+- the usual reviewer, on a second account;+- an agent from another model family.++Round 1 below. Round 2 is a re-review of the fixed artifacts by the usual reviewer.++## Findings++Reviewer A is the usual reviewer, reviewer B the other-family agent.++### Blockers and majors++1. design D7 (A, blocker): a lease carried by delayed file sync cannot guarantee a single renderer. Fixed: one view writer named by a shared human settings record, moved only by the user, pages stale while it is offline (design D7, specs human-view and topics).+2. design D7 (A, blocker): a render checksum does not keep the merge base, and a phone edit can race a render. Fixed: the last rendered text is stored as a blob, edits are detected before rendering, the page is re-checked before the rename, and the sync-conflict copy of a page is ingested as a human edit.+3. design D11 (A, blocker): migration did not stop legacy writers, so late writes could be lost. Fixed: this machine is quiesced through the freeze marker, the journal is per line, a final delta pass runs, and late legacy writes from other machines are imported until the legacy tree leaves the vault.+4. design D11 (A, blocker; B, major): a later machine would skip its own unsynced legacy records, and a `migration-done` record could arrive before its data. Fixed: a later machine waits for the completion cut, then imports its own missing records by checksum.+5. design and spec rollback (A, blocker; B, major): rollback lost post-migration records. Fixed: rollback replays them into the legacy layout through exporters; kinds with no legacy form are reported.+6. design D13 (A, blocker; B, major): phase 2 needed the renderer that ships in phase 3. Fixed: the view writer, the render protocol and the minimal pages move to phase 2.+7. spec brain-migration (B, major): the mixed-version window could empty the brain of an old machine. Fixed: the legacy tree leaves the vault only after every roster device has switched or been retired, or on `--force` with a report.+8. design D6 (A, major; B, major): the digest watermark had no membership rule and stalled on offline devices. Fixed: per-partition digests over explicit cuts, compared only when the cuts are identical, with a roster of 30 days minus retired devices.+9. design D3 (A, major): the HLC lacked the receive rule. Fixed: every catch-up raises the local clock, with a slow-clock reply scenario and test.+10. design D5 (A, major): size and mtime miss a same-size replacement, and catch-up had no cost bound. Fixed: file identity plus a verified-prefix hash, reset on replacement, and a benchmark of under 20 ms for 500 unchanged shards.+11. design D11 (A, major): the snapshot path excludes secrets and other per-vault state. Fixed: an explicit backup of every non-rebuildable surface, each verified by a test restore.+12. spec brain-store (A, major): the setup rule could sync `private/` to a server. Fixed: `shared/` and `private/` are separate sync folders, the store root is never synced, and a test covers a server holding only `shared/`.+13. tasks 3.x (A, major): concurrent dream runs could create duplicate topics. Fixed: topic planning runs only on the view writer, and a test covers concurrent dream.+14. proposal (B, major): a leftover "gardener device" config key. Fixed.+15. spec human-view (B, major): the lease scenario was unreachable under sync delay. Fixed: the lease was replaced by the view writer.++### Minors++16. spec topics vs design D8 (B, minor): the lists of event kinds disagreed. Fixed: one canonical list in D8, referenced by the spec.+17. spec brain-store compaction (B, minor): file and record tombstones were conflated. Fixed: a `compacted` marker record, with reader behaviour specified.+18. spec brain-store blobs (B, minor): no behaviour defined for a blob that has not arrived. Fixed: the body is shown as pending, filled in on catch-up, and doctor reports blobs still missing after a day.+19. tasks (B, minor): no task covered the background rebuild or the view language. Fixed in tasks 1.8 and 2.9.+20. spec brain-store snapshots (B, minor): "manifest order" was undefined. Fixed: retention orders by the creation time recorded in each manifest.++### Round 2 (usual reviewer, re-review of the fixes)++Resolved as fixed in round 1: 6, 9, 10, 11, 12, 14, 16, 17, 18, 19, 20.++Still open after round 2, and settled by the author:++22. 1 and 15 (blocker): a role move or two simultaneous first claims could overlap writers. Fixed: a move is a request, the old writer records a release, and the new writer renders only after it sees that release. `--force` exists for an unreachable writer, with a warning. Simultaneous claims resolve to the lowest (clock, device), and a fresh writer waits one catch-up before its first render.+23. 2 (blocker): an edit between the last check and the rename could be overwritten, and not every sync tool makes conflict copies. Fixed: the writer keeps the replaced bytes as a blob for 30 days and re-reads the page after the rename; replaced bytes that differ from the base are ingested as a human edit; `o2b view recover` lists versions. The promise is narrowed to "never silently lost; a racing edit may land one render later".+24. 3 (blocker): the fleet freeze marker is shared and does not drain in-flight writes. Fixed: a device-local migration gate (shared lock per write, exclusive for the migration), with a multi-process test.+25. 4 (blocker): a later machine without a partition could wait forever, and checksum-only matching could merge distinct records. Fixed: the wait covers only partitions it holds, and the journal key is (device, path, item or line, checksum).+26. 5 (blocker): rollback missed late remote records and had no order. Fixed: replay every record absent from the restored tree by stable identity, in fold order, idempotently and resumably.+27. 7 (blocker): a dormant device dropped out of the 30-day roster. Fixed: a durable migration cohort with no age limit; removal waits for switch, retire or `--force`.+28. 8 (major): digest records changed their own cut. Fixed: the `digests` stream is excluded from cuts, with a test for two publishers converging on one cut.+29. 13 (major): two dream processes on the writer could create the same topic. Fixed: topic planning runs under a device-local exclusive lock, with a two-process test.+30. tasks (major): verification gaps for the above. Fixed in tasks 1.7, 2.3, 2.5, 2.6, 2.7, 2.8 and 3.4.++The schema allows at most one re-review round, so these fixes were not reviewed again.++## Questions for the owner++Answered by the owner on 2026-11-06:+31. A role move waits for the old writer's release by default, and `--force` is available. Yes.+32. A device stays in the migration cohort until it switches or is retired, even after months offline. Yes.+33. "An edit is never silently lost; one that races a render may appear one render later" is accepted.++## Verdict++Ready for implementation: yes.diff --git a/openspec/changes/brain-store-and-topics/specs/agent-context/spec.md b/openspec/changes/brain-store-and-topics/specs/agent-context/spec.mdnew file mode 100644index 00000000..1e1c42af--- /dev/null+++ b/openspec/changes/brain-store-and-topics/specs/agent-context/spec.md@@ -0,0 +1,46 @@+# Spec Delta++## Purpose++Agent context decides what each of many concurrent agents on many machines receives from the brain, so every agent can reach what the others saved quickly while its context window holds only what its current task needs.++## ADDED Requirements++### Requirement: Session start digest+At session start an agent SHALL receive, within a configured token budget: the heads of the active topics of its project scope (title, one-line description, status, goal), its applicable rules, and pinned context. It SHALL NOT receive topic bodies, raw records or other projects' topics.++#### Scenario: Agent starts in a project with many topics+- **WHEN** an agent starts in project P that has 30 active topics and the budget fits 12 heads+- **THEN** it receives at most 12 heads, chosen by relevance to the session, plus a line saying how many more exist and how to list them++### Requirement: Detail on demand+An agent SHALL be able to fetch a topic's full page, its recent events, or a search over its records through the existing tool surface, without loading other topics.++#### Scenario: Agent opens one topic+- **WHEN** an agent asks for topic T's details+- **THEN** it receives T's page and recent events only++### Requirement: Neighbour updates+Before a turn, an agent SHALL receive new records written by other agents since its last turn on the same topic or project only when they pass a relevance check against the current task, within a small token budget. Records it wrote itself SHALL never be returned.++#### Scenario: Another agent changed a shared decision+- **WHEN** an agent on another machine records a decision on the topic this agent works on+- **THEN** this agent's next turn includes a one-line notice of that decision with a pointer to fetch it++#### Scenario: Unrelated neighbour activity+- **WHEN** other agents record routine progress on unrelated topics in the same project+- **THEN** nothing is injected into this agent's turn++### Requirement: Freshness bound+Records from another machine SHALL be visible to an agent's reads as soon as file sync has delivered them, with no extra delay added by Open Second Brain beyond one index catch-up.++#### Scenario: Visible after sync+- **WHEN** a record from machine B has been delivered to machine A+- **THEN** the next read by any agent on A includes it++### Requirement: Budgets are enforced and reported+Every injection SHALL respect its token budget and SHALL report when content was cut, naming what was left out and how to get it.++#### Scenario: Budget exceeded+- **WHEN** the selected heads and rules exceed the session start budget+- **THEN** the lowest-ranked items are dropped, and the digest ends with a line naming how many were dropped and the command to list themdiff --git a/openspec/changes/brain-store-and-topics/specs/brain-index/spec.md b/openspec/changes/brain-store-and-topics/specs/brain-index/spec.mdnew file mode 100644index 00000000..3e1801d1--- /dev/null+++ b/openspec/changes/brain-store-and-topics/specs/brain-index/spec.md@@ -0,0 +1,57 @@+# Spec Delta++## Purpose++The brain index gives every machine fast local search and reads over the brain store, and over the user's notes when a vault is configured, as a derived per-device cache that can always be rebuilt and is never synced.++## ADDED Requirements++### Requirement: Derived and device-local+The index SHALL be built only from the store and, when configured, the vault. It SHALL live in device-local state and SHALL NOT be synced. Deleting it SHALL lose no information.++#### Scenario: Index deleted+- **WHEN** the index file is deleted and a search runs+- **THEN** the index is rebuilt from the store and the vault, and the search returns the same results as before++### Requirement: Catch-up before reads+Before answering a read, the index SHALL ingest every record appended to store files since its last watermark for each file. When nothing changed, the check SHALL cost one metadata lookup per stream file and no file reads. A shard whose file identity changed, that shrank, or whose verified prefix no longer matches SHALL be re-read from the start, and the re-read SHALL be idempotent.++#### Scenario: Record from another machine+- **WHEN** a record from machine B arrives by file sync and an agent on machine A searches right after+- **THEN** the search on A includes B's record without a manual reindex++#### Scenario: Same-size replacement+- **WHEN** a shard file is replaced by a different file of the same size+- **THEN** the next catch-up detects the new identity, re-reads it, and the index holds each record once++#### Scenario: Nothing changed+- **WHEN** no store file changed since the last read+- **THEN** the read opens no store file++### Requirement: Cheap change probe+The index SHALL expose a "what is new since watermark W" query that returns new record ids by stream, scope and topic, so agents and hooks can poll without running a search.++#### Scenario: Probe after a neighbour's write+- **WHEN** another agent records a decision on topic T after watermark W+- **THEN** the probe for W returns that record id under topic T++### Requirement: Rebuild on format change+When the record format version, the index schema or the chunker changes, the index SHALL rebuild in the background into a new file and swap it in only when complete. Reads during the rebuild SHALL use the old index.++#### Scenario: Upgrade with a new schema+- **WHEN** a new release raises the index schema version+- **THEN** reads keep working on the old index while the new one builds, and the swap happens without a failed read++### Requirement: Unknown record versions+A record whose format version is newer than the reader understands SHALL be skipped and reported by doctor. It SHALL NOT stop the rest of the file from being indexed.++#### Scenario: Older binary meets newer records+- **WHEN** a machine running an older release reads a record with a higher version+- **THEN** that record is skipped, the rest are indexed, and doctor tells the user to upgrade that machine++### Requirement: Search covers brain and notes separately+Search SHALL distinguish brain records from user notes, and SHALL let a caller limit a query to either. Brain records SHALL never be indexed as if they were user notes.++#### Scenario: Notes only+- **WHEN** a user asks for notes about a subject+- **THEN** the results contain user notes only, with no signals, log events or preferencesdiff --git a/openspec/changes/brain-store-and-topics/specs/brain-migration/spec.md b/openspec/changes/brain-store-and-topics/specs/brain-migration/spec.mdnew file mode 100644index 00000000..2e525cc8--- /dev/null+++ b/openspec/changes/brain-store-and-topics/specs/brain-migration/spec.md@@ -0,0 +1,104 @@+# Spec Delta++## Purpose++Brain migration moves an existing install whose machine data lives in `<vault>/Brain/` into the brain store and the human view, safely for every user of the public product, without losing evidence and without breaking agents mid-transition.++## ADDED Requirements++### Requirement: One migration command+The product SHALL ship one migration command that converts an existing legacy brain (every `Brain/` lane and the per-vault state under `.open-second-brain/`) into the brain store and the human view. The command SHALL be idempotent and resumable: re-running it after an interruption SHALL continue where it stopped and SHALL never duplicate records. An upgrade SHALL offer it but SHALL NOT run it without the user's consent.++#### Scenario: Interrupted migration+- **WHEN** the migration is killed halfway and run again+- **THEN** it continues from the last verified item, and the store holds every legacy record exactly once++#### Scenario: Upgrade on a legacy install+- **WHEN** a user upgrades to the release on a legacy layout+- **THEN** status and doctor say a migration is available and name the command, and nothing moves until the user runs it++### Requirement: Dry run first+The migration command SHALL support a dry run that writes nothing and reports, per source path, how many items would move, to which stream or view page, and which items it cannot map.++#### Scenario: Dry run on a live install+- **WHEN** the user runs the migration with the dry-run flag+- **THEN** no file changes anywhere, and the report lists counts per source and every unmapped item++### Requirement: Quiesce and back up before moving+A real migration SHALL first stop this machine's legacy writers through a device-local gate that drains in-flight writes, then snapshot the `Brain/` tree and back up every non-rebuildable per-vault surface (secrets, keys, attestations, checkpoints) explicitly, verify each backup by a test restore, and SHALL refuse to start if any step fails. Writes attempted on this machine during the migration SHALL be refused with a message saying a migration is in progress.++#### Scenario: Agent writes during migration+- **WHEN** an agent on the migrating machine records feedback mid-migration+- **THEN** the call is refused with a migration-in-progress message and nothing is written to the legacy tree++#### Scenario: Snapshot fails+- **WHEN** the snapshot cannot be written because the disk is full+- **THEN** the migration stops before moving anything and says why++### Requirement: Verified counts+After converting, the migration SHALL re-scan every source and import whatever changed or grew since it was journaled, repeating until a pass imports nothing. It SHALL then verify that every source record exists in the store with the same content checksum, and SHALL report the counts.++#### Scenario: Verification mismatch+- **WHEN** one signal fails to appear in the store+- **THEN** the old tree is left in place, and the report names the missing item++### Requirement: Machine-data removal from the vault+After the legacy tree leaves the vault, the vault SHALL contain no Open Second Brain machine data; only the human view, if targeted there, SHALL remain. The legacy tree SHALL be archived to device-local state and never deleted automatically.++#### Scenario: Archived, not deleted+- **WHEN** the legacy tree leaves the vault+- **THEN** a dated copy exists in device-local state and nothing was deleted++### Requirement: Removal waits for the migration cohort+The legacy tree SHALL leave the vault only when every device in the durable migration cohort (every device id found in the legacy tree, with no age limit) has switched or been retired, or when the user forces it with a report naming the devices that will stop receiving data.++#### Scenario: All machines switched+- **WHEN** every roster device has switched and the view target is inside the vault+- **THEN** the vault holds the view folder and the user's own notes, and no other Open Second Brain file++#### Scenario: One machine still on the old release+- **WHEN** machine B has not upgraded yet+- **THEN** the legacy tree stays in the vault, B keeps working on it, and doctor on upgraded machines names B as still on the legacy layout++### Requirement: Machines migrate independently+Each machine SHALL switch to the store when the user runs the migration on it. A later machine SHALL wait until its copy of the store holds every record named in the first machine's completion record, then import its own legacy records that the store lacks (matched by checksum), move its own device-local state and record that it switched.++#### Scenario: Second machine holds records the first never saw+- **WHEN** machine B migrates after A, and B's legacy tree holds signals that never synced to A+- **THEN** B imports exactly those signals, the store holds every record once, and B records that it switched++#### Scenario: Completion record arrives before its data+- **WHEN** B receives A's completion record before the store files it names+- **THEN** B's migration waits and reports what it is waiting for, and proceeds once the files arrive++### Requirement: Transition reads+Until the legacy tree leaves the vault, a switched machine SHALL import new or grown legacy records written by machines not yet switched, line by line, exactly once. It SHALL never write into the legacy tree.++#### Scenario: Old machine keeps writing+- **WHEN** a not-yet-upgraded machine writes a signal into the legacy `Brain/inbox/`+- **THEN** an upgraded machine imports it into the store once, and doctor reports the old machine's device id as still on the legacy layout++### Requirement: Legacy tree regeneration is detected+Doctor SHALL report when a legacy `Brain/` machine directory reappears in the vault after migration, and SHALL name the writer when the file carries one.++#### Scenario: Agent follows stale instructions+- **WHEN** an agent creates `Brain/preferences/` in the vault after migration+- **THEN** doctor reports the directory and the agent name found in it++### Requirement: Path discovery for outside readers+The CLI and MCP server SHALL expose the current store root and view target, so skills, hooks and plugins resolve paths by asking instead of hard-coding them. Shipped skills SHALL refer only to tools and these commands, never to store file paths.++#### Scenario: Plugin asks for the store path+- **WHEN** a plugin runs the store path command+- **THEN** it receives the absolute store root and view target for the current config++### Requirement: Rollback+The user SHALL be able to roll a machine back to the legacy layout until the legacy tree leaves the vault. Rollback SHALL restore the snapshot and backups, then replay into the legacy layout, in fold order and idempotently, every store record whose identity is absent from the restored tree, including remote records delivered after the snapshot. Record kinds with no legacy form SHALL stay in the store and SHALL be listed in the report.++#### Scenario: Rollback after a bad migration+- **WHEN** the user rolls back a machine on which agents recorded feedback and notes after the switch+- **THEN** the legacy tree holds the pre-migration state plus those new records, and the machine runs on the legacy layout again++#### Scenario: Records with no legacy form+- **WHEN** topics were created after the switch and the user rolls back+- **THEN** the topics stay in the store, and the rollback report lists themdiff --git a/openspec/changes/brain-store-and-topics/specs/brain-store/spec.md b/openspec/changes/brain-store-and-topics/specs/brain-store/spec.mdnew file mode 100644index 00000000..92dfd8bf--- /dev/null+++ b/openspec/changes/brain-store-and-topics/specs/brain-store/spec.md@@ -0,0 +1,155 @@+# Spec Delta++## Purpose++The brain store holds every piece of Open Second Brain machine data outside the user's notes, in an open documented format that several machines and many concurrent agents can write without conflicts and that converges to the same state everywhere.++## ADDED Requirements++### Requirement: Store location independent of the vault+The store SHALL live at a configurable root directory that is not inside a configured vault. When no root is configured, a per-user default data directory SHALL be used. A configured root inside the vault SHALL be refused, and doctor SHALL name the cause.++#### Scenario: Default root+- **WHEN** Open Second Brain starts with no store root configured+- **THEN** it uses the per-user default data directory and reports it in status++#### Scenario: Root inside the vault+- **WHEN** the store root is configured to a path inside the vault+- **THEN** every write refuses with an error naming the setting, and doctor reports the same++### Requirement: Store works without a vault+Every memory operation (feedback, evidence, notes to the log, pinned context, search over brain records, dream, briefs) SHALL work when no vault is configured.++#### Scenario: No vault configured+- **WHEN** an agent records feedback and later searches for it on a machine with no vault configured+- **THEN** both calls succeed and the search returns the record++### Requirement: One writer device per stream file+Stream records SHALL be appended to files named by partition, stream, device and month (`<partition>/<stream>/<device>/<YYYY-MM>.jsonl`). A device SHALL write only files that carry its own device id. Concurrent agents on one device SHALL append to the same device file.++#### Scenario: Two machines write at once+- **WHEN** agents on machines A and B each record feedback within the same second+- **THEN** A's record is in a file named with A's device id and B's in one named with B's, and file sync creates no conflict copy++#### Scenario: Two agents on one machine+- **WHEN** two agent processes on one device append records concurrently+- **THEN** both records are present, each as one complete line, in that device's file++### Requirement: Record envelope+Every stream record SHALL carry a format version, a unique id, a hybrid logical clock stamp, the device id, the agent identity, the record kind and a content checksum. The envelope SHALL be documented in a public format document shipped with the product.++#### Scenario: Record shape+- **WHEN** any record is written+- **THEN** the line parses as JSON with the fields `v`, `id`, `hlc`, `device`, `agent`, `kind`, `sum` and a kind-specific body, and the checksum verifies++### Requirement: Torn and unverified lines+A reader SHALL skip a trailing line that is incomplete or fails its checksum, and SHALL read it again on a later pass. It SHALL NOT treat the line as deleted. A middle line that fails verification SHALL be reported by doctor.++#### Scenario: Half-synced last line+- **WHEN** a shard arrives by file sync with its last line cut mid-record+- **THEN** reads return every complete record before it, and after the rest arrives the next read returns the completed record++### Requirement: Deterministic order and fold+All machines SHALL order records by hybrid logical clock, then device id, then record id. Every catch-up SHALL raise the local clock to the largest clock ingested, so a record written in reply to a remote record orders after it. Reading the same set of records in any delivery order SHALL produce the same folded state.++#### Scenario: Different delivery order+- **WHEN** machine A receives B's shard before C's and machine D receives C's before B's+- **THEN** after both have all three shards, A and D compute the same folded state++#### Scenario: Reply from a machine with a slow clock+- **WHEN** machine B, whose wall clock is two minutes behind, records a correction to a decision it received from machine A+- **THEN** every machine folds the correction after A's decision++#### Scenario: Duplicate delivery+- **WHEN** the same record arrives twice, for example after a file was restored+- **THEN** the fold applies it once++### Requirement: Mutable entities resolve by authority then time+Entities that change over time (preferences, pinned context, topic fields, assignments) SHALL be folded from their records. A human record SHALL beat an agent record, which SHALL beat a decision-model record. Within one authority, the later clock SHALL win. Removal SHALL be a tombstone record; nothing SHALL be physically deleted by a fold.++#### Scenario: Concurrent edits to pinned context+- **WHEN** agents on two machines replace pinned context at nearly the same time+- **THEN** every machine shows the replacement with the later clock, and the other remains in the history++#### Scenario: Human beats a later agent edit+- **WHEN** the user retires a preference and an agent later records evidence that would confirm it+- **THEN** the preference stays retired and the evidence is kept in its history++### Requirement: Large bodies as content-addressed blobs+Bodies too large for a stream line (reports, source summaries, distillations, payloads, archived source text) SHALL be stored as immutable files named by their content hash and referenced from a record. A blob SHALL never be rewritten.++#### Scenario: Blob not yet arrived+- **WHEN** a record arrives that references a blob file not yet delivered+- **THEN** reads show the record with its body marked pending, the next catch-up fills it in, and doctor reports blobs still missing after a day++#### Scenario: Report stored+- **WHEN** an agent saves a research report+- **THEN** its text is in a blob named by its hash, a record references the blob, and the human view shows the report after the next render++### Requirement: State digest across machines+Each machine SHALL publish, per partition, a digest of each fold together with the exact cut of records it covers, excluding digest records from the cut. Doctor SHALL compare only digests with identical cuts and SHALL report a mismatch. The roster SHALL be the devices with records in the last 30 days minus retired devices.++#### Scenario: Offline device does not stall checks+- **WHEN** one laptop has been offline for two weeks+- **THEN** the other machines keep comparing digests among themselves, and doctor reports the laptop as silent, not as divergent++#### Scenario: Divergence detected+- **WHEN** a fold bug makes machine A's preference state differ from machine B's for the same records+- **THEN** doctor on either machine reports the divergence with both device ids and the stream++### Requirement: Device-local state stays local+Locks, caches, leases on local resources, hook state, the derived index and snapshots SHALL live in a device-local directory that is not part of the synced store. The setup guide SHALL list the `shared` and `private` partition folders as separate sync folders and SHALL say never to sync the store root or the device-local directory as a whole.++#### Scenario: Cache never syncs+- **WHEN** the store folder is synced to another machine+- **THEN** no lock, cache, index or snapshot file of the first machine appears on the second++### Requirement: Bounded growth+Caches SHALL be pruned by age or count. Stream files of closed months SHALL never be rewritten except by compaction on their owning device, which SHALL write the same records to a new file, then a `compacted` record naming the old and new files, then remove the old file. Readers SHALL treat a shard named in a `compacted` record as replaced and SHALL not report its disappearance.++#### Scenario: Prompt cache does not grow without bound+- **WHEN** an agent runs thousands of turns over a month+- **THEN** the context-pack cache holds no entries older than its time to live after the next prune++### Requirement: Snapshots per device+Snapshots and rollback SHALL keep working with the store. Snapshots SHALL be device-local and unsynced. Every snapshot reason, upgrades included, SHALL obey the retention limit, and retention SHALL keep the newest recovery points by the creation time recorded in each manifest, not by file mtime.++#### Scenario: Upgrade snapshots are pruned+- **WHEN** more upgrade snapshots exist than the retention count+- **THEN** the oldest ones by manifest order are removed, and the most recent recovery point that rollback needs is kept++### Requirement: Transport agnostic+The store SHALL work on a single machine with no sync, and with any file-sync tool that copies whole files (for example Syncthing, a cloud drive folder or a network share). It SHALL NOT require a server, a specific sync tool or a network connection to write.++#### Scenario: Single machine+- **WHEN** a user runs Open Second Brain on one laptop with no sync configured+- **THEN** every operation works and doctor reports no sync warning++#### Scenario: Offline write+- **WHEN** a laptop with no network records feedback and later reconnects+- **THEN** the record reaches the other machines through the user's sync tool and every machine converges++### Requirement: Sensitivity partitions+The store SHALL keep records in partitions by sensitivity, at least `shared` and `private`, each a separate top-level folder. Records SHALL go to the partition of their visibility, and personal-scope topics SHALL default to `private`. A user SHALL be able to sync each partition to a different set of machines, for example keeping `private` off a server. A machine without a partition SHALL work on the partitions it has and SHALL never move records between them.++#### Scenario: Private partition kept off a server+- **WHEN** a user syncs `shared` to a server but not `private`+- **THEN** agents on the server see shared records and topics only, and personal topics are absent there without errors++#### Scenario: Private record written on a machine without the partition+- **WHEN** an agent on a machine that has no `private` partition records a private item+- **THEN** the write is refused with a message saying this machine does not hold the private partition++### Requirement: Threat model is documented+The product SHALL document what the store contains in plain text, which partitions exist, what leaves the machine through sync and decision models, and that encryption at rest is the user's sync or disk layer's job.++#### Scenario: Docs read before setup+- **WHEN** a user reads the setup guide+- **THEN** it states, per partition, what is stored, where it goes and how to keep it off a given machine++### Requirement: Shared store settings+Settings that every machine must agree on (the view writer, topic thresholds, the view language, decision-model use modes for shared folds) SHALL be stored as records in the store, not in device-local config.++#### Scenario: Setting changed on one machine+- **WHEN** the user changes the topic creation threshold on machine A+- **THEN** machine B applies the new threshold after the record syncsdiff --git a/openspec/changes/brain-store-and-topics/specs/human-view/spec.md b/openspec/changes/brain-store-and-topics/specs/human-view/spec.mdnew file mode 100644index 00000000..f5068299--- /dev/null+++ b/openspec/changes/brain-store-and-topics/specs/human-view/spec.md@@ -0,0 +1,76 @@+# Spec Delta++## Purpose++The human view is the small set of readable Markdown pages a person actually wants from the brain, written to a folder of the user's choice so any Markdown viewer, Obsidian included, can show them on any device without indexing machine data.++## ADDED Requirements++### Requirement: Configurable target+The human view SHALL be written to a configurable folder: a folder inside the vault, any other folder, or none. With no target, the brain SHALL work fully and write no pages.++#### Scenario: No target+- **WHEN** no human-view target is configured+- **THEN** no page is written anywhere, and every brain operation still works++#### Scenario: Vault target+- **WHEN** the target is a folder inside the vault+- **THEN** Obsidian shows the pages, and no other brain file exists in the vault++### Requirement: Fixed page set+The view SHALL contain: a page of what the brain knows about the user (confirmed rules grouped by subject), a weekly history in plain language, decisions, reports and source summaries, and topics. Raw signals, log events, ledgers, metrics, caches and agent context digests SHALL NOT appear in the view.++#### Scenario: Machine data excluded+- **WHEN** the view is rendered on an install with thousands of signals and log events+- **THEN** the view holds pages from the fixed set only, and none of them is a raw signal, log file or ledger++### Requirement: Small and stable file count+The number of files in the view SHALL grow with topics, reports and weeks, not with signals or events. Re-rendering with no new content SHALL change no file.++#### Scenario: Idle render+- **WHEN** the view is rendered twice with no new records in between+- **THEN** no file's bytes or modification time change++### Requirement: Plain Markdown+Pages SHALL be plain Markdown readable in any viewer, without YAML frontmatter and without links that only resolve in Obsidian. Machine identifiers needed to map a page back to the store SHALL sit in one HTML comment line.++#### Scenario: Read in a generic viewer+- **WHEN** a page is opened in a plain Markdown viewer+- **THEN** it renders with no frontmatter block and with working relative links++### Requirement: Language of the view+Generated prose in the view SHALL use the user's configured language. Quoted source text SHALL stay in its original language.++#### Scenario: Russian-speaking user+- **WHEN** the view language is set to Russian+- **THEN** headings and generated summaries are in Russian, and quoted English source lines stay in English++### Requirement: Human edits flow back+An edit the user makes to a view page SHALL be detected by the view writer before it rewrites that page, and recorded in the store as a human record. The last rendered text SHALL be kept in the store as the merge base. Pages that are summaries only (history, the user profile page) SHALL accept edits as corrections that the next render keeps.++#### Scenario: Edit overwritten by a racing render+- **WHEN** a sync tool that makes no conflict copies delivers a phone edit just before the writer renames a new version of that page+- **THEN** the writer finds the replaced bytes differ from its base, records them as a human edit, renders again, and the edit is in the page one render later++#### Scenario: User corrects a rule on the profile page+- **WHEN** the user rewrites a rule's wording on the profile page+- **THEN** the store gains a human record changing that rule, and the next render shows the user's wording++### Requirement: One view writer+Only the view writer device, named by a shared human settings record, SHALL write view pages. The first machine that migrates or initialises the store SHALL become the view writer, and only the user SHALL move the role. A move SHALL take effect only after the old writer records that it released the role, unless the user forces it because the old writer is unreachable. No other code or device SHALL write into the view folder.++#### Scenario: Render on another machine+- **WHEN** a machine that is not the view writer runs dream+- **THEN** it writes no view page, and its report names the view writer++#### Scenario: User moves the role+- **WHEN** the user runs the command to make the current machine the view writer+- **THEN** the previous writer records its release at its next catch-up, this machine starts rendering only after it has seen that release, and no page is written by both++#### Scenario: Forced move+- **WHEN** the old writer is unreachable and the user forces the move+- **THEN** this machine renders at once, the command warns about a possible extra render by the old writer, and the old writer stops at its first catch-up after the change++#### Scenario: Silent view writer+- **WHEN** the view writer has published nothing for 3 days+- **THEN** doctor on every machine reports it and names the command to move the rolediff --git a/openspec/changes/brain-store-and-topics/specs/topics/spec.md b/openspec/changes/brain-store-and-topics/specs/topics/spec.mdnew file mode 100644index 00000000..ad64d727--- /dev/null+++ b/openspec/changes/brain-store-and-topics/specs/topics/spec.md@@ -0,0 +1,123 @@+# Spec Delta++## Purpose++Topics give the user one readable place per area of work (an initiative, a project, a sub-project, a personal matter) where the goal, decisions, open questions and history of that area live, kept current by agents without the user curating every line.++## ADDED Requirements++### Requirement: Topic page+Each topic SHALL be a folder in the human view holding a required `topic.md` and optional companion files. `topic.md` SHALL use a fixed section order: title, one-line description, status, goal, milestones, decisions, open questions, log (newest first), related. Empty optional sections SHALL be omitted.++#### Scenario: New topic page shape+- **WHEN** a topic is created with a title and a goal+- **THEN** its folder contains a `topic.md` with the title, the one-line description, `Status: Active`, the goal and a related section, and no empty optional sections++#### Scenario: Page stays scannable+- **WHEN** a topic has more milestones, decisions or log entries than the page budget allows+- **THEN** the oldest done milestones and log entries move to a companion archive file linked from the related section, and `topic.md` stays within its budget++### Requirement: Topic status lifecycle+A topic SHALL have exactly one status from `Active`, `Waiting`, `Blocked`, `On hold`, `Done` and `Closed`. `Done` SHALL carry a resolved date. A topic with no new event for a configurable quiet period SHALL be offered to the user for a status decision rather than changed automatically.++#### Scenario: Quiet topic+- **WHEN** an `Active` topic has had no event for longer than the quiet period+- **THEN** the next brief or digest asks the user whether to keep it, put it on hold, mark it done or close it, and the status is unchanged until the user answers++### Requirement: Topic events as the write path+Agents SHALL change a topic only by recording topic events in the brain store, from the canonical list in design.md D8 (`topic-create`, `topic-rename`, `topic-status`, `topic-goal`, `decision`, `open-question`, `question-resolved`, `log-entry`, `milestone`, `milestone-done`, `assign`, `unassign`, `merge`, `split`, `link`, `undo`). Agents SHALL NOT write `topic.md` directly.++#### Scenario: Agent records a decision+- **WHEN** an agent records a decision for topic T+- **THEN** a `decision` event naming T is appended to that agent's own shard, and no file in the human view is written by that agent++#### Scenario: Direct page write is refused+- **WHEN** an agent calls a note-writing tool on a path inside a topic folder+- **THEN** the call is refused with a message naming the topic event tool to use instead++### Requirement: Topic pages are rendered by the view writer+A topic page SHALL be rendered as a pure function of the topic's records. Pages SHALL be written only by the view writer device named in the shared settings. While the view writer is offline, pages SHALL stay as they are and no other device SHALL write them.++#### Scenario: Two machines record events for one topic+- **WHEN** agents on two machines record events for topic T before either sees the other's+- **THEN** after both files reach the view writer, it renders one `topic.md` containing both events in clock order, and no sync conflict copy of `topic.md` exists++#### Scenario: View writer offline+- **WHEN** the view-writer laptop is closed for a week+- **THEN** no other machine writes topic pages, agents keep recording topic events, and doctor on the other machines reports the silent writer and the command to move the role++### Requirement: Stable topic identity+Each topic SHALL have an immutable id. The folder name and title SHALL be display values. Renaming a topic SHALL keep its id and every reference to it.++#### Scenario: Rename+- **WHEN** the user renames topic T+- **THEN** its folder and title change, its id stays, and events recorded before the rename still belong to it++### Requirement: Human edits win+A user edit to `topic.md` SHALL be detected by the view writer before every render, merged three ways against the last rendered text (kept in the store), and recorded as a human event in the store before the page is rewritten. A human event SHALL take precedence over any agent or decision-model event that touches the same item.++#### Scenario: User rewrites the goal+- **WHEN** the user edits the goal in `topic.md` and an agent event later proposes a different goal+- **THEN** the rendered page keeps the user's goal, and the agent's proposal appears as an open question attributed to the agent++#### Scenario: User edit on the phone+- **WHEN** the user edits `topic.md` on a phone that only syncs the human view+- **THEN** the view writer records the edit as a human event and the next render keeps it++#### Scenario: Edit races a render+- **WHEN** the phone's edit to `topic.md` arrives while the view writer is rewriting that page+- **THEN** either the pre-rename check catches it, or the resulting sync-conflict copy is ingested as a human edit; in both cases the user's text is in the next render and no copy is left behind++### Requirement: Log entries are earned+Only corrections, decisions made outside the normal flow, blockers, reframings and rejected approaches (with the reason) SHALL produce a log entry on the topic page. Routine progress SHALL stay in the store and SHALL NOT appear on the page.++#### Scenario: Routine progress+- **WHEN** an agent records that it ran the tests and they passed+- **THEN** the event is stored but `topic.md` gains no log entry++### Requirement: Milestone completion needs evidence or the user+A milestone SHALL be marked done only by the user, or by an agent that cites verifiable evidence. A decision-model verdict alone SHALL only propose completion.++#### Scenario: Decision model thinks a milestone is done+- **WHEN** the milestone-done verdict is positive but no agent cited evidence+- **THEN** the page shows the milestone as open with a "looks done, confirm" marker, and the status stays open++### Requirement: Automatic grouping during dream+The topic-planning step of dream SHALL run only on the view writer. It SHALL route unassigned events to existing topics and SHALL create a new topic only when related unassigned events cross a configured threshold and come from at least two sessions. Each automatic create, route or move SHALL be undoable and SHALL be listed in the dream report. An undo SHALL be a synced human record that every machine honours.++#### Scenario: New topic from a cluster+- **WHEN** enough unassigned events about one subject accumulate in one project+- **THEN** dream creates a topic with a drafted title and goal, links the events, lists the creation in its report, and the user can undo it with one command++#### Scenario: Undo an automatic move+- **WHEN** the user undoes an automatic route of event E to topic T+- **THEN** E is unassigned, a human event records the undo, and later dream passes do not route E to T again++### Requirement: Merges and splits are proposed+Merging two topics and splitting one SHALL be proposed to the user and applied only after the user confirms.++#### Scenario: Two machines run dream at once+- **WHEN** dream runs on the view writer and on another machine over the same unassigned events+- **THEN** only the view writer creates topics, and exactly one topic exists for the cluster++#### Scenario: One busy session does not make a topic+- **WHEN** many related events come from a single session+- **THEN** no topic is created until the subject recurs in another session++#### Scenario: Two topics look the same+- **WHEN** the same-topic verdict is positive for topics A and B+- **THEN** the brief proposes the merge, and both topics stay unchanged until the user confirms++### Requirement: Topics on request+The user SHALL be able, through an agent, to create a topic, move material into a topic, rename it, change its status, merge or split topics, and archive a topic. Each request SHALL be recorded as a human event.++#### Scenario: User asks for a topic+- **WHEN** the user says to start a topic for a personal matter with a stated goal+- **THEN** a topic with that goal exists in the human view after the next render, and the request is stored as a human event++### Requirement: Topic scope+A topic SHALL belong to a project scope or to the personal scope. Agents SHALL see the topics of their current project scope by default, and cross-project topics only on request.++#### Scenario: Agent in another project+- **WHEN** an agent works in project P+- **THEN** topic heads from project Q are not injected unless the agent searches for them or the user links the topicsdiff --git a/openspec/changes/brain-store-and-topics/tasks.md b/openspec/changes/brain-store-and-topics/tasks.mdnew file mode 100644index 00000000..eb0f5e74--- /dev/null+++ b/openspec/changes/brain-store-and-topics/tasks.md@@ -0,0 +1,99 @@+# Tasks++Phases follow design.md D13. Each phase ends in its own release PR, and the version bump, CHANGELOG entry and docs ride inside that PR (CLAUDE.md "Versioning"). Tests are written first for every unit of behaviour.++## 1. Phase 1: store core++- [x] 1.1 Write `FORMAT.md`, covering the envelope, streams, partitions, blobs, fold rules, clock rules, compaction markers and versioning, and ship it into every partition. Verify: a doc test checks that every envelope field, stream and record kind named in code appears in the document.+- [x] 1.2 Add store root, partition and device-local directory resolution in `path-constants.ts`, `paths.ts` and config: a per-user default, refusal of a root inside the vault, and the device-local directory from `platform-dirs.ts`. Verify: unit tests for the default, an override, the refusal and Windows paths.+- [x] 1.3 Implement the record envelope, ULID ids and checksums, and the HLC with both its send rule and its receive rule. Verify: unit tests for monotonicity under a backwards wall clock, and a cross-device reply from a machine with a slow clock that folds after the record it answers.+- [x] 1.4 Implement the shard appender: a single append under a device-local lock, a line-size cap and spill into blobs. Verify: a test with concurrent child processes on one device yields N complete lines; the Windows CI job runs the same test.+- [x] 1.5 Implement the shard reader. It skips an incomplete or checksum-failing last line and retries it later, reports bad middle lines, skips unknown `v`, handles `compacted` markers and marks a missing blob as pending. Verify: fixture tests for a cut line, a corrupt line, a future version, a compacted shard and a blob that arrives late.+- [x] 1.6 Implement folds for preferences, pinned context and settings. Precedence is human > agent > model, then the later clock wins; removals are tombstones. Verify: property tests that shuffle shard delivery order and duplicate lines, and assert an identical folded state.+- [x] 1.7 Implement per-partition state digests with explicit cuts, the roster (30 days, minus retired devices) and the doctor comparison. Verify: tests for an injected fold difference (reported), an offline device (reported as silent, not divergent), a machine without the private partition (no false alarm), and two publishers converging on one identical cut.+- [x] 1.8 Move `brain.sqlite` to device-local state. Add the watermark table with file identity and a verified-prefix hash, the `records` table, the source column and catch-up before reads. Verify:+ - a new record is searchable without a reindex;+ - an unchanged store opens no file (fs spy);+ - a same-size replacement and a truncation are re-read once;+ - the catch-up benchmark with 500 unchanged shards stays under 20 ms;+ - a background rebuild after a schema bump keeps reads working and swaps without a failed read.+- [x] 1.9 Add the change probe: the `brain_changes` MCP tool and `o2b brain changes --since`. Verify: a test returns a neighbour's record id under its topic and scope.+- [x] 1.10 Defect fixes that ride along:+ - prune `.state/anticipatory` by TTL;+ - make every snapshot reason, upgrades included, obey retention ordered by the manifest's creation time;+ - lock `pinned.md` writes;+ - replace the full-file rewrite in `log.ts` with appends.++ Verify: a regression test for each, including a retention test where the newest recovery point survives.+- [x] 1.11 Put dual writes (store plus legacy tree) behind a flag that is off by default, and document the flag in `docs/`. Verify: an integration test with the flag on finds each record in both places with matching content.+- [ ] 1.12 Integration. Run the full gate (`bun run test`, `lint`, `typecheck`, `scripts/sync-version.ts --check`, `sync-plugin-mirrors:check`, `check:paths`); it must be green on Linux and in the Windows CI job. Then open the release PR with the version bump and CHANGELOG.++## 2. Phase 2: migration, the vault-free mode and the minimal human view++- [ ] 2.1 Add a mapper for every row of `STATE_SURFACES`: stream, blob, device-local state, an explicit backup (secrets, keys, attestations, checkpoints) or drop. Verify: a test fails when a surface has no mapper.+- [ ] 2.2 Implement `o2b brain migrate-store --dry-run`. Verify: on a fixture vault with real layout shapes and several device ids, the report lists the roster, counts per surface and unmapped items, and the tree hash is unchanged.+- [ ] 2.3 Implement the real migration on the first machine:+ - quiesce through the freeze marker;+ - snapshot, plus explicit backups each verified by a test restore;+ - conversion with a journal per item and per line;+ - the final delta pass;+ - verification;+ - the `migration-done` record with its cut.++ Verify with tests for:+ - a clean run;+ - a kill halfway followed by `--resume` (no duplicates);+ - a write attempted during migration (refused);+ - several writer processes with writes in flight when the migration starts (drained, none lost);+ - two distinct legacy records with identical content (both kept);+ - a legacy file that grows during conversion (imported by the delta pass);+ - a verification mismatch (legacy tree untouched);+ - a backup failure (nothing moved).+- [ ] 2.4 Implement the later-machine path. It waits for the `migration-done` cut, imports its own legacy records the store lacks, moves its device-local state and records `device-switched`. It also imports late legacy writes during the transition, line by line. Verify: two- and three-device fixture tests, including a completion record that arrives before its data and a machine still on the old release that keeps writing.+- [ ] 2.5 Implement removal of the legacy tree, gated on the roster (every device switched or retired, or `--force` with a report), into a dated archive in the device-local state. Verify: tests for gate closed, gate open, `--force`, a cohort device offline for longer than 30 days (gate stays closed), and doctor naming the devices still on the legacy layout.+- [ ] 2.6 Implement `--rollback`: freeze, restore the snapshot and the backups, replay post-switch records into the legacy layout through legacy exporters (signals, log, preferences, pinned context, notes), and report kinds that have no legacy form. Verify: a test that migrates, writes new records, receives a remote pre-switch record late, rolls back, and finds every one of them in the legacy tree once and in fold order; a resumed rollback duplicates nothing.+- [ ] 2.7 Add the view writer: a shared settings record, the first migrating or initialising machine takes the role, `o2b view writer --here`, and a doctor check for a silent writer. Verify: tests for the initial role, two simultaneous first claims (one winner, no pages by the loser), a move with release before sync (no page written by both), a forced move, and the silent-writer report.+- [ ] 2.8 Implement the render protocol. It detects edits against the stored base before rendering, merges three ways with the user winning, re-checks before the rename, ingests the sync-conflict copy of a page, and writes only changed bytes. Verify:+ - an idle render changes no mtime;+ - a phone-style whole-file rewrite becomes human records;+ - a racing edit with no conflict copy is recovered from the replaced bytes;+ - a racing edit with a conflict copy leaves no copy behind;+ - `o2b view recover` lists replaced versions.+- [ ] 2.9 Render the minimal pages `about-me.md`, `history/<YYYY>-W<ww>.md` and `decisions.md`, with the HTML id comment, no frontmatter, and `view.language` for generated prose. Verify: snapshot tests in English and Russian, where quoted source lines stay in the original language.+- [ ] 2.10 Make the store the only write path once migrated, and make the vault optional in config. Generate `.base` files only through the vault adapter. Verify: the whole test suite passes with no vault configured, and `rg 'Brain/' src` lists only legacy-reader, exporter and migration modules.+- [ ] 2.11 Add `o2b store path` and the store fields in `second_brain_status`. Rewrite the skills, the MCP instruction segments, hook messages and templates so they name tools and commands only. Regenerate `plugins/codex` with `bun run sync-plugin-mirrors`. Verify: `sync-plugin-mirrors:check` passes, and a grep test finds no `Brain/` path in shipped skill text.+- [ ] 2.12 Add doctor checks for:+ - a legacy directory reappearing after removal, with the writer when known;+ - another device's id in the local state;+ - an available migration;+ - devices still on the legacy layout.++ Verify: doctor tests for each.+- [ ] 2.13 Write the setup and migration guide in `docs/`. It covers syncing `shared/` and `private/` as separate folders, never the store root or the device-local directory; that phones get only the view; the threat model; and rollback. Verify: the documented commands run as written in a doc test against a fixture, and a test where a server gets only `shared/` works without errors.+- [ ] 2.14 Integration. Run the full gate on Linux and Windows. Then run a manual migration on a copy of a real multi-machine install, which the owner checks: counts, the view, search on two machines and a rollback. Then open the release PR.++## 3. Phase 3: topics, plus reports and sources++- [ ] 3.1 Implement topic records and folds for the canonical event list in design.md D8, with an immutable `topic_id`. Verify: property tests for order independence, and a rename that keeps every reference.+- [ ] 3.2 Render `topics/<date>-<slug>/topic.md` through the phase 2 render protocol, with the fixed section order, the page budget and the companion archive. Also render `reports/` and `sources/`. Verify: snapshot tests, including budget overflow.+- [ ] 3.3 Refuse note-tool writes into the view folder, with a pointer to the topic tools. Verify: a test on `brain_create_note` and `brain_update_note`.+- [ ] 3.4 Add topic planning to dream, run on the view writer only: route unassigned records, create on N records from at least two sessions, propose merges and splits, prompt on quiet topics, write report entries, and support undo as a synced human record. Verify:+ - dream tests for every scenario in `specs/topics/spec.md`;+ - a concurrent dream on two machines, and two dream processes on the view writer, each yield exactly one topic per cluster.+- [ ] 3.5 Add the `brain_topic` MCP tool and the `o2b topic` CLI verbs. Rename the preference-topic internals to `ruleTopic` and the resource to `osb://rule-topic/{slug}`, with an alias for one minor version, and add `osb://topic/{id}`. Verify: MCP contract tests, an alias test and a CHANGELOG note.+- [ ] 3.6 Write the topics guide in docs: what a topic is, the page schema, how to ask an agent, and undo. Verify: a doc test runs the listed CLI verbs.+- [ ] 3.7 Integration. Run the full gate on Linux and Windows. Then the owner checks topics by hand on two machines and in a phone view, including a phone edit. Then open the release PR.++## 4. Phase 4: decision-model uses and agent context++- [ ] 4.1 Register the uses `topic_route`, `event_kind`, `human_readable`, `topic_new`, `topic_same`, `question_resolved`, `milestone_done`, `head_select` and `neighbour_relevant` in the decision-model framework. Each is off by default and has a deterministic fallback. Verdicts are stored with model, version, mode and confidence. A private-data guard blocks hosted providers. Verify: per-use tests for off, shadow (recorded, no effect) and enforce, plus a test that folds never call a model.+- [ ] 4.2 Build the session start digest: topic heads within budget, rules, pinned context and a "more available" line. Verify: hook tests with 30 topics and a 12-head budget.+- [ ] 4.3 Add neighbour updates before a turn, using the change probe, the relevance gate and a small budget, and never echoing the agent's own records. Verify: hook tests for the related and unrelated cases in `specs/agent-context/spec.md`.+- [ ] 4.4 Report budget cuts in every injection. Verify: tests assert the dropped-count line.+- [ ] 4.5 Extend `docs/decision-models.md` with the new uses, their privacy defaults and the shadow-then-enforce path. Verify: a doc test checks that every registered use is documented.+- [ ] 4.6 Integration. Run the full gate on Linux and Windows. Then the owner checks by hand with several concurrent agents on two machines. Then open the release PR.++## Workflow follow-up++- Archive the change only after every phase is released, works end to end and the owner has checked it by hand.+- Verify the archived specs under `openspec/specs/`.diff --git a/openspec/config.yaml b/openspec/config.yamlnew file mode 100644index 00000000..b22e64f3--- /dev/null+++ b/openspec/config.yaml@@ -0,0 +1,32 @@+schema: jeex++# Project context (optional)+# Add only constraints that should guide OpenSpec artifacts and workflows.+# Include constraints an agent cannot infer by reading the code.+# Keep general project documentation and discoverable codebase facts out.+# Example:+# context: |+# Designs and tasks must cover Windows, macOS, and Linux+# Write all artifacts in Spanish++# Per-artifact rules (optional)+# Add custom rules for specific artifacts.+# Example:+# rules:+# proposal:+# - Keep proposals under 500 words+# - Always state what is out of scope+# tasks:+# - Break tasks into chunks of max 2 hours++# Per-operation guidance (optional)+# Add advisory guidance for how apply and archive work should be conducted.+# This is separate from artifact rules above.+# Example:+# operations:+# apply:+# guidance:+# - Keep test summaries concise+# archive:+# guidance:+# - Summarize the archive outcome before finishingdiff --git a/openspec/specs/.gitkeep b/openspec/specs/.gitkeepnew file mode 100644index 00000000..e69de29bdiff --git a/src/cli/brain.ts b/src/cli/brain.tsindex c0dab015..d13b7757 100644--- a/src/cli/brain.ts+++ b/src/cli/brain.ts@@ -110,6 +110,7 @@ import {cmdBrainPayload,cmdBrainReceipts,cmdBrainStorage,+ cmdBrainChanges,cmdBrainSessionSummary,cmdBrainIdeaLineage,cmdBrainNoteHistory,@@ -418,6 +419,8 @@ export async function handleBrainSubcommand(argv: ReadonlyArray<string>): Promisreturn await cmdBrainReceipts(rest);case "storage":return await cmdBrainStorage(rest);+ case "changes":+ return await cmdBrainChanges(rest);case "session-summary":return await cmdBrainSessionSummary(rest);case "idea-lineage":diff --git a/src/cli/brain/upgrade-render.ts b/src/cli/brain/upgrade-render.tsindex b9992d36..c6264497 100644--- a/src/cli/brain/upgrade-render.ts+++ b/src/cli/brain/upgrade-render.ts@@ -6,6 +6,7 @@* calls these after `planUpgrade()` returns.*/+import { describeManualRevisionAhead } from "../../core/brain/templates.ts";import type { UpgradeFilePlan, UpgradePlan } from "../../core/brain/upgrade.ts";import { info, ok } from "../output.ts";@@ -22,6 +23,7 @@ export function renderUpgradePlanJson(plan: UpgradePlan): {before_size: number;after_size: number;error?: string;+ ahead_revision?: number;}>;} {return {@@ -34,12 +36,17 @@ export function renderUpgradePlanJson(plan: UpgradePlan): {before_size: f.before?.length ?? 0,after_size: f.after.length,...(f.error ? { error: f.error } : {}),+ ...(f.aheadRevision !== undefined ? { ahead_revision: f.aheadRevision } : {}),})),};}export function printUpgradePlanText(plan: UpgradePlan): void {for (const f of plan.files) {+ if (f.status === "noop" && f.aheadRevision !== undefined) {+ info(` ${describeManualRevisionAhead(f.path, f.aheadRevision)}`);+ continue;+ }if (f.status === "noop") {ok(` ${f.path}: up to date`);continue;diff --git a/src/cli/brain/verbs/changes.ts b/src/cli/brain/verbs/changes.tsnew file mode 100644index 00000000..bd9584a7--- /dev/null+++ b/src/cli/brain/verbs/changes.ts@@ -0,0 +1,87 @@+/**+ * `o2b brain changes [--since <watermark>]` - the brain store change probe.+ *+ * One builder serves this verb and the `brain_changes` MCP tool+ * (`../../../mcp/brain/changes-tools.ts`); the watermark contract lives in+ * `../../../core/search/brain-store/changes.ts`. The verb prints the new+ * record ids grouped by partition, stream, scope and topic, then the+ * watermark to pass next time. `--json` prints the builder's object as-is.+ *+ * The CLI runs at local reach, so it always gets the measured form.+ */++import {+ CHANGES_DEFAULT_LIMIT,+ CHANGES_MAX_LIMIT,+} from "../../../core/search/brain-store/changes.ts";+import { TRANSPORT_REACH } from "../../../core/graph/transport-reach.ts";+import { buildBrainChanges, type BrainChangesView } from "../../../mcp/brain/changes-tools.ts";+import { CliError } from "../../argparse.ts";+import { brainVerbContext, failWith, parse, writeJson } from "../helpers.ts";++export async function cmdBrainChanges(argv: string[]): Promise<number> {+ const { flags } = parse(argv, {+ vault: { type: "string" },+ since: { type: "string" },+ limit: { type: "string" },+ json: { type: "boolean" },+ });+ const { vault, config } = brainVerbContext(flags);+ const rawLimit = flags["limit"] as string | undefined;+ const limit = parseLimit(rawLimit);+ if (!Number.isInteger(limit) || limit < 1 || limit > CHANGES_MAX_LIMIT) {+ throw new CliError(`--limit must be an integer in 1..${CHANGES_MAX_LIMIT}`);+ }+ const since = flags["since"] as string | undefined;++ let view: BrainChangesView;+ try {+ view = await buildBrainChanges({+ vault,+ reach: TRANSPORT_REACH.local,+ configPath: config,+ ...(since !== undefined ? { since } : {}),+ limit,+ });+ } catch (exc) {+ return failWith("read the brain store changes", exc);+ }++ if (flags["json"]) writeJson(view);+ else renderText(view);+ return 0;+}++/** `--limit` as a number; NaN unless it is plain decimal digits (`Number` takes "1e3", "0x10", " 5 "). */+function parseLimit(raw: string | undefined): number {+ if (raw === undefined) return CHANGES_DEFAULT_LIMIT;+ return /^\d+$/.test(raw) ? Number(raw) : Number.NaN;+}++function label(value: string | null): string {+ return value ?? "-";+}++function renderText(view: BrainChangesView): void {+ if (!view.measured) {+ process.stdout.write(`not measured: ${view.reason} - ${view.detail}\n`);+ return;+ }+ if (!view.storeInUse) {+ process.stdout.write("no brain store is in use on this machine\n");+ return;+ }+ for (const warning of view.warnings) process.stdout.write(`warning: ${warning}\n`);+ if (view.reset) {+ process.stdout.write("the watermark came from a replaced index; listing from the start\n");+ }+ process.stdout.write(`${view.count} new record(s)\n`);+ for (const g of view.groups) {+ const stream = g.ledger === null ? g.stream : `${g.stream}/${g.ledger}`;+ process.stdout.write(+ ` ${g.partition} ${stream} scope=${label(g.scope)} topic=${label(g.topic)}: ${g.ids.join(", ")}\n`,+ );+ }+ if (view.truncated) process.stdout.write("more records are waiting after the watermark\n");+ process.stdout.write(`watermark: ${view.watermark ?? "-"}\n`);+}diff --git a/src/cli/brain/verbs/index.ts b/src/cli/brain/verbs/index.tsindex 0e36d706..e2569093 100644--- a/src/cli/brain/verbs/index.ts+++ b/src/cli/brain/verbs/index.ts@@ -90,6 +90,7 @@ export { cmdBrainSgrep } from "./sgrep.ts";export { cmdBrainContinuity } from "./continuity.ts";export { cmdBrainReceipts } from "./receipts.ts";export { cmdBrainStorage } from "./storage.ts";+export { cmdBrainChanges } from "./changes.ts";export { cmdBrainPayload } from "./payload.ts";export { cmdBrainSessionSummary } from "./session-summary.ts";export { cmdBrainIdeaLineage } from "./idea-lineage.ts";diff --git a/src/cli/brain/verbs/protect.ts b/src/cli/brain/verbs/protect.tsindex 73d55cf9..26005253 100644--- a/src/cli/brain/verbs/protect.ts+++ b/src/cli/brain/verbs/protect.ts@@ -86,23 +86,27 @@ function appendUnprotectReceipt(opts: {result: UnprotectResult;}): void {try {- appendAuditRecord(hookAuditDir(opts.vault), {- timestamp: new Date().toISOString(),- actor: opts.actor,- action: "brain-unprotect",- target: opts.result.destination,- ok: true,- details: {- pid: process.pid,- before_hash: `sha256:${createHash("sha256").update(opts.compute.before).digest("hex")}`,- summary: opts.result.changed- ? `removed OSB-managed rules from ${basename(opts.result.destination)}`- : `nothing OSB-managed to remove for ${opts.result.target}`,- consent: opts.consent,- changed: opts.result.changed,- ...(opts.result.backupPath ? { backup: opts.result.backupPath } : {}),+ appendAuditRecord(+ hookAuditDir(opts.vault),+ {+ timestamp: new Date().toISOString(),+ actor: opts.actor,+ action: "brain-unprotect",+ target: opts.result.destination,+ ok: true,+ details: {+ pid: process.pid,+ before_hash: `sha256:${createHash("sha256").update(opts.compute.before).digest("hex")}`,+ summary: opts.result.changed+ ? `removed OSB-managed rules from ${basename(opts.result.destination)}`+ : `nothing OSB-managed to remove for ${opts.result.target}`,+ consent: opts.consent,+ changed: opts.result.changed,+ ...(opts.result.backupPath ? { backup: opts.result.backupPath } : {}),+ },},- });+ opts.vault,+ );} catch {/* evidence, not the guard */}diff --git a/src/cli/brain/verbs/snapshot.ts b/src/cli/brain/verbs/snapshot.tsindex 72d55e44..e0a0cc19 100644--- a/src/cli/brain/verbs/snapshot.ts+++ b/src/cli/brain/verbs/snapshot.ts@@ -100,6 +100,16 @@ export async function cmdBrainSnapshotLog(argv: string[]): Promise<number> {if (listing.skipped.length > 0) {process.stderr.write(renderSnapshotListingSkips(listing.skipped) + "\n");}+ // A sidecar stamp that was not believed decides where retention puts the+ // archive, so it is said out loud too.+ for (const s of all) {+ if (s.created_at_untrusted !== undefined) {+ process.stderr.write(+ `warning: ${s.run_id} is ordered by its file time ${s.created_at}: ` ++ `${s.created_at_untrusted}\n`,+ );+ }+ }// The reason filter compares against what the SIDECAR recorded, so a// snapshot whose reason is unknown is never swept into a named bucket by@@ -153,6 +163,10 @@ function renderLogJson(s: SnapshotInfo): Record<string, unknown> {return {run_id: s.run_id,created_at: s.created_at,+ // Present only when the sidecar's stamp was set aside for the mtime.+ ...(s.created_at_untrusted !== undefined+ ? { created_at_untrusted: s.created_at_untrusted }+ : {}),// `null` is UNKNOWN provenance and stays null in the payload: a// consumer must be able to tell an unstamped snapshot from a stamped// one, which a substituted label would hide.diff --git a/src/cli/command-manifest.ts b/src/cli/command-manifest.tsindex 485a06ad..ad6a0d35 100644--- a/src/cli/command-manifest.ts+++ b/src/cli/command-manifest.ts@@ -480,6 +480,16 @@ export const CLI_COMMAND_MANIFEST: CliRootManifest = Object.freeze({"Render the vault storage report: usage per surface and the forecast tier against the cap",[flag("vault", "string"), flag("json", "boolean")],),+ command(+ "changes",+ "List brain store record ids new since a watermark, grouped by stream, scope and topic",+ [+ flag("vault", "string"),+ flag("since", "string"),+ flag("limit", "string"),+ flag("json", "boolean"),+ ],+ ),command("audit", "Render mutation audit trail"),command("generation-reports",@@ -1089,6 +1099,7 @@ export const CLI_COMMAND_MANIFEST: CliRootManifest = Object.freeze({flag("keyword-only", "boolean"),flag("match-mode", "string"),flag("kind", "string"),+ flag("source", "string"),flag("path", "string"),flag("keyword-weight", "string"),flag("semantic-weight", "string"),@@ -1279,6 +1290,18 @@ export const CLI_COMMAND_MANIFEST: CliRootManifest = Object.freeze({),],),+ command(+ "store",+ "Brain store verbs",+ [],+ [+ command(+ "init",+ "Create the brain store (both partitions, or --partitions shared), or complete a half-created one",+ [flag("partitions", "string"), flag("config", "string"), flag("json", "boolean")],+ ),+ ],+ ),command("discipline","Daily logging discipline verbs",diff --git a/src/cli/json-helpers.ts b/src/cli/json-helpers.tsindex de6f86f4..91d7067d 100644--- a/src/cli/json-helpers.ts+++ b/src/cli/json-helpers.ts@@ -52,6 +52,7 @@ export const COMMANDS_WITH_INTERNAL_JSON: ReadonlySet<string> = new Set(["search","vault","state",+ "store","discipline","partner","decision-model",diff --git a/src/cli/main.ts b/src/cli/main.tsindex e7bb8caf..379008d9 100644--- a/src/cli/main.ts+++ b/src/cli/main.ts@@ -54,6 +54,7 @@ import { handlePartnerSubcommand } from "./partner.ts";import { handleSearchSubcommand } from "./search.ts";import { handleDecisionModelSubcommand } from "./decision-model.ts";import { handleStateSubcommand } from "./state.ts";+import { handleStoreSubcommand } from "./store.ts";import { installMcpSignalDrain, type McpSignalDrainHandle } from "./mcp-drain.ts";import { installMcpFaultGuard } from "./mcp-fault-guard.ts";import { handleVaultSubcommand } from "./vault.ts";@@ -1384,6 +1385,8 @@ async function dispatchCommand(command: string, rest: string[]): Promise<number>return await handleSearchSubcommand(rest);case "state":return await handleStateSubcommand(rest);+ case "store":+ return await handleStoreSubcommand(rest);case "vault":return await handleVaultSubcommand(rest);case "partner":diff --git a/src/cli/search/verbs/query.ts b/src/cli/search/verbs/query.tsindex f2334fc0..61f19e1f 100644--- a/src/cli/search/verbs/query.ts+++ b/src/cli/search/verbs/query.ts@@ -33,6 +33,7 @@ import {import { CLI_TRANSPORT_REACH } from "../../transport-reach.ts";import { FTS_MATCH_MODES, isFtsMatchMode } from "../../../core/search/fts-match-mode.ts";import { SEARCH_KINDS, isSearchKind } from "../../../core/search/property-pushdown.ts";+import { SEARCH_SOURCES, isSearchSource } from "../../../core/search/brain-store/constants.ts";import {DISCLOSURE_MODE,DISCLOSURE_MODES,@@ -128,6 +129,11 @@ export async function cmdSearchQuery(argv: ReadonlyArray<string>): Promise<numbethrow new CliError(`--kind must be one of ${SEARCH_KINDS.join(", ")}`);}const kind = kindRaw;+ const sourceRaw = flagString(flags, "source");+ if (sourceRaw !== undefined && !isSearchSource(sourceRaw)) {+ throw new CliError(`--source must be one of ${SEARCH_SOURCES.join(", ")}`);+ }+ const source = sourceRaw;const cfg = resolveConfig(flags);@@ -172,6 +178,7 @@ export async function cmdSearchQuery(argv: ReadonlyArray<string>): Promise<numbekeywordOnly: flagBoolean(flags, "keyword-only"),pathPrefix: flagString(flags, "path"),...(kind !== undefined ? { kind } : {}),+ ...(source !== undefined ? { source } : {}),...(matchMode !== undefined ? { matchMode } : {}),...(properties !== undefined ? { properties } : {}),...(degreeFilters !== undefined ? { degreeFilters } : {}),diff --git a/src/cli/store.ts b/src/cli/store.tsnew file mode 100644index 00000000..95f28c49--- /dev/null+++ b/src/cli/store.ts@@ -0,0 +1,141 @@+/**+ * `o2b store` - verbs on the brain store, the append-only folder outside+ * the vault that Open Second Brain is moving its machine data into.+ *+ * Only `init` exists today. It is the one way a store is created: writers+ * and the index never create one. Run it once on the first machine; every+ * other machine receives the partitions through sync, and a re-run+ * completes a store whose creation stopped half way. The work itself lives+ * in `core/store/store-init.ts`; this file parses flags and renders.+ */++import { ConfigReadError } from "../core/config.ts";+import { STORE_PARTITIONS, type StorePartition } from "../core/store/constants.ts";+import { initStore, StoreInitRefusal, type InitStoreResult } from "../core/store/store-init.ts";+import { StoreOpenError } from "../core/store/store-open.ts";+import {+ resolveConfiguredStoreRoot,+ StoreRootInsideVaultError,+} from "../core/store/store-paths.ts";+import { CliError, parseFlags } from "./argparse.ts";+import { sortedReplacer } from "./helpers.ts";++const USAGE =+ "usage: o2b store init [--partitions shared|shared,private] [--config <file>] [--json]";++/** `refused` is an answer (the store exists, or is partial), not a broken argv. */+const STORE_EXIT = Object.freeze({ ok: 0, refused: 1, usage: 2 } as const);++export async function handleStoreSubcommand(argv: ReadonlyArray<string>): Promise<number> {+ const verb = argv[0];+ if (verb === undefined || verb === "-h" || verb === "--help") {+ process.stdout.write(`${USAGE}\n`);+ return verb === undefined ? STORE_EXIT.usage : STORE_EXIT.ok;+ }+ const rest = argv.slice(1);+ switch (verb) {+ case "init":+ return cmdStoreInit(rest);+ default:+ process.stderr.write(`error: unknown store verb: ${verb}\n${USAGE}\n`);+ return STORE_EXIT.usage;+ }+}++function parsePartitions(value: string | undefined): StorePartition[] {+ if (value === undefined) return [...STORE_PARTITIONS];+ const names = value+ .split(",")+ .map((name) => name.trim())+ .filter((name) => name !== "");+ const known = new Set<string>(STORE_PARTITIONS);+ const unknown = names.filter((name) => !known.has(name));+ if (names.length === 0 || unknown.length > 0) {+ throw new CliError(+ `--partitions takes a comma-separated list of ${STORE_PARTITIONS.join(", ")}` ++ (unknown.length > 0 ? `; unknown: ${unknown.join(", ")}` : ""),+ );+ }+ return names as StorePartition[];+}++function renderResult(result: InitStoreResult): string {+ const verb = result.status === "created" ? "Created" : "Completed";+ return (+ `${verb} the brain store at ${result.root}\n` ++ ` store id: ${result.storeId}\n` ++ ` partitions: ${result.partitions.join(", ")}` ++ (result.status === "completed" ? ` (added: ${result.created.join(", ") || "none"})` : "") ++ "\nSync each partition folder as its own sync folder; never sync the store root.\n"+ );+}++function cmdStoreInit(argv: ReadonlyArray<string>): number {+ let partitions: StorePartition[];+ let configPath: string | undefined;+ let json: boolean;+ try {+ const { flags, positional } = parseFlags(argv, {+ partitions: { type: "string" },+ config: { type: "string" },+ json: { type: "boolean" },+ });+ if (positional.length > 0) throw new CliError(`unexpected argument: ${positional[0]}`);+ partitions = parsePartitions(flags["partitions"] as string | undefined);+ configPath = flags["config"] as string | undefined;+ json = flags["json"] === true;+ } catch (err) {+ if (!(err instanceof CliError)) throw err;+ // A flag parse can fail before `--json` is read: look for it in argv.+ if (argv.includes("--json")) writeJsonFailure("usage", err.message);+ process.stderr.write(`error: ${err.message}\n${USAGE}\n`);+ return STORE_EXIT.usage;+ }++ try {+ const { root } = resolveConfiguredStoreRoot(configPath);+ const result = initStore({ root, partitions });+ process.stdout.write(+ json+ ? `${JSON.stringify({ ok: true, ...result }, sortedReplacer, 2)}\n`+ : renderResult(result),+ );+ return STORE_EXIT.ok;+ } catch (err) {+ if (!(err instanceof Error) || !isInitFailure(err)) throw err;+ if (json) writeJsonFailure(err instanceof StoreInitRefusal ? err.reason : "error", err.message);+ process.stderr.write(`error: ${err.message}\n`);+ return STORE_EXIT.refused;+ }+}++/**+ * Failures init reports as an answer rather than a crash: its refusals, a+ * store root it cannot use, an unreadable machine config, and a filesystem+ * error (`EACCES`, `EROFS`, `ENOSPC`, ...) on the store root.+ */+function isInitFailure(err: Error): boolean {+ return (+ err instanceof StoreInitRefusal ||+ err instanceof StoreOpenError ||+ err instanceof StoreRootInsideVaultError ||+ err instanceof ConfigReadError ||+ isFilesystemError(err)+ );+}++/**+ * A system call's error code. Node's own argument errors (`ERR_INVALID_ARG_TYPE`+ * and the rest of the `ERR_` family) carry a string code too, but they are+ * programming errors, and they crash with their stack instead.+ */+function isFilesystemError(err: Error): boolean {+ const code = (err as NodeJS.ErrnoException).code;+ return typeof code === "string" && !code.startsWith("ERR_");+}++function writeJsonFailure(reason: string, message: string): void {+ process.stdout.write(+ `${JSON.stringify({ ok: false, reason, error: message }, sortedReplacer, 2)}\n`,+ );+}diff --git a/src/core/brain/anticipatory-cache.ts b/src/core/brain/anticipatory-cache.tsindex 5e18f3e5..87a6e667 100644--- a/src/core/brain/anticipatory-cache.ts+++ b/src/core/brain/anticipatory-cache.ts@@ -19,18 +19,20 @@import { createHash } from "node:crypto";import { existsSync, mkdirSync, readFileSync } from "node:fs";-import { join, posix } from "node:path";+import { join } from "node:path";import { resolveModelContextWindowEnvTokens } from "../config.ts";import { atomicWriteFileSync } from "../fs-atomic.ts";import type { StampTokens } from "../integrity/stamp.ts";+import { pruneAnticipatoryCache } from "./anticipatory-prune.ts";import { packContext, type ContextPackItem } from "./context-pack.ts";import { resolveModelContextWindowTokens } from "./model-window.ts";import { readLineageLedger } from "./lineage/ledger.ts";import { packStampRefusal, packStampTokens, type ContextPackStamp } from "./pack-stamp.ts";import { resolveOwnerScopeDelivery } from "./preferences-collect.ts";import { resolveSessionLineage } from "./lineage/resolve.ts";-import { BRAIN_ROOT_REL, ensureInsideVault } from "./paths.ts";+import { BRAIN_ANTICIPATORY_REL } from "./path-constants.ts";+import { ensureInsideVault } from "./paths.ts";import { assertVaultIdentityForWrite } from "./vault-identity.ts";import { searchSessionRecall, type SessionRecallHit } from "./session-recall.ts";import { loadBrainConfig } from "./policy.ts";@@ -60,8 +62,6 @@ export const DEFAULT_ANTICIPATORY_MAX_TOKENS = 2_000;const ANTICIPATORY_WINDOW_BUDGET_DIVISOR = 100;const DEFAULT_SESSION_HITS = 5;-const CACHE_DIR_REL = posix.join(BRAIN_ROOT_REL, ".state", "anticipatory");-export interface AnticipatoryContext {readonly items: ReadonlyArray<ContextPackItem>;readonly session_hits: ReadonlyArray<SessionRecallHit>;@@ -225,7 +225,7 @@ export function anticipatoryCachePath(): string {const scope = resolveOwnerScopeDelivery(vault, agentScope ?? undefined).enforcedScope;const key = safeCacheKey(scope === null ? rootSessionId : `${rootSessionId}\u0000${scope}`);- return ensureInsideVault(join(vault, CACHE_DIR_REL, `${key}.json`), vault);+ return ensureInsideVault(join(vault, BRAIN_ANTICIPATORY_REL, `${key}.json`), vault);}function resolveRootId(vault: string, sessionId: string): string {@@ -445,8 +445,11 @@ export function refreshAnticipatoryCache(stamp: toCacheStamp(bundle.stamp),context: bundle.context,};- mkdirSync(join(vault, CACHE_DIR_REL), { recursive: true });+ mkdirSync(join(vault, BRAIN_ANTICIPATORY_REL), { recursive: true });atomicWriteFileSync(path, `${JSON.stringify(cache, null, 2)}\n`);+ // Retention rides on the write, never on the read path: entries are+ // one per session and nothing else deletes them (rate-limited inside).+ pruneAnticipatoryCache(vault, { keep: path });return Object.freeze({refreshed: true,rootSessionId: rootId,diff --git a/src/core/brain/anticipatory-prune.ts b/src/core/brain/anticipatory-prune.tsnew file mode 100644index 00000000..8862fe22--- /dev/null+++ b/src/core/brain/anticipatory-prune.ts@@ -0,0 +1,156 @@+/**+ * Retention for the anticipatory context cache+ * (`Brain/.state/anticipatory/`).+ *+ * The cache writes one entry per lineage root and owner scope on every+ * prompt and, before this module, nothing ever deleted one: a live+ * install held 3,647 entries (305 MB). Pruning removes entries whose+ * file is older than {@link ANTICIPATORY_CACHE_RETENTION_MS}, then+ * enforces a hard cap of {@link ANTICIPATORY_CACHE_MAX_ENTRIES} keeping+ * the newest.+ *+ * Cost model: the prune piggybacks on a refresh that already wrote, and+ * at most once per {@link ANTICIPATORY_PRUNE_INTERVAL_MS} (one `stat` of+ * a marker file decides). The read path never prunes, so a warm read+ * pays nothing.+ *+ * Ages come from file mtimes against the wall clock, not from the+ * refresh's injected clock: mtimes are wall-clock facts, and comparing+ * them with a test or replay clock would delete live entries.+ *+ * Fail-soft like the cache itself: any filesystem error ends the prune+ * quietly; a file another process removed first is simply skipped.+ */++import { readdirSync, statSync, unlinkSync } from "node:fs";+import { join } from "node:path";++import { atomicWriteFileSync } from "../fs-atomic.ts";+import { BRAIN_ANTICIPATORY_REL } from "./path-constants.ts";+import { ensureInsideVault } from "./paths.ts";++/**+ * How long an entry outlives its last write. Deliberately much longer+ * than the 120 s freshness TTL: a TTL-stale entry still steers the live+ * rebuild with its last signal text (the `stale` read state), so pruning+ * at the TTL would turn every idle session's `stale` read into a bare+ * `miss`. A day keeps that behaviour and bounds the directory.+ */+export const ANTICIPATORY_CACHE_RETENTION_MS = 24 * 60 * 60 * 1_000;+/** Hard cap on cache entries kept after the age pass (newest win). */+export const ANTICIPATORY_CACHE_MAX_ENTRIES = 256;+/** Minimum spacing between two opportunistic prunes. */+export const ANTICIPATORY_PRUNE_INTERVAL_MS = 10 * 60 * 1_000;++/** Marker whose mtime records the last prune; never pruned itself. */+const PRUNE_MARKER = ".last-prune";+const ENTRY_SUFFIX = ".json";++export interface PruneAnticipatoryCacheOptions {+ /** Absolute path that must survive (the entry the caller just wrote). */+ readonly keep?: string;+}++export interface PruneAnticipatoryCacheResult {+ readonly ran: boolean;+ readonly removed: number;+}++interface Candidate {+ readonly path: string;+ readonly mtimeMs: number;+ readonly entry: boolean;+}++function removeQuietly(path: string): boolean {+ try {+ unlinkSync(path);+ return true;+ } catch {+ return false;+ }+}++function dueForPrune(markerPath: string, nowMs: number): boolean {+ try {+ return nowMs - statSync(markerPath).mtimeMs >= ANTICIPATORY_PRUNE_INTERVAL_MS;+ } catch {+ return true; // no marker yet+ }+}++function listCandidates(dir: string): Candidate[] {+ const out: Candidate[] = [];+ for (const dirent of readdirSync(dir, { withFileTypes: true })) {+ if (!dirent.isFile() || dirent.name === PRUNE_MARKER) continue;+ const path = join(dir, dirent.name);+ try {+ out.push({+ path,+ mtimeMs: statSync(path).mtimeMs,+ entry: dirent.name.endsWith(ENTRY_SUFFIX),+ });+ } catch {+ // Removed by a concurrent prune between readdir and stat.+ }+ }+ return out;+}++/**+ * Prune the anticipatory cache: drop files older than the retention+ * window (entries and stray atomic-write temp files alike), then cap the+ * remaining entries at the newest {@link ANTICIPATORY_CACHE_MAX_ENTRIES}.+ * Rate-limited; never throws.+ */+export function pruneAnticipatoryCache(+ vault: string,+ options: PruneAnticipatoryCacheOptions = {},+): PruneAnticipatoryCacheResult {+ try {+ const dir = ensureInsideVault(join(vault, BRAIN_ANTICIPATORY_REL), vault);+ const markerPath = join(dir, PRUNE_MARKER);+ const nowMs = Date.now();+ if (!dueForPrune(markerPath, nowMs)) {+ return { ran: false, removed: 0 };+ }+ let candidates: Candidate[];+ try {+ candidates = listCandidates(dir);+ } catch {+ return { ran: false, removed: 0 }; // no cache directory yet+ }+ // Stamp first: a concurrent writer that stats the marker now skips+ // its own scan instead of racing this one over the same files.+ atomicWriteFileSync(markerPath, `${new Date(nowMs).toISOString()}\n`);++ let removed = 0;+ const kept: Candidate[] = [];+ for (const candidate of candidates) {+ if (candidate.path === options.keep) {+ kept.push(candidate);+ continue;+ }+ if (nowMs - candidate.mtimeMs > ANTICIPATORY_CACHE_RETENTION_MS) {+ if (removeQuietly(candidate.path)) removed++;+ } else if (candidate.entry) {+ kept.push(candidate);+ }+ }++ if (kept.length > ANTICIPATORY_CACHE_MAX_ENTRIES) {+ // Newest first; the kept path sorts to the front so it always survives.+ const ordered = kept.toSorted((a, b) => {+ if (a.path === options.keep) return -1;+ if (b.path === options.keep) return 1;+ return b.mtimeMs - a.mtimeMs;+ });+ for (const candidate of ordered.slice(ANTICIPATORY_CACHE_MAX_ENTRIES)) {+ if (removeQuietly(candidate.path)) removed++;+ }+ }+ return { ran: true, removed };+ } catch {+ return { ran: false, removed: 0 };+ }+}diff --git a/src/core/brain/apply-evidence.ts b/src/core/brain/apply-evidence.tsindex 3ad562b4..71967278 100644--- a/src/core/brain/apply-evidence.ts+++ b/src/core/brain/apply-evidence.ts@@ -41,7 +41,22 @@ import {REMEMBER_KEY_STATUS,rememberKey,} from "./idempotency-ledger.ts";-import { appendLogEvent, type AppendLogEventResult, type BrainLogEntry } from "./log.ts";+import {+ appendLogEvent,+ logEventPrivacyContent,+ type AppendLogEventResult,+ type BrainLogEntry,+} from "./log.ts";+import { dualWrite, isDualWriteEnabled } from "../store/dual-write.ts";+import { withOperationPrivacy } from "../store/operation-scope.ts";+import { isPrivatePageFile, preferenceEvidenceRecord } from "../store/dual-write-records.ts";+import {+ callerInput,+ opaqueFields,+ operationPrivacy,+ type OperationPrivacy,+ type PrivacyVerdict,+} from "../store/operation-privacy.ts";import { parsePreference } from "./preference.ts";import { preferencePath, validateSlug } from "./paths.ts";import { isoSecond } from "./time.ts";@@ -150,6 +165,11 @@ export interface AppendApplyEvidenceOptions {* every preference counts.*/readonly readable?: (rel: string) => boolean;+ /**+ * The privacy verdict of an enclosing operation (a write batch), which+ * every store record of this call inherits (`store/operation-privacy.ts`).+ */+ readonly storePrivate?: PrivacyVerdict;}/**@@ -179,26 +199,25 @@ export interface AppendApplyEvidenceResult {readonly deduped?: boolean;}+/** A validated evidence call: its target and the event body it appends. */+interface PreparedEvidence {+ readonly prefFilePath: string;+ readonly target: ReturnType<typeof parsePreference>;+ /** The event body, as the call hands it to the log appender. */+ readonly body: Record<string, string>;+}+/**- * Append one `apply-evidence` event to today's log. Throws- * {@link BrainPreferenceNotFoundError} when the preference id does not- * resolve to a file under `Brain/preferences/`.- *- * The log file is created on the first event of the day (the appender- * inside `log.ts` handles that transparently). Subsequent calls on the- * same UTC day append.+ * Validate one evidence call and render the event body it appends. Shared+ * by {@link appendApplyEvidence} and {@link applyEvidencePrivacy}, so the+ * privacy a write batch judges before it commits is judged from the very+ * body the append writes.*/-export function appendApplyEvidence(+function prepareEvidence(vault: string,input: AppendApplyEvidenceInput,- opts: AppendApplyEvidenceOptions = {},-): AppendApplyEvidenceResult {- if (opts.role !== undefined) {- const verdict = checkRolePermission(opts.role, BRAIN_OPERATIONS.evidence_record);- if (!verdict.allowed) {- throw new BrainRolePermissionError(opts.role, verdict.reason ?? "denied");- }- }+ readable: ((rel: string) => boolean) | undefined,+): PreparedEvidence {if (!input.pref_id || !input.pref_id.trim()) {throw new Error("apply-evidence missing field: pref_id");}@@ -245,7 +264,7 @@ export function appendApplyEvidence(}validateSlug(slug);const prefFilePath = preferencePath(vault, slug);- if (!isApplyEvidenceTargetPresent(vault, prefFilePath, opts.readable)) {+ if (!isApplyEvidenceTargetPresent(vault, prefFilePath, readable)) {throw new BrainPreferenceNotFoundError(`pref-${slug}`, prefFilePath);}// Parse so a corrupted target produces a meaningful error rather@@ -253,9 +272,6 @@ export function appendApplyEvidence(// The parsed pref also supplies the principle used to title the// wikilink we emit below.const target = parsePreference(prefFilePath);-- const now = opts.now ?? new Date();- const timestamp = isoSecond(now);const wikilink = renderPrefLink({ id: target.id, principle: target.principle });// Render the canonical payload. Ordering is deliberate: the wikilink@@ -277,66 +293,163 @@ export function appendApplyEvidence(}const trimmedNote = note?.trim();if (trimmedNote) body["note"] = trimmedNote;+ return { prefFilePath, target, body };+}++/**+ * The privacy verdict of one evidence call (`store/operation-privacy.ts`):+ * private when the target preference is private or cannot be judged, when+ * the event body or any field of the caller's `input` (its idempotency+ * key included) names a private or unresolvable page or carries a+ * `<private>` region, or when `inherit` (an enclosing operation) is.+ */+function evidencePrivacy(+ vault: string,+ input: AppendApplyEvidenceInput,+ prepared: PreparedEvidence,+ inherit?: PrivacyVerdict,+): OperationPrivacy {+ return operationPrivacy(vault, {+ target: () => isPrivatePageFile(prepared.prefFilePath),+ content: [logEventPrivacyContent(prepared.body), callerInput(input, EVIDENCE_INPUT_OPAQUE)],+ inherit: [inherit],+ });+}++/** Opaque fields of an evidence call's input: its idempotency key. */+const EVIDENCE_INPUT_OPAQUE: ReadonlySet<string> = opaqueFields();++/**+ * The privacy verdict {@link appendApplyEvidence} would give `input`, for+ * an enclosing operation (a write batch) that judges itself before it+ * commits. A call that would be refused cannot be judged and counts as+ * private.+ */+export function applyEvidencePrivacy(+ vault: string,+ input: AppendApplyEvidenceInput,+ readable?: (rel: string) => boolean,+): OperationPrivacy {+ let prepared: PreparedEvidence;+ try {+ prepared = prepareEvidence(vault, input, readable);+ } catch {+ return () => true;+ }+ return evidencePrivacy(vault, input, prepared);+}- // Idempotency consult (C1): a repeat with the same key + same payload- // dedupes (no second row); the same key + a different payload throws- // before appending. The hash covers the rendered event body β exactly- // what would land in the log.- const idKey = input.idempotency_key?.trim();- let idContentHash: string | undefined;- if (idKey) {- idContentHash = computePayloadHash(body);- const existing = lookupKey(vault, idKey);- if (existing) {- if (existing.contentHash === idContentHash) {- const ref = (existing.ref ?? {}) as { logged_at?: string; log_path?: string };+/**+ * Append one `apply-evidence` event to today's log. Throws+ * {@link BrainPreferenceNotFoundError} when the preference id does not+ * resolve to a file under `Brain/preferences/`.+ *+ * The log file is created on the first event of the day (the appender+ * inside `log.ts` handles that transparently). Subsequent calls on the+ * same UTC day append.+ */+export function appendApplyEvidence(+ vault: string,+ input: AppendApplyEvidenceInput,+ opts: AppendApplyEvidenceOptions = {},+): AppendApplyEvidenceResult {+ if (opts.role !== undefined) {+ const verdict = checkRolePermission(opts.role, BRAIN_OPERATIONS.evidence_record);+ if (!verdict.allowed) {+ throw new BrainRolePermissionError(opts.role, verdict.reason ?? "denied");+ }+ }+ const prepared = prepareEvidence(vault, input, opts.readable);+ const { target, body } = prepared;+ // One privacy verdict for every store record this call writes: the log+ // event, the idempotency receipt and the evidence record. It is judged+ // once, before anything is appended, so it follows the preference as+ // read here even if the file is rewritten or retired meanwhile. Judged+ // only when the dual write is on (with it off nothing changes).+ const privacy = evidencePrivacy(vault, input, prepared, opts.storePrivate);+ if (isDualWriteEnabled()) privacy();+ // Every store record written from here on, by this call or by any+ // writer it calls, carries this verdict (`store/operation-scope.ts`).+ return withOperationPrivacy(privacy, () => {+ const now = opts.now ?? new Date();+ const timestamp = isoSecond(now);++ // Idempotency consult (C1): a repeat with the same key + same payload+ // dedupes (no second row); the same key + a different payload throws+ // before appending. The hash covers the rendered event body β exactly+ // what would land in the log.+ const idKey = input.idempotency_key?.trim();+ let idContentHash: string | undefined;+ if (idKey) {+ idContentHash = computePayloadHash(body);+ const existing = lookupKey(vault, idKey);+ if (existing) {+ if (existing.contentHash === idContentHash) {+ const ref = (existing.ref ?? {}) as { logged_at?: string; log_path?: string };+ return {+ logged_at: ref.logged_at ?? timestamp,+ log_path: ref.log_path ? join(vault, ref.log_path) : "",+ deduped: true,+ };+ }+ throw new IdempotencyPayloadMismatchError(idKey, existing.contentHash, idContentHash);+ }+ }++ const entry: BrainLogEntry = {+ timestamp,+ eventType: BRAIN_LOG_EVENT_KIND.applyEvidence,+ body,+ };+ const result: AppendLogEventResult = appendLogEvent(vault, entry, { storePrivate: privacy });++ // Record the key AFTER the row lands so a future retry dedupes. Under a+ // concurrent same-key race the unlocked lookupKey above can miss a rival+ // write; rememberKey re-checks under its shard lock and returns the verdict,+ // which we MUST act on (the ledger never throws β the writer decides).+ if (idKey && idContentHash !== undefined) {+ const remembered = rememberKey(vault, {+ key: idKey,+ contentHash: idContentHash,+ createdAt: timestamp,+ ref: { logged_at: timestamp, log_path: relative(vault, result.logPath) },+ private: privacy,+ });+ if (remembered.status === REMEMBER_KEY_STATUS.payload_mismatch) {+ throw new IdempotencyPayloadMismatchError(+ idKey,+ remembered.record.contentHash,+ idContentHash,+ );+ }+ if (remembered.status === REMEMBER_KEY_STATUS.duplicate_match) {+ // A rival process won the key with the same payload between our unlocked+ // lookup and this locked record; report the winner's row as the deduped+ // result instead of a second normal write.+ const ref = (remembered.record.ref ?? {}) as { logged_at?: string; log_path?: string };return {logged_at: ref.logged_at ?? timestamp,- log_path: ref.log_path ? join(vault, ref.log_path) : "",+ log_path: ref.log_path ? join(vault, ref.log_path) : result.logPath,deduped: true,};}- throw new IdempotencyPayloadMismatchError(idKey, existing.contentHash, idContentHash);}- }- const entry: BrainLogEntry = {- timestamp,- eventType: BRAIN_LOG_EVENT_KIND.applyEvidence,- body,- };- const result: AppendLogEventResult = appendLogEvent(vault, entry);-- // Record the key AFTER the row lands so a future retry dedupes. Under a- // concurrent same-key race the unlocked lookupKey above can miss a rival- // write; rememberKey re-checks under its shard lock and returns the verdict,- // which we MUST act on (the ledger never throws β the writer decides).- if (idKey && idContentHash !== undefined) {- const remembered = rememberKey(vault, {- key: idKey,- contentHash: idContentHash,- createdAt: timestamp,- ref: { logged_at: timestamp, log_path: relative(vault, result.logPath) },- });- if (remembered.status === REMEMBER_KEY_STATUS.payload_mismatch) {- throw new IdempotencyPayloadMismatchError(- idKey,- remembered.record.contentHash,- idContentHash,- );- }- if (remembered.status === REMEMBER_KEY_STATUS.duplicate_match) {- // A rival process won the key with the same payload between our unlocked- // lookup and this locked record; report the winner's row as the deduped- // result instead of a second normal write.- const ref = (remembered.record.ref ?? {}) as { logged_at?: string; log_path?: string };- return {- logged_at: ref.logged_at ?? timestamp,- log_path: ref.log_path ? join(vault, ref.log_path) : result.logPath,- deduped: true,- };- }- }+ // Brain store dual write (task 1.11): the log event above is dual-written+ // by the log appender; the evidence record feeds the preference fold's+ // counters. Off by default, never fails this append.+ dualWrite(+ () =>+ preferenceEvidenceRecord({+ id: target.id,+ result: input.result,+ artifact: body["artifact"]!,+ agent: body["agent"]!,+ private: privacy(),+ }),+ { vault },+ );- return { logged_at: timestamp, log_path: result.logPath };+ return { logged_at: timestamp, log_path: result.logPath };+ });}diff --git a/src/core/brain/artifact-ref-resolve.ts b/src/core/brain/artifact-ref-resolve.tsnew file mode 100644index 00000000..77d9925e--- /dev/null+++ b/src/core/brain/artifact-ref-resolve.ts@@ -0,0 +1,165 @@+/**+ * Resolve a reference a report row or a log event carries to the+ * vault-relative path of the page it names, or `null` when it names none+ * on disk.+ *+ * Extracted from `./artifact-ref-view.ts` so a writer below the search+ * layer can resolve references the same way: the brain store's partition+ * rule for log events (`store/reference-privacy.ts`) is reached from the+ * log appender, and the view module imports a search type the log must+ * not depend on. This module imports nothing above `brain/paths.ts`.+ */++import { isAbsolute, join } from "node:path";+import { existsSync, statSync } from "node:fs";++import { pathIsInside, posixRel, vaultRelative } from "../path-safety.ts";+import { BRAIN_DECISIONS_REL, BRAIN_SOURCES_REL, brainDirs } from "./paths.ts";+import { ANCHORED_WIKILINK_RE, stripWikilinkDecoration } from "./wikilink.ts";++/** The `.md` extension every Brain artifact id resolves through. */+const MARKDOWN_EXT = ".md";++/**+ * Strip the wikilink brackets a report row may have kept around its+ * reference, leaving the target verbatim.+ *+ * The brackets are SYNTAX, not part of the reference: a retirement's+ * `retired_by`, a dream transition's `link` and an evidence row's+ * `artifact` all carry `[[β¦]]` straight out of frontmatter or a log+ * body, and `[[Brain/preferences/pref-x.md]]` names exactly the page+ * `Brain/preferences/pref-x.md`. Before this, such a reference matched+ * neither branch below and the row failed OPEN.+ *+ * Deliberately NOT `parseWikilinkRich`: that normaliser collapses folder+ * segments and drops `.md`, which turns a path-shaped link into a bare+ * basename that resolves to no artifact - the same fail-open by a longer+ * route.+ *+ * The alias and anchor DO come off, through the decoration-only half of+ * that normaliser. Leaving them on was a fail-open with a comment on it:+ * `pref-x|alias`, `pref-x#Raw` and+ * `Brain/preferences/pref-x.md|the rule` end in neither `.md` nor an id+ * any directory holds, so they resolved to nothing and their rows passed+ * unconditionally - and these are not hypothetical spellings, they are+ * what `brain_apply_evidence` documents for its own `artifact` argument.+ * Cutting decoration can only ever SHORTEN the target, so a reference+ * that resolved before still resolves and one that did not may now.+ */+function unbracket(ref: string): string {+ const match = ANCHORED_WIKILINK_RE.exec(ref.trim());+ return stripWikilinkDecoration(match === null ? ref : match[1]!);+}++/**+ * Resolve a bare Brain artifact id to its vault-relative path, or `null`+ * when no artifact of that id is on disk.+ *+ * ## Why the directory list is the whole boundary+ *+ * `visible()` reads an id that resolves to no file as "this row names+ * nothing that could be hidden" and lets the row through. That reading is+ * true only for ids this function would have FOUND had the artifact+ * existed - so every directory omitted here is a directory whose pages+ * are silently unclassifiable, and every binding's fail-closed promise+ * turns into a fail-open one for exactly those pages. The list is+ * therefore every `Brain/` directory holding id-addressable Markdown:+ *+ * - `preferences` / `retired` carry `owner:` through the preference+ * writer, and carry `visibility:` wherever an operator wrote one;+ * - `inbox` / `processed` / `pending` carry whatever an operator or an+ * importer wrote into a signal's frontmatter;+ * - `sources` (`src-<slug>.md`) and `entities` are taggable the same+ * way, and `brain_search_by_source` already filters the first of them+ * on the search side - so an id-shaped reference to one reaching a+ * view here and passing was the two halves disagreeing;+ * - `decisions` (`decision-<slug>.md`) is named by id in the+ * decision-change receipts (`[[decision-<slug>]]`).+ *+ * `log` is deliberately absent - a log shard is named by date, is shared+ * by construction, and carries no per-page claim to read. `bases` holds+ * `.base` view definitions rather than Markdown pages, and `snapshots`+ * holds dated copies addressed by path rather than by id.+ */+function artifactPath(vault: string, id: string): string | null {+ const dirs = brainDirs(vault);+ for (const dir of [+ dirs.preferences,+ dirs.retired,+ dirs.inbox,+ dirs.processed,+ dirs.archived,+ dirs.pending,+ join(vault, BRAIN_SOURCES_REL),+ dirs.entities,+ join(vault, BRAIN_DECISIONS_REL),+ ]) {+ const abs = join(dir, `${id}${MARKDOWN_EXT}`);+ // The visibility predicate speaks vault-relative POSIX paths - the+ // form a path-shaped reference already carries. Handing it the native+ // `Brain\preferences\...` spelling on Windows would match no rule and+ // let a hidden artifact through, the fail-open this view exists to+ // prevent. Slicing the vault's length off `abs` has the same failure+ // for a vault spelled `/v/` or `/v/x/..` (`join` normalizes `abs`, not+ // `vault`), so the path is taken relative to the resolved vault.+ if (existsSync(abs)) return vaultRelative(abs, vault);+ }+ return null;+}++/**+ * The candidate an extensionless vault-page reference denotes: the bare+ * spelling when that file exists, else its `.md` twin when the twin+ * exists - the same first-existing rule the claim ledger's write side+ * applies to an extensionless source, so the read-side gate cannot drift+ * from the spelling the writer used. When neither file exists the+ * reference names nothing here (`null` reads as visible): a convention+ * like `Notes/<slug>-applied` in a log payload is not a page, and+ * judging it as a missing `.md` page would drop every row carrying it.+ * Both candidates are probed only inside the vault, so a+ * traversal-shaped reference never reaches the filesystem outside it.+ */+function pageCandidate(vault: string, bare: string): string | null {+ if (isVaultFile(vault, bare)) return bare;+ const twin = bare + MARKDOWN_EXT;+ if (isVaultFile(vault, twin)) return twin;+ return null;+}++/** The vault-relative path names a regular file, so it can name a page. */+function isVaultFile(vault: string, rel: string): boolean {+ if (!pathIsInside(join(vault, rel), vault)) return false;+ try {+ return statSync(join(vault, rel)).isFile();+ } catch {+ return false;+ }+}++/**+ * The vault-relative path `ref` names, or `null` when it names nothing on+ * disk. A reference that names a path is resolved as one, including its+ * extensionless spelling, whose .md twin is the page an Obsidian writer+ * named (a gate that resolved only the .md form failed OPEN for exactly+ * that spelling). A bare id is a Brain artifact id ({@link artifactPath}).+ * A `.md` path is returned as written, even outside the vault: the caller+ * decides what a path outside the vault means.+ *+ * Two spellings are brought to the vault-relative POSIX form first, since+ * the visibility rules and the callers' join speak only that form:+ *+ * - on Windows a `\` is a separator (`posixRel`), so+ * `Brain\preferences\pref-x` is the path it spells rather than a bare+ * id that resolves to nothing;+ * - an absolute path is made relative to the vault: one inside the vault+ * names its page, one outside comes back climbing out of it (or+ * absolute, on another Windows drive), which every caller refuses.+ */+export function resolveArtifactRef(vault: string, ref: string): string | null {+ const spelled = posixRel(unbracket(ref));+ if (spelled.length === 0) return null;+ const bare = isAbsolute(spelled) ? vaultRelative(spelled, vault) : spelled;+ if (bare.length === 0) return null;+ if (bare.endsWith(MARKDOWN_EXT)) return bare;+ return bare.includes("/") ? pageCandidate(vault, bare) : artifactPath(vault, bare);+}diff --git a/src/core/brain/artifact-ref-view.ts b/src/core/brain/artifact-ref-view.tsindex 025cbc3e..4dd95515 100644--- a/src/core/brain/artifact-ref-view.ts+++ b/src/core/brain/artifact-ref-view.ts@@ -29,16 +29,11 @@* one of these views reports how many rows it withheld.*/-import { join } from "node:path";-import { existsSync, statSync } from "node:fs";+import { resolve } from "node:path";-import { pathIsInside, vaultRelative } from "../path-safety.ts";+import { pathIsInside } from "../path-safety.ts";import type { FrontmatterCache } from "../search/result-filters.ts";-import { BRAIN_DECISIONS_REL, BRAIN_SOURCES_REL, brainDirs } from "./paths.ts";-import { ANCHORED_WIKILINK_RE, stripWikilinkDecoration } from "./wikilink.ts";--/** The `.md` extension every Brain artifact id resolves through. */-const MARKDOWN_EXT = ".md";+import { resolveArtifactRef } from "./artifact-ref-resolve.ts";/*** A reference a report row carries: either a vault-relative path@@ -54,37 +49,6 @@ const MARKDOWN_EXT = ".md";*/export type ArtifactRef = string | null | undefined;-/**- * Strip the wikilink brackets a report row may have kept around its- * reference, leaving the target verbatim.- *- * The brackets are SYNTAX, not part of the reference: a retirement's- * `retired_by`, a dream transition's `link` and an evidence row's- * `artifact` all carry `[[β¦]]` straight out of frontmatter or a log- * body, and `[[Brain/preferences/pref-x.md]]` names exactly the page- * `Brain/preferences/pref-x.md`. Before this, such a reference matched- * neither branch below and the row failed OPEN.- *- * Deliberately NOT `parseWikilinkRich`: that normaliser collapses folder- * segments and drops `.md`, which turns a path-shaped link into a bare- * basename that resolves to no artifact - the same fail-open by a longer- * route.- *- * The alias and anchor DO come off, through the decoration-only half of- * that normaliser. Leaving them on was a fail-open with a comment on it:- * `pref-x|alias`, `pref-x#Raw` and- * `Brain/preferences/pref-x.md|the rule` end in neither `.md` nor an id- * any directory holds, so they resolved to nothing and their rows passed- * unconditionally - and these are not hypothetical spellings, they are- * what `brain_apply_evidence` documents for its own `artifact` argument.- * Cutting decoration can only ever SHORTEN the target, so a reference- * that resolved before still resolves and one that did not may now.- */-function unbracket(ref: string): string {- const match = ANCHORED_WIKILINK_RE.exec(ref.trim());- return stripWikilinkDecoration(match === null ? ref : match[1]!);-}-/** One rule, bound to one vault, asked over references. */export interface ArtifactRefView {/**@@ -121,91 +85,6 @@ export const UNFILTERED_ARTIFACT_REFS: ArtifactRefView = Object.freeze({keep: <T>(rows: ReadonlyArray<T>) => rows,});-/**- * Resolve a bare Brain artifact id to its vault-relative path, or `null`- * when no artifact of that id is on disk.- *- * ## Why the directory list is the whole boundary- *- * `visible()` reads an id that resolves to no file as "this row names- * nothing that could be hidden" and lets the row through. That reading is- * true only for ids this function would have FOUND had the artifact- * existed - so every directory omitted here is a directory whose pages- * are silently unclassifiable, and every binding's fail-closed promise- * turns into a fail-open one for exactly those pages. The list is- * therefore every `Brain/` directory holding id-addressable Markdown:- *- * - `preferences` / `retired` carry `owner:` through the preference- * writer, and carry `visibility:` wherever an operator wrote one;- * - `inbox` / `processed` / `pending` carry whatever an operator or an- * importer wrote into a signal's frontmatter;- * - `sources` (`src-<slug>.md`) and `entities` are taggable the same- * way, and `brain_search_by_source` already filters the first of them- * on the search side - so an id-shaped reference to one reaching a- * view here and passing was the two halves disagreeing;- * - `decisions` (`decision-<slug>.md`) is named by id in the- * decision-change receipts (`[[decision-<slug>]]`).- *- * `log` is deliberately absent - a log shard is named by date, is shared- * by construction, and carries no per-page claim to read. `bases` holds- * `.base` view definitions rather than Markdown pages, and `snapshots`- * holds dated copies addressed by path rather than by id.- */-function artifactPath(vault: string, id: string): string | null {- const dirs = brainDirs(vault);- for (const dir of [- dirs.preferences,- dirs.retired,- dirs.inbox,- dirs.processed,- dirs.archived,- dirs.pending,- join(vault, BRAIN_SOURCES_REL),- dirs.entities,- join(vault, BRAIN_DECISIONS_REL),- ]) {- const abs = join(dir, `${id}${MARKDOWN_EXT}`);- // The visibility predicate speaks vault-relative POSIX paths - the- // form a path-shaped reference already carries. Handing it the native- // `Brain\preferences\...` spelling on Windows would match no rule and- // let a hidden artifact through, the fail-open this view exists to- // prevent. Slicing the vault's length off `abs` has the same failure- // for a vault spelled `/v/` or `/v/x/..` (`join` normalizes `abs`, not- // `vault`), so the path is taken relative to the resolved vault.- if (existsSync(abs)) return vaultRelative(abs, vault);- }- return null;-}--/**- * The candidate an extensionless vault-page reference denotes: the bare- * spelling when that file exists, else its `.md` twin when the twin- * exists - the same first-existing rule the claim ledger's write side- * applies to an extensionless source, so the read-side gate cannot drift- * from the spelling the writer used. When neither file exists the- * reference names nothing here (`null` reads as visible): a convention- * like `Notes/<slug>-applied` in a log payload is not a page, and- * judging it as a missing `.md` page would drop every row carrying it.- * Both candidates are probed only inside the vault, so a- * traversal-shaped reference never reaches the filesystem outside it.- */-function pageCandidate(vault: string, bare: string): string | null {- if (isVaultFile(vault, bare)) return bare;- const twin = bare + MARKDOWN_EXT;- if (isVaultFile(vault, twin)) return twin;- return null;-}--/** The vault-relative path names a regular file, so it can name a page. */-function isVaultFile(vault: string, rel: string): boolean {- if (!pathIsInside(join(vault, rel), vault)) return false;- try {- return statSync(join(vault, rel)).isFile();- } catch {- return false;- }-}-/*** Bind one per-path rule to one vault, as a reference-shaped view.*@@ -229,27 +108,15 @@ export function artifactRefView(if (ref === null || ref === undefined || ref.length === 0) return true;const memo = verdicts.get(ref);if (memo !== undefined) return memo;- // A reference that names a path is resolved as one - including its- // extensionless spelling, whose .md twin is the page an Obsidian- // writer named (a gate that resolved only the .md form failed OPEN- // for exactly that spelling). A bare id is a Brain artifact id, and- // an id with no artifact on disk names nothing that could be hidden- // - see {@link artifactPath} for why that reading is only true while- // its directory list is complete.- const bare = unbracket(ref);- const rel =- bare.length === 0- ? null- : bare.endsWith(MARKDOWN_EXT)- ? bare- : bare.includes("/")- ? pageCandidate(vault, bare)- : artifactPath(vault, bare);+ // A bare id with no artifact on disk names nothing that could be+ // hidden - see `artifact-ref-resolve.ts` for why that reading is only+ // true while its directory list is complete.+ const rel = resolveArtifactRef(vault, ref);// A reference that resolves outside the vault names no page anyone// could be shown, and is hidden before the rule reads anything: log// bodies carry strings an earlier caller wrote.const verdict =- rel === null ? true : pathIsInside(join(vault, rel), vault) && pathVisible(rel, cache);+ rel === null ? true : pathIsInside(resolve(vault, rel), vault) && pathVisible(rel, cache);verdicts.set(ref, verdict);return verdict;};diff --git a/src/core/brain/continuity/promote-host-memory.ts b/src/core/brain/continuity/promote-host-memory.tsindex 09591c55..428c4a23 100644--- a/src/core/brain/continuity/promote-host-memory.ts+++ b/src/core/brain/continuity/promote-host-memory.ts@@ -59,7 +59,7 @@ import { BRAIN_PREFERENCES_REL, preferencePath, retiredPath, vaultRelative } froimport { planAction, type PlannedFile } from "../claude-memory-plan.ts";import { renderPreferenceFromMemory, slugifyMemoryName } from "../claude-memory-render.ts";import { resolvedOwnerFor } from "../preference.ts";-import { createSnapshot } from "../snapshot.ts";+import { takeSnapshot } from "../snapshot-gate.ts";import { TagSyntaxError } from "../tag-syntax.ts";import { isoSecond } from "../time.ts";import { BRAIN_LOG_EVENT_KIND, BRAIN_SNAPSHOT_REASON } from "../types.ts";@@ -528,14 +528,13 @@ export function promoteHostMemory(opts: PromoteHostMemoryOpts): PromoteHostMemor// run still landed. The caller (CLI) uses the thrown error to exit 2.let snapshotRunId: string | null = null;if (filesToWrite.length > 0) {- // The run-id prefix and the recorded reason are one constant, so the- // archive's filename can never disagree with its stamped provenance.- const runId = `${BRAIN_SNAPSHOT_REASON.promoteHostMemory}-${promotedAt.replace(/:/g, "-")}`;- createSnapshot(opts.vault, runId, {- reason: BRAIN_SNAPSHOT_REASON.promoteHostMemory,+ // Through the snapshot gate, like every other reason: the run id is+ // derived from the reason (so the archive's filename cannot disagree+ // with its stamped provenance) and `snapshots.retention_count` is+ // enforced around the new archive.+ snapshotRunId = takeSnapshot(opts.vault, BRAIN_SNAPSHOT_REASON.promoteHostMemory, {now,- });- snapshotRunId = runId;+ }).runId;}const applied: PlannedFile[] = [];diff --git a/src/core/brain/continuity/store.ts b/src/core/brain/continuity/store.tsindex 0c796cbe..f7b8f447 100644--- a/src/core/brain/continuity/store.ts+++ b/src/core/brain/continuity/store.ts@@ -24,6 +24,9 @@ import type {ContinuityRecordPage,ContinuitySourceRef,} from "./types.ts";+import { dualWrite, type DualWriteRecord } from "../../store/dual-write.ts";+import { DUAL_WRITE_LEDGERS, ledgerRowRecord } from "../../store/dual-write-records.ts";+import { rowNamesPrivatePage } from "../../store/reference-privacy.ts";export type {AppendContinuityRecordInput,@@ -223,6 +226,10 @@ export function appendContinuityRecords(} finally {handle.release();}+ // Brain store dual write (task 1.11): off by default, never fails this append.+ // A record flagged private (a `<private>` region was stripped, or the+ // caller said so) stays out of `shared`, as the legacy reader withholds it.+ dualWrite(() => records.map((r) => continuityRowRecord(vault, r)), { vault });}return Object.freeze(built.map((entry) => entry.record));@@ -351,9 +358,24 @@ function appendRecord(vault: string, record: ContinuityRecord): ContinuityRecord} finally {handle.release();}+ // Brain store dual write (task 1.11): off by default, never fails this append.+ dualWrite(() => continuityRowRecord(vault, record), { vault });return record;}+/**+ * The store copy of a continuity record: `private` only when the record is+ * flagged private or its text names a page that is private or cannot be+ * judged; a turn that names nothing private goes to `shared`.+ */+function continuityRowRecord(vault: string, record: ContinuityRecord): DualWriteRecord {+ return ledgerRowRecord(+ DUAL_WRITE_LEDGERS.continuity,+ record,+ record.private === true || rowNamesPrivatePage(vault, record) ? "private" : "shared",+ );+}+/*** Read every stored record across every device shard, optionally skipping* whole months that a `since`/`until` filter proves cannot contribute adiff --git a/src/core/brain/decisions/receipts.ts b/src/core/brain/decisions/receipts.tsindex 85052c59..fe9736ca 100644--- a/src/core/brain/decisions/receipts.ts+++ b/src/core/brain/decisions/receipts.ts@@ -38,6 +38,9 @@ import { appendLogEvent } from "../log.ts";import { decodeOffsetCursor, encodeOffsetCursor } from "../offset-cursor.ts";import { BRAIN_LOG_EVENT_KIND } from "../types.ts";import { assertVaultIdentityForWrite } from "../vault-identity.ts";+import { dualWrite } from "../../store/dual-write.ts";+import { DUAL_WRITE_LEDGERS, ledgerRowRecord } from "../../store/dual-write-records.ts";+import { rowNamesPrivatePage } from "../../store/reference-privacy.ts";/** Schema tag stamped on every receipt line. */export const DECISION_CHANGE_SCHEMA_VERSION = "decision_change.v1";@@ -316,6 +319,18 @@ export function appendDecisionChangeReceipt(mkdirSync(receiptsDir(vault), { recursive: true });const path = receiptShardPath(vault, input.configPath);appendFileSync(path, JSON.stringify(receipt) + "\n");+ // Brain store dual write (task 1.11): off by default, never fails this append.+ // A receipt about a private item (its subject, evidence or rationale+ // names a private or unjudgeable preference or page) stays out of `shared`.+ dualWrite(+ () =>+ ledgerRowRecord(+ DUAL_WRITE_LEDGERS.decisionReceipts,+ receipt,+ rowNamesPrivatePage(vault, receipt) ? "private" : "shared",+ ),+ { vault },+ );// Surface the change in the merged activity timeline. Emitted only on an// actual append, never on an idempotent replay, so the log never// double-counts a change. Fail-soft: a log hiccup must not lose the receipt.diff --git a/src/core/brain/destructive-sites.ts b/src/core/brain/destructive-sites.tsindex b9c0f15a..c15f2e92 100644--- a/src/core/brain/destructive-sites.ts+++ b/src/core/brain/destructive-sites.ts@@ -487,6 +487,15 @@ export const DESTRUCTIVE_SITES: Readonly<Record<string, DestructiveSiteDeclarati"NOT a snapshot-excluded entry, so the bytes the removal takes are inside that run's " +"recovery point even though this primitive never takes one of its own.",},+ "src/core/brain/anticipatory-prune.ts": {+ calls: ["unlinkSync"],+ recovery: UNARCHIVED_BRAIN,+ reason:+ "prunes the anticipatory context cache under `Brain/.state/anticipatory/` by file age " ++ "and a hard count cap, never the entry the calling refresh just wrote. Every entry is " ++ "a derived context pack rebuilt from the vault it sits in, so removing one costs one " ++ "recomputation on the next refresh or read and loses no content.",+ },"src/core/brain/notes/write-record.ts": {calls: ["unlinkSync"],recovery: UNARCHIVED_BRAIN,diff --git a/src/core/brain/diagnostics.ts b/src/core/brain/diagnostics.tsindex 9ad247d8..05328d32 100644--- a/src/core/brain/diagnostics.ts+++ b/src/core/brain/diagnostics.ts@@ -181,6 +181,12 @@ export const DIAGNOSTIC_SIGNALS: ReadonlyMap<string, DiagnosticSignal> = new MapnextCommand: "o2b brain init",autoRepairable: false,},+ {+ code: "store-missing",+ issueClass: "brain store not created yet",+ nextCommand: "o2b store init",+ autoRepairable: false,+ },{code: "config-invalid",issueClass: "invalid Brain config",@@ -341,6 +347,15 @@ export const DIAGNOSTIC_SIGNALS: ReadonlyMap<string, DiagnosticSignal> = new MapnextCommand: "o2b brain upgrade --dry-run",autoRepairable: false,},+ {+ // A synced managed file carries a newer template revision than this+ // release ships: another device runs a newer release. This device+ // keeps the file as it is; updating Open Second Brain here clears it.+ code: "managed-file-from-newer-release",+ issueClass: "Brain manual written by a newer release",+ nextCommand: "o2b brain upgrade --dry-run",+ autoRepairable: false,+ },{code: "doctor-warnings",issueClass: "doctor warnings",diff --git a/src/core/brain/doctor-exits.ts b/src/core/brain/doctor-exits.tsindex e25470e5..527e73f1 100644--- a/src/core/brain/doctor-exits.ts+++ b/src/core/brain/doctor-exits.ts@@ -52,6 +52,97 @@ export interface DoctorExitExclusion {}const EXCLUSIONS: ReadonlyArray<DoctorExitExclusion> = [+ // --- The brain store (task 1.11, a phase 1 trial) ------------------------+ {+ code: "store-dual-write-failures",+ reason:+ "a failed dual write names a cause outside the store itself (a full disk, a partition this " ++ "machine does not hold, a refused root), and the legacy write it shadowed was kept; the " ++ "fix is to remove that cause, which differs per failure and is named in the finding",+ },+ {+ code: "store-dual-write-skipped",+ reason:+ "the store needs a device id this machine has not been given; choosing one is a decision " ++ "about how this machine is named among the user's devices, which no command can make for them",+ },+ {+ code: "store-root-invalid",+ reason:+ "the configured store root cannot be used (inside the vault, or holding partitions of two " ++ "stores); where the store should live, and which store is the real one, is the user's choice",+ },+ {+ code: "store-digest-divergent",+ reason:+ "two machines folded identical records into different state, which is a defect in the " ++ "release that computed one of them; repairing it by rewriting records would destroy the " ++ "evidence, so the finding asks for both store folders to be kept and the bug reported",+ },+ {+ code: "store-digest-silent",+ reason:+ "a device that stopped publishing digests is either offline, waiting for sync, or gone for " ++ "good; only the user knows which, and only a human device-retire record takes it off the roster",+ },+ {+ code: "store-record-id-conflict",+ reason:+ "a record id arrived with two different contents, so a shard was edited or a writer is " ++ "broken; every machine already keeps the same version, and deciding which content was " ++ "meant needs a person reading both",+ },+ {+ code: "store-dual-write-no-store",+ reason:+ "the skipped records never reached the store and no command can recreate them from the " ++ "legacy tree; creating the store stops new skips, and the counter is reset by deleting a " ++ "device-local file once the user has seen it",+ },+ {+ code: "store-clock-ahead",+ reason:+ "the records carry the clock of the device that wrote them; the fix is the clock of that " ++ "machine, which is outside the vault, and records already written are never rewritten",+ },+ {+ code: "store-device-dir-reserved",+ reason:+ "a peer machine's device id is a name Windows reserves for a device, so its shard folder " ++ "cannot exist on this Windows machine; the fix is that peer's device id, which is outside " ++ "this machine",+ },+ {+ code: "store-mode-loose",+ reason:+ "the looser mode was set outside Open Second Brain (a sync client, a restore, a manual " ++ "chmod); the finding names the exact chmod command, and changing permissions on the " ++ "user's files is left to the user",+ },+ {+ code: "store-record-id-cross-partition",+ reason:+ "a record id appears in both partitions, so a peer copied or forged a record; the index " ++ "keeps the first copy, and deciding which copy is genuine needs a person reading both",+ },+ {+ code: "store-shard-tail-held",+ reason:+ "the held bytes are the unfinished last line of another device's shard; only that device's " ++ "next append or a completed sync closes it, and no command on this machine can",+ },+ {+ code: "store-shard-unreadable",+ reason:+ "a shard file this machine holds could not be read (permissions, a disk error, a sync " ++ "client holding a lock); the cause is named in the finding and differs per machine",+ },+ {+ code: "store-partition-unreadable",+ reason:+ "a partition folder this machine holds could not be read (permissions, a disk error, a " ++ "sync client holding a lock); the cause is named in the finding and differs per machine",+ },// --- Judgements over content -------------------------------------------{code: "active-budget-pressure",diff --git a/src/core/brain/doctor.ts b/src/core/brain/doctor.tsindex 6ad73748..c5c2ba72 100644--- a/src/core/brain/doctor.ts+++ b/src/core/brain/doctor.ts@@ -95,6 +95,7 @@ import { removedToolReferenceCheck } from "./doctor/removed-tool-checks.ts";import { makeStaleDependencyCheck } from "./doctor/stale-dependency-check.ts";import { auditStaleDependencies } from "./stale-dependency.ts";import { frozenVaultCheck } from "./doctor/frozen-check.ts";+import { storeCheck } from "./doctor/store-check.ts";import { gitTrackedStateCheck } from "./doctor/git-tracked-state-check.ts";import { secretsSyncExposureCheck } from "./doctor/secrets-sync-check.ts";import { logChainCheck } from "./doctor/log-chain-check.ts";@@ -258,6 +259,8 @@ const DOCTOR_CHECKS: ReadonlyArray<DoctorCheck> = Object.freeze([rerankHealthCheck,payloadRegistryCheck,permissionsDocumentCheck,+ // The brain store section (task 1.11): silent unless the store is in use.+ storeCheck,denyConsultedLanesCheck,]);diff --git a/src/core/brain/doctor/store-check.ts b/src/core/brain/doctor/store-check.tsnew file mode 100644index 00000000..4a614f1f--- /dev/null+++ b/src/core/brain/doctor/store-check.ts@@ -0,0 +1,421 @@+/**+ * The brain store section of the doctor (design D6, task 1.11).+ *+ * Skipped silently when the store is not in use on this machine: the+ * dual-write flag is off and no store root is configured (neither the+ * `OPEN_SECOND_BRAIN_STORE_ROOT` variable nor the `store_root` config key).+ * A user who never opted in sees nothing, and the doctor's report stays+ * byte-identical to what it was before the store existed.+ *+ * When the store is in use it reports, all as warnings:+ *+ * - dual writes that failed or were skipped (the device-local counters+ * `store/dual-write.ts` keeps). The legacy writes were kept, so this is+ * a gap in the trial store, not lost data;+ * - no store at the root yet: writers never create one, so it says to run+ * `o2b store init`;+ * - a store root the configuration cannot use (inside the vault, or+ * partitions of different stores);+ * - state-digest findings (`checkStateDigests`): a fold that diverges+ * between machines over the same cut, and roster devices that have+ * published no digest for a week;+ * - record ids delivered with different content (`prepareRecords`), which+ * is tampering or a writer bug;+ * - records whose clock is more than the drift bound (`HLC_MAX_DRIFT_MS`)+ * ahead of now, per device with the newest stamp. They are still folded+ * and win "later clock" ties, so a broken clock on one machine shows up+ * here instead of silently outvoting the others;+ * - a held partition that cannot be read (the others are still checked),+ * and a shard that cannot be read, by its path: the partition's other+ * shards are still checked, but its digests are not compared (a cut+ * missing a shard would read as a false divergence), and when the+ * shard is in `shared` no partition reports silent devices, because+ * the device retirements may be in it;+ * - a shard whose last bytes have not verified for an hour: the reader+ * holds that tail back, so the record in it is read nowhere;+ * - what a synced peer can deliver (`store-trust-check.ts`): a record id+ * in both partitions, and store paths other local accounts can read.+ *+ * Read-only: it never creates the store or refreshes its format document.+ */++import { statSync } from "node:fs";+import { join } from "node:path";++import { STORE_PARTITIONS, type StorePartition } from "../../store/constants.ts";+import type { StoreRecord } from "../../store/envelope.ts";+import { compareHlc, formatHlc, HLC_MAX_DRIFT_MS, parseHlc, type Hlc } from "../../store/hlc.ts";+import { compareCodeUnits } from "../../store/compare.ts";+import { isDualWriteEnabled, readDualWriteStatus } from "../../store/dual-write.ts";+import { prepareRecords } from "../../store/fold.ts";+import { checkStateDigests } from "../../store/state-digest-check.ts";+import type { DigestFinding } from "../../store/state-digest-compare.ts";+import {+ readPartition,+ type PartitionShard,+ type UnreadableShard,+} from "../../store/state-digest.ts";+import { inspectStore, type StoreInspection } from "../../store/store-open.ts";+import {+ dualWriteStatusPath,+ isPathInsideResolved,+ partitionDir,+ resolveConfiguredStoreRoot,+ StoreRootInsideVaultError,+ type ResolvedStoreRoot,+} from "../../store/store-paths.ts";+import type { DoctorIssue } from "../types.ts";+import {+ crossPartitionIdIssues,+ looseModeIssues,+ reservedDeviceDirIssues,+} from "./store-trust-check.ts";+import type { DoctorCheck, DoctorCheckContext, DoctorFindings } from "./check.ts";++/** Dual writes failed; the legacy writes were kept. */+export const STORE_DUAL_WRITE_FAILURES_CODE = "store-dual-write-failures";+/** Dual writes were skipped because this machine has no device id. */+export const STORE_DUAL_WRITE_SKIPPED_CODE = "store-dual-write-skipped";+/** The configured store root cannot be used. */+export const STORE_ROOT_INVALID_CODE = "store-root-invalid";+/** A fold differs between machines over the same cut. */+export const STORE_DIGEST_DIVERGENT_CODE = "store-digest-divergent";+/** A roster device has published no state digest for a week. */+export const STORE_DIGEST_SILENT_CODE = "store-digest-silent";+/** One record id was delivered with different content. */+export const STORE_RECORD_ID_CONFLICT_CODE = "store-record-id-conflict";+/** A partition this machine holds could not be read. */+export const STORE_PARTITION_UNREADABLE_CODE = "store-partition-unreadable";+/** One shard of a held partition could not be read; the rest were checked. */+export const STORE_SHARD_UNREADABLE_CODE = "store-shard-unreadable";+/** A shard's last bytes have not verified for a long time, so its last record is read nowhere. */+export const STORE_SHARD_TAIL_HELD_CODE = "store-shard-tail-held";+/** No store exists at the root; `o2b store init` creates one. */+export const STORE_MISSING_CODE = "store-missing";+/** Dual writes were skipped because no store existed. */+export const STORE_DUAL_WRITE_NO_STORE_CODE = "store-dual-write-no-store";+/** Records carry a clock more than the drift bound ahead of now. */+export const STORE_CLOCK_AHEAD_CODE = "store-clock-ahead";++/** Age after which a held-back shard tail is no longer an append or a sync in progress. */+export const HELD_TAIL_STALE_MS = 60 * 60 * 1000;++/** Conflicting ids named in one finding before the rest are only counted. */+const CONFLICT_SAMPLE = 5;++function warn(out: DoctorFindings, code: string, message: string, path?: string): void {+ out.issues.push({+ severity: "warning",+ code,+ ...(path !== undefined ? { path } : {}),+ message,+ } satisfies DoctorIssue);+}++function dualWriteFindings(out: DoctorFindings): void {+ const path = dualWriteStatusPath();+ const status = readDualWriteStatus(path);+ if (status.failures > 0) {+ warn(+ out,+ STORE_DUAL_WRITE_FAILURES_CODE,+ `${status.failures} brain store dual write(s) failed on this machine` ++ (status.last_failure_at !== null ? `, the last at ${status.last_failure_at}` : "") ++ (status.last_error !== null ? ` (${status.last_error})` : "") ++ "; the legacy writes were kept, so the store is missing those records. " ++ "Fix the cause, then delete the counter file to reset it",+ path,+ );+ }+ if (status.skipped_no_device > 0) {+ warn(+ out,+ STORE_DUAL_WRITE_SKIPPED_CODE,+ `${status.skipped_no_device} brain store dual write(s) were skipped because this machine ` ++ "has no device id; set device_id in the machine config (and leave O2B_DEVICE_ID unset " ++ "or set it to a real id) so the store can name this device's shards",+ path,+ );+ }+ if (status.skipped_no_store > 0) {+ warn(+ out,+ STORE_DUAL_WRITE_NO_STORE_CODE,+ `${status.skipped_no_store} brain store dual write(s) were skipped because no store ` ++ "existed; the legacy writes were kept, so the store is missing those records. " ++ "Run `o2b store init` if it has not been run, then delete the counter file to reset it",+ path,+ );+ }+}++/** Records more than the drift bound ahead of `nowMs`, per device: count and newest stamp. */+function clockAheadByDevice(+ records: ReadonlyArray<StoreRecord>,+ nowMs: number,+): Map<string, { count: number; newest: Hlc }> {+ const out = new Map<string, { count: number; newest: Hlc }>();+ for (const record of records) {+ const stamp = parseHlc(record.hlc);+ if (stamp === null || stamp.physical - nowMs <= HLC_MAX_DRIFT_MS) continue;+ const seen = out.get(record.device);+ if (seen === undefined) out.set(record.device, { count: 1, newest: stamp });+ else {+ seen.count += 1;+ if (compareHlc(stamp, seen.newest) > 0) seen.newest = stamp;+ }+ }+ return out;+}++function clockAheadFinding(+ out: DoctorFindings,+ partition: string,+ path: string,+ ahead: Map<string, { count: number; newest: Hlc }>,+): void {+ if (ahead.size === 0) return;+ const total = [...ahead.values()].reduce((sum, d) => sum + d.count, 0);+ const devices = [...ahead]+ .toSorted(([a], [b]) => compareCodeUnits(a, b))+ .map(+ ([device, d]) =>+ `${device} (${d.count}, newest ${formatHlc(d.newest)} = ` ++ `${new Date(d.newest.physical).toISOString()})`,+ )+ .join(", ");+ warn(+ out,+ STORE_CLOCK_AHEAD_CODE,+ `${total} record(s) in the ${partition} partition carry a clock more than ` ++ `${HLC_MAX_DRIFT_MS / 3_600_000} hours ahead of now: ${devices}. They are still folded and ` ++ "win ties on the later clock; fix the clock of the named device",+ path,+ );+}++function digestMessage(finding: DigestFinding): string {+ if (finding.kind === "divergent") {+ const devices = finding.devices.map((d) => `${d.device} (${d.hash.slice(0, 12)})`).join(", ");+ return (+ `the ${finding.fold} fold of the ${finding.partition} partition differs between devices ` ++ `that read the same records (cut ${finding.cutHash.slice(0, 12)}): ${devices}. ` ++ "Two machines computed different state from identical input, which is a fold bug; " ++ "keep both machines' store folders as they are and report it"+ );+ }+ const last =+ finding.lastDigestMs === null+ ? "has never published one"+ : `last published one at ${new Date(finding.lastDigestMs).toISOString()}`;+ return (+ `device ${finding.device} has written to the ${finding.partition} partition but ${last}; ` ++ "its state cannot be compared until it catches up. If the machine is gone for good, " ++ "retire it with a human device-retire record"+ );+}++/**+ * Read every partition this machine holds, once, for every check below. A+ * shard that cannot be read is reported by its path and left out; the+ * other shards are still checked. Returns the shards read and the+ * partitions read in full.+ */+function readHeldPartitions(+ store: StoreInspection,+ out: DoctorFindings,+): { shards: Map<StorePartition, PartitionShard[]>; complete: Set<StorePartition> } {+ const shards = new Map<StorePartition, PartitionShard[]>();+ const complete = new Set<StorePartition>();+ for (const partition of STORE_PARTITIONS) {+ if (!store.partitions.has(partition)) continue;+ const dir = partitionDir(store.root, partition);+ // In `shared` the device retirements live, which every partition's+ // roster applies: without them a retired device would read as silent.+ const retirements =+ partition === "shared"+ ? "; device retirements could not all be read, so no partition reports silent devices"+ : "";+ const unreadable: UnreadableShard[] = [];+ try {+ shards.set(partition, readPartition(dir, { onUnreadable: (s) => unreadable.push(s) }));+ } catch (err) {+ warn(+ out,+ STORE_PARTITION_UNREADABLE_CODE,+ `the ${partition} partition could not be read (` ++ (err instanceof Error ? err.message : String(err)) ++ `); its digests and record ids were not checked${retirements}`,+ dir,+ );+ continue;+ }+ for (const shard of unreadable) {+ warn(+ out,+ STORE_SHARD_UNREADABLE_CODE,+ `the shard ${shard.rel} in the ${partition} partition could not be read (` ++ (shard.error instanceof Error ? shard.error.message : String(shard.error)) ++ "), for example while a sync client holds it; the partition's digests were not " ++ `compared, and its other shards were still checked${retirements}`,+ shard.path,+ );+ }+ if (unreadable.length === 0) complete.add(partition);+ }+ return { shards, complete };+}++/**+ * Shards whose last bytes have not verified for {@link HELD_TAIL_STALE_MS}:+ * the reader holds such a tail back, so the record in it reaches no index+ * and no fold on any machine. A tail still being written or synced is+ * younger than that.+ */+function heldTailFindings(+ store: StoreInspection,+ shards: ReadonlyMap<StorePartition, ReadonlyArray<PartitionShard>>,+ nowMs: number,+ out: DoctorFindings,+): void {+ for (const [partition, own] of shards) {+ for (const shard of own) {+ if (shard.heldTailBytes === 0) continue;+ const path = join(partitionDir(store.root, partition), ...shard.rel.split("/"));+ let mtimeMs: number;+ try {+ mtimeMs = statSync(path).mtimeMs;+ } catch {+ continue; // gone since the read: nothing held any more+ }+ if (nowMs - mtimeMs < HELD_TAIL_STALE_MS) continue;+ warn(+ out,+ STORE_SHARD_TAIL_HELD_CODE,+ `the last ${shard.heldTailBytes} byte(s) of the shard ${shard.rel} in the ${partition} ` ++ `partition have not verified since ${new Date(mtimeMs).toISOString()}, so no machine ` ++ "reads the record there. A crash in the middle of an append or a damaged sync copy " ++ `leaves such a tail; the next append by device ${shard.device} starts on a new line, ` ++ "and the tail is then counted as a corrupt line",+ path,+ );+ }+ }+}++function storeFindings(store: StoreInspection, ctx: DoctorCheckContext, out: DoctorFindings): void {+ const nowMs = ctx.now.getTime();+ const { shards, complete } = readHeldPartitions(store, out);+ // Digests are compared only over partitions read in full: a cut with a+ // shard missing would read as a divergence that is not there.+ const digestShards = new Map([...shards].filter(([partition]) => complete.has(partition)));+ const retirementsKnown = !store.partitions.has("shared") || complete.has("shared");+ const report = checkStateDigests(store, { now: () => nowMs, shards: digestShards });+ for (const finding of report.findings) {+ if (finding.kind === "silent" && !retirementsKnown) continue;+ warn(+ out,+ finding.kind === "divergent" ? STORE_DIGEST_DIVERGENT_CODE : STORE_DIGEST_SILENT_CODE,+ digestMessage(finding),+ partitionDir(store.root, finding.partition),+ );+ }+ heldTailFindings(store, shards, nowMs, out);+ out.issues.push(...crossPartitionIdIssues(store, shards));+ out.issues.push(...looseModeIssues(store));+ out.issues.push(...reservedDeviceDirIssues(store));+ for (const [partition, own] of shards) {+ const records = own.flatMap((s) => s.all);+ clockAheadFinding(+ out,+ partition,+ partitionDir(store.root, partition),+ clockAheadByDevice(records, nowMs),+ );+ const { conflicts } = prepareRecords(records);+ if (conflicts.length === 0) continue;+ const sample = conflicts+ .slice(0, CONFLICT_SAMPLE)+ .map((c) => `${c.id} (${c.versions} versions)`)+ .join(", ");+ const more =+ conflicts.length > CONFLICT_SAMPLE ? ` and ${conflicts.length - CONFLICT_SAMPLE} more` : "";+ warn(+ out,+ STORE_RECORD_ID_CONFLICT_CODE,+ `${conflicts.length} record id(s) in the ${partition} partition were delivered with ` ++ `different content: ${sample}${more}. Every machine keeps the same version, but a record ` ++ "should never change after it is written: look for an edited shard file or a writer bug",+ partitionDir(store.root, partition),+ );+ }+}++/** Whether this machine uses the store: the flag is on or a root is configured. */+function storeInUse(+ ctx: DoctorCheckContext,+ root: ResolvedStoreRoot | null,+ rootError: unknown,+): boolean {+ if (isDualWriteEnabled(ctx.configPath)) return true;+ if (root !== null) return root.origin !== "default";+ // The resolver refused the root: in use only when the user configured one.+ return rootError instanceof StoreRootInsideVaultError && rootError.origin !== "default";+}++export const storeCheck: DoctorCheck = {+ failSoft: true,+ run(ctx: DoctorCheckContext, out: DoctorFindings): void {+ let root: ResolvedStoreRoot | null = null;+ let rootError: unknown = null;+ try {+ root = resolveConfiguredStoreRoot(ctx.configPath);+ // The vault this pass checks may not be the configured one; a root+ // inside it is just as wrong.+ if (isPathInsideResolved(root.root, ctx.vault, process.platform)) {+ rootError = new StoreRootInsideVaultError(root.root, ctx.vault, root.origin);+ }+ } catch (err) {+ rootError = err;+ }+ if (!storeInUse(ctx, root, rootError)) return;++ dualWriteFindings(out);+ if (rootError !== null || root === null) {+ warn(+ out,+ STORE_ROOT_INVALID_CODE,+ rootError instanceof Error ? rootError.message : String(rootError),+ );+ return;+ }+ let store: StoreInspection | null;+ try {+ store = inspectStore(root.root);+ } catch (err) {+ warn(+ out,+ STORE_ROOT_INVALID_CODE,+ err instanceof Error ? err.message : String(err),+ root.root,+ );+ return;+ }+ if (store === null) {+ // With dual writes off nothing is skipped, so a root that holds no+ // store yet is not a finding (a configured root may be prepared+ // before the flag is turned on).+ if (!isDualWriteEnabled(ctx.configPath)) return;+ warn(+ out,+ STORE_MISSING_CODE,+ `there is no brain store at ${root.root} yet, so dual writes are skipped. Run ` ++ "`o2b store init` on the first machine (`--partitions shared` on a machine that must " ++ "not hold private records); other machines receive the partitions through sync",+ root.root,+ );+ return;+ }+ storeFindings(store, ctx, out);+ },+};diff --git a/src/core/brain/doctor/store-trust-check.ts b/src/core/brain/doctor/store-trust-check.tsnew file mode 100644index 00000000..c7f21174--- /dev/null+++ b/src/core/brain/doctor/store-trust-check.ts@@ -0,0 +1,200 @@+/**+ * Doctor findings about what a synced peer can deliver into the brain+ * store, part of the store section (`store-check.ts`):+ *+ * - a record id found in both partitions. Records never move between+ * partitions, so one of the copies was put there by a peer or a broken+ * writer; the search index keeps the first copy it read and refuses the+ * other (`search/brain-store/ingest.ts`);+ * - a store directory or file whose permissions let other local accounts+ * read it (POSIX only). The store creates directories `0700` and files+ * `0600`; a looser mode comes from an older build, a restore, or a sync+ * tool that applied its own permissions. The format document is left+ * out: it is readable on purpose and holds no record;+ * - on Windows, a device directory named like a Windows device (`nul`,+ * `con`, ...). A POSIX peer may hold such an id; on Windows the name+ * is a device, so the shard listings skip that directory and its+ * records are not read on this machine.+ *+ * Read-only: it never changes a mode or a file.+ */++import { lstatSync, readdirSync } from "node:fs";+import { join } from "node:path";++import { isValidDeviceId, isWindowsReservedDeviceId } from "../../config.ts";+import {+ LEDGER_STREAM,+ STORE_FORMAT_FILE,+ STORE_PARTITIONS,+ STORE_STREAMS,+ type StorePartition,+} from "../../store/constants.ts";+import type { PartitionShard } from "../../store/state-digest.ts";+import type { StoreInspection } from "../../store/store-open.ts";+import { partitionDir } from "../../store/store-paths.ts";+import type { DoctorIssue } from "../types.ts";++/** One record id was found in both partitions. */+export const STORE_RECORD_ID_CROSS_PARTITION_CODE = "store-record-id-cross-partition";+/** A store directory or file grants other local accounts access. */+export const STORE_MODE_LOOSE_CODE = "store-mode-loose";++/** On Windows, a device directory whose name Windows reserves for a device. */+export const STORE_DEVICE_DIR_RESERVED_CODE = "store-device-dir-reserved";++/** Ids or paths named in one finding before the rest are only counted. */+const SAMPLE = 5;++/** Permission bits the store never grants to the group or to others. */+const GROUP_OTHER_BITS = 0o077;++function sampled(items: ReadonlyArray<string>): string {+ const more = items.length > SAMPLE ? ` and ${items.length - SAMPLE} more` : "";+ return `${items.slice(0, SAMPLE).join(", ")}${more}`;+}++/** Record ids present in more than one partition this machine read. */+export function crossPartitionIdIssues(+ store: StoreInspection,+ shards: ReadonlyMap<StorePartition, ReadonlyArray<PartitionShard>>,+): DoctorIssue[] {+ const seen = new Map<string, StorePartition>();+ const twice: string[] = [];+ for (const partition of STORE_PARTITIONS) {+ const own = new Set<string>();+ for (const shard of shards.get(partition) ?? []) {+ for (const record of shard.all) own.add(record.id);+ }+ for (const id of own) {+ const first = seen.get(id);+ if (first === undefined) seen.set(id, partition);+ else if (first !== partition) twice.push(id);+ }+ }+ if (twice.length === 0) return [];+ return [+ {+ severity: "warning",+ code: STORE_RECORD_ID_CROSS_PARTITION_CODE,+ path: store.root,+ message:+ `${twice.length} record id(s) are in both the shared and the private partition: ` ++ `${sampled(twice)}. Records never move between partitions, so one copy was written by ` ++ "a peer or a broken writer; search keeps the first copy it read and ignores the other. " ++ "Find the shard that should not hold the id and remove that line",+ },+ ];+}++/** `value` single-quoted for a POSIX shell, an inner quote closed, escaped and reopened. */+function singleQuoted(value: string): string {+ return `'${value.replace(/'/g, "'\\''")}'`;+}++/** Paths under `dir` (itself included) whose mode grants group or other access. */+function loosePaths(dir: string, out: string[]): void {+ let stat;+ try {+ stat = lstatSync(dir);+ } catch {+ return;+ }+ if (stat.isSymbolicLink()) return;+ if ((stat.mode & GROUP_OTHER_BITS) !== 0) out.push(dir);+ if (!stat.isDirectory()) return;+ let names: string[];+ try {+ names = readdirSync(dir);+ } catch {+ return;+ }+ for (const name of names) {+ // The format document describes the format and holds no record; it is+ // written readable on purpose, inside a folder only the owner enters.+ if (name !== STORE_FORMAT_FILE) loosePaths(join(dir, name), out);+ }+}++/**+ * Held partitions whose directories or files grant other local accounts+ * access. Windows has no POSIX modes to check, so nothing is reported there.+ */+export function looseModeIssues(+ store: StoreInspection,+ platform: string = process.platform,+): DoctorIssue[] {+ if (platform === "win32") return [];+ const issues: DoctorIssue[] = [];+ for (const partition of STORE_PARTITIONS) {+ if (!store.partitions.has(partition)) continue;+ const dir = partitionDir(store.root, partition);+ const loose: string[] = [];+ loosePaths(dir, loose);+ if (loose.length === 0) continue;+ issues.push({+ severity: "warning",+ code: STORE_MODE_LOOSE_CODE,+ path: dir,+ message:+ `${loose.length} path(s) in the ${partition} partition grant other accounts on this ` ++ `machine access (group or other permission bits): ${sampled(loose)}. The store keeps ` ++ `its directories at 0700 and its files at 0600; run ` ++ `\`chmod -R go-rwx ${singleQuoted(dir)}\` to restore that`,+ });+ }+ return issues;+}++function dirNames(dir: string): string[] {+ try {+ return readdirSync(dir, { withFileTypes: true })+ .filter((entry) => entry.isDirectory())+ .map((entry) => entry.name);+ } catch {+ return [];+ }+}++/**+ * On Windows, device directories of held partitions named like a Windows+ * device (`nul`, `con`, ...): the shard listings skip them, so their+ * records are not read here. Elsewhere nothing is reported, because such a+ * name is read like any other device id.+ */+export function reservedDeviceDirIssues(+ store: StoreInspection,+ platform: string = process.platform,+): DoctorIssue[] {+ if (platform !== "win32") return [];+ const issues: DoctorIssue[] = [];+ for (const partition of STORE_PARTITIONS) {+ if (!store.partitions.has(partition)) continue;+ const root = partitionDir(store.root, partition);+ const reserved: string[] = [];+ for (const stream of STORE_STREAMS) {+ const streamDirs =+ stream === LEDGER_STREAM+ ? dirNames(join(root, stream)).map((ledger) => join(root, stream, ledger))+ : [join(root, stream)];+ for (const dir of streamDirs) {+ for (const name of dirNames(dir)) {+ if (isValidDeviceId(name) && isWindowsReservedDeviceId(name))+ reserved.push(join(dir, name));+ }+ }+ }+ if (reserved.length === 0) continue;+ issues.push({+ severity: "warning",+ code: STORE_DEVICE_DIR_RESERVED_CODE,+ path: root,+ message:+ `${reserved.length} device folder(s) in the ${partition} partition carry a name Windows ` ++ `reserves for a device: ${sampled(reserved)}. Windows cannot read them, so the records in ` ++ "them are left out on this machine. Give the device that wrote them another device_id " ++ "in its machine config",+ });+ }+ return issues;+}diff --git a/src/core/brain/dream-apply.ts b/src/core/brain/dream-apply.tsindex 04012b02..48f9dd3a 100644--- a/src/core/brain/dream-apply.ts+++ b/src/core/brain/dream-apply.ts@@ -23,6 +23,7 @@* knows where that point is.*/+import type { Authority } from "../store/constants.ts";import { existsSync, mkdirSync } from "node:fs";import { basename } from "node:path";@@ -51,6 +52,13 @@ import {} from "./types.ts";import { renameWithRetry } from "../fs-atomic.ts";+/**+ * The authority of every dream write under brain store dual writes: dream+ * is an automatic pass, so it decides as an agent even when an operator+ * started it from the CLI.+ */+const DREAM_AUTHORITY = "agent" satisfies Authority;+const DAY_MS = 24 * 3600 * 1000;/** Agent of record when the caller declared no name. */@@ -194,7 +202,7 @@ function writePreferences(input: DreamApplyInput, agent: string): void {...(np.visibility.length > 0 ? { visibility: np.visibility } : {}),},[],- { overwrite: false },+ { overwrite: false, authority: DREAM_AUTHORITY },historyOpts,);}@@ -233,7 +241,7 @@ function writePreferences(input: DreamApplyInput, agent: string): void {...(ct.owner ? { owner: ct.owner } : {}),},[],- { overwrite: false },+ { overwrite: false, authority: DREAM_AUTHORITY },historyOpts,);}@@ -290,7 +298,7 @@ function writePreferences(input: DreamApplyInput, agent: string): void {lenientScopeTags: true,},[],- { overwrite: true },+ { overwrite: true, authority: DREAM_AUTHORITY },historyOpts,);}@@ -376,6 +384,7 @@ function executeRetires(try {moveToRetired(vault, fromPath, r.reason, {now,+ authority: DREAM_AUTHORITY,retired_by: wikilinkToRun,...(r.supersededBy ? { superseded_by: r.supersededBy } : {}),});diff --git a/src/core/brain/entities/page-merge.ts b/src/core/brain/entities/page-merge.tsindex 0dd8fd9f..f8c4226b 100644--- a/src/core/brain/entities/page-merge.ts+++ b/src/core/brain/entities/page-merge.ts@@ -599,27 +599,31 @@ export function applyEntityMerge(const agent = opts.agent ?? "unknown";// Reliability audit record (the destructive-entity-verb template: the// hygiene audit directory under Brain/log/ carries week shards).- appendAuditRecord(join(brainDirsForWrite(vault).log, HYGIENE_AUDIT_DIR), {- timestamp: (opts.now ?? new Date()).toISOString(),- actor: agent,- action: "entity_merge",- target: plan.keep_id,- ok: true,- details: {- dropped: plan.drop_id,- category: plan.category,- alias_added: plan.alias_added ?? "",- // The full moved set, not just the display name: the aliases the- // dropped page held are nowhere else in the trail.- aliases_merged: JSON.stringify(plan.aliases_merged),- body_folded: String(plan.body_folded),- relations_absorbed: String(plan.relations_absorbed),- inbound_edges_retargeted: String(plan.inbound_edges_retargeted),- cyclic_edges_removed: String(plan.cyclic_edges_removed),- plan_hash: verified,- snapshot_run_id: gated.snapshot.runId,+ appendAuditRecord(+ join(brainDirsForWrite(vault).log, HYGIENE_AUDIT_DIR),+ {+ timestamp: (opts.now ?? new Date()).toISOString(),+ actor: agent,+ action: "entity_merge",+ target: plan.keep_id,+ ok: true,+ details: {+ dropped: plan.drop_id,+ category: plan.category,+ alias_added: plan.alias_added ?? "",+ // The full moved set, not just the display name: the aliases the+ // dropped page held are nowhere else in the trail.+ aliases_merged: JSON.stringify(plan.aliases_merged),+ body_folded: String(plan.body_folded),+ relations_absorbed: String(plan.relations_absorbed),+ inbound_edges_retargeted: String(plan.inbound_edges_retargeted),+ cyclic_edges_removed: String(plan.cyclic_edges_removed),+ plan_hash: verified,+ snapshot_run_id: gated.snapshot.runId,+ },},- });+ vault,+ );// Brain log event (the `merge` kind, entity payload), so the merge// surfaces in the activity timeline like every other lifecycle event.diff --git a/src/core/brain/git/store.ts b/src/core/brain/git/store.tsindex e3e21714..fc00a7fa 100644--- a/src/core/brain/git/store.ts+++ b/src/core/brain/git/store.ts@@ -41,6 +41,8 @@ import { atomicWriteFileSync } from "../../fs-atomic.ts";import { isFullSha } from "./reader.ts";import { acquireLockSyncWithRetry, ingestLockRemedy } from "../sync-lockfile.ts";import { assertVaultIdentityForWrite } from "../vault-identity.ts";+import { dualWrite } from "../../store/dual-write.ts";+import { DUAL_WRITE_LEDGERS, ledgerRowRecord } from "../../store/dual-write-records.ts";export interface GitCommitRecord {readonly kind: "commit";@@ -290,18 +292,47 @@ export function appendGitRecords(const handle = acquireLockSyncWithRetry(commitsPath(vault, repoKey), undefined, {remedy: ingestLockRemedy,});+ let result: LockedAppend;try {- return appendGitRecordsLocked(vault, repoKey, records);+ result = appendGitRecordsLocked(vault, repoKey, records);} finally {handle.release();}+ // Brain store dual write (task 1.11): off by default, never fails this+ // append, and run after the ingest lock is released so a bulk history+ // ingest does not hold it through one store append per line.+ if (result.lines.length > 0) {+ const lines = result.lines;+ dualWrite(+ () =>+ lines.map((line) =>+ ledgerRowRecord(+ DUAL_WRITE_LEDGERS.gitCommits,+ {+ repo_key: repoKey,+ record: JSON.parse(line) as unknown,+ },+ // Commit messages and paths can name private work.+ "private-when-held",+ ),+ ),+ { vault },+ );+ }+ return result.result;+}++/** What the locked append wrote: the outcome, and the lines it appended. */+interface LockedAppend {+ readonly result: AppendGitRecordsResult;+ readonly lines: ReadonlyArray<string>;}function appendGitRecordsLocked(vault: string,repoKey: string,records: ReadonlyArray<GitRecord>,-): AppendGitRecordsResult {+): LockedAppend {// Tag identity is (name, target): a RETARGETED tag (same name, new// commit after a force-move) appends a fresh record instead of being// silently dropped; listGitTags surfaces the latest record per name.@@ -325,7 +356,7 @@ function appendGitRecordsLocked(mkdirSync(gitStoreDir(vault, repoKey), { recursive: true });appendFileSync(commitsPath(vault, repoKey), lines.join(""));}- return { appended: lines.length, appendedCommits, appendedTags, skipped };+ return { result: { appended: lines.length, appendedCommits, appendedTags, skipped }, lines };}/** Commits oldest-first (file order, devices merged by commit time), optionally filtered. */diff --git a/src/core/brain/health/edit-history.ts b/src/core/brain/health/edit-history.tsindex 9777a3f3..7efe4374 100644--- a/src/core/brain/health/edit-history.ts+++ b/src/core/brain/health/edit-history.ts@@ -17,6 +17,9 @@ import { dirname } from "node:path";import { jsonlLedgerGrammar, readShardedLines } from "../ledger-shards.ts";import { preferenceHistoryPath, preferenceHistoryStem } from "../paths.ts";import { assertVaultIdentityForWrite } from "../vault-identity.ts";+import { dualWrite } from "../../store/dual-write.ts";+import { DUAL_WRITE_LEDGERS, ledgerRowRecord } from "../../store/dual-write-records.ts";+import { rowNamesPrivatePage } from "../../store/reference-privacy.ts";export interface EditHistoryEntry {/** ISO timestamp of the mutation. */@@ -90,15 +93,34 @@ export function appendEditHistory(const path = preferenceHistoryPath(vault, slug);const seen = new Set(readEditHistory(vault, slug).map(dedupKey));const lines: string[] = [];+ const appended: EditHistoryEntry[] = [];for (const e of entries) {const key = dedupKey(e);if (seen.has(key)) continue;seen.add(key);lines.push(JSON.stringify(e));+ appended.push(e);}if (lines.length === 0) return 0;mkdirSync(dirname(path), { recursive: true });appendFileSync(path, lines.join("\n") + "\n");+ // Brain store dual write (task 1.11): off by default, never fails this append.+ // A private preference's history rows stay out of the shared store+ // partition, as do rows about a preference whose page cannot be judged+ // and rows whose values name a private or unjudgeable page.+ dualWrite(+ () => {+ const prefPrivate = rowNamesPrivatePage(vault, `pref-${slug}`);+ return appended.map((entry) =>+ ledgerRowRecord(+ DUAL_WRITE_LEDGERS.editHistory,+ { slug, entry },+ prefPrivate || rowNamesPrivatePage(vault, entry) ? "private" : "shared",+ ),+ );+ },+ { vault },+ );return lines.length;}diff --git a/src/core/brain/hygiene/apply.ts b/src/core/brain/hygiene/apply.tsindex 6dd827d0..53eb8bcc 100644--- a/src/core/brain/hygiene/apply.ts+++ b/src/core/brain/hygiene/apply.ts@@ -248,18 +248,22 @@ export async function applyHygienePlan(}if (applied.length > 0 || errors.length > 0) {- appendAuditRecord(join(brainDirsForWrite(vault).log, HYGIENE_AUDIT_DIR), {- timestamp: opts.now.toISOString(),- actor: opts.agent,- action: "hygiene_apply",- target: "Brain",- ok: errors.length === 0,- details: {- applied: applied.length,- errors: errors.length,- actions: applied.map((action) => `${action.action}:${action.finding_id}`),+ appendAuditRecord(+ join(brainDirsForWrite(vault).log, HYGIENE_AUDIT_DIR),+ {+ timestamp: opts.now.toISOString(),+ actor: opts.agent,+ action: "hygiene_apply",+ target: "Brain",+ ok: errors.length === 0,+ details: {+ applied: applied.length,+ errors: errors.length,+ actions: applied.map((action) => `${action.action}:${action.finding_id}`),+ },},- });+ vault,+ );}return Object.freeze({diff --git a/src/core/brain/idempotency-ledger.ts b/src/core/brain/idempotency-ledger.tsindex e95c8969..202b4247 100644--- a/src/core/brain/idempotency-ledger.ts+++ b/src/core/brain/idempotency-ledger.ts@@ -51,6 +51,9 @@ import { BRAIN_ROOT_REL, ensureInsideVault } from "./paths.ts";import { acquireLockSync } from "./sync-lockfile.ts";import { isoSecond } from "./time.ts";import { assertVaultIdentityForWrite } from "./vault-identity.ts";+import { dualWrite } from "../store/dual-write.ts";+import { DUAL_WRITE_LEDGERS, ledgerRowRecord } from "../store/dual-write-records.ts";+import { rowNamesPrivatePage } from "../store/reference-privacy.ts";/** Month-sharded JSONL root, distinct from `Brain/log/` (the human trail). */const IDEMPOTENCY_REL = `${BRAIN_ROOT_REL}/logs/idempotency`;@@ -65,6 +68,22 @@ export const IDEMPOTENCY_GRAMMAR: LedgerShardGrammar = Object.freeze({extensions: Object.freeze([JSONL_LEDGER_EXT]),});+/**+ * Receipt fields whose values are opaque rather than page references: the+ * client key, its namespace, the payload hash, the timestamps, and the+ * write and review ids a write batch's results carry. The store copy's+ * privacy judge skips them (see {@link rememberKey}).+ */+const RECEIPT_OPAQUE_FIELDS: ReadonlySet<string> = new Set([+ "key",+ "namespace",+ "contentHash",+ "createdAt",+ "logged_at",+ "write_id",+ "pending_id",+]);+/** Hard cap on a client key. Long enough for `<session-id>:<slug>` joins. */const KEY_MAX_LEN = 256;@@ -103,6 +122,17 @@ export interface RememberKeyInput {* month shard, so a backfilled write lands in its real month. */readonly createdAt?: string;readonly ref?: Readonly<Record<string, unknown>>;+ /**+ * The privacy verdict of the operation the key guards+ * (`store/operation-privacy.ts`). Only the brain store copy reads it,+ * and when given it is final: the receipt lands where the operation's+ * other records land and is not judged again from its `ref`. Absent,+ * the receipt is judged from its own `ref`. A function is the verdict+ * judged lazily, inside the store copy's own dual write: it runs exactly+ * when that copy is written, under the flag that copy reads, so the+ * judge can never be skipped while the copy still lands.+ */+ readonly private?: boolean | (() => boolean);}export interface RememberKeyResult {@@ -233,6 +263,7 @@ export function rememberKey(vault: string, input: RememberKeyInput): RememberKeymkdirSync(join(vault, IDEMPOTENCY_REL), { recursive: true });const shardPath = idempotencyLogPath(vault, month);const handle = acquireLockSync(shardPath);+ let inserted: IdempotencyRecord | undefined;try {// Re-scan under the lock so a same-shard concurrent insert is caught.// The lock is on THIS device's shard - the only file this call can@@ -256,9 +287,45 @@ export function rememberKey(vault: string, input: RememberKeyInput): RememberKey...(input.ref !== undefined ? { ref: input.ref } : {}),});writeFileSync(shardPath, `${JSON.stringify(record)}\n`, { encoding: "utf8", flag: "a" });+ inserted = record;return { status: REMEMBER_KEY_STATUS.inserted, record };} finally {handle.release();+ // Brain store dual write (task 1.11): off by default, never fails this+ // append, and run after the release so the store's own lock and fsync+ // never lengthen this ledger's critical section.+ if (inserted !== undefined) {+ const row = inserted;+ // A receipt that carries its operation's verdict follows it and is+ // never judged again: the operation fixed one partition for every+ // record it writes, and a second judge reading the vault later (a+ // page turned private in between) would split them. A receipt with+ // no verdict names the written item (its path, id or log entry) in+ // its `ref` and is judged from it: one whose references name a page+ // that is private or cannot be judged goes to `private` only. The+ // key, hash and timestamps are opaque and never judged as+ // references. Either way the dual-write entry point still raises a+ // receipt carrying a `<private>` region; a region inside an+ // operation's receipt is already in the content its verdict judged.+ const verdict = input.private;+ dualWrite(+ () =>+ ledgerRowRecord(+ DUAL_WRITE_LEDGERS.idempotency,+ row,+ (+ verdict === undefined+ ? rowNamesPrivatePage(vault, row, RECEIPT_OPAQUE_FIELDS)+ : typeof verdict === "function"+ ? verdict()+ : verdict+ )+ ? "private"+ : "shared",+ ),+ { vault },+ );+ }}}diff --git a/src/core/brain/import-claude-memory.ts b/src/core/brain/import-claude-memory.tsindex 9c079aa7..83f27cc5 100644--- a/src/core/brain/import-claude-memory.ts+++ b/src/core/brain/import-claude-memory.ts@@ -5,7 +5,7 @@ import { atomicWriteFileSync } from "../fs-atomic.ts";import { digestVerifies, sealWithDigest, sha256Hex } from "../integrity/digest.ts";import { appendLogEvent } from "./log.ts";import { BRAIN_LOG_EVENT_KIND, BRAIN_SNAPSHOT_REASON } from "./types.ts";-import { createSnapshot } from "./snapshot.ts";+import { takeSnapshot } from "./snapshot-gate.ts";import { isoSecond } from "./time.ts";import { loadBrainConfig } from "./policy.ts";import { DEFAULT_BRAIN_CONFIG } from "./policy/defaults.ts";@@ -382,14 +382,13 @@ export function importClaudeMemory(opts: ImportClaudeMemoryOpts): ImportClaudeMelet snapshotRunId: string | null = null;if (filesToWrite.length > 0) {- // The run-id prefix and the recorded reason are one constant, so the- // archive's filename can never disagree with its stamped provenance.- const runId = `${BRAIN_SNAPSHOT_REASON.importClaudeMemory}-${importedAt.replace(/:/g, "-")}`;- createSnapshot(opts.vault, runId, {- reason: BRAIN_SNAPSHOT_REASON.importClaudeMemory,+ // Through the gate rather than `createSnapshot`, so the archive obeys+ // `snapshots.retention_count` like every other reason (it used to+ // bypass retention). The gate derives the run id from the reason, so+ // the archive's filename still cannot disagree with its provenance.+ snapshotRunId = takeSnapshot(opts.vault, BRAIN_SNAPSHOT_REASON.importClaudeMemory, {now,- });- snapshotRunId = runId;+ }).runId;}const applied: PlannedFile[] = [];diff --git a/src/core/brain/lineage/ledger.ts b/src/core/brain/lineage/ledger.tsindex 604c266f..0ae8fc4b 100644--- a/src/core/brain/lineage/ledger.ts+++ b/src/core/brain/lineage/ledger.ts@@ -89,6 +89,8 @@ import { BRAIN_ROOT_REL, ensureInsideVault } from "../paths.ts";import { acquireLockSync, type LockHandle, removeStaleLockSync } from "../sync-lockfile.ts";import { assertVaultIdentityForWrite, VaultIdentityMismatchError } from "../vault-identity.ts";import type { SessionLineage } from "./types.ts";+import { dualWrite } from "../../store/dual-write.ts";+import { DUAL_WRITE_LEDGERS, ledgerRowRecord } from "../../store/dual-write-records.ts";/** Crutch link window: a continuation must start this close to the* predecessor's compression evidence. CRUTCH(t_1459706f). */@@ -917,6 +919,7 @@ export function recordLineageObservation(}let handle: LockHandle | undefined;+ let appended: LedgerLine | undefined;try {const path = sessionLineageLedgerPath(vault);mkdirSync(dirname(path), { recursive: true });@@ -960,14 +963,29 @@ export function recordLineageObservation(const retained = entries.slice(-RETAIN_LEDGER_LINES).map((entry) => entry.raw);retained.push(serialized);atomicWriteFileSync(path, `${retained.join("\n")}\n`);+ appended = line;return { status: LINEAGE_RECORD_STATUS.appended, seq, compacted: true };}appendFileSync(path, `${serialized}\n`, "utf8");+ appended = line;return { status: LINEAGE_RECORD_STATUS.appended, seq };} catch {return recordGap(vault, obs, LINEAGE_GAP_REASON.writeFailed);} finally {handle?.release();+ // Brain store dual write (task 1.11): the new line only (the store never+ // compacts it away), off by default and never failing this append. It+ // runs after the release: this lock is taken without a retry, so every+ // millisecond the store's own lock and fsync held it would turn a+ // concurrent observation into a lockBusy gap.+ if (appended !== undefined) {+ const row = appended;+ // Lineage says which sessions ran where (working directories, repos,+ // branches): it goes to `private` when this machine holds it.+ dualWrite(() => ledgerRowRecord(DUAL_WRITE_LEDGERS.lineage, row, "private-when-held"), {+ vault,+ });+ }}}diff --git a/src/core/brain/log-append-io.ts b/src/core/brain/log-append-io.tsnew file mode 100644index 00000000..b66c3595--- /dev/null+++ b/src/core/brain/log-append-io.ts@@ -0,0 +1,272 @@+/**+ * Append-only file I/O for the Brain log shards (`log.ts`).+ *+ * The appender used to read a whole day shard and rewrite it through a+ * temp file and a rename for every event, which cost the size of the day+ * file per event. This module gives it the two primitives an append+ * needs instead, both bounded by the size of the file's TAIL:+ *+ * - {@link scanLinesFromEnd} walks a file's lines backwards in chunks+ * and stops at the first line the caller accepts, so the hash chain+ * finds its predecessor without reading the day.+ * - {@link appendSeparated} adds one block with exactly the bytes the+ * old rewrite produced (`trimEnd(existing) + separator + block`),+ * reading only the trailing whitespace. In the normal case that is a+ * single write on a descriptor opened with the append flag; only an+ * unusual whitespace tail (blank lines an editor left) is trimmed in+ * place with a truncate first.+ *+ * Callers hold the log directory lock (`acquireLogLock`); nothing here+ * locks. A write that fails part way is undone (the file is cut back to+ * the bytes it had), so a full disk leaves the shard as it was rather than+ * with a torn row. Durability matches the atomic writer the appender used before:+ * the file is fsynced after the write, and the parent directory is+ * fsynced best-effort when the write created the file.+ */++import {+ closeSync,+ fstatSync,+ fsyncSync,+ ftruncateSync,+ openSync,+ readSync,+ truncateSync,+ writeSync,+} from "node:fs";+import { dirname } from "node:path";++const NEWLINE = 0x0a;+/** Bytes read per backward step; one chunk holds many log rows. */+const TAIL_CHUNK_BYTES = 64 * 1024;+/** Bytes inspected for trailing whitespace before falling back to a full read. */+const WHITESPACE_PROBE_BYTES = 4 * 1024;++function readAt(fd: number, position: number, length: number): Buffer {+ const buf = Buffer.alloc(length);+ let read = 0;+ while (read < length) {+ const n = readSync(fd, buf, read, length - read, position + read);+ if (n === 0) break;+ read += n;+ }+ return read === length ? buf : buf.subarray(0, read);+}++function writeAll(fd: number, data: Buffer, position: number | null): void {+ let written = 0;+ while (written < data.byteLength) {+ written += writeSync(+ fd,+ data,+ written,+ data.byteLength - written,+ position === null ? null : position + written,+ );+ }+}++/**+ * Write `data` at `position` (or at the end, for `null`) and fsync. When+ * the write or the fsync fails (a full disk, an I/O error), the file is+ * cut back to `restoreSize` bytes and `restoreTail` is written after them,+ * best effort, before the error is rethrown: a write that stopped half way+ * must not leave a torn row in the shard that every later read and the+ * hash-chain check would then see as damage.+ */+function writeOrRestore(+ path: string,+ fd: number,+ data: Buffer,+ position: number | null,+ restoreSize: number,+ restoreTail: Buffer = Buffer.alloc(0),+): void {+ try {+ writeAll(fd, data, position);+ fsyncSync(fd);+ } catch (err) {+ try {+ try {+ ftruncateSync(fd, restoreSize);+ } catch {+ // A descriptor opened for appending may not truncate (Windows+ // grants it append access only); the path can.+ truncateSync(path, restoreSize);+ }+ if (restoreTail.byteLength > 0) writeAll(fd, restoreTail, restoreSize);+ fsyncSync(fd);+ } catch {+ // Best effort: the original error is the one the caller must see.+ }+ throw err;+ }+}++/** Open for reading, or `null` when the file does not exist. */+function openForRead(path: string): number | null {+ try {+ return openSync(path, "r");+ } catch (err) {+ if ((err as NodeJS.ErrnoException).code === "ENOENT") return null;+ throw err;+ }+}++/**+ * Visit the lines of `path` from the last to the first, decoded as+ * UTF-8, and return the first non-`null` answer `visit` gives. A final+ * line without a trailing newline is still a line, exactly as+ * `text.split(/\r?\n/)` would yield it; a trailing `\r` is dropped.+ * Returns `null` for a missing or empty file or when no line answers.+ *+ * Splitting happens on the raw `\n` byte, which never occurs inside a+ * multi-byte UTF-8 sequence, so a chunk boundary cannot corrupt a line.+ */+export function scanLinesFromEnd<T>(path: string, visit: (line: string) => T | null): T | null {+ const fd = openForRead(path);+ if (fd === null) return null;+ try {+ let position = fstatSync(fd).size;+ // The bytes after the last newline seen so far, as the chunks that hold+ // them (front first). They hold no newline, so only a freshly read chunk+ // is ever scanned, and they are joined once, when their line is visited:+ // a long line costs its length, not its length squared.+ let carry: Buffer[] = [];+ while (position > 0) {+ const size = Math.min(TAIL_CHUNK_BYTES, position);+ position -= size;+ const chunk = readAt(fd, position, size);+ let end = chunk.length;+ for (let i = chunk.length - 1; i >= 0; i--) {+ if (chunk[i] !== NEWLINE) continue;+ const head = chunk.subarray(i + 1, end);+ const line = carry.length > 0 ? Buffer.concat([head, ...carry]) : head;+ const answer = visitSegment(line, 0, line.length, visit);+ if (answer !== null) return answer;+ carry = [];+ end = i;+ }+ // Everything before the first newline may continue in the previous chunk.+ if (end > 0) carry.unshift(chunk.subarray(0, end));+ }+ if (carry.length === 0) return null;+ const first = Buffer.concat(carry);+ return visitSegment(first, 0, first.length, visit);+ } finally {+ closeSync(fd);+ }+}++function visitSegment<T>(+ buf: Buffer,+ start: number,+ end: number,+ visit: (line: string) => T | null,+): T | null {+ let stop = end;+ if (stop > start && buf[stop - 1] === 0x0d) stop--;+ return visit(buf.toString("utf8", start, stop));+}++/** Trailing whitespace of the file as `/\s+$/` sees it, and its byte length. */+function trailingWhitespace(fd: number, size: number): { text: string; bytes: number } {+ let probe = Math.min(WHITESPACE_PROBE_BYTES, size);+ for (;;) {+ const tail = readAt(fd, size - probe, probe).toString("utf8");+ const text = /\s+$/.exec(tail)?.[0] ?? "";+ // A probe that is whitespace all the way back may have cut the run+ // short; widen it until the run ends inside the probe or the file does.+ if (text.length < tail.length || probe === size) {+ return { text, bytes: Buffer.byteLength(text, "utf8") };+ }+ probe = Math.min(probe * 4, size);+ }+}++function fsyncDirBestEffort(path: string): void {+ try {+ const dfd = openSync(dirname(path), "r");+ try {+ fsyncSync(dfd);+ } finally {+ closeSync(dfd);+ }+ } catch {+ // Directory fsync is a best-effort durability step; some platforms refuse it.+ }+}++/**+ * Append `block` to `path` so the file ends up byte-identical to+ * `existing.replace(/\s+$/, "") + separator + block`, or to `initial`+ * when the file is missing or empty.+ *+ * The trailing whitespace already on disk decides the write: when it is+ * a prefix of `separator` (the shape every append leaves), the missing+ * rest of the separator and the block go out in one append. Any other+ * whitespace tail is truncated away first, then the separator and block+ * are written in its place. Nothing before the trailing whitespace is+ * ever read or rewritten.+ */+export function appendSeparated(+ path: string,+ block: string,+ separator: string,+ initial: string,+): void {+ const readFd = openForRead(path);+ let size = 0;+ let whitespace = { text: "", bytes: 0 };+ if (readFd !== null) {+ try {+ size = fstatSync(readFd).size;+ if (size > 0) whitespace = trailingWhitespace(readFd, size);+ } finally {+ closeSync(readFd);+ }+ }++ if (size === 0) {+ const fd = openSync(path, "a");+ try {+ writeOrRestore(path, fd, Buffer.from(initial, "utf8"), null, 0);+ } finally {+ closeSync(fd);+ }+ fsyncDirBestEffort(path);+ return;+ }++ if (separator.startsWith(whitespace.text)) {+ const fd = openSync(path, "a");+ try {+ writeOrRestore(+ path,+ fd,+ Buffer.from(separator.slice(whitespace.text.length) + block, "utf8"),+ null,+ size,+ );+ } finally {+ closeSync(fd);+ }+ return;+ }++ const keep = size - whitespace.bytes;+ const fd = openSync(path, "r+");+ try {+ ftruncateSync(fd, keep);+ writeOrRestore(+ path,+ fd,+ Buffer.from(separator + block, "utf8"),+ keep,+ keep,+ Buffer.from(whitespace.text, "utf8"),+ );+ } finally {+ closeSync(fd);+ }+}diff --git a/src/core/brain/log.ts b/src/core/brain/log.tsindex 9756befd..827dc970 100644--- a/src/core/brain/log.ts+++ b/src/core/brain/log.ts@@ -20,9 +20,11 @@* file is absent, it is created with a canonical frontmatter* header (`kind: brain-log`, `date`, `tags`) and the title line.* Subsequent appends preserve previous bytes verbatim β the- * log is append-only. Atomicity is achieved by reading the- * existing contents, appending the new block, and writing the- * result back through `fs-atomic` in one shot.+ * log is append-only. Each event is ONE append per file under the+ * log directory lock (`log-append-io.ts`): the appender reads only+ * the shard's tail (the previous chain link, the trailing+ * whitespace), never the whole day, which it used to read and+ * rewrite through a temp file for every event.** Every appended event carries an `origin_channel` bullet beside the* `agent` one: the server-derived channel of the process that wrote it@@ -40,9 +42,7 @@import { existsSync, mkdirSync, readFileSync } from "node:fs";-import lockfile from "proper-lockfile";--import { atomicWriteFileSync } from "../fs-atomic.ts";+import { appendSeparated, scanLinesFromEnd } from "./log-append-io.ts";import { canonicalJson, sha256Hex } from "../integrity/digest.ts";import {brainDirs,@@ -55,6 +55,11 @@ import {import { WRITE_LANE } from "./freeze-marker.ts";import { isValidDeviceId } from "../config.ts";import { listShardedFiles, resolveAppendShardId } from "./ledger-shards.ts";+import { dualWrite } from "../store/dual-write.ts";+import { acquireDirLock } from "../store/local-lock.ts";+import { logEventRecord } from "../store/dual-write-records.ts";+import { operationPrivacy, type PrivacyVerdict } from "../store/operation-privacy.ts";+import { logRefsNamePrivatePage } from "../store/reference-privacy.ts";import { ORIGIN_CHANNEL_FIELD, originChannelStamp } from "../origin-channel.ts";import { BRAIN_LOG_EVENT_KIND, BRAIN_LOG_EVENT_KIND_SET, type BrainLogEventKind } from "./types.ts";import { PREF_ID_PREFIX } from "./dream-plan.ts";@@ -273,40 +278,38 @@ export function parseLogDayFile(vault: string, date: string, path: string): Pars* this function. That's the stability guarantee the test suite asks* for.*/+/** Longest wait for the log directory lock before an append gives up. */+export const LOG_LOCK_WAIT_MS = 2_000;+/**- * Acquire the per-log-day directory lock with a bounded retry loop.+ * Acquire the per-log-day directory lock with a bounded wait.*- * `proper-lockfile`'s sync API refuses the `retries` option (it- * cannot block the event loop on a callback), so the retry loop is- * spelled out here: on `ELOCKED` the call sleeps for `SLEEP_MS` and- * tries again, up to `MAX_ATTEMPTS`. Any non-`ELOCKED` error is- * rethrown immediately (permission, fs corruption, β¦).+ * `proper-lockfile`'s sync API refuses the `retries` option (it cannot+ * block the event loop on a callback), so the wait is spelled out in+ * `acquireDirLock` (`store/local-lock.ts`): jittered, growing sleeps+ * while the lock is held, up to {@link LOG_LOCK_WAIT_MS}, then an+ * `ELOCKED` refusal. A Windows lock directory still being deleted by the+ * previous holder counts as held, not as a permission error. Any other+ * error is rethrown immediately (permission, fs corruption, β¦).** Exported so the fixtures that reproduce log-lock contention hold the* SAME lock the appender takes (the attestation digest and verify* suites): if this site or its options move, the fixtures fail loudly* instead of silently reproducing nothing.*- * Total worst-case wait: `MAX_ATTEMPTS * SLEEP_MS` β 500 ms β short- * enough to feel synchronous to a coding agent, long enough to ride- * out a sibling `appendLogEvent` call that landed within the same- * millisecond.+ * Two seconds is short enough to feel synchronous to a coding agent and+ * long enough for a writer to get its turn among several agents+ * appending at once on a host whose fsync is slow (Windows), where a+ * fixed handful of 50 ms retries lost every round to the writers that+ * re-took the lock the moment they released it.*/export function acquireLogLock(logDir: string): () => void {- const MAX_ATTEMPTS = 10;- const SLEEP_MS = 50;- let lastErr: unknown;- for (let attempt = 0; attempt < MAX_ATTEMPTS; attempt++) {- try {- return lockfile.lockSync(logDir, { stale: 10_000, realpath: false });- } catch (err) {- const code = (err as NodeJS.ErrnoException).code;- if (code !== "ELOCKED") throw err;- lastErr = err;- if (attempt < MAX_ATTEMPTS - 1) Bun.sleepSync(SLEEP_MS);- }- }- throw lastErr;+ return acquireDirLock(logDir, {+ staleMs: 10_000,+ budgetMs: LOG_LOCK_WAIT_MS,+ label: "log lock",+ remedy: "another process is appending to the Brain log; retry the write",+ });}export interface AppendLogEventOptions {@@ -321,6 +324,32 @@ export interface AppendLogEventOptions {* Passing the empty string here forces the legacy pair explicitly.*/readonly deviceId?: string;+ /**+ * Brain store dual write: the privacy verdict of the operation this+ * event belongs to (`store/operation-privacy.ts`). A private verdict+ * sends the event's store record to `private` even when the event names+ * no private page; an event that names one goes there regardless.+ * Judged only when dual writes are on.+ */+ readonly storePrivate?: PrivacyVerdict;+}++/**+ * Fields of a log event body that are stamps rather than page references:+ * the server-derived origin channel. The writing `agent` is NOT opaque: a+ * caller supplies it as a free string, so it is judged like any other+ * field. An operation that judges the event it is about to append judges+ * its body with these same opaque fields ({@link logEventPrivacyContent}),+ * so its verdict covers the appender's own.+ */+export const LOG_EVENT_OPAQUE_FIELDS: ReadonlySet<string> = new Set([ORIGIN_CHANNEL_FIELD]);++/** A log event body as content an operation's privacy verdict judges. */+export function logEventPrivacyContent(body: Readonly<Record<string, unknown>>): {+ readonly value: unknown;+ readonly opaque: ReadonlySet<string>;+} {+ return { value: body, opaque: LOG_EVENT_OPAQUE_FIELDS };}export function appendLogEvent(@@ -400,40 +429,47 @@ export function appendLogEvent(// One row per event. The row is a deterministic projection of the// markdown body so the markdown and JSONL representations describe// the same event byte-for-byte after JSON.parse.- // The chain (Task E) costs nothing extra here: the shard's bytes are- // already in hand under the directory lock, so the link to the- // previous line is one backward scan of text this append had to read- // anyway. Holding the lock is also what makes the link CORRECT - two- // appenders reading the same head would otherwise write two lines- // claiming the same predecessor.- const existingJsonl = existsSync(jsonlPath) ? readFileSync(jsonlPath, "utf8") : "";- const line = renderJsonlLine(diskEvent, lastChainHash(existingJsonl));- const nextJsonl =- existingJsonl === "" ? `${line}\n` : `${existingJsonl.replace(/\s+$/, "")}\n${line}\n`;- atomicWriteFileSync(jsonlPath, nextJsonl);+ // The chain (Task E) needs only the previous link: the shard is read+ // backwards from its end and the scan stops at the newest line that+ // carries one, so the cost is the tail, not the day. Holding the lock+ // is what makes the link CORRECT - two appenders reading the same+ // head would otherwise write two lines claiming the same predecessor.+ //+ // A torn last line (a crash mid-append, no trailing newline) is+ // skipped by the head scan exactly as before, and `appendSeparated`+ // starts the new row on its own line, so the fragment stays one+ // malformed line the reader warns about instead of corrupting the+ // row written after it.+ const line = renderJsonlLine(diskEvent, scanLinesFromEnd(jsonlPath, chainHashOfLine));+ appendSeparated(jsonlPath, `${line}\n`, "\n", `${line}\n`);// ---- Markdown (human surface) -------------------------------------- const existing = existsSync(path) ? readFileSync(path, "utf8") : "";+ // One blank line between blocks and a single trailing newline, the+ // same bytes the former whole-file rewrite produced; the block always+ // ends in a newline, so the file always does too.const block = renderEventBlock(diskEvent, ts.hms);-- let next: string;- if (existing === "") {- next = renderFileHeader(ts.date) + "\n" + block;- } else {- // Guarantee exactly one blank line between blocks; previous file- // may or may not end with a trailing newline.- const trimmed = existing.replace(/\s+$/, "");- next = `${trimmed}\n\n${block}`;- }- // Always finish with a single trailing newline β standard Markdown- // hygiene, and matches what `formatFrontmatter` emits elsewhere.- if (!next.endsWith("\n")) next += "\n";-- atomicWriteFileSync(path, next);+ appendSeparated(path, block, "\n\n", renderFileHeader(ts.date) + "\n" + block);} finally {release();}+ // Brain store dual write (task 1.11): off by default, never fails this append.+ // An event that names a private page (a private preference's id and+ // principle, a private note's link, in any field and inside free text),+ // whose body carries a `<private>` region or the placeholder a stripped+ // one leaves, or that belongs to a private operation goes to `private`+ // only. A reconcile event's guessed preference is judged only when its+ // page exists (`logRefsNamePrivatePage`).+ const guessed = reconcileTopicPreferenceId(diskEvent);+ const isPrivate = operationPrivacy(vault, {+ inherit: [+ opts.storePrivate,+ () => guessed !== undefined && logRefsNamePrivatePage(vault, [guessed], guessed),+ ],+ content: [logEventPrivacyContent(diskEvent.body)],+ });+ dualWrite(() => logEventRecord(diskEvent, isPrivate()), { vault });+return { logPath: path };}@@ -574,21 +610,31 @@ export function logChainHash(function lastChainHash(jsonl: string): string | null {const lines = jsonl.split(/\r?\n/);for (let i = lines.length - 1; i >= 0; i--) {- const line = lines[i]!;- if (line.trim() === "") continue;- let parsed: unknown;- try {- parsed = JSON.parse(line);- } catch {- continue;- }- if (parsed === null || typeof parsed !== "object") continue;- const h = (parsed as Record<string, unknown>)[LOG_CHAIN_FIELDS.h];- if (typeof h === "string" && h !== "") return h;+ const h = chainHashOfLine(lines[i]!);+ if (h !== null) return h;}return null;}+/**+ * The chain hash one JSONL line carries, or `null` for a blank, an+ * unparseable or a pre-chain line. The per-line rule of+ * {@link lastChainHash}, shared with the appender's backward file scan+ * so the two can never disagree about which line is the head.+ */+function chainHashOfLine(line: string): string | null {+ if (line.trim() === "") return null;+ let parsed: unknown;+ try {+ parsed = JSON.parse(line);+ } catch {+ return null;+ }+ if (parsed === null || typeof parsed !== "object") return null;+ const h = (parsed as Record<string, unknown>)[LOG_CHAIN_FIELDS.h];+ return typeof h === "string" && h !== "" ? h : null;+}+/*** The JSONL-only half of the log's shard grammar, for the head collector* below. The recogniser itself lives in `ledger-shards.ts` like everydiff --git a/src/core/brain/maintenance/journal.ts b/src/core/brain/maintenance/journal.tsindex e38417d3..1c76f49e 100644--- a/src/core/brain/maintenance/journal.ts+++ b/src/core/brain/maintenance/journal.ts@@ -28,6 +28,9 @@ import type { StorageForecastTier } from "../storage/forecast.ts";import type { HostPressureUnmeasurableReason } from "./host-pressure.ts";import { isCustomLaneTask } from "./custom-task-id.ts";import { renameWithRetry } from "../../fs-atomic.ts";+import { dualWrite } from "../../store/dual-write.ts";+import { DUAL_WRITE_LEDGERS, ledgerRowRecord } from "../../store/dual-write-records.ts";+import { rowNamesPrivatePage } from "../../store/reference-privacy.ts";export const MAINTENANCE_JOURNAL_CAP = 500;@@ -226,6 +229,19 @@ export function appendJournal(vault: string, entry: MaintenanceJournalEntry): vo// cap is enforced separately by `sweepJournal`, which runMaintenance// calls while it holds the lease - the only safe rewrite point.appendFileSync(path, JSON.stringify(entry) + "\n");+ // Brain store dual write (task 1.11): off by default, never fails this append.+ // Task ids, verdicts and gate readings; a failed task's `error` text can+ // carry a path, so a row naming a private or unjudgeable page goes to+ // `private` only.+ dualWrite(+ () =>+ ledgerRowRecord(+ DUAL_WRITE_LEDGERS.maintenanceJournal,+ entry,+ rowNamesPrivatePage(vault, entry) ? "private" : "shared",+ ),+ { vault },+ );}/** Trim the journal to the newest `cap` lines. Lease-holder only. */diff --git a/src/core/brain/merge.ts b/src/core/brain/merge.tsindex 8c11db75..a5ced250 100644--- a/src/core/brain/merge.ts+++ b/src/core/brain/merge.ts@@ -25,6 +25,8 @@import { existsSync } from "node:fs";import { join } from "node:path";+import { isPrivatePageFile, isPrivatePreference } from "../store/dual-write-records.ts";+import { regenerateActiveQuiet } from "./active.ts";import { computeContentHash } from "./content-hash.ts";import { buildEntityIndex } from "./entities/index-builder.ts";@@ -274,6 +276,9 @@ export function mergePreferences(revision_after: keep.revision ?? null,hash_before: keepHash,hash_after: keepHash,+ // The row names the drop too (`merged-in <drop>`): private when+ // either side is. The drop is already in `retired/` by now.+ private: () => isPrivatePageFile(keepPath) || isPrivatePreference(vault, dropSlug),},{ now },);diff --git a/src/core/brain/metrics.ts b/src/core/brain/metrics.tsindex 7e270b14..bde2527b 100644--- a/src/core/brain/metrics.ts+++ b/src/core/brain/metrics.ts@@ -34,6 +34,9 @@ import {} from "./ledger-shards.ts";import { acquireLockSyncWithRetry } from "./sync-lockfile.ts";import { assertVaultIdentityForWrite } from "./vault-identity.ts";+import { dualWrite } from "../store/dual-write.ts";+import { DUAL_WRITE_LEDGERS, ledgerRowRecord } from "../store/dual-write-records.ts";+import { rowNamesPrivatePage } from "../store/reference-privacy.ts";/** On-disk schema version stamped on every metric record. */export const METRICS_SCHEMA_VERSION = "o2b.metrics.v1";@@ -165,6 +168,19 @@ export function appendMetric(vault: string, input: AppendMetricInput): void {} finally {handle.release();}+ // Brain store dual write (task 1.11): off by default, never fails this append.+ // A sample is counts and timings, but its payload is caller-shaped: one+ // that names a private page, or a page that cannot be judged, goes to+ // `private` only.+ dualWrite(+ () =>+ ledgerRowRecord(+ DUAL_WRITE_LEDGERS.metrics,+ record,+ rowNamesPrivatePage(vault, record) ? "private" : "shared",+ ),+ { vault },+ );}/**diff --git a/src/core/brain/note.ts b/src/core/brain/note.tsindex 809b90e1..913418d9 100644--- a/src/core/brain/note.ts+++ b/src/core/brain/note.ts@@ -13,7 +13,15 @@ import { resolveAgentName } from "../config.ts";import { vaultRelative } from "../path-safety.ts";import { sanitiseTextField } from "../redactor.ts";-import { appendLogEvent } from "./log.ts";+import {+ callerInput,+ opaqueFields,+ operationPrivacy,+ type OperationPrivacy,+ type PrivacyVerdict,+} from "../store/operation-privacy.ts";+import { withOperationPrivacy } from "../store/operation-scope.ts";+import { appendLogEvent, logEventPrivacyContent } from "./log.ts";import {mirrorNote,mirrorReportFields,@@ -34,6 +42,11 @@ export interface AppendBrainNoteInput {readonly now?: Date;/** Config path for `resolveAgentName`. Optional. */readonly configPath?: string;+ /**+ * The privacy verdict of an enclosing operation (a write batch), which+ * the event's store record inherits. See `AppendLogEventOptions.storePrivate`.+ */+ readonly storePrivate?: PrivacyVerdict;}export interface AppendBrainNoteResult {@@ -59,19 +72,64 @@ export interface AppendBrainNoteResult {readonly mirror_reason?: string;}+function sanitiseNoteText(text: string): string {+ return sanitiseTextField(text, { maxLen: NOTE_TEXT_MAX_LEN, singleLine: true }).trim();+}++/**+ * Fields of a note call's input that are local settings, not text: the+ * vault, the clock, the config path and an enclosing verdict.+ */+const NOTE_INPUT_OPAQUE: ReadonlySet<string> = opaqueFields(+ "vault",+ "now",+ "configPath",+ "storePrivate",+);++/**+ * The privacy verdict of the note event {@link appendBrainNote} would+ * append for `input`: its whole input (the text, raw and as the event+ * carries it, and the agent), judged as the log appender judges the+ * event, plus `inherit` (an enclosing operation). A write batch judges+ * its log lines with it before it commits.+ */+export function brainNotePrivacy(+ vault: string,+ input: Omit<AppendBrainNoteInput, "vault">,+ inherit?: PrivacyVerdict,+): OperationPrivacy {+ return operationPrivacy(vault, {+ content: [+ logEventPrivacyContent({ text: sanitiseNoteText(input.text) }),+ callerInput(input, NOTE_INPUT_OPAQUE),+ ],+ inherit: [inherit],+ });+}+/*** Append one `note` event to `Brain/log/<today>.md` (and the JSONL* sidecar via `appendLogEvent`). Throws plain `Error` on empty text* β wrappers translate the error to their protocol's idiom.*/export function appendBrainNote(input: AppendBrainNoteInput): AppendBrainNoteResult {- const sanitised = sanitiseTextField(input.text, {- maxLen: NOTE_TEXT_MAX_LEN,- singleLine: true,- }).trim();+ const sanitised = sanitiseNoteText(input.text);if (!sanitised) {throw new Error("brain_note: text is required");}+ // Every store record written from here on (the note event, a mirror+ // copy, anything a writer below appends) carries this call's verdict+ // (`store/operation-scope.ts`).+ const privacy = brainNotePrivacy(input.vault, input, input.storePrivate);+ return withOperationPrivacy(privacy, () => appendJudgedNote(input, sanitised, privacy));+}++function appendJudgedNote(+ input: AppendBrainNoteInput,+ sanitised: string,+ privacy: OperationPrivacy,+): AppendBrainNoteResult {const explicitAgent = normalizeAgentArgument(input.agent ?? null);const agent = explicitAgent ?? resolveAgentName(input.configPath);const timestamp = isoSecond(input.now ?? new Date());@@ -80,7 +138,7 @@ export function appendBrainNote(input: AppendBrainNoteInput): AppendBrainNoteReseventType: BRAIN_LOG_EVENT_KIND.note,body: { text: sanitised, agent },} as const;- const res = appendLogEvent(input.vault, entry);+ const res = appendLogEvent(input.vault, entry, { storePrivate: privacy });// t_936a1a61: mirror AFTER the primary append succeeded; the mirror// is fail-soft and must never alter the primary result.const shared = resolveSharedNamespace(input.configPath ?? null);diff --git a/src/core/brain/notes/create-note-privacy.ts b/src/core/brain/notes/create-note-privacy.tsnew file mode 100644index 00000000..c2b2230c--- /dev/null+++ b/src/core/brain/notes/create-note-privacy.ts@@ -0,0 +1,46 @@+/**+ * The privacy verdict of one note create (`store/operation-privacy.ts`),+ * shared by the direct create writer and the write batch's `create_note`+ * operation so both judge a create by one rule.+ *+ * A create is private when the frontmatter it writes reserves the page as+ * private, when its frontmatter, content or template names a private page+ * or carries a `<private>` region, when any other caller-supplied field+ * does, or when an enclosing operation is private. The config path is a+ * local setting: checked for a region, never judged as a page reference.+ */++import { isPrivateFrontmatter } from "../../store/dual-write-records.ts";+import {+ callerInput,+ opaqueFields,+ operationPrivacy,+ type OperationPrivacy,+ type PrivacyVerdict,+} from "../../store/operation-privacy.ts";++/**+ * The fields of a create this judge reads by name, structurally; every+ * other field the caller passed is judged as content too.+ */+export interface JudgedCreate {+ readonly frontmatter?: Readonly<Record<string, unknown>>;+ readonly content?: string;+ readonly storePrivate?: PrivacyVerdict;+}++const CREATE_INPUT_OPAQUE: ReadonlySet<string> = opaqueFields("configPath");++/** The single, memoised privacy verdict of creating a note from `input`. */+export function createNotePrivacy(+ vault: string,+ input: JudgedCreate,+ inherit?: PrivacyVerdict,+): OperationPrivacy {+ const { storePrivate, ...caller } = input;+ return operationPrivacy(vault, {+ target: () => isPrivateFrontmatter(input.frontmatter ?? {}),+ content: [callerInput(caller, CREATE_INPUT_OPAQUE)],+ inherit: [storePrivate, inherit],+ });+}diff --git a/src/core/brain/notes/create-note.ts b/src/core/brain/notes/create-note.tsindex b0988199..1157c4f2 100644--- a/src/core/brain/notes/create-note.ts+++ b/src/core/brain/notes/create-note.ts@@ -87,6 +87,9 @@ import {type NoteTemplateVariables,} from "./note-template.ts";import { NOTE_WRITE_OP, recordNoteWrite } from "./write-record.ts";+import type { PrivacyVerdict } from "../../store/operation-privacy.ts";+import { withOperationPrivacy } from "../../store/operation-scope.ts";+import { createNotePrivacy } from "./create-note-privacy.ts";import { ROUTE_STAGE, timeStageSync } from "../../route-scope.ts";import { REVIEW_LANE } from "../write-gate.ts";import { resolveWriteDisposition, stageForReview } from "../pending/pending-lanes.ts";@@ -181,6 +184,11 @@ export interface CreateNoteInput {* config-derived subject.*/readonly subject?: WriteSubject;+ /**+ * Brain store dual write: the privacy verdict of an enclosing operation+ * (a write batch), which the note-write event's store record inherits.+ */+ readonly storePrivate?: PrivacyVerdict;}/** What a {@link createNote} call actually did. `staged` means the review gate parked the bytes in the queue. */@@ -737,6 +745,15 @@ export function logWatchedNoteOwnerWrite(* refusal.*/export function createNote(vault: string, input: CreateNoteInput): CreateNoteResult {+ // One operation: every store record written below (the owner-write+ // decision row, the review gate's row, the note-write event) carries the+ // create's verdict (`store/operation-scope.ts`).+ return withOperationPrivacy(createNotePrivacy(vault, input), () =>+ createNoteInScope(vault, input),+ );+}++function createNoteInScope(vault: string, input: CreateNoteInput): CreateNoteResult {// Vault-identity write guard (context-integrity-gates, Unit J). This// backs `brain_create_note`, `brain_append_note`, and// `brain_update_note` - the headline note writers.@@ -879,6 +896,7 @@ export function createNote(vault: string, input: CreateNoteInput): CreateNoteResbefore: null,after: { bytes: formatFrontmatter(frontmatter, body) },...(input.configPath !== undefined ? { configPath: input.configPath } : {}),+ ...(input.storePrivate !== undefined ? { storePrivate: input.storePrivate } : {}),}),);return { path: relPath, outcome: "created", created: true, ...receipt };diff --git a/src/core/brain/notes/write-record.ts b/src/core/brain/notes/write-record.tsindex 2277198c..679e5588 100644--- a/src/core/brain/notes/write-record.ts+++ b/src/core/brain/notes/write-record.ts@@ -43,6 +43,7 @@ import { dirname, isAbsolute, join } from "node:path";import { atomicWriteFileSync } from "../../fs-atomic.ts";import { resolveAgentName } from "../../config.ts";import { canonicalJson, sha256Hex } from "../../integrity/digest.ts";+import type { PrivacyVerdict } from "../../store/operation-privacy.ts";import { appendLogEvent } from "../log.ts";import {SHA256_HEX_RE,@@ -207,6 +208,12 @@ export interface RecordNoteWriteInput {* on disk would be the wrong one.*/readonly configPath?: string;+ /**+ * Brain store dual write: the privacy verdict of the operation this+ * write belongs to (a write batch), which the event's store record+ * inherits (`AppendLogEventOptions.storePrivate`).+ */+ readonly storePrivate?: PrivacyVerdict;}/**@@ -262,21 +269,25 @@ export function recordNoteWrite(vault: string, input: RecordNoteWriteInput): Not// string[]` and nothing else, so the byte counts are rendered rather// than carried as numbers a reader would have to coerce back.const writeId = noteWriteId(idInput);- appendLogEvent(vault, {- timestamp,- eventType: BRAIN_LOG_EVENT_KIND.noteWrite,- agent,- body: {- write_id: writeId,- op: idInput.op,- target: idInput.target,- hash_before: idInput.hash_before,- hash_after: idInput.hash_after,- bytes_before: String(bytesBefore),- bytes_after: String(bytesAfter),+ appendLogEvent(+ vault,+ {+ timestamp,+ eventType: BRAIN_LOG_EVENT_KIND.noteWrite,agent,+ body: {+ write_id: writeId,+ op: idInput.op,+ target: idInput.target,+ hash_before: idInput.hash_before,+ hash_after: idInput.hash_after,+ bytes_before: String(bytesBefore),+ bytes_after: String(bytesAfter),+ agent,+ },},- });+ input.storePrivate !== undefined ? { storePrivate: input.storePrivate } : {},+ );return { write_id: writeId };} catch (err) {return {diff --git a/src/core/brain/operator-snapshot.ts b/src/core/brain/operator-snapshot.tsindex 438eb571..74093ea7 100644--- a/src/core/brain/operator-snapshot.ts+++ b/src/core/brain/operator-snapshot.ts@@ -15,7 +15,7 @@* than sinking the whole snapshot.*/-import { existsSync, readdirSync, statSync } from "node:fs";+import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";import { join } from "node:path";import { resolveSearchConfig } from "../search/index.ts";@@ -30,10 +30,11 @@ import {} from "../maintenance/self-heal-upgrade-state.ts";import { runHygieneScan } from "./hygiene/scan.ts";import type { HygieneFinding } from "./hygiene/types.ts";-import { brainConfigPath, brainDirs } from "./paths.ts";+import { brainConfigPath, brainDirs, brainManualPath, vaultRelative } from "./paths.ts";import { loadTemporalConfigSafe } from "./policy.ts";import { listProfiles } from "./portability/profiles.ts";import { buildReviewCandidates } from "./review-candidates.ts";+import { describeManualRevisionAhead, manualRevisionAhead } from "./templates.ts";import { buildTimelineIndex } from "./temporal/build-index.ts";import { findStaleEntries } from "./temporal/stale-watch.ts";@@ -243,6 +244,14 @@ export async function buildOperatorSnapshot(if (selfHealUpgradeFailure !== null) {problem("self-heal-upgrade-failed", describeSelfHealUpgradeFailure(selfHealUpgradeFailure));}+ const manualAhead = readManualRevisionAhead(vault);+ if (manualAhead !== null) {+ problem(+ "managed-file-from-newer-release",+ `${describeManualRevisionAhead(vaultRelative(brainManualPath(vault), vault), manualAhead)}; ` ++ "update Open Second Brain on this device",+ );+ }// --- Doctor + semantic health ---let healthVerdict = "clean";@@ -522,3 +531,15 @@ function renderStoreLine(store: SnapshotStore): string {return `store: writer lock state unknown (${store.writerLockReason ?? "reason unavailable"}); ${caller}`;}}++/**+ * The manual's template revision when a newer release wrote it, else null.+ * Fail-soft like every source here: an unreadable manual reads as current.+ */+function readManualRevisionAhead(vault: string): number | null {+ try {+ return manualRevisionAhead(readFileSync(brainManualPath(vault), "utf8"));+ } catch {+ return null;+ }+}diff --git a/src/core/brain/path-constants.ts b/src/core/brain/path-constants.tsindex 072d92d6..f8490a9d 100644--- a/src/core/brain/path-constants.ts+++ b/src/core/brain/path-constants.ts@@ -106,6 +106,13 @@ export const BRAIN_STATE_REL = posix.join(BRAIN_ROOT_REL, "state");*/export const BRAIN_INTERNAL_STATE_DIR = ".state";export const BRAIN_INTERNAL_STATE_REL = posix.join(BRAIN_ROOT_REL, BRAIN_INTERNAL_STATE_DIR);+/**+ * Anticipatory context cache: `Brain/.state/anticipatory/<key>.json`. One+ * entry per lineage root and enforced owner scope, refreshed on hook+ * events and pruned by age and count on write.+ */+export const BRAIN_ANTICIPATORY_DIR = "anticipatory";+export const BRAIN_ANTICIPATORY_REL = posix.join(BRAIN_INTERNAL_STATE_REL, BRAIN_ANTICIPATORY_DIR);/** Obsidian Bases view definitions: `Brain/bases/<view>.base` (v1.15.0). */export const BRAIN_BASES_REL = posix.join(BRAIN_ROOT_REL, "bases");/** Ingested source summary pages: `Brain/sources/src-<slug>.md` (v1.7.0). */diff --git a/src/core/brain/permissions/ledger.ts b/src/core/brain/permissions/ledger.tsindex e7f54ff9..f2ca3936 100644--- a/src/core/brain/permissions/ledger.ts+++ b/src/core/brain/permissions/ledger.ts@@ -39,6 +39,8 @@ import {import { BRAIN_ROOT_REL } from "../path-constants.ts";import { assertVaultIdentityForWrite } from "../vault-identity.ts";import type { PermissionAction } from "./document.ts";+import { dualWrite } from "../../store/dual-write.ts";+import { DUAL_WRITE_LEDGERS, ledgerRowRecord } from "../../store/dual-write-records.ts";/** Month-sharded JSONL root under `Brain/logs/`, beside the idempotency ledger. */const DECISIONS_REL = `${BRAIN_ROOT_REL}/logs/decisions`;@@ -132,12 +134,17 @@ export function appendDecisionLedger(const dir = decisionLedgerDir(vault);mkdirSync(dir, { recursive: true });const shardPath = join(dir, decisionLedgerShardPath(month, shardId));+ const stored = stripEmptyOptionals(row);withShardLock(shardPath, () => {- writeFileSync(shardPath, `${JSON.stringify(stripEmptyOptionals(row))}\n`, {+ writeFileSync(shardPath, `${JSON.stringify(stored)}\n`, {encoding: "utf8",flag: "a",});});+ // Brain store dual write (task 1.11): off by default, never fails this append.+ dualWrite(() => ledgerRowRecord(DUAL_WRITE_LEDGERS.permissions, stored, "private-when-held"), {+ vault,+ });return { logged: true };} catch (err) {const message = err instanceof Error ? err.message : String(err);diff --git a/src/core/brain/pin.ts b/src/core/brain/pin.tsindex 9b30f100..4698cc9e 100644--- a/src/core/brain/pin.ts+++ b/src/core/brain/pin.ts@@ -30,9 +30,13 @@import { existsSync } from "node:fs";import { writeFrontmatterAtomic, parseFrontmatter } from "../vault.ts";+import { authorityFromOrigin, dualWrite } from "../store/dual-write.ts";+import { withOperationPrivacy } from "../store/operation-scope.ts";+import { preferenceSetRecord } from "../store/dual-write-records.ts";+import { callerInput, opaqueFields } from "../store/operation-privacy.ts";import { regenerateActiveQuiet } from "./active.ts";-import { appendLogEvent, type BrainLogEntry } from "./log.ts";-import { parsePreference } from "./preference.ts";+import { appendLogEvent, logEventPrivacyContent, type BrainLogEntry } from "./log.ts";+import { parsePreference, preferencePrivacy, storeFieldsOf } from "./preference.ts";import { preferencePath, validateSlug } from "./paths.ts";import { assertVaultIdentityForWrite } from "./vault-identity.ts";import { isoSecond } from "./time.ts";@@ -40,6 +44,9 @@ import { BRAIN_LOG_EVENT_KIND, type BrainPreference } from "./types.ts";import { renderPrefLink } from "./wikilink.ts";import { BrainPreferenceNotFoundError } from "./apply-evidence.ts";+/** Fields of a pin call's input that are not text: its clock. */+const PIN_INPUT_OPAQUE: ReadonlySet<string> = opaqueFields("now");+export interface SetPinnedOptions {/** Override the wall clock used in the log event. */readonly now?: Date;@@ -118,7 +125,6 @@ export function setPinned(existsErrorKind: "preference",vaultForRelativePath: vault,});-// Emit the log event only on a real transition.const now = opts.now ?? new Date();const entry: BrainLogEntry = {@@ -132,10 +138,36 @@ export function setPinned(agent: (opts.agent ?? "cli").trim() || "cli",},};- appendLogEvent(vault, entry);- regenerateActiveQuiet(vault, { now });+ // One privacy verdict for both store records of this call, the pinned+ // field and the log event: the preference's own (its frontmatter, its+ // content fields), the event's body and the caller's whole input.+ const privacy = preferencePrivacy(vault, storeFieldsOf(newMeta), [+ logEventPrivacyContent(entry.body),+ callerInput({ prefId, ...opts }, PIN_INPUT_OPAQUE),+ ]);+ // Every store record written from here on, by this call or by any+ // writer it calls, carries this verdict (`store/operation-scope.ts`).+ return withOperationPrivacy(privacy, () => {+ // Brain store dual write (task 1.11): the one field this call changed,+ // filed under the preference's own scope.+ dualWrite(+ () => {+ const record = preferenceSetRecord({+ id: `pref-${slug}`,+ frontmatter: { pinned: value },+ authority: authorityFromOrigin(),+ private: privacy(),+ });+ const scope = current.scope?.trim();+ return record === null ? null : { ...record, scope: scope ? scope : null };+ },+ { vault },+ );+ appendLogEvent(vault, entry, { storePrivate: privacy });+ regenerateActiveQuiet(vault, { now });- return { path, changed: true };+ return { path, changed: true };+ });}/**diff --git a/src/core/brain/pinned.ts b/src/core/brain/pinned.tsindex 22899c57..e04938d0 100644--- a/src/core/brain/pinned.ts+++ b/src/core/brain/pinned.ts@@ -1,8 +1,32 @@+/**+ * Pinned context: the transient current-task scratchpad at+ * `Brain/pinned.md`, read, written, appended, cleared or batch-edited by+ * the `brain_pinned_context` tool.+ *+ * Every mutation is a read-modify-write of one file, and several agents+ * share it. The atomic rename only guarantees that no reader sees a torn+ * file; it says nothing about a second writer that read the same "before"+ * state, so two concurrent appends used to lose one of them. Every write+ * therefore runs under the per-file sync lock (`pinned.md.lock`) and+ * re-reads the current content inside it, the same discipline as the+ * preference transaction (`preference-txn.ts`). The lock waits rather+ * than refusing: a pinned write is short, and a refusal would hand the+ * agent a retry for what is only ordinary contention.+ *+ * Under the brain store dual-write flag every committed state is also+ * appended to the store as a full-text `pinned-set` (or a `pinned-clear`),+ * with the authority of the process's origin (see `store/dual-write.ts`).+ */+import { existsSync, readFileSync } from "node:fs";import { atomicWriteFileSync } from "../fs-atomic.ts";+import { pinnedRecord } from "../store/dual-write-records.ts";+import { authorityFromOrigin, dualWrite, isDualWriteEnabled } from "../store/dual-write.ts";+import { pinnedTextIsPrivate } from "../store/reference-privacy.ts";import { sanitiseTextField } from "../redactor.ts";import { brainPinnedPath } from "./paths.ts";+import { acquireLockSyncWithRetry } from "./sync-lockfile.ts";import { assertVaultIdentityForWrite } from "./vault-identity.ts";export const MAX_PINNED_CONTEXT_LEN = 20_000;@@ -25,17 +49,38 @@ export function readPinnedContext(vault: string): PinnedContext {};}+/**+ * Run `fn` holding the pinned file's sync lock. Whatever `fn` reads of the+ * current content it must read INSIDE this call, or the lock protects+ * nothing.+ */+function withPinnedLock<T>(vault: string, fn: () => T): T {+ const handle = acquireLockSyncWithRetry(brainPinnedPath(vault));+ try {+ return fn();+ } finally {+ handle.release();+ }+}+export function writePinnedContext(vault: string, content: unknown): PinnedContext {- return commitPinnedContent(vault, normalisePinnedContentNoTruncate(content), "write");+ const normalised = normalisePinnedContentNoTruncate(content);+ // Vault-identity write guard (Unit J) BEFORE the lock, as clear and the+ // batch path do: a refused vault gets no lock file and no lock wait.+ assertVaultIdentityForWrite(vault);+ return withPinnedLock(vault, () => commitPinnedContent(vault, normalised, "write"));}export function appendPinnedContext(vault: string, content: unknown): PinnedContext {const incoming = normalisePinnedContentNoTruncate(content);if (incoming.length === 0) return readPinnedContext(vault);- const current = readPinnedContext(vault).content;- const next = current.length > 0 ? `${current}\n\n${incoming}` : incoming;- return commitPinnedContent(vault, next, "append");+ assertVaultIdentityForWrite(vault);+ return withPinnedLock(vault, () => {+ const current = readPinnedContext(vault).content;+ const next = current.length > 0 ? `${current}\n\n${incoming}` : incoming;+ return commitPinnedContent(vault, next, "append");+ });}/**@@ -57,6 +102,12 @@ function commitPinnedContent(assertWithinPinnedBudget(normalised, operation);const path = brainPinnedPath(vault);atomicWriteFileSync(path, normalised.length > 0 ? `${normalised}\n` : "");+ // Brain store dual write (task 1.11), inside the pinned lock so the store+ // sees replacements in the order the file did.+ dualWrite(+ () => pinnedRecord(normalised, authorityFromOrigin(), pinnedTextIsPrivate(vault, normalised)),+ { vault },+ );return { path, present: true, content: normalised };}@@ -64,8 +115,24 @@ export function clearPinnedContext(vault: string): PinnedContext {// Vault-identity write guard (context-integrity-gates, Unit J).assertVaultIdentityForWrite(vault);const path = brainPinnedPath(vault);- atomicWriteFileSync(path, "");- return { path, present: true, content: "" };+ return withPinnedLock(vault, () => {+ // A clear goes where a set of the text it clears goes, so it lands in+ // the same partition register as that set. The text is read only for+ // the dual write: with the flag off a clear never depends on reading+ // the old file, and one that cannot be read is judged private (fail+ // closed), never shared.+ let namesPrivate = true;+ if (isDualWriteEnabled()) {+ try {+ namesPrivate = pinnedTextIsPrivate(vault, readPinnedContext(vault).content);+ } catch {+ namesPrivate = true;+ }+ }+ atomicWriteFileSync(path, "");+ dualWrite(() => pinnedRecord(null, authorityFromOrigin(), namesPrivate), { vault });+ return { path, present: true, content: "" };+ });}/**@@ -187,16 +254,30 @@ export function applyPinnedOperations(throw new PinnedBatchError("invalid_operation", -1, "operations must be a non-empty array");}- let projected = readPinnedContext(vault).content;- operations.forEach((operation, index) => {- projected = projectPinnedOperation(projected, operation, index);- });+ return withPinnedLock(vault, () => {+ // Projected from the content read under the lock, so a batch never+ // overwrites a write that landed between its read and its commit.+ let projected = readPinnedContext(vault).content;+ operations.forEach((operation, index) => {+ projected = projectPinnedOperation(projected, operation, index);+ });- assertWithinPinnedBudget(projected, "batch");+ assertWithinPinnedBudget(projected, "batch");- const path = brainPinnedPath(vault);- atomicWriteFileSync(path, projected.length > 0 ? `${projected}\n` : "");- return { path, present: true, content: projected, applied: operations.length, done: true };+ const path = brainPinnedPath(vault);+ atomicWriteFileSync(path, projected.length > 0 ? `${projected}\n` : "");+ dualWrite(+ () => pinnedRecord(projected, authorityFromOrigin(), pinnedTextIsPrivate(vault, projected)),+ { vault },+ );+ return {+ path,+ present: true,+ content: projected,+ applied: operations.length,+ done: true as const,+ };+ });}function projectPinnedOperation(diff --git a/src/core/brain/pref-audit.ts b/src/core/brain/pref-audit.tsindex dc7b54d5..dc48096a 100644--- a/src/core/brain/pref-audit.ts+++ b/src/core/brain/pref-audit.ts@@ -72,6 +72,12 @@ import {import { assertVaultIdentityForWrite } from "./vault-identity.ts";import { isoSecond } from "./time.ts";import { PREF_AUDIT_OP, type PrefAuditOp, type PrefAuditRecord } from "./types.ts";+import { dualWrite } from "../store/dual-write.ts";+import {+ auditRowRecord,+ DUAL_WRITE_LEDGERS,+ isPrivatePreference,+} from "../store/dual-write-records.ts";/*** Opt-in audit sink threaded through a mutation chokepoint. When@@ -98,6 +104,14 @@ export interface AppendPrefAuditInput {readonly revision_after: number | null;readonly hash_before: string | null;readonly hash_after: string | null;+ /**+ * Whether the preference is private (any privacy marker,+ * `isPrivateFrontmatter`), or how to tell; a function is called only when+ * the brain store dual write is on. Never written to the audit line; it+ * keeps the store copy of the row in the `private` partition only, where+ * the preference's own records go, even on a machine without it.+ */+ readonly private?: boolean | (() => boolean);}/** One warning raised while reading an audit JSONL file. */@@ -172,6 +186,22 @@ export function appendPrefAudit(const path = prefAuditPath(vault, input.pref_id);mkdirSync(dirname(path), { recursive: true });appendFileSync(path, renderPrefAuditLine(record), "utf8");+ // Brain store dual write (task 1.11): off by default, never fails this append.+ // Audit rows go to `private` when this machine holds it, else `shared`+ // (`auditRowRecord`). A private preference's trail is private only: the+ // caller's flag (it knows the file it just wrote, merged or retired), or+ // the preference file found on disk.+ dualWrite(+ () =>+ auditRowRecord(+ DUAL_WRITE_LEDGERS.preferenceAudit,+ record,+ record.agent,+ (typeof input.private === "function" ? input.private() : input.private === true) ||+ isPrivatePreference(vault, record.pref_id.replace(/^pref-/, "")),+ ),+ { vault },+ );return true;}diff --git a/src/core/brain/preference-txn.ts b/src/core/brain/preference-txn.tsindex c32e4b8a..9748f39e 100644--- a/src/core/brain/preference-txn.ts+++ b/src/core/brain/preference-txn.ts@@ -29,6 +29,8 @@import { existsSync } from "node:fs";+import { isPrivatePageFile } from "../store/dual-write-records.ts";+import { computeContentHash } from "./content-hash.ts";import { appendEditHistory, type EditHistoryEntry } from "./health/edit-history.ts";import { appendPrefAudit, type PrefAuditSink } from "./pref-audit.ts";@@ -270,6 +272,7 @@ export function writePreferenceTxn(revision_after: inputWithDefaults.revision ?? null,hash_before: existing ? computeContentHash(existing.principle, existing.scope) : null,hash_after: computeContentHash(inputWithDefaults.principle, inputWithDefaults.scope),+ private: () => isPrivatePageFile(result.path),},{ now: audit.now?.() ?? new Date() },);diff --git a/src/core/brain/preference.ts b/src/core/brain/preference.tsindex dd2ef66f..24af73ad 100644--- a/src/core/brain/preference.ts+++ b/src/core/brain/preference.ts@@ -33,6 +33,17 @@* complete before the old one disappears.*/+import type { Authority } from "../store/constants.ts";+import { authorityFromOrigin, dualWrite, type DualWriteRecord } from "../store/dual-write.ts";+import { isPrivateFrontmatter, preferenceSetRecord } from "../store/dual-write-records.ts";+import {+ callerInput,+ operationPrivacy,+ PREFERENCE_OPAQUE_FIELDS,+ type JudgedContent,+ type OperationPrivacy,+} from "../store/operation-privacy.ts";+import { withOperationPrivacy } from "../store/operation-scope.ts";import { existsSync, readFileSync, unlinkSync } from "node:fs";import { basename, dirname, join, relative } from "node:path";@@ -327,6 +338,14 @@ export interface WritePreferenceOptions {* config-derived identity.*/readonly subject?: WriteSubject;+ /**+ * Who decided this write, for the brain store dual write (task 1.11):+ * `human` (an operator command), `agent` (an agent or an automatic pass+ * such as dream) or `model` (a decision-model verdict). Absent derives+ * it from the process's origin channel (`authorityFromOrigin`). It does+ * not change the legacy file.+ */+ readonly authority?: Authority;}export interface ParsePreferenceOptions {@@ -373,6 +392,14 @@ export interface MoveToRetiredOptions {* pre-suite behaviour (no audit file).*/readonly audit?: { readonly agent: string };+ /**+ * Who decided this write, for the brain store dual write (task 1.11):+ * `human` (an operator command), `agent` (an agent or an automatic pass+ * such as dream) or `model` (a decision-model verdict). Absent derives+ * it from the process's origin channel (`authorityFromOrigin`). It does+ * not change the legacy file.+ */+ readonly authority?: Authority;}export interface MoveToRetiredResult {@@ -425,6 +452,35 @@ export function writePreference(const path = preferencePath(vault, slug);const id = `pref-${slug}`;+ // Every store record written from here on (an owner-write decision row,+ // the idempotency receipt, the preference's records, anything a writer+ // below appends) carries one verdict (`store/operation-scope.ts`): the+ // caller's fields as the page will carry them and its whole input, and+ // the page the write lands on, as it reads when the first record is+ // judged. Both sides of the merge a rewrite makes are so covered.+ const privacy = operationPrivacy(vault, {+ inherit: [+ () =>+ preferencePrivacy(vault, storeFieldsOf(preferenceFrontmatter(input, id)), [+ callerInput(input, PREFERENCE_OPAQUE_FIELDS),+ ])(),+ () =>+ existsSync(path) && preferencePrivacy(vault, storeFieldsOf(parseFrontmatter(path)[0]))(),+ ],+ });+ return withOperationPrivacy(privacy, () =>+ writeJudgedPreference(vault, input, options, slug, path, id),+ );+}++function writeJudgedPreference(+ vault: string,+ input: WritePreferenceInput,+ options: WritePreferenceOptions,+ slug: string,+ path: string,+ id: string,+): WritePreferenceResult {// Ownership (a-label-is-not-a-boundary, U1). Resolved BEFORE the// idempotency hash so a write that changes the owner cannot dedupe// against one that did not - the hash already folds `owner` in for@@ -474,7 +530,10 @@ export function writePreference(const next = formatFrontmatter(metadata, body);const prev = readFileSync(path, "utf8");if (next === prev) {- recordPreferenceKey(vault, idKey, idContentHash, owned.created_at, id, path);+ const unchanged = preferencePrivacy(vault, storeFieldsOf(metadata), [+ callerInput(input, PREFERENCE_OPAQUE_FIELDS),+ ]);+ recordPreferenceKey(vault, idKey, idContentHash, owned.created_at, id, path, unchanged);return { path, id };}} catch {@@ -489,7 +548,18 @@ export function writePreference(vaultForRelativePath: vault,});- recordPreferenceKey(vault, idKey, idContentHash, owned.created_at, id, path);+ // One privacy verdict for every store record this write produces: the+ // idempotency receipt and the preference's human and derived records,+ // judged from the fields they carry and the caller's whole input.+ const written = storeFieldsOf(metadata);+ const privacy = preferencePrivacy(vault, written, [callerInput(input, PREFERENCE_OPAQUE_FIELDS)]);+ recordPreferenceKey(vault, idKey, idContentHash, owned.created_at, id, path, privacy);+ // Brain store dual write (task 1.11): off by default, never fails this write.+ dualWrite(+ () =>+ preferenceStoreRecords(id, written, options.authority ?? authorityFromOrigin(), privacy()),+ { vault, ...(options.configPath !== undefined ? { configPath: options.configPath } : {}) },+ );return { path, id };}@@ -764,6 +834,7 @@ function recordPreferenceKey(createdAt: string,id: string,path: string,+ privacy: OperationPrivacy,): void {if (!idKey || contentHash === undefined) return;rememberKey(vault, {@@ -771,6 +842,7 @@ function recordPreferenceKey(contentHash,createdAt,ref: { id, path: relative(vault, path) },+ private: privacy,});}@@ -1089,6 +1161,82 @@ export function normalizeDerivedKeys(meta: Record<string, unknown>): Record<strireturn out;}+/**+ * A preference's frontmatter under the field names the brain store folds+ * (dual writes, task 1.11): derived keys lose their on-disk `_` prefix and+ * the textual `"null"` sentinel becomes `null`, so the store holds what+ * the file means rather than how it is spelled.+ */+export function storeFieldsOf(meta: Record<string, unknown>): Record<string, unknown> {+ const out = normalizeDerivedKeys(meta);+ for (const name of DERIVED_FIELDS) if (out[name] === "null") out[name] = null;+ return out;+}++const DERIVED_FIELD_SET: ReadonlySet<string> = new Set(DERIVED_FIELDS);++/** The derived field a retire decides itself, at the retiring caller's authority. */+const RETIRE_DECIDED_FIELDS: ReadonlyArray<string> = Object.freeze(["status"]);++/**+ * The single privacy verdict of a preference write+ * (`store/operation-privacy.ts`), from the fields the store records carry:+ * the frontmatter reserving the preference as private, or any content+ * field (`principle`, `evidenced_by`, `supersedes` and the other+ * relationship fields, ...) naming a private or unresolvable page or+ * carrying a `<private>` region. `extra` is further content of the same+ * operation (the writer's caller input, a pin's log event). Judged once,+ * on first use.+ */+export function preferencePrivacy(+ vault: string,+ fields: Readonly<Record<string, unknown>>,+ extra: ReadonlyArray<JudgedContent> = [],+): OperationPrivacy {+ return operationPrivacy(vault, {+ target: () => isPrivateFrontmatter(fields),+ content: [{ value: fields, opaque: PREFERENCE_OPAQUE_FIELDS }, ...extra],+ });+}++/**+ * The brain store records of one preference write (dual writes, task+ * 1.11). Fields the fold resolves by authority first: when a human writes,+ * only the fields the human decided carry human authority. The derived+ * fields the dream pass owns ({@link DERIVED_FIELDS}, minus `decided`, the+ * ones this write itself decides) go out in a second record at agent+ * authority, so a later dream write can still win them, as it does on the+ * file. Every record keeps the scope the whole preference has and the+ * partition of the write's one privacy verdict (`isPrivate`).+ */+function preferenceStoreRecords(+ id: string,+ fields: Readonly<Record<string, unknown>>,+ authority: Authority,+ isPrivate: boolean,+ decided: ReadonlyArray<string> = [],+): DualWriteRecord[] | null {+ const whole = preferenceSetRecord({ id, frontmatter: fields, authority, private: isPrivate });+ if (whole === null) return null;+ if (authority !== "human") return [whole];+ const keep = new Set(decided);+ const own: Record<string, unknown> = {};+ const derived: Record<string, unknown> = {};+ for (const [name, value] of Object.entries(fields)) {+ if (DERIVED_FIELD_SET.has(name) && !keep.has(name)) derived[name] = value;+ else own[name] = value;+ }+ const placement = { scope: whole.scope ?? null };+ const out: DualWriteRecord[] = [];+ for (const record of [+ preferenceSetRecord({ id, frontmatter: own, authority, private: isPrivate }),+ preferenceSetRecord({ id, frontmatter: derived, authority: "agent", private: isPrivate }),+ ]) {+ if (record !== null) out.push({ ...record, ...placement });+ }+ return out;+}+/*** Parse a preference file. Defaults `pinned` to `false` when the field* is absent (Β§5.3). Throws {@link BrainStatusFolderMismatchError} when@@ -1556,6 +1704,25 @@ export function moveToRetired(}unlinkSync(prefPath);+ // Brain store dual write (task 1.11): a retire is a field change of the+ // same preference id (`status: retired`), never a removal. The retired+ // file's identity keys (`id: ret-<slug>`, `kind`, `aliases`) are not+ // fields of `pref-<slug>`, so they stay out; the status is what a retire+ // decides, at the caller's authority.+ dualWrite(+ () => {+ const { id: _id, kind: _kind, aliases: _aliases, ...lifecycle } = storeFieldsOf(newMeta);+ return preferenceStoreRecords(+ oldId,+ lifecycle,+ opts.authority ?? authorityFromOrigin(),+ preferencePrivacy(vault, lifecycle)(),+ RETIRE_DECIDED_FIELDS,+ );+ },+ { vault },+ );+// Per-preference mutation audit (opt-in, Brain lifecycle suite F1).// Keyed by the ORIGINAL `pref-<slug>` id so create -> ... -> retire// all land in one trail. A retire is a lifecycle transition, so it@@ -1576,6 +1743,7 @@ export function moveToRetired(revision_after: null,hash_before: contentHash,hash_after: contentHash,+ private: isPrivateFrontmatter(meta),},{ now: opts.now },);diff --git a/src/core/brain/pretool-host-backup.ts b/src/core/brain/pretool-host-backup.tsindex b1059fb3..2dee2d0e 100644--- a/src/core/brain/pretool-host-backup.ts+++ b/src/core/brain/pretool-host-backup.ts@@ -328,19 +328,23 @@ function appendReceipt(): string | null {if (opts.vault === null) return null;try {- return appendAuditRecord(hookAuditDir(opts.vault), {- timestamp: opts.now.toISOString(),- actor: opts.actor,- action: "host-settings-backup",- target: opts.target,- ok: true,- details: {- pid: process.pid,- before_hash: beforeHash,- summary: `backed up ${basename(opts.target)} (${contents.length} bytes) before an agent file write`,- backup: backupPath,+ return appendAuditRecord(+ hookAuditDir(opts.vault),+ {+ timestamp: opts.now.toISOString(),+ actor: opts.actor,+ action: "host-settings-backup",+ target: opts.target,+ ok: true,+ details: {+ pid: process.pid,+ before_hash: beforeHash,+ summary: `backed up ${basename(opts.target)} (${contents.length} bytes) before an agent file write`,+ backup: backupPath,+ },},- });+ opts.vault,+ );} catch {// The receipt is evidence, not the guard: a failed append must not// turn a completed backup into a deny (the orient precedent).diff --git a/src/core/brain/query-demand.ts b/src/core/brain/query-demand.tsindex c37310a3..ad39cc02 100644--- a/src/core/brain/query-demand.ts+++ b/src/core/brain/query-demand.ts@@ -48,6 +48,8 @@ import type { CompletenessVerdict } from "../search/types.ts";import { isRecallAdequacyLevel } from "./recall-adequacy.ts";import type { RecallAdequacyLevel, RecallAdequacyVerdict } from "./recall-adequacy.ts";import { assertVaultIdentityForWrite } from "./vault-identity.ts";+import { dualWrite } from "../store/dual-write.ts";+import { DUAL_WRITE_LEDGERS, ledgerRowRecord } from "../store/dual-write-records.ts";/** Longest single normalized term kept; longer tokens are dropped as a* privacy guard (a 40+ char alnum run is far likelier a secret/id than a@@ -266,6 +268,12 @@ export function recordQueryDemand(} finally {handle.release();}+ // Brain store dual write (task 1.11): off by default, never fails this append.+ // The terms are what the user searched for, so they go to `private` when+ // this machine holds it.+ dualWrite(() => ledgerRowRecord(DUAL_WRITE_LEDGERS.queryDemand, record, "private-when-held"), {+ vault,+ });return record;}diff --git a/src/core/brain/recompile.ts b/src/core/brain/recompile.tsindex a831d507..555d041b 100644--- a/src/core/brain/recompile.ts+++ b/src/core/brain/recompile.ts@@ -207,19 +207,23 @@ export async function executeRecompile(!dryRun &&(rederived.length > 0 || archived.length > 0 || manual.length > 0 || errors.length > 0)) {- appendAuditRecord(join(brainDirsForWrite(vault).log, HYGIENE_AUDIT_DIR), {- timestamp: opts.now.toISOString(),- actor: opts.agent,- action: "targeted_recompile",- target: "Brain",- ok: errors.length === 0,- details: {- rederived: rederived.length,- archived: archived.length,- manual: manual.length,- errors: errors.length,+ appendAuditRecord(+ join(brainDirsForWrite(vault).log, HYGIENE_AUDIT_DIR),+ {+ timestamp: opts.now.toISOString(),+ actor: opts.agent,+ action: "targeted_recompile",+ target: "Brain",+ ok: errors.length === 0,+ details: {+ rederived: rederived.length,+ archived: archived.length,+ manual: manual.length,+ errors: errors.length,+ },},- });+ vault,+ );}return Object.freeze({diff --git a/src/core/brain/recurrence.ts b/src/core/brain/recurrence.tsindex 2fdf34d7..3a0ec157 100644--- a/src/core/brain/recurrence.ts+++ b/src/core/brain/recurrence.ts@@ -5,6 +5,9 @@ import { interleaveShardRows, jsonlLedgerGrammar, readShardLinesByShard } from "import { BRAIN_LOG_REL } from "./path-constants.ts";import { proceduralRecurrencePath, RECURRENCE_LEDGER_STEM } from "./paths.ts";import { assertVaultIdentityForWrite } from "./vault-identity.ts";+import { dualWrite } from "../store/dual-write.ts";+import { DUAL_WRITE_LEDGERS, ledgerRowRecord } from "../store/dual-write-records.ts";+import { claimSourceIsPrivate, rowNamesPrivatePage } from "../store/reference-privacy.ts";/** The recurrence ledger's file-name layout, handed to the shared shard grammar. */const RECURRENCE_LEDGER_GRAMMAR = jsonlLedgerGrammar(RECURRENCE_LEDGER_STEM);@@ -242,6 +245,20 @@ function appendEvent(vault: string, event: RecurrenceEvent): void {const path = proceduralRecurrencePath(vault);mkdirSync(dirname(path), { recursive: true });appendFileSync(path, `${JSON.stringify(event)}\n`, { encoding: "utf8" });+ // Brain store dual write (task 1.11): off by default, never fails this append.+ // `sourceId` and `scope` can name a page: a source that is a private+ // page, or a page link that names none here, goes to `private` only.+ dualWrite(+ () =>+ ledgerRowRecord(+ DUAL_WRITE_LEDGERS.recurrence,+ event,+ claimSourceIsPrivate(vault, event.sourceId) || rowNamesPrivatePage(vault, event)+ ? "private"+ : "shared",+ ),+ { vault },+ );}/**diff --git a/src/core/brain/schema-mutate.ts b/src/core/brain/schema-mutate.tsindex 50239bea..65f3066c 100644--- a/src/core/brain/schema-mutate.ts+++ b/src/core/brain/schema-mutate.ts@@ -264,6 +264,7 @@ export async function applySchemaMutations(...(opts.reason ? { reason: opts.reason } : {}),},},+ vault,);return {applied: mutations.length,diff --git a/src/core/brain/secrets/bundle.ts b/src/core/brain/secrets/bundle.tsindex 9242b43d..485da264 100644--- a/src/core/brain/secrets/bundle.ts+++ b/src/core/brain/secrets/bundle.ts@@ -520,14 +520,18 @@ function auditBundle(action: string,details: Record<string, unknown>,): void {- appendAuditRecord(joinBrainLog(vault), {- timestamp: ctx.now.toISOString(),- actor: ctx.agent,- action,- target: "bundle",- ok: true,- details,- });+ appendAuditRecord(+ joinBrainLog(vault),+ {+ timestamp: ctx.now.toISOString(),+ actor: ctx.agent,+ action,+ target: "bundle",+ ok: true,+ details,+ },+ vault,+ );}function joinBrainLog(vault: string): string {diff --git a/src/core/brain/secrets/exec.ts b/src/core/brain/secrets/exec.tsindex cbc9ecb7..e5828139 100644--- a/src/core/brain/secrets/exec.ts+++ b/src/core/brain/secrets/exec.ts@@ -135,25 +135,33 @@ export async function runWithSecret(});const resolved = resolveSecretForExec(vault, name, ctx);if (!matchesAllowlist(resolved.allow, argv)) {- appendAuditRecord(join(brainDirsForWrite(vault).log, SECRET_CUSTODY_AUDIT_DIR), {- timestamp: ctx.now.toISOString(),- actor: ctx.agent,- action: "secret_exec_denied",- target: resolved.name,- ok: false,- details: { command: auditCommand, allow: resolved.allow },- });+ appendAuditRecord(+ join(brainDirsForWrite(vault).log, SECRET_CUSTODY_AUDIT_DIR),+ {+ timestamp: ctx.now.toISOString(),+ actor: ctx.agent,+ action: "secret_exec_denied",+ target: resolved.name,+ ok: false,+ details: { command: auditCommand, allow: resolved.allow },+ },+ vault,+ );throw new SecretExecDeniedError(resolved.name, command, resolved.allow);}- appendAuditRecord(join(brainDirsForWrite(vault).log, SECRET_CUSTODY_AUDIT_DIR), {- timestamp: ctx.now.toISOString(),- actor: ctx.agent,- action: "secret_exec_started",- target: resolved.name,- ok: true,- details: { command: auditCommand, env_var: resolved.env_var },- });+ appendAuditRecord(+ join(brainDirsForWrite(vault).log, SECRET_CUSTODY_AUDIT_DIR),+ {+ timestamp: ctx.now.toISOString(),+ actor: ctx.agent,+ action: "secret_exec_started",+ target: resolved.name,+ ok: true,+ details: { command: auditCommand, env_var: resolved.env_var },+ },+ vault,+ );const childEnv: Record<string, string> = {};for (const key of SAFE_BASE_ENV) {diff --git a/src/core/brain/secrets/store.ts b/src/core/brain/secrets/store.tsindex c84a96da..97176cc4 100644--- a/src/core/brain/secrets/store.ts+++ b/src/core/brain/secrets/store.ts@@ -545,12 +545,16 @@ function audit(name: string,details: Record<string, unknown>,): void {- appendAuditRecord(join(brainDirsForWrite(vault).log, SECRET_CUSTODY_AUDIT_DIR), {- timestamp: ctx.now.toISOString(),- actor: ctx.agent,- action,- target: name,- ok: true,- details,- });+ appendAuditRecord(+ join(brainDirsForWrite(vault).log, SECRET_CUSTODY_AUDIT_DIR),+ {+ timestamp: ctx.now.toISOString(),+ actor: ctx.agent,+ action,+ target: name,+ ok: true,+ details,+ },+ vault,+ );}diff --git a/src/core/brain/secrets/token-store.ts b/src/core/brain/secrets/token-store.tsindex 4f7bb2d5..0b05ce98 100644--- a/src/core/brain/secrets/token-store.ts+++ b/src/core/brain/secrets/token-store.ts@@ -437,12 +437,16 @@ function auditToken(name: string,details: Record<string, unknown>,): void {- appendAuditRecord(join(brainDirsForWrite(vault).log, SECRET_CUSTODY_AUDIT_DIR), {- timestamp: new Date().toISOString(),- actor: "cli",- action,- target: name,- ok: true,- details,- });+ appendAuditRecord(+ join(brainDirsForWrite(vault).log, SECRET_CUSTODY_AUDIT_DIR),+ {+ timestamp: new Date().toISOString(),+ actor: "cli",+ action,+ target: name,+ ok: true,+ details,+ },+ vault,+ );}diff --git a/src/core/brain/session-lifecycle.ts b/src/core/brain/session-lifecycle.tsindex d090cf53..0582f6bc 100644--- a/src/core/brain/session-lifecycle.ts+++ b/src/core/brain/session-lifecycle.ts@@ -540,6 +540,7 @@ export async function captureSessionLifecycleEvent(...counters,},},+ vault,);return {diff --git a/src/core/brain/signal.ts b/src/core/brain/signal.tsindex 6f87fbfd..4a749af8 100644--- a/src/core/brain/signal.ts+++ b/src/core/brain/signal.ts@@ -24,7 +24,16 @@* identical files β a property exercised by the roundtrip test.*/-import { join, relative } from "node:path";+import { dualWrite } from "../store/dual-write.ts";+import { isPrivateFrontmatter, signalRecord } from "../store/dual-write-records.ts";+import {+ callerInput,+ operationPrivacy,+ SIGNAL_OPAQUE_FIELDS,+ type OperationPrivacy,+} from "../store/operation-privacy.ts";+import { withOperationPrivacy } from "../store/operation-scope.ts";+import { join, relative, resolve } from "node:path";import type { WriteSubject } from "./write-disposition.ts";import type { FrontmatterMap } from "../types.ts";@@ -351,6 +360,44 @@ export function writeSignal(validateSignalInput(sanitiseSignalInput(resolvedInput)),);+ // One privacy verdict for every store record this write produces (the+ // review gate's decision row, the signal and its idempotency receipt),+ // judged lazily so dual writes off judge nothing: the frontmatter+ // reserving the page as private, or any content field (`principle`,+ // `source`, `raw`, ...) naming a private or unresolvable page or carrying+ // a `<private>` region, or any field of the caller's input (its+ // idempotency key included) doing so. Judged from the frontmatter the+ // signal will carry; its final id (a collision suffix) is opaque, so the+ // first candidate's id judges the same. Every record written from here+ // on, by this call or any writer it calls, carries it+ // (`store/operation-scope.ts`).+ const candidate = renderSignalDocument(+ sanitised,+ `${signalPrefix(sanitised.date)}-${sanitised.slug}`,+ ).metadata;+ const privacy = operationPrivacy(vault, {+ target: () => isPrivateFrontmatter(candidate),+ content: [+ {+ value: { frontmatter: candidate, raw: sanitised.raw ?? null },+ opaque: SIGNAL_OPAQUE_FIELDS,+ },+ callerInput(input, SIGNAL_OPAQUE_FIELDS),+ ],+ });+ return withOperationPrivacy(privacy, () =>+ writeJudgedSignal(vault, input, options, resolvedInput, sanitised, privacy),+ );+}++function writeJudgedSignal(+ vault: string,+ input: WriteSignalInput,+ options: WriteSignalOptions,+ resolvedInput: WriteSignalInput,+ sanitised: WriteSignalInput,+ privacy: OperationPrivacy,+): WriteSignalResult {// Idempotency consult (C1): when a client key is supplied, hash the// semantic payload and check the ledger BEFORE allocating a slug or// touching disk. A prior write with the same key short-circuits here β@@ -444,6 +491,8 @@ export function writeSignal(),);+ const frontmatter = renderSignalDocument(sanitised, id).metadata;+// Record the key AFTER the file lands so a future retry dedupes. `ref`// stores the vault-relative path + id so the dedupe branch above can// return the original coordinates without re-deriving them.@@ -455,10 +504,31 @@ export function writeSignal(contentHash: hash,createdAt: sanitised.created_at,ref: { id, path: relative(vault, allocated.path) },+ private: privacy,}),);}+ // Brain store dual write (task 1.11): off by default, never fails this write.+ // `staged` says where the file landed: the review gate's staging, or an+ // explicit target that is the pending directory (`stagePendingSignal`).+ const landedStaged =+ gateStaged ||+ (options.targetDir !== undefined && resolve(options.targetDir) === resolve(dirs.pending));+ dualWrite(+ () =>+ signalRecord({+ vault,+ path: allocated.path,+ id,+ staged: landedStaged,+ frontmatter,+ raw: sanitised.raw,+ private: privacy(),+ }),+ { vault },+ );+return { path: allocated.path, id, staged: gateStaged };}diff --git a/src/core/brain/skill-proposals.ts b/src/core/brain/skill-proposals.tsindex 5b53303c..81916d8e 100644--- a/src/core/brain/skill-proposals.ts+++ b/src/core/brain/skill-proposals.ts@@ -73,6 +73,9 @@ import {type ContinuityRecord,} from "./continuity/store.ts";import type { ContinuityPayload } from "./continuity/types.ts";+import { dualWrite } from "../store/dual-write.ts";+import { DUAL_WRITE_LEDGERS, ledgerRowRecord } from "../store/dual-write-records.ts";+import { rowNamesPrivatePage } from "../store/reference-privacy.ts";/*** Pattern kind stamped on a proposal an author DECLARED through an@@ -361,12 +364,16 @@ export function learnSkillProposals({ minEvidence: minSupport },);if (!verdict.accepted) {- appendVerifierRejection(vault, {- id: proposalId,- name_key: nameKey,- reason: verdict.reason,- at: now.toISOString(),- });+ appendVerifierRejection(+ vault,+ {+ id: proposalId,+ name_key: nameKey,+ reason: verdict.reason,+ at: now.toISOString(),+ },+ candidate.supportingRecords,+ );verifierRejected.push(proposalId);continue;}@@ -2292,14 +2299,34 @@ export function verifierRejectionLedgerPath(vault: string): string {);}-/** Append one verifier-rejection record to the JSONL ledger. */+/**+ * Append one verifier-rejection record to the JSONL ledger. `sources` are+ * the continuity records the rejected candidate was drawn from.+ */function appendVerifierRejection(vault: string,entry: { id: string; name_key: string; reason: string; at: string },+ sources: ReadonlyArray<ContinuityRecord>,): void {const path = verifierRejectionLedgerPath(vault);mkdirSync(dirname(path), { recursive: true });appendFileSync(path, `${JSON.stringify(entry)}\n`, { encoding: "utf8" });+ // Brain store dual write (task 1.11): off by default, never fails this append.+ // The proposal's name is drawn from session turns: a row whose turns are+ // flagged private, or that names a private or unjudgeable page (in the+ // row or in those turns), goes to `private` only.+ dualWrite(+ () =>+ ledgerRowRecord(+ DUAL_WRITE_LEDGERS.verifierRejections,+ entry,+ sources.some((record) => record.private === true) ||+ rowNamesPrivatePage(vault, [entry, sources])+ ? "private"+ : "shared",+ ),+ { vault },+ );}function detectCandidates(diff --git a/src/core/brain/snapshot.ts b/src/core/brain/snapshot.tsindex 629395f4..578293c2 100644--- a/src/core/brain/snapshot.ts+++ b/src/core/brain/snapshot.ts@@ -271,8 +271,22 @@ export interface CreateSnapshotOptions extends SnapshotStoreOptions {export interface SnapshotInfo {readonly run_id: string;readonly path: string;- /** ISO-8601 UTC mtime of the archive file. */+ /**+ * ISO-8601 UTC creation time: the `generated_at` the manifest sidecar+ * recorded when the archive was taken, or the archive file's mtime when+ * there is no readable sidecar. The manifest wins because an mtime is a+ * property of the copy, not of the snapshot: `rsync -t`, `cp -p` or a+ * stepped clock rewrite it, and retention orders by this field.+ */readonly created_at: string;+ /**+ * Present only when the sidecar's `generated_at` was set aside for the+ * mtime: why it was not believed (later than now, or earlier than the+ * time the run id itself carries). A hand-edited sidecar or a broken+ * clock would otherwise pin one archive as the newest forever, and every+ * prune would then delete the genuinely newest ones.+ */+ readonly created_at_untrusted?: string;readonly size_bytes: number;/*** Absolute path of the sidecar manifest, or `null` when the@@ -424,7 +438,9 @@ export interface PruneSnapshotsOptions {/*** Run ids this pass must never remove, whatever the ordering says.*- * The retention order is by MTIME, and the caller that most needs this+ * The retention order was by MTIME when this was added (it is now the+ * manifest's creation time, falling back to mtime for an archive with+ * no readable sidecar), and the caller that most needs this* is the one that just wrote an archive: "the newest file is the newest* mtime" is an assumption about the filesystem, not arithmetic. `rsync* -t`, `cp -p`, an NFS server with clock skew, or a system clock@@ -1507,7 +1523,8 @@ function runArchiveProducer(// ----- listSnapshots / pruneSnapshots --------------------------------------/**- * Enumerate `.snapshots/*.tar.zst` in newest-first order (by mtime),+ * Enumerate `.snapshots/*.tar.zst` in newest-first order (by the+ * manifest's recorded creation time, see {@link SnapshotInfo.created_at}),* alongside the archive-shaped entries that could not be described.** Files outside the canonical naming pattern are skipped and NOT reported:@@ -1539,7 +1556,12 @@ export function listSnapshots(vault: string): SnapshotListing {throw new BrainSnapshotListingError(dirs.snapshots, err);}const infos: SnapshotInfo[] = [];+ // Archive mtimes, kept beside the rows only to break a creation-time+ // tie: the manifest records whole seconds, so two archives taken in+ // the same second compare equal on `created_at`.+ const mtimes = new Map<string, number>();const skipped: SnapshotEntrySkip[] = [];+ const nowMs = Date.now();for (const name of entries) {if (!name.endsWith(SNAPSHOT_ARCHIVE_SUFFIX)) continue;const runId = name.slice(0, -SNAPSHOT_ARCHIVE_SUFFIX.length);@@ -1579,10 +1601,13 @@ export function listSnapshots(vault: string): SnapshotListing {// the same file twice and could disagree if a peer rewrote it between// them.const manifest = readManifestSidecar(vault, runId);+ mtimes.set(runId, st.mtimeMs);+ const created = snapshotCreatedAt(manifest?.generated_at, st.mtimeMs, runId, nowMs);infos.push({run_id: runId,path: full,- created_at: new Date(st.mtimeMs).toISOString(),+ created_at: created.at,+ ...(created.untrusted !== null ? { created_at_untrusted: created.untrusted } : {}),size_bytes: st.size,manifest_path: existsSync(sidecar) ? sidecar : null,store_archive_path: existsSync(storeArchive) ? storeArchive : null,@@ -1596,14 +1621,87 @@ export function listSnapshots(vault: string): SnapshotListing {reason: manifest?.snapshot_reason ?? null,});}- // Sort newest-first by mtime. We deliberately avoid lexicographic- // sort on the run_id because manual rollback runs might use a- // non-timestamped id and we still want them to land where the- // operator's mental model expects (most recent first).- infos.sort((a, b) => Date.parse(b.created_at) - Date.parse(a.created_at));+ // Sort newest-first by recorded creation time, then by mtime within+ // the same second, then by run id so the order is total. We avoid a+ // lexicographic run_id sort as the primary key because manual rollback+ // runs might use a non-timestamped id and we still want them to land+ // where the operator's mental model expects (most recent first).+ infos.sort(+ (a, b) =>+ Date.parse(b.created_at) - Date.parse(a.created_at) ||+ (mtimes.get(b.run_id) ?? 0) - (mtimes.get(a.run_id) ?? 0) ||+ (a.run_id < b.run_id ? 1 : a.run_id > b.run_id ? -1 : 0),+ );return { snapshots: infos, skipped };}+/** How far ahead of now a sidecar stamp may be before it reads as a broken clock or an edit. */+const SNAPSHOT_STAMP_FUTURE_SKEW_MS = 5 * 60 * 1000;++/** Slack below the run id's time: both are whole seconds, and the sidecar is written after. */+const SNAPSHOT_STAMP_RUN_ID_SLACK_MS = 1000;++/**+ * The UTC time a run id carries (`<reason>-YYYY-MM-DD-HHMMSS`, with an+ * optional `-<n>` collision suffix), or `null` for an id without one.+ */+function runIdStampMs(runId: string): number | null {+ const m = /-(\d{4})-(\d{2})-(\d{2})-(\d{2})(\d{2})(\d{2})(?:-\d+)?$/.exec(runId);+ if (m === null) return null;+ const [year, month, day, hour, minute, second] = m.slice(1).map(Number) as [+ number,+ number,+ number,+ number,+ number,+ number,+ ];+ const ms = Date.UTC(year, month - 1, day, hour, minute, second);+ return Number.isFinite(ms) ? ms : null;+}++/**+ * The creation time retention orders by: the manifest's `generated_at`+ * when it parses as a date and is believable, else the archive's mtime.+ * An unparseable stamp falls back rather than sorting as `NaN`, which+ * would make the comparator inconsistent and the prune order undefined.+ * A stamp later than now (beyond a small skew) or earlier than the run+ * id's own time falls back too, and the reason is returned so the+ * listing can report it.+ */+function snapshotCreatedAt(+ generatedAt: string | undefined,+ mtimeMs: number,+ runId: string,+ nowMs: number,+): { readonly at: string; readonly untrusted: string | null } {+ let untrusted: string | null = null;+ if (generatedAt !== undefined) {+ const ms = Date.parse(generatedAt);+ if (Number.isFinite(ms)) {+ const runMs = runIdStampMs(runId);+ // Quoted as JSON: the stamp is printed, and a parseable one can still+ // carry a newline or a terminal escape inside a `(...)` comment. JSON+ // leaves DEL and the C1 controls (U+009B is a one-character CSI) as+ // they are, so those are escaped too.+ const shown = JSON.stringify(generatedAt).replace(+ /[\u007f-\u009f]/g,+ (c) => `\\u${c.charCodeAt(0).toString(16).padStart(4, "0")}`,+ );+ if (ms > nowMs + SNAPSHOT_STAMP_FUTURE_SKEW_MS) {+ untrusted = `the manifest's generated_at ${shown} is later than now`;+ } else if (runMs !== null && ms < runMs - SNAPSHOT_STAMP_RUN_ID_SLACK_MS) {+ untrusted =+ `the manifest's generated_at ${shown} is earlier than the run id's own time ` ++ new Date(runMs).toISOString();+ } else {+ return { at: new Date(ms).toISOString(), untrusted: null };+ }+ }+ }+ return { at: new Date(mtimeMs).toISOString(), untrusted };+}+/*** Delete all but the `retention_count` newest archives. Returns what it* removed, what resisted removal, how many archives survive, and - whendiff --git a/src/core/brain/templates.ts b/src/core/brain/templates.tsindex 2ef9d68a..dcc4455c 100644--- a/src/core/brain/templates.ts+++ b/src/core/brain/templates.ts@@ -9,7 +9,7 @@* rendered file rather than disappearing silently.*/-import { readFileSync, statSync } from "node:fs";+import { readFileSync } from "node:fs";import { dirname, join, resolve } from "node:path";import { fileURLToPath } from "node:url";@@ -26,6 +26,38 @@ const TEMPLATE_DIR = resolve(dirname(fileURLToPath(import.meta.url)), "templates/** Operating manual rendered at `Brain/_BRAIN.md`. */export const BRAIN_MANUAL_TEMPLATE_PATH = join(TEMPLATE_DIR, "_BRAIN.md.tpl");+/**+ * Revision of the manual template, rendered into the manual's frontmatter+ * as `template_revision:`. A manual without the line is revision 0.+ *+ * The manual is synced vault content and devices sharing a vault may run+ * different releases. Without an order between renderings, an older+ * release saw a newer release's manual as a pending upgrade and rewrote it+ * back, and the newer release upgraded it forward again, each step behind a+ * pre-apply snapshot. The upgrade plan now leaves a manual from a newer+ * revision as it is (`planManagedPath` in `upgrade.ts`).+ *+ * Bump it by one whenever the rendered manual changes (the template text,+ * or a release constant it renders), and set+ * {@link BRAIN_MANUAL_TEMPLATE_SHA256} to the new hash: a test fails while+ * the hash does not match, so a change cannot ship under an old revision.+ * The revision moves only with the template, so a release that leaves the+ * template alone causes no upgrade on any vault.+ */+export const BRAIN_MANUAL_TEMPLATE_REVISION = 1;++/**+ * SHA-256 (hex) of the manual as this release renders it with every+ * device-independent substitution applied (all but `vault_name`), line+ * endings normalised to LF, at {@link BRAIN_MANUAL_TEMPLATE_REVISION}. A+ * change to the template text OR to a release constant it renders+ * (`schema_version`, `manifest_sidecar_since`) changes the bytes every+ * device writes, so it fails the guard test until the revision is bumped.+ * Read only by that test.+ */+export const BRAIN_MANUAL_TEMPLATE_SHA256 =+ "40b711db15b7215225cc8218d12400dd72825f39fe859b8446a5665b32367804";+/** Directory holding the bundled Obsidian Bases view definitions. */export const BASES_TEMPLATE_DIR = join(TEMPLATE_DIR, "bases");@@ -80,6 +112,7 @@ export function buildSubstitutions(return new Map<string, string>([["vault_name", vaultDisplayName(vault)],["schema_version", String(config.schema_version)],+ ["template_revision", String(BRAIN_MANUAL_TEMPLATE_REVISION)],// The release the sidecar manifest shipped in. A substitution rather// than a literal in the template, because the same version is stated// in the rollback warning and in the verb help; one owner, three@@ -97,16 +130,18 @@ export function renderTemplate(template: string,substitutions: ReadonlyMap<string, string>,): string {- let out = template;- for (const [key, value] of substitutions) {- const pattern = new RegExp(`\\{\\{\\s*${escapeRegex(key)}\\s*\\}\\}`, "g");- // Function form keeps the substitution literal β string-form- // `replace` interprets `$&` / `$1` / `$n` / `$$` in `value` as- // backreference syntax. A vault name like `pay-$1` or- // `team-$everyone` would otherwise be silently mangled.- out = out.replace(pattern, () => value);- }- return out;+ if (substitutions.size === 0) return template;+ // One pass over the template: a substituted value is never scanned+ // again, so a value that itself reads `{{schema_version}}` (a vault name+ // kept from a synced manual, say) stays literal instead of being+ // expanded by a later key.+ const keys = [...substitutions.keys()].map(escapeRegex).join("|");+ const pattern = new RegExp(`\\{\\{\\s*(${keys})\\s*\\}\\}`, "g");+ // Function form keeps the substitution literal β string-form+ // `replace` interprets `$&` / `$1` / `$n` / `$$` in `value` as+ // backreference syntax. A vault name like `pay-$1` or+ // `team-$everyone` would otherwise be silently mangled.+ return template.replace(pattern, (match, key: string) => substitutions.get(key) ?? match);}/**@@ -125,56 +160,92 @@ export function renderBrainManual(}/**- * Render the manual for `vault`, keeping the `vault_name` spelling an- * existing manual already carries when that spelling names the SAME- * directory as `vault`.+ * Render the manual for `vault`, keeping the `vault_name` an existing+ * manual already carries.*- * The display name is the basename as the caller spelled the path. On a- * case-insensitive filesystem (macOS, Windows) `.../vault` and `.../Vault`- * open one directory, so two runtimes configured with the two spellings- * rendered two different manuals for one vault. Each saw the other's as a- * pending upgrade, and the start-up self-heal re-ran that upgrade, snapshot- * included, on every start.+ * The display name is the basename of the vault path on THIS device, but+ * the manual is synced vault content. A vault shared between a Mac+ * (`/Users/<user>/Vault`) and Linux hosts (`/root/vault`, `/srv/vault`)+ * gave every device its own spelling: each saw the manual another device+ * wrote as a pending upgrade, and the start-up self-heal rewrote it back,+ * pre-apply snapshot included, on every start of every device (hundreds of+ * `upgrade-*` snapshots on one live vault). The same happened with two+ * spellings of one directory on a case-insensitive filesystem.*- * The filesystem decides, not a platform guess: the existing spelling is- * kept only when it differs from ours by case alone AND a `stat` of the- * path under that spelling reaches the same file (device and inode, read as- * bigints so Windows file ids compare exactly). On a case-sensitive- * filesystem where `vault` and `Vault` are two directories the probe says- * so, and the manual is re-rendered as before.+ * So the name is decided once, when the manual is first written (or when+ * an existing manual has no `vault_name:` line), and kept from then on: a+ * device-local fact must never make synced content look stale. The cost is+ * cosmetic: a vault moved to a new directory name keeps its old display+ * name until the line is edited by hand.*/export function renderBrainManualFor(vault: string,existing: string | null,config: BrainConfig = DEFAULT_BRAIN_CONFIG,): string {- const rendered = renderBrainManual(vault, config);- if (existing === null) return rendered;- const ours = vaultDisplayName(vault);- const theirs = recordedVaultName(existing);- if (theirs === null || theirs === ours) return rendered;- if (theirs.toLowerCase() !== ours.toLowerCase()) return rendered;- if (!sameDirectory(vault, join(dirname(resolve(vault)), theirs))) return rendered;+ const recorded = existing === null ? null : recordedVaultName(existing);+ if (recorded === null) return renderBrainManual(vault, config);const substitutions = new Map(buildSubstitutions(vault, config));- substitutions.set("vault_name", theirs);+ substitutions.set("vault_name", recorded);return renderTemplate(readTemplate(BRAIN_MANUAL_TEMPLATE_PATH), substitutions);}-/** The `vault_name:` value a rendered manual carries, or null. */+/**+ * The frontmatter block of a rendered manual, or null. A leading UTF-8 BOM+ * (some Windows editors add one on save) is allowed before the opening+ * fence.+ */+function manualFrontmatter(manual: string): string | null {+ const match = /^\uFEFF?---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/.exec(manual);+ return match === null ? null : match[1]!;+}++/**+ * The `vault_name:` value a rendered manual carries in its frontmatter,+ * or null. A line in the body never counts: it would be lifted into the+ * frontmatter for good.+ */function recordedVaultName(manual: string): string | null {- const match = /^vault_name: (.+)$/m.exec(manual);- return match === null ? null : match[1]!.trim();+ const frontmatter = manualFrontmatter(manual);+ if (frontmatter === null) return null;+ const match = /^vault_name: (.+?)\r?$/m.exec(frontmatter);+ if (match === null) return null;+ const name = match[1]!.trim();+ return name === "" ? null : name;}-/** Whether two paths open the same file, by device and inode. */-function sameDirectory(a: string, b: string): boolean {- try {- const sa = statSync(a, { bigint: true });- const sb = statSync(b, { bigint: true });- return sa.dev === sb.dev && sa.ino === sb.ino;- } catch {- return false;- }+/**+ * The `template_revision:` a rendered manual carries in its frontmatter.+ * A manual without the line (written before the stamp existed), or with a+ * value that is not a non-negative integer, is revision 0.+ */+export function templateRevisionOf(manual: string): number {+ const frontmatter = manualFrontmatter(manual);+ if (frontmatter === null) return 0;+ const match = /^template_revision:[ \t]*(\d+)[ \t]*\r?$/m.exec(frontmatter);+ return match === null ? 0 : Number(match[1]);+}++/**+ * The manual's template revision when a newer release wrote it (higher than+ * {@link BRAIN_MANUAL_TEMPLATE_REVISION}), else null. Such a manual is never+ * rewritten back to this release's template.+ */+export function manualRevisionAhead(manual: string): number | null {+ const revision = templateRevisionOf(manual);+ return revision > BRAIN_MANUAL_TEMPLATE_REVISION ? revision : null;+}++/**+ * One line for a manual a newer release wrote, kept rather than rewritten+ * to this release's template. `o2b brain upgrade` and `o2b brain status`+ * both print it, so the two surfaces word it the same way.+ */+export function describeManualRevisionAhead(path: string, aheadRevision: number): string {+ return (+ `${path}: kept; written by a newer release (template revision ${aheadRevision}, ` ++ `this release ships ${BRAIN_MANUAL_TEMPLATE_REVISION})`+ );}/**diff --git a/src/core/brain/templates/_BRAIN.md.tpl b/src/core/brain/templates/_BRAIN.md.tplindex 4c6fbeb6..90dec29e 100644--- a/src/core/brain/templates/_BRAIN.md.tpl+++ b/src/core/brain/templates/_BRAIN.md.tpl@@ -2,6 +2,7 @@kind: brain-manualvault_name: {{vault_name}}schema_version: {{schema_version}}+template_revision: {{template_revision}}---# Brain β operating manualdiff --git a/src/core/brain/truth/store.ts b/src/core/brain/truth/store.tsindex 4977ec43..d4ab78e3 100644--- a/src/core/brain/truth/store.ts+++ b/src/core/brain/truth/store.ts@@ -61,6 +61,9 @@ import type {} from "./types.ts";import { TRUTH_SCHEMA_VERSION } from "./types.ts";import { assertVaultIdentityForWrite } from "../vault-identity.ts";+import { dualWrite } from "../../store/dual-write.ts";+import { truthClaimRowRecord } from "../../store/dual-write-records.ts";+import { claimSourceIsPrivate } from "../../store/reference-privacy.ts";/** Default cap on retained claim events (explicit sweep only). */export const CLAIM_EVENT_MAX_COUNT = 10000;@@ -372,6 +375,12 @@ export function appendClaimEvent(mkdirSync(truthDir(vault), { recursive: true });const path = claimShardPath(vault, opts.configPath);appendFileSync(path, JSON.stringify(event) + "\n");+ // Brain store dual write (task 1.11): off by default, never fails this append.+ // A claim taken from a private page goes to `private` only.+ dualWrite(() => truthClaimRowRecord(event, claimSourceIsPrivate(vault, event.source)), {+ vault,+ ...(opts.configPath !== undefined ? { configPath: opts.configPath } : {}),+ });writeTruthState(vault, computeTruthState(readClaimEvents(vault).events));return Object.freeze({ path, event });}diff --git a/src/core/brain/upgrade.ts b/src/core/brain/upgrade.tsindex 5c91d0e8..e8a48a3a 100644--- a/src/core/brain/upgrade.ts+++ b/src/core/brain/upgrade.ts@@ -27,8 +27,8 @@ import { appendLogEvent } from "./log.ts";import { brainConfigPath, brainManualPath, vaultRelative } from "./paths.ts";import { BrainConfigError, loadBrainConfig } from "./policy.ts";import { DEFAULT_BRAIN_CONFIG_YAML } from "./config-template.ts";-import { createSnapshot } from "./snapshot.ts";-import { renderBrainManualFor } from "./templates.ts";+import { takeSnapshot } from "./snapshot-gate.ts";+import { manualRevisionAhead, renderBrainManualFor } from "./templates.ts";import { isoSecond } from "./time.ts";import { BRAIN_LOG_EVENT_KIND, BRAIN_SNAPSHOT_REASON } from "./types.ts";import { assertVaultIdentityForWrite } from "./vault-identity.ts";@@ -55,6 +55,8 @@ export interface UpgradeFilePlan {* and `update`.*/readonly error: string;+ /** Set only on a `noop` row for a file a newer template revision wrote. */+ readonly aheadRevision?: number;}export interface UpgradePlan {@@ -131,6 +133,7 @@ export function planUpgrade(vault: string): UpgradePlan {brainManualPath(vault),vaultRelative(brainManualPath(vault), vault),(existing) => renderBrainManualFor(vault, existing),+ manualRevisionAhead,),...planCorruptedPreferences(vault),];@@ -155,8 +158,9 @@ export function planUpgrade(vault: string): UpgradePlan {* 3. Check every `update` row against the disk. A file that no* longer holds the bytes (or the absence) the plan read refuses* the whole run, naming each path, before anything is written.- * 4. `createSnapshot(vault, run_id)` β sidecar manifest comes- * along automatically. The run id includes a `upgrade-` prefix+ * 4. `takeSnapshot(vault, "upgrade")`: the sidecar manifest comes+ * along automatically and retention runs with this archive+ * protected. The run id includes a `upgrade-` prefix* so the operator can spot upgrade snapshots in `--list`.* 5. Write each `update` file via `atomicWriteFileSync` with* `expectBefore: file.before`, so an edit that landed during the@@ -224,9 +228,15 @@ export function applyUpgrade(vault: string, opts: ApplyUpgradeOptions = {}): Upg}const now = opts.now ?? new Date();- // One constant for the run-id prefix and the recorded reason.- const runId = `${BRAIN_SNAPSHOT_REASON.upgrade}-${isoSecondCompact(now)}`;- const snap = createSnapshot(vault, runId, { reason: BRAIN_SNAPSHOT_REASON.upgrade, now });+ // Through the gate, not `createSnapshot` directly: the gate is what+ // enforces `snapshots.retention_count` (with this archive protected).+ // Calling `createSnapshot` here let upgrade archives bypass retention+ // entirely; a live install that self-healed on every session start+ // held 911 of them. The gate also mints a collision-safe run id under+ // the same `upgrade-` prefix, so two applies in one second no longer+ // refuse each other.+ const snap = takeSnapshot(vault, BRAIN_SNAPSHOT_REASON.upgrade, { now });+ const runId = snap.runId;const updated: string[] = [];for (const file of plan.files) {@@ -323,6 +333,7 @@ function planManagedPath(absolutePath: string,relPath: string,renderTarget: (existing: string | null) => string,+ revisionAhead: (existing: string) => number | null,): UpgradeFilePlan {if (!existsSync(absolutePath)) {// File missing entirely: an upgrade should restore it. Treat as@@ -335,6 +346,10 @@ function planManagedPath(} catch (err) {return makeError(relPath, `read failed: ${(err as Error).message}`);}+ // A synced file from a newer release is never rewritten back: devices on+ // two releases otherwise rewrote it in turn, a snapshot each time.+ const ahead = revisionAhead(before);+ if (ahead !== null) return Object.freeze({ ...makeNoop(relPath), aheadRevision: ahead });// The target is rendered against what is on disk, so a rendering that// may legitimately keep an existing spelling (the vault name on a// case-insensitive filesystem) can.@@ -403,14 +418,6 @@ function midApplyDriftMessage(drifted: string, updated: ReadonlyArray<string>):);}-/**- * Compact ISO without colons or `Z` suffix so the run id is- * filesystem-safe under every snapshot validator.- */-function isoSecondCompact(d: Date): string {- return isoSecond(d).replace(/[:Z]/g, "");-}-/*** `applyUpgrade` is callable from tests that may not have set up a* real plugin config. Fall back to an empty path string sodiff --git a/src/core/brain/watchdog.ts b/src/core/brain/watchdog.tsindex 091b39c2..25415002 100644--- a/src/core/brain/watchdog.ts+++ b/src/core/brain/watchdog.ts@@ -5,7 +5,7 @@ import { appendAuditRecord, type AuditRecord } from "../reliability/audit.ts";import { buildProbeReport, type ProbeCheck, type ProbeReport } from "../reliability/probe.ts";import { WATCHDOG_AUDIT_DIR, WATCHDOG_FALLBACK_AUDIT_DIR } from "./audit-dirs.ts";import { DERIVED_STORE_DIR } from "./path-constants.ts";-import { resolveIndexPath } from "../search/paths.ts";+import { resolveConfiguredIndexPath } from "../search/paths.ts";import {BRAIN_CONFIG_FILE,BRAIN_INBOX_REL,@@ -135,7 +135,7 @@ export function runBrainWatchdog(vault: string, opts: WatchdogOptions = {}): Bra}}- const indexPath = resolveIndexPath(vault, null);+ const indexPath = resolveConfiguredIndexPath(vault);const indexKind = pathKind(indexPath);if (indexKind === "file") {checks.push({@@ -260,16 +260,20 @@ export function watchdogFallbackAuditDir(vault: string): string {function appendWatchdogAudit(vault: string, logDir: string, record: AuditRecord): string {try {- return appendAuditRecord(join(logDir, WATCHDOG_AUDIT_DIR), record);+ return appendAuditRecord(join(logDir, WATCHDOG_AUDIT_DIR), record, vault);} catch (error) {- return appendAuditRecord(watchdogFallbackAuditDir(vault), {- ...record,- ok: false,- details: {- ...record.details,- audit_fallback_reason: (error as Error).message ?? String(error),+ return appendAuditRecord(+ watchdogFallbackAuditDir(vault),+ {+ ...record,+ ok: false,+ details: {+ ...record.details,+ audit_fallback_reason: (error as Error).message ?? String(error),+ },},- });+ vault,+ );}}diff --git a/src/core/brain/write-batch-privacy.ts b/src/core/brain/write-batch-privacy.tsnew file mode 100644index 00000000..b88577be--- /dev/null+++ b/src/core/brain/write-batch-privacy.ts@@ -0,0 +1,145 @@+/**+ * The privacy verdict of a write batch (`store/operation-privacy.ts`): one+ * verdict for the whole batch, judged from its operations once, when the+ * batch writes its first store record (after every operation validated,+ * and never with dual writes off), and handed to every store record the+ * batch writes (each operation's log event, each note-write event, each+ * evidence record, every inner idempotency receipt and the batch's+ * request receipt). The records of one batch so never land in different+ * partitions.+ *+ * The batch's whole caller input is judged as content: every field of+ * every operation object (its `agent`, its `idempotency_key`, any field a+ * later operation kind adds) and the request id, so no caller field can+ * reach a record body without the verdict having seen it. Keys, ids and+ * local settings are opaque ({@link BATCH_INPUT_OPAQUE}): checked for a+ * `<private>` region, never judged as page references.+ *+ * A batch is also private when any operation is, by the rule each+ * operation's own writer applies, so the batch verdict covers every inner+ * verdict:+ *+ * - `apply_evidence`: the evidence call's own verdict+ * (`applyEvidencePrivacy`): its preference is private or cannot be+ * judged, or its event names a private page or carries a region; a call+ * that would be refused cannot be judged and counts as private;+ * - `append_log_line`: the note event's own verdict (`brainNotePrivacy`);+ * - `create_note`: the frontmatter it creates reserves the page as+ * private, or its frontmatter or content names a private page or+ * carries a region;+ * - `update_note`, `append_note`: the page it changes is private or+ * cannot be judged (missing, unreadable, outside the vault), the+ * frontmatter an update merges reserves it, or the text it writes names+ * a private page or carries a region.+ *+ * Note pages have no store copy of their own; their privacy reaches the+ * store through the batch's log events and receipt.+ */++import { existsSync } from "node:fs";++import { isPrivateFrontmatter, isPrivatePageFile } from "../store/dual-write-records.ts";+import {+ callerInput,+ opaqueFields,+ operationPrivacy,+ type JudgedContent,+ type OperationPrivacy,+ type PrivacyVerdict,+} from "../store/operation-privacy.ts";+import { applyEvidencePrivacy, type AppendApplyEvidenceInput } from "./apply-evidence.ts";+import { brainNotePrivacy } from "./note.ts";+import { resolveNoteTarget } from "./notes/create-note.ts";+import { createNotePrivacy, type JudgedCreate } from "./notes/create-note-privacy.ts";++/**+ * The fields of a batch operation this judge reads. Structural, so this+ * module does not import the batch kernel that imports it.+ */+export type JudgedOperation =+ | { readonly kind: "apply_evidence"; readonly input: AppendApplyEvidenceInput }+ | { readonly kind: "append_log_line"; readonly input: { readonly text: string } }+ | ({ readonly kind: "create_note" } & JudgedCreate)+ | {+ readonly kind: "update_note";+ readonly path: string;+ readonly frontmatter?: Readonly<Record<string, unknown>>;+ readonly body?: string;+ }+ | { readonly kind: "append_note"; readonly path: string; readonly content: string };++/**+ * Fields of a batch's input that are keys, ids or local settings: the+ * request id, each operation's kind, an inner idempotency key, a clock and+ * a config path an `append_log_line` input may carry.+ */+const BATCH_INPUT_OPAQUE: ReadonlySet<string> = opaqueFields("requestId", "now", "configPath");++/**+ * The single privacy verdict of a batch of `operations` sent under+ * `requestId`. `readable` is the caller's read filter, as the evidence+ * writer applies it.+ */+export function writeBatchPrivacy(+ vault: string,+ operations: ReadonlyArray<unknown>,+ requestId: string | undefined,+ readable?: (rel: string) => boolean,+): OperationPrivacy {+ // Nothing is read from the operations until a record is written: the+ // batch validates every operation first, and a malformed one must+ // surface as its indexed batch error, not as whatever reading it here+ // throws. Once judged, a shape this judge cannot read counts as private.+ return operationPrivacy(vault, {+ content: [callerInput({ operations, requestId: requestId ?? null }, BATCH_INPUT_OPAQUE)],+ inherit: [+ () =>+ operations.some((op) => {+ const verdict = operationVerdict(vault, op as JudgedOperation, readable);+ return typeof verdict === "function" ? verdict() : verdict;+ }),+ ],+ });+}++function operationVerdict(+ vault: string,+ op: JudgedOperation,+ readable: ((rel: string) => boolean) | undefined,+): PrivacyVerdict {+ switch (op.kind) {+ case "apply_evidence":+ return applyEvidencePrivacy(vault, op.input, readable);+ case "append_log_line":+ return brainNotePrivacy(vault, op.input);+ case "create_note":+ return createNotePrivacy(vault, op);+ case "update_note":+ return operationPrivacy(vault, {+ target: () => pageIsPrivate(vault, op.path) || isPrivateFrontmatter(op.frontmatter ?? {}),+ content: [text({ frontmatter: op.frontmatter ?? null, body: op.body ?? null })],+ });+ case "append_note":+ return operationPrivacy(vault, {+ target: () => pageIsPrivate(vault, op.path),+ content: [text({ content: op.content })],+ });+ default:+ return true;+ }+}++function text(value: unknown): JudgedContent {+ return { value };+}++/** A page that cannot be resolved, found or read counts as private. */+function pageIsPrivate(vault: string, path: string): boolean {+ let abs: string;+ try {+ abs = resolveNoteTarget(vault, path).abs;+ } catch {+ return true;+ }+ return !existsSync(abs) || isPrivatePageFile(abs);+}diff --git a/src/core/brain/write-batch.ts b/src/core/brain/write-batch.tsindex 4bf6f667..0cd3e90c 100644--- a/src/core/brain/write-batch.ts+++ b/src/core/brain/write-batch.ts@@ -63,6 +63,9 @@ import { preferencePath, validateSlug } from "./paths.ts";import { refuseDocumentDeny, type WriteSubject } from "./write-disposition.ts";import { REVIEW_LANE } from "./write-gate.ts";import { assertVaultIdentityForWrite } from "./vault-identity.ts";+import { writeBatchPrivacy } from "./write-batch-privacy.ts";+import type { OperationPrivacy } from "../store/operation-privacy.ts";+import { withOperationPrivacy } from "../store/operation-scope.ts";import { BRAIN_APPLY_RESULT } from "./types.ts";import { ROUTE_STAGE, timeStageSync } from "../route-scope.ts";import {@@ -498,36 +501,50 @@ export function applyWriteBatch(// op against the pre-batch disk state means a second op on the same file// would silently clobber the first at commit time. Refuse it loudly.const noteTargets = new Set<string>();- const planned: PlannedOperation[] = operations.map((operation, index) =>- projectOperation(vault, operation, index, noteTargets, opts),- );+ // One privacy verdict for every store record the batch writes (its log+ // events, note-write events, evidence records, inner receipts and its+ // request receipt),+ // judged from the operations only when the first record is written,+ // after every operation validated (`write-batch-privacy.ts`).+ const privacy = writeBatchPrivacy(vault, operations, requestId, opts.readable);+ // Every store record written from here on, by the batch or by any+ // writer it calls (a note's owner-write decision row included), carries+ // this verdict (`operation-scope.ts`).+ return withOperationPrivacy(privacy, () => {+ const planned: PlannedOperation[] = operations.map((operation, index) =>+ projectOperation(vault, operation, index, noteTargets, opts, privacy),+ );- const results = planned.map((p) => p.commit());- const result: WriteBatchResult = { applied: operations.length, results, done: true };- if (idempotency !== undefined && requestId !== undefined) {- // Record AFTER the commit so a sequential retry dedupes against a- // durable receipt. `rememberKey` re-checks under its shard lock; the- // residual crash window between commit and record is the one the- // ledger documents for every writer that follows this pattern.- const stored: Readonly<Record<string, unknown>> = {- applied: result.applied,- results: result.results.map((opResult) => storedOpResult(vault, opResult)),- done: result.done,- };- const remembered = rememberKey(vault, {- key: requestId,- namespace: WRITE_BATCH_KEY_NAMESPACE,- contentHash: idempotency.contentHash,- ref: stored,- });- // The unlocked consult above can miss a concurrent call's record; the- // locked re-check's verdict is acted on, never dropped. Either way this- // call's writes have landed, so the verdict is a receipt status on the- // committed result, never an error that would read as "nothing- // written" and invite a second application under a fresh ID.- return { ...result, receipt: { requestId, status: RECEIPT_STATUS_FOR[remembered.status] } };- }- return result;+ const results = planned.map((p) => p.commit());+ const result: WriteBatchResult = { applied: operations.length, results, done: true };+ if (idempotency !== undefined && requestId !== undefined) {+ // Record AFTER the commit so a sequential retry dedupes against a+ // durable receipt. `rememberKey` re-checks under its shard lock; the+ // residual crash window between commit and record is the one the+ // ledger documents for every writer that follows this pattern.+ const stored: Readonly<Record<string, unknown>> = {+ applied: result.applied,+ results: result.results.map((opResult) => storedOpResult(vault, opResult)),+ done: result.done,+ };+ // The receipt's coordinates do not say what the batch touched, so the+ // batch hands the ledger its own verdict for the store copy.+ const remembered = rememberKey(vault, {+ key: requestId,+ namespace: WRITE_BATCH_KEY_NAMESPACE,+ contentHash: idempotency.contentHash,+ ref: stored,+ private: privacy,+ });+ // The unlocked consult above can miss a concurrent call's record; the+ // locked re-check's verdict is acted on, never dropped. Either way this+ // call's writes have landed, so the verdict is a receipt status on the+ // committed result, never an error that would read as "nothing+ // written" and invite a second application under a fresh ID.+ return { ...result, receipt: { requestId, status: RECEIPT_STATUS_FOR[remembered.status] } };+ }+ return result;+ });}/** The receipt status of a committed batch, by the locked re-check's verdict. */@@ -607,19 +624,47 @@ function projectOperation(index: number,noteTargets: Set<string>,opts: ApplyWriteBatchOptions,+ privacy: OperationPrivacy,): PlannedOperation {const kind = (operation as { readonly kind?: unknown } | null | undefined)?.kind;switch (kind) {case "create_note":- return projectCreateNote(vault, operation as CreateNoteOperation, index, noteTargets, opts);+ return projectCreateNote(+ vault,+ operation as CreateNoteOperation,+ index,+ noteTargets,+ opts,+ privacy,+ );case "update_note":- return projectUpdateNote(vault, operation as UpdateNoteOperation, index, noteTargets, opts);+ return projectUpdateNote(+ vault,+ operation as UpdateNoteOperation,+ index,+ noteTargets,+ opts,+ privacy,+ );case "append_note":- return projectAppendNote(vault, operation as AppendNoteOperation, index, noteTargets, opts);+ return projectAppendNote(+ vault,+ operation as AppendNoteOperation,+ index,+ noteTargets,+ opts,+ privacy,+ );case "apply_evidence":- return projectApplyEvidence(vault, operation as ApplyEvidenceOperation, index, opts.readable);+ return projectApplyEvidence(+ vault,+ operation as ApplyEvidenceOperation,+ index,+ opts.readable,+ privacy,+ );case "append_log_line":- return projectAppendLogLine(vault, operation as AppendLogLineOperation, index);+ return projectAppendLogLine(vault, operation as AppendLogLineOperation, index, privacy);default:throw new WriteBatchError("invalid_operation",@@ -678,6 +723,7 @@ function projectCreateNote(index: number,noteTargets: Set<string>,opts: ApplyWriteBatchOptions,+ privacy: OperationPrivacy,): PlannedOperation {const target = reserveNoteTarget(vault, op.path, index, noteTargets);// The owner gate at PROJECTION (write-side-trust, Task 13): a@@ -714,6 +760,7 @@ function projectCreateNote(...(op.content !== undefined ? { content: op.content } : {}),...(opts.configPath !== undefined ? { configPath: opts.configPath } : {}),...(opts.subject !== undefined ? { subject: opts.subject } : {}),+ storePrivate: privacy,});if (res.outcome === "staged") {// The review gate staged the create (write-side trust, Task 9).@@ -845,6 +892,7 @@ function projectUpdateNote(index: number,noteTargets: Set<string>,opts: ApplyWriteBatchOptions,+ privacy: OperationPrivacy,): PlannedOperation {if (op.frontmatter === undefined && op.body === undefined) {throw new WriteBatchError(@@ -954,6 +1002,7 @@ function projectUpdateNote(contents,NOTE_WRITE_OP.update,opts,+ privacy,);// The warn row the projection's verdict asked for, logged only when// the write actually commits - never during projection, where a@@ -1001,6 +1050,7 @@ function projectAppendNote(index: number,noteTargets: Set<string>,opts: ApplyWriteBatchOptions,+ privacy: OperationPrivacy,): PlannedOperation {if (typeof op.content !== "string" || op.content.trim().length === 0) {throw new WriteBatchError(@@ -1037,6 +1087,7 @@ function projectAppendNote(contents,NOTE_WRITE_OP.append,opts,+ privacy,);// Honest for the same reason the update's flag is: a rewrite whose// bytes already sit on disk (a hand-edited note that already@@ -1104,6 +1155,7 @@ function commitNoteRewrite(contents: string,op: NoteWriteOp,opts: ApplyWriteBatchOptions,+ privacy: OperationPrivacy,): CommittedNoteRewrite {if (before === contents) return { wrote: false };storeBeforeImage(vault, before);@@ -1117,6 +1169,7 @@ function commitNoteRewrite(before: { bytes: before },after: { bytes: contents },...(opts.configPath !== undefined ? { configPath: opts.configPath } : {}),+ storePrivate: privacy,}),);return { wrote: true, ...audit };@@ -1141,6 +1194,7 @@ function projectApplyEvidence(op: ApplyEvidenceOperation,index: number,readable: ((rel: string) => boolean) | undefined,+ privacy: OperationPrivacy,): PlannedOperation {const input = op.input;if (input === null || typeof input !== "object") {@@ -1205,6 +1259,7 @@ function projectApplyEvidence(const res = appendApplyEvidence(vault, input, {...op.options,...(readable !== undefined ? { readable } : {}),+ storePrivate: privacy,});return { kind: "apply_evidence", logged_at: res.logged_at, log_path: res.log_path };},@@ -1220,6 +1275,7 @@ function projectAppendLogLine(vault: string,op: AppendLogLineOperation,index: number,+ privacy: OperationPrivacy,): PlannedOperation {const input = op.input;if (@@ -1236,7 +1292,7 @@ function projectAppendLogLine(}return {commit: () => {- const res = appendBrainNote({ vault, ...input });+ const res = appendBrainNote({ vault, ...input, storePrivate: privacy });return { kind: "append_log_line", logged_at: res.logged_at, log_path: res.log_path };},};diff --git a/src/core/config.ts b/src/core/config.tsindex f57507d2..08e46771 100644--- a/src/core/config.ts+++ b/src/core/config.ts@@ -29,6 +29,7 @@ import {type WikiLinkFormat,} from "./brain/link-graph/format-wikilink.ts";import type { LinkOutputFormat } from "./brain/wikilink.ts";+import { STORE_DUAL_WRITE_CONFIG_KEY, STORE_DUAL_WRITE_ENV } from "./store/constants.ts";import type { ConfigDiscovery } from "./types.ts";/**@@ -505,22 +506,74 @@ const SHARED_NAMESPACE_KEY = "shared_namespace";*/export const DEVICE_ID_RE = /^[a-z0-9][a-z0-9-]{0,31}$/;+/**+ * Names Windows reserves for devices in every path component (`nul`,+ * `con`, `com1`, ...): there a directory under such a name makes writes+ * vanish or reads block. Device ids carry no dot, so the reserved forms+ * with an extension cannot occur.+ */+const WINDOWS_RESERVED_DEVICE_NAME_RE = /^(con|prn|aux|nul|com[1-9]|lpt[1-9])$/;++/**+ * Whether `value` has the shape of a device id. Platform-independent: it+ * judges data that comes from peers (record envelopes, shard listings,+ * folds, digests, log shards), and every machine must accept the same+ * records or their folds and digests stop matching across platforms. A+ * Windows reserved name is a valid id here; choosing this machine's own+ * id is {@link isUsableLocalDeviceId}.+ */export function isValidDeviceId(value: string): boolean {return DEVICE_ID_RE.test(value) && !value.startsWith("sync-conflict");}+/** Whether `value` is one of the names Windows reserves for devices (`nul`, `con`, ...). */+export function isWindowsReservedDeviceId(value: string): boolean {+ return WINDOWS_RESERVED_DEVICE_NAME_RE.test(value);+}++/**+ * Whether `value` may be THIS machine's device id on `platform`. A new id+ * is never a Windows reserved name on any platform (the generated form+ * cannot be one). An existing configured reserved id is refused only on+ * Windows: a POSIX machine whose id is one of them keeps it, so its log+ * shards and store directories stay under that name.+ */+export function isUsableLocalDeviceId(+ value: string,+ platform: NodeJS.Platform = process.platform,+): boolean {+ return isValidDeviceId(value) && !(platform === "win32" && isWindowsReservedDeviceId(value));+}++/** Environment variable that overrides the machine config's `device_id`. */+export const DEVICE_ID_ENV = "O2B_DEVICE_ID";++/**+ * The device id {@link resolveDeviceId} would answer, read without+ * minting one: null when the env override opts out (the empty string)+ * or when no valid id is configured yet. For readers that must agree+ * with the writers' identity but must never write the machine config.+ */+export function readDeviceId(configPath?: string | null): string | null {+ const env = process.env[DEVICE_ID_ENV];+ if (env === "") return null;+ if (env !== undefined && isUsableLocalDeviceId(env)) return env;+ const value = discoverConfig(configPath ?? defaultConfigPath()).data["device_id"];+ return value !== undefined && isUsableLocalDeviceId(value) ? value : null;+}+export function resolveDeviceId(configPath?: string): string {// Env override: a valid id wins outright; the empty string opts out// of sharding (legacy single-file log pair). The test preload pins// this to "" so the suite stays deterministic; an invalid value// falls through to config resolution.- const env = process.env["O2B_DEVICE_ID"];- if (env !== undefined && (env === "" || isValidDeviceId(env))) return env;+ const env = process.env[DEVICE_ID_ENV];+ if (env !== undefined && (env === "" || isUsableLocalDeviceId(env))) return env;const resolved = configPath ?? defaultConfigPath();const read = (): string | null => {const value = discoverConfig(resolved).data["device_id"];- return value && isValidDeviceId(value) ? value : null;+ return value && isUsableLocalDeviceId(value) ? value : null;};const existing = read();@@ -989,6 +1042,17 @@ export function resolveNearDuplicateWriteWideningEnabled(configPath?: string): b);}+/**+ * Brain store dual writes (task 1.11, a phase 1 trial). Default OFF: the+ * legacy writers write only the vault tree. When on, every covered legacy+ * write also appends the equivalent record to the brain store+ * (`src/core/store/dual-write.ts`); a store failure never fails the+ * legacy write. Env twin: `OPEN_SECOND_BRAIN_STORE_DUAL_WRITE`.+ */+export function resolveStoreDualWrite(configPath?: string): boolean {+ return resolveConfigFlag(STORE_DUAL_WRITE_ENV, STORE_DUAL_WRITE_CONFIG_KEY, configPath);+}+/*** SessionEnd handoff-note gate (Agent Surface Suite, t_28afa4d2).* Default OFF: lifecycle capture writes no handoff note unlessdiff --git a/src/core/install/ownership.ts b/src/core/install/ownership.tsindex 257c7a9d..31140663 100644--- a/src/core/install/ownership.ts+++ b/src/core/install/ownership.ts@@ -388,6 +388,48 @@ export const OUT_OF_VAULT_STATE: ReadonlyArray<OutOfVaultState> = Object.freeze("carries numbers, names and timestamps - never vault text.",sources: ["src/core/decision-model/thresholds.ts", "src/core/decision-model/config.ts"],},+ {+ id: "brain_store",+ label: "brain store",+ location: WINDOWS+ ? `%OPEN_SECOND_BRAIN_STORE_ROOT%, else the store_root config key, else (${describeBaseDir("data", "win32")})\\open-second-brain\\store\\`+ : "${OPEN_SECOND_BRAIN_STORE_ROOT:-the store_root config key, else ${XDG_DATA_HOME:-~/.local/share}/open-second-brain/store}/",+ carries_memory: true,+ created_by:+ "the first brain store dual write, only while the store_dual_write setting (a phase 1 trial, off by default) is on",+ removed_by: "deleting that directory yourself; it is the store's only copy on this machine",+ note:+ "The documented append-only store of Open Second Brain machine data (FORMAT.md inside it), " ++ "kept outside the vault on purpose: a store root inside the vault is refused. Its shared " ++ "and private partition folders are what a user syncs between machines.",+ sources: ["src/core/store/store-paths.ts"],+ },+ {+ id: "brain_store_device_state",+ label: "brain store device-local state",+ location: WINDOWS+ ? `(${describeBaseDir("state", "win32")})\\open-second-brain\\stores\\`+ : "${XDG_STATE_HOME:-~/.local/state}/open-second-brain/stores/",+ carries_memory: true,+ created_by:+ "the first write to a brain store from this machine, the first search index build while a " ++ "brain store is in use, or the first failed or skipped dual write (dual-write.json)",+ removed_by:+ "deleting that directory yourself while nothing writes to the store; locks and the clock " ++ "are recreated, the dual-write failure and skip counters the doctor reports start again " ++ "from zero, and `o2b search index` rebuilds the search index",+ note:+ "Append locks, blob temp files, the persisted hybrid logical clock of this device and, " ++ "while a brain store is in use, the search index (index/<vault key>/ under the store id, " ++ "a copy of every indexed chunk), in one directory per store id, plus dual-write.json, the " ++ "counter of failed or skipped dual writes the doctor reports. It is never synced and never " ++ "lives inside the store, so another machine never sees a lock or a clock of this one.",+ sources: [+ "src/core/store/store-paths.ts",+ "src/core/platform-dirs.ts",+ "src/core/search/brain-store/location.ts",+ ],+ },]);/**@@ -616,6 +658,12 @@ export const SOURCES_INVISIBLE_TO_THE_SWEEP: ReadonlyMap<string, string> = new M"directory its caller hands it and builds no root of its own, so there is no home or XDG " +"token in the source to match on",],+ [+ "src/core/search/brain-store/location.ts",+ "the store index path is `join(store.deviceStateDir, ...)`: the device-local state directory " ++ "arrives from `deviceStateDirFor()` in src/core/store/store-paths.ts, which IS swept, so " ++ "no home or XDG token appears in this file's own source",+ ],["src/core/search/paths.ts","the relocated index path comes from OPEN_SECOND_BRAIN_SEARCH_DB or search_db_path, an " +diff --git a/src/core/platform-dirs.ts b/src/core/platform-dirs.tsindex 5cbd9f93..2625264a 100644--- a/src/core/platform-dirs.ts+++ b/src/core/platform-dirs.ts@@ -34,7 +34,7 @@*/import { homedir } from "node:os";-import { join, win32 } from "node:path";+import { join, posix, win32 } from "node:path";/** Injected view of the environment the resolvers read. */export interface PlatformDirsEnv {@@ -99,7 +99,9 @@ function baseDir(kind: BaseKind, source: PlatformDirsEnv): string {const xdg = nonEmpty(source.env[XDG_VARIABLE[kind]]);if (xdg) return xdg;if (isWindows(source)) return windowsLocalAppData(source);- return join(source.home, ...POSIX_DEFAULT[kind]);+ // A POSIX layout keeps POSIX separators even when resolved on a Windows+ // host (an injected source), so callers joining onto it stay consistent.+ return posix.join(source.home, ...POSIX_DEFAULT[kind]);}/**diff --git a/src/core/reliability/audit.ts b/src/core/reliability/audit.tsindex 20b14e6c..1065ade9 100644--- a/src/core/reliability/audit.ts+++ b/src/core/reliability/audit.ts@@ -1,5 +1,5 @@import { closeSync, fsyncSync, mkdirSync, openSync, writeFileSync } from "node:fs";-import { join } from "node:path";+import { basename, join } from "node:path";import { redactRawOutput } from "../redactor.ts";import {@@ -8,6 +8,10 @@ import {shardedFileName,type LedgerShardGrammar,} from "../brain/ledger-shards.ts";+import { dualWrite } from "../store/dual-write.ts";+import { auditRowRecord, DUAL_WRITE_LEDGERS } from "../store/dual-write-records.ts";+import { isRecordLabel } from "../store/envelope.ts";+import { logRefsNamePrivatePage } from "../store/reference-privacy.ts";// The one value this module reads at module-evaluation time is declared in// the leaf `path-constants.ts` and re-exported by `ledger-shards.ts` (see// that constant's docblock for the import cycle that motivated the move).@@ -36,7 +40,12 @@ export interface AuditRecord {readonly details?: Record<string, unknown>;}-export function appendAuditRecord(auditRoot: string, record: AuditRecord): string {+/**+ * Append `record` to the week shard under `auditRoot`. `vault` is the vault+ * the trail belongs to: the brain store dual write refuses a store root+ * inside it, as it does for every other legacy write.+ */+export function appendAuditRecord(auditRoot: string, record: AuditRecord, vault?: string): string {const timestamp = new Date(record.timestamp);if (!Number.isFinite(timestamp.getTime())) {throw new Error(`invalid audit timestamp: ${record.timestamp}`);@@ -62,9 +71,48 @@ export function appendAuditRecord(auditRoot: string, record: AuditRecord): strin} finally {closeSync(fileDescriptor);}+ // Brain store dual write (task 1.11): the redacted row, exactly as written,+ // with the trail it belongs to. Every audit trail (hygiene, secret custody,+ // hook audit, watchdog, schema mutations, ...) shares this one store+ // ledger, so the directory name is what maps a row back to its trail.+ // Audit rows go to `private` when this machine holds it, else `shared`;+ // a row whose target or details name a private page goes to `private`+ // only, judged by the rule the Brain log events use.+ dualWrite(+ () => {+ const written = JSON.parse(line) as AuditRecord;+ return auditRowRecord(+ DUAL_WRITE_LEDGERS.reliabilityAudit,+ { audit_dir: basename(auditRoot), record: written },+ isRecordLabel(written.actor) ? written.actor : undefined,+ auditRowNamesPrivatePage(vault, written),+ );+ },+ vault !== undefined ? { vault } : {},+ );return path;}+/** Every string in `value`, nested arrays and objects included. */+function stringsIn(value: unknown, out: string[] = []): string[] {+ if (typeof value === "string") out.push(value);+ else if (Array.isArray(value)) for (const v of value) stringsIn(v, out);+ else if (value !== null && typeof value === "object") {+ for (const v of Object.values(value)) stringsIn(v, out);+ }+ return out;+}++/**+ * Whether an audit row names a private page through its target or the+ * strings in its details. Without the vault nothing can be judged, so the+ * row counts as private (fails closed).+ */+function auditRowNamesPrivatePage(vault: string | undefined, record: AuditRecord): boolean {+ if (vault === undefined) return true;+ return logRefsNamePrivatePage(vault, [record.target, ...stringsIn(record.details)]);+}+export function isoWeekLabel(input: Date): string {const date = new Date(Date.UTC(input.getUTCFullYear(), input.getUTCMonth(), input.getUTCDate()));const dayNumber = date.getUTCDay() || 7;diff --git a/src/core/search/brain-store/catch-up.ts b/src/core/search/brain-store/catch-up.tsnew file mode 100644index 00000000..6eaeeb40--- /dev/null+++ b/src/core/search/brain-store/catch-up.ts@@ -0,0 +1,428 @@+/**+ * Catch-up before reads (design D5, task 1.8): before a search or a change+ * probe answers, the index ingests every record appended to the brain+ * store since its watermark for each shard.+ *+ * The cheap path is the common one. At most once per+ * {@link catchUpIntervalMs} per process and index, the shards are listed+ * (directory listings cached by directory mtime) and stat'ed, and the+ * stats are compared with the watermarks this process last saw. When+ * nothing moved, the check ends there: no store file is opened and the+ * index is not opened either.+ *+ * When a shard moved, the index is opened for writing (only when no other+ * writer holds it, so a running rebuild never blocks a read) and each+ * changed shard is read from its stored offset through the store reader.+ * A shard whose identity changed, that shrank below its offset, or whose+ * verified prefix no longer hashes the same is re-read from offset 0; the+ * re-read is idempotent by record id, and records the shard no longer+ * holds are removed. A shard that disappeared takes its records with it,+ * except those a sibling shard still holds (`orphans.ts`).+ *+ * An index that is missing or not at the current schema is left alone:+ * the read's self-heal builds or upgrades it, and the rebuild ingests the+ * store into the staging file before the swap ({@link ingestStoreInto}).+ */++import { Database } from "bun:sqlite";++import { readDeviceId } from "../../config.ts";+import { closeDatabase } from "../../sqlite-close.ts";+import { observeClock } from "../../store/clock-store.ts";+import { compareHlc, parseHlc } from "../../store/hlc.ts";+import { readBlobBody, readShard } from "../../store/reader.ts";+import { blobPath, partitionDir } from "../../store/store-paths.ts";+import type { StorePartition } from "../../store/constants.ts";+import { LATEST_SCHEMA_VERSION, readSchemaVersion } from "../schema.ts";+import { Store } from "../store.ts";+import {+ deleteWatermark,+ hasBrainRecordTables,+ pendingRecords,+ readWatermarks,+ recordIdsOfShard,+ writeWatermark,+ type StoreWatermark,+} from "../store/brain-records.ts";+import { isWriterLockHeld } from "../store/writer-lock.ts";+import { SearchError, type ResolvedSearchConfig } from "../types.ts";+import { STORE_CATCH_UP_INTERVAL_ENV, STORE_CATCH_UP_INTERVAL_MS } from "./constants.ts";+import { completePendingRecord, ingestRecord } from "./ingest.ts";+import type { IndexedStore } from "./location.ts";+import { settleOrphans, type Orphans } from "./orphans.ts";+import { prefixHash } from "./prefix-hash.ts";+import { ShardScanner, statShardFile, type ShardStat } from "./shard-scan.ts";++/** Why a catch-up did not look at, or did not write, the store. */+export type CatchUpSkip =+ | "no-store"+ | "throttled"+ | "no-index"+ | "not-current"+ | "locked"+ | "failed";++export interface CatchUpResult {+ /** Null when the check ran to the end (whether or not anything changed). */+ readonly skipped: CatchUpSkip | null;+ /** Shards read in this pass. */+ readonly shardsRead: number;+ /** Records added to the index. */+ readonly added: number;+ /** Records removed because their shard no longer holds them. */+ readonly removed: number;+ /** Pending blob bodies that arrived and were indexed. */+ readonly completed: number;+ /** The failure, when {@link skipped} is `failed`. */+ readonly error?: string;+}++export interface CatchUpOptions {+ /** Ignore the throttle (a write path that must see the store now). */+ readonly force?: boolean;+}++type FileStat = Pick<ShardStat, "identity" | "size" | "mtimeMs">;++/** Per-process memory of one index's catch-up. */+interface ProcessState {+ readonly scanner: ShardScanner;+ readonly storeRoot: string;+ lastCheckMs: number;+ indexIdentity: string | null;+ /** Shard stats as of the watermarks last seen, or null when unknown. */+ known: Map<string, FileStat> | null;+ /**+ * Blob files whose arrival would complete a pending record, each with+ * its stat when last looked at (null: absent or not looked at yet). A+ * blob that is present but fails verification keeps its stat here, so+ * it triggers a write pass again only once it changes.+ */+ pendingBlobs: ReadonlyMap<string, FileStat | null>;+}++const states = new Map<string, ProcessState>();++const NOTHING = { shardsRead: 0, added: 0, removed: 0, completed: 0 } as const;++/**+ * Forget what this process last saw of the index at `dbPath`, so the next+ * catch-up reads its watermarks again: for a writer that emptied the+ * store tables behind catch-up's back.+ */+export function forgetCatchUpState(dbPath: string): void {+ states.delete(dbPath);+}++/** The throttle between two metadata passes, from the environment or the default. */+export function catchUpIntervalMs(env: NodeJS.ProcessEnv = process.env): number {+ const raw = env[STORE_CATCH_UP_INTERVAL_ENV]?.trim();+ if (raw === undefined || raw === "") return STORE_CATCH_UP_INTERVAL_MS;+ const n = Number(raw);+ return Number.isInteger(n) && n >= 0 ? n : STORE_CATCH_UP_INTERVAL_MS;+}++function stateFor(config: ResolvedSearchConfig, store: IndexedStore): ProcessState {+ const existing = states.get(config.dbPath);+ if (existing !== undefined && existing.storeRoot === store.root) return existing;+ const fresh: ProcessState = {+ scanner: new ShardScanner(store),+ storeRoot: store.root,+ lastCheckMs: Number.NEGATIVE_INFINITY,+ indexIdentity: null,+ known: null,+ pendingBlobs: new Map(),+ };+ states.set(config.dbPath, fresh);+ return fresh;+}++function sameStat(a: FileStat, b: FileStat): boolean {+ return a.identity === b.identity && a.size === b.size && a.mtimeMs === b.mtimeMs;+}++/** Whether any pending blob looks different from when it was last looked at. */+function blobMoved(pendingBlobs: ReadonlyMap<string, FileStat | null>): boolean {+ for (const [path, before] of pendingBlobs) {+ const now = statShardFile(path);+ if (now === null ? before !== null : before === null || !sameStat(before, now)) return true;+ }+ return false;+}++function unchanged(known: Map<string, FileStat>, shards: ReadonlyArray<ShardStat>): boolean {+ if (known.size !== shards.length) return false;+ return shards.every((s) => {+ const k = known.get(s.key);+ return k !== undefined && sameStat(k, s);+ });+}++function knownFrom(marks: Map<string, StoreWatermark>): Map<string, FileStat> {+ const out = new Map<string, FileStat>();+ for (const [key, m] of marks)+ out.set(key, { identity: m.identity, size: m.size, mtimeMs: m.mtimeMs });+ return out;+}++function pendingBlobPaths(store: IndexedStore, db: Database): string[] {+ return pendingRecords(db).map((r) =>+ blobPath(partitionDir(store.root, r.partition as StorePartition), r.sum),+ );+}++/** Watermarks and pending blobs of a current index, read-only; null when it is not current. */+function peekIndex(+ dbPath: string,+ store: IndexedStore,+): { known: Map<string, FileStat>; pendingBlobs: Map<string, FileStat | null> } | null {+ let db: Database;+ try {+ db = new Database(dbPath, { readonly: true });+ } catch {+ return null;+ }+ try {+ if (readSchemaVersion(db) !== LATEST_SCHEMA_VERSION || !hasBrainRecordTables(db)) return null;+ // Not looked at yet: a blob already present triggers one pass.+ const pendingBlobs = new Map(pendingBlobPaths(store, db).map((p) => [p, null] as const));+ return { known: knownFrom(readWatermarks(db)), pendingBlobs };+ } catch {+ return null;+ } finally {+ closeDatabase(db);+ }+}++interface SyncTotals {+ shardsRead: number;+ added: number;+ removed: number;+ completed: number;+ /** Largest clock ingested from another device. */+ remoteHlc: string | null;+ /**+ * The blobs still pending after the pass, each stat'ed just BEFORE the+ * read that found it missing or broken: a blob that arrives between that+ * read and the end of the pass then looks moved on the next check, so it+ * is read again instead of being taken as already looked at.+ */+ pendingBlobs: Map<string, FileStat | null>;+}++/**+ * Read one changed shard and ingest its records. Records it was credited+ * with and no longer holds go to `orphans` rather than out of the index:+ * a compaction may hold them in a sibling shard. Returns the watermark to+ * write once the orphans are settled.+ */+function readOneShard(+ index: Store,+ config: ResolvedSearchConfig,+ store: IndexedStore,+ shard: ShardStat,+ mark: StoreWatermark | undefined,+ totals: SyncTotals,+ device: string | null,+ orphans: Orphans,+): { watermark: StoreWatermark; fromStart: boolean } {+ const db = index.brainRecordsConnection();+ const resume =+ mark !== undefined &&+ mark.identity === shard.identity &&+ shard.size >= mark.offset &&+ prefixHash(shard.path, mark.offset) === mark.prefixHash;+ const from = resume ? mark.offset : 0;+ const read = readShard(shard.path, {+ offset: from,+ partitionRoot: partitionDir(store.root, shard.partition),+ });+ totals.shardsRead++;+ const seen = new Set<string>();+ for (const r of read.records) {+ const outcome = ingestRecord(index, config, r.record, shard, r.bodyState === "pending");+ // A copy refused for sitting in the other partition does not hold the+ // record: it must not keep an orphaned row alive.+ if (outcome === "refused") continue;+ seen.add(r.record.id);+ orphans.delete(r.record.id);+ if (outcome === "added") totals.added++;+ if (r.record.device !== device) {+ const hlc = parseHlc(r.record.hlc);+ const best = totals.remoteHlc === null ? null : parseHlc(totals.remoteHlc);+ if (hlc !== null && (best === null || compareHlc(hlc, best) > 0))+ totals.remoteHlc = r.record.hlc;+ }+ }+ if (!resume && mark !== undefined) {+ for (const id of recordIdsOfShard(db, shard.key)) if (!seen.has(id)) orphans.set(id, shard.key);+ }+ const count = (kind: string): number => read.diagnostics.filter((d) => d.kind === kind).length;+ const post = statShardFile(shard.path) ?? shard;+ // The stat (and the prefix hash) are taken after the read, so they may+ // describe a newer file than the one read. Only an untouched file may+ // vouch for the read; an append keeps the prefix, so the next pass+ // resumes; anything else (a same-size swap or rewrite by a sync tool)+ // leaves no prefix hash, so the next pass reads the shard from 0.+ const sameFile = post.identity === shard.identity;+ const untouched =+ sameFile &&+ post.size === read.size &&+ (shard.size !== read.size || post.mtimeMs === shard.mtimeMs);+ const appended = sameFile && post.size > read.size;+ const watermark: StoreWatermark = {+ shard: shard.key,+ partition: shard.partition,+ identity: post.identity,+ size: read.size,+ mtimeMs: untouched ? post.mtimeMs : -1,+ offset: read.nextOffset,+ prefixHash: untouched || appended ? prefixHash(shard.path, read.nextOffset) : "",+ unknownVersions: (resume ? mark.unknownVersions : 0) + count("unknown-version"),+ corruptLines: (resume ? mark.corruptLines : 0) + count("corrupt-line"),+ };+ return { watermark, fromStart: !resume };+}++/** Bring `index` level with the shards in `shards`; returns what changed. */+function syncShards(+ index: Store,+ config: ResolvedSearchConfig,+ store: IndexedStore,+ shards: ReadonlyArray<ShardStat>,+): SyncTotals {+ const db = index.brainRecordsConnection();+ const marks = readWatermarks(db);+ const device = readDeviceId(config.configPath);+ const totals: SyncTotals = {+ shardsRead: 0,+ added: 0,+ removed: 0,+ completed: 0,+ remoteHlc: null,+ pendingBlobs: new Map(),+ };+ try {+ const orphans: Orphans = new Map();+ const present = new Set<string>();+ const readInFull = new Set<string>();+ const next: StoreWatermark[] = [];+ for (const shard of shards) {+ present.add(shard.key);+ const mark = marks.get(shard.key);+ if (mark !== undefined && sameStat(mark, shard)) continue;+ const read = readOneShard(index, config, store, shard, mark, totals, device, orphans);+ if (read.fromStart) readInFull.add(shard.key);+ next.push(read.watermark);+ }+ const vanished = [...marks.keys()].filter((key) => !present.has(key));+ for (const key of vanished) {+ for (const id of recordIdsOfShard(db, key)) if (!orphans.has(id)) orphans.set(id, key);+ }+ const settled = settleOrphans(index, config, store, shards, orphans, readInFull);+ totals.removed += settled.removed;+ // Watermarks move only once the orphans are settled: a pass that+ // stops before that reads the same shards again next time, and a+ // shard whose orphans could not be settled keeps its old watermark+ // (a vanished one keeps its row), so the next pass meets them again.+ for (const w of next) if (!settled.retry.has(w.shard)) writeWatermark(db, w);+ for (const key of vanished) if (!settled.retry.has(key)) deleteWatermark(db, key);+ for (const pending of pendingRecords(db)) {+ const partitionRoot = partitionDir(store.root, pending.partition as StorePartition);+ const path = blobPath(partitionRoot, pending.sum);+ const before = statShardFile(path);+ // A blob that is absent, still arriving, or that can never hold the+ // body (hash-valid but not the record's JSON object) keeps the+ // record pending; it never throws out of the pass.+ const blob = readBlobBody(partitionRoot, pending.sum);+ if (blob.status !== "ok") {+ totals.pendingBlobs.set(path, before);+ continue;+ }+ completePendingRecord(index, config, pending, blob.body);+ totals.completed++;+ }+ } finally {+ // Whatever was already written moves the revision, even when a later+ // shard throws: the next pass finds those shards level and changes+ // nothing, so it would never bump for them.+ if (totals.added + totals.removed + totals.completed > 0) index.bumpIndexRevision();+ }+ if (device !== null && totals.remoteHlc !== null) {+ try {+ observeClock(store.deviceStateDir, device, parseHlc(totals.remoteHlc)!);+ } catch {+ // The receive rule is best effort here: the next catch-up raises it.+ }+ }+ return totals;+}++/**+ * Ingest the whole store into an index that is open for writing: the+ * rebuild path, which builds a staging index before the swap. Every+ * shard is read from offset 0 there, so records an older binary skipped+ * for an unknown format version are picked up.+ */+export function ingestStoreInto(index: Store, config: ResolvedSearchConfig): void {+ const store = config.brainStore;+ if (store === null || store === undefined) return;+ syncShards(index, config, store, new ShardScanner(store).scan());+}++/** Catch the index of `config` up with its brain store; never throws. */+export async function catchUpBrainStore(+ config: ResolvedSearchConfig,+ opts: CatchUpOptions = {},+): Promise<CatchUpResult> {+ const store = config.brainStore;+ if (store === null || store === undefined) return { skipped: "no-store", ...NOTHING };+ const state = stateFor(config, store);+ const now = Date.now();+ if (opts.force !== true && now - state.lastCheckMs < catchUpIntervalMs()) {+ return { skipped: "throttled", ...NOTHING };+ }+ state.lastCheckMs = now;+ try {+ const indexIdentity = statShardFile(config.dbPath)?.identity ?? null;+ if (indexIdentity === null) {+ state.known = null;+ return { skipped: "no-index", ...NOTHING };+ }+ if (indexIdentity !== state.indexIdentity) {+ state.known = null;+ state.indexIdentity = indexIdentity;+ }+ const shards = state.scanner.scan();+ if (state.known === null) {+ const peek = peekIndex(config.dbPath, store);+ if (peek === null) return { skipped: "not-current", ...NOTHING };+ state.known = peek.known;+ state.pendingBlobs = peek.pendingBlobs;+ }+ if (!blobMoved(state.pendingBlobs) && unchanged(state.known, shards)) {+ return { skipped: null, ...NOTHING };+ }+ if (isWriterLockHeld(config.dbPath)) return { skipped: "locked", ...NOTHING };+ const index = await Store.open(config, { mode: "write" });+ try {+ const totals = syncShards(index, config, store, shards);+ state.known = knownFrom(readWatermarks(index.brainRecordsConnection()));+ state.pendingBlobs = totals.pendingBlobs;+ return {+ skipped: null,+ shardsRead: totals.shardsRead,+ added: totals.added,+ removed: totals.removed,+ completed: totals.completed,+ };+ } finally {+ await index.close();+ }+ } catch (e) {+ state.known = null;+ if (e instanceof SearchError && e.code === "INDEX_LOCKED")+ return { skipped: "locked", ...NOTHING };+ return { skipped: "failed", ...NOTHING, error: e instanceof Error ? e.message : String(e) };+ }+}diff --git a/src/core/search/brain-store/changes.ts b/src/core/search/brain-store/changes.tsnew file mode 100644index 00000000..849c23c4--- /dev/null+++ b/src/core/search/brain-store/changes.ts@@ -0,0 +1,164 @@+/**+ * The change probe (design D5, task 1.9): "what is new in the brain store+ * since watermark W", answered from the index, never from a store file.+ *+ * A watermark is `<index generation>.<ingest sequence>`. The sequence is+ * the order this machine's index ingested records in, so a record that+ * arrives late by file sync (with an older clock than records already+ * seen) is still new after W. The generation is minted with each index+ * file; a watermark from a replaced index (a rebuild renumbers the+ * sequence) is reported as a reset and the probe answers from the start.+ *+ * The probe catches the index up first, like every read, then returns the+ * new record ids grouped by partition, stream, scope and topic, oldest+ * first, with the watermark to pass next time. A page cut by `limit`+ * returns the watermark of its last record, so the caller pages forward.+ */++import { openReadOrSelfHeal } from "../pipeline/store-open.ts";+import { recordsAfter } from "../store/brain-records.ts";+import { SearchError, type ResolvedSearchConfig } from "../types.ts";+import { catchUpBrainStore, type CatchUpResult } from "./catch-up.ts";+import { STORE_INDEX_GENERATION_KEY } from "./constants.ts";++/** Records one probe returns by default. */+export const CHANGES_DEFAULT_LIMIT = 500;++/** The most records one probe returns. */+export const CHANGES_MAX_LIMIT = 5000;++/** New record ids that share a partition, stream, ledger, scope and topic. */+export interface ChangeGroup {+ readonly partition: string;+ readonly stream: string;+ readonly ledger: string | null;+ readonly scope: string | null;+ readonly topic: string | null;+ /** Record ids in ingest order. */+ readonly ids: ReadonlyArray<string>;+}++export interface BrainChanges {+ /** False when no brain store is in use; nothing else is then reported. */+ readonly storeInUse: boolean;+ /** The watermark to pass as `since` next time; null without a store or an index. */+ readonly watermark: string | null;+ /** True when `since` came from another index generation and the probe started over. */+ readonly reset: boolean;+ /** True when more records are waiting after {@link watermark}. */+ readonly truncated: boolean;+ /** Number of record ids across the groups. */+ readonly count: number;+ readonly groups: ReadonlyArray<ChangeGroup>;+ /**+ * Why the answer may be incomplete: a catch-up that failed leaves+ * records out until a later probe catches up. Empty when it is current.+ */+ readonly warnings: ReadonlyArray<string>;+}++export interface BrainChangesOptions {+ /** A watermark from an earlier probe; absent starts from the first record. */+ readonly since?: string;+ readonly limit?: number;+}++const WATERMARK_RE = /^([0-9A-HJKMNP-TV-Z]{26})\.(0|[1-9]\d{0,15})$/;++/** Parse a watermark; null when it is not one. */+export function parseWatermark(text: string): { generation: string; seq: number } | null {+ const m = WATERMARK_RE.exec(text.trim());+ return m === null ? null : { generation: m[1]!, seq: Number(m[2]) };+}++function formatWatermark(generation: string, seq: number): string {+ return `${generation}.${seq}`;+}++const NO_STORE: BrainChanges = Object.freeze({+ storeInUse: false,+ watermark: null,+ reset: false,+ truncated: false,+ count: 0,+ groups: Object.freeze([]),+ warnings: Object.freeze([]),+});++/** The warning a failed catch-up adds, worded as search words it. */+function catchUpWarnings(results: ReadonlyArray<CatchUpResult>): string[] {+ const failed = results.findLast((r) => r.skipped === "failed");+ return failed === undefined+ ? []+ : [`brain store catch-up failed, records may be missing: ${failed.error}`];+}++/** The new record ids since `opts.since`, grouped; throws `INVALID_INPUT` for a malformed watermark or limit. */+export async function brainChanges(+ config: ResolvedSearchConfig,+ opts: BrainChangesOptions = {},+): Promise<BrainChanges> {+ const since = opts.since === undefined ? null : parseWatermark(opts.since);+ if (opts.since !== undefined && since === null) {+ throw new SearchError(+ "INVALID_INPUT",+ `"${opts.since}" is not a watermark; pass the watermark an earlier probe returned`,+ );+ }+ const limit = opts.limit ?? CHANGES_DEFAULT_LIMIT;+ if (!Number.isInteger(limit) || limit < 1 || limit > CHANGES_MAX_LIMIT) {+ throw new SearchError("INVALID_INPUT", `limit must be an integer in 1..${CHANGES_MAX_LIMIT}`);+ }+ if (config.brainStore === null || config.brainStore === undefined) return NO_STORE;+ // Catch-up before the read, as every read does; an index the open has+ // to build or upgrade first is caught up right after it.+ const catchUps = [await catchUpBrainStore(config)];+ const index = await openReadOrSelfHeal(config);+ try {+ if (catchUps[0]!.skipped === "no-index" || catchUps[0]!.skipped === "not-current") {+ catchUps.push(await catchUpBrainStore(config, { force: true }));+ }+ const warnings = catchUpWarnings(catchUps);+ const db = index.brainRecordsConnection();+ const generation = index.getState(STORE_INDEX_GENERATION_KEY);+ if (generation === null) return { ...NO_STORE, storeInUse: true, warnings };+ const reset = since !== null && since.generation !== generation;+ const from = since !== null && !reset ? since.seq : 0;+ const rows = recordsAfter(db, from, limit + 1);+ const truncated = rows.length > limit;+ const page = truncated ? rows.slice(0, limit) : rows;+ const groups = new Map<string, ChangeGroup & { ids: string[] }>();+ for (const r of page) {+ const key = JSON.stringify([r.partition, r.stream, r.ledger, r.scope, r.topic]);+ let group = groups.get(key);+ if (group === undefined) {+ group = {+ partition: r.partition,+ stream: r.stream,+ ledger: r.ledger,+ scope: r.scope,+ topic: r.topic,+ ids: [],+ };+ groups.set(key, group);+ }+ group.ids.push(r.id);+ }+ // An empty page keeps the caller's position: sequences only grow+ // within a generation, so a record committed after this read is still+ // above it, while a second read of the highest sequence could step+ // past a record committed between the two reads.+ const lastSeq = page.length > 0 ? page[page.length - 1]!.seq : from;+ return {+ storeInUse: true,+ watermark: formatWatermark(generation, lastSeq),+ reset,+ truncated,+ count: page.length,+ groups: [...groups.values()],+ warnings,+ };+ } finally {+ await index.close();+ }+}diff --git a/src/core/search/brain-store/constants.ts b/src/core/search/brain-store/constants.tsnew file mode 100644index 00000000..ede35e53--- /dev/null+++ b/src/core/search/brain-store/constants.ts@@ -0,0 +1,95 @@+/**+ * Names the store-aware search index uses (design D5): where the index+ * lives in a store's device-local state, how a brain record is keyed in+ * the `documents` table, which streams are searchable, the catch-up+ * throttle, and the two values of the document source column.+ *+ * The store's own names (partitions, streams, file names) stay in+ * `src/core/store/constants.ts`; this module only names what the index+ * adds on top of them.+ */++import type { StoreStream } from "../../store/constants.ts";++/**+ * Subdirectory of a store's device-local state directory that holds one+ * index per vault: `<device state>/index/<vault key>/brain.sqlite`. The+ * vault key keeps two vaults on one machine from sharing (and sweeping)+ * one index.+ */+export const STORE_INDEX_DIR = "index";++/**+ * File in a store's {@link STORE_INDEX_DIR} naming the store root the+ * store was last read at on this machine. A probe that answers `unknown`+ * keeps only an index whose store was last seen at the root it probed, so+ * a retired or moved store's index is never picked up.+ */+export const STORE_INDEX_ROOT_FILE = "store-root";++/** Hex characters of the vault path hash that name a vault's index directory. */+export const STORE_INDEX_VAULT_KEY_LENGTH = 16;++/**+ * First segment of the `documents.path` of every brain record:+ * `.brain-store/<partition>/<record id>`. A dot directory, so no vault+ * note can ever carry the same path: the vault walker skips dot+ * directories.+ */+export const STORE_RECORD_PATH_PREFIX = ".brain-store";++/** Whether an indexed document path names a brain store record. */+export function isStoreRecordPath(path: string): boolean {+ return path.startsWith(`${STORE_RECORD_PATH_PREFIX}/`);+}++/**+ * Streams whose records are made searchable through the chunk and FTS+ * path. Every stream is still ingested into the `records` table (the+ * change probe reports all of them); ledgers, settings and digests are+ * bookkeeping that would only add noise to recall.+ */+export const SEARCHABLE_STORE_STREAMS: ReadonlySet<StoreStream> = new Set<StoreStream>([+ "events",+ "log",+ "topics",+]);++/** Environment variable that sets the catch-up throttle in milliseconds (0 checks on every read). */+export const STORE_CATCH_UP_INTERVAL_ENV = "OPEN_SECOND_BRAIN_STORE_CATCHUP_INTERVAL_MS";++/** Default catch-up throttle: shards are stat'ed at most once per second per process. */+export const STORE_CATCH_UP_INTERVAL_MS = 1000;++/** The two values of `documents.source`. */+export const DOCUMENT_SOURCE = Object.freeze({+ /** A user note from the vault. */+ note: "note",+ /** A brain record: a store record, or a page of the legacy `Brain/` tree. */+ brain: "brain",+} as const);+export type DocumentSource = (typeof DOCUMENT_SOURCE)[keyof typeof DOCUMENT_SOURCE];++/** The caller-facing values of the search `source` option. */+export const SEARCH_SOURCES = Object.freeze(["notes", "brain"] as const);+export type SearchSource = (typeof SEARCH_SOURCES)[number];++/** Whether `value` is one of {@link SEARCH_SOURCES}. */+export function isSearchSource(value: unknown): value is SearchSource {+ return typeof value === "string" && (SEARCH_SOURCES as ReadonlyArray<string>).includes(value);+}++/** The document source a search source keeps. */+export function documentSourceFor(source: SearchSource): DocumentSource {+ return source === "notes" ? DOCUMENT_SOURCE.note : DOCUMENT_SOURCE.brain;+}++/** `index_state` key of the index generation the change probe's watermarks are bound to. */+export const STORE_INDEX_GENERATION_KEY = "store_index_generation";++/**+ * `index_state` key of the highest ingest sequence a removed record held.+ * New records are numbered above it, so removing the newest record never+ * lets the next one reuse its sequence behind a change-probe watermark.+ */+export const STORE_RECORD_SEQ_FLOOR_KEY = "store_record_seq_floor";diff --git a/src/core/search/brain-store/ingest.ts b/src/core/search/brain-store/ingest.tsnew file mode 100644index 00000000..f2b90afa--- /dev/null+++ b/src/core/search/brain-store/ingest.ts@@ -0,0 +1,204 @@+/**+ * Write one brain store record into the index, or take one out (design+ * D5): the `records` row, and for a searchable stream the document and+ * chunks its text is searched through.+ *+ * Idempotent by record id. Records are immutable (their id names one+ * envelope and its checksum), so a record already indexed with its body+ * only has its shard attribution refreshed on a re-read; it is re-chunked+ * only when its body was a pending blob that has since arrived.+ */++import { posix } from "node:path";++import { REMOTE_DENY_VISIBILITY_TOKEN } from "../../graph/visibility.ts";+import { sha256Hex } from "../../integrity/digest.ts";+import { STORE_FORMAT_VERSION } from "../../store/constants.ts";+import type { StoreRecord } from "../../store/envelope.ts";+import { chunkMarkdown } from "../chunker.ts";+import { expandTextForCjkFts } from "../cjk-tokenizer.ts";+import { extractEntities } from "../entities.ts";+import type { Store } from "../store.ts";+import {+ clearStoreTables,+ deleteRecordRow,+ getRecord,+ holdsStoreRows,+ storeRecordDocumentPaths,+ upsertRecord,+ type RecordRow,+ type StoredRecord,+} from "../store/brain-records.ts";+import type { ChunkInput } from "../store/chunks.ts";+import type { ResolvedSearchConfig } from "../types.ts";+import { SEARCHABLE_STORE_STREAMS, STORE_RECORD_PATH_PREFIX } from "./constants.ts";+import { renderRecordText } from "./record-text.ts";+import type { ShardStat } from "./shard-scan.ts";++/** The `documents.path` a store record's text is indexed under. */+export function storeRecordPath(partition: string, id: string): string {+ return posix.join(STORE_RECORD_PATH_PREFIX, partition, id);+}++function authorityOf(record: StoreRecord): string | null {+ const value = record.body["authority"];+ return typeof value === "string" && value.trim() !== "" ? value : null;+}++function physicalSeconds(hlc: string): number {+ const ms = Number(hlc.split(".")[0]);+ return Number.isFinite(ms) ? Math.floor(ms / 1000) : 0;+}++/** Where a record was read from: the parts of a {@link ShardStat} ingest needs. */+export type RecordPlace = Pick<ShardStat, "key" | "partition" | "stream" | "ledger">;++/**+ * What {@link ingestRecord} did. `refused`: the id is already indexed+ * from the other partition. Records never move between partitions, so the+ * second copy is not indexed (it could otherwise relabel or shadow the+ * first); doctor reports such ids.+ */+export type IngestOutcome = "added" | "refreshed" | "unchanged" | "refused";++function indexText(+ store: Store,+ config: ResolvedSearchConfig,+ record: StoreRecord,+ shard: RecordPlace,+ pending: boolean,+): number {+ const { title, content } = renderRecordText(record, shard.stream, pending);+ const docId = store.upsertDocument({+ path: storeRecordPath(shard.partition, record.id),+ title,+ contentHash: sha256Hex(content),+ mtime: physicalSeconds(record.hlc),+ size: Buffer.byteLength(content),+ pageType: null,+ eventAnchor: null,+ // A private-partition record is reserved exactly like a page that+ // declares `visibility: private`.+ visibility: shard.partition === "private" ? [REMOTE_DENY_VISIBILITY_TOKEN] : [],+ pinned: false,+ });+ const chunked = chunkMarkdown(content, title, {+ maxTokens: config.chunkSize,+ minTokens: config.chunkMinSize,+ overlapTokens: config.chunkOverlap,+ });+ const inputs: ChunkInput[] = chunked.chunks.map((c) => ({+ chunkIndex: c.chunkIndex,+ content: c.content,+ ftsContent: expandTextForCjkFts(c.content),+ contentHash: sha256Hex(c.content),+ startLine: c.startLine,+ endLine: c.endLine,+ tokenCount: c.tokenCount,+ headingPath: c.headingPath,+ }));+ const replaced = store.replaceDocumentChunks(docId, inputs);+ replaced.chunkIds.forEach((cid, i) => {+ if (!replaced.keptChunkIds.has(cid)) {+ store.replaceEntities(cid, extractEntities(chunked.chunks[i]!.content));+ }+ });+ return docId;+}++/** Ingest one verified record read from `shard`. */+export function ingestRecord(+ store: Store,+ config: ResolvedSearchConfig,+ record: StoreRecord,+ shard: RecordPlace,+ pending: boolean,+): IngestOutcome {+ const db = store.brainRecordsConnection();+ const existing = getRecord(db, record.id);+ if (existing !== null && existing.partition !== shard.partition) return "refused";+ const row: RecordRow = {+ id: record.id,+ partition: shard.partition,+ stream: shard.stream,+ ledger: shard.ledger,+ kind: record.kind,+ scope: record.scope,+ topic: record.topic,+ hlc: record.hlc,+ device: record.device,+ agent: record.agent,+ authority: pending ? (existing?.authority ?? null) : authorityOf(record),+ sum: record.sum,+ shard: shard.key,+ bodyPending: pending,+ };+ const searchable = SEARCHABLE_STORE_STREAMS.has(shard.stream);+ if (existing !== null && !existing.bodyPending && (existing.documentId !== null || !searchable)) {+ if (existing.shard !== shard.key)+ upsertRecord(db, { ...row, bodyPending: false }, existing.documentId);+ return "unchanged";+ }+ if (existing !== null && existing.bodyPending && pending) {+ if (existing.shard !== shard.key) upsertRecord(db, row, existing.documentId);+ return "unchanged";+ }+ const docId = searchable ? indexText(store, config, record, shard, pending) : null;+ upsertRecord(db, row, docId);+ return existing === null ? "added" : "refreshed";+}++/**+ * Index the body of a record that was ingested while its blob was still+ * pending, now that the blob has arrived.+ */+export function completePendingRecord(+ store: Store,+ config: ResolvedSearchConfig,+ stored: StoredRecord,+ body: StoreRecord["body"],+): void {+ const record: StoreRecord = {+ v: STORE_FORMAT_VERSION,+ id: stored.id,+ hlc: stored.hlc,+ device: stored.device,+ agent: stored.agent,+ kind: stored.kind,+ scope: stored.scope,+ topic: stored.topic,+ sum: stored.sum,+ body,+ };+ const place: RecordPlace = {+ key: stored.shard,+ partition: stored.partition as RecordPlace["partition"],+ stream: stored.stream as RecordPlace["stream"],+ ledger: stored.ledger,+ };+ ingestRecord(store, config, record, place, false);+}++/** Remove one record and its document from the index. */+export function removeRecord(store: Store, record: StoredRecord): void {+ if (record.documentId !== null)+ store.deleteDocument(storeRecordPath(record.partition, record.id));+ deleteRecordRow(store.brainRecordsConnection(), record.id);+}++/**+ * Take every brain store record out of an index whose vault no longer+ * reads a store (the store was turned off, removed, or no longer+ * resolves). Only an index file shared by both modes (an explicit+ * `search_db_path`) can be in that state; the vault sweep never removes+ * these documents, so this is their cleanup. Returns the number of+ * documents removed, or null when the index held nothing of a store.+ */+export function purgeStoreRecords(store: Store): number | null {+ const db = store.brainRecordsConnection();+ const paths = storeRecordDocumentPaths(db, `${STORE_RECORD_PATH_PREFIX}/`);+ if (paths.length === 0 && !holdsStoreRows(db)) return null;+ for (const path of paths) store.deleteDocument(path);+ clearStoreTables(db);+ return paths.length;+}diff --git a/src/core/search/brain-store/location.ts b/src/core/search/brain-store/location.tsnew file mode 100644index 00000000..a4d8603a--- /dev/null+++ b/src/core/search/brain-store/location.ts@@ -0,0 +1,225 @@+/**+ * Whether the search index is store-aware, and where it then lives+ * (design D5, task 1.8).+ *+ * A store is "in use" when the resolved store root (environment, machine+ * config, then the per-user default; see `store/store-paths.ts`) holds at+ * least one partition carrying the store identity file. Nothing here+ * creates a store or writes into one: the probe only reads `store.json`.+ *+ * When a store is in use the index lives in the store's device-local state+ * directory, one file per vault:+ * `<device state>/index/<vault key>/brain.sqlite`. When no store is in use+ * (every install before migration) the legacy vault location stays, and an+ * explicit `search_db_path` / `OPEN_SECOND_BRAIN_SEARCH_DB` override wins+ * in both cases (see `../paths.ts`).+ */++import { mkdirSync, readdirSync, readFileSync, realpathSync, statSync } from "node:fs";+import { join, resolve } from "node:path";++import { DERIVED_STORE_FILE } from "../../brain/path-constants.ts";+import { defaultConfigPath } from "../../config.ts";+import { sha256Hex } from "../../integrity/digest.ts";+import { atomicWriteFileSync } from "../../fs-atomic.ts";+import { processDirsEnv, type PlatformDirsEnv } from "../../platform-dirs.ts";+import { STORE_PARTITIONS, type StorePartition } from "../../store/constants.ts";+import { readStoreId } from "../../store/store-open.ts";+import { isUlid } from "../../store/ulid.ts";+import {+ deviceStateDirFor,+ partitionDir,+ resolveStoreRoot,+ storesStateDir,+ StoreRootInsideVaultError,+} from "../../store/store-paths.ts";+import {+ STORE_INDEX_DIR,+ STORE_INDEX_ROOT_FILE,+ STORE_INDEX_VAULT_KEY_LENGTH,+} from "./constants.ts";++/** A store the index reads, as this machine holds it. */+export interface IndexedStore {+ readonly root: string;+ readonly storeId: string;+ /** Device-local state directory of the store (never synced). */+ readonly deviceStateDir: string;+ /** Partitions this machine holds, in {@link STORE_PARTITIONS} order. */+ readonly partitions: ReadonlyArray<StorePartition>;+}++/**+ * What a read-only look at a store root found: the store, no store (no+ * partition holds an identity file), or `unknown` when it could not tell+ * (an identity file is unreadable, or the partitions disagree about the+ * store id: a broken store is not indexed; the store's own open refuses it+ * by name).+ */+export type StoreProbe =+ | { readonly kind: "store"; readonly store: IndexedStore }+ | { readonly kind: "absent" }+ /** `root`: the store root probed, `null` when it could not be resolved. */+ | { readonly kind: "unknown"; readonly root: string | null };++/** Read-only probe of the store at `root`; see {@link StoreProbe}. */+export function probeStoreRoot(root: string, dirs: PlatformDirsEnv = processDirsEnv()): StoreProbe {+ const held: StorePartition[] = [];+ const ids = new Set<string>();+ for (const partition of STORE_PARTITIONS) {+ let id: string | null;+ try {+ id = readStoreId(partitionDir(root, partition));+ } catch {+ return { kind: "unknown", root };+ }+ if (id === null) continue;+ held.push(partition);+ ids.add(id);+ }+ if (held.length === 0) return { kind: "absent" };+ if (ids.size !== 1) return { kind: "unknown", root };+ const storeId = [...ids][0]!;+ return {+ kind: "store",+ store: { root, storeId, deviceStateDir: deviceStateDirFor(storeId, dirs), partitions: held },+ };+}++/** The held store at `root`, or `null` when there is none or it cannot be read. */+export function probeIndexedStore(+ root: string,+ dirs: PlatformDirsEnv = processDirsEnv(),+): IndexedStore | null {+ const probe = probeStoreRoot(root, dirs);+ return probe.kind === "store" ? probe.store : null;+}++export interface ResolveIndexedStoreOptions {+ readonly vault: string;+ /** Parsed machine config (`key: value`); empty when no file was read. */+ readonly config: Readonly<Record<string, string>>;+ /** Path of the machine config file; relative `store_root` values anchor to its directory. */+ readonly configPath?: string | null;+ readonly dirs?: PlatformDirsEnv;+}++/**+ * Which store the index of `vault` reads. A store root configured inside+ * the vault is not in use (`absent`): the store's own resolver refuses it+ * by name wherever a store is opened, and the index must not fail every+ * search over it. A root that cannot be resolved at all is `unknown`.+ */+export function resolveIndexedStoreProbe(opts: ResolveIndexedStoreOptions): StoreProbe {+ const dirs = opts.dirs ?? processDirsEnv();+ let root: string;+ try {+ root = resolveStoreRoot({+ ...dirs,+ config: opts.config,+ configPath: opts.configPath ?? defaultConfigPath(),+ vault: opts.vault,+ }).root;+ } catch (err) {+ return err instanceof StoreRootInsideVaultError+ ? { kind: "absent" }+ : { kind: "unknown", root: null };+ }+ return probeStoreRoot(root, dirs);+}++/** The store the index of `vault` reads, or `null` when none is in use or it cannot be read. */+export function resolveIndexedStore(opts: ResolveIndexedStoreOptions): IndexedStore | null {+ const probe = resolveIndexedStoreProbe(opts);+ return probe.kind === "store" ? probe.store : null;+}++/**+ * The directory name of a vault's index under a store: a short hash of the+ * vault's real path. The real path follows symlinks and, on macOS and+ * Windows, answers the on-disk spelling of each segment (drive letter+ * included), so one vault reached through a link or a different casing+ * keeps one index. A vault that does not exist yet hashes its resolved path.+ */+export function vaultIndexKey(vault: string): string {+ let real: string;+ try {+ real = realpathSync.native(vault);+ } catch {+ real = resolve(vault);+ }+ return sha256Hex(real).slice(0, STORE_INDEX_VAULT_KEY_LENGTH);+}++/** The index file of `vault` inside `store`'s device-local state. */+export function storeIndexPath(store: IndexedStore, vault: string): string {+ return join(store.deviceStateDir, STORE_INDEX_DIR, vaultIndexKey(vault), DERIVED_STORE_FILE);+}++/** The store root `deviceStateDir`'s store was last read at, or `null`. */+function rememberedRoot(deviceStateDir: string): string | null {+ try {+ return readFileSync(join(deviceStateDir, STORE_INDEX_DIR, STORE_INDEX_ROOT_FILE), "utf8");+ } catch {+ return null;+ }+}++/**+ * Note on this machine that `store` was read at its root, for+ * {@link lastStoreIndexPath}. Best effort: a failure only means a later+ * `unknown` probe uses the legacy location instead.+ */+export function rememberStoreRoot(store: IndexedStore): void {+ if (rememberedRoot(store.deviceStateDir) === store.root) return;+ try {+ const dir = join(store.deviceStateDir, STORE_INDEX_DIR);+ mkdirSync(dir, { recursive: true });+ atomicWriteFileSync(join(dir, STORE_INDEX_ROOT_FILE), store.root);+ } catch {+ // the next resolve tries again+ }+}++/**+ * The index of `vault` this machine last wrote under a store last read at+ * `root`, or `null` when it holds none: for a probe that answered+ * `unknown`. A store.json a sync tool is rewriting, or two partitions that+ * briefly disagree, tell nothing about where the index lives, and falling+ * back to the vault's legacy location would read and write a different+ * database (a stale one, or an empty one rebuilt in full) until the store+ * reads again. The store id is what names the index directory, so every+ * store directory of this machine whose store was last read at `root`+ * ({@link rememberStoreRoot}) is looked in, and the most recently written+ * index wins. A store retired or moved away from `root` is never picked.+ */+export function lastStoreIndexPath(+ vault: string,+ root: string | null,+ dirs: PlatformDirsEnv = processDirsEnv(),+): string | null {+ if (root === null) return null;+ let ids: string[];+ try {+ ids = readdirSync(storesStateDir(dirs)).filter((name) => isUlid(name));+ } catch {+ return null;+ }+ const key = vaultIndexKey(vault);+ let best: { readonly path: string; readonly mtimeMs: number } | null = null;+ for (const id of ids) {+ const stateDir = deviceStateDirFor(id, dirs);+ if (rememberedRoot(stateDir) !== root) continue;+ const path = join(stateDir, STORE_INDEX_DIR, key, DERIVED_STORE_FILE);+ let mtimeMs: number;+ try {+ const stat = statSync(path);+ if (!stat.isFile()) continue;+ mtimeMs = stat.mtimeMs;+ } catch {+ continue;+ }+ if (best === null || mtimeMs > best.mtimeMs) best = { path, mtimeMs };+ }+ return best?.path ?? null;+}diff --git a/src/core/search/brain-store/orphans.ts b/src/core/search/brain-store/orphans.tsnew file mode 100644index 00000000..96a5bc48--- /dev/null+++ b/src/core/search/brain-store/orphans.ts@@ -0,0 +1,109 @@+/**+ * Records a catch-up pass found missing from the shard it credited them+ * to (design D5): a shard re-read from the start that no longer holds+ * them, or a shard that disappeared. They are removed from the index+ * only when no shard holds them any more.+ *+ * A compaction (`store/FORMAT.md`) writes the same records to a new shard+ * of the same stream and device before it removes the old one, so for a+ * while two shards hold one record and the index credits it to whichever+ * it read last. Removing on that single credit alone would drop records+ * the new shard still holds and that catch-up never reads again.+ */++import { posix } from "node:path";++import { readShard } from "../../store/reader.ts";+import { partitionDir } from "../../store/store-paths.ts";+import type { Store } from "../store.ts";+import { getRecord } from "../store/brain-records.ts";+import type { ResolvedSearchConfig } from "../types.ts";+import { ingestRecord, removeRecord } from "./ingest.ts";+import type { IndexedStore } from "./location.ts";+import type { ShardStat } from "./shard-scan.ts";++/** Records a shard no longer holds: record id to the shard key it was credited to. */+export type Orphans = Map<string, string>;++/** Length of the `YYYY-MM` month every shard name starts with. */+const SHARD_MONTH_LENGTH = "YYYY-MM".length;++/**+ * The shards a compaction can move a record between: the same partition,+ * stream, ledger and device (the key's directory) and the same month,+ * because a record lives only in a shard of its clock's month+ * (`YYYY-MM.jsonl` or a compaction output `YYYY-MM.<suffix>.jsonl`). The+ * device's other months are never read to settle an orphan.+ */+function shardGroup(key: string): string {+ return `${posix.dirname(key)}/${posix.basename(key).slice(0, SHARD_MONTH_LENGTH)}`;+}++/** What {@link settleOrphans} did. */+export interface SettledOrphans {+ /** Rows removed: no shard holds them any more. */+ readonly removed: number;+ /**+ * Shard keys whose orphans could not be settled because a sibling could+ * not be read. Their watermarks must stay as they were, so the next pass+ * finds the same orphans again and retries once the sibling reads.+ */+ readonly retry: ReadonlySet<string>;+}++/**+ * Remove the orphans no shard holds any more. A compaction writes the same+ * records to a sibling shard (same partition, stream, ledger, device and+ * month) before it removes the old one, so every present sibling not read+ * in full this pass is read here, and a record found there is credited to+ * it instead of removed.+ */+export function settleOrphans(+ index: Store,+ config: ResolvedSearchConfig,+ store: IndexedStore,+ shards: ReadonlyArray<ShardStat>,+ orphans: Orphans,+ readInFull: ReadonlySet<string>,+): SettledOrphans {+ if (orphans.size === 0) return { removed: 0, retry: new Set() };+ const groups = new Set([...orphans.values()].map(shardGroup));+ // A group with a sibling that cannot be read cannot be settled: its+ // orphans stay in the index (the sibling may hold them) rather than fail+ // the whole pass, which would fail the same way on every pass.+ const unsettled = new Set<string>();+ for (const sibling of shards) {+ if (orphans.size === 0) break;+ const group = shardGroup(sibling.key);+ if (readInFull.has(sibling.key) || !groups.has(group)) continue;+ let read: ReturnType<typeof readShard>;+ try {+ read = readShard(sibling.path, {+ partitionRoot: partitionDir(store.root, sibling.partition),+ });+ } catch {+ unsettled.add(group);+ continue;+ }+ for (const r of read.records) {+ if (!orphans.has(r.record.id)) continue;+ orphans.delete(r.record.id);+ ingestRecord(index, config, r.record, sibling, r.bodyState === "pending");+ }+ }+ const db = index.brainRecordsConnection();+ let removed = 0;+ const retry = new Set<string>();+ for (const [id, shard] of orphans) {+ if (unsettled.has(shardGroup(shard))) {+ retry.add(shard);+ continue;+ }+ const stored = getRecord(db, id);+ // Credited to another shard since: that shard holds it.+ if (stored === null || stored.shard !== shard) continue;+ removeRecord(index, stored);+ removed++;+ }+ return { removed, retry };+}diff --git a/src/core/search/brain-store/prefix-hash.ts b/src/core/search/brain-store/prefix-hash.tsnew file mode 100644index 00000000..248dae0c--- /dev/null+++ b/src/core/search/brain-store/prefix-hash.ts@@ -0,0 +1,49 @@+/**+ * The verified-prefix hash of a shard watermark (design D5).+ *+ * Catch-up must notice a shard that was rewritten under the same name,+ * inode and size (a sync tool writing in place, a restored copy), or it+ * would resume from an offset that no longer starts a line. Re-hashing the+ * whole verified prefix on every append would cost a full read of the+ * shard each time it grows, so the hash covers samples of the prefix: its+ * length, its first {@link PREFIX_SAMPLE_BYTES} bytes and the last+ * {@link PREFIX_SAMPLE_BYTES} bytes before the offset. A rewrite that+ * keeps the length and both samples byte for byte is not detected; any+ * other rewrite is.+ *+ * Only a shard whose stat changed is hashed, so an unchanged store opens+ * no file.+ */++import { closeSync, openSync, readSync } from "node:fs";++import { sha256Hex } from "../../integrity/digest.ts";++/** Bytes sampled from each end of the verified prefix. */+export const PREFIX_SAMPLE_BYTES = 4096;++function readAt(fd: number, position: number, length: number): Buffer {+ const out = Buffer.alloc(length);+ let read = 0;+ while (read < length) {+ const n = readSync(fd, out, read, length - read, position + read);+ if (n === 0) break;+ read += n;+ }+ return out.subarray(0, read);+}++/** The hash of the first `offset` bytes of the shard at `path`, as sampled. */+export function prefixHash(path: string, offset: number): string {+ if (offset <= 0) return sha256Hex("0:");+ const fd = openSync(path, "r");+ try {+ const headLength = Math.min(PREFIX_SAMPLE_BYTES, offset);+ const head = readAt(fd, 0, headLength);+ const tailStart = Math.max(headLength, offset - PREFIX_SAMPLE_BYTES);+ const tail = readAt(fd, tailStart, offset - tailStart);+ return sha256Hex(Buffer.concat([Buffer.from(`${offset}:`), head, tail]));+ } finally {+ closeSync(fd);+ }+}diff --git a/src/core/search/brain-store/record-text.ts b/src/core/search/brain-store/record-text.tsnew file mode 100644index 00000000..48edcbbc--- /dev/null+++ b/src/core/search/brain-store/record-text.ts@@ -0,0 +1,130 @@+/**+ * The searchable text of one brain store record (design D5).+ *+ * A record body is any JSON object, so the text is built generically: a+ * title from the first descriptive string field, then every scalar of the+ * body as a `key: value` line (nested objects flattened with dotted keys,+ * bounded in depth and length), then one line of envelope metadata so a+ * query for the kind, the stream or the agent finds the record too. The+ * result goes through the ordinary markdown chunker, so a long body is+ * split the same way a long note is.+ *+ * Values are agent and model text and often hold markdown of their own. A+ * value line that would open a heading or a code fence is escaped, so a+ * body can never fake a heading path or swallow the lines after it.+ */++import type { StoreRecord } from "../../store/envelope.ts";++/** Body fields tried, in order, for the record's title. */+const TITLE_FIELDS = ["title", "summary", "principle", "decision", "text", "message"] as const;++/** Longest title kept, in characters. */+const TITLE_MAX_CHARS = 120;++/** Nesting depth flattened into `key: value` lines. */+const MAX_DEPTH = 3;++/** Longest rendered body, in characters; the rest is cut. */+const BODY_MAX_CHARS = 64 * 1024;++export interface RecordText {+ readonly title: string;+ readonly content: string;+}++function oneLine(value: string): string {+ return value.replace(/\s+/g, " ").trim();+}++function titleOf(record: StoreRecord, pending: boolean): string {+ if (!pending) {+ for (const field of TITLE_FIELDS) {+ const value = record.body[field];+ if (typeof value === "string" && value.trim() !== "") {+ const line = oneLine(value);+ return line.length > TITLE_MAX_CHARS ? `${line.slice(0, TITLE_MAX_CHARS - 1)}β¦` : line;+ }+ }+ }+ return record.kind;+}++function scalarText(value: unknown): string | null {+ if (typeof value === "string") return value;+ if (typeof value === "number" || typeof value === "boolean") return String(value);+ return null;+}++/** A line the chunker would read as a heading or a fence when it starts a line. */+const STRUCTURAL_LINE_RE = /^(?:#|```|~~~)/;++/** `text` with every line that would open a heading or a fence escaped. */+function inert(text: string): string {+ return text+ .split("\n")+ .map((line) => (STRUCTURAL_LINE_RE.test(line) ? `\\${line}` : line))+ .join("\n");+}++/** Rendered lines and the characters still allowed. */+interface Sink {+ readonly lines: string[];+ left: number;+}++function emit(sink: Sink, line: string): void {+ if (sink.left <= 0) return;+ const kept = line.length > sink.left ? line.slice(0, sink.left) : line;+ sink.lines.push(kept);+ sink.left -= kept.length + 1;+}++function flatten(value: unknown, key: string, depth: number, sink: Sink): void {+ if (sink.left <= 0) return;+ const scalar = scalarText(value);+ if (scalar !== null) {+ emit(sink, inert(`${key}: ${scalar}`));+ return;+ }+ if (Array.isArray(value)) {+ const scalars = value.map(scalarText).filter((s): s is string => s !== null);+ if (scalars.length > 0) emit(sink, inert(`${key}: ${scalars.join(", ")}`));+ if (depth < MAX_DEPTH) {+ value.forEach((item, i) => {+ if (typeof item === "object" && item !== null)+ flatten(item, `${key}.${i}`, depth + 1, sink);+ });+ }+ return;+ }+ if (typeof value === "object" && value !== null && depth < MAX_DEPTH) {+ for (const [k, v] of Object.entries(value))+ flatten(v, key === "" ? k : `${key}.${k}`, depth + 1, sink);+ }+}++/** Title and markdown content of `record`; `pending` marks a blob body not yet delivered. */+export function renderRecordText(+ record: StoreRecord,+ stream: string,+ pending: boolean,+): RecordText {+ const title = titleOf(record, pending);+ // The budget stops the walk itself, so a huge body is never rendered whole.+ const sink: Sink = { lines: [], left: BODY_MAX_CHARS };+ if (!pending) flatten(record.body, "", 0, sink);+ const body = sink.lines.join("\n");+ const meta = [+ `kind: ${record.kind}`,+ `stream: ${stream}`,+ ...(record.scope !== null ? [`scope: ${record.scope}`] : []),+ ...(record.topic !== null ? [`topic: ${record.topic}`] : []),+ `agent: ${record.agent}`,+ `device: ${record.device}`,+ ].join("\n");+ const content = [`# ${title}`, pending ? "(body not delivered yet)" : body, meta]+ .filter((part) => part !== "")+ .join("\n\n");+ return { title, content: `${content}\n` };+}diff --git a/src/core/search/brain-store/shard-scan.ts b/src/core/search/brain-store/shard-scan.tsnew file mode 100644index 00000000..6179d0d3--- /dev/null+++ b/src/core/search/brain-store/shard-scan.ts@@ -0,0 +1,168 @@+/**+ * The metadata pass of catch-up (design D5): every shard of every held+ * partition, with one `stat` per shard and no file opened.+ *+ * Directory listings are cached by directory mtime: a directory whose+ * mtime has not moved since it was listed is not listed again, so an+ * unchanged store costs one `stat` per directory and per shard. A listing+ * taken within {@link RACY_LISTING_MS} of the directory's mtime is not+ * trusted (an entry added in the same mtime tick would be invisible to+ * the comparison), the same rule `git` applies to racily clean files.+ *+ * File identity is `dev:ino` from a bigint stat (on Windows, Node reports+ * the volume serial number and the 64-bit file index there). A filesystem+ * that reports no inode falls back to the birth time, and failing that to+ * an empty identity: the verified-prefix hash then has to catch a+ * replacement on its own.+ */++import { lstatSync, readdirSync, statSync } from "node:fs";+import { join, posix } from "node:path";++import {+ LEDGER_STREAM,+ STORE_STREAMS,+ type StorePartition,+ type StoreStream,+} from "../../store/constants.ts";+import { isReadableDeviceDir, isShardFileName } from "../../store/shard-list.ts";+import { LEDGER_NAME_RE, partitionDir } from "../../store/store-paths.ts";+import type { IndexedStore } from "./location.ts";++/** A listing taken this close to its directory's mtime is re-taken next time. */+export const RACY_LISTING_MS = 2000;++/** One shard as the metadata pass sees it. */+export interface ShardStat {+ /** `<partition>/<rel>`: the watermark key. */+ readonly key: string;+ readonly partition: StorePartition;+ readonly stream: StoreStream;+ readonly ledger: string | null;+ readonly device: string;+ /** Partition-relative path, `/`-separated. */+ readonly rel: string;+ readonly path: string;+ readonly identity: string;+ readonly size: number;+ readonly mtimeMs: number;+}++interface Entry {+ readonly name: string;+ readonly dir: boolean;+ readonly file: boolean;+}++interface CachedListing {+ readonly mtimeMs: number;+ readonly listedAt: number;+ readonly entries: ReadonlyArray<Entry>;+}++/** The identity, size and mtime of a file, or `null` when it is gone. */+export function statShardFile(+ path: string,+): Pick<ShardStat, "identity" | "size" | "mtimeMs"> | null {+ const st = statSync(path, { bigint: true, throwIfNoEntry: false });+ if (st === undefined || !st.isFile()) return null;+ let identity = "";+ if (st.ino !== 0n) identity = `${st.dev}:${st.ino}`;+ else if (st.birthtimeNs !== 0n) identity = `birth:${st.birthtimeNs}`;+ return { identity, size: Number(st.size), mtimeMs: Number(st.mtimeNs / 1_000_000n) };+}++/** A per-process scanner of one store, holding the directory listing cache. */+export class ShardScanner {+ private readonly listings = new Map<string, CachedListing>();++ constructor(private readonly store: IndexedStore) {}++ /** Every shard of the held partitions, sorted by key. */+ scan(): ShardStat[] {+ const out: ShardStat[] = [];+ for (const partition of this.store.partitions) {+ const root = partitionDir(this.store.root, partition);+ for (const stream of STORE_STREAMS) {+ const streamDir = join(root, stream);+ if (stream === LEDGER_STREAM) {+ for (const ledger of this.list(streamDir)) {+ if (!ledger.dir || !LEDGER_NAME_RE.test(ledger.name)) continue;+ this.scanDevices(out, partition, stream, ledger.name, join(streamDir, ledger.name));+ }+ } else {+ this.scanDevices(out, partition, stream, null, streamDir);+ }+ }+ }+ return out.toSorted((a, b) => (a.key < b.key ? -1 : a.key > b.key ? 1 : 0));+ }++ private scanDevices(+ out: ShardStat[],+ partition: StorePartition,+ stream: StoreStream,+ ledger: string | null,+ dir: string,+ ): void {+ for (const device of this.list(dir)) {+ if (!device.dir || !isReadableDeviceDir(device.name)) continue;+ const deviceDir = join(dir, device.name);+ for (const file of this.list(deviceDir)) {+ if (!file.file || !isShardFileName(file.name)) continue;+ const path = join(deviceDir, file.name);+ const st = statShardFile(path);+ if (st === null) continue; // removed between the listing and the stat+ const segments = ledger === null ? [stream] : [stream, ledger];+ const rel = posix.join(...segments, device.name, file.name);+ out.push({+ key: `${partition}/${rel}`,+ partition,+ stream,+ ledger,+ device: device.name,+ rel,+ path,+ ...st,+ });+ }+ }+ }++ /**+ * The entries of `dir`, from the cache when its mtime has not moved.+ * Every directory listed here is below a partition folder, and `lstat`+ * reads one that is a symbolic link or a junction as no directory: a+ * linked stream, ledger or device folder a peer synced could otherwise+ * index another partition's records under this one.+ */+ private list(dir: string): ReadonlyArray<Entry> {+ const st = lstatSync(dir, { throwIfNoEntry: false });+ if (st === undefined || !st.isDirectory()) {+ this.listings.delete(dir);+ return [];+ }+ const cached = this.listings.get(dir);+ if (+ cached !== undefined &&+ cached.mtimeMs === st.mtimeMs &&+ cached.listedAt - st.mtimeMs > RACY_LISTING_MS+ ) {+ return cached.entries;+ }+ const listedAt = Date.now();+ let entries: Entry[];+ try {+ entries = readdirSync(dir, { withFileTypes: true }).map((d) => ({+ name: d.name,+ dir: d.isDirectory(),+ file: d.isFile(),+ }));+ } catch (err) {+ if ((err as NodeJS.ErrnoException).code === "ENOENT") return [];+ throw err;+ }+ this.listings.set(dir, { mtimeMs: st.mtimeMs, listedAt, entries });+ return entries;+ }+}diff --git a/src/core/search/cross-vault.ts b/src/core/search/cross-vault.tsindex f2bc4bcd..601579a5 100644--- a/src/core/search/cross-vault.ts+++ b/src/core/search/cross-vault.ts@@ -22,11 +22,15 @@* version; the origin label makes any skew diagnosable per result.*/+import { existsSync } from "node:fs";import { resolve } from "node:path";import { ORIGIN_REACH, ORIGIN_REACH_REASON } from "../brain/portability/origin-reach.ts";import { listSearchOrigins } from "../brain/portability/origins.ts";+import { isStoreRecordPath } from "./brain-store/constants.ts";+import { storeIndexPath } from "./brain-store/location.ts";import { resolveSearchConfig } from "./index.ts";+import { resolveIndexPath } from "./paths.ts";import { RETRIEVAL_DEGRADATION, buildRetrievalTrail, noteDegradation } from "./retrieval-trail.ts";import { search } from "./search.ts";import { readActiveSessionFocus } from "./session-focus.ts";@@ -44,6 +48,78 @@ import type {SearchOutcome,} from "./types.ts";+/**+ * The config a read-only origin is searched with. The brain store is+ * machine-wide, so every vault resolves the same one: its records are the+ * active origin's to answer, and a read-only origin never catches up on+ * it. Such an origin reads the index its vault already has: the+ * store-aware one when this machine built it, else the legacy vault index.+ */+function readOnlyOriginConfig(base: ResolvedSearchConfig): ResolvedSearchConfig {+ const store = base.brainStore;+ if (store === null || store === undefined) return base;+ const storeAware = storeIndexPath(store, base.vault);+ const dbPath =+ base.dbPath === storeAware && !existsSync(storeAware)+ ? resolveIndexPath(base.vault, null, null)+ : base.dbPath;+ return Object.freeze({ ...base, brainStore: null, dbPath });+}++/**+ * A read-only origin's answer without brain store records (the active+ * origin carries them). Only `results` and `cards` are cut to `limit`;+ * every other field (`total`, coverage, warnings, the retrieval trail)+ * is the answer of the window that was searched, which after a refill+ * round is the widest one. The union reads them as that origin's own+ * measurements: `total` is a lower bound on the pool and coverage is+ * folded by maximum, so a wider window cannot make either claim more+ * than the origin found.+ */+function withoutStoreRecords(outcome: SearchOutcome, limit: number): SearchOutcome {+ return {+ ...outcome,+ results: outcome.results.filter((r) => !isStoreRecordPath(r.path)).slice(0, limit),+ ...(outcome.cards !== undefined+ ? { cards: outcome.cards.filter((c) => !isStoreRecordPath(c.path)).slice(0, limit) }+ : {}),+ };+}++/** Rows an answer carries, in whichever collection its mode fills. */+function rowCount(outcome: SearchOutcome): number {+ return outcome.results.length + (outcome.cards?.length ?? 0);+}++/** Times a read-only origin is asked again, with its window doubled, to refill dropped rows. */+const STORE_REFILL_ROUNDS = 3;++/**+ * Search a read-only origin and drop its brain store records. The records+ * are dropped after the origin cut its answer to `limit`, so when its+ * store-aware index ranked them in the window the origin is asked again+ * with a wider one, until the window holds `limit` notes, the origin has+ * nothing more to give, or the rounds run out.+ */+async function searchReadOnlyOrigin(+ config: ResolvedSearchConfig,+ opts: SearchOptions,+ limit: number,+): Promise<SearchOutcome> {+ let window = limit;+ for (let round = 0; ; round++) {+ // eslint-disable-next-line no-await-in-loop -- each round depends on the last+ const answered = await search(config, { ...opts, limit: window });+ const kept = withoutStoreRecords(answered, limit);+ const dropped = rowCount(answered) - rowCount(kept);+ const exhausted = rowCount(answered) < window;+ if (dropped === 0 || rowCount(kept) >= limit || exhausted || round >= STORE_REFILL_ROUNDS) {+ return kept;+ }+ window *= 2;+ }+}+function labelled(result: BrainSearchResult, label: string): BrainSearchResult {return Object.freeze({...result,@@ -187,10 +263,11 @@ export async function searchAcrossVaults(continue;}try {- const base =+ const resolved =isActive && activeConfig !== undefined? activeConfig: resolveSearchConfig({ vault: origin.vault, configPath });+ const base = isActive ? resolved : readOnlyOriginConfig(resolved);// Never write cache rows into a read-only external index.const config = isActive? base@@ -199,12 +276,9 @@ export async function searchAcrossVaults(recall: Object.freeze({ ...base.recall, cacheEnabled: false }),});// eslint-disable-next-line no-await-in-loop -- per-origin stores, sequential by design- const outcome = await search(config, {- ...opts,- sessionFocus,- limit,- ...(isActive ? {} : { selfHeal: false }),- });+ const outcome = await (isActive+ ? search(config, { ...opts, sessionFocus, limit })+ : searchReadOnlyOrigin(config, { ...opts, sessionFocus, selfHeal: false }, limit));merged.push(...outcome.results.map((result) => labelled(result, origin.label)));if (outcome.cards !== undefined) {mergedCards.push(...outcome.cards.map((card) => labelledCard(card, origin.label)));diff --git a/src/core/search/index.ts b/src/core/search/index.tsindex 173453bc..58625522 100644--- a/src/core/search/index.ts+++ b/src/core/search/index.ts@@ -13,7 +13,8 @@ import {} from "../validate.ts";import { resolveVaultScope } from "../vault-scope/index.ts";import { DEFAULT_HYBRID_DEADLINE_MS } from "./pipeline/request.ts";-import { resolveIndexPath, SEARCH_DB_CONFIG_KEY, SEARCH_DB_ENV } from "./paths.ts";+import { resolveIndexPathForProbe, SEARCH_DB_CONFIG_KEY, SEARCH_DB_ENV } from "./paths.ts";+import { resolveIndexedStoreProbe } from "./brain-store/location.ts";import { buildFtsTokenize } from "./schema.ts";import { isFusionMode, DEFAULT_RRF_K } from "./fusion.ts";import { DEFAULT_RECENCY } from "./recency.ts";@@ -856,9 +857,19 @@ export function resolveSearchConfig(opts: {? discoverConfig(opts.configPath).data: {};- const dbPath = resolveIndexPath(+ // The brain store the index catches up from, when one is in use; the+ // index then lives in the store's device-local state (design D5).+ const storeProbe = resolveIndexedStoreProbe({+ vault: opts.vault,+ config,+ configPath: opts.configPath ?? null,+ });+ const brainStore = storeProbe.kind === "store" ? storeProbe.store : null;+ // An `unknown` probe keeps the store index this machine last wrote.+ const dbPath = resolveIndexPathForProbe(opts.vault,envOrConfig(env, config, SEARCH_DB_ENV, SEARCH_DB_CONFIG_KEY),+ storeProbe,);const chunkSize = parseInteger(@@ -1558,6 +1569,8 @@ export function resolveSearchConfig(opts: {const base: ResolvedSearchConfig = Object.freeze({vault: opts.vault,dbPath,+ brainStore,+ ...(storeProbe.kind === "unknown" ? { brainStoreUnknown: true } : {}),configPath: opts.configPath ?? null,scopeRules,chunkSize,diff --git a/src/core/search/indexer.ts b/src/core/search/indexer.tsindex b1b518b5..5a26b22c 100644--- a/src/core/search/indexer.ts+++ b/src/core/search/indexer.ts@@ -115,6 +115,9 @@ import {import { LATEST_SCHEMA_VERSION, documentAttributesFromFrontmatter } from "./schema.ts";import { chunkWindowDiagnosticCode, CHUNK_HOLD_REASON, SearchError } from "./types.ts";import { walkVault } from "./walker.ts";+import { forgetCatchUpState, ingestStoreInto } from "./brain-store/catch-up.ts";+import { purgeStoreRecords } from "./brain-store/ingest.ts";+import { STORE_RECORD_PATH_PREFIX } from "./brain-store/constants.ts";import {callableVisibilitySurfaces,excludedCallableVisibilitySurfaces,@@ -726,6 +729,18 @@ async function indexIntoRun(opts?.onFile?.({ path, kind: "deleted" });}}+ // Store records are left out of the sweep above; an index whose vault+ // reads no store any more drops them here (design D5). A run that+ // could not tell whether a store is in use keeps them: a store.json a+ // sync tool is rewriting would otherwise cost a re-read of every shard.+ if (!config.brainStore && config.brainStoreUnknown !== true) {+ const purged = purgeStoreRecords(store);+ if (purged !== null) {+ forgetCatchUpState(config.dbPath);+ if (purged > 0) markLinkResolutionPending();+ stats.deleted += purged;+ }+ }// Link and alias resolution are a pure function of the documents and// their links. A run that changed no document (and was not forced)@@ -1534,13 +1549,37 @@ async function reindexInto(// `onProgress` is dropped from the forwarded options: the build// reports into THIS run's counter, passed explicitly, rather than// opening a second one over the same sink.- const stats = await indexInto(+ let stats = await indexInto(tempConfig,{ ...opts, force: !resume, onProgress: undefined },undefined,progress,);+ // The brain store goes into the staging index too (design D5), every+ // shard from offset 0, so the swapped-in index answers with the store+ // from its first read instead of catching up on it afterwards. It is+ // best effort: a store that cannot be read must not throw the note+ // rebuild away. A shard whose watermark was not written is read from+ // offset 0 by the next catch-up, so nothing is lost; the failure is+ // reported among the run's errors.+ if (config.brainStore) {+ try {+ await withStagingStore(tempConfig, (store) => ingestStoreInto(store, tempConfig));+ } catch (e) {+ stats = {+ ...stats,+ errors: [+ ...stats.errors,+ {+ path: STORE_RECORD_PATH_PREFIX,+ message: `brain store not ingested, the next catch-up reads it: ${e instanceof Error ? e.message : String(e)}`,+ },+ ],+ };+ }+ }+// Clear the marker so the swapped-in live index carries no staging// state. Only present when resume was enabled.if (config.resumeReindex) {diff --git a/src/core/search/paths.ts b/src/core/search/paths.tsindex a3563e29..8e56380b 100644--- a/src/core/search/paths.ts+++ b/src/core/search/paths.ts@@ -1,8 +1,11 @@/*** Resolve the on-disk location of the search index file.*- * Default: `<vault>/.open-second-brain/brain.sqlite`. Overridable- * through CLI `--db` or config `search_db_path`.+ * Default: `<vault>/.open-second-brain/brain.sqlite`. When a brain store+ * is in use (see `brain-store/location.ts`) the default is the store's+ * device-local state instead: `<device state>/index/<vault key>/brain.sqlite`.+ * Either default is overridable through CLI `--db` or config+ * `search_db_path`.** The two name components come from `brain/path-constants.ts`, the leaf* module that already owns every vault-relative name in this project.@@ -18,6 +21,14 @@ import { join } from "node:path";import { DERIVED_STORE_DIR, DERIVED_STORE_FILE } from "../brain/path-constants.ts";import { defaultConfigPath, discoverConfig } from "../config.ts";import { envOrConfig } from "../validate.ts";+import {+ lastStoreIndexPath,+ rememberStoreRoot,+ resolveIndexedStoreProbe,+ storeIndexPath,+ type IndexedStore,+ type StoreProbe,+} from "./brain-store/location.ts";/** Environment variable that overrides the store location. */export const SEARCH_DB_ENV = "OPEN_SECOND_BRAIN_SEARCH_DB";@@ -25,14 +36,42 @@ export const SEARCH_DB_ENV = "OPEN_SECOND_BRAIN_SEARCH_DB";/** Machine-config key that overrides the store location. */export const SEARCH_DB_CONFIG_KEY = "search_db_path";-export function resolveIndexPath(vault: string, override: string | null): string {+export function resolveIndexPath(+ vault: string,+ override: string | null,+ store: IndexedStore | null = null,+): string {if (override !== null) {const trimmed = override.trim();if (trimmed !== "") return trimmed;}+ if (store !== null) return storeIndexPath(store, vault);return join(vault, DERIVED_STORE_DIR, DERIVED_STORE_FILE);}+/**+ * {@link resolveIndexPath} for a store probe. A probe that could not tell+ * whether a store is in use keeps the store index this machine last wrote+ * for the vault under a store last read at the same root+ * (`lastStoreIndexPath`; a `store` probe records that root), so a passing failure to read+ * store.json neither reads a stale legacy index nor rebuilds an empty one;+ * the legacy location is used only when no such index exists. An explicit+ * override wins as always.+ */+export function resolveIndexPathForProbe(+ vault: string,+ override: string | null,+ probe: StoreProbe,+): string {+ const overridden = override !== null && override.trim() !== "";+ if (probe.kind === "store") rememberStoreRoot(probe.store);+ if (probe.kind === "unknown" && !overridden) {+ const last = lastStoreIndexPath(vault, probe.root);+ if (last !== null) return last;+ }+ return resolveIndexPath(vault, override, probe.kind === "store" ? probe.store : null);+}+/*** The store location a caller holding no resolved search config should* use: the default, unless the environment or the machine config moves it.@@ -53,8 +92,9 @@ export function resolveIndexPath(vault: string, override: string | null): stringexport function resolveConfiguredIndexPath(vault: string, configPath?: string): string {const path = configPath ?? defaultConfigPath();const config = discoverConfig(path).data;- return resolveIndexPath(+ return resolveIndexPathForProbe(vault,envOrConfig(process.env, config, SEARCH_DB_ENV, SEARCH_DB_CONFIG_KEY),+ resolveIndexedStoreProbe({ vault, config, configPath: path }),);}diff --git a/src/core/search/pipeline/pool-filters.ts b/src/core/search/pipeline/pool-filters.tsindex 66eac63b..12aae55b 100644--- a/src/core/search/pipeline/pool-filters.ts+++ b/src/core/search/pipeline/pool-filters.ts@@ -27,6 +27,8 @@ import {type FrontmatterCache,} from "../result-filters.ts";import type { Store } from "../store.ts";+import { documentSourceFor, type DocumentSource } from "../brain-store/constants.ts";+import { documentSources } from "../store/brain-records.ts";import type { DegreePredicate } from "../property-filter.ts";import type { BrainSearchResult, SearchOptions } from "../types.ts";@@ -61,6 +63,8 @@ export interface PoolFilters {readonly reach: TransportReach;readonly agentScope: ReturnType<typeof normalizeAgentScope>;readonly scopeFilter: ReturnType<typeof normalizeScopeFilter> | null;+ /** The document source the caller limited the search to, or null for both. */+ readonly source: DocumentSource | null;/*** True when at least one requested filter can drop a ranked row, which* is what makes the candidate pool overfetch up front.@@ -115,6 +119,7 @@ export function resolvePoolFilters(opts: SearchOptions): PoolFilters {(normalizedScope.session !== null || normalizedScope.project !== null)? normalizedScope: null;+ const source = opts.source !== undefined ? documentSourceFor(opts.source) : null;return {properties,pushdown,@@ -124,7 +129,9 @@ export function resolvePoolFilters(opts: SearchOptions): PoolFilters {reach,agentScope,scopeFilter,+ source,canDropRows:+ source !== null ||properties !== null ||hasVisibilityRequest ||agentScope !== null ||@@ -183,7 +190,10 @@ export function applyPoolFilters(// Belief lifecycle suite (t_7d5a3589): drop tombstoned (incl.// superseded-non-tip) memories before any other post-rank stage.// A vault with no tombstoned entries passes through unchanged.- const statusFiltered = applyStatusFilter(ranked, ctx.vault, ctx.frontmatterCache);+ // Source (design D5) first: it reads only the index, and a row it drops+ // costs no frontmatter read in the stages after it.+ const sourced = filters.source !== null ? applySourceFilter(ranked, filters.source, ctx) : ranked;+ const statusFiltered = applyStatusFilter(sourced, ctx.vault, ctx.frontmatterCache);const propFiltered =filters.properties !== null? applyPropertyFilter(statusFiltered, filters.properties, ctx.vault, ctx.frontmatterCache)@@ -268,6 +278,23 @@ export function applyPoolFilters(};}+/**+ * Keep the rows whose document has the requested source. A row whose+ * document the index no longer holds is dropped: nothing says which side+ * it belongs to.+ */+function applySourceFilter(+ ranked: ReadonlyArray<BrainSearchResult>,+ source: DocumentSource,+ ctx: FilterContext,+): ReadonlyArray<BrainSearchResult> {+ const sources = documentSources(+ ctx.store.brainRecordsConnection(),+ ranked.map((r) => r.documentId),+ );+ return ranked.filter((r) => sources.get(r.documentId) === source);+}+/*** Judge the traversal-arm rows (searchType "link") under the promoted* property filter with the same live predicate every other row's fallbackdiff --git a/src/core/search/query-cache.ts b/src/core/search/query-cache.tsindex 630d63f6..26a22f29 100644--- a/src/core/search/query-cache.ts+++ b/src/core/search/query-cache.ts@@ -161,6 +161,8 @@ export function buildCacheKey(// promoted properties need no separate input - they are part of// `properties`, already canonicalized above.kind: opts.kind ?? undefined,+ // The source filter (design D5) partitions the cache the same way; absent keeps the key.+ source: opts.source ?? undefined,// Per-source-session pool cap override (t_bb6ce095) partitions the// cache: an explicit `0` forces the cap off for this query, which// differs from the config default. Dropped when absent, so a querydiff --git a/src/core/search/result-filters.ts b/src/core/search/result-filters.tsindex fa559c16..98a9096e 100644--- a/src/core/search/result-filters.ts+++ b/src/core/search/result-filters.ts@@ -38,6 +38,7 @@ import {type RankAdjustVerdict,} from "./rank-adjust.ts";import type { BrainSearchResult } from "./types.ts";+import { isStoreRecordPath } from "./brain-store/constants.ts";/*** A cached frontmatter read, plus whether the file could be read at all.@@ -407,6 +408,12 @@ export function applyVisibilityScope(* ids, retired ids and evidence artifacts, and the page carries no* visibility that could say so. The log's dedicated readers render its* events per reader instead.+ *+ * A brain store record ({@link isStoreRecordPath}) answers `false` below+ * local reach too: it is not a file in the vault, so no frontmatter can+ * be measured for it, and its body may name the same reserved ids a log+ * page does. Store records reach local callers only until the store has+ * per-record visibility of its own.*/export function isPathReadableAtReach(vault: string,@@ -416,7 +423,10 @@ export function isPathReadableAtReach(indexedTags: ReadonlyArray<string> = [],): boolean {if (!pathIsInside(join(vault, path), vault)) return false;- if (reach !== TRANSPORT_REACH.local && (isCompiledDigestRel(path) || isBrainLogRel(path))) {+ if (+ reach !== TRANSPORT_REACH.local &&+ (isCompiledDigestRel(path) || isBrainLogRel(path) || isStoreRecordPath(path))+ ) {return false;}const entry = readCachedFrontmatterEntry(frontmatterCache, vault, path);diff --git a/src/core/search/retrieval-trail.ts b/src/core/search/retrieval-trail.tsindex aa7f357c..5cdd9546 100644--- a/src/core/search/retrieval-trail.ts+++ b/src/core/search/retrieval-trail.ts@@ -79,6 +79,12 @@ export const RETRIEVAL_DEGRADATION = Object.freeze({* stored in the query cache.*/indexStale: "index-stale",+ /**+ * The brain store catch-up before this read failed, so store records+ * appended since the last good catch-up may be missing from the answer.+ * The failure's own message rides the warning sentence, not the code.+ */+ storeCatchUpFailed: "store-catch-up-failed",/*** The query tokenised to an empty FTS match, so the keyword lane never* ran. The purest silent empty in the tree: `fts.ts` returned no hits@@ -232,6 +238,7 @@ export type RetrievalDegradationCode =/** Membership list, ordered lane by lane along the pipeline. */export const RETRIEVAL_DEGRADATION_CODES: ReadonlyArray<RetrievalDegradationCode> = Object.freeze([RETRIEVAL_DEGRADATION.indexStale,+ RETRIEVAL_DEGRADATION.storeCatchUpFailed,RETRIEVAL_DEGRADATION.keywordFtsMatchEmpty,RETRIEVAL_DEGRADATION.keywordTrigramLaneFault,RETRIEVAL_DEGRADATION.semanticEmbeddingsAbsent,@@ -431,6 +438,8 @@ export function describeRetrievalDegradation(code: RetrievalDegradationCode): stswitch (code) {case RETRIEVAL_DEGRADATION.indexStale:return "the index was last updated more than ten minutes ago, so notes changed since then may be missing";+ case RETRIEVAL_DEGRADATION.storeCatchUpFailed:+ return "the brain store catch-up before this read failed, so store records added since the last good catch-up may be missing";case RETRIEVAL_DEGRADATION.keywordFtsMatchEmpty:return "the query carried no term the keyword index can match, so the keyword lane never ran";case RETRIEVAL_DEGRADATION.keywordTrigramLaneFault:diff --git a/src/core/search/schema.ts b/src/core/search/schema.tsindex e5a9539e..a09f6544 100644--- a/src/core/search/schema.ts+++ b/src/core/search/schema.ts@@ -13,13 +13,20 @@ import { SearchError } from "./types.ts";import { hasPrivacyMarkerKey, remoteDenyVisibilityTokens } from "../graph/privacy-markers.ts";import { parseFrontmatterText } from "../vault.ts";import { closeDatabase } from "../sqlite-close.ts";+import { BRAIN_ROOT_REL } from "../brain/path-constants.ts";+import { newUlid } from "../store/ulid.ts";+import {+ DOCUMENT_SOURCE,+ STORE_INDEX_GENERATION_KEY,+ STORE_RECORD_PATH_PREFIX,+} from "./brain-store/constants.ts";/*** Latest schema version this code understands. A DB with a value above* this raises `SCHEMA_MISMATCH` on open β the operator must reindex* with a newer binary.*/-export const LATEST_SCHEMA_VERSION = 16;+export const LATEST_SCHEMA_VERSION = 17;/*** The one command that rebuilds an index this binary cannot read. Every@@ -787,8 +794,115 @@ export const MIGRATIONS: ReadonlyArray<Migration> = Object.freeze([restampMarkerVisibility(db);},},+ {+ // v17 (brain store index, design D5, task 1.8) - what the index needs+ // to read the brain store beside the vault:+ //+ // - `store_watermarks`: one row per shard - its file identity, size,+ // mtime, the byte offset read so far and a hash of the verified+ // prefix - so catch-up reads only what was appended and re-reads a+ // replaced, shrunk or rewritten shard from the start;+ // - `records`: one row per store record (envelope fields, the shard+ // it was last read from, an ingest sequence the change probe pages+ // by, and the document its text was indexed under, if any);+ // - `documents.source`: a VIRTUAL generated column deriving `note` or+ // `brain` from the path alone (store records and the legacy+ // `Brain/` tree are brain), so no writer can forget to set it and+ // no backfill is needed;+ // - the index generation: a fresh ULID per index file, so a watermark+ // from a replaced index is recognised as stale.+ //+ // In place and reindex-safe: no existing row changes. The empty+ // watermark table makes the next catch-up read every shard from offset+ // 0, which is also what picks up records an older binary skipped for+ // an unknown format version.+ version: 17,+ up(db) {+ const docCols = db.query<{ name: string }, []>("PRAGMA table_xinfo(documents)").all();+ if (!docCols.some((c) => c.name === DOCUMENT_SOURCE_COLUMN)) {+ db.exec(+ `ALTER TABLE documents ADD COLUMN ${DOCUMENT_SOURCE_COLUMN} TEXT ` ++ `GENERATED ALWAYS AS (${documentSourceExpression()}) VIRTUAL`,+ );+ }+ db.exec(DDL_V17_STORE);+ db.query("INSERT OR IGNORE INTO index_state(key, value, updated_at) VALUES (?, ?, ?)").run(+ STORE_INDEX_GENERATION_KEY,+ newUlid(),+ new Date().toISOString(),+ );+ },+ },]);+/** The `documents` column naming where a document came from (v17). */+export const DOCUMENT_SOURCE_COLUMN = "source";++/** One row per store shard the index has read (v17). */+export const STORE_WATERMARKS_TABLE = "store_watermarks";++/** One row per store record the index has ingested (v17). */+export const RECORDS_TABLE = "records";++const DDL_V17_STORE = `+CREATE TABLE IF NOT EXISTS ${STORE_WATERMARKS_TABLE} (+ shard TEXT PRIMARY KEY,+ partition TEXT NOT NULL,+ identity TEXT NOT NULL,+ size INTEGER NOT NULL,+ mtime_ms INTEGER NOT NULL,+ byte_offset INTEGER NOT NULL,+ prefix_hash TEXT NOT NULL,+ unknown_versions INTEGER NOT NULL DEFAULT 0,+ corrupt_lines INTEGER NOT NULL DEFAULT 0,+ updated_at TEXT NOT NULL+);+CREATE TABLE IF NOT EXISTS ${RECORDS_TABLE} (+ id TEXT PRIMARY KEY,+ seq INTEGER NOT NULL UNIQUE,+ document_id INTEGER REFERENCES documents(id) ON DELETE SET NULL,+ partition TEXT NOT NULL,+ stream TEXT NOT NULL,+ ledger TEXT,+ kind TEXT NOT NULL,+ scope TEXT,+ topic TEXT,+ hlc TEXT NOT NULL,+ device TEXT NOT NULL,+ agent TEXT NOT NULL,+ authority TEXT,+ sum TEXT NOT NULL,+ shard TEXT NOT NULL,+ body_pending INTEGER NOT NULL DEFAULT 0,+ indexed_at TEXT NOT NULL+);+CREATE INDEX IF NOT EXISTS idx_records_shard ON ${RECORDS_TABLE}(shard);+CREATE INDEX IF NOT EXISTS idx_records_document ON ${RECORDS_TABLE}(document_id);+CREATE INDEX IF NOT EXISTS idx_records_pending ON ${RECORDS_TABLE}(body_pending) WHERE body_pending = 1;+`;++/** SQL string literal of `value` (single quotes doubled). */+function sqlLiteral(value: string): string {+ return `'${value.replaceAll("'", "''")}'`;+}++/**+ * The generated-column expression of {@link DOCUMENT_SOURCE_COLUMN}: a+ * store record (`.brain-store/...`) or a page of the legacy brain tree+ * (`Brain` or `Brain/...`, compared case-sensitively) is `brain`, every+ * other path is a user `note`.+ */+function documentSourceExpression(): string {+ const storePrefix = `${STORE_RECORD_PATH_PREFIX}/`;+ const brainPrefix = `${BRAIN_ROOT_REL}/`;+ return (+ `CASE WHEN substr(path, 1, ${storePrefix.length}) = ${sqlLiteral(storePrefix)} ` ++ `OR path = ${sqlLiteral(BRAIN_ROOT_REL)} ` ++ `OR substr(path, 1, ${brainPrefix.length}) = ${sqlLiteral(brainPrefix)} ` ++ `THEN ${sqlLiteral(DOCUMENT_SOURCE.brain)} ELSE ${sqlLiteral(DOCUMENT_SOURCE.note)} END`+ );+}+/*** The `documents` column holding what the index measured of a page's* `visibility:` frontmatter. Named once: the migration, the store, thediff --git a/src/core/search/search-options-descriptor.ts b/src/core/search/search-options-descriptor.tsindex aa3a614d..19080764 100644--- a/src/core/search/search-options-descriptor.ts+++ b/src/core/search/search-options-descriptor.ts@@ -50,6 +50,7 @@ import { DISCLOSURE_MODES } from "./disclosure-mode.ts";import { FTS_MATCH_MODES } from "./fts-match-mode.ts";import { RECALL_PROFILE_NAMES } from "./profiles.ts";import { SEARCH_KINDS } from "./property-pushdown.ts";+import { SEARCH_SOURCES } from "./brain-store/constants.ts";/** The longest `query` the served brain_search schema advertises, enforced by its handler. */export const MCP_QUERY_MAX_CHARS = 2000;@@ -110,7 +111,7 @@ export interface SearchOptionRow {/*** Every caller-facing field of the search language, in the order the- * served schema declares them. The three cli-only rows close the table:+ * served schema declares them. The cli-only rows close the table:* they back `SearchOptions` fields the served MCP schema omits, and their* fragments are documentation (they never reach the mcp projection).*/@@ -669,6 +670,20 @@ export const SEARCH_OPTION_ROWS: ReadonlyArray<SearchOptionRow> = Object.freeze(surfaces: ["cli"],default: "false",},+ {+ name: "source",+ option: "source",+ schema: {+ type: "string",+ enum: [...SEARCH_SOURCES],+ description:+ "Limit results to the user's notes ('notes') or to brain records ('brain'). CLI-only for now: the served MCP schema is unchanged.",+ },+ cliFlag: "source",+ cliKind: "string",+ surfaces: ["cli"],+ default: "absent: notes and brain records",+ },] satisfies readonly SearchOptionRow[]);/** The derived shape of the served `brain_search` input schema. */diff --git a/src/core/search/search.ts b/src/core/search/search.tsindex 41d08b79..ca2536f4 100644--- a/src/core/search/search.ts+++ b/src/core/search/search.ts@@ -56,6 +56,7 @@ import { noSecondPass, runSecondPassRecall } from "./pipeline/second-pass.ts";import { runSemanticLane, type SemanticLaneOutcome } from "./pipeline/semantic-lane.ts";import type { SemanticEmbedTiming } from "./semantic-phase.ts";import { openReadOrSelfHeal } from "./pipeline/store-open.ts";+import { catchUpBrainStore, type CatchUpResult } from "./brain-store/catch-up.ts";import { resolveEffectiveWeights } from "./pipeline/weights.ts";import { detectHybridDegrade } from "./enrich.ts";import { isAbortError } from "./embeddings/http-util.ts";@@ -422,10 +423,19 @@ export async function search(// Read-only origins (cross-vault search) disable self-healing: a// rebuild would write an index INTO the external vault. Default// (selfHeal absent) keeps the legacy heal-and-retry behaviour.+ // Catch-up before reads (design D5): ingest what the brain store gained+ // since the last check. Read-only origins never write their index. An+ // index the open below has to build or upgrade first is caught up right+ // after it, so the answer already includes the store.+ const catchUps: CatchUpResult[] = [];+ if (opts.selfHeal !== false) catchUps.push(await catchUpBrainStore(effectiveConfig));const store =opts.selfHeal === false? await Store.open(effectiveConfig, { mode: "read" }): await openReadOrSelfHeal(effectiveConfig);+ if (catchUps[0]?.skipped === "no-index" || catchUps[0]?.skipped === "not-current") {+ catchUps.push(await catchUpBrainStore(effectiveConfig, { force: true }));+ }try {const warnings: string[] = [];// The typed sink that rides beside `warnings` (evidence-at-the-boundary,@@ -433,6 +443,11 @@ export async function search(// caller can tell an exhausted corpus from a broken embedder without// matching on prose.const degraded: RetrievalDegradationSink = [];+ const failedCatchUp = catchUps.findLast((c) => c.skipped === "failed");+ if (failedCatchUp !== undefined) {+ warnings.push(`brain store catch-up failed, records may be missing: ${failedCatchUp.error}`);+ noteDegradation(degraded, RETRIEVAL_DEGRADATION.storeCatchUpFailed);+ }// Freshen on read: an index older than the interval starts one// background incremental run (never into a read-only origin); this// answer comes from the index as it is. A badly stale index is nameddiff --git a/src/core/search/store.ts b/src/core/search/store.tsindex decbd7cc..487a228d 100644--- a/src/core/search/store.ts+++ b/src/core/search/store.ts@@ -1132,6 +1132,18 @@ export class Store {return census.chunksOverTokenWindow(this.db, windowTokens);}+ // ββ brain store records (v17, design D5) βββββββββββββββββββββββββββββββββββ++ /**+ * The connection the brain store tables are read and written through+ * (`store/brain-records.ts`). Store-record documents and chunks still go+ * through the typed document and chunk methods above; only the two v17+ * tables, which no other caller touches, are handed the connection.+ */+ brainRecordsConnection(): Database {+ return this.db;+ }+// ββ direct accessors used by indexer/CLI/status ββββββββββββββββββββββββββββ/** Escape hatch for status queries that don't fit the typed API. */diff --git a/src/core/search/store/brain-records.ts b/src/core/search/store/brain-records.tsnew file mode 100644index 00000000..0490b085--- /dev/null+++ b/src/core/search/store/brain-records.ts@@ -0,0 +1,327 @@+/**+ * The brain store tables of the index (schema v17, design D5): the+ * per-shard watermarks catch-up resumes from, and one row per ingested+ * store record. Pure SQL over a connection; `brain-store/catch-up.ts`+ * decides what to write and `brain-store/changes.ts` reads the change+ * probe from here.+ */++import { Database } from "bun:sqlite";++import { DOCUMENT_SOURCE_COLUMN, RECORDS_TABLE, STORE_WATERMARKS_TABLE } from "../schema.ts";+import { STORE_RECORD_SEQ_FLOOR_KEY, type DocumentSource } from "../brain-store/constants.ts";+import { nowIso } from "./sql.ts";++/** Where catch-up stopped in one shard, and what the shard looked like then. */+export interface StoreWatermark {+ /** `<partition>/<partition-relative shard path>`. */+ readonly shard: string;+ readonly partition: string;+ /** File identity (`dev:ino`, or a fallback; see `brain-store/shard-scan.ts`). */+ readonly identity: string;+ readonly size: number;+ readonly mtimeMs: number;+ /** First byte not consumed. */+ readonly offset: number;+ /** Hash of samples of the verified prefix (`brain-store/prefix-hash.ts`). */+ readonly prefixHash: string;+ /** Lines skipped for a newer format version, counted over the whole shard. */+ readonly unknownVersions: number;+ /** Middle lines that failed verification, counted over the whole shard. */+ readonly corruptLines: number;+}++/** One ingested record, as the `records` table holds it. */+export interface RecordRow {+ readonly id: string;+ readonly partition: string;+ readonly stream: string;+ readonly ledger: string | null;+ readonly kind: string;+ readonly scope: string | null;+ readonly topic: string | null;+ readonly hlc: string;+ readonly device: string;+ readonly agent: string;+ readonly authority: string | null;+ /** The envelope checksum; also the blob name of a spilled body. */+ readonly sum: string;+ readonly shard: string;+ readonly bodyPending: boolean;+}++/** A stored record with its ingest sequence and indexed document. */+export interface StoredRecord extends RecordRow {+ readonly seq: number;+ readonly documentId: number | null;+}++interface WatermarkSqlRow {+ shard: string;+ partition: string;+ identity: string;+ size: number;+ mtime_ms: number;+ byte_offset: number;+ prefix_hash: string;+ unknown_versions: number;+ corrupt_lines: number;+}++/** Whether `db` carries the v17 store tables (an older index does not). */+export function hasBrainRecordTables(db: Database): boolean {+ return (+ db+ .query<{ n: number }, [string]>(+ "SELECT COUNT(*) AS n FROM sqlite_master WHERE type = 'table' AND name = ?",+ )+ .get(STORE_WATERMARKS_TABLE)!.n === 1+ );+}++/** Every stored watermark, keyed by shard. */+export function readWatermarks(db: Database): Map<string, StoreWatermark> {+ const rows = db+ .query<WatermarkSqlRow, []>(+ "SELECT shard, partition, identity, size, mtime_ms, byte_offset, prefix_hash, " ++ `unknown_versions, corrupt_lines FROM ${STORE_WATERMARKS_TABLE}`,+ )+ .all();+ const out = new Map<string, StoreWatermark>();+ for (const r of rows) {+ out.set(r.shard, {+ shard: r.shard,+ partition: r.partition,+ identity: r.identity,+ size: r.size,+ mtimeMs: r.mtime_ms,+ offset: r.byte_offset,+ prefixHash: r.prefix_hash,+ unknownVersions: r.unknown_versions,+ corruptLines: r.corrupt_lines,+ });+ }+ return out;+}++export function writeWatermark(db: Database, w: StoreWatermark): void {+ db.query(+ `INSERT INTO ${STORE_WATERMARKS_TABLE}(shard, partition, identity, size, mtime_ms, byte_offset, ` ++ "prefix_hash, unknown_versions, corrupt_lines, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) " ++ "ON CONFLICT(shard) DO UPDATE SET partition = excluded.partition, identity = excluded.identity, " ++ "size = excluded.size, mtime_ms = excluded.mtime_ms, byte_offset = excluded.byte_offset, " ++ "prefix_hash = excluded.prefix_hash, unknown_versions = excluded.unknown_versions, " ++ "corrupt_lines = excluded.corrupt_lines, updated_at = excluded.updated_at",+ ).run(+ w.shard,+ w.partition,+ w.identity,+ w.size,+ w.mtimeMs,+ w.offset,+ w.prefixHash,+ w.unknownVersions,+ w.corruptLines,+ nowIso(),+ );+}++export function deleteWatermark(db: Database, shard: string): void {+ db.query(`DELETE FROM ${STORE_WATERMARKS_TABLE} WHERE shard = ?`).run(shard);+}++interface RecordSqlRow {+ id: string;+ seq: number;+ document_id: number | null;+ partition: string;+ stream: string;+ ledger: string | null;+ kind: string;+ scope: string | null;+ topic: string | null;+ hlc: string;+ device: string;+ agent: string;+ authority: string | null;+ sum: string;+ shard: string;+ body_pending: number;+}++const RECORD_COLUMNS =+ "id, seq, document_id, partition, stream, ledger, kind, scope, topic, hlc, device, agent, " ++ "authority, sum, shard, body_pending";++function toStored(r: RecordSqlRow): StoredRecord {+ return {+ id: r.id,+ seq: r.seq,+ documentId: r.document_id,+ partition: r.partition,+ stream: r.stream,+ ledger: r.ledger,+ kind: r.kind,+ scope: r.scope,+ topic: r.topic,+ hlc: r.hlc,+ device: r.device,+ agent: r.agent,+ authority: r.authority,+ sum: r.sum,+ shard: r.shard,+ bodyPending: r.body_pending === 1,+ };+}++export function getRecord(db: Database, id: string): StoredRecord | null {+ const row = db+ .query<RecordSqlRow, [string]>(`SELECT ${RECORD_COLUMNS} FROM ${RECORDS_TABLE} WHERE id = ?`)+ .get(id);+ return row === null ? null : toStored(row);+}++/**+ * The next ingest sequence: one above both the highest live row and the+ * highest sequence a removed row ever held ({@link deleteRecordRow} keeps+ * that floor), so a sequence is never handed out twice within one index+ * generation and a change-probe watermark never hides a later record.+ */+const NEXT_SEQ_SQL =+ `(SELECT MAX(COALESCE((SELECT MAX(seq) FROM ${RECORDS_TABLE}), 0), ` ++ "COALESCE((SELECT CAST(value AS INTEGER) FROM index_state WHERE key = ?), 0)) + 1)";++/**+ * Insert a record, or refresh the row of one already ingested. An existing+ * row keeps its ingest sequence, so re-reading a shard never makes the+ * change probe report a record twice.+ */+export function upsertRecord(db: Database, row: RecordRow, documentId: number | null): void {+ db.query(+ `INSERT INTO ${RECORDS_TABLE}(id, seq, document_id, partition, stream, ledger, kind, scope, ` ++ "topic, hlc, device, agent, authority, sum, shard, body_pending, indexed_at) " ++ `VALUES (?, ${NEXT_SEQ_SQL}, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ` ++ "ON CONFLICT(id) DO UPDATE SET document_id = excluded.document_id, partition = excluded.partition, " ++ "stream = excluded.stream, ledger = excluded.ledger, kind = excluded.kind, scope = excluded.scope, " ++ "topic = excluded.topic, hlc = excluded.hlc, device = excluded.device, agent = excluded.agent, " ++ "authority = excluded.authority, sum = excluded.sum, shard = excluded.shard, " ++ "body_pending = excluded.body_pending, " ++ "indexed_at = excluded.indexed_at",+ ).run(+ row.id,+ STORE_RECORD_SEQ_FLOOR_KEY,+ documentId,+ row.partition,+ row.stream,+ row.ledger,+ row.kind,+ row.scope,+ row.topic,+ row.hlc,+ row.device,+ row.agent,+ row.authority,+ row.sum,+ row.shard,+ row.bodyPending ? 1 : 0,+ nowIso(),+ );+}++/** Ids of the records last read from `shard`. */+export function recordIdsOfShard(db: Database, shard: string): string[] {+ return db+ .query<{ id: string }, [string]>(`SELECT id FROM ${RECORDS_TABLE} WHERE shard = ?`)+ .all(shard)+ .map((r) => r.id);+}++/** Delete a record row, keeping its sequence as the floor the next sequence starts above. */+export function deleteRecordRow(db: Database, id: string): void {+ db.transaction(() => {+ db.query(+ "INSERT INTO index_state(key, value, updated_at) " ++ `SELECT ?, CAST(seq AS TEXT), ? FROM ${RECORDS_TABLE} WHERE id = ? ` ++ "ON CONFLICT(key) DO UPDATE SET value = CAST(MAX(CAST(index_state.value AS INTEGER), " ++ "CAST(excluded.value AS INTEGER)) AS TEXT), updated_at = excluded.updated_at",+ ).run(STORE_RECORD_SEQ_FLOOR_KEY, nowIso(), id);+ db.query(`DELETE FROM ${RECORDS_TABLE} WHERE id = ?`).run(id);+ })();+}++/** Paths of every indexed document that is a brain store record. */+export function storeRecordDocumentPaths(db: Database, prefix: string): string[] {+ return db+ .query<{ path: string }, [number, string]>(+ "SELECT path FROM documents WHERE substr(path, 1, ?) = ?",+ )+ .all(prefix.length, prefix)+ .map((r) => r.path);+}++/**+ * Empty the store tables: every record row and watermark. The highest+ * sequence is kept as the floor, as {@link deleteRecordRow} keeps it, so+ * records ingested later are still new after any watermark handed out.+ */+export function clearStoreTables(db: Database): void {+ db.transaction(() => {+ db.query(+ "INSERT INTO index_state(key, value, updated_at) " ++ `SELECT ?, CAST(MAX(seq) AS TEXT), ? FROM ${RECORDS_TABLE} WHERE true HAVING MAX(seq) IS NOT NULL ` ++ "ON CONFLICT(key) DO UPDATE SET value = CAST(MAX(CAST(index_state.value AS INTEGER), " ++ "CAST(excluded.value AS INTEGER)) AS TEXT), updated_at = excluded.updated_at",+ ).run(STORE_RECORD_SEQ_FLOOR_KEY, nowIso());+ db.query(`DELETE FROM ${RECORDS_TABLE}`).run();+ db.query(`DELETE FROM ${STORE_WATERMARKS_TABLE}`).run();+ })();+}++/** Whether any store record or watermark is held. */+export function holdsStoreRows(db: Database): boolean {+ return (+ db+ .query<{ n: number }, []>(+ `SELECT EXISTS(SELECT 1 FROM ${RECORDS_TABLE}) OR EXISTS(SELECT 1 FROM ${STORE_WATERMARKS_TABLE}) AS n`,+ )+ .get()!.n === 1+ );+}++/** Records whose body was a blob that had not arrived yet. */+export function pendingRecords(db: Database): StoredRecord[] {+ return db+ .query<RecordSqlRow, []>(+ `SELECT ${RECORD_COLUMNS} FROM ${RECORDS_TABLE} WHERE body_pending = 1 ORDER BY seq`,+ )+ .all()+ .map(toStored);+}++/** Records ingested after sequence `since`, oldest first, at most `limit`. */+export function recordsAfter(db: Database, since: number, limit: number): StoredRecord[] {+ return db+ .query<RecordSqlRow, [number, number]>(+ `SELECT ${RECORD_COLUMNS} FROM ${RECORDS_TABLE} WHERE seq > ? ORDER BY seq LIMIT ?`,+ )+ .all(since, limit)+ .map(toStored);+}++/** The source of each of `documentIds` that is indexed. */+export function documentSources(+ db: Database,+ documentIds: ReadonlyArray<number>,+): Map<number, DocumentSource> {+ const out = new Map<number, DocumentSource>();+ if (documentIds.length === 0) return out;+ // One statement for the whole candidate pool, not one per document.+ const rows = db+ .query<{ id: number; source: DocumentSource }, [string]>(+ `SELECT id, ${DOCUMENT_SOURCE_COLUMN} AS source FROM documents ` ++ "WHERE id IN (SELECT value FROM json_each(?))",+ )+ .all(JSON.stringify([...new Set(documentIds)]));+ for (const row of rows) out.set(row.id, row.source);+ return out;+}diff --git a/src/core/search/store/documents.ts b/src/core/search/store/documents.tsindex 35331ef8..ff4ac471 100644--- a/src/core/search/store/documents.ts+++ b/src/core/search/store/documents.ts@@ -18,6 +18,7 @@ import {encodeDocumentVisibility,} from "../schema.ts";import { SearchError } from "../types.ts";+import { STORE_RECORD_PATH_PREFIX } from "../brain-store/constants.ts";import { pathPrefixRange } from "./path-prefix.ts";import { nowIso } from "./sql.ts";import { purgeVecRowsForDocument } from "./vectors.ts";@@ -127,7 +128,18 @@ export interface DocumentSummary {readonly size: number;}+/**+ * Every indexed VAULT document, keyed by path; never a brain store record+ * (paths under {@link STORE_RECORD_PATH_PREFIX}). The indexers compare+ * this map with a walk of the vault, where a store record never appears,+ * so listing one would read as a deleted note and the sweep would remove+ * it. The other callers (the link graph, communities, bridge discovery,+ * belief clustering, index-root coverage) are vault views too and get+ * vault documents only by the same rule. A caller that needs the store+ * records reads them through `brain-records.ts`.+ */export function listDocuments(db: Database): Map<string, DocumentSummary> {+ const storePrefix = `${STORE_RECORD_PATH_PREFIX}/`;const rows = db.query<{@@ -137,9 +149,9 @@ export function listDocuments(db: Database): Map<string, DocumentSummary> {mtime: number;size: number;},- []- >("SELECT id, path, content_hash, mtime, size FROM documents")- .all();+ [number, string]+ >("SELECT id, path, content_hash, mtime, size FROM documents WHERE substr(path, 1, ?) != ?")+ .all(storePrefix.length, storePrefix);const map = new Map<string, DocumentSummary>();for (const r of rows) {map.set(r.path, {diff --git a/src/core/search/types.ts b/src/core/search/types.tsindex 4bdf0087..ee95bd7c 100644--- a/src/core/search/types.ts+++ b/src/core/search/types.ts@@ -23,6 +23,8 @@ import type { VaultPathRule, VaultScopeRules } from "../vault-scope/defaults.ts"import type { NeedsLlmStep } from "../brain/llm-step.ts";import type { MaintenanceSpendReceipt } from "../brain/maintenance/journal.ts";import type { EmbeddingPriceOverride, EmbeddingPriceSource } from "./embeddings/pricing.ts";+import type { IndexedStore } from "./brain-store/location.ts";+import type { SearchSource } from "./brain-store/constants.ts";import type { DegreePredicate } from "./property-filter.ts";import type { TemporalIntent } from "./temporal-intent.ts";import type { FtsMatchMode } from "./fts-match-mode.ts";@@ -1040,6 +1042,14 @@ export interface SearchOptions {* byte-identical to prior behaviour.*/readonly kind?: "page" | "section";+ /**+ * Source filter (design D5): `notes` keeps only the user's notes, `brain`+ * only brain records (store records and pages of the legacy `Brain/`+ * tree), judged by the index's `documents.source` column. Applied as a+ * post-rank pool filter, so the pool overfetches when it is set. Absent =+ * both, byte-identical to prior behaviour.+ */+ readonly source?: SearchSource;/*** Graph-degree cardinality predicates (t_9bee8f0b). Each predicate* selects notes by backlink/outlink count (orphans `backlinks = 0`,@@ -1926,6 +1936,20 @@ export interface ResolvedFreshenConfig {export interface ResolvedSearchConfig {readonly vault: string;readonly dbPath: string;+ /**+ * The brain store this index catches up from before every read (design+ * D5), or null/absent when no store is in use: the index then holds the+ * vault's notes only, exactly as before the store existed.+ */+ readonly brainStore?: IndexedStore | null;+ /**+ * `true` when this resolution could not tell whether a store is in use+ * (the store root did not resolve, an identity file was unreadable, or+ * the partitions disagreed), as opposed to finding none. The indexer+ * then keeps the store records an index already holds instead of+ * purging them over what may be a passing failure.+ */+ readonly brainStoreUnknown?: boolean;/*** The config file this resolution read, or null when it consulted no* file (env-only). Carried so a per-phase re-read (the relationaldiff --git a/src/core/state/surfaces.ts b/src/core/state/surfaces.tsindex 34a841b6..25eff457 100644--- a/src/core/state/surfaces.ts+++ b/src/core/state/surfaces.ts@@ -940,7 +940,7 @@ export const STATE_SURFACES: ReadonlyArray<StateSurface> = Object.freeze(["Pre-rendered context packs keyed by root and agent scope. Inside the Markdown tree and " +"still derived: deleting it costs one recomputation, and every byte in it came from the " +"vault it sits in.",- sources: ["src/core/brain/anticipatory-cache.ts"],+ sources: ["src/core/brain/anticipatory-cache.ts", "src/core/brain/anticipatory-prune.ts"],},{id: STATE_SURFACE_ID.exactState,diff --git a/src/core/store/FORMAT.md b/src/core/store/FORMAT.mdnew file mode 100644index 00000000..92dba7c3--- /dev/null+++ b/src/core/store/FORMAT.md@@ -0,0 +1,271 @@+<!-- open-second-brain-store-format: 1 -->++# Open Second Brain store format++Format version: 1++This document describes the on-disk format of an Open Second Brain brain store: the folder that holds every piece of Open Second Brain machine data outside the user's notes. The format is open and plain text so that any tool, in any language, can read it, and so that several machines and many concurrent agents can write it through an ordinary file-sync tool without conflicts.++A copy of this document is written into the store root and into every partition when a store is created, and refreshed when a newer release ships a newer format version. The copy in a partition travels with the data it describes.++## Contents of the store++The store contains records in plain text JSON. Nothing in it is encrypted. Encryption at rest is the job of the disk or the sync layer the user chooses.++## Layout++```+<store>/+ FORMAT.md this document+ shared/ partition, synced to every working machine+ FORMAT.md+ store.json store identity+ 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+ digests/<device>/<YYYY-MM>.jsonl state digests+ blobs/<sha256[0:2]>/<sha256> large bodies, immutable+ private/ same shape, for private-visibility records+```++### Partitions++A partition is a top-level folder that holds records of one sensitivity. There are two:++- `shared`: records every working machine may hold.+- `private`: records of private visibility, for example personal-scope topics.++Each partition is synced as its own folder, so a user can keep `private` off a given machine (for example a server). The store root itself is never a sync folder, and records never move between partitions. A machine that does not hold a partition works on the partitions it has; a write to a partition the machine does not hold is refused.++### Store identity++Every partition holds `store.json`:++```+{ "store_id": "<ulid>", "format": 1 }+```++The store id is the same in every partition of one store. It keys the device-local state directory on each machine. The file is created once, with an exclusive create, and never rewritten.++A store is created only by an explicit command (`o2b store init`), on one machine; writers never create one. Every other machine receives the partitions, identity files included, through sync. Creation writes the identity file of every partition it was asked for (both by default, or `shared` alone for a machine that must not hold private records) before it reports success. When some of the requested partitions already carry an identity file, creation adds the missing ones with that store id and never mints a second one; the file's content depends only on the store id, so a copy created locally and one delivered by sync are identical. Creation refuses when every requested partition is already held, when the partitions name different store ids, and when a partition folder holds store files without `store.json` (the identity has not arrived yet, or was lost). A writer that finds no store skips its write rather than creating one.++### Streams++A stream is a family of shards inside a partition:++- `events`: signals, evidence, notes and feedback.+- `log`: the operational log, lifecycle and continuity records.+- `ledgers`: named append-only ledgers, one directory per ledger name (`ledgers/<name>/...`). A ledger name is 1 to 64 lowercase letters, digits and hyphens, starting with a letter or digit.+- `topics`: topic events.+- `settings`: settings every machine must agree on.+- `digests`: state digests that let machines compare their folded state.++### Shards++A shard is one file of one stream, written by one device, for one month:++```+<partition>/<stream>/<device>/<YYYY-MM>.jsonl+<partition>/ledgers/<name>/<device>/<YYYY-MM>.jsonl+```++- `<device>` is the writing device's id: lowercase letters, digits and hyphens, at most 32 characters, never starting with `sync-conflict`.+- Every machine accepts the same device ids in records and shard paths, whatever its platform, so folds and digests agree across platforms. Only a machine's choice of its own id depends on the platform: a new id is never a name Windows reserves for a device (`con`, `prn`, `aux`, `nul`, `com1` to `com9`, `lpt1` to `lpt9`), and an existing id that is one of them is refused only on Windows. Such a directory cannot exist on NTFS, so on Windows a peer's device directory under a reserved name is skipped, its records are not read on that machine, and the doctor reports it.+- `<YYYY-MM>` is the UTC month of the physical part of the record's clock.+- A device writes only shards that carry its own device id. Concurrent agents on one device append to the same file. Two machines therefore never write the same file, and a file-sync tool never has to merge one.+- A compaction output may carry a suffix before the extension: `<YYYY-MM>.<suffix>.jsonl`, where the suffix is 1 to 40 lowercase letters, digits and hyphens, starts with a letter or digit, and never starts with `sync-conflict`.+- Any other file name in a stream directory (for example a sync tool's conflict copy) is not a shard and is not read as one.++Every line of a shard is one record, encoded as UTF-8 JSON and terminated by a newline (`\n`). A record is written with a single append, under a lock that is local to the writing device and never stored inside the store. A line, newline included, is at most 16384 bytes long (the line-size cap); a record whose line would be longer has its body spilled into a blob.++## Record envelope++Every record has this shape:++```+{ "v": 1, "id": "<ulid>", "hlc": "<physical_ms>.<counter>", "device": "<device id>",+ "agent": "<agent name>", "kind": "<kind>", "scope": "<scope>" | null,+ "topic": "<topic id>" | null, "sum": "<sha256>", "body": { ... } }+```++Fields:++- `v`: format version of the record, an integer. This document describes version 1.+- `id`: the record id, a ULID (26 Crockford base32 characters, uppercase). Unique across all machines without coordination.+- `hlc`: the record's hybrid logical clock stamp, `<physical_ms>.<counter>`: milliseconds since the Unix epoch, a dot, and a counter. Both parts are non-negative integers without leading zeros.+- `device`: the id of the device that wrote the record. It matches the device segment of the shard path.+- `agent`: the identity of the agent that wrote the record: a non-empty, single-line string of at most 200 characters.+- `kind`: the record kind, 1 to 64 lowercase letters, digits and hyphens, starting with a letter. The kind decides the shape of the body.+- `scope`: the soft category of the record (a non-empty, single-line string of at most 200 characters), or `null`.+- `topic`: the id (a ULID) of the topic the record belongs to, or `null`.+- `sum`: the lowercase hex sha256 of the body's canonical JSON.+- `body`: a JSON object whose shape depends on `kind`.++### Canonical JSON and the checksum++The canonical JSON of a value is its JSON text with object keys sorted by code unit order at every level, array order kept, no whitespace, and object entries whose value is undefined omitted. `sum` is the sha256 of the canonical JSON of `body`, encoded as UTF-8, written as 64 lowercase hex characters. A reader recomputes it from the parsed body, so a body serialised with a different key order still verifies. A body nests objects and arrays at most 64 levels deep, the body object itself counting as one level: a writer never writes a deeper body, and a reader reports a record whose body (inline or in its blob) is deeper as a corrupt line and skips it.++### Blob references++When a line would exceed the line-size cap, the writer stores the body as a blob and writes a blob reference as the line's body:++```+{ "$blob": "<sha256>", "bytes": <length of the blob in bytes> }+```++The key `$blob` is reserved: no record body may use it. The reference's hash equals the record's `sum`, and `bytes` is a non-negative integer.++## Blobs++A blob is an immutable file at `<partition>/blobs/<sha256[0:2]>/<sha256>`. Its content is the canonical JSON of a record body, encoded as UTF-8, and its name is the sha256 of that content, so the name of a blob that holds a record's body is the record's `sum`.++- A blob is written once, with an exclusive create, and never rewritten or appended to. A writer prepares the content in a temp file and links it to the final name; where the filesystem has no hard links (FAT, exFAT) it creates the final name directly, so a reader may briefly see a partly written blob, which it treats as pending.+- A temp file never takes a blob name. A writer keeps it outside the store when it can; otherwise it sits in the blob's folder under a name that starts with `.tmp-`. Readers ignore every name in `blobs/` that starts with a dot, and a sync setup should ignore them too (for example a Syncthing ignore pattern `.tmp-*`).+- A blob file that exists but does not hash to its name can only ever hold one content, so a writer that needs that blob may rewrite it with that content.+- A blob that is referenced but absent, or whose content does not hash to its name, or whose length is not the `bytes` of the reference, is pending: a reader shows the record with its body marked pending and fills the body in on a later read, once the sync tool has delivered the whole file. A reader sizes a blob before it reads it and does not load one larger than 64 MiB.+- A blob that hashes to its name but is not the canonical JSON of a JSON object can never change, since its name fixes its content. A reader skips the record that references it and reports it as a corrupt line.++## Clock rules++Every device keeps a hybrid logical clock and persists it in its device-local state, so it survives restarts.++- Send rule: for each new record, when the wall clock is ahead of the local clock's physical part, the stamp is the wall clock with counter 0; otherwise the physical part stays and the counter increments. The result becomes the local clock. A device's stamps are therefore strictly increasing even when its wall clock steps backwards.+- Receive rule: whenever a device ingests records from other devices, it raises its local clock to at least the largest stamp it ingested. A record written in reply to a remote record therefore orders after it, even when the replying machine's wall clock is behind. A stamp whose physical part is more than one day (86400000 ms) ahead of the device's wall clock is not adopted, so one record from a broken clock cannot move every later stamp into the far future.++Stamps compare by physical part, then by counter.++## Order and folds++All machines order records by `hlc`, then `device`, then `id`, each compared as written (numbers for the clock, code unit order for the strings). The same set of records gives the same order on every machine, in any delivery order. A record that is delivered twice (for example after a file was restored) is applied once, by its `id`.++Entities that change over time (preferences, pinned context, topic fields, assignments and settings) are folds over their records:++- Precedence by authority: a human record beats an agent record, which beats a decision-model record.+- Within one authority, the record with the later clock wins.+- Removal is a tombstone record. A fold never deletes a record; the losing records stay in the history.++A record whose body is still a pending blob is not folded until its body arrives. A record of a fold kind whose body is malformed is not applied; the fold reports it. When two deliveries share an `id` but differ in content, the fold keeps the one that comes first in fold order (then by canonical JSON) and reports the conflict.++### Authority++A record of a mutable entity carries its authority in its body, in the field `authority`. It is part of the body, so the checksum covers it. It is never inferred from the `agent` name, and a mutable-entity record without a valid `authority` is not applied. The values, from the strongest to the weakest:++- `human`: the user decided, through a command, a tool call made on the user's explicit request, or an edit of the human view.+- `agent`: an agent decided on its own.+- `model`: a decision model decided.++### Preferences++A preference is identified by the string in its records' `preference` field. Each field of a preference is its own register, resolved by authority, then clock, so a human change to one field (for example `status`) is not undone by a later agent change while an agent may still change a field no human has set. Whether the preference exists is one more register: every `preference-set` proposes that it exists, a `preference-remove` proposes that it does not. Evidence records never change a field or the existence.++The counters `applied_count`, `violated_count` and `outdated_count` are derived by counting `preference-evidence` records by their `result`. They are never written back: a `preference-set` that names a counter field is ignored for that field, and a `preference-set` that names only counter fields is not applied.++### Pinned context++Pinned context is one register per partition. A `pinned-set` replaces the whole text; an append is written as a `pinned-set` of the full new text. A `pinned-clear` is the tombstone. When two machines replace it at nearly the same time, the replacement with the later clock is shown and the other stays in the history.++### Shared settings++Settings every machine must agree on are records in the `settings` stream of the `shared` partition, never device-local config. Each key is one register, resolved by authority, then clock; a `setting-unset` is the tombstone and the key falls back to its default. Keys are dot-separated lowercase words. Keys this version knows, with their values:++- `view.writer`: the device id of the one device that renders the human view. No default. Moving the role follows the view writer protocol of the release that defines it.+- `view.language`: the language tag (for example `en`, `ru` or `pt-BR`) of generated prose in the human view. No default; the renderer decides.+- `topics.new_min_records`: how many related unassigned records start a new topic, a positive integer. Default 5.+- `topics.new_min_sessions`: from how many sessions those records must come, a positive integer. Default 2.++A record that sets a known key to an invalid value is not applied. A key this version does not know is kept as the JSON value written, so an older reader keeps a newer release's setting instead of losing it.++## Reading++A reader parses each line, checks the envelope and verifies the checksum.++- An incomplete last line (no terminating newline) or a last line that fails verification is skipped and read again on a later pass. It is not treated as deleted: a sync tool may still be delivering the rest of the file.+- A line in the middle of a shard that fails verification is reported as a diagnostic and skipped.+- A record whose `v` is greater than the version a reader understands is skipped and reported, and the reader goes on with the next line.+- A run of bytes longer than the line-size cap without a newline can never be a record. It is reported as a corrupt line and skipped up to the next newline, or to the end of the shard; it is never held back as an incomplete last line. A reader reads a shard in bounded chunks, never whole.+- A record whose `device` is not the device segment of its shard's path is reported as a corrupt line and skipped.+- A record id appears in one partition only: records never move between partitions. A reader that finds an id already read from the other partition keeps the first copy and ignores the second, and a doctor reports the id.++## Trust++Records carry no signature. The checksum detects damage, not forgery: any machine that can write a partition folder, and anything the sync tool delivers into it, can write records under any device id, agent or authority. A machine that syncs a partition is therefore trusted with everything in that partition. The reader's checks (envelope, checksum, line-size cap, device segment, blob shape and size) keep one bad file from stopping the store or reaching outside it; they do not authenticate a peer. Keep `private` only on machines you trust with private records.++A writer never follows a symbolic link (or, on Windows, a junction) below a partition folder: it refuses a stream, ledger, device or blob folder that is a link, and a shard that is a link or has more than one hard link, and writes nothing. A reader opens a shard or blob only when it is a regular file: a link or a special file (a FIFO) under that name is reported and never read through or waited on. The partition folder itself may be a link. Folders the store creates are readable by their owner only (mode `0700`), and so are shards, blobs and `store.json` (mode `0600`), in both partitions; the format document stays readable by everyone.++## Compaction++Shards of closed months are never rewritten, except by compaction on their owning device. Compaction writes the same records to a new shard, then appends a record of kind `compacted` to the same stream of the same device, then removes the old shards. Its body is:++```+{ "replaces": ["<shard path>", ...], "into": ["<shard path>", ...] }+```++Shard paths in the body are relative to the partition and use `/` as the separator, for example `events/dev-a/2026-01.jsonl`. A reader treats a shard named in `replaces` as replaced: its disappearance is expected and is not reported as missing.++## State digests++Machines compare their folded state through digests, one per partition, published in the partition's `digests` stream.++A digest covers an explicit cut: one entry for every shard the publishing machine holds in the partition, excluding the `digests` stream itself, so publishing a digest never changes the cut it is compared on. Shards with no verified record yet are left out. An entry, and the cut, sorted by shard path:++```+{ "shard": "<partition-relative shard path>", "count": <verified records>,+ "last": "<id of the last verified record>", "pending": <records whose blob has not arrived> }+```++`pending` is part of the cut because a record whose blob has not arrived cannot be folded yet; two machines that differ only in a delivered blob have different cuts. The digest carries the sha256 of the canonical JSON of the cut, and for each fold (`preferences`, `pinned`, `settings`) the sha256 of the canonical JSON of the fold's resolved state computed from exactly the records in the cut.++- Comparison: only digests whose cuts are identical are compared, each device's latest digest per cut, among the digests of the last 7 days. A fold whose hash differs between two such digests is reported as divergent, with the devices, the partition and the fold.+- Roster: the devices with records in the partition during the last 30 days, minus the devices retired by a `device-retire` record with `authority` `human`. A retired device that writes a record after its retire record is on the roster again. Retire records are read from the `settings` stream of `shared` and apply to every partition.+- Silence: a roster device that has published no digest in the partition for 7 days is reported as silent, never as divergent. A device first seen less than 7 days ago is not reported yet.++An offline device, an idle device or a machine without a partition therefore never stalls the comparison and never raises a false alarm.++## Record kinds++Record kinds are defined by the stream and the feature that writes them. Kinds this version of the format defines at the store level:++- `compacted`: a compaction replaced the shards in `replaces` with the shards in `into`.++Kinds of the mutable-entity folds, with their bodies (fields marked optional may be absent):++- `preference-set`: `{ "authority", "preference": "<id>", "fields": { "<name>": <json>, ... } }`, written to `events`. Proposes a value for each named field (lowercase words joined by underscores) and that the preference exists.+- `preference-remove`: `{ "authority", "preference": "<id>" }`, written to `events`. The tombstone of a preference.+- `preference-evidence`: `{ "preference": "<id>", "result": "applied" | "violated" | "outdated", "artifact": "<reference>" (optional) }`, written to `events`. One application of a preference; it carries no authority.+- `pinned-set`: `{ "authority", "content": "<text>" }`, written to `events`. Replaces the pinned context.+- `pinned-clear`: `{ "authority" }`, written to `events`. The tombstone of the pinned context.+- `setting-set`: `{ "authority", "key": "<key>", "value": <json, not null> }`, written to `settings` in `shared`.+- `setting-unset`: `{ "authority", "key": "<key>" }`, written to `settings` in `shared`. The tombstone of a setting.++Kinds of the state digests:++- `device-retire`: `{ "authority": "human", "device": "<device id>", "reason": "<text>" (optional) }`, written to `settings` in `shared`. Takes a device off the digest roster.+- `state-digest`: `{ "partition": "shared" | "private", "cut": [<entry>, ...], "cut_hash": "<sha256>", "folds": { "preferences": "<sha256>", "pinned": "<sha256>", "settings": "<sha256>" } }`, written to `digests` in its partition.++Kinds written by the dual writes of format version 1 (a trial: while the dual-write setting is on, the release's existing writers also append these records beside their legacy files). Mutable entities reuse the fold kinds above: preference writes and retires are `preference-set` records of the `pref-<slug>` id (a retire sets `status` to `retired`), apply-evidence is `preference-evidence`, and pinned context is `pinned-set` or `pinned-clear`. Pinned context goes to `private` when the writing machine holds that partition and to `shared` when it does not; a text that carries a `<private>` region (or the placeholder a stripped one leaves) or links a private page goes to `private` only. A `pinned-clear` is judged by the text it clears, so it lands where that text's `pinned-set` did. The two partition registers are not merged: a machine that holds `private` writes its sets and clears there, a machine that does not writes them to `shared`, and each partition's register (and its digest) reflects only the records in that partition.++All records one write produces land in one partition. The write is judged once: it is private when the page it writes or is about is private (or cannot be read), or when any of its content fields (a signal's principle, sources and raw text, a preference's principle, evidence and relationship fields, an event's text or artifact) carries a `<private>` region, links a private page, or names a preference whose page is not on disk; its own id, generated paths, hashes, timestamps, keys and agent names are not judged as links. That one verdict places every record of the write: a signal and its `idempotency` receipt, the records of a preference write, an apply-evidence event with its `preference-evidence` record and receipt, a pin's `preference-set` and its event, and every event and receipt of a write batch.++Every dual-written body also carries `"vault_id": "<id>" | null`: the id in the `Brain/vault-id.json` marker of the vault the legacy write went to, or `null` when that vault has no marker. One store serves every vault on a machine. In format version 1 the field only records where a record came from: the search index of each vault reads every record of the store, and nothing filters by it yet. A later version decides whether a vault reads only its own records.++The other kinds:++- `signal`: `{ "id": "<signal id>", "path": "<vault-relative path of the signal file>", "staged": <bool>, "frontmatter": { ... }, "raw": "<text>" | null }`, written to `events`. One captured taste signal, with the frontmatter its file carries and its raw text.+- `log-event`: `{ "timestamp": "<ISO-8601>", "event_type": "<kind>", "body": { ... } }`, written to `log`. One operational log event, including notes and apply-evidence. An event goes to `shared`, except one that names a private page (a preference, or any page it links, in any field or inside its text), carries a `<private>` region, or belongs to a private write, which goes to `private` only; a preference id whose page is not on disk counts as private.+- `ledger-row`: `{ "row": <json> }`, written to `ledgers/<name>`. One row of an append-only ledger, as the ledger wrote it. Rows go to `shared`, with these exceptions. A row that names a private page goes to `private` only: every string the row carries is judged, at any depth, so a `<private>` region, a link or path to a private page, a preference id whose page is private or not on the writing machine (it cannot be judged), or a path outside the vault sends the row to `private` only. This covers `idempotency` receipts (a receipt for a write about a private preference too), `recurrence` events (a source that is a private page, or a link or `.md` path that names no page, as for a truth claim), `continuity`, `metrics`, `maintenance-journal`, `verifier-rejections` (also when a session turn the rejected proposal was drawn from is flagged `private`), `edit-history` and `decision-receipts` rows. A `continuity` row flagged `private` (a `<private>` region was stripped from it, or its writer said so) goes to `private` only. `lineage` rows (which sessions ran in which working directory, repository and branch), `query-demand` rows (what the user searched for), `permissions` rows (which writes were allowed or refused, and on what) and `git-commits` rows (commit messages and paths) go to `private` when the writing machine holds that partition and to `shared` when it does not. `truth-claims` rows go to `private` when the writing machine holds that partition and to `shared` when it does not; a claim whose source is a private page, or a link or `.md` path that names no page on the writing machine, goes to `private` only. Audit rows, `preference-audit` and `reliability-audit` (which every audit trail shares, secret custody included, named by the row's `audit_dir`), follow the same rule: `private` when the writing machine holds it, else `shared`; an audit row about a private preference still goes to `private` only. Ledger names: `idempotency`, `continuity`, `metrics`, `lineage`, `permissions`, `git-commits`, `reliability-audit`, `maintenance-journal`, `verifier-rejections`, `preference-audit`, `edit-history`, `decision-receipts`, `truth-claims`, `query-demand` and `recurrence`.++Every other kind is defined by the feature that writes it, and a reader that does not know a kind keeps the record and leaves its body alone.++## Device-local state++Each machine keeps a device-local directory outside the store, keyed by the store id: append locks, the persisted clock, blob temp files, the search index, caches, hook state and snapshots. It is never synced. Sync only the partition folders, each as its own sync folder; never sync the store root or the device-local directory as a whole.++## Versioning++The format version is the integer `v` in every record and the `format` field of `store.json`.++- A change that every reader of the current version can still read keeps the version.+- A change that an older reader would misread raises the version. An older reader then skips the newer records and reports them, and never rewrites them.+- A release may refresh `FORMAT.md` in a partition only with a document of the same or a newer format version; an older release never replaces a newer document.diff --git a/src/core/store/appender.ts b/src/core/store/appender.tsnew file mode 100644index 00000000..1cd266b1--- /dev/null+++ b/src/core/store/appender.ts@@ -0,0 +1,204 @@+/**+ * The shard appender of the brain store (design D2, task 1.4).+ *+ * One record is one JSON line, written to+ * `<partition>/<stream>[/<ledger>]/<device>/<YYYY-MM>.jsonl` with a single+ * append call, under a device-local advisory lock on that shard. The lock+ * lives in the device-local state directory, never in the synced store,+ * and is held only for the write. Only this device ever writes a shard+ * named with its device id, so the lock orders concurrent processes on one+ * machine and nothing else.+ *+ * Steps for one record:+ * 1. Refuse a partition this machine does not hold.+ * 2. Take the next clock stamp (send rule, persisted per device).+ * 3. Build the envelope. When the line would exceed the line-size cap,+ * write the body as a blob first and put a blob reference on the line;+ * the blob is complete before any line names it. Its temp file goes to+ * the device-local state directory when that is on the store's+ * filesystem (see `blobs.ts`).+ * 4. Under the shard lock, append the line and fsync it. When the shard+ * does not end in a newline (a write torn by a crash), a newline goes+ * first, so the torn fragment stays one bad line that readers report+ * and the new record stays whole.+ *+ * On Windows `O_APPEND` opens the file with `FILE_APPEND_DATA`, so every+ * write lands at the end; the local lock makes that hold for any line size.+ * Directories are created `0700` and shards `0600`, in both partitions.+ */++import { closeSync, fstatSync, fsyncSync, openSync, readSync, writeSync } from "node:fs";+import { dirname, join } from "node:path";++import { tickClock, type WallClock } from "./clock-store.ts";+import {+ BLOB_REF_BYTES_KEY,+ BLOB_REF_KEY,+ STORE_LINE_CAP_BYTES,+ STORE_TMP_DIR,+ type StorePartition,+} from "./constants.ts";+import { buildRecord, canonicalBodyText, type RecordBody, type StoreRecord } from "./envelope.ts";+import { writeBlob } from "./blobs.ts";+import { withLocalLock } from "./local-lock.ts";+import { ensureStoreDir, openShardForAppend } from "./safe-fs.ts";+import type { StoreHandle } from "./store-open.ts";+import {+ partitionDir,+ shardLockTarget,+ shardMonth,+ shardPath,+ shardRelPath,+ type StreamRef,+} from "./store-paths.ts";++/** What a writer appends. */+export interface AppendInput extends StreamRef {+ readonly partition: StorePartition;+ readonly kind: string;+ readonly agent: string;+ readonly scope?: string | null;+ readonly topic?: string | null;+ readonly body: RecordBody;+}++export interface AppendOptions {+ /** Wall clock for the send rule (default: `Date.now`). */+ readonly now?: WallClock;+}++export interface AppendResult {+ /** The record with its full body. */+ readonly record: StoreRecord;+ /** The shard the line went to. */+ readonly path: string;+ /** The shard path relative to its partition, with `/` separators. */+ readonly rel: string;+ /** Whether the body was spilled into a blob. */+ readonly spilled: boolean;+}++/** A write to a partition this machine does not hold. */+export class PartitionUnavailableError extends Error {+ readonly partition: StorePartition;++ constructor(partition: StorePartition, root: string) {+ super(+ `this machine does not hold the ${partition} partition of the brain store at ${root}; ` ++ `the record was not written. Sync the ${partition} folder to this machine to write ${partition} records here.`,+ );+ this.name = "PartitionUnavailableError";+ this.partition = partition;+ }+}++/** A record that does not fit a line even with its body spilled. */+export class RecordTooLargeError extends Error {+ constructor(bytes: number) {+ super(+ `a store record line is ${bytes} bytes even with its body in a blob, above the ${STORE_LINE_CAP_BYTES}-byte cap; shorten its agent, scope or kind`,+ );+ this.name = "RecordTooLargeError";+ }+}++const NEWLINE = 0x0a;++function lineBytes(record: StoreRecord): Buffer {+ return Buffer.from(`${JSON.stringify(record)}\n`, "utf8");+}++function fsyncDirBestEffort(dir: string): void {+ try {+ const fd = openSync(dir, "r");+ try {+ fsyncSync(fd);+ } finally {+ closeSync(fd);+ }+ } catch {+ // Directory fsync is a best-effort durability step; some platforms refuse it.+ }+}++/**+ * Append `bytes` to `path`, first closing a torn last line with a newline.+ * The line is fsynced before this returns (and a new shard's directory+ * entry too, best-effort), so a reported append survives a power loss.+ * No symlink under the partition folder is followed (`safe-fs.ts`).+ */+function appendLine(partitionRoot: string, path: string, bytes: Buffer): void {+ ensureStoreDir(partitionRoot, dirname(path));+ const fd = openShardForAppend(path);+ let created = false;+ try {+ const size = fstatSync(fd).size;+ created = size === 0;+ let payload = bytes;+ if (size > 0) {+ const last = Buffer.alloc(1);+ readSync(fd, last, 0, 1, size - 1);+ if (last[0] !== NEWLINE) payload = Buffer.concat([Buffer.from([NEWLINE]), bytes]);+ }+ let written = 0;+ while (written < payload.length) {+ written += writeSync(fd, payload, written, payload.length - written);+ }+ fsyncSync(fd);+ } finally {+ closeSync(fd);+ }+ if (created) fsyncDirBestEffort(dirname(path));+}++/** Append one record to this device's shard of the given stream. */+export function appendRecord(+ store: StoreHandle,+ input: AppendInput,+ options: AppendOptions = {},+): AppendResult {+ if (!store.partitions.has(input.partition)) {+ throw new PartitionUnavailableError(input.partition, store.root);+ }+ const ref: StreamRef =+ input.ledger === undefined+ ? { stream: input.stream }+ : { stream: input.stream, ledger: input.ledger };+ const hlc = tickClock(store.deviceStateDir, store.device, options.now);+ const month = shardMonth(hlc.physical);+ // Validates the stream, ledger and device before anything is written.+ const rel = shardRelPath(ref, store.device, month);+ const record = buildRecord({+ hlc,+ device: store.device,+ agent: input.agent,+ kind: input.kind,+ scope: input.scope ?? null,+ topic: input.topic ?? null,+ body: input.body,+ });++ let bytes = lineBytes(record);+ let spilled = false;+ if (bytes.length > STORE_LINE_CAP_BYTES) {+ const text = canonicalBodyText(record.body);+ const reference = {+ [BLOB_REF_KEY]: record.sum,+ [BLOB_REF_BYTES_KEY]: Buffer.byteLength(text, "utf8"),+ };+ bytes = lineBytes({ ...record, body: reference });+ // Checked before the blob is written, so a refused record leaves no+ // orphan blob in the synced partition.+ if (bytes.length > STORE_LINE_CAP_BYTES) throw new RecordTooLargeError(bytes.length);+ writeBlob(partitionDir(store.root, input.partition), text, {+ tempDir: join(store.deviceStateDir, STORE_TMP_DIR),+ });+ spilled = true;+ }++ const path = shardPath(store.root, input.partition, ref, store.device, month);+ withLocalLock(shardLockTarget(store.deviceStateDir, input.partition, rel), () =>+ appendLine(partitionDir(store.root, input.partition), path, bytes),+ );+ return { record, path, rel, spilled };+}diff --git a/src/core/store/blobs.ts b/src/core/store/blobs.tsnew file mode 100644index 00000000..8426de02--- /dev/null+++ b/src/core/store/blobs.ts@@ -0,0 +1,323 @@+/**+ * Content-addressed blobs of the brain store (design D1, D2).+ *+ * A blob is the canonical JSON of a record body that was too large for a+ * shard line, stored at `<partition>/blobs/<sha[0:2]>/<sha>`, where the+ * name is the sha256 of the content. Blobs are immutable: a blob is+ * created once and never changed. Two processes spilling the same body+ * race for one name, and the loser simply finds the blob already there.+ *+ * How a blob is created, so that no reader on this machine sees a+ * half-written one and nothing temporary lands where a sync tool picks it+ * up as data:+ *+ * 1. The content goes to a temp file first. The temp file lives in the+ * device-local state directory when that directory is on the same+ * filesystem as the store (it is never synced). Otherwise it lives in+ * the blob's own directory under a dot-prefixed name, which FORMAT.md+ * tells readers and sync setups to ignore.+ * 2. The temp file is hard-linked to the final name, which fails when the+ * name is taken, so the create is exclusive.+ * 3. Some filesystems (FAT, exFAT) have no hard links. There the final+ * name is created directly with an exclusive create (`wx`). A reader+ * may then briefly see a partly written blob; it reads it as pending,+ * exactly like a blob a sync tool is still delivering.+ *+ * When the final name is already taken, the existing file is verified.+ * Its content is fixed by its name, so a file that does not hash to its+ * name (a crash during a direct create, or a sync tool still writing) is+ * given a short grace and then replaced with the one content it can ever+ * have: written to a temp file beside it and renamed over it, so a reader+ * never sees the repair half done.+ *+ * A blob that a record references but that is absent, or whose bytes do+ * not hash to its name, is pending: the reader marks the record's body+ * pending and tries again later.+ */++import {+ closeSync,+ fstatSync,+ fsyncSync,+ linkSync,+ mkdirSync,+ openSync,+ readFileSync,+ readSync,+ statSync,+ unlinkSync,+ writeSync,+} from "node:fs";+import { basename, dirname, join } from "node:path";++import { renameWithRetry, sleepSync } from "../fs-atomic.ts";+import { sha256Hex } from "../integrity/digest.ts";+import { BLOB_TEMP_PREFIX, STORE_BLOB_MAX_BYTES } from "./constants.ts";+import {+ ensureStoreDir,+ openRegularFileForRead,+ STORE_DIR_MODE,+ STORE_FILE_MODE,+} from "./safe-fs.ts";+import { blobPath } from "./store-paths.ts";++/** Errors of `link(2)` that mean the filesystem cannot hard-link here. */+export const NO_LINK_CODES = new Set([+ "EPERM",+ "ENOTSUP",+ "EOPNOTSUPP",+ "ENOSYS",+ "EXDEV",+ "EMLINK",+]);++/** How long a taken name that does not verify may still be in the middle of a write. */+const VERIFY_ATTEMPTS = 5;+const VERIFY_SLEEP_MS = 20;++export interface WrittenBlob {+ readonly sha: string;+ readonly path: string;+ /** False when the blob was already present (written earlier, or by another process). */+ readonly created: boolean;+}++export interface WriteBlobOptions {+ /**+ * Device-local directory for the temp file. Used when it is on the same+ * filesystem as the store; otherwise the temp file is a dot-prefixed+ * file beside the blob.+ */+ readonly tempDir?: string;+ /**+ * The hard-link call. A seam only so tests can reproduce a filesystem+ * without hard links (FAT, exFAT), which no test host can mount+ * unprivileged; production always uses `fs.linkSync`.+ */+ readonly link?: (existingPath: string, newPath: string) => void;+ /**+ * The rename a repair uses. A seam only so tests can reproduce a Windows+ * sharing violation (a rename over a file another process still holds+ * open), which no POSIX test host can produce; production always uses+ * `renameWithRetry`.+ */+ readonly rename?: (from: string, to: string) => void;+}++/** Errors of a rename over a file that another process still holds open (Windows). */+const STILL_OPEN_CODES = new Set(["EPERM", "EBUSY"]);++function errnoCode(err: unknown): string | undefined {+ return (err as NodeJS.ErrnoException | null)?.code;+}++function sameFilesystem(a: string, b: string): boolean {+ try {+ return statSync(a).dev === statSync(b).dev;+ } catch {+ return false;+ }+}++function writeAll(fd: number, bytes: Buffer): void {+ let written = 0;+ while (written < bytes.length) written += writeSync(fd, bytes, written, bytes.length - written);+ fsyncSync(fd);+}++/** Create `path` with `bytes`, failing with EEXIST when the name is taken. */+function createExclusive(path: string, bytes: Buffer): void {+ const fd = openSync(path, "wx", STORE_FILE_MODE);+ try {+ writeAll(fd, bytes);+ } finally {+ closeSync(fd);+ }+}++function tempPathFor(target: string, tempDir: string | undefined): string {+ const unique = `${process.pid}.${Date.now()}.${Math.random().toString(16).slice(2)}`;+ const blobDir = dirname(target);+ if (tempDir !== undefined) {+ try {+ mkdirSync(tempDir, { recursive: true });+ if (sameFilesystem(tempDir, blobDir)) return join(tempDir, `${basename(target)}.${unique}`);+ } catch {+ // An unusable device-local directory falls back to the blob directory.+ }+ }+ return join(blobDir, `${BLOB_TEMP_PREFIX}${basename(target)}.${unique}`);+}++/**+ * Whether `path` hashes to `sha` within `attempts` reads, sleeping+ * `sleepMs` between them; a missing file counts as not yet written.+ */+function verifies(+ path: string,+ sha: string,+ size: number,+ attempts: number,+ sleepMs: number,+): boolean {+ for (let attempt = 0; attempt < attempts; attempt += 1) {+ try {+ // A symlink or anything but a file of the right size is never read:+ // the repair renames over the name itself, never through it.+ const fd = openRegularFileForRead(path);+ if (fd !== null) {+ try {+ if (fstatSync(fd).size === size && sha256Hex(readFileSync(fd)) === sha) return true;+ } finally {+ closeSync(fd);+ }+ }+ } catch (err) {+ if (errnoCode(err) !== "ENOENT") throw err;+ }+ if (attempt < attempts - 1) sleepSync(sleepMs);+ }+ return false;+}++/**+ * The blob at `path` already exists: make sure it holds `bytes`. A file+ * that does not verify gets a short grace (another process may be in the+ * middle of a direct create) and is then atomically replaced with its one+ * content.+ */+function settleExisting(path: string, sha: string, bytes: Buffer, options: WriteBlobOptions): void {+ if (verifies(path, sha, bytes.length, VERIFY_ATTEMPTS, VERIFY_SLEEP_MS)) return;+ // The repair temp goes where the first write's temp went: the+ // device-local directory when it can, so a crash before the rename+ // leaves nothing in the synced partition.+ const repair = tempPathFor(path, options.tempDir);+ try {+ createExclusive(repair, bytes);+ try {+ (options.rename ?? renameWithRetry)(repair, path);+ } catch (err) {+ // A writer still holding the name open (Windows, a slow direct+ // create on a filesystem without hard links) refuses the rename.+ // That writer is writing the one content the name can have, so it+ // is given a longer grace before the refusal counts.+ const code = errnoCode(err);+ if (code === undefined || !STILL_OPEN_CODES.has(code)) throw err;+ if (!verifies(path, sha, bytes.length, VERIFY_ATTEMPTS, VERIFY_SLEEP_MS * 10)) throw err;+ }+ } finally {+ try {+ unlinkSync(repair);+ } catch {+ // renamed into place, or never created+ }+ }+ if (!verifies(path, sha, bytes.length, 1, 0)) {+ throw new Error(+ `blob ${path} does not hold the content its name promises, even after a rewrite`,+ );+ }+}++/**+ * Create `path` with `bytes` exactly once: a complete temp file hard-linked+ * to the name, or, where the filesystem has no hard links, an exclusive+ * create of the name itself. Returns `false` when the name is already+ * taken; every other error propagates. Shared with the store identity+ * file, which needs the same exclusive create on the same filesystems.+ */+export function createFileOnce(+ path: string,+ bytes: Buffer,+ options: WriteBlobOptions = {},+): boolean {+ const link = options.link ?? linkSync;+ mkdirSync(dirname(path), { recursive: true, mode: STORE_DIR_MODE });+ const temp = tempPathFor(path, options.tempDir);+ try {+ createExclusive(temp, bytes);+ try {+ link(temp, path);+ return true;+ } catch (err) {+ const code = errnoCode(err);+ if (code === "EEXIST") return false;+ if (code === undefined || !NO_LINK_CODES.has(code)) throw err;+ }+ } finally {+ try {+ unlinkSync(temp);+ } catch {+ // never created, or already gone+ }+ }+ // No hard links on this filesystem: an exclusive create of the final name.+ try {+ createExclusive(path, bytes);+ return true;+ } catch (err) {+ if (errnoCode(err) !== "EEXIST") throw err;+ return false;+ }+}++/** Store `text` as a blob in the partition at `partitionRoot`. */+export function writeBlob(+ partitionRoot: string,+ text: string,+ options: WriteBlobOptions = {},+): WrittenBlob {+ const sha = sha256Hex(text);+ const path = blobPath(partitionRoot, sha);+ const bytes = Buffer.from(text, "utf8");+ // `blobs/<xx>/` may not be a symlink a peer planted (`safe-fs.ts`).+ ensureStoreDir(partitionRoot, dirname(path));+ if (createFileOnce(path, bytes, options)) return { sha, path, created: true };+ settleExisting(path, sha, bytes, options);+ return { sha, path, created: false };+}++/** Outcome of {@link readBlob}. */+export type BlobRead =+ | { readonly status: "ok"; readonly text: string }+ | { readonly status: "missing" }+ | { readonly status: "mismatch" };++/**+ * Read and verify blob `sha`: its bytes must hash to its name. The file is+ * sized before it is read: one that is not a regular file, is larger than+ * {@link STORE_BLOB_MAX_BYTES}, or is not the `bytes` long the reference+ * promises is a mismatch and is never read into memory.+ */+export function readBlob(partitionRoot: string, sha: string, bytes?: number): BlobRead {+ const path = blobPath(partitionRoot, sha);+ let fd: number;+ try {+ // Only a regular file is opened: a symlink or a FIFO a peer planted+ // under a blob name is never followed or blocked on.+ // A blob folder that is a link is refused too.+ const opened = openRegularFileForRead(path, partitionRoot);+ if (opened === null) return { status: "mismatch" };+ fd = opened;+ } catch (err) {+ if ((err as NodeJS.ErrnoException).code === "ENOENT") return { status: "missing" };+ throw err;+ }+ try {+ const stat = fstatSync(fd);+ if (stat.size > STORE_BLOB_MAX_BYTES) return { status: "mismatch" };+ if (bytes !== undefined && stat.size !== bytes) return { status: "mismatch" };+ const content = Buffer.alloc(stat.size);+ let read = 0;+ while (read < content.length) {+ const n = readSync(fd, content, read, content.length - read, read);+ if (n === 0) break;+ read += n;+ }+ const got = content.subarray(0, read);+ if (sha256Hex(got) !== sha) return { status: "mismatch" };+ return { status: "ok", text: got.toString("utf8") };+ } finally {+ closeSync(fd);+ }+}diff --git a/src/core/store/clock-store.ts b/src/core/store/clock-store.tsnew file mode 100644index 00000000..4d810e5d--- /dev/null+++ b/src/core/store/clock-store.ts@@ -0,0 +1,86 @@+/**+ * The local hybrid logical clock of one device, persisted in the+ * device-local state directory so it survives restarts (design D3).+ *+ * Without persistence a process that starts while the wall clock is behind+ * the last stamp it issued (a clock step, a suspended VM) would issue+ * stamps that order before its own earlier records. Every tick and every+ * observation is a read, a rule from `hlc.ts` and an atomic write, under a+ * device-local lock so concurrent processes on one device never issue the+ * same stamp.+ *+ * The file is `<device-state-dir>/clock/<device>.json`, holding+ * `{ "hlc": "<physical_ms>.<counter>" }`. A missing file, or one whose+ * content does not parse, starts from zero: the send rule still takes the+ * wall clock, so the only loss is protection against a backwards wall+ * clock across that one restart. A file that exists but cannot be read+ * right now (EBUSY, EPERM, EACCES from an antivirus or indexer handle on+ * Windows) is an error instead: the write fails rather than the saved+ * clock, and the remote stamps it absorbed, being reset.+ */++import { readFileSync } from "node:fs";+import { join } from "node:path";++import { atomicWriteText } from "../fs-atomic.ts";+import { STORE_CLOCK_DIR } from "./constants.ts";+import { formatHlc, HLC_ZERO, parseHlc, receiveHlc, sendHlc, type Hlc } from "./hlc.ts";+import { withLocalLock } from "./local-lock.ts";++/** Wall clock in milliseconds; injectable so tests can move time. */+export type WallClock = () => number;++const systemWallClock: WallClock = () => Date.now();++/** Path of the persisted clock of `device` under a device-local state directory. */+export function clockFilePath(deviceStateDir: string, device: string): string {+ return join(deviceStateDir, STORE_CLOCK_DIR, `${device}.json`);+}++/**+ * The persisted clock of `device`, or `null` when none was stored or its+ * content does not parse. Any read error but a missing file propagates.+ */+export function readClock(deviceStateDir: string, device: string): Hlc | null {+ let text: string;+ try {+ text = readFileSync(clockFilePath(deviceStateDir, device), "utf8");+ } catch (err) {+ if ((err as NodeJS.ErrnoException).code === "ENOENT") return null;+ throw err;+ }+ try {+ const parsed = JSON.parse(text) as { hlc?: unknown };+ return typeof parsed.hlc === "string" ? parseHlc(parsed.hlc) : null;+ } catch {+ return null;+ }+}++function update(deviceStateDir: string, device: string, step: (local: Hlc) => Hlc): Hlc {+ const path = clockFilePath(deviceStateDir, device);+ return withLocalLock(path, () => {+ const next = step(readClock(deviceStateDir, device) ?? HLC_ZERO);+ atomicWriteText(path, `${JSON.stringify({ hlc: formatHlc(next) })}\n`);+ return next;+ });+}++/** Send rule, persisted: the stamp for one new local record. */+export function tickClock(+ deviceStateDir: string,+ device: string,+ now: WallClock = systemWallClock,+): Hlc {+ return update(deviceStateDir, device, (local) => sendHlc(local, now()));+}++/** Receive rule, persisted: raise the local clock after ingesting `remote`. */+export function observeClock(+ deviceStateDir: string,+ device: string,+ remote: Hlc,+ now: WallClock = systemWallClock,+): Hlc {+ return update(deviceStateDir, device, (local) => receiveHlc(local, remote, now()));+}diff --git a/src/core/store/compare.ts b/src/core/store/compare.tsnew file mode 100644index 00000000..6235d43a--- /dev/null+++ b/src/core/store/compare.ts@@ -0,0 +1,11 @@+/**+ * The one string order the brain store uses wherever two machines must+ * agree on an order: code unit order, as written, with no locale. Shard+ * paths, record ids and cut entries all sort through it.+ */++/** Negative, zero or positive as `a` sorts before, with or after `b` in code unit order. */+export function compareCodeUnits(a: string, b: string): number {+ if (a === b) return 0;+ return a < b ? -1 : 1;+}diff --git a/src/core/store/constants.ts b/src/core/store/constants.tsnew file mode 100644index 00000000..f8184b66--- /dev/null+++ b/src/core/store/constants.ts@@ -0,0 +1,269 @@+/**+ * Names of the brain store: the one place that spells every directory,+ * file, stream, partition, envelope field and store-level record kind.+ *+ * The brain store (design D1) is the open, documented, append-only home of+ * every piece of Open Second Brain machine data outside the user's notes.+ * Every other store module builds its paths and validates its records+ * against the names here, and the `FORMAT.md` doc test checks that the+ * shipped format document names each of them, so the code and the public+ * format cannot drift apart silently.+ */++/** Format version written into every record envelope (`v`). */+export const STORE_FORMAT_VERSION = 1;++/** The format document shipped into the store root and every partition. */+export const STORE_FORMAT_FILE = "FORMAT.md";++/** Per-partition identity file: the store id and the format version that created it. */+export const STORE_IDENTITY_FILE = "store.json";++/** Sensitivity partitions, each a separate top-level folder synced on its own. */+export const STORE_PARTITIONS = Object.freeze(["shared", "private"] as const);+export type StorePartition = (typeof STORE_PARTITIONS)[number];++/**+ * Streams inside a partition. `ledgers` carries one more path segment, the+ * ledger name (`ledgers/<name>/<device>/<YYYY-MM>.jsonl`).+ */+export const STORE_STREAMS = Object.freeze([+ "events",+ "log",+ "ledgers",+ "topics",+ "settings",+ "digests",+] as const);+export type StoreStream = (typeof STORE_STREAMS)[number];++/** The stream whose files sit one directory deeper, under a ledger name. */+export const LEDGER_STREAM: StoreStream = "ledgers";++/** Content-addressed blob directory inside a partition. */+export const STORE_BLOBS_DIR = "blobs";++/** Extension of every shard file. */+export const STORE_SHARD_EXT = "jsonl";++/**+ * Envelope fields in the order the appender writes them. `topic` and+ * `scope` may be `null`; every other field is always present.+ */+export const ENVELOPE_FIELDS = Object.freeze([+ "v",+ "id",+ "hlc",+ "device",+ "agent",+ "kind",+ "scope",+ "topic",+ "sum",+ "body",+] as const);+export type EnvelopeField = (typeof ENVELOPE_FIELDS)[number];++/**+ * Reserved key of a blob reference body: `{ "$blob": <sha256>, "bytes": <n> }`.+ * A record whose body was spilled into `blobs/` carries this body on its+ * line; the real body is the blob's content.+ */+export const BLOB_REF_KEY = "$blob";++/** The byte-count key that rides beside {@link BLOB_REF_KEY}. */+export const BLOB_REF_BYTES_KEY = "bytes";++/** Store-level record kind: a compaction replaced one set of shards with another. */+export const COMPACTED_KIND = "compacted";++/**+ * Record kinds the store layer itself defines and understands. Domain+ * kinds (signals, topics, settings) are defined by the modules that own+ * them, in later waves.+ */+export const STORE_RECORD_KINDS = Object.freeze([COMPACTED_KIND] as const);++/**+ * Line-size cap in bytes, newline included. A record whose line would be+ * longer is written with its body spilled into a blob.+ */+export const STORE_LINE_CAP_BYTES = 16 * 1024;++/**+ * Deepest nesting of objects and arrays a record body may have, the body+ * object itself counting as one level. A deeper body is never written and+ * is read as a corrupt record, so checksumming a body peer-planted in a+ * blob can never exhaust the stack.+ */+export const STORE_BODY_MAX_DEPTH = 64;++/**+ * Largest blob a reader loads. A spilled body is a record body (a pinned+ * text, a signal, a ledger row), far below this; a larger file in a+ * synced `blobs/` folder is refused unread rather than allocated.+ */+export const STORE_BLOB_MAX_BYTES = 64 * 1024 * 1024;++/** Machine-config key that sets the store root. */+export const STORE_ROOT_CONFIG_KEY = "store_root";++/** Environment variable that sets the store root, ahead of the config key. */+export const STORE_ROOT_ENV = "OPEN_SECOND_BRAIN_STORE_ROOT";++/** Directory name of the default store root under the per-user data directory. */+export const STORE_DEFAULT_DIR = "store";++/** Directory under the tool's state root that holds one device-local directory per store id. */+export const STORE_STATE_DIR = "stores";++/** Device-local subdirectory of shard append locks (never inside the synced store). */+export const STORE_LOCKS_DIR = "locks";++/** Device-local subdirectory of the persisted hybrid logical clock. */+export const STORE_CLOCK_DIR = "clock";++// ---------------------------------------------------------------------------+// Folds of mutable entities and state digests (tasks 1.6 and 1.7, design D4+// and D6). One block, so it merges cleanly beside other additions.+// ---------------------------------------------------------------------------++/** Body field that carries the authority of a mutable-entity record. */+export const AUTHORITY_FIELD = "authority";++/**+ * Body field every dual-written record carries: the id of the vault the+ * legacy write went to (`Brain/vault-id.json`), or `null` when that vault+ * has no identity marker or the caller named no vault.+ */+export const VAULT_ID_FIELD = "vault_id";++/**+ * Who decided a mutable-entity record, from the strongest to the weakest:+ * the user, an agent, a decision model. A stronger authority always beats+ * a weaker one; within one authority the later clock wins.+ */+export const AUTHORITIES = Object.freeze(["human", "agent", "model"] as const);+export type Authority = (typeof AUTHORITIES)[number];++/** Preference records (`events` stream): a field update, a removal, evidence. */+export const PREFERENCE_SET_KIND = "preference-set";+export const PREFERENCE_REMOVE_KIND = "preference-remove";+export const PREFERENCE_EVIDENCE_KIND = "preference-evidence";++/** Pinned context records (`events` stream): a replacement and a clear. */+export const PINNED_SET_KIND = "pinned-set";+export const PINNED_CLEAR_KIND = "pinned-clear";++/** Shared setting records (`settings` stream): a value and its removal. */+export const SETTING_SET_KIND = "setting-set";+export const SETTING_UNSET_KIND = "setting-unset";++/** A human record that takes a device off the digest roster (`settings` stream). */+export const DEVICE_RETIRE_KIND = "device-retire";++/** A published state digest (`digests` stream). */+export const STATE_DIGEST_KIND = "state-digest";++/** Every record kind the folds and digests define; FORMAT.md documents each. */+export const FOLD_RECORD_KINDS = Object.freeze([+ PREFERENCE_SET_KIND,+ PREFERENCE_REMOVE_KIND,+ PREFERENCE_EVIDENCE_KIND,+ PINNED_SET_KIND,+ PINNED_CLEAR_KIND,+ SETTING_SET_KIND,+ SETTING_UNSET_KIND,+ DEVICE_RETIRE_KIND,+ STATE_DIGEST_KIND,+] as const);++/** Results an evidence record may carry. */+export const EVIDENCE_RESULTS = Object.freeze(["applied", "violated", "outdated"] as const);+export type EvidenceResult = (typeof EVIDENCE_RESULTS)[number];++/**+ * Preference counters derived in the fold from evidence records. They are+ * never written back: a `preference-set` that names one is ignored for it.+ */+export const PREFERENCE_COUNTER_FIELDS = Object.freeze([+ "applied_count",+ "violated_count",+ "outdated_count",+] as const);++/** Setting keys this version knows and validates. Other keys fold as plain JSON values. */+export const SETTING_VIEW_WRITER = "view.writer";+export const SETTING_VIEW_LANGUAGE = "view.language";+export const SETTING_TOPIC_MIN_RECORDS = "topics.new_min_records";+export const SETTING_TOPIC_MIN_SESSIONS = "topics.new_min_sessions";+export const SETTING_KEYS = Object.freeze([+ SETTING_VIEW_WRITER,+ SETTING_VIEW_LANGUAGE,+ SETTING_TOPIC_MIN_RECORDS,+ SETTING_TOPIC_MIN_SESSIONS,+] as const);+export type SettingKey = (typeof SETTING_KEYS)[number];++/** The folds a state digest hashes, in the order the digest body lists them. */+export const STATE_DIGEST_FOLDS = Object.freeze(["preferences", "pinned", "settings"] as const);+export type StateDigestFold = (typeof STATE_DIGEST_FOLDS)[number];++/** One day in milliseconds, for the day-based windows below. */+export const DAY_MS = 24 * 60 * 60 * 1000;++/** Roster window: devices with records in the partition during the last N days. */+export const DIGEST_ROSTER_WINDOW_DAYS = 30;++/** A roster device that has published no digest for N days is reported as silent. */+export const DIGEST_SILENCE_DAYS = 7;++/** Doctor compares the digests published during the last N days. */+export const DIGEST_COMPARE_WINDOW_DAYS = 7;++// ---------------------------------------------------------------------------+// Dual writes (task 1.11, design D13 phase 1): the legacy writers also append+// the equivalent store record while the flag is on.+// ---------------------------------------------------------------------------++/** Machine-config key of the dual-write flag (default off). */+export const STORE_DUAL_WRITE_CONFIG_KEY = "store_dual_write";++/** Environment variable that sets the dual-write flag, ahead of the config key. */+export const STORE_DUAL_WRITE_ENV = "OPEN_SECOND_BRAIN_STORE_DUAL_WRITE";++/** A signal written by a legacy signal writer (`events` stream). */+export const SIGNAL_KIND = "signal";++/** One event of the legacy Brain log (`log` stream). */+export const LOG_EVENT_KIND = "log-event";++/** One row of a legacy append-only ledger (`ledgers/<name>` stream). */+export const LEDGER_ROW_KIND = "ledger-row";++/** Record kinds the dual writes define, beside the fold kinds they reuse. */+export const DUAL_WRITE_RECORD_KINDS = Object.freeze([+ SIGNAL_KIND,+ LOG_EVENT_KIND,+ LEDGER_ROW_KIND,+] as const);++/**+ * Device-local file (under the tool's state root, beside the per-store+ * directories) that counts dual writes that failed or were skipped, so+ * doctor can report them.+ */+export const DUAL_WRITE_STATUS_FILE = "dual-write.json";++/**+ * Device-local subdirectory where blob temp files are written before they+ * are linked into the store, when it is on the store's filesystem.+ */+export const STORE_TMP_DIR = "tmp";++/**+ * Prefix of a blob temp file written inside `blobs/` (when the device-local+ * directory is on another filesystem). Readers and sync setups ignore+ * names that start with a dot.+ */+export const BLOB_TEMP_PREFIX = ".tmp-";diff --git a/src/core/store/dual-write-records.ts b/src/core/store/dual-write-records.tsnew file mode 100644index 00000000..b641eaa1--- /dev/null+++ b/src/core/store/dual-write-records.ts@@ -0,0 +1,322 @@+/**+ * The store records each legacy writer produces under dual writes (task+ * 1.11). One builder per legacy surface, so the mapping from the legacy+ * tree to the store is written down in one place:+ *+ * - a signal file -> `signal` in `events`+ * - a Brain log event -> `log-event` in `log`+ * - a preference write/retire -> `preference-set` in `events`+ * - apply-evidence -> `preference-evidence` in `events`+ * - pinned context -> `pinned-set` / `pinned-clear` in `events`+ * - a per-device ledger row -> `ledger-row` in `ledgers/<name>`+ *+ * Authority (FORMAT.md, "Authority") is never inferred here: the legacy+ * caller passes it, usually from `authorityFromOrigin()`.+ *+ * Bodies are plain JSON: values are passed through a JSON round trip so a+ * `Date` or an `undefined` in a legacy structure cannot make the checksum+ * depend on how a value happens to serialise.+ */++import { existsSync } from "node:fs";+import { relative, sep } from "node:path";++import { preferencePath, retiredPath } from "../brain/paths.ts";+import { remoteDenyVisibilityTokens } from "../graph/privacy-markers.ts";+import { REMOTE_DENY_VISIBILITY_TOKEN } from "../graph/visibility.ts";+import type { FrontmatterMap } from "../types.ts";+import { DEGRADATION_CODE } from "../integrity/degradation.ts";+import { parseFrontmatterWithNotices } from "../vault.ts";+import {+ AUTHORITY_FIELD,+ LEDGER_ROW_KIND,+ LOG_EVENT_KIND,+ PINNED_CLEAR_KIND,+ PINNED_SET_KIND,+ PREFERENCE_COUNTER_FIELDS,+ PREFERENCE_EVIDENCE_KIND,+ PREFERENCE_SET_KIND,+ SIGNAL_KIND,+ type Authority,+ type EvidenceResult,+} from "./constants.ts";+import type { DualWriteRecord } from "./dual-write.ts";+import type { RecordBody } from "./envelope.ts";+import { PREFERENCE_FIELD_RE } from "./fold-preferences.ts";++const COUNTERS = new Set<string>(PREFERENCE_COUNTER_FIELDS);++function plain<T>(value: T): T {+ return JSON.parse(JSON.stringify(value ?? null)) as T;+}++function vaultRel(vault: string, path: string): string {+ return relative(vault, path).split(sep).join("/");+}++function textOf(value: unknown): string | null {+ return typeof value === "string" && value.trim() !== "" ? value.trim() : null;+}++/**+ * Whether a page's frontmatter reserves it as private, by the same rule+ * search and remote reads use: the reserved `visibility` token, or an+ * informal marker such as `access: private` (`graph/privacy-markers.ts`).+ * Such a page's records go to the `private` partition.+ */+export function isPrivateFrontmatter(frontmatter: Readonly<Record<string, unknown>>): boolean {+ return remoteDenyVisibilityTokens(frontmatter as FrontmatterMap).includes(+ REMOTE_DENY_VISIBILITY_TOKEN,+ );+}++/**+ * {@link isPrivateFrontmatter} for a page on disk. Every brain writer that+ * decides a record's partition from a file goes through here, so one rule+ * decides privacy everywhere. A file that exists but cannot be read or+ * parsed counts as private, the partition that leaks nothing.+ */+export function isPrivatePageFile(path: string): boolean {+ // The parser reports a failed read as a notice with an empty map, which+ // would read as open, so the notice is what decides here.+ const [frontmatter, , notices] = parseFrontmatterWithNotices(path);+ if (notices.some((n) => n.code === DEGRADATION_CODE.frontmatterUnreadable)) return true;+ return isPrivateFrontmatter(frontmatter);+}++/**+ * Whether the preference `pref-<slug>` (active or retired) is private, so+ * the log events and ledger rows that name it stay out of `shared`. A+ * preference with no file reads as not private.+ */+export function isPrivatePreference(vault: string, slug: string): boolean {+ for (const path of [preferencePath(vault, slug), retiredPath(vault, slug)]) {+ if (existsSync(path) && isPrivatePageFile(path)) return true;+ }+ return false;+}++/**+ * A signal file the legacy writer created, in the partition of the write's+ * single privacy verdict (`operation-privacy.ts`).+ */+export function signalRecord(input: {+ readonly vault: string;+ readonly path: string;+ readonly id: string;+ readonly staged: boolean;+ readonly frontmatter: Readonly<Record<string, unknown>>;+ readonly raw: string | undefined;+ readonly private: boolean;+}): DualWriteRecord {+ const frontmatter = plain(input.frontmatter) as Record<string, unknown>;+ return {+ stream: "events",+ kind: SIGNAL_KIND,+ agent: textOf(frontmatter["agent"]) ?? undefined,+ scope: textOf(frontmatter["scope"]),+ private: input.private,+ body: {+ id: input.id,+ path: vaultRel(input.vault, input.path),+ staged: input.staged,+ frontmatter,+ raw: input.raw ?? null,+ },+ };+}++/** One Brain log event, as the legacy appender wrote it. */+export function logEventRecord(+ event: {+ readonly timestamp: string;+ readonly eventType: string;+ readonly agent?: string;+ readonly body: Readonly<Record<string, unknown>>;+ },+ /** `true` when the event names a private item (a private preference). */+ isPrivate = false,+): DualWriteRecord {+ const body = plain(event.body) as Record<string, unknown>;+ return {+ stream: "log",+ kind: LOG_EVENT_KIND,+ agent: textOf(body["agent"]) ?? textOf(event.agent) ?? undefined,+ private: isPrivate,+ body: { timestamp: event.timestamp, event_type: event.eventType, body },+ };+}++/**+ * The fields a preference record carries: every frontmatter key that is a+ * valid field name, minus the counters (derived from evidence in the fold,+ * never written back). A `null` value is kept: it says the field is unset.+ */+export function preferenceFields(+ frontmatter: Readonly<Record<string, unknown>>,+): Record<string, unknown> {+ const out: Record<string, unknown> = {};+ for (const [name, value] of Object.entries(plain(frontmatter) as Record<string, unknown>)) {+ if (!PREFERENCE_FIELD_RE.test(name) || COUNTERS.has(name)) continue;+ out[name] = value;+ }+ return out;+}++/**+ * A preference as the legacy writer just wrote (or retired) it, in the+ * partition of the write's single privacy verdict (`operation-privacy.ts`).+ */+export function preferenceSetRecord(input: {+ readonly id: string;+ readonly frontmatter: Readonly<Record<string, unknown>>;+ readonly authority: Authority;+ readonly agent?: string;+ readonly private: boolean;+}): DualWriteRecord | null {+ const fields = preferenceFields(input.frontmatter);+ if (Object.keys(fields).length === 0) return null;+ return {+ stream: "events",+ kind: PREFERENCE_SET_KIND,+ ...(input.agent !== undefined ? { agent: input.agent } : {}),+ scope: textOf(fields["scope"]),+ private: input.private,+ body: { [AUTHORITY_FIELD]: input.authority, preference: input.id, fields },+ };+}++/** One application of a preference (`brain_apply_evidence`). */+export function preferenceEvidenceRecord(input: {+ readonly id: string;+ readonly result: EvidenceResult;+ readonly artifact: string;+ readonly agent: string;+ readonly private: boolean;+}): DualWriteRecord {+ return {+ stream: "events",+ kind: PREFERENCE_EVIDENCE_KIND,+ agent: input.agent,+ private: input.private,+ body: { preference: input.id, result: input.result, artifact: input.artifact },+ };+}++/**+ * The pinned context after a legacy write: its full text, or `null` for a+ * clear. Pinned facts are often drawn from the notes an agent is working+ * on, so the record goes to `private` when this machine holds it and to+ * `shared` when it does not. A text that carries a `<private>` region or+ * names a private page (`namesPrivate`, `pinnedTextIsPrivate` in+ * `reference-privacy.ts`) goes to `private` only; a clear is judged by the+ * text it clears, so it lands where that text's set did.+ */+export function pinnedRecord(+ content: string | null,+ authority: Authority,+ namesPrivate: boolean,+): DualWriteRecord {+ const body: RecordBody =+ content === null ? { [AUTHORITY_FIELD]: authority } : { [AUTHORITY_FIELD]: authority, content };+ return {+ stream: "events",+ kind: content === null ? PINNED_CLEAR_KIND : PINNED_SET_KIND,+ ...partitionOf(namesPrivate ? "private" : "private-when-held"),+ body,+ };+}++/**+ * Where a ledger row goes. Every ledger site states it, so a new site+ * cannot fall into `shared` by default:+ *+ * - `private`: the row names a private item (a private preference, a+ * private page, a turn with a `<private>` region); on a machine without+ * that partition the appender refuses it and the refusal is counted;+ * - `private-when-held`: the row says what this machine or its user did+ * (audit trails, session lineage, search terms) and names no private+ * page; it goes to `private` when this machine holds it, else `shared`;+ * - `shared`: the row carries nothing about the user's private notes.+ */+export type RowPartition = "shared" | "private" | "private-when-held";++function partitionOf(+ partition: RowPartition,+): Pick<DualWriteRecord, "private" | "privateWhenHeld"> {+ return {+ private: partition === "private",+ ...(partition === "private-when-held" ? { privateWhenHeld: true } : {}),+ };+}++/** One row of a per-device legacy ledger, under `ledgers/<name>`, in the partition its caller states. */+export function ledgerRowRecord(+ ledger: string,+ row: unknown,+ partition: RowPartition,+ agent?: string,+): DualWriteRecord {+ return {+ stream: "ledgers",+ ledger,+ kind: LEDGER_ROW_KIND,+ ...(agent !== undefined ? { agent } : {}),+ ...partitionOf(partition),+ body: { row: plain(row) },+ };+}++/**+ * One `truth-claims` ledger row. A claim taken from a private page+ * (`sourceIsPrivate`, `reference-privacy.ts`) goes to `private` only; any+ * other claim goes to `private` when this machine holds it and to+ * `shared` when it does not.+ */+export function truthClaimRowRecord(row: unknown, sourceIsPrivate: boolean): DualWriteRecord {+ return ledgerRowRecord(+ DUAL_WRITE_LEDGERS.truthClaims,+ row,+ sourceIsPrivate ? "private" : "private-when-held",+ );+}++/**+ * One row of an audit trail: the `preference-audit` ledger, or the+ * `reliability-audit` ledger that every `Brain/log/<trail>/` audit shares+ * (hygiene, secret custody, hook audit, watchdog, ...). Audit rows say who+ * did what to which item, so they go to `private` when this machine holds+ * it and to `shared` when it does not. A row about a private item passes+ * `isPrivate` and goes only to `private`: on a machine without that+ * partition the appender refuses it, as for any private record.+ */+export function auditRowRecord(+ ledger: typeof DUAL_WRITE_LEDGERS.preferenceAudit | typeof DUAL_WRITE_LEDGERS.reliabilityAudit,+ row: unknown,+ agent: string | undefined,+ isPrivate: boolean,+): DualWriteRecord {+ return ledgerRowRecord(ledger, row, isPrivate ? "private" : "private-when-held", agent);+}++/**+ * Store ledger names of the per-device legacy ledgers that dual-write+ * their rows (`ledgers/<name>/<device>/<YYYY-MM>.jsonl`).+ */+export const DUAL_WRITE_LEDGERS = Object.freeze({+ idempotency: "idempotency",+ continuity: "continuity",+ metrics: "metrics",+ lineage: "lineage",+ permissions: "permissions",+ gitCommits: "git-commits",+ reliabilityAudit: "reliability-audit",+ maintenanceJournal: "maintenance-journal",+ verifierRejections: "verifier-rejections",+ preferenceAudit: "preference-audit",+ editHistory: "edit-history",+ decisionReceipts: "decision-receipts",+ truthClaims: "truth-claims",+ queryDemand: "query-demand",+ recurrence: "recurrence",+} as const);diff --git a/src/core/store/dual-write.ts b/src/core/store/dual-write.tsnew file mode 100644index 00000000..6c574515--- /dev/null+++ b/src/core/store/dual-write.ts@@ -0,0 +1,325 @@+/**+ * Dual writes (task 1.11, design D13 phase 1): while the `store_dual_write`+ * flag is on, the legacy writers also append the equivalent record to the+ * brain store, so the store can be checked against the legacy tree before+ * any reader depends on it.+ *+ * Rules every legacy writer gets from this one entry point:+ *+ * - **Off means untouched.** With the flag off, {@link dualWrite} returns+ * after reading the flag; the record builder is never called and+ * nothing is written anywhere, so legacy behaviour is byte-identical.+ * - **The legacy write always wins.** A store failure of any kind (no+ * store root, a root inside the vault, a partition this machine does not+ * hold, a full disk) is caught here. It is counted in the device-local+ * status file that doctor reads, and the first one in a process prints+ * one warning on stderr. It never reaches the legacy caller.+ * - **A real device id is required.** The store refuses the empty device+ * id that the `O2B_DEVICE_ID=""` opt-out selects. Then the dual write is+ * skipped, counted, and warned about once per process.+ * - **Dual writes never create a store.** Only `o2b store init` does. With+ * no store at the root, the dual write is skipped, counted, and warned+ * about once per process; doctor tells the user to run the init.+ * - **Vault identity.** Every record body carries the writing vault's+ * id (`vault_id`, FORMAT.md), so a later phase can tell which vault a+ * record came from. Phase 1 indexes every record of the store in every+ * vault on the machine and does not filter by it.+ * - **Partitions.** A record marked private goes to `private`; when this+ * machine does not hold it, the appender's refusal applies, which counts+ * as a failure and leaves the legacy write alone. A record marked+ * private-when-held goes to `private` when this machine holds it and to+ * `shared` otherwise. A record whose body carries a `<private>` region,+ * or the placeholder a stripped one leaves, at any depth is private+ * whatever its builder judged (`private-region.ts`). A record written+ * while a private writer operation runs is private too, whoever wrote+ * it (`operation-scope.ts`).+ *+ * Call it after the legacy write has succeeded and after any legacy lock is+ * released (the store takes its own device-local lock), passing the vault+ * written and, when the caller has one, its config path. The record kinds+ * and their bodies are built in `dual-write-records.ts`.+ */++import { readFileSync } from "node:fs";++import { atomicWriteFileSync } from "../fs-atomic.ts";+import { resolveAgentName, resolveStoreDualWrite } from "../config.ts";+import { ORIGIN_CHANNEL, resolveOriginChannel } from "../origin-channel.ts";+import { resolveAppendShardId } from "../brain/ledger-shards.ts";+import { readVaultIdentity } from "../brain/vault-identity.ts";+import { appendRecord } from "./appender.ts";+import {+ STORE_PARTITIONS,+ VAULT_ID_FIELD,+ type Authority,+ type StorePartition,+} from "./constants.ts";+import type { RecordBody } from "./envelope.ts";+import { withLocalLock } from "./local-lock.ts";+import { activeOperationPrivate } from "./operation-scope.ts";+import { valueCarriesPrivateRegion } from "./private-region.ts";+import { NoStoreError, openStore, readStoreId, type StoreHandle } from "./store-open.ts";+import {+ dualWriteStatusPath,+ isPathInsideResolved,+ partitionDir,+ resolveConfiguredStoreRoot,+ StoreRootInsideVaultError,+ type StreamRef,+} from "./store-paths.ts";++/** One store record a legacy write produces. */+export interface DualWriteRecord extends StreamRef {+ /** `true` sends the record to the `private` partition. */+ readonly private?: boolean;+ /**+ * `true` sends the record to `private` when this machine holds that+ * partition, and to `shared` when it does not: for truth claims and+ * audit rows that name no private page. Ignored when `private` is+ * `true`.+ */+ readonly privateWhenHeld?: boolean;+ readonly kind: string;+ /** The writing agent; defaults to the configured agent name. */+ readonly agent?: string;+ readonly scope?: string | null;+ readonly body: RecordBody;+}++/**+ * Where a dual write comes from: the vault the legacy write went to and the+ * machine config it was made under. Without it the flag and the store root+ * come from the default config, which is wrong for a caller working on+ * another vault or under another config.+ */+export interface DualWriteContext {+ /** The vault the legacy write went to; a store root inside it is refused. */+ readonly vault?: string;+ /** The machine config the flag and the store root are read from. */+ readonly configPath?: string;+}++/** What {@link dualWrite} builds lazily, only when the flag is on. */+export type DualWriteBuild = () => DualWriteRecord | ReadonlyArray<DualWriteRecord> | null;++/** The counters doctor reads. */+export interface DualWriteStatus {+ /** Dual writes that threw and were dropped (the legacy write was kept). */+ readonly failures: number;+ /** Dual writes skipped because this machine has no device id. */+ readonly skipped_no_device: number;+ /** Dual writes skipped because no store exists at the root yet. */+ readonly skipped_no_store: number;+ readonly last_error: string | null;+ readonly last_failure_at: string | null;+ readonly last_skip_at: string | null;+}++const EMPTY_STATUS: DualWriteStatus = Object.freeze({+ failures: 0,+ skipped_no_device: 0,+ skipped_no_store: 0,+ last_error: null,+ last_failure_at: null,+ last_skip_at: null,+});++type WarningKind = "failure" | "device" | "store";+const warned = new Set<WarningKind>();+const handles = new Map<string, StoreHandle>();++/** Whether the dual-write flag is on. An unreadable config reads as off. */+export function isDualWriteEnabled(configPath?: string): boolean {+ try {+ return resolveStoreDualWrite(configPath);+ } catch {+ return false;+ }+}++/**+ * The authority of a write whose caller named none, from the process's+ * origin channel: an operator running `o2b` decides as a human; an agent+ * calling a tool, a bulk import, or an unclaimed process decides as an+ * agent. Decision-model verdicts pass `model` explicitly.+ */+export function authorityFromOrigin(): Authority {+ // The strict read: it decides authority and stamps nothing, and an+ // unclaimed process (which throws here) decides as an agent.+ try {+ return resolveOriginChannel() === ORIGIN_CHANNEL.cli ? "human" : "agent";+ } catch {+ return "agent";+ }+}++/** Read the device-local dual-write counters. */+export function readDualWriteStatus(path: string = dualWriteStatusPath()): DualWriteStatus {+ try {+ const parsed = JSON.parse(readFileSync(path, "utf8")) as Partial<DualWriteStatus>;+ return {+ failures: typeof parsed.failures === "number" ? parsed.failures : 0,+ skipped_no_device:+ typeof parsed.skipped_no_device === "number" ? parsed.skipped_no_device : 0,+ skipped_no_store: typeof parsed.skipped_no_store === "number" ? parsed.skipped_no_store : 0,+ last_error: typeof parsed.last_error === "string" ? parsed.last_error : null,+ last_failure_at: typeof parsed.last_failure_at === "string" ? parsed.last_failure_at : null,+ last_skip_at: typeof parsed.last_skip_at === "string" ? parsed.last_skip_at : null,+ };+ } catch {+ return EMPTY_STATUS;+ }+}++function bumpStatus(update: (status: DualWriteStatus) => DualWriteStatus): void {+ try {+ const path = dualWriteStatusPath();+ withLocalLock(path, () => {+ const next = update(readDualWriteStatus(path));+ atomicWriteFileSync(path, `${JSON.stringify(next, null, 2)}\n`);+ });+ } catch {+ // The counter is diagnostics; failing to keep it must not fail anything.+ }+}++function warnOnce(kind: WarningKind, message: string): void {+ if (warned.has(kind)) return;+ warned.add(kind);+ try {+ process.stderr.write(`Open Second Brain: ${message}\n`);+ } catch {+ // stderr closed: nothing left to tell+ }+}++function recordFailure(err: unknown): void {+ const message = err instanceof Error ? err.message : String(err);+ warnOnce(+ "failure",+ `a brain store dual write failed (${message}); the legacy write is intact. ` ++ "Later failures in this process are counted, not printed; `o2b brain doctor` reports them.",+ );+ const at = new Date().toISOString();+ bumpStatus((s) => ({+ ...s,+ failures: s.failures + 1,+ last_error: message.slice(0, 500),+ last_failure_at: at,+ }));+}++function recordNoDevice(): void {+ warnOnce(+ "device",+ "brain store dual writes are on but this machine has no device id (O2B_DEVICE_ID is empty " ++ "or device_id is unset); the dual writes are skipped and the legacy writes are intact.",+ );+ const at = new Date().toISOString();+ bumpStatus((s) => ({ ...s, skipped_no_device: s.skipped_no_device + 1, last_skip_at: at }));+}++function recordNoStore(root: string): void {+ warnOnce(+ "store",+ `brain store dual writes are on but there is no store at ${root}; the dual writes are ` ++ "skipped and the legacy writes are intact. Run `o2b store init` to create the store.",+ );+ const at = new Date().toISOString();+ bumpStatus((s) => ({ ...s, skipped_no_store: s.skipped_no_store + 1, last_skip_at: at }));+}++function storeFor(device: string, context: DualWriteContext): StoreHandle {+ const { root, origin } = resolveConfiguredStoreRoot(context.configPath);+ // The resolver checks the configured vault; the vault actually written+ // may be another one, and a root inside it is just as wrong.+ const vault = context.vault?.trim();+ if (vault !== undefined && vault !== "" && isPathInsideResolved(root, vault, process.platform)) {+ throw new StoreRootInsideVaultError(root, vault, origin);+ }+ const key = `${root}\u0000${device}`;+ const cached = handles.get(key);+ // A partition that went away under a running process (unsynced, or the+ // store removed), that arrived later (a sync delivered `private`), or a+ // different store put at the same root (deleted and created again) is+ // noticed on the next write: the store is opened again, so the clock and+ // the locks come from that store's device-local state.+ if (+ cached !== undefined &&+ STORE_PARTITIONS.every((p) => {+ const id = readStoreId(partitionDir(root, p));+ return cached.partitions.has(p) ? id === cached.storeId : id === null;+ })+ ) {+ return cached;+ }+ const handle = openStore({ root, device });+ handles.set(key, handle);+ return handle;+}++/** The id of the vault written, or `null` when it has no identity marker or none was named. */+function vaultIdOf(context: DualWriteContext): string | null {+ const vault = context.vault?.trim();+ if (vault === undefined || vault === "") return null;+ return readVaultIdentity(vault)?.vault_id ?? null;+}++function defaultAgent(): string {+ try {+ return resolveAgentName();+ } catch {+ return "agent";+ }+}++/**+ * Append the store records `build` describes, when the flag is on. Never+ * throws; see the module docblock for what happens on failure.+ */+export function dualWrite(build: DualWriteBuild, context: DualWriteContext = {}): void {+ if (!isDualWriteEnabled(context.configPath)) return;+ try {+ const device = resolveAppendShardId();+ if (device === "") {+ recordNoDevice();+ return;+ }+ const built = build();+ if (built === null) return;+ const records: ReadonlyArray<DualWriteRecord> = Array.isArray(built)+ ? built+ : [built as DualWriteRecord];+ if (records.length === 0) return;+ let store: StoreHandle;+ try {+ store = storeFor(device, context);+ } catch (err) {+ if (!(err instanceof NoStoreError)) throw err;+ recordNoStore(err.root);+ return;+ }+ const vaultId = vaultIdOf(context);+ for (const record of records) {+ const partition: StorePartition =+ record.private === true ||+ activeOperationPrivate() ||+ valueCarriesPrivateRegion(record.body) ||+ (record.privateWhenHeld === true && store.partitions.has("private"))+ ? "private"+ : "shared";+ appendRecord(store, {+ partition,+ stream: record.stream,+ ...(record.ledger !== undefined ? { ledger: record.ledger } : {}),+ kind: record.kind,+ agent:+ record.agent !== undefined && record.agent.trim() !== "" ? record.agent : defaultAgent(),+ scope: record.scope ?? null,+ body: { ...record.body, [VAULT_ID_FIELD]: vaultId },+ });+ }+ } catch (err) {+ recordFailure(err);+ }+}diff --git a/src/core/store/envelope.ts b/src/core/store/envelope.tsnew file mode 100644index 00000000..6a9cd749--- /dev/null+++ b/src/core/store/envelope.ts@@ -0,0 +1,249 @@+/**+ * The record envelope of the brain store (design D3), built and verified.+ *+ * Every line of every shard is one envelope:+ *+ * ```+ * { "v": 1, "id": <ulid>, "hlc": "<physical_ms>.<counter>", "device": <id>,+ * "agent": <name>, "kind": <kind>, "scope": <scope|null>,+ * "topic": <topic ulid|null>, "sum": <sha256 of body>, "body": { ... } }+ * ```+ *+ * `sum` is the lowercase hex sha256 of the body's canonical JSON (keys+ * sorted recursively, see `integrity/digest.ts`), so a body that another+ * implementation re-serialises with a different key order still verifies.+ * The body is normalised through JSON before it is hashed, so what is+ * hashed is exactly what a reader parses back.+ *+ * A body spilled into a blob is replaced on the line by a reference+ * `{ "$blob": <sha256>, "bytes": <n> }` whose hash equals `sum`: the blob+ * file is named by the hash of its content, and its content is the+ * canonical JSON of the body. See `blobs.ts`.+ */++import { isValidDeviceId } from "../config.ts";+import { canonicalJson, sha256Hex } from "../integrity/digest.ts";+import {+ BLOB_REF_BYTES_KEY,+ BLOB_REF_KEY,+ ENVELOPE_FIELDS,+ STORE_BODY_MAX_DEPTH,+ STORE_FORMAT_VERSION,+} from "./constants.ts";+import { compareHlc, formatHlc, parseHlc, type Hlc } from "./hlc.ts";+import { isUlid, newUlid } from "./ulid.ts";++/** A JSON object body. */+export type RecordBody = { readonly [key: string]: unknown };++/** One stored record, exactly as it appears on a line. */+export interface StoreRecord {+ readonly v: number;+ readonly id: string;+ readonly hlc: string;+ readonly device: string;+ readonly agent: string;+ readonly kind: string;+ readonly scope: string | null;+ readonly topic: string | null;+ readonly sum: string;+ readonly body: RecordBody;+}++/** What a writer supplies; the id, version and checksum are derived. */+export interface RecordInput {+ readonly hlc: Hlc;+ readonly device: string;+ readonly agent: string;+ readonly kind: string;+ readonly scope?: string | null;+ readonly topic?: string | null;+ readonly body: RecordBody;+ /** Explicit id; a fresh ULID when omitted. */+ readonly id?: string;+}++/** A refusal to build a record from invalid input. */+export class EnvelopeError extends Error {+ constructor(message: string) {+ super(message);+ this.name = "EnvelopeError";+ }+}++/** Record kinds: lowercase words joined by hyphens. */+export const RECORD_KIND_RE = /^[a-z][a-z0-9-]{0,63}$/;+const MAX_LABEL_LENGTH = 200;+const SHA256_RE = /^[0-9a-f]{64}$/;++/** Canonical JSON text of a body: what `sum` hashes and what a blob holds. */+export function canonicalBodyText(body: RecordBody): string {+ return canonicalJson(body);+}++/** The checksum of a body: sha256 of its canonical JSON. */+export function bodyChecksum(body: RecordBody): string {+ return sha256Hex(canonicalBodyText(body));+}++function isPlainObject(value: unknown): value is Record<string, unknown> {+ return typeof value === "object" && value !== null && !Array.isArray(value);+}++/**+ * Whether `body` nests objects and arrays deeper than+ * {@link STORE_BODY_MAX_DEPTH}, the body itself counting as one level.+ * Iterative, so the check itself cannot exhaust the stack; it is made+ * before any recursive walk (the canonical JSON) touches the body.+ */+export function bodyTooDeep(body: unknown): boolean {+ const stack: Array<readonly [unknown, number]> = [[body, 1]];+ while (stack.length > 0) {+ const [value, depth] = stack.pop()!;+ if (value === null || typeof value !== "object") continue;+ if (depth > STORE_BODY_MAX_DEPTH) return true;+ for (const child of Array.isArray(value) ? value : Object.values(value)) {+ if (child !== null && typeof child === "object") stack.push([child, depth + 1]);+ }+ }+ return false;+}++/** The corrupt-record reason for a body nested past the bound. */+export const BODY_TOO_DEEP_REASON = `body nests deeper than ${STORE_BODY_MAX_DEPTH} levels`;++/** Whether a line body is a blob reference rather than the body itself. */+export function isBlobRef(body: RecordBody): boolean {+ const bytes = body[BLOB_REF_BYTES_KEY];+ return (+ Object.keys(body).length === 2 &&+ typeof body[BLOB_REF_KEY] === "string" &&+ typeof bytes === "number" &&+ Number.isSafeInteger(bytes) &&+ bytes >= 0+ );+}++/**+ * Why `value` is not a valid label (`agent`, `scope`): a non-empty,+ * one-line string of at most {@link MAX_LABEL_LENGTH} characters. `null`+ * when it is valid. One rule for building and for verifying.+ */+function labelProblem(value: unknown): string | null {+ if (typeof value !== "string" || value.trim() === "" || value.length > MAX_LABEL_LENGTH) {+ return `must be a non-empty string of at most ${MAX_LABEL_LENGTH} characters`;+ }+ if (/[\r\n]/.test(value)) return "must be one line";+ return null;+}++/** Whether `value` can stand as a record's `agent` or `scope`. */+export function isRecordLabel(value: unknown): value is string {+ return labelProblem(value) === null;+}++function label(name: string, value: string | null | undefined, nullable: boolean): string | null {+ if (value === null || value === undefined) {+ if (nullable) return null;+ throw new EnvelopeError(`record ${name} is required`);+ }+ const problem = labelProblem(value);+ if (problem !== null) throw new EnvelopeError(`record ${name} ${problem}`);+ return value;+}++/**+ * Build a record from writer input. Throws {@link EnvelopeError} for a+ * device id the shard grammar refuses, a malformed kind, an empty agent,+ * a topic that is not a ULID, or a body that uses the reserved blob key.+ */+export function buildRecord(input: RecordInput): StoreRecord {+ if (!isValidDeviceId(input.device)) {+ throw new EnvelopeError(+ `record device "${input.device}" is not a valid device id (lowercase letters, digits and hyphens, not "sync-conflict")`,+ );+ }+ if (!RECORD_KIND_RE.test(input.kind)) {+ throw new EnvelopeError(`record kind "${input.kind}" must match ${RECORD_KIND_RE}`);+ }+ const agent = label("agent", input.agent, false)!;+ const scope = label("scope", input.scope, true);+ const topic = input.topic ?? null;+ if (topic !== null && !isUlid(topic)) {+ throw new EnvelopeError(`record topic "${topic}" must be a topic id (ULID) or null`);+ }+ if (!isPlainObject(input.body)) throw new EnvelopeError("record body must be a JSON object");+ if (bodyTooDeep(input.body)) throw new EnvelopeError(`record ${BODY_TOO_DEEP_REASON}`);+ if (BLOB_REF_KEY in input.body) {+ throw new EnvelopeError(`record body must not use the reserved key "${BLOB_REF_KEY}"`);+ }+ const id = input.id ?? newUlid(input.hlc.physical);+ if (!isUlid(id)) throw new EnvelopeError(`record id "${id}" must be a ULID`);+ const body = JSON.parse(JSON.stringify(input.body)) as RecordBody;+ return {+ v: STORE_FORMAT_VERSION,+ id,+ hlc: formatHlc(input.hlc),+ device: input.device,+ agent,+ kind: input.kind,+ scope,+ topic,+ sum: bodyChecksum(body),+ body,+ };+}++/** Outcome of {@link verifyEnvelope}. */+export type EnvelopeCheck =+ | { readonly ok: true; readonly record: StoreRecord }+ | { readonly ok: false; readonly reason: string; readonly unknownVersion?: number };++const fail = (reason: string): EnvelopeCheck => ({ ok: false, reason });++/**+ * Verify a parsed line: every field present with the right shape, a+ * known version, and a checksum that matches the body (for a blob+ * reference, a reference whose hash equals `sum`; the blob itself is+ * checked when it is read). A version newer than this build understands+ * is reported with `unknownVersion` so the caller can skip it apart from+ * corruption.+ */+export function verifyEnvelope(value: unknown): EnvelopeCheck {+ if (!isPlainObject(value)) return fail("line is not a JSON object");+ for (const field of ENVELOPE_FIELDS) {+ if (!(field in value)) return fail(`missing field "${field}"`);+ }+ const v = value["v"];+ if (typeof v !== "number" || !Number.isSafeInteger(v) || v < 1) return fail("invalid version");+ if (v !== STORE_FORMAT_VERSION) {+ return { ok: false, reason: `unknown format version ${v}`, unknownVersion: v };+ }+ const { id, hlc, device, agent, kind, scope, topic, sum, body } = value;+ if (!isUlid(id)) return fail("invalid id");+ if (typeof hlc !== "string" || parseHlc(hlc) === null) return fail("invalid hlc");+ if (typeof device !== "string" || !isValidDeviceId(device)) return fail("invalid device");+ if (labelProblem(agent) !== null) return fail("invalid agent");+ if (typeof kind !== "string" || !RECORD_KIND_RE.test(kind)) return fail("invalid kind");+ if (scope !== null && labelProblem(scope) !== null) return fail("invalid scope");+ if (topic !== null && !isUlid(topic)) return fail("invalid topic");+ if (typeof sum !== "string" || !SHA256_RE.test(sum)) return fail("invalid sum");+ if (!isPlainObject(body)) return fail("invalid body");+ if (bodyTooDeep(body)) return fail(BODY_TOO_DEEP_REASON);+ if (isBlobRef(body)) {+ if (body[BLOB_REF_KEY] !== sum)+ return fail("checksum mismatch: blob reference does not match sum");+ } else if (bodyChecksum(body) !== sum) {+ return fail("checksum mismatch");+ }+ return { ok: true, record: value as unknown as StoreRecord };+}++/** Fold order (design D3): hlc, then device id, then record id. */+export function compareRecords(a: StoreRecord, b: StoreRecord): number {+ const byClock = compareHlc(parseHlc(a.hlc)!, parseHlc(b.hlc)!);+ if (byClock !== 0) return byClock;+ if (a.device !== b.device) return a.device < b.device ? -1 : 1;+ if (a.id !== b.id) return a.id < b.id ? -1 : 1;+ return 0;+}diff --git a/src/core/store/fold-pinned.ts b/src/core/store/fold-pinned.tsnew file mode 100644index 00000000..80646d62--- /dev/null+++ b/src/core/store/fold-pinned.ts@@ -0,0 +1,86 @@+/**+ * The pinned context fold (design D4, task 1.6): the current-task+ * scratchpad every agent of the user shares, computed from its records.+ *+ * Input records (usually in the `events` stream):+ *+ * - `pinned-set` `{ authority, content }`: replaces the whole pinned+ * context with `content` (a string). An append is written as a set of+ * the full new text, so the record says exactly what the writer saw.+ * - `pinned-clear` `{ authority }`: a tombstone; the context is empty.+ *+ * Pinned context is one register, resolved by authority, then clock.+ * When agents on two machines replace it at nearly the same time, every+ * machine shows the replacement with the later clock; the other stays in+ * the history and can still be read from there.+ */++import { PINNED_CLEAR_KIND, PINNED_SET_KIND } from "./constants.ts";+import type { StoreRecord } from "./envelope.ts";+import {+ prepareRecords,+ recordAuthority,+ RegisterSet,+ TOMBSTONE,+ type RegisterEntry,+ type RejectedRecord,+} from "./fold.ts";++export interface PinnedFold {+ /** The current content; `null` when nothing was pinned or a clear won. */+ readonly content: string | null;+ /** Whether a clear won. */+ readonly cleared: boolean;+ /** Id of the winning record, or `null` when there are no pinned records. */+ readonly winner: string | null;+ /** Every applied pinned record in fold order, the winner included. */+ readonly history: ReadonlyArray<RegisterEntry<string>>;+ readonly rejected: ReadonlyArray<RejectedRecord>;+}++const KEY = "pinned";++function rejection(record: StoreRecord): string | null {+ if (recordAuthority(record) === null) return "missing or invalid authority";+ if (record.kind === PINNED_SET_KIND && typeof record.body["content"] !== "string") {+ return "content must be a string";+ }+ return null;+}++/** Fold pinned context records (any order, duplicates allowed). */+export function foldPinned(input: Iterable<StoreRecord>): PinnedFold {+ const { records } = prepareRecords(input);+ const register = new RegisterSet<string>();+ const rejected: RejectedRecord[] = [];+ for (const record of records) {+ if (record.kind !== PINNED_SET_KIND && record.kind !== PINNED_CLEAR_KIND) continue;+ const reason = rejection(record);+ if (reason !== null) {+ rejected.push({ id: record.id, kind: record.kind, reason });+ continue;+ }+ const authority = recordAuthority(record)!;+ const value =+ record.kind === PINNED_CLEAR_KIND ? TOMBSTONE : (record.body["content"] as string);+ register.offer(KEY, { record, authority, value });+ }+ const state = register.get(KEY);+ return {+ content: state?.value ?? null,+ cleared: state?.removed ?? false,+ winner: state?.winner.record.id ?? null,+ history: state?.history ?? [],+ rejected,+ };+}++/** The resolved pinned state as plain JSON, for the state digest. */+export function pinnedFingerprint(fold: PinnedFold): unknown {+ return {+ content: fold.content,+ cleared: fold.cleared,+ winner: fold.winner,+ rejected: fold.rejected.map((r) => r.id),+ };+}diff --git a/src/core/store/fold-preferences.ts b/src/core/store/fold-preferences.tsnew file mode 100644index 00000000..148ecd0b--- /dev/null+++ b/src/core/store/fold-preferences.ts@@ -0,0 +1,224 @@+/**+ * The preference fold (design D4, task 1.6): the state of every+ * preference computed from its records, in any delivery order.+ *+ * Input records (kinds from `constants.ts`, usually in the `events` stream):+ *+ * - `preference-set` `{ authority, preference, fields: { <name>: <json> } }`:+ * proposes a value for each named field. Every field is its own+ * register, resolved by authority, then clock, so a human retire+ * (`status: "retired"`) is not undone by a later agent edit while an+ * agent may still refine a field no human has touched. A set also+ * proposes that the preference exists.+ * - `preference-remove` `{ authority, preference }`: a tombstone on the+ * preference's existence, resolved by the same rule. The records and+ * the last field values stay; the preference simply no longer exists.+ * - `preference-evidence` `{ preference, result, artifact? }`: one+ * application of the rule. The counters `applied_count`,+ * `violated_count` and `outdated_count` are derived from these records+ * and are never written back; a set that names a counter field is+ * ignored for that field, and a set that names only counters is+ * rejected (it would otherwise propose existence with no field). Evidence never changes a field or the+ * existence, so a retired preference stays retired however much+ * evidence later arrives; the evidence is kept in its history.+ *+ * Output: one {@link PreferenceState} per preference id, with the winning+ * values, the record that won each, the derived counters and the full+ * history, plus the records rejected as malformed.+ */++import {+ EVIDENCE_RESULTS,+ PREFERENCE_COUNTER_FIELDS,+ PREFERENCE_EVIDENCE_KIND,+ PREFERENCE_REMOVE_KIND,+ PREFERENCE_SET_KIND,+ type EvidenceResult,+} from "./constants.ts";+import type { StoreRecord } from "./envelope.ts";+import {+ prepareRecords,+ recordAuthority,+ RegisterSet,+ TOMBSTONE,+ type RejectedRecord,+} from "./fold.ts";++/** Field names: lowercase words joined by underscores. */+export const PREFERENCE_FIELD_RE = /^[a-z][a-z0-9_]{0,63}$/;+const MAX_ID_LENGTH = 200;++export type PreferenceCounters = {+ readonly [K in (typeof PREFERENCE_COUNTER_FIELDS)[number]]: number;+};++export interface PreferenceState {+ readonly id: string;+ /** Whether a set won the existence register (no removal beat it). */+ readonly exists: boolean;+ /** Whether a removal won the existence register. */+ readonly removed: boolean;+ /** Winning field values, keys in code unit order. */+ readonly fields: Readonly<Record<string, unknown>>;+ /** Id of the record that won each field. */+ readonly fieldWinners: Readonly<Record<string, string>>;+ /** Id of the record that won the existence register, or `null` with evidence only. */+ readonly existenceWinner: string | null;+ /** Counters derived from evidence; never written back. */+ readonly counters: PreferenceCounters;+ /** Every set, removal and evidence record of this preference, in fold order. */+ readonly history: ReadonlyArray<StoreRecord>;+}++export interface PreferencesFold {+ /** Preference states by id, inserted in code unit order of the id. */+ readonly preferences: ReadonlyMap<string, PreferenceState>;+ readonly rejected: ReadonlyArray<RejectedRecord>;+}++const COUNTER_OF: Readonly<Record<EvidenceResult, keyof PreferenceCounters>> = {+ applied: "applied_count",+ violated: "violated_count",+ outdated: "outdated_count",+};++const COUNTERS = new Set<string>(PREFERENCE_COUNTER_FIELDS);+const KINDS = new Set<string>([+ PREFERENCE_SET_KIND,+ PREFERENCE_REMOVE_KIND,+ PREFERENCE_EVIDENCE_KIND,+]);++function preferenceId(record: StoreRecord): string | null {+ const id = record.body["preference"];+ if (typeof id !== "string" || id.trim() === "" || id.length > MAX_ID_LENGTH) return null;+ return /[\r\n]/.test(id) ? null : id;+}++function isPlainObject(value: unknown): value is Record<string, unknown> {+ return typeof value === "object" && value !== null && !Array.isArray(value);+}++/** Why a record of a preference kind cannot be applied, or `null` when it can. */+function rejection(record: StoreRecord): string | null {+ if (preferenceId(record) === null) return "missing or invalid preference id";+ if (record.kind === PREFERENCE_EVIDENCE_KIND) {+ const result = record.body["result"];+ return (EVIDENCE_RESULTS as ReadonlyArray<unknown>).includes(result)+ ? null+ : `evidence result must be one of ${EVIDENCE_RESULTS.join(", ")}`;+ }+ if (recordAuthority(record) === null) return "missing or invalid authority";+ if (record.kind === PREFERENCE_REMOVE_KIND) return null;+ const fields = record.body["fields"];+ if (!isPlainObject(fields) || Object.keys(fields).length === 0) {+ return "fields must be a non-empty object";+ }+ const bad = Object.keys(fields).find((name) => !PREFERENCE_FIELD_RE.test(name));+ if (bad !== undefined) return `invalid field name "${bad}"`;+ // A set that names only derived counters would change no field yet still+ // propose that the preference exists (and could undo a removal).+ return Object.keys(fields).some((name) => !COUNTERS.has(name))+ ? null+ : "fields name only derived counters";+}++const fieldKey = (id: string, field: string): string => `${id}\u0000${field}`;++/** Counters of a preference with no evidence yet, one per counter field. */+function zeroCounters(): Record<keyof PreferenceCounters, number> {+ return Object.fromEntries(PREFERENCE_COUNTER_FIELDS.map((name) => [name, 0])) as Record<+ keyof PreferenceCounters,+ number+ >;+}++/** Fold preference records (any order, duplicates allowed) into preference states. */+export function foldPreferences(input: Iterable<StoreRecord>): PreferencesFold {+ const { records } = prepareRecords(input);+ const existence = new RegisterSet<true>();+ const fields = new RegisterSet<unknown>();+ const fieldNames = new Map<string, Set<string>>();+ const history = new Map<string, StoreRecord[]>();+ const counters = new Map<string, Record<keyof PreferenceCounters, number>>();+ const rejected: RejectedRecord[] = [];++ for (const record of records) {+ if (!KINDS.has(record.kind)) continue;+ const reason = rejection(record);+ if (reason !== null) {+ rejected.push({ id: record.id, kind: record.kind, reason });+ continue;+ }+ const id = preferenceId(record)!;+ const own = history.get(id) ?? [];+ own.push(record);+ history.set(id, own);+ if (record.kind === PREFERENCE_EVIDENCE_KIND) {+ const count = counters.get(id) ?? zeroCounters();+ count[COUNTER_OF[record.body["result"] as EvidenceResult]] += 1;+ counters.set(id, count);+ continue;+ }+ const authority = recordAuthority(record)!;+ if (record.kind === PREFERENCE_REMOVE_KIND) {+ existence.offer(id, { record, authority, value: TOMBSTONE });+ continue;+ }+ existence.offer(id, { record, authority, value: true });+ const names = fieldNames.get(id) ?? new Set<string>();+ for (const [name, value] of Object.entries(record.body["fields"] as Record<string, unknown>)) {+ if (COUNTERS.has(name)) continue; // derived, never written back+ names.add(name);+ fields.offer(fieldKey(id, name), { record, authority, value });+ }+ fieldNames.set(id, names);+ }++ const preferences = new Map<string, PreferenceState>();+ for (const id of [...history.keys()].toSorted()) {+ const exist = existence.get(id);+ const values: Record<string, unknown> = {};+ const winners: Record<string, string> = {};+ for (const name of [...(fieldNames.get(id) ?? [])].toSorted()) {+ const state = fields.get(fieldKey(id, name))!;+ values[name] = state.value;+ winners[name] = state.winner.record.id;+ }+ preferences.set(id, {+ id,+ exists: exist !== undefined && !exist.removed,+ removed: exist?.removed ?? false,+ fields: values,+ fieldWinners: winners,+ existenceWinner: exist?.winner.record.id ?? null,+ counters: counters.get(id) ?? zeroCounters(),+ history: history.get(id)!,+ });+ }+ return { preferences, rejected };+}++/**+ * The resolved preference state as plain JSON, for the state digest: what+ * every machine must agree on for the same records. History is left out;+ * it is the records themselves, which the digest's cut already pins.+ */+export function preferencesFingerprint(fold: PreferencesFold): unknown {+ // `Object.fromEntries` defines own properties, so an id such as+ // `__proto__` is a key like any other and is never dropped from the hash.+ const out = Object.fromEntries(+ [...fold.preferences].map(([id, state]) => [+ id,+ {+ exists: state.exists,+ removed: state.removed,+ fields: state.fields,+ field_winners: state.fieldWinners,+ existence_winner: state.existenceWinner,+ counters: state.counters,+ },+ ]),+ );+ return { preferences: out, rejected: fold.rejected.map((r) => r.id) };+}diff --git a/src/core/store/fold-settings.ts b/src/core/store/fold-settings.tsnew file mode 100644index 00000000..301f6120--- /dev/null+++ b/src/core/store/fold-settings.ts@@ -0,0 +1,137 @@+/**+ * The shared settings fold (design D4, spec "Shared store settings";+ * task 1.6): values every machine must agree on, stored as records in the+ * `settings` stream of the `shared` partition instead of in device-local+ * config, so a change made on one machine applies on every other once the+ * record syncs.+ *+ * Input records:+ *+ * - `setting-set` `{ authority, key, value }`: proposes `value` for `key`.+ * - `setting-unset` `{ authority, key }`: a tombstone; the key falls back+ * to its default.+ *+ * Each key is one register, resolved by authority, then clock. Keys this+ * version knows are validated (see {@link SETTING_RULES}); a record with+ * an invalid value is rejected and does not take effect. Unknown keys+ * (written by a newer release) fold as plain JSON values, so an older+ * machine keeps them instead of losing them.+ */++import {+ SETTING_SET_KIND,+ SETTING_TOPIC_MIN_RECORDS,+ SETTING_TOPIC_MIN_SESSIONS,+ SETTING_UNSET_KIND,+ SETTING_VIEW_LANGUAGE,+ SETTING_VIEW_WRITER,+ type SettingKey,+} from "./constants.ts";+import { isValidDeviceId } from "../config.ts";+import type { StoreRecord } from "./envelope.ts";+import {+ prepareRecords,+ recordAuthority,+ RegisterSet,+ TOMBSTONE,+ type RegisterState,+ type RejectedRecord,+} from "./fold.ts";++/** Setting keys: dot-separated lowercase words with underscores. */+export const SETTING_KEY_RE = /^[a-z][a-z0-9_]*(\.[a-z][a-z0-9_]*){0,7}$/;++/** Validation and default of a known key. */+interface SettingRule {+ readonly valid: (value: unknown) => boolean;+ readonly expected: string;+ readonly fallback: unknown;+}++const positiveInt = (value: unknown): boolean =>+ typeof value === "number" && Number.isSafeInteger(value) && value >= 1;++/** Language tags such as `en`, `ru` or `pt-BR`. */+const LANGUAGE_RE = /^[A-Za-z]{2,3}(-[A-Za-z0-9]{2,8}){0,3}$/;++/** The keys this version knows: what a valid value is, and the default. */+export const SETTING_RULES: Readonly<Record<SettingKey, SettingRule>> = Object.freeze({+ [SETTING_VIEW_WRITER]: {+ valid: (value) => typeof value === "string" && isValidDeviceId(value),+ expected: "a device id",+ fallback: null,+ },+ [SETTING_VIEW_LANGUAGE]: {+ valid: (value) => typeof value === "string" && LANGUAGE_RE.test(value),+ expected: "a language tag such as en or pt-BR",+ fallback: null,+ },+ [SETTING_TOPIC_MIN_RECORDS]: { valid: positiveInt, expected: "a positive integer", fallback: 5 },+ [SETTING_TOPIC_MIN_SESSIONS]: { valid: positiveInt, expected: "a positive integer", fallback: 2 },+});++function ruleOf(key: string): SettingRule | undefined {+ return Object.hasOwn(SETTING_RULES, key) ? SETTING_RULES[key as SettingKey] : undefined;+}++export interface SettingsFold {+ /** Resolved keys, inserted in code unit order. */+ readonly settings: ReadonlyMap<string, RegisterState<unknown>>;+ readonly rejected: ReadonlyArray<RejectedRecord>;+}++function rejection(record: StoreRecord): string | null {+ if (recordAuthority(record) === null) return "missing or invalid authority";+ const key = record.body["key"];+ if (typeof key !== "string" || !SETTING_KEY_RE.test(key)) return "missing or invalid key";+ if (record.kind === SETTING_UNSET_KIND) return null;+ if (!("value" in record.body) || record.body["value"] === null) return "value is required";+ const rule = ruleOf(key);+ if (rule !== undefined && !rule.valid(record.body["value"])) {+ return `${key} must be ${rule.expected}`;+ }+ return null;+}++/** Fold setting records (any order, duplicates allowed). */+export function foldSettings(input: Iterable<StoreRecord>): SettingsFold {+ const { records } = prepareRecords(input);+ const registers = new RegisterSet<unknown>();+ const rejected: RejectedRecord[] = [];+ for (const record of records) {+ if (record.kind !== SETTING_SET_KIND && record.kind !== SETTING_UNSET_KIND) continue;+ const reason = rejection(record);+ if (reason !== null) {+ rejected.push({ id: record.id, kind: record.kind, reason });+ continue;+ }+ const value = record.kind === SETTING_UNSET_KIND ? TOMBSTONE : record.body["value"];+ registers.offer(record.body["key"] as string, {+ record,+ authority: recordAuthority(record)!,+ value,+ });+ }+ const settings = new Map<string, RegisterState<unknown>>();+ for (const key of registers.keys()) settings.set(key, registers.get(key)!);+ return { settings, rejected };+}++/**+ * The effective value of `key`: the folded value, or the key's default+ * when it was never set or a removal won (`null` for an unknown key).+ */+export function settingValue(fold: SettingsFold, key: string): unknown {+ const state = fold.settings.get(key);+ if (state !== undefined && !state.removed) return state.value;+ return ruleOf(key)?.fallback ?? null;+}++/** The resolved settings as plain JSON, for the state digest. */+export function settingsFingerprint(fold: SettingsFold): unknown {+ const out: Record<string, unknown> = {};+ for (const [key, state] of fold.settings) {+ out[key] = { value: state.value, removed: state.removed, winner: state.winner.record.id };+ }+ return { settings: out, rejected: fold.rejected.map((r) => r.id) };+}diff --git a/src/core/store/fold.ts b/src/core/store/fold.tsnew file mode 100644index 00000000..edd8543e--- /dev/null+++ b/src/core/store/fold.ts@@ -0,0 +1,184 @@+/**+ * The generic fold engine of the brain store (design D3, D4; task 1.6).+ *+ * Pure: no I/O, no clock. Every concrete fold (preferences, pinned+ * context, settings) is built from the two pieces here.+ *+ * - {@link prepareRecords} turns any delivered set of verified records+ * into one canonical sequence: duplicates collapse by record id (a+ * record delivered twice is applied once), then the records sort in+ * fold order (hlc, device, id). The same set gives the same sequence in+ * any delivery order. Records whose body is still a pending blob+ * reference are held out, since their content is not known yet.+ * - {@link RegisterSet} resolves keyed registers by authority, then clock:+ * a human record beats an agent record, which beats a decision-model+ * record; within one authority the record later in fold order wins.+ * Nothing is dropped: every offer stays in the register's history, so a+ * losing value remains queryable. A removal is an ordinary offer whose+ * value is the {@link TOMBSTONE}.+ *+ * Records whose kind a fold handles but whose body is malformed are not+ * applied; the fold reports them as rejected so doctor can name them.+ */++import { canonicalJson } from "../integrity/digest.ts";+import { compareCodeUnits } from "./compare.ts";+import { AUTHORITIES, AUTHORITY_FIELD, type Authority } from "./constants.ts";+import { compareRecords, isBlobRef, type StoreRecord } from "./envelope.ts";++/** The value of a register that a removal record decided. */+export const TOMBSTONE: unique symbol = Symbol("tombstone");+export type Tombstone = typeof TOMBSTONE;++/** A record a fold refused to apply, with the reason. */+export interface RejectedRecord {+ readonly id: string;+ readonly kind: string;+ readonly reason: string;+}++/** Two deliveries that share an id but not their content. */+export interface IdConflict {+ readonly id: string;+ /** Number of distinct versions delivered. */+ readonly versions: number;+}++export interface PreparedRecords {+ /** Unique records in fold order. */+ readonly records: ReadonlyArray<StoreRecord>;+ /** Deliveries dropped as exact duplicates of a record already seen. */+ readonly duplicates: number;+ /** Ids delivered with different content; one version was kept deterministically. */+ readonly conflicts: ReadonlyArray<IdConflict>;+ /** Records whose body is a blob that has not arrived (or not verified) yet. */+ readonly pending: ReadonlyArray<StoreRecord>;+}++/**+ * Pick the version of a conflicting id to keep: the smallest in fold+ * order, then by canonical text, so every machine keeps the same one.+ */+function preferVersion(a: StoreRecord, b: StoreRecord): StoreRecord {+ const order = compareRecords(a, b);+ if (order !== 0) return order < 0 ? a : b;+ return canonicalJson(a) <= canonicalJson(b) ? a : b;+}++/** Deduplicate by id, hold out pending bodies, and sort in fold order. */+export function prepareRecords(input: Iterable<StoreRecord>): PreparedRecords {+ const byId = new Map<string, StoreRecord>();+ // Canonical texts of every version delivered, kept only for repeated ids.+ const delivered = new Map<string, Set<string>>();+ let duplicates = 0;+ for (const record of input) {+ const seen = byId.get(record.id);+ if (seen === undefined) {+ byId.set(record.id, record);+ continue;+ }+ let texts = delivered.get(record.id);+ if (texts === undefined) {+ texts = new Set([canonicalJson(seen)]);+ delivered.set(record.id, texts);+ }+ const text = canonicalJson(record);+ if (texts.has(text)) {+ duplicates += 1; // an exact copy of a version already delivered+ continue;+ }+ texts.add(text);+ byId.set(record.id, preferVersion(seen, record));+ }+ const records: StoreRecord[] = [];+ const pending: StoreRecord[] = [];+ for (const record of byId.values()) (isBlobRef(record.body) ? pending : records).push(record);+ records.sort(compareRecords);+ pending.sort(compareRecords);+ const conflicts = [...delivered.entries()]+ .filter(([, texts]) => texts.size > 1)+ .map(([id, texts]) => ({ id, versions: texts.size }))+ .toSorted((a, b) => compareCodeUnits(a.id, b.id));+ return { records, duplicates, conflicts, pending };+}++/** Rank of an authority: higher beats lower. */+export function authorityRank(authority: Authority): number {+ return AUTHORITIES.length - AUTHORITIES.indexOf(authority);+}++/** Whether `value` names an authority. */+export function isAuthority(value: unknown): value is Authority {+ return typeof value === "string" && (AUTHORITIES as ReadonlyArray<string>).includes(value);+}++/**+ * The authority a mutable-entity record carries in its body, or `null`+ * when the field is missing or names no authority. It is never inferred+ * from the agent name.+ */+export function recordAuthority(record: StoreRecord): Authority | null {+ const value = record.body[AUTHORITY_FIELD];+ return isAuthority(value) ? value : null;+}++/** One offer to a register: who said what, and in which record. */+export interface RegisterEntry<V> {+ readonly record: StoreRecord;+ readonly authority: Authority;+ readonly value: V | Tombstone;+}++/** A resolved register. */+export interface RegisterState<V> {+ /** The winning value; `null` when a tombstone won. */+ readonly value: V | null;+ /** Whether a removal won. */+ readonly removed: boolean;+ /** The winning offer. */+ readonly winner: RegisterEntry<V>;+ /** Every offer in fold order, the winner included. */+ readonly history: ReadonlyArray<RegisterEntry<V>>;+}++/** Whether `next` beats `current`, given that `next` comes later in fold order. */+function beats(next: Authority, current: Authority): boolean {+ return authorityRank(next) >= authorityRank(current);+}++/**+ * Keyed registers resolved by authority, then fold order. Offers must+ * arrive in fold order (the order of {@link prepareRecords}); a later+ * offer of the same or a stronger authority takes the register.+ */+export class RegisterSet<V> {+ readonly #winners = new Map<string, RegisterEntry<V>>();+ readonly #history = new Map<string, RegisterEntry<V>[]>();++ offer(key: string, entry: RegisterEntry<V>): void {+ const current = this.#winners.get(key);+ if (current === undefined || beats(entry.authority, current.authority)) {+ this.#winners.set(key, entry);+ }+ const history = this.#history.get(key) ?? [];+ history.push(entry);+ this.#history.set(key, history);+ }++ get(key: string): RegisterState<V> | undefined {+ const winner = this.#winners.get(key);+ if (winner === undefined) return undefined;+ const removed = winner.value === TOMBSTONE;+ return {+ value: removed ? null : (winner.value as V),+ removed,+ winner,+ history: this.#history.get(key)!,+ };+ }++ /** Keys in code unit order. */+ keys(): string[] {+ return [...this.#winners.keys()].toSorted();+ }+}diff --git a/src/core/store/format-doc.ts b/src/core/store/format-doc.tsnew file mode 100644index 00000000..90711434--- /dev/null+++ b/src/core/store/format-doc.ts@@ -0,0 +1,63 @@+/**+ * The store's public format document (`FORMAT.md`, task 1.1), shipped+ * beside this module and written into the store root and every partition.+ *+ * The document's first line carries its format version as an HTML+ * comment (`<!-- open-second-brain-store-format: N -->`). A copy on disk+ * is replaced only by a document of a strictly newer version (or when it+ * declares none), so an older release running on one machine never+ * downgrades the description that travels with the data, and two releases+ * that ship the same version with different prose never rewrite each+ * other's copy on every open (sync churn, conflict copies).+ */++import { readFileSync } from "node:fs";+import { join } from "node:path";+import { fileURLToPath } from "node:url";++import { atomicWriteText } from "../fs-atomic.ts";+import { STORE_FORMAT_FILE } from "./constants.ts";++const VERSION_MARKER_RE = /^<!-- open-second-brain-store-format: (\d+) -->/;++/** File mode of the format document: readable by every tool that opens the store. */+const FORMAT_DOC_MODE = 0o644;++let shipped: string | undefined;++/** The format document this release ships. */+export function shippedFormatDoc(): string {+ shipped ??= readFileSync(+ join(fileURLToPath(new URL(".", import.meta.url)), STORE_FORMAT_FILE),+ "utf8",+ );+ return shipped;+}++/** The format version a document declares on its first line, or `null` when it declares none. */+export function formatDocVersion(text: string): number | null {+ const match = VERSION_MARKER_RE.exec(text);+ return match === null ? null : Number(match[1]);+}++/**+ * Write the shipped format document into `dir` unless a copy of the same+ * or a newer format version is already there. Returns whether it wrote.+ */+export function writeFormatDoc(dir: string): boolean {+ const text = shippedFormatDoc();+ const target = join(dir, STORE_FORMAT_FILE);+ let existing: string | null = null;+ try {+ existing = readFileSync(target, "utf8");+ } catch {+ existing = null;+ }+ if (existing === text) return false;+ if (existing !== null) {+ const onDisk = formatDocVersion(existing);+ const ours = formatDocVersion(text);+ if (onDisk !== null && ours !== null && onDisk >= ours) return false;+ }+ return atomicWriteText(target, text, { mode: FORMAT_DOC_MODE });+}diff --git a/src/core/store/hlc.ts b/src/core/store/hlc.tsnew file mode 100644index 00000000..0dd3b32d--- /dev/null+++ b/src/core/store/hlc.ts@@ -0,0 +1,91 @@+/**+ * Hybrid logical clock (design D3): pure arithmetic, no I/O.+ *+ * A stamp is `{ physical, counter }`, written `"<physical_ms>.<counter>"`.+ * Records fold in (hlc, device, id) order, and two rules keep that order+ * causal across machines whose wall clocks disagree:+ *+ * - Send: when the wall clock is ahead of the local clock's physical part,+ * the stamp is the wall clock with counter 0; otherwise the physical+ * part stays and the counter increments. Every stamp a device issues is+ * therefore strictly greater than the one before, even when the wall+ * clock steps backwards.+ * - Receive: observing a remote stamp raises the local clock to at least+ * that stamp. The next send then orders after it, so a record written+ * in reply to a remote record folds after it even when the replying+ * machine's wall clock is behind. A remote stamp more than+ * {@link HLC_MAX_DRIFT_MS} ahead of the wall clock (a broken clock, a+ * damaged line) is not adopted, so one bad record cannot push this+ * device's clock into the far future for good.+ *+ * Persistence of the local clock per device lives in `clock-store.ts`.+ */++/** One hybrid logical clock stamp. */+export interface Hlc {+ /** Milliseconds since the Unix epoch. */+ readonly physical: number;+ /** Tie-breaker within one physical millisecond. */+ readonly counter: number;+}++/** Remote stamps further ahead of the wall clock than this are not adopted (one day). */+export const HLC_MAX_DRIFT_MS = 24 * 60 * 60 * 1000;++/** The clock before anything was sent or observed. */+export const HLC_ZERO: Hlc = Object.freeze({ physical: 0, counter: 0 });++/** Non-negative integers without leading zeros: `0`, `7`, `1762400000123`. */+const HLC_RE = /^(0|[1-9]\d{0,15})\.(0|[1-9]\d{0,9})$/;++/** The text form written into the envelope's `hlc` field. */+export function formatHlc(clock: Hlc): string {+ return `${clock.physical}.${clock.counter}`;+}++/** Parse the text form; `null` for anything that is not exactly one stamp. */+export function parseHlc(text: string): Hlc | null {+ const match = HLC_RE.exec(text);+ if (match === null) return null;+ const physical = Number(match[1]);+ const counter = Number(match[2]);+ if (!Number.isSafeInteger(physical) || !Number.isSafeInteger(counter)) return null;+ return { physical, counter };+}++/** Negative, zero or positive as `a` orders before, with or after `b`. */+export function compareHlc(a: Hlc, b: Hlc): number {+ if (a.physical !== b.physical) return a.physical < b.physical ? -1 : 1;+ if (a.counter !== b.counter) return a.counter < b.counter ? -1 : 1;+ return 0;+}++/** The larger of two stamps. */+export function maxHlc(a: Hlc, b: Hlc): Hlc {+ return compareHlc(a, b) >= 0 ? a : b;+}++/**+ * Send rule: the stamp for a new local record, given the local clock and+ * the wall clock in milliseconds. The result is also the new local clock.+ */+export function sendHlc(local: Hlc, wallMs: number): Hlc {+ const wall = Math.max(0, Math.floor(wallMs));+ if (wall > local.physical) return { physical: wall, counter: 0 };+ return { physical: local.physical, counter: local.counter + 1 };+}++/**+ * Receive rule: the local clock after observing `remote`. It never moves+ * backwards and never falls below the remote stamp, so the next+ * {@link sendHlc} orders after everything observed so far. The wall clock+ * only matters when it is ahead of both. A remote stamp more than+ * {@link HLC_MAX_DRIFT_MS} ahead of the wall clock is ignored.+ */+export function receiveHlc(local: Hlc, remote: Hlc, wallMs: number): Hlc {+ const wall = Math.max(0, Math.floor(wallMs));+ const adoptable = remote.physical - wall <= HLC_MAX_DRIFT_MS;+ const known = adoptable ? maxHlc(local, remote) : local;+ if (wall > known.physical) return { physical: wall, counter: 0 };+ return known;+}diff --git a/src/core/store/local-lock.ts b/src/core/store/local-lock.tsnew file mode 100644index 00000000..e2f729c9--- /dev/null+++ b/src/core/store/local-lock.ts@@ -0,0 +1,144 @@+/**+ * Device-local advisory lock for the brain store (design D2).+ *+ * Every lock the store takes lives in the device-local state directory,+ * never inside the synced store: a lock file that a sync tool copies to+ * another machine would either block that machine or be deleted under the+ * holder. The lock is held only for the short critical section it guards+ * (one shard append, one clock tick).+ *+ * Built on `proper-lockfile`'s directory lock, the same primitive the log+ * appender and the device-id generator use, because it recovers from a+ * crashed holder: a lock directory older than {@link STORE_LOCK_STALE_MS}+ * is taken over. The synchronous lock never refreshes its age while held,+ * so the window has to outlast any critical section a live holder can be+ * stuck in: one append and its fsync are milliseconds long, but a paused+ * VM, an antivirus scan or a stalled disk can hold one for many seconds,+ * and taking such a lock over would let two writers interleave in one+ * shard. Sixty seconds, the window the vault writer lock uses+ * (`brain/sync-lockfile.ts`). The directory form works the same on+ * Windows, where it needs no handle kept open.+ *+ * The wait is bounded by the shared lock budget+ * (`OPEN_SECOND_BRAIN_LOCK_WAIT_MS`, five seconds by default) and is a+ * blocking sleep, like every other synchronous lock in this tree.+ *+ * On Windows a released lock directory lingers in a "delete pending" state+ * until the last handle closes, and a `mkdir` of that name meanwhile fails+ * with `EPERM` instead of `EEXIST`. {@link isLockContention} counts that as+ * a held lock, so a writer that loses a race to a releasing holder waits+ * its turn instead of failing; the Brain log lock (`brain/log.ts`) shares+ * the rule.+ */++import { mkdirSync } from "node:fs";+import { dirname } from "node:path";++import lockfile from "proper-lockfile";++import { isWindowsDeletePending, resolveLockWaitBudgetMs } from "../brain/sync-lockfile.ts";+import { sleepSync } from "../fs-atomic.ts";++/** Age after which a lock directory counts as abandoned by a crashed holder. */+export const STORE_LOCK_STALE_MS = 60_000;++/** Upper bound of one sleep between attempts. */+const RETRY_SLEEP_MAX_MS = 20;++/**+ * Whether a failed `proper-lockfile` acquire of `lockTarget` means another+ * holder has the lock: `ELOCKED`, or on Windows an `EPERM`/`EACCES` while+ * the lock directory `<lockTarget>.lock` is still there (a release that+ * has not finished). An `EPERM` with nothing at the name is a directory+ * that refuses writes and stays an error. `platform` is a test seam.+ */+export function isLockContention(+ err: unknown,+ lockTarget: string,+ platform: NodeJS.Platform = process.platform,+): boolean {+ const e = err as NodeJS.ErrnoException;+ return e.code === "ELOCKED" || isWindowsDeletePending(e, `${lockTarget}.lock`, platform);+}++/** A Windows `EPERM`/`EACCES`, the code a lock create gets while a name is being deleted. */+export function isWindowsRefusal(+ err: unknown,+ platform: NodeJS.Platform = process.platform,+): boolean {+ const code = (err as NodeJS.ErrnoException).code;+ return platform === "win32" && (code === "EPERM" || code === "EACCES");+}++/** How {@link acquireDirLock} waits and what its refusal says. */+export interface DirLockOptions {+ /** Age after which the lock directory counts as abandoned. */+ readonly staleMs: number;+ /** Longest total wait before giving up with `ELOCKED`. */+ readonly budgetMs: number;+ /** What the refusal calls the lock ("store lock", "log lock"). */+ readonly label: string;+ /** What the refusal tells the operator to do next. */+ readonly remedy: string;+}++/**+ * Take the `proper-lockfile` directory lock of `lockTarget`+ * (`<lockTarget>.lock`), waiting with jittered, growing sleeps while it is+ * held, and return its release. Throws an `ELOCKED` error naming the+ * target when the lock stays held past the budget; any other failure is+ * rethrown as it is.+ */+export function acquireDirLock(lockTarget: string, options: DirLockOptions): () => void {+ const started = Date.now();+ let refusalRetried = false;+ for (let attempt = 0; ; attempt++) {+ try {+ return lockfile.lockSync(lockTarget, { stale: options.staleMs, realpath: false });+ } catch (err) {+ if (!isLockContention(err, lockTarget)) {+ // A Windows EPERM with nothing at the name is a refusing directory+ // or a release that finished between the mkdir and the check; one+ // more try tells them apart.+ if (refusalRetried || !isWindowsRefusal(err)) throw err;+ refusalRetried = true;+ continue;+ }+ if (Date.now() - started >= options.budgetMs) {+ const refused: NodeJS.ErrnoException = new Error(+ `${options.label} busy: ${lockTarget}: still held after waiting ` ++ `${Date.now() - started} ms; ${options.remedy}`,+ { cause: err },+ );+ refused.code = "ELOCKED";+ refused.path = lockTarget;+ throw refused;+ }+ // Jittered, growing sleep so waiters do not wake in lockstep.+ sleepSync(1 + Math.floor(Math.random() * Math.min(RETRY_SLEEP_MAX_MS, 2 + attempt * 2)));+ }+ }+}++/**+ * Run `fn` while holding the device-local lock named by `lockTarget` (a+ * path inside the device-local state directory; the lock directory is+ * `<lockTarget>.lock`). Throws an `ELOCKED` error naming the target when+ * the lock stays held past the wait budget.+ */+export function withLocalLock<T>(lockTarget: string, fn: () => T, budgetMs?: number): T {+ mkdirSync(dirname(lockTarget), { recursive: true });+ const release = acquireDirLock(lockTarget, {+ staleMs: STORE_LOCK_STALE_MS,+ budgetMs: budgetMs ?? resolveLockWaitBudgetMs(),+ label: "store lock",+ remedy:+ "retry once the other writer finishes, or allow a longer wait with " ++ "OPEN_SECOND_BRAIN_LOCK_WAIT_MS=<milliseconds>",+ });+ try {+ return fn();+ } finally {+ release();+ }+}diff --git a/src/core/store/operation-privacy.ts b/src/core/store/operation-privacy.tsnew file mode 100644index 00000000..cd74393c--- /dev/null+++ b/src/core/store/operation-privacy.ts@@ -0,0 +1,166 @@+/**+ * One privacy verdict per writer operation. A legacy write that dual-writes+ * several store records (a signal and its idempotency receipt, a+ * preference's human and derived records, an evidence event, its evidence+ * record and its receipt, a write batch's log events and its receipt)+ * judges its privacy ONCE, here, and hands the same verdict to every+ * record it writes. No record of the operation judges itself into a less+ * private partition, so the records of one write never land in different+ * partitions. The `<private>` region check of the dual-write entry point+ * (`dual-write.ts`) stays as a backstop that can only raise a record.+ * Each operation also runs its body inside its verdict's ambient scope+ * (`operation-scope.ts`), so a record written down the call chain by a+ * writer the operation never hands the verdict to (a permissions decision+ * row, a metric, an audit event) follows the operation too.+ *+ * An operation is private when any of these holds:+ *+ * - its target page is private or cannot be judged (`target`);+ * - any content-bearing value names a private page or one that cannot be+ * judged, or carries a `<private>` region or the placeholder a stripped+ * one leaves (`content`, judged by {@link rowNamesPrivatePage});+ * - an enclosing or inner operation's verdict is private (`inherit`).+ *+ * Each `content` entry names its `opaque` fields: the record's own id,+ * hashes, timestamps and keys (a generated path is not passed as content+ * at all). Their values are not written to name a page, so they are never+ * judged as references (they are still checked for a `<private>` region).+ * The writer identities `agent` and `owner` are NOT opaque: a writer takes+ * them from its caller as free strings, so they are judged as content+ * like any other. A plain identity such as `@claude-devbox-agent` names no+ * page and leaves the operation shared.+ *+ * Every operation also judges its WHOLE caller-supplied input+ * ({@link callerInput}): every field the caller can set, not a list picked+ * by hand, so a field that reaches a record body (a writer identity, an+ * idempotency key, a batch request id) cannot carry a link or a region the+ * verdict did not see. A record body may still hold strings the writer+ * generated itself (allocated ids, timestamps, hashes, the origin channel,+ * vault-relative paths it derived); none of them is caller text, so none+ * can carry a region.+ *+ * The verdict is lazy and memoised: nothing is judged unless a record is+ * actually written (dual writes off judges nothing), and once judged it+ * never changes for the rest of the operation. A judge that throws counts+ * as private, the partition that leaks nothing.+ */++import { EXPIRATION_DATE_FIELD } from "../brain/expiration.ts";+import { ORIGIN_CHANNEL_FIELD } from "../origin-channel.ts";+import { rowNamesPrivatePage } from "./reference-privacy.ts";++/** A privacy verdict: a fixed answer, or one judged on first use. */+export type PrivacyVerdict = boolean | (() => boolean);++/** One content-bearing value of an operation, with its opaque fields. */+export interface JudgedContent {+ readonly value: unknown;+ readonly opaque?: ReadonlySet<string>;+}++/** What one operation's privacy is judged from. */+export interface OperationPrivacyParts {+ /** Whether the target page is private or cannot be judged. */+ readonly target?: PrivacyVerdict;+ /** The operation's content-bearing values. */+ readonly content?: ReadonlyArray<JudgedContent>;+ /** Verdicts of an enclosing operation or of the operation's parts. */+ readonly inherit?: ReadonlyArray<PrivacyVerdict | undefined>;+}++/** The operation's verdict, judged once on first call. */+export type OperationPrivacy = () => boolean;++/**+ * Opaque fields every record shares: its own coordinates and stamps. The+ * writer identities (`agent`, `owner`) are caller-supplied strings and+ * stay content.+ */+export const COMMON_OPAQUE_FIELDS: ReadonlyArray<string> = Object.freeze([+ "id",+ "kind",+ "created_at",+ "updated_at",+ "idempotency_key",+ EXPIRATION_DATE_FIELD,+ ORIGIN_CHANNEL_FIELD,+]);++/** {@link COMMON_OPAQUE_FIELDS} plus `extra`, as a set. */+export function opaqueFields(...extra: ReadonlyArray<string>): ReadonlySet<string> {+ return new Set([...COMMON_OPAQUE_FIELDS, ...extra]);+}++/**+ * Opaque fields of a signal's frontmatter and caller input: dates,+ * event-time stamps, the slug its id is allocated from, the dedup hash,+ * the session and vault it came from. Everything else+ * (`principle`, `source`, `raw`, `scope`, tags, ...) is content.+ */+export const SIGNAL_OPAQUE_FIELDS: ReadonlySet<string> = opaqueFields(+ "date",+ "slug",+ "valid_from",+ "recorded_at",+ "authored_at",+ "dedup_hash",+ "session_ref",+ "origin_vault",+);++/**+ * Opaque fields of a preference's store fields and caller input:+ * timestamps, hashes, the slug its id is made of and the revision+ * counter. Everything else (`principle`, `evidenced_by`,+ * `supersedes` and other relationship fields, `scope`, ...) is content.+ */+export const PREFERENCE_OPAQUE_FIELDS: ReadonlySet<string> = opaqueFields(+ "slug",+ "confirmed_at",+ "unconfirmed_until",+ "last_evidence_at",+ "retired_at",+ "valid_from",+ "valid_until",+ "content_hash",+ "revision",+);++/**+ * The whole caller-supplied input of an operation as content. `opaque`+ * names its keys, hashes, timestamps, ids and local settings (a config+ * path, a clock): checked for a `<private>` region like every string, but+ * never judged as page references.+ */+export function callerInput(value: unknown, opaque: ReadonlySet<string>): JudgedContent {+ return { value, opaque };+}++function holds(verdict: PrivacyVerdict | undefined): boolean {+ return typeof verdict === "function" ? verdict() : verdict === true;+}++function judge(vault: string, parts: OperationPrivacyParts): boolean {+ if (holds(parts.target)) return true;+ if ((parts.inherit ?? []).some(holds)) return true;+ // The row judge checks every string, opaque or not, for a region, and+ // every non-opaque one as a page reference.+ return (parts.content ?? []).some(({ value, opaque }) =>+ rowNamesPrivatePage(vault, value, opaque),+ );+}++/** The single, memoised privacy verdict of one writer operation. */+export function operationPrivacy(vault: string, parts: OperationPrivacyParts): OperationPrivacy {+ let verdict: boolean | undefined;+ return () => {+ if (verdict === undefined) {+ try {+ verdict = judge(vault, parts);+ } catch {+ verdict = true;+ }+ }+ return verdict;+ };+}diff --git a/src/core/store/operation-scope.ts b/src/core/store/operation-scope.tsnew file mode 100644index 00000000..fed2f1dd--- /dev/null+++ b/src/core/store/operation-scope.ts@@ -0,0 +1,75 @@+/**+ * The ambient operation scope: every brain store record written while a+ * writer operation runs inherits that operation's privacy verdict, with no+ * per-site threading.+ *+ * A writer operation (a signal, a preference, apply-evidence, a Brain+ * note, a pin, a write batch, a direct note create) runs its body inside+ * {@link withOperationPrivacy}. The dual-write entry point (`dual-write.ts`)+ * reads {@link activeOperationPrivate} for every record it writes and+ * raises the record to `private` when the active verdict is private. So+ * any record written down the call chain (a ledger row, a permissions+ * decision row, an audit event, a receipt, a metric) follows the operation+ * it belongs to, including records the operation's own code never sees.+ *+ * Rules:+ *+ * - **Raise-only.** The scope can send a record to `private`; it never+ * lowers a record its builder or the `<private>` region backstop judged+ * private.+ * - **Nesting ORs.** An operation started inside another (a batch's note+ * create, an evidence write's log event) is private when either verdict+ * is: an inner operation can only raise what it writes.+ * - **Lazy.** The verdict is called only when a record is written, so dual+ * writes off judge nothing, exactly as before.+ * - **Sync and async.** The scope is an `AsyncLocalStorage` store: it+ * holds for the synchronous body and follows every promise, timer and+ * callback the body starts, on every platform Node and Bun run on.+ * Outside any operation there is no scope and nothing is raised.+ */++import { AsyncLocalStorage } from "node:async_hooks";++/**+ * A verdict as `operation-privacy.ts` spells it (`PrivacyVerdict`): a fixed+ * answer or one judged on first use. Declared here, not imported, because+ * the dual-write entry point reads this module and the privacy judges read+ * the dual-write records.+ */+type ScopeVerdict = boolean | (() => boolean);++const storage = new AsyncLocalStorage<() => boolean>();++function holds(verdict: ScopeVerdict | undefined): boolean {+ return typeof verdict === "function" ? verdict() : verdict === true;+}++/**+ * Run `fn` as one writer operation whose verdict is `verdict`, ORed with+ * the verdict of any enclosing operation. Returns what `fn` returns (a+ * promise for an async body, which keeps the scope across its awaits).+ */+export function withOperationPrivacy<T>(verdict: ScopeVerdict | undefined, fn: () => T): T {+ const outer = storage.getStore();+ let judged: boolean | undefined;+ const scoped = (): boolean => {+ if (judged === undefined) {+ try {+ judged = (outer !== undefined && outer()) || holds(verdict);+ } catch {+ judged = true;+ }+ }+ return judged;+ };+ return storage.run(scoped, fn);+}++/**+ * Whether the writer operation running now is private. `false` outside+ * any operation. Judged once per operation on first use; a verdict that+ * throws counts as private, the partition that leaks nothing.+ */+export function activeOperationPrivate(): boolean {+ return storage.getStore()?.() ?? false;+}diff --git a/src/core/store/private-region.ts b/src/core/store/private-region.tsnew file mode 100644index 00000000..bc860f37--- /dev/null+++ b/src/core/store/private-region.ts@@ -0,0 +1,72 @@+/**+ * The `<private>` region test every brain store dual write shares: whether+ * a text, or any string a record body carries at any depth, has a+ * `<private>` region or the placeholder a stripped one leaves. A record+ * whose text holds one goes to `private` only, whatever else its writer+ * judged. Kept apart from `reference-privacy.ts`, which judges the pages a+ * record names, so the dual-write entry point can apply it to every record+ * without importing the page judges (and the record builders they use).+ */++import { PRIVATE_REGION_PLACEHOLDER, privateRegionTexts } from "../redactor.ts";++/**+ * Whether `text` carries a `<private>` region, or the placeholder a+ * stripped one leaves (the shared redactor strips regions this way, so a+ * writer that sanitised its text still carries the mark).+ */+export function textCarriesPrivateRegion(text: string): boolean {+ return text.includes(PRIVATE_REGION_PLACEHOLDER) || privateRegionTexts(text).length > 0;+}++/**+ * Whether any string `value` carries, at any depth, has a `<private>`+ * region or the placeholder a stripped one leaves+ * ({@link textCarriesPrivateRegion}). A value nested deeper than the walk+ * goes cannot be judged in full and counts as carrying one. Used for every+ * dual-written record body, so a record whose text holds a region goes to+ * `private` only whatever its writer judged.+ */+export function valueCarriesPrivateRegion(value: unknown): boolean {+ const strings = rowStrings(value, new Set());+ return strings === null || strings.texts.some(textCarriesPrivateRegion);+}++/**+ * Deepest container nesting {@link rowStrings} walks. A row nested deeper+ * cannot be judged in full, so its judges fail closed.+ */+const ROW_WALK_MAX_DEPTH = 32;++/**+ * Every string `row` carries, at any depth (`texts`), and those outside an+ * `opaque` field (`references`). `null` when the row nests deeper than+ * {@link ROW_WALK_MAX_DEPTH} and so cannot be judged in full.+ */+export function rowStrings(+ row: unknown,+ opaque: ReadonlySet<string>,+): { readonly texts: string[]; readonly references: string[] } | null {+ const references: string[] = [];+ const texts: string[] = [];+ // Iterative, so a deeply nested row cannot overflow the stack.+ const stack: Array<readonly [unknown, number, boolean]> = [[row, 0, false]];+ while (stack.length > 0) {+ const [value, depth, isOpaque] = stack.pop()!;+ if (typeof value === "string") {+ texts.push(value);+ if (!isOpaque) references.push(value);+ continue;+ }+ if (value === null || typeof value !== "object") continue;+ if (depth >= ROW_WALK_MAX_DEPTH) return null;+ if (Array.isArray(value)) {+ for (const child of value) stack.push([child, depth + 1, isOpaque]);+ continue;+ }+ for (const [field, child] of Object.entries(value)) {+ stack.push([child, depth + 1, isOpaque || opaque.has(field)]);+ }+ }+ return { texts, references };+}diff --git a/src/core/store/reader.ts b/src/core/store/reader.tsnew file mode 100644index 00000000..60e49b28--- /dev/null+++ b/src/core/store/reader.ts@@ -0,0 +1,395 @@+/**+ * The shard reader of the brain store (design D3, task 1.5).+ *+ * Reads one shard from a byte offset (the index resumes from the offset+ * it stored), parses and verifies every line, and returns the records with+ * the diagnostics a doctor reports:+ *+ * - An incomplete last line (no newline yet) or a last line that fails+ * verification is NOT consumed: `nextOffset` stops before it, so the+ * next read retries it once the sync tool has delivered the rest. It is+ * never treated as deleted, and it is reported only as a pending tail.+ * - A middle line that fails verification is skipped and reported.+ * - A record with an unknown format version is skipped and reported.+ * - A `compacted` record is returned like any other and its shard lists+ * are collected, so a caller can tell a replaced shard from a missing one.+ * - A record whose body is a blob reference gets its body from the blob+ * when the blob is present and verifies; otherwise the record is+ * returned with its body pending, to be filled in on a later read. A+ * blob that verifies but does not hold the record's body (not a JSON+ * object, not canonical, a different length than the reference says)+ * can never change, since its name fixes its content: the record is+ * skipped and reported as a corrupt line.+ * - A record whose `device` is not the device directory its shard sits+ * in is skipped and reported as a corrupt line: only that device+ * writes there.+ *+ * The shard is read in bounded chunks, never whole. A run of bytes longer+ * than the line-size cap without a newline can never be a record (the+ * writer refuses such a line), so it is reported as a corrupt line and+ * consumed, never held back as a pending tail.+ */++import { basename, dirname } from "node:path";+import { closeSync, fstatSync, readSync } from "node:fs";++import { isValidDeviceId } from "../config.ts";+import {+ BLOB_REF_BYTES_KEY,+ BLOB_REF_KEY,+ COMPACTED_KIND,+ STORE_LINE_CAP_BYTES,+} from "./constants.ts";+import { readBlob } from "./blobs.ts";+import {+ BODY_TOO_DEEP_REASON,+ bodyChecksum,+ bodyTooDeep,+ isBlobRef,+ verifyEnvelope,+ type RecordBody,+ type StoreRecord,+} from "./envelope.ts";+import { openRegularFileForRead } from "./safe-fs.ts";+import { isShardFileName } from "./shard-list.ts";++/** Where a returned record's body came from. */+export type BodyState = "inline" | "blob" | "pending";++export interface ReadRecord {+ /** The record; for a pending blob its body is still the blob reference. */+ readonly record: StoreRecord;+ readonly bodyState: BodyState;+ /** Byte offset of the line in the shard. */+ readonly offset: number;+ /** Byte length of the line, newline included. */+ readonly length: number;+}++export type ShardDiagnosticKind =+ | "corrupt-line"+ | "unknown-version"+ | "offset-past-end"+ | "not-a-file";++export interface ShardDiagnostic {+ readonly kind: ShardDiagnosticKind;+ /** Byte offset of the line concerned (or the requested offset). */+ readonly offset: number;+ readonly reason: string;+}++/** One compaction a shard announced: partition-relative shard paths. */+export interface Compaction {+ readonly id: string;+ readonly replaces: ReadonlyArray<string>;+ readonly into: ReadonlyArray<string>;+}++export interface ShardRead {+ readonly records: ReadonlyArray<ReadRecord>;+ readonly diagnostics: ReadonlyArray<ShardDiagnostic>;+ readonly compactions: ReadonlyArray<Compaction>;+ /** First byte not consumed: where the next read of this shard resumes. */+ readonly nextOffset: number;+ /** Bytes after `nextOffset` held back for a retry (an incomplete or unverified last line). */+ readonly pendingTailBytes: number;+ /** Size of the shard when it was read. */+ readonly size: number;+}++export interface ReadShardOptions {+ /** Byte offset to start from (default 0); must be the start of a line. */+ readonly offset?: number;+ /**+ * The shard's partition directory, to resolve blob references (without it+ * blob bodies stay pending) and to refuse a shard reached through a linked+ * folder below it.+ */+ readonly partitionRoot?: string;+}++const NEWLINE = 0x0a;++/** Bytes read from a shard per call. */+const READ_CHUNK_BYTES = 1024 * 1024;++function isPaths(value: unknown): value is string[] {+ return Array.isArray(value) && value.every((item) => typeof item === "string" && item.length > 0);+}++function asCompaction(record: StoreRecord): Compaction | null {+ const { replaces, into } = record.body as { replaces?: unknown; into?: unknown };+ if (!isPaths(replaces) || !isPaths(into)) return null;+ return { id: record.id, replaces, into };+}++function isPlainObject(value: unknown): value is Record<string, unknown> {+ return typeof value === "object" && value !== null && !Array.isArray(value);+}++/** Outcome of {@link readBlobBody}. */+export type BlobBodyRead =+ | { readonly status: "ok"; readonly body: RecordBody }+ /** Absent, or not (yet) hashing to its name: a sync tool may still deliver it. */+ | { readonly status: "pending" }+ /** Hashes to its name but is not the record's body; it can never change. */+ | { readonly status: "invalid"; readonly reason: string };++/**+ * The body a blob reference points at: blob `sum` in the partition at+ * `partitionRoot`, parsed and checked to be the canonical JSON of a plain+ * object whose checksum is `sum`. `bytes`, when given, is the length the+ * reference promises. Never throws for what the blob holds.+ */+export function readBlobBody(partitionRoot: string, sum: string, bytes?: number): BlobBodyRead {+ const blob = readBlob(partitionRoot, sum, bytes);+ if (blob.status !== "ok") return { status: "pending" };+ let parsed: unknown;+ try {+ parsed = JSON.parse(blob.text);+ } catch {+ return { status: "invalid", reason: `blob ${sum} is not valid JSON` };+ }+ if (!isPlainObject(parsed) || BLOB_REF_KEY in parsed) {+ return { status: "invalid", reason: `blob ${sum} does not hold a record body (a JSON object)` };+ }+ // Before the checksum: its canonical JSON walks the body recursively.+ if (bodyTooDeep(parsed))+ return { status: "invalid", reason: `blob ${sum}: ${BODY_TOO_DEEP_REASON}` };+ if (bodyChecksum(parsed) !== sum) {+ return { status: "invalid", reason: `blob ${sum} does not hold the canonical JSON of a body` };+ }+ return { status: "ok", body: parsed };+}++function resolveBody(+ record: StoreRecord,+ partitionRoot: string | undefined,+): "inline" | "pending" | { readonly body: RecordBody } | { readonly invalid: string } {+ if (!isBlobRef(record.body)) return "inline";+ if (partitionRoot === undefined) return "pending";+ const read = readBlobBody(+ partitionRoot,+ record.body[BLOB_REF_KEY] as string,+ record.body[BLOB_REF_BYTES_KEY] as number,+ );+ if (read.status === "ok") return { body: read.body };+ if (read.status === "invalid") return { invalid: read.reason };+ return "pending";+}++/**+ * The device a shard path belongs to: its parent directory, when the path+ * has the shard shape (`<device>/<YYYY-MM>[.<suffix>].jsonl`). `null` for+ * any other path, which is then not checked.+ */+function shardDeviceOf(path: string): string | null {+ if (!isShardFileName(basename(path))) return null;+ const device = basename(dirname(path));+ return isValidDeviceId(device) ? device : null;+}++/** What one complete line turned out to be. */+type LineOutcome =+ | { readonly kind: "record"; readonly record: ReadRecord; readonly compaction: Compaction | null }+ | { readonly kind: "skip" }+ | { readonly kind: "diagnostic"; readonly diagnostic: ShardDiagnostic }+ | { readonly kind: "hold" };++function readLine(+ text: string,+ lineOffset: number,+ length: number,+ isLast: boolean,+ shardDevice: string | null,+ partitionRoot: string | undefined,+): LineOutcome {+ if (text.trim() === "") return { kind: "skip" };+ let check: ReturnType<typeof verifyEnvelope>;+ try {+ check = verifyEnvelope(JSON.parse(text));+ } catch {+ check = { ok: false, reason: "line is not valid JSON" };+ }+ const corrupt = (reason: string): LineOutcome => ({+ kind: "diagnostic",+ diagnostic: { kind: "corrupt-line", offset: lineOffset, reason },+ });+ if (!check.ok) {+ if (check.unknownVersion !== undefined) {+ return {+ kind: "diagnostic",+ diagnostic: { kind: "unknown-version", offset: lineOffset, reason: check.reason },+ };+ }+ // An unverified last line may still be arriving: retry it later.+ return isLast ? { kind: "hold" } : corrupt(check.reason);+ }+ let record = check.record;+ if (shardDevice !== null && record.device !== shardDevice) {+ return corrupt(+ `record device "${record.device}" is not the device "${shardDevice}" whose shard it is in`,+ );+ }+ const body = resolveBody(record, partitionRoot);+ let bodyState: BodyState;+ if (typeof body === "string") bodyState = body;+ else if ("invalid" in body) return corrupt(body.invalid);+ else {+ record = { ...record, body: body.body };+ bodyState = "blob";+ }+ const compaction =+ record.kind === COMPACTED_KIND && bodyState !== "pending" ? asCompaction(record) : null;+ return { kind: "record", record: { record, bodyState, offset: lineOffset, length }, compaction };+}++/** Read and verify the shard at `path` from `options.offset`. */+export function readShard(path: string, options: ReadShardOptions = {}): ShardRead {+ const start = options.offset ?? 0;+ const records: ReadRecord[] = [];+ const diagnostics: ShardDiagnostic[] = [];+ const compactions: Compaction[] = [];+ const shardDevice = shardDeviceOf(path);+ // The same guard as a blob read: a symlink or a FIFO a sync peer swaps+ // in under the name after the listing is never followed or blocked on.+ // With the partition known, a shard reached through a linked folder+ // below it is refused the same way.+ const fd = openRegularFileForRead(path, options.partitionRoot);+ if (fd === null) {+ diagnostics.push({+ kind: "not-a-file",+ offset: start,+ reason:+ "the shard is not a regular file (a symbolic link or a special file) or is reached " ++ "through a linked folder inside the partition; it is not read",+ });+ // Nothing was read past `start`, so the size says the same as the offset.+ return {+ records,+ diagnostics,+ compactions,+ nextOffset: start,+ pendingTailBytes: 0,+ size: start,+ };+ }+ try {+ const size = fstatSync(fd).size;+ if (start > size) {+ diagnostics.push({+ kind: "offset-past-end",+ offset: start,+ reason: `offset ${start} is past the end of the shard (${size} bytes); the shard was truncated or replaced`,+ });+ return { records, diagnostics, compactions, nextOffset: start, pendingTailBytes: 0, size };+ }+ const chunk = Buffer.alloc(Math.min(READ_CHUNK_BYTES, Math.max(size - start, 1)));+ /** First byte not consumed. */+ let consumed = start;+ /** File offset just past the bytes read so far. */+ let position = start;+ /** Bytes of the current line read so far (its start is `consumed`). */+ let carry: Buffer[] = [];+ let carried = 0;+ /** Inside a run longer than the cap: discard up to the next newline. */+ let oversized = false;+ const overlong = (): void => {+ diagnostics.push({+ kind: "corrupt-line",+ offset: consumed,+ reason: `line is longer than the ${STORE_LINE_CAP_BYTES}-byte line-size cap`,+ });+ };+ let held = false;+ while (!held && position < size) {+ const n = readSync(fd, chunk, 0, Math.min(chunk.length, size - position), position);+ if (n === 0) break;+ const base = position;+ position += n;+ let cursor = 0;+ while (cursor < n) {+ const end = chunk.subarray(0, n).indexOf(NEWLINE, cursor);+ if (end === -1) {+ if (!oversized) {+ carry.push(Buffer.from(chunk.subarray(cursor, n)));+ carried += n - cursor;+ if (carried >= STORE_LINE_CAP_BYTES) {+ oversized = true;+ carry = [];+ carried = 0;+ }+ }+ break;+ }+ const lineEnd = base + end + 1;+ if (oversized) {+ overlong();+ oversized = false;+ } else if (carried + (end - cursor) + 1 > STORE_LINE_CAP_BYTES) {+ overlong();+ } else {+ carry.push(chunk.subarray(cursor, end));+ const text = Buffer.concat(carry).toString("utf8");+ const outcome = readLine(+ text,+ consumed,+ lineEnd - consumed,+ lineEnd === size,+ shardDevice,+ options.partitionRoot,+ );+ if (outcome.kind === "hold") {+ held = true;+ break;+ }+ if (outcome.kind === "diagnostic") diagnostics.push(outcome.diagnostic);+ if (outcome.kind === "record") {+ records.push(outcome.record);+ if (outcome.compaction !== null) compactions.push(outcome.compaction);+ }+ }+ carry = [];+ carried = 0;+ consumed = lineEnd;+ cursor = end + 1;+ }+ }+ // A run past the cap that reaches the end of the shard is no record+ // either; holding it back would re-read it on every pass.+ if (!held && oversized) {+ overlong();+ consumed = position;+ }+ return {+ records,+ diagnostics,+ compactions,+ nextOffset: consumed,+ pendingTailBytes: size - consumed,+ size,+ };+ } finally {+ closeSync(fd);+ }+}++/**+ * The partition-relative paths of every shard the given compactions+ * replaced. A known shard that has disappeared and is in this set was+ * compacted away, not lost.+ */+export function replacedShards(compactions: Iterable<Compaction>): ReadonlySet<string> {+ const out = new Set<string>();+ for (const compaction of compactions) for (const rel of compaction.replaces) out.add(rel);+ return out;+}++/** How a shard that a caller knew about but can no longer find is to be read. */+export function classifyMissingShard(+ rel: string,+ replaced: ReadonlySet<string>,+): "replaced" | "missing" {+ return replaced.has(rel) ? "replaced" : "missing";+}diff --git a/src/core/store/reference-privacy.ts b/src/core/store/reference-privacy.tsnew file mode 100644index 00000000..72566940--- /dev/null+++ b/src/core/store/reference-privacy.ts@@ -0,0 +1,176 @@+/**+ * The partition of a dual-written record that names pages rather than+ * being one: a Brain log event names preferences and other pages through+ * ids and wikilinks, and a truth claim names the page it was taken from.+ * A record that names a private page goes to `private` only. On a machine+ * without that partition the appender refuses it and the refusal is+ * counted, so a private page's id, principle or facts never reach+ * `shared`, the partition every machine syncs.+ *+ * Every page is judged by {@link isPrivatePageFile}, the rule every other+ * brain dual-write site uses: a page that exists but cannot be read counts+ * as private. A reference that can only mean a page fails closed when it+ * resolves to none, because a page that is not there cannot be judged:+ *+ * - a preference id (`pref-<slug>` or `ret-<slug>`, bare or as a link)+ * with neither its active nor its retired page on disk;+ * - a claim source written as a wikilink or a `.md` path that names no+ * file in the vault.+ *+ * Any other string a log event carries (an artifact such as+ * `[[src/cli/main.ts:120-145]]`, a log shard link, free text) is resolved+ * by the reference reader the log's per-reader views use+ * (`brain/artifact-ref-resolve.ts`): when it names a page, that page is+ * judged, and when it names none it names nothing private. A claim source+ * that is neither a wikilink nor a `.md` path (a URL, free text) is judged+ * only when it names a file.+ */++import { existsSync, statSync } from "node:fs";+import { resolve } from "node:path";++import { resolveArtifactRef } from "../brain/artifact-ref-resolve.ts";+import { resolveNotePath } from "../brain/note-path.ts";+import { preferencePath, retiredPath } from "../brain/paths.ts";+import { extractId } from "../brain/temporal/period-common.ts";+import { pathIsInside } from "../path-safety.ts";+import { extractWikilinks } from "../vault.ts";+import {+ ANCHORED_WIKILINK_RE,+ stripBrainIdPrefix,+ stripWikilinkDecoration,+} from "../brain/wikilink.ts";+import { isPrivatePageFile } from "./dual-write-records.ts";+import { rowStrings, textCarriesPrivateRegion } from "./private-region.ts";++/** Extension of a vault page. */+const PAGE_EXTENSION = ".md";++/**+ * Whether the preference `id` names is private: its active or retired page+ * is, or neither page is on disk (it cannot be judged).+ */+function preferenceIdIsPrivate(vault: string, id: string): boolean {+ let paths: string[];+ try {+ const slug = stripBrainIdPrefix(id);+ paths = [preferencePath(vault, slug), retiredPath(vault, slug)].filter((p) => existsSync(p));+ } catch {+ return true; // a slug no page can carry: nothing to judge+ }+ return paths.length === 0 || paths.some((p) => isPrivatePageFile(p));+}++/**+ * Whether a Brain log event names a private page, given the references it+ * carries (`logEntryArtifactRefs` in `brain/log.ts`, which passes them so+ * this module needs no import of the log). `guessed` is the preference a+ * reconcile event's topic would be: a guess from the topic name, not a+ * reference the event carries, so it is judged only when its page exists.+ * Read only when dual writes are on; see the module docblock for the rule.+ */+export function logRefsNamePrivatePage(+ vault: string,+ refs: ReadonlyArray<string | undefined>,+ guessed?: string,+): boolean {+ // Only the guess itself is spared the missing-page rule: the same id+ // written into the event's body is a reference it carries, judged like+ // any other.+ let guessSpared = guessed === undefined;+ for (const ref of refs) {+ if (ref === undefined || ref === "") continue;+ const isGuess = !guessSpared && ref === guessed;+ if (isGuess) guessSpared = true;+ const id = extractId(ref);+ if (id !== undefined && !isGuess && preferenceIdIsPrivate(vault, id)) return true;+ const rel = resolveArtifactRef(vault, ref);+ if (rel === null) continue;+ // A path outside the vault names no page anyone may be shown. `resolve`,+ // not `join`: a relative path stays under the vault either way, and an+ // absolute one is judged where it is rather than glued onto the vault.+ const abs = resolve(vault, rel);+ if (!pathIsInside(abs, vault) || (existsSync(abs) && isPrivatePageFile(abs))) return true;+ }+ return false;+}++/**+ * Whether a truth claim's source is a private page. The source resolves+ * the way the claim ledger resolves it for its validity window+ * (`brain/truth/store.ts`): the wikilink body or the string as given,+ * tried as is and then with `.md`, inside the vault only.+ */+export function claimSourceIsPrivate(vault: string, source: string): boolean {+ const trimmed = source.trim();+ const anchored = ANCHORED_WIKILINK_RE.exec(trimmed);+ const target = stripWikilinkDecoration(anchored !== null ? anchored[1]! : trimmed);+ if (target === "") return false;+ const pageRef = anchored !== null || target.endsWith(PAGE_EXTENSION);+ const id = extractId(target);+ if (id !== undefined) return preferenceIdIsPrivate(vault, id);+ const candidates = target.endsWith(PAGE_EXTENSION) ? [target] : [target, target + PAGE_EXTENSION];+ for (const candidate of candidates) {+ let path: string;+ try {+ path = resolveNotePath(vault, candidate, { mustExist: false });+ } catch {+ // Outside the vault: no page anyone may be shown.+ return pageRef;+ }+ try {+ if (!statSync(path).isFile()) continue;+ } catch {+ continue;+ }+ return isPrivatePageFile(path);+ }+ return pageRef;+}++/**+ * Whether a pinned-context text must stay out of `shared`: it carries a+ * `<private>` region or the placeholder a stripped one leaves (the pinned+ * writer strips regions before it writes, as continuity does), or one of+ * its wikilinks names a private page (judged as a log event's references+ * are, {@link logRefsNamePrivatePage}).+ */+export function pinnedTextIsPrivate(vault: string, text: string): boolean {+ if (textCarriesPrivateRegion(text)) return true;+ return logRefsNamePrivatePage(+ vault,+ extractWikilinks(text).map((target) => `[[${target}]]`),+ );+}++/**+ * Whether a ledger row names a private page, so its store copy goes to+ * `private` only. Every string the row carries, at any depth, is checked+ * for a `<private>` region or the placeholder a stripped one leaves. Every+ * string outside an `opaque` field is also judged as a reference: a+ * wikilink inside free text, and the string itself as a preference id, a+ * page path or an artifact id, by the rules of {@link pinnedTextIsPrivate}+ * and {@link logRefsNamePrivatePage}. A preference id whose page is not on+ * disk cannot be judged and counts as private, as does a path outside the+ * vault.+ *+ * `opaque` names the fields whose values are not references at any depth:+ * a client's idempotency key, a payload hash, a timestamp, an allocated+ * id. Such a value is chosen by a client or a hash function, not written+ * to name a page, so a key spelled `pref-unused` names no preference and+ * cannot make an open item's row private. Read only when dual writes are+ * on.+ */+export function rowNamesPrivatePage(+ vault: string,+ row: unknown,+ opaque: ReadonlySet<string> = new Set(),+): boolean {+ const strings = rowStrings(row, opaque);+ if (strings === null) return true;+ return (+ strings.texts.some(textCarriesPrivateRegion) ||+ strings.references.some((text) => pinnedTextIsPrivate(vault, text)) ||+ logRefsNamePrivatePage(vault, strings.references)+ );+}diff --git a/src/core/store/safe-fs.ts b/src/core/store/safe-fs.tsnew file mode 100644index 00000000..485b45b7--- /dev/null+++ b/src/core/store/safe-fs.ts@@ -0,0 +1,217 @@+/**+ * Symlink-safe directories and files inside a partition of the brain store.+ *+ * A partition is a sync folder: anything a peer or the sync tool delivers+ * lands in it, symlinks included (Syncthing replicates them on POSIX+ * hosts). A writer that followed such a link would append a record line,+ * or create a blob, wherever the link points, outside the store. So every+ * write goes through here:+ *+ * - {@link ensureStoreDir} walks from the partition folder to the target+ * directory one component at a time with `lstat`, creates what is+ * missing with mode `0700`, and refuses a component that is a symlink+ * (on Windows `lstat` reports junctions and other name-surrogate+ * reparse points the same way) or not a directory. The partition folder+ * itself is the user's choice and may be a link.+ * - {@link openShardForAppend} refuses a shard name that is a symlink,+ * opens it with `O_NOFOLLOW` where the platform has it (elsewhere it+ * checks after the open that the name is still that file and no link;+ * mode `0600` for a new shard), and checks the open file: a regular+ * file with one link.+ * A hard link would let a peer's file and a file outside the store be+ * the same file.+ *+ * Every refusal is a {@link StoreUnsafePathError} naming the path; the+ * dual write counts it as a failure and keeps the legacy write.+ */++import {+ closeSync,+ constants,+ fstatSync,+ lstatSync,+ mkdirSync,+ openSync,+ type Stats,+} from "node:fs";+import { dirname, isAbsolute, join, relative, sep } from "node:path";++/** Mode of every directory the store creates: the owner only. */+export const STORE_DIR_MODE = 0o700;++/** Mode of every file the store creates: the owner only. */+export const STORE_FILE_MODE = 0o600;++/** A path inside a partition that the store refuses to write through. */+export class StoreUnsafePathError extends Error {+ readonly path: string;++ constructor(path: string, why: string) {+ super(+ `refusing to write through ${path} in the brain store: it ${why}. ` ++ "Something other than Open Second Brain put it there (a sync peer, a restore, a manual " ++ "edit); remove it and let the store create the path again",+ );+ this.name = "StoreUnsafePathError";+ this.path = path;+ }+}++function errnoCode(err: unknown): string | undefined {+ return (err as NodeJS.ErrnoException | null)?.code;+}++/** `lstat`, or `null` when nothing is at `path`. */+function lstatOrNull(path: string): Stats | null {+ try {+ return lstatSync(path);+ } catch (err) {+ if (errnoCode(err) === "ENOENT") return null;+ throw err;+ }+}++function assertRealDirectory(path: string): void {+ const stat = lstatOrNull(path);+ if (stat === null) return;+ if (stat.isSymbolicLink()) throw new StoreUnsafePathError(path, "is a symbolic link");+ if (!stat.isDirectory()) throw new StoreUnsafePathError(path, "is not a directory");+}++/**+ * Make `dir` exist under `partitionRoot` without following any symlink+ * below the partition folder. `dir` must be `partitionRoot` or inside it.+ */+export function ensureStoreDir(partitionRoot: string, dir: string): void {+ const rel = relative(partitionRoot, dir);+ if (rel === ".." || rel.startsWith(`..${sep}`) || isAbsolute(rel)) {+ throw new StoreUnsafePathError(dir, "is outside the partition folder");+ }+ mkdirSync(partitionRoot, { recursive: true, mode: STORE_DIR_MODE });+ let current = partitionRoot;+ for (const part of rel === "" ? [] : rel.split(sep)) {+ current = join(current, part);+ assertRealDirectory(current);+ try {+ mkdirSync(current, { mode: STORE_DIR_MODE });+ } catch (err) {+ if (errnoCode(err) !== "EEXIST") throw err;+ }+ // Checked again after the create: another process may have won it.+ assertRealDirectory(current);+ }+}++/** `O_NOFOLLOW` where the platform defines it (not on Windows), else 0. */+export const NO_FOLLOW: number = (constants as { O_NOFOLLOW?: number }).O_NOFOLLOW ?? 0;++/** `O_NONBLOCK` where the platform defines it (not on Windows), else 0. */+const NON_BLOCK: number = (constants as { O_NONBLOCK?: number }).O_NONBLOCK ?? 0;++/**+ * Whether `dir` is `partitionRoot` or inside it and every directory below+ * the partition folder on the way to it is a real directory, by `lstat`:+ * no symbolic link, and on Windows no junction or other name-surrogate+ * reparse point. A missing component is not a directory. The partition+ * folder itself is the user's choice and may be a link.+ */+export function isRealDirBelowPartition(partitionRoot: string, dir: string): boolean {+ const rel = relative(partitionRoot, dir);+ if (rel === ".." || rel.startsWith(`..${sep}`) || isAbsolute(rel)) return false;+ let current = partitionRoot;+ for (const part of rel === "" ? [] : rel.split(sep)) {+ current = join(current, part);+ const stat = lstatOrNull(current);+ if (stat === null || stat.isSymbolicLink() || !stat.isDirectory()) return false;+ }+ return true;+}++/**+ * Open `path` read-only only when it is a regular file, or `null` when it+ * is not: a symlink is never followed (`O_NOFOLLOW` where defined; where+ * not, the `lstat` before the open and a check after it that the name is+ * still the opened file) and a FIFO swapped in after the+ * `lstat` is never blocked on (`O_NONBLOCK`, then `fstat`). A missing file+ * throws `ENOENT` as `openSync` does.+ *+ * With `partitionRoot`, the file must also have been reached without a+ * link at any directory below the partition folder+ * ({@link isRealDirBelowPartition}), checked after the open: a linked+ * stream or device folder a peer synced could otherwise hand the reader+ * another partition's records, or files outside the store, under this+ * partition's name.+ */+export function openRegularFileForRead(path: string, partitionRoot?: string): number | null {+ if (!lstatSync(path).isFile()) return null;+ let fd: number;+ try {+ fd = openSync(path, constants.O_RDONLY | NO_FOLLOW | NON_BLOCK);+ } catch (err) {+ if (errnoCode(err) === "ELOOP") return null;+ throw err;+ }+ let keep = false;+ try {+ const opened = fstatSync(fd);+ // Without O_NOFOLLOW (Windows) the open follows whatever is at the+ // name: a link swapped in after the lstat shows here.+ keep =+ opened.isFile() &&+ (NO_FOLLOW !== 0 || nameIsOpenedFile(path, opened)) &&+ (partitionRoot === undefined || isRealDirBelowPartition(partitionRoot, dirname(path)));+ } finally {+ if (!keep) closeSync(fd);+ }+ return keep ? fd : null;+}++/** Whether the name `path` still refers to the file `opened` describes, and is no link. */+function nameIsOpenedFile(path: string, opened: Stats): boolean {+ const now = lstatOrNull(path);+ return now !== null && !now.isSymbolicLink() && now.ino === opened.ino && now.dev === opened.dev;+}++/** The name `path` still refers to the file `opened` describes, and is no link. */+function assertNameIsOpenedFile(path: string, opened: Stats): void {+ const now = lstatOrNull(path);+ if (now === null) throw new StoreUnsafePathError(path, "was removed while it was opened");+ if (now.isSymbolicLink()) throw new StoreUnsafePathError(path, "is a symbolic link");+ if (now.ino !== opened.ino || now.dev !== opened.dev) {+ throw new StoreUnsafePathError(path, "was replaced while it was opened");+ }+}++/**+ * Open the shard at `path` for appending (read and append, created with+ * mode `0600` when new). Its directory must already have been made by+ * {@link ensureStoreDir}. Throws {@link StoreUnsafePathError} for a+ * symlink, a non-regular file or a file with more than one link.+ */+export function openShardForAppend(path: string): number {+ const before = lstatOrNull(path);+ if (before?.isSymbolicLink() === true) throw new StoreUnsafePathError(path, "is a symbolic link");+ let fd: number;+ try {+ fd = openSync(+ path,+ constants.O_RDWR | constants.O_APPEND | constants.O_CREAT | NO_FOLLOW,+ STORE_FILE_MODE,+ );+ } catch (err) {+ if (errnoCode(err) === "ELOOP") throw new StoreUnsafePathError(path, "is a symbolic link");+ throw err;+ }+ try {+ const stat = fstatSync(fd);+ if (!stat.isFile()) throw new StoreUnsafePathError(path, "is not a regular file");+ if (stat.nlink > 1) throw new StoreUnsafePathError(path, `has ${stat.nlink} hard links`);+ // Without O_NOFOLLOW (Windows) the open itself follows whatever is at+ // the name: a link swapped in after the first lstat shows here.+ if (NO_FOLLOW === 0) assertNameIsOpenedFile(path, stat);+ } catch (err) {+ closeSync(fd);+ throw err;+ }+ return fd;+}diff --git a/src/core/store/shard-list.ts b/src/core/store/shard-list.tsnew file mode 100644index 00000000..78d16e34--- /dev/null+++ b/src/core/store/shard-list.ts@@ -0,0 +1,85 @@+/**+ * Enumerate the shards of one stream in a partition (design D1).+ *+ * A shard is `<stream>[/<ledger>]/<device>/<YYYY-MM>[.<suffix>].jsonl`,+ * where the optional suffix names a compaction output. Every other entry+ * (a sync tool's conflict copy, a temp file, a stray directory) is not a+ * shard and is left out, so a reader never folds a half-merged copy.+ */++import { readdirSync, type Dirent } from "node:fs";+import { join, posix } from "node:path";++import { isValidDeviceId, isWindowsReservedDeviceId } from "../config.ts";+import { compareCodeUnits } from "./compare.ts";+import { STORE_SHARD_EXT } from "./constants.ts";+import { LEDGER_NAME_RE, type StreamRef } from "./store-paths.ts";++/** Shard file names: a month, an optional compaction suffix, the extension. */+export const SHARD_FILE_RE = new RegExp(+ `^\\d{4}-(0[1-9]|1[0-2])(\\.[a-z0-9][a-z0-9-]{0,39})?\\.${STORE_SHARD_EXT}$`,+);++/** Whether `name` is a shard file name (and not a sync tool's conflict copy). */+export function isShardFileName(name: string): boolean {+ return SHARD_FILE_RE.test(name) && !name.includes(".sync-conflict");+}++/**+ * Whether a device directory named `name` is read on `platform`: a valid+ * device id, and on Windows not a reserved name (`nul`, `con`, ...),+ * which there names a device rather than a directory. Such a directory+ * cannot exist on NTFS; one that does is skipped and the doctor reports+ * it. Elsewhere a reserved name is read like any other id.+ */+export function isReadableDeviceDir(+ name: string,+ platform: NodeJS.Platform = process.platform,+): boolean {+ return isValidDeviceId(name) && !(platform === "win32" && isWindowsReservedDeviceId(name));+}++export interface ShardEntry {+ readonly device: string;+ /** Path relative to the partition, `/`-separated. */+ readonly rel: string;+ /** Absolute path. */+ readonly path: string;+}++function entries(dir: string): Dirent[] {+ try {+ return readdirSync(dir, { withFileTypes: true });+ } catch (err) {+ if ((err as NodeJS.ErrnoException).code === "ENOENT") return [];+ throw err;+ }+}++/**+ * Every shard of `ref` in the partition at `partitionRoot`, sorted by+ * relative path. A shard name that is a symbolic link is listed too, as is+ * a shard under a stream or ledger folder that is a link: given the+ * partition, the reader refuses to read through either (`not-a-file`), and+ * listing them is what lets the doctor report them instead of passing over+ * them in silence. A device folder that is a link is no directory entry+ * here and is skipped.+ */+export function listShards(partitionRoot: string, ref: StreamRef): ShardEntry[] {+ const segments = ref.ledger === undefined ? [ref.stream] : [ref.stream, ref.ledger];+ if (ref.ledger !== undefined && !LEDGER_NAME_RE.test(ref.ledger)) return [];+ const streamDir = join(partitionRoot, ...segments);+ const out: ShardEntry[] = [];+ for (const deviceEntry of entries(streamDir)) {+ if (!deviceEntry.isDirectory() || !isReadableDeviceDir(deviceEntry.name)) continue;+ for (const file of entries(join(streamDir, deviceEntry.name))) {+ if (!(file.isFile() || file.isSymbolicLink()) || !isShardFileName(file.name)) continue;+ out.push({+ device: deviceEntry.name,+ rel: posix.join(...segments, deviceEntry.name, file.name),+ path: join(streamDir, deviceEntry.name, file.name),+ });+ }+ }+ return out.toSorted((a, b) => compareCodeUnits(a.rel, b.rel));+}diff --git a/src/core/store/state-digest-check.ts b/src/core/store/state-digest-check.tsnew file mode 100644index 00000000..d900147a--- /dev/null+++ b/src/core/store/state-digest-check.ts@@ -0,0 +1,73 @@+/**+ * The doctor-facing state digest check (design D6, task 1.7): read every+ * partition this machine holds and compare its digests.+ *+ * It never waits for anything: a partition this machine lacks is simply+ * not checked (no finding, no error), and devices that are offline only+ * ever show up as silent. Retire records come from the `shared`+ * partition's `settings` stream and apply to every partition's roster.+ *+ * The result is structured so doctor can render it; this module does not+ * format text or decide exit codes.+ */++import type { WallClock } from "./clock-store.ts";+import { DEVICE_RETIRE_KIND, STORE_PARTITIONS, type StorePartition } from "./constants.ts";+import type { StoreRecord } from "./envelope.ts";+import {+ compareDigests,+ type DigestComparison,+ type DigestFinding,+} from "./state-digest-compare.ts";+import { readPartition, type PartitionShard } from "./state-digest.ts";+import type { StoreHandle } from "./store-open.ts";+import { partitionDir } from "./store-paths.ts";++export interface StateDigestReport {+ /** One comparison per partition this machine holds, in partition order. */+ readonly partitions: ReadonlyArray<DigestComparison>;+ /** Partitions this machine does not hold, which were not checked. */+ readonly skipped: ReadonlyArray<StorePartition>;+ /** Every finding of every partition. */+ readonly findings: ReadonlyArray<DigestFinding>;+}++/**+ * Check the state digests of every partition `store` holds. A caller that+ * has already read the partitions passes them as `shards` (only those+ * partitions are checked), so the history is not read twice.+ */+export function checkStateDigests(+ store: Pick<StoreHandle, "root" | "partitions">,+ options: {+ readonly now?: WallClock;+ readonly shards?: ReadonlyMap<StorePartition, ReadonlyArray<PartitionShard>>;+ } = {},+): StateDigestReport {+ const nowMs = (options.now ?? (() => Date.now()))();+ const shards = new Map<StorePartition, ReadonlyArray<PartitionShard>>();+ for (const partition of STORE_PARTITIONS) {+ if (options.shards !== undefined) {+ const given = options.shards.get(partition);+ if (given !== undefined) shards.set(partition, given);+ } else if (store.partitions.has(partition)) {+ shards.set(partition, readPartition(partitionDir(store.root, partition)));+ }+ }+ const retireRecords: StoreRecord[] = (shards.get("shared") ?? [])+ .filter((shard) => shard.stream === "settings")+ .flatMap((shard) => shard.records)+ .filter((record) => record.kind === DEVICE_RETIRE_KIND);+ const partitions: DigestComparison[] = [];+ const skipped: StorePartition[] = [];+ for (const partition of STORE_PARTITIONS) {+ const own = shards.get(partition);+ if (own === undefined) {+ skipped.push(partition);+ continue;+ }+ const records = own.flatMap((shard) => shard.all);+ partitions.push(compareDigests({ partition, records, retireRecords, nowMs }));+ }+ return { partitions, skipped, findings: partitions.flatMap((p) => p.findings) };+}diff --git a/src/core/store/state-digest-compare.ts b/src/core/store/state-digest-compare.tsnew file mode 100644index 00000000..a342e4a2--- /dev/null+++ b/src/core/store/state-digest-compare.ts@@ -0,0 +1,216 @@+/**+ * The digest roster and comparison (design D6, task 1.7). Pure: the+ * caller reads the records, this module decides what doctor reports.+ *+ * - Roster: the devices with records in the partition during the last+ * 30 days, minus devices retired by a `device-retire` human record. A+ * retired device that writes again after its retire record (a reused+ * id, a machine brought back) is on the roster again.+ * - Silent: a roster device that has published no digest in the partition+ * for 7 days. A device first seen less than 7 days ago gets that much+ * grace before it is reported.+ * - Divergent: two devices whose latest digests over the SAME cut carry a+ * different hash for a fold. Digests over different cuts are never+ * compared, so an offline device, an idle device or a machine without+ * a partition can neither stall the check nor raise a false alarm; it+ * is at most reported as silent.+ *+ * Only digests from the last 7 days are compared, so a divergence that a+ * fixed release no longer produces stops being reported once its digests+ * age out.+ */++import {+ AUTHORITY_FIELD,+ DAY_MS,+ DEVICE_RETIRE_KIND,+ DIGEST_COMPARE_WINDOW_DAYS,+ DIGEST_ROSTER_WINDOW_DAYS,+ DIGEST_SILENCE_DAYS,+ STATE_DIGEST_FOLDS,+ STATE_DIGEST_KIND,+ type StateDigestFold,+ type StorePartition,+} from "./constants.ts";+import { isValidDeviceId } from "../config.ts";+import { compareRecords, type StoreRecord } from "./envelope.ts";+import { prepareRecords } from "./fold.ts";+import { parseHlc } from "./hlc.ts";+import type { DigestBody } from "./state-digest.ts";++const SHA256_RE = /^[0-9a-f]{64}$/;++const physical = (record: StoreRecord): number => parseHlc(record.hlc)!.physical;++/** A digest record whose body has the digest shape, or `null`. */+export function parseDigest(record: StoreRecord): DigestBody | null {+ if (record.kind !== STATE_DIGEST_KIND) return null;+ const body = record.body as Partial<Record<keyof DigestBody, unknown>>;+ if (typeof body.partition !== "string" || !Array.isArray(body.cut)) return null;+ if (typeof body.cut_hash !== "string" || !SHA256_RE.test(body.cut_hash)) return null;+ const folds = body.folds as Record<string, unknown> | undefined;+ if (typeof folds !== "object" || folds === null) return null;+ for (const fold of STATE_DIGEST_FOLDS) {+ if (typeof folds[fold] !== "string" || !SHA256_RE.test(folds[fold] as string)) return null;+ }+ return record.body as unknown as DigestBody;+}++export interface RosterDevice {+ readonly device: string;+ /** Physical time of its first and last record in the window. */+ readonly firstSeenMs: number;+ readonly lastSeenMs: number;+}++export interface Roster {+ readonly devices: ReadonlyArray<RosterDevice>;+ /** Devices with records in the window that a human retired. */+ readonly retired: ReadonlyArray<string>;+}++/**+ * The roster of a partition at `nowMs`. `retireRecords` are the+ * `device-retire` records to apply (they live in the `shared` partition's+ * `settings` stream, so the private partition's roster uses them too);+ * only those with `authority: "human"` count.+ */+export function computeRoster(+ partitionRecords: Iterable<StoreRecord>,+ retireRecords: Iterable<StoreRecord>,+ nowMs: number,+): Roster {+ const since = nowMs - DIGEST_ROSTER_WINDOW_DAYS * DAY_MS;+ const seen = new Map<string, { first: number; last: StoreRecord }>();+ const prepared = prepareRecords(partitionRecords);+ const all = [...prepared.records, ...prepared.pending].toSorted(compareRecords);+ for (const record of all) {+ const ms = physical(record);+ if (ms < since) continue;+ const entry = seen.get(record.device);+ if (entry === undefined) seen.set(record.device, { first: ms, last: record });+ else entry.last = record; // fold order: later records come later+ }+ const retiredAt = new Map<string, StoreRecord>();+ for (const record of prepareRecords(retireRecords).records) {+ if (record.kind !== DEVICE_RETIRE_KIND || record.body[AUTHORITY_FIELD] !== "human") continue;+ const device = record.body["device"];+ if (typeof device === "string" && isValidDeviceId(device)) retiredAt.set(device, record);+ }+ const devices: RosterDevice[] = [];+ const retired: string[] = [];+ for (const device of [...seen.keys()].toSorted()) {+ const { first, last } = seen.get(device)!;+ const retire = retiredAt.get(device);+ if (retire !== undefined && compareRecords(last, retire) < 0) {+ retired.push(device);+ continue;+ }+ devices.push({ device, firstSeenMs: first, lastSeenMs: physical(last) });+ }+ return { devices, retired };+}++export interface DivergentDevice {+ readonly device: string;+ readonly hash: string;+ /** Id of the digest record. */+ readonly digest: string;+}++export type DigestFinding =+ | {+ readonly kind: "divergent";+ readonly partition: StorePartition;+ readonly fold: StateDigestFold;+ readonly cutHash: string;+ readonly devices: ReadonlyArray<DivergentDevice>;+ }+ | {+ readonly kind: "silent";+ readonly partition: StorePartition;+ readonly device: string;+ /** Physical time of its last digest in the partition, `null` when it never published one. */+ readonly lastDigestMs: number | null;+ readonly lastRecordMs: number;+ };++export interface DigestComparison {+ readonly partition: StorePartition;+ readonly roster: Roster;+ /** Cuts that at least two devices published digests for, with those devices. */+ readonly comparedCuts: ReadonlyArray<{+ readonly cutHash: string;+ readonly devices: ReadonlyArray<string>;+ }>;+ readonly findings: ReadonlyArray<DigestFinding>;+}++export interface CompareDigestsInput {+ readonly partition: StorePartition;+ /** Every record read from the partition, digests included. */+ readonly records: ReadonlyArray<StoreRecord>;+ /** `device-retire` records (see {@link computeRoster}). */+ readonly retireRecords: ReadonlyArray<StoreRecord>;+ readonly nowMs: number;+}++/** Compare a partition's digests and report divergence and silence. */+export function compareDigests(input: CompareDigestsInput): DigestComparison {+ const { partition, nowMs } = input;+ const roster = computeRoster(input.records, input.retireRecords, nowMs);+ const digests = prepareRecords(input.records)+ .records.map((record) => ({ record, body: parseDigest(record) }))+ .filter((d): d is { record: StoreRecord; body: DigestBody } => d.body?.partition === partition);++ const lastDigest = new Map<string, number>();+ for (const { record } of digests) lastDigest.set(record.device, physical(record));++ // Latest digest per (cut, device) inside the comparison window.+ const since = nowMs - DIGEST_COMPARE_WINDOW_DAYS * DAY_MS;+ const byCut = new Map<string, Map<string, { record: StoreRecord; body: DigestBody }>>();+ for (const digest of digests) {+ if (physical(digest.record) < since) continue;+ const devices = byCut.get(digest.body.cut_hash) ?? new Map();+ devices.set(digest.record.device, digest); // fold order: the latest wins+ byCut.set(digest.body.cut_hash, devices);+ }++ const findings: DigestFinding[] = [];+ const comparedCuts: Array<{ cutHash: string; devices: string[] }> = [];+ for (const cutHash of [...byCut.keys()].toSorted()) {+ const devices = byCut.get(cutHash)!;+ if (devices.size < 2) continue;+ const names = [...devices.keys()].toSorted();+ comparedCuts.push({ cutHash, devices: names });+ for (const fold of STATE_DIGEST_FOLDS) {+ const hashes = new Set(names.map((device) => devices.get(device)!.body.folds[fold]));+ if (hashes.size < 2) continue;+ findings.push({+ kind: "divergent",+ partition,+ fold,+ cutHash,+ devices: names.map((device) => {+ const { record, body } = devices.get(device)!;+ return { device, hash: body.folds[fold], digest: record.id };+ }),+ });+ }+ }++ const silentSince = nowMs - DIGEST_SILENCE_DAYS * DAY_MS;+ for (const member of roster.devices) {+ const last = lastDigest.get(member.device) ?? null;+ if (last !== null && last >= silentSince) continue;+ if (member.firstSeenMs >= silentSince) continue; // still in its grace period+ findings.push({+ kind: "silent",+ partition,+ device: member.device,+ lastDigestMs: last,+ lastRecordMs: member.lastSeenMs,+ });+ }+ return { partition, roster, comparedCuts, findings };+}diff --git a/src/core/store/state-digest.ts b/src/core/store/state-digest.tsnew file mode 100644index 00000000..3047703a--- /dev/null+++ b/src/core/store/state-digest.ts@@ -0,0 +1,295 @@+/**+ * Per-partition state digests over explicit cuts (design D6, task 1.7):+ * the cut, the fold hashes, and publishing a digest record.+ *+ * A cut says exactly which records a digest covers: one entry per shard+ * this machine holds in the partition, excluding the `digests` stream, so+ * publishing a digest never changes the cut it is compared on:+ *+ * ```+ * { "shard": "<partition-relative path>", "count": <verified records>,+ * "last": "<id of the last record>", "pending": <records whose blob has not arrived> }+ * ```+ *+ * `pending` is part of the cut because a record whose body is still a+ * missing blob cannot be folded yet: two machines with the same records+ * but a blob present on only one of them have different cuts and are not+ * compared, rather than reported as divergent. Shards with no verified+ * record yet (only a torn first line) are left out.+ *+ * The digest hashes each fold (`STATE_DIGEST_FOLDS`) computed from exactly+ * the records in the cut: sha256 of the canonical JSON of the fold's+ * fingerprint. Two machines with identical cuts must have identical fold+ * hashes; `state-digest-compare.ts` reports when they do not.+ */++import { readdirSync } from "node:fs";+import { join } from "node:path";++import { canonicalJson, sha256Hex } from "../integrity/digest.ts";+import { compareCodeUnits } from "./compare.ts";+import { appendRecord, type AppendResult } from "./appender.ts";+import { observeClock, type WallClock } from "./clock-store.ts";+import {+ DAY_MS,+ LEDGER_STREAM,+ STATE_DIGEST_KIND,+ STORE_STREAMS,+ type StateDigestFold,+ type StorePartition,+ type StoreStream,+} from "./constants.ts";+import { compareRecords, type StoreRecord } from "./envelope.ts";+import { foldPinned, pinnedFingerprint } from "./fold-pinned.ts";+import { foldPreferences, preferencesFingerprint } from "./fold-preferences.ts";+import { foldSettings, settingsFingerprint } from "./fold-settings.ts";+import { parseHlc } from "./hlc.ts";+import { readShard } from "./reader.ts";+import { listShards } from "./shard-list.ts";+import type { StoreHandle } from "./store-open.ts";+import { LEDGER_NAME_RE, partitionDir, type StreamRef } from "./store-paths.ts";++/** The stream digests are published in, and which every cut leaves out. */+export const DIGEST_STREAM: StoreStream = "digests";++/** One shard as this machine has read it. */+export interface PartitionShard {+ /** Partition-relative path, `/`-separated. */+ readonly rel: string;+ readonly device: string;+ readonly stream: StoreStream;+ /** Records with a known body, in file order. */+ readonly records: ReadonlyArray<StoreRecord>;+ /** Records whose body is a blob that has not arrived yet, in file order. */+ readonly pending: ReadonlyArray<StoreRecord>;+ /** Every verified record, in file order (`records` and `pending` interleaved). */+ readonly all: ReadonlyArray<StoreRecord>;+ /** Bytes after the last verified line that the reader held back (a torn or unverified tail). */+ readonly heldTailBytes: number;+}++/** A shard {@link readPartition} could not read. */+export interface UnreadableShard {+ /** Partition-relative path, `/`-separated. */+ readonly rel: string;+ readonly path: string;+ readonly error: unknown;+}++export interface ReadPartitionOptions {+ /**+ * Called for a shard that cannot be read (a sync client's lock, a+ * permission). The shard is then left out and the others are still+ * read. Without it the first such error is thrown.+ */+ readonly onUnreadable?: (shard: UnreadableShard) => void;+}++export interface CutEntry {+ readonly shard: string;+ readonly count: number;+ readonly last: string;+ readonly pending: number;+}++/** Fold name to sha256. */+export type FoldHashes = { readonly [F in StateDigestFold]: string };++/** The body of a `state-digest` record. */+export interface DigestBody {+ readonly partition: StorePartition;+ readonly cut: ReadonlyArray<CutEntry>;+ readonly cut_hash: string;+ readonly folds: FoldHashes;+}++function ledgerNames(partitionRoot: string): string[] {+ try {+ return readdirSync(join(partitionRoot, LEDGER_STREAM), { withFileTypes: true })+ .filter((entry) => entry.isDirectory() && LEDGER_NAME_RE.test(entry.name))+ .map((entry) => entry.name)+ .toSorted();+ } catch (err) {+ if ((err as NodeJS.ErrnoException).code === "ENOENT") return [];+ throw err;+ }+}++function streamRefs(partitionRoot: string): Array<StreamRef & { stream: StoreStream }> {+ const refs: Array<StreamRef & { stream: StoreStream }> = [];+ for (const stream of STORE_STREAMS) {+ if (stream === LEDGER_STREAM) {+ for (const ledger of ledgerNames(partitionRoot)) refs.push({ stream, ledger });+ } else {+ refs.push({ stream });+ }+ }+ return refs;+}++/**+ * Read every shard of every stream in a partition (digests included),+ * sorted by relative path. Torn or unverified tails are held back by the+ * reader and are not part of this read; each shard says how many bytes it+ * held back.+ */+export function readPartition(+ partitionRoot: string,+ options: ReadPartitionOptions = {},+): PartitionShard[] {+ const out: PartitionShard[] = [];+ for (const ref of streamRefs(partitionRoot)) {+ for (const shard of listShards(partitionRoot, ref)) {+ let read: ReturnType<typeof readShard>;+ try {+ read = readShard(shard.path, { partitionRoot });+ } catch (error) {+ if (options.onUnreadable === undefined) throw error;+ options.onUnreadable({ rel: shard.rel, path: shard.path, error });+ continue;+ }+ // A link or special file under a shard name holds no record here; the+ // caller that asks hears of it rather than seeing an empty shard.+ const notAFile = read.diagnostics.find((d) => d.kind === "not-a-file");+ if (notAFile !== undefined && options.onUnreadable !== undefined) {+ options.onUnreadable({+ rel: shard.rel,+ path: shard.path,+ error: new Error(notAFile.reason),+ });+ continue;+ }+ const all = read.records.map((r) => r.record);+ out.push({+ rel: shard.rel,+ device: shard.device,+ stream: ref.stream,+ all,+ records: read.records.filter((r) => r.bodyState !== "pending").map((r) => r.record),+ pending: read.records.filter((r) => r.bodyState === "pending").map((r) => r.record),+ heldTailBytes: read.pendingTailBytes,+ });+ }+ }+ return out.toSorted((a, b) => compareCodeUnits(a.rel, b.rel));+}++/** The shards a cut covers: every stream but the digests. */+export function cutShards(shards: ReadonlyArray<PartitionShard>): PartitionShard[] {+ return shards.filter((shard) => shard.stream !== DIGEST_STREAM && shard.all.length > 0);+}++/** The cut of the given shards, sorted by shard path. */+export function computeCut(shards: ReadonlyArray<PartitionShard>): CutEntry[] {+ return cutShards(shards)+ .map((shard) => ({+ shard: shard.rel,+ count: shard.all.length,+ last: shard.all[shard.all.length - 1]!.id,+ pending: shard.pending.length,+ }))+ .toSorted((a, b) => compareCodeUnits(a.shard, b.shard));+}++/** sha256 of the canonical JSON of a cut: equal cuts, equal hashes. */+export function cutHash(cut: ReadonlyArray<CutEntry>): string {+ return sha256Hex(canonicalJson(cut));+}++const hash = (value: unknown): string => sha256Hex(canonicalJson(value));++/** The hash of each digested fold, computed from exactly `records`. */+export function foldHashes(records: ReadonlyArray<StoreRecord>): FoldHashes {+ return {+ preferences: hash(preferencesFingerprint(foldPreferences(records))),+ pinned: hash(pinnedFingerprint(foldPinned(records))),+ settings: hash(settingsFingerprint(foldSettings(records))),+ };+}++/** The digest body of a partition as read in `shards`. */+export function buildDigestBody(+ partition: StorePartition,+ shards: ReadonlyArray<PartitionShard>,+): DigestBody {+ const cut = computeCut(shards);+ const covered = cutShards(shards).flatMap((shard) => shard.records);+ return { partition, cut, cut_hash: cutHash(cut), folds: foldHashes(covered) };+}++export interface PublishDigestOptions {+ readonly partition: StorePartition;+ /** Agent identity written on the digest record. */+ readonly agent: string;+ readonly now?: WallClock;+ /**+ * Skip publishing when this device's latest digest in the partition has+ * the same cut and fold hashes and is younger than this (default one+ * day), so frequent catch-ups do not grow the digests stream while an+ * idle device still publishes often enough not to look silent.+ */+ readonly minIntervalMs?: number;+}++export type PublishDigestResult =+ | { readonly published: true; readonly body: DigestBody; readonly append: AppendResult }+ | { readonly published: false; readonly body: DigestBody; readonly reason: "unchanged" };++function latestOwnDigest(+ shards: ReadonlyArray<PartitionShard>,+ device: string,+): StoreRecord | null {+ const own = shards+ .filter((shard) => shard.stream === DIGEST_STREAM && shard.device === device)+ .flatMap((shard) => shard.records)+ .filter((record) => record.kind === STATE_DIGEST_KIND)+ .toSorted(compareRecords);+ return own.at(-1) ?? null;+}++/**+ * Catch up on a partition this machine holds and publish its digest as a+ * `state-digest` record in the partition's `digests` stream. The local+ * clock first observes every record read (receive rule), so the digest+ * orders after everything it covers.+ */+export function publishStateDigest(+ store: StoreHandle,+ options: PublishDigestOptions,+): PublishDigestResult {+ const now = options.now ?? (() => Date.now());+ const shards = readPartition(partitionDir(store.root, options.partition));+ const body = buildDigestBody(options.partition, shards);+ const latest = latestOwnDigest(shards, store.device);+ if (latest !== null) {+ const age = now() - parseHlc(latest.hlc)!.physical;+ const same =+ latest.body["cut_hash"] === body.cut_hash &&+ canonicalJson(latest.body["folds"]) === canonicalJson(body.folds);+ if (same && age < (options.minIntervalMs ?? DAY_MS)) {+ return { published: false, body, reason: "unchanged" };+ }+ }+ // The newest record by fold order: one linear scan, no sort.+ let newest: StoreRecord | undefined;+ for (const shard of shards) {+ for (const record of shard.all) {+ if (newest === undefined || compareRecords(record, newest) > 0) newest = record;+ }+ }+ if (newest !== undefined) {+ observeClock(store.deviceStateDir, store.device, parseHlc(newest.hlc)!, now);+ }+ const append = appendRecord(+ store,+ {+ partition: options.partition,+ stream: DIGEST_STREAM,+ kind: STATE_DIGEST_KIND,+ agent: options.agent,+ body: { ...body },+ },+ { now },+ );+ return { published: true, body, append };+}diff --git a/src/core/store/store-init.ts b/src/core/store/store-init.tsnew file mode 100644index 00000000..ae6d48ff--- /dev/null+++ b/src/core/store/store-init.ts@@ -0,0 +1,269 @@+/**+ * Create a brain store (`o2b store init`): the only code path that mints a+ * store id or writes an identity file.+ *+ * Writers never create a store. A store is created once, on one machine,+ * by an explicit command; every other machine receives its partitions+ * through sync. That rules out the race in which a second machine whose+ * sync has not delivered `shared/store.json` yet would mint a store id of+ * its own.+ *+ * Rules:+ *+ * - **Requested partitions.** Both partitions by default; a machine that+ * must not hold `private` (a server) asks for `shared` only.+ * - **One id.** The first requested partition's identity file is created+ * with an exclusive create, so two processes running init at once agree+ * on one id; every other partition adopts it.+ * - **Completion, never a second id.** When some requested partitions are+ * already held (an init that stopped half way, or a machine adding a+ * partition later), the missing ones are created with the held store id.+ * The identity file's content is fixed by the id, so a copy created here+ * and one delivered by sync are byte-identical.+ * - **Refusals.** Init refuses when every requested partition is already+ * held (the store exists), when the partitions belong to different+ * stores, and when a partition folder holds store files without its+ * identity file (a partial store: the identity has not been synced, or+ * was lost); it names what is missing rather than guessing an id.+ * - **Durable before success.** Every requested identity file is written+ * and flushed, and the result is read back, before init reports+ * success. The format document goes into the root and every requested+ * partition.+ */++import { closeSync, fsyncSync, openSync, readdirSync } from "node:fs";+import { join } from "node:path";++import { sleepSync } from "../fs-atomic.ts";+import { createFileOnce } from "./blobs.ts";+import {+ STORE_FORMAT_FILE,+ STORE_FORMAT_VERSION,+ STORE_IDENTITY_FILE,+ STORE_PARTITIONS,+ type StorePartition,+} from "./constants.ts";+import { writeFormatDoc } from "./format-doc.ts";+import { heldPartitions, readStoreId, StoreIdentityError, StoreOpenError } from "./store-open.ts";+import { partitionDir } from "./store-paths.ts";+import { newUlid } from "./ulid.ts";++export interface InitStoreOptions {+ readonly root: string;+ /** Partitions this machine holds (default: all of them). */+ readonly partitions?: ReadonlyArray<StorePartition>;+}++export interface InitStoreResult {+ /** `created`: a new store id; `completed`: missing partitions added to a held store. */+ readonly status: "created" | "completed";+ readonly root: string;+ readonly storeId: string;+ /** Partitions whose identity file this run wrote. */+ readonly created: ReadonlyArray<StorePartition>;+ /** Partitions held after this run. */+ readonly partitions: ReadonlyArray<StorePartition>;+}++/**+ * Why init refused: the store `exists`; a partition is `partial` (store+ * files without an identity file); the partitions are `mixed` (two store+ * ids); an identity file is `corrupt` (it holds no valid store id).+ */+export type StoreInitRefusalReason = "exists" | "partial" | "mixed" | "corrupt";++/** Init would not run; the message says why and what to do. */+export class StoreInitRefusal extends Error {+ constructor(+ readonly reason: StoreInitRefusalReason,+ message: string,+ ) {+ super(message);+ this.name = "StoreInitRefusal";+ }+}++/**+ * Entries of a partition folder that only a store writes: anything but the+ * format document and dot-prefixed names (temp files, sync tools' markers+ * such as `.stfolder`).+ */+function storeEntries(dir: string): string[] {+ let names: string[];+ try {+ names = readdirSync(dir);+ } catch (err) {+ if ((err as NodeJS.ErrnoException).code === "ENOENT") return [];+ throw err;+ }+ return names.filter((name) => name !== STORE_FORMAT_FILE && !name.startsWith("."));+}++/** Flush a file and, best effort, its folder entry. */+function flush(path: string, dir: string): void {+ // Opened read-write: Windows refuses fsync (FlushFileBuffers) on a read-only handle.+ const fd = openSync(path, "r+");+ try {+ fsyncSync(fd);+ } finally {+ closeSync(fd);+ }+ try {+ const dirFd = openSync(dir, "r");+ try {+ fsyncSync(dirFd);+ } finally {+ closeSync(dirFd);+ }+ } catch {+ // Windows cannot open a directory for fsync; NTFS journals the entry.+ }+}++/** How long the id of an identity file another init is still writing is waited for. */+const IDENTITY_READ_ATTEMPTS = 10;+const IDENTITY_READ_SLEEP_MS = 20;++/**+ * The id in an identity file another process created. Where the+ * filesystem has no hard links, that process creates the final name first+ * and writes into it, so the file may still be empty or half written: it+ * is read again for a short while before it counts as corrupt.+ */+function readWinnerId(dir: string): string {+ const path = join(dir, STORE_IDENTITY_FILE);+ for (let attempt = 1; ; attempt += 1) {+ try {+ const id = readStoreId(dir);+ if (id !== null) return id;+ if (attempt >= IDENTITY_READ_ATTEMPTS) {+ throw new StoreOpenError(`${path} vanished while init ran`);+ }+ } catch (err) {+ if (!(err instanceof StoreIdentityError)) throw err;+ if (attempt >= IDENTITY_READ_ATTEMPTS) {+ // The other init created the file and never wrote its id (it+ // stopped in between, on a filesystem without hard links). A+ // re-run alone would refuse the same file as corrupt.+ throw new StoreInitRefusal(+ "corrupt",+ `${path} was created by another store init but still holds no store id ` ++ `(${err.message}); that init may have stopped before writing it. If no init is ` ++ "running, remove the file and run `o2b store init` again",+ );+ }+ }+ sleepSync(IDENTITY_READ_SLEEP_MS);+ }+}++/**+ * Create `dir`'s identity file for `storeId`. Returns the id the file+ * holds afterwards and whether this call wrote it. The temp file goes into+ * the store root, which is never synced (FORMAT.md), so a crash cannot+ * leave it in a partition folder that sync copies to other machines.+ */+function createIdentity(+ root: string,+ dir: string,+ storeId: string,+): { readonly id: string; readonly won: boolean } {+ const path = join(dir, STORE_IDENTITY_FILE);+ const text = `${JSON.stringify({ store_id: storeId, format: STORE_FORMAT_VERSION })}\n`;+ // Another process that created it first wins: its id is the store's id.+ const won = createFileOnce(path, Buffer.from(text, "utf8"), { tempDir: root });+ if (!won) return { id: readWinnerId(dir), won };+ flush(path, dir);+ return { id: storeId, won };+}++function ordered(partitions: ReadonlyArray<StorePartition>): StorePartition[] {+ return STORE_PARTITIONS.filter((p) => partitions.includes(p));+}++/** Create the store at `options.root`, or complete a half-created one. */+export function initStore(options: InitStoreOptions): InitStoreResult {+ const { root } = options;+ const requested = ordered(options.partitions ?? STORE_PARTITIONS);+ if (requested.length === 0) {+ throw new TypeError("store init needs at least one partition");+ }++ let held: Set<StorePartition>;+ let heldId: string | null;+ try {+ ({ held, storeId: heldId } = heldPartitions(root));+ } catch (err) {+ if (err instanceof StoreIdentityError) throw new StoreInitRefusal("corrupt", err.message);+ if (err instanceof StoreOpenError) throw new StoreInitRefusal("mixed", err.message);+ throw err;+ }++ const missing = requested.filter((p) => !held.has(p));+ if (missing.length === 0) {+ throw new StoreInitRefusal(+ "exists",+ `a brain store already exists at ${root} (store id ${heldId}, partitions: ` ++ `${ordered([...held]).join(", ")}); nothing to create`,+ );+ }+ for (const partition of missing) {+ const dir = partitionDir(root, partition);+ const found = storeEntries(dir);+ if (found.length > 0) {+ throw new StoreInitRefusal(+ "partial",+ `${dir} holds store files (${found.slice(0, 3).join(", ")}) but no ` ++ `${STORE_IDENTITY_FILE}: the ${partition} partition's identity is missing. ` ++ "Let sync deliver it from a machine that holds the store, or restore it from a " ++ "backup; init does not guess the store id of existing records",+ );+ }+ }++ let storeId = heldId ?? newUlid();+ const created: StorePartition[] = [];+ for (const partition of missing) {+ let identity: { readonly id: string; readonly won: boolean };+ try {+ identity = createIdentity(root, partitionDir(root, partition), storeId);+ } catch (err) {+ // The winner's file still corrupt after the grace: the same refusal+ // the read of the held partitions above gives it.+ if (err instanceof StoreIdentityError) throw new StoreInitRefusal("corrupt", err.message);+ throw err;+ }+ const { id: winner, won } = identity;+ if (won) created.push(partition);+ if (heldId === null && partition === missing[0]) storeId = winner;+ else if (winner !== storeId) {+ throw new StoreInitRefusal(+ "mixed",+ `${partitionDir(root, partition)} was given store id ${winner} while init ran, ` ++ `but the store id is ${storeId}; keep one store per root`,+ );+ }+ }++ writeFormatDoc(root);+ for (const partition of requested) writeFormatDoc(partitionDir(root, partition));++ // Read back what is on disk before reporting success.+ const after = heldPartitions(root);+ const absent = requested.filter((p) => !after.held.has(p));+ if (after.storeId !== storeId || absent.length > 0) {+ throw new StoreOpenError(+ `store init at ${root} did not leave the expected store (id ${storeId}, missing: ` ++ `${absent.join(", ") || "none"}); run it again`,+ );+ }+ return {+ // `created` only when this run minted the id: an init that lost the+ // race for the first identity file completed the winner's store.+ status: heldId === null && created.includes(missing[0]!) ? "created" : "completed",+ root,+ storeId,+ created,+ partitions: ordered([...after.held]),+ };+}diff --git a/src/core/store/store-open.ts b/src/core/store/store-open.tsnew file mode 100644index 00000000..0c26111c--- /dev/null+++ b/src/core/store/store-open.ts@@ -0,0 +1,171 @@+/**+ * Open an existing brain store, and describe it as a {@link StoreHandle}+ * the appender and reader work through.+ *+ * A partition is held on this machine when its folder carries the store+ * identity file (`store.json`, `{ "store_id": <ulid>, "format": 1 }`).+ * Opening never creates a store or a partition: a store is created only by+ * `o2b store init` (`store-init.ts`). A root that holds no partition is+ * refused with {@link NoStoreError}, so a writer on a second machine whose+ * sync has not delivered the store yet cannot mint a store id of its own.+ * The format document of the root and of every held partition is+ * refreshed (never downgraded).+ *+ * Partitions of two different stores under one root are refused by name.+ */++import { readFileSync, statSync } from "node:fs";+import { join } from "node:path";++import { processDirsEnv, type PlatformDirsEnv } from "../platform-dirs.ts";+import { isUsableLocalDeviceId } from "../config.ts";+import { STORE_IDENTITY_FILE, STORE_PARTITIONS, type StorePartition } from "./constants.ts";+import { writeFormatDoc } from "./format-doc.ts";+import { deviceStateDirFor, partitionDir } from "./store-paths.ts";+import { isUlid } from "./ulid.ts";++/** An opened store, as one device sees it. */+export interface StoreHandle {+ /** The store root. */+ readonly root: string;+ /** The store id shared by every partition. */+ readonly storeId: string;+ /** This device's id; it names every shard this device writes. */+ readonly device: string;+ /** Device-local state directory: locks, the persisted clock. Never synced. */+ readonly deviceStateDir: string;+ /** Partitions this machine holds. */+ readonly partitions: ReadonlySet<StorePartition>;+}++export interface OpenStoreOptions {+ readonly root: string;+ readonly device: string;+ /** Platform source for the device-local directory (default: this process). */+ readonly dirs?: PlatformDirsEnv;+}++/** A store that cannot be opened as asked. */+export class StoreOpenError extends Error {+ constructor(message: string) {+ super(message);+ this.name = "StoreOpenError";+ }+}++/** The root holds no store yet; `o2b store init` creates one. */+export class NoStoreError extends StoreOpenError {+ constructor(readonly root: string) {+ super(+ `no brain store at ${root}: no partition holds ${STORE_IDENTITY_FILE}; ` ++ "run `o2b store init` to create one, or let sync deliver it from a machine that has it",+ );+ this.name = "NoStoreError";+ }+}++/** A partition's identity file exists but holds no valid store id (corrupt, or half written). */+export class StoreIdentityError extends StoreOpenError {+ constructor(message: string) {+ super(message);+ this.name = "StoreIdentityError";+ }+}++/** The store id in a partition's identity file; `null` when the partition is not held. */+export function readStoreId(dir: string): string | null {+ let text: string;+ try {+ text = readFileSync(join(dir, STORE_IDENTITY_FILE), "utf8");+ } catch (err) {+ if ((err as NodeJS.ErrnoException).code === "ENOENT") return null;+ throw err;+ }+ let parsed: { store_id?: unknown };+ try {+ parsed = JSON.parse(text) as { store_id?: unknown };+ } catch {+ throw new StoreIdentityError(`${join(dir, STORE_IDENTITY_FILE)} is not valid JSON`);+ }+ if (!isUlid(parsed.store_id)) {+ throw new StoreIdentityError(`${join(dir, STORE_IDENTITY_FILE)} carries no valid store_id`);+ }+ return parsed.store_id;+}++/**+ * The partitions under `root` that carry an identity file, and the one+ * store id they share. Throws {@link StoreOpenError} when they belong to+ * different stores. The one rule of which partitions count as held, for+ * the read-only open, the writing open and `store init`.+ */+export function heldPartitions(root: string): {+ held: Set<StorePartition>;+ storeId: string | null;+} {+ // A root that exists but is not a directory holds no store and never+ // will. Said here, because the partition reads below cannot: POSIX+ // answers them with ENOTDIR, but Windows answers ENOENT, which would+ // read as "no store yet, run init".+ if (statSync(root, { throwIfNoEntry: false })?.isDirectory() === false) {+ throw new StoreOpenError(+ `the brain store root ${root} is not a directory; move the file away or point ` ++ "the store root at a directory",+ );+ }+ const ids = new Map<StorePartition, string>();+ for (const partition of STORE_PARTITIONS) {+ const id = readStoreId(partitionDir(root, partition));+ if (id !== null) ids.set(partition, id);+ }+ if (new Set(ids.values()).size > 1) {+ throw new StoreOpenError(+ `the partitions under ${root} belong to different stores (${[...ids]+ .map(([p, id]) => `${p}: ${id}`)+ .join(", ")}); keep one store per root`,+ );+ }+ const first = ids.values().next();+ return { held: new Set(ids.keys()), storeId: first.done === true ? null : first.value };+}++/** What a read-only look at a store root finds. */+export interface StoreInspection {+ readonly root: string;+ readonly storeId: string;+ readonly partitions: ReadonlySet<StorePartition>;+}++/**+ * Look at the store at `root` without creating or refreshing anything:+ * `null` when no partition holds an identity file. Throws+ * {@link StoreOpenError} when the partitions belong to different stores.+ * For read-only callers (doctor); writers use {@link openStore}.+ */+export function inspectStore(root: string): StoreInspection | null {+ const { held, storeId } = heldPartitions(root);+ return storeId === null ? null : { root, storeId, partitions: held };+}++/** Open the store at `options.root`; throws {@link NoStoreError} when it holds none. */+export function openStore(options: OpenStoreOptions): StoreHandle {+ if (!isUsableLocalDeviceId(options.device)) {+ throw new StoreOpenError(+ `the brain store needs a device id, got "${options.device}"; set device_id in the machine ` ++ `config or O2B_DEVICE_ID to lowercase letters, digits and hyphens`,+ );+ }+ const { held, storeId } = heldPartitions(options.root);+ if (storeId === null) throw new NoStoreError(options.root);+ // The root copy is device-local (the root is never synced), so it is+ // refreshed like every partition copy.+ writeFormatDoc(options.root);+ for (const partition of held) writeFormatDoc(partitionDir(options.root, partition));+ return {+ root: options.root,+ storeId,+ device: options.device,+ deviceStateDir: deviceStateDirFor(storeId, options.dirs ?? processDirsEnv()),+ partitions: held,+ };+}diff --git a/src/core/store/store-paths.ts b/src/core/store/store-paths.tsnew file mode 100644index 00000000..e4a76ea4--- /dev/null+++ b/src/core/store/store-paths.ts@@ -0,0 +1,303 @@+/**+ * Where the brain store lives (design D1): the store root, its partitions,+ * shards and blobs, and the device-local state directory beside it.+ *+ * The store root comes from `OPEN_SECOND_BRAIN_STORE_ROOT`, then the+ * `store_root` machine-config key, then a per-user default under the+ * platform data directory (`platform-dirs.ts`). A root inside the+ * configured vault is refused with an error naming the setting that put it+ * there: the store exists precisely so that no Open Second Brain machine+ * file lives in the user's notes.+ *+ * The device-local state directory (locks, the persisted clock, later the+ * index and caches) is `<state root>/stores/<store id>`, outside the store+ * and never synced. Every resolver takes an injected platform source so+ * Windows paths can be tested from any host; the process forms read the+ * running process.+ */++import { realpathSync } from "node:fs";+import { homedir } from "node:os";+import { join, posix, win32 } from "node:path";++import { defaultConfigPath, discoverConfig, isValidDeviceId, resolveVault } from "../config.ts";+import {+ APP_DIR_NAME,+ dataBaseDir,+ processDirsEnv,+ stateBaseDir,+ type PlatformDirsEnv,+} from "../platform-dirs.ts";+import {+ DUAL_WRITE_STATUS_FILE,+ LEDGER_STREAM,+ STORE_BLOBS_DIR,+ STORE_DEFAULT_DIR,+ STORE_LOCKS_DIR,+ STORE_ROOT_CONFIG_KEY,+ STORE_ROOT_ENV,+ STORE_SHARD_EXT,+ STORE_STATE_DIR,+ type StorePartition,+ type StoreStream,+} from "./constants.ts";+import { isUlid } from "./ulid.ts";++/** Everything {@link resolveStoreRoot} reads, injected. */+export interface StoreRootSource extends PlatformDirsEnv {+ /** Parsed machine config (`key: value`). */+ readonly config: Readonly<Record<string, string>>;+ /** Path of the machine config file; relative values anchor to its directory. */+ readonly configPath: string;+ /** The configured vault, or `null` when none is configured. */+ readonly vault: string | null;+}++/** Which setting supplied the root. */+export type StoreRootOrigin = "env" | "config" | "default";++export interface ResolvedStoreRoot {+ readonly root: string;+ readonly origin: StoreRootOrigin;+}++/** A configured store root that sits inside the configured vault. */+export class StoreRootInsideVaultError extends Error {+ readonly root: string;+ readonly vault: string;+ readonly setting: string;+ readonly origin: StoreRootOrigin;++ constructor(root: string, vault: string, origin: StoreRootOrigin) {+ const setting =+ origin === "env"+ ? `the ${STORE_ROOT_ENV} environment variable`+ : origin === "config"+ ? `\`${STORE_ROOT_CONFIG_KEY}\` in the machine config`+ : "the default store root";+ const remedy =+ origin === "default"+ ? `set \`${STORE_ROOT_CONFIG_KEY}\` in the machine config to a directory outside the vault`+ : `change ${setting} to a directory outside the vault, or remove it to use the per-user default`;+ super(+ `the brain store root ${root} (from ${setting}) is inside the vault ${vault}; ` ++ `the store must live outside the vault: ${remedy}.`,+ );+ this.name = "StoreRootInsideVaultError";+ this.root = root;+ this.vault = vault;+ this.setting = setting;+ this.origin = origin;+ }+}++function pathsFor(platform: string): typeof posix {+ return platform === "win32" ? win32 : posix;+}++function expandHome(value: string, source: PlatformDirsEnv): string {+ const paths = pathsFor(source.platform);+ if (value === "~") return source.home;+ if (value.startsWith("~/") || (source.platform === "win32" && value.startsWith("~\\"))) {+ return paths.join(source.home, value.slice(2));+ }+ return value;+}++/**+ * The path with symlinks resolved as far as it exists, when the source+ * describes this host (a Windows source examined on Linux cannot be+ * resolved, and is compared as written).+ */+function resolveLinks(path: string, platform: string): string {+ if (platform !== process.platform) return path;+ const paths = pathsFor(platform);+ let head = path;+ const tail: string[] = [];+ for (;;) {+ try {+ return paths.join(realpathSync(head), ...tail.toReversed());+ } catch {+ const parent = paths.dirname(head);+ if (parent === head) return path;+ tail.push(paths.basename(head));+ head = parent;+ }+ }+}++/** Platforms whose default filesystems compare names without case (NTFS, APFS, HFS+). */+const CASE_INSENSITIVE_PLATFORMS: ReadonlySet<string> = new Set(["win32", "darwin"]);++/**+ * Whether `child` is `parent` or lies inside it, on `platform`'s path+ * rules. Case is folded where the default filesystem ignores it, so a+ * differently cased spelling of the vault still counts as the vault; on a+ * case-sensitive macOS volume that only errs towards "inside".+ */+export function isPathInside(child: string, parent: string, platform: string): boolean {+ const paths = pathsFor(platform);+ const fold = (p: string): string =>+ CASE_INSENSITIVE_PLATFORMS.has(platform) ? p.toLowerCase() : p;+ const rel = paths.relative(fold(paths.resolve(parent)), fold(paths.resolve(child)));+ // `..` only as a whole segment: `..store` is a child named "..store".+ const escapes = rel === ".." || rel.startsWith(`..${paths.sep}`);+ return rel === "" || (!escapes && !paths.isAbsolute(rel));+}++/**+ * Whether `child` lies inside `parent` as written or once symlinks are+ * resolved on both (macOS `/var` -> `/private/var`, a vault reached through+ * a linked folder). Every "store root inside the vault" check uses it, so+ * the resolver and the doctor cannot disagree.+ */+export function isPathInsideResolved(child: string, parent: string, platform: string): boolean {+ return (+ isPathInside(child, parent, platform) ||+ isPathInside(resolveLinks(child, platform), resolveLinks(parent, platform), platform)+ );+}++/** The per-user default store root: `<data base>/open-second-brain/store`. */+export function defaultStoreRoot(source: PlatformDirsEnv = processDirsEnv()): string {+ return pathsFor(source.platform).join(dataBaseDir(source), APP_DIR_NAME, STORE_DEFAULT_DIR);+}++/**+ * Resolve the store root from an injected source. Throws+ * {@link StoreRootInsideVaultError} when the root is the vault or inside it.+ */+export function resolveStoreRoot(source: StoreRootSource): ResolvedStoreRoot {+ const paths = pathsFor(source.platform);+ const env = source.env[STORE_ROOT_ENV]?.trim();+ const configured = source.config[STORE_ROOT_CONFIG_KEY]?.trim();+ let resolved: ResolvedStoreRoot;+ if (env) {+ resolved = { root: paths.resolve(expandHome(env, source)), origin: "env" };+ } else if (configured) {+ const expanded = expandHome(configured, source);+ const root = paths.isAbsolute(expanded)+ ? paths.normalize(expanded)+ : paths.resolve(paths.dirname(source.configPath), expanded);+ resolved = { root, origin: "config" };+ } else {+ resolved = { root: defaultStoreRoot(source), origin: "default" };+ }+ if (source.vault !== null && source.vault.trim() !== "") {+ const vault = expandHome(source.vault.trim(), source);+ if (isPathInsideResolved(resolved.root, vault, source.platform))+ throw new StoreRootInsideVaultError(resolved.root, vault, resolved.origin);+ }+ return resolved;+}++/**+ * The store root for this process: the environment, the machine config at+ * `configPath` (default: the resolved config path) and the configured vault.+ */+export function resolveConfiguredStoreRoot(configPath?: string): ResolvedStoreRoot {+ const path = configPath ?? defaultConfigPath();+ return resolveStoreRoot({+ platform: process.platform,+ home: homedir(),+ env: process.env,+ config: discoverConfig(path).data,+ configPath: path,+ vault: resolveVault(path),+ });+}++/** The device-local directory holding every store's state: `<state base>/open-second-brain/stores`. */+export function storesStateDir(source: PlatformDirsEnv = processDirsEnv()): string {+ return pathsFor(source.platform).join(stateBaseDir(source), APP_DIR_NAME, STORE_STATE_DIR);+}++/** The device-local state directory of store `storeId`: `<state base>/open-second-brain/stores/<id>`. */+export function deviceStateDirFor(+ storeId: string,+ source: PlatformDirsEnv = processDirsEnv(),+): string {+ if (!isUlid(storeId)) throw new Error(`store id "${storeId}" is not a ULID`);+ return pathsFor(source.platform).join(storesStateDir(source), storeId);+}++/**+ * The device-local dual-write status file (failure and skip counters):+ * `<state base>/open-second-brain/stores/dual-write.json`. It sits beside+ * the per-store directories because a failure may happen before any store+ * could be opened.+ */+export function dualWriteStatusPath(source: PlatformDirsEnv = processDirsEnv()): string {+ return pathsFor(source.platform).join(storesStateDir(source), DUAL_WRITE_STATUS_FILE);+}++/** Directory of one partition. */+export function partitionDir(root: string, partition: StorePartition): string {+ return join(root, partition);+}++/** A stream, with the ledger name the `ledgers` stream needs. */+export interface StreamRef {+ readonly stream: StoreStream;+ readonly ledger?: string;+}++/** Ledger names: lowercase words joined by hyphens. */+export const LEDGER_NAME_RE = /^[a-z0-9][a-z0-9-]{0,63}$/;++/** Months as `YYYY-MM`. */+export const SHARD_MONTH_RE = /^\d{4}-(0[1-9]|1[0-2])$/;++/** The UTC month (`YYYY-MM`) of a millisecond timestamp: the shard a record goes to. */+export function shardMonth(physicalMs: number): string {+ return new Date(physicalMs).toISOString().slice(0, 7);+}++function streamSegments(ref: StreamRef): string[] {+ if (ref.stream === LEDGER_STREAM) {+ if (ref.ledger === undefined || !LEDGER_NAME_RE.test(ref.ledger)) {+ throw new Error(`the ${LEDGER_STREAM} stream needs a ledger name matching ${LEDGER_NAME_RE}`);+ }+ return [ref.stream, ref.ledger];+ }+ if (ref.ledger !== undefined) throw new Error(`stream ${ref.stream} takes no ledger name`);+ return [ref.stream];+}++/**+ * The shard path relative to its partition, always with `/` separators:+ * the form records (the `compacted` marker) use to name a shard.+ */+export function shardRelPath(ref: StreamRef, device: string, month: string): string {+ if (!isValidDeviceId(device)) throw new Error(`"${device}" is not a valid device id`);+ if (!SHARD_MONTH_RE.test(month)) throw new Error(`"${month}" is not a YYYY-MM month`);+ return posix.join(...streamSegments(ref), device, `${month}.${STORE_SHARD_EXT}`);+}++/** Absolute shard path: `<root>/<partition>/<stream>[/<ledger>]/<device>/<YYYY-MM>.jsonl`. */+export function shardPath(+ root: string,+ partition: StorePartition,+ ref: StreamRef,+ device: string,+ month: string,+): string {+ return join(partitionDir(root, partition), ...shardRelPath(ref, device, month).split("/"));+}++const SHA256_RE = /^[0-9a-f]{64}$/;++/** Blob path inside a partition: `blobs/<sha[0:2]>/<sha>`. */+export function blobPath(partitionRoot: string, sha: string): string {+ if (!SHA256_RE.test(sha)) throw new Error(`"${sha}" is not a sha256 hex digest`);+ return join(partitionRoot, STORE_BLOBS_DIR, sha.slice(0, 2), sha);+}++/** Device-local lock target of one shard (the lock is `<target>.lock`, never in the store). */+export function shardLockTarget(+ deviceStateDir: string,+ partition: StorePartition,+ rel: string,+): string {+ return join(deviceStateDir, STORE_LOCKS_DIR, partition, ...rel.split("/"));+}diff --git a/src/core/store/ulid.ts b/src/core/store/ulid.tsnew file mode 100644index 00000000..c1cc6998--- /dev/null+++ b/src/core/store/ulid.ts@@ -0,0 +1,81 @@+/**+ * ULID record ids for the brain store (design D3).+ *+ * A ULID is 26 Crockford base32 characters: 48 bits of millisecond time+ * followed by 80 random bits, so ids sort by creation time as text and+ * never need coordination between machines. Ids issued by one process+ * within the same millisecond are made strictly increasing by adding one+ * to the previous random part (the monotonic variant of the spec). Record+ * order never rests on ids alone: they only break ties after the clock+ * and the device id.+ */++import { randomBytes } from "node:crypto";++const ALPHABET = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";+const TIME_CHARS = 10;+const RANDOM_CHARS = 16;+const ULID_RE = /^[0-7][0-9A-HJKMNP-TV-Z]{25}$/;+const MAX_TIME = 2 ** 48 - 1;++let lastTime = -1;+let lastRandom: number[] = [];++function encodeTime(time: number): string {+ let out = "";+ let rest = time;+ for (let i = 0; i < TIME_CHARS; i++) {+ out = ALPHABET[rest % 32]! + out;+ rest = Math.floor(rest / 32);+ }+ return out;+}++function freshRandom(): number[] {+ const bytes = randomBytes(RANDOM_CHARS);+ return Array.from(bytes, (byte) => byte % 32);+}++/** Add one to a base32 digit array; `false` when it overflowed. */+function increment(digits: number[]): boolean {+ for (let i = digits.length - 1; i >= 0; i--) {+ if (digits[i]! < 31) {+ digits[i]! += 1;+ return true;+ }+ digits[i] = 0;+ }+ return false;+}++/** A new ULID for time `nowMs` (default: the wall clock). */+export function newUlid(nowMs: number = Date.now()): string {+ const time = Math.min(MAX_TIME, Math.max(0, Math.floor(nowMs)));+ if (time === lastTime) {+ // Same millisecond: step the random part, so ids stay unique and+ // ordered within this process. An overflow (2^80 ids in one+ // millisecond) moves to the next millisecond.+ if (!increment(lastRandom)) {+ lastTime += 1;+ lastRandom = freshRandom();+ }+ } else {+ // A new (or an earlier) millisecond starts afresh; 80 random bits keep+ // ids unique when the clock steps back.+ lastTime = time;+ lastRandom = freshRandom();+ }+ return encodeTime(lastTime) + lastRandom.map((d) => ALPHABET[d]).join("");+}++/** Whether `value` is a canonical (uppercase) ULID. */+export function isUlid(value: unknown): value is string {+ return typeof value === "string" && ULID_RE.test(value);+}++/** The millisecond time encoded in a ULID. */+export function ulidTime(id: string): number {+ let time = 0;+ for (const ch of id.slice(0, TIME_CHARS)) time = time * 32 + ALPHABET.indexOf(ch);+ return time;+}diff --git a/src/mcp/brain-tools.ts b/src/mcp/brain-tools.tsindex f682f1ef..907bdc2d 100644--- a/src/mcp/brain-tools.ts+++ b/src/mcp/brain-tools.ts@@ -47,6 +47,7 @@ import { DECISIONS_TOOLS } from "./brain/decisions-tools.ts";import { TENSION_TOOLS } from "./brain/tension-tools.ts";import { STORAGE_TOOLS } from "./brain/storage-tools.ts";import { RECEIPT_TOOLS } from "./brain/receipt-tools.ts";+import { CHANGES_TOOLS } from "./brain/changes-tools.ts";import type { ToolDefinition } from "./tool-contract.ts";export { vaultRelativeSafe } from "./brain/shared.ts";@@ -93,4 +94,6 @@ export const BRAIN_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([// metrics receipt ledgers....STORAGE_TOOLS,...RECEIPT_TOOLS,+ // Brain store change probe (design D5): new record ids since a watermark.+ ...CHANGES_TOOLS,]);diff --git a/src/mcp/brain/changes-tools.ts b/src/mcp/brain/changes-tools.tsnew file mode 100644index 00000000..38cb3057--- /dev/null+++ b/src/mcp/brain/changes-tools.ts@@ -0,0 +1,118 @@+/**+ * `brain_changes`: the change probe over the brain store (design D5, task+ * 1.9). One builder serves both front doors, this tool and+ * `o2b brain changes --since <watermark>`; see+ * `../../core/search/brain-store/changes.ts` for the watermark contract.+ *+ * It is a cheap poll for agents and hooks: an index query after catch-up,+ * returning record ids only, never bodies. Below local reach it answers+ * nothing, by name: brain store records reach local callers only, the+ * same rule search applies to them (`isPathReadableAtReach`).+ */++import {+ brainChanges,+ CHANGES_DEFAULT_LIMIT,+ CHANGES_MAX_LIMIT,+ type BrainChanges,+} from "../../core/search/brain-store/changes.ts";+import { resolveSearchConfig } from "../../core/search/index.ts";+import { SearchError } from "../../core/search/types.ts";+import { TRANSPORT_REACH, type TransportReach } from "../../core/graph/transport-reach.ts";+import { coerceInt, coerceStr } from "../coerce.ts";+import { INVALID_PARAMS, MCPError } from "../protocol.ts";+import { contextReach, type ServerContext, type ToolDefinition } from "../tool-contract.ts";++/** The reason a probe below local reach names. */+export const CHANGES_REACH_REASON = "reach" as const;++/** The answer a caller below local reach receives. */+export interface BrainChangesRefusal {+ readonly measured: false;+ readonly reason: typeof CHANGES_REACH_REASON;+ readonly detail: string;+}++export type BrainChangesView = (BrainChanges & { readonly measured: true }) | BrainChangesRefusal;++export interface BuildBrainChangesOptions {+ readonly vault: string;+ readonly reach: TransportReach;+ readonly configPath?: string;+ readonly since?: string;+ readonly limit?: number;+}++/** Run the probe, or name the reach refusal. Throws `SearchError` for bad input. */+export async function buildBrainChanges(opts: BuildBrainChangesOptions): Promise<BrainChangesView> {+ if (opts.reach !== TRANSPORT_REACH.local) {+ return {+ measured: false,+ reason: CHANGES_REACH_REASON,+ detail: "brain store records are reported at local reach only",+ };+ }+ const config = resolveSearchConfig({+ vault: opts.vault,+ ...(opts.configPath !== undefined ? { configPath: opts.configPath } : {}),+ });+ const changes = await brainChanges(config, {+ ...(opts.since !== undefined ? { since: opts.since } : {}),+ ...(opts.limit !== undefined ? { limit: opts.limit } : {}),+ });+ return { measured: true, ...changes };+}++async function toolBrainChanges(+ ctx: ServerContext,+ args: Record<string, unknown>,+): Promise<Record<string, unknown>> {+ const since = coerceStr(args, "since", false) ?? undefined;+ const limit = coerceInt(args, "limit", CHANGES_DEFAULT_LIMIT, 1, CHANGES_MAX_LIMIT);+ try {+ const view = await buildBrainChanges({+ vault: ctx.vault,+ reach: contextReach(ctx),+ ...(ctx.configPath ? { configPath: ctx.configPath } : {}),+ ...(since !== undefined ? { since } : {}),+ limit,+ });+ return { ...view };+ } catch (e) {+ if (e instanceof SearchError && e.code === "INVALID_INPUT") {+ throw new MCPError(INVALID_PARAMS, `brain_changes: ${e.message}`);+ }+ throw e;+ }+}++export const CHANGES_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([+ {+ name: "brain_changes",+ kind: "read",+ description:+ "Change probe over the brain store: record ids new since a watermark, grouped by partition, stream, scope and topic, with the watermark to pass next. An index query after catch-up; ids only, no bodies. Local reach only.",+ inputSchema: {+ type: "object",+ properties: {+ since: {+ type: "string",+ maxLength: 64,+ description:+ "Watermark from an earlier brain_changes answer. Absent starts from the first record; one from a replaced index starts over with reset: true.",+ },+ limit: {+ type: "integer",+ minimum: 1,+ maximum: CHANGES_MAX_LIMIT,+ description: `Most record ids to return (default ${CHANGES_DEFAULT_LIMIT}). A cut page sets truncated: true; pass its watermark to read on.`,+ },+ },+ additionalProperties: false,+ },+ // No previewBudget: the answer is ids only, bounded by `limit`, and+ // it declares its own cut (`truncated` plus the watermark to pass+ // next). A head preview would drop the watermark, which sorts last.+ handler: toolBrainChanges,+ },+]);diff --git a/src/mcp/registry-guard.ts b/src/mcp/registry-guard.tsindex 287dc285..48139722 100644--- a/src/mcp/registry-guard.ts+++ b/src/mcp/registry-guard.ts@@ -405,6 +405,8 @@ export const PREVIEW_BUDGET_EXEMPT: Readonly<Record<string, string>> = Object.fr"bounded destination table: the handler caps the page at limit and total_matched reports " +"the pre-truncation count; the fold is recomputed per call, so a cursor pages one walk, " +"and the per-kind readers remain the full-record surface",+ brain_changes:+ "record ids only, bounded by limit; a cut page says truncated: true and carries the watermark to pass next, which a head preview would cut off",brain_context_presets: "small preset list",brain_pre_compact_extract: "bounded extract; host injects it whole by design",brain_skill_proposals: "bounded proposal list",diff --git a/tests/cli/brain-changes.test.ts b/tests/cli/brain-changes.test.tsnew file mode 100644index 00000000..f0ddfe10--- /dev/null+++ b/tests/cli/brain-changes.test.ts@@ -0,0 +1,99 @@+/**+ * `o2b brain changes [--since <watermark>]` (task 1.9): the CLI front+ * door of the change probe. The probe's semantics are covered in+ * `tests/core/search/brain-store-changes.test.ts`; this file covers the+ * verb: it finds the configured store, builds the index on first use, and+ * returns a neighbour's record under its topic and scope after the+ * watermark it printed.+ */+import { afterEach, beforeEach, expect, test } from "bun:test";+import { writeFileSync } from "node:fs";+import { join } from "node:path";++import { STORE_CATCH_UP_INTERVAL_ENV } from "../../src/core/search/brain-store/constants.ts";+import { appendRecord } from "../../src/core/store/appender.ts";+import { STORE_ROOT_ENV } from "../../src/core/store/constants.ts";+import {+ LOCAL_DEVICE,+ makeStoreIndexFixture,+ REMOTE_DEVICE,+ type StoreIndexFixture,+} from "../core/search/fixtures/brain-store-index.ts";+import { runCli } from "../helpers/run-cli.ts";++let fx: StoreIndexFixture;+let env: Record<string, string>;++beforeEach(() => {+ fx = makeStoreIndexFixture("osb-cli-changes-");+ fx.open(LOCAL_DEVICE);+ fx.writeNote("notes/a.md", "# A\n\nA note.\n");+ const configPath = join(fx.parent, "config.yaml");+ writeFileSync(configPath, `vault: ${fx.vault}\n`);+ const state = fx.dirs(LOCAL_DEVICE).env;+ env = {+ OPEN_SECOND_BRAIN_CONFIG: configPath,+ [STORE_ROOT_ENV]: fx.root,+ [STORE_CATCH_UP_INTERVAL_ENV]: "0",+ XDG_STATE_HOME: state["XDG_STATE_HOME"]!,+ LOCALAPPDATA: state["LOCALAPPDATA"]!,+ };+});+afterEach(() => fx.cleanup());++interface ChangesJson {+ measured: boolean;+ storeInUse: boolean;+ watermark: string;+ count: number;+ groups: Array<{ stream: string; scope: string | null; topic: string | null; ids: string[] }>;+}++async function changes(...args: string[]): Promise<ChangesJson> {+ const res = await runCli(["brain", "changes", "--vault", fx.vault, "--json", ...args], { env });+ expect(res.stderr).not.toContain("error");+ expect(res.returncode).toBe(0);+ return JSON.parse(res.stdout) as ChangesJson;+}++// The grouping itself is the core probe's (tests/core/search/brain-store-changes.test.ts);+// here the verb finds the configured store and the watermark round-trips.+test("returns a neighbour's record id after the watermark it printed", async () => {+ const neighbour = fx.open(REMOTE_DEVICE);+ const decide = (text: string) =>+ appendRecord(neighbour, {+ partition: "shared",+ stream: "events",+ kind: "decision",+ agent: "agent-b",+ body: { text },+ }).record;+ decide("an earlier decision");+ const first = await changes();+ expect(first).toMatchObject({ measured: true, storeInUse: true, count: 1 });++ const record = decide("pick the north bank");+ const after = await changes("--since", first.watermark);+ expect(after.count).toBe(1);+ expect(after.groups.flatMap((g) => g.ids)).toEqual([record.id]);+});++test("the text form ends with the watermark, and a bad one is refused", async () => {+ const text = await runCli(["brain", "changes", "--vault", fx.vault], { env });+ expect(text.returncode).toBe(0);+ expect(text.stdout).toMatch(/watermark: [0-9A-Z]{26}\.\d+\n$/);+ const bad = await runCli(["brain", "changes", "--vault", fx.vault, "--since", "yesterday"], {+ env,+ });+ expect(bad.returncode).not.toBe(0);+ expect(bad.stderr).toContain("not a watermark");+});++test.each(["1e3", "0x10", " 5 ", "2.0"])(+ "--limit %p is refused: only plain digits",+ async (raw) => {+ const res = await runCli(["brain", "changes", "--vault", fx.vault, "--limit", raw], { env });+ expect(res.returncode).not.toBe(0);+ expect(res.stderr).toContain("--limit must be an integer");+ },+);diff --git a/tests/cli/search-query-flags.test.ts b/tests/cli/search-query-flags.test.tsindex dcdb8482..1f534871 100644--- a/tests/cli/search-query-flags.test.ts+++ b/tests/cli/search-query-flags.test.ts@@ -56,6 +56,7 @@ const LEGACY_QUERY_FLAGS: Record<string, { type: string; default?: string }> = {"evidence-pack": { type: "boolean" },"include-superseded": { type: "boolean" },since: { type: "string" },+ source: { type: "string" },until: { type: "string" },global: { type: "boolean" },"no-record-access": { type: "boolean" },diff --git a/tests/core/architecture/append-shard-census.test.ts b/tests/core/architecture/append-shard-census.test.tsindex 742ea9c9..8d7abe54 100644--- a/tests/core/architecture/append-shard-census.test.ts+++ b/tests/core/architecture/append-shard-census.test.ts@@ -26,7 +26,9 @@** ## The append-mode forms*- * `appendFileSync(` / `appendFile(`; `openSync(` / `open(` whose second+ * `appendFileSync(` / `appendFile(`; `appendSeparated(` (the Brain log's+ * append primitive, which appends to whatever path its caller passes);+ * `openSync(` / `open(` whose second* argument is an `"a"` or `"a+"` literal; and any `flag:` / `flags:`* property set to one (the `writeFileSync(..., { flag: "a" })` and* `createWriteStream` spellings). Read off the shared source lexer, so a@@ -48,13 +50,17 @@ const SWEPT_ROOT = "src";/*** Functions whose result is a per-device shard name or the shard id- * itself: the shared grammar's builders, and the device-id resolver the- * older hand-rolled shard paths call directly.+ * itself: the shared grammar's builders, the device-id resolver the+ * older hand-rolled shard paths call directly, and the brain store's+ * shard path builder (`store/store-paths.ts`), whose+ * `<stream>/<device>/<YYYY-MM>.jsonl` names carry the device id as a+ * directory rather than a file-name segment.*/const SHARD_NAMING_PRIMITIVES: ReadonlyArray<string> = Object.freeze(["shardedFileName","resolveAppendShardId","resolveDeviceId",+ "shardRelPath",]);/** An allow-list reason has to be an argument, not a label. */@@ -71,6 +77,10 @@ const APPEND_ALLOW_LIST: Readonly<Record<string, string>> = Object.freeze({"src/core/brain/diagnostics.ts":"the doctor repair appends the terminal interrupted marker to a dangling per-run dream workrun " +"file, under a lock, and that file is unique to the run that created it",+ "src/core/brain/log-append-io.ts":+ "the Brain log's append primitive takes the path it appends to from its caller; every call of " ++ "appendSeparated is itself an append form this census checks, so each caller must name a " ++ "device shard (appendLogEvent builds them with logShardPath or logShardJsonlPath)","src/core/doctor.ts":"the config-writeable probe opens the machine config file in append mode and writes zero bytes; " +"it lives outside the vault, is not a ledger, and removes the file it created",@@ -99,6 +109,9 @@ const APPEND_MODE_LITERAL = /^(["'`])a\+?\1$/;const APPEND_SHAPES: ReadonlyArray<AppendShape> = Object.freeze<AppendShape[]>([{ form: "appendFile", pattern: /\bappendFile(?:Sync)?\s*\(/g, isAppend: () => true },+ // The Brain log's append primitive (`log-append-io.ts`) appends to the+ // path it is given, so each caller is an append site in its own right.+ { form: "appendSeparated", pattern: /\bappendSeparated\s*\(/g, isAppend: () => true },{form: 'open(..., "a")',pattern: /\bopen(?:Sync)?\s*\(/g,diff --git a/tests/core/architecture/snapshot-retention-census.test.ts b/tests/core/architecture/snapshot-retention-census.test.tsnew file mode 100644index 00000000..5fe365cc--- /dev/null+++ b/tests/core/architecture/snapshot-retention-census.test.ts@@ -0,0 +1,79 @@+/**+ * Every Brain snapshot obeys `snapshots.retention_count`.+ *+ * Retention is enforced in exactly one place: `takeSnapshot` in+ * `src/core/brain/snapshot-gate.ts` writes the archive and prunes around+ * it. A module that calls `createSnapshot` directly writes an archive no+ * prune ever follows, which is how upgrade archives once grew to 911+ * copies on a live install and how promote-host-memory archives escaped+ * retention until it was routed through the gate.+ *+ * So the direct callers are counted. `snapshot.ts` defines the function+ * and `snapshot-gate.ts` is the gate; any other module calling it fails+ * here until it goes through `takeSnapshot` (or `withDestructiveSnapshot`,+ * which calls it). The source is read through the shared lexer's code+ * view, so a call named in a comment or a string is not counted, and the+ * gate's own call is required to be found, so the census cannot pass over+ * a pattern that stopped matching.+ */++import { describe, expect, test } from "bun:test";+import { readFileSync, readdirSync } from "node:fs";+import { join, relative, resolve } from "node:path";++import { lexCode } from "../../helpers/source-lexer.ts";++const REPO_ROOT = resolve(import.meta.dir, "..", "..", "..");+const SRC_ROOT = join(REPO_ROOT, "src");++/** A call of `createSnapshot`, not its definition or a longer name. */+const DIRECT_CALL_RE = /(?<![\w.$])createSnapshot\s*\(/g;+const DEFINITION_RE = /function\s+createSnapshot\s*\(/g;++/** Modules allowed to call `createSnapshot` directly, with the reason. */+const ALLOWED: Readonly<Record<string, string>> = Object.freeze({+ "src/core/brain/snapshot.ts": "defines createSnapshot",+ "src/core/brain/snapshot-gate.ts": "takeSnapshot: the archive and the prune around it",+});++function sourceFiles(dir: string): string[] {+ const out: string[] = [];+ for (const entry of readdirSync(dir, { withFileTypes: true })) {+ const full = join(dir, entry.name);+ if (entry.isDirectory()) out.push(...sourceFiles(full));+ else if (/\.(?:ts|mts|cts|tsx)$/.test(entry.name)) out.push(full);+ }+ return out;+}++/** How many direct calls `text` makes, definitions excluded. */+function directCalls(text: string): number {+ const code = lexCode(text);+ const calls = code.match(DIRECT_CALL_RE)?.length ?? 0;+ const definitions = code.match(DEFINITION_RE)?.length ?? 0;+ return calls - definitions;+}++describe("snapshot retention census", () => {+ const callers = sourceFiles(SRC_ROOT)+ .map((path) => ({+ rel: relative(REPO_ROOT, path).split("\\").join("/"),+ calls: directCalls(readFileSync(path, "utf8")),+ }))+ .filter((f) => f.calls > 0);++ test("only the gate calls createSnapshot directly", () => {+ const offenders = callers.map((f) => f.rel).filter((rel) => !(rel in ALLOWED));+ expect(offenders).toEqual([]);+ });++ test("the census finds the gate's own call, so its pattern still matches", () => {+ expect(callers.map((f) => f.rel)).toContain("src/core/brain/snapshot-gate.ts");+ });++ test("a call in a comment or string is not counted, a real one is", () => {+ expect(directCalls('// createSnapshot(vault)\nconst s = "createSnapshot(x)";\n')).toBe(0);+ expect(directCalls("export function createSnapshot(v: string) {}\n")).toBe(0);+ expect(directCalls("createSnapshot(vault, id, { reason });\n")).toBe(1);+ });+});diff --git a/tests/core/architecture/write-site-census.test.ts b/tests/core/architecture/write-site-census.test.tsindex 5742fd9d..9d2ef2d2 100644--- a/tests/core/architecture/write-site-census.test.ts+++ b/tests/core/architecture/write-site-census.test.ts@@ -209,6 +209,9 @@ const SHARED_WRITE_CALLS: ReadonlyArray<string> = Object.freeze(["atomicCreateFileSyncExclusive","writeFrontmatterAtomic","writeFrontmatter",+ // The Brain log's append writer (`src/core/brain/log-append-io.ts`):+ // one append per event to a JSONL shard or its markdown twin.+ "appendSeparated",]);/** A dotted call name as a pattern that tolerates spacing around the dot. */@@ -320,6 +323,15 @@ const C = WRITE_CATEGORY;*/const DIRECT_WRITE_EXCLUSIONS: Readonly<Record<string, WriteExclusion>> = Object.freeze({// --- The shared writers themselves ------------------------------------+ "src/core/brain/log-append-io.ts": {+ categories: [C.sharedWriterItself, C.appendOnlyLedger],+ calls: ["ftruncateSync", "truncateSync", "writeSync"],+ reason:+ "this module IS the append writer the Brain log routes through: one write per event on a " ++ "descriptor opened with the append flag, a truncate to drop trailing whitespace an editor " ++ "left, so the shard ends byte-identical to the rewrite it replaced, and a truncate back to " ++ "the old size when a write fails part way.",+ },"src/core/fs-atomic.ts": {categories: [C.sharedWriterItself],calls: ["linkSync", "renameSync", "unlinkSync", "writeSync"],@@ -731,6 +743,14 @@ const DIRECT_WRITE_EXCLUSIONS: Readonly<Record<string, WriteExclusion>> = Object"inside `withDestructiveSnapshot`, which the destructive-site census holds, and the " +"plan is re-measured inside that recovery point so a newly referenced payload survives.",},+ "src/core/brain/anticipatory-prune.ts": {+ categories: [C.retentionDelete],+ calls: ["unlinkSync"],+ reason:+ "prunes anticipatory cache entries by file age and a count cap. Every entry is a derived " ++ "context pack rebuilt on the next refresh, so there is nothing for a shared writer to " ++ "author on the way out, and the prune marker goes through `atomicWriteFileSync`.",+ },"src/core/brain/notes/write-record.ts": {categories: [C.retentionDelete],calls: ["unlinkSync"],@@ -1374,8 +1394,17 @@ const DIRECT_ROWS = ROWS.filter((row) => row.directCalls.length > 0);* 84 -> 85: the pledge intake's mid-batch rollback* (`src/core/brain/pledge-intake.ts`) - one rmSync that resets the vault to* the pre-intake state, its re-anchor rewrite still on the shared writer.+ *+ * 86 -> 87: the anticipatory cache prune+ * (`src/core/brain/anticipatory-prune.ts`) - a retention delete by age and+ * count whose marker write routes through the shared atomic writer.+ *+ * 87 -> 88: the Brain log's append writer+ * (`src/core/brain/log-append-io.ts`) - the log appender stopped+ * rewriting each day shard through the atomic writer and appends one+ * event per write instead; the raw calls are that writer's implementation.*/-const DIRECT_WRITE_ROWS = 86;+const DIRECT_WRITE_ROWS = 88;/*** Measured modules reaching a write through a shared helper. An equality.@@ -1566,8 +1595,22 @@ const DIRECT_WRITE_ROWS = 86;* `instruction-block.lock.json` ownership record through the shared* atomic writer - every byte it writes rides a shared helper, so it* joins the shared class needing no exclusion.+ *+ * 137 -> 138: the anticipatory cache prune+ * (`src/core/brain/anticipatory-prune.ts`) commits its rate-limit marker+ * through the shared atomic writer - cache machine state, not a note.+ *+ * 138 -> 139: the Brain log's append writer+ * (`src/core/brain/log-append-io.ts`) declares `appendSeparated`, which+ * this census now names as a shared writer, so the module reads as a+ * shared row the way `fs-atomic.ts` does for its own writers.+ *+ * 139 -> 140: the store-aware index location+ * (`src/core/search/brain-store/location.ts`) records the store root it+ * last read in device-local state, through the shared atomic writer, so+ * an unknown probe keeps only an index of the same root.*/-const SHARED_HELPER_ROWS = 137;+const SHARED_HELPER_ROWS = 140;// ----- Origin-channel coverage boundary (Unit C) ----------------------------@@ -1666,8 +1709,14 @@ const STAMPED_PATHS: ReadonlySet<string> = new Set(* 83 -> 84: the pledge intake's mid-batch rollback* (`src/core/brain/pledge-intake.ts`) - a reset to the pre-intake state* stamps no channel either.+ * 85 -> 86: the anticipatory cache prune+ * (`src/core/brain/anticipatory-prune.ts`) - a retention delete of derived+ * cache entries stamps nothing.+ * 86 -> 87: the Brain log's append writer+ * (`src/core/brain/log-append-io.ts`) - the stamp is applied by its caller,+ * `log.ts`, which still reads as a stamped shared-helper row.*/-const UNSTAMPED_DIRECT_ROWS = 85;+const UNSTAMPED_DIRECT_ROWS = 87;/*** Shared-helper write sites the stamp does not reach, measured the same@@ -1761,8 +1810,17 @@ const UNSTAMPED_DIRECT_ROWS = 85;* `instruction-block.lock.json` ownership record through the shared* atomic writer - both under the apply arm only, the plan and the dry* run write nothing, and neither write stamps an origin channel.+ * 132 -> 133: the anticipatory cache prune's rate-limit marker+ * (`src/core/brain/anticipatory-prune.ts`), written through the shared+ * atomic writer, carries no origin channel.+ * 133 -> 134: the Brain log's append writer+ * (`src/core/brain/log-append-io.ts`) is a shared row by its own+ * declaration and stamps nothing; `log.ts`, its caller, stamps.+ * 134 -> 135: the store-aware index location's remembered store root+ * (`src/core/search/brain-store/location.ts`) is device-local machine+ * state, not a note, and carries no origin channel.*/-const UNSTAMPED_SHARED_ROWS = 132;+const UNSTAMPED_SHARED_ROWS = 135;describe("in-vault write-site census", () => {test("every direct-fs write site carries a written exclusion", () => {diff --git a/tests/core/brain.pinned.test.ts b/tests/core/brain.pinned.test.tsindex 5ec4ee86..32c990c4 100644--- a/tests/core/brain.pinned.test.ts+++ b/tests/core/brain.pinned.test.ts@@ -1,9 +1,17 @@import { afterEach, beforeEach, describe, expect, test } from "bun:test";-import { existsSync, mkdtempSync, readFileSync, rmSync } from "node:fs";+import { chmodSync, existsSync, mkdtempSync, readFileSync, rmSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";-import { brainPinnedPath } from "../../src/core/brain/paths.ts";+import { bootstrapBrain } from "../../src/core/brain/init.ts";+import { brainDirsForWrite, brainPinnedPath } from "../../src/core/brain/paths.ts";+import { acquireLockSync, LOCK_WAIT_BUDGET_MS } from "../../src/core/brain/sync-lockfile.ts";+import {+ resetVaultIdentityPins,+ VaultIdentityMismatchError,+ vaultIdentityPath,+ writeVaultIdentity,+} from "../../src/core/brain/vault-identity.ts";import {MAX_PINNED_CONTEXT_LEN,PinnedBatchError,@@ -14,6 +22,7 @@ import {writePinnedContext,} from "../../src/core/brain/pinned.ts";import { PRIVATE_REGION_PLACEHOLDER } from "../../src/core/redactor.ts";+import { CHMOD_CANNOT_DENY } from "../helpers/platform.ts";let vault: string;@@ -65,6 +74,18 @@ describe("pinned context core", () => {expect(existsSync(brainPinnedPath(vault))).toBe(true);expect(readFileSync(brainPinnedPath(vault), "utf8")).toBe("");});++ // POSIX modes only, and root reads a 0000 file anyway.+ test.skipIf(CHMOD_CANNOT_DENY)(+ "with dual writes off a clear does not read the file it clears",+ () => {+ writePinnedContext(vault, "Temporary fact");+ chmodSync(brainPinnedPath(vault), 0o000);+ const pinned = clearPinnedContext(vault);+ expect(pinned.content).toBe("");+ expect(readFileSync(brainPinnedPath(vault), "utf8")).toBe("");+ },+ );});describe("pinned context single-op budget honesty", () => {@@ -193,3 +214,29 @@ describe("pinned context batch operations", () => {expect(existsSync(brainPinnedPath(vault))).toBe(false);});});++describe("pinned context on a vault the identity guard refuses", () => {+ // The guard runs before the pinned lock is taken, so a refused vault+ // never waits on (or creates) that lock.+ for (const [name, write] of [+ ["write", (v: string) => writePinnedContext(v, "guarded")],+ ["append", (v: string) => appendPinnedContext(v, "guarded")],+ ] as const) {+ test(`${name} refuses without waiting on a held lock`, () => {+ resetVaultIdentityPins();+ bootstrapBrain(vault);+ brainDirsForWrite(vault);+ rmSync(vaultIdentityPath(vault));+ writeVaultIdentity(vault);+ const held = acquireLockSync(brainPinnedPath(vault));+ const started = Date.now();+ try {+ expect(() => write(vault)).toThrow(VaultIdentityMismatchError);+ } finally {+ held.release();+ resetVaultIdentityPins();+ }+ expect(Date.now() - started).toBeLessThan(LOCK_WAIT_BUDGET_MS);+ });+ }+});diff --git a/tests/core/brain/anticipatory-prune.test.ts b/tests/core/brain/anticipatory-prune.test.tsnew file mode 100644index 00000000..32b388a9--- /dev/null+++ b/tests/core/brain/anticipatory-prune.test.ts@@ -0,0 +1,112 @@+/**+ * Anticipatory cache pruning.+ *+ * Every prompt refreshes `Brain/.state/anticipatory/<key>.json` and+ * nothing used to delete those files: a live install accumulated 3,647+ * entries (305 MB). A refresh that writes now prunes the directory,+ * rate-limited, by age and by a hard count cap, and never removes the+ * entry it just wrote.+ */++import { afterEach, beforeEach, describe, expect, setSystemTime, test } from "bun:test";+import {+ existsSync,+ mkdirSync,+ mkdtempSync,+ readdirSync,+ rmSync,+ utimesSync,+ writeFileSync,+} from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import { refreshAnticipatoryCache } from "../../../src/core/brain/anticipatory-cache.ts";+import {+ ANTICIPATORY_CACHE_MAX_ENTRIES,+ ANTICIPATORY_CACHE_RETENTION_MS,+ ANTICIPATORY_PRUNE_INTERVAL_MS,+ pruneAnticipatoryCache,+} from "../../../src/core/brain/anticipatory-prune.ts";+import { bootstrapBrain } from "../../../src/core/brain/init.ts";+import { BRAIN_ANTICIPATORY_REL } from "../../../src/core/brain/path-constants.ts";++let vault: string;+let cacheDir: string;++beforeEach(() => {+ vault = mkdtempSync(join(tmpdir(), "o2b-anticipatory-prune-"));+ bootstrapBrain(vault);+ cacheDir = join(vault, BRAIN_ANTICIPATORY_REL);+});++afterEach(() => {+ setSystemTime();+ rmSync(vault, { recursive: true, force: true });+});++function plantEntry(name: string, ageMs: number): string {+ const path = join(cacheDir, `${name}.json`);+ writeFileSync(path, "{}\n");+ const at = new Date(Date.now() - ageMs);+ utimesSync(path, at, at);+ return path;+}++function entries(): string[] {+ return readdirSync(cacheDir).filter((name) => name.endsWith(".json"));+}++describe("anticipatory cache pruning", () => {+ test("the first writing refresh prunes without an explicit call", () => {+ // Plant before the directory has ever been pruned.+ mkdirSync(cacheDir, { recursive: true });+ const expired = plantEntry("expired", ANTICIPATORY_CACHE_RETENTION_MS + 60_000);+ const fresh = plantEntry("fresh", 5_000);++ const result = refreshAnticipatoryCache(vault, { sessionId: "s-1", now: new Date() });++ expect(result.refreshed).toBe(true);+ expect(existsSync(result.path)).toBe(true);+ expect(existsSync(expired)).toBe(false);+ expect(existsSync(fresh)).toBe(true);+ });++ test("the count cap holds and keeps the newest entries", () => {+ mkdirSync(cacheDir, { recursive: true });+ const extra = 7;+ const total = ANTICIPATORY_CACHE_MAX_ENTRIES + extra;+ // Entry i is i minutes old, all well inside the retention window.+ for (let i = 0; i < total; i++) plantEntry(`e-${String(i).padStart(4, "0")}`, (i + 1) * 60_000);++ const result = refreshAnticipatoryCache(vault, { sessionId: "s-cap", now: new Date() });++ const left = entries();+ expect(left.length).toBe(ANTICIPATORY_CACHE_MAX_ENTRIES);+ expect(existsSync(result.path)).toBe(true);+ // The oldest planted entries went first.+ for (let i = total - extra - 1; i < total; i++) {+ expect(left).not.toContain(`e-${String(i).padStart(4, "0")}.json`);+ }+ expect(left).toContain("e-0000.json");+ });++ test("pruning is rate-limited between writing refreshes", () => {+ refreshAnticipatoryCache(vault, { sessionId: "s-1", now: new Date() });+ const expired = plantEntry("expired", ANTICIPATORY_CACHE_RETENTION_MS + 60_000);++ refreshAnticipatoryCache(vault, { sessionId: "s-2", now: new Date() });++ // Inside the rate-limit window the second write does not scan the directory.+ expect(existsSync(expired)).toBe(true);+ // Once the window has passed, the next writing refresh prunes again.+ const later = new Date(Date.now() + ANTICIPATORY_PRUNE_INTERVAL_MS + 1_000);+ setSystemTime(later);+ refreshAnticipatoryCache(vault, { sessionId: "s-3", now: later });+ expect(existsSync(expired)).toBe(false);+ });++ test("a missing cache directory is not an error", () => {+ expect(pruneAnticipatoryCache(vault)).toEqual({ ran: false, removed: 0 });+ });+});diff --git a/tests/core/brain/artifact-ref-view.test.ts b/tests/core/brain/artifact-ref-view.test.tsindex d8c1f96f..a9aa6255 100644--- a/tests/core/brain/artifact-ref-view.test.ts+++ b/tests/core/brain/artifact-ref-view.test.ts@@ -206,3 +206,32 @@ describe("a reference that leaves the vault", () => {expect(asked).toEqual(["notes/inside.md"]);});});++describe("absolute and Windows spellings", () => {+ test("an absolute path to the hidden page is judged where it is, and withheld", () => {+ expect(hidingView().visible(join(vault, "Brain", "preferences", `${HIDDEN_ID}.md`))).toBe(+ false,+ );+ expect(hidingView().visible(`[[${join(vault, "Brain", "preferences", HIDDEN_ID)}]]`)).toBe(+ false,+ );+ });++ test("an absolute path outside the vault is hidden without asking the rule", () => {+ const asked: string[] = [];+ const view = artifactRefView(vault, (rel) => {+ asked.push(rel);+ return true;+ });+ expect(view.visible(join(vault, "..", "outside.md"))).toBe(false);+ expect(asked).toEqual([]);+ });++ test.skipIf(process.platform !== "win32")(+ "a backslash path is the path it spells on Windows, not a bare id",+ () => {+ expect(hidingView().visible(`Brain\\preferences\\${HIDDEN_ID}`)).toBe(false);+ expect(hidingView().visible(`Brain\\preferences\\${HIDDEN_ID}.md`)).toBe(false);+ },+ );+});diff --git a/tests/core/brain/doctor-exit-census.test.ts b/tests/core/brain/doctor-exit-census.test.tsindex 07efa7c3..c80e0073 100644--- a/tests/core/brain/doctor-exit-census.test.ts+++ b/tests/core/brain/doctor-exit-census.test.ts@@ -214,6 +214,7 @@ const DOCTOR_REGISTERED_CODES: ReadonlyArray<string> = ["stale-dependency","storage-capacity-critical","storage-capacity-warn",+ "store-missing","sync-conflict-log","tier-drift","topic-key-collision",diff --git a/tests/core/brain/doctor-store.test.ts b/tests/core/brain/doctor-store.test.tsnew file mode 100644index 00000000..dd6ac0f6--- /dev/null+++ b/tests/core/brain/doctor-store.test.ts@@ -0,0 +1,488 @@+/**+ * The doctor's brain store section (task 1.11): silent while the store is+ * not in use, and when it is, the dual-write counters, state-digest+ * findings and same-id conflicts.+ */+import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import {+ appendFileSync,+ chmodSync,+ existsSync,+ mkdirSync,+ mkdtempSync,+ rmSync,+ symlinkSync,+ utimesSync,+ writeFileSync,+} from "node:fs";+import { tmpdir } from "node:os";+import { dirname, join } from "node:path";++import { runDoctor } from "../../../src/core/brain/doctor.ts";+import {+ STORE_CLOCK_AHEAD_CODE,+ STORE_DIGEST_DIVERGENT_CODE,+ STORE_DUAL_WRITE_FAILURES_CODE,+ STORE_DUAL_WRITE_NO_STORE_CODE,+ STORE_MISSING_CODE,+ STORE_DIGEST_SILENT_CODE,+ STORE_PARTITION_UNREADABLE_CODE,+ STORE_RECORD_ID_CONFLICT_CODE,+ STORE_ROOT_INVALID_CODE,+ STORE_SHARD_TAIL_HELD_CODE,+ STORE_SHARD_UNREADABLE_CODE,+} from "../../../src/core/brain/doctor/store-check.ts";+import {+ reservedDeviceDirIssues,+ STORE_DEVICE_DIR_RESERVED_CODE,+ STORE_MODE_LOOSE_CODE,+ STORE_RECORD_ID_CROSS_PARTITION_CODE,+} from "../../../src/core/brain/doctor/store-trust-check.ts";+import { resetVaultIdentityPins } from "../../../src/core/brain/vault-identity.ts";+import { appendRecord } from "../../../src/core/store/appender.ts";+import { STORE_DUAL_WRITE_ENV, STORE_ROOT_ENV } from "../../../src/core/store/constants.ts";+import { bodyChecksum } from "../../../src/core/store/envelope.ts";+import { publishStateDigest } from "../../../src/core/store/state-digest.ts";+import { inspectStore, openStore, type StoreHandle } from "../../../src/core/store/store-open.ts";+import { ensureStore } from "../store/fixtures/temp-store.ts";+import { dualWriteStatusPath, shardPath } from "../../../src/core/store/store-paths.ts";+import { CHMOD_CANNOT_DENY, IS_WINDOWS } from "../../helpers/platform.ts";++const ENV_KEYS = [+ STORE_DUAL_WRITE_ENV,+ STORE_ROOT_ENV,+ "HOME",+ "XDG_STATE_HOME",+ "XDG_DATA_HOME",+ "LOCALAPPDATA",+] as const;+const NOW = Date.UTC(2026, 10, 6, 12, 0, 0);++let parent: string;+let vault: string;+let storeRoot: string;+const saved = new Map<string, string | undefined>();++beforeEach(() => {+ for (const key of ENV_KEYS) saved.set(key, process.env[key]);+ parent = mkdtempSync(join(tmpdir(), "osb-doctor-store-"));+ vault = join(parent, "vault");+ storeRoot = join(parent, "store");+ for (const d of ["preferences", "retired", "inbox", "processed", "log"]) {+ mkdirSync(join(vault, "Brain", d), { recursive: true });+ }+ writeFileSync(join(vault, "Brain", "_brain.yaml"), "schema_version: 1\n");+ process.env["HOME"] = join(parent, "home");+ process.env["XDG_STATE_HOME"] = join(parent, "state");+ process.env["XDG_DATA_HOME"] = join(parent, "data");+ process.env["LOCALAPPDATA"] = join(parent, "state");+ delete process.env[STORE_DUAL_WRITE_ENV];+ delete process.env[STORE_ROOT_ENV];+ resetVaultIdentityPins();+});++afterEach(() => {+ for (const key of ENV_KEYS) {+ const value = saved.get(key);+ if (value === undefined) delete process.env[key];+ else process.env[key] = value;+ }+ resetVaultIdentityPins();+ rmSync(parent, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });+});++function storeCodes(): string[] {+ const report = runDoctor(vault, { now: new Date(NOW + 10) });+ return [...report.warnings, ...report.errors]+ .map((issue) => issue.code)+ .filter((code) => code.startsWith("store-"));+}++function writeFailureCounter(failures: number): void {+ const path = dualWriteStatusPath();+ mkdirSync(dirname(path), { recursive: true });+ writeFileSync(path, JSON.stringify({ failures, skipped_no_device: 0, last_error: "disk full" }));+}++/** Open the store as `device`, with that machine's own device-local state. */+function machine(device: string): StoreHandle {+ ensureStore(storeRoot);+ return openStore({+ root: storeRoot,+ device,+ dirs: {+ platform: process.platform,+ home: join(parent, "home", device),+ env: {+ XDG_STATE_HOME: join(parent, "state", device),+ LOCALAPPDATA: join(parent, "state", device),+ },+ },+ });+}++const at = (ms: number) => () => ms;++describe("store not in use", () => {+ test("no flag and no store root: the section says nothing, even about old counters", () => {+ writeFailureCounter(4);+ expect(storeCodes()).toEqual([]);+ // Read-only: the default store root was not created by looking.+ expect(existsSync(join(parent, "data"))).toBe(false);+ });++ test("a configured root with no store and the flag off asks for no init", () => {+ process.env[STORE_ROOT_ENV] = storeRoot;+ expect(storeCodes()).toEqual([]);+ expect(existsSync(storeRoot)).toBe(false);+ });+});++describe("store in use", () => {+ test("the flag on with failed dual writes reports the failure count", () => {+ process.env[STORE_DUAL_WRITE_ENV] = "1";+ process.env[STORE_ROOT_ENV] = storeRoot;+ writeFailureCounter(3);+ const report = runDoctor(vault, { now: new Date(NOW) });+ const finding = report.warnings.find((i) => i.code === STORE_DUAL_WRITE_FAILURES_CODE);+ expect(finding?.message).toContain("3 brain store dual write(s) failed");+ expect(finding?.message).toContain("disk full");+ // No store was created, so the only other finding is the init hint.+ expect(storeCodes()).toEqual([STORE_DUAL_WRITE_FAILURES_CODE, STORE_MISSING_CODE]);+ expect(existsSync(storeRoot)).toBe(false);+ });++ test("no store yet: doctor says to run o2b store init, and creates nothing", () => {+ process.env[STORE_DUAL_WRITE_ENV] = "1";+ process.env[STORE_ROOT_ENV] = storeRoot;+ const report = runDoctor(vault, { now: new Date(NOW) });+ const finding = report.warnings.find((i) => i.code === STORE_MISSING_CODE);+ expect(finding?.message).toContain("o2b store init");+ expect(existsSync(storeRoot)).toBe(false);+ });++ test("dual writes skipped for lack of a store are counted and point at the init", () => {+ process.env[STORE_DUAL_WRITE_ENV] = "1";+ process.env[STORE_ROOT_ENV] = storeRoot;+ const path = dualWriteStatusPath();+ mkdirSync(dirname(path), { recursive: true });+ writeFileSync(path, JSON.stringify({ failures: 0, skipped_no_store: 4 }));+ machine("dev-a"); // the store exists now; the skipped records are still missing+ const report = runDoctor(vault, { now: new Date(NOW) });+ const finding = report.warnings.find((i) => i.code === STORE_DUAL_WRITE_NO_STORE_CODE);+ expect(finding?.message).toContain("4 brain store dual write(s) were skipped");+ expect(finding?.message).toContain("o2b store init");+ expect(storeCodes()).not.toContain(STORE_MISSING_CODE);+ });++ test("a configured root inside the vault is reported, not thrown", () => {+ process.env[STORE_ROOT_ENV] = join(vault, "store");+ expect(storeCodes()).toEqual([STORE_ROOT_INVALID_CODE]);+ });++ test("a root inside the vault is reported when the vault is reached through a link", () => {+ // A directory junction needs no privilege on Windows; elsewhere the type is ignored.+ const linked = join(parent, "linked-vault");+ symlinkSync(vault, linked, "junction");+ process.env[STORE_ROOT_ENV] = join(vault, "store");+ const report = runDoctor(linked, { now: new Date(NOW) });+ expect(report.warnings.map((i) => i.code)).toContain(STORE_ROOT_INVALID_CODE);+ });++ // An unreadable shard file needs POSIX permissions and a user they bind.+ const canDenyRead = !CHMOD_CANNOT_DENY;+ test.if(canDenyRead)(+ "a partition that cannot be read is reported and the others are still checked",+ () => {+ process.env[STORE_ROOT_ENV] = storeRoot;+ const a = machine("dev-a");+ const written = appendRecord(+ a,+ { partition: "shared", stream: "events", kind: "note", agent: "t", body: { text: "one" } },+ { now: at(NOW - 1000) },+ );+ const body = { text: "edited" };+ const forged = { ...written.record, body, sum: bodyChecksum(body) };+ const copy = shardPath(storeRoot, "shared", { stream: "events" }, "dev-a", "2026-10");+ mkdirSync(dirname(copy), { recursive: true });+ appendFileSync(copy, `${JSON.stringify(forged)}\n`);+ // A private shard this user may not read.+ const hidden = appendRecord(+ a,+ { partition: "private", stream: "events", kind: "note", agent: "t", body: { text: "two" } },+ { now: at(NOW - 1000) },+ );+ chmodSync(hidden.path, 0o000);+ let codes: string[];+ try {+ codes = storeCodes();+ } finally {+ chmodSync(hidden.path, 0o600);+ }+ expect(codes).toContain(STORE_SHARD_UNREADABLE_CODE);+ expect(codes).toContain(STORE_RECORD_ID_CONFLICT_CODE);+ },+ );++ test.if(canDenyRead)(+ "one shard that cannot be read is named, and the partition's other shards are still checked",+ () => {+ process.env[STORE_ROOT_ENV] = storeRoot;+ const a = machine("dev-a");+ const written = appendRecord(+ a,+ { partition: "shared", stream: "events", kind: "note", agent: "t", body: { text: "one" } },+ { now: at(NOW - 1000) },+ );+ const body = { text: "edited" };+ const forged = { ...written.record, body, sum: bodyChecksum(body) };+ const copy = shardPath(storeRoot, "shared", { stream: "events" }, "dev-a", "2026-10");+ mkdirSync(dirname(copy), { recursive: true });+ appendFileSync(copy, `${JSON.stringify(forged)}\n`);+ // A shard of the same partition, locked by a sync client.+ const locked = appendRecord(+ a,+ { partition: "shared", stream: "log", kind: "log-event", agent: "t", body: { n: 1 } },+ { now: at(NOW - 1000) },+ );+ chmodSync(locked.path, 0o000);+ let report: ReturnType<typeof runDoctor>;+ try {+ report = runDoctor(vault, { now: new Date(NOW + 10) });+ } finally {+ chmodSync(locked.path, 0o600);+ }+ const unreadable = report.warnings.find((i) => i.code === STORE_SHARD_UNREADABLE_CODE);+ expect(unreadable?.path).toBe(locked.path);+ expect(report.warnings.map((i) => i.code)).toContain(STORE_RECORD_ID_CONFLICT_CODE);+ expect(report.warnings.map((i) => i.code)).not.toContain(STORE_PARTITION_UNREADABLE_CODE);+ },+ );++ test.if(canDenyRead)(+ "a shared shard that cannot be read stops silent-device findings, which need its retirements",+ () => {+ process.env[STORE_ROOT_ENV] = storeRoot;+ const old = machine("dev-old");+ appendRecord(+ old,+ { partition: "private", stream: "events", kind: "note", agent: "t", body: { n: 1 } },+ { now: at(NOW - 10 * 24 * 60 * 60 * 1000) },+ );+ const locked = appendRecord(+ machine("dev-a"),+ { partition: "shared", stream: "settings", kind: "note", agent: "t", body: { n: 2 } },+ { now: at(NOW - 1000) },+ );+ expect(storeCodes()).toContain(STORE_DIGEST_SILENT_CODE);+ chmodSync(locked.path, 0o000);+ let codes: string[];+ try {+ codes = storeCodes();+ } finally {+ chmodSync(locked.path, 0o600);+ }+ expect(codes).toContain(STORE_SHARD_UNREADABLE_CODE);+ expect(codes).not.toContain(STORE_DIGEST_SILENT_CODE);+ },+ );++ test("a shard tail that has not verified for an hour is reported, a fresh one is not", () => {+ process.env[STORE_ROOT_ENV] = storeRoot;+ const written = appendRecord(+ machine("dev-a"),+ { partition: "shared", stream: "events", kind: "note", agent: "t", body: { text: "one" } },+ { now: at(NOW - 1000) },+ );+ // A crash mid-append left half a line with no newline.+ appendFileSync(written.path, '{"v":1,"id":"01');+ const touch = (ms: number) => utimesSync(written.path, new Date(ms), new Date(ms));+ touch(NOW - 60_000);+ expect(storeCodes()).not.toContain(STORE_SHARD_TAIL_HELD_CODE);+ touch(NOW - 2 * 60 * 60 * 1000);+ const report = runDoctor(vault, { now: new Date(NOW) });+ const held = report.warnings.find((i) => i.code === STORE_SHARD_TAIL_HELD_CODE);+ expect(held?.path).toBe(written.path);+ expect(held?.message).toContain("dev-a");+ });++ test("a healthy store with matching digests reports nothing", () => {+ process.env[STORE_ROOT_ENV] = storeRoot;+ const a = machine("dev-a");+ appendRecord(+ a,+ {+ partition: "shared",+ stream: "events",+ kind: "pinned-set",+ agent: "t",+ body: { authority: "human", content: "x" },+ },+ { now: at(NOW - 1000) },+ );+ publishStateDigest(a, { partition: "shared", agent: "doctor", now: at(NOW) });+ expect(storeCodes()).toEqual([]);+ });++ test("a fold that diverges over the same cut is reported", () => {+ process.env[STORE_ROOT_ENV] = storeRoot;+ const a = machine("dev-a");+ const b = machine("dev-b");+ appendRecord(+ a,+ {+ partition: "shared",+ stream: "events",+ kind: "pinned-set",+ agent: "t",+ body: { authority: "human", content: "x" },+ },+ { now: at(NOW - 1000) },+ );+ const good = publishStateDigest(a, { partition: "shared", agent: "doctor", now: at(NOW) });+ appendRecord(+ b,+ {+ partition: "shared",+ stream: "digests",+ kind: "state-digest",+ agent: "doctor",+ body: { ...good.body, folds: { ...good.body.folds, pinned: "0".repeat(64) } },+ },+ { now: at(NOW + 5) },+ );+ expect(storeCodes()).toEqual([STORE_DIGEST_DIVERGENT_CODE]);+ });++ test("one record id delivered with different content is reported", () => {+ process.env[STORE_ROOT_ENV] = storeRoot;+ const a = machine("dev-a");+ const written = appendRecord(+ a,+ {+ partition: "shared",+ stream: "events",+ kind: "note",+ agent: "t",+ body: { text: "original" },+ },+ { now: at(NOW - 1000) },+ );+ // The same id, re-delivered with an edited body (and a checksum that+ // matches the edit), as a hand-edited copy of the shard would carry.+ const body = { text: "edited" };+ const forged = { ...written.record, body, sum: bodyChecksum(body) };+ const copy = shardPath(storeRoot, "shared", { stream: "events" }, "dev-a", "2026-10");+ mkdirSync(dirname(copy), { recursive: true });+ appendFileSync(copy, `${JSON.stringify(forged)}\n`);+ const report = runDoctor(vault, { now: new Date(NOW + 10) });+ const finding = report.warnings.find((i) => i.code === STORE_RECORD_ID_CONFLICT_CODE);+ expect(finding?.message).toContain(written.record.id);+ });+});++describe("what a synced peer can deliver", () => {+ test("a record id in both partitions is reported", () => {+ process.env[STORE_ROOT_ENV] = storeRoot;+ const a = machine("dev-a");+ const written = appendRecord(+ a,+ { partition: "private", stream: "events", kind: "note", agent: "t", body: { text: "x" } },+ { now: at(NOW - 1000) },+ );+ const copy = shardPath(storeRoot, "shared", { stream: "events" }, "dev-a", "2026-11");+ mkdirSync(dirname(copy), { recursive: true });+ appendFileSync(copy, `${JSON.stringify(written.record)}\n`);+ const report = runDoctor(vault, { now: new Date(NOW + 10) });+ const finding = report.warnings.find((i) => i.code === STORE_RECORD_ID_CROSS_PARTITION_CODE);+ expect(finding?.message).toContain(written.record.id);+ });++ // A file symlink needs a privilege on Windows.+ test.skipIf(IS_WINDOWS)(+ "a shard name that is a symbolic link is reported, not passed over",+ () => {+ process.env[STORE_ROOT_ENV] = storeRoot;+ machine("dev-a");+ const outside = join(parent, "outside.jsonl");+ writeFileSync(outside, "");+ const link = shardPath(storeRoot, "shared", { stream: "events" }, "dev-b", "2026-10");+ mkdirSync(dirname(link), { recursive: true });+ symlinkSync(outside, link);+ const report = runDoctor(vault, { now: new Date(NOW + 10) });+ const finding = report.warnings.find((i) => i.code === STORE_SHARD_UNREADABLE_CODE);+ expect(finding?.path).toBe(link);+ expect(finding?.message).toContain("not a regular file");+ },+ );++ test("on Windows a device folder named like a Windows device is reported, elsewhere not", () => {+ machine("dev-a");+ for (const dir of [+ join(storeRoot, "shared", "events", "nul"),+ join(storeRoot, "private", "ledgers", "continuity", "com1"),+ join(storeRoot, "shared", "events", "nul-box"),+ ]) {+ mkdirSync(dir, { recursive: true });+ }+ const store = inspectStore(storeRoot)!;+ const issues = reservedDeviceDirIssues(store, "win32");+ expect(issues.map((i) => i.code)).toEqual([+ STORE_DEVICE_DIR_RESERVED_CODE,+ STORE_DEVICE_DIR_RESERVED_CODE,+ ]);+ expect(issues[0]!.message).toContain(join(storeRoot, "shared", "events", "nul"));+ expect(issues[0]!.message).not.toContain("nul-box");+ expect(issues[1]!.message).toContain(+ join(storeRoot, "private", "ledgers", "continuity", "com1"),+ );+ expect(reservedDeviceDirIssues(store, "linux")).toEqual([]);+ });+});++describe.skipIf(IS_WINDOWS)("modes of the store", () => {+ test("a shard other accounts can read is reported; the owner-only store is not", () => {+ process.env[STORE_ROOT_ENV] = storeRoot;+ const written = appendRecord(+ machine("dev-a"),+ { partition: "private", stream: "events", kind: "note", agent: "t", body: { text: "x" } },+ { now: at(NOW - 1000) },+ );+ expect(storeCodes()).not.toContain(STORE_MODE_LOOSE_CODE);+ chmodSync(written.path, 0o644);+ const report = runDoctor(vault, { now: new Date(NOW + 10) });+ const finding = report.warnings.find((i) => i.code === STORE_MODE_LOOSE_CODE);+ expect(finding?.message).toContain(written.path);+ expect(finding?.message).toContain(`chmod -R go-rwx '${join(storeRoot, "private")}'`);+ });+});++describe("clocks ahead of now", () => {+ const DAY = 24 * 60 * 60 * 1000;+ const write = (store: StoreHandle, ms: number) =>+ appendRecord(+ store,+ { partition: "shared", stream: "events", kind: "note", agent: "t", body: { at: ms } },+ { now: at(ms) },+ ).record;++ test("records more than the drift bound ahead are reported per device with the newest stamp", () => {+ process.env[STORE_ROOT_ENV] = storeRoot;+ const broken = machine("dev-broken");+ write(broken, NOW + 2 * DAY);+ const newest = write(broken, NOW + 3 * DAY);+ write(machine("dev-ok"), NOW - 1000);+ const report = runDoctor(vault, { now: new Date(NOW) });+ const finding = report.warnings.find((i) => i.code === STORE_CLOCK_AHEAD_CODE);+ expect(finding?.message).toContain("2 record(s) in the shared partition");+ expect(finding?.message).toContain(`dev-broken (2, newest ${newest.hlc}`);+ expect(finding?.message).not.toContain("dev-ok");+ });++ test("a record ahead by less than the bound is not reported", () => {+ process.env[STORE_ROOT_ENV] = storeRoot;+ write(machine("dev-a"), NOW + DAY - 60_000);+ const report = runDoctor(vault, { now: new Date(NOW) });+ expect(report.warnings.map((i) => i.code)).not.toContain(STORE_CLOCK_AHEAD_CODE);+ });+});diff --git a/tests/core/brain/dual-write-sites.test.ts b/tests/core/brain/dual-write-sites.test.tsnew file mode 100644index 00000000..4b9f18e5--- /dev/null+++ b/tests/core/brain/dual-write-sites.test.ts@@ -0,0 +1,724 @@+/**+ * What the legacy writers hand the brain store under dual writes (task+ * 1.11), site by site: which partition a row goes to, which scope and+ * authority it carries, and which vault and config it is checked against.+ *+ * Every test runs against its own temp HOME, state base, vault and store+ * root under one named parent, removed in teardown. The origin channel is+ * cleared after each test, so an operator-channel test cannot leak into+ * the next one.+ */+import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import { appendApplyEvidence } from "../../../src/core/brain/apply-evidence.ts";+import { bootstrapBrain } from "../../../src/core/brain/init.ts";+import { appendLogEvent } from "../../../src/core/brain/log.ts";+import { mergePreferences } from "../../../src/core/brain/merge.ts";+import { stagePendingSignal } from "../../../src/core/brain/pending.ts";+import { setPinned } from "../../../src/core/brain/pin.ts";+import { moveToRetired, writePreference } from "../../../src/core/brain/preference.ts";+import { writePreferenceTxn } from "../../../src/core/brain/preference-txn.ts";+import { appendClaimEvent } from "../../../src/core/brain/truth/store.ts";+import { clearOriginChannel, setOriginChannel } from "../../../src/core/origin-channel.ts";+import { appendAuditRecord } from "../../../src/core/reliability/audit.ts";+import {+ LEDGER_ROW_KIND,+ LOG_EVENT_KIND,+ PREFERENCE_EVIDENCE_KIND,+ PREFERENCE_SET_KIND,+ SIGNAL_KIND,+ STORE_DUAL_WRITE_ENV,+ STORE_ROOT_ENV,+} from "../../../src/core/store/constants.ts";+import { readDualWriteStatus } from "../../../src/core/store/dual-write.ts";+import type { StoreRecord } from "../../../src/core/store/envelope.ts";+import { foldPreferences } from "../../../src/core/store/fold-preferences.ts";+import { readPartition } from "../../../src/core/store/state-digest.ts";+import { ensureStore } from "../store/fixtures/temp-store.ts";++const ENV_KEYS = [+ STORE_DUAL_WRITE_ENV,+ STORE_ROOT_ENV,+ "O2B_DEVICE_ID",+ "HOME",+ "XDG_STATE_HOME",+ "LOCALAPPDATA",+] as const;++let parent: string;+let vault: string;+let storeRoot: string;+const saved = new Map<string, string | undefined>();++beforeEach(() => {+ for (const key of ENV_KEYS) saved.set(key, process.env[key]);+ parent = mkdtempSync(join(tmpdir(), "osb-dual-write-sites-"));+ vault = join(parent, "vault");+ storeRoot = join(parent, "store");+ mkdirSync(vault, { recursive: true });+ bootstrapBrain(vault);+ process.env["HOME"] = join(parent, "home");+ process.env["XDG_STATE_HOME"] = join(parent, "state");+ process.env["LOCALAPPDATA"] = join(parent, "state");+ process.env[STORE_ROOT_ENV] = storeRoot;+ process.env["O2B_DEVICE_ID"] = "dev-a";+ process.env[STORE_DUAL_WRITE_ENV] = "1";+ // Writers never create a store; `o2b store init` does.+ ensureStore(storeRoot);+});++afterEach(() => {+ clearOriginChannel();+ for (const key of ENV_KEYS) {+ const value = saved.get(key);+ if (value === undefined) delete process.env[key];+ else process.env[key] = value;+ }+ rmSync(parent, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });+});++function storeRecords(partition: "shared" | "private" = "shared"): StoreRecord[] {+ const dir = join(storeRoot, partition);+ return existsSync(dir) ? readPartition(dir).flatMap((shard) => shard.records) : [];+}++function ledgerRows(ledger: string, partition: "shared" | "private" = "shared"): StoreRecord[] {+ const dir = join(storeRoot, partition);+ if (!existsSync(dir)) return [];+ return readPartition(dir)+ .filter((shard) => shard.rel.startsWith(`ledgers/${ledger}/`))+ .flatMap((shard) => shard.records)+ .filter((r) => r.kind === LEDGER_ROW_KIND);+}++function preferenceInput(slug: string, extra: Record<string, unknown> = {}) {+ return {+ slug,+ topic: slug,+ principle: `principle ${slug}`,+ created_at: "2026-05-01T00:00:00Z",+ unconfirmed_until: "2026-05-30T00:00:00Z",+ status: "unconfirmed" as const,+ evidenced_by: [],+ ...extra,+ };+}++describe("signals", () => {+ test("a signal staged into Brain/pending is recorded as staged", () => {+ stagePendingSignal(vault, {+ topic: "staged",+ signal: "positive",+ agent: "claude",+ principle: "Stage it for review",+ created_at: "2026-11-06T10:00:00Z",+ date: "2026-11-06",+ slug: "staged",+ });+ const record = storeRecords().find((r) => r.kind === SIGNAL_KIND);+ expect(record?.body["staged"]).toBe(true);+ expect(String(record?.body["path"])).toStartWith("Brain/pending/");+ });+});++describe("a private preference keeps its trail in the private partition", () => {+ test("the audit rows of its create and retire", () => {+ const written = writePreferenceTxn(+ vault,+ preferenceInput("hidden", { visibility: ["private"] }),+ [],+ {},+ undefined,+ { agent: "claude" },+ );+ moveToRetired(vault, written.path, "user-rejected", {+ now: new Date("2026-11-06T12:00:00Z"),+ retired_by: "[[operator]]",+ audit: { agent: "claude" },+ });+ expect(ledgerRows("preference-audit", "shared")).toEqual([]);+ const ops = ledgerRows("preference-audit", "private").map(+ (r) => (r.body["row"] as Record<string, unknown>)["op"],+ );+ expect(ops).toEqual(["create", "retire"]);+ });++ test("a private write lands exactly its preference-set record and its audit row in private", () => {+ writePreferenceTxn(+ vault,+ preferenceInput("hidden-count", { visibility: ["private"] }),+ [],+ {},+ undefined,+ { agent: "claude" },+ );+ expect(+ storeRecords("private")+ .map((r) => r.kind)+ .toSorted(),+ ).toEqual([LEDGER_ROW_KIND, PREFERENCE_SET_KIND].toSorted());+ expect(storeRecords("shared")).toEqual([]);+ });++ test("on a machine without the private partition its audit rows never reach shared", () => {+ dropPrivatePartition();+ writePreferenceTxn(+ vault,+ preferenceInput("hidden-here", { visibility: ["private"] }),+ [],+ {},+ undefined,+ { agent: "claude" },+ );+ expect(ledgerRows("preference-audit", "shared")).toEqual([]);+ // The appender refused the private row, which counts as a failure.+ // Exactly the two private records of the write were refused: its+ // preference-set record and its audit row (the control above lands+ // the same two in `private`).+ expect(readDualWriteStatus().failures).toBe(2);+ });++ test("its evidence", () => {+ writePreference(vault, preferenceInput("hidden-ev", { visibility: ["private"] }));+ appendApplyEvidence(vault, {+ pref_id: "pref-hidden-ev",+ artifact: "[[note]]",+ result: "applied",+ agent: "claude",+ });+ expect(storeRecords("shared").filter((r) => r.kind === PREFERENCE_EVIDENCE_KIND)).toEqual([]);+ expect(storeRecords("private").filter((r) => r.kind === PREFERENCE_EVIDENCE_KIND).length).toBe(+ 1,+ );+ });+});++/** Add an informal privacy marker to a page, as a hand edit would. */+function markByHand(path: string, marker: string): void {+ const text = readFileSync(path, "utf8");+ writeFileSync(path, text.replace(/^---\r?\n/, `---\n${marker}\n`));+}++const evidenceOrEvent = (r: StoreRecord) =>+ r.kind === PREFERENCE_EVIDENCE_KIND || r.kind === LOG_EVENT_KIND;++const isPin = (r: StoreRecord) =>+ r.kind === PREFERENCE_SET_KIND && Object.keys(r.body["fields"] as object).join() === "pinned";++const retireSets = (partition: "shared" | "private") =>+ storeRecords(partition).filter(+ (r) =>+ r.kind === PREFERENCE_SET_KIND &&+ (r.body["fields"] as Record<string, unknown>)["status"] === "retired",+ );++const auditOps = (partition: "shared" | "private") =>+ ledgerRows("preference-audit", partition).map(+ (r) => (r.body["row"] as Record<string, unknown>)["op"],+ );++const mergeRows = (partition: "shared" | "private") =>+ ledgerRows("preference-audit", partition).filter(+ (r) => (r.body["row"] as Record<string, unknown>)["op"] === "merge",+ );++describe("an informal privacy marker on disk decides the partition at every site", () => {+ // The same rule search and remote reads use: `access: private`,+ // `confidentiality: secret` and `sensitivity: confidential` reserve a+ // page as private just like `visibility: private`.+ test("evidence and its log event", () => {+ const { path } = writePreference(vault, preferenceInput("by-hand-ev"));+ markByHand(path, "access: private");+ appendApplyEvidence(vault, {+ pref_id: "pref-by-hand-ev",+ artifact: "[[note]]",+ result: "applied",+ agent: "claude",+ });+ expect(storeRecords("shared").filter(evidenceOrEvent)).toEqual([]);+ expect(+ storeRecords("private")+ .filter(evidenceOrEvent)+ .map((r) => r.kind)+ .toSorted(),+ ).toEqual([LOG_EVENT_KIND, PREFERENCE_EVIDENCE_KIND].toSorted());+ });++ test("a pin", () => {+ const { path } = writePreference(vault, preferenceInput("by-hand-pin"));+ markByHand(path, "confidentiality: secret");+ setPinned(vault, "pref-by-hand-pin", true);+ expect(storeRecords("shared").filter(isPin)).toEqual([]);+ expect(storeRecords("private").filter(isPin).length).toBe(1);+ });++ test("a retire and its audit row", () => {+ const written = writePreferenceTxn(vault, preferenceInput("by-hand-ret"), [], {}, undefined, {+ agent: "claude",+ });+ markByHand(written.path, "sensitivity: confidential");+ moveToRetired(vault, written.path, "user-rejected", {+ now: new Date("2026-11-06T12:00:00Z"),+ retired_by: "[[operator]]",+ audit: { agent: "claude" },+ });+ expect(retireSets("shared")).toEqual([]);+ expect(retireSets("private").length).toBeGreaterThan(0);+ // The create happened before the hand edit; the retire follows the marker.+ expect(auditOps("shared")).not.toContain("retire");+ expect(auditOps("private")).toContain("retire");+ });++ test("the merge audit row of a hand-marked keep", () => {+ for (const slug of ["keep-mark", "drop-mark"]) {+ writePreferenceTxn(+ vault,+ preferenceInput(slug, {+ topic: "shared-topic",+ status: "confirmed",+ confirmed_at: "2026-05-02T00:00:00Z",+ }),+ [],+ {},+ undefined,+ { agent: "claude" },+ );+ }+ markByHand(join(vault, "Brain", "preferences", "pref-keep-mark.md"), "access: private");+ mergePreferences(vault, "pref-keep-mark", "pref-drop-mark", {+ now: new Date("2026-11-06T12:00:00Z"),+ agentName: "operator",+ });+ expect(mergeRows("shared")).toEqual([]);+ expect(mergeRows("private").length).toBe(1);+ });++ test("an unmarked page with an unrelated access value stays shared", () => {+ const { path } = writePreference(vault, preferenceInput("by-hand-team"));+ markByHand(path, "access: team");+ appendApplyEvidence(vault, {+ pref_id: "pref-by-hand-team",+ artifact: "[[note]]",+ result: "applied",+ agent: "claude",+ });+ expect(storeRecords("private").filter((r) => r.kind === PREFERENCE_EVIDENCE_KIND)).toEqual([]);+ expect(storeRecords("shared").filter((r) => r.kind === PREFERENCE_EVIDENCE_KIND).length).toBe(+ 1,+ );+ });+});++describe("authority of preference fields", () => {+ test("an operator write leaves the derived fields to the dream pass", () => {+ setOriginChannel("cli");+ writePreference(vault, preferenceInput("by-operator", { scope: "coding" }));+ clearOriginChannel();+ // The dream pass later promotes it, at agent authority.+ writePreference(+ vault,+ preferenceInput("by-operator", {+ scope: "coding",+ status: "confirmed",+ confirmed_at: "2026-05-02T00:00:00Z",+ }),+ { overwrite: true, authority: "agent" },+ );+ const state = foldPreferences(storeRecords()).preferences.get("pref-by-operator")!;+ expect(state.fields["status"]).toBe("confirmed");+ expect(state.fields["principle"]).toBe("principle by-operator");+ // The operator's own fields stay human; every record keeps the scope.+ const sets = storeRecords().filter((r) => r.kind === PREFERENCE_SET_KIND);+ const human = sets.find((r) => r.body["authority"] === "human")!;+ expect(Object.keys(human.body["fields"] as object)).toContain("principle");+ expect(Object.keys(human.body["fields"] as object)).not.toContain("status");+ expect(sets.every((r) => r.scope === "coding")).toBe(true);+ });++ test("an operator retire decides the status and keeps the preference's identity", () => {+ const { path } = writePreference(vault, preferenceInput("rejected"));+ setOriginChannel("cli");+ moveToRetired(vault, path, "user-rejected", {+ now: new Date("2026-11-06T12:00:00Z"),+ retired_by: "[[operator]]",+ });+ clearOriginChannel();+ const state = foldPreferences(storeRecords()).preferences.get("pref-rejected")!;+ expect(state.fields["status"]).toBe("retired");+ expect(state.fields["id"]).toBe("pref-rejected");+ expect(state.fields["kind"]).not.toBe("brain-retired");+ const humanStatus = storeRecords().find(+ (r) =>+ r.kind === PREFERENCE_SET_KIND &&+ r.body["authority"] === "human" &&+ "status" in (r.body["fields"] as object),+ );+ expect(humanStatus).toBeDefined();+ });++ test("a pin carries the preference's scope", () => {+ writePreference(vault, preferenceInput("scoped", { scope: "writing" }));+ setPinned(vault, "pref-scoped", true);+ const pin = storeRecords()+ .filter((r) => r.kind === PREFERENCE_SET_KIND)+ .find((r) => Object.keys(r.body["fields"] as object).join() === "pinned");+ expect(pin).toBeDefined();+ expect(pin!.scope).toBe("writing");+ });+});++describe("the vault and config a dual write is checked against", () => {+ test("a store root inside the vault being written is refused, the legacy write kept", () => {+ // The configured vault (the suite's default) is another directory, so+ // only the vault actually written can catch this root.+ const inside = join(vault, "store");+ process.env[STORE_ROOT_ENV] = inside;+ appendLogEvent(vault, {+ timestamp: "2026-11-06T10:01:00Z",+ eventType: "note",+ agent: "claude",+ body: { text: "kept" },+ });+ expect(existsSync(inside)).toBe(false);+ expect(readDualWriteStatus().failures).toBe(1);+ });++ test("an audit row checks the store root against the vault it belongs to", () => {+ const inside = join(vault, "store");+ process.env[STORE_ROOT_ENV] = inside;+ appendAuditRecord(+ join(vault, "Brain", "log", "hygiene"),+ {+ timestamp: "2026-11-06T10:00:00Z",+ actor: "claude",+ action: "apply",+ target: "note",+ ok: true,+ },+ vault,+ );+ expect(existsSync(inside)).toBe(false);+ expect(readDualWriteStatus().failures).toBe(1);+ });++ test("the flag is read from the config the caller names", () => {+ delete process.env[STORE_DUAL_WRITE_ENV];+ const configPath = join(parent, "config.yaml");+ writeFileSync(configPath, `vault: ${vault}\nstore_dual_write: "true"\n`);+ appendClaimEvent(+ vault,+ {+ ts: "2026-06-01T10:00:00Z",+ agent: "claude",+ entity: "Alice Mason",+ aspect: "employer",+ value: "Google",+ source: "[[Brain/notes/standup.md]]",+ },+ { configPath },+ );+ expect(ledgerRows("truth-claims", "private").length).toBe(1);+ });+});++/** This machine holds only `shared`, as after `o2b store init --partitions shared`. */+function dropPrivatePartition(): void {+ rmSync(join(storeRoot, "private"), { recursive: true, force: true });+}++function auditTrailRow(+ trail: string,+ extra: { target?: string; details?: Record<string, unknown> } = {},+ rowVault: string | null = vault,+): void {+ appendAuditRecord(+ join(vault, "Brain", "log", trail),+ {+ timestamp: "2026-11-06T10:00:00Z",+ actor: "claude",+ action: "apply",+ target: extra.target ?? "note",+ ok: true,+ ...(extra.details !== undefined ? { details: extra.details } : {}),+ },+ rowVault ?? undefined,+ );+}++const logEvents = (partition: "shared" | "private") =>+ storeRecords(partition).filter((r) => r.kind === LOG_EVENT_KIND);++function writeNote(rel: string, frontmatter: string): void {+ const abs = join(vault, rel);+ mkdirSync(join(abs, ".."), { recursive: true });+ writeFileSync(abs, `---\n${frontmatter}\n---\n\n# Note\n`);+}++function claimFrom(source: string): void {+ appendClaimEvent(vault, {+ ts: "2026-06-01T10:00:00Z",+ agent: "claude",+ entity: "Alice Mason",+ aspect: "employer",+ value: "Google",+ source,+ });+}++/** Two preferences on one topic, the one to drop marked private by hand, then merged. */+function mergeWithPrivateDrop(holdPrivate: boolean): void {+ for (const slug of ["keep-open", "drop-secret"]) {+ writePreferenceTxn(+ vault,+ preferenceInput(slug, {+ topic: "merged-topic",+ status: "confirmed",+ confirmed_at: "2026-05-02T00:00:00Z",+ }),+ [],+ {},+ undefined,+ { agent: "claude" },+ );+ }+ markByHand(join(vault, "Brain", "preferences", "pref-drop-secret.md"), "access: private");+ if (!holdPrivate) dropPrivatePartition();+ mergePreferences(vault, "pref-keep-open", "pref-drop-secret", {+ now: new Date("2026-11-06T12:00:00Z"),+ agentName: "operator",+ });+}++describe("a log event that names a private page stays out of shared", () => {+ test("the log event of a pin on a private preference", () => {+ writePreference(vault, preferenceInput("pinned-secret", { visibility: ["private"] }));+ setPinned(vault, "pref-pinned-secret", true);+ expect(logEvents("shared")).toEqual([]);+ expect(logEvents("private").length).toBeGreaterThan(0);+ });++ /**+ * Records of the merge that name the private preference, refused on a+ * shared-only machine: the dropped preference's retiring preference-set+ * record and its retire audit row, the merge audit row and the merge log+ * event.+ */+ const MERGE_PRIVATE_RECORDS = 4;++ test("a merge whose dropped preference is private lands its rows in private", () => {+ mergeWithPrivateDrop(true);+ expect(mergeRows("private")).toHaveLength(1);+ expect(logEvents("private").filter((r) => r.body["event_type"] === "merge")).toHaveLength(1);+ expect(mergeRows("shared")).toEqual([]);+ expect(readDualWriteStatus().failures).toBe(0);+ });++ test("a merge whose dropped preference is private, with its audit row", () => {+ mergeWithPrivateDrop(false);+ expect(mergeRows("shared")).toEqual([]);+ expect(logEvents("shared").filter((r) => r.body["event_type"] === "merge")).toEqual([]);+ // Every record the control lands in private was refused here, not skipped.+ expect(readDualWriteStatus().failures).toBe(MERGE_PRIVATE_RECORDS);+ });++ test("on a machine without the private partition it is refused and counted", () => {+ writePreference(vault, preferenceInput("named-secret", { visibility: ["private"] }));+ dropPrivatePartition();+ appendLogEvent(vault, {+ timestamp: "2026-11-06T10:00:00Z",+ eventType: "note",+ agent: "claude",+ body: {+ text: "about [[pref-named-secret|principle named-secret]]",+ rule: "[[pref-named-secret]]",+ },+ });+ expect(logEvents("shared")).toEqual([]);+ expect(readDualWriteStatus().failures).toBe(1);+ });++ test("a note page reserved as private, named by its path", () => {+ writeNote("notes/diary.md", "visibility: private");+ appendLogEvent(vault, {+ timestamp: "2026-11-06T10:00:00Z",+ eventType: "note",+ agent: "claude",+ body: { text: "edited", target: "[[notes/diary]]" },+ });+ expect(logEvents("shared")).toEqual([]);+ expect(logEvents("private").length).toBe(1);+ });++ test("a preference id with no page on disk cannot be judged and counts as private", () => {+ appendLogEvent(vault, {+ timestamp: "2026-11-06T10:00:00Z",+ eventType: "note",+ agent: "claude",+ body: { rule: "[[pref-gone]]" },+ });+ expect(logEvents("shared")).toEqual([]);+ expect(logEvents("private").length).toBe(1);+ });++ test("a private page named by its absolute path stays out of shared", () => {+ writeNote("notes/diary.md", "visibility: private");+ appendLogEvent(vault, {+ timestamp: "2026-11-06T10:00:00Z",+ eventType: "note",+ agent: "claude",+ body: { text: "edited", target: join(vault, "notes", "diary.md") },+ });+ expect(logEvents("shared")).toEqual([]);+ expect(logEvents("private").length).toBe(1);+ });++ test("an absolute path outside the vault names no page anyone may be shown", () => {+ appendLogEvent(vault, {+ timestamp: "2026-11-06T10:00:00Z",+ eventType: "note",+ agent: "claude",+ body: { text: "read", target: join(parent, "elsewhere.md") },+ });+ expect(logEvents("shared")).toEqual([]);+ expect(logEvents("private").length).toBe(1);+ });++ test("a reconcile event naming its topic's missing preference by id is not spared", () => {+ appendLogEvent(vault, {+ timestamp: "2026-11-06T10:00:00Z",+ eventType: "reconcile",+ agent: "claude",+ body: { topic: "gone-topic", preference: "pref-gone-topic" },+ });+ expect(logEvents("shared")).toEqual([]);+ expect(logEvents("private").length).toBe(1);+ });++ test("a reconcile event's topic guess alone does not make it private", () => {+ appendLogEvent(vault, {+ timestamp: "2026-11-06T10:00:00Z",+ eventType: "reconcile",+ agent: "claude",+ body: { topic: "gone-topic" },+ });+ expect(logEvents("private")).toEqual([]);+ expect(logEvents("shared").length).toBe(1);+ });++ test("an event naming open pages and non-page artifacts stays shared", () => {+ writePreference(vault, preferenceInput("open-rule"));+ writeNote("notes/open.md", "tags: [x]");+ appendLogEvent(vault, {+ timestamp: "2026-11-06T10:00:00Z",+ eventType: "note",+ agent: "claude",+ body: {+ rule: "[[pref-open-rule]]",+ page: "[[notes/open]]",+ artifact: "[[src/cli/main.ts:120-145]]",+ text: "free text",+ },+ });+ expect(logEvents("private")).toEqual([]);+ expect(logEvents("shared").length).toBe(1);+ });+});++describe("a truth claim taken from a private page stays out of shared", () => {+ test("a private source goes to private", () => {+ writeNote("notes/standup.md", "access: private");+ claimFrom("[[notes/standup]]");+ expect(ledgerRows("truth-claims", "shared")).toEqual([]);+ expect(ledgerRows("truth-claims", "private").length).toBe(1);+ });++ test("a private source on a machine without the private partition is refused", () => {+ writeNote("notes/standup.md", "visibility: private");+ dropPrivatePartition();+ claimFrom("[[notes/standup.md]]");+ expect(ledgerRows("truth-claims", "shared")).toEqual([]);+ expect(readDualWriteStatus().failures).toBe(1);+ });++ test("a linked source that resolves to no page is refused on a shared-only machine", () => {+ dropPrivatePartition();+ claimFrom("[[notes/not-synced-yet]]");+ expect(ledgerRows("truth-claims", "shared")).toEqual([]);+ expect(readDualWriteStatus().failures).toBe(1);+ });++ test("an open source or a non-page source reaches shared on a shared-only machine", () => {+ writeNote("notes/open.md", "tags: [x]");+ dropPrivatePartition();+ claimFrom("[[notes/open]]");+ claimFrom("https://example.com/about");+ expect(ledgerRows("truth-claims", "shared").length).toBe(2);+ expect(readDualWriteStatus().failures).toBe(0);+ });+});++describe("audit rows go to private when this machine holds it, else shared", () => {+ test("a preference-audit row of an open preference", () => {+ writePreferenceTxn(vault, preferenceInput("open"), [], {}, undefined, { agent: "claude" });+ expect(ledgerRows("preference-audit", "private").length).toBe(1);+ expect(ledgerRows("preference-audit", "shared")).toEqual([]);+ });++ test("a preference-audit row of an open preference on a shared-only machine", () => {+ dropPrivatePartition();+ writePreferenceTxn(vault, preferenceInput("open"), [], {}, undefined, { agent: "claude" });+ expect(ledgerRows("preference-audit", "shared").length).toBe(1);+ expect(readDualWriteStatus().failures).toBe(0);+ });++ test.each(["hygiene", "secret-custody"])("a reliability-audit row of the %s trail", (trail) => {+ auditTrailRow(trail);+ expect(ledgerRows("reliability-audit", "shared")).toEqual([]);+ const rows = ledgerRows("reliability-audit", "private");+ expect(rows.length).toBe(1);+ const row = rows[0]!.body["row"] as Record<string, unknown>;+ expect(row["audit_dir"]).toBe(trail);+ expect((row["record"] as Record<string, unknown>)["action"]).toBe("apply");+ });++ test.each(["hygiene", "secret-custody"])(+ "a reliability-audit row of the %s trail on a shared-only machine",+ (trail) => {+ dropPrivatePartition();+ auditTrailRow(trail);+ expect(ledgerRows("reliability-audit", "shared").length).toBe(1);+ expect(readDualWriteStatus().failures).toBe(0);+ },+ );++ test("a reliability-audit row carries its actor as the record's agent", () => {+ auditTrailRow("hygiene");+ expect(ledgerRows("reliability-audit", "private")[0]!.agent).toBe("claude");+ });++ test.each([+ ["target", { target: "notes/diary.md" }],+ ["details", { details: { pages: ["[[notes/diary]]"] } }],+ ] as const)(+ "a reliability-audit row naming a private page in its %s is private only",+ (_, extra) => {+ writeNote("notes/diary.md", "visibility: private");+ auditTrailRow("hygiene", extra);+ expect(ledgerRows("reliability-audit", "private").length).toBe(1);+ dropPrivatePartition();+ auditTrailRow("hygiene", extra);+ expect(ledgerRows("reliability-audit", "shared")).toEqual([]);+ expect(readDualWriteStatus().failures).toBe(1);+ },+ );++ test("a reliability-audit row written without its vault cannot be judged and is private only", () => {+ dropPrivatePartition();+ auditTrailRow("hygiene", {}, null);+ expect(ledgerRows("reliability-audit", "shared")).toEqual([]);+ expect(readDualWriteStatus().failures).toBe(1);+ });+});diff --git a/tests/core/brain/gitignore-guard.test.ts b/tests/core/brain/gitignore-guard.test.tsindex 2265eea2..4f4fd248 100644--- a/tests/core/brain/gitignore-guard.test.ts+++ b/tests/core/brain/gitignore-guard.test.ts@@ -403,6 +403,10 @@ function derivedStoreSites(): string[] {* paths outside the covered directory) fails the membership assertion.*/const DECLARED_SITES: ReadonlyMap<string, string> = new Map([+ [+ "core/search/brain-store/location.ts",+ "names the legacy derived-store file to place the store-aware index outside the vault",+ ],["cli/bootstrap/receipt.ts", "bootstraps the bootstrap lockfile under the store"],["cli/bootstrap/run.ts", "CLI bootstrap reporting that names the store"],["cli/brain/help-text.ts", "help prose naming the store directory"],diff --git a/tests/core/brain/log-append-io.test.ts b/tests/core/brain/log-append-io.test.tsnew file mode 100644index 00000000..b71aad2b--- /dev/null+++ b/tests/core/brain/log-append-io.test.ts@@ -0,0 +1,137 @@+/**+ * The Brain log's append primitives (`log-append-io.ts`) on their own:+ * a write that fails part way leaves the shard as it was, and the+ * backward line scan reads a line longer than many chunks correctly.+ *+ * A full disk is simulated with the forwarding `node:fs` mock idiom of+ * `tests/core/brain/ingest/incremental-extract.test.ts`: every call is+ * passed through untouched, except that while a target file is armed, a+ * write to it lands only half its bytes and the next one raises ENOSPC,+ * the shape a real short write followed by a full disk has. Later writes+ * go through again, so the rollback itself can be observed.+ */++import * as fsNamespace from "node:fs";+import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import { afterEach, beforeEach, describe, expect, mock, test } from "bun:test";++const realWriteSync = fsNamespace.writeSync;+const realFstatSync = fsNamespace.fstatSync;+const realStatSync = fsNamespace.statSync;+let armed: { readonly dev: number; readonly ino: number } | undefined;+let shortWriteDone = false;++mock.module("node:fs", () => ({+ ...fsNamespace,+ writeSync(+ fd: number,+ buffer: Buffer,+ offset: number,+ length: number,+ position: number | null,+ ): number {+ if (armed !== undefined) {+ const st = realFstatSync(fd);+ if (st.dev === armed.dev && st.ino === armed.ino) {+ if (shortWriteDone) {+ // One failure, then the disk has room again: what the rollback+ // writes back must land.+ armed = undefined;+ throw Object.assign(new Error("ENOSPC: no space left on device, write"), {+ code: "ENOSPC",+ });+ }+ shortWriteDone = true;+ const half = Math.max(1, Math.floor(length / 2));+ return realWriteSync(fd, buffer, offset, half, position);+ }+ }+ return realWriteSync(fd, buffer, offset, length, position);+ },+}));++const { appendSeparated, scanLinesFromEnd } =+ await import("../../../src/core/brain/log-append-io.ts");++let dir: string;++beforeEach(() => {+ dir = mkdtempSync(join(tmpdir(), "osb-log-append-io-"));+ armed = undefined;+ shortWriteDone = false;+});++afterEach(() => {+ armed = undefined;+ rmSync(dir, { recursive: true, force: true });+});++function arm(path: string): void {+ const st = realStatSync(path);+ armed = { dev: st.dev, ino: st.ino };+ shortWriteDone = false;+}++const BLOCK = `{"row":"${"x".repeat(200)}"}\n`;++describe("a failed append leaves the shard as it was", () => {+ test("the normal append path", () => {+ const path = join(dir, "shard.jsonl");+ const before = `{"row":1}\n{"row":2}\n`;+ writeFileSync(path, before);+ arm(path);++ expect(() => appendSeparated(path, BLOCK, "\n", BLOCK)).toThrow(/ENOSPC/);++ expect(readFileSync(path, "utf8")).toBe(before);+ appendSeparated(path, BLOCK, "\n", BLOCK);+ expect(readFileSync(path, "utf8")).toBe(`${before}${BLOCK}`);+ });++ test("the path that trims an unusual whitespace tail first", () => {+ const path = join(dir, "day.md");+ const before = "## 10:00 - note\n\ntext\n\n\n\n";+ writeFileSync(path, before);+ arm(path);++ expect(() => appendSeparated(path, "## 11:00 - note\n", "\n\n", "x")).toThrow(/ENOSPC/);++ expect(readFileSync(path, "utf8")).toBe(before);+ });++ test("the first write into an empty file", () => {+ const path = join(dir, "empty.jsonl");+ writeFileSync(path, "");+ arm(path);++ expect(() => appendSeparated(path, BLOCK, "\n", BLOCK)).toThrow(/ENOSPC/);++ expect(readFileSync(path, "utf8")).toBe("");+ });+});++describe("scanLinesFromEnd", () => {+ test("reads a line many chunks long, and the lines around it", () => {+ const path = join(dir, "long.jsonl");+ const long = "y".repeat(64 * 1024 * 5 + 17);+ writeFileSync(path, `first\r\n${long}\r\nlast`);+ const seen: string[] = [];+ expect(+ scanLinesFromEnd(path, (line) => {+ seen.push(line);+ return null;+ }),+ ).toBeNull();+ expect(seen).toEqual(["last", long, "first"]);+ });++ test("a file that is one line with no newline is that line", () => {+ const path = join(dir, "one.jsonl");+ const long = "z".repeat(64 * 1024 * 3 + 5);+ writeFileSync(path, long);+ expect(scanLinesFromEnd(path, (line) => line)).toBe(long);+ });+});diff --git a/tests/core/brain/log-append.test.ts b/tests/core/brain/log-append.test.tsnew file mode 100644index 00000000..0e3db9a6--- /dev/null+++ b/tests/core/brain/log-append.test.ts@@ -0,0 +1,241 @@+/**+ * The Brain log appender writes one event as one append.+ *+ * It used to read the whole `<date>[.<device>].jsonl` shard and its+ * markdown twin and rewrite both through a temp file and a rename for+ * every event, so each event cost the size of the day file (about 5k+ * events a day per device). These tests pin what the append has to keep:+ * the per-shard hash chain, today's handling of a torn last line, the+ * markdown view's bytes, and correctness under concurrent processes.+ */++import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import {+ appendFileSync,+ mkdirSync,+ mkdtempSync,+ readFileSync,+ rmSync,+ statSync,+ writeFileSync,+} from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import { verifyLogChain } from "../../../src/core/brain/log-chain.ts";+import { readLogDay } from "../../../src/core/brain/log-jsonl.ts";+import { appendLogEvent, LOG_CHAIN_FIELDS } from "../../../src/core/brain/log.ts";+import { logJsonlPath, logPath } from "../../../src/core/brain/paths.ts";++const DATE = "2026-06-01";+const SPAWN_TIMEOUT_MS = 60_000;+const BARRIER_LEAD_MS = 1_500;++let root: string;+let vault: string;++beforeEach(() => {+ root = mkdtempSync(join(tmpdir(), "o2b-log-append-"));+ vault = join(root, "vault");+ mkdirSync(join(vault, "Brain"), { recursive: true });+});++afterEach(() => {+ rmSync(root, { recursive: true, force: true });+});++function pad(n: number): string {+ return String(n).padStart(2, "0");+}++function stamp(i: number): string {+ const s = i % 60;+ const m = Math.floor(i / 60) % 60;+ const h = 10 + Math.floor(i / 3600);+ return `${DATE}T${pad(h)}:${pad(m)}:${pad(s)}Z`;+}++function append(i: number, text = `event ${i}`): void {+ appendLogEvent(+ vault,+ { timestamp: stamp(i), eventType: "note", body: { text, agent: "@tester" } },+ { deviceId: "" },+ );+}++function jsonlLines(): string[] {+ return readFileSync(logJsonlPath(vault, DATE), "utf8").split("\n");+}++describe("log append", () => {+ test("the hash chain stays valid over many appends", () => {+ const count = 300;+ for (let i = 0; i < count; i++) append(i);++ const result = verifyLogChain(vault);+ expect(result.ok).toBe(true);+ expect(result.shards[0]).toMatchObject({ chained: count, legacy: 0, firstBreak: null });+ expect(readLogDay(vault, DATE).entries).toHaveLength(count);+ // One line per event, one trailing newline.+ expect(readFileSync(logJsonlPath(vault, DATE), "utf8").endsWith("}\n")).toBe(true);+ });++ test("the markdown view keeps its exact shape", () => {+ append(0, "first");+ append(1, "second");++ const md = readFileSync(logPath(vault, DATE), "utf8");+ // The channel depends on the host running the suite; the line carrying+ // it is pinned, and every event of one process names the same one.+ const channel = /^- origin_channel: (\S+)$/m.exec(md)?.[1];+ expect(channel).toBeDefined();+ expect(md).toBe(+ [+ "---",+ "kind: brain-log",+ `date: ${DATE}`,+ "tags: [brain, brain/log]",+ "---",+ "",+ `# Brain log β ${DATE}`,+ "",+ "## 10:00:00Z β note",+ "- text: first",+ "- agent: @tester",+ `- origin_channel: ${channel}`,+ "",+ "## 10:00:01Z β note",+ "- text: second",+ "- agent: @tester",+ `- origin_channel: ${channel}`,+ "",+ ].join("\n"),+ );+ });++ test("an append does not replace the shard file", () => {+ append(0);+ const before = statSync(logJsonlPath(vault, DATE));+ const mdBefore = statSync(logPath(vault, DATE));+ append(1);+ const after = statSync(logJsonlPath(vault, DATE));+ const mdAfter = statSync(logPath(vault, DATE));+ // A rewrite renames a new inode into place; an append keeps the file.+ // Windows reports a zero inode on some file systems, so compare only+ // when the platform gives one.+ if (before.ino !== 0) {+ expect(after.ino).toBe(before.ino);+ expect(mdAfter.ino).toBe(mdBefore.ino);+ }+ expect(after.size).toBeGreaterThan(before.size);+ });++ test("a torn last line stays its own line and the chain links past it", () => {+ append(0);+ append(1);+ const path = logJsonlPath(vault, DATE);+ const intact = readFileSync(path, "utf8");+ const torn = '{"ts":"2026-06-01T10:00:0';+ appendFileSync(path, torn);++ append(2);++ const lines = jsonlLines();+ // Two intact rows, the torn fragment untouched on its own line, the+ // new row, and the trailing newline.+ expect(lines).toHaveLength(5);+ expect(lines.slice(0, 2).join("\n") + "\n").toBe(intact);+ expect(lines[2]).toBe(torn);+ expect(lines[4]).toBe("");+ const second = JSON.parse(lines[1]!) as Record<string, unknown>;+ const added = JSON.parse(lines[3]!) as Record<string, unknown>;+ expect(added[LOG_CHAIN_FIELDS.prev]).toBe(second[LOG_CHAIN_FIELDS.h]);++ // The reader skips the fragment with a warning and keeps every event.+ const day = readLogDay(vault, DATE);+ expect(day.entries).toHaveLength(3);+ expect(day.warnings.some((w) => w.message.includes("malformed JSONL line"))).toBe(true);+ });++ test("a complete last line without a trailing newline gets one before the next row", () => {+ append(0);+ const path = logJsonlPath(vault, DATE);+ writeFileSync(path, readFileSync(path, "utf8").replace(/\n$/, ""));++ append(1);++ const lines = jsonlLines();+ expect(lines).toHaveLength(3);+ expect(verifyLogChain(vault).ok).toBe(true);+ });++ test("trailing blank lines are collapsed exactly as the rewrite did", () => {+ append(0);+ const path = logJsonlPath(vault, DATE);+ appendFileSync(path, "\n\n \n");+ const md = logPath(vault, DATE);+ appendFileSync(md, "\n\n\n");++ append(1);++ expect(jsonlLines()).toHaveLength(3);+ expect(verifyLogChain(vault).ok).toBe(true);+ expect(readFileSync(md, "utf8")).not.toContain("\n\n\n");+ expect(readFileSync(md, "utf8").endsWith("\n")).toBe(true);+ });++ test(+ "concurrent appends from child processes all land with a valid chain",+ async () => {+ const writers = 4;+ const perWriter = 25;+ const script = join(root, "log-writer.ts");+ const logModule = join(import.meta.dir, "../../../src/core/brain/log.ts");+ writeFileSync(+ script,+ [+ `import { appendLogEvent } from ${JSON.stringify(logModule)};`,+ "const [vault, tag, count, startAt] = process.argv.slice(2);",+ "while (Date.now() < Number(startAt)) Bun.sleepSync(1);",+ "for (let i = 0; i < Number(count); i++) {",+ " appendLogEvent(",+ " vault,",+ ` { timestamp: "${DATE}T11:00:00Z", eventType: "note", body: { text: \`\${tag}-\${i}\` } },`,+ ' { deviceId: "" },',+ " );",+ "}",+ ].join("\n"),+ "utf8",+ );+ const startAt = String(Date.now() + BARRIER_LEAD_MS);+ const procs = Array.from({ length: writers }, (_, index) =>+ Bun.spawn([process.execPath, script, vault, `w${index}`, String(perWriter), startAt], {+ stdout: "pipe",+ stderr: "pipe",+ env: { ...process.env },+ }),+ );+ const failures: string[] = [];+ await Promise.all(+ procs.map(async (proc) => {+ const err = await new Response(proc.stderr).text();+ const code = await proc.exited;+ if (code !== 0) failures.push(`exit ${code}: ${err.trim()}`);+ }),+ );+ expect(failures).toEqual([]);++ const total = writers * perWriter;+ const result = verifyLogChain(vault);+ expect(result.ok).toBe(true);+ expect(result.shards[0]).toMatchObject({ chained: total, firstBreak: null });+ const texts = readLogDay(vault, DATE).entries.map((e) => e.body["text"]);+ for (let w = 0; w < writers; w++) {+ for (let i = 0; i < perWriter; i++) expect(texts).toContain(`w${w}-${i}`);+ }+ const md = readFileSync(logPath(vault, DATE), "utf8");+ expect(md.match(/^## /gm)?.length).toBe(total);+ },+ SPAWN_TIMEOUT_MS,+ );+});diff --git a/tests/core/brain/manual-template-revision.test.ts b/tests/core/brain/manual-template-revision.test.tsnew file mode 100644index 00000000..0a093b0b--- /dev/null+++ b/tests/core/brain/manual-template-revision.test.ts@@ -0,0 +1,231 @@+/**+ * The `template_revision` stamp in `Brain/_BRAIN.md` and the upgrade rules+ * built on it.+ *+ * The manual is synced vault content, and devices sharing one vault do not+ * always run the same release. Without a stamp, a device on an older release+ * saw a newer release's manual as a pending upgrade and rewrote it back to+ * its own template; the newer device then upgraded it forward again, each+ * step behind a pre-apply snapshot. With the stamp, a manual from a newer+ * template revision is left as it is.+ *+ * The hash guard keeps the stamp honest: the hash of the manual as this+ * release renders it (every substitution but the device-local vault name)+ * is recorded next to its revision, so changing the template text or a+ * release constant it renders without bumping the revision fails here.+ */++import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import { createHash } from "node:crypto";+import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import { bootstrapBrain } from "../../../src/core/brain/init.ts";+import { brainManualPath, snapshotsDir } from "../../../src/core/brain/paths.ts";+import {+ BRAIN_MANUAL_TEMPLATE_PATH,+ BRAIN_MANUAL_TEMPLATE_REVISION,+ BRAIN_MANUAL_TEMPLATE_SHA256,+ buildSubstitutions,+ renderTemplate,+ templateRevisionOf,+} from "../../../src/core/brain/templates.ts";+import { planUpgrade } from "../../../src/core/brain/upgrade.ts";+import { atomicWriteFileSync } from "../../../src/core/fs-atomic.ts";+import {+ runSelfHealUpgrade,+ SELF_HEAL_UPGRADE_OUTCOME,+} from "../../../src/core/maintenance/self-heal-upgrade.ts";+import { runCli } from "../../helpers/run-cli.ts";++const MANUAL = "Brain/_BRAIN.md";++let root: string;+let vault: string;+let configPath: string;++beforeEach(() => {+ root = mkdtempSync(join(tmpdir(), "o2b-manual-revision-"));+ vault = join(root, "vault");+ mkdirSync(vault, { recursive: true });+ configPath = join(root, "config.yaml");+ atomicWriteFileSync(configPath, `vault: ${vault}\n`);+ bootstrapBrain(vault, { configPath });+});++afterEach(() => {+ rmSync(root, { recursive: true, force: true });+});++function manual(): string {+ return readFileSync(brainManualPath(vault), "utf8");+}++function writeManual(body: string): void {+ atomicWriteFileSync(brainManualPath(vault), body);+}++/** The current manual with its stamp set to `revision` (or removed when null). */+function withRevision(body: string, revision: string | null): string {+ const stamp = /^template_revision: .*\n/m;+ return revision === null+ ? body.replace(stamp, "")+ : body.replace(stamp, `template_revision: ${revision}\n`);+}++function manualRow() {+ return planUpgrade(vault).files.find((f) => f.path === MANUAL)!;+}++function snapshotCount(): number {+ const dir = snapshotsDir(vault);+ return existsSync(dir) ? readdirSync(dir).length : 0;+}++describe("template revision hash guard", () => {+ test("the recorded hash matches the manual this release renders", () => {+ // Every substitution but the device-local vault name: the template text+ // and the release constants it renders decide the bytes together.+ const substitutions = new Map(buildSubstitutions("guard"));+ substitutions.delete("vault_name");+ const template = readFileSync(BRAIN_MANUAL_TEMPLATE_PATH, "utf8").replace(/\r\n/g, "\n");+ const text = renderTemplate(template, substitutions);+ const actual = createHash("sha256").update(text, "utf8").digest("hex");+ if (actual !== BRAIN_MANUAL_TEMPLATE_SHA256) {+ throw new Error(+ "src/core/brain/templates/_BRAIN.md.tpl, or a release constant it renders " ++ "(schema_version, manifest_sidecar_since), changed without a revision bump. " ++ "Increase BRAIN_MANUAL_TEMPLATE_REVISION in src/core/brain/templates.ts by one " ++ `and set BRAIN_MANUAL_TEMPLATE_SHA256 to "${actual}". ` ++ "Devices on an older revision keep a newer manual as it is, so a template change " ++ "that keeps the old revision would be fought over between releases.",+ );+ }+ expect(actual).toBe(BRAIN_MANUAL_TEMPLATE_SHA256);+ });+});++describe("the rendered manual carries the revision", () => {+ test("a fresh manual is stamped with this release's revision", () => {+ expect(templateRevisionOf(manual())).toBe(BRAIN_MANUAL_TEMPLATE_REVISION);+ expect(manualRow().status).toBe("noop");+ });++ test("a manual without a stamp reads as revision 0", () => {+ expect(templateRevisionOf(withRevision(manual(), null))).toBe(0);+ });++ test("a stamp that is not a non-negative integer reads as revision 0", () => {+ for (const bad of ["abc", "-3", "1.5", ""]) {+ expect(templateRevisionOf(withRevision(manual(), bad))).toBe(0);+ }+ });++ test("a manual saved with a byte order mark keeps its revision", () => {+ expect(templateRevisionOf(`\uFEFF${manual()}`)).toBe(BRAIN_MANUAL_TEMPLATE_REVISION);+ });++ test("a stamp outside the frontmatter is not the manual's revision", () => {+ const body = `${withRevision(manual(), null)}\ntemplate_revision: 99\n`;+ expect(templateRevisionOf(body)).toBe(0);+ });+});++describe("upgrade plan rules for the manual", () => {+ test("a manual from before the stamp is upgraded to the stamped rendering", () => {+ const current = manual();+ writeManual(withRevision(current, null));++ const row = manualRow();+ expect(row.status).toBe("update");+ expect(row.after).toBe(current);+ });++ test("a manual from an older revision is upgraded", () => {+ const current = manual();+ writeManual(`${withRevision(current, String(BRAIN_MANUAL_TEMPLATE_REVISION - 1))}old text\n`);++ expect(manualRow().status).toBe("update");+ });++ test("a manual from the same revision with other bytes is still repaired", () => {+ const current = manual();+ writeManual(`${current}hand edit\n`);++ const row = manualRow();+ expect(row.status).toBe("update");+ expect(row.after).toBe(current);+ });++ test("a manual from a newer revision is left as it is and reported", () => {+ const newer = `${withRevision(manual(), String(BRAIN_MANUAL_TEMPLATE_REVISION + 1))}newer rule\n`;+ writeManual(newer);++ const plan = planUpgrade(vault);+ const row = plan.files.find((f) => f.path === MANUAL)!;+ expect(row.status).toBe("noop");+ expect(row.aheadRevision).toBe(BRAIN_MANUAL_TEMPLATE_REVISION + 1);+ expect(plan.pending).toBe(0);+ });++ test("self-heal neither rewrites nor snapshots a manual from a newer revision", () => {+ const newer = `${withRevision(manual(), String(BRAIN_MANUAL_TEMPLATE_REVISION + 1))}newer rule\n`;+ writeManual(newer);++ expect(runSelfHealUpgrade(vault).outcome).toBe(SELF_HEAL_UPGRADE_OUTCOME.current);+ expect(manual()).toBe(newer);+ expect(snapshotCount()).toBe(0);+ });+});++/** Replace the manual with one a newer release would write. */+function writeNewer(): void {+ writeManual(`${withRevision(manual(), String(BRAIN_MANUAL_TEMPLATE_REVISION + 1))}newer rule\n`);+}++describe("the newer revision is visible to the operator", () => {+ test("`o2b brain upgrade --dry-run` names both revisions", async () => {+ writeNewer();+ const r = await runCli(["brain", "upgrade", "--vault", vault, "--dry-run"], {+ env: { OPEN_SECOND_BRAIN_CONFIG: configPath },+ });+ expect(r.returncode).toBe(0);+ expect(r.stdout).toContain(+ `${MANUAL}: kept; written by a newer release (template revision ` ++ `${BRAIN_MANUAL_TEMPLATE_REVISION + 1}, this release ships ${BRAIN_MANUAL_TEMPLATE_REVISION})`,+ );+ });++ test("`o2b brain upgrade --check --json` reports it without a pending change", async () => {+ writeNewer();+ const r = await runCli(["brain", "upgrade", "--vault", vault, "--check", "--json"], {+ env: { OPEN_SECOND_BRAIN_CONFIG: configPath },+ });+ expect(r.returncode).toBe(0);+ const out = JSON.parse(r.stdout) as {+ pending: number;+ files: Array<{ path: string; status: string; ahead_revision?: number }>;+ };+ expect(out.pending).toBe(0);+ const row = out.files.find((f) => f.path === MANUAL)!;+ expect(row.status).toBe("noop");+ expect(row.ahead_revision).toBe(BRAIN_MANUAL_TEMPLATE_REVISION + 1);+ });++ test("`o2b brain status` lists it as a problem", async () => {+ writeNewer();+ const r = await runCli(["brain", "status", "--vault", vault], {+ env: { OPEN_SECOND_BRAIN_CONFIG: configPath },+ });+ expect(r.stdout).toContain("[managed-file-from-newer-release]");+ expect(r.stdout).toContain(`template revision ${BRAIN_MANUAL_TEMPLATE_REVISION + 1}`);+ });++ test("`o2b brain status` stays quiet when the manual is current", async () => {+ const r = await runCli(["brain", "status", "--vault", vault], {+ env: { OPEN_SECOND_BRAIN_CONFIG: configPath },+ });+ expect(r.stdout).not.toContain("[managed-file-from-newer-release]");+ });+});diff --git a/tests/core/brain/pinned-concurrency.test.ts b/tests/core/brain/pinned-concurrency.test.tsnew file mode 100644index 00000000..e9974076--- /dev/null+++ b/tests/core/brain/pinned-concurrency.test.ts@@ -0,0 +1,115 @@+/**+ * `Brain/pinned.md` under concurrent writers.+ *+ * Every pinned operation is a read-modify-write of one file. The atomic+ * rename guarantees no reader sees a torn file, and nothing about a+ * second writer that read the same "before" state: without a lock two+ * agents appending at once lose one append. These tests spawn real+ * `bun` children, the same discipline as+ * `tests/core/brain/ingest/concurrent-shared-writes.test.ts`.+ */++import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import { existsSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import { bootstrapBrain } from "../../../src/core/brain/init.ts";+import { brainPinnedPath } from "../../../src/core/brain/paths.ts";+import { readPinnedContext } from "../../../src/core/brain/pinned.ts";++const WRITERS = 4;+const PER_WRITER = 15;+const SPAWN_TIMEOUT_MS = 60_000;+/** Children spin until a shared instant so their writes really overlap. */+const BARRIER_LEAD_MS = 1_500;++let root: string;+let vault: string;++beforeEach(() => {+ root = mkdtempSync(join(tmpdir(), "o2b-pinned-race-"));+ vault = join(root, "vault");+ bootstrapBrain(vault);+});++afterEach(() => {+ rmSync(root, { recursive: true, force: true });+});++function srcModule(rel: string): string {+ return join(import.meta.dir, "../../../src", rel);+}++async function runWriters(lines: readonly string[]): Promise<void> {+ const script = join(root, "pinned-writer.ts");+ writeFileSync(+ script,+ [+ "const [vault, tag, count, startAt] = process.argv.slice(2);",+ "while (Date.now() < Number(startAt)) Bun.sleepSync(1);",+ ...lines,+ ].join("\n"),+ "utf8",+ );+ const startAt = String(Date.now() + BARRIER_LEAD_MS);+ const procs = Array.from({ length: WRITERS }, (_, index) =>+ Bun.spawn([process.execPath, script, vault, `w${index}`, String(PER_WRITER), startAt], {+ stdout: "pipe",+ stderr: "pipe",+ env: { ...process.env },+ }),+ );+ const failures: string[] = [];+ await Promise.all(+ procs.map(async (proc) => {+ const err = await new Response(proc.stderr).text();+ const code = await proc.exited;+ if (code !== 0) failures.push(`exit ${code}: ${err.trim()}`);+ }),+ );+ expect(failures).toEqual([]);+}++function expectedTokens(): string[] {+ const out: string[] = [];+ for (let w = 0; w < WRITERS; w++) {+ for (let i = 0; i < PER_WRITER; i++) out.push(`note-w${w}-${i}`);+ }+ return out;+}++describe("pinned context concurrent writers", () => {+ test(+ "every append from concurrent processes lands",+ async () => {+ await runWriters([+ `import { appendPinnedContext } from ${JSON.stringify(srcModule("core/brain/pinned.ts"))};`,+ "for (let i = 0; i < Number(count); i++) appendPinnedContext(vault, `note-${tag}-${i}`);",+ ]);++ const content = readPinnedContext(vault).content;+ const missing = expectedTokens().filter((token) => !content.includes(token));+ expect(missing).toEqual([]);+ expect(existsSync(`${brainPinnedPath(vault)}.lock`)).toBe(false);+ },+ SPAWN_TIMEOUT_MS,+ );++ test(+ "every batch append from concurrent processes lands",+ async () => {+ await runWriters([+ `import { applyPinnedOperations } from ${JSON.stringify(srcModule("core/brain/pinned.ts"))};`,+ "for (let i = 0; i < Number(count); i++) {",+ " applyPinnedOperations(vault, [{ op: 'append', content: `note-${tag}-${i}` }]);",+ "}",+ ]);++ const content = readPinnedContext(vault).content;+ const missing = expectedTokens().filter((token) => !content.includes(token));+ expect(missing).toEqual([]);+ },+ SPAWN_TIMEOUT_MS,+ );+});diff --git a/tests/core/brain/snapshot-gate-coverage.test.ts b/tests/core/brain/snapshot-gate-coverage.test.tsindex 1301b15c..9c27e2ab 100644--- a/tests/core/brain/snapshot-gate-coverage.test.ts+++ b/tests/core/brain/snapshot-gate-coverage.test.ts@@ -257,10 +257,16 @@ describe("the dream pass runs behind the gate, not beside it", () => {// bootstrapped `_BRAIN.md` names the new directory. Verified before// updating: with `dream.archive_stale_signals: false` and the previous// manual template this branch reproduces the previous literal exactly.+ //+ // Re-measured a FIFTH time, for one named reason: the bootstrapped+ // `_BRAIN.md` carries a `template_revision:` line in its frontmatter,+ // so a release never rewrites a manual a newer release wrote. Verified+ // before updating: with that one template line removed, this branch+ // reproduces the previous literal exactly.seedSignal("tidy");dream(vault, { now: NOW, agentName: "tester" });expect(dreamOutputDigest(join(vault, "Brain"))).toBe(- "cc900f3916b844d2fb04f8156b04a5e0ee6f70115035f790580742e036477f61",+ "044a18bcd0538c768e0c5d98e071125683805ceb6579f2acbadc96916a126210",);});diff --git a/tests/core/brain/snapshot-retention-order.test.ts b/tests/core/brain/snapshot-retention-order.test.tsnew file mode 100644index 00000000..682e8dd4--- /dev/null+++ b/tests/core/brain/snapshot-retention-order.test.ts@@ -0,0 +1,258 @@+/**+ * Snapshot retention for every reason, ordered by manifest time.+ *+ * Two defects found on a live install (911 upgrade archives, 1.7 GB):+ *+ * - `applyUpgrade` took its pre-apply snapshot straight through+ * `createSnapshot` and never pruned, so upgrade archives escaped+ * `snapshots.retention_count` entirely.+ * - Retention ordered archives by file mtime, which `rsync -t`,+ * `cp -p` or a stepped clock can make lie. The creation time the+ * manifest sidecar records is the order that matters.+ */++import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import {+ mkdirSync,+ mkdtempSync,+ readFileSync,+ rmSync,+ unlinkSync,+ utimesSync,+ writeFileSync,+} from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import { bootstrapBrain } from "../../../src/core/brain/init.ts";+import { manifestSidecarPath } from "../../../src/core/brain/manifest.ts";+import { brainConfigPath, brainManualPath, snapshotPath } from "../../../src/core/brain/paths.ts";+import { createSnapshot, listSnapshots, pruneSnapshots } from "../../../src/core/brain/snapshot.ts";+import { BRAIN_SNAPSHOT_REASON } from "../../../src/core/brain/types.ts";+import { importClaudeMemory } from "../../../src/core/brain/import-claude-memory.ts";+import { promoteHostMemory } from "../../../src/core/brain/continuity/promote-host-memory.ts";+import { recordHostMemoryWrite } from "../../../src/core/brain/host-memory-write.ts";+import { applyUpgrade } from "../../../src/core/brain/upgrade.ts";+import { atomicWriteFileSync } from "../../../src/core/fs-atomic.ts";++let root: string;+let vault: string;+let configPath: string;++beforeEach(() => {+ root = mkdtempSync(join(tmpdir(), "o2b-snap-retention-"));+ vault = join(root, "vault");+ configPath = join(root, "config.yaml");+ atomicWriteFileSync(configPath, `vault: ${vault}\n`);+ bootstrapBrain(vault, { configPath });+});++afterEach(() => {+ rmSync(root, { recursive: true, force: true });+});++function setRetention(count: number): void {+ const path = brainConfigPath(vault);+ const body = readFileSync(path, "utf8").replace(+ /retention_count: \d+/,+ `retention_count: ${count}`,+ );+ atomicWriteFileSync(path, body);+}++/**+ * Plant an archive whose manifest records `createdAt` while its file+ * mtime claims `mtime`: the shape a copied or clock-skewed archive has.+ */+function plantArchive(runId: string, createdAt: string, mtime: string): void {+ createSnapshot(vault, runId, { reason: BRAIN_SNAPSHOT_REASON.upgrade });+ const sidecar = manifestSidecarPath(vault, runId);+ const manifest = JSON.parse(readFileSync(sidecar, "utf8")) as Record<string, unknown>;+ manifest["generated_at"] = createdAt;+ writeFileSync(sidecar, JSON.stringify(manifest));+ const when = new Date(mtime);+ utimesSync(snapshotPath(vault, runId), when, when);+}++function runIds(): string[] {+ return listSnapshots(vault).snapshots.map((s) => s.run_id);+}++describe("snapshot retention order", () => {+ test("archives are listed newest-first by manifest creation time, not mtime", () => {+ // Manifest order a < b < c; mtimes claim the reverse.+ plantArchive("upgrade-a", "2026-01-01T00:00:00Z", "2026-12-03T00:00:00Z");+ plantArchive("upgrade-b", "2026-01-02T00:00:00Z", "2026-12-02T00:00:00Z");+ plantArchive("upgrade-c", "2026-01-03T00:00:00Z", "2026-12-01T00:00:00Z");++ expect(runIds()).toEqual(["upgrade-c", "upgrade-b", "upgrade-a"]);+ });++ test("prune removes the oldest by manifest time even when mtimes say otherwise", () => {+ plantArchive("upgrade-a", "2026-01-01T00:00:00Z", "2026-12-03T00:00:00Z");+ plantArchive("upgrade-b", "2026-01-02T00:00:00Z", "2026-12-02T00:00:00Z");+ plantArchive("upgrade-c", "2026-01-03T00:00:00Z", "2026-12-01T00:00:00Z");++ const res = pruneSnapshots(vault, 1);++ expect(res.refusal).toBeNull();+ expect(runIds()).toEqual(["upgrade-c"]);+ });++ test("an archive without a readable sidecar is ordered by its mtime", () => {+ plantArchive("upgrade-a", "2026-01-03T00:00:00Z", "2026-01-01T00:00:00Z");+ plantArchive("upgrade-b", "2026-01-02T00:00:00Z", "2026-01-02T00:00:00Z");+ // Without its sidecar, a's manifest time (newest) is gone: its mtime (oldest) counts.+ unlinkSync(manifestSidecarPath(vault, "upgrade-a"));++ expect(runIds()).toEqual(["upgrade-b", "upgrade-a"]);+ });++ test("an unparseable generated_at falls back to the mtime instead of sorting as NaN", () => {+ plantArchive("upgrade-a", "garbage", "2026-01-01T00:00:00Z");+ plantArchive("upgrade-b", "2026-01-02T00:00:00Z", "2026-01-02T00:00:00Z");+ plantArchive("upgrade-c", "2026-01-03T00:00:00Z", "2026-01-03T00:00:00Z");++ expect(runIds()).toEqual(["upgrade-c", "upgrade-b", "upgrade-a"]);+ });++ test("archives taken in the same second are ordered by mtime, then by run id", () => {+ plantArchive("upgrade-a", "2026-01-02T00:00:00Z", "2026-01-02T00:00:05Z");+ plantArchive("upgrade-b", "2026-01-02T00:00:00Z", "2026-01-02T00:00:01Z");+ plantArchive("upgrade-c", "2026-01-02T00:00:00Z", "2026-01-02T00:00:01Z");++ expect(runIds()).toEqual(["upgrade-a", "upgrade-c", "upgrade-b"]);+ });++ test("a protected run id survives even when it is the oldest", () => {+ plantArchive("upgrade-a", "2026-01-01T00:00:00Z", "2026-01-01T00:00:00Z");+ plantArchive("upgrade-b", "2026-01-02T00:00:00Z", "2026-01-02T00:00:00Z");+ plantArchive("upgrade-c", "2026-01-03T00:00:00Z", "2026-01-03T00:00:00Z");++ pruneSnapshots(vault, 1, { protectRunIds: ["upgrade-a"] });++ expect(runIds()).toEqual(["upgrade-a"]);+ });+});++describe("a sidecar stamp that cannot be right", () => {+ test("a far-future generated_at does not pin its archive as the newest", () => {+ plantArchive("upgrade-a", "2026-01-01T00:00:00Z", "2026-01-01T00:00:00Z");+ plantArchive("upgrade-b", "2026-01-02T00:00:00Z", "2026-01-02T00:00:00Z");+ // A broken clock or an edit: ordered by its mtime, the oldest here.+ plantArchive("upgrade-broken", "2099-01-01T00:00:00Z", "2025-12-01T00:00:00Z");++ const listed = listSnapshots(vault).snapshots;+ expect(listed.map((s) => s.run_id)).toEqual(["upgrade-b", "upgrade-a", "upgrade-broken"]);+ const broken = listed.find((s) => s.run_id === "upgrade-broken")!;+ expect(broken.created_at).toBe("2025-12-01T00:00:00.000Z");+ expect(broken.created_at_untrusted).toContain("later than now");+ expect(listed.find((s) => s.run_id === "upgrade-b")!.created_at_untrusted).toBeUndefined();++ pruneSnapshots(vault, 1);+ expect(runIds()).toEqual(["upgrade-b"]);+ });++ test("a stamp carrying control characters is reported without them", () => {+ plantArchive(+ "upgrade-odd",+ "Fri Jan 01 2099 00:00:00 GMT+0000 (x\n\u001b[2J\u007f\u009b2J\u0085)",+ "2026-01-01T00:00:00Z",+ );+ const reason = listSnapshots(vault).snapshots[0]!.created_at_untrusted!;+ expect(reason).toContain("later than now");+ expect(reason).not.toMatch(/[\u0000-\u001f\u007f-\u009f]/);+ expect(reason).toContain("\\u009b2J");+ });++ test("a generated_at earlier than the run id's own time falls back to the mtime", () => {+ plantArchive("upgrade-2026-03-01-120000", "2020-01-01T00:00:00Z", "2026-03-01T12:00:05Z");+ plantArchive("upgrade-2026-02-01-120000", "2026-02-01T12:00:01Z", "2026-02-01T12:00:01Z");++ const listed = listSnapshots(vault).snapshots;+ expect(listed.map((s) => s.run_id)).toEqual([+ "upgrade-2026-03-01-120000",+ "upgrade-2026-02-01-120000",+ ]);+ expect(listed[0]!.created_at).toBe("2026-03-01T12:00:05.000Z");+ expect(listed[0]!.created_at_untrusted).toContain("earlier than the run id's own time");+ expect(listed[1]!.created_at_untrusted).toBeUndefined();+ });+});++describe("upgrade snapshots obey retention", () => {+ test("applyUpgrade prunes older archives oldest-first and keeps its own", () => {+ setRetention(2);+ // Older recovery points, with mtimes reversed against manifest time+ // and all of them claiming to be newer than the upgrade about to run.+ plantArchive("upgrade-old-1", "2026-01-01T00:00:00Z", "2030-01-03T00:00:00Z");+ plantArchive("upgrade-old-2", "2026-01-02T00:00:00Z", "2030-01-02T00:00:00Z");+ plantArchive("upgrade-old-3", "2026-01-03T00:00:00Z", "2030-01-01T00:00:00Z");+ atomicWriteFileSync(brainManualPath(vault), "stale operator copy\n");++ const res = applyUpgrade(vault, { agent: "test-agent" });++ expect(res.run_id.startsWith("upgrade-")).toBe(true);+ const left = runIds();+ expect(left).toHaveLength(2);+ expect(left).toContain(res.run_id);+ expect(left).toContain("upgrade-old-3");+ });++ test("repeated upgrades never grow past the retention count", () => {+ setRetention(2);+ for (let i = 0; i < 4; i++) {+ atomicWriteFileSync(brainManualPath(vault), `stale operator copy ${i}\n`);+ const res = applyUpgrade(vault, {+ agent: "test-agent",+ now: new Date(Date.UTC(2026, 10, 6, 12, 0, i)),+ });+ expect(runIds()).toContain(res.run_id);+ }+ expect(runIds()).toHaveLength(2);+ });+});++describe("import snapshots obey retention", () => {+ test("a Claude memory import prunes older archives and keeps its own", () => {+ setRetention(1);+ plantArchive("upgrade-old-1", "2026-01-01T00:00:00Z", "2030-01-02T00:00:00Z");+ plantArchive("upgrade-old-2", "2026-01-02T00:00:00Z", "2030-01-01T00:00:00Z");+ const memoryDir = join(root, "memory");+ mkdirSync(memoryDir);+ writeFileSync(+ join(memoryDir, "feedback_a.md"),+ "---\nname: rule-a\ndescription: Rule A.\nmetadata:\n type: feedback\n---\n\nBody A.\n",+ );++ const res = importClaudeMemory({+ vault,+ memoryDir,+ mode: "apply",+ allowArbitraryMemoryPath: true,+ now: new Date("2026-11-06T10:00:00Z"),+ });++ expect(res.snapshotRunId).not.toBeNull();+ expect(runIds()).toEqual([res.snapshotRunId!]);+ });+});++describe("promote snapshots obey retention", () => {+ test("a host-memory promotion prunes older archives and keeps its own", () => {+ setRetention(1);+ plantArchive("upgrade-old-1", "2026-01-01T00:00:00Z", "2030-01-02T00:00:00Z");+ plantArchive("upgrade-old-2", "2026-01-02T00:00:00Z", "2030-01-01T00:00:00Z");+ recordHostMemoryWrite(vault, {+ action: "add",+ target: "user",+ content: "User prefers dark mode",+ createdAt: "2026-06-20T10:00:00Z",+ });++ const res = promoteHostMemory({ vault, mode: "apply", now: new Date("2026-07-01T12:00:00Z") });++ expect(res.snapshotRunId).toStartWith("promote-host-memory-");+ expect(runIds()).toEqual([res.snapshotRunId!]);+ });+});diff --git a/tests/core/brain/sync-lockfile.test.ts b/tests/core/brain/sync-lockfile.test.tsindex 3863ee83..29043108 100644--- a/tests/core/brain/sync-lockfile.test.ts+++ b/tests/core/brain/sync-lockfile.test.ts@@ -333,6 +333,7 @@ describe("every module that takes a lock is under a scanned root", () => {["core/brain/link-graph/hallways.ts", "Brain"],["core/brain/link-graph/orphan-repair.ts", "Brain"],["core/brain/payload-registry.ts", "Brain"],+ ["core/brain/pinned.ts", "Brain"],["core/brain/pledge-intake.ts", "Brain"],["core/brain/pledges.ts", "Brain"],["core/brain/preference-txn.ts", "Brain"],diff --git a/tests/core/brain/vault-guard-census.test.ts b/tests/core/brain/vault-guard-census.test.tsindex 88895a8f..d8a55219 100644--- a/tests/core/brain/vault-guard-census.test.ts+++ b/tests/core/brain/vault-guard-census.test.ts@@ -100,6 +100,14 @@ const UNGUARDED_WITH_REASON: Readonly<Record<string, string>> = Object.freeze({"fail-open injection cache. The hook contract is that a degraded injection " +"still returns something; a refusal here would turn a cache miss into a " +"broken SessionStart.",+ "src/core/brain/anticipatory-prune.ts":+ "retention of a derived cache. Its only caller, `refreshAnticipatoryCache`, " ++ "runs it right after its own guarded write, and a prune refused for want " ++ "of a write intent would only let the cache grow without bound.",+ "src/core/brain/log-append-io.ts":+ "append primitive over a caller-supplied path, the same shape as the lock " ++ "primitives above; its only caller, `appendLogEvent`, resolves the log " ++ "directory through `brainDirsForWrite` before it calls in.","src/core/brain/maintenance/lease.ts":"lock primitive. The lease file is how concurrent maintenance runs " +"serialize; the runs it protects are guarded at their own entry points, " +diff --git a/tests/core/brain/vault-name-case.test.ts b/tests/core/brain/vault-name-case.test.tsindex 88116527..c836177d 100644--- a/tests/core/brain/vault-name-case.test.ts+++ b/tests/core/brain/vault-name-case.test.ts@@ -1,6 +1,7 @@/*** `vault_name` in `Brain/_BRAIN.md` does not flip between two spellings of- * the same vault directory.+ * the same vault directory, nor between the directory names two devices+ * give one synced vault.** The display name is the basename of the vault path as the caller spelled* it. On a case-insensitive filesystem (macOS, Windows) `.../vault` and@@ -53,13 +54,20 @@ function manualPlan(vault: string) {return planUpgrade(vault).files.find((f) => f.path === "Brain/_BRAIN.md")!;}-/** Whether `root` itself treats `Vault` and `vault` as one name. */-function rootIsCaseInsensitive(): boolean {- mkdirSync(join(root, "Probe"));- const insensitive = existsSync(join(root, "probe"));- rmSync(join(root, "Probe"), { recursive: true });- return insensitive;+/**+ * Whether the temp filesystem treats `Vault` and `vault` as one name,+ * probed once in a directory of its own so a skip is reported as a skip.+ */+function tmpIsCaseInsensitive(): boolean {+ const probeRoot = mkdtempSync(join(tmpdir(), "o2b-case-probe-"));+ try {+ mkdirSync(join(probeRoot, "Probe"));+ return existsSync(join(probeRoot, "probe"));+ } finally {+ rmSync(probeRoot, { recursive: true, force: true });+ }}+const CASE_INSENSITIVE_TMP = tmpIsCaseInsensitive();describe("vault_name under two spellings of one vault directory", () => {test("a manual rendered under the other spelling is not a pending change", () => {@@ -79,32 +87,82 @@ describe("vault_name under two spellings of one vault directory", () => {});describe("vault_name for two different directories", () => {- test.skipIf(process.platform === "win32" || process.platform === "darwin")(- "a case-only difference that names ANOTHER directory is still a pending change",+ // A vault synced between devices is a different directory on each, often+ // under a different name (`/Users/<user>/Vault` on a Mac, `/root/vault` on+ // a server). The manual is synced content, so the name it already carries+ // stays; re-rendering it per device made every device undo the other's+ // write on every start.+ test.skipIf(CASE_INSENSITIVE_TMP)(+ "a manual synced from a directory named in another case is not a pending change",() => {- if (rootIsCaseInsensitive()) return;- // Two real vaults whose names differ only in case. The manual copied- // from `Vault` into `vault` really is stale there.const upper = join(root, "Vault");const lower = join(root, "vault");bootstrap(upper);bootstrap(lower);copyFileSync(brainManualPath(upper), brainManualPath(lower));- const plan = manualPlan(lower);-- expect(plan.status).toBe("update");- expect(plan.after).toContain("vault_name: vault");+ expect(manualPlan(lower).status).toBe("noop");},);- test("a manual naming an unrelated vault is still a pending change", () => {+ test("a manual naming an unrelated directory keeps that name", () => {const vault = join(root, "notes");bootstrap(vault);const path = brainManualPath(vault);const body = readFileSync(path, "utf8").replace("vault_name: notes", "vault_name: Elsewhere");atomicWriteFileSync(path, body);- expect(manualPlan(vault).status).toBe("update");+ expect(manualPlan(vault).status).toBe("noop");+ });++ test("a manual without a vault_name line gets this vault's name", () => {+ const vault = join(root, "notes");+ bootstrap(vault);+ const path = brainManualPath(vault);+ atomicWriteFileSync(path, readFileSync(path, "utf8").replace(/^vault_name: .*\n/m, ""));++ const plan = manualPlan(vault);++ expect(plan.status).toBe("update");+ expect(plan.after).toContain("vault_name: notes");+ });++ test("a vault_name line in the body is not the manual's name", () => {+ const vault = join(root, "notes");+ bootstrap(vault);+ const path = brainManualPath(vault);+ const body = readFileSync(path, "utf8").replace(/^vault_name: .*\n/m, "");+ atomicWriteFileSync(path, `${body}\nvault_name: Operator note\n`);++ const plan = manualPlan(vault);++ expect(plan.status).toBe("update");+ expect(plan.after).toContain("vault_name: notes");+ expect(plan.after).not.toContain("vault_name: Operator note\nschema_version");+ });++ test("a kept name that reads like a placeholder stays literal", () => {+ const vault = join(root, "notes");+ bootstrap(vault);+ const path = brainManualPath(vault);+ const named = readFileSync(path, "utf8").replace(+ "vault_name: notes",+ "vault_name: {{schema_version}}",+ );+ atomicWriteFileSync(path, named);++ expect(manualPlan(vault).status).toBe("noop");+ });++ test("a manual saved with a byte order mark keeps its name", () => {+ const vault = join(root, "notes");+ bootstrap(vault);+ const path = brainManualPath(vault);+ const named = readFileSync(path, "utf8").replace("vault_name: notes", "vault_name: Elsewhere");+ atomicWriteFileSync(path, `\uFEFF${named}`);++ const plan = manualPlan(vault);++ expect(plan.after).toContain("vault_name: Elsewhere");});});diff --git a/tests/core/brain/watchdog.test.ts b/tests/core/brain/watchdog.test.tsindex 29580fb1..af8d2c1e 100644--- a/tests/core/brain/watchdog.test.ts+++ b/tests/core/brain/watchdog.test.ts@@ -25,6 +25,30 @@ function seedHealthyVault(): void {}describe("runBrainWatchdog", () => {+ test("checks the search index where the search layer resolves it, not the vault default", () => {+ // The vault and its relocated index share one temp parent, so nothing+ // lands beside it in the shared temp directory.+ const parent = mkdtempSync(join(tmpdir(), "o2b-watchdog-relocated-"));+ const relocatedVault = join(parent, "vault");+ mkdirSync(relocatedVault);+ bootstrapBrain(relocatedVault);+ const relocated = join(parent, "index", "brain.sqlite");+ mkdirSync(join(parent, "index"));+ writeFileSync(relocated, "sqlite placeholder", "utf8");+ const previous = process.env.OPEN_SECOND_BRAIN_SEARCH_DB;+ process.env.OPEN_SECOND_BRAIN_SEARCH_DB = relocated;+ try {+ const result = runBrainWatchdog(relocatedVault, { now: new Date("2026-05-30T12:00:00Z") });+ expect(result.report.checks).toContainEqual(+ expect.objectContaining({ name: "search-index", status: "ok" }),+ );+ } finally {+ if (previous === undefined) delete process.env.OPEN_SECOND_BRAIN_SEARCH_DB;+ else process.env.OPEN_SECOND_BRAIN_SEARCH_DB = previous;+ rmSync(parent, { recursive: true, force: true });+ }+ });+test("reports healthy probes with backoff and audit metadata", () => {seedHealthyVault();diff --git a/tests/core/config.device-id.test.ts b/tests/core/config.device-id.test.tsindex 700b4bab..17bd0872 100644--- a/tests/core/config.device-id.test.ts+++ b/tests/core/config.device-id.test.ts@@ -8,12 +8,18 @@*/import { afterEach, beforeEach, describe, expect, test } from "bun:test";-import { mkdtempSync, readFileSync, rmSync } from "node:fs";+import { existsSync, mkdtempSync, readFileSync, rmSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";-import { resolveDeviceId } from "../../src/core/config.ts";+import {+ isUsableLocalDeviceId,+ isValidDeviceId,+ readDeviceId,+ resolveDeviceId,+} from "../../src/core/config.ts";import { atomicWriteFileSync } from "../../src/core/fs-atomic.ts";+import { IS_WINDOWS } from "../helpers/platform.ts";let configHome: string;let configPath: string;@@ -63,3 +69,57 @@ describe("resolveDeviceId", () => {expect(id).toMatch(/^[a-f0-9]{8}$/);});});++describe("isValidDeviceId", () => {+ test("accepts the names Windows reserves for devices: peers' data is judged alike everywhere", () => {+ for (const name of ["con", "prn", "aux", "nul", "com1", "lpt9"]) {+ expect(isValidDeviceId(name)).toBe(true);+ }+ expect(isValidDeviceId("sync-conflict-x")).toBe(false);+ expect(isValidDeviceId("Upper")).toBe(false);+ });+});++describe("isUsableLocalDeviceId", () => {+ test("on Windows refuses the names Windows reserves for devices, and only those", () => {+ for (const name of ["con", "prn", "aux", "nul", "com1", "com9", "lpt1", "lpt9"]) {+ expect(isUsableLocalDeviceId(name, "win32")).toBe(false);+ }+ for (const name of ["con1", "nul-box", "com10", "lpt0", "console", "aux-2"]) {+ expect(isUsableLocalDeviceId(name, "win32")).toBe(true);+ }+ });++ test("elsewhere a reserved Windows name stays a usable id", () => {+ for (const name of ["con", "nul", "com1", "lpt9"]) {+ expect(isUsableLocalDeviceId(name, "linux")).toBe(true);+ expect(isUsableLocalDeviceId(name, "darwin")).toBe(true);+ }+ });++ test("a reserved name in the config is replaced on Windows and kept elsewhere", () => {+ atomicWriteFileSync(configPath, 'device_id: "nul"\n');+ if (IS_WINDOWS) expect(resolveDeviceId(configPath)).toMatch(/^[a-f0-9]{8}$/);+ else expect(resolveDeviceId(configPath)).toBe("nul");+ });+});++describe("readDeviceId", () => {+ test("answers the configured id and never mints one", () => {+ expect(readDeviceId(configPath)).toBeNull();+ expect(existsSync(configPath)).toBe(false);+ atomicWriteFileSync(configPath, 'device_id: "vps-main"\n');+ expect(readDeviceId(configPath)).toBe("vps-main");+ });++ test("agrees with resolveDeviceId on the env override, opt-out included", () => {+ atomicWriteFileSync(configPath, 'device_id: "vps-main"\n');+ process.env["O2B_DEVICE_ID"] = "laptop-1";+ expect(readDeviceId(configPath)).toBe(resolveDeviceId(configPath));+ // The empty string opts out of a device identity: the writers then+ // write nothing, so a reader has no local device either.+ process.env["O2B_DEVICE_ID"] = "";+ expect(resolveDeviceId(configPath)).toBe("");+ expect(readDeviceId(configPath)).toBeNull();+ });+});diff --git a/tests/core/install/tool-ceiling.test.ts b/tests/core/install/tool-ceiling.test.tsindex 0fe5d3b6..040addad 100644--- a/tests/core/install/tool-ceiling.test.ts+++ b/tests/core/install/tool-ceiling.test.ts@@ -348,8 +348,9 @@ describe("the capability report states the ceiling it runs under", () => {// 118 registered tools through v1.90.0; the dated-commitments wave// added brain_pledge and brain_intake_pledges (120); the delivery-trust// wave added brain_attestations (121); the agent-presence wave added- // brain_skill_rewrite_status (122).- expect(evaluated.available_tool_count).toBe(122);+ // brain_skill_rewrite_status (122); the brain-store wave added+ // brain_changes (123).+ expect(evaluated.available_tool_count).toBe(123);expect(evaluated.advertised_tool_count).toBe(7);});});diff --git a/tests/core/maintenance/self-heal-upgrade-synced-vault.test.ts b/tests/core/maintenance/self-heal-upgrade-synced-vault.test.tsnew file mode 100644index 00000000..46302f75--- /dev/null+++ b/tests/core/maintenance/self-heal-upgrade-synced-vault.test.ts@@ -0,0 +1,227 @@+/**+ * The automatic Brain upgrade settles on a vault that several devices share+ * through a file sync, instead of re-applying on every start.+ *+ * A live vault synced between a Mac (`/Users/<user>/Vault`) and Linux hosts+ * (`/root/vault`, `/srv/vault`, `~/vault`) collected hundreds of+ * `upgrade-*` snapshots: every device rendered `vault_name` in+ * `Brain/_BRAIN.md` from its OWN path basename, saw the synced manual the+ * other device wrote as a pending upgrade, and the start-up self-heal+ * rewrote it back, pre-apply snapshot included. The sync then carried the+ * rewrite to the other device, which did the same.+ *+ * Devices on different releases fought the same way: an older release saw+ * the manual a newer release wrote as a pending upgrade and rewrote it back+ * to its own template. The manual now carries a `template_revision` stamp,+ * and a release never rewrites a manual from a newer revision.+ *+ * Each device is modelled as its own directory; "sync" copies the synced+ * vault content (everything but the device-local snapshots) from one+ * device's copy to the other's, as a file sync would. The newer release is+ * real code: a copy of `src/` whose manual template has one more line and a+ * revision one higher, run in its own process.+ */++import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from "bun:test";+import {+ cpSync,+ existsSync,+ mkdirSync,+ mkdtempSync,+ readdirSync,+ readFileSync,+ rmSync,+ symlinkSync,+ writeFileSync,+} from "node:fs";+import { tmpdir } from "node:os";+import { dirname, join, relative, resolve, sep } from "node:path";+import { fileURLToPath } from "node:url";++import { bootstrapBrain } from "../../../src/core/brain/init.ts";+import { brainManualPath, snapshotsDir } from "../../../src/core/brain/paths.ts";+import {+ BRAIN_MANUAL_TEMPLATE_REVISION,+ templateRevisionOf,+} from "../../../src/core/brain/templates.ts";+import { atomicWriteFileSync } from "../../../src/core/fs-atomic.ts";+import {+ runSelfHealUpgrade,+ SELF_HEAL_UPGRADE_OUTCOME,+} from "../../../src/core/maintenance/self-heal-upgrade.ts";++let root: string;+let mac: string;+let linux: string;+let prevConfigEnv: string | undefined;++beforeEach(() => {+ root = mkdtempSync(join(tmpdir(), "o2b-self-heal-synced-"));+ mac = join(root, "mac", "Vault");+ linux = join(root, "linux", "vault");+ mkdirSync(mac, { recursive: true });+ const configPath = join(root, "config.yaml");+ atomicWriteFileSync(configPath, `vault: ${mac}\n`);+ prevConfigEnv = process.env["OPEN_SECOND_BRAIN_CONFIG"];+ process.env["OPEN_SECOND_BRAIN_CONFIG"] = configPath;+ bootstrapBrain(mac, { configPath });+ sync(mac, linux);+});++afterEach(() => {+ if (prevConfigEnv === undefined) delete process.env["OPEN_SECOND_BRAIN_CONFIG"];+ else process.env["OPEN_SECOND_BRAIN_CONFIG"] = prevConfigEnv;+ rmSync(root, { recursive: true, force: true });+});++/** Copy the synced vault content from one device's copy to another's. */+function sync(from: string, to: string): void {+ const local = relative(from, snapshotsDir(from));+ cpSync(from, to, {+ recursive: true,+ filter: (src) => {+ const rel = relative(from, src);+ return rel !== local && !rel.startsWith(`${local}${sep}`);+ },+ });+}++function snapshotCount(vault: string): number {+ const dir = snapshotsDir(vault);+ return existsSync(dir) ? readdirSync(dir).length : 0;+}++describe("self-heal upgrade on a vault synced between devices", () => {+ test("devices whose vault directories are named differently do not re-apply", () => {+ const outcomes: string[] = [];+ for (let round = 0; round < 2; round++) {+ outcomes.push(runSelfHealUpgrade(linux).outcome);+ sync(linux, mac);+ outcomes.push(runSelfHealUpgrade(mac).outcome);+ sync(mac, linux);+ }++ expect(outcomes).toEqual(Array(4).fill(SELF_HEAL_UPGRADE_OUTCOME.current));+ expect(snapshotCount(mac)).toBe(0);+ expect(snapshotCount(linux)).toBe(0);+ });+});++const REPO_ROOT = resolve(dirname(fileURLToPath(import.meta.url)), "..", "..", "..");++/** The line only the newer release's manual template carries. */+const NEWER_TEMPLATE_LINE = "A rule only the newer release ships.";++/**+ * Build a newer release under `dir`: a copy of this release's `src/` whose+ * manual template has one more line and a revision one higher, plus a+ * runner that bootstraps a vault or runs the self-heal upgrade on one.+ * Returns the runner's path.+ */+function buildNewerRelease(dir: string): string {+ mkdirSync(dir, { recursive: true });+ cpSync(join(REPO_ROOT, "src"), join(dir, "src"), { recursive: true });+ cpSync(join(REPO_ROOT, "package.json"), join(dir, "package.json"));+ // A junction needs no privilege on Windows; other platforms ignore the type.+ symlinkSync(join(REPO_ROOT, "node_modules"), join(dir, "node_modules"), "junction");++ const templatesTs = join(dir, "src", "core", "brain", "templates.ts");+ const source = readFileSync(templatesTs, "utf8");+ const bumped = source.replace(+ /BRAIN_MANUAL_TEMPLATE_REVISION = (\d+);/,+ (_m, n: string) => `BRAIN_MANUAL_TEMPLATE_REVISION = ${Number(n) + 1};`,+ );+ if (bumped === source) throw new Error("templates.ts no longer declares the revision");+ writeFileSync(templatesTs, bumped);+ const template = join(dir, "src", "core", "brain", "templates", "_BRAIN.md.tpl");+ writeFileSync(template, `${readFileSync(template, "utf8")}\n${NEWER_TEMPLATE_LINE}\n`);++ const runner = join(dir, "run.ts");+ writeFileSync(+ runner,+ [+ 'import { bootstrapBrain } from "./src/core/brain/init.ts";',+ 'import { runSelfHealUpgrade } from "./src/core/maintenance/self-heal-upgrade.ts";',+ "const [verb, vault, configPath] = process.argv.slice(2);",+ 'if (verb === "bootstrap") bootstrapBrain(vault!, { configPath: configPath! });',+ "else process.stdout.write(runSelfHealUpgrade(vault!).outcome);",+ "",+ ].join("\n"),+ );+ return runner;+}++/** Run the newer release's runner; returns its stdout. */+function runNewer(runner: string, ...args: string[]): string {+ const proc = Bun.spawnSync([process.execPath, runner, ...args], {+ env: { ...process.env, OPEN_SECOND_BRAIN_CONFIG: join(root, "config.yaml") },+ stdout: "pipe",+ stderr: "pipe",+ });+ if (proc.exitCode !== 0) {+ throw new Error(`newer release failed: ${proc.stderr.toString()}`);+ }+ return proc.stdout.toString();+}++describe("self-heal upgrade on a vault synced between releases", () => {+ // `mac` runs the newer release, `linux` this one. The vault paths are+ // reused from the setup above; only the release differs.+ // Built once for the block, in its own temp directory: both tests only+ // read the release, and copying `src/` per test doubled the run time.+ let runner: string;+ let releaseRoot: string;++ beforeAll(() => {+ releaseRoot = mkdtempSync(join(tmpdir(), "o2b-self-heal-newer-release-"));+ runner = buildNewerRelease(join(releaseRoot, "newer-release"));+ });++ afterAll(() => {+ rmSync(releaseRoot, { recursive: true, force: true });+ });++ function alternate(rounds: number): string[] {+ const outcomes: string[] = [];+ for (let round = 0; round < rounds; round++) {+ outcomes.push(runNewer(runner, "self-heal", mac));+ sync(mac, linux);+ outcomes.push(runSelfHealUpgrade(linux).outcome);+ sync(linux, mac);+ }+ return outcomes;+ }++ test("a manual the newer release wrote is kept by the older one", () => {+ rmSync(mac, { recursive: true, force: true });+ rmSync(linux, { recursive: true, force: true });+ mkdirSync(mac, { recursive: true });+ runNewer(runner, "bootstrap", mac, join(root, "config.yaml"));+ sync(mac, linux);+ const written = readFileSync(brainManualPath(mac), "utf8");+ expect(templateRevisionOf(written)).toBe(BRAIN_MANUAL_TEMPLATE_REVISION + 1);++ const outcomes = alternate(2);++ expect(outcomes).toEqual(Array(4).fill(SELF_HEAL_UPGRADE_OUTCOME.current));+ expect(snapshotCount(mac)).toBe(0);+ expect(snapshotCount(linux)).toBe(0);+ expect(readFileSync(brainManualPath(linux), "utf8")).toBe(written);+ expect(readFileSync(brainManualPath(mac), "utf8")).toBe(written);+ }, 60_000);++ test("the newer release upgrades an older manual once and both then settle", () => {+ const outcomes = alternate(3);++ expect(outcomes).toEqual([+ SELF_HEAL_UPGRADE_OUTCOME.applied,+ ...Array(5).fill(SELF_HEAL_UPGRADE_OUTCOME.current),+ ]);+ // The one forward upgrade: one archive (with its sidecar manifest).+ expect(readdirSync(snapshotsDir(mac)).filter((f) => f.endsWith(".tar.zst"))).toHaveLength(1);+ expect(snapshotCount(linux)).toBe(0);+ const kept = readFileSync(brainManualPath(linux), "utf8");+ expect(kept).toContain(NEWER_TEMPLATE_LINE);+ expect(templateRevisionOf(kept)).toBe(BRAIN_MANUAL_TEMPLATE_REVISION + 1);+ }, 60_000);+});diff --git a/tests/core/platform-dirs.test.ts b/tests/core/platform-dirs.test.tsindex 59c3e8c0..60098142 100644--- a/tests/core/platform-dirs.test.ts+++ b/tests/core/platform-dirs.test.ts@@ -6,7 +6,7 @@*/import { describe, expect, test } from "bun:test";-import { join, win32 } from "node:path";+import { join, posix as posixPath, win32 } from "node:path";import {cacheBaseDir,@@ -35,15 +35,15 @@ function windows(vars: Record<string, string> = { LOCALAPPDATA: LOCAL }): Platfodescribe("POSIX defaults follow the XDG base directory layout", () => {test("config, data, state and cache", () => {- expect(configBaseDir(posix())).toBe(join(POSIX_HOME, ".config"));- expect(dataBaseDir(posix())).toBe(join(POSIX_HOME, ".local", "share"));- expect(stateBaseDir(posix())).toBe(join(POSIX_HOME, ".local", "state"));- expect(cacheBaseDir(posix())).toBe(join(POSIX_HOME, ".cache"));+ expect(configBaseDir(posix())).toBe(posixPath.join(POSIX_HOME, ".config"));+ expect(dataBaseDir(posix())).toBe(posixPath.join(POSIX_HOME, ".local", "share"));+ expect(stateBaseDir(posix())).toBe(posixPath.join(POSIX_HOME, ".local", "state"));+ expect(cacheBaseDir(posix())).toBe(posixPath.join(POSIX_HOME, ".cache"));});test("macOS keeps the XDG layout, not ~/Library", () => {const mac: PlatformDirsEnv = { platform: "darwin", home: "/Users/t", env: {} };- expect(configBaseDir(mac)).toBe(join("/Users/t", ".config"));+ expect(configBaseDir(mac)).toBe(posixPath.join("/Users/t", ".config"));});test("each XDG variable wins over its default", () => {@@ -60,7 +60,9 @@ describe("POSIX defaults follow the XDG base directory layout", () => {});test("an empty XDG variable counts as unset", () => {- expect(configBaseDir(posix({ XDG_CONFIG_HOME: "" }))).toBe(join(POSIX_HOME, ".config"));+ expect(configBaseDir(posix({ XDG_CONFIG_HOME: "" }))).toBe(+ posixPath.join(POSIX_HOME, ".config"),+ );});});diff --git a/tests/core/search/brain-store-catch-up-bench.test.ts b/tests/core/search/brain-store-catch-up-bench.test.tsnew file mode 100644index 00000000..d29a0070--- /dev/null+++ b/tests/core/search/brain-store-catch-up-bench.test.ts@@ -0,0 +1,92 @@+/**+ * The phase 1 catch-up benchmark (design D5): with 500 unchanged shards+ * the catch-up check before a read stays under 20 ms. That budget holds+ * on a quiet workstation only, so it is asserted only when `O2B_BENCH=1`+ * asks for the benchmark. Every other run (CI, a loaded laptop, Windows+ * with a virus scanner, coverage) asserts the functional half, that no+ * shard is read, and prints the measured value without judging it.+ */+import { afterEach, beforeEach, expect, test } from "bun:test";+import { mkdirSync, utimesSync, writeFileSync } from "node:fs";+import { dirname } from "node:path";++import { STORE_CATCH_UP_INTERVAL_ENV } from "../../../src/core/search/brain-store/constants.ts";+import { catchUpBrainStore } from "../../../src/core/search/brain-store/catch-up.ts";+import { indexVault } from "../../../src/core/search/indexer.ts";+import { buildRecord } from "../../../src/core/store/envelope.ts";+import { shardPath } from "../../../src/core/store/store-paths.ts";+import {+ LOCAL_DEVICE,+ makeStoreIndexFixture,+ type StoreIndexFixture,+} from "./fixtures/brain-store-index.ts";++const DEVICES = 100;+const MONTHS = 5;+const BUDGET_MS = 20;+/** Environment variable that asks for the strict benchmark budget. */+const BENCH_ENV = "O2B_BENCH";+const RUNS = 7;++let fx: StoreIndexFixture;+let savedInterval: string | undefined;+beforeEach(() => {+ savedInterval = process.env[STORE_CATCH_UP_INTERVAL_ENV];+ process.env[STORE_CATCH_UP_INTERVAL_ENV] = "0";+ fx = makeStoreIndexFixture("osb-store-bench-");+});+afterEach(() => {+ if (savedInterval === undefined) delete process.env[STORE_CATCH_UP_INTERVAL_ENV];+ else process.env[STORE_CATCH_UP_INTERVAL_ENV] = savedInterval;+ fx.cleanup();+});++test("the catch-up check over 500 unchanged shards stays within budget", async () => {+ fx.open(LOCAL_DEVICE);+ const config = fx.config();+ await indexVault(config);+ const dirs = new Set<string>();+ for (let d = 0; d < DEVICES; d++) {+ const device = `dev-${String(d).padStart(3, "0")}`;+ for (let m = 1; m <= MONTHS; m++) {+ const month = `2026-0${m}`;+ const path = shardPath(fx.root, "shared", { stream: "digests" }, device, month);+ mkdirSync(dirname(path), { recursive: true });+ const record = buildRecord({+ hlc: { physical: Date.UTC(2026, m - 1, 2), counter: d },+ device,+ agent: "bench",+ kind: "digest",+ body: { n: d * MONTHS + m },+ });+ writeFileSync(path, `${JSON.stringify(record)}\n`);+ dirs.add(dirname(path));+ dirs.add(dirname(dirname(path)));+ }+ }+ // A store at rest: its directories were last changed well before now.+ const past = new Date(Date.now() - 60_000);+ for (const dir of dirs) utimesSync(dir, past, past);++ const first = await catchUpBrainStore(config);+ expect(first.added).toBe(DEVICES * MONTHS);++ const samples: number[] = [];+ for (let i = 0; i < RUNS; i++) {+ const t0 = performance.now();+ // Sequential by design: each run measures one catch-up check on its own.+ // eslint-disable-next-line no-await-in-loop+ const result = await catchUpBrainStore(config);+ samples.push(performance.now() - t0);+ expect(result).toMatchObject({ skipped: null, shardsRead: 0 });+ }+ const median = samples.toSorted((a, b) => a - b)[Math.floor(RUNS / 2)]!;+ const benchmark = process.env[BENCH_ENV] === "1";+ // eslint-disable-next-line no-console+ console.log(+ `catch-up check, ${DEVICES * MONTHS} unchanged shards: median ${median.toFixed(2)} ms ` ++ `(runs: ${samples.map((s) => s.toFixed(2)).join(", ")}; ` ++ `${benchmark ? `budget ${BUDGET_MS} ms` : `not judged, set ${BENCH_ENV}=1`})`,+ );+ if (benchmark) expect(median).toBeLessThan(BUDGET_MS);+}, 60_000);diff --git a/tests/core/search/brain-store-catch-up-edges.test.ts b/tests/core/search/brain-store-catch-up-edges.test.tsnew file mode 100644index 00000000..abcce68e--- /dev/null+++ b/tests/core/search/brain-store-catch-up-edges.test.ts@@ -0,0 +1,157 @@+/**+ * Catch-up edge cases (design D3, D5): a spilled body whose blob arrives+ * after its line, a line from a newer format version, a rebuild that+ * re-reads every shard from offset 0, and the receive rule of the clock.+ */+import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import { appendFileSync, readFileSync, rmSync, writeFileSync } from "node:fs";++import { TRANSPORT_REACH } from "../../../src/core/graph/transport-reach.ts";+import { STORE_CATCH_UP_INTERVAL_ENV } from "../../../src/core/search/brain-store/constants.ts";+import { catchUpBrainStore } from "../../../src/core/search/brain-store/catch-up.ts";+import { storeRecordPath } from "../../../src/core/search/brain-store/ingest.ts";+import { indexVault, reindexVault } from "../../../src/core/search/indexer.ts";+import { search } from "../../../src/core/search/search.ts";+import { Store } from "../../../src/core/search/store.ts";+import type { ResolvedSearchConfig } from "../../../src/core/search/types.ts";+import { appendRecord } from "../../../src/core/store/appender.ts";+import { readClock } from "../../../src/core/store/clock-store.ts";+import { compareHlc, parseHlc } from "../../../src/core/store/hlc.ts";+import { blobPath, partitionDir } from "../../../src/core/store/store-paths.ts";+import {+ LOCAL_DEVICE,+ makeStoreIndexFixture,+ REMOTE_DEVICE,+ type StoreIndexFixture,+} from "./fixtures/brain-store-index.ts";++let fx: StoreIndexFixture;+const saved: Record<string, string | undefined> = {};+beforeEach(() => {+ saved["interval"] = process.env[STORE_CATCH_UP_INTERVAL_ENV];+ saved["device"] = process.env["O2B_DEVICE_ID"];+ process.env[STORE_CATCH_UP_INTERVAL_ENV] = "0";+ fx = makeStoreIndexFixture("osb-store-edges-");+});+afterEach(() => {+ if (saved["interval"] === undefined) delete process.env[STORE_CATCH_UP_INTERVAL_ENV];+ else process.env[STORE_CATCH_UP_INTERVAL_ENV] = saved["interval"];+ if (saved["device"] === undefined) delete process.env["O2B_DEVICE_ID"];+ else process.env["O2B_DEVICE_ID"] = saved["device"];+ fx.cleanup();+});++async function readyIndex(): Promise<ResolvedSearchConfig> {+ fx.open(LOCAL_DEVICE);+ fx.writeNote("notes/a.md", "# A\n\nA note.\n");+ const config = fx.config();+ await indexVault(config);+ return config;+}++async function found(config: ResolvedSearchConfig, query: string): Promise<string[]> {+ const outcome = await search(config, { query, limit: 10, transportReach: TRANSPORT_REACH.local });+ return [...new Set(outcome.results.map((r) => r.path))];+}++async function scalar(config: ResolvedSearchConfig, sql: string): Promise<number> {+ const store = await Store.open(config, { mode: "read" });+ try {+ return store.rawQuery<{ n: number }>(sql)[0]!.n;+ } finally {+ await store.close();+ }+}++describe("catch-up edge cases", () => {+ test("a spilled body is indexed once its blob arrives", async () => {+ const config = await readyIndex();+ const filler = "lorem ".repeat(4000);+ const { record, spilled } = appendRecord(fx.open(REMOTE_DEVICE), {+ partition: "shared",+ stream: "events",+ kind: "decision",+ agent: "agent-b",+ body: { text: `Phalarope migration plan ${filler}` },+ });+ expect(spilled).toBe(true);+ const blob = blobPath(partitionDir(fx.root, "shared"), record.sum);+ const bytes = readFileSync(blob);+ rmSync(blob);++ expect(await found(config, "phalarope")).toEqual([]);+ expect(await scalar(config, "SELECT COUNT(*) AS n FROM records WHERE body_pending = 1")).toBe(+ 1,+ );++ writeFileSync(blob, bytes);+ expect(await found(config, "phalarope")).toEqual([storeRecordPath("shared", record.id)]);+ expect(await scalar(config, "SELECT COUNT(*) AS n FROM records WHERE body_pending = 1")).toBe(+ 0,+ );+ });++ test("a newer-version line is skipped and counted, and the rest is indexed", async () => {+ const config = await readyIndex();+ const b = fx.open(REMOTE_DEVICE);+ const first = appendRecord(b, {+ partition: "shared",+ stream: "events",+ kind: "decision",+ agent: "agent-b",+ body: { text: "Godwit decision one" },+ });+ appendFileSync(+ first.path,+ `${JSON.stringify({ ...first.record, v: 99, id: "01M00000000000000000000000" })}\n`,+ );+ appendRecord(b, {+ partition: "shared",+ stream: "events",+ kind: "decision",+ agent: "agent-b",+ body: { text: "Godwit decision two" },+ });+ expect((await found(config, "godwit")).length).toBe(2);+ expect(await scalar(config, "SELECT SUM(unknown_versions) AS n FROM store_watermarks")).toBe(1);+ });++ test("a rebuild re-reads every shard from offset 0 into the swapped-in index", async () => {+ const config = await readyIndex();+ const { record } = appendRecord(fx.open(REMOTE_DEVICE), {+ partition: "shared",+ stream: "events",+ kind: "decision",+ agent: "agent-b",+ body: { text: "Whimbrel decision" },+ });+ await catchUpBrainStore(config);+ await reindexVault(config);+ // Straight after the swap, before any catch-up: the record is there.+ expect(await scalar(config, "SELECT COUNT(*) AS n FROM records")).toBe(1);+ expect(await found(config, "whimbrel")).toEqual([storeRecordPath("shared", record.id)]);+ });++ test("catch-up raises the local clock to the largest remote clock it ingested", async () => {+ const config = await readyIndex();+ process.env["O2B_DEVICE_ID"] = LOCAL_DEVICE;+ const ahead = Date.now() + 60 * 60 * 1000;+ const { record } = appendRecord(+ fx.open(REMOTE_DEVICE),+ {+ partition: "shared",+ stream: "events",+ kind: "decision",+ agent: "agent-b",+ body: { text: "x" },+ },+ { now: () => ahead },+ );+ await catchUpBrainStore(config);+ const local = readClock(config.brainStore!.deviceStateDir, LOCAL_DEVICE);+ expect(local).not.toBeNull();+ const remote = parseHlc(record.hlc);+ expect(remote).not.toBeNull();+ expect(compareHlc(local!, remote!)).toBeGreaterThanOrEqual(0);+ });+});diff --git a/tests/core/search/brain-store-catch-up-races.test.ts b/tests/core/search/brain-store-catch-up-races.test.tsnew file mode 100644index 00000000..6b56cd1c--- /dev/null+++ b/tests/core/search/brain-store-catch-up-races.test.ts@@ -0,0 +1,349 @@+/**+ * Catch-up under the moves a sync tool and a compaction make (design D5):+ * a record two shards hold for a while, a shard swapped while it is read,+ * a blob that arrives broken, and a pass that stops partway. In each case+ * the index must end up holding what the store holds, without a rebuild+ * and without reopening the index on every read.+ */+import { afterEach, beforeEach, describe, expect, spyOn, test } from "bun:test";+import * as fs from "node:fs";+import { dirname, join } from "node:path";++import { STORE_CATCH_UP_INTERVAL_ENV } from "../../../src/core/search/brain-store/constants.ts";+import { catchUpBrainStore } from "../../../src/core/search/brain-store/catch-up.ts";+import { storeRecordPath } from "../../../src/core/search/brain-store/ingest.ts";+import { indexVault, reindexVault } from "../../../src/core/search/indexer.ts";+import { RETRIEVAL_DEGRADATION } from "../../../src/core/search/retrieval-trail.ts";+import { search } from "../../../src/core/search/search.ts";+import { Store } from "../../../src/core/search/store.ts";+import { INDEX_REVISION_STATE_KEY } from "../../../src/core/search/store/state.ts";+import type { ResolvedSearchConfig } from "../../../src/core/search/types.ts";+import { TRANSPORT_REACH } from "../../../src/core/graph/transport-reach.ts";+import { appendRecord } from "../../../src/core/store/appender.ts";+import * as blobs from "../../../src/core/store/blobs.ts";+import { buildRecord, type StoreRecord } from "../../../src/core/store/envelope.ts";+import { blobPath, partitionDir, shardPath } from "../../../src/core/store/store-paths.ts";+import {+ LOCAL_DEVICE,+ makeStoreIndexFixture,+ REMOTE_DEVICE,+ type StoreIndexFixture,+} from "./fixtures/brain-store-index.ts";+import { CHMOD_CANNOT_DENY, IS_WINDOWS } from "../../helpers/platform.ts";++let fx: StoreIndexFixture;+let savedInterval: string | undefined;+beforeEach(() => {+ savedInterval = process.env[STORE_CATCH_UP_INTERVAL_ENV];+ process.env[STORE_CATCH_UP_INTERVAL_ENV] = "0";+ fx = makeStoreIndexFixture("osb-store-races-");+});+afterEach(() => {+ if (savedInterval === undefined) delete process.env[STORE_CATCH_UP_INTERVAL_ENV];+ else process.env[STORE_CATCH_UP_INTERVAL_ENV] = savedInterval;+ fx.cleanup();+});++async function readyIndex(): Promise<ResolvedSearchConfig> {+ fx.open(LOCAL_DEVICE);+ fx.writeNote("notes/a.md", "# A\n\nA note.\n");+ const config = fx.config();+ await indexVault(config);+ return config;+}++async function found(config: ResolvedSearchConfig, query: string): Promise<string[]> {+ const outcome = await search(config, { query, limit: 10, transportReach: TRANSPORT_REACH.local });+ return [...new Set(outcome.results.map((r) => r.path))];+}++async function readState(config: ResolvedSearchConfig, key: string): Promise<string | null> {+ const store = await Store.open(config, { mode: "read" });+ try {+ return store.getState(key);+ } finally {+ await store.close();+ }+}++const line = (record: StoreRecord): string => `${JSON.stringify(record)}\n`;++function remoteRecord(text: string, physical: number): StoreRecord {+ return buildRecord({+ hlc: { physical, counter: 0 },+ device: REMOTE_DEVICE,+ agent: "agent-b",+ kind: "decision",+ body: { text },+ });+}++function remoteShard(month: string, suffix = ""): string {+ const path = shardPath(fx.root, "shared", { stream: "events" }, REMOTE_DEVICE, month);+ return suffix === "" ? path : path.replace(/\.jsonl$/, `.${suffix}.jsonl`);+}++function writeShard(path: string, text: string): void {+ fs.mkdirSync(dirname(path), { recursive: true });+ fs.writeFileSync(path, text);+}++// A mode bit is the portable way to make one shard unreadable; it cannot+// stop root or a Windows reader.+const canDenyRead = !CHMOD_CANNOT_DENY;+// Windows refuses a rename over a file another handle holds open (EPERM), so a+// shard cannot be swapped under a reader that has it open there.+const testSwapUnderOpenReader = test.skipIf(IS_WINDOWS);++describe("catch-up races", () => {+ test("a compacted-away shard leaves the records its replacement holds", async () => {+ const config = await readyIndex();+ const a = remoteRecord("Stilt colony decision", Date.UTC(2026, 0, 5));+ const old = remoteShard("2026-01");+ const compacted = remoteShard("2026-01", "c1");+ // Both shards exist in one pass; the old one sorts last, so the+ // record is credited to it.+ writeShard(old, line(a));+ writeShard(compacted, line(a));+ await catchUpBrainStore(config);+ fs.rmSync(old);+ const pass = await catchUpBrainStore(config);+ expect(pass.removed).toBe(0);+ expect(await found(config, "stilt colony")).toEqual([storeRecordPath("shared", a.id)]);+ // Credited to the shard that holds it now: removing that one removes it.+ fs.rmSync(compacted);+ expect((await catchUpBrainStore(config)).removed).toBe(1);+ expect(await found(config, "stilt colony")).toEqual([]);+ });++ test.skipIf(!canDenyRead)(+ "a vanished shard does not read the device's other months to settle its records",+ async () => {+ const config = await readyIndex();+ const jan = remoteShard("2026-01");+ const feb = remoteShard("2026-02");+ writeShard(jan, line(remoteRecord("Sanderling decision", Date.UTC(2026, 0, 5))));+ writeShard(feb, line(remoteRecord("Dunlin decision", Date.UTC(2026, 1, 5))));+ await catchUpBrainStore(config);+ fs.chmodSync(feb, 0o000);+ try {+ fs.rmSync(jan);+ const pass = await catchUpBrainStore(config);+ expect(pass.skipped).toBeNull();+ expect(pass.removed).toBe(1);+ } finally {+ fs.chmodSync(feb, 0o644);+ }+ },+ );++ test.skipIf(!canDenyRead)(+ "a same-month sibling that cannot be read keeps the orphans instead of failing the pass",+ async () => {+ const config = await readyIndex();+ const a = remoteRecord("Whimbrel decision", Date.UTC(2026, 0, 5));+ const old = remoteShard("2026-01");+ const compacted = remoteShard("2026-01", "c1");+ writeShard(old, line(a));+ writeShard(compacted, line(a));+ await catchUpBrainStore(config);+ fs.chmodSync(compacted, 0o000);+ try {+ fs.rmSync(old);+ const pass = await catchUpBrainStore(config);+ expect(pass.skipped).toBeNull();+ expect(pass.removed).toBe(0);+ } finally {+ fs.chmodSync(compacted, 0o644);+ }+ expect(await found(config, "whimbrel")).toEqual([storeRecordPath("shared", a.id)]);+ },+ );++ test.skipIf(!canDenyRead)(+ "orphans a sibling could not settle are retried once it reads again",+ async () => {+ const config = await readyIndex();+ const a = remoteRecord("Godwit decision", Date.UTC(2026, 0, 5));+ const b = remoteRecord("Redshank decision", Date.UTC(2026, 0, 6));+ const old = remoteShard("2026-01");+ const sibling = remoteShard("2026-01", "c1");+ writeShard(old, line(a));+ // The sibling does not hold `a`: once it can be read, `a` has no shard.+ writeShard(sibling, line(b));+ await catchUpBrainStore(config);+ fs.chmodSync(sibling, 0o000);+ try {+ fs.rmSync(old);+ expect((await catchUpBrainStore(config)).removed).toBe(0);+ expect((await catchUpBrainStore(config)).removed).toBe(0);+ } finally {+ fs.chmodSync(sibling, 0o644);+ }+ expect((await catchUpBrainStore(config)).removed).toBe(1);+ expect(await found(config, "godwit")).toEqual([]);+ expect(await found(config, "redshank")).toEqual([storeRecordPath("shared", b.id)]);+ },+ );++ testSwapUnderOpenReader(+ "a shard swapped for a same-size file during its read is read again",+ async () => {+ const config = await readyIndex();+ const shard = remoteShard("2026-11");+ const a = remoteRecord("alpha knot", Date.UTC(2026, 10, 3));+ const b = remoteRecord("bravo knot", Date.UTC(2026, 10, 3));+ const c = remoteRecord("delta knot", Date.UTC(2026, 10, 3));+ expect(new Set([line(a).length, line(b).length, line(c).length]).size).toBe(1);+ writeShard(shard, line(a));+ await catchUpBrainStore(config);++ const swap = (text: string): void => {+ const tmp = join(dirname(shard), "swap.tmp");+ fs.writeFileSync(tmp, text);+ fs.renameSync(tmp, shard);+ };+ swap(line(b));+ const realOpen = fs.openSync;+ let swapped = false;+ const open = spyOn(fs, "openSync").mockImplementation(((+ ...args: Parameters<typeof realOpen>+ ) => {+ const fd = realOpen(...args);+ // The reader holds the file it opened; the sync tool swaps the path.+ if (!swapped && String(args[0]) === shard) {+ swapped = true;+ swap(line(c));+ }+ return fd;+ }) as typeof realOpen);+ try {+ await catchUpBrainStore(config);+ } finally {+ open.mockRestore();+ }+ expect(swapped).toBe(true);+ // The pass read b; the next one must not trust the stat it took of c.+ await catchUpBrainStore(config);+ expect(await found(config, "knot")).toEqual([storeRecordPath("shared", c.id)]);+ },+ );++ test("a blob that arrives just after the pass looked for it is read on the next pass", async () => {+ const config = await readyIndex();+ const { record, spilled } = appendRecord(fx.open(REMOTE_DEVICE), {+ partition: "shared",+ stream: "events",+ kind: "decision",+ agent: "agent-b",+ body: { text: `Avocet census ${"lorem ".repeat(4000)}` },+ });+ expect(spilled).toBe(true);+ const blob = blobPath(partitionDir(fx.root, "shared"), record.sum);+ const bytes = fs.readFileSync(blob);+ fs.rmSync(blob);+ // The sync tool delivers the blob right after the pass's last look for+ // it (the shard read looks first, the pending-body loop last).+ const original = blobs.readBlob;+ let looks = 0;+ const read = spyOn(blobs, "readBlob").mockImplementation((root, sha) => {+ const answer = original(root, sha);+ looks += 1;+ if (looks === 2) fs.writeFileSync(blob, bytes);+ return answer;+ });+ try {+ expect((await catchUpBrainStore(config)).completed).toBe(0);+ } finally {+ read.mockRestore();+ }+ expect(looks).toBe(2);+ expect((await catchUpBrainStore(config)).completed).toBe(1);+ expect(await found(config, "avocet census")).toEqual([storeRecordPath("shared", record.id)]);+ });++ test("a blob that fails verification does not reopen the index on every read", async () => {+ const config = await readyIndex();+ const { record, spilled } = appendRecord(fx.open(REMOTE_DEVICE), {+ partition: "shared",+ stream: "events",+ kind: "decision",+ agent: "agent-b",+ body: { text: `Pratincole survey ${"lorem ".repeat(4000)}` },+ });+ expect(spilled).toBe(true);+ const blob = blobPath(partitionDir(fx.root, "shared"), record.sum);+ const bytes = fs.readFileSync(blob);+ fs.rmSync(blob);+ await catchUpBrainStore(config);++ fs.writeFileSync(blob, bytes.subarray(0, bytes.length - 10));+ await catchUpBrainStore(config);+ const open = spyOn(Store, "open");+ try {+ expect(await catchUpBrainStore(config)).toMatchObject({ skipped: null, completed: 0 });+ expect(open).not.toHaveBeenCalled();+ } finally {+ open.mockRestore();+ }+ fs.writeFileSync(blob, bytes);+ expect((await catchUpBrainStore(config)).completed).toBe(1);+ });++ test.skipIf(!canDenyRead)("a pass that stops partway still moves the revision", async () => {+ const config = await readyIndex();+ const before = Number(await readState(config, INDEX_REVISION_STATE_KEY));+ writeShard(remoteShard("2026-10"), line(remoteRecord("Ruff decision", Date.UTC(2026, 9, 3))));+ const broken = remoteShard("2026-12");+ writeShard(broken, line(remoteRecord("Unread decision", Date.UTC(2026, 11, 3))));+ fs.chmodSync(broken, 0o000);+ try {+ const pass = await catchUpBrainStore(config);+ expect(pass.skipped).toBe("failed");+ expect(Number(await readState(config, INDEX_REVISION_STATE_KEY))).toBeGreaterThan(before);+ } finally {+ fs.chmodSync(broken, 0o644);+ }+ expect((await catchUpBrainStore(config)).skipped).toBeNull();+ expect((await found(config, "decision")).length).toBe(2);+ });++ test.skipIf(!canDenyRead)("a rebuild survives a shard it cannot read", async () => {+ const config = await readyIndex();+ const broken = remoteShard("2026-11");+ writeShard(broken, line(remoteRecord("Unread decision", Date.UTC(2026, 10, 3))));+ fs.chmodSync(broken, 0o000);+ try {+ await reindexVault(config);+ expect(await found(config, "note")).toEqual(["notes/a.md"]);+ } finally {+ fs.chmodSync(broken, 0o644);+ }+ // The next catch-up reads the shard the rebuild could not.+ expect(await found(config, "unread decision")).toHaveLength(1);+ });+});++describe("a failed catch-up on the search trail", () => {+ test.skipIf(!canDenyRead)("is a typed degradation beside its warning", async () => {+ const config = await readyIndex();+ const broken = remoteShard("2026-11");+ writeShard(broken, line(remoteRecord("Unread decision", Date.UTC(2026, 10, 3))));+ fs.chmodSync(broken, 0o000);+ try {+ const outcome = await search(config, {+ query: "note",+ limit: 5,+ transportReach: TRANSPORT_REACH.local,+ });+ expect(outcome.warnings).toEqual(+ expect.arrayContaining([expect.stringContaining("brain store catch-up failed")]),+ );+ expect(outcome.retrievalTrail?.degraded.map((d) => d.code)).toContain(+ RETRIEVAL_DEGRADATION.storeCatchUpFailed,+ );+ } finally {+ fs.chmodSync(broken, 0o644);+ }+ });+});diff --git a/tests/core/search/brain-store-catch-up.test.ts b/tests/core/search/brain-store-catch-up.test.tsnew file mode 100644index 00000000..090e1096--- /dev/null+++ b/tests/core/search/brain-store-catch-up.test.ts@@ -0,0 +1,373 @@+/**+ * Catch-up before reads (design D5, task 1.8): records appended to the+ * brain store become searchable without a reindex, an unchanged store+ * opens no store file, a replaced or truncated shard is re-read once and+ * holds each record once, and a notes-only search returns no brain record.+ */+import { afterEach, beforeEach, describe, expect, spyOn, test } from "bun:test";+import * as fs from "node:fs";+import { dirname, join } from "node:path";++import { STORE_CATCH_UP_INTERVAL_ENV } from "../../../src/core/search/brain-store/constants.ts";+import { catchUpBrainStore } from "../../../src/core/search/brain-store/catch-up.ts";+import { brainChanges } from "../../../src/core/search/brain-store/changes.ts";+import { REMOTE_DENY_VISIBILITY_TOKEN } from "../../../src/core/graph/visibility.ts";+import { storeRecordPath } from "../../../src/core/search/brain-store/ingest.ts";+import { indexVault } from "../../../src/core/search/indexer.ts";+import { search } from "../../../src/core/search/search.ts";+import { Store } from "../../../src/core/search/store.ts";+import { appendRecord } from "../../../src/core/store/appender.ts";+import { buildRecord, type StoreRecord } from "../../../src/core/store/envelope.ts";+import { shardPath } from "../../../src/core/store/store-paths.ts";+import type { ResolvedSearchConfig } from "../../../src/core/search/types.ts";+import { TRANSPORT_REACH } from "../../../src/core/graph/transport-reach.ts";+import {+ LOCAL_DEVICE,+ makeStoreIndexFixture,+ REMOTE_DEVICE,+ type StoreIndexFixture,+} from "./fixtures/brain-store-index.ts";++let fx: StoreIndexFixture;+let savedInterval: string | undefined;++beforeEach(() => {+ savedInterval = process.env[STORE_CATCH_UP_INTERVAL_ENV];+ process.env[STORE_CATCH_UP_INTERVAL_ENV] = "0";+ fx = makeStoreIndexFixture();+});+afterEach(() => {+ if (savedInterval === undefined) delete process.env[STORE_CATCH_UP_INTERVAL_ENV];+ else process.env[STORE_CATCH_UP_INTERVAL_ENV] = savedInterval;+ fx.cleanup();+});++async function readyIndex(): Promise<ResolvedSearchConfig> {+ fx.open(LOCAL_DEVICE);+ fx.writeNote("notes/heron.md", "# Heron note\n\nThe user wrote about herons at the lake.\n");+ const config = fx.config();+ await indexVault(config);+ return config;+}++function remoteAppend(+ text: string,+ extra: { scope?: string; topic?: string } = {},+): StoreRecord & { shardFile: string } {+ const b = fx.open(REMOTE_DEVICE);+ const result = appendRecord(b, {+ partition: "shared",+ stream: "events",+ kind: "decision",+ agent: "agent-b",+ ...extra,+ body: { text },+ });+ return { ...result.record, shardFile: result.path };+}++async function paths(config: ResolvedSearchConfig, query: string, source?: "notes" | "brain") {+ const outcome = await search(config, {+ query,+ limit: 10,+ transportReach: TRANSPORT_REACH.local,+ ...(source ? { source } : {}),+ });+ return outcome.results.map((r) => r.path);+}++async function recordCount(config: ResolvedSearchConfig): Promise<number> {+ const store = await Store.open(config, { mode: "read" });+ try {+ return store.rawQuery<{ n: number }>("SELECT COUNT(*) AS n FROM records")[0]!.n;+ } finally {+ await store.close();+ }+}++const line = (record: StoreRecord): string => `${JSON.stringify(record)}\n`;++function remoteRecord(text: string, physical: number): StoreRecord {+ return buildRecord({+ hlc: { physical, counter: 0 },+ device: REMOTE_DEVICE,+ agent: "agent-b",+ kind: "decision",+ body: { text },+ });+}++const NOV_2026 = Date.UTC(2026, 10, 3);++function remoteShard(): string {+ return shardPath(fx.root, "shared", { stream: "events" }, REMOTE_DEVICE, "2026-11");+}++describe("catch-up before reads", () => {+ test("a record from another machine is searchable without a reindex", async () => {+ const config = await readyIndex();+ const record = remoteAppend("Kingfisher nesting decision for the north bank");+ const found = await paths(config, "kingfisher nesting");+ expect(found).toContain(storeRecordPath("shared", record.id));+ });++ test("notes-only search returns no brain record, brain-only no note", async () => {+ const config = await readyIndex();+ const record = remoteAppend("Herons were seen at the lake again");+ const all = await paths(config, "herons lake");+ expect(all).toContain("notes/heron.md");+ expect(all).toContain(storeRecordPath("shared", record.id));+ const notes = await paths(config, "herons lake", "notes");+ expect(notes).toEqual(["notes/heron.md"]);+ const brain = await paths(config, "herons lake", "brain");+ expect(brain).toEqual([storeRecordPath("shared", record.id)]);+ });++ test("an unchanged store opens no store file", async () => {+ const config = await readyIndex();+ remoteAppend("First record");+ remoteAppend("Second record");+ const first = await catchUpBrainStore(config);+ expect(first.skipped).toBeNull();+ expect(first.added).toBe(2);+ const open = spyOn(fs, "openSync");+ const readFile = spyOn(fs, "readFileSync");+ const touched = (): string[] =>+ [...open.mock.calls, ...readFile.mock.calls]+ .map((call) => String(call[0]))+ .filter((p) => p.startsWith(fx.root));+ try {+ const again = await catchUpBrainStore(config);+ expect(again).toMatchObject({ skipped: null, shardsRead: 0, added: 0 });+ expect(touched()).toEqual([]);+ // The spy does see the reader: one more record is read through it.+ remoteAppend("Third record");+ open.mockClear();+ readFile.mockClear();+ expect((await catchUpBrainStore(config)).added).toBe(1);+ expect(touched().length).toBeGreaterThan(0);+ } finally {+ open.mockRestore();+ readFile.mockRestore();+ }+ });++ test("a shard replaced by a same-size file is re-read once and holds each record once", async () => {+ const config = await readyIndex();+ const shard = remoteShard();+ fs.mkdirSync(dirname(shard), { recursive: true });+ const a = remoteRecord("alpha plover", NOV_2026);+ const b = remoteRecord("gamma plover", NOV_2026);+ expect(line(a).length).toBe(line(b).length);+ fs.writeFileSync(shard, line(a));+ expect((await catchUpBrainStore(config)).added).toBe(1);++ const replacement = join(dirname(shard), "replacement.tmp");+ fs.writeFileSync(replacement, line(b));+ fs.renameSync(replacement, shard);+ const reread = await catchUpBrainStore(config);+ expect(reread).toMatchObject({ shardsRead: 1, added: 1, removed: 1 });+ expect(await recordCount(config)).toBe(1);+ expect(await paths(config, "plover")).toEqual([storeRecordPath("shared", b.id)]);+ expect((await catchUpBrainStore(config)).shardsRead).toBe(0);+ });++ test("a same-size rewrite in place is found by the prefix hash once its mtime moves", async () => {+ const config = await readyIndex();+ const shard = remoteShard();+ fs.mkdirSync(dirname(shard), { recursive: true });+ const a = remoteRecord("alpha sandpiper", NOV_2026);+ const b = remoteRecord("gamma sandpiper", NOV_2026);+ fs.writeFileSync(shard, line(a));+ await catchUpBrainStore(config);+ const before = fs.statSync(shard);+ fs.writeFileSync(shard, line(b));+ // Same inode, same size; only the mtime says something happened.+ fs.utimesSync(shard, before.atime, new Date(before.mtimeMs + 5000));+ expect(fs.statSync(shard).ino).toBe(before.ino);+ expect(fs.statSync(shard).size).toBe(before.size);+ const reread = await catchUpBrainStore(config);+ expect(reread).toMatchObject({ shardsRead: 1, added: 1, removed: 1 });+ expect(await paths(config, "sandpiper")).toEqual([storeRecordPath("shared", b.id)]);+ });++ test("a truncated shard is re-read from the start once, then resumes from its offset", async () => {+ const config = await readyIndex();+ const shard = remoteShard();+ fs.mkdirSync(dirname(shard), { recursive: true });+ const a = remoteRecord("first curlew", NOV_2026);+ const b = remoteRecord("second curlew", NOV_2026 + 1);+ fs.writeFileSync(shard, line(a) + line(b));+ expect((await catchUpBrainStore(config)).added).toBe(2);++ fs.truncateSync(shard, Buffer.byteLength(line(a)));+ const reread = await catchUpBrainStore(config);+ expect(reread).toMatchObject({ shardsRead: 1, added: 0, removed: 1 });+ expect(await recordCount(config)).toBe(1);+ expect((await catchUpBrainStore(config)).shardsRead).toBe(0);++ const c = remoteRecord("third curlew", NOV_2026 + 2);+ fs.appendFileSync(shard, line(c));+ expect(await catchUpBrainStore(config)).toMatchObject({ shardsRead: 1, added: 1, removed: 0 });+ expect(await recordCount(config)).toBe(2);+ });++ test("a half-delivered last line is read once the rest arrives, and only once", async () => {+ const config = await readyIndex();+ const shard = remoteShard();+ fs.mkdirSync(dirname(shard), { recursive: true });+ const a = remoteRecord("first lapwing", NOV_2026);+ const b = remoteRecord("second lapwing", NOV_2026 + 1);+ const cut = 30;+ fs.writeFileSync(shard, line(a) + line(b).slice(0, cut));+ expect(await catchUpBrainStore(config)).toMatchObject({ shardsRead: 1, added: 1 });+ expect(await paths(config, "second lapwing")).not.toContain(storeRecordPath("shared", b.id));++ fs.appendFileSync(shard, line(b).slice(cut));+ expect(await catchUpBrainStore(config)).toMatchObject({ shardsRead: 1, added: 1, removed: 0 });+ expect(await recordCount(config)).toBe(2);+ const found = await paths(config, "second lapwing");+ expect(found.filter((p) => p === storeRecordPath("shared", b.id))).toHaveLength(1);+ expect((await catchUpBrainStore(config)).shardsRead).toBe(0);+ });++ test("a complete last line that fails its checksum is read once a good copy replaces it", async () => {+ const config = await readyIndex();+ const shard = remoteShard();+ fs.mkdirSync(dirname(shard), { recursive: true });+ const a = remoteRecord("first stint", NOV_2026);+ const b = remoteRecord("second stint", NOV_2026 + 1);+ const damaged = { ...b, sum: "0".repeat(b.sum.length) };+ fs.writeFileSync(shard, line(a) + line(damaged));+ expect(await catchUpBrainStore(config)).toMatchObject({ shardsRead: 1, added: 1 });+ expect(await recordCount(config)).toBe(1);++ // The sync tool delivers the good copy over the damaged one.+ const before = fs.statSync(shard);+ fs.writeFileSync(shard, line(a) + line(b));+ fs.utimesSync(shard, before.atime, new Date(before.mtimeMs + 5000));+ expect(await catchUpBrainStore(config)).toMatchObject({ shardsRead: 1, added: 1, removed: 0 });+ expect(await recordCount(config)).toBe(2);+ expect(await paths(config, "second stint")).toContain(storeRecordPath("shared", b.id));+ });++ test("a deleted shard takes its records out of the index", async () => {+ const config = await readyIndex();+ const record = remoteAppend("Avocet survey decision");+ expect(await paths(config, "avocet")).toContain(storeRecordPath("shared", record.id));+ fs.rmSync(record.shardFile);+ expect(await paths(config, "avocet")).toEqual([]);+ expect(await recordCount(config)).toBe(0);+ });++ test("the incremental vault index keeps store records", async () => {+ const config = await readyIndex();+ const record = remoteAppend("Dunlin roost decision");+ await catchUpBrainStore(config);+ await indexVault(config);+ expect(await paths(config, "dunlin roost")).toContain(storeRecordPath("shared", record.id));+ });+});++describe("the private partition on the read side", () => {+ test("a private record is found locally, reserved as private, and grouped apart", async () => {+ const config = await readyIndex();+ const b = fx.open(REMOTE_DEVICE);+ const append = (partition: "shared" | "private", text: string) =>+ appendRecord(b, {+ partition,+ stream: "events",+ kind: "decision",+ agent: "agent-b",+ body: { text },+ }).record;+ const secret = append("private", "Garganey private decision");+ const open = append("shared", "Garganey shared decision");+ const found = await paths(config, "garganey");+ expect(found).toContain(storeRecordPath("private", secret.id));+ expect(found).toContain(storeRecordPath("shared", open.id));++ const store = await Store.open(config, { mode: "read" });+ try {+ const visibility = (path: string) =>+ store.rawQuery<{ v: string }>(+ `SELECT visibility AS v FROM documents WHERE path = '${path}'`,+ )[0]?.v;+ expect(JSON.parse(visibility(storeRecordPath("private", secret.id))!)).toEqual([+ REMOTE_DENY_VISIBILITY_TOKEN,+ ]);+ expect(JSON.parse(visibility(storeRecordPath("shared", open.id))!)).toEqual([]);+ } finally {+ await store.close();+ }++ const changes = await brainChanges(config);+ expect(changes.groups.map((g) => [g.partition, g.ids])).toEqual(+ expect.arrayContaining([+ ["private", [secret.id]],+ ["shared", [open.id]],+ ]),+ );+ expect(changes.groups).toHaveLength(2);+ });+});++describe("the throttle at its default interval", () => {+ test("a second look inside the window is skipped; a forced one still reads", async () => {+ delete process.env[STORE_CATCH_UP_INTERVAL_ENV];+ const config = await readyIndex();+ remoteAppend("Pratincole decision");+ expect(await catchUpBrainStore(config)).toMatchObject({ skipped: null, added: 1 });+ const late = remoteAppend("Courser decision");+ expect(await catchUpBrainStore(config)).toMatchObject({ skipped: "throttled", shardsRead: 0 });+ expect(await catchUpBrainStore(config, { force: true })).toMatchObject({+ skipped: null,+ added: 1,+ });+ expect(await paths(config, "courser")).toContain(storeRecordPath("shared", late.id));+ });+});++describe("reach", () => {+ test("a store record is withheld from a remote caller", async () => {+ const config = await readyIndex();+ const record = remoteAppend("Shelduck count decision");+ expect(await paths(config, "shelduck")).toContain(storeRecordPath("shared", record.id));+ // A note with the same word comes back, so the reach filter, not an+ // empty answer, is what withholds the record.+ fx.writeNote("notes/shelduck.md", "# Shelduck\n\nShelduck count at the estuary.\n");+ await indexVault(config);+ const remote = await search(config, { query: "shelduck", limit: 10 });+ expect(remote.results.map((r) => r.path)).toEqual(["notes/shelduck.md"]);+ });+});++describe("an index shared by both modes", () => {+ test("drops the store records once the vault reads no store", async () => {+ const config = await readyIndex();+ const record = remoteAppend("Oystercatcher decision");+ expect(await paths(config, "oystercatcher")).toContain(storeRecordPath("shared", record.id));+ // Same index file (an explicit search_db_path), the store no longer resolves.+ const storeless: ResolvedSearchConfig = Object.freeze({ ...config, brainStore: null });+ await indexVault(storeless);+ expect(await paths(storeless, "oystercatcher")).toEqual([]);+ expect(await paths(storeless, "heron")).toEqual(["notes/heron.md"]);+ expect(await recordCount(storeless)).toBe(0);+ // Back on the store: everything is read again.+ expect(await paths(config, "oystercatcher")).toContain(storeRecordPath("shared", record.id));+ });++ test("keeps the store records when a run cannot tell whether a store is in use", async () => {+ const config = await readyIndex();+ const record = remoteAppend("Turnstone decision");+ expect(await paths(config, "turnstone")).toContain(storeRecordPath("shared", record.id));+ // A store.json mid-rewrite: the run neither found the store nor its absence.+ const unsure: ResolvedSearchConfig = Object.freeze({+ ...config,+ brainStore: null,+ brainStoreUnknown: true,+ });+ await indexVault(unsure);+ expect(await recordCount(unsure)).toBeGreaterThan(0);+ });+});diff --git a/tests/core/search/brain-store-changes.test.ts b/tests/core/search/brain-store-changes.test.tsnew file mode 100644index 00000000..e7521ca4--- /dev/null+++ b/tests/core/search/brain-store-changes.test.ts@@ -0,0 +1,189 @@+/**+ * The change probe (design D5, task 1.9): new record ids since a+ * watermark, grouped by partition, stream, scope and topic, answered from+ * the index after catch-up.+ */+import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import { appendFileSync, chmodSync, mkdirSync, rmSync } from "node:fs";+import { dirname } from "node:path";++import { brainChanges } from "../../../src/core/search/brain-store/changes.ts";+import { STORE_CATCH_UP_INTERVAL_ENV } from "../../../src/core/search/brain-store/constants.ts";+import { indexVault, reindexVault } from "../../../src/core/search/indexer.ts";+import type { ResolvedSearchConfig } from "../../../src/core/search/types.ts";+import { appendRecord } from "../../../src/core/store/appender.ts";+import { buildRecord } from "../../../src/core/store/envelope.ts";+import { shardPath } from "../../../src/core/store/store-paths.ts";+import { newUlid } from "../../../src/core/store/ulid.ts";+import { makeConfig } from "../../helpers/search-fixtures.ts";+import {+ LOCAL_DEVICE,+ makeStoreIndexFixture,+ REMOTE_DEVICE,+ type StoreIndexFixture,+} from "./fixtures/brain-store-index.ts";+import { CHMOD_CANNOT_DENY } from "../../helpers/platform.ts";++let fx: StoreIndexFixture;+let savedInterval: string | undefined;+beforeEach(() => {+ savedInterval = process.env[STORE_CATCH_UP_INTERVAL_ENV];+ process.env[STORE_CATCH_UP_INTERVAL_ENV] = "0";+ fx = makeStoreIndexFixture("osb-store-changes-");+});+afterEach(() => {+ if (savedInterval === undefined) delete process.env[STORE_CATCH_UP_INTERVAL_ENV];+ else process.env[STORE_CATCH_UP_INTERVAL_ENV] = savedInterval;+ fx.cleanup();+});++async function readyIndex(): Promise<ResolvedSearchConfig> {+ fx.open(LOCAL_DEVICE);+ fx.writeNote("notes/a.md", "# A\n\nA note.\n");+ const config = fx.config();+ await indexVault(config);+ return config;+}++function neighbourDecision(text: string, scope: string | null, topic: string | null) {+ return appendRecord(fx.open(REMOTE_DEVICE), {+ partition: "shared",+ stream: "events",+ kind: "decision",+ agent: "agent-b",+ scope,+ topic,+ body: { text },+ }).record;+}++describe("brainChanges", () => {+ test("returns a neighbour's record id under its topic and scope", async () => {+ const config = await readyIndex();+ neighbourDecision("an earlier decision", null, null);+ const before = await brainChanges(config);+ expect(before.count).toBe(1);+ const w = before.watermark!;++ const topic = newUlid();+ const record = neighbourDecision("pick the north bank", "project:estuary", topic);+ const after = await brainChanges(config, { since: w });+ expect(after.reset).toBe(false);+ expect(after.count).toBe(1);+ expect(after.groups).toEqual([+ {+ partition: "shared",+ stream: "events",+ ledger: null,+ scope: "project:estuary",+ topic,+ ids: [record.id],+ },+ ]);+ // Nothing new since the watermark it returned.+ const idle = await brainChanges(config, { since: after.watermark! });+ expect(idle).toMatchObject({ count: 0, groups: [], watermark: after.watermark });+ });++ test("a late record with an older clock is still new after the watermark", async () => {+ const config = await readyIndex();+ neighbourDecision("first", null, null);+ const w = (await brainChanges(config)).watermark!;+ const late = buildRecord({+ hlc: { physical: Date.UTC(2025, 0, 1), counter: 0 },+ device: REMOTE_DEVICE,+ agent: "agent-b",+ kind: "decision",+ body: { text: "written offline long ago" },+ });+ const shard = shardPath(fx.root, "shared", { stream: "events" }, REMOTE_DEVICE, "2025-01");+ mkdirSync(dirname(shard), { recursive: true });+ appendFileSync(shard, `${JSON.stringify(late)}\n`);+ const after = await brainChanges(config, { since: w });+ expect(after.groups.flatMap((g) => g.ids)).toEqual([late.id]);+ });++ test("a record ingested after the newest one was removed is still new after the watermark", async () => {+ const config = await readyIndex();+ neighbourDecision("kept", null, null);+ await brainChanges(config);+ const late = buildRecord({+ hlc: { physical: Date.UTC(2025, 0, 1), counter: 0 },+ device: REMOTE_DEVICE,+ agent: "agent-b",+ kind: "decision",+ body: { text: "removed again" },+ });+ const shard = shardPath(fx.root, "shared", { stream: "events" }, REMOTE_DEVICE, "2025-01");+ mkdirSync(dirname(shard), { recursive: true });+ appendFileSync(shard, `${JSON.stringify(late)}\n`);+ const w = (await brainChanges(config)).watermark!;+ // The newest ingested record leaves with its shard; the next record+ // must not reuse its sequence and hide behind the watermark.+ rmSync(shard);+ expect((await brainChanges(config, { since: w })).count).toBe(0);+ const next = neighbourDecision("after the removal", null, null);+ const after = await brainChanges(config, { since: w });+ expect(after.groups.flatMap((g) => g.ids)).toEqual([next.id]);+ });++ test("a limit pages forward through the watermark", async () => {+ const config = await readyIndex();+ const a = neighbourDecision("one", null, null);+ const b = neighbourDecision("two", null, null);+ const first = await brainChanges(config, { limit: 1 });+ expect(first).toMatchObject({ truncated: true, count: 1 });+ expect(first.groups[0]!.ids).toEqual([a.id]);+ const second = await brainChanges(config, { since: first.watermark!, limit: 1 });+ expect(second).toMatchObject({ truncated: false, count: 1 });+ expect(second.groups[0]!.ids).toEqual([b.id]);+ });++ test("a watermark from a replaced index starts over and says so", async () => {+ const config = await readyIndex();+ const a = neighbourDecision("one", null, null);+ const w = (await brainChanges(config)).watermark!;+ await reindexVault(config);+ const after = await brainChanges(config, { since: w });+ expect(after.reset).toBe(true);+ expect(after.groups.flatMap((g) => g.ids)).toEqual([a.id]);+ });++ // An unreadable shard is the portable way to make a catch-up fail; a+ // mode bit cannot stop root or a Windows reader.+ const canDenyRead = !CHMOD_CANNOT_DENY;+ test.skipIf(!canDenyRead)("a failed catch-up is named in the warnings", async () => {+ const config = await readyIndex();+ const first = await brainChanges(config);+ expect(first.warnings).toEqual([]);+ const { path: shard } = appendRecord(fx.open(REMOTE_DEVICE), {+ partition: "shared",+ stream: "events",+ kind: "decision",+ agent: "agent-b",+ body: { text: "unreadable for now" },+ });+ chmodSync(shard, 0o000);+ try {+ const failed = await brainChanges(config, { since: first.watermark! });+ expect(failed.count).toBe(0);+ expect(failed.warnings).toEqual([+ expect.stringContaining("brain store catch-up failed, records may be missing"),+ ]);+ } finally {+ chmodSync(shard, 0o644);+ }+ const healed = await brainChanges(config, { since: first.watermark! });+ expect(healed).toMatchObject({ count: 1, warnings: [] });+ });++ test("a malformed watermark is refused by name", async () => {+ const config = await readyIndex();+ await expect(brainChanges(config, { since: "yesterday" })).rejects.toThrow("not a watermark");+ });++ test("without a store nothing is reported", async () => {+ const config = makeConfig({ vault: fx.vault, dbPath: `${fx.parent}/legacy.sqlite` });+ expect(await brainChanges(config)).toMatchObject({ storeInUse: false, watermark: null });+ });+});diff --git a/tests/core/search/brain-store-location.test.ts b/tests/core/search/brain-store-location.test.tsnew file mode 100644index 00000000..a2bc72ac--- /dev/null+++ b/tests/core/search/brain-store-location.test.ts@@ -0,0 +1,181 @@+/**+ * Where the search index lives (design D5, task 1.8): in the store's+ * device-local state when a store is in use, one file per vault, and at+ * the legacy vault location otherwise; an explicit override wins either+ * way.+ */+import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import { mkdirSync, symlinkSync, writeFileSync } from "node:fs";+import { dirname, join } from "node:path";++import { DERIVED_STORE_DIR, DERIVED_STORE_FILE } from "../../../src/core/brain/path-constants.ts";+import { resolveSearchConfig } from "../../../src/core/search/index.ts";+import {+ probeIndexedStore,+ resolveIndexedStore,+ storeIndexPath,+} from "../../../src/core/search/brain-store/location.ts";+import { resolveConfiguredIndexPath, resolveIndexPath } from "../../../src/core/search/paths.ts";+import {+ STORE_IDENTITY_FILE,+ STORE_ROOT_CONFIG_KEY,+ STORE_ROOT_ENV,+} from "../../../src/core/store/constants.ts";+import {+ LOCAL_DEVICE,+ makeStoreIndexFixture,+ type StoreIndexFixture,+} from "./fixtures/brain-store-index.ts";++let fx: StoreIndexFixture;+beforeEach(() => {+ fx = makeStoreIndexFixture("osb-store-location-");+});+afterEach(() => fx.cleanup());++const legacyPath = (vault: string): string => join(vault, DERIVED_STORE_DIR, DERIVED_STORE_FILE);++describe("index location", () => {+ test("no store in use keeps the legacy vault location", () => {+ const dirs = fx.dirs(LOCAL_DEVICE);+ const store = resolveIndexedStore({+ vault: fx.vault,+ config: { [STORE_ROOT_CONFIG_KEY]: fx.root },+ dirs,+ });+ expect(store).toBeNull();+ expect(resolveIndexPath(fx.vault, null, store)).toBe(legacyPath(fx.vault));+ });++ test("a store in use moves the index into its device-local state, one file per vault", () => {+ fx.open(LOCAL_DEVICE);+ const dirs = fx.dirs(LOCAL_DEVICE);+ const store = resolveIndexedStore({+ vault: fx.vault,+ config: { [STORE_ROOT_CONFIG_KEY]: fx.root },+ dirs,+ });+ expect(store).not.toBeNull();+ expect(store!.partitions).toEqual(["shared", "private"]);+ const path = resolveIndexPath(fx.vault, null, store);+ expect(path.startsWith(store!.deviceStateDir)).toBe(true);+ expect(path.endsWith(DERIVED_STORE_FILE)).toBe(true);+ const other = storeIndexPath(store!, join(fx.parent, "other-vault"));+ expect(other).not.toBe(path);+ });++ test("one vault reached through a link keeps one index", () => {+ fx.open(LOCAL_DEVICE);+ const store = probeIndexedStore(fx.root, fx.dirs(LOCAL_DEVICE))!;+ const link = join(fx.parent, "vault-link");+ // A junction needs no privilege on Windows; elsewhere the type is ignored.+ symlinkSync(fx.vault, link, "junction");+ expect(storeIndexPath(store, link)).toBe(storeIndexPath(store, fx.vault));+ expect(storeIndexPath(store, `${fx.vault}/./`)).toBe(storeIndexPath(store, fx.vault));+ });++ test("an explicit override wins over the store location", () => {+ fx.open(LOCAL_DEVICE);+ const store = probeIndexedStore(fx.root, fx.dirs(LOCAL_DEVICE));+ const override = join(fx.parent, "elsewhere", "index.sqlite");+ expect(resolveIndexPath(fx.vault, override, store)).toBe(override);+ });++ test("a store root inside the vault is not used", () => {+ const store = resolveIndexedStore({+ vault: fx.vault,+ config: { [STORE_ROOT_CONFIG_KEY]: join(fx.vault, "store") },+ dirs: fx.dirs(LOCAL_DEVICE),+ });+ expect(store).toBeNull();+ });+});++describe("resolveSearchConfig", () => {+ const saved: Record<string, string | undefined> = {};+ const keys = [STORE_ROOT_ENV, "XDG_STATE_HOME", "LOCALAPPDATA"];+ beforeEach(() => {+ for (const k of keys) saved[k] = process.env[k];+ });+ afterEach(() => {+ for (const k of keys) {+ if (saved[k] === undefined) delete process.env[k];+ else process.env[k] = saved[k];+ }+ });++ test("attaches the store and places the index in its device-local state", () => {+ fx.open(LOCAL_DEVICE);+ const env = fx.dirs(LOCAL_DEVICE).env;+ process.env[STORE_ROOT_ENV] = fx.root;+ process.env["XDG_STATE_HOME"] = env["XDG_STATE_HOME"];+ process.env["LOCALAPPDATA"] = env["LOCALAPPDATA"];+ const config = resolveSearchConfig({ vault: fx.vault });+ expect(config.brainStore?.root).toBe(fx.root);+ expect(config.dbPath.startsWith(config.brainStore!.deviceStateDir)).toBe(true);+ });++ test("without a store the config carries none and the index stays in the vault", () => {+ process.env[STORE_ROOT_ENV] = fx.root;+ const config = resolveSearchConfig({ vault: fx.vault });+ expect(config.brainStore).toBeNull();+ expect(config.brainStoreUnknown).toBeUndefined();+ expect(config.dbPath).toBe(legacyPath(fx.vault));+ });++ test("a store that reads as unknown keeps the store index this machine last wrote", () => {+ fx.open(LOCAL_DEVICE);+ const env = fx.dirs(LOCAL_DEVICE).env;+ process.env[STORE_ROOT_ENV] = fx.root;+ process.env["XDG_STATE_HOME"] = env["XDG_STATE_HOME"];+ process.env["LOCALAPPDATA"] = env["LOCALAPPDATA"];+ const known = resolveSearchConfig({ vault: fx.vault }).dbPath;+ mkdirSync(dirname(known), { recursive: true });+ writeFileSync(known, "");+ // A sync tool mid-rewrite of store.json.+ writeFileSync(join(fx.root, "shared", STORE_IDENTITY_FILE), "{");+ const config = resolveSearchConfig({ vault: fx.vault });+ expect(config.brainStore).toBeNull();+ expect(config.brainStoreUnknown).toBe(true);+ expect(config.dbPath).toBe(known);+ expect(resolveConfiguredIndexPath(fx.vault, join(fx.parent, "no-config.yaml"))).toBe(known);+ });++ test("a store that reads as unknown never picks the index of a store at another root", () => {+ fx.open(LOCAL_DEVICE);+ const env = fx.dirs(LOCAL_DEVICE).env;+ process.env[STORE_ROOT_ENV] = fx.root;+ process.env["XDG_STATE_HOME"] = env["XDG_STATE_HOME"];+ process.env["LOCALAPPDATA"] = env["LOCALAPPDATA"];+ const retired = resolveSearchConfig({ vault: fx.vault }).dbPath;+ mkdirSync(dirname(retired), { recursive: true });+ writeFileSync(retired, "");+ // The root moved; the new store's store.json is mid-write.+ const moved = join(fx.parent, "moved-store");+ mkdirSync(join(moved, "shared"), { recursive: true });+ writeFileSync(join(moved, "shared", STORE_IDENTITY_FILE), "{");+ process.env[STORE_ROOT_ENV] = moved;+ const config = resolveSearchConfig({ vault: fx.vault });+ expect(config.brainStoreUnknown).toBe(true);+ expect(config.dbPath).toBe(legacyPath(fx.vault));+ });++ test("a store that reads as unknown with no store index yet uses the legacy location", () => {+ fx.open(LOCAL_DEVICE);+ const env = fx.dirs(LOCAL_DEVICE).env;+ process.env[STORE_ROOT_ENV] = fx.root;+ process.env["XDG_STATE_HOME"] = env["XDG_STATE_HOME"];+ process.env["LOCALAPPDATA"] = env["LOCALAPPDATA"];+ writeFileSync(join(fx.root, "shared", STORE_IDENTITY_FILE), "{");+ expect(resolveSearchConfig({ vault: fx.vault }).dbPath).toBe(legacyPath(fx.vault));+ });++ test("an identity file it cannot read says the store is unknown, not absent", () => {+ mkdirSync(join(fx.root, "shared"), { recursive: true });+ writeFileSync(join(fx.root, "shared", STORE_IDENTITY_FILE), "{");+ process.env[STORE_ROOT_ENV] = fx.root;+ const config = resolveSearchConfig({ vault: fx.vault });+ expect(config.brainStore).toBeNull();+ expect(config.brainStoreUnknown).toBe(true);+ });+});diff --git a/tests/core/search/brain-store-rebuild.test.ts b/tests/core/search/brain-store-rebuild.test.tsnew file mode 100644index 00000000..ca64628d--- /dev/null+++ b/tests/core/search/brain-store-rebuild.test.ts@@ -0,0 +1,131 @@+/**+ * Rebuild on format change (design D5): while a background rebuild builds+ * the new index in another process, reads keep answering from the old+ * one, store records included, and the swap happens without a failed+ * read. The rebuild is the self-heal one an index chunked by older rules+ * gets, and the new index carries the store from its first read.+ */+import { afterEach, beforeEach, expect, test } from "bun:test";+import { Database } from "bun:sqlite";+import { existsSync, statSync, writeFileSync } from "node:fs";+import { join } from "node:path";++import { TRANSPORT_REACH } from "../../../src/core/graph/transport-reach.ts";+import { STORE_CATCH_UP_INTERVAL_ENV } from "../../../src/core/search/brain-store/constants.ts";+import { storeRecordPath } from "../../../src/core/search/brain-store/ingest.ts";+import { indexVault } from "../../../src/core/search/indexer.ts";+import { search } from "../../../src/core/search/search.ts";+import { inspectIndex } from "../../../src/core/search/self-heal.ts";+import { CHUNKER_VERSION_STATE_KEY } from "../../../src/core/search/store/state.ts";+import { isWriterLockHeld } from "../../../src/core/search/store/writer-lock.ts";+import { appendRecord } from "../../../src/core/store/appender.ts";+import {+ LOCAL_DEVICE,+ makeStoreIndexFixture,+ REMOTE_DEVICE,+ type StoreIndexFixture,+} from "./fixtures/brain-store-index.ts";++const NOTES = 400;+const WORKER = join(import.meta.dir, "fixtures", "store-rebuild-worker.ts");++let fx: StoreIndexFixture;+let savedInterval: string | undefined;+beforeEach(() => {+ savedInterval = process.env[STORE_CATCH_UP_INTERVAL_ENV];+ process.env[STORE_CATCH_UP_INTERVAL_ENV] = "0";+ fx = makeStoreIndexFixture("osb-store-rebuild-");+});+afterEach(() => {+ if (savedInterval === undefined) delete process.env[STORE_CATCH_UP_INTERVAL_ENV];+ else process.env[STORE_CATCH_UP_INTERVAL_ENV] = savedInterval;+ fx.cleanup();+});++test("reads keep working during a background rebuild and after its swap", async () => {+ fx.open(LOCAL_DEVICE);+ for (let i = 0; i < NOTES; i++) {+ fx.writeNote(`notes/n${i}.md`, `# Note ${i}\n\nOrdinary note number ${i} about the estuary.\n`);+ }+ const config = fx.config();+ await indexVault(config);+ const { record } = appendRecord(fx.open(REMOTE_DEVICE), {+ partition: "shared",+ stream: "events",+ kind: "decision",+ agent: "agent-b",+ body: { text: "Turnstone ringing decision" },+ });+ const expected = storeRecordPath("shared", record.id);+ const read = async (): Promise<string[]> =>+ (+ await search(config, { query: "turnstone", limit: 5, transportReach: TRANSPORT_REACH.local })+ ).results.map((r) => r.path);+ expect(await read()).toContain(expected);++ // Chunks cut by older rules: the condition a format change leaves.+ const db = new Database(config.dbPath);+ db.query("UPDATE index_state SET value = '0' WHERE key = ?").run(CHUNKER_VERSION_STATE_KEY);+ db.close();+ expect(inspectIndex(config)).toBe("rebuild");+ const before = statSync(config.dbPath).ino;++ const signal = join(fx.parent, "rebuild-locked");+ const gate = join(fx.parent, "rebuild-go");+ const child = Bun.spawn([process.execPath, WORKER, fx.parent, signal, gate], {+ env: { ...process.env },+ stdout: "pipe",+ stderr: "pipe",+ });+ const failures: string[] = [];+ const readOnce = async (): Promise<void> => {+ try {+ const paths = await read();+ if (!paths.includes(expected)) failures.push(`missing record: ${paths.join(", ")}`);+ } catch (e) {+ failures.push(e instanceof Error ? e.message : String(e));+ }+ };+ let exited = false;+ void child.exited.then(() => {+ exited = true;+ });+ // The child pauses inside its rebuild, holding the writer lock, until+ // the gate opens: reads in that window run while the rebuild is under way.+ // eslint-disable-next-line no-unmodified-loop-condition+ while (!existsSync(signal) && !exited) {+ // eslint-disable-next-line no-await-in-loop+ await Bun.sleep(5);+ }+ try {+ expect(existsSync(signal)).toBe(true);+ expect(isWriterLockHeld(config.dbPath)).toBe(true);+ await readOnce();+ await readOnce();+ expect(isWriterLockHeld(config.dbPath)).toBe(true);+ } finally {+ // Never leave the child waiting on the gate, whatever failed above.+ writeFileSync(gate, "go\n");+ }+ // Then reads keep going through the rest of the rebuild and its swap.+ // `exited` flips in the child's exit callback; each read below is+ // sequential on purpose, the next one starts after the last answered.+ // eslint-disable-next-line no-unmodified-loop-condition+ while (!exited) {+ // eslint-disable-next-line no-await-in-loop+ await readOnce();+ // Search is synchronous SQLite under its awaits; yield to the event+ // loop so the child's exit is observed.+ // eslint-disable-next-line no-await-in-loop+ await Bun.sleep(5);+ }+ const code = await child.exited;+ const stdout = await new Response(child.stdout).text();+ const stderr = await new Response(child.stderr).text();+ expect({ code, stderr }).toEqual({ code: 0, stderr: expect.any(String) });+ expect(JSON.parse(stdout.trim()).kind).toBe("rebuilt");+ expect(failures).toEqual([]);+ expect(statSync(config.dbPath).ino).not.toBe(before);+ expect(inspectIndex(config)).toBe("current");+ expect(await read()).toContain(expected);+}, 120_000);diff --git a/tests/core/search/brain-store-record-text.test.ts b/tests/core/search/brain-store-record-text.test.tsnew file mode 100644index 00000000..10d9594a--- /dev/null+++ b/tests/core/search/brain-store-record-text.test.ts@@ -0,0 +1,55 @@+/**+ * The searchable text of a brain store record (design D5): agent and+ * model text often carries markdown of its own, and none of it may change+ * the structure the chunker sees.+ */+import { describe, expect, test } from "bun:test";++import { renderRecordText } from "../../../src/core/search/brain-store/record-text.ts";+import { chunkMarkdown } from "../../../src/core/search/chunker.ts";+import { buildRecord } from "../../../src/core/store/envelope.ts";++function record(body: Record<string, unknown>) {+ return buildRecord({+ hlc: { physical: Date.UTC(2026, 10, 3), counter: 0 },+ device: "dev-b",+ agent: "agent-b",+ kind: "decision",+ body,+ });+}++describe("renderRecordText", () => {+ test("a body with headings and an open fence keeps the record's structure", () => {+ const { title, content } = renderRecordText(+ record({+ title: "Estuary plan",+ text: "Line one\n# Fake heading\n## Another\n```ts\nconst unclosed = true;",+ decision: "north bank",+ }),+ "events",+ false,+ );+ const chunks = chunkMarkdown(content, title, {+ maxTokens: 4000,+ minTokens: 1,+ overlapTokens: 0,+ }).chunks;+ expect(chunks.map((c) => c.headingPath)).toEqual(["Estuary plan"]);+ const text = chunks.map((c) => c.content).join("\n");+ // The fence did not swallow what follows it.+ expect(text).toContain("decision: north bank");+ expect(text).toContain("agent: agent-b");+ });++ test("a huge body is cut at the budget", () => {+ const { content } = renderRecordText(+ record({ text: "word ".repeat(40_000), tail: "never reached" }),+ "events",+ false,+ );+ expect(content.length).toBeLessThan(70 * 1024);+ expect(content).not.toContain("never reached");+ expect(content).toContain("agent: agent-b");+ });+});diff --git a/tests/core/search/brain-store-trust.test.ts b/tests/core/search/brain-store-trust.test.tsnew file mode 100644index 00000000..642ff7a1--- /dev/null+++ b/tests/core/search/brain-store-trust.test.ts@@ -0,0 +1,147 @@+/**+ * Catch-up against what a lower-trust peer can deliver into a synced+ * partition: a blob that hashes to its name but is not a record body, and+ * a record id copied into the other partition. Neither may stop catch-up,+ * and neither may relabel or replace what is already indexed.+ */+import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import { appendFileSync, mkdirSync, writeFileSync } from "node:fs";+import { dirname, join } from "node:path";++import { sha256Hex } from "../../../src/core/integrity/digest.ts";+import { STORE_CATCH_UP_INTERVAL_ENV } from "../../../src/core/search/brain-store/constants.ts";+import { catchUpBrainStore } from "../../../src/core/search/brain-store/catch-up.ts";+import { indexVault } from "../../../src/core/search/indexer.ts";+import { Store } from "../../../src/core/search/store.ts";+import type { ResolvedSearchConfig } from "../../../src/core/search/types.ts";+import { appendRecord } from "../../../src/core/store/appender.ts";+import { BLOB_REF_BYTES_KEY, BLOB_REF_KEY } from "../../../src/core/store/constants.ts";+import { blobPath, partitionDir } from "../../../src/core/store/store-paths.ts";+import {+ LOCAL_DEVICE,+ makeStoreIndexFixture,+ REMOTE_DEVICE,+ type StoreIndexFixture,+} from "./fixtures/brain-store-index.ts";++let fx: StoreIndexFixture;+let savedInterval: string | undefined;+beforeEach(() => {+ savedInterval = process.env[STORE_CATCH_UP_INTERVAL_ENV];+ process.env[STORE_CATCH_UP_INTERVAL_ENV] = "0";+ fx = makeStoreIndexFixture("osb-store-trust-");+});+afterEach(() => {+ if (savedInterval === undefined) delete process.env[STORE_CATCH_UP_INTERVAL_ENV];+ else process.env[STORE_CATCH_UP_INTERVAL_ENV] = savedInterval;+ fx.cleanup();+});++async function readyIndex(): Promise<ResolvedSearchConfig> {+ fx.open(LOCAL_DEVICE);+ fx.writeNote("notes/a.md", "# A\n\nA note.\n");+ const config = fx.config();+ await indexVault(config);+ return config;+}++async function rows<T>(config: ResolvedSearchConfig, sql: string): Promise<T[]> {+ const store = await Store.open(config, { mode: "read" });+ try {+ return store.rawQuery<T>(sql);+ } finally {+ await store.close();+ }+}++function remoteNote(partition: "shared" | "private", text: string) {+ return appendRecord(fx.open(REMOTE_DEVICE), {+ partition,+ stream: "events",+ kind: "decision",+ agent: "agent-b",+ body: { text },+ });+}++describe("catch-up against a lower-trust peer", () => {+ test("a pending blob that arrives holding no record body keeps the record pending", async () => {+ const config = await readyIndex();+ const first = remoteNote("shared", "Avocet first");+ const content = "null";+ const sum = sha256Hex(content);+ const crafted = {+ ...first.record,+ id: "01M00000000000000000000001",+ sum,+ body: { [BLOB_REF_KEY]: sum, [BLOB_REF_BYTES_KEY]: Buffer.byteLength(content) },+ };+ appendFileSync(first.path, `${JSON.stringify(crafted)}\n`);+ expect((await catchUpBrainStore(config, { force: true })).skipped).toBeNull();++ const blob = blobPath(partitionDir(fx.root, "shared"), sum);+ mkdirSync(dirname(blob), { recursive: true });+ writeFileSync(blob, content);+ const after = await catchUpBrainStore(config, { force: true });+ expect(after.skipped).toBeNull();+ expect(after.error).toBeUndefined();+ const pending = await rows<{ id: string }>(+ config,+ "SELECT id FROM records WHERE body_pending = 1",+ );+ expect(pending.map((r) => r.id)).toEqual([crafted.id]);++ // Later records are still indexed.+ remoteNote("shared", "Avocet second");+ expect((await catchUpBrainStore(config, { force: true })).added).toBe(1);+ });++ test("an id copied into the other partition neither relabels nor replaces the record", async () => {+ const config = await readyIndex();+ const genuine = remoteNote("shared", "Stilt genuine");+ await catchUpBrainStore(config, { force: true });++ const forged = { ...genuine.record };+ const privateShard = join(+ partitionDir(fx.root, "private"),+ "events",+ REMOTE_DEVICE,+ genuine.path.split(/[\\/]/).at(-1)!,+ );+ mkdirSync(dirname(privateShard), { recursive: true });+ writeFileSync(privateShard, `${JSON.stringify(forged)}\n`);+ expect((await catchUpBrainStore(config, { force: true })).skipped).toBeNull();++ const indexed = await rows<{ partition: string; shard: string }>(+ config,+ `SELECT partition, shard FROM records WHERE id = '${genuine.record.id}'`,+ );+ expect(indexed.map((r) => r.partition)).toEqual(["shared"]);+ expect(indexed[0]!.shard).toContain("shared");+ });++ test("a copy in the other partition does not keep a removed record indexed", async () => {+ const config = await readyIndex();+ const genuine = remoteNote("private", "Stilt removed");+ await catchUpBrainStore(config, { force: true });++ // One pass meets both: the private shard rewritten without the record+ // (read first, so the record is orphaned) and a shared copy of it.+ writeFileSync(genuine.path, "");+ const sharedShard = join(+ partitionDir(fx.root, "shared"),+ "events",+ REMOTE_DEVICE,+ genuine.path.split(/[\\/]/).at(-1)!,+ );+ mkdirSync(dirname(sharedShard), { recursive: true });+ writeFileSync(sharedShard, `${JSON.stringify(genuine.record)}\n`);+ expect((await catchUpBrainStore(config, { force: true })).skipped).toBeNull();++ const indexed = await rows<{ partition: string }>(+ config,+ `SELECT partition FROM records WHERE id = '${genuine.record.id}' AND partition = 'private'`,+ );+ expect(indexed).toEqual([]);+ });+});diff --git a/tests/core/search/cross-vault-brain-store.test.ts b/tests/core/search/cross-vault-brain-store.test.tsnew file mode 100644index 00000000..a9e7b278--- /dev/null+++ b/tests/core/search/cross-vault-brain-store.test.ts@@ -0,0 +1,131 @@+/**+ * Cross-vault union search over a machine that holds a brain store+ * (design D5). The store is machine-wide, so every vault resolves it; a+ * read-only origin still reads the index its own vault has, and the+ * store's records come back once, from the active origin.+ */+import { afterEach, beforeEach, expect, test } from "bun:test";+import { mkdirSync, rmSync, writeFileSync } from "node:fs";+import { join } from "node:path";++import { addRecallSource } from "../../../src/core/brain/portability/recall-sources.ts";+import { TRANSPORT_REACH } from "../../../src/core/graph/transport-reach.ts";+import { STORE_CATCH_UP_INTERVAL_ENV } from "../../../src/core/search/brain-store/constants.ts";+import { catchUpBrainStore } from "../../../src/core/search/brain-store/catch-up.ts";+import { storeRecordPath } from "../../../src/core/search/brain-store/ingest.ts";+import { searchAcrossVaults } from "../../../src/core/search/cross-vault.ts";+import { resolveSearchConfig } from "../../../src/core/search/index.ts";+import { indexVault } from "../../../src/core/search/indexer.ts";+import { resolveIndexPath } from "../../../src/core/search/paths.ts";+import { appendRecord } from "../../../src/core/store/appender.ts";+import { STORE_ROOT_ENV } from "../../../src/core/store/constants.ts";+import { makeConfig, writeMd } from "../../helpers/search-fixtures.ts";+import {+ LOCAL_DEVICE,+ makeStoreIndexFixture,+ REMOTE_DEVICE,+ type StoreIndexFixture,+} from "./fixtures/brain-store-index.ts";++const ENV_KEYS = [STORE_ROOT_ENV, STORE_CATCH_UP_INTERVAL_ENV, "XDG_STATE_HOME", "LOCALAPPDATA"];++let fx: StoreIndexFixture;+let configPath: string;+let external: string;+const saved: Record<string, string | undefined> = {};++beforeEach(() => {+ for (const k of ENV_KEYS) saved[k] = process.env[k];+ fx = makeStoreIndexFixture("osb-cross-vault-store-");+ external = join(fx.parent, "external-vault");+ mkdirSync(join(external, "Brain"), { recursive: true });+ configPath = join(fx.parent, "config.yaml");+ writeFileSync(configPath, `vault: "${fx.vault}"\n`);+ const state = fx.dirs(LOCAL_DEVICE).env;+ process.env[STORE_ROOT_ENV] = fx.root;+ process.env[STORE_CATCH_UP_INTERVAL_ENV] = "0";+ process.env["XDG_STATE_HOME"] = state["XDG_STATE_HOME"];+ process.env["LOCALAPPDATA"] = state["LOCALAPPDATA"];+});+afterEach(() => {+ for (const k of ENV_KEYS) {+ if (saved[k] === undefined) delete process.env[k];+ else process.env[k] = saved[k];+ }+ fx.cleanup();+});++test("a read-only origin reads its own index and the store answers once", async () => {+ // The external vault's index was built where a vault without a store keeps it.+ writeMd(+ external,+ "Brain/notes/external.md",+ "# External\n\nThe griffin visits the external vault.",+ );+ await indexVault(makeConfig({ vault: external, dbPath: resolveIndexPath(external, null, null) }));++ fx.open(LOCAL_DEVICE);+ fx.writeNote("notes/local.md", "# Local\n\nThe griffin nests in the local vault.\n");+ await indexVault(resolveSearchConfig({ vault: fx.vault, configPath }));+ const { record } = appendRecord(fx.open(REMOTE_DEVICE), {+ partition: "shared",+ stream: "events",+ kind: "decision",+ agent: "agent-b",+ body: { text: "Griffin ringing decision" },+ });+ addRecallSource(configPath, fx.vault, "team", external);++ const outcome = await searchAcrossVaults(configPath, fx.vault, {+ query: "griffin",+ limit: 10,+ transportReach: TRANSPORT_REACH.local,+ });+ expect(outcome.warnings).toEqual([]);+ const answered = outcome.results.map((r) => `${r.origin} ${r.path}`);+ expect(answered.toSorted()).toEqual(+ [+ `local ${storeRecordPath("shared", record.id)}`,+ "local notes/local.md",+ "source/team Brain/notes/external.md",+ ].toSorted(),+ );+});++test("store records a read-only origin ranks first do not take its notes' slots", async () => {+ fx.open(LOCAL_DEVICE);+ const remote = fx.open(REMOTE_DEVICE);+ for (const n of [1, 2, 3]) {+ appendRecord(remote, {+ partition: "shared",+ stream: "events",+ kind: "decision",+ agent: "agent-b",+ body: { text: `Kittiwake kittiwake kittiwake decision ${n}` },+ });+ }+ // The external vault's index was built on this machine, so it is store-aware+ // and holds the store's records, which outrank its one note.+ writeMd(+ external,+ "Brain/notes/external.md",+ `# External\n\nA kittiwake was seen once. ${"Filler words about the coast. ".repeat(40)}`,+ );+ const externalConfig = resolveSearchConfig({ vault: external, configPath });+ await indexVault(externalConfig);+ expect((await catchUpBrainStore(externalConfig, { force: true })).added).toBe(3);+ // The records are gone from the store before the active vault reads it,+ // so only the external index still ranks them.+ rmSync(join(fx.root, "shared", "events"), { recursive: true, force: true });+ fx.writeNote("notes/local.md", "# Local\n\nNothing about seabirds here.\n");+ await indexVault(resolveSearchConfig({ vault: fx.vault, configPath }));+ addRecallSource(configPath, fx.vault, "team", external);++ const outcome = await searchAcrossVaults(configPath, fx.vault, {+ query: "kittiwake",+ limit: 2,+ transportReach: TRANSPORT_REACH.local,+ });+ const answered = outcome.results.map((r) => `${r.origin} ${r.path}`);+ expect(answered).toEqual(["source/team Brain/notes/external.md"]);+});diff --git a/tests/core/search/fixtures/brain-store-index.ts b/tests/core/search/fixtures/brain-store-index.tsnew file mode 100644index 00000000..73708529--- /dev/null+++ b/tests/core/search/fixtures/brain-store-index.ts@@ -0,0 +1,83 @@+/**+ * Test helper: a vault, a brain store and the search index of one machine+ * ("dev-a") that lives in the store's device-local state, all under one+ * named temp parent removed in teardown.+ */+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { dirname, join } from "node:path";++import {+ probeIndexedStore,+ storeIndexPath,+} from "../../../../src/core/search/brain-store/location.ts";+import type { ResolvedSearchConfig } from "../../../../src/core/search/types.ts";+import type { PlatformDirsEnv } from "../../../../src/core/platform-dirs.ts";+import { openStore, type StoreHandle } from "../../../../src/core/store/store-open.ts";+import { ensureStore } from "../../store/fixtures/temp-store.ts";+import { makeConfig } from "../../../helpers/search-fixtures.ts";++export const LOCAL_DEVICE = "dev-a";+export const REMOTE_DEVICE = "dev-b";++export interface StoreIndexFixture {+ readonly parent: string;+ readonly vault: string;+ readonly root: string;+ /** Platform source whose state base is private to `machine`. */+ dirs(machine: string): PlatformDirsEnv;+ /** The store as `device` opens it (creating it on first use). */+ open(device: string): StoreHandle;+ /** The search config of the local machine, with the store attached. */+ config(): ResolvedSearchConfig;+ writeNote(rel: string, text: string): void;+ cleanup(): void;+}++/** Platform source whose state base under `parent` is private to `machine`. */+export function fixtureDirs(parent: string, machine: string): PlatformDirsEnv {+ return {+ platform: process.platform,+ home: join(parent, "home", machine),+ env: {+ XDG_STATE_HOME: join(parent, "state", machine),+ LOCALAPPDATA: join(parent, "state", machine),+ },+ };+}++/** The local machine's search config for the fixture under `parent`. */+export function fixtureConfig(parent: string): ResolvedSearchConfig {+ const vault = join(parent, "vault");+ const store = probeIndexedStore(join(parent, "store"), fixtureDirs(parent, LOCAL_DEVICE));+ if (store === null) throw new Error("no store under the fixture root");+ return Object.freeze({+ ...makeConfig({ vault, dbPath: storeIndexPath(store, vault) }),+ brainStore: store,+ });+}++export function makeStoreIndexFixture(prefix = "osb-store-index-"): StoreIndexFixture {+ const parent = mkdtempSync(join(tmpdir(), prefix));+ const vault = join(parent, "vault");+ const root = join(parent, "store");+ mkdirSync(join(vault, "Brain"), { recursive: true });+ const dirs = (machine: string): PlatformDirsEnv => fixtureDirs(parent, machine);+ return {+ parent,+ vault,+ root,+ dirs,+ open: (device) => {+ ensureStore(root);+ return openStore({ root, device, dirs: dirs(device) });+ },+ config: () => fixtureConfig(parent),+ writeNote: (rel, text) => {+ const abs = join(vault, rel);+ mkdirSync(dirname(abs), { recursive: true });+ writeFileSync(abs, text);+ },+ cleanup: () => rmSync(parent, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 }),+ };+}diff --git a/tests/core/search/fixtures/store-rebuild-worker.ts b/tests/core/search/fixtures/store-rebuild-worker.tsnew file mode 100644index 00000000..d02f5df7--- /dev/null+++ b/tests/core/search/fixtures/store-rebuild-worker.ts@@ -0,0 +1,38 @@+/**+ * Child process of the rebuild test: rebuild the fixture's index the way a+ * background self-heal does, while the parent keeps searching it.+ *+ * With a signal and a gate path, the rebuild stops at its first indexed+ * file (it holds the writer lock by then, before the swap), creates the+ * signal file, and waits until the gate file exists. The parent reads the+ * index in that window, so a read during the rebuild is proved rather than+ * left to timing. The pause rides the indexer's own per-file callback; no+ * production code knows about it.+ *+ * Usage: bun store-rebuild-worker.ts <fixture parent> [<signal path> <gate path>]+ */+import { existsSync, writeFileSync } from "node:fs";++import { healIndex } from "../../../../src/core/search/self-heal.ts";+import { fixtureConfig } from "./brain-store-index.ts";++const [parent, signal, gate] = process.argv.slice(2);+if (parent === undefined) throw new Error("usage: store-rebuild-worker.ts <fixture parent>");+let paused = false;+const onFile = (): void => {+ if (paused || signal === undefined || gate === undefined) return;+ paused = true;+ writeFileSync(signal, "locked\n");+ // A parent that dies or times out never opens the gate: end rather than+ // stay behind holding the writer lock.+ const deadline = Date.now() + 30_000;+ while (!existsSync(gate)) {+ if (Date.now() > deadline) {+ process.stderr.write("the gate never opened\n");+ process.exit(2);+ }+ Bun.sleepSync(5);+ }+};+const outcome = await healIndex(fixtureConfig(parent), { onFile });+process.stdout.write(`${JSON.stringify(outcome)}\n`);diff --git a/tests/core/search/schema-migration-v10.test.ts b/tests/core/search/schema-migration-v10.test.tsindex ac807840..9c9c4c9b 100644--- a/tests/core/search/schema-migration-v10.test.ts+++ b/tests/core/search/schema-migration-v10.test.ts@@ -40,11 +40,8 @@ function hasColumn(db: Database, table: string, name: string): boolean {// v16 (privacy-marker visibility restamp): the marker-aware visibility// re-measurement joined (v15 (chunk skip-and-hold) had added the// chunk_embedding_holds table; v14 the chunk_kind column, taxonomy-// indexes and document_attributes side table).-test("latest schema version is 16", () => {- expect(LATEST_SCHEMA_VERSION).toBe(16);-});-+// indexes and document_attributes side table). v17 (brain store index)+// added the watermark and records tables and the source column.test("fresh migration reaches latest with the authored_at column", () => {const db = new Database(dbPath);expect(applyMigrations(db)).toBe(LATEST_SCHEMA_VERSION);diff --git a/tests/core/search/schema-v14.test.ts b/tests/core/search/schema-v14.test.tsindex b2dd2687..ce11aeb9 100644--- a/tests/core/search/schema-v14.test.ts+++ b/tests/core/search/schema-v14.test.ts@@ -215,10 +215,10 @@ function attributesFor(path: string): ReadonlyArray<{ key: string; value: stringdescribe("the v14 entry", () => {test("remains in the frozen array once later entries append after it", () => {- expect(LATEST_SCHEMA_VERSION).toBe(16);- expect(MIGRATIONS.length).toBe(16);- expect(MIGRATIONS[MIGRATIONS.length - 2]!.version).toBe(15);- expect(MIGRATIONS[MIGRATIONS.length - 3]!.version).toBe(14);+ // The latest version is pinned once, in the newest migration's test.+ expect(MIGRATIONS.length).toBe(LATEST_SCHEMA_VERSION);+ expect(MIGRATIONS[13]!.version).toBe(14);+ expect(MIGRATIONS[14]!.version).toBe(15);});test("runs from a rewound v13 index and stamps the version", async () => {diff --git a/tests/core/search/schema-v15.test.ts b/tests/core/search/schema-v15.test.tsindex e0bf5d7d..4a2adb1c 100644--- a/tests/core/search/schema-v15.test.ts+++ b/tests/core/search/schema-v15.test.ts@@ -91,11 +91,11 @@ function tableSql(): string | null {}describe("the v15 entry", () => {- test("appends to MIGRATIONS ahead of the later v16 entry", () => {- expect(LATEST_SCHEMA_VERSION).toBe(16);- expect(MIGRATIONS.length).toBe(16);+ test("appends to MIGRATIONS ahead of the later v16 and v17 entries", () => {+ // The latest version is pinned once, in the newest migration's test.+ expect(MIGRATIONS.length).toBe(LATEST_SCHEMA_VERSION);expect(MIGRATIONS[14]!.version).toBe(15);- expect(MIGRATIONS[MIGRATIONS.length - 1]!.version).toBe(16);+ expect(MIGRATIONS[15]!.version).toBe(16);});test("runs from a rewound v14 index and stamps the version", async () => {diff --git a/tests/core/search/schema-v16.test.ts b/tests/core/search/schema-v16.test.tsindex 359ca6ca..a33f3580 100644--- a/tests/core/search/schema-v16.test.ts+++ b/tests/core/search/schema-v16.test.ts@@ -92,10 +92,9 @@ function columnOf(path: string): string | null {}describe("the v16 entry", () => {- test("appends to MIGRATIONS as the latest version and adds no DDL", () => {- expect(LATEST_SCHEMA_VERSION).toBe(16);- expect(MIGRATIONS.length).toBe(16);- expect(MIGRATIONS[MIGRATIONS.length - 1]!.version).toBe(16);+ test("appends to MIGRATIONS after v15 and adds no DDL", () => {+ expect(MIGRATIONS.length).toBe(LATEST_SCHEMA_VERSION);+ expect(MIGRATIONS[15]!.version).toBe(16);});test("runs from a rewound v15 index and stamps the version", async () => {@@ -104,7 +103,7 @@ describe("the v16 entry", () => {expect(migrate()).toBe(LATEST_SCHEMA_VERSION);const db = new Database(dbPath, { readonly: true });try {- expect(readSchemaVersion(db)).toBe(16);+ expect(readSchemaVersion(db)).toBe(LATEST_SCHEMA_VERSION);} finally {db.close();}diff --git a/tests/core/search/schema-v17.test.ts b/tests/core/search/schema-v17.test.tsnew file mode 100644index 00000000..adb0cd5f--- /dev/null+++ b/tests/core/search/schema-v17.test.ts@@ -0,0 +1,124 @@+/**+ * Schema v17 (brain store index, design D5): the per-shard watermark+ * table, the `records` table, the derived `documents.source` column and+ * the index generation the change probe binds its watermarks to.+ *+ * Pinned here: a fresh index and an index upgraded in place from v16 end+ * with the same tables, every existing document keeps its rows, and the+ * source column tells a user note from a page of the legacy `Brain/` tree+ * and from a store record without any write by the indexer.+ */++import { Database } from "bun:sqlite";+import { afterEach, beforeEach, describe, expect, test } from "bun:test";++import { indexVault } from "../../../src/core/search/indexer.ts";+import {+ LATEST_SCHEMA_VERSION,+ MIGRATIONS,+ applyMigrations,+ readSchemaVersion,+} from "../../../src/core/search/schema.ts";+import { STORE_INDEX_GENERATION_KEY } from "../../../src/core/search/brain-store/constants.ts";+import { createTempVault, makeConfig, writeMd } from "../../helpers/search-fixtures.ts";++let vault: string;+let dbPath: string;+let cleanup: () => void;++beforeEach(() => {+ ({ vault, dbPath, cleanup } = createTempVault("schema-v17"));+});+afterEach(() => cleanup());++function tables(db: Database): Set<string> {+ return new Set(+ db+ .query<{ name: string }, []>("SELECT name FROM sqlite_master WHERE type = 'table'")+ .all()+ .map((r) => r.name),+ );+}++function sourceOf(db: Database, path: string): string | null {+ return (+ db.query<{ source: string }, [string]>("SELECT source FROM documents WHERE path = ?").get(path)+ ?.source ?? null+ );+}++/** Undo v17 and stamp v16, as a v16 binary left the file. */+function rewindToV16(): void {+ const db = new Database(dbPath);+ try {+ db.exec("DROP TABLE IF EXISTS records");+ db.exec("DROP TABLE IF EXISTS store_watermarks");+ db.exec("ALTER TABLE documents DROP COLUMN source");+ db.query("DELETE FROM index_state WHERE key = ?").run(STORE_INDEX_GENERATION_KEY);+ db.query("UPDATE index_state SET value = '16' WHERE key = 'schema_version'").run();+ } finally {+ db.close();+ }+}++describe("schema v17", () => {+ test("is the latest migration", () => {+ expect(LATEST_SCHEMA_VERSION).toBe(17);+ expect(MIGRATIONS[MIGRATIONS.length - 1]!.version).toBe(17);+ });++ test("a fresh index carries the store tables and an index generation", () => {+ const db = new Database(":memory:");+ try {+ expect(applyMigrations(db)).toBe(17);+ const present = tables(db);+ expect(present.has("records")).toBe(true);+ expect(present.has("store_watermarks")).toBe(true);+ const generation = db+ .query<{ value: string }, [string]>("SELECT value FROM index_state WHERE key = ?")+ .get(STORE_INDEX_GENERATION_KEY)?.value;+ expect(generation).toMatch(/^[0-9A-HJKMNP-TV-Z]{26}$/);+ } finally {+ db.close();+ }+ });++ test("the source column separates notes, the legacy Brain tree and store records", async () => {+ writeMd(vault, "notes/heron.md", "# Heron\n\nA note about herons.\n");+ writeMd(vault, "Brain/signals/sig-1.md", "# Signal\n\nA brain signal.\n");+ writeMd(vault, "Brainstorm/idea.md", "# Idea\n\nA user note that shares a prefix.\n");+ await indexVault(makeConfig({ vault, dbPath }));+ const db = new Database(dbPath);+ try {+ db.query(+ "INSERT INTO documents(path, basename, title, content_hash, mtime, size, created_at, updated_at, indexed_at) " ++ "VALUES ('.brain-store/shared/01J00000000000000000000000', 'x', NULL, 'h', 0, 0, '', '', '')",+ ).run();+ expect(sourceOf(db, "notes/heron.md")).toBe("note");+ expect(sourceOf(db, "Brainstorm/idea.md")).toBe("note");+ expect(sourceOf(db, "Brain/signals/sig-1.md")).toBe("brain");+ expect(sourceOf(db, ".brain-store/shared/01J00000000000000000000000")).toBe("brain");+ } finally {+ db.close();+ }+ });++ test("a v16 index upgrades in place and keeps its documents", async () => {+ writeMd(vault, "notes/heron.md", "# Heron\n\nA note about herons.\n");+ writeMd(vault, "Brain/signals/sig-1.md", "# Signal\n\nA brain signal.\n");+ await indexVault(makeConfig({ vault, dbPath }));+ rewindToV16();+ const db = new Database(dbPath);+ try {+ expect(readSchemaVersion(db)).toBe(16);+ expect(applyMigrations(db)).toBe(17);+ expect(tables(db).has("records")).toBe(true);+ expect(sourceOf(db, "notes/heron.md")).toBe("note");+ expect(sourceOf(db, "Brain/signals/sig-1.md")).toBe("brain");+ // Running it again changes nothing.+ expect(applyMigrations(db)).toBe(17);+ } finally {+ db.close();+ }+ });+});diff --git a/tests/core/search/search-query-schema-artifact.test.ts b/tests/core/search/search-query-schema-artifact.test.tsindex 85f53f98..23451f8f 100644--- a/tests/core/search/search-query-schema-artifact.test.ts+++ b/tests/core/search/search-query-schema-artifact.test.ts@@ -277,6 +277,7 @@ const SEARCH_OPTIONS_KEY_PROBE: Record<keyof SearchOptions, true> = {matchMode: true,properties: true,kind: true,+ source: true,degreeFilters: true,mmrLambda: true,maxHops: true,diff --git a/tests/core/store/appender.test.ts b/tests/core/store/appender.test.tsnew file mode 100644index 00000000..dd21cbc2--- /dev/null+++ b/tests/core/store/appender.test.ts@@ -0,0 +1,296 @@+import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import {+ appendFileSync,+ existsSync,+ mkdirSync,+ readFileSync,+ readdirSync,+ rmSync,+ writeFileSync,+} from "node:fs";+import { join } from "node:path";++import { appendRecord, PartitionUnavailableError } from "../../../src/core/store/appender.ts";+import { BLOB_REF_KEY, STORE_LINE_CAP_BYTES } from "../../../src/core/store/constants.ts";+import { compareRecords } from "../../../src/core/store/envelope.ts";+import { clockFilePath, observeClock } from "../../../src/core/store/clock-store.ts";+import { parseHlc } from "../../../src/core/store/hlc.ts";+import { readShard } from "../../../src/core/store/reader.ts";+import { listShards } from "../../../src/core/store/shard-list.ts";+import {+ blobPath,+ isPathInside,+ partitionDir,+ shardLockTarget,+} from "../../../src/core/store/store-paths.ts";+import { openStore } from "../../../src/core/store/store-open.ts";+import { ensureStore, makeTempStore, type TempStore } from "./fixtures/temp-store.ts";++const NOV_2026 = Date.UTC(2026, 10, 6, 12, 0, 0);++describe("shard appender", () => {+ let tmp: TempStore;+ beforeEach(() => {+ tmp = makeTempStore("osb-store-append-");+ });+ afterEach(() => tmp.cleanup());++ test("writes one verified line per record into the device's monthly shard", () => {+ const store = tmp.open("dev-a");+ const result = appendRecord(+ store,+ {+ partition: "shared",+ stream: "events",+ kind: "feedback",+ agent: "a1",+ scope: "writing",+ body: { n: 1 },+ },+ { now: () => NOV_2026 },+ );+ expect(result.rel).toBe("events/dev-a/2026-11.jsonl");+ expect(result.path).toBe(join(tmp.root, "shared", "events", "dev-a", "2026-11.jsonl"));+ const text = readFileSync(result.path, "utf8");+ expect(text.endsWith("\n")).toBe(true);+ expect(text.split("\n")).toHaveLength(2);+ const read = readShard(result.path);+ expect(read.records.map((r) => r.record)).toEqual([result.record]);+ expect(read.diagnostics).toEqual([]);+ });++ test("ledgers go one directory deeper, under their name", () => {+ const store = tmp.open("dev-a");+ const result = appendRecord(+ store,+ {+ partition: "private",+ stream: "ledgers",+ ledger: "receipts",+ kind: "receipt",+ agent: "a1",+ body: {},+ },+ { now: () => NOV_2026 },+ );+ expect(result.rel).toBe("ledgers/receipts/dev-a/2026-11.jsonl");+ });++ test("no lock or clock file is ever written inside the store", () => {+ const store = tmp.open("dev-a");+ for (let i = 0; i < 3; i++) {+ appendRecord(store, {+ partition: "shared",+ stream: "log",+ kind: "note",+ agent: "a1",+ body: { i },+ });+ }+ // Directories too: a lock is a `<target>.lock` directory while held,+ // and its parent directory stays behind after release.+ const walk = (dir: string): string[] =>+ readdirSync(dir, { withFileTypes: true }).flatMap((e) =>+ e.isDirectory() ? [join(dir, e.name), ...walk(join(dir, e.name))] : [join(dir, e.name)],+ );+ const names = walk(tmp.root);+ expect(names.filter((n) => n.includes(".lock") || n.includes("clock"))).toEqual([]);+ const lockTarget = shardLockTarget(store.deviceStateDir, "shared", "log/dev-a/2026-11.jsonl");+ for (const path of [lockTarget, clockFilePath(store.deviceStateDir, "dev-a")]) {+ expect(isPathInside(path, store.deviceStateDir, process.platform)).toBe(true);+ expect(isPathInside(path, tmp.root, process.platform)).toBe(false);+ }+ expect(existsSync(store.deviceStateDir)).toBe(true);+ });++ test("a write to a partition this machine does not hold is refused with a clear message", () => {+ tmp.open("dev-a");+ // This machine syncs only the shared partition.+ rmSync(join(tmp.root, "private"), { recursive: true, force: true });+ const sharedOnly = tmp.open("dev-a");+ const write = () =>+ appendRecord(sharedOnly, {+ partition: "private",+ stream: "events",+ kind: "x",+ agent: "a",+ body: {},+ });+ expect(write).toThrow(PartitionUnavailableError);+ expect(write).toThrow(/does not hold the private partition/);+ expect(existsSync(join(tmp.root, "private"))).toBe(false);+ });++ test("a body over the line cap spills into an immutable blob named by the record's sum", () => {+ const store = tmp.open("dev-a");+ const body = { report: "r".repeat(STORE_LINE_CAP_BYTES * 2) };+ const result = appendRecord(store, {+ partition: "shared",+ stream: "events",+ kind: "report",+ agent: "a",+ body,+ });+ expect(result.spilled).toBe(true);+ const line = readFileSync(result.path, "utf8");+ expect(Buffer.byteLength(line)).toBeLessThanOrEqual(STORE_LINE_CAP_BYTES);+ expect(JSON.parse(line).body[BLOB_REF_KEY]).toBe(result.record.sum);+ expect(existsSync(blobPath(partitionDir(tmp.root, "shared"), result.record.sum))).toBe(true);+ const read = readShard(result.path, { partitionRoot: partitionDir(tmp.root, "shared") });+ expect(read.records[0]!.bodyState).toBe("blob");+ expect(read.records[0]!.record.body).toEqual(body);+ });++ test("a torn last line left by a crash stays one reported bad line and the next record is whole", () => {+ const store = tmp.open("dev-a");+ const first = appendRecord(store, {+ partition: "shared",+ stream: "events",+ kind: "x",+ agent: "a",+ body: { n: 1 },+ });+ appendFileSync(first.path, '{"v":1,"id":"01J');+ const third = appendRecord(store, {+ partition: "shared",+ stream: "events",+ kind: "x",+ agent: "a",+ body: { n: 3 },+ });+ const read = readShard(first.path);+ expect(read.records.map((r) => r.record.id)).toEqual([first.record.id, third.record.id]);+ expect(read.diagnostics.map((d) => d.kind)).toEqual(["corrupt-line"]);+ });++ test("records of one device are strictly increasing in clock order, even when the wall clock steps back", () => {+ const store = tmp.open("dev-a");+ const walls = [NOV_2026, NOV_2026 - 60_000, NOV_2026 - 120_000, NOV_2026];+ const records = walls.map(+ (wall) =>+ appendRecord(+ store,+ { partition: "shared", stream: "events", kind: "x", agent: "a", body: {} },+ { now: () => wall },+ ).record,+ );+ for (let i = 1; i < records.length; i++)+ expect(compareRecords(records[i]!, records[i - 1]!)).toBeGreaterThan(0);+ });++ test("a reply written after observing a faster machine's record folds after it", () => {+ ensureStore(tmp.root);+ const fast = openStore({ root: tmp.root, device: "fast-a", dirs: tmp.dirs("a") });+ const slow = openStore({ root: tmp.root, device: "slow-b", dirs: tmp.dirs("b") });+ const decision = appendRecord(+ fast,+ {+ partition: "shared",+ stream: "events",+ kind: "decision",+ agent: "a",+ body: { d: "use monthly shards" },+ },+ { now: () => NOV_2026 + 120_000 },+ ).record;+ // Machine B catches up on A's shard and observes every clock it ingests.+ for (const shard of listShards(partitionDir(tmp.root, "shared"), { stream: "events" })) {+ for (const { record } of readShard(shard.path).records) {+ observeClock(slow.deviceStateDir, slow.device, parseHlc(record.hlc)!, () => NOV_2026);+ }+ }+ const correction = appendRecord(+ slow,+ {+ partition: "shared",+ stream: "events",+ kind: "correction",+ agent: "b",+ body: { of: decision.id },+ },+ { now: () => NOV_2026 + 1 },+ ).record;+ expect(compareRecords(correction, decision)).toBeGreaterThan(0);+ });+});++describe("concurrent appends on one device", () => {+ let tmp: TempStore;+ beforeEach(() => {+ tmp = makeTempStore("osb-store-concurrent-");+ });+ afterEach(() => tmp.cleanup());++ test("child processes produce N complete, verifiable lines and one shared blob", async () => {+ const WORKERS = 6;+ const EACH = 100;+ // Every worker reports ready, then all start on one go file.+ const readyDir = join(tmp.parent, "ready");+ const goFile = join(tmp.parent, "go");+ mkdirSync(readyDir, { recursive: true });+ const stateHome = join(tmp.parent, "state", "one-device");+ ensureStore(tmp.root);+ const store = openStore({+ root: tmp.root,+ device: "dev-a",+ dirs: {+ platform: process.platform,+ home: stateHome,+ env: { XDG_STATE_HOME: stateHome, LOCALAPPDATA: stateHome },+ },+ });+ const worker = join(import.meta.dir, "fixtures", "append-worker.ts");+ const children = Array.from({ length: WORKERS }, (_, i) =>+ Bun.spawn(+ [+ process.execPath,+ worker,+ tmp.root,+ "dev-a",+ stateHome,+ String(i),+ String(EACH),+ readyDir,+ goFile,+ ],+ { stdout: "ignore", stderr: "pipe" },+ ),+ );+ const readyBy = Date.now() + 30_000;+ while (readdirSync(readyDir).length < WORKERS && Date.now() < readyBy) await Bun.sleep(5);+ writeFileSync(goFile, "go\n");+ // stderr is drained while waiting, so a noisy worker cannot block on a full pipe.+ const [codes, errors] = await Promise.all([+ Promise.all(children.map((child) => child.exited)),+ Promise.all(children.map((child) => new Response(child.stderr).text())),+ ]);+ expect(errors.filter((e) => e.trim() !== "")).toEqual([]);+ expect(codes).toEqual(Array.from({ length: WORKERS }, () => 0));++ const shards = listShards(partitionDir(tmp.root, "shared"), { stream: "events" });+ expect(shards.map((s) => s.device)).toEqual(["dev-a"]);+ const records = shards.flatMap(+ (s) => readShard(s.path, { partitionRoot: partitionDir(tmp.root, "shared") }).records,+ );+ const diagnostics = shards.flatMap((s) => readShard(s.path).diagnostics);+ expect(diagnostics).toEqual([]);+ expect(records).toHaveLength(WORKERS * EACH);+ expect(new Set(records.map((r) => r.record.id)).size).toBe(WORKERS * EACH);+ expect(new Set(records.map((r) => r.record.hlc)).size).toBe(WORKERS * EACH);+ expect(records.every((r) => r.bodyState !== "pending")).toBe(true);+ const blobDirs = readdirSync(join(tmp.root, "shared", "blobs"));+ const blobs = blobDirs.flatMap((d) => readdirSync(join(tmp.root, "shared", "blobs", d)));+ // Every worker spilled the same large body, so they raced for one blob name.+ expect(blobs).toHaveLength(1);+ expect(records.filter((r) => r.bodyState === "blob")).toHaveLength(+ WORKERS * Math.ceil(EACH / 3),+ );+ // The workers really contended: their lines interleave in the shard+ // rather than forming one block per worker.+ const switches = records.filter(+ (r, i) => i > 0 && r.record.agent !== records[i - 1]!.record.agent,+ ).length;+ expect(switches).toBeGreaterThan(WORKERS - 1);+ expect(store.storeId).toMatch(/^[0-9A-Z]{26}$/);+ }, 60_000);+});diff --git a/tests/core/store/blobs.test.ts b/tests/core/store/blobs.test.tsnew file mode 100644index 00000000..31d8b54e--- /dev/null+++ b/tests/core/store/blobs.test.ts@@ -0,0 +1,233 @@+/**+ * Blob creation (design D1, D2): where the temp file goes, the exclusive+ * create, and the fallback for filesystems without hard links.+ */+import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import {+ existsSync,+ linkSync,+ mkdirSync,+ readdirSync,+ readFileSync,+ renameSync,+ writeFileSync,+} from "node:fs";+import { basename, dirname, join } from "node:path";++import { sha256Hex } from "../../../src/core/integrity/digest.ts";+import { NO_LINK_CODES, readBlob, writeBlob } from "../../../src/core/store/blobs.ts";+import { appendRecord } from "../../../src/core/store/appender.ts";+import { BLOB_TEMP_PREFIX, STORE_LINE_CAP_BYTES } from "../../../src/core/store/constants.ts";+import { blobPath, partitionDir } from "../../../src/core/store/store-paths.ts";+import { makeTempStore, type TempStore } from "./fixtures/temp-store.ts";++/** Every file under `dir`, relative, `/`-separated. */+function walk(dir: string, prefix = ""): string[] {+ if (!existsSync(dir)) return [];+ return readdirSync(dir, { withFileTypes: true }).flatMap((entry) =>+ entry.isDirectory()+ ? walk(join(dir, entry.name), `${prefix}${entry.name}/`)+ : [`${prefix}${entry.name}`],+ );+}++/** A link call that behaves like a FAT or exFAT volume. */+function noHardLinks(): never {+ throw Object.assign(new Error("operation not permitted, link"), { code: "EPERM" });+}++/** A link call that fails for a reason unrelated to hard-link support. */+function diskFull(): never {+ throw Object.assign(new Error("no space left"), { code: "ENOSPC" });+}++describe("writeBlob", () => {+ let tmp: TempStore;+ let partition: string;+ beforeEach(() => {+ tmp = makeTempStore("osb-store-blob-");+ partition = partitionDir(tmp.open("dev-a").root, "shared");+ });+ afterEach(() => tmp.cleanup());++ test("with a device-local temp dir on the same filesystem, nothing temporary touches blobs/", () => {+ const tempDir = join(tmp.parent, "state", "dev-a", "tmp");+ const text = JSON.stringify({ note: "hello" });+ const sources: string[] = [];+ const written = writeBlob(partition, text, {+ tempDir,+ link: (from, to) => {+ sources.push(from);+ linkSync(from, to);+ },+ });+ expect(written.created).toBe(true);+ expect(sources.length).toBe(1);+ expect(dirname(sources[0]!)).toBe(tempDir);+ expect(walk(join(partition, "blobs"))).toEqual([`${written.sha.slice(0, 2)}/${written.sha}`]);+ expect(walk(tempDir)).toEqual([]);+ expect(readBlob(partition, written.sha)).toEqual({ status: "ok", text });+ });++ test("with no usable device-local dir the temp file is dot-prefixed beside the blob", () => {+ const sources: string[] = [];+ const written = writeBlob(partition, JSON.stringify({ note: "beside" }), {+ link: (from, to) => {+ sources.push(from);+ linkSync(from, to);+ },+ });+ expect(dirname(sources[0]!)).toBe(dirname(written.path));+ expect(basename(sources[0]!).startsWith(BLOB_TEMP_PREFIX)).toBe(true);+ expect(existsSync(sources[0]!)).toBe(false);+ });++ test("an unusable device-local dir falls back to a dot-prefixed temp beside the blob", () => {+ const fileNotDir = join(tmp.parent, "not-a-dir");+ writeFileSync(fileNotDir, "");+ const sources: string[] = [];+ const written = writeBlob(partition, JSON.stringify({ note: "fallback" }), {+ tempDir: join(fileNotDir, "tmp"),+ link: (from, to) => {+ sources.push(from);+ linkSync(from, to);+ },+ });+ expect(dirname(sources[0]!)).toBe(dirname(written.path));+ expect(basename(sources[0]!).startsWith(BLOB_TEMP_PREFIX)).toBe(true);+ expect(walk(join(partition, "blobs"))).toEqual([`${written.sha.slice(0, 2)}/${written.sha}`]);+ });++ const noLinkCodes = ["EPERM", "ENOTSUP", "EOPNOTSUPP", "ENOSYS", "EXDEV", "EMLINK"];++ test("the codes below are every code that means the filesystem has no hard links", () => {+ expect([...NO_LINK_CODES].toSorted()).toEqual(noLinkCodes.toSorted());+ });++ test.each(noLinkCodes)(+ "a link refused with %s falls back to an exclusive create of the final name",+ (code) => {+ const text = JSON.stringify({ note: `no link ${code}` });+ const written = writeBlob(partition, text, {+ link: () => {+ throw Object.assign(new Error(`link refused: ${code}`), { code });+ },+ });+ expect(written.created).toBe(true);+ expect(readBlob(partition, written.sha)).toEqual({ status: "ok", text });+ expect(walk(join(partition, "blobs"))).toEqual([`${written.sha.slice(0, 2)}/${written.sha}`]);+ },+ );++ test("without hard links the final name is created exclusively and reads back verified", () => {+ const text = JSON.stringify({ note: "fat volume" });+ const written = writeBlob(partition, text, { link: noHardLinks });+ expect(written.created).toBe(true);+ expect(readBlob(partition, written.sha)).toEqual({ status: "ok", text });+ // No temp file is left behind anywhere in the blob tree.+ expect(walk(join(partition, "blobs"))).toEqual([`${written.sha.slice(0, 2)}/${written.sha}`]);+ });++ test("without hard links a second write of the same body is a verified no-op", () => {+ const text = JSON.stringify({ note: "twice" });+ writeBlob(partition, text, { link: noHardLinks });+ const again = writeBlob(partition, text, { link: noHardLinks });+ expect(again.created).toBe(false);+ expect(readBlob(partition, again.sha)).toEqual({ status: "ok", text });+ });++ test("a taken name holding a torn write is repaired to the content its name promises", () => {+ const text = JSON.stringify({ note: "repair me" });+ const sha = sha256Hex(text);+ const path = blobPath(partition, sha);+ // A crash halfway through a direct create left the first half on disk.+ mkdirSync(dirname(path), { recursive: true });+ writeFileSync(path, text.slice(0, 5));+ expect(readBlob(partition, sha).status).toBe("mismatch");+ const written = writeBlob(partition, text, { link: noHardLinks });+ expect(written.created).toBe(false);+ expect(readFileSync(path, "utf8")).toBe(text);+ // The repair goes through a temp file renamed over the blob; none is left behind.+ expect(walk(join(partition, "blobs"))).toEqual([`${sha.slice(0, 2)}/${sha}`]);+ });++ /** A torn first half of `text` at its blob name, as a crash during a direct create leaves it. */+ function tornBlob(text: string): string {+ const path = blobPath(partition, sha256Hex(text));+ mkdirSync(dirname(path), { recursive: true });+ writeFileSync(path, text.slice(0, 5));+ return path;+ }++ test("a repair writes its temp file in the device-local dir, not in blobs/", () => {+ const text = JSON.stringify({ note: "repair locally" });+ tornBlob(text);+ const tempDir = join(tmp.parent, "state", "dev-a", "tmp");+ const sources: string[] = [];+ writeBlob(partition, text, {+ tempDir,+ link: noHardLinks,+ rename: (from, to) => {+ sources.push(from);+ renameSync(from, to);+ },+ });+ expect(sources.map((s) => dirname(s))).toEqual([tempDir]);+ });++ test("a repair refused because the writer still holds the blob open waits for that writer", () => {+ const text = JSON.stringify({ note: "slow writer" });+ const path = tornBlob(text);+ const written = writeBlob(partition, text, {+ link: noHardLinks,+ rename: () => {+ // The slow writer finishes while the rename is refused.+ writeFileSync(path, text);+ throw Object.assign(new Error("resource busy or locked, rename"), { code: "EBUSY" });+ },+ });+ expect(written.created).toBe(false);+ expect(readBlob(partition, written.sha)).toEqual({ status: "ok", text });+ expect(walk(join(partition, "blobs"))).toEqual([`${written.sha.slice(0, 2)}/${written.sha}`]);+ });++ test("a refused repair of a blob that never completes still fails", () => {+ const text = JSON.stringify({ note: "never completes" });+ tornBlob(text);+ expect(() =>+ writeBlob(partition, text, {+ link: noHardLinks,+ rename: () => {+ throw Object.assign(new Error("operation not permitted, rename"), { code: "EPERM" });+ },+ }),+ ).toThrow("operation not permitted");+ });++ test("a link failure that is not about hard-link support propagates and leaves no temp file", () => {+ expect(() => writeBlob(partition, "{}", { link: diskFull })).toThrow("no space left");+ expect(walk(join(partition, "blobs"))).toEqual([]);+ });+});++describe("appendRecord spills through the device-local temp dir", () => {+ let tmp: TempStore;+ beforeEach(() => {+ tmp = makeTempStore("osb-store-blob-append-");+ });+ afterEach(() => tmp.cleanup());++ test("a spilled body leaves only the blob in blobs/", () => {+ const store = tmp.open("dev-a");+ const result = appendRecord(store, {+ partition: "shared",+ stream: "events",+ kind: "note",+ agent: "tester",+ body: { text: "x".repeat(STORE_LINE_CAP_BYTES * 2) },+ });+ expect(result.spilled).toBe(true);+ const sha = result.record.sum;+ expect(walk(join(tmp.root, "shared", "blobs"))).toEqual([`${sha.slice(0, 2)}/${sha}`]);+ });+});diff --git a/tests/core/store/dual-write-legacy-bytes.test.ts b/tests/core/store/dual-write-legacy-bytes.test.tsnew file mode 100644index 00000000..c274636b--- /dev/null+++ b/tests/core/store/dual-write-legacy-bytes.test.ts@@ -0,0 +1,172 @@+/**+ * Dual writes leave the legacy files byte-identical (task 1.11): the same+ * writer sequence run into two fresh vaults, one with the flag off and one+ * with it on, produces the same bytes in every file under `Brain/`. Both+ * runs share one fixed clock, so only ids a run mints itself can differ,+ * and those are masked.+ *+ * Everything lives under one named temp parent, removed in teardown, with+ * its own HOME, state base and store root.+ */+import { afterEach, beforeEach, describe, expect, setSystemTime, test } from "bun:test";+import { mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync } from "node:fs";+import { tmpdir } from "node:os";+import { join, relative } from "node:path";++import { appendApplyEvidence } from "../../../src/core/brain/apply-evidence.ts";+import { bootstrapBrain } from "../../../src/core/brain/init.ts";+import { appendLogEvent } from "../../../src/core/brain/log.ts";+import {+ appendPinnedContext,+ clearPinnedContext,+ writePinnedContext,+} from "../../../src/core/brain/pinned.ts";+import { moveToRetired, writePreference } from "../../../src/core/brain/preference.ts";+import { writeSignal } from "../../../src/core/brain/signal.ts";+import { appendClaimEvent } from "../../../src/core/brain/truth/store.ts";+import { appendAuditRecord } from "../../../src/core/reliability/audit.ts";+import { STORE_DUAL_WRITE_ENV, STORE_ROOT_ENV } from "../../../src/core/store/constants.ts";+import { readPartition } from "../../../src/core/store/state-digest.ts";+import { initStore } from "../../../src/core/store/store-init.ts";++const ENV_KEYS = [+ STORE_DUAL_WRITE_ENV,+ STORE_ROOT_ENV,+ "O2B_DEVICE_ID",+ "HOME",+ "XDG_STATE_HOME",+ "LOCALAPPDATA",+] as const;++const NOW = new Date("2026-11-06T10:00:00Z");++let parent: string;+let storeRoot: string;+const saved = new Map<string, string | undefined>();++beforeEach(() => {+ for (const key of ENV_KEYS) saved.set(key, process.env[key]);+ parent = mkdtempSync(join(tmpdir(), "osb-dual-write-bytes-"));+ storeRoot = join(parent, "store");+ process.env["HOME"] = join(parent, "home");+ process.env["XDG_STATE_HOME"] = join(parent, "state");+ process.env["LOCALAPPDATA"] = join(parent, "state");+ process.env[STORE_ROOT_ENV] = storeRoot;+ process.env["O2B_DEVICE_ID"] = "dev-a";+ initStore({ root: storeRoot });+ setSystemTime(NOW);+});++afterEach(() => {+ setSystemTime();+ for (const key of ENV_KEYS) {+ const value = saved.get(key);+ if (value === undefined) delete process.env[key];+ else process.env[key] = value;+ }+ rmSync(parent, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });+});++/** Every legacy writer the trial taps, in one fixed sequence. */+function runWriters(vault: string): void {+ writeSignal(vault, {+ topic: "bytes",+ signal: "positive",+ agent: "claude",+ principle: "Keep the legacy bytes",+ created_at: "2026-11-06T10:00:00Z",+ date: "2026-11-06",+ slug: "bytes",+ scope: "coding",+ raw: "the user said so",+ });+ appendLogEvent(vault, {+ timestamp: "2026-11-06T10:01:00Z",+ eventType: "note",+ agent: "claude",+ body: { text: "a milestone" },+ });+ writePinnedContext(vault, "first");+ appendPinnedContext(vault, "second");+ clearPinnedContext(vault);+ const pref = writePreference(vault, {+ slug: "bytes",+ topic: "bytes",+ principle: "principle bytes",+ created_at: "2026-05-01T00:00:00Z",+ unconfirmed_until: "2026-05-30T00:00:00Z",+ status: "confirmed",+ confirmed_at: "2026-05-02T00:00:00Z",+ evidenced_by: [],+ confidence: "high",+ }).path;+ appendApplyEvidence(vault, {+ pref_id: "pref-bytes",+ artifact: "[[some-note]]",+ result: "applied",+ agent: "claude",+ });+ moveToRetired(vault, pref, "user-rejected", { now: NOW, retired_by: "[[operator]]" });+ appendAuditRecord(join(vault, "Brain", "log", "hygiene"), {+ timestamp: "2026-11-06T10:02:00Z",+ actor: "claude",+ action: "apply",+ target: "note",+ ok: true,+ });+ appendClaimEvent(vault, {+ ts: "2026-11-06T10:03:00Z",+ agent: "claude",+ entity: "Alice Mason",+ aspect: "employer",+ value: "Google",+ source: "https://example.com/about",+ });+}++/** Ids a run mints itself: ULIDs, UUIDs and the 32-hex vault id. */+const RUN_LOCAL_ID_RE =+ /\b[0-9A-HJKMNP-TV-Z]{26}\b|\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\b|\b[0-9a-f]{32}\b/gi;++function brainFiles(vault: string): Map<string, string> {+ const root = join(vault, "Brain");+ const out = new Map<string, string>();+ const walk = (dir: string): void => {+ for (const entry of readdirSync(dir, { withFileTypes: true })) {+ const full = join(dir, entry.name);+ if (entry.isDirectory()) walk(full);+ else {+ const rel = relative(root, full).split("\\").join("/");+ out.set(rel, readFileSync(full, "latin1").replace(RUN_LOCAL_ID_RE, "<id>"));+ }+ }+ };+ walk(root);+ return out;+}++function runInFreshVault(name: string, flag: boolean): Map<string, string> {+ if (flag) process.env[STORE_DUAL_WRITE_ENV] = "1";+ else delete process.env[STORE_DUAL_WRITE_ENV];+ // One vault name in both runs: the manual records it.+ const vault = join(parent, name, "vault");+ mkdirSync(vault, { recursive: true });+ bootstrapBrain(vault);+ runWriters(vault);+ return brainFiles(vault);+}++describe("the legacy files with the flag off and on", () => {+ test("are byte-identical under Brain/, and only the run with the flag on fills the store", () => {+ const off = runInFreshVault("off", false);+ const recordsAfterOff = readPartition(join(storeRoot, "shared")).length;+ const on = runInFreshVault("on", true);+ expect(recordsAfterOff).toBe(0);+ expect(readPartition(join(storeRoot, "shared")).length).toBeGreaterThan(0);++ expect([...on.keys()].toSorted()).toEqual([...off.keys()].toSorted());+ // Non-vacuous: the writers really wrote into each tree.+ expect(off.size).toBeGreaterThan(5);+ for (const [rel, bytes] of off) expect(on.get(rel), rel).toBe(bytes);+ });+});diff --git a/tests/core/store/dual-write-operation-privacy.test.ts b/tests/core/store/dual-write-operation-privacy.test.tsnew file mode 100644index 00000000..c12b0db7--- /dev/null+++ b/tests/core/store/dual-write-operation-privacy.test.ts@@ -0,0 +1,744 @@+/**+ * One privacy verdict per write operation: every brain store record one+ * writer operation produces (the main record, the split preference+ * records, the log event, the evidence record, the idempotency receipt)+ * lands in ONE partition. Checked for every operation kind against every+ * trigger that makes an operation private, plus an all-open control:+ *+ * - `target`: the page the operation writes or is about is private;+ * - `link`: a content field links a private page;+ * - `region`: a content field carries a `<private>` region.+ *+ * A second suite walks every string field of each operation's caller+ * input and puts a region, then a private link, into each one in turn,+ * so a caller field the verdict does not read fails by name.+ *+ * A third suite runs every private cell again on a machine WITHOUT the+ * `private` partition: none of the operation's records may reach `shared`+ * (they are refused instead), whatever stream they belong to.+ *+ * The records an operation wrote are the ones present after it and absent+ * before it, across both partitions and every stream (events, log,+ * ledgers, receipts, anything a writer down the call chain appends), not+ * only the kinds a case names. Every test runs against its own temp+ * HOME, state base, vault and store root under one named parent, removed+ * in teardown.+ */+import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import { appendFileSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { dirname, join, relative } from "node:path";++import { appendApplyEvidence } from "../../../src/core/brain/apply-evidence.ts";+import { bootstrapBrain } from "../../../src/core/brain/init.ts";+import { appendBrainNote } from "../../../src/core/brain/note.ts";+import { logShardPath } from "../../../src/core/brain/paths.ts";+import { setPinned } from "../../../src/core/brain/pin.ts";+import { writePreference } from "../../../src/core/brain/preference.ts";+import { writeSignal } from "../../../src/core/brain/signal.ts";+import { applyWriteBatch, WriteBatchError } from "../../../src/core/brain/write-batch.ts";+import { createNote } from "../../../src/core/brain/notes/create-note.ts";+import { brainConfigPath } from "../../../src/core/brain/paths.ts";+import { STORE_DUAL_WRITE_ENV, STORE_ROOT_ENV } from "../../../src/core/store/constants.ts";+import { readPartition } from "../../../src/core/store/state-digest.ts";+import { initStore } from "../../../src/core/store/store-init.ts";++const ENV_KEYS = [+ STORE_DUAL_WRITE_ENV,+ STORE_ROOT_ENV,+ "O2B_DEVICE_ID",+ "HOME",+ "XDG_STATE_HOME",+ "LOCALAPPDATA",+ "OPEN_SECOND_BRAIN_CONFIG",+ "VAULT_AGENT_NAME",+] as const;++let parent: string;+let vault: string;+let storeRoot: string;+const saved = new Map<string, string | undefined>();++beforeEach(() => {+ for (const key of ENV_KEYS) saved.set(key, process.env[key]);+ parent = mkdtempSync(join(tmpdir(), "osb-operation-privacy-"));+ vault = join(parent, "vault");+ storeRoot = join(parent, "store");+ mkdirSync(vault, { recursive: true });+ bootstrapBrain(vault);+ process.env["HOME"] = join(parent, "home");+ process.env["XDG_STATE_HOME"] = join(parent, "state");+ process.env["LOCALAPPDATA"] = join(parent, "state");+ process.env[STORE_ROOT_ENV] = storeRoot;+ process.env["O2B_DEVICE_ID"] = "dev-a";+ process.env[STORE_DUAL_WRITE_ENV] = "1";+ delete process.env["VAULT_AGENT_NAME"];+ const config = join(parent, "config.yaml");+ writeFileSync(config, `vault: ${JSON.stringify(vault)}\nagent_name: agent-self\n`);+ process.env["OPEN_SECOND_BRAIN_CONFIG"] = config;+ initStore({ root: storeRoot });+ writePage("Notes/secret.md", "visibility: [private]");+});++afterEach(() => {+ for (const key of ENV_KEYS) {+ const value = saved.get(key);+ if (value === undefined) delete process.env[key];+ else process.env[key] = value;+ }+ rmSync(parent, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });+});++type Partition = "shared" | "private";++function writePage(rel: string, frontmatter: string): void {+ const abs = join(vault, rel);+ mkdirSync(dirname(abs), { recursive: true });+ writeFileSync(abs, `---\n${frontmatter}\n---\n\nbody\n`);+}++/** Every record of the store, as `partition:kind:checksum-ish` keys. */+function snapshot(): Map<string, Partition> {+ const out = new Map<string, Partition>();+ for (const partition of ["shared", "private"] as const) {+ for (const shard of readPartition(join(storeRoot, partition))) {+ shard.records.forEach((record, index) => {+ out.set(`${partition}:${shard.rel}:${index}:${record.kind}`, partition);+ });+ }+ }+ return out;+}++/** The partition and kind of every record `operation` added. */+function recordsOf(operation: () => unknown): Array<{ partition: Partition; kind: string }> {+ const before = snapshot();+ operation();+ const added: Array<{ partition: Partition; kind: string }> = [];+ for (const [key, partition] of snapshot()) {+ if (!before.has(key)) added.push({ partition, kind: key.split(":").at(-1)! });+ }+ return added;+}++function seedPreference(slug: string, extra: Record<string, unknown> = {}): void {+ writePreference(vault, {+ slug,+ topic: slug,+ principle: `principle ${slug}`,+ created_at: "2026-05-01T00:00:00Z",+ unconfirmed_until: "2026-05-30T00:00:00Z",+ status: "confirmed",+ confirmed_at: "2026-05-02T00:00:00Z",+ evidenced_by: [],+ confidence: "high",+ ...extra,+ });+}++type Trigger = "open" | "target" | "link" | "region" | "identity";++/** Per trigger: the field values that make the operation private. */+const TEXT: Record<Trigger, string> = {+ open: "a plain line",+ target: "a plain line",+ link: "see [[Notes/secret]] for the details",+ region: "met <private>the landlord</private> today",+ identity: "a plain line",+};++/**+ * The writer identity (`agent`, `owner`) an operation carries: a private+ * link under the `identity` trigger, a realistic agent name otherwise, so+ * every open control proves a plain identity names nothing private.+ */+function identity(trigger: Trigger): string {+ return trigger === "identity" ? "[[Notes/secret]]" : "@claude-devbox-agent";+}++interface Case {+ /** Triggers this operation kind can carry. */+ readonly triggers: ReadonlyArray<Trigger>;+ /** Seeds what the operation needs; its records are not the operation's. */+ readonly seed?: (trigger: Trigger) => void;+ /** Runs the operation. */+ readonly run: (trigger: Trigger) => void;+ /** Kinds of record the operation writes, at least. */+ readonly minRecords: number;+ /**+ * The operation writes a record that goes to `private` whenever this+ * machine holds it (a permissions decision row), so its open control+ * runs on a machine without `private`, where all of it lands in `shared`.+ */+ readonly heldPrivateRecord?: true;+}++/**+ * Turn the owner-write gate to `warn`: a note naming a foreign `owner`+ * is written, and the gate appends one decision row for it.+ */+function watchOwnerWrites(): void {+ appendFileSync(brainConfigPath(vault), "\nintegrity:\n owner_scope_writes: warn\n");+}++let counter = 0;+function nextKey(): string {+ counter += 1;+ return `k-${counter}`;+}++const CASES: Record<string, Case> = {+ "signal write (raw)": {+ triggers: ["open", "link", "region", "identity"],+ minRecords: 2,+ run: (trigger) => {+ writeSignal(vault, {+ topic: "plain-topic",+ signal: "positive",+ agent: identity(trigger),+ principle: "keep it short",+ created_at: "2026-11-06T10:00:00Z",+ date: "2026-11-06",+ slug: "plain-topic",+ raw: TEXT[trigger],+ idempotency_key: nextKey(),+ });+ },+ },+ "signal write (principle)": {+ triggers: ["open", "link", "region"],+ minRecords: 2,+ run: (trigger) => {+ writeSignal(vault, {+ topic: "plain-topic",+ signal: "positive",+ agent: identity(trigger),+ principle: TEXT[trigger],+ created_at: "2026-11-06T10:00:00Z",+ date: "2026-11-06",+ slug: "plain-topic",+ idempotency_key: nextKey(),+ });+ },+ },+ "signal write (source)": {+ triggers: ["open", "link"],+ minRecords: 2,+ run: (trigger) => {+ writeSignal(vault, {+ topic: "plain-topic",+ signal: "positive",+ agent: identity(trigger),+ principle: "keep it short",+ created_at: "2026-11-06T10:00:00Z",+ date: "2026-11-06",+ slug: "plain-topic",+ source: [trigger === "link" ? "[[Notes/secret]]" : "[[Notes/open]]"],+ idempotency_key: nextKey(),+ });+ },+ },+ "preference write (human split)": {+ triggers: ["open", "target", "link", "region"],+ minRecords: 3,+ run: (trigger) => {+ writePreference(+ vault,+ {+ slug: "rule",+ topic: "rule",+ principle: TEXT[trigger],+ created_at: "2026-05-01T00:00:00Z",+ unconfirmed_until: "2026-05-30T00:00:00Z",+ status: "confirmed",+ confirmed_at: "2026-05-02T00:00:00Z",+ evidenced_by: [],+ confidence: "high",+ idempotency_key: nextKey(),+ ...(trigger === "target" ? { visibility: ["private"] } : {}),+ },+ { authority: "human" },+ );+ },+ },+ "preference write (owner)": {+ triggers: ["open", "identity"],+ minRecords: 2,+ run: (trigger) => {+ writePreference(vault, {+ slug: "rule",+ topic: "rule",+ principle: "keep it short",+ created_at: "2026-05-01T00:00:00Z",+ unconfirmed_until: "2026-05-30T00:00:00Z",+ status: "confirmed",+ confirmed_at: "2026-05-02T00:00:00Z",+ evidenced_by: [],+ confidence: "high",+ owner: identity(trigger),+ idempotency_key: nextKey(),+ });+ },+ },+ "preference write (evidenced_by)": {+ triggers: ["open", "link"],+ minRecords: 2,+ run: (trigger) => {+ writePreference(vault, {+ slug: "rule",+ topic: "rule",+ principle: "keep it short",+ created_at: "2026-05-01T00:00:00Z",+ unconfirmed_until: "2026-05-30T00:00:00Z",+ status: "confirmed",+ confirmed_at: "2026-05-02T00:00:00Z",+ evidenced_by: [trigger === "link" ? "[[Notes/secret]]" : "[[Notes/open]]"],+ confidence: "high",+ idempotency_key: nextKey(),+ });+ },+ },+ "apply_evidence (artifact)": {+ triggers: ["open", "target", "link", "region", "identity"],+ minRecords: 3,+ seed: (trigger) =>+ seedPreference("rule", trigger === "target" ? { visibility: ["private"] } : {}),+ run: (trigger) => {+ appendApplyEvidence(vault, {+ pref_id: "pref-rule",+ artifact: trigger === "region" ? "[[src/main.ts]]" : TEXT[trigger],+ result: "applied",+ agent: identity(trigger),+ ...(trigger === "region" ? { note: TEXT.region } : {}),+ idempotency_key: nextKey(),+ });+ },+ },+ brain_note: {+ triggers: ["open", "link", "region", "identity"],+ minRecords: 1,+ run: (trigger) => {+ appendBrainNote({ vault, text: TEXT[trigger], agent: identity(trigger) });+ },+ },+ write_batch: {+ triggers: ["open", "target", "link", "region", "identity"],+ minRecords: 4,+ seed: (trigger) => {+ seedPreference("open-rule");+ seedPreference("rule", trigger === "target" ? { visibility: ["private"] } : {});+ },+ run: (trigger) => {+ applyWriteBatch(+ vault,+ [+ {+ kind: "append_log_line",+ input: { text: "a plain line first", agent: identity(trigger) },+ },+ {+ kind: "apply_evidence",+ input: {+ pref_id: "pref-open-rule",+ artifact: "[[src/main.ts]]",+ result: "applied",+ agent: identity(trigger),+ },+ },+ {+ kind: "apply_evidence",+ input: {+ pref_id: "pref-rule",+ artifact: "[[src/other.ts]]",+ result: "applied",+ agent: identity(trigger),+ },+ },+ {+ kind: "append_log_line",+ input: { text: TEXT[trigger], agent: identity(trigger) },+ },+ ],+ { requestId: nextKey() },+ );+ },+ },+ "write_batch (private note page)": {+ triggers: ["open", "target"],+ minRecords: 2,+ run: (trigger) => {+ applyWriteBatch(+ vault,+ [+ {+ kind: "append_log_line",+ input: { text: "a plain line first", agent: identity(trigger) },+ },+ {+ kind: "create_note",+ path: "Notes/new.md",+ frontmatter: trigger === "target" ? { visibility: ["private"] } : { title: "new" },+ content: "plain body",+ },+ ],+ { requestId: nextKey() },+ );+ },+ },+ "preference write (watched foreign owner on a private page)": {+ triggers: ["open", "target"],+ minRecords: 3,+ heldPrivateRecord: true,+ seed: () => watchOwnerWrites(),+ run: (trigger) => {+ writePreference(vault, {+ slug: "rule",+ topic: "rule",+ principle: "keep it short",+ created_at: "2026-05-01T00:00:00Z",+ unconfirmed_until: "2026-05-30T00:00:00Z",+ status: "confirmed",+ confirmed_at: "2026-05-02T00:00:00Z",+ evidenced_by: [],+ confidence: "high",+ owner: "agent-cross-owner",+ idempotency_key: nextKey(),+ ...(trigger === "target" ? { visibility: ["private"] } : {}),+ });+ },+ },+ "write_batch (watched foreign owner on a private note)": {+ triggers: ["open", "target"],+ minRecords: 3,+ heldPrivateRecord: true,+ seed: () => watchOwnerWrites(),+ run: (trigger) => {+ applyWriteBatch(+ vault,+ [+ {+ kind: "create_note",+ path: "Notes/owned.md",+ frontmatter: {+ owner: "agent-cross-owner",+ ...(trigger === "target" ? { visibility: ["private"] } : {}),+ },+ content: "plain body",+ },+ ],+ { requestId: nextKey() },+ );+ },+ },+ "create_note (watched foreign owner on a private note)": {+ triggers: ["open", "target"],+ minRecords: 2,+ heldPrivateRecord: true,+ seed: () => watchOwnerWrites(),+ run: (trigger) => {+ createNote(vault, {+ path: "Notes/owned.md",+ frontmatter: {+ owner: "agent-cross-owner",+ ...(trigger === "target" ? { visibility: ["private"] } : {}),+ },+ content: "plain body",+ });+ },+ },+ pin: {+ triggers: ["open", "target", "link", "region"],+ minRecords: 2,+ seed: (trigger) =>+ seedPreference("rule", {+ principle: TEXT[trigger],+ ...(trigger === "target" ? { visibility: ["private"] } : {}),+ }),+ run: () => {+ setPinned(vault, "pref-rule", true, { agent: identity("open") });+ },+ },+};++describe("one privacy verdict per write operation", () => {+ for (const [name, c] of Object.entries(CASES)) {+ for (const trigger of c.triggers) {+ const expected: Partition = trigger === "open" ? "shared" : "private";+ test(`${name}, ${trigger}: every record lands in ${expected}`, () => {+ writePage("Notes/open.md", "title: open");+ c.seed?.(trigger);+ if (trigger === "open" && c.heldPrivateRecord === true) {+ rmSync(join(storeRoot, "private"), { recursive: true, force: true });+ }+ const added = recordsOf(() => c.run(trigger));+ expect(added.length).toBeGreaterThanOrEqual(c.minRecords);+ expect(added.filter((r) => r.partition !== expected)).toEqual([]);+ });+ }+ }+});++describe("a private operation on a machine without the private partition", () => {+ for (const [name, c] of Object.entries(CASES)) {+ for (const trigger of c.triggers) {+ if (trigger === "open") continue;+ test(`${name}, ${trigger}: no record of the operation reaches shared`, () => {+ writePage("Notes/open.md", "title: open");+ c.seed?.(trigger);+ rmSync(join(storeRoot, "private"), { recursive: true, force: true });+ const added = recordsOf(() => c.run(trigger));+ expect(added).toEqual([]);+ });+ }+ }+});++describe("the operation verdict is final for its receipt", () => {+ test("a page turned private between verdict and receipt keeps the operation in one partition", () => {+ // The evidence call judges its preference and its event, both open,+ // and writes its log event under that verdict. The daily log page its+ // receipt names is private by the time the receipt is written (another+ // writer reserved it): the receipt still follows the operation.+ seedPreference("rule");+ const day = new Date().toISOString().slice(0, 10);+ const shard = logShardPath(vault, day, "dev-a");+ writePage(relative(vault, shard), "visibility: [private]");+ const added = recordsOf(() =>+ appendApplyEvidence(vault, {+ pref_id: "pref-rule",+ artifact: "[[src/main.ts]]",+ result: "applied",+ agent: identity("open"),+ idempotency_key: nextKey(),+ }),+ );+ expect(added.length).toBeGreaterThanOrEqual(3);+ expect(new Set(added.map((r) => r.partition)).size).toBe(1);+ });+});++describe("a malformed batch is refused by index before any privacy judge", () => {+ const MALFORMED: Record<string, ReadonlyArray<unknown>> = {+ "a null operation": [null],+ "an append_log_line without input": [{ kind: "append_log_line" }],+ };+ for (const dual of ["off", "on"] as const) {+ for (const [name, operations] of Object.entries(MALFORMED)) {+ test(`${name}, dual write ${dual}: indexed WriteBatchError, nothing written`, () => {+ if (dual === "off") delete process.env[STORE_DUAL_WRITE_ENV];+ const added = recordsOf(() => {+ let thrown: unknown;+ try {+ applyWriteBatch(vault, operations as never, {+ requestId: nextKey(),+ });+ } catch (err) {+ thrown = err;+ }+ expect(thrown).toBeInstanceOf(WriteBatchError);+ expect((thrown as WriteBatchError).index).toBe(0);+ });+ expect(added).toEqual([]);+ });+ }+ }+});++/**+ * The verdict covers every caller-supplied input. For each operation kind,+ * every string field of the caller's input (walked at any depth; for a+ * batch, every field of every operation and the request id) gets, one at a+ * time, a `<private>` region, and in a second cell a `[[Notes/secret]]`+ * link. Whatever the operation then writes lands in ONE partition: a+ * region anywhere, or a link in any field that is not opaque (a key, a+ * hash, a timestamp, an id), makes it `private`. A caller field the+ * verdict does not read would leave some records in `shared` and fail here.+ */+interface FieldCase {+ /** Seeds what the operation needs. */+ readonly seed?: () => void;+ /** A fresh caller input. */+ readonly input: () => Record<string, unknown>;+ /** Runs the operation on `input`. */+ readonly run: (input: Record<string, unknown>) => unknown;+ /** Fields a link in which names nothing: keys, hashes, timestamps, ids. */+ readonly opaque: ReadonlySet<string>;+ /**+ * Fields the writer validates (an enum, a slug, a date, a path, an+ * operation kind): any extra text there refuses the input before a+ * record is written. Every other cell must write records.+ */+ readonly refuses: ReadonlySet<string>;+}++type FieldPath = ReadonlyArray<string | number>;++/** The path of every string `value` carries, at any depth. */+function stringPaths(value: unknown, at: FieldPath = []): FieldPath[] {+ if (typeof value === "string") return [at];+ if (Array.isArray(value)) return value.flatMap((child, i) => stringPaths(child, [...at, i]));+ if (value !== null && typeof value === "object") {+ return Object.entries(value).flatMap(([key, child]) => stringPaths(child, [...at, key]));+ }+ return [];+}++/** `input` with the string at `path` passed through `edit`. */+function editAt<T>(input: T, path: FieldPath, edit: (s: string) => string): T {+ const copy = structuredClone(input) as Record<string | number, unknown>;+ let node = copy;+ for (const key of path.slice(0, -1)) node = node[key] as Record<string | number, unknown>;+ const last = path.at(-1)!;+ node[last] = edit(node[last] as string);+ return copy as T;+}++const FIELD_CASES: Record<string, FieldCase> = {+ signal: {+ input: () => ({+ topic: "plain-topic",+ signal: "positive",+ agent: "@claude-devbox-agent",+ principle: "keep it short",+ created_at: "2026-11-06T10:00:00Z",+ date: "2026-11-06",+ slug: "plain-topic",+ scope: "coding",+ source: ["[[Notes/open]]"],+ raw: "a plain line",+ idempotency_key: nextKey(),+ }),+ run: (input) => writeSignal(vault, input as never),+ opaque: new Set(["created_at", "date", "slug", "idempotency_key"]),+ refuses: new Set(["signal", "date", "slug", "scope"]),+ },+ preference: {+ input: () => ({+ slug: "rule",+ topic: "rule",+ principle: "keep it short",+ created_at: "2026-05-01T00:00:00Z",+ unconfirmed_until: "2026-05-30T00:00:00Z",+ status: "confirmed",+ confirmed_at: "2026-05-02T00:00:00Z",+ evidenced_by: ["[[Notes/open]]"],+ confidence: "high",+ scope: "coding",+ owner: "@claude-devbox-agent",+ idempotency_key: nextKey(),+ }),+ run: (input) => writePreference(vault, input as never),+ opaque: new Set(["slug", "created_at", "unconfirmed_until", "confirmed_at", "idempotency_key"]),+ refuses: new Set(["slug", "status", "scope"]),+ },+ apply_evidence: {+ seed: () => seedPreference("rule"),+ input: () => ({+ pref_id: "pref-rule",+ artifact: "[[src/main.ts]]",+ result: "applied",+ agent: "@claude-devbox-agent",+ note: "a plain line",+ outcome: "success",+ idempotency_key: nextKey(),+ }),+ run: (input) => appendApplyEvidence(vault, input as never),+ opaque: new Set(["idempotency_key"]),+ refuses: new Set(["pref_id", "result", "outcome"]),+ },+ brain_note: {+ input: () => ({ text: "a plain line", agent: "@claude-devbox-agent" }),+ run: (input) => appendBrainNote({ vault, ...(input as { text: string; agent: string }) }),+ opaque: new Set(),+ refuses: new Set(),+ },+ pin: {+ seed: () => seedPreference("rule"),+ input: () => ({ prefId: "pref-rule", agent: "@claude-devbox-agent" }),+ run: (input) =>+ setPinned(vault, input["prefId"] as string, true, { agent: input["agent"] as string }),+ opaque: new Set(),+ refuses: new Set(["prefId"]),+ },+ write_batch: {+ seed: () => seedPreference("open-rule"),+ input: () => ({+ requestId: nextKey(),+ operations: [+ {+ kind: "append_log_line",+ input: { text: "a plain line first", agent: "@claude-devbox-agent" },+ },+ {+ kind: "apply_evidence",+ input: {+ pref_id: "pref-open-rule",+ artifact: "[[src/main.ts]]",+ result: "applied",+ agent: "@claude-devbox-agent",+ note: "a plain line",+ idempotency_key: nextKey(),+ },+ },+ {+ kind: "create_note",+ path: "Notes/new.md",+ frontmatter: { title: "new" },+ content: "plain body",+ },+ {+ kind: "append_log_line",+ input: { text: "a plain line last", agent: "@claude-devbox-agent" },+ },+ ],+ }),+ run: (input) =>+ applyWriteBatch(vault, input["operations"] as never, {+ requestId: input["requestId"] as string,+ }),+ opaque: new Set(["requestId", "kind", "idempotency_key"]),+ refuses: new Set(["kind", "pref_id", "result", "path"]),+ },+};++const INJECTIONS = {+ region: (s: string) => `${s}<private>x</private>`,+ link: (s: string) => `${s} [[Notes/secret]]`,+} as const;++describe("the operation verdict covers every caller-supplied field", () => {+ for (const [name, c] of Object.entries(FIELD_CASES)) {+ test(`${name}, open control: every record lands in shared`, () => {+ writePage("Notes/open.md", "title: open");+ c.seed?.();+ const added = recordsOf(() => c.run(c.input()));+ expect(added.length).toBeGreaterThan(0);+ expect(added.filter((r) => r.partition !== "shared")).toEqual([]);+ });+ for (const path of stringPaths(c.input())) {+ const field = path.findLast((p) => typeof p === "string") as string;+ for (const [injection, edit] of Object.entries(INJECTIONS)) {+ const named = injection === "region" || !c.opaque.has(field);+ test(`${name}, ${injection} in ${path.join(".")}: one partition${named ? ", private" : ""}`, () => {+ writePage("Notes/open.md", "title: open");+ c.seed?.();+ const input = editAt(c.input(), path, edit);+ const added = recordsOf(() => {+ try {+ c.run(input);+ } catch {+ // A refused input: checked below to have written nothing.+ }+ });+ if (c.refuses.has(field)) {+ expect(added).toEqual([]);+ return;+ }+ expect(added.length).toBeGreaterThan(0);+ expect(new Set(added.map((r) => r.partition)).size).toBe(1);+ if (named) expect(added.filter((r) => r.partition !== "private")).toEqual([]);+ });+ }+ }+ }+});diff --git a/tests/core/store/dual-write-private-regions.test.ts b/tests/core/store/dual-write-private-regions.test.tsnew file mode 100644index 00000000..f5dd213b--- /dev/null+++ b/tests/core/store/dual-write-private-regions.test.ts@@ -0,0 +1,204 @@+/**+ * Dual-written records whose text carries a `<private>` region, or the+ * placeholder a stripped region leaves, go to `private` only: a Brain log+ * event, a signal, a preference, a preference-evidence record and a ledger+ * row that would otherwise go to `private` only when this machine holds it.+ *+ * Every test runs against its own temp HOME, state base, vault and store+ * root under one named parent, removed in teardown.+ */+import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import { appendApplyEvidence } from "../../../src/core/brain/apply-evidence.ts";+import { bootstrapBrain } from "../../../src/core/brain/init.ts";+import { appendLogEvent } from "../../../src/core/brain/log.ts";+import { appendBrainNote } from "../../../src/core/brain/note.ts";+import { writePreference } from "../../../src/core/brain/preference.ts";+import { writeSignal } from "../../../src/core/brain/signal.ts";+import { appendClaimEvent } from "../../../src/core/brain/truth/store.ts";+import {+ PREFERENCE_EVIDENCE_KIND,+ PREFERENCE_SET_KIND,+ SIGNAL_KIND,+ STORE_DUAL_WRITE_ENV,+ STORE_ROOT_ENV,+} from "../../../src/core/store/constants.ts";+import type { StoreRecord } from "../../../src/core/store/envelope.ts";+import { readPartition } from "../../../src/core/store/state-digest.ts";+import { initStore } from "../../../src/core/store/store-init.ts";++const ENV_KEYS = [+ STORE_DUAL_WRITE_ENV,+ STORE_ROOT_ENV,+ "O2B_DEVICE_ID",+ "HOME",+ "XDG_STATE_HOME",+ "LOCALAPPDATA",+ "OPEN_SECOND_BRAIN_CONFIG",+] as const;++let parent: string;+let vault: string;+let storeRoot: string;+const saved = new Map<string, string | undefined>();++beforeEach(() => {+ for (const key of ENV_KEYS) saved.set(key, process.env[key]);+ parent = mkdtempSync(join(tmpdir(), "osb-private-regions-"));+ vault = join(parent, "vault");+ storeRoot = join(parent, "store");+ mkdirSync(vault, { recursive: true });+ bootstrapBrain(vault);+ process.env["HOME"] = join(parent, "home");+ process.env["XDG_STATE_HOME"] = join(parent, "state");+ process.env["LOCALAPPDATA"] = join(parent, "state");+ process.env[STORE_ROOT_ENV] = storeRoot;+ process.env["O2B_DEVICE_ID"] = "dev-a";+ process.env[STORE_DUAL_WRITE_ENV] = "1";+ initStore({ root: storeRoot });+});++afterEach(() => {+ for (const key of ENV_KEYS) {+ const value = saved.get(key);+ if (value === undefined) delete process.env[key];+ else process.env[key] = value;+ }+ rmSync(parent, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });+});++function records(partition: "shared" | "private"): StoreRecord[] {+ return readPartition(join(storeRoot, partition)).flatMap((s) => s.records);+}++function logEvents(partition: "shared" | "private"): StoreRecord[] {+ return readPartition(join(storeRoot, partition))+ .filter((s) => s.rel.startsWith("log/"))+ .flatMap((s) => s.records);+}++function ofKind(partition: "shared" | "private", kind: string): StoreRecord[] {+ return records(partition).filter((r) => r.kind === kind);+}++function ledgerRows(partition: "shared" | "private", ledger: string): StoreRecord[] {+ return readPartition(join(storeRoot, partition))+ .filter((s) => s.rel.startsWith(`ledgers/${ledger}/`))+ .flatMap((s) => s.records);+}++function seedPreference(slug: string, extra: Record<string, unknown> = {}): void {+ writePreference(vault, {+ slug,+ topic: slug,+ principle: `principle ${slug}`,+ created_at: "2026-05-01T00:00:00Z",+ unconfirmed_until: "2026-05-30T00:00:00Z",+ status: "confirmed",+ confirmed_at: "2026-05-02T00:00:00Z",+ evidenced_by: [],+ confidence: "high",+ ...extra,+ });+}++describe("log events", () => {+ test("a note whose text had a <private> region goes to private only", () => {+ appendBrainNote({+ vault,+ text: "met <private>the landlord about the lease</private> today",+ agent: "claude",+ });+ expect(logEvents("shared")).toEqual([]);+ expect(logEvents("private").length).toBe(1);+ });++ test("an event whose body carries an unstripped <private> region goes to private only", () => {+ appendLogEvent(vault, {+ timestamp: "2026-11-06T10:01:00Z",+ eventType: "note",+ agent: "claude",+ body: { text: "keep <private>this</private> local" },+ });+ expect(logEvents("shared")).toEqual([]);+ expect(logEvents("private").length).toBe(1);+ });++ test("an event with no region and no private reference still goes to shared", () => {+ appendBrainNote({ vault, text: "a plain milestone", agent: "claude" });+ expect(logEvents("shared").length).toBe(1);+ expect(logEvents("private")).toEqual([]);+ });++ test("on a machine without the private partition the event is refused, not shared", () => {+ rmSync(join(storeRoot, "private"), { recursive: true, force: true });+ appendBrainNote({ vault, text: "a <private>secret</private> note", agent: "claude" });+ expect(logEvents("shared")).toEqual([]);+ });+});++describe("other dual-written records", () => {+ test("a signal whose principle carries a <private> region goes to private only", () => {+ writeSignal(vault, {+ topic: "lease",+ signal: "positive",+ agent: "claude",+ principle: "Ask <private>the landlord</private> before renewing",+ created_at: "2026-11-06T10:00:00Z",+ date: "2026-11-06",+ slug: "lease",+ });+ expect(ofKind("shared", SIGNAL_KIND)).toEqual([]);+ expect(ofKind("private", SIGNAL_KIND).length).toBe(1);+ });++ test("a preference whose principle carries a <private> region goes to private only", () => {+ seedPreference("lease", { principle: "Ask <private>the landlord</private> first" });+ expect(ofKind("shared", PREFERENCE_SET_KIND)).toEqual([]);+ expect(ofKind("private", PREFERENCE_SET_KIND).length).toBeGreaterThan(0);+ });++ test("evidence whose artifact carries a <private> region goes to private only", () => {+ seedPreference("open");+ appendApplyEvidence(vault, {+ pref_id: "pref-open",+ artifact: "draft <private>for the landlord</private>",+ result: "applied",+ agent: "claude",+ });+ expect(ofKind("shared", PREFERENCE_EVIDENCE_KIND)).toEqual([]);+ expect(ofKind("private", PREFERENCE_EVIDENCE_KIND).length).toBe(1);+ });++ test("evidence whose artifact names a private page follows its log event to private", () => {+ seedPreference("open");+ const path = join(vault, "Notes/secret.md");+ mkdirSync(join(path, ".."), { recursive: true });+ writeFileSync(path, "---\nvisibility: [private]\n---\nbody\n");+ appendApplyEvidence(vault, {+ pref_id: "pref-open",+ artifact: "[[Notes/secret]]",+ result: "applied",+ agent: "claude",+ });+ expect(logEvents("private").length).toBe(1);+ expect(ofKind("shared", PREFERENCE_EVIDENCE_KIND)).toEqual([]);+ expect(ofKind("private", PREFERENCE_EVIDENCE_KIND).length).toBe(1);+ });++ test("a claim whose value carries a <private> region is refused, not shared, on a machine without private", () => {+ rmSync(join(storeRoot, "private"), { recursive: true, force: true });+ appendClaimEvent(vault, {+ ts: "2026-06-01T10:00:00Z",+ agent: "claude",+ entity: "Alice Mason",+ aspect: "address",+ value: "<private>12 Elm Street</private>",+ source: "https://example.com/directory",+ });+ expect(ledgerRows("shared", "truth-claims")).toEqual([]);+ });+});diff --git a/tests/core/store/dual-write-row-privacy.test.ts b/tests/core/store/dual-write-row-privacy.test.tsnew file mode 100644index 00000000..38ebcc5a--- /dev/null+++ b/tests/core/store/dual-write-row-privacy.test.ts@@ -0,0 +1,302 @@+/**+ * Dual-written ledger rows that name pages (idempotency receipts,+ * recurrence events, continuity turns, verifier rejections) follow the+ * fail-closed reference-privacy rule: a row that names a private page, or+ * a preference whose page cannot be judged, goes to `private` only; any+ * other row keeps the partition its ledger states.+ *+ * Every test runs against its own temp HOME, state base, vault and store+ * root under one named parent, removed in teardown.+ */+import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import { appendApplyEvidence } from "../../../src/core/brain/apply-evidence.ts";+import { appendContinuityRecord } from "../../../src/core/brain/continuity/store.ts";+import { applyWriteBatch } from "../../../src/core/brain/write-batch.ts";+import { bootstrapBrain } from "../../../src/core/brain/init.ts";+import { writePreference } from "../../../src/core/brain/preference.ts";+import {+ applyRecurrenceEvidence,+ purgeRecurrenceSource,+} from "../../../src/core/brain/recurrence.ts";+import { STORE_DUAL_WRITE_ENV, STORE_ROOT_ENV } from "../../../src/core/store/constants.ts";+import { readDualWriteStatus } from "../../../src/core/store/dual-write.ts";+import type { StoreRecord } from "../../../src/core/store/envelope.ts";+import { rowNamesPrivatePage } from "../../../src/core/store/reference-privacy.ts";+import { readPartition } from "../../../src/core/store/state-digest.ts";+import { initStore } from "../../../src/core/store/store-init.ts";++const ENV_KEYS = [+ STORE_DUAL_WRITE_ENV,+ STORE_ROOT_ENV,+ "O2B_DEVICE_ID",+ "HOME",+ "XDG_STATE_HOME",+ "LOCALAPPDATA",+ "OPEN_SECOND_BRAIN_CONFIG",+] as const;++let parent: string;+let vault: string;+let storeRoot: string;+const saved = new Map<string, string | undefined>();++beforeEach(() => {+ for (const key of ENV_KEYS) saved.set(key, process.env[key]);+ parent = mkdtempSync(join(tmpdir(), "osb-row-privacy-"));+ vault = join(parent, "vault");+ storeRoot = join(parent, "store");+ mkdirSync(vault, { recursive: true });+ bootstrapBrain(vault);+ process.env["HOME"] = join(parent, "home");+ process.env["XDG_STATE_HOME"] = join(parent, "state");+ process.env["LOCALAPPDATA"] = join(parent, "state");+ process.env[STORE_ROOT_ENV] = storeRoot;+ process.env["O2B_DEVICE_ID"] = "dev-a";+ process.env[STORE_DUAL_WRITE_ENV] = "1";+ initStore({ root: storeRoot });+});++afterEach(() => {+ for (const key of ENV_KEYS) {+ const value = saved.get(key);+ if (value === undefined) delete process.env[key];+ else process.env[key] = value;+ }+ rmSync(parent, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });+});++function ledgerRows(partition: "shared" | "private", ledger: string): StoreRecord[] {+ return readPartition(join(storeRoot, partition))+ .filter((s) => s.rel.startsWith(`ledgers/${ledger}/`))+ .flatMap((s) => s.records);+}++function seedPreference(slug: string, extra: Record<string, unknown> = {}): void {+ writePreference(vault, {+ slug,+ topic: slug,+ principle: `principle ${slug}`,+ created_at: "2026-05-01T00:00:00Z",+ unconfirmed_until: "2026-05-30T00:00:00Z",+ status: "confirmed",+ confirmed_at: "2026-05-02T00:00:00Z",+ evidenced_by: [],+ confidence: "high",+ ...extra,+ });+}++/** The Brain log events dual-written to one partition. */+function logEvents(partition: "shared" | "private"): StoreRecord[] {+ return readPartition(join(storeRoot, partition))+ .filter((s) => s.rel.startsWith("log/"))+ .flatMap((s) => s.records);+}++/** The client keys of the idempotency receipts in one partition. */+function receiptKeys(partition: "shared" | "private"): unknown[] {+ return ledgerRows(partition, "idempotency").map(+ (r) => (r.body["row"] as Record<string, unknown>)["key"],+ );+}++/** One batch operation recording evidence against `prefId`. */+function evidence(prefId: string) {+ return {+ kind: "apply_evidence",+ input: { pref_id: prefId, artifact: "[[some-note]]", result: "applied", agent: "claude" },+ } as const;+}++function writePage(rel: string, frontmatter: string): void {+ const path = join(vault, rel);+ mkdirSync(join(path, ".."), { recursive: true });+ writeFileSync(path, `---\n${frontmatter}\n---\nbody\n`);+}++describe("idempotency receipts", () => {+ test("a private preference's receipt stays out of shared, an open one lands there", () => {+ seedPreference("hush", { visibility: ["private"], idempotency_key: "k-hush" });+ seedPreference("open", { idempotency_key: "k-open" });+ const sharedKeys = ledgerRows("shared", "idempotency").map(+ (r) => (r.body["row"] as Record<string, unknown>)["key"],+ );+ expect(sharedKeys).toEqual(["k-open"]);+ const privateKeys = ledgerRows("private", "idempotency").map(+ (r) => (r.body["row"] as Record<string, unknown>)["key"],+ );+ expect(privateKeys).toEqual(["k-hush"]);+ });++ test("evidence on a private preference keeps its receipt out of shared", () => {+ seedPreference("hush", { visibility: ["private"] });+ appendApplyEvidence(vault, {+ pref_id: "pref-hush",+ artifact: "[[some-note]]",+ result: "applied",+ agent: "claude",+ idempotency_key: "k-evidence",+ });+ expect(ledgerRows("shared", "idempotency")).toEqual([]);+ expect(ledgerRows("private", "idempotency").length).toBe(1);+ });++ test("a batch receipt carries the batch's privacy verdict", () => {+ seedPreference("hush", { visibility: ["private"] });+ seedPreference("open");+ applyWriteBatch(vault, [evidence("pref-hush")], { requestId: "batch-hush" });+ applyWriteBatch(vault, [evidence("pref-open")], { requestId: "batch-open" });+ expect(receiptKeys("shared")).toEqual(["batch-open"]);+ expect(receiptKeys("private")).toEqual(["batch-hush"]);+ });++ test("a batch receipt is judged under the flag its own dual write reads, not the batch's config", () => {+ // The machine config turns dual writes on; the config the batch is+ // handed turns them off. The receipt is still dual-written (under the+ // machine config), so its privacy must still be judged.+ delete process.env[STORE_DUAL_WRITE_ENV];+ const machineConfig = join(parent, "machine.yaml");+ const batchConfig = join(parent, "batch.yaml");+ writeFileSync(machineConfig, "store_dual_write: true\n");+ writeFileSync(batchConfig, "store_dual_write: false\n");+ process.env["OPEN_SECOND_BRAIN_CONFIG"] = machineConfig;+ seedPreference("hush", { visibility: ["private"] });+ applyWriteBatch(vault, [evidence("pref-hush")], {+ requestId: "batch-hush",+ configPath: batchConfig,+ });+ expect(receiptKeys("shared")).toEqual([]);+ expect(receiptKeys("private")).toEqual(["batch-hush"]);+ });++ test("a log line naming a bare private preference id keeps its batch receipt out of shared", () => {+ seedPreference("hush", { visibility: ["private"] });+ applyWriteBatch(vault, [{ kind: "append_log_line", input: { text: "pref-hush" } }], {+ requestId: "batch-log",+ });+ // The log writer routes the event to private; the receipt follows it.+ expect(logEvents("private").length).toBe(1);+ expect(logEvents("shared")).toEqual([]);+ expect(receiptKeys("shared")).toEqual([]);+ expect(receiptKeys("private")).toEqual(["batch-log"]);+ });++ test("evidence whose artifact names a private page keeps its batch receipt out of shared", () => {+ seedPreference("open");+ writePage("Notes/secret.md", "visibility: [private]");+ applyWriteBatch(+ vault,+ [+ {+ kind: "apply_evidence",+ input: {+ pref_id: "pref-open",+ artifact: "[[Notes/secret]]",+ result: "applied",+ agent: "claude",+ },+ },+ ],+ { requestId: "batch-secret-artifact" },+ );+ expect(logEvents("shared")).toEqual([]);+ expect(logEvents("private").length).toBe(1);+ expect(receiptKeys("shared")).toEqual([]);+ expect(receiptKeys("private")).toEqual(["batch-secret-artifact"]);+ });++ test("an opaque key or hash that looks like a reference does not make a receipt private", () => {+ seedPreference("open");+ appendApplyEvidence(vault, {+ pref_id: "pref-open",+ artifact: "[[some-note]]",+ result: "applied",+ agent: "claude",+ idempotency_key: "pref-unused",+ });+ applyWriteBatch(+ vault,+ [+ {+ kind: "apply_evidence",+ input: { pref_id: "pref-open", artifact: "[[x]]", result: "violated", agent: "claude" },+ },+ ],+ { requestId: "ret-unused" },+ );+ expect(receiptKeys("shared")).toEqual(["pref-unused", "ret-unused"]);+ expect(ledgerRows("private", "idempotency")).toEqual([]);+ });++ test("a private receipt is refused on a machine without the private partition", () => {+ rmSync(join(storeRoot, "private"), { recursive: true, force: true });+ seedPreference("hush", { visibility: ["private"], idempotency_key: "k-hush" });+ expect(ledgerRows("shared", "idempotency")).toEqual([]);+ expect(readDualWriteStatus().failures).toBeGreaterThan(0);+ });+});++describe("recurrence events", () => {+ test("a source naming a private page, or a page link that names none, stays out of shared", () => {+ writePage("Notes/secret.md", "visibility: [private]");+ writePage("Notes/open.md", "topic: x");+ const learn = (sourceId: string): void => {+ applyRecurrenceEvidence(vault, {+ contentHash: "h1",+ scope: "coding",+ sourceId,+ action: "learn",+ });+ };+ learn("[[Notes/secret]]");+ learn("[[Notes/missing]]");+ purgeRecurrenceSource(vault, "Notes/secret.md");+ learn("[[Notes/open]]");+ learn("session-42");+ const sources = (partition: "shared" | "private"): unknown[] =>+ ledgerRows(partition, "recurrence").map(+ (r) => (r.body["row"] as Record<string, unknown>)["sourceId"],+ );+ expect(sources("shared")).toEqual(["[[Notes/open]]", "session-42"]);+ expect(sources("private")).toEqual([+ "[[Notes/secret]]",+ "[[Notes/missing]]",+ "Notes/secret.md",+ ]);+ });+});++describe("continuity turns", () => {+ test("a turn that links a private page stays out of shared", () => {+ writePage("Notes/secret.md", "visibility: [private]");+ appendContinuityRecord(vault, {+ kind: "session_turn",+ createdAt: "2026-11-06T10:00:00.000Z",+ payload: { text: "worked on [[Notes/secret]]" },+ });+ appendContinuityRecord(vault, {+ kind: "session_turn",+ createdAt: "2026-11-06T10:01:00.000Z",+ payload: { text: "plain turn" },+ });+ expect(ledgerRows("shared", "continuity").length).toBe(1);+ expect(ledgerRows("private", "continuity").length).toBe(1);+ });+});++describe("the row judge", () => {+ test("judges strings at any depth and fails closed past its depth bound", () => {+ seedPreference("hush", { visibility: ["private"] });+ expect(rowNamesPrivatePage(vault, { a: [{ b: "see [[pref-hush]]" }] })).toBe(true);+ expect(rowNamesPrivatePage(vault, { a: ["x <private>y</private>"] })).toBe(true);+ expect(rowNamesPrivatePage(vault, { ref: "pref-never-written" })).toBe(true);+ expect(rowNamesPrivatePage(vault, { n: 1, text: "plain", list: ["a", "b"] })).toBe(false);+ let deep: unknown = "plain";+ for (let i = 0; i < 10_000; i++) deep = [deep];+ expect(rowNamesPrivatePage(vault, deep)).toBe(true);+ });+});diff --git a/tests/core/store/dual-write.test.ts b/tests/core/store/dual-write.test.tsnew file mode 100644index 00000000..8198c93e--- /dev/null+++ b/tests/core/store/dual-write.test.ts@@ -0,0 +1,680 @@+/**+ * Dual writes (task 1.11): with the flag on, the legacy writers also append+ * the equivalent store record; with it off the store is never touched; a+ * store failure never fails the legacy write.+ *+ * Every test runs against its own temp HOME, state base, vault and store+ * root under one named parent, removed in teardown.+ */+import { afterEach, beforeEach, describe, expect, spyOn, test } from "bun:test";+import {+ chmodSync,+ existsSync,+ mkdirSync,+ mkdtempSync,+ readFileSync,+ renameSync,+ rmSync,+ writeFileSync,+} from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import { appendApplyEvidence } from "../../../src/core/brain/apply-evidence.ts";+import { bootstrapBrain } from "../../../src/core/brain/init.ts";+import { appendLogEvent } from "../../../src/core/brain/log.ts";+import { readLogDay } from "../../../src/core/brain/log-jsonl.ts";+import {+ appendPinnedContext,+ clearPinnedContext,+ readPinnedContext,+ writePinnedContext,+} from "../../../src/core/brain/pinned.ts";+import {+ moveToRetired,+ normalizeDerivedKeys,+ preferencePrivacy,+ writePreference,+} from "../../../src/core/brain/preference.ts";+import { writeSignal } from "../../../src/core/brain/signal.ts";+import { clearOriginChannel, setOriginChannel } from "../../../src/core/origin-channel.ts";+import { parseFrontmatter } from "../../../src/core/vault.ts";+import {+ appendContinuityRecord,+ appendContinuitySourceInvalidation,+} from "../../../src/core/brain/continuity/store.ts";+import { appendDecisionChangeReceipt } from "../../../src/core/brain/decisions/receipts.ts";+import { appendDecisionLedger } from "../../../src/core/brain/permissions/ledger.ts";+import { recordQueryDemand } from "../../../src/core/brain/query-demand.ts";+import { readVaultIdentity } from "../../../src/core/brain/vault-identity.ts";+import { brainPinnedPath } from "../../../src/core/brain/paths.ts";+import {+ LEDGER_ROW_KIND,+ LOG_EVENT_KIND,+ SIGNAL_KIND,+ STORE_DUAL_WRITE_ENV,+ STORE_ROOT_ENV,+} from "../../../src/core/store/constants.ts";+import { readDualWriteStatus } from "../../../src/core/store/dual-write.ts";+import { initStore } from "../../../src/core/store/store-init.ts";+import { appendClaimEvent } from "../../../src/core/brain/truth/store.ts";+import {+ preferenceFields,+ isPrivateFrontmatter,+ isPrivatePageFile,+} from "../../../src/core/store/dual-write-records.ts";+import type { StoreRecord } from "../../../src/core/store/envelope.ts";+import { foldPinned } from "../../../src/core/store/fold-pinned.ts";+import { foldPreferences } from "../../../src/core/store/fold-preferences.ts";+import { readPartition } from "../../../src/core/store/state-digest.ts";+import { deviceStateDirFor, dualWriteStatusPath } from "../../../src/core/store/store-paths.ts";+import { CHMOD_CANNOT_DENY } from "../../helpers/platform.ts";++const ENV_KEYS = [+ STORE_DUAL_WRITE_ENV,+ STORE_ROOT_ENV,+ "O2B_DEVICE_ID",+ "HOME",+ "XDG_STATE_HOME",+ "LOCALAPPDATA",+] as const;++let parent: string;+let vault: string;+let storeRoot: string;+const saved = new Map<string, string | undefined>();++beforeEach(() => {+ for (const key of ENV_KEYS) saved.set(key, process.env[key]);+ parent = mkdtempSync(join(tmpdir(), "osb-dual-write-"));+ vault = join(parent, "vault");+ storeRoot = join(parent, "store");+ mkdirSync(vault, { recursive: true });+ bootstrapBrain(vault);+ process.env["HOME"] = join(parent, "home");+ process.env["XDG_STATE_HOME"] = join(parent, "state");+ process.env["LOCALAPPDATA"] = join(parent, "state");+ process.env[STORE_ROOT_ENV] = storeRoot;+ process.env["O2B_DEVICE_ID"] = "dev-a";+ process.env[STORE_DUAL_WRITE_ENV] = "1";+ // As `o2b store init` would on this machine; writers never create a store.+ initStore({ root: storeRoot });+});++afterEach(() => {+ for (const key of ENV_KEYS) {+ const value = saved.get(key);+ if (value === undefined) delete process.env[key];+ else process.env[key] = value;+ }+ rmSync(parent, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });+});++/** A frontmatter value as the legacy text parser reads it back. */+function asText(value: unknown): unknown {+ return Array.isArray(value) ? value.map((v) => String(v)) : String(value);+}++function storeRecords(partition: "shared" | "private" = "shared"): StoreRecord[] {+ return readPartition(join(storeRoot, partition)).flatMap((shard) => shard.records);+}++function seedPreference(slug: string, extra: Record<string, unknown> = {}): string {+ return writePreference(vault, {+ slug,+ topic: slug,+ principle: `principle ${slug}`,+ created_at: "2026-05-01T00:00:00Z",+ unconfirmed_until: "2026-05-30T00:00:00Z",+ status: "confirmed",+ confirmed_at: "2026-05-02T00:00:00Z",+ evidenced_by: [],+ confidence: "high",+ ...extra,+ }).path;+}++function writeSampleSignal(): { path: string; id: string } {+ return writeSignal(vault, {+ topic: "dual-write",+ signal: "positive",+ agent: "claude",+ principle: "Write both trees while the trial runs",+ created_at: "2026-11-06T10:00:00Z",+ date: "2026-11-06",+ slug: "dual-write",+ scope: "coding",+ raw: "the user said so",+ });+}++function writeSampleLogEvent(): void {+ appendLogEvent(vault, {+ timestamp: "2026-11-06T10:01:00Z",+ eventType: "note",+ agent: "claude",+ body: { text: "a milestone" },+ });+}++describe("flag on: each legacy write lands in both places with matching content", () => {+ test("a signal", () => {+ const { path, id } = writeSampleSignal();+ const record = storeRecords().find((r) => r.kind === SIGNAL_KIND);+ expect(record).toBeDefined();+ const [frontmatter] = parseFrontmatter(path);+ expect(record!.body["id"]).toBe(id);+ expect(record!.body["path"]).toBe(`Brain/inbox/${id}.md`);+ expect(record!.body["frontmatter"]).toEqual(JSON.parse(JSON.stringify(frontmatter)));+ expect(record!.body["raw"]).toBe("the user said so");+ expect(record!.agent).toBe("claude");+ expect(record!.scope).toBe("coding");+ expect(record!.device).toBe("dev-a");+ });++ test("a log event", () => {+ writeSampleLogEvent();+ const legacy = readLogDay(vault, "2026-11-06").entries;+ expect(legacy.length).toBe(1);+ const records = storeRecords().filter((r) => r.kind === LOG_EVENT_KIND);+ expect(records.length).toBe(1);+ expect(records[0]!.body).toEqual({+ timestamp: legacy[0]!.timestamp,+ event_type: legacy[0]!.eventType,+ body: JSON.parse(JSON.stringify(legacy[0]!.body)),+ vault_id: readVaultIdentity(vault)!.vault_id,+ });+ });++ test("pinned context folds to the legacy file through write, append and clear", () => {+ writePinnedContext(vault, "first");+ appendPinnedContext(vault, "second");+ expect(foldPinned(storeRecords("private")).content).toBe(readPinnedContext(vault).content);+ expect(foldPinned(storeRecords("private")).content).toBe("first\n\nsecond");+ clearPinnedContext(vault);+ const fold = foldPinned(storeRecords("private"));+ expect(fold.cleared).toBe(true);+ expect(fold.content ?? "").toBe(readPinnedContext(vault).content);+ expect(fold.rejected).toEqual([]);+ });++ test("a preference write, evidence and a retire fold to the legacy state", () => {+ const path = seedPreference("alpha");+ let fold = foldPreferences(storeRecords());+ const state = fold.preferences.get("pref-alpha")!;+ expect(state.exists).toBe(true);+ // The legacy file is read back as text values with `_`-prefixed derived+ // keys; the store keeps the writer's typed values under the plain names.+ // Every field matches once both are spelled the same way.+ const legacy = preferenceFields(normalizeDerivedKeys(parseFrontmatter(path)[0]));+ expect(Object.keys(state.fields)).toEqual(Object.keys(legacy).toSorted());+ for (const [name, value] of Object.entries(legacy)) {+ expect(asText(state.fields[name])).toEqual(asText(value));+ }+ expect(fold.rejected).toEqual([]);++ appendApplyEvidence(vault, {+ pref_id: "pref-alpha",+ artifact: "[[some-note]]",+ result: "applied",+ agent: "claude",+ });+ fold = foldPreferences(storeRecords());+ expect(fold.preferences.get("pref-alpha")!.counters.applied_count).toBe(1);+ // The evidence is also a log event, exactly as in the legacy log.+ expect(storeRecords().filter((r) => r.kind === LOG_EVENT_KIND).length).toBe(1);++ const retired = moveToRetired(vault, path, "user-rejected", {+ now: new Date("2026-11-06T12:00:00Z"),+ retired_by: "[[operator]]",+ });+ fold = foldPreferences(storeRecords());+ const after = fold.preferences.get("pref-alpha")!;+ expect(after.fields["status"]).toBe("retired");+ expect(after.fields["status"]).toBe(parseFrontmatter(retired.path)[0]["_status"]);+ });++ test("authority follows the origin: an operator command is human, an agent call is agent", () => {+ setOriginChannel("cli");+ try {+ seedPreference("by-operator");+ } finally {+ clearOriginChannel();+ }+ const records = storeRecords().filter((r) => r.kind === "preference-set");+ // The operator decides the fields it wrote; the derived fields the dream+ // pass owns go out beside them at agent authority.+ expect(records.map((r) => r.body["authority"])).toEqual(["human", "agent"]);+ });++ test("an unclaimed or agent process writes agent authority, and the caller can override it", () => {+ seedPreference("by-agent");+ writePreference(+ vault,+ {+ slug: "by-model",+ topic: "by-model",+ principle: "principle by-model",+ created_at: "2026-05-01T00:00:00Z",+ unconfirmed_until: "2026-05-30T00:00:00Z",+ status: "unconfirmed",+ evidenced_by: [],+ },+ { authority: "model" },+ );+ const byId = new Map(+ storeRecords()+ .filter((r) => r.kind === "preference-set")+ .map((r) => [r.body["preference"], r.body["authority"]]),+ );+ expect(byId.get("pref-by-agent")).toBe("agent");+ expect(byId.get("pref-by-model")).toBe("model");+ });++ test("a private preference goes to the private partition", () => {+ seedPreference("secret", { visibility: ["private"] });+ expect(storeRecords("shared").filter((r) => r.kind === "preference-set")).toEqual([]);+ expect(storeRecords("private").filter((r) => r.kind === "preference-set").length).toBe(1);+ });++ test("an informal privacy marker routes a record to the private partition", () => {+ // Hand-edited pages carry these; the legacy writers keep what is on disk.+ for (const marker of [+ { access: "private" },+ { Confidentiality: "Secret" },+ { sensitivity: ["confidential"] },+ ]) {+ expect(isPrivateFrontmatter({ topic: "x", ...marker })).toBe(true);+ expect(preferencePrivacy(vault, { topic: "x", ...marker })()).toBe(true);+ }+ expect(preferencePrivacy(vault, { topic: "y", access: "team" })()).toBe(false);+ });++ test("a page file decides privacy by the same markers, and an unreadable one is private", () => {+ const page = join(vault, "page.md");+ writeFileSync(page, "---\nconfidentiality: secret\n---\nbody\n");+ expect(isPrivatePageFile(page)).toBe(true);+ writeFileSync(page, "---\ntopic: x\n---\nbody\n");+ expect(isPrivatePageFile(page)).toBe(false);+ // A directory where the page should be cannot be read as a page.+ const unreadable = join(vault, "folder.md");+ mkdirSync(unreadable);+ expect(isPrivatePageFile(unreadable)).toBe(true);+ });++ test("evidence on a private preference keeps its log event and ledger rows out of shared", () => {+ seedPreference("hush", { visibility: ["private"] });+ appendApplyEvidence(vault, {+ pref_id: "pref-hush",+ artifact: "[[some-note]]",+ result: "applied",+ agent: "claude",+ });+ const shared = storeRecords("shared").map((r) => JSON.stringify(r));+ expect(shared.filter((line) => line.includes("hush"))).toEqual([]);+ const kinds = storeRecords("private").map((r) => r.kind);+ expect(kinds).toContain(LOG_EVENT_KIND);+ expect(kinds).toContain("preference-evidence");+ });++ test("a partition that arrives after the first write is used without a restart", () => {+ seedPreference("first"); // opens and caches the store with both partitions+ const parked = join(parent, "private-parked");+ renameSync(join(storeRoot, "private"), parked);+ seedPreference("while-away", { visibility: ["private"] });+ expect(readDualWriteStatus().failures).toBe(1);+ renameSync(parked, join(storeRoot, "private")); // the sync delivers it again+ seedPreference("after-sync", { visibility: ["private"] });+ expect(readDualWriteStatus().failures).toBe(1);+ const ids = storeRecords("private").map((r) => r.body["preference"]);+ expect(ids).toContain("pref-after-sync");+ });++ test("a different store created at the same root is used with its own device-local state", () => {+ seedPreference("first"); // opens and caches the first store+ rmSync(storeRoot, { recursive: true, force: true });+ const { storeId } = initStore({ root: storeRoot });+ seedPreference("second");+ expect(storeRecords("shared").map((r) => r.body["preference"])).toEqual(["pref-second"]);+ // The clock and the locks of the write came from the new store's state.+ expect(existsSync(deviceStateDirFor(storeId))).toBe(true);+ });++ test("a per-device ledger row lands under ledgers/<name>", () => {+ const row = appendContinuitySourceInvalidation(vault, {+ createdAt: "2026-11-06T10:00:00Z",+ source: { id: "src-1" },+ reason: "test",+ });+ const shards = readPartition(join(storeRoot, "shared")).filter((s) =>+ s.rel.startsWith("ledgers/continuity/dev-a/"),+ );+ const records = shards.flatMap((s) => s.records);+ expect(records.length).toBe(1);+ expect(records[0]!.kind).toBe(LEDGER_ROW_KIND);+ expect(records[0]!.body["row"]).toEqual(JSON.parse(JSON.stringify(row)));+ });+});++describe("flag off", () => {+ test("writes nothing to the store and leaves no status file", () => {+ delete process.env[STORE_DUAL_WRITE_ENV];+ writeSampleSignal();+ writeSampleLogEvent();+ writePinnedContext(vault, "pinned");+ seedPreference("off");+ expect(storeRecords("shared")).toEqual([]);+ expect(storeRecords("private")).toEqual([]);+ expect(existsSync(dualWriteStatusPath())).toBe(false);+ expect(readLogDay(vault, "2026-11-06").entries.length).toBe(1);+ });+});++const WORKER = join(import.meta.dir, "fixtures", "dual-write-worker.ts");++/** Run `count` log appends in a fresh process; its stderr. */+async function appendInChild(count: number): Promise<string> {+ const child = Bun.spawn([process.execPath, WORKER, vault, String(count)], {+ env: { ...process.env },+ stdout: "ignore",+ stderr: "pipe",+ });+ const [code, stderr] = await Promise.all([child.exited, new Response(child.stderr).text()]);+ expect(code).toBe(0);+ return stderr;+}++const occurrences = (text: string, needle: string): number => text.split(needle).length - 1;++describe("store failures never fail the legacy write", () => {+ test("an unusable store root keeps every legacy write, counts the failures and warns once", () => {+ // A regular file where the store root should be: the store cannot open.+ rmSync(storeRoot, { recursive: true, force: true });+ writeFileSync(storeRoot, "not a directory");+ const stderr = spyOn(process.stderr, "write").mockImplementation(() => true);+ try {+ writeSampleLogEvent();+ writePinnedContext(vault, "kept");+ const pref = seedPreference("kept");+ expect(readLogDay(vault, "2026-11-06").entries.length).toBe(1);+ expect(readPinnedContext(vault).content).toBe("kept");+ expect(existsSync(pref)).toBe(true);+ } finally {+ stderr.mockRestore();+ }+ const status = readDualWriteStatus();+ expect(status.failures).toBe(3);+ expect(status.last_error).not.toBeNull();+ });++ test("a process prints the failure warning exactly once", async () => {+ rmSync(storeRoot, { recursive: true, force: true });+ writeFileSync(storeRoot, "not a directory");+ const stderr = await appendInChild(3);+ expect(occurrences(stderr, "brain store dual write failed")).toBe(1);+ expect(readDualWriteStatus().failures).toBe(3);+ });++ test("a process prints the missing device id warning exactly once", async () => {+ process.env["O2B_DEVICE_ID"] = "";+ const stderr = await appendInChild(2);+ expect(occurrences(stderr, "no device id")).toBe(1);+ expect(readDualWriteStatus().skipped_no_device).toBe(2);+ });++ test("a private record on a machine without the private partition is refused, the legacy write kept", () => {+ seedPreference("open"); // opens the store with both partitions+ rmSync(join(storeRoot, "private"), { recursive: true, force: true });+ const path = seedPreference("hidden", { visibility: ["private"] });+ expect(existsSync(path)).toBe(true);+ expect(existsSync(join(storeRoot, "private"))).toBe(false);+ expect(readDualWriteStatus().failures).toBe(1);+ });++ test("an empty device id skips the dual writes and counts the skip", () => {+ process.env["O2B_DEVICE_ID"] = "";+ const stderr = spyOn(process.stderr, "write").mockImplementation(() => true);+ try {+ writeSampleLogEvent();+ writeSampleLogEvent();+ } finally {+ stderr.mockRestore();+ }+ expect(readLogDay(vault, "2026-11-06").entries.length).toBe(2);+ expect(storeRecords("shared")).toEqual([]);+ expect(readDualWriteStatus().skipped_no_device).toBe(2);+ });+});++describe("a torn identity file under a running process", () => {+ test("the write is refused and counted, the legacy write kept, and the next one lands", () => {+ seedPreference("first"); // opens and caches the store+ const identityFile = join(storeRoot, "shared", "store.json");+ const intact = readFileSync(identityFile, "utf8");+ writeFileSync(identityFile, intact.slice(0, 5)); // a sync tool mid-copy+ const path = seedPreference("during");+ expect(existsSync(path)).toBe(true);+ expect(readDualWriteStatus().failures).toBe(1);+ expect(readDualWriteStatus().last_error).toContain("store.json");+ writeFileSync(identityFile, intact);+ seedPreference("after");+ const ids = storeRecords("shared").map((r) => r.body["preference"]);+ expect(ids).toEqual(["pref-first", "pref-after"]);+ });+});++describe("no store yet", () => {+ test("dual writes never create a store: they are skipped and counted, the legacy writes kept", () => {+ rmSync(storeRoot, { recursive: true, force: true });+ const stderr = spyOn(process.stderr, "write").mockImplementation(() => true);+ try {+ writeSampleLogEvent();+ const pref = seedPreference("no-store");+ expect(existsSync(pref)).toBe(true);+ } finally {+ stderr.mockRestore();+ }+ expect(readLogDay(vault, "2026-11-06").entries.length).toBe(1);+ expect(existsSync(storeRoot)).toBe(false);+ const status = readDualWriteStatus();+ expect(status.skipped_no_store).toBe(2);+ expect(status.failures).toBe(0);+ });++ test("a process prints the no-store warning exactly once, naming the init command", async () => {+ rmSync(storeRoot, { recursive: true, force: true });+ const stderr = await appendInChild(3);+ expect(occurrences(stderr, "o2b store init")).toBe(1);+ expect(readDualWriteStatus().skipped_no_store).toBe(3);+ });++ test("once the store is created, the next write lands in it", () => {+ rmSync(storeRoot, { recursive: true, force: true });+ const stderr = spyOn(process.stderr, "write").mockImplementation(() => true);+ try {+ seedPreference("before-init");+ } finally {+ stderr.mockRestore();+ }+ initStore({ root: storeRoot });+ seedPreference("after-init");+ const ids = storeRecords("shared").map((r) => r.body["preference"]);+ expect(ids).toEqual(["pref-after-init"]);+ });+});++function appendSampleClaim(): void {+ appendClaimEvent(vault, {+ ts: "2026-06-01T10:00:00Z",+ agent: "claude",+ entity: "Alice Mason",+ aspect: "employer",+ value: "Acme",+ source: "[[Brain/notes/standup.md]]",+ });+}++function claimRows(partition: "shared" | "private"): StoreRecord[] {+ return storeRecords(partition).filter((r) => r.kind === LEDGER_ROW_KIND);+}++describe("truth claims", () => {+ test("go to private when this machine holds the private partition", () => {+ appendSampleClaim();+ expect(claimRows("private").length).toBe(1);+ expect(claimRows("shared")).toEqual([]);+ });++ test("from an open page go to shared on a machine without the private partition", () => {+ rmSync(join(storeRoot, "private"), { recursive: true, force: true });+ mkdirSync(join(vault, "Brain", "notes"), { recursive: true });+ writeFileSync(join(vault, "Brain", "notes", "standup.md"), "# Standup\n");+ appendSampleClaim();+ expect(claimRows("shared").length).toBe(1);+ expect(readDualWriteStatus().failures).toBe(0);+ });+});++function ledgerRows(partition: "shared" | "private", ledger: string): StoreRecord[] {+ return readPartition(join(storeRoot, partition))+ .filter((s) => s.rel.startsWith(`ledgers/${ledger}/`))+ .flatMap((s) => s.records);+}++function dropPrivatePartition(): void {+ rmSync(join(storeRoot, "private"), { recursive: true, force: true });+}++function appendTurn(text: string): void {+ appendContinuityRecord(vault, {+ kind: "session_turn",+ createdAt: "2026-11-06T10:00:00.000Z",+ payload: { text },+ });+}++function appendReceipt(subject: string): void {+ appendDecisionChangeReceipt(vault, {+ subject,+ before: "a",+ after: "b",+ actor: "claude",+ reasonCode: "test",+ ts: "2026-11-06T10:00:00Z",+ });+}++function receiptSubjects(partition: "shared" | "private"): unknown[] {+ return ledgerRows(partition, "decision-receipts").map(+ (r) => (r.body["row"] as Record<string, unknown>)["subject"],+ );+}++describe("privacy of ledger rows and pinned context", () => {+ test("a continuity record flagged private lands in private, an open one in shared", () => {+ appendTurn("open turn");+ appendTurn("before <private>a secret</private> after");+ expect(ledgerRows("shared", "continuity").map((r) => r.body["row"])).toEqual([+ expect.objectContaining({ private: false }),+ ]);+ expect(ledgerRows("private", "continuity").map((r) => r.body["row"])).toEqual([+ expect.objectContaining({ private: true }),+ ]);+ });++ test("a private continuity record is refused when this machine does not hold private", () => {+ dropPrivatePartition();+ appendTurn("before <private>a secret</private> after");+ expect(ledgerRows("shared", "continuity")).toEqual([]);+ expect(readDualWriteStatus().failures).toBe(1);+ });++ test("a decision receipt about a private preference stays out of shared", () => {+ seedPreference("hush", { visibility: ["private"] });+ seedPreference("open");+ appendReceipt("pref-hush");+ appendReceipt("pref-open");+ expect(receiptSubjects("shared")).toEqual(["pref-open"]);+ expect(receiptSubjects("private")).toEqual(["pref-hush"]);+ });++ test("search terms go to private when this machine holds it, else to shared", () => {+ recordQueryDemand(vault, { query: "salary negotiation", resultCount: 1 });+ expect(ledgerRows("private", "query-demand").length).toBe(1);+ expect(ledgerRows("shared", "query-demand")).toEqual([]);+ dropPrivatePartition();+ recordQueryDemand(vault, { query: "salary negotiation", resultCount: 1 });+ expect(ledgerRows("shared", "query-demand").length).toBe(1);+ });++ test("permission decisions go to private when this machine holds it, else to shared", () => {+ const row = {+ ts: "2026-11-06T12:00:00Z",+ actor: "agent",+ via: "mcp",+ action: "write" as const,+ target: "Notes/salary.md",+ verdict: "allow",+ source: "default",+ reason: "test",+ };+ appendDecisionLedger(vault, row);+ expect(ledgerRows("private", "permissions").length).toBe(1);+ expect(ledgerRows("shared", "permissions")).toEqual([]);+ dropPrivatePartition();+ appendDecisionLedger(vault, row);+ expect(ledgerRows("shared", "permissions").length).toBe(1);+ });++ test("pinned text with a private region or a link to a private page is private only", () => {+ seedPreference("hush", { visibility: ["private"] });+ dropPrivatePartition();+ writePinnedContext(vault, "plain facts");+ writePinnedContext(vault, "facts <private>secret</private>");+ writePinnedContext(vault, "see [[pref-hush]]");+ const contents = storeRecords("shared").map((r) => r.body["content"]);+ expect(contents).toEqual(["plain facts"]);+ expect(readDualWriteStatus().failures).toBe(2);+ });++ test("a pinned clear goes where a set of the text it clears goes", () => {+ writePinnedContext(vault, "facts <private>secret</private>");+ clearPinnedContext(vault);+ expect(storeRecords("private").map((r) => r.kind)).toEqual(["pinned-set", "pinned-clear"]);++ dropPrivatePartition();+ writePinnedContext(vault, "plain facts");+ clearPinnedContext(vault);+ expect(storeRecords("shared").map((r) => r.kind)).toEqual(["pinned-set", "pinned-clear"]);+ writePinnedContext(vault, "facts <private>secret</private>");+ clearPinnedContext(vault);+ expect(storeRecords("shared").map((r) => r.kind)).toEqual(["pinned-set", "pinned-clear"]);+ expect(readDualWriteStatus().failures).toBe(2);+ });++ // POSIX modes only, and root reads a 0000 file anyway.+ test.skipIf(CHMOD_CANNOT_DENY)(+ "a pinned clear whose old text cannot be read is judged private",+ () => {+ dropPrivatePartition();+ writePinnedContext(vault, "plain facts");+ chmodSync(brainPinnedPath(vault), 0o000);+ clearPinnedContext(vault);+ expect(readFileSync(brainPinnedPath(vault), "utf8")).toBe("");+ expect(storeRecords("shared").map((r) => r.kind)).toEqual(["pinned-set"]);+ expect(readDualWriteStatus().failures).toBe(1);+ },+ );+});++describe("vault identity", () => {+ test("every dual-written record carries the writing vault's id", () => {+ const id = readVaultIdentity(vault)!.vault_id;+ writeSampleSignal();+ writeSampleLogEvent();+ writePinnedContext(vault, "facts");+ const all = [...storeRecords("shared"), ...storeRecords("private")];+ expect(all.length).toBeGreaterThan(2);+ for (const record of all) expect(record.body["vault_id"]).toBe(id);+ });+});diff --git a/tests/core/store/envelope.test.ts b/tests/core/store/envelope.test.tsnew file mode 100644index 00000000..a3e04df2--- /dev/null+++ b/tests/core/store/envelope.test.ts@@ -0,0 +1,154 @@+import { describe, expect, test } from "bun:test";++import {+ BLOB_REF_KEY,+ ENVELOPE_FIELDS,+ STORE_FORMAT_VERSION,+} from "../../../src/core/store/constants.ts";+import {+ bodyChecksum,+ buildRecord,+ compareRecords,+ EnvelopeError,+ verifyEnvelope,+} from "../../../src/core/store/envelope.ts";+import { isUlid, newUlid, ulidTime } from "../../../src/core/store/ulid.ts";++describe("ulid", () => {+ test("is 26 Crockford base32 characters carrying the time", () => {+ const id = newUlid(1_762_400_000_123);+ expect(isUlid(id)).toBe(true);+ expect(ulidTime(id)).toBe(1_762_400_000_123);+ });++ test("ids issued in one millisecond are unique and strictly increasing", () => {+ const ids = Array.from({ length: 500 }, () => newUlid(1_762_400_000_000));+ expect(new Set(ids).size).toBe(ids.length);+ expect(ids.toSorted()).toEqual(ids);+ });++ test("rejects malformed ids", () => {+ for (const bad of [+ "",+ "01ARZ3NDEKTSV4RRFFQ69G5FA",+ "01ARZ3NDEKTSV4RRFFQ69G5FAVU",+ "01arz3ndektsv4rrffq69g5fav",+ "01ARZ3NDEKTSV4RRFFQ69G5FAI",+ ]) {+ expect(isUlid(bad)).toBe(false);+ }+ });+});++describe("body checksum", () => {+ test("ignores key order, so a re-serialised body still verifies", () => {+ expect(bodyChecksum({ a: 1, b: { c: [1, 2], d: "x" } })).toBe(+ bodyChecksum({ b: { d: "x", c: [1, 2] }, a: 1 }),+ );+ });++ test("is a lowercase sha256 hex", () => {+ expect(bodyChecksum({})).toMatch(/^[0-9a-f]{64}$/);+ });+});++describe("record envelope", () => {+ const base = {+ hlc: { physical: 1_762_400_000_000, counter: 2 },+ device: "dev-a",+ agent: "claude-devbox-agent",+ kind: "feedback",+ scope: "writing",+ topic: null,+ body: { principle: "No exclamation marks in docs", when: new Date(0) },+ };++ test("carries every envelope field in the documented order, and verifies", () => {+ const record = buildRecord(base);+ expect(Object.keys(record)).toEqual([...ENVELOPE_FIELDS]);+ expect(record.v).toBe(STORE_FORMAT_VERSION);+ expect(record.hlc).toBe("1762400000000.2");+ expect(isUlid(record.id)).toBe(true);+ const reparsed = JSON.parse(JSON.stringify(record)) as unknown;+ expect(verifyEnvelope(reparsed)).toEqual({ ok: true, record });+ });++ test("stores the JSON form of the body, so values like dates verify after a round trip", () => {+ const record = buildRecord(base);+ expect(record.body).toEqual({+ principle: "No exclamation marks in docs",+ when: "1970-01-01T00:00:00.000Z",+ });+ });++ test("a tampered body fails verification", () => {+ const record = JSON.parse(JSON.stringify(buildRecord(base))) as Record<string, unknown>;+ (record["body"] as Record<string, unknown>)["principle"] = "changed";+ expect(verifyEnvelope(record)).toMatchObject({+ ok: false,+ reason: expect.stringContaining("checksum"),+ });+ });++ test("a missing field fails verification", () => {+ const record = JSON.parse(JSON.stringify(buildRecord(base))) as Record<string, unknown>;+ delete record["agent"];+ expect(verifyEnvelope(record)).toMatchObject({ ok: false });+ });++ // Folds and digests must agree across platforms, so a Windows reader+ // accepts what a POSIX peer named `nul` wrote (this runs in the Windows job).+ test("a record from a device named like a Windows device verifies on every platform", () => {+ const record = buildRecord({ ...base, device: "nul" });+ const reparsed = JSON.parse(JSON.stringify(record)) as unknown;+ expect(verifyEnvelope(reparsed)).toEqual({ ok: true, record });+ });++ test("an unknown version is reported apart from corruption", () => {+ const record = JSON.parse(JSON.stringify(buildRecord(base))) as Record<string, unknown>;+ record["v"] = STORE_FORMAT_VERSION + 1;+ expect(verifyEnvelope(record)).toMatchObject({+ ok: false,+ unknownVersion: STORE_FORMAT_VERSION + 1,+ });+ });++ test("verification refuses labels and blob references that building would never write", () => {+ const line = (over: Record<string, unknown>): Record<string, unknown> => ({+ ...(JSON.parse(JSON.stringify(buildRecord(base))) as Record<string, unknown>),+ ...over,+ });+ expect(verifyEnvelope(line({ agent: "a".repeat(201) }))).toMatchObject({ ok: false });+ expect(verifyEnvelope(line({ agent: "two\nlines" }))).toMatchObject({ ok: false });+ expect(verifyEnvelope(line({ scope: "" }))).toMatchObject({ ok: false });+ expect(verifyEnvelope(line({ scope: "s".repeat(201) }))).toMatchObject({ ok: false });+ expect(verifyEnvelope(line({ scope: null }))).toMatchObject({ ok: true });+ const record = buildRecord(base);+ for (const bytes of [-1, 1.5]) {+ const spilled = { ...record, body: { [BLOB_REF_KEY]: record.sum, bytes } };+ expect(verifyEnvelope(JSON.parse(JSON.stringify(spilled)))).toMatchObject({ ok: false });+ }+ const valid = { ...record, body: { [BLOB_REF_KEY]: record.sum, bytes: 10 } };+ expect(verifyEnvelope(JSON.parse(JSON.stringify(valid)))).toMatchObject({ ok: true });+ });++ test("refuses invalid input when building", () => {+ expect(() => buildRecord({ ...base, device: "" })).toThrow(EnvelopeError);+ expect(() => buildRecord({ ...base, device: "sync-conflict-x" })).toThrow(EnvelopeError);+ expect(() => buildRecord({ ...base, kind: "Not A Kind" })).toThrow(EnvelopeError);+ expect(() => buildRecord({ ...base, agent: " " })).toThrow(EnvelopeError);+ expect(() => buildRecord({ ...base, topic: "not-a-ulid" })).toThrow(EnvelopeError);+ expect(() => buildRecord({ ...base, body: { [BLOB_REF_KEY]: "x" } })).toThrow(EnvelopeError);+ });++ test("fold order is hlc, then device, then id", () => {+ const a = buildRecord({ ...base, hlc: { physical: 10, counter: 0 }, device: "dev-b" });+ const b = buildRecord({ ...base, hlc: { physical: 10, counter: 0 }, device: "dev-a" });+ const c = buildRecord({ ...base, hlc: { physical: 9, counter: 5 }, device: "dev-z" });+ expect([a, b, c].toSorted(compareRecords).map((r) => r.device)).toEqual([+ "dev-z",+ "dev-a",+ "dev-b",+ ]);+ });+});diff --git a/tests/core/store/fixtures/append-worker.ts b/tests/core/store/fixtures/append-worker.tsnew file mode 100644index 00000000..ee6e7adc--- /dev/null+++ b/tests/core/store/fixtures/append-worker.ts@@ -0,0 +1,59 @@+/**+ * Child process for the concurrent-append test: opens the store as one+ * device and appends `count` records, every third one large enough to+ * spill its body into a blob (all workers spill the SAME large body, so+ * they also race for one blob name).+ *+ * Every worker writes `<ready dir>/<worker>` once it is up and then waits+ * for the go file the parent writes when all are ready, so they append at+ * the same time rather than one after another as each process happens to+ * start, however slowly the runner starts them. A go file that never+ * comes ends the worker after 30 s instead of leaving it behind.+ *+ * argv: <root> <device> <stateHome> <worker> <count> <ready dir> <go file>+ */+import { existsSync, writeFileSync } from "node:fs";+import { join } from "node:path";++import { appendRecord } from "../../../../src/core/store/appender.ts";+import { STORE_LINE_CAP_BYTES } from "../../../../src/core/store/constants.ts";+import { openStore } from "../../../../src/core/store/store-open.ts";++const [root, device, stateHome, worker, countText, readyDir, goFile] = process.argv.slice(2) as [+ string,+ string,+ string,+ string,+ string,+ string,+ string,+];+const store = openStore({+ root,+ device,+ dirs: {+ platform: process.platform,+ home: stateHome,+ env: { XDG_STATE_HOME: stateHome, LOCALAPPDATA: stateHome },+ },+});+// Above the line cap, so every third record spills into a blob.+const large = "x".repeat(STORE_LINE_CAP_BYTES * 2);+writeFileSync(join(readyDir, worker), "ready\n");+const deadline = Date.now() + 30_000;+while (!existsSync(goFile)) {+ if (Date.now() > deadline) {+ process.stderr.write("the go file never came\n");+ process.exit(2);+ }+ Bun.sleepSync(1);+}+for (let i = 0; i < Number(countText); i++) {+ appendRecord(store, {+ partition: "shared",+ stream: "events",+ kind: "feedback",+ agent: `worker-${worker}`,+ body: i % 3 === 0 ? { large } : { worker, i },+ });+}diff --git a/tests/core/store/fixtures/dual-write-worker.ts b/tests/core/store/fixtures/dual-write-worker.tsnew file mode 100644index 00000000..ff3014b8--- /dev/null+++ b/tests/core/store/fixtures/dual-write-worker.ts@@ -0,0 +1,18 @@+/**+ * Child process for the dual-write warning tests: a fresh process, so the+ * once-per-process warning state starts clean. Appends `count` log events+ * to the vault with the environment the parent test prepared.+ *+ * argv: <vault> <count>+ */+import { appendLogEvent } from "../../../../src/core/brain/log.ts";++const [vault, countText] = process.argv.slice(2) as [string, string];+for (let i = 0; i < Number(countText); i++) {+ appendLogEvent(vault, {+ timestamp: "2026-11-06T10:01:00Z",+ eventType: "note",+ agent: "claude",+ body: { text: `event ${i}` },+ });+}diff --git a/tests/core/store/fixtures/fold-records.ts b/tests/core/store/fixtures/fold-records.tsnew file mode 100644index 00000000..a582c7d1--- /dev/null+++ b/tests/core/store/fixtures/fold-records.ts@@ -0,0 +1,81 @@+/**+ * Test helper: verified store records built in memory, and a seeded+ * random generator so property tests are reproducible from their seed.+ */+import type { Authority } from "../../../../src/core/store/constants.ts";+import {+ buildRecord,+ type RecordBody,+ type StoreRecord,+} from "../../../../src/core/store/envelope.ts";++const ALPHABET = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";++/** mulberry32: a small seeded generator returning floats in [0, 1). */+export function seededRandom(seed: number): () => number {+ let a = seed >>> 0;+ return () => {+ a = (a + 0x6d2b79f5) >>> 0;+ let t = a;+ t = Math.imul(t ^ (t >>> 15), t | 1);+ t ^= t + Math.imul(t ^ (t >>> 7), t | 61);+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;+ };+}++export const pick = <T>(rng: () => number, items: ReadonlyArray<T>): T =>+ items[Math.floor(rng() * items.length)]!;++/** Fisher-Yates shuffle into a new array. */+export function shuffled<T>(rng: () => number, items: ReadonlyArray<T>): T[] {+ const out = [...items];+ for (let i = out.length - 1; i > 0; i--) {+ const j = Math.floor(rng() * (i + 1));+ [out[i], out[j]] = [out[j]!, out[i]!];+ }+ return out;+}++/** A valid ULID for `ms` whose random part comes from `rng`. */+export function seededUlid(rng: () => number, ms: number): string {+ let time = "";+ let rest = ms;+ for (let i = 0; i < 10; i++) {+ time = ALPHABET[rest % 32]! + time;+ rest = Math.floor(rest / 32);+ }+ let random = "";+ for (let i = 0; i < 16; i++) random += pick(rng, [...ALPHABET]);+ return time + random;+}++const fallbackRng = seededRandom(7);++export interface RecSpec {+ readonly device?: string;+ readonly physical: number;+ readonly counter?: number;+ readonly kind: string;+ readonly body: RecordBody;+ readonly agent?: string;+ readonly id?: string;+ readonly rng?: () => number;+}++/** Build one verified record. */+export function rec(spec: RecSpec): StoreRecord {+ return buildRecord({+ hlc: { physical: spec.physical, counter: spec.counter ?? 0 },+ device: spec.device ?? "dev-a",+ agent: spec.agent ?? "agent-1",+ kind: spec.kind,+ body: spec.body,+ id: spec.id ?? seededUlid(spec.rng ?? fallbackRng, spec.physical),+ });+}++/** Body of a mutable-entity record with its authority. */+export const authored = (authority: Authority, body: RecordBody): RecordBody => ({+ authority,+ ...body,+});diff --git a/tests/core/store/fixtures/temp-store.ts b/tests/core/store/fixtures/temp-store.tsnew file mode 100644index 00000000..8482d84e--- /dev/null+++ b/tests/core/store/fixtures/temp-store.ts@@ -0,0 +1,57 @@+/**+ * Test helper: one named temp parent per test holding a store root and a+ * device-local state base per simulated machine, removed in teardown.+ */+import { mkdtempSync, rmSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import type { PlatformDirsEnv } from "../../../../src/core/platform-dirs.ts";+import { initStore } from "../../../../src/core/store/store-init.ts";+import {+ inspectStore,+ openStore,+ type StoreHandle,+} from "../../../../src/core/store/store-open.ts";++/**+ * Create the store at `root` with both partitions unless one is there,+ * as `o2b store init` would on the first machine. Writers never create a+ * store, so every fixture that writes needs one first.+ */+export function ensureStore(root: string): void {+ if (inspectStore(root) === null) initStore({ root });+}++export interface TempStore {+ readonly parent: string;+ readonly root: string;+ /** Platform source whose state base is private to `machine`. */+ dirs(machine: string): PlatformDirsEnv;+ /** Open the store as `device` (created first when absent), with that device's own device-local state. */+ open(device: string): StoreHandle;+ cleanup(): void;+}++export function makeTempStore(prefix = "osb-store-"): TempStore {+ const parent = mkdtempSync(join(tmpdir(), prefix));+ const root = join(parent, "store");+ const dirs = (machine: string): PlatformDirsEnv => ({+ platform: process.platform,+ home: join(parent, "home", machine),+ env: {+ XDG_STATE_HOME: join(parent, "state", machine),+ LOCALAPPDATA: join(parent, "state", machine),+ },+ });+ return {+ parent,+ root,+ dirs,+ open: (device) => {+ ensureStore(root);+ return openStore({ root, device, dirs: dirs(device) });+ },+ cleanup: () => rmSync(parent, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 }),+ };+}diff --git a/tests/core/store/fold-property.test.ts b/tests/core/store/fold-property.test.tsnew file mode 100644index 00000000..b669eae7--- /dev/null+++ b/tests/core/store/fold-property.test.ts@@ -0,0 +1,129 @@+/**+ * Property tests of the folds (task 1.6): for random record sets from+ * several devices, every delivery a file-sync tool can produce (shards in+ * any order, lines delivered twice, partial shards completed later) folds+ * to exactly the state of the complete set. Each seed is reproducible.+ */+import { describe, expect, test } from "bun:test";++import type { StoreRecord } from "../../../src/core/store/envelope.ts";+import { foldPinned, pinnedFingerprint } from "../../../src/core/store/fold-pinned.ts";+import {+ foldPreferences,+ preferencesFingerprint,+} from "../../../src/core/store/fold-preferences.ts";+import { foldSettings, settingsFingerprint } from "../../../src/core/store/fold-settings.ts";+import { authored, pick, rec, seededRandom, shuffled } from "./fixtures/fold-records.ts";++const T = Date.UTC(2026, 10, 6, 12, 0, 0);+const DEVICES = ["dev-a", "dev-b", "dev-c"];+const AUTHORITIES = ["human", "agent", "agent", "model"] as const;+const PREFS = ["p1", "p2", "p3"];+const FIELDS = ["principle", "status", "scope", "applied_count"];+const SETTINGS: ReadonlyArray<readonly [string, ReadonlyArray<unknown>]> = [+ ["topics.new_min_records", [1, 3, 8, 0]],+ ["view.language", ["en", "ru", "not a tag"]],+ ["view.writer", ["dev-a", "dev-b"]],+ ["future.knob", [true, { n: 1 }]],+];++function randomBody(rng: () => number): { kind: string; body: Record<string, unknown> } {+ const authority = rng() < 0.05 ? undefined : pick(rng, AUTHORITIES);+ const withAuthority = (body: Record<string, unknown>) =>+ authority === undefined ? body : authored(authority, body);+ const roll = rng();+ if (roll < 0.25) {+ const fields: Record<string, unknown> = {};+ for (const field of FIELDS)+ if (rng() < 0.5) fields[field] = `${field}-${Math.floor(rng() * 4)}`;+ return {+ kind: "preference-set",+ body: withAuthority({ preference: pick(rng, PREFS), fields }),+ };+ }+ if (roll < 0.32)+ return { kind: "preference-remove", body: withAuthority({ preference: pick(rng, PREFS) }) };+ if (roll < 0.5) {+ return {+ kind: "preference-evidence",+ body: {+ preference: pick(rng, PREFS),+ result: pick(rng, ["applied", "violated", "outdated"]),+ },+ };+ }+ if (roll < 0.62)+ return { kind: "pinned-set", body: withAuthority({ content: `pin-${Math.floor(rng() * 5)}` }) };+ if (roll < 0.67) return { kind: "pinned-clear", body: withAuthority({}) };+ const [key, values] = pick(rng, SETTINGS);+ if (roll < 0.92)+ return { kind: "setting-set", body: withAuthority({ key, value: pick(rng, values) }) };+ return { kind: "setting-unset", body: withAuthority({ key }) };+}++/** One shard per device, records in the order the device wrote them. */+function randomShards(rng: () => number): StoreRecord[][] {+ return DEVICES.map((device) => {+ const records: StoreRecord[] = [];+ let physical = T;+ let counter = 0;+ const count = 10 + Math.floor(rng() * 30);+ for (let i = 0; i < count; i++) {+ // Small steps so devices often share a millisecond and stamps tie.+ const step = Math.floor(rng() * 3);+ if (step === 0) counter += 1;+ else {+ physical += step;+ counter = 0;+ }+ records.push(rec({ device, physical, counter, rng, ...randomBody(rng) }));+ }+ return records;+ });+}++function state(records: ReadonlyArray<StoreRecord>): unknown {+ const preferences = foldPreferences(records);+ const pinned = foldPinned(records);+ return {+ preferences: preferencesFingerprint(preferences),+ preferenceHistory: [...preferences.preferences.values()].map((p) => p.history.map((r) => r.id)),+ pinned: pinnedFingerprint(pinned),+ pinnedHistory: pinned.history.map((e) => e.record.id),+ settings: settingsFingerprint(foldSettings(records)),+ };+}++const SEEDS = Array.from({ length: 60 }, (_, i) => i + 1);++describe("fold properties", () => {+ test.each(SEEDS)("seed %i: shards delivered in any device order fold the same", (seed) => {+ const rng = seededRandom(seed);+ const shards = randomShards(rng);+ const expected = state(shards.flat());+ for (let round = 0; round < 3; round++) {+ expect(state(shuffled(rng, shards).flat())).toEqual(expected);+ }+ });++ test.each(SEEDS)("seed %i: duplicated lines in a shuffled delivery are applied once", (seed) => {+ const rng = seededRandom(1000 + seed);+ const all = randomShards(rng).flat();+ const expected = state(all);+ const duplicates = all.filter(() => rng() < 0.3);+ expect(state(shuffled(rng, [...all, ...duplicates, ...duplicates]))).toEqual(expected);+ });++ test.each(SEEDS)(+ "seed %i: a prefix read again beside the complete shards folds to the full state",+ (seed) => {+ const rng = seededRandom(2000 + seed);+ const shards = randomShards(rng);+ const expected = state(shards.flat());+ // A prefix of each shard (what a sync still in flight delivered) read+ // again together with the complete shards, in any order.+ const partial = shards.map((shard) => shard.slice(0, Math.floor(rng() * shard.length)));+ expect(state([...partial.flat(), ...shuffled(rng, shards).flat()])).toEqual(expected);+ },+ );+});diff --git a/tests/core/store/fold.test.ts b/tests/core/store/fold.test.tsnew file mode 100644index 00000000..f4e66531--- /dev/null+++ b/tests/core/store/fold.test.ts@@ -0,0 +1,435 @@+/**+ * The fold engine and the concrete folds: duplicate delivery, fold order,+ * authority precedence, tombstones, kept history, derived counters and+ * the spec scenarios of the brain store.+ */+import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import { cpSync, mkdirSync } from "node:fs";+import { join } from "node:path";++import { appendRecord } from "../../../src/core/store/appender.ts";+import { prepareRecords } from "../../../src/core/store/fold.ts";+import { foldPinned } from "../../../src/core/store/fold-pinned.ts";+import {+ foldPreferences,+ preferencesFingerprint,+} from "../../../src/core/store/fold-preferences.ts";+import { canonicalJson } from "../../../src/core/integrity/digest.ts";+import { foldSettings, settingValue } from "../../../src/core/store/fold-settings.ts";+import { readShard } from "../../../src/core/store/reader.ts";+import { listShards } from "../../../src/core/store/shard-list.ts";+import { partitionDir } from "../../../src/core/store/store-paths.ts";+import { authored, rec } from "./fixtures/fold-records.ts";+import { makeTempStore, type TempStore } from "./fixtures/temp-store.ts";++const T = Date.UTC(2026, 10, 6, 12, 0, 0);++const prefSet = (+ device: string,+ physical: number,+ authority: "human" | "agent" | "model",+ fields: Record<string, unknown>,+ preference = "p1",+) =>+ rec({+ device,+ physical,+ kind: "preference-set",+ body: authored(authority, { preference, fields }),+ });++const fingerprint = (fold: ReturnType<typeof foldPreferences>): string =>+ canonicalJson(preferencesFingerprint(fold));++/** The folded topic-creation threshold of the settings shards in a partition. */+const threshold = (partitionRoot: string): unknown =>+ settingValue(+ foldSettings(+ listShards(partitionRoot, { stream: "settings" }).flatMap((shard) =>+ readShard(shard.path).records.map((r) => r.record),+ ),+ ),+ "topics.new_min_records",+ );++describe("prepareRecords", () => {+ test("applies a record delivered twice once, in fold order", () => {+ const a = rec({ device: "dev-b", physical: T + 2, kind: "x", body: {} });+ const b = rec({ device: "dev-a", physical: T + 2, kind: "x", body: {} });+ const c = rec({ device: "dev-c", physical: T + 1, kind: "x", body: {} });+ const prepared = prepareRecords([a, b, a, c, b]);+ expect(prepared.records.map((r) => r.id)).toEqual([c.id, b.id, a.id]);+ expect(prepared.duplicates).toBe(2);+ expect(prepared.conflicts).toEqual([]);+ });++ test("keeps the same version of a conflicting id in any delivery order", () => {+ const first = rec({ physical: T, kind: "x", body: { n: 1 } });+ const second = { ...rec({ physical: T, kind: "x", body: { n: 2 } }), id: first.id };+ const one = prepareRecords([first, second]);+ const two = prepareRecords([second, first]);+ expect(one.records).toEqual(two.records);+ expect(one.conflicts).toEqual([{ id: first.id, versions: 2 }]);+ });++ test("a delivery that conflicts is a conflict, not also a duplicate", () => {+ const original = rec({ device: "dev-a", physical: T, kind: "x", body: { v: 1 } });+ const altered = { ...original, body: { v: 2 } };+ const prepared = prepareRecords([original, altered, original, altered]);+ expect(prepared.conflicts).toEqual([{ id: original.id, versions: 2 }]);+ // The third and fourth deliveries repeat a version already seen.+ expect(prepared.duplicates).toBe(2);+ expect(prepareRecords([original, altered]).duplicates).toBe(0);+ });++ test("holds out a record whose body is a pending blob", () => {+ const inline = rec({ physical: T, kind: "x", body: {} });+ const pending = {+ ...inline,+ id: rec({ physical: T + 1, kind: "x", body: {} }).id,+ body: { $blob: inline.sum, bytes: 2 },+ };+ const prepared = prepareRecords([inline, pending]);+ expect(prepared.records.map((r) => r.id)).toEqual([inline.id]);+ expect(prepared.pending.map((r) => r.id)).toEqual([pending.id]);+ });+});++describe("authority precedence", () => {+ test("a human record beats a later agent record, which beats a later model record", () => {+ const human = prefSet("dev-a", T, "human", { principle: "human" });+ const agent = prefSet("dev-b", T + 10, "agent", { principle: "agent", scope: "coding" });+ const model = prefSet("dev-c", T + 20, "model", { principle: "model", scope: "model" });+ const state = foldPreferences([model, agent, human]).preferences.get("p1")!;+ expect(state.fields).toEqual({ principle: "human", scope: "coding" });+ expect(state.fieldWinners).toEqual({ principle: human.id, scope: agent.id });+ });++ test("within one authority the later clock wins, the device breaking a clock tie", () => {+ const early = prefSet("dev-z", T, "agent", { principle: "early" });+ const tieLow = prefSet("dev-a", T + 5, "agent", { principle: "tie-a" });+ const tieHigh = prefSet("dev-b", T + 5, "agent", { principle: "tie-b" });+ for (const order of [+ [early, tieLow, tieHigh],+ [tieHigh, early, tieLow],+ ]) {+ expect(foldPreferences(order).preferences.get("p1")!.fields["principle"]).toBe("tie-b");+ }+ });++ test("a record without an authority is rejected, never guessed from the agent name", () => {+ const bad = rec({+ physical: T,+ agent: "human",+ kind: "preference-set",+ body: { preference: "p1", fields: { principle: "x" } },+ });+ const fold = foldPreferences([bad]);+ expect(fold.preferences.size).toBe(0);+ expect(fold.rejected).toEqual([+ { id: bad.id, kind: "preference-set", reason: "missing or invalid authority" },+ ]);+ });+});++describe("preference fold", () => {+ test("a human retire beats later agent evidence and a later agent re-confirm (spec scenario)", () => {+ const created = prefSet("dev-a", T, "agent", { principle: "use tabs", status: "confirmed" });+ const retire = prefSet("dev-a", T + 100, "human", {+ status: "retired",+ retired_reason: "user-rejected",+ });+ const evidence = rec({+ device: "dev-b",+ physical: T + 200,+ kind: "preference-evidence",+ body: { preference: "p1", result: "applied", artifact: "[[x]]" },+ });+ const reconfirm = prefSet("dev-b", T + 300, "agent", { status: "confirmed" });+ const state = foldPreferences([reconfirm, evidence, retire, created]).preferences.get("p1")!;+ expect(state.fields["status"]).toBe("retired");+ expect(state.counters.applied_count).toBe(1);+ expect(state.history.map((r) => r.id)).toEqual([+ created.id,+ retire.id,+ evidence.id,+ reconfirm.id,+ ]);+ });++ test("counters come from evidence only and are never written back", () => {+ const set = prefSet("dev-a", T, "human", {+ principle: "p",+ applied_count: 99,+ violated_count: 7,+ });+ const evidence = ["applied", "violated", "applied", "outdated"].map((result, i) =>+ rec({+ device: "dev-b",+ physical: T + i + 1,+ kind: "preference-evidence",+ body: { preference: "p1", result },+ }),+ );+ const state = foldPreferences([set, ...evidence, evidence[0]!]).preferences.get("p1")!;+ expect(state.counters).toEqual({ applied_count: 2, violated_count: 1, outdated_count: 1 });+ expect(state.fields).toEqual({ principle: "p" });+ });++ test("a removal is a tombstone that keeps the records and the last values", () => {+ const set = prefSet("dev-a", T, "agent", { principle: "p" });+ const remove = rec({+ physical: T + 1,+ kind: "preference-remove",+ body: authored("agent", { preference: "p1" }),+ });+ const state = foldPreferences([remove, set]).preferences.get("p1")!;+ expect(state).toMatchObject({+ exists: false,+ removed: true,+ fields: { principle: "p" },+ existenceWinner: remove.id,+ });+ expect(state.history.map((r) => r.id)).toEqual([set.id, remove.id]);+ const revived = prefSet("dev-a", T + 2, "agent", { principle: "q" });+ expect(foldPreferences([set, remove, revived]).preferences.get("p1")).toMatchObject({+ exists: true,+ removed: false,+ });+ });++ test("an agent removal does not remove a preference a human set", () => {+ const human = prefSet("dev-a", T, "human", { principle: "p" });+ const remove = rec({+ physical: T + 1,+ kind: "preference-remove",+ body: authored("agent", { preference: "p1" }),+ });+ expect(foldPreferences([human, remove]).preferences.get("p1")).toMatchObject({+ exists: true,+ removed: false,+ });+ });++ test("evidence alone does not make a preference exist", () => {+ const evidence = rec({+ physical: T,+ kind: "preference-evidence",+ body: { preference: "p9", result: "violated" },+ });+ expect(foldPreferences([evidence]).preferences.get("p9")).toMatchObject({+ exists: false,+ removed: false,+ existenceWinner: null,+ counters: { violated_count: 1 },+ });+ });++ test("a set that names only derived counters is rejected and cannot undo a removal", () => {+ const set = prefSet("dev-a", T, "agent", { status: "confirmed" });+ const remove = rec({+ device: "dev-a",+ physical: T + 1,+ kind: "preference-remove",+ body: authored("agent", { preference: "p1" }),+ });+ const countersOnly = prefSet("dev-a", T + 2, "human", { applied_count: 3 });+ const fold = foldPreferences([set, remove, countersOnly]);+ expect(fold.preferences.get("p1")!.exists).toBe(false);+ expect(fold.rejected).toEqual([+ { id: countersOnly.id, kind: "preference-set", reason: "fields name only derived counters" },+ ]);+ });++ test("a preference id that is an Object.prototype key still counts in the fingerprint", () => {+ const plain = foldPreferences([prefSet("dev-a", T, "human", { status: "confirmed" }, "p1")]);+ const withProto = foldPreferences([+ prefSet("dev-a", T, "human", { status: "confirmed" }, "p1"),+ prefSet("dev-a", T + 1, "human", { status: "confirmed" }, "__proto__"),+ ]);+ expect(fingerprint(withProto)).not.toBe(fingerprint(plain));+ expect(fingerprint(withProto)).toContain('"__proto__"');+ });++ test("malformed preference records are rejected", () => {+ const records = [+ rec({+ physical: T,+ kind: "preference-evidence",+ body: { preference: "p1", result: "maybe" },+ }),+ rec({+ physical: T + 1,+ kind: "preference-set",+ body: authored("agent", { preference: "p1", fields: {} }),+ }),+ rec({+ physical: T + 2,+ kind: "preference-set",+ body: authored("agent", { preference: "p1", fields: { "Bad-Name": 1 } }),+ }),+ rec({+ physical: T + 3,+ kind: "preference-remove",+ body: authored("agent", { preference: "" }),+ }),+ ];+ const fold = foldPreferences(records);+ expect(fold.preferences.size).toBe(0);+ expect(fold.rejected.map((r) => r.reason)).toEqual([+ "evidence result must be one of applied, violated, outdated",+ "fields must be a non-empty object",+ 'invalid field name "Bad-Name"',+ "missing or invalid preference id",+ ]);+ });+});++describe("pinned context fold", () => {+ test("concurrent replacements: the later clock wins on every machine, the other stays in history (spec scenario)", () => {+ const fromA = rec({+ device: "dev-a",+ physical: T,+ kind: "pinned-set",+ body: authored("agent", { content: "from A" }),+ });+ const fromB = rec({+ device: "dev-b",+ physical: T + 3,+ kind: "pinned-set",+ body: authored("agent", { content: "from B" }),+ });+ const onA = foldPinned([fromA, fromB]);+ const onB = foldPinned([fromB, fromA]);+ expect(onA).toEqual(onB);+ expect(onA.content).toBe("from B");+ expect(onA.history.map((e) => e.value)).toEqual(["from A", "from B"]);+ });++ test("a clear is a tombstone; a later set pins again", () => {+ const set = rec({ physical: T, kind: "pinned-set", body: authored("agent", { content: "x" }) });+ const clear = rec({ physical: T + 1, kind: "pinned-clear", body: authored("agent", {}) });+ expect(foldPinned([set, clear])).toMatchObject({+ content: null,+ cleared: true,+ winner: clear.id,+ });+ const again = rec({+ physical: T + 2,+ kind: "pinned-set",+ body: authored("agent", { content: "y" }),+ });+ expect(foldPinned([again, clear, set])).toMatchObject({ content: "y", cleared: false });+ });++ test("a human pin survives a later agent replacement", () => {+ const human = rec({+ physical: T,+ kind: "pinned-set",+ body: authored("human", { content: "mine" }),+ });+ const agent = rec({+ physical: T + 1,+ kind: "pinned-set",+ body: authored("agent", { content: "agent" }),+ });+ expect(foldPinned([agent, human]).content).toBe("mine");+ });++ test("nothing pinned folds to an empty state", () => {+ expect(foldPinned([])).toEqual({+ content: null,+ cleared: false,+ winner: null,+ history: [],+ rejected: [],+ });+ });+});++describe("settings fold", () => {+ test("defaults apply until a key is set, and again after it is unset", () => {+ const set = rec({+ physical: T,+ kind: "setting-set",+ body: authored("human", { key: "topics.new_min_records", value: 8 }),+ });+ const unset = rec({+ physical: T + 1,+ kind: "setting-unset",+ body: authored("human", { key: "topics.new_min_records" }),+ });+ expect(settingValue(foldSettings([]), "topics.new_min_records")).toBe(5);+ expect(settingValue(foldSettings([set]), "topics.new_min_records")).toBe(8);+ expect(settingValue(foldSettings([unset, set]), "topics.new_min_records")).toBe(5);+ expect(settingValue(foldSettings([]), "topics.new_min_sessions")).toBe(2);+ expect(settingValue(foldSettings([]), "view.language")).toBeNull();+ });++ test("an invalid value for a known key is rejected; an unknown key is kept as written", () => {+ const records = [+ rec({+ physical: T,+ kind: "setting-set",+ body: authored("human", { key: "view.language", value: "ru" }),+ }),+ rec({+ physical: T + 1,+ kind: "setting-set",+ body: authored("human", { key: "view.language", value: "not a tag" }),+ }),+ rec({+ physical: T + 2,+ kind: "setting-set",+ body: authored("agent", { key: "view.writer", value: "Bad Device" }),+ }),+ rec({+ physical: T + 3,+ kind: "setting-set",+ body: authored("agent", { key: "future.knob", value: { a: 1 } }),+ }),+ ];+ const fold = foldSettings(records);+ expect(settingValue(fold, "view.language")).toBe("ru");+ expect(settingValue(fold, "view.writer")).toBeNull();+ expect(settingValue(fold, "future.knob")).toEqual({ a: 1 });+ expect(fold.rejected.map((r) => r.reason)).toEqual([+ "view.language must be a language tag such as en or pt-BR",+ "view.writer must be a device id",+ ]);+ });+});++describe("a setting changed on one machine applies on another (spec scenario)", () => {+ let tmp: TempStore;+ beforeEach(() => {+ tmp = makeTempStore("osb-store-fold-");+ });+ afterEach(() => tmp.cleanup());++ test("machine B folds machine A's threshold record once it has the shard", () => {+ const a = tmp.open("dev-a");+ // Machine B has its own copy of the shared partition, filled only by sync.+ const bShared = partitionDir(join(tmp.parent, "machine-b"), "shared");+ mkdirSync(bShared, { recursive: true });+ expect(threshold(bShared)).toBe(5);+ appendRecord(+ a,+ {+ partition: "shared",+ stream: "settings",+ kind: "setting-set",+ agent: "cli",+ body: { authority: "human", key: "topics.new_min_records", value: 3 },+ },+ { now: () => T },+ );+ expect(threshold(partitionDir(tmp.root, "shared"))).toBe(3);+ // B still folds the default until the sync tool delivers A's shard.+ expect(threshold(bShared)).toBe(5);+ cpSync(join(partitionDir(tmp.root, "shared"), "settings"), join(bShared, "settings"), {+ recursive: true,+ });+ expect(threshold(bShared)).toBe(3);+ });+});diff --git a/tests/core/store/format-doc.test.ts b/tests/core/store/format-doc.test.tsnew file mode 100644index 00000000..668262b7--- /dev/null+++ b/tests/core/store/format-doc.test.ts@@ -0,0 +1,112 @@+/**+ * The shipped FORMAT.md names every envelope field, stream, partition and+ * store-level record kind the code defines, and every other store name a+ * reader of the files meets, so the public format cannot fall behind the code.+ */+import { describe, expect, test } from "bun:test";++import {+ AUTHORITIES,+ AUTHORITY_FIELD,+ BLOB_REF_BYTES_KEY,+ BLOB_REF_KEY,+ BLOB_TEMP_PREFIX,+ DUAL_WRITE_RECORD_KINDS,+ ENVELOPE_FIELDS,+ FOLD_RECORD_KINDS,+ PREFERENCE_COUNTER_FIELDS,+ SETTING_KEYS,+ STATE_DIGEST_FOLDS,+ STORE_BLOBS_DIR,+ STORE_FORMAT_FILE,+ STORE_FORMAT_VERSION,+ STORE_IDENTITY_FILE,+ STORE_BODY_MAX_DEPTH,+ STORE_LINE_CAP_BYTES,+ STORE_PARTITIONS,+ STORE_RECORD_KINDS,+ STORE_STREAMS,+} from "../../../src/core/store/constants.ts";+import { DUAL_WRITE_LEDGERS } from "../../../src/core/store/dual-write-records.ts";+import { formatDocVersion, shippedFormatDoc } from "../../../src/core/store/format-doc.ts";++const doc = shippedFormatDoc();++/** A definition bullet for `name`: `- \`<name>\`:` at the start of a line, the name matched literally. */+const bullet = (name: string): RegExp =>+ new RegExp(`^- \`${name.replaceAll(/[.*+?^${}()|[\]\\]/g, "\\$&")}\`:`, "m");++/** Names written as inline code, the way the document spells every format term. */+const codeSpans = new Set([...doc.matchAll(/`([^`\n]+)`/g)].map((m) => m[1]!));++describe("FORMAT.md", () => {+ test.each([...ENVELOPE_FIELDS])("documents the envelope field %s", (field) => {+ expect(codeSpans.has(field)).toBe(true);+ expect(doc).toMatch(bullet(field));+ });++ test.each([...STORE_STREAMS])("documents the stream %s", (stream) => {+ expect(doc).toMatch(bullet(stream));+ });++ test.each([...STORE_PARTITIONS])("documents the partition %s", (partition) => {+ expect(doc).toMatch(bullet(partition));+ });++ test.each([...STORE_RECORD_KINDS])("documents the store record kind %s", (kind) => {+ expect(doc).toMatch(bullet(kind));+ });++ test.each([...DUAL_WRITE_RECORD_KINDS])("documents the dual-write record kind %s", (kind) => {+ expect(doc).toMatch(bullet(kind));+ });++ test.each(Object.values(DUAL_WRITE_LEDGERS))("documents the dual-write ledger %s", (name) => {+ expect(doc).toContain(`\`${name}\``);+ });++ test("tells readers and sync setups to ignore dot-prefixed blob temp files", () => {+ expect(doc).toContain(`\`${BLOB_TEMP_PREFIX}\``);+ });++ test.each([...FOLD_RECORD_KINDS])("documents the fold and digest record kind %s", (kind) => {+ expect(doc).toMatch(bullet(kind));+ });++ test.each([...AUTHORITIES])("documents the authority %s", (authority) => {+ expect(doc).toMatch(bullet(authority));+ });++ test.each([...SETTING_KEYS])("documents the setting key %s", (key) => {+ expect(doc).toMatch(bullet(key));+ });++ test("names the authority field, the derived counters and the digested folds", () => {+ expect(codeSpans.has(AUTHORITY_FIELD)).toBe(true);+ for (const name of [...PREFERENCE_COUNTER_FIELDS, ...STATE_DIGEST_FOLDS]) {+ expect(codeSpans.has(name)).toBe(true);+ }+ });++ test("names the files, the blob reference keys and the line cap", () => {+ for (const name of [STORE_FORMAT_FILE, STORE_IDENTITY_FILE, BLOB_REF_KEY, BLOB_REF_BYTES_KEY]) {+ expect(doc).toContain(name);+ }+ expect(doc).toContain(`${STORE_BLOBS_DIR}/<sha256[0:2]>/<sha256>`);+ expect(doc).toContain(String(STORE_LINE_CAP_BYTES));+ expect(doc).toContain(`at most ${STORE_BODY_MAX_DEPTH} levels deep`);+ });++ test("declares the format version the code writes", () => {+ expect(formatDocVersion(doc)).toBe(STORE_FORMAT_VERSION);+ expect(doc).toContain(`Format version: ${STORE_FORMAT_VERSION}`);+ });++ test("follows the documentation style rules", () => {+ expect(doc).toContain("Open Second Brain");+ const prose = doc.replaceAll(/<!--.*?-->/g, "");+ expect(/\bOSB\b/.test(prose)).toBe(false);+ expect(prose.includes("!")).toBe(false);+ expect(prose.includes("β")).toBe(false);+ });+});diff --git a/tests/core/store/hlc.test.ts b/tests/core/store/hlc.test.tsnew file mode 100644index 00000000..ee32242b--- /dev/null+++ b/tests/core/store/hlc.test.ts@@ -0,0 +1,142 @@+import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { dirname, join } from "node:path";++import {+ compareHlc,+ formatHlc,+ HLC_MAX_DRIFT_MS,+ parseHlc,+ receiveHlc,+ sendHlc,+ type Hlc,+} from "../../../src/core/store/hlc.ts";+import {+ clockFilePath,+ observeClock,+ readClock,+ tickClock,+} from "../../../src/core/store/clock-store.ts";++describe("hlc text form", () => {+ test("round-trips physical milliseconds and counter", () => {+ const clock: Hlc = { physical: 1_762_400_000_123, counter: 7 };+ expect(formatHlc(clock)).toBe("1762400000123.7");+ expect(parseHlc("1762400000123.7")).toEqual(clock);+ });++ test("rejects malformed stamps", () => {+ for (const bad of ["", "1.2.3", "abc.1", "12", "-1.0", "1.-1", "01.0", "1.01", "1e3.0"]) {+ expect(parseHlc(bad)).toBeNull();+ }+ });++ test("orders by physical, then counter", () => {+ expect(compareHlc({ physical: 1, counter: 9 }, { physical: 2, counter: 0 })).toBeLessThan(0);+ expect(compareHlc({ physical: 2, counter: 1 }, { physical: 2, counter: 0 })).toBeGreaterThan(0);+ expect(compareHlc({ physical: 2, counter: 1 }, { physical: 2, counter: 1 })).toBe(0);+ });+});++describe("hlc send rule", () => {+ test("takes the wall clock when it is ahead", () => {+ expect(sendHlc({ physical: 100, counter: 4 }, 200)).toEqual({ physical: 200, counter: 0 });+ });++ test("increments the counter on a tie", () => {+ expect(sendHlc({ physical: 200, counter: 4 }, 200)).toEqual({ physical: 200, counter: 5 });+ });++ test("stays monotonic when the wall clock goes backwards", () => {+ let clock: Hlc = { physical: 0, counter: 0 };+ const stamps: Hlc[] = [];+ for (const wall of [1000, 1005, 900, 900, 400, 1005, 1006]) {+ clock = sendHlc(clock, wall);+ stamps.push(clock);+ }+ for (let i = 1; i < stamps.length; i++) {+ expect(compareHlc(stamps[i]!, stamps[i - 1]!)).toBeGreaterThan(0);+ }+ });+});++describe("hlc receive rule", () => {+ test("raises the local clock above a remote clock from a faster machine", () => {+ const local = { physical: 1000, counter: 0 };+ const remote = { physical: 121_000, counter: 3 };+ const raised = receiveHlc(local, remote, 1001);+ expect(compareHlc(raised, remote)).toBeGreaterThanOrEqual(0);+ // The next stamp the slow machine sends orders after the remote one.+ expect(compareHlc(sendHlc(raised, 1002), remote)).toBeGreaterThan(0);+ });++ test("a remote stamp more than the drift bound ahead of the wall clock is not adopted", () => {+ const wall = Date.UTC(2026, 10, 6);+ const local = { physical: wall - 5, counter: 1 };+ const farFuture = { physical: wall + HLC_MAX_DRIFT_MS + 1, counter: 0 };+ expect(receiveHlc(local, farFuture, wall)).toEqual({ physical: wall, counter: 0 });+ // Just inside the bound, the remote stamp is still adopted.+ const near = { physical: wall + HLC_MAX_DRIFT_MS, counter: 2 };+ expect(receiveHlc(local, near, wall)).toEqual(near);+ });++ test("never lowers the local clock", () => {+ const local = { physical: 5000, counter: 2 };+ expect(+ compareHlc(receiveHlc(local, { physical: 10, counter: 0 }, 20), local),+ ).toBeGreaterThanOrEqual(0);+ });+});++describe("persisted device clock", () => {+ let root: string;+ beforeEach(() => {+ root = mkdtempSync(join(tmpdir(), "osb-store-clock-"));+ });+ afterEach(() => {+ rmSync(root, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });+ });++ test("survives a restart: a new tick after a backwards wall clock still orders later", () => {+ const first = tickClock(root, "dev-a", () => 50_000);+ // A "restart" is a fresh call with nothing in memory; only the file remains.+ const second = tickClock(root, "dev-a", () => 10_000);+ expect(compareHlc(second, first)).toBeGreaterThan(0);+ expect(readClock(root, "dev-a")).toEqual(second);+ });++ test("an observed remote clock lifts later ticks above it", () => {+ const remote = { physical: 9_000_000, counter: 4 };+ observeClock(root, "dev-b", remote, () => 1_000);+ const reply = tickClock(root, "dev-b", () => 1_001);+ expect(compareHlc(reply, remote)).toBeGreaterThan(0);+ });++ test("a corrupt clock file falls back to the wall clock instead of failing the write", () => {+ const path = clockFilePath(root, "dev-c");+ mkdirSync(dirname(path), { recursive: true });+ writeFileSync(path, "{not json");+ expect(tickClock(root, "dev-c", () => 777)).toEqual({ physical: 777, counter: 0 });+ });++ test("a far-future remote stamp from a broken clock does not poison later ticks", () => {+ const wall = Date.UTC(2026, 10, 6);+ // Year 9999 and beyond: a month name for it would break every later append.+ observeClock(root, "dev-f", { physical: 9_000_000_000_000_000, counter: 0 }, () => wall);+ expect(tickClock(root, "dev-f", () => wall + 1)).toEqual({ physical: wall + 1, counter: 0 });+ });++ test("a clock file that exists but cannot be read fails the tick instead of resetting the clock", () => {+ const path = clockFilePath(root, "dev-d");+ // A directory where the file should be: the read fails with something other than ENOENT.+ mkdirSync(path, { recursive: true });+ expect(() => readClock(root, "dev-d")).toThrow();+ expect(() => tickClock(root, "dev-d", () => 777)).toThrow();+ });++ test("clocks of two devices are independent", () => {+ tickClock(root, "dev-a", () => 9_000);+ expect(readClock(root, "dev-z")).toBeNull();+ });+});diff --git a/tests/core/store/local-lock.test.ts b/tests/core/store/local-lock.test.tsnew file mode 100644index 00000000..f7fcd4a0--- /dev/null+++ b/tests/core/store/local-lock.test.ts@@ -0,0 +1,77 @@+/**+ * The device-local store lock (`local-lock.ts`): a crashed holder's lock is+ * taken over, but a live holder stuck in a slow append keeps its lock.+ */+import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import { mkdirSync, mkdtempSync, rmSync, utimesSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import {+ isLockContention,+ STORE_LOCK_STALE_MS,+ withLocalLock,+} from "../../../src/core/store/local-lock.ts";++let parent: string;+let target: string;++beforeEach(() => {+ parent = mkdtempSync(join(tmpdir(), "osb-store-lock-"));+ target = join(parent, "locks", "shard");+});+afterEach(() => rmSync(parent, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 }));++/** A lock directory another process took `ageMs` ago and never released. */+function heldSince(ageMs: number): void {+ const dir = `${target}.lock`;+ mkdirSync(dir, { recursive: true });+ const at = new Date(Date.now() - ageMs);+ utimesSync(dir, at, at);+}++describe("withLocalLock", () => {+ test("a holder stuck for 30 seconds keeps its lock", () => {+ heldSince(30_000);+ let ran = false;+ expect(() =>+ withLocalLock(+ target,+ () => {+ ran = true;+ },+ 50,+ ),+ ).toThrow("store lock busy");+ expect(ran).toBe(false);+ });++ test("a lock older than the stale window is taken over from a crashed holder", () => {+ heldSince(STORE_LOCK_STALE_MS + 5_000);+ expect(withLocalLock(target, () => "ran", 50)).toBe("ran");+ });+});++const eperm = (): NodeJS.ErrnoException => Object.assign(new Error("EPERM"), { code: "EPERM" });++describe("isLockContention", () => {+ test("a held lock is contention on every platform", () => {+ const held = Object.assign(new Error("held"), { code: "ELOCKED" });+ expect(isLockContention(held, target, "linux")).toBe(true);+ expect(isLockContention(held, target, "win32")).toBe(true);+ });++ test("a Windows EPERM on a lock directory still going away is contention", () => {+ heldSince(0);+ expect(isLockContention(eperm(), target, "win32")).toBe(true);+ });++ test("a Windows EPERM with nothing at the lock name is a real refusal", () => {+ expect(isLockContention(eperm(), target, "win32")).toBe(false);+ });++ test("EPERM stays an error on POSIX", () => {+ heldSince(0);+ expect(isLockContention(eperm(), target, "linux")).toBe(false);+ });+});diff --git a/tests/core/store/operation-scope.test.ts b/tests/core/store/operation-scope.test.tsnew file mode 100644index 00000000..fd9a45db--- /dev/null+++ b/tests/core/store/operation-scope.test.ts@@ -0,0 +1,180 @@+/**+ * The ambient operation scope (`operation-scope.ts`): a store record+ * written while a writer operation runs follows that operation's verdict,+ * whoever writes it, on the synchronous path and across awaits and timers.+ * Nested operations can only raise; two operations running at once never+ * see each other's verdict.+ *+ * The record under test is a plain Brain log event, which on its own lands+ * in `shared`. Every test runs against its own temp HOME, state base,+ * vault and store root under one named parent, removed in teardown.+ */+import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import { mkdirSync, mkdtempSync, rmSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { setTimeout as sleep } from "node:timers/promises";++import { bootstrapBrain } from "../../../src/core/brain/init.ts";+import { appendLogEvent } from "../../../src/core/brain/log.ts";+import { STORE_DUAL_WRITE_ENV, STORE_ROOT_ENV } from "../../../src/core/store/constants.ts";+import { withOperationPrivacy } from "../../../src/core/store/operation-scope.ts";+import { readPartition } from "../../../src/core/store/state-digest.ts";+import { initStore } from "../../../src/core/store/store-init.ts";++const ENV_KEYS = [+ STORE_DUAL_WRITE_ENV,+ STORE_ROOT_ENV,+ "O2B_DEVICE_ID",+ "HOME",+ "XDG_STATE_HOME",+ "LOCALAPPDATA",+] as const;++let parent: string;+let vault: string;+let storeRoot: string;+const saved = new Map<string, string | undefined>();++beforeEach(() => {+ for (const key of ENV_KEYS) saved.set(key, process.env[key]);+ parent = mkdtempSync(join(tmpdir(), "osb-operation-scope-"));+ vault = join(parent, "vault");+ storeRoot = join(parent, "store");+ mkdirSync(vault, { recursive: true });+ bootstrapBrain(vault);+ process.env["HOME"] = join(parent, "home");+ process.env["XDG_STATE_HOME"] = join(parent, "state");+ process.env["LOCALAPPDATA"] = join(parent, "state");+ process.env[STORE_ROOT_ENV] = storeRoot;+ process.env["O2B_DEVICE_ID"] = "dev-a";+ process.env[STORE_DUAL_WRITE_ENV] = "1";+ initStore({ root: storeRoot });+});++afterEach(() => {+ for (const key of ENV_KEYS) {+ const value = saved.get(key);+ if (value === undefined) delete process.env[key];+ else process.env[key] = value;+ }+ rmSync(parent, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });+});++/** Append a plain log event whose text is `marker`. */+function writePlain(marker: string): void {+ appendLogEvent(vault, {+ timestamp: "2026-11-06T10:00:00Z",+ eventType: "note",+ body: { text: marker, agent: "@claude-devbox-agent" },+ });+}++/** The partition the event carrying `marker` landed in. */+function partitionOf(marker: string): "shared" | "private" | "missing" {+ for (const partition of ["shared", "private"] as const) {+ for (const shard of readPartition(join(storeRoot, partition))) {+ if (shard.records.some((r) => JSON.stringify(r.body).includes(marker))) return partition;+ }+ }+ return "missing";+}++/** Three records under one verdict, each after a timer, so two runs interleave. */+function runInterleaved(verdict: boolean, marker: string): Promise<void> {+ const step = async (i: number): Promise<void> => {+ await sleep(1);+ writePlain(`${marker}-${i}`);+ };+ return withOperationPrivacy(verdict, async () => {+ await step(0);+ await step(1);+ await step(2);+ });+}++describe("the operation scope", () => {+ test("outside any operation a plain record lands in shared", () => {+ writePlain("outside");+ expect(partitionOf("outside")).toBe("shared");+ });++ test("a private operation sends a record written on its synchronous path to private", () => {+ withOperationPrivacy(true, () => writePlain("sync"));+ expect(partitionOf("sync")).toBe("private");+ });++ test("a shared operation leaves a plain record in shared", () => {+ withOperationPrivacy(+ () => false,+ () => writePlain("open"),+ );+ expect(partitionOf("open")).toBe("shared");+ });++ test("the scope follows the operation across awaits and timers", async () => {+ await withOperationPrivacy(true, async () => {+ await Promise.resolve();+ writePlain("after-microtask");+ await sleep(5);+ writePlain("after-timer");+ await new Promise<void>((done) => {+ setImmediate(() => {+ writePlain("in-callback");+ done();+ });+ });+ });+ expect(partitionOf("after-microtask")).toBe("private");+ expect(partitionOf("after-timer")).toBe("private");+ expect(partitionOf("in-callback")).toBe("private");+ });++ test("an inner operation can raise, never lower, and the outer verdict holds again after it", () => {+ withOperationPrivacy(true, () => {+ withOperationPrivacy(false, () => writePlain("inner-open-in-private"));+ });+ withOperationPrivacy(false, () => {+ withOperationPrivacy(true, () => writePlain("inner-private-in-open"));+ writePlain("outer-open-after-inner");+ });+ expect(partitionOf("inner-open-in-private")).toBe("private");+ expect(partitionOf("inner-private-in-open")).toBe("private");+ expect(partitionOf("outer-open-after-inner")).toBe("shared");+ });++ test("two operations running at once keep their own verdicts", async () => {+ await Promise.all([runInterleaved(true, "busy-private"), runInterleaved(false, "busy-open")]);+ for (const i of [0, 1, 2]) {+ expect(partitionOf(`busy-private-${i}`)).toBe("private");+ expect(partitionOf(`busy-open-${i}`)).toBe("shared");+ }+ });++ test("a verdict that throws counts as private", () => {+ withOperationPrivacy(+ () => {+ throw new Error("cannot judge");+ },+ () => writePlain("throwing"),+ );+ expect(partitionOf("throwing")).toBe("private");+ });++ test("the verdict is judged once, and not at all with dual writes off", () => {+ let calls = 0;+ const verdict = (): boolean => {+ calls += 1;+ return false;+ };+ delete process.env[STORE_DUAL_WRITE_ENV];+ withOperationPrivacy(verdict, () => writePlain("off"));+ expect(calls).toBe(0);+ process.env[STORE_DUAL_WRITE_ENV] = "1";+ withOperationPrivacy(verdict, () => {+ writePlain("first");+ writePlain("second");+ });+ expect(calls).toBe(1);+ });+});diff --git a/tests/core/store/reader.test.ts b/tests/core/store/reader.test.tsnew file mode 100644index 00000000..c57d6825--- /dev/null+++ b/tests/core/store/reader.test.ts@@ -0,0 +1,313 @@+import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import { appendFileSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { dirname, join } from "node:path";++import {+ BLOB_REF_BYTES_KEY,+ BLOB_REF_KEY,+ COMPACTED_KIND,+ STORE_BODY_MAX_DEPTH,+ STORE_FORMAT_VERSION,+ STORE_LINE_CAP_BYTES,+} from "../../../src/core/store/constants.ts";+import { sha256Hex } from "../../../src/core/integrity/digest.ts";+import {+ buildRecord,+ canonicalBodyText,+ EnvelopeError,+ type RecordBody,+ type StoreRecord,+} from "../../../src/core/store/envelope.ts";+import { writeBlob } from "../../../src/core/store/blobs.ts";+import {+ classifyMissingShard,+ readBlobBody,+ readShard,+ replacedShards,+} from "../../../src/core/store/reader.ts";+import { listShards } from "../../../src/core/store/shard-list.ts";++const line = (record: unknown): string => `${JSON.stringify(record)}\n`;++let counter = 0;+/** A fixture record; every call gets its own, increasing clock stamp. */+function makeRecord(body?: RecordBody, kind = "note"): StoreRecord {+ const n = ++counter;+ return buildRecord({+ hlc: { physical: Date.UTC(2026, 10, 1) + n, counter: 0 },+ device: "dev-b",+ agent: "agent-b",+ kind,+ body: body ?? { n },+ });+}++describe("shard reader fixtures", () => {+ let dir: string;+ let partition: string;+ let shard: string;+ beforeEach(() => {+ dir = mkdtempSync(join(tmpdir(), "osb-store-read-"));+ partition = join(dir, "shared");+ shard = join(partition, "events", "dev-b", "2026-11.jsonl");+ mkdirSync(dirname(shard), { recursive: true });+ });+ afterEach(() => {+ rmSync(dir, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });+ });++ test("a cut last line is held back and read once the rest arrives", () => {+ const a = makeRecord();+ const b = makeRecord();+ const full = line(b);+ writeFileSync(shard, line(a) + full.slice(0, 30));+ const first = readShard(shard);+ expect(first.records.map((r) => r.record.id)).toEqual([a.id]);+ expect(first.diagnostics).toEqual([]);+ expect(first.pendingTailBytes).toBe(30);+ expect(first.nextOffset).toBe(Buffer.byteLength(line(a)));++ appendFileSync(shard, full.slice(30));+ const second = readShard(shard, { offset: first.nextOffset });+ expect(second.records.map((r) => r.record.id)).toEqual([b.id]);+ expect(second.pendingTailBytes).toBe(0);+ expect(second.nextOffset).toBe(second.size);+ });++ test("a complete last line that fails its checksum is retried, not reported", () => {+ const a = makeRecord();+ const bad = { ...makeRecord(), sum: "0".repeat(64) };+ writeFileSync(shard, line(a) + line(bad));+ const read = readShard(shard);+ expect(read.records.map((r) => r.record.id)).toEqual([a.id]);+ expect(read.diagnostics).toEqual([]);+ expect(read.pendingTailBytes).toBe(Buffer.byteLength(line(bad)));+ });++ test("a corrupt middle line is reported and skipped; the lines around it are read", () => {+ const a = makeRecord();+ const c = makeRecord();+ const tampered = { ...makeRecord(), body: { n: "tampered" } };+ writeFileSync(shard, line(a) + line(tampered) + "{not json\n" + line(c));+ const read = readShard(shard);+ expect(read.records.map((r) => r.record.id)).toEqual([a.id, c.id]);+ expect(read.diagnostics.map((d) => [d.kind, d.offset])).toEqual([+ ["corrupt-line", Buffer.byteLength(line(a))],+ ["corrupt-line", Buffer.byteLength(line(a) + line(tampered))],+ ]);+ expect(read.diagnostics[0]!.reason).toContain("checksum");+ expect(read.nextOffset).toBe(read.size);+ });++ test("a record of a future format version is skipped and reported", () => {+ const a = makeRecord();+ const future = { ...makeRecord(), v: STORE_FORMAT_VERSION + 1, shiny: true };+ const c = makeRecord();+ writeFileSync(shard, line(a) + line(future) + line(c));+ const read = readShard(shard);+ expect(read.records.map((r) => r.record.id)).toEqual([a.id, c.id]);+ expect(read.diagnostics).toEqual([+ {+ kind: "unknown-version",+ offset: Buffer.byteLength(line(a)),+ reason: `unknown format version ${STORE_FORMAT_VERSION + 1}`,+ },+ ]);+ });++ test("a future-version last line is consumed like any other, not retried forever", () => {+ const future = { ...makeRecord(), v: STORE_FORMAT_VERSION + 1 };+ writeFileSync(shard, line(future));+ const read = readShard(shard);+ expect(read.diagnostics.map((d) => d.kind)).toEqual(["unknown-version"]);+ expect(read.nextOffset).toBe(read.size);+ });++ test("a compacted shard is reported as replaced, not missing", () => {+ const old = "events/dev-b/2026-10.jsonl";+ const into = "events/dev-b/2026-10.c1.jsonl";+ writeFileSync(join(partition, ...into.split("/")), line(makeRecord()));+ const marker = makeRecord({ replaces: [old], into: [into] }, COMPACTED_KIND);+ writeFileSync(shard, line(marker));+ const read = readShard(shard);+ expect(read.compactions).toEqual([{ id: marker.id, replaces: [old], into: [into] }]);+ const replaced = replacedShards(read.compactions);+ expect(classifyMissingShard(old, replaced)).toBe("replaced");+ expect(classifyMissingShard("events/dev-b/2026-09.jsonl", replaced)).toBe("missing");+ // The compaction output is a shard; a sync conflict copy is not.+ writeFileSync(+ join(partition, "events", "dev-b", "2026-11.sync-conflict-20261106.jsonl"),+ "x\n",+ );+ expect(listShards(partition, { stream: "events" }).map((s) => s.rel)).toEqual([+ into,+ "events/dev-b/2026-11.jsonl",+ ]);+ });++ test("a blob that arrives late: pending first, filled in on a later read", () => {+ const body = { report: "long text" };+ const full = makeRecord(body);+ const text = canonicalBodyText(full.body);+ const onLine = {+ ...full,+ body: { [BLOB_REF_KEY]: full.sum, [BLOB_REF_BYTES_KEY]: Buffer.byteLength(text) },+ };+ writeFileSync(shard, line(onLine));++ const before = readShard(shard, { partitionRoot: partition });+ expect(before.diagnostics).toEqual([]);+ expect(before.records[0]!.bodyState).toBe("pending");+ expect(before.records[0]!.record.id).toBe(full.id);++ // A partially delivered blob is still pending.+ const blobFile = join(partition, "blobs", full.sum.slice(0, 2), full.sum);+ mkdirSync(dirname(blobFile), { recursive: true });+ writeFileSync(blobFile, text.slice(0, 5));+ expect(readShard(shard, { partitionRoot: partition }).records[0]!.bodyState).toBe("pending");+ rmSync(blobFile);++ expect(writeBlob(partition, text).sha).toBe(full.sum);+ const after = readShard(shard, { partitionRoot: partition });+ expect(after.records[0]!.bodyState).toBe("blob");+ expect(after.records[0]!.record.body).toEqual(body);+ });++ /**+ * A line whose blob reference passes the envelope check (its hash is the+ * record's sum) and a blob that hashes to its name, holding `content`.+ */+ function craftedBlobLine(content: string, bytes = Buffer.byteLength(content)): string {+ const sum = sha256Hex(content);+ const record = {+ ...makeRecord(),+ sum,+ body: { [BLOB_REF_KEY]: sum, [BLOB_REF_BYTES_KEY]: bytes },+ };+ const blobFile = join(partition, "blobs", sum.slice(0, 2), sum);+ mkdirSync(dirname(blobFile), { recursive: true });+ writeFileSync(blobFile, content);+ return line(record);+ }++ test("a hash-valid blob that is not a record body is reported and skipped, never thrown", () => {+ for (const content of ["null", "[1,2]", "42", "not json at all", '{"$blob":"x","b":1}']) {+ const before = makeRecord();+ const after = makeRecord();+ writeFileSync(shard, line(before) + craftedBlobLine(content) + line(after));+ const read = readShard(shard, { partitionRoot: partition });+ expect(read.records.map((r) => r.record.id)).toEqual([before.id, after.id]);+ expect(read.diagnostics.map((d) => d.kind)).toEqual(["corrupt-line"]);+ expect(read.nextOffset).toBe(read.size);+ expect(readBlobBody(partition, sha256Hex(content)).status).toBe("invalid");+ }+ });++ test("a hash-valid blob nested past the depth bound is a corrupt record, the pass goes on", () => {+ // Deep enough to overflow a recursive canonicalization.+ const depth = 100_000;+ const content = `{"a":${"[".repeat(depth)}${"]".repeat(depth)}}`;+ const before = makeRecord();+ const after = makeRecord();+ writeFileSync(shard, line(before) + craftedBlobLine(content) + line(after));+ const read = readShard(shard, { partitionRoot: partition });+ expect(read.records.map((r) => r.record.id)).toEqual([before.id, after.id]);+ expect(read.diagnostics.map((d) => d.kind)).toEqual(["corrupt-line"]);+ expect(read.nextOffset).toBe(read.size);+ expect(readBlobBody(partition, sha256Hex(content)).status).toBe("invalid");+ });++ test("an inline body nested past the depth bound is a corrupt line and is never written", () => {+ let deep: unknown = 1;+ for (let i = 0; i < STORE_BODY_MAX_DEPTH; i++) deep = [deep];+ // The body object is one level, so this body is one level too deep.+ expect(() => makeRecord({ deep } as RecordBody)).toThrow(EnvelopeError);+ const atBound = makeRecord({ deep: (deep as unknown[])[0] } as RecordBody);+ const sum = sha256Hex(JSON.stringify({ deep }));+ const tooDeep = { ...makeRecord(), sum, body: { deep } };+ writeFileSync(shard, line(atBound) + line(tooDeep) + line(makeRecord()));+ const read = readShard(shard, { partitionRoot: partition });+ expect(read.records.length).toBe(2);+ expect(read.records[0]!.record.id).toBe(atBound.id);+ expect(read.diagnostics.map((d) => d.kind)).toEqual(["corrupt-line"]);+ });++ test("a blob that holds a non-canonical form of an object is not a record body", () => {+ const content = '{ "b": 1, "a": 2 }';+ writeFileSync(shard, craftedBlobLine(content) + line(makeRecord()));+ const read = readShard(shard, { partitionRoot: partition });+ expect(read.diagnostics.map((d) => d.kind)).toEqual(["corrupt-line"]);+ });++ test("a blob whose size is not the size its reference promises stays pending", () => {+ const full = makeRecord({ report: "long text" });+ const text = canonicalBodyText(full.body);+ writeBlob(partition, text);+ const onLine = {+ ...full,+ body: { [BLOB_REF_KEY]: full.sum, [BLOB_REF_BYTES_KEY]: Buffer.byteLength(text) + 1 },+ };+ writeFileSync(shard, line(onLine));+ const read = readShard(shard, { partitionRoot: partition });+ expect(read.records[0]!.bodyState).toBe("pending");+ expect(readBlobBody(partition, full.sum, Buffer.byteLength(text)).status).toBe("ok");+ });++ test("a run longer than the line cap is a corrupt line, not a pending tail", () => {+ const a = makeRecord();+ const b = makeRecord();+ const run = "x".repeat(STORE_LINE_CAP_BYTES + 10);+ writeFileSync(shard, line(a) + run + "\n" + line(b));+ const middle = readShard(shard);+ expect(middle.records.map((r) => r.record.id)).toEqual([a.id, b.id]);+ expect(middle.diagnostics.map((d) => d.kind)).toEqual(["corrupt-line"]);++ // At the end of the shard, with no newline at all, it is consumed too.+ writeFileSync(shard, line(a) + run);+ const tail = readShard(shard);+ expect(tail.records.map((r) => r.record.id)).toEqual([a.id]);+ expect(tail.diagnostics.map((d) => d.kind)).toEqual(["corrupt-line"]);+ expect(tail.pendingTailBytes).toBe(0);+ expect(tail.nextOffset).toBe(tail.size);+ });++ test("a shard larger than one read chunk is read whole, lines across chunk edges included", () => {+ // About 3 MB, so lines cross the edges of the 1 MiB read chunks.+ const records = Array.from({ length: 300 }, () => makeRecord({ pad: "p".repeat(10_000) }));+ writeFileSync(shard, records.map(line).join(""));+ const read = readShard(shard);+ expect(read.diagnostics).toEqual([]);+ expect(read.records.map((r) => r.record.id)).toEqual(records.map((r) => r.id));+ expect(read.nextOffset).toBe(read.size);+ const offsets = read.records.map((r) => r.offset);+ expect(offsets[1]).toBe(read.records[0]!.length);+ });++ test("a record whose device is not its shard directory's device is reported and skipped", () => {+ const own = makeRecord();+ const forged = buildRecord({+ hlc: { physical: Date.UTC(2026, 10, 2), counter: 0 },+ device: "dev-victim",+ agent: "agent-x",+ kind: "note",+ body: { n: 1 },+ });+ writeFileSync(shard, line(forged) + line(own));+ const read = readShard(shard);+ expect(read.records.map((r) => r.record.id)).toEqual([own.id]);+ expect(read.diagnostics.map((d) => [d.kind, d.offset])).toEqual([["corrupt-line", 0]]);+ });++ test("reading from an offset returns only later lines; an offset past the end is reported", () => {+ const a = makeRecord();+ const b = makeRecord();+ writeFileSync(shard, line(a) + line(b));+ const offset = Buffer.byteLength(line(a));+ const read = readShard(shard, { offset });+ expect(read.records.map((r) => [r.record.id, r.offset])).toEqual([[b.id, offset]]);+ const past = readShard(shard, { offset: 10_000 });+ expect(past.diagnostics.map((d) => d.kind)).toEqual(["offset-past-end"]);+ expect(past.records).toEqual([]);+ });+});diff --git a/tests/core/store/safe-fs.test.ts b/tests/core/store/safe-fs.test.tsnew file mode 100644index 00000000..b3bb867f--- /dev/null+++ b/tests/core/store/safe-fs.test.ts@@ -0,0 +1,223 @@+/**+ * The store never writes through what a sync peer can plant in a partition+ * (a symlinked directory or shard, a hard-linked shard, a symlinked blob+ * folder), and creates its directories and files for the owner only.+ *+ * Symlinks need no privilege on POSIX; on Windows creating one does, so+ * the symlink cases run where the fixture can be built.+ */+import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import {+ existsSync,+ linkSync,+ mkdirSync,+ mkdtempSync,+ readFileSync,+ rmSync,+ statSync,+ symlinkSync,+ writeFileSync,+} from "node:fs";+import { tmpdir } from "node:os";+import { dirname, join } from "node:path";++import { appendRecord, type AppendInput } from "../../../src/core/store/appender.ts";+import { readBlob, writeBlob } from "../../../src/core/store/blobs.ts";+import { readShard } from "../../../src/core/store/reader.ts";+import { readPartition } from "../../../src/core/store/state-digest.ts";+import { ShardScanner } from "../../../src/core/search/brain-store/shard-scan.ts";+import { initStore } from "../../../src/core/store/store-init.ts";+import { StoreUnsafePathError } from "../../../src/core/store/safe-fs.ts";+import { sha256Hex } from "../../../src/core/integrity/digest.ts";+import { blobPath, partitionDir, shardPath } from "../../../src/core/store/store-paths.ts";+import { IS_WINDOWS } from "../../helpers/platform.ts";+import { makeTempStore, type TempStore } from "./fixtures/temp-store.ts";++const NOV_2026 = Date.UTC(2026, 10, 6, 12, 0, 0);+const NOTE: AppendInput = {+ partition: "shared",+ stream: "events",+ kind: "note",+ agent: "a1",+ body: { text: "hello" },+};++/** Whether this host lets the test create a symlink (Windows needs a privilege). */+const CAN_SYMLINK = ((): boolean => {+ const probe = mkdtempSync(join(tmpdir(), "osb-symlink-probe-"));+ try {+ symlinkSync(probe, join(probe, "link"), "dir");+ return true;+ } catch {+ return false;+ } finally {+ rmSync(probe, { recursive: true, force: true });+ }+})();++let tmp: TempStore;+let outside: string;+beforeEach(() => {+ tmp = makeTempStore("osb-store-safe-");+ outside = join(tmp.parent, "outside");+ mkdirSync(outside, { recursive: true });+});+afterEach(() => tmp.cleanup());++function append(device = "dev-a") {+ return appendRecord(tmp.open(device), NOTE, { now: () => NOV_2026 });+}++describe("symlinks and hard links a peer can plant", () => {+ test.if(CAN_SYMLINK)(+ "a symlinked device directory is refused and nothing is written through it",+ () => {+ tmp.open("dev-a");+ const streamDir = join(partitionDir(tmp.root, "shared"), "events");+ mkdirSync(streamDir, { recursive: true });+ symlinkSync(outside, join(streamDir, "dev-a"), "dir");+ expect(() => append()).toThrow(StoreUnsafePathError);+ expect(existsSync(join(outside, "2026-11.jsonl"))).toBe(false);+ },+ );++ test.if(CAN_SYMLINK)("a symlinked stream directory is refused", () => {+ tmp.open("dev-a");+ symlinkSync(outside, join(partitionDir(tmp.root, "shared"), "events"), "dir");+ expect(() => append()).toThrow(StoreUnsafePathError);+ expect(existsSync(join(outside, "dev-a"))).toBe(false);+ });++ test.if(CAN_SYMLINK)("a shard that is a symlink to a file outside the store is refused", () => {+ tmp.open("dev-a");+ const victim = join(outside, "rc-file");+ writeFileSync(victim, "keep me\n");+ const shard = shardPath(tmp.root, "shared", { stream: "events" }, "dev-a", "2026-11");+ mkdirSync(dirname(shard), { recursive: true });+ symlinkSync(victim, shard, "file");+ expect(() => append()).toThrow(StoreUnsafePathError);+ expect(readFileSync(victim, "utf8")).toBe("keep me\n");+ });++ test("a shard hard-linked to a file outside the store is refused", () => {+ tmp.open("dev-a");+ const victim = join(outside, "config-file");+ writeFileSync(victim, "keep me\n");+ const shard = shardPath(tmp.root, "shared", { stream: "events" }, "dev-a", "2026-11");+ mkdirSync(dirname(shard), { recursive: true });+ linkSync(victim, shard);+ expect(() => append()).toThrow(StoreUnsafePathError);+ expect(readFileSync(victim, "utf8")).toBe("keep me\n");+ });++ test.if(CAN_SYMLINK)(+ "a symlinked blob folder is refused, and a symlinked blob is never read",+ () => {+ tmp.open("dev-a");+ const partition = partitionDir(tmp.root, "shared");+ const text = '{"a":1}';+ const sha = sha256Hex(text);+ const folder = dirname(blobPath(partition, sha));+ mkdirSync(dirname(folder), { recursive: true });+ symlinkSync(outside, folder, "dir");+ expect(() => writeBlob(partition, text)).toThrow(StoreUnsafePathError);+ expect(existsSync(join(outside, sha))).toBe(false);++ // A blob name that is itself a symlink, even to the right content.+ rmSync(folder);+ mkdirSync(folder);+ writeFileSync(join(outside, sha), text);+ symlinkSync(join(outside, sha), join(folder, sha), "file");+ expect(readBlob(partition, sha).status).toBe("mismatch");+ },+ );++ test.if(CAN_SYMLINK)("a shard that is a symlink is reported, never read through", () => {+ const real = append();+ const victim = join(outside, "copied-shard");+ writeFileSync(victim, readFileSync(real.path));+ const shard = shardPath(tmp.root, "shared", { stream: "events" }, "dev-a", "2026-12");+ symlinkSync(victim, shard, "file");+ const read = readShard(shard);+ expect(read.records).toEqual([]);+ expect(read.diagnostics.map((d) => d.kind)).toEqual(["not-a-file"]);+ // Read from a resume offset, the size agrees with the offset it hands back.+ const resumed = readShard(shard, { offset: 10 });+ expect(resumed.nextOffset).toBe(10);+ expect(resumed.size).toBe(10);+ });++ test.if(CAN_SYMLINK)(+ "a linked folder below a partition is never read through: reader, scanner and blobs",+ () => {+ const store = tmp.open("dev-a");+ appendRecord(store, { ...NOTE, partition: "private" }, { now: () => NOV_2026 });+ const shared = partitionDir(tmp.root, "shared");+ const privateEvents = join(partitionDir(tmp.root, "private"), "events");+ // A peer syncs `shared/events` as a link to the private events folder,+ // and `shared/ledgers/x` as a link to a folder holding a device folder.+ symlinkSync(privateEvents, join(shared, "events"), "dir");+ mkdirSync(join(shared, "ledgers"), { recursive: true });+ symlinkSync(privateEvents, join(shared, "ledgers", "x"), "dir");++ const unreadable: string[] = [];+ const shards = readPartition(shared, { onUnreadable: ({ rel }) => unreadable.push(rel) });+ expect(shards.flatMap((s) => s.all)).toEqual([]);+ expect(unreadable).toContain("events/dev-a/2026-11.jsonl");+ const throughLink = join(shared, "events", "dev-a", "2026-11.jsonl");+ expect(+ readShard(throughLink, { partitionRoot: shared }).diagnostics.map((d) => d.kind),+ ).toEqual(["not-a-file"]);++ const scanner = new ShardScanner({+ root: tmp.root,+ storeId: "s",+ deviceStateDir: join(tmp.parent, "state"),+ partitions: ["shared", "private"],+ });+ expect(scanner.scan().map((s) => s.key)).toEqual(["private/events/dev-a/2026-11.jsonl"]);++ // A blob reached through a linked blob folder is not read, even when+ // the file there holds the right content.+ const text = '{"a":1}';+ const sha = sha256Hex(text);+ const folder = dirname(blobPath(shared, sha));+ mkdirSync(dirname(folder), { recursive: true });+ writeFileSync(join(outside, sha), text);+ symlinkSync(outside, folder, "dir");+ expect(readBlob(shared, sha).status).toBe("mismatch");+ },+ );++ test.skipIf(IS_WINDOWS)("a shard that is a FIFO is reported without blocking", () => {+ const shard = shardPath(tmp.root, "shared", { stream: "events" }, "dev-a", "2026-11");+ mkdirSync(dirname(shard), { recursive: true });+ expect(Bun.spawnSync(["mkfifo", shard]).exitCode).toBe(0);+ const read = readShard(shard);+ expect(read.records).toEqual([]);+ expect(read.diagnostics.map((d) => d.kind)).toEqual(["not-a-file"]);+ });+});++function modeOf(path: string): number {+ return statSync(path).mode & 0o777;+}++describe.skipIf(IS_WINDOWS)("modes", () => {+ test("partitions, shard directories, shards and blobs are for the owner only", () => {+ const root = join(tmp.parent, "fresh");+ initStore({ root });+ expect(modeOf(partitionDir(root, "shared"))).toBe(0o700);+ expect(modeOf(partitionDir(root, "private"))).toBe(0o700);++ const result = append();+ expect(modeOf(result.path)).toBe(0o600);+ expect(modeOf(dirname(result.path))).toBe(0o700);+ expect(modeOf(dirname(dirname(result.path)))).toBe(0o700);++ const partition = partitionDir(tmp.root, "private");+ const blob = writeBlob(partition, '{"b":2}');+ expect(modeOf(blob.path)).toBe(0o600);+ expect(modeOf(dirname(blob.path))).toBe(0o700);+ });+});diff --git a/tests/core/store/state-digest.test.ts b/tests/core/store/state-digest.test.tsnew file mode 100644index 00000000..f26d0aa2--- /dev/null+++ b/tests/core/store/state-digest.test.ts@@ -0,0 +1,371 @@+/**+ * Per-partition state digests over explicit cuts (task 1.7): publishers+ * converge on one cut, an injected fold difference is reported, an+ * offline device is silent and not divergent, a machine without the+ * private partition raises no false alarm, and retired devices leave the+ * roster.+ */+import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import { appendFileSync, cpSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";+import { dirname, join } from "node:path";++import { appendRecord } from "../../../src/core/store/appender.ts";+import type { StorePartition } from "../../../src/core/store/constants.ts";+import type { RecordBody } from "../../../src/core/store/envelope.ts";+import { checkStateDigests } from "../../../src/core/store/state-digest-check.ts";+import { compareDigests } from "../../../src/core/store/state-digest-compare.ts";+import {+ buildDigestBody,+ computeCut,+ publishStateDigest,+ readPartition,+} from "../../../src/core/store/state-digest.ts";+import { openStore, type StoreHandle } from "../../../src/core/store/store-open.ts";+import { partitionDir } from "../../../src/core/store/store-paths.ts";+import { makeTempStore, type TempStore } from "./fixtures/temp-store.ts";++const DAY = 24 * 60 * 60 * 1000;+const NOW = Date.UTC(2026, 10, 6, 12, 0, 0);+const at = (ms: number) => () => ms;++function write(+ store: StoreHandle,+ ms: number,+ kind: string,+ body: RecordBody,+ partition: StorePartition = "shared",+ stream: "events" | "settings" = "events",+) {+ return appendRecord(store, { partition, stream, kind, agent: "agent-1", body }, { now: at(ms) });+}++function seedPreferences(+ a: StoreHandle,+ b: StoreHandle,+ ms: number,+ partition: StorePartition = "shared",+) {+ write(+ a,+ ms,+ "preference-set",+ { authority: "agent", preference: "p1", fields: { principle: "tabs" } },+ partition,+ );+ write(b, ms + 1, "preference-evidence", { preference: "p1", result: "applied" }, partition);+ write(b, ms + 2, "pinned-set", { authority: "agent", content: "task" }, partition);+}++function silentDevices(report: ReturnType<typeof checkStateDigests>): string[] {+ return report.findings.flatMap((f) => (f.kind === "silent" ? [f.device] : []));+}++describe("state digests", () => {+ let tmp: TempStore;+ beforeEach(() => {+ tmp = makeTempStore("osb-store-digest-");+ });+ afterEach(() => tmp.cleanup());++ test("two publishers converge on one identical cut, and their digests agree", () => {+ const a = tmp.open("dev-a");+ const b = tmp.open("dev-b");+ seedPreferences(a, b, NOW - 60_000);+ const fromA = publishStateDigest(a, { partition: "shared", agent: "doctor", now: at(NOW) });+ const fromB = publishStateDigest(b, { partition: "shared", agent: "doctor", now: at(NOW + 5) });+ expect(fromA.published && fromB.published).toBe(true);+ // B read A's digest before publishing; the digests stream is not in the cut.+ expect(fromB.body.cut).toEqual(fromA.body.cut);+ expect(fromB.body.cut_hash).toBe(fromA.body.cut_hash);+ expect(fromB.body.folds).toEqual(fromA.body.folds);+ expect(fromA.body.cut.map((e) => e.shard)).toEqual([+ "events/dev-a/2026-11.jsonl",+ "events/dev-b/2026-11.jsonl",+ ]);++ const report = checkStateDigests(a, { now: at(NOW + 10) });+ const shared = report.partitions.find((p) => p.partition === "shared")!;+ expect(shared.comparedCuts).toEqual([+ { cutHash: fromA.body.cut_hash, devices: ["dev-a", "dev-b"] },+ ]);+ expect(report.findings).toEqual([]);+ });++ test("an unchanged state is not republished within the interval, and is after it", () => {+ const a = tmp.open("dev-a");+ write(a, NOW - 1000, "pinned-set", { authority: "human", content: "x" });+ expect(+ publishStateDigest(a, { partition: "shared", agent: "doctor", now: at(NOW) }).published,+ ).toBe(true);+ const again = publishStateDigest(a, {+ partition: "shared",+ agent: "doctor",+ now: at(NOW + 1000),+ });+ expect(again).toMatchObject({ published: false, reason: "unchanged" });+ const later = publishStateDigest(a, {+ partition: "shared",+ agent: "doctor",+ now: at(NOW + 2 * DAY),+ });+ expect(later.published).toBe(true);+ if (later.published) expect(later.body.cut_hash).toBe(again.body.cut_hash);+ });++ test("an injected fold difference over the same cut is reported with both devices and the fold", () => {+ const a = tmp.open("dev-a");+ const b = tmp.open("dev-b");+ seedPreferences(a, b, NOW - 60_000);+ const good = publishStateDigest(a, { partition: "shared", agent: "doctor", now: at(NOW) });+ // dev-b runs a release whose preference fold differs: same cut, other hash.+ const wrong = { ...good.body, folds: { ...good.body.folds, preferences: "0".repeat(64) } };+ const bad = appendRecord(+ b,+ {+ partition: "shared",+ stream: "digests",+ kind: "state-digest",+ agent: "doctor",+ body: wrong,+ },+ { now: at(NOW + 5) },+ );++ for (const machine of [a, b]) {+ const report = checkStateDigests(machine, { now: at(NOW + 10) });+ expect(report.findings).toEqual([+ {+ kind: "divergent",+ partition: "shared",+ fold: "preferences",+ cutHash: good.body.cut_hash,+ devices: [+ {+ device: "dev-a",+ hash: good.body.folds.preferences,+ digest: good.published ? good.append.record.id : "",+ },+ { device: "dev-b", hash: "0".repeat(64), digest: bad.record.id },+ ],+ },+ ]);+ }+ });++ test("an offline device is reported as silent, never as divergent, and does not stall the others", () => {+ const a = tmp.open("dev-a");+ const b = tmp.open("dev-b");+ const laptop = tmp.open("laptop");+ // The laptop wrote and published two weeks ago, then went offline.+ write(laptop, NOW - 14 * DAY, "pinned-set", { authority: "agent", content: "old" });+ publishStateDigest(laptop, {+ partition: "shared",+ agent: "doctor",+ now: at(NOW - 14 * DAY + 10),+ });+ seedPreferences(a, b, NOW - 60_000);+ publishStateDigest(a, { partition: "shared", agent: "doctor", now: at(NOW) });+ publishStateDigest(b, { partition: "shared", agent: "doctor", now: at(NOW + 5) });++ const report = checkStateDigests(a, { now: at(NOW + 10) });+ const shared = report.partitions.find((p) => p.partition === "shared")!;+ expect(shared.roster.devices.map((d) => d.device)).toEqual(["dev-a", "dev-b", "laptop"]);+ expect(shared.comparedCuts.map((c) => c.devices)).toEqual([["dev-a", "dev-b"]]);+ expect(report.findings).toEqual([+ {+ kind: "silent",+ partition: "shared",+ device: "laptop",+ lastDigestMs: NOW - 14 * DAY + 10,+ lastRecordMs: NOW - 14 * DAY + 10,+ },+ ]);+ });++ test("a machine without the private partition raises no false alarm on either side", () => {+ const a = tmp.open("dev-a");+ const b = tmp.open("dev-b");+ seedPreferences(a, b, NOW - 60_000);+ seedPreferences(a, b, NOW - 30_000, "private");+ // The server syncs only shared: its store root holds no private folder.+ const serverRoot = join(tmp.parent, "server-store");+ cpSync(join(tmp.root, "shared"), join(serverRoot, "shared"), { recursive: true });+ const server = openStore({ root: serverRoot, device: "server", dirs: tmp.dirs("server") });+ expect([...server.partitions]).toEqual(["shared"]);++ for (const laptop of [a, b]) {+ publishStateDigest(laptop, { partition: "shared", agent: "doctor", now: at(NOW) });+ publishStateDigest(laptop, { partition: "private", agent: "doctor", now: at(NOW) });+ }+ // The laptops' shared digests reach the server; the server publishes its own.+ cpSync(join(tmp.root, "shared", "digests"), join(serverRoot, "shared", "digests"), {+ recursive: true,+ });+ const fromServer = publishStateDigest(server, {+ partition: "shared",+ agent: "doctor",+ now: at(NOW + 5),+ });+ cpSync(join(serverRoot, "shared", "digests"), join(tmp.root, "shared", "digests"), {+ recursive: true,+ });++ const onServer = checkStateDigests(server, { now: at(NOW + 10) });+ expect(onServer.skipped).toEqual(["private"]);+ expect(onServer.partitions.map((p) => p.partition)).toEqual(["shared"]);+ expect(onServer.partitions[0]!.comparedCuts).toEqual([+ { cutHash: fromServer.body.cut_hash, devices: ["dev-a", "dev-b", "server"] },+ ]);+ expect(onServer.findings).toEqual([]);++ const onLaptop = checkStateDigests(a, { now: at(NOW + 10) });+ const priv = onLaptop.partitions.find((p) => p.partition === "private")!;+ expect(priv.roster.devices.map((d) => d.device)).toEqual(["dev-a", "dev-b"]);+ expect(onLaptop.findings).toEqual([]);+ });++ test("a human device-retire record takes a device off the roster; an agent one does not", () => {+ const a = tmp.open("dev-a");+ const old = tmp.open("old-pc");+ write(old, NOW - 20 * DAY, "pinned-set", { authority: "agent", content: "x" });+ write(+ a,+ NOW - 1000,+ "device-retire",+ { authority: "agent", device: "old-pc" },+ "shared",+ "settings",+ );+ expect(silentDevices(checkStateDigests(a, { now: at(NOW) }))).toContain("old-pc");++ write(+ a,+ NOW - 500,+ "device-retire",+ { authority: "human", device: "old-pc" },+ "shared",+ "settings",+ );+ const report = checkStateDigests(a, { now: at(NOW) });+ const shared = report.partitions.find((p) => p.partition === "shared")!;+ expect(shared.roster.retired).toEqual(["old-pc"]);+ expect(silentDevices(report)).not.toContain("old-pc");++ // The retired id writes again after its retire record: back on the roster.+ write(old, NOW + 100, "pinned-set", { authority: "agent", content: "back" });+ const back = checkStateDigests(a, { now: at(NOW + 200) }).partitions.find(+ (p) => p.partition === "shared",+ )!;+ expect(back.roster.devices.map((d) => d.device)).toContain("old-pc");+ });++ test("devices outside the 30-day window are not on the roster; new devices get a grace period", () => {+ const a = tmp.open("dev-a");+ const gone = tmp.open("gone");+ write(gone, NOW - 40 * DAY, "pinned-set", { authority: "agent", content: "x" });+ write(a, NOW - 2 * DAY, "pinned-set", { authority: "agent", content: "y" });+ const report = checkStateDigests(a, { now: at(NOW) });+ const shared = report.partitions.find((p) => p.partition === "shared")!;+ expect(shared.roster.devices.map((d) => d.device)).toEqual(["dev-a"]);+ expect(report.findings).toEqual([]);+ });++ test("a torn tail is not part of the cut, and a pending blob is counted in it", () => {+ const a = tmp.open("dev-a");+ const first = write(a, NOW, "pinned-set", { authority: "agent", content: "x" });+ appendFileSync(first.path, '{"v":1,"id":"01K');+ const big = write(a, NOW + 1, "pinned-set", {+ authority: "agent",+ content: "y".repeat(20_000),+ });+ expect(big.spilled).toBe(true);+ const withBlob = computeCut(readPartition(partitionDir(tmp.root, "shared")));+ expect(withBlob).toEqual([{ shard: first.rel, count: 2, last: big.record.id, pending: 0 }]);++ // A machine that has the shard but not yet the blob has a different cut.+ const other = join(tmp.parent, "other");+ cpSync(join(tmp.root, "shared", "events"), join(other, "events"), { recursive: true });+ const shards = readPartition(other);+ expect(computeCut(shards)).toEqual([+ { shard: first.rel, count: 2, last: big.record.id, pending: 1 },+ ]);+ expect(buildDigestBody("shared", shards).cut_hash).not.toBe(+ buildDigestBody("shared", readPartition(partitionDir(tmp.root, "shared"))).cut_hash,+ );+ });++ test("machines that receive shards in different orders, some cut mid-line, reach one digest", () => {+ const writers = ["dev-a", "dev-b", "dev-c"].map((device) => tmp.open(device));+ writers.forEach((store, i) => {+ for (let n = 0; n < 5; n++) {+ const ms = NOW - 10_000 + n * 7 + i;+ write(store, ms, "preference-set", {+ authority: n % 2 === 0 ? "agent" : "model",+ preference: `p${n % 2}`,+ fields: { principle: `${store.device}-${n}` },+ });+ write(store, ms + 1, "pinned-set", { authority: "agent", content: `${store.device}-${n}` });+ }+ });+ const source = readPartition(partitionDir(tmp.root, "shared"));+ const deliver = (machine: string, order: number[], cutFirst: boolean) => {+ const root = join(tmp.parent, machine);+ for (const index of order) {+ const shard = source[index]!;+ const target = join(root, ...shard.rel.split("/"));+ mkdirSync(dirname(target), { recursive: true });+ const bytes = readFileSync(join(partitionDir(tmp.root, "shared"), ...shard.rel.split("/")));+ // A sync tool still copying: the file ends mid-record first.+ if (cutFirst) writeFileSync(target, bytes.subarray(0, Math.floor(bytes.length * 0.6)));+ }+ const early = buildDigestBody("shared", readPartition(root));+ for (const index of order) {+ const shard = source[index]!;+ cpSync(+ join(partitionDir(tmp.root, "shared"), ...shard.rel.split("/")),+ join(root, ...shard.rel.split("/")),+ );+ }+ return { early, final: buildDigestBody("shared", readPartition(root)) };+ };+ const one = deliver("machine-1", [0, 1, 2], true);+ const two = deliver("machine-2", [2, 0, 1], false);+ // Machine 2 had nothing before its copy: an empty cut, not a partial one.+ expect(two.early.cut).toEqual([]);+ const reference = buildDigestBody("shared", source);+ expect(one.early.cut_hash).not.toBe(reference.cut_hash);+ expect(one.final).toEqual(reference);+ expect(two.final).toEqual(reference);+ });++ test("digests of another partition and malformed digests are ignored", () => {+ const a = tmp.open("dev-a");+ write(a, NOW, "pinned-set", { authority: "agent", content: "x" });+ const body = publishStateDigest(a, {+ partition: "shared",+ agent: "doctor",+ now: at(NOW + 1),+ }).body;+ const records = readPartition(partitionDir(tmp.root, "shared")).flatMap((s) => s.all);+ const foreign = {+ ...records.at(-1)!,+ id: "01KZZZZZZZZZZZZZZZZZZZZZZZ",+ device: "dev-b",+ body: { ...body, partition: "private" },+ };+ const broken = {+ ...records.at(-1)!,+ id: "01KZZZZZZZZZZZZZZZZZZZZZZY",+ device: "dev-c",+ body: { partition: "shared" },+ };+ const result = compareDigests({+ partition: "shared",+ records: [...records, foreign, broken],+ retireRecords: [],+ nowMs: NOW + 2,+ });+ expect(result.comparedCuts).toEqual([]);+ expect(result.findings).toEqual([]);+ });+});diff --git a/tests/core/store/store-init.test.ts b/tests/core/store/store-init.test.tsnew file mode 100644index 00000000..828b8d89--- /dev/null+++ b/tests/core/store/store-init.test.ts@@ -0,0 +1,230 @@+/**+ * `o2b store init` (`store-init.ts`): the only way a store is created.+ * It writes one store id into every requested partition, completes a+ * half-created store with the id it already has, and refuses an existing+ * store, a partial one, and partitions of two stores.+ */+import { afterEach, beforeEach, describe, expect, spyOn, test } from "bun:test";+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import {+ STORE_FORMAT_FILE,+ STORE_FORMAT_VERSION,+ STORE_IDENTITY_FILE,+ STORE_ROOT_ENV,+} from "../../../src/core/store/constants.ts";+import * as blobs from "../../../src/core/store/blobs.ts";+import { shippedFormatDoc } from "../../../src/core/store/format-doc.ts";+import { initStore, StoreInitRefusal } from "../../../src/core/store/store-init.ts";+import { inspectStore } from "../../../src/core/store/store-open.ts";+import { runCli } from "../../helpers/run-cli.ts";++let parent: string;+let root: string;++beforeEach(() => {+ parent = mkdtempSync(join(tmpdir(), "osb-store-init-"));+ root = join(parent, "store");+});+afterEach(() => rmSync(parent, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 }));++function identity(partition: string): unknown {+ return JSON.parse(readFileSync(join(root, partition, STORE_IDENTITY_FILE), "utf8"));+}++function refusal(run: () => unknown): StoreInitRefusal {+ try {+ run();+ } catch (err) {+ if (err instanceof StoreInitRefusal) return err;+ throw err;+ }+ throw new Error("init did not refuse");+}++describe("store init", () => {+ test("creates both partitions with one store id and the format document everywhere", () => {+ const result = initStore({ root });+ expect(result.status).toBe("created");+ expect(result.partitions).toEqual(["shared", "private"]);+ for (const partition of ["shared", "private"]) {+ expect(identity(partition)).toEqual({+ store_id: result.storeId,+ format: STORE_FORMAT_VERSION,+ });+ }+ for (const dir of [root, join(root, "shared"), join(root, "private")]) {+ expect(readFileSync(join(dir, STORE_FORMAT_FILE), "utf8")).toBe(shippedFormatDoc());+ }+ expect(inspectStore(root)?.storeId).toBe(result.storeId);+ });++ test("a machine that must not hold private records creates shared only", () => {+ const result = initStore({ root, partitions: ["shared"] });+ expect(result.partitions).toEqual(["shared"]);+ expect(existsSync(join(root, "private"))).toBe(false);+ });++ test("refuses when the store already exists and leaves it as it was", () => {+ const first = initStore({ root });+ const before = readFileSync(join(root, "shared", STORE_IDENTITY_FILE), "utf8");+ const err = refusal(() => initStore({ root }));+ expect(err.reason).toBe("exists");+ expect(err.message).toContain(first.storeId);+ expect(readFileSync(join(root, "shared", STORE_IDENTITY_FILE), "utf8")).toBe(before);+ });++ test("a re-run completes a half-created store with the id it already has", () => {+ const first = initStore({ root });+ // The first run stopped after shared: private has its folder but no identity.+ rmSync(join(root, "private", STORE_IDENTITY_FILE));+ const second = initStore({ root });+ expect(second.status).toBe("completed");+ expect(second.storeId).toBe(first.storeId);+ expect(second.created).toEqual(["private"]);+ expect(identity("private")).toEqual({ store_id: first.storeId, format: STORE_FORMAT_VERSION });+ });++ test("a shared-only store gains private later with the same id", () => {+ const first = initStore({ root, partitions: ["shared"] });+ const second = initStore({ root });+ expect(second.storeId).toBe(first.storeId);+ expect(second.partitions).toEqual(["shared", "private"]);+ });++ test("a partition folder with records but no identity is refused by name, not given a new id", () => {+ initStore({ root, partitions: ["shared"] });+ mkdirSync(join(root, "private", "events"), { recursive: true });+ writeFileSync(join(root, "private", "events", "dev-a.jsonl"), "{}\n");+ const err = refusal(() => initStore({ root }));+ expect(err.reason).toBe("partial");+ expect(err.message).toContain(STORE_IDENTITY_FILE);+ expect(err.message).toContain("private");+ expect(existsSync(join(root, "private", STORE_IDENTITY_FILE))).toBe(false);+ });++ test("records synced without any identity file are refused, so no store id is minted", () => {+ mkdirSync(join(root, "shared", "events"), { recursive: true });+ writeFileSync(join(root, "shared", "events", "dev-a.jsonl"), "{}\n");+ expect(refusal(() => initStore({ root })).reason).toBe("partial");+ expect(inspectStore(root)).toBeNull();+ });++ test("sync tool markers and temp files do not make a folder partial", () => {+ mkdirSync(join(root, "shared", ".stfolder"), { recursive: true });+ writeFileSync(join(root, "shared", ".tmp-store.json.1"), "");+ expect(initStore({ root }).status).toBe("created");+ });++ test("partitions of two different stores are refused", () => {+ initStore({ root, partitions: ["shared"] });+ mkdirSync(join(root, "private"), { recursive: true });+ writeFileSync(+ join(root, "private", STORE_IDENTITY_FILE),+ `${JSON.stringify({ store_id: "01JBZ3NDEKTSV4RRFFQ69G5FAV", format: 1 })}\n`,+ );+ expect(refusal(() => initStore({ root })).reason).toBe("mixed");+ });++ test("an identity file that holds no store id is refused as corrupt", () => {+ mkdirSync(join(root, "shared"), { recursive: true });+ writeFileSync(join(root, "shared", STORE_IDENTITY_FILE), "{");+ expect(refusal(() => initStore({ root })).reason).toBe("corrupt");+ });++ test("an empty partition list is a caller error, not a refusal", () => {+ expect(() => initStore({ root, partitions: [] })).toThrow(TypeError);+ });+});++function env(): Record<string, string> {+ return { [STORE_ROOT_ENV]: root, HOME: join(parent, "home") };+}++describe("o2b store init", () => {+ test("creates the store, then refuses a second run with exit 1", async () => {+ const created = await runCli(["store", "init", "--json"], { env: env() });+ expect(created.returncode).toBe(0);+ const body = JSON.parse(created.stdout) as { ok: boolean; status: string; storeId: string };+ expect(body.ok).toBe(true);+ expect(body.status).toBe("created");+ expect(inspectStore(root)?.storeId).toBe(body.storeId);++ const again = await runCli(["store", "init"], { env: env() });+ expect(again.returncode).toBe(1);+ expect(again.stderr).toContain("already exists");+ });++ test("--partitions shared leaves private out", async () => {+ const r = await runCli(["store", "init", "--partitions", "shared"], { env: env() });+ expect(r.returncode).toBe(0);+ expect([...(inspectStore(root)?.partitions ?? [])]).toEqual(["shared"]);+ });++ test("concurrent runs agree on one store and only one reports creating it", async () => {+ // The sandboxed HOME also holds Bun's transpiler cache. One run first+ // fills it, so the six racing children start warm instead of each+ // transpiling the whole CLI at once (26 to 32 s on the Windows runner).+ const warm = await runCli(["version"], { env: env(), subprocess: true });+ expect(warm.returncode).toBe(0);+ const runs = await Promise.all(+ [1, 2, 3, 4, 5, 6].map(() =>+ runCli(["store", "init", "--json"], { env: env(), subprocess: true }),+ ),+ );+ const answers = runs.map((r) => JSON.parse(r.stdout) as Record<string, unknown>);+ const done = answers.filter((a) => a["ok"] === true);+ // A run that lost is refused for the store the others made, never for another reason.+ const refused = answers.filter((a) => a["ok"] !== true).map((a) => a["reason"]);+ expect(refused.filter((reason) => reason !== "exists" && reason !== "partial")).toEqual([]);+ expect(done.length + refused.length).toBe(answers.length);+ expect(done.filter((a) => a["status"] === "created").length).toBe(1);+ const written = done.flatMap((a) => a["created"] as string[]);+ expect(written.toSorted()).toEqual(["private", "shared"]);+ expect(new Set(done.map((a) => a["storeId"]))).toEqual(new Set([inspectStore(root)?.storeId]));+ // Six cold CLI processes start at once: a loaded CI runner needs more than the 5 s default.+ }, 30_000);++ test("with --json a usage error is a JSON answer too", async () => {+ const r = await runCli(["store", "init", "--partitions", "secret", "--json"], { env: env() });+ expect(r.returncode).toBe(2);+ expect(JSON.parse(r.stdout)).toMatchObject({ ok: false, reason: "usage" });+ });++ test("with --json a filesystem error on the store root is a JSON answer", async () => {+ // The root sits under a regular file, so no folder can be made there.+ writeFileSync(join(parent, "blocker"), "");+ root = join(parent, "blocker", "store");+ const r = await runCli(["store", "init", "--json"], { env: env() });+ expect(r.returncode).toBe(1);+ expect(JSON.parse(r.stdout)).toMatchObject({ ok: false, reason: "error" });+ });++ test("an unknown partition name is a usage error that creates nothing", async () => {+ const r = await runCli(["store", "init", "--partitions", "secret"], { env: env() });+ expect(r.returncode).toBe(2);+ expect(existsSync(root)).toBe(false);+ });+});++describe("an init that loses the race to one that stopped half way", () => {+ test("an identity file that never gets its id is refused as corrupt, with the way out", () => {+ // The winner created the name with an exclusive create (no hard links+ // on its filesystem) and stopped before writing the id into it.+ const lost = spyOn(blobs, "createFileOnce").mockImplementation((path: string) => {+ mkdirSync(join(path, ".."), { recursive: true });+ writeFileSync(path, "");+ return false;+ });+ try {+ const err = refusal(() => initStore({ root }));+ expect(err.reason).toBe("corrupt");+ expect(err.message).toContain(join(root, "shared", STORE_IDENTITY_FILE));+ expect(err.message).toContain("remove the file and run `o2b store init` again");+ } finally {+ lost.mockRestore();+ }+ });+});diff --git a/tests/core/store/store-open.test.ts b/tests/core/store/store-open.test.tsnew file mode 100644index 00000000..a4109eb9--- /dev/null+++ b/tests/core/store/store-open.test.ts@@ -0,0 +1,106 @@+import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import { existsSync, readFileSync, rmSync, writeFileSync } from "node:fs";+import { join } from "node:path";++import {+ STORE_FORMAT_FILE,+ STORE_FORMAT_VERSION,+ STORE_IDENTITY_FILE,+} from "../../../src/core/store/constants.ts";+import { shippedFormatDoc } from "../../../src/core/store/format-doc.ts";+import { NoStoreError, openStore, StoreOpenError } from "../../../src/core/store/store-open.ts";+import { makeTempStore, type TempStore } from "./fixtures/temp-store.ts";++describe("opening a brain store", () => {+ let tmp: TempStore;+ beforeEach(() => {+ tmp = makeTempStore("osb-store-open-");+ });+ afterEach(() => tmp.cleanup());++ test("an initialised store opens with both partitions and a device-local state dir outside it", () => {+ const store = tmp.open("dev-a");+ expect([...store.partitions].toSorted()).toEqual(["private", "shared"]);+ expect(store.deviceStateDir).toContain(store.storeId);+ expect(store.deviceStateDir.startsWith(tmp.root)).toBe(false);+ });++ test("reopening keeps the store id", () => {+ expect(tmp.open("dev-a").storeId).toBe(tmp.open("dev-b").storeId);+ });++ test("a machine that holds only the shared partition does not grow a private one", () => {+ tmp.open("dev-a");+ rmSync(join(tmp.root, "private"), { recursive: true, force: true });+ const store = tmp.open("dev-b");+ expect([...store.partitions]).toEqual(["shared"]);+ expect(existsSync(join(tmp.root, "private"))).toBe(false);+ });++ test("partitions of two different stores under one root are refused", () => {+ tmp.open("dev-a");+ writeFileSync(+ join(tmp.root, "private", STORE_IDENTITY_FILE),+ `${JSON.stringify({ store_id: "01JBZ3NDEKTSV4RRFFQ69G5FAV", format: 1 })}\n`,+ );+ expect(() => tmp.open("dev-a")).toThrow(/different stores/);+ });++ test("an invalid device id is refused by name", () => {+ expect(() => openStore({ root: tmp.root, device: "", dirs: tmp.dirs("x") })).toThrow(+ StoreOpenError,+ );+ });++ test("a root without a store is refused with the init hint, and nothing is created", () => {+ expect(() => openStore({ root: tmp.root, device: "dev-a", dirs: tmp.dirs("a") })).toThrow(+ NoStoreError,+ );+ expect(() => openStore({ root: tmp.root, device: "dev-a", dirs: tmp.dirs("a") })).toThrow(+ /o2b store init/,+ );+ expect(existsSync(tmp.root)).toBe(false);+ });++ test("a root that is a regular file is refused as not a directory, not as a missing store", () => {+ writeFileSync(tmp.root, "not a directory");+ let caught: unknown;+ try {+ openStore({ root: tmp.root, device: "dev-a", dirs: tmp.dirs("a") });+ } catch (err) {+ caught = err;+ }+ expect(caught).toBeInstanceOf(StoreOpenError);+ expect(caught).not.toBeInstanceOf(NoStoreError);+ expect((caught as Error).message).toContain("not a directory");+ });++ test("a newer format document on disk is never downgraded; an older one is refreshed", () => {+ tmp.open("dev-a");+ const sharedDoc = join(tmp.root, "shared", STORE_FORMAT_FILE);+ const newer = "<!-- open-second-brain-store-format: 99 -->\n# newer\n";+ writeFileSync(sharedDoc, newer);+ tmp.open("dev-a");+ expect(readFileSync(sharedDoc, "utf8")).toBe(newer);+ writeFileSync(sharedDoc, "<!-- open-second-brain-store-format: 0 -->\n# older\n");+ tmp.open("dev-a");+ expect(readFileSync(sharedDoc, "utf8")).toBe(shippedFormatDoc());+ });++ test("a copy of the same format version with other prose is left alone, so releases do not churn it", () => {+ tmp.open("dev-a");+ const sharedDoc = join(tmp.root, "shared", STORE_FORMAT_FILE);+ const sameVersion = `<!-- open-second-brain-store-format: ${STORE_FORMAT_VERSION} -->\n# other prose\n`;+ writeFileSync(sharedDoc, sameVersion);+ tmp.open("dev-a");+ expect(readFileSync(sharedDoc, "utf8")).toBe(sameVersion);+ });++ test("the root copy of the format document is refreshed on an existing store too", () => {+ tmp.open("dev-a");+ const rootDoc = join(tmp.root, STORE_FORMAT_FILE);+ writeFileSync(rootDoc, "<!-- open-second-brain-store-format: 0 -->\n# older\n");+ tmp.open("dev-b");+ expect(readFileSync(rootDoc, "utf8")).toBe(shippedFormatDoc());+ });+});diff --git a/tests/core/store/store-paths.test.ts b/tests/core/store/store-paths.test.tsnew file mode 100644index 00000000..9f16d672--- /dev/null+++ b/tests/core/store/store-paths.test.ts@@ -0,0 +1,202 @@+import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import { mkdirSync, mkdtempSync, rmSync, symlinkSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import { STORE_ROOT_CONFIG_KEY, STORE_ROOT_ENV } from "../../../src/core/store/constants.ts";+import {+ blobPath,+ deviceStateDirFor,+ isPathInside,+ partitionDir,+ resolveStoreRoot,+ shardPath,+ shardRelPath,+ StoreRootInsideVaultError,+ type StoreRootSource,+} from "../../../src/core/store/store-paths.ts";++const posixSource = (over: Partial<StoreRootSource> = {}): StoreRootSource => ({+ platform: "linux",+ home: "/home/u",+ env: {},+ config: {},+ configPath: "/home/u/.config/open-second-brain/config.yaml",+ vault: "/home/u/vault",+ ...over,+});++const windowsSource = (over: Partial<StoreRootSource> = {}): StoreRootSource => ({+ platform: "win32",+ home: "C:\\Users\\u",+ env: { LOCALAPPDATA: "C:\\Users\\u\\AppData\\Local" },+ config: {},+ configPath: "C:\\Users\\u\\AppData\\Local\\open-second-brain\\config.yaml",+ vault: "D:\\Vault",+ ...over,+});++describe("store root resolution", () => {+ test("defaults to the per-user data directory", () => {+ expect(resolveStoreRoot(posixSource())).toEqual({+ root: "/home/u/.local/share/open-second-brain/store",+ origin: "default",+ });+ });++ test("the default honours XDG_DATA_HOME", () => {+ expect(resolveStoreRoot(posixSource({ env: { XDG_DATA_HOME: "/data" } })).root).toBe(+ "/data/open-second-brain/store",+ );+ });++ test("the config key overrides the default, with ~ and relative values resolved", () => {+ expect(+ resolveStoreRoot(posixSource({ config: { [STORE_ROOT_CONFIG_KEY]: "~/sync/brain" } })),+ ).toEqual({+ root: "/home/u/sync/brain",+ origin: "config",+ });+ expect(+ resolveStoreRoot(posixSource({ config: { [STORE_ROOT_CONFIG_KEY]: "brain" } })).root,+ ).toBe("/home/u/.config/open-second-brain/brain");+ });++ test("the environment variable beats the config key", () => {+ const source = posixSource({+ env: { [STORE_ROOT_ENV]: "/srv/brain" },+ config: { [STORE_ROOT_CONFIG_KEY]: "/elsewhere" },+ });+ expect(resolveStoreRoot(source)).toEqual({ root: "/srv/brain", origin: "env" });+ });++ test("a root inside the vault is refused with an error naming the setting", () => {+ const fromConfig = posixSource({ config: { [STORE_ROOT_CONFIG_KEY]: "/home/u/vault/.brain" } });+ expect(() => resolveStoreRoot(fromConfig)).toThrow(StoreRootInsideVaultError);+ expect(() => resolveStoreRoot(fromConfig)).toThrow(STORE_ROOT_CONFIG_KEY);+ const fromEnv = posixSource({ env: { [STORE_ROOT_ENV]: "/home/u/vault" } });+ expect(() => resolveStoreRoot(fromEnv)).toThrow(STORE_ROOT_ENV);+ });++ test("a sibling whose name only starts with the vault's is not inside it", () => {+ expect(+ resolveStoreRoot(posixSource({ env: { [STORE_ROOT_ENV]: "/home/u/vault-brain" } })).root,+ ).toBe("/home/u/vault-brain");+ });++ test("a child folder whose name starts with two dots is inside the vault", () => {+ const dotted = posixSource({ env: { [STORE_ROOT_ENV]: "/home/u/vault/..store" } });+ expect(() => resolveStoreRoot(dotted)).toThrow(StoreRootInsideVaultError);+ expect(isPathInside("/home/u/vault/..store", "/home/u/vault", "linux")).toBe(true);+ expect(isPathInside("/home/u/other", "/home/u/vault", "linux")).toBe(false);+ expect(isPathInside("/home/u", "/home/u/vault", "linux")).toBe(false);+ });++ test("macOS compares without case, like its default volumes", () => {+ const mac = posixSource({+ platform: "darwin",+ home: "/Users/u",+ vault: "/Users/u/Notes/Vault",+ env: { [STORE_ROOT_ENV]: "/Users/u/notes/vault/store" },+ });+ expect(() => resolveStoreRoot(mac)).toThrow(StoreRootInsideVaultError);+ expect(isPathInside("/Users/u/notes/vault/store", "/Users/u/Notes/Vault", "linux")).toBe(false);+ });++ test("no vault configured means nothing to refuse", () => {+ expect(+ resolveStoreRoot(posixSource({ vault: null, env: { [STORE_ROOT_ENV]: "/home/u/vault/x" } }))+ .root,+ ).toBe("/home/u/vault/x");+ });++ describe("Windows paths", () => {+ test("defaults under LOCALAPPDATA", () => {+ expect(resolveStoreRoot(windowsSource()).root).toBe(+ "C:\\Users\\u\\AppData\\Local\\open-second-brain\\store",+ );+ });++ test("expands ~\\ and anchors a relative value to the config directory", () => {+ expect(+ resolveStoreRoot(windowsSource({ config: { [STORE_ROOT_CONFIG_KEY]: "~\\Brain" } })).root,+ ).toBe("C:\\Users\\u\\Brain");+ expect(+ resolveStoreRoot(windowsSource({ config: { [STORE_ROOT_CONFIG_KEY]: "brain" } })).root,+ ).toBe("C:\\Users\\u\\AppData\\Local\\open-second-brain\\brain");+ });++ test("refuses a root inside the vault regardless of case and separator", () => {+ const inside = windowsSource({ env: { [STORE_ROOT_ENV]: "d:/vault/Store" } });+ expect(() => resolveStoreRoot(inside)).toThrow(StoreRootInsideVaultError);+ expect(resolveStoreRoot(windowsSource({ env: { [STORE_ROOT_ENV]: "D:\\Brain" } })).root).toBe(+ "D:\\Brain",+ );+ });+ });+});++describe("store root inside the vault through a symlink", () => {+ let dir: string;+ beforeEach(() => {+ dir = mkdtempSync(join(tmpdir(), "osb-store-paths-"));+ });+ afterEach(() => {+ rmSync(dir, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });+ });++ test.skipIf(process.platform === "win32")("is refused once the link is resolved", () => {+ const vault = join(dir, "vault");+ mkdirSync(join(vault, "inner"), { recursive: true });+ const link = join(dir, "link");+ symlinkSync(join(vault, "inner"), link);+ const source = posixSource({ home: dir, vault, env: { [STORE_ROOT_ENV]: link } });+ expect(() => resolveStoreRoot(source)).toThrow(StoreRootInsideVaultError);+ });+});++describe("store layout paths", () => {+ test("shards are named by partition, stream, device and month", () => {+ expect(shardPath("/s", "shared", { stream: "events" }, "dev-a", "2026-11")).toBe(+ join("/s", "shared", "events", "dev-a", "2026-11.jsonl"),+ );+ expect(+ shardPath("/s", "private", { stream: "ledgers", ledger: "receipts" }, "dev-a", "2026-01"),+ ).toBe(join("/s", "private", "ledgers", "receipts", "dev-a", "2026-01.jsonl"));+ expect(shardRelPath({ stream: "ledgers", ledger: "receipts" }, "dev-a", "2026-01")).toBe(+ "ledgers/receipts/dev-a/2026-01.jsonl",+ );+ });++ test("a ledger stream needs a valid ledger name, other streams take none", () => {+ expect(() => shardRelPath({ stream: "ledgers" }, "dev-a", "2026-01")).toThrow();+ expect(() => shardRelPath({ stream: "ledgers", ledger: "../x" }, "dev-a", "2026-01")).toThrow();+ expect(() => shardRelPath({ stream: "events", ledger: "x" }, "dev-a", "2026-01")).toThrow();+ expect(() => shardRelPath({ stream: "events" }, "../dev", "2026-01")).toThrow();+ });++ test("blobs are fanned out by the first two hex characters", () => {+ const sha = "ab".padEnd(64, "0");+ expect(blobPath(partitionDir("/s", "shared"), sha)).toBe(+ join("/s", "shared", "blobs", "ab", sha),+ );+ expect(() => blobPath("/s/shared", "not-a-sha")).toThrow();+ });++ test("the device-local directory is keyed by store id and lives in the state directory", () => {+ const id = "01JBZ3NDEKTSV4RRFFQ69G5FAV";+ expect(deviceStateDirFor(id, { platform: "linux", home: "/home/u", env: {} })).toBe(+ "/home/u/.local/state/open-second-brain/stores/01JBZ3NDEKTSV4RRFFQ69G5FAV",+ );+ expect(+ deviceStateDirFor(id, {+ platform: "win32",+ home: "C:\\Users\\u",+ env: { LOCALAPPDATA: "C:\\L" },+ }),+ ).toBe("C:\\L\\open-second-brain\\stores\\01JBZ3NDEKTSV4RRFFQ69G5FAV");+ expect(() =>+ deviceStateDirFor("../../x", { platform: "linux", home: "/h", env: {} }),+ ).toThrow();+ });+});diff --git a/tests/helpers/tool-probe-catalogue.ts b/tests/helpers/tool-probe-catalogue.tsindex 14da21bc..db1c5a72 100644--- a/tests/helpers/tool-probe-catalogue.ts+++ b/tests/helpers/tool-probe-catalogue.ts@@ -299,8 +299,10 @@ export const REASONS_REACHING_OWNER_CONTENT: ReadonlySet<string> = new Set([REAS// 106 -> 107 -> 108, the second hop the agent-presence wave (t_635e3e72):// brain_skill_rewrite_status joins driven beside brain_skill_proposals,// one ownerless recipe - ids and rates only, nothing owner-tagged to reach.-export const PROBE_ENTRY_COUNT = 108;-export const PROBE_RECIPE_COUNT = 251;+// 108 -> 109, the brain store wave: brain_changes, one ownerless recipe -+// record ids from the index, and store records carry no `owner:`.+export const PROBE_ENTRY_COUNT = 109;+export const PROBE_RECIPE_COUNT = 252;export const PROBE_TWO_SIDED_COUNT = 32;/**@@ -524,6 +526,13 @@ export const NON_CONTENT: ReadonlyArray<ProbeEntry> = [},],},+ {+ // The brain store change probe answers record ids from the index; a+ // store record envelope carries an `agent`, never an `owner:`, and the+ // fixture vault holds no store at all, so the probe reports none.+ name: "brain_changes",+ calls: one({}, REASON.ownerlessLane),+ },{name: "brain_claims",calls: [diff --git a/tests/mcp/brain-changes.test.ts b/tests/mcp/brain-changes.test.tsnew file mode 100644index 00000000..59b17934--- /dev/null+++ b/tests/mcp/brain-changes.test.ts@@ -0,0 +1,115 @@+/**+ * `brain_changes` (task 1.9): the MCP front door of the change probe.+ *+ * 1. At local reach it returns a neighbour's record id under its topic+ * and scope, after the watermark of an earlier call.+ * 2. Below local reach it answers nothing, by name: brain store records+ * reach local callers only, the rule search applies to them too.+ * 3. A malformed watermark is an invalid-params error naming the fix.+ * 4. A page larger than a preview still carries its watermark inline.+ */+import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import { writeFileSync } from "node:fs";+import { join } from "node:path";++import { TRANSPORT_REACH } from "../../src/core/graph/transport-reach.ts";+import { STORE_CATCH_UP_INTERVAL_ENV } from "../../src/core/search/brain-store/constants.ts";+import { appendRecord } from "../../src/core/store/appender.ts";+import { STORE_ROOT_ENV } from "../../src/core/store/constants.ts";+import { CHANGES_REACH_REASON, CHANGES_TOOLS } from "../../src/mcp/brain/changes-tools.ts";+import { ArtifactStore } from "../../src/mcp/artifact-store.ts";+import { MCPError } from "../../src/mcp/protocol.ts";+import { buildMcpToolResult } from "../../src/mcp/server.ts";+import type { ServerContext } from "../../src/mcp/tool-contract.ts";+import {+ LOCAL_DEVICE,+ makeStoreIndexFixture,+ REMOTE_DEVICE,+ type StoreIndexFixture,+} from "../core/search/fixtures/brain-store-index.ts";++const handler = CHANGES_TOOLS.find((t) => t.name === "brain_changes")!.handler;+const ENV_KEYS = [STORE_ROOT_ENV, STORE_CATCH_UP_INTERVAL_ENV, "XDG_STATE_HOME", "LOCALAPPDATA"];++let fx: StoreIndexFixture;+let ctx: ServerContext;+const saved: Record<string, string | undefined> = {};++beforeEach(() => {+ for (const k of ENV_KEYS) saved[k] = process.env[k];+ fx = makeStoreIndexFixture("osb-mcp-changes-");+ fx.open(LOCAL_DEVICE);+ const state = fx.dirs(LOCAL_DEVICE).env;+ process.env[STORE_ROOT_ENV] = fx.root;+ process.env[STORE_CATCH_UP_INTERVAL_ENV] = "0";+ process.env["XDG_STATE_HOME"] = state["XDG_STATE_HOME"];+ process.env["LOCALAPPDATA"] = state["LOCALAPPDATA"];+ const configPath = join(fx.parent, "config.yaml");+ writeFileSync(configPath, `vault: ${fx.vault}\n`);+ ctx = { vault: fx.vault, configPath, repoRoot: null, reach: TRANSPORT_REACH.local };+});+afterEach(() => {+ for (const k of ENV_KEYS) {+ if (saved[k] === undefined) delete process.env[k];+ else process.env[k] = saved[k];+ }+ fx.cleanup();+});++function neighbour(text: string, scope?: string, topic?: string) {+ return appendRecord(fx.open(REMOTE_DEVICE), {+ partition: "shared",+ stream: "events",+ kind: "decision",+ agent: "agent-b",+ ...(scope !== undefined ? { scope } : {}),+ ...(topic !== undefined ? { topic } : {}),+ body: { text },+ }).record;+}++describe("brain_changes", () => {+ // The grouping itself is the core probe's (tests/core/search/brain-store-changes.test.ts);+ // here the tool reaches the configured store and the watermark round-trips.+ test("returns a neighbour's record id after the watermark it handed out", async () => {+ neighbour("an earlier decision");+ const first = (await handler(ctx, {})) as Record<string, unknown>;+ expect(first).toMatchObject({ measured: true, storeInUse: true, count: 1 });++ const record = neighbour("pick the north bank");+ const after = (await handler(ctx, { since: first["watermark"] })) as Record<string, unknown>;+ const groups = after["groups"] as ReadonlyArray<{ readonly ids: ReadonlyArray<string> }>;+ expect(groups.flatMap((g) => g.ids)).toEqual([record.id]);+ });++ test("below local reach nothing is reported, by name", async () => {+ neighbour("a decision");+ const res = (await handler({ ...ctx, reach: TRANSPORT_REACH.remote }, {})) as Record<+ string,+ unknown+ >;+ expect(res).toMatchObject({ measured: false, reason: CHANGES_REACH_REASON });+ expect(res["groups"]).toBeUndefined();+ });++ test("a malformed watermark is an invalid-params error", async () => {+ await expect(handler(ctx, { since: "yesterday" })).rejects.toBeInstanceOf(MCPError);+ await expect(handler(ctx, { since: "yesterday" })).rejects.toThrow("not a watermark");+ });+});++describe("brain_changes through the MCP result builder", () => {+ test("a page too large for a preview keeps its watermark inline", async () => {+ for (let i = 0; i < 80; i++) neighbour(`decision ${i}`);+ const tool = CHANGES_TOOLS.find((t) => t.name === "brain_changes")!;+ const structured = await tool.handler(ctx, { limit: 60 });+ const artifacts = new ArtifactStore({ vault: fx.vault, runId: "run-changes" });+ const result = buildMcpToolResult(tool, structured, artifacts) as {+ content: Array<{ text: string }>;+ };+ const text = JSON.parse(result.content[0]!.text) as Record<string, unknown>;+ expect(text["preview_truncated"]).toBeUndefined();+ expect(text).toMatchObject({ truncated: true, count: 60 });+ expect(text["watermark"]).toBe((structured as Record<string, unknown>)["watermark"]);+ });+});diff --git a/tests/mcp/brain-tools-parity.test.ts b/tests/mcp/brain-tools-parity.test.tsindex 51fb1edd..e57cf107 100644--- a/tests/mcp/brain-tools-parity.test.ts+++ b/tests/mcp/brain-tools-parity.test.ts@@ -78,7 +78,10 @@* `brain_intake_pledges` (the agent-executed extraction intake over the* same family: typed pledge extractions posted against a source page,* validated whole before any write, counterparty names anchored- * server-side against the canonical entity registry).+ * server-side against the canonical entity registry); the brain store+ * release added `brain_changes` (the change probe: record ids new since a+ * watermark, grouped by partition, stream, scope and topic, answered from+ * the index after catch-up, local reach only).*/import { afterEach, describe, expect, test } from "bun:test";@@ -105,6 +108,7 @@ const FROZEN_BRAIN_TOOL_NAMES = ["brain_benchmark","brain_bridges","brain_brief",+ "brain_changes","brain_claims","brain_clusters","brain_codegraph_report",diff --git a/tests/mcp/list-pagination-census.test.ts b/tests/mcp/list-pagination-census.test.tsindex b3aca157..9b8a1097 100644--- a/tests/mcp/list-pagination-census.test.ts+++ b/tests/mcp/list-pagination-census.test.ts@@ -119,6 +119,9 @@ const REPORT_CAPS: Readonly<Record<string, string>> = {"Time-window paging by documented convention: rows are ascending assertion ts, so " +"tail-following paginates by advancing `since` (knowledge-tools.ts); a cursor would " +"duplicate a mechanism the surface already has.",+ brain_changes:+ "Watermark paging by contract: a cut page returns the watermark of its last record and " ++ "`since` continues from it (brain-store/changes.ts); a cursor would duplicate the watermark.",brain_search:"Ranking stability: results are a ranked, index-dependent answer, not a stable set - " +"re-running the query for a second page races the index, and offset paging would present " +@@ -167,11 +170,12 @@ describe("list-pagination census", () => {test("the populations are pinned as equalities", () => {// 24 -> 25: brain_write_destinations (actionable-now batch) carries// limit + cursor beside brain_writes, so the limit-bearing population- // grows by one.- expect(pagingTools().filter((tool) => tool.hasLimit)).toHaveLength(25);- // 10 recorded caps: eight Tier-B report/window caps and the two- // Tier-C ranked-retrieval non-goals.- expect(Object.keys(REPORT_CAPS)).toHaveLength(10);+ // grows by one. 25 -> 26: brain_changes (brain store change probe)+ // pages by its watermark.+ expect(pagingTools().filter((tool) => tool.hasLimit)).toHaveLength(26);+ // 11 recorded caps: eight Tier-B report/window caps, the watermark+ // probe and the two Tier-C ranked-retrieval non-goals.+ expect(Object.keys(REPORT_CAPS)).toHaveLength(11);});test("the census can fail", () => {diff --git a/tests/mcp/mcp.test.ts b/tests/mcp/mcp.test.tsindex fb799ec3..b377e4e4 100644--- a/tests/mcp/mcp.test.ts+++ b/tests/mcp/mcp.test.ts@@ -260,6 +260,8 @@ describe("tool listing", () => {"brain_receipts",// The vault storage report (storage-lifecycle)."brain_storage",+ // The brain store change probe (brain store and topics, phase 1).+ "brain_changes",// Observed-use verdict feeding recall ranking (Retrieval & Ranking Quality)."brain_observed_use","brain_knowledge_gaps",diff --git a/tests/setup.ts b/tests/setup.tsindex 7ac27845..37426cf9 100644--- a/tests/setup.ts+++ b/tests/setup.ts@@ -77,6 +77,20 @@ if (!process.env["OPEN_SECOND_BRAIN_CONFIG"]) {process.env["OPEN_SECOND_BRAIN_CONFIG"] = configPath;}+// The brain store root defaults to a per-user data directory, and a store+// found there moves the search index into the store's device-local state+// (`src/core/search/brain-store/location.ts`). A developer machine that+// holds a real store, or exports OPEN_SECOND_BRAIN_STORE_ROOT to one (a+// documented user setting; an empty export falls back to the default+// root), would then change where every search test's index lives. So the+// suite always points the root at a directory that does not exist: no+// store is in use unless a test creates one and sets the variable itself.+{+ const storeParent = mkdtempSync(join(tmpdir(), "osb-test-store-root-"));+ afterAll(() => rmSync(storeParent, REMOVE_TREE));+ process.env["OPEN_SECOND_BRAIN_STORE_ROOT"] = join(storeParent, "store");+}+// Windows keeps the per-user config/state/cache roots under// `%LOCALAPPDATA%` (and a few host-agent roots, e.g. Cursor's sessions,// under `%APPDATA%`) - see `src/core/platform-dirs.ts`. Suites isolate