Skip to content

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

TypeScript

fix(store): close brain-store follow-ups 3.9, 3.10, 3.11, 3.18, 3.21 (#305)

Serg Eroshecad26facd61e
diff --git a/CHANGELOG.md b/CHANGELOG.md
index c56ba621..85e26a05 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -13,6 +13,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Fixed
+- **A lane entry id maps to exactly one legacy path.** A page and a JSON file of one name (`x.json.md` and `x.json`) no longer share an entry id, and a name that would not map back to itself (a file with another extension or none, a folder named like another folder's lane, such as `exact-state/`) is refused by name on a store-only machine and listed by the migration as an item it could not convert, instead of being filed under an id that names another path. A folder of your own under `Brain/` spelled otherwise than a lane name (`My Notes/`, `project_x/`) is still imported, under its lane (`my-notes`), and a rollback puts it back at its own path; two folders that would take one lane (`My Notes/` beside `my-notes/`) are listed and archived instead, and `brain_doctor` names them before a migration (`lane-folder-unimportable`) so you can rename one first. A page an earlier release's migration filed under the id of the file beside it is moved to its own id by the next dream pass on a store-only machine that holds `private`, once per machine, and again once new records arrive (or after a pass that could not read every shard), and the file gets its id back; a page removed after its repair stays removed. `brain_doctor` names any page still filed that way (`lane-id-misfiled`) with the remedy, also on a store where no machine holds `private`.
+- **A procedure use no longer appends store records.** The procedural memory usage counters, graph and recall hints are machine state, kept in the device-local state once a machine is switched, so `mark_used` and `mark_outcome` rewrite one local file instead of appending the index, the usage file, the graph and the hints to the store on every use. The migration moves the counters into the device-local state, and counters an index still carries are read and moved on the next reconcile. Counters are per machine from now on. A machine switched by an earlier release reads the counters, graph and hints from their store records until it has its own copy, adopting them on the first read, and the removal of the legacy tree retires those records.
+- **A schema apply is attested on a machine that holds only `shared`.** A store-only apply writes its audit row to `shared`, beside the schema settings records it attests, so such a machine reports another device's apply as `ok` instead of `modified` or unverified. The shared row carries the attestation and the mutation list; the reason stays on the whole row in `private`, where audit rows always went on a machine that holds it, and a batch or reason that names a private page or carries a `<private>` region leaves only the attestation on the shared row.
+- **Private evidence no longer moves a shared preference.** An `apply-evidence` event that lands in `private` because its note or artifact names a private page no longer confirms, quarantines, retires or re-scores a shared preference in dream or in the review candidates, and no longer turns the preference itself private, is copied as a private record by a merge and left out of the merge's sums, and no longer makes every dream pass rewrite the preference; it still counts toward a preference that is private, and in the counters a local caller of a machine that holds `private` reads; a remote MCP caller is shown the counters of the shared evidence alone.
+- **The seen-shards ledger is updated under a device-local lock.** Two processes on one machine could interleave their read-modify-write of the ledger, so a tracking read could bring back entries `o2b store partition leave` had just cleared, or a leave could drop a shard another process had just recorded; every update now re-reads the ledger under the lock, and a lock left by a crashed process costs a process one short wait. The procedural usage file is read and written under its lock the same way, so a reconcile no longer drops a use another process counted.
+
- **The search index writer lock stays fresh through long synchronous work, and a writer that lost it no longer touches its successor's lock.** The lock's heartbeat ran on the event loop, so a holder blocked in synchronous work - a snapshot's `tar` or `zstd` run, the store archive's integrity scan and `VACUUM INTO`, the restore that holds the lock from its recovery point through the swap, an FTS rebuild, a migration, the index walk between embedding batches - left the lock untouched for longer than its 60-second stale window on a large vault, and a second writer took it over while the first was still writing. Each of those steps now keeps the lock fresh from a worker thread for a stated bound (the tool's kill timeout, or fifteen minutes for an in-process step without one), and the index walk refreshes it as it goes; past the bound the worker stops, so a holder wedged inside the step still goes stale and is taken over one window later, and a crashed or killed holder goes stale as before. Every refresh and the release first check that the lock is still the one this holder stamped (its mtime, which carries a random sub-millisecond fraction, and its inode): a lock another writer took over is never refreshed or removed, also at process exit, and neither is one so close to its stale window that a contender may be taking it over at that moment. Each protected step refuses with `INDEX_LOCKED` when the lock is not provably this holder's before it starts and again when it ends, and the holder's commits - the reindex swap, right before its first rename, and the restore swap, before the Brain renames and again before the store replacement, undoing the renames when the lock was lost in between - refuse with nothing touched instead of replacing what the other writer committed, and a write-mode store stops at the moment it sees the loss: its connection turns read-only and the loss is raised as `INDEX_LOCKED`, which from the heartbeat ends the process as the old lock library did. The brain store catch-up and the link and relation passes of an index run keep the lock fresh too. The on-disk lock is unchanged, so older releases on the same index exclude and are excluded by it; an older release still removes the lock without checking whose it is, which this release detects and refuses its commit on. `OPEN_SECOND_BRAIN_WRITER_LOCK_STALE_MS` sets the stale window (one minute by default, at most one day); the lock beats at least every 20 seconds whatever the window, so an older release never sees a live lock as stale, and a value below one minute is unsafe while an older release shares the index and is warned about.
- **Two Windows-flaky tests are fixed at their cause.** The hung and TERM-ignoring version-child tests read the child's pid from a shell `$$` that the 150 ms budget could cut off mid-write, and that is not the native pid on Windows; the child is now a Bun process that writes its native pid atomically, and a run whose child the budget cut off before it reported is repeated at a doubled budget instead of failing on a pid it never wrote. The concurrent `o2b store init` test started six full CLI processes at once and raced their startup against its 30-second budget on a loaded runner; six processes now load the init verb's handler, report ready and start together on one signal, so the test races the store creation itself and process start is no longer part of the race, and a racer never outlives the test.
- **A failed snapshot restore no longer leaves `Brain/` replaced beside the old derived store.** `restoreSnapshot` replaced the live `Brain/` tree before it decompressed the archived derived store, so a `zstd` failure or timeout, a corrupt payload or a full disk at that point stopped the rollback with the tree already restored and the store not. Every step that can fail now runs before anything live changes: the archive is extracted and the `Brain/` entries staged and verified on the live tree's filesystem (under `.snapshots/` when it shares a device with `Brain/`), the store archive is checked against the digest its manifest recorded, decompressed beside the live store and integrity-checked, and only then is the store's writer lock acquired and the recovery point taken, so lock contention also refuses with nothing touched. The lock is held from before the recovery point through the swap, and the recovery point's store archive is written under it, so no write can land between the two and the recovery point holds every commit the swap replaces. The recovery point skips its own lock only for an opaque token minted where the restore acquires the lock, while that lock is held and on the same store; a string naming the store's path, an object that merely looks like a token or a token whose lock was already released takes the lock as usual. The recovery point archives exactly the store the swap replaces, under the restore's coverage policy, also with a `derivedStorePath` override, and the restore refuses before the swap when the recovery point's manifest records a different store. A lock release that fails after the swap committed is reported as a committed restore that names the recovery point, and one that fails after an earlier error is added to that error instead of replacing it. The swap itself is a run of renames: live entries are moved aside, staged ones moved in, then the staged store renamed over the live one, and a rename that fails is undone in reverse. If the undo fails too, the error says how many entries were swapped, where the pre-restore entries were kept and which recovery point puts the tree back. Excluded entries, the preserved `.snapshots/`, manifest-driven store inclusion and the reported restore states are unchanged. A rollback journal (`-journal`, the DELETE journal mode the store uses on remote filesystems) that the old store left beside it, hot after a crash, moves with the outgoing store to `.bak-journal` and back on every undo, for a store inside `Brain/` or outside it, so SQLite never replays it over the replacement; a journal that cannot be moved undoes the whole restore. The old store's `-wal`/`-shm` are removed after the store swap with the Windows retry, and a removal that still fails undoes the whole restore instead of reporting success beside an orphan write-ahead log; when no store was live before the restore, the error says so instead of claiming a pre-restore store was put back. A restore staging directory left directly under `Brain/` (a restore killed mid-swap, when `.snapshots/` is on another device) is skipped by the archiver, the manifest walker and the restore, so it is never archived or swapped back as Brain content. A sound store the restore replaces is always archived in its recovery point, whatever the coverage policy or size cap, and the restore refuses when the recovery point records it as left out; an absent store or one that fails its integrity scan does not block the restore that replaces it, also when the vault's policy turns store coverage on: the recovery point then leaves that store out explicitly instead of refusing it, so the restore recreates or heals it. A derived store that lives directly under `Brain/` (a `search_db_path` or `derivedStorePath` such as `Brain/index.sqlite`) is kept out of the `Brain/` tree swap together with its journals, writer lock, `.bak` and the restore's staged file, so the store swap finds its staged file and the restore completes; the placement is judged for the directory entry the store swap renames, not the file a symlink there points to, so a `Brain/index.sqlite` that links to a database outside `Brain/` is restored at the link instead of having its staged replacement moved away by the tree swap; the raw copy of the store that the `Brain/` archive carries as a top-level entry is not restored over it, so the store is written once, from the store archive, or left untouched when the snapshot did not cover it. A store nested deeper inside a `Brain/` directory the swap replaces as a whole is refused before anything is extracted or touched, with an error that names the directory.
diff --git a/openclaw/index.js b/openclaw/index.js
index b2e01c9e..7a05c97c 100644
--- a/openclaw/index.js
+++ b/openclaw/index.js
@@ -5967,6 +5967,32 @@ var init_store_open = __esm(() => {
import { mkdirSync as mkdirSync10, readFileSync as readFileSync11, statSync as statSync8 } from "node:fs";
import { createHash as createHash4 } from "node:crypto";
import { basename as basename6, dirname as dirname11, join as join17, resolve as resolve8 } from "node:path";
+function withLocalLock2(lockTarget, fn, budgetMs) {
+ const lock = (init_local_lock(), {});
+ return withLocalLock(lockTarget, fn, budgetMs);
+}
+function applyChanges(ledger, changes) {
+ const held = new Map;
+ for (const change of changes) {
+ let holds = held.get(change.partitionRoot);
+ if (holds === undefined) {
+ try {
+ holds = readStoreId(change.partitionRoot) !== null;
+ } catch {
+ holds = false;
+ }
+ held.set(change.partitionRoot, holds);
+ }
+ if (!holds)
+ continue;
+ const own = ledger.get(change.partition) ?? new Set;
+ for (const rel of change.fresh)
+ own.add(rel);
+ for (const rel of change.expected)
+ own.delete(rel);
+ ledger.set(change.partition, own);
+ }
+}
function isPartition2(value) {
return STORE_PARTITIONS.includes(value);
}
@@ -6003,21 +6029,48 @@ function load3(path) {
loaded2.set(path, { stamp, ledger });
return ledger;
}
+function writeChanged(path, ledger, change) {
+ change(ledger);
+ const shards = {};
+ for (const [partition, rels] of [...ledger].toSorted(([a], [b]) => compareCodeUnits(a, b))) {
+ shards[partition] = [...rels].toSorted();
+ }
+ mkdirSync10(dirname11(path), { recursive: true });
+ atomicWriteText(path, `${JSON.stringify({ version: 1, shards }, null, 2)}
+`);
+ loaded2.set(path, { stamp: stampOf2(path), ledger });
+}
function update2(path, change) {
+ const queued = pending.get(path) ?? [];
+ if (change !== null)
+ queued.push(change);
+ if (queued.length > PENDING_MAX)
+ queued.splice(0, queued.length - PENDING_MAX);
+ pending.set(path, queued);
+ const until = busyUntil.get(path);
+ if (until !== undefined && Date.now() < until)
+ return;
+ const holder = lockHolderStamp(path);
try {
+ withLocalLock2(path, () => {
+ loaded2.delete(path);
+ writeChanged(path, load3(path), (ledger) => applyChanges(ledger, queued));
+ }, TRACK_LOCK_BUDGET_MS);
+ pending.delete(path);
+ busyUntil.delete(path);
+ } catch (err) {
loaded2.delete(path);
- const ledger = load3(path);
- change(ledger);
- const shards = {};
- for (const [partition, rels] of [...ledger].toSorted(([a], [b]) => compareCodeUnits(a, b))) {
- shards[partition] = [...rels].toSorted();
- }
- mkdirSync10(dirname11(path), { recursive: true });
- atomicWriteText(path, `${JSON.stringify({ version: 1, shards }, null, 2)}
-`);
- loaded2.set(path, { stamp: stampOf2(path), ledger });
+ const after = lockHolderStamp(path);
+ if (err?.code === "ELOCKED" && holder !== null && after === holder && Date.now() - after >= TRACK_LOCK_BUDGET_MS) {
+ busyUntil.set(path, Date.now() + TRACK_BACKOFF_MS);
+ }
+ }
+}
+function lockHolderStamp(path) {
+ try {
+ return statSync8(`${path}.lock`).mtimeMs;
} catch {
- loaded2.delete(path);
+ return null;
}
}
function seenLedgerFile(storeRoot, storeId) {
@@ -6067,7 +6120,15 @@ function trackSeenShards(partitionRoot, scope, listed, replaced = new Set) {
const at = ledgerPath2(partitionRoot);
if (at === null)
return [];
- const seen = load3(at.path).get(at.partition) ?? new Set;
+ const seen = new Set(load3(at.path).get(at.partition) ?? []);
+ for (const change of pending.get(at.path) ?? []) {
+ if (change.partition !== at.partition)
+ continue;
+ for (const rel of change.fresh)
+ seen.add(rel);
+ for (const rel of change.expected)
+ seen.delete(rel);
+ }
const present = new Set(listed);
const fresh = listed.filter((rel) => !seen.has(rel));
let missing = [...seen].filter((rel) => rel.startsWith(scope.prefix) && !present.has(rel) && (scope.device === undefined || deviceOf(rel) === scope.device) && (scope.month === undefined || scope.month(monthOf(rel))));
@@ -6078,19 +6139,16 @@ function trackSeenShards(partitionRoot, scope, listed, replaced = new Set) {
expected = [...expected, ...missing.filter((rel) => retired.has(deviceOf(rel)))];
missing = missing.filter((rel) => !retired.has(deviceOf(rel)));
}
- if (readOnlyDepth === 0 && (fresh.length > 0 || expected.length > 0)) {
- update2(at.path, (ledger) => {
- const own = ledger.get(at.partition) ?? new Set;
- for (const rel of fresh)
- own.add(rel);
- for (const rel of expected)
- own.delete(rel);
- ledger.set(at.partition, own);
- });
+ if (readOnlyDepth === 0) {
+ if (fresh.length > 0 || expected.length > 0) {
+ update2(at.path, { partitionRoot, partition: at.partition, fresh, expected });
+ } else if ((pending.get(at.path)?.length ?? 0) > 0) {
+ update2(at.path, null);
+ }
}
return missing.toSorted();
}
-var loaded2, readOnlyDepth = 0, SEEN_SHARD_MISSING_REASON;
+var loaded2, TRACK_LOCK_BUDGET_MS = 500, TRACK_BACKOFF_MS = 1e4, busyUntil, pending, PENDING_MAX = 1000, readOnlyDepth = 0, SEEN_SHARD_MISSING_REASON;
var init_seen_shards = __esm(() => {
init_fs_atomic();
init_platform_dirs();
@@ -6101,6 +6159,8 @@ var init_seen_shards = __esm(() => {
init_store_open();
init_store_paths();
loaded2 = new Map;
+ busyUntil = new Map;
+ pending = new Map;
SEEN_SHARD_MISSING_REASON = "this machine read the shard before and it is gone now (the store never deletes a shard); " + "its records are unknown until sync delivers it again";
});
@@ -7781,8 +7841,27 @@ var init_fold_signals = __esm(() => {
STATE_SET = new Set(SIGNAL_STATE_VALUES);
});
+// src/core/store/caller-reach.ts
+import { AsyncLocalStorage } from "node:async_hooks";
+var storage;
+var init_caller_reach = __esm(() => {
+ storage = new AsyncLocalStorage;
+});
+
// src/core/store/read/store-entities.ts
import { statSync as statSync12 } from "node:fs";
+function sharedCountersOf(history, privateIds) {
+ const out = Object.fromEntries(PREFERENCE_COUNTER_FIELDS.map((name) => [name, 0]));
+ for (const record of history) {
+ if (record.kind !== PREFERENCE_EVIDENCE_KIND || privateIds.has(record.id))
+ continue;
+ const result = record.body["result"];
+ if (typeof result === "string" && EVIDENCE_RESULTS.includes(result)) {
+ out[`${result}_count`] += 1;
+ }
+ }
+ return out;
+}
function fingerprintOf(store) {
const parts = [store.storeId, `quarantine=${quarantineStamp(store.root)}`];
for (const partition of [...store.partitions].toSorted()) {
@@ -7833,9 +7912,14 @@ function build(store) {
const fold = foldPreferences(all.map((e) => e.record));
const preferences = new Map;
for (const [id, state] of fold.preferences) {
- const inPrivate = state.history.some((record) => privateIds.has(record.id));
+ const inPrivate = state.history.some((record) => privateIds.has(record.id) && record.kind !== PREFERENCE_EVIDENCE_KIND);
const markedPrivate = state.removed ? state.history.some((record) => record.kind === PREFERENCE_SET_KIND && isPrivateFrontmatter(record.body["fields"] ?? {})) : isPrivateFrontmatter(state.fields);
- preferences.set(id, { state, private: degraded || inPrivate || markedPrivate });
+ preferences.set(id, {
+ state,
+ private: degraded || inPrivate || markedPrivate,
+ sharedCounters: sharedCountersOf(state.history, privateIds),
+ privateRecordIds: new Set(state.history.filter((record) => privateIds.has(record.id)).map((record) => record.id))
+ });
}
const signals = new Map;
const partitionOf = new Map(all.map((e) => [e.record.id, e.partition]));
@@ -7898,6 +7982,7 @@ var init_store_entities = __esm(() => {
init_fold_pinned();
init_fold_signals();
init_fold_preferences();
+ init_caller_reach();
init_shard_list();
init_store_open();
init_store_paths();
@@ -8405,13 +8490,13 @@ var init_origin_channel = __esm(() => {
});
// src/core/store/operation-scope.ts
-import { AsyncLocalStorage } from "node:async_hooks";
+import { AsyncLocalStorage as AsyncLocalStorage2 } from "node:async_hooks";
function activeOperationPrivate() {
- return storage.getStore()?.() ?? false;
+ return storage2.getStore()?.() ?? false;
}
-var storage;
+var storage2;
var init_operation_scope = __esm(() => {
- storage = new AsyncLocalStorage;
+ storage2 = new AsyncLocalStorage2;
});
// src/core/store/dual-write.ts
@@ -8918,7 +9003,12 @@ function appendAuditRecord(auditRoot, record, vault, options = {}) {
legacy: () => appendLegacyAuditLine(auditRoot, timestamp, line),
store: () => {
const written = JSON.parse(line);
- return auditRowRecord(DUAL_WRITE_LEDGERS.reliabilityAudit, { audit_dir: basename8(auditRoot), record: written }, isRecordLabel(written.actor) ? written.actor : undefined, auditRowNamesPrivatePage(vault, written));
+ const row = { audit_dir: basename8(auditRoot), record: written };
+ const agent = isRecordLabel(written.actor) ? written.actor : undefined;
+ if (options.attestsShared === true) {
+ return ledgerRowRecord(DUAL_WRITE_LEDGERS.reliabilityAudit, row, "shared", agent);
+ }
+ return auditRowRecord(DUAL_WRITE_LEDGERS.reliabilityAudit, row, agent, auditRowNamesPrivatePage(vault, written));
},
context,
...options.failOpen === true || basename8(auditRoot) === HOOK_AUDIT_TRAIL ? { failOpen: true } : {}
diff --git a/openspec/changes/brain-store-and-topics/design.md b/openspec/changes/brain-store-and-topics/design.md
index e66abb84..d2634d9e 100644
--- a/openspec/changes/brain-store-and-topics/design.md
+++ b/openspec/changes/brain-store-and-topics/design.md
@@ -296,6 +296,14 @@ The inventory for task 2.10 (316 modules reach the legacy tree) raised questions
As built (phase 2): a tombstone carries no content, so it goes to the partition of the entry it removes whatever the rest of its operation is, and no enclosing verdict raises it; this is the one exception to one partition per operation. A folder move or removal places each entry and its tombstone in that entry's own partition (a moved entry can still be raised, never lowered), so a device that holds only `shared` sees a shared entry leave a mixed folder. A write that raises a shared entry to `private` (a lane page or file, an exact-state aspect) writes the entry's shared tombstone first in the same store write, so a device that holds only `shared` sees the entry go and a device that holds both reads the private value.
As built (phase 2): a store read whose answer decides a protection fails closed when it cannot see a shard it should consider. A shard counts as unseen when it cannot be read, or when this machine read it before and it is gone now: every stream listing records the shards it saw in a device-local ledger per store (`seen-shards-<root hash>.json`), and a shard the ledger names that the listing no longer finds is reported as unreadable, unless a `compacted` record replaced it or a human retired the device that wrote it. On an unseen shard a lane or exact-state write is judged private (refused on a machine without `private`), an exported lane entry counts as private, the capture boundary captures nothing, the permissions gates refuse, an agent settings write is refused (`settings_unreadable`), a signal removal refuses, the brain settings readers throw instead of answering defaults, and the decision ledger throws instead of answering "never gated". Doctor reports each unseen shard by its path (`store-shard-unreadable`). A shard read only in part counts as unseen too: one that holds a record whose body blob has not arrived, or a bad line in the middle (a checksum or envelope that does not verify, a record of a newer format). Its readable records are still read, and no fold cache keeps a read over an unseen shard, so the fold is read again once the blob arrives even though the shard did not change. Two cases are not gaps: the last line held back while an append is still arriving (the existing reading rule), and a line torn by a crash and closed by the next append, recognised as a JSON object cut short and never a record any machine read. The removal of the legacy tree refuses on a `settings` shard read only in part unless `--force`, since such a line may never read again; doctor's shard check does not report a partial read as an unreadable shard. On a machine the sticky marker names switched, a store that cannot be opened (`store.json` missing or corrupt) or that no longer shows its `shared` partition is unseen as a whole, never "no store, no rules": the permissions gates refuse, the brain settings readers throw and capture closes, an agent settings write is refused (`settings_unreadable`), lane and exact-state privacy is judged private, a signal removal refuses, and the decision ledger and the attestations refuse to read as empty. A machine that never switched still reads "no store" as nothing stored. The partitions a machine holds are sticky the same way: opening a store for writing and `o2b store init` record, in a device-local list per store root, every partition this machine holds, and a listed partition whose `store.json` is now missing makes the store unopenable by name. On every store-only machine (switched, or with no legacy tree) every protection reader then fails closed as for an unopenable store, so a private lane entry is never read as shared because its partition's identity file went away; every store write refuses, and doctor names the partition (`store-partition-lost`, an error). A machine that never held a partition (set up with `--partitions shared`) keeps working with the partitions it has. No command takes a partition off the list: the remedy is to restore its `store.json` from sync or a backup.
+### D15. Phase 3 store follow-ups (tasks 3.9, 3.10, 3.11, 3.18, 3.21)
+
+1. **Lane entry ids (3.9).** The path rule of `store/lane-paths.ts` is a bijection on the paths it accepts: a path names an entry only when that entry turns back into the same path, and every other name is refused with its reason. A page whose name without `.md` reads as a kept file (`x.json.md`) keeps its whole name, so it no longer takes the id of `x.json`. A user's top folder spelled otherwise than its lane name (`My Notes/`, `project_x/`: case, spaces, other separators) is not refused by the migration: its pages are imported under the normalized lane, with the original path in the `migrated` mark, which is where a rollback writes them back; two folders that take one lane are refused, both but the one spelled as the lane, and doctor names such folders before a migration (`lane-folder-unimportable`). Refused are a file with another extension or none, a top folder that is not a lane name or is the lane name of another folder (`exact-state`, `brain`), and the place of a root file with a lane. A store-only write of such a name refuses, and the migration lists it as an item it could not convert (archived with the other unparseable items) instead of filing it under an id that names another path. Refusal was chosen over an escaped encoding for these names: none of them is written by a writer of this tool, and an encoding would change the ids of entries already in stores. An earlier release did file a migrated page `x.json.md` under `x.json`: a store-only dream pass runs a repair (`store-migration/lane-id-repair.ts`) that moves such a record, recognised by the legacy path in its `migrated` mark, to the id its path maps to now, and gives the old id back the latest record that is not the page's (the file `x.json`), with at least the authority of the page record it replaces, or removes it. The page is written under its new id only when that id has no history at all, so a page removed after its repair stays removed. Every moved or restored record keeps the body it copies, its `migrated` mark included. The repair runs only on a machine that holds `private` (one without it cannot see a file's own record there and would remove the file's id over it), and once per store on a machine: a device-local marker records a finished pass that read every shard in full, with a stamp, taken before the read, of the `events` shards other devices write, so a later pass reads the stream again only once another machine's records arrived, a late import of a machine still on the earlier release included, and never for this machine's own writes. A pass that met an unreadable shard, one gone since it was read, or a pending blob writes nothing at all (it may have missed the file beside a page, or a removal) and runs again. The page's value and the old id's own value are each resolved as the register resolves them (authority, then fold order), never taken from the latest record. Each record lands in the partition of the record it copies; a file restored in `private` over a page that lives in `shared` also removes the page from `shared`, and a removal the move into an id replaces is kept when the move lands in another partition, so a machine that holds only one partition never keeps a stale page. The plan is written only once a read right before the write finds the same lane records, and made again from that read otherwise. The old id's own state counts its removals: a file removed before a page was filed over it stays removed. A page whose own id holds only a page filed there from the id after it (`x.json.md.md` under `x.json.md`) takes that id in the same pass, which moves the other page on. On a store where no machine holds `private` the repair never runs, so doctor reports mis-filed ids on every machine (`lane-id-misfiled`; it names only the repairs of pages the caller may read, below local reach only those no record of the `private` partition takes part in, with one remedy whatever the machine holds, and the legacy-folder check states its finding by name only, with no names or counts), naming them and the remedy: a dream pass on a machine that holds `private`, or adding the partition on one with `o2b store init --partitions shared,private` first. The old id's tombstone or restore is appended before the page's new record, and the rollback exporter writes an entry back to the legacy path of a `migrated` mark only when that path names the entry under the current rule (or names no entry the rule maps, a blob lane's file or a respelled folder), else to the entry's own path, so a rollback after a repair leaves both files at their own paths, and a lone page the snapshot restores is never removed by its old id's tombstone.
+2. **Procedural counters (3.10).** The usage counters of procedural memory (`usage.jsonl`: uses, last use, successes, failures), the procedural graph and the recall hints are machine state, at their vault-relative paths on an unswitched machine and in the device-local state once switched, like the claim graph and the rollup ledger (D14 item 11). A use or an outcome rewrites only the usage file, so a usage tick appends no store record. Every read-modify-write of the usage file (a tick, an outcome, the reconcile that moves an index's counters into it) runs under the file's write lock and reads the file again inside it, so a reconcile in one process never drops a tick another process counted. A reconcile moves the counters an older index carries into the usage file before it rewrites the index without them, so a rebuild that fails afterwards leaves them in the usage file. A first adoption of the stored usage record is written under the same lock, only while the file is still absent. The index stays a shared `lane-entry` and is written with its counters at rest; a reader takes the counters from the usage file and falls back to those an older index still carries, and the next reconcile writes them into the usage file. The migration moves `usage.jsonl` into the device-local state (a `device-local` surface) and drops the graph and hints, which each machine recomputes. Counters are per machine from then on: they rank procedures for the machine that uses them, and machines need not agree on them. A machine switched before this change holds the three files as `lane-entry` records only: a reader with no machine-state copy yet reads that record and adopts it into the machine state on the first read, writing no store record, so the graph, the hints and the counters answer before the next reconcile. The records stay until the legacy tree leaves the vault, because a rollback replays post-switch records into the legacy tree and a tombstone would remove the legacy file they came from; the removal of the legacy tree, after which no rollback can run, adopts them on its own machine and then tombstones each one whose copy this machine now holds (`store-migration/retire-adopted.ts`); one it could not adopt (its device-local folder refused the write) or whose tombstone could not be written stays live, the one copy there is. A rollback before that loses only the counter ticks counted after the switch, which live in the device-local state; the legacy files come back from the snapshot. A machine that never read the records before their tombstone arrives rebuilds the graph and hints on its next reconcile and starts its counters from those its index carries.
+3. **Schema apply attestation (3.11).** Of the two options, the audit row moves: a store-only apply writes it to `shared`, the partition of the `brain.schema.*` settings records it attests, so a machine that holds only `shared` finds the digest the pack must match and reports another device's apply as attested. The other option, accepting the newest settings records as attested, was rejected because it would accept any settings write to a schema field as an audited apply, which is exactly what the integrity check exists to tell apart. The `reason` does not belong on the shared row: it is free text an operator wrote, and audit rows have always stayed in `private` on a machine that holds it. So the shared row carries what attests the pack (actor, time, target, count, digest) and the mutation list, which the shared `brain.schema.*` records hold anyway, and the whole row, reason included, goes to `private` as every audit row does when this machine holds it; on a machine that does not, the shared row keeps the reason, the exposure such a machine always had. One privacy verdict covers the batch and the reason: a private page named (the rule every audit row is judged by) or a `<private>` region; when it holds, the shared row keeps only the attestation and says the mutations were withheld, so an apply whose reason the store would move to `private` is still attested in `shared`.
+4. **Private evidence (3.18).** A private `apply-evidence` event never changes a shared preference's status, confidence, evidence timestamps or evidence sections, which dream writes to `shared` for every machine and remote caller; it counts toward a preference that is itself private. Every number derived from evidence that lands in `shared` follows the same rule: a merge copies each private evidence record of the drop as a private record (each copy keeps its source's partition), and its sums count a private use whenever the keep it lands on is private, and the shared and the private copies are written as two store writes, one per partition, since one write lands in one; the merge's log event and audit trail carry the sums of the shared evidence for a shared preference; dream compares a preference's counters against the ones the scan would count, so a shared preference with private uses settles instead of being rewritten every pass. A `preference-evidence` record in `private` no longer makes its preference private (before, the first private use moved the whole preference into `private` on this machine, where every later write followed it). The counters fold the partitions a machine holds, so a local caller on a machine that holds `private` sees its own private uses counted: that is the local view the event may affect, and it is never written back. A caller below local reach is shown the counters a machine that holds only `shared` folds: each preference of the store fold carries both, and the MCP server runs every tool call and resource read of a remote transport in an ambient scope (`store/caller-reach.ts`) that the preference facades and the rebuilt preference pages read, so the MCP tools, the `brain_context` digest, the operator snapshot and the review candidates all answer with the shared counters there. The device-local digest cache is always rendered with nothing withheld, since only local readers are served it; a remote caller gets its own render.
+5. **Seen-shards ledger (3.21).** Every read-modify-write of the ledger runs under the device-local lock of the ledger file and re-reads it inside the lock, so a tracking read and a partition leave in two processes never undo each other. The lock guards the ledger alone and takes no other lock inside it, so a reader that holds a store lock may take it; a tracking update waits at most half a second and then skips, which only delays tracking to the next read, a skipped change stays queued in the process, counts as seen in its next listings (so a shard it names is still reported once gone) and is written with its next update, which a listing with nothing new also tries (a change for a partition the machine no longer holds is dropped then, and a partition leave drops its own process's queue for that partition), so a skip delays tracking, it does not drop it; and after a skip behind a lock one holder has kept the whole wait and longer (a crashed process's) the process leaves the ledger alone for ten seconds without waiting, so such a lock costs a hook one wait, not one per listing, while a lock other processes take and release in turn backs nothing off, whatever its directory's stat says (a released lock directory can linger with its old stat on Windows); the leave waits the full lock budget and refuses as before.
+
## 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.
diff --git a/openspec/changes/brain-store-and-topics/specs/brain-store/spec.md b/openspec/changes/brain-store-and-topics/specs/brain-store/spec.md
index 92dfd8bf..173c147c 100644
--- a/openspec/changes/brain-store-and-topics/specs/brain-store/spec.md
+++ b/openspec/changes/brain-store-and-topics/specs/brain-store/spec.md
@@ -140,6 +140,21 @@ The store SHALL keep records in partitions by sensitivity, at least `shared` and
- **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: Private evidence stays out of shared preferences
+An `apply-evidence` event that lands in `private` because its artifact or note names a private page SHALL NOT change the status, confidence, evidence timestamps or evidence sections of a preference that is not itself private: those fields are read from `shared` by every machine and remote caller. Such an event SHALL NOT make the preference private, a merge SHALL copy it as a private record, and no number derived from it SHALL be written to `shared`. It MAY count in the evidence counters a local caller of a machine that holds `private` reads, which fold the partitions that machine holds; a caller below local reach SHALL be shown the counters of the `shared` evidence alone. Toward a preference that is itself private it SHALL count like any other evidence.
+
+#### Scenario: Private evidence on a shared preference
+- **WHEN** a machine that holds `private` records evidence whose note names a private page against a shared, unconfirmed preference and runs dream
+- **THEN** the preference stays unconfirmed with the confidence it had, as a machine that holds only `shared` reads it, and later shared evidence on it still lands in `shared` and counts
+
+#### Scenario: Evidence counters below local reach
+- **WHEN** a remote MCP caller reads that shared preference, its page or a digest built from it, on the machine that holds `private`
+- **THEN** its applied and violated counts leave the private evidence out, while a local caller sees it counted
+
+#### Scenario: Private evidence on a private preference
+- **WHEN** the same evidence targets a preference that is itself private
+- **THEN** dream confirms that preference
+
### 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.
diff --git a/openspec/changes/brain-store-and-topics/tasks.md b/openspec/changes/brain-store-and-topics/tasks.md
index 98d62021..3930151f 100644
--- a/openspec/changes/brain-store-and-topics/tasks.md
+++ b/openspec/changes/brain-store-and-topics/tasks.md
@@ -83,19 +83,19 @@ Phases follow design.md D13. Each phase ends in its own release PR, and the vers
- [ ] 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.
- [x] 3.8 Keep a lane page's raw text in its `lane-entry` record (an optional `raw` body field, FORMAT.md), so a store-only machine reads back staged bytes verbatim (OCR F291). Verify: a round-trip test of text without frontmatter and of quoted values. Done in change `store-hardening`.
-- [ ] 3.9 Make lane entry ids a bijection with legacy paths (every extension, `x.json` vs `x.json.md`, folders that are not lane names), or refuse the names that do not round-trip (OCR F295). Verify: a round-trip test over the lane path table.
-- [ ] 3.10 Keep the procedural graph and hint counters as device-local state instead of re-appending whole `lane-entry` records on every usage tick (OCR F360). Verify: a usage tick appends no store record, and a migration test moves the counters into the device-local state.
-- [ ] 3.11 Write the schema-apply audit row in the partition of the pack records it attests (`shared`), with one privacy verdict over the batch and its reason, or have the schema integrity check accept the newest settings records as attested (OCR F394). Verify: a machine that holds only `shared` reports a schema apply from another device as attested, not `modified`.
+- [x] 3.9 Make lane entry ids a bijection with legacy paths (every extension, `x.json` vs `x.json.md`, folders that are not lane names), or refuse the names that do not round-trip (OCR F295). Verify: a round-trip test over the lane path table. Done: refused names, design D15 item 1.
+- [x] 3.10 Keep the procedural graph and hint counters as device-local state instead of re-appending whole `lane-entry` records on every usage tick (OCR F360). Verify: a usage tick appends no store record, and a migration test moves the counters into the device-local state. Done: design D15 item 2.
+- [x] 3.11 Write the schema-apply audit row in the partition of the pack records it attests (`shared`), with one privacy verdict over the batch and its reason, or have the schema integrity check accept the newest settings records as attested (OCR F394). Verify: a machine that holds only `shared` reports a schema apply from another device as attested, not `modified`. Done: the row moves to `shared`, design D15 item 3.
- [ ] 3.12 Settle the cross-device merge of the schema field lists (a set merge rather than last writer wins on the whole list), personas as files or records, and whether the shared namespace gets a store of its own; the mirror into this machine's own store refuses until then (OCR F397, F464, F398). Verify: a concurrent edit test on two devices for the field lists, and a test per decision taken.
- [x] 3.13 Keep private-partition log events out of the OKF `log.md`, or carry a privacy marker for them: a log entry has no frontmatter for the `visibility: [private]` stamp pages from the private partition now get (OCR F333, log side). Verify: an export test on a switched machine with one private and one shared log event. Done in change `lane-pages-split`.
- [x] 3.14 Split the store side of `src/core/store/lane-pages.ts` (fold accessors, partition keep-rule, lane-entry writers) into its own module: the file is over the 700-line limit after the replace-keeps-private fix. Verify: no behaviour change, the lanes and store suites pass unchanged. Done in change `lane-pages-split`.
- [x] 3.15 Name a shard that reads only in part (a corrupt middle line, a record of a newer format, a blob that never arrives) in a doctor finding with its path, and add a repair that quarantines the bad line, so a protection read that fails closed on it can be released without a hand edit. Also decide whether rollback and the late import wait for a pending blob rather than leave its record out. Verify: a doctor test per gap kind, a quarantine test that reopens capture. Done in change `store-hardening`.
- [x] 3.16 Add an operator verb that takes a partition off this machine on purpose (for example `o2b store partition leave private`): held partitions are sticky per machine since the phase 2 review, so a machine that stops syncing `private/` refuses every store operation until the verb clears it from the held list. Verify: leaving `private` turns the machine shared-only with no refusal, and a lost `private/store.json` without the verb still fails closed. Done in change `store-hardening`.
- [x] 3.17 Audit every reader that renders store log events to a caller below local reach without `logEntryAtReach` or `logEntriesAtReach` (the active-preferences digest's most-applied counts, the morning brief, temporal citations, status, backlinks, analytics, anything else built on `logDayReader`, `storeLogDays` or `readStoreLogEvents`), and make each withhold events marked `fromPrivatePartition` (change `lane-pages-split`, design D3). Verify: a remote-reach test per reader with one private event that names nothing. Done in change `store-hardening`.
-- [ ] 3.18 Decide and apply how private `apply-evidence` events take part in the dream and evidence computations (`evidence.ts`, `dream-refresh.ts`, the review candidates of the operator snapshot): today a private event moves a shared preference's confidence and status, which every machine and remote caller then sees (out of scope of change `store-hardening`). Verify: a dream test on a switched machine with private evidence on a shared preference, asserting the decided outcome.
+- [x] 3.18 Decide and apply how private `apply-evidence` events take part in the dream and evidence computations (`evidence.ts`, `dream-refresh.ts`, the review candidates of the operator snapshot): today a private event moves a shared preference's confidence and status, which every machine and remote caller then sees (out of scope of change `store-hardening`). Verify: a dream test on a switched machine with private evidence on a shared preference, asserting the decided outcome. Done: design D15 item 4, spec brain-store "Private evidence stays out of shared preferences".
- [x] 3.19 Split the source files past the 700-line limit that the store readers touch (`src/core/brain/digest.ts`, `src/mcp/brain/query-tools.ts`, `src/mcp/resources.ts`, `src/mcp/brain/brief-tools.ts`, and the other MCP tool files past it), with no behaviour change. Verify: `wc -l` shows each under 700, and the suites of those modules pass unchanged.
- [x] 3.20 Keep the name of a lost private partition out of fail-closed reader errors served below local reach: `src/core/store/read/protection-store.ts` copies the store-open error, which names `private/store.json`, into findings such as `permissions-unreadable` that a remote caller receives (found in the second repair round of change `store-hardening`; the store check's own finding is already redacted). Verify: a remote-reach doctor test with a lost `private/store.json` whose whole answer does not contain `private`.
-- [ ] 3.21 Serialize the seen-shards ledger's read-modify-write (`update` in `src/core/store/seen-shards.ts`) under the device-local lock: two processes on one machine can interleave, so a stale write from `trackSeenShards` can bring back entries `o2b store partition leave` just cleared, or a leave can drop a shard another process just recorded (pull-request review of change `store-hardening`). Verify: a two-process test in which a tracked shard and a partition removal both survive.
+- [x] 3.21 Serialize the seen-shards ledger's read-modify-write (`update` in `src/core/store/seen-shards.ts`) under the device-local lock: two processes on one machine can interleave, so a stale write from `trackSeenShards` can bring back entries `o2b store partition leave` just cleared, or a leave can drop a shard another process just recorded (pull-request review of change `store-hardening`). Verify: a two-process test in which a tracked shard and a partition removal both survive. Done: design D15 item 5.
- [x] 3.22 Cache a read that skipped a quarantined pending blob: the entity read and the lane fold do not cache such a read (change `store-hardening`), so a blob that never arrives makes them rescan their shards on every call. Put the availability of the pending blobs into the cache fingerprint instead. Verify: the read is cached while the blob is absent, and the record appears on the first read after the blob arrives.
- [ ] 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.
diff --git a/src/core/brain/active.ts b/src/core/brain/active.ts
index c21872fa..b292a7e5 100644
--- a/src/core/brain/active.ts
+++ b/src/core/brain/active.ts
@@ -36,6 +36,7 @@ import { existsSync, mkdirSync, readdirSync, readFileSync } from "node:fs";
import { dirname, posix } from "node:path";
import { atomicWriteFileSync } from "../fs-atomic.ts";
+import { withPrivateShown } from "../store/caller-reach.ts";
import { parseFrontmatter } from "../vault.ts";
import { computeMostApplied, type MostAppliedEntry } from "./most-applied.ts";
import {
@@ -332,15 +333,18 @@ export function activeDigestPathForRead(
const stamp = readGeneratedAt(path);
const stampMs = stamp === null ? Number.NaN : Date.parse(stamp);
// One read pass: the check render and a regeneration share one log read.
- return withLogReadPass(() => {
- if (stamp !== null && !Number.isNaN(stampMs)) {
- // Keep the log window at the cached generation, but do not keep serving
- // a preference whose explicit expiration has passed since then.
- const atStamp = renderActiveAt(vault, { now: new Date(stampMs) }, now);
- if (readExistingBody(path) === atStamp.body.trim()) return path;
- }
- return regenerateActive(vault, { now }).path;
- });
+ // The cache is a local reader's file: checked with nothing withheld.
+ return withPrivateShown(() =>
+ withLogReadPass(() => {
+ if (stamp !== null && !Number.isNaN(stampMs)) {
+ // Keep the log window at the cached generation, but do not keep serving
+ // a preference whose explicit expiration has passed since then.
+ const atStamp = renderActiveAt(vault, { now: new Date(stampMs) }, now);
+ if (readExistingBody(path) === atStamp.body.trim()) return path;
+ }
+ return regenerateActive(vault, { now }).path;
+ }),
+ );
}
/**
@@ -360,7 +364,10 @@ export function regenerateActive(
if (!onDemand && vault !== null) assertVaultIdentityForWrite(vault);
const path =
onDemand || vault === null ? digestCachePath(vault, "active") : brainActivePath(vault);
- const rendered = renderActive(vault, { now });
+ // The file is shared with every later reader, so it is rendered with
+ // nothing withheld even for a caller below local reach (who is served
+ // its own render, `renderActiveForReader`).
+ const rendered = withPrivateShown(() => renderActive(vault, { now }));
// `readExistingBody` returns the trimmed body (parseFrontmatter
// trims internally), so compare against the trimmed render for an
diff --git a/src/core/brain/doctor-exits.ts b/src/core/brain/doctor-exits.ts
index 6c40764b..0a3f946d 100644
--- a/src/core/brain/doctor-exits.ts
+++ b/src/core/brain/doctor-exits.ts
@@ -192,6 +192,19 @@ const EXCLUSIONS: ReadonlyArray<DoctorExitExclusion> = [
"which of the two is still needed only the user can tell, so the remedy is to compare, " +
"copy over and delete the folder by hand",
},
+ {
+ code: "lane-folder-unimportable",
+ reason:
+ "which name each folder of the user's own legacy tree should take is the user's choice, " +
+ "and renaming a folder moves the user's files, so the remedy is a rename by hand",
+ },
+ {
+ code: "lane-id-misfiled",
+ reason:
+ "the repair runs only on a machine that holds the private partition, which may be " +
+ "another machine than the one running doctor, and on a store where none holds it the " +
+ "partition must first be added on one; the finding names which of the two applies",
+ },
{
code: "store-device-state-foreign",
reason:
diff --git a/src/core/brain/doctor.ts b/src/core/brain/doctor.ts
index 5f2f91df..38ef1126 100644
--- a/src/core/brain/doctor.ts
+++ b/src/core/brain/doctor.ts
@@ -100,6 +100,7 @@ import { auditStaleDependencies } from "./stale-dependency.ts";
import { frozenVaultCheck } from "./doctor/frozen-check.ts";
import { deviceStateCheck } from "./doctor/device-state-check.ts";
import { adoptConflictsCheck } from "./doctor/adopt-conflicts-check.ts";
+import { laneFolderCollisionCheck, laneIdMisfiledCheck } from "./doctor/lane-id-check.ts";
import { migrationCheck } from "./doctor/migration-check.ts";
import { storeCheck } from "./doctor/store-check.ts";
import { runStoreSideDoctor } from "./doctor/store-side-pass.ts";
@@ -283,6 +284,9 @@ const DOCTOR_CHECKS: ReadonlyArray<DoctorCheck> = Object.freeze([
migrationCheck,
// Machine state a switch kept aside (task 2.10).
adoptConflictsCheck,
+ // Lane ids an earlier release filed under another path (task 3.9).
+ laneIdMisfiledCheck,
+ laneFolderCollisionCheck,
denyConsultedLanesCheck,
]);
diff --git a/src/core/brain/doctor/lane-id-check.ts b/src/core/brain/doctor/lane-id-check.ts
new file mode 100644
index 00000000..de7ab517
--- /dev/null
+++ b/src/core/brain/doctor/lane-id-check.ts
@@ -0,0 +1,148 @@
+/**
+ * The doctor finding for lane entry ids an earlier release filed under
+ * another path's id (task 3.9, design D15 item 1): a migrated page
+ * `x.json.md` whose record sits under `x.json`. A store-only dream pass on
+ * a machine that holds `private` repairs them
+ * (`store-migration/lane-id-repair.ts`); a machine without `private` never
+ * runs the repair, since a file's own record there may be invisible to it,
+ * so on a store where no machine holds `private` the ids stay mis-filed
+ * until one does. The finding names them on every machine, with what to
+ * run. Read-only.
+ */
+
+import { readdirSync } from "node:fs";
+import { join } from "node:path";
+
+import { BRAIN_ROOT_REL } from "../path-constants.ts";
+import {
+ brainRelOfEntry,
+ laneFolderRivals,
+ lanePlaceOf,
+ normalizedFolderPlace,
+} from "../../store/lane-paths.ts";
+import { configuredStore } from "../../store/read/store-entities.ts";
+import { misfiledLaneIds } from "../../store-migration/lane-id-repair.ts";
+import { TRANSPORT_REACH } from "../../graph/transport-reach.ts";
+import { withholdsPrivate } from "./store-check.ts";
+import { pushUncertain } from "./uncertain-stream.ts";
+import type {
+ DoctorCheck,
+ DoctorCheckContext,
+ DoctorFindings,
+ StoreSideCheckContext,
+ StoreSideDoctorCheck,
+} from "./check.ts";
+
+/** Lane entries filed under the id of another path. */
+export const LANE_ID_MISFILED_CODE = "lane-id-misfiled";
+
+/** How many mis-filed entries the message names. */
+const NAMED = 5;
+
+export const laneIdMisfiledCheck: StoreSideDoctorCheck = {
+ failSoft: true,
+ run(ctx: StoreSideCheckContext, out: DoctorFindings): void {
+ // Below local reach only the repairs no record of the `private`
+ // partition takes part in are named and counted.
+ // And only the pages the caller may read, by both paths they answer to.
+ const readable = ctx.readable;
+ const pathOf = (key: string): string => {
+ const [lane, ...rest] = key.split("/");
+ return `${BRAIN_ROOT_REL}/${brainRelOfEntry(lane!, rest.join("/"))}`;
+ };
+ const misfiled = misfiledLaneIds(ctx.configPath, {
+ sharedOnly: withholdsPrivate(ctx),
+ }).filter(
+ (r) => readable === undefined || (readable(pathOf(r.from)) && readable(pathOf(r.to))),
+ );
+ if (misfiled.length === 0) return;
+ const store = configuredStore(ctx.configPath);
+ const named = misfiled
+ .slice(0, NAMED)
+ .map((r) => `${r.from} (its own id is ${r.to})`)
+ .join(", ");
+ const more = misfiled.length > NAMED ? `, and ${misfiled.length - NAMED} more` : "";
+ // Below local reach one remedy for every machine: which partitions this
+ // machine holds is not the caller's to learn.
+ const remedy = withholdsPrivate(ctx)
+ ? "run `o2b brain dream` on a machine that holds every partition, or run `brain_doctor` " +
+ "locally for the exact remedy"
+ : store?.partitions.has("private") === true
+ ? "the next `o2b brain dream` on this machine repairs them"
+ : "this machine does not hold the private partition, so it does not repair them: run " +
+ "`o2b brain dream` on a machine that holds it, or, when no machine does, add it on one " +
+ "with `o2b store init --partitions shared,private` and run `o2b brain dream` there";
+ out.issues.push({
+ severity: "warning",
+ code: LANE_ID_MISFILED_CODE,
+ path: store?.root ?? "",
+ message:
+ `${misfiled.length} lane page(s) an earlier release imported are filed under the id of ` +
+ `another path, so no path reads them: ${named}${more}. ${remedy}`,
+ });
+ },
+};
+
+/** Top folders of the legacy tree whose pages the migration cannot import. */
+export const LANE_FOLDER_UNIMPORTABLE_CODE = "lane-folder-unimportable";
+
+/**
+ * The top folders of a vault's legacy `Brain/` tree whose pages no lane
+ * takes (task 3.9): a folder whose name maps to no lane of its own (the
+ * root lane, another folder's lane, no lane name at all), or one whose
+ * lane another folder of the tree takes too (`My Notes/` beside
+ * `my-notes/`). The migration lists their pages as items it could not
+ * convert and archives them; renaming the folder before migrating keeps
+ * them. A folder spelled otherwise than its lane with no rival is
+ * imported under its lane, so it is not named. Read-only.
+ */
+export const laneFolderCollisionCheck: DoctorCheck = {
+ failSoft: true,
+ run(ctx: DoctorCheckContext, out: DoctorFindings): void {
+ const brain = join(ctx.vault, BRAIN_ROOT_REL);
+ let folders: string[];
+ try {
+ folders = readdirSync(brain, { withFileTypes: true })
+ .filter((d) => d.isDirectory() && !d.name.startsWith("."))
+ .map((d) => d.name);
+ } catch {
+ return;
+ }
+ const named: string[] = [];
+ for (const folder of folders) {
+ // A probe page: only the folder's name decides.
+ if (lanePlaceOf(`${folder}/probe.md`) !== null) continue;
+ const place = normalizedFolderPlace(`${folder}/probe.md`);
+ if (place === null) {
+ named.push(`${folder} (its name is no lane of its own)`);
+ continue;
+ }
+ const rivals = laneFolderRivals(folders, folder, place.lane);
+ if (rivals.length > 0)
+ named.push(`${folder} (lane ${place.lane}, also ${rivals.join(", ")})`);
+ }
+ if (named.length === 0) return;
+ // Folder names of the vault, and how many: a local-reach fact. Below
+ // local reach the finding is stated by name only, with no names or
+ // figures.
+ if (ctx.reach !== undefined && ctx.reach !== TRANSPORT_REACH.local) {
+ pushUncertain(out.uncertain, {
+ code: LANE_FOLDER_UNIMPORTABLE_CODE,
+ path: brain,
+ message:
+ "some folders of the legacy tree would not import; run brain_doctor locally to see " +
+ "which",
+ });
+ return;
+ }
+ out.issues.push({
+ severity: "warning",
+ code: LANE_FOLDER_UNIMPORTABLE_CODE,
+ path: brain,
+ message:
+ `the migration cannot import the pages of ${named.length} folder(s) of the legacy ` +
+ `${BRAIN_ROOT_REL} tree and would archive them: ${named.join("; ")}. Rename each to a ` +
+ "lane name of its own (lowercase letters, digits and hyphens) before migrating",
+ });
+ },
+};
diff --git a/src/core/brain/doctor/records.ts b/src/core/brain/doctor/records.ts
index baef406c..079a9b54 100644
--- a/src/core/brain/doctor/records.ts
+++ b/src/core/brain/doctor/records.ts
@@ -19,6 +19,8 @@
import { existsSync, readdirSync, type Dirent } from "node:fs";
import { join } from "node:path";
+import { compareCodeUnits } from "../../store/compare.ts";
+
import { memoryFromStore, storeRecordPages, UNSTAGED_STATES } from "../memory-pages.ts";
import { storePreferenceRecords, storeRetiredRecords } from "../memory-page-records.ts";
import { storeLogDays } from "../log-days.ts";
@@ -66,9 +68,17 @@ const MARKDOWN_EXT = ".md";
* a directory nobody created - and those are different findings.
*/
function listRecordDir(dir: string, swept: SweptPath | undefined): Dirent[] | null {
- if (swept !== undefined) return readSweptDir(dir, swept, SWEEP_ORIGIN.root);
- if (!existsSync(dir)) return null;
- return readdirSync(dir, { withFileTypes: true });
+ const entries =
+ swept !== undefined
+ ? readSweptDir(dir, swept, SWEEP_ORIGIN.root)
+ : existsSync(dir)
+ ? readdirSync(dir, { withFileTypes: true })
+ : null;
+ // In name order: `readdir` answers in whatever order the filesystem
+ // keeps (hash order on ext4), and the records of a store-only machine
+ // come sorted by path, so an unsorted listing made the two machines'
+ // answers differ in order only.
+ return entries === null ? null : entries.toSorted((a, b) => compareCodeUnits(a.name, b.name));
}
/** The read context of the machine config the doctor was started against. */
diff --git a/src/core/brain/doctor/store-side-pass.ts b/src/core/brain/doctor/store-side-pass.ts
index 43de7ea7..5f5ba228 100644
--- a/src/core/brain/doctor/store-side-pass.ts
+++ b/src/core/brain/doctor/store-side-pass.ts
@@ -16,6 +16,7 @@ import { computeTrustVerdict } from "../trust/compute-trust-verdict.ts";
import type { TrustVerdict } from "../types.ts";
import type { DoctorFindings, StoreSideDoctorCheck } from "./check.ts";
import { adoptConflictsCheck } from "./adopt-conflicts-check.ts";
+import { laneIdMisfiledCheck } from "./lane-id-check.ts";
import { deviceStateCheck } from "./device-state-check.ts";
import type { RunDoctorOptions, RunDoctorResult } from "./report.ts";
import { storeCheck } from "./store-check.ts";
@@ -27,6 +28,7 @@ export const STORE_SIDE_CHECKS: ReadonlyArray<StoreSideDoctorCheck> = Object.fre
viewWriterCheck,
deviceStateCheck,
adoptConflictsCheck,
+ laneIdMisfiledCheck,
]);
/**
diff --git a/src/core/brain/dream-refresh.ts b/src/core/brain/dream-refresh.ts
index 007e4196..571269a4 100644
--- a/src/core/brain/dream-refresh.ts
+++ b/src/core/brain/dream-refresh.ts
@@ -10,7 +10,9 @@
import { BAND_RANK, computeConfidence, rebandConfidence } from "./confidence.ts";
import type { PlanState, ScanResult } from "./dream-plan.ts";
-import { collectEvidenceForSlug } from "./evidence.ts";
+import { collectEvidenceForSlug, privateEvidenceCounts } from "./evidence.ts";
+import { preferencesStoreOnly, storePreferenceEntry } from "./preference-store.ts";
+import { countersForShared } from "../store/read/store-entities.ts";
import { logDayReader } from "./log-days.ts";
import { isPinned } from "./pin.ts";
import { wouldRewritePreference } from "./preference.ts";
@@ -131,6 +133,8 @@ export interface ApplyEvidenceEntry {
readonly result: (typeof BRAIN_APPLY_RESULT)[keyof typeof BRAIN_APPLY_RESULT];
/** Downstream outcome when recorded (t_d478df53). */
readonly outcome?: "success" | "failure";
+ /** The event was read from the `private` partition (see `evidence.ts`). */
+ readonly fromPrivatePartition?: true;
}
export function scanApplyEvidence(vault: string | null): ApplyEvidenceEntry[] {
@@ -172,19 +176,45 @@ export function scanApplyEvidence(vault: string | null): ApplyEvidenceEntry[] {
...(e.body["outcome"] === "success" || e.body["outcome"] === "failure"
? { outcome: e.body["outcome"] as "success" | "failure" }
: {}),
+ ...(e.fromPrivatePartition === true ? { fromPrivatePartition: true as const } : {}),
});
}
}
- const resolved = out.map((entry) => ({
- ...entry,
- pref_slug: resolveMergeAlias(entry.pref_slug, mergeAliases),
- }));
+ // A private event counts only toward a private preference (`evidence.ts`),
+ // judged after the merge aliases name the preference it lands on.
+ const takesPrivate = new Map<string, boolean>();
+ const counts = (slug: string): boolean => {
+ let known = takesPrivate.get(slug);
+ if (known === undefined) {
+ known = privateEvidenceCounts(slug);
+ takesPrivate.set(slug, known);
+ }
+ return known;
+ };
+ const resolved = out
+ .map((entry) => ({
+ ...entry,
+ pref_slug: resolveMergeAlias(entry.pref_slug, mergeAliases),
+ }))
+ .filter((entry) => entry.fromPrivatePartition !== true || counts(entry.pref_slug));
// Stable order: by timestamp ascending. Multiple entries at the same
// second keep their parse order (parseLogDay returns insertion order).
resolved.sort((a, b) => Date.parse(a.timestamp) - Date.parse(b.timestamp));
return resolved;
}
+/** The applied and violated counts of `pref` as the dream scan counts evidence. */
+function priorCounters(
+ vault: string | null,
+ slug: string,
+ pref: { readonly applied_count: number; readonly violated_count: number },
+): { readonly applied: number; readonly violated: number } {
+ const entry = preferencesStoreOnly(vault) ? storePreferenceEntry(slug) : undefined;
+ if (entry === undefined) return { applied: pref.applied_count, violated: pref.violated_count };
+ const counters = countersForShared(entry);
+ return { applied: counters.applied_count, violated: counters.violated_count };
+}
+
function parseWikilinkFromBodyValue(value: unknown): string | null {
return typeof value === "string" ? parseWikilink(value) : null;
}
@@ -230,6 +260,10 @@ export function planRefresh(
for (const rec of scan.preferences) {
const slug = rec.pref.id.startsWith("pref-") ? rec.pref.id.slice("pref-".length) : rec.pref.id;
if (retiringSlugs.has(slug)) continue;
+ // The counters the preference holds now, counted by the rule the scan
+ // counts its evidence by: a shared preference's private uses are left
+ // out (`evidence.ts`), or every pass would see them as a change.
+ const prior = priorCounters(vault, slug, rec.pref);
const ev = bySlug.get(slug) ?? [];
const applied = ev.filter((e) => e.result === BRAIN_APPLY_RESULT.applied).length;
@@ -277,7 +311,7 @@ export function planRefresh(
) {
status = BRAIN_PREFERENCE_STATUS.quarantine;
} else if (status === BRAIN_PREFERENCE_STATUS.quarantine) {
- const newViolated = violated > rec.pref.violated_count;
+ const newViolated = violated > prior.violated;
if (newViolated) {
if (isPinned(rec.pref)) {
plan.retainPinned.push({
@@ -348,8 +382,8 @@ export function planRefresh(
const valueDifferent =
previousValue !== null && Math.abs(previousValue - confidence.value) > 1e-6;
const countersChanged =
- applied !== rec.pref.applied_count ||
- violated !== rec.pref.violated_count ||
+ applied !== prior.applied ||
+ violated !== prior.violated ||
lastEvidence !== rec.pref.last_evidence_at ||
status !== rec.pref.status ||
confirmedAt !== rec.pref.confirmed_at ||
diff --git a/src/core/brain/dream.ts b/src/core/brain/dream.ts
index 12b8154c..61e2df3b 100644
--- a/src/core/brain/dream.ts
+++ b/src/core/brain/dream.ts
@@ -100,6 +100,7 @@ import { buildLinkCandidateManifest, type LinkCandidateManifest } from "./notes/
import { gatedOwnerScopeView } from "./owner-scope-view.ts";
import { brainDirsForWrite, collisionCandidateName } from "./paths.ts";
import { isStoreOnly } from "../store/store-only.ts";
+import { repairLaneEntryIds } from "../store-migration/lane-id-repair.ts";
import { loadBrainConfig } from "./policy.ts";
import { buildReconcileOutcomes } from "./reconcile-outcomes.ts";
import {
@@ -308,6 +309,16 @@ function dreamRun(
progress.start(DREAM_STAGE.scan);
opts.safeguard?.checkpoint();
const cfg = loadBrainConfig(vault);
+ // Lane entries an earlier release filed under another path's id are
+ // moved to their own (`store-migration/lane-id-repair.ts`); a no-op once
+ // repaired, and never a reason to fail the pass.
+ if (!dryRun && (vault === null || isStoreOnly({ vault }))) {
+ try {
+ repairLaneEntryIds(vault);
+ } catch {
+ // The next pass tries again.
+ }
+ }
// Per-run gate resolution (no-dead-ends, Unit E): the override wins for
// this run, the configured value decides when it is absent. Resolved
// once, here, so the heal branch below has a single source of truth and
diff --git a/src/core/brain/evidence.ts b/src/core/brain/evidence.ts
index da61bab4..3013738e 100644
--- a/src/core/brain/evidence.ts
+++ b/src/core/brain/evidence.ts
@@ -6,8 +6,23 @@
* pass, so the file mirrors what the counters say.
*
* Pure read: no I/O outside reading log files.
+ *
+ * ## Private evidence on a shared preference (task 3.18)
+ *
+ * On a store-only machine an `apply-evidence` event lands in `private`
+ * when its artifact or note names a private page, even when the
+ * preference it targets is shared. Such an event never counts toward a
+ * shared preference: the counters, the status, the confidence and the
+ * `## Recent ...` sections it would move live on the shared preference
+ * record, which every machine and remote caller reads, so counting it
+ * would publish what the private partition holds. It counts toward a
+ * preference that is itself private, whose record stays in `private`.
+ * The event stays in this machine's private log, where a local reader
+ * sees it. {@link privateEvidenceCounts} is the one rule both the dream
+ * scan and this collector apply.
*/
+import { storePreferenceEntry } from "./preference-store.ts";
import { logDayReader } from "./log-days.ts";
import {
BRAIN_APPLY_RESULT,
@@ -41,6 +56,20 @@ export function listLogDays(vault: string): string[] {
return days;
}
+/**
+ * Whether a private `apply-evidence` event may count toward the preference
+ * `pref-<slug>`: only when that preference is known to be private. A
+ * preference the store does not resolve takes none (fail closed: counting
+ * could publish the event on a shared record).
+ */
+export function privateEvidenceCounts(slug: string): boolean {
+ try {
+ return storePreferenceEntry(slug)?.private === true;
+ } catch {
+ return false;
+ }
+}
+
export interface CollectEvidenceOptions {
/** Maximum `applied` rows to return. Default 5. */
readonly maxApplied?: number;
@@ -94,6 +123,7 @@ export function collectEvidenceForSlug(
} catch {
return { applied, violated };
}
+ let takesPrivate: boolean | undefined;
for (const day of dates.toReversed()) {
if (cutoff && day < cutoff.slice(0, 10)) break;
const { entries } = log.day(day);
@@ -105,6 +135,9 @@ export function collectEvidenceForSlug(
if (cutoff && e.timestamp < cutoff) continue;
const prefRef = e.body["preference"];
if (typeof prefRef !== "string" || !eqId(prefRef, slug)) continue;
+ if (e.fromPrivatePartition === true && !(takesPrivate ??= privateEvidenceCounts(slug))) {
+ continue;
+ }
const result = e.body["result"];
if (typeof result !== "string") continue;
const artifact = typeof e.body["artifact"] === "string" ? e.body["artifact"] : "";
diff --git a/src/core/brain/memory-pages.ts b/src/core/brain/memory-pages.ts
index d660ba47..0845e99f 100644
--- a/src/core/brain/memory-pages.ts
+++ b/src/core/brain/memory-pages.ts
@@ -66,6 +66,7 @@ import {
BRAIN_RETIRED_REL,
} from "./path-constants.ts";
import { storeEntryMeta } from "./preference-page-meta.ts";
+import { privateWithheld } from "../store/caller-reach.ts";
import { preferencePageBody } from "./preference-body.ts";
import { CODEC_VERSION, expand } from "./portability/codec.ts";
import { textOfFields } from "./preference-store.ts";
@@ -369,7 +370,9 @@ function rebuiltPages(
byVault = new Map();
REBUILT_PAGES.set(entities, byVault);
}
- const key = vault ?? "\u0000no-vault";
+ // A caller below local reach gets the counters without the private
+ // partition's evidence (`store/caller-reach.ts`): its pages are kept apart.
+ const key = `${privateWithheld() ? "withheld" : "all"}\u0000${vault ?? "\u0000no-vault"}`;
const known = byVault.get(key);
if (known !== undefined) return known;
const pages: StoreMemoryPage[] = [];
diff --git a/src/core/brain/merge.ts b/src/core/brain/merge.ts
index 7643e4d3..91bd9099 100644
--- a/src/core/brain/merge.ts
+++ b/src/core/brain/merge.ts
@@ -35,6 +35,7 @@ import { storeWrite } from "../store/store-write.ts";
import { regenerateActiveQuiet } from "./active.ts";
import { preferencesStoreOnly, storePreferenceEntry } from "./preference-store.ts";
+import { countersForShared } from "../store/read/store-entities.ts";
import { computeContentHash } from "./content-hash.ts";
import { buildEntityIndex } from "./entities/index-builder.ts";
import { guardEntityMerge, type GuardEntityLike } from "./truth/merge-guard.ts";
@@ -206,8 +207,42 @@ export function mergePreferences(
}
const merged_evidenced_by = mergeEvidencedBy(keep.evidenced_by, drop.evidenced_by);
- const applied_sum = keep.applied_count + drop.applied_count;
- const violated_sum = keep.violated_count + drop.violated_count;
+ // Once switched, a shared preference's private uses stay out of the
+ // sums the merge log event and audit trail carry (task 3.18), and a drop
+ // record an earlier, interrupted run of this merge already copied to the
+ // keep is counted once, in the keep's counters.
+ const counts = (pref: typeof keep, slug: string) => {
+ const entry = storeOnly ? storePreferenceEntry(slug) : undefined;
+ if (entry === undefined) return { applied: pref.applied_count, violated: pref.violated_count };
+ const counters = countersForShared(entry);
+ return { applied: counters.applied_count, violated: counters.violated_count };
+ };
+ const keepCounts = counts(keep, keepSlug);
+ const dropCounts = ((): { applied: number; violated: number } => {
+ const dropEntry = storeOnly ? storePreferenceEntry(dropSlug) : undefined;
+ if (dropEntry === undefined) return counts(drop, dropSlug);
+ const copied = new Set(
+ (storePreferenceEntry(keepSlug)?.state.history ?? [])
+ .map((record) => record.body[MERGED_FROM_FIELD])
+ .filter((id): id is string => typeof id === "string"),
+ );
+ let applied = 0;
+ let violated = 0;
+ for (const record of dropEntry.state.history) {
+ if (record.kind !== PREFERENCE_EVIDENCE_KIND || copied.has(record.id)) continue;
+ // A private use counts unless the keep it lands on is shared: copied
+ // to a private keep (or from a private drop) it is part of the keep.
+ const keepPrivate = storePreferenceEntry(keepSlug)?.private ?? true;
+ if (!dropEntry.private && !keepPrivate && dropEntry.privateRecordIds.has(record.id)) {
+ continue;
+ }
+ if (record.body["result"] === "applied") applied += 1;
+ else if (record.body["result"] === "violated") violated += 1;
+ }
+ return { applied, violated };
+ })();
+ const applied_sum = keepCounts.applied + dropCounts.applied;
+ const violated_sum = keepCounts.violated + dropCounts.violated;
const last_evidence_at = maxIso(keep.last_evidence_at, drop.last_evidence_at);
const plan: MergePlan = Object.freeze({
@@ -278,20 +313,29 @@ export function mergePreferences(
);
if (evidence.length > 0) {
const pairPrivate = (keepEntry?.private ?? true) || (dropEntry?.private ?? true);
- storeWrite(
- () =>
- evidence.map((record) =>
- preferenceEvidenceRecord({
- id: keep.id,
- result: record.body["result"] as EvidenceResult,
- artifact: typeof record.body["artifact"] === "string" ? record.body["artifact"] : "",
- agent: opts.agentName ?? "merge",
- private: pairPrivate,
- mergedFrom: record.id,
- }),
- ),
- { vault },
- );
+ // A record of the drop that sits in `private` (its artifact named a
+ // private page) stays there as a copy too. One store write lands in
+ // one partition, so the shared and the private copies are two writes.
+ const isPrivate = (record: (typeof evidence)[number]): boolean =>
+ pairPrivate || (dropEntry?.privateRecordIds.has(record.id) ?? true);
+ for (const group of [evidence.filter((r) => !isPrivate(r)), evidence.filter(isPrivate)]) {
+ if (group.length === 0) continue;
+ storeWrite(
+ () =>
+ group.map((record) =>
+ preferenceEvidenceRecord({
+ id: keep.id,
+ result: record.body["result"] as EvidenceResult,
+ artifact:
+ typeof record.body["artifact"] === "string" ? record.body["artifact"] : "",
+ agent: opts.agentName ?? "merge",
+ private: isPrivate(record),
+ mergedFrom: record.id,
+ }),
+ ),
+ { vault },
+ );
+ }
}
}
@@ -356,8 +400,8 @@ export function mergePreferences(
keep: renderPrefLink({ id: keep.id, principle: keep.principle }),
drop: renderPrefLink({ id: drop.id, principle: drop.principle }),
signal_union: `${merged_evidenced_by.length} (was ${keep.evidenced_by.length}, ${drop.evidenced_by.length})`,
- applied_sum: `${applied_sum} (was ${keep.applied_count}, ${drop.applied_count})`,
- violated_sum: `${violated_sum} (was ${keep.violated_count}, ${drop.violated_count})`,
+ applied_sum: `${applied_sum} (was ${keepCounts.applied}, ${dropCounts.applied})`,
+ violated_sum: `${violated_sum} (was ${keepCounts.violated}, ${dropCounts.violated})`,
agent: opts.agentName ?? "unknown",
},
},
diff --git a/src/core/brain/paths.ts b/src/core/brain/paths.ts
index eed5bd0f..3f5eec1a 100644
--- a/src/core/brain/paths.ts
+++ b/src/core/brain/paths.ts
@@ -593,19 +593,23 @@ export function proceduralMemoryIndexPath(vault: string): string {
return ensureInsideVault(join(vault, BRAIN_PROCEDURAL_MEMORY_REL, "index.json"), vault);
}
-/** Procedural-memory usage sidecar path: `Brain/procedural-memory/usage.jsonl`. */
+/**
+ * Procedural-memory usage counters: `Brain/procedural-memory/usage.jsonl`,
+ * machine state (device-local once switched). They tick on every use, so a
+ * synced record per tick would grow the store without bound (task 3.10).
+ */
export function proceduralMemoryUsagePath(vault: string): string {
- return ensureInsideVault(join(vault, BRAIN_PROCEDURAL_MEMORY_REL, "usage.jsonl"), vault);
+ return machineStatePath(vault, BRAIN_PROCEDURAL_MEMORY_REL, "usage.jsonl");
}
-/** Procedural graph projection path: `Brain/procedural-memory/graph.json`. */
+/** Procedural graph projection: `Brain/procedural-memory/graph.json`, machine state. */
export function proceduralGraphPath(vault: string): string {
- return ensureInsideVault(join(vault, BRAIN_PROCEDURAL_MEMORY_REL, "graph.json"), vault);
+ return machineStatePath(vault, BRAIN_PROCEDURAL_MEMORY_REL, "graph.json");
}
-/** Prospective recall hints path: `Brain/procedural-memory/hints.json`. */
+/** Prospective recall hints: `Brain/procedural-memory/hints.json`, machine state. */
export function proceduralHintsPath(vault: string): string {
- return ensureInsideVault(join(vault, BRAIN_PROCEDURAL_MEMORY_REL, "hints.json"), vault);
+ return machineStatePath(vault, BRAIN_PROCEDURAL_MEMORY_REL, "hints.json");
}
/** Declarative attention-flows directory: `Brain/attention/flows/`. */
diff --git a/src/core/brain/preference-page-meta.ts b/src/core/brain/preference-page-meta.ts
index b3ae3b49..060bd13f 100644
--- a/src/core/brain/preference-page-meta.ts
+++ b/src/core/brain/preference-page-meta.ts
@@ -9,7 +9,7 @@
* would carry, typed as the legacy parser types it.
*/
-import type { StorePreference } from "../store/read/store-entities.ts";
+import { countersAtReach, type StorePreference } from "../store/read/store-entities.ts";
import type { FrontmatterMap } from "../types.ts";
import { formatFrontmatter, parseFrontmatterText } from "../vault.ts";
import { isRetiredEntry } from "./preference-store.ts";
@@ -55,8 +55,10 @@ export function storeEntryMeta(
if (DERIVED_FIELD_SET.has(name)) meta[`_${name}`] = value === null ? "null" : value;
else if (value !== null) meta[name] = value;
}
- meta["_applied_count"] = entry.state.counters.applied_count;
- meta["_violated_count"] = entry.state.counters.violated_count;
+ // Below local reach without the private partition's evidence (task 3.18).
+ const counters = countersAtReach(entry);
+ meta["_applied_count"] = counters.applied_count;
+ meta["_violated_count"] = counters.violated_count;
meta["kind"] = retired ? "brain-retired" : "brain-preference";
meta["id"] = `${retired ? "ret" : "pref"}-${slug}`;
const [typed] = parseFrontmatterText(formatFrontmatter(meta as FrontmatterMap, ""));
diff --git a/src/core/brain/procedural-graph.ts b/src/core/brain/procedural-graph.ts
index 934faa7e..32bc2007 100644
--- a/src/core/brain/procedural-graph.ts
+++ b/src/core/brain/procedural-graph.ts
@@ -1,5 +1,8 @@
+import { mkdirSync, readFileSync } from "node:fs";
import { basename, dirname, join } from "node:path";
+import { atomicWriteFileSync } from "../fs-atomic.ts";
+
import { ensureInsideVault } from "../path-safety.ts";
import {
proceduralGraphPath,
@@ -15,8 +18,10 @@ import {
lanePageExists,
listLaneFiles,
parseLanePage,
- writeLaneText,
+ lanePagesInStore,
+ readLaneText,
} from "../store/lane-pages.ts";
+import { BRAIN_PROCEDURAL_MEMORY_REL } from "./path-constants.ts";
export type ProceduralGraphNodeKind = "procedure" | "skill" | "runbook" | "proposal" | "entity";
export type ProceduralGraphEdgeKind =
@@ -143,16 +148,87 @@ export function rebuildProceduralGraph(
),
};
- const path = proceduralGraphPath(vault);
- writeLaneText(vault, path, `${JSON.stringify(projection, null, 2)}\n`);
+ writeMachineStateText(proceduralGraphPath(vault), `${JSON.stringify(projection, null, 2)}\n`);
return projection;
}
+/**
+ * Write a procedural projection or counter file. They are machine state
+ * (`paths.ts`), never store records: the graph and the hints are
+ * recomputed on each machine, and the counters tick on every use.
+ */
+export function writeMachineStateText(path: string, text: string): void {
+ mkdirSync(dirname(path), { recursive: true });
+ atomicWriteFileSync(path, text);
+}
+
+/** The text of a machine-state file, or null when there is none. */
+function readMachineStateText(path: string): string | null {
+ try {
+ return readFileSync(path, "utf8");
+ } catch {
+ return null;
+ }
+}
+
+/**
+ * The text of the procedural projection or counter file at `path` (its
+ * machine-state location), or null when there is none.
+ *
+ * A machine switched before these files became machine state (task 3.10)
+ * holds them as `lane-entry` records of the store, the migration's import
+ * of the legacy files. Until this machine has its own copy, that record is
+ * read and adopted: copied into the machine-state location on the first
+ * read, so a switched machine answers from it before its next reconcile.
+ * The record itself stays in the store until the legacy tree leaves the
+ * vault (`store-migration/removal.ts` retires it then), so a rollback
+ * still finds the legacy file it was imported from.
+ *
+ * `guard` runs the adoption write: a file other writers update (the usage
+ * counters) passes the run of its write lock, and the copy is written only
+ * when the file is still absent inside it, so an adoption never lands over
+ * a tick another process wrote first. A caller that already holds the lock
+ * passes none.
+ */
+export function readProceduralState(
+ vault: string,
+ path: string,
+ guard: (write: () => void) => void = (write) => write(),
+): string | null {
+ const own = readMachineStateText(path);
+ if (own !== null) return own;
+ if (!lanePagesInStore(vault)) return null;
+ const stored = join(vault, BRAIN_PROCEDURAL_MEMORY_REL, basename(path));
+ if (stored === path) return null;
+ let text: string | null;
+ try {
+ text = readLaneText(vault, stored);
+ } catch {
+ return null;
+ }
+ if (text === null) return null;
+ let answer = text;
+ try {
+ guard(() => {
+ // Another process may have adopted (and ticked) it meanwhile.
+ const now = readMachineStateText(path);
+ if (now !== null) {
+ answer = now;
+ return;
+ }
+ writeMachineStateText(path, text);
+ });
+ } catch {
+ // Adopted on the next read instead; the answer stands.
+ }
+ return answer;
+}
+
export function readProceduralGraph(vault: string): ProceduralGraphProjection | null {
- const path = proceduralGraphPath(vault);
- if (!lanePageExists(vault, path)) return null;
+ const text = readProceduralState(vault, proceduralGraphPath(vault));
+ if (text === null) return null;
try {
- const parsed = JSON.parse(readLaneFile(vault, path)) as ProceduralGraphProjection;
+ const parsed = JSON.parse(text) as ProceduralGraphProjection;
if (parsed.schema_version !== 1) return null;
if (!Array.isArray(parsed.nodes) || !Array.isArray(parsed.edges)) return null;
return parsed;
diff --git a/src/core/brain/procedural-hints.ts b/src/core/brain/procedural-hints.ts
index d9e0f416..06f39755 100644
--- a/src/core/brain/procedural-hints.ts
+++ b/src/core/brain/procedural-hints.ts
@@ -1,11 +1,11 @@
import { proceduralHintsPath } from "./paths.ts";
-import { readProceduralGraph, type ProceduralGraphProjection } from "./procedural-graph.ts";
import {
- assertLaneWrite,
- readLaneFile,
- lanePageExists,
- writeLaneText,
-} from "../store/lane-pages.ts";
+ readProceduralState,
+ readProceduralGraph,
+ writeMachineStateText,
+ type ProceduralGraphProjection,
+} from "./procedural-graph.ts";
+import { assertLaneWrite } from "../store/lane-pages.ts";
export interface ProceduralHintEntry {
readonly node_id: string;
@@ -59,16 +59,15 @@ export function rebuildProceduralHints(
entries: Object.freeze(entries.toSorted((l, r) => l.node_id.localeCompare(r.node_id))),
};
- const path = proceduralHintsPath(vault);
- writeLaneText(vault, path, `${JSON.stringify(projection, null, 2)}\n`);
+ writeMachineStateText(proceduralHintsPath(vault), `${JSON.stringify(projection, null, 2)}\n`);
return projection;
}
export function readProceduralHints(vault: string): ProceduralHintsProjection | null {
- const path = proceduralHintsPath(vault);
- if (!lanePageExists(vault, path)) return null;
+ const text = readProceduralState(vault, proceduralHintsPath(vault));
+ if (text === null) return null;
try {
- const parsed = JSON.parse(readLaneFile(vault, path)) as ProceduralHintsProjection;
+ const parsed = JSON.parse(text) as ProceduralHintsProjection;
if (parsed.schema_version !== 1) return null;
if (!Array.isArray(parsed.entries)) return null;
return parsed;
diff --git a/src/core/brain/procedural-memory.ts b/src/core/brain/procedural-memory.ts
index 9a8fd98c..89728f58 100644
--- a/src/core/brain/procedural-memory.ts
+++ b/src/core/brain/procedural-memory.ts
@@ -9,7 +9,11 @@ import { BRAIN_ROOT_REL } from "./path-constants.ts";
import { ensureInsideVault } from "../path-safety.ts";
import { rebuildProceduralHints } from "./procedural-hints.ts";
-import { rebuildProceduralGraph } from "./procedural-graph.ts";
+import {
+ readProceduralState,
+ rebuildProceduralGraph,
+ writeMachineStateText,
+} from "./procedural-graph.ts";
import { proceduralMemoryIndexPath, proceduralMemoryUsagePath } from "./paths.ts";
import type { ProceduralEntryKind, ProceduralMemoryEntry, ProceduralOutcome } from "./types.ts";
import {
@@ -20,6 +24,7 @@ import {
parseLanePage,
writeLaneText,
readLaneFile,
+ withLaneLock,
} from "../store/lane-pages.ts";
interface UsageRecord {
@@ -88,6 +93,18 @@ export function reconcileProceduralMemory(
if (!nextById.has(id) && counted(old)) removed++;
}
+ // The counters live in the usage file only: the index is written without
+ // them, so counters an older index still carries move into it here,
+ // before the index loses them (a failed rebuild after the index write
+ // must not leave them nowhere). The file is read again under its lock,
+ // and only an entry it does not name takes the index's counters: a tick
+ // another process counted since the read above is kept.
+ assertLaneWrite(vault);
+ withUsageLock(vault, () => {
+ const fresh = readUsageMap(vault, true);
+ for (const [id, used] of usageOf(next)) if (!fresh.has(id)) fresh.set(id, used);
+ writeUsageMap(vault, fresh);
+ });
writeProjections(vault, next, () => writeIndex(vault, next));
return { total: next.filter(counted).length, added, updated, removed };
}
@@ -100,15 +117,17 @@ export function listProceduralMemory(vault: string): ReadonlyArray<ProceduralMem
entries?: Array<ProceduralMemoryEntry>;
};
if (!Array.isArray(parsed.entries)) return Object.freeze([]);
+ const usage = readUsageMap(vault);
// Normalize additive fields so an older index reads with defaults
// instead of `undefined`: the outcome counters (pre-t_703f7b18) and the
- // four contract lists (pre no-dead-ends Unit I).
+ // four contract lists (pre no-dead-ends Unit I). The counters come from
+ // the usage file; an index written before they moved there still
+ // carries its own, read for an entry the usage file does not name.
return Object.freeze(
parsed.entries.map((entry) =>
Object.freeze({
...entry,
- successCount: typeof entry.successCount === "number" ? entry.successCount : 0,
- failureCount: typeof entry.failureCount === "number" ? entry.failureCount : 0,
+ ...counters(entry, usage.get(entry.id)),
prerequisites: asStringArray(entry.prerequisites),
rollback: asStringArray(entry.rollback),
sideEffects: asStringArray(entry.sideEffects),
@@ -162,29 +181,11 @@ export function markProceduralMemoryUsed(
const target = entries.find((entry) => entry.id === id);
if (!target) return null;
- const next = entries.map((entry) =>
- entry.id === id
- ? {
- ...entry,
- usedCount: entry.usedCount + 1,
- lastUsedAt: now.toISOString(),
- }
- : entry,
- );
- writeProjections(vault, next, () => {
- writeIndex(vault, next);
- const usage = readUsageMap(vault);
- const prev = usage.get(id);
- usage.set(id, {
- usedCount: (prev?.usedCount ?? 0) + 1,
- lastUsedAt: now.toISOString(),
- successCount: prev?.successCount ?? 0,
- failureCount: prev?.failureCount ?? 0,
- });
- writeUsageMap(vault, usage);
- });
-
- return next.find((entry) => entry.id === id) ?? null;
+ return writeUsageTick(vault, entries, target, (current) => ({
+ ...current,
+ usedCount: current.usedCount + 1,
+ lastUsedAt: now.toISOString(),
+ }));
}
/**
@@ -205,40 +206,80 @@ export function recordProceduralOutcome(
const target = entries.find((entry) => entry.id === id);
if (!target) return null;
- const next = entries.map((entry) =>
- entry.id === id
- ? {
- ...entry,
- successCount: entry.successCount + (outcome === "success" ? 1 : 0),
- failureCount: entry.failureCount + (outcome === "failure" ? 1 : 0),
- }
- : entry,
- );
- writeProjections(vault, next, () => {
- writeIndex(vault, next);
- const usage = readUsageMap(vault);
- const prev = usage.get(id);
- usage.set(id, {
- usedCount: prev?.usedCount ?? target.usedCount,
- lastUsedAt: prev?.lastUsedAt ?? target.lastUsedAt,
- successCount: (prev?.successCount ?? 0) + (outcome === "success" ? 1 : 0),
- failureCount: (prev?.failureCount ?? 0) + (outcome === "failure" ? 1 : 0),
- });
+ return writeUsageTick(vault, entries, target, (current) => ({
+ ...current,
+ successCount: current.successCount + (outcome === "success" ? 1 : 0),
+ failureCount: current.failureCount + (outcome === "failure" ? 1 : 0),
+ }));
+}
+
+/**
+ * Record one tick of `target`'s counters: only the usage file changes, a
+ * file of machine state (`paths.ts`). The index, the graph and the hints
+ * hold no counter, so a tick appends no store record (task 3.10).
+ */
+function writeUsageTick(
+ vault: string,
+ entries: ReadonlyArray<ProceduralMemoryEntry>,
+ target: ProceduralMemoryEntry,
+ tick: (current: UsageRecord) => UsageRecord,
+): ProceduralMemoryEntry {
+ assertLaneWrite(vault);
+ // Read, counted and written under the usage file's lock, so two ticks,
+ // or a tick and a reconcile, of two processes never lose one.
+ return withUsageLock(vault, () => {
+ const usage = readUsageMap(vault, true);
+ for (const [id, used] of usageOf(entries)) if (!usage.has(id)) usage.set(id, used);
+ const next = tick(usage.get(target.id) ?? counters(target, undefined));
+ usage.set(target.id, next);
writeUsageMap(vault, usage);
+ return { ...target, ...next };
});
+}
+
+/** Run `fn` holding the write lock of this machine's usage file. */
+function withUsageLock<T>(vault: string, fn: () => T): T {
+ return withLaneLock(vault, proceduralMemoryUsagePath(vault), fn);
+}
+
+/** The counters of `entry`: the usage file's when it names the entry, else the index's own. */
+function counters(
+ entry: Partial<ProceduralMemoryEntry>,
+ used: UsageRecord | undefined,
+): UsageRecord {
+ if (used !== undefined) return used;
+ return {
+ usedCount: typeof entry.usedCount === "number" ? entry.usedCount : 0,
+ lastUsedAt: typeof entry.lastUsedAt === "string" ? entry.lastUsedAt : null,
+ successCount: typeof entry.successCount === "number" ? entry.successCount : 0,
+ failureCount: typeof entry.failureCount === "number" ? entry.failureCount : 0,
+ };
+}
- return next.find((entry) => entry.id === id) ?? null;
+/** The usage records of every entry that has been used or has an outcome. */
+function usageOf(entries: ReadonlyArray<ProceduralMemoryEntry>): Map<string, UsageRecord> {
+ const out = new Map<string, UsageRecord>();
+ for (const entry of entries) {
+ const used = counters(entry, undefined);
+ const blank =
+ used.usedCount === 0 &&
+ used.lastUsedAt === null &&
+ used.successCount === 0 &&
+ used.failureCount === 0;
+ if (!blank) out.set(entry.id, used);
+ }
+ return out;
}
/** Fields of an index entry that are counters and stamps, never page references. */
const PROJECTION_OPAQUE = opaqueFields("lastUsedAt", "usedCount", "successCount", "failureCount");
/**
- * Write the index (and usage) with `write`, then rebuild the graph and
- * hints, as ONE operation: one privacy verdict over the entries every one
- * of these projections is derived from (an entry naming a private page
- * makes them all private), so the index, the usage sidecar, the graph and
- * the hints never land in different partitions.
+ * Write the index with `write`, then rebuild the graph and hints, as ONE
+ * operation: one privacy verdict over the entries every one of these
+ * projections is derived from (an entry naming a private page makes them
+ * all private). The graph and the hints are machine state (`paths.ts`), so
+ * the verdict reaches the index only, the one store record here.
*/
function writeProjections(
vault: string,
@@ -396,14 +437,19 @@ function asStringOrNull(value: unknown): string | null {
return typeof value === "string" && value.trim().length > 0 ? value.trim() : null;
}
+/** The counters an index entry carries: none, they live in the usage file. */
+const AT_REST = Object.freeze({ lastUsedAt: null, usedCount: 0, successCount: 0, failureCount: 0 });
+
function writeIndex(vault: string, entries: ReadonlyArray<ProceduralMemoryEntry>): void {
// Vault-identity write guard (context-integrity-gates, Unit J).
assertLaneWrite(vault);
const path = proceduralMemoryIndexPath(vault);
+ // The counters live in the usage file (machine state); the index, a lane
+ // record, carries them at rest so a use never changes it.
const payload = JSON.stringify(
{
schema_version: 1,
- entries,
+ entries: entries.map((entry) => ({ ...entry, ...AT_REST })),
},
null,
2,
@@ -411,12 +457,20 @@ function writeIndex(vault: string, entries: ReadonlyArray<ProceduralMemoryEntry>
writeLaneText(vault, path, `${payload}\n`);
}
-function readUsageMap(vault: string): Map<string, UsageRecord> {
- const path = proceduralMemoryUsagePath(vault);
- if (!lanePageExists(vault, path)) return new Map();
+/**
+ * This machine's usage counters. `locked`: the caller holds the usage
+ * file's lock; otherwise a first adoption of the store record takes it.
+ */
+function readUsageMap(vault: string, locked = false): Map<string, UsageRecord> {
+ const text = readProceduralState(
+ vault,
+ proceduralMemoryUsagePath(vault),
+ locked ? undefined : (write) => withUsageLock(vault, write),
+ );
+ if (text === null) return new Map();
const out = new Map<string, UsageRecord>();
- for (const line of readLaneFile(vault, path).split("\n")) {
+ for (const line of text.split("\n")) {
if (!line.trim()) continue;
try {
const parsed = JSON.parse(line) as Record<string, unknown>;
@@ -452,5 +506,5 @@ function writeUsageMap(vault: string, usage: ReadonlyMap<string, UsageRecord>):
if (value.failureCount > 0) record["failureCount"] = value.failureCount;
lines.push(JSON.stringify(record));
}
- writeLaneText(vault, path, `${lines.join("\n")}${lines.length > 0 ? "\n" : ""}`);
+ writeMachineStateText(path, `${lines.join("\n")}${lines.length > 0 ? "\n" : ""}`);
}
diff --git a/src/core/brain/schema-mutate-store.ts b/src/core/brain/schema-mutate-store.ts
index 4256a9ec..a8e335ba 100644
--- a/src/core/brain/schema-mutate-store.ts
+++ b/src/core/brain/schema-mutate-store.ts
@@ -13,6 +13,13 @@
* the store's audit ledger (`appendAuditRecord` routes it there on a
* store-only machine). Nothing under the vault's `Brain/` is written; the
* lock is device-local.
+ *
+ * The audit row attests the shared pack records, so it is written to
+ * `shared` too (task 3.11): a machine that holds only `shared` reads the
+ * digest it must hold the pack against, and reports another device's
+ * apply as attested instead of `modified`. The shared row carries no
+ * reason on a machine that holds `private`, where the whole row goes as
+ * before; see `sharedAttestation`.
*/
import { mkdirSync } from "node:fs";
@@ -20,9 +27,16 @@ import { join } from "node:path";
import { resolveAgentName } from "../config.ts";
import { processDirsEnv } from "../platform-dirs.ts";
-import { AUDIT_STORE_LEDGER_NAME, appendAuditRecord } from "../reliability/audit.ts";
+import {
+ AUDIT_STORE_LEDGER_NAME,
+ appendAuditRecord,
+ auditRowNamesPrivatePage,
+ type AuditRecord,
+} from "../reliability/audit.ts";
import { withFileLock } from "../reliability/lock.ts";
import { authorityFromOrigin } from "../store/dual-write.ts";
+import { configuredStore } from "../store/read/store-entities.ts";
+import { valueCarriesPrivateRegion } from "../store/private-region.ts";
import { storesStateDir } from "../store/store-paths.ts";
import { brainDirs } from "./paths.ts";
import {
@@ -79,23 +93,26 @@ export async function applySchemaMutationsToStore(
renderSchemaBlock(nextPack),
);
const packDigest = computeSchemaPackDigest(nextPack);
- const auditPath = appendAuditRecord(
- join(brainDirs(vault).log, SCHEMA_MUTATION_AUDIT_DIR),
- {
- timestamp: opts.now.toISOString(),
- actor: opts.actor,
- action: SCHEMA_MUTATION_AUDIT_ACTION,
- target: STORE_SCHEMA_PACK_SOURCE,
- ok: true,
- details: {
- applied: mutations.length,
- mutations,
- [SCHEMA_PACK_DIGEST_FIELD]: packDigest,
- ...(opts.reason ? { reason: opts.reason } : {}),
- },
+ const record: AuditRecord = {
+ timestamp: opts.now.toISOString(),
+ actor: opts.actor,
+ action: SCHEMA_MUTATION_AUDIT_ACTION,
+ target: STORE_SCHEMA_PACK_SOURCE,
+ ok: true,
+ details: {
+ applied: mutations.length,
+ mutations,
+ [SCHEMA_PACK_DIGEST_FIELD]: packDigest,
+ ...(opts.reason ? { reason: opts.reason } : {}),
},
- vault,
- );
+ };
+ const auditRoot = join(brainDirs(vault).log, SCHEMA_MUTATION_AUDIT_DIR);
+ const holdsPrivate = configuredStore()?.partitions.has("private") === true;
+ const attestation = sharedAttestation(vault, record, holdsPrivate);
+ const auditPath = appendAuditRecord(auditRoot, attestation, vault, { attestsShared: true });
+ // The whole row, reason included, stays where audit rows always went:
+ // `private` on a machine that holds it.
+ if (holdsPrivate) appendAuditRecord(auditRoot, record, vault);
return {
applied: mutations.length,
// The row's store shard is a device path; the result names the ledger.
@@ -105,3 +122,33 @@ export async function applySchemaMutationsToStore(
};
});
}
+
+/** What the shared row says in place of a batch that names a private page. */
+export const SCHEMA_AUDIT_WITHHELD = "the mutations name a private page";
+
+/**
+ * The audit row of an apply as the shared partition holds it (task 3.11,
+ * design D15 item 3): what attests the pack (actor, time, target, count,
+ * digest) and the mutation list, which the shared `brain.schema.*` records
+ * hold anyway. The reason is free text an operator wrote: it is left off
+ * the shared row on a machine that holds `private`, where the whole row
+ * goes as every audit row does, and kept on it on a machine that does
+ * not, as before. One privacy verdict covers the batch and the reason (a
+ * private page named, by the rule every audit row is judged by, or a
+ * `<private>` region): when it holds, the shared row keeps only the
+ * attestation and says so.
+ */
+function sharedAttestation(vault: string, record: AuditRecord, holdsPrivate: boolean): AuditRecord {
+ const details = record.details ?? {};
+ const isPrivate =
+ auditRowNamesPrivatePage(vault, record) || valueCarriesPrivateRegion(record.details);
+ const { reason, mutations, ...attests } = details;
+ return {
+ ...record,
+ details: {
+ ...attests,
+ ...(isPrivate ? { withheld: SCHEMA_AUDIT_WITHHELD } : { mutations }),
+ ...(!isPrivate && !holdsPrivate && reason !== undefined ? { reason } : {}),
+ },
+ };
+}
diff --git a/src/core/reliability/audit.ts b/src/core/reliability/audit.ts
index a97550ee..8befe1d0 100644
--- a/src/core/reliability/audit.ts
+++ b/src/core/reliability/audit.ts
@@ -8,7 +8,11 @@ import {
shardedFileName,
type LedgerShardGrammar,
} from "../brain/ledger-shards.ts";
-import { auditRowRecord, DUAL_WRITE_LEDGERS } from "../store/dual-write-records.ts";
+import {
+ auditRowRecord,
+ DUAL_WRITE_LEDGERS,
+ ledgerRowRecord,
+} from "../store/dual-write-records.ts";
import { isRecordLabel } from "../store/envelope.ts";
import { logRefsNamePrivatePage } from "../store/reference-privacy.ts";
import { isStoreOnly } from "../store/store-only.ts";
@@ -65,6 +69,15 @@ export interface AppendAuditRecordOptions {
* hook audit trail (`hook-audit`) is always fail-open.
*/
readonly failOpen?: boolean;
+ /**
+ * The row attests records of the `shared` partition (a schema apply
+ * attests the shared `brain.schema.*` settings records it wrote), so on a
+ * store-only machine it goes to `shared`, the partition of what it
+ * attests: a machine that holds only `shared` can then check the
+ * attestation (task 3.11). The caller has judged the row's privacy once
+ * and left out what is private; no per-row privacy judgment runs.
+ */
+ readonly attestsShared?: boolean;
}
/**
@@ -122,10 +135,15 @@ export function appendAuditRecord(
legacy: () => appendLegacyAuditLine(auditRoot, timestamp, line),
store: () => {
const written = JSON.parse(line) as AuditRecord;
+ const row = { audit_dir: basename(auditRoot), record: written };
+ const agent = isRecordLabel(written.actor) ? written.actor : undefined;
+ if (options.attestsShared === true) {
+ return ledgerRowRecord(DUAL_WRITE_LEDGERS.reliabilityAudit, row, "shared", agent);
+ }
return auditRowRecord(
DUAL_WRITE_LEDGERS.reliabilityAudit,
- { audit_dir: basename(auditRoot), record: written },
- isRecordLabel(written.actor) ? written.actor : undefined,
+ row,
+ agent,
auditRowNamesPrivatePage(vault, written),
);
},
diff --git a/src/core/state/surfaces.ts b/src/core/state/surfaces.ts
index 07d810a6..7bcc93ba 100644
--- a/src/core/state/surfaces.ts
+++ b/src/core/state/surfaces.ts
@@ -166,6 +166,9 @@ export const STATE_SURFACE_ID = Object.freeze({
rollupLedger: "rollup_ledger",
crossTopicLedger: "cross_topic_ledger",
proposalWatermark: "proposal_watermark",
+ proceduralUsage: "procedural_usage",
+ proceduralGraph: "procedural_graph",
+ proceduralHints: "procedural_hints",
captureWatermark: "capture_watermark",
decisionLedger: "decision_ledger",
sourceArchives: "source_archives",
@@ -351,6 +354,9 @@ const QUERY_DEMAND_FILE = `${QUERY_DEMAND_LEDGER_STEM}.${JSONL_LEDGER_EXT}`;
const CAPTURE_DECISIONS_FILE = `${CAPTURE_DECISION_LEDGER_STEM}.${JSONL_LEDGER_EXT}`;
const CAPTURE_WATERMARK_FILE = ".catchup-watermark.json";
const PROPOSAL_WATERMARK_FILE = "proposal-watermark.json";
+const PROCEDURAL_USAGE_FILE = "usage.jsonl";
+const PROCEDURAL_GRAPH_FILE = "graph.json";
+const PROCEDURAL_HINTS_FILE = "hints.json";
const TRUTH_DIR = "truth";
const BRAIN_INTERNAL_STATE_DIR = ".state";
const LINEAGE_LEDGER_FILE = "session-lineage.jsonl";
@@ -1261,6 +1267,50 @@ export const STATE_SURFACES: ReadonlyArray<StateSurface> = Object.freeze([
"from the beginning, which costs time and re-proposes nothing already accepted.",
sources: ["src/core/brain/paths.ts"],
},
+ {
+ id: STATE_SURFACE_ID.proceduralUsage,
+ label: "procedural memory usage counters",
+ tier: STATE_TIER.vaultContent,
+ switched: STATE_SWITCHED.deviceLocal,
+ derive: (vault) => join(vault, BRAIN_PROCEDURAL_MEMORY_REL, PROCEDURAL_USAGE_FILE),
+ override_env: null,
+ override_config_key: null,
+ carries_memory: false,
+ reason:
+ "How often and how recently each procedure was used, and how its uses turned out. The " +
+ "counters tick on every use, so they stay on the machine that counts them instead of " +
+ "appending a whole record to the store per tick; a reset restarts the counts and the " +
+ "ranking they feed.",
+ sources: ["src/core/brain/paths.ts"],
+ },
+ {
+ id: STATE_SURFACE_ID.proceduralGraph,
+ label: "procedural graph projection",
+ tier: STATE_TIER.derived,
+ switched: STATE_SWITCHED.deviceLocal,
+ derive: (vault) => join(vault, BRAIN_PROCEDURAL_MEMORY_REL, PROCEDURAL_GRAPH_FILE),
+ override_env: null,
+ override_config_key: null,
+ carries_memory: false,
+ reason:
+ "A projection of the procedural memory index and the skill proposals into nodes and " +
+ "edges. It is recomputed from those, which are the source of truth.",
+ sources: ["src/core/brain/paths.ts"],
+ },
+ {
+ id: STATE_SURFACE_ID.proceduralHints,
+ label: "procedural recall hints",
+ tier: STATE_TIER.derived,
+ switched: STATE_SWITCHED.deviceLocal,
+ derive: (vault) => join(vault, BRAIN_PROCEDURAL_MEMORY_REL, PROCEDURAL_HINTS_FILE),
+ override_env: null,
+ override_config_key: null,
+ carries_memory: false,
+ reason:
+ "The recall cues of each procedural graph node. They are recomputed from the procedural " +
+ "graph.",
+ sources: ["src/core/brain/paths.ts"],
+ },
{
id: STATE_SURFACE_ID.captureWatermark,
label: "capture catchup watermark",
diff --git a/src/core/store-migration/exporters.ts b/src/core/store-migration/exporters.ts
index af5edf71..a5039c23 100644
--- a/src/core/store-migration/exporters.ts
+++ b/src/core/store-migration/exporters.ts
@@ -58,7 +58,7 @@ import {
import { preferencePath, retiredPath, validateSlug } from "../brain/paths.ts";
import { preferencePageBody } from "../brain/preference.ts";
import { PREFERENCE_TEXT_FIELD } from "../brain/preference-store.ts";
-import { brainRelOfEntry } from "../store/lane-paths.ts";
+import { brainRelOfEntry, lanePlaceOf } from "../store/lane-paths.ts";
import { rawParsesBack, renderLaneText } from "../store/lane-raw.ts";
import { signalPagePath } from "../store/read/signals.ts";
import {
@@ -91,7 +91,7 @@ import {
import { foldPreferences } from "../store/fold-preferences.ts";
import type { FrontmatterMap } from "../types.ts";
import { formatFrontmatter, parseFrontmatterWithNotices } from "../vault.ts";
-import { migratedMark } from "./migration-records.ts";
+import { migratedMark, type MigratedMark } from "./migration-records.ts";
/** Kinds an exporter writes back. */
export const EXPORTED_KINDS: ReadonlySet<string> = new Set([
@@ -397,12 +397,29 @@ function exportPinned(vault: string, records: ReadonlyArray<StoreRecord>): void
}
/**
- * Where a lane entry is written back: the path it was imported from, else
- * its own page; null when that path leaves `Brain/`.
+ * Where a lane entry is written back: the path its winning record was
+ * imported from, else the path any of its records was imported from, else
+ * its own page; null when that path leaves `Brain/`. A mark counts only
+ * when its legacy path names this entry under the current path rule, or
+ * names no entry the rule maps (a blob lane's file, a folder whose name
+ * is not a lane name): an entry an earlier release filed under another
+ * path's id holds records imported from that other path
+ * (`lane-id-repair.ts`), and writing to it would remove or overwrite the
+ * other file.
*/
function laneEntryPath(vault: string, key: string, fold: LaneFold): string | null {
const state = fold.entries.get(key);
- const imported = state?.history.map((h) => migratedMark(h.record)).find((m) => m !== null);
+ const fits = (mark: MigratedMark | null): mark is MigratedMark => {
+ if (mark === null) return false;
+ if (!mark.key.startsWith(BRAIN_PREFIX)) return true;
+ const place = lanePlaceOf(mark.key.slice(BRAIN_PREFIX.length));
+ return place === null || laneEntryKey(place.lane, place.entry) === key;
+ };
+ const winner = state?.history.find((h) => h.record.id === state.winner);
+ const own = winner !== undefined ? migratedMark(winner.record) : null;
+ const imported = fits(own)
+ ? own
+ : state?.history.map((h) => migratedMark(h.record)).find((m) => fits(m));
const [lane, ...rest] = key.split("/");
return brainPath(
vault,
diff --git a/src/core/store-migration/lane-id-repair.ts b/src/core/store-migration/lane-id-repair.ts
new file mode 100644
index 00000000..2bd657d2
--- /dev/null
+++ b/src/core/store-migration/lane-id-repair.ts
@@ -0,0 +1,421 @@
+/**
+ * Repair of lane entry ids an earlier release gave a page whose name ends
+ * in a kept extension and `.md` (task 3.9, design D15 item 1).
+ *
+ * Before the lane path rule became a bijection, the migration imported
+ * `Brain/<lane>/x.json.md` as entry `x.json`, the id of the file
+ * `x.json` beside it, and both landed under one key. The rule now gives
+ * the page the id `x.json.md`, so such a record is read by no path. Every
+ * imported record carries the legacy path it came from (its `migrated`
+ * mark), which tells the two apart:
+ *
+ * - the page's latest record is written again under the id the rule
+ * gives its path, in the partition it lives in, unless that id holds a
+ * live entry already;
+ * - when the page's record is what the old key holds now, the old key is
+ * given back the latest record that is not the page's (the file
+ * `x.json`), or removed when there is none.
+ *
+ * A rollback writes each entry back to the legacy path of a mark that
+ * names that entry under the current rule (`exporters.ts`
+ * `laneEntryPath`), so the old key's restore or removal lands on `x.json`
+ * and never on the page, which the snapshot restores. Only records with a
+ * mark are moved: a writer of this tool
+ * never wrote such a page itself. Every moved or restored record keeps the
+ * body it copies, its `migrated` mark included, so the record under the
+ * new id still names the legacy path it came from. Running it again finds
+ * nothing to do.
+ */
+
+import { BRAIN_ROOT_REL } from "../brain/path-constants.ts";
+import type { StoreRecord } from "../store/envelope.ts";
+import type { DualWriteRecord } from "../store/dual-write.ts";
+import type { StorePartition } from "../store/constants.ts";
+import { authorityRank, RegisterSet, TOMBSTONE, type RegisterEntry } from "../store/fold.ts";
+import type { Authority } from "../store/constants.ts";
+import { lanePlaceOf } from "../store/lane-paths.ts";
+import {
+ foldLaneEntries,
+ LANE_ENTRY_KIND,
+ LANE_ENTRY_REMOVE_KIND,
+ laneEntryKey,
+ type LaneEntryValue,
+} from "../store/lane-records.ts";
+import { configuredStore } from "../store/read/store-entities.ts";
+import { readStreamRecords } from "../store/read/stream-read.ts";
+import { withoutSeenRecording } from "../store/seen-shards.ts";
+import { storeWrite } from "../store/store-write.ts";
+import { resolveDeviceId } from "../config.ts";
+import { deviceStateDirFor, partitionDir } from "../store/store-paths.ts";
+import { listShards } from "../store/shard-list.ts";
+import { processDirsEnv } from "../platform-dirs.ts";
+import { atomicWriteFileSync } from "../fs-atomic.ts";
+import { createHash } from "node:crypto";
+import { mkdirSync, readFileSync, statSync } from "node:fs";
+import { dirname, join } from "node:path";
+import { migratedMark } from "./migration-records.ts";
+
+const MD = ".md";
+const BRAIN_PREFIX = `${BRAIN_ROOT_REL}/`;
+
+/** One entry moved to the id its legacy path maps to. */
+export interface LaneIdRepair {
+ /** `<lane>/<entry>` the page's record was filed under. */
+ readonly from: string;
+ /** `<lane>/<entry>` it is written under now. */
+ readonly to: string;
+ /**
+ * What the old key holds afterwards: its own value back, nothing, the
+ * page filed under the id before it (`replaced`), or what it held.
+ */
+ readonly left: "restored" | "removed" | "replaced" | "unchanged";
+}
+
+interface Located {
+ readonly record: StoreRecord;
+ readonly partition: StorePartition;
+}
+
+/** The id an imported record's legacy path maps to now, when it is the `.md` page of its key. */
+function pageTarget(record: StoreRecord, lane: string, entry: string): string | null {
+ const mark = migratedMark(record);
+ if (mark === null || !mark.key.startsWith(BRAIN_PREFIX) || !mark.key.endsWith(MD)) return null;
+ const place = lanePlaceOf(mark.key.slice(BRAIN_PREFIX.length));
+ if (place === null || place.lane !== lane || place.entry !== `${entry}${MD}`) return null;
+ return laneEntryKey(place.lane, place.entry);
+}
+
+/**
+ * The record a register of `entries` alone would hold (authority, then
+ * fold order, a removal included), or undefined for none.
+ */
+function winnerOf(
+ entries: ReadonlyArray<RegisterEntry<LaneEntryValue>>,
+): RegisterEntry<LaneEntryValue> | undefined {
+ const register = new RegisterSet<LaneEntryValue>();
+ for (const entry of entries) register.offer("", entry);
+ return register.get("")?.winner;
+}
+
+function higherAuthority(a: Authority, b: Authority): Authority {
+ return authorityRank(a) >= authorityRank(b) ? a : b;
+}
+
+function located(
+ record: StoreRecord,
+ partition: StorePartition,
+ kind: string,
+ body: Record<string, unknown>,
+): DualWriteRecord {
+ return {
+ stream: "events",
+ kind,
+ ...(record.agent !== undefined && record.agent !== null ? { agent: record.agent } : {}),
+ private: partition === "private",
+ located: { partition, content: kind === LANE_ENTRY_KIND },
+ body,
+ };
+}
+
+/** What one mis-filed key needs, worked out before anything is written. */
+interface KeyPlan {
+ readonly key: string;
+ readonly lane: string;
+ readonly entry: string;
+ /** The page's latest record under this key. */
+ readonly page: RegisterEntry<LaneEntryValue>;
+ /** Its own id. */
+ readonly to: string;
+ /**
+ * The records giving the old key its value back, or its removal, each
+ * with the partition it lands in.
+ */
+ readonly old: ReadonlyArray<{
+ readonly record: DualWriteRecord;
+ readonly partition: StorePartition;
+ readonly removal: boolean;
+ }>;
+ readonly left: LaneIdRepair["left"];
+}
+
+/** The repairs the records call for, with the records that carry them out, in order. */
+export function planLaneIdRepairs(all: ReadonlyArray<Located>): {
+ readonly repairs: ReadonlyArray<LaneIdRepair>;
+ readonly records: ReadonlyArray<DualWriteRecord>;
+ /** `from` of every repair a record of the `private` partition takes part in. */
+ readonly privateKeys: ReadonlySet<string>;
+} {
+ const partitionOf = new Map(all.map((r) => [r.record.id, r.partition] as const));
+ const fold = foldLaneEntries(all.map((r) => r.record));
+ const plans = new Map<string, KeyPlan>();
+ for (const [key, state] of fold.entries) {
+ const live = state.history.filter((h) => h.value !== TOMBSTONE);
+ const first = live[0];
+ if (first === undefined) continue;
+ const lane = first.record.body["lane"] as string;
+ const entry = first.record.body["entry"] as string;
+ const isPage = (h: RegisterEntry<LaneEntryValue>): boolean =>
+ h.value !== TOMBSTONE && pageTarget(h.record, lane, entry) !== null;
+ const pages = live.filter(isPage);
+ // The page's own value: its records resolved as the register resolves
+ // them (authority, then fold order), not its latest record.
+ const page = winnerOf(pages);
+ if (page === undefined) continue;
+ const to = pageTarget(page.record, lane, entry)!;
+ const old: Array<{ record: DualWriteRecord; partition: StorePartition; removal: boolean }> = [];
+ let left: LaneIdRepair["left"] = "unchanged";
+ const winner = state.history.find((h) => h.record.id === state.winner)!;
+ if (!state.removed && isPage(winner)) {
+ // The old key's own latest state, a removal included: a file deleted
+ // before the page was filed over it stays deleted.
+ const own = winnerOf(state.history.filter((h) => !isPage(h)));
+ // At least the winner's authority, or a page imported with `human`
+ // authority would keep winning and every pass repair again.
+ const authority = higherAuthority(own?.authority ?? winner.authority, winner.authority);
+ const pagePartition = partitionOf.get(winner.record.id) ?? "shared";
+ const removal = (partition: StorePartition) => ({
+ record: located(winner.record, partition, LANE_ENTRY_REMOVE_KIND, {
+ authority,
+ lane,
+ entry,
+ }),
+ partition,
+ removal: true,
+ });
+ if (own === undefined || own.value === TOMBSTONE) {
+ old.push(removal(pagePartition));
+ left = "removed";
+ } else {
+ const ownPartition = partitionOf.get(own.record.id) ?? "shared";
+ // A file restored in `private` over a page that lives in `shared`:
+ // a machine that holds only `shared` must see the page leave too.
+ if (pagePartition === "shared" && ownPartition === "private") old.push(removal("shared"));
+ old.push({
+ record: located(own.record, ownPartition, LANE_ENTRY_KIND, {
+ ...own.record.body,
+ authority,
+ }),
+ partition: ownPartition,
+ removal: false,
+ });
+ left = "restored";
+ }
+ }
+ plans.set(key, { key, lane, entry, page, to, old, left });
+ }
+ const repairs: LaneIdRepair[] = [];
+ const privateKeys = new Set<string>();
+ for (const [key, plan] of plans) {
+ const state = fold.entries.get(key)!;
+ const involved = [plan.page.record.id, ...state.history.map((h) => h.record.id)];
+ if (involved.some((id) => partitionOf.get(id) === "private")) privateKeys.add(key);
+ }
+ const olds: DualWriteRecord[] = [];
+ const moves: DualWriteRecord[] = [];
+ /** Ids a page moves into in this pass, with the partition the move lands in. */
+ const replaced = new Map<string, StorePartition>();
+ for (const plan of plans.values()) {
+ // The page is written under its own id only when that id has no
+ // history of its own: an id that was written, or removed since, is the
+ // user's to keep that way, so a page deleted after its repair stays
+ // deleted. An id that holds nothing but a page filed there from the id
+ // after it (`x.json.md.md` under `x.json.md`) is no history of its own:
+ // that page moves on in this pass, and this one takes its place.
+ const target = fold.entries.get(plan.to);
+ const targetPlan = plans.get(plan.to);
+ const onlyMisfiled =
+ target !== undefined &&
+ targetPlan !== undefined &&
+ targetPlan.left === "removed" &&
+ target.history.every(
+ (h) =>
+ h.value !== TOMBSTONE && pageTarget(h.record, targetPlan.lane, targetPlan.entry) !== null,
+ );
+ const targetFresh = target === undefined || onlyMisfiled;
+ const movePartition = partitionOf.get(plan.page.record.id) ?? "shared";
+ if (targetFresh) {
+ const [toLane, ...rest] = plan.to.split("/");
+ const targetWinner =
+ target === undefined
+ ? undefined
+ : target.history.find((h) => h.record.id === target.winner);
+ moves.push(
+ located(plan.page.record, movePartition, LANE_ENTRY_KIND, {
+ ...plan.page.record.body,
+ lane: toLane,
+ entry: rest.join("/"),
+ authority: higherAuthority(
+ plan.page.authority,
+ targetWinner?.authority ?? plan.page.authority,
+ ),
+ }),
+ );
+ // The page this one replaces leaves in this pass: no removal of its
+ // id in the partition the move lands in, which the move clears.
+ if (onlyMisfiled) replaced.set(plan.to, movePartition);
+ }
+ if (plan.left !== "unchanged" || targetFresh) {
+ repairs.push({ from: plan.key, to: plan.to, left: plan.left });
+ }
+ }
+ for (const plan of plans.values()) {
+ for (const { record, partition, removal } of plan.old) {
+ // A removal in another partition than the move's stays: a machine
+ // that holds only that partition must see the old page go.
+ if (removal && replaced.get(plan.key) === partition) continue;
+ olds.push(record);
+ }
+ }
+ return {
+ repairs: repairs.map((r) => (replaced.has(r.from) ? { ...r, left: "replaced" as const } : r)),
+ // The old keys' restores and removals first, then the moves.
+ records: [...olds, ...moves],
+ privateKeys,
+ };
+}
+
+/** How many times a plan is made again from a read that moved before it is given up. */
+const REPLAN_ATTEMPTS = 3;
+
+/** Whether two reads hold the same lane records. */
+function sameRecords(a: ReadonlyArray<Located>, b: ReadonlyArray<Located>): boolean {
+ if (a.length !== b.length) return false;
+ const ids = new Set(a.map((r) => r.record.id));
+ return b.every((r) => ids.has(r.record.id));
+}
+
+/** The device-local marker of a store whose lane ids were repaired on this machine. */
+const REPAIRED_MARKER = "lane-ids-repaired.json";
+
+/**
+ * Find and repair the mis-filed pages of the configured store (see the
+ * module comment). Returns what it repaired; nothing when the store
+ * cannot be read or holds none.
+ *
+ * Runs only on a machine that holds `private`: on one without it, a
+ * file's own record in `private` is invisible and the repair would
+ * remove the file's id over it. A device-local marker records a finished
+ * pass that read every shard in full, with a stamp of the `events`
+ * shards it read: a later dream pass reads the stream again only once
+ * something new arrived in it (a late import of a machine still on the
+ * earlier release included), and a pass whose write fails, or that could
+ * not read a shard, leaves no marker and runs again.
+ */
+export function repairLaneEntryIds(vault: string | null): ReadonlyArray<LaneIdRepair> {
+ const store = configuredStore();
+ if (store === null || !store.partitions.has("private")) return [];
+ const marker = join(deviceStateDirFor(store.storeId, processDirsEnv()), REPAIRED_MARKER);
+ // Stamped before the read, over the shards of the other devices only:
+ // a mis-filed record comes from another machine's import, never from
+ // this machine, whose own writes (this pass's included) do not re-arm
+ // the repair, and a shard that arrives after the read moves the stamp.
+ const stamp = eventsStamp(store);
+ if (readMarkerStamp(marker) === stamp) return [];
+ let { all, complete } = laneRecordsOf(store);
+ // A read that missed a shard (unreadable, gone since this machine read
+ // it, or holding a record whose blob has not arrived) may have missed
+ // the file beside a page, or a removal: nothing is written from it, and
+ // the next pass reads again.
+ if (!complete) return [];
+ let { repairs, records } = planLaneIdRepairs(all);
+ // Planned from a read another writer may have moved past (a person's
+ // edit of an id the plan touches): the plan is written only once a read
+ // right before the write finds the same lane records, and planned again
+ // from that read otherwise, a few times at most.
+ for (let attempt = 0; records.length > 0; attempt++) {
+ const again = laneRecordsOf(store);
+ if (!again.complete) return [];
+ if (sameRecords(all, again.all)) break;
+ if (attempt >= REPLAN_ATTEMPTS) return [];
+ ({ all, complete } = again);
+ ({ repairs, records } = planLaneIdRepairs(all));
+ }
+ if (records.length > 0) storeWrite(() => records, { vault });
+ mkdirSync(dirname(marker), { recursive: true });
+ atomicWriteFileSync(
+ marker,
+ `${JSON.stringify({ version: 3, repaired: repairs.length, events: stamp }, null, 2)}\n`,
+ );
+ return repairs;
+}
+
+/** The `events` stamp a marker recorded, or null for none (or one of an older version). */
+function readMarkerStamp(marker: string): string | null {
+ try {
+ const parsed = JSON.parse(readFileSync(marker, "utf8")) as { events?: unknown };
+ const { version, events } = parsed as { version?: unknown; events?: unknown };
+ return version === 3 && typeof events === "string" ? events : null;
+ } catch {
+ return null;
+ }
+}
+
+/**
+ * A digest of the `events` shards of the held partitions that other
+ * devices write (path, size, mtime): it moves whenever another machine's
+ * record arrives, a late import of a machine still on the earlier release
+ * included, and never for this machine's own writes.
+ */
+function eventsStamp(store: NonNullable<ReturnType<typeof configuredStore>>): string {
+ let own = "";
+ try {
+ own = resolveDeviceId();
+ } catch {
+ // No device id: every shard counts.
+ }
+ const lines: string[] = [];
+ for (const partition of [...store.partitions].toSorted()) {
+ for (const shard of listShards(partitionDir(store.root, partition), { stream: "events" })) {
+ if (own !== "" && shard.device === own) continue;
+ let stamp = "missing";
+ try {
+ const stat = statSync(shard.path);
+ stamp = `${stat.size}:${stat.mtimeMs}`;
+ } catch {
+ // gone between the listing and the stat: reads as changed
+ }
+ lines.push(`${partition}/${shard.rel}=${stamp}`);
+ }
+ }
+ return createHash("sha256").update(lines.join("\n")).digest("hex");
+}
+
+/** The lane records of every held partition, and whether every shard was read in full. */
+function laneRecordsOf(store: NonNullable<ReturnType<typeof configuredStore>>): {
+ readonly all: ReadonlyArray<Located>;
+ readonly complete: boolean;
+} {
+ const all: Located[] = [];
+ let complete = true;
+ for (const partition of store.partitions) {
+ const read = readStreamRecords(store.root, partition, { stream: "events" });
+ if (read.unreadable.length > 0 || read.skippedPending) complete = false;
+ for (const record of read.records) {
+ if (record.kind === LANE_ENTRY_KIND || record.kind === LANE_ENTRY_REMOVE_KIND) {
+ all.push({ record, partition });
+ }
+ }
+ }
+ return { all, complete };
+}
+
+/**
+ * The mis-filed pages of the configured store as this machine reads it,
+ * written nowhere: what the doctor reports (`lane-id-check.ts`), on any
+ * machine, so a store no machine of which holds `private` (where the
+ * repair never runs) shows them too. `sharedOnly` leaves out every repair
+ * a record of the `private` partition takes part in.
+ */
+export function misfiledLaneIds(
+ configPath?: string,
+ options: { readonly sharedOnly?: boolean } = {},
+): ReadonlyArray<LaneIdRepair> {
+ const store = configuredStore(configPath);
+ if (store === null) return [];
+ return withoutSeenRecording(() => {
+ const { repairs, privateKeys } = planLaneIdRepairs(laneRecordsOf(store).all);
+ // `sharedOnly`: what a caller below local reach may be told, the
+ // repairs no record of the `private` partition takes part in.
+ return options.sharedOnly === true ? repairs.filter((r) => !privateKeys.has(r.from)) : repairs;
+ });
+}
diff --git a/src/core/store-migration/legacy-scan.ts b/src/core/store-migration/legacy-scan.ts
index 28cddc8a..9e358f90 100644
--- a/src/core/store-migration/legacy-scan.ts
+++ b/src/core/store-migration/legacy-scan.ts
@@ -17,7 +17,14 @@ import { basename, join, relative, sep } from "node:path";
import { isSyncConflictName, parseShardedName } from "../brain/ledger-shards.ts";
import { DEGRADATION_CODE } from "../integrity/degradation.ts";
import { parseFrontmatterWithNotices } from "../vault.ts";
-import { entryOfPath, lanePlaceOf, ROOT_LANE } from "../store/lane-paths.ts";
+import {
+ entryOfPath,
+ laneNameRefusal,
+ laneFolderRivals,
+ lanePlaceOf,
+ normalizedFolderPlace,
+ ROOT_LANE,
+} from "../store/lane-paths.ts";
import type { LegacyItem, Locator } from "./destinations.ts";
import { claims } from "./legacy-claims.ts";
@@ -261,13 +268,50 @@ function entryPlace(
path: string,
): { lane: string; entry: string } {
const rel = relative(locator.root, path).split(sep).join("/");
- if (locator.lane === null) {
- const place = lanePlaceOf(rel);
- if (place !== null) return place;
+ if (locator.lane === null && rel !== "") {
+ // A name that does not map to an entry and back is listed as an item
+ // the migration could not convert, never filed under an id that
+ // names another path (`store/lane-paths.ts`).
+ const place = lanePlaceOf(rel) ?? spelledFolderPlace(locator.root, rel);
+ if (place === null) throw new Error(laneNameRefusal(rel) ?? "not a lane entry");
+ return place;
}
return { lane: locator.lane ?? ROOT_LANE, entry: entryOfPath(rel === "" ? basename(path) : rel) };
}
+/**
+ * The place of a page in a user's top folder spelled otherwise than its
+ * lane name (`normalizedFolderPlace`), when no other top folder of the
+ * tree at `root` takes the same lane; null otherwise. Two folders that
+ * map to one lane (`My Notes/` beside `my-notes/` or `my_notes/`) are
+ * refused, both but the one already named as the lane: their entries
+ * would share ids.
+ */
+function spelledFolderPlace(root: string, rel: string): { lane: string; entry: string } | null {
+ const place = normalizedFolderPlace(rel);
+ if (place === null) return null;
+ const folder = rel.split("/")[0]!;
+ const rivals = laneFolderRivals(topFolders(root), folder, place.lane);
+ if (rivals.length > 0) {
+ throw new Error(
+ `the folder ${folder} maps to the lane ${place.lane}, which ${rivals.join(", ")} also ` +
+ "takes; rename one of them so each folder has a lane of its own",
+ );
+ }
+ return place;
+}
+
+/** The names of the folders directly under `root`. */
+function topFolders(root: string): string[] {
+ try {
+ return readdirSync(root, { withFileTypes: true })
+ .filter((d) => d.isDirectory())
+ .map((d) => d.name);
+ } catch {
+ return [];
+ }
+}
+
function entryItem(locator: Extract<Locator, { shape: "entries" }>, path: string): LegacyItem {
const place = entryPlace(locator, path);
if (path.endsWith(PAGE_EXT)) {
diff --git a/src/core/store-migration/removal.ts b/src/core/store-migration/removal.ts
index 6fcbc48b..be04949a 100644
--- a/src/core/store-migration/removal.ts
+++ b/src/core/store-migration/removal.ts
@@ -75,6 +75,7 @@ import {
MIGRATION_STREAM,
} from "./migration-records.ts";
import type { ConvertHooks } from "./convert.ts";
+import { retireAdoptedLaneEntries } from "./retire-adopted.ts";
import { GATED_IMPORT_WAIT_MS, importLateLegacyWrites } from "./transition.ts";
/** Where archives of removed legacy trees go, inside the device-local state. */
@@ -416,6 +417,14 @@ function removeUnderGate(
});
writeRemovalMarker(store, { vault: resolve(vault), at, archive, forced, stopped: pending });
rmSync(journal, { force: true });
+ // No rollback can run from here on: the records of files that are
+ // machine state now are retired (`retire-adopted.ts`). Best effort: a
+ // record left live is only read by a machine without its own copy yet.
+ try {
+ retireAdoptedLaneEntries(store, vault, options.agent);
+ } catch {
+ // see above
+ }
return {
removed: true,
archive,
diff --git a/src/core/store-migration/retire-adopted.ts b/src/core/store-migration/retire-adopted.ts
new file mode 100644
index 00000000..43901e71
--- /dev/null
+++ b/src/core/store-migration/retire-adopted.ts
@@ -0,0 +1,96 @@
+/**
+ * Retiring the store records of files that became machine state after the
+ * migration imported them (task 3.10, design D15 item 2).
+ *
+ * A machine switched before the procedural usage counters, graph and
+ * hints became machine state holds them as `lane-entry` records, the
+ * migration's import of the legacy files. Each switched machine adopts
+ * them into its own machine state on first read
+ * (`brain/procedural-graph.ts` `readProceduralState`), and the records are
+ * never written again. They stay in the store while a rollback is still
+ * possible: a rollback replays post-switch records into the legacy tree,
+ * so a tombstone written earlier would remove the legacy file it was
+ * imported from. Once the legacy tree has left the vault a rollback is
+ * refused, and the removal retires them here: each one this machine has
+ * adopted into its own state (its copy is there after the adoption) gets
+ * one tombstone in the partition the entry lives in; one it could not
+ * adopt, or whose tombstone could not be written, stays live. A machine that never read them before the tombstone
+ * arrives rebuilds the graph and hints on its next reconcile and starts
+ * its counters from those its index still carries.
+ */
+
+import { existsSync } from "node:fs";
+
+import { appendRecord } from "../store/appender.ts";
+import { AUTHORITY_FIELD } from "../store/constants.ts";
+import { foldLaneEntries, LANE_ENTRY_REMOVE_KIND, laneEntryKey } from "../store/lane-records.ts";
+import { readStreamRecords } from "../store/read/stream-read.ts";
+import type { StoreHandle } from "../store/store-open.ts";
+import type { StoreRecord } from "../store/envelope.ts";
+import type { StorePartition } from "../store/constants.ts";
+import {
+ proceduralGraphPath,
+ proceduralHintsPath,
+ proceduralMemoryUsagePath,
+} from "../brain/paths.ts";
+import { readProceduralState } from "../brain/procedural-graph.ts";
+
+/** The lane of the procedural memory files. */
+const PROCEDURAL_LANE = "procedural-memory";
+
+/** The entries that are machine state now, with the location each one is adopted into. */
+const ADOPTED: ReadonlyArray<{ readonly entry: string; readonly path: (v: string) => string }> =
+ Object.freeze([
+ { entry: "usage.jsonl", path: proceduralMemoryUsagePath },
+ { entry: "graph.json", path: proceduralGraphPath },
+ { entry: "hints.json", path: proceduralHintsPath },
+ ]);
+
+/**
+ * Adopt the entries into this machine's state, then tombstone each one the
+ * store still holds live. Returns the `<lane>/<entry>` keys retired.
+ */
+export function retireAdoptedLaneEntries(
+ store: StoreHandle,
+ vault: string,
+ agent: string,
+): string[] {
+ const partitionOf = new Map<string, StorePartition>();
+ const records: StoreRecord[] = [];
+ for (const partition of store.partitions) {
+ for (const record of readStreamRecords(store.root, partition, { stream: "events" }).records) {
+ partitionOf.set(record.id, partition);
+ records.push(record);
+ }
+ }
+ const fold = foldLaneEntries(records);
+ const retired: string[] = [];
+ for (const { entry, path } of ADOPTED) {
+ const key = laneEntryKey(PROCEDURAL_LANE, entry);
+ const state = fold.entries.get(key);
+ if (state === undefined || state.removed || state.value === null) continue;
+ // Only a record this machine holds its own copy of is retired: an
+ // adoption whose write failed (a full disk, a device-local folder it
+ // may not write) leaves the record live, the one copy there is.
+ try {
+ readProceduralState(vault, path(vault));
+ } catch {
+ continue;
+ }
+ if (!existsSync(path(vault))) continue;
+ try {
+ appendRecord(store, {
+ partition: partitionOf.get(state.winner) ?? "shared",
+ stream: "events",
+ kind: LANE_ENTRY_REMOVE_KIND,
+ agent,
+ body: { [AUTHORITY_FIELD]: "human", lane: PROCEDURAL_LANE, entry },
+ });
+ } catch {
+ // Left live, read only by a machine without its own copy yet.
+ continue;
+ }
+ retired.push(key);
+ }
+ return retired;
+}
diff --git a/src/core/store-migration/surface-map.ts b/src/core/store-migration/surface-map.ts
index edd2e8a0..50629966 100644
--- a/src/core/store-migration/surface-map.ts
+++ b/src/core/store-migration/surface-map.ts
@@ -374,6 +374,16 @@ export const SURFACE_MAP: Readonly<Record<StateSurfaceId, SurfaceMapping>> = Obj
[STATE_SURFACE_ID.rollupLedger]: plain(deviceLocal, MOVED + "consolidation counters"),
[STATE_SURFACE_ID.crossTopicLedger]: plain(deviceLocal, MOVED + "the daily promotion budget"),
[STATE_SURFACE_ID.proposalWatermark]: plain(deviceLocal, MOVED + "a scan watermark"),
+ [STATE_SURFACE_ID.proceduralUsage]: plain(
+ deviceLocal,
+ MOVED + "use and outcome counters that tick on every use of a procedure",
+ ),
+ [STATE_SURFACE_ID.proceduralGraph]: rebuildable(
+ plain(drop, "a projection recomputed from the procedural memory index"),
+ ),
+ [STATE_SURFACE_ID.proceduralHints]: rebuildable(
+ plain(drop, "recall cues recomputed from the procedural graph"),
+ ),
[STATE_SURFACE_ID.captureWatermark]: plain(deviceLocal, MOVED + "a catch-up watermark"),
[STATE_SURFACE_ID.decisionLedger]: ledger(
DUAL_WRITE_LEDGERS.permissions,
diff --git a/src/core/store/FORMAT.md b/src/core/store/FORMAT.md
index 092d4e1a..40c3f143 100644
--- a/src/core/store/FORMAT.md
+++ b/src/core/store/FORMAT.md
@@ -162,7 +162,9 @@ A preference is identified by the string in its records' `preference` field. Eac
The field `text` carries the preference page's body, the Markdown below its frontmatter, when the body holds prose the other fields do not render: an imported memory's text, a person's notes under the page's headings, or a writer's guidance on how to apply the rule. A body that is only the `## Origin` list of `evidenced_by` (and, once retired, the `## Retired` section built from the retire fields) carries no prose, and its `text` is absent or `null`. Like every field, `text` is a register resolved by authority, then clock, so prose a human wrote is not replaced by a later agent write. A page rebuilt from the fold carries `text` as its body, not as a frontmatter key; with no `text`, the body is rendered from the fields.
-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.
+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. The counters count the evidence of every partition the reading machine holds, so they are that machine's own view; a caller below local reach (a remote MCP transport) is shown the counters of the `shared` evidence alone.
+
+A preference is private when one of its `preference-set` or `preference-remove` records sits in `private`, or when its fields reserve it as private. A `preference-evidence` record in `private` does not make the preference private: such a record lands there because its artifact or note names a private page. It counts toward the preference's counters on a machine that holds `private`, and it is never used to compute the status, confidence or evidence fields of a shared preference, so those fields read the same on every machine. Toward a preference that is itself private it counts like any other evidence.
### Pinned context
diff --git a/src/core/store/caller-reach.ts b/src/core/store/caller-reach.ts
new file mode 100644
index 00000000..86135854
--- /dev/null
+++ b/src/core/store/caller-reach.ts
@@ -0,0 +1,45 @@
+/**
+ * Whether the work running now answers a caller below local reach (a
+ * remote MCP transport), as an ambient scope.
+ *
+ * Most readers that serve a remote caller take the reach as an explicit
+ * view (`brain/reach-view.ts`). A value that the store folds compute deep
+ * below every such reader cannot take one: the evidence counters of a
+ * preference (`applied_count`, `violated_count`, `outdated_count`) are
+ * folded from every partition this machine holds, and a remote caller
+ * must see them without the evidence of the `private` partition (task
+ * 3.18, design D15 item 4). The MCP server runs each tool call and
+ * resource read of a remote transport inside {@link withPrivateWithheld},
+ * so every reader below it, the preference facades, the digests, the
+ * operator snapshot and the review candidates, answers with the counters
+ * a machine that holds only `shared` would fold. Outside any scope (the
+ * CLI, hooks, a local transport) nothing is withheld.
+ */
+
+import { AsyncLocalStorage } from "node:async_hooks";
+
+const storage = new AsyncLocalStorage<true>();
+
+/**
+ * Run `fn` for a caller below local reach when `withhold` is true, and as
+ * it is otherwise. Returns what `fn` returns (a promise for an async body,
+ * which keeps the scope across its awaits).
+ */
+export function withPrivateWithheld<T>(withhold: boolean, fn: () => T): T {
+ return withhold ? storage.run(true, fn) : fn();
+}
+
+/** Whether the caller of the work running now is below local reach. */
+export function privateWithheld(): boolean {
+ return storage.getStore() === true;
+}
+
+/**
+ * Run `fn` with nothing withheld, inside a caller's scope too: for work
+ * whose result is shared with every later caller, such as a digest cache
+ * a local reader is served (a caller below local reach is given its own
+ * render, never the cache).
+ */
+export function withPrivateShown<T>(fn: () => T): T {
+ return storage.exit(fn);
+}
diff --git a/src/core/store/lane-entry-store.ts b/src/core/store/lane-entry-store.ts
index 1cb3c14c..37f22af9 100644
--- a/src/core/store/lane-entry-store.ts
+++ b/src/core/store/lane-entry-store.ts
@@ -15,7 +15,7 @@ import { BRAIN_ROOT_REL } from "../brain/path-constants.ts";
import { canonicalJson } from "../integrity/digest.ts";
import type { FrontmatterMap } from "../types.ts";
import { laneStoreFold } from "./lane-fold-cache.ts";
-import { lanePlaceOf } from "./lane-paths.ts";
+import { laneNameRefusal, lanePlaceOf } from "./lane-paths.ts";
import {
laneEntryKey,
laneEntryRecord,
@@ -59,8 +59,11 @@ export function brainRelOf(vault: string, path: string): string {
}
function placeOf(vault: string, path: string): { lane: string; entry: string } {
- const place = lanePlaceOf(brainRelOf(vault, path));
- if (place === null) throw new Error(`not a Brain lane page: ${path}`);
+ const rel = brainRelOf(vault, path);
+ const place = lanePlaceOf(rel);
+ if (place === null) {
+ throw new Error(`not a Brain lane page: ${path}: ${laneNameRefusal(rel) ?? "no lane entry"}`);
+ }
return place;
}
diff --git a/src/core/store/lane-paths.ts b/src/core/store/lane-paths.ts
index 57e4813c..04545c8f 100644
--- a/src/core/store/lane-paths.ts
+++ b/src/core/store/lane-paths.ts
@@ -22,7 +22,8 @@ export const ROOT_LANE = "brain";
const MD = ".md";
/** Extensions an entry id keeps: the files of a lane that are not pages. */
-const KEPT_EXTENSION_RE = /\.(?:json|jsonl|yaml|yml|txt|base|csv)$/;
+const KEPT_EXTENSIONS = Object.freeze(["json", "jsonl", "yaml", "yml", "txt", "base", "csv"]);
+const KEPT_EXTENSION_RE = new RegExp(`\\.(?:${KEPT_EXTENSIONS.join("|")})$`);
/** Folders whose lane is not their own name, and the one root file with a lane. */
const FOLDER_LANES: Readonly<Record<string, string>> = Object.freeze({
@@ -53,18 +54,23 @@ export function folderOfLane(lane: string): string {
return LANE_FOLDERS[lane] ?? lane;
}
-/** The entry id of a path inside its lane folder: `.md` dropped, other extensions kept. */
-export function entryOfPath(inLane: string): string {
- return inLane.endsWith(MD) ? inLane.slice(0, -MD.length) : inLane;
+/** Whether an entry id is a file name as it stands, with no `.md` to add back. */
+function keepsItsName(entry: string): boolean {
+ return KEPT_EXTENSION_RE.test(entry) || entry.endsWith(MD);
}
/**
- * The lane and entry of a `Brain/`-relative path (`/`-separated), or null
- * for a path that names no entry (empty, or the root itself).
+ * The entry id of a path inside its lane folder: `.md` dropped, other
+ * extensions kept, and the whole name kept for a page whose name without
+ * `.md` would read as a kept file (`x.json.md`).
*/
-export function lanePlaceOf(brainRel: string): { lane: string; entry: string } | null {
- const segments = brainRel.split("/").filter((s) => s !== "");
- if (segments.length === 0) return null;
+export function entryOfPath(inLane: string): string {
+ if (!inLane.endsWith(MD)) return inLane;
+ const stem = inLane.slice(0, -MD.length);
+ return keepsItsName(stem) ? inLane : stem;
+}
+
+function placeOfSegments(segments: ReadonlyArray<string>): { lane: string; entry: string } {
if (segments.length === 1) {
const special = ROOT_FILE_LANES[segments[0]!];
if (special !== undefined) return special;
@@ -74,11 +80,93 @@ export function lanePlaceOf(brainRel: string): { lane: string; entry: string } |
return { lane: laneOfFolder(folder), entry: entryOfPath(rest.join("/")) };
}
+/**
+ * Why the `Brain/`-relative path `brainRel` (`/`-separated) names no lane
+ * entry, or null when it names one. A path names no entry when it is
+ * empty (the root itself) or when its place would not turn back into the
+ * same path (see the module comment).
+ */
+export function laneNameRefusal(brainRel: string): string | null {
+ const segments = brainRel.split("/").filter((s) => s !== "");
+ if (segments.length === 0) return "the Brain root is not a lane entry";
+ const place = placeOfSegments(segments);
+ const back = place.entry === "" ? null : brainRelOfEntry(place.lane, place.entry);
+ if (back === segments.join("/")) return null;
+ return (
+ `the name ${segments.join("/")} does not map to a lane entry and back ` +
+ `(lane ${place.lane}, entry ${place.entry === "" ? "(empty)" : place.entry}` +
+ `${back === null ? "" : `, which maps back to ${back}`}); a lane entry is a .md page ` +
+ `or a file ending in .${KEPT_EXTENSIONS.join(", .")}, in a folder named as its lane`
+ );
+}
+
+/**
+ * The lane and entry of a `Brain/`-relative path (`/`-separated), or null
+ * for a path that names no entry: empty, the root itself, or a name that
+ * does not round-trip ({@link laneNameRefusal}).
+ */
+export function lanePlaceOf(brainRel: string): { lane: string; entry: string } | null {
+ if (laneNameRefusal(brainRel) !== null) return null;
+ return placeOfSegments(brainRel.split("/").filter((s) => s !== ""));
+}
+
/** The `Brain/`-relative path of an entry (`/`-separated). */
export function brainRelOfEntry(lane: string, entry: string): string {
for (const [file, place] of Object.entries(ROOT_FILE_LANES)) {
if (place.lane === lane && place.entry === entry) return file;
}
- const file = KEPT_EXTENSION_RE.test(entry) ? entry : `${entry}${MD}`;
+ const file = keepsItsName(entry) ? entry : `${entry}${MD}`;
return lane === ROOT_LANE ? file : `${folderOfLane(lane)}/${file}`;
}
+
+/**
+ * The place a legacy path whose top folder is spelled otherwise than its
+ * lane name (`My Notes/x.md`, `project_x/x.md`: case, spaces, other
+ * separators) takes in the store: the normalized lane (`my-notes`) and
+ * the entry of the rest of the path, or null for any other path. Such a
+ * path is refused by {@link lanePlaceOf}, since the entry would turn back
+ * into the normalized folder; the migration imports it here and keeps the
+ * original path in the record's `migrated` mark, which is where a
+ * rollback writes it back. Null as well when the normalized name is no
+ * plain lane (the root lane, another folder's lane, or no lane name at
+ * all), and when the rest of the path does not round-trip; the caller
+ * also refuses a folder whose normalized lane another folder of the tree
+ * takes.
+ */
+export function normalizedFolderPlace(brainRel: string): { lane: string; entry: string } | null {
+ const segments = brainRel.split("/").filter((s) => s !== "");
+ if (segments.length < 2) return null;
+ const [folder, ...rest] = segments as [string, ...string[]];
+ if (FOLDER_LANES[folder] !== undefined) return null;
+ const lane = laneNameOf(folder);
+ if (lane === folder || lane === ROOT_LANE || laneNameOf(lane) !== lane) return null;
+ if (
+ folder
+ .toLowerCase()
+ .replace(/[^a-z0-9-]+/g, "-")
+ .replace(/^-+|-+$/g, "") !== lane
+ ) {
+ return null;
+ }
+ if (laneOfFolder(lane) !== lane || folderOfLane(lane) !== lane) return null;
+ const inLane = rest.join("/");
+ const entry = entryOfPath(inLane);
+ if (entry === "" || brainRelOfEntry(lane, entry) !== `${lane}/${inLane}`) return null;
+ return { lane, entry };
+}
+
+/**
+ * The top folders among `folders` (names directly under `Brain/`) whose
+ * pages the migration files under `lane` besides `folder`: a rival of a
+ * respelled folder. A dot-folder is no rival (the catch-all claims none
+ * of its pages), and a folder whose lane is another name (`state` is
+ * `exact-state`, `.archives` is `source-archive`) takes that lane, not its
+ * spelling.
+ */
+export function laneFolderRivals(
+ folders: ReadonlyArray<string>,
+ folder: string,
+ lane: string,
+): string[] {
+ return folders.filter((f) => f !== folder && !f.startsWith(".") && laneOfFolder(f) === lane);
+}
diff --git a/src/core/store/read/preferences.ts b/src/core/store/read/preferences.ts
index 4dbd284d..123e5c6f 100644
--- a/src/core/store/read/preferences.ts
+++ b/src/core/store/read/preferences.ts
@@ -40,7 +40,7 @@ import type { PreferenceCounters } from "../fold-preferences.ts";
import { isPrivatePageFile } from "../private-page.ts";
import type { StoreInspection } from "../store-open.ts";
import { readSource, type ReadContext } from "./read-context.ts";
-import { readEntitiesOf } from "./store-entities.ts";
+import { countersAtReach, readEntitiesOf } from "./store-entities.ts";
/** One preference as the facades return it. */
export interface PreferenceEntry {
@@ -139,7 +139,8 @@ function legacyEntries(
function storeEntries(store: StoreInspection, retired: boolean): PreferenceEntry[] {
const out: PreferenceEntry[] = [];
- for (const [id, { state, private: isPrivate }] of readEntitiesOf(store).preferences) {
+ for (const [id, entry] of readEntitiesOf(store).preferences) {
+ const { state, private: isPrivate } = entry;
if (!state.exists || !id.startsWith(PREFERENCE_PREFIX)) continue;
if ((state.fields["status"] === RETIRED_STATUS) !== retired) continue;
out.push({
@@ -148,7 +149,8 @@ function storeEntries(store: StoreInspection, retired: boolean): PreferenceEntry
retired,
private: isPrivate,
fields: viewFields(state.fields),
- counters: state.counters,
+ // Below local reach without the private partition's evidence (task 3.18).
+ counters: countersAtReach(entry),
});
}
return out;
diff --git a/src/core/store/read/store-entities.ts b/src/core/store/read/store-entities.ts
index 055bd6c3..f7705ec2 100644
--- a/src/core/store/read/store-entities.ts
+++ b/src/core/store/read/store-entities.ts
@@ -21,8 +21,12 @@
*
* Privacy (FORMAT.md, "Partitions"): an entity is private when any of
* its records sits in `private`, or when its fields reserve it as private
- * by the rule every legacy page uses (`isPrivateFrontmatter`). Nothing is
- * written.
+ * by the rule every legacy page uses (`isPrivateFrontmatter`). A
+ * preference's `preference-evidence` records do not count for it: one
+ * lands in `private` because its artifact or note names a private page,
+ * which says nothing about the rule itself, and counting it would move a
+ * shared preference into `private` on its first such use (task 3.18).
+ * Nothing is written.
*/
import { statSync } from "node:fs";
@@ -30,6 +34,9 @@ import { statSync } from "node:fs";
import {
PINNED_CLEAR_KIND,
PINNED_SET_KIND,
+ EVIDENCE_RESULTS,
+ PREFERENCE_COUNTER_FIELDS,
+ PREFERENCE_EVIDENCE_KIND,
PREFERENCE_SET_KIND,
SIGNAL_KIND,
type StorePartition,
@@ -43,7 +50,12 @@ import {
SIGNAL_STATE_KIND,
type SignalLifecycle,
} from "../fold-signals.ts";
-import { foldPreferences, type PreferenceState } from "../fold-preferences.ts";
+import {
+ foldPreferences,
+ type PreferenceCounters,
+ type PreferenceState,
+} from "../fold-preferences.ts";
+import { privateWithheld } from "../caller-reach.ts";
import { listShards } from "../shard-list.ts";
import { inspectStore, type StoreInspection } from "../store-open.ts";
import { partitionDir, pendingBlobStampLines, resolveConfiguredStoreRoot } from "../store-paths.ts";
@@ -54,6 +66,55 @@ import { quarantineStamp } from "../shard-quarantine.ts";
export interface StorePreference {
readonly state: PreferenceState;
readonly private: boolean;
+ /**
+ * The evidence counters without the evidence of the `private` partition:
+ * what a machine that holds only `shared` folds, and what a caller below
+ * local reach is shown ({@link countersAtReach}).
+ */
+ readonly sharedCounters: PreferenceCounters;
+ /** Ids of the records of {@link PreferenceState.history} that sit in `private`. */
+ readonly privateRecordIds: ReadonlySet<string>;
+}
+
+/**
+ * The evidence counters of `entry` for the caller of the work running now:
+ * the shared counters below local reach (`../caller-reach.ts`), every held
+ * partition's otherwise (task 3.18).
+ */
+export function countersAtReach(entry: StorePreference): PreferenceCounters {
+ return privateWithheld() ? entry.sharedCounters : entry.state.counters;
+}
+
+/**
+ * The evidence counters that may be written into a record about `entry`
+ * other machines read (a merge summary, a dream comparison): every held
+ * partition's for a private preference, the shared ones otherwise, so a
+ * private use never reaches `shared` through a derived number (task 3.18).
+ */
+export function countersForShared(entry: StorePreference): PreferenceCounters {
+ return entry.private ? entry.state.counters : entry.sharedCounters;
+}
+
+/** The counters of `history`'s evidence records that are not in `privateIds`. */
+function sharedCountersOf(
+ history: ReadonlyArray<StoreRecord>,
+ privateIds: ReadonlySet<string>,
+): PreferenceCounters {
+ const out = Object.fromEntries(PREFERENCE_COUNTER_FIELDS.map((name) => [name, 0])) as Record<
+ (typeof PREFERENCE_COUNTER_FIELDS)[number],
+ number
+ >;
+ for (const record of history) {
+ if (record.kind !== PREFERENCE_EVIDENCE_KIND || privateIds.has(record.id)) continue;
+ const result = record.body["result"];
+ if (
+ typeof result === "string" &&
+ (EVIDENCE_RESULTS as ReadonlyArray<string>).includes(result)
+ ) {
+ out[`${result}_count` as (typeof PREFERENCE_COUNTER_FIELDS)[number]] += 1;
+ }
+ }
+ return out;
}
/**
@@ -172,7 +233,9 @@ function build(store: StoreInspection): StoreEntities {
const fold = foldPreferences(all.map((e) => e.record));
const preferences = new Map<string, StorePreference>();
for (const [id, state] of fold.preferences) {
- const inPrivate = state.history.some((record) => privateIds.has(record.id));
+ const inPrivate = state.history.some(
+ (record) => privateIds.has(record.id) && record.kind !== PREFERENCE_EVIDENCE_KIND,
+ );
// A removed preference's fold holds no fields, so its history is what
// still says whether it was marked private.
const markedPrivate = state.removed
@@ -182,7 +245,14 @@ function build(store: StoreInspection): StoreEntities {
isPrivateFrontmatter((record.body["fields"] ?? {}) as Record<string, unknown>),
)
: isPrivateFrontmatter(state.fields);
- preferences.set(id, { state, private: degraded || inPrivate || markedPrivate });
+ preferences.set(id, {
+ state,
+ private: degraded || inPrivate || markedPrivate,
+ sharedCounters: sharedCountersOf(state.history, privateIds),
+ privateRecordIds: new Set(
+ state.history.filter((record) => privateIds.has(record.id)).map((record) => record.id),
+ ),
+ });
}
const signals = new Map<string, StoreSignal>();
const partitionOf = new Map(all.map((e) => [e.record.id, e.partition] as const));
diff --git a/src/core/store/seen-shards.ts b/src/core/store/seen-shards.ts
index 236948c2..7bf297c2 100644
--- a/src/core/store/seen-shards.ts
+++ b/src/core/store/seen-shards.ts
@@ -20,9 +20,23 @@
* The ledger lives in the store's device-local directory
* (`<state>/open-second-brain/stores/<store id>/seen-shards-<root hash>.json`),
* so a store recreated under the same root, or a copy of a store at another
- * root, starts a fresh one. It is written
- * best-effort, without a lock (a reader must not take one): a lost update
- * between two processes only delays tracking a shard to the next read.
+ * root, starts a fresh one. Every read-modify-write of the ledger runs
+ * under the device-local lock of the ledger file (`local-lock.ts`), and
+ * re-reads the file inside it, so two processes on one machine never
+ * interleave: a stale write from {@link trackSeenShards} cannot bring
+ * back the entries a partition leave just cleared, and a leave cannot
+ * drop a shard another process just recorded. The lock guards only the
+ * ledger file and takes no other lock inside it, so a reader that already
+ * holds a store lock can take it. A tracking update stays best-effort: it
+ * waits at most {@link TRACK_LOCK_BUDGET_MS} (a read must not stall on a
+ * lock a crashed process left), and a lock still busy then leaves the
+ * change queued in the process: the next update of the ledger writes it
+ * with its own, so a skip delays tracking a shard, it does not drop it. After a
+ * skip behind a lock one holder kept through the whole wait (a crashed
+ * process's) the process leaves the ledger alone for
+ * {@link TRACK_BACKOFF_MS} without waiting, so a hook that lists several
+ * streams behind it loses the wait once, not once per listing; a lock
+ * other processes take and release in turn backs nothing off.
* A surface that promises to write nothing (doctor, the status block)
* runs inside {@link withoutSeenRecording}: it still reports a shard the
* ledger names that is gone, and records nothing. Leaving a partition
@@ -63,6 +77,66 @@ interface Loaded {
const loaded = new Map<string, Loaded>();
+/**
+ * The device-local lock, loaded on the first ledger write: every stream
+ * read imports this module, and a hot path that only reads (a hook with
+ * its feature off) must not load the lock modules for it.
+ */
+function withLocalLock<T>(lockTarget: string, fn: () => T, budgetMs?: number): T {
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
+ const lock = require("./local-lock.ts") as typeof import("./local-lock.ts");
+ return lock.withLocalLock(lockTarget, fn, budgetMs);
+}
+
+/** Longest wait of a tracking update for the ledger lock; a leave waits the full lock budget. */
+const TRACK_LOCK_BUDGET_MS = 500;
+
+/** How long a tracking update that found the lock busy keeps the process off it. */
+const TRACK_BACKOFF_MS = 10_000;
+
+/** Ledger paths whose lock was found busy, with the time the back-off ends. */
+const busyUntil = new Map<string, number>();
+
+/** One tracking change: shards a listing saw, and shards it found replaced. */
+interface TrackChange {
+ readonly partitionRoot: string;
+ readonly partition: StorePartition;
+ readonly fresh: ReadonlyArray<string>;
+ readonly expected: ReadonlyArray<string>;
+}
+
+/** Tracking changes of this process an update could not write yet, per ledger path. */
+const pending = new Map<string, TrackChange[]>();
+
+/** The most changes kept for one ledger path while its lock stays busy. */
+const PENDING_MAX = 1_000;
+
+/**
+ * Apply `changes` to `ledger`, leaving out those of a partition this
+ * machine no longer holds (its identity file is gone): a change queued
+ * before `o2b store partition leave` cleared the partition must not bring
+ * its entries back.
+ */
+function applyChanges(ledger: Ledger, changes: ReadonlyArray<TrackChange>): void {
+ const held = new Map<string, boolean>();
+ for (const change of changes) {
+ let holds = held.get(change.partitionRoot);
+ if (holds === undefined) {
+ try {
+ holds = readStoreId(change.partitionRoot) !== null;
+ } catch {
+ holds = false;
+ }
+ held.set(change.partitionRoot, holds);
+ }
+ if (!holds) continue;
+ const own = ledger.get(change.partition) ?? new Set<string>();
+ for (const rel of change.fresh) own.add(rel);
+ for (const rel of change.expected) own.delete(rel);
+ ledger.set(change.partition, own);
+ }
+}
+
/** Depth of read-only scopes in this process. */
let readOnlyDepth = 0;
@@ -165,22 +239,75 @@ function isStrictLedger(value: unknown): boolean {
);
}
-/** Apply `change` to the ledger on disk and write it back; never throws. */
-function update(path: string, change: (ledger: Ledger) => void): void {
+/**
+ * Apply `change` to the ledger on disk and write it back. The caller holds
+ * the ledger lock, and `ledger` is the file as read inside it.
+ */
+function writeChanged(path: string, ledger: Ledger, change: (ledger: Ledger) => void): void {
+ change(ledger);
+ const shards: Record<string, string[]> = {};
+ for (const [partition, rels] of [...ledger].toSorted(([a], [b]) => compareCodeUnits(a, b))) {
+ shards[partition] = [...rels].toSorted();
+ }
+ mkdirSync(dirname(path), { recursive: true });
+ atomicWriteText(path, `${JSON.stringify({ version: 1, shards }, null, 2)}\n`);
+ loaded.set(path, { stamp: stampOf(path), ledger });
+}
+
+/**
+ * Apply `change`, with every change of this process an earlier update
+ * could not write, to the ledger on disk under the ledger lock, reading
+ * the file again inside it; never throws (best-effort, see the module
+ * comment).
+ */
+function update(path: string, change: TrackChange | null): void {
+ const queued = pending.get(path) ?? [];
+ if (change !== null) queued.push(change);
+ // Bounded: a process that never gets the lock keeps its newest changes.
+ if (queued.length > PENDING_MAX) queued.splice(0, queued.length - PENDING_MAX);
+ pending.set(path, queued);
+ const until = busyUntil.get(path);
+ if (until !== undefined && Date.now() < until) return;
+ const holder = lockHolderStamp(path);
try {
+ withLocalLock(
+ path,
+ () => {
+ loaded.delete(path);
+ // Every change an earlier update of this process could not write,
+ // then this one: a skip delays a shard's tracking, it does not drop it.
+ writeChanged(path, load(path), (ledger) => applyChanges(ledger, queued));
+ },
+ TRACK_LOCK_BUDGET_MS,
+ );
+ pending.delete(path);
+ busyUntil.delete(path);
+ } catch (err) {
loaded.delete(path);
- const ledger = load(path);
- change(ledger);
- const shards: Record<string, string[]> = {};
- for (const [partition, rels] of [...ledger].toSorted(([a], [b]) => compareCodeUnits(a, b))) {
- shards[partition] = [...rels].toSorted();
+ // Backed off only from a lock one holder has kept the whole wait and
+ // longer (a crashed process's, or one stuck). A lock that other
+ // processes take and release in turn is live contention, whatever its
+ // directory's stat says (on Windows a released lock directory can
+ // linger with its old stat while a delete is pending), so the next
+ // read tries again.
+ const after = lockHolderStamp(path);
+ if (
+ (err as NodeJS.ErrnoException | null)?.code === "ELOCKED" &&
+ holder !== null &&
+ after === holder &&
+ Date.now() - after >= TRACK_LOCK_BUDGET_MS
+ ) {
+ busyUntil.set(path, Date.now() + TRACK_BACKOFF_MS);
}
- mkdirSync(dirname(path), { recursive: true });
- atomicWriteText(path, `${JSON.stringify({ version: 1, shards }, null, 2)}\n`);
- loaded.set(path, { stamp: stampOf(path), ledger });
+ }
+}
+
+/** The modification time of the ledger's lock directory, or null when none is held. */
+function lockHolderStamp(path: string): number | null {
+ try {
+ return statSync(`${path}.lock`).mtimeMs;
} catch {
- // Best-effort, see the module comment.
- loaded.delete(path);
+ return null;
}
}
@@ -213,9 +340,11 @@ function ledgerPath(partitionRoot: string): { path: string; partition: StorePart
* the store `storeId`, and return how many there were. Checked, not
* best-effort: the ledger is read strictly, so a file that exists but
* cannot be read or parsed throws (the lenient `load` would answer an
- * empty map and report a clearing that did not happen), and the ledger's
- * `update` never throws, so this verifies the write landed before the
- * caller reports the partition cleared.
+ * empty map and report a clearing that did not happen), and the write is
+ * verified to have landed before the caller reports the partition cleared.
+ * The read, the write and the check run under one hold of the ledger lock,
+ * so a tracking update of another process lands before or after the whole
+ * clearing, never inside it.
*/
export function forgetSeenPartition(
storeRoot: string,
@@ -223,18 +352,34 @@ export function forgetSeenPartition(
partition: StorePartition,
): number {
const path = seenLedgerFile(storeRoot, storeId);
- const count = loadStrict(path).get(partition)?.size ?? 0;
- if (count > 0) {
- update(path, (ledger) => {
- ledger.delete(partition);
- });
- if ((loadStrict(path).get(partition)?.size ?? 0) > 0) {
- throw new Error(
- `could not clear the seen-shard entries of the ${partition} partition in ${path}`,
- );
- }
+ // This process's queued tracking of the partition goes with its entries.
+ const queued = pending.get(path);
+ if (queued !== undefined) {
+ pending.set(
+ path,
+ queued.filter((change) => change.partition !== partition),
+ );
}
- return count;
+ return withLocalLock(path, () => {
+ loaded.delete(path);
+ const ledger = loadStrict(path);
+ const count = ledger.get(partition)?.size ?? 0;
+ if (count > 0) {
+ try {
+ writeChanged(path, ledger, (l) => {
+ l.delete(partition);
+ });
+ } catch {
+ loaded.delete(path);
+ }
+ if ((loadStrict(path).get(partition)?.size ?? 0) > 0) {
+ throw new Error(
+ `could not clear the seen-shard entries of the ${partition} partition in ${path}`,
+ );
+ }
+ }
+ return count;
+ });
}
function deviceOf(rel: string): string {
@@ -284,7 +429,15 @@ export function trackSeenShards(
): string[] {
const at = ledgerPath(partitionRoot);
if (at === null) return [];
- const seen = load(at.path).get(at.partition) ?? new Set<string>();
+ // What this machine has seen: the ledger, and what this process saw but
+ // could not write to it yet (a queued change), so a shard tracked behind
+ // a busy lock is still named once it is gone.
+ const seen = new Set(load(at.path).get(at.partition) ?? []);
+ for (const change of pending.get(at.path) ?? []) {
+ if (change.partition !== at.partition) continue;
+ for (const rel of change.fresh) seen.add(rel);
+ for (const rel of change.expected) seen.delete(rel);
+ }
const present = new Set(listed);
const fresh = listed.filter((rel) => !seen.has(rel));
let missing = [...seen].filter(
@@ -301,13 +454,13 @@ export function trackSeenShards(
expected = [...expected, ...missing.filter((rel) => retired.has(deviceOf(rel)))];
missing = missing.filter((rel) => !retired.has(deviceOf(rel)));
}
- if (readOnlyDepth === 0 && (fresh.length > 0 || expected.length > 0)) {
- update(at.path, (ledger) => {
- const own = ledger.get(at.partition) ?? new Set<string>();
- for (const rel of fresh) own.add(rel);
- for (const rel of expected) own.delete(rel);
- ledger.set(at.partition, own);
- });
+ if (readOnlyDepth === 0) {
+ if (fresh.length > 0 || expected.length > 0) {
+ update(at.path, { partitionRoot, partition: at.partition, fresh, expected });
+ } else if ((pending.get(at.path)?.length ?? 0) > 0) {
+ // Nothing new, but changes are still queued: try to write them now.
+ update(at.path, null);
+ }
}
return missing.toSorted();
}
diff --git a/src/mcp/server.ts b/src/mcp/server.ts
index 12be59ce..48aa56d8 100644
--- a/src/mcp/server.ts
+++ b/src/mcp/server.ts
@@ -20,6 +20,7 @@ import {
vaultFrozenRefusal,
} from "./frozen-refusal.ts";
import { assertNoCallerSuppliedReach } from "./reach-refusal.ts";
+import { withPrivateWithheld } from "../core/store/caller-reach.ts";
import { buildInstructions } from "./instructions.ts";
import {
INTERNAL_ERROR,
@@ -317,9 +318,13 @@ export class MCPServer {
/** Public method for CLI tool-call bridge — the legacy code reached into `_tools`. */
async callTool(name: string, args: Record<string, unknown>): Promise<Record<string, unknown>> {
const tool = findTool(this.tools, name);
- return toolResult(
- tool,
- this.forCaller(await this.invokeToolHandler(tool, args, undefined, undefined)),
+ // The same scope `tools/call` runs in: below local reach the readers
+ // answer without what only the `private` partition knows.
+ return withPrivateWithheld(this.reach !== TRANSPORT_REACH.local, async () =>
+ toolResult(
+ tool,
+ this.forCaller(await this.invokeToolHandler(tool, args, undefined, undefined)),
+ ),
);
}
@@ -501,14 +506,22 @@ export class MCPServer {
} else if (method === "tools/list") {
result = this.handleToolsList();
} else if (method === "tools/call") {
- result = await this.handleToolsCall(params, identity);
+ // Below local reach every reader answers without what only the
+ // `private` partition knows, down to the folds' derived counters.
+ result = await withPrivateWithheld(this.reach !== TRANSPORT_REACH.local, () =>
+ this.handleToolsCall(params, identity),
+ );
} else if (method === "resources/list") {
result = this.handleResourcesList();
} else if (method === "resources/templates/list") {
result = this.handleResourcesTemplatesList();
} else if (method === "resources/read") {
// A resource body is prose the brain rendered; it may name a host path.
- result = this.forCaller(this.handleResourcesRead(params, identity));
+ result = this.forCaller(
+ await withPrivateWithheld(this.reach !== TRANSPORT_REACH.local, () =>
+ this.handleResourcesRead(params, identity),
+ ),
+ );
} else if (method.startsWith("notifications/")) {
return null;
} else {
diff --git a/tests/cli/brain-explorer.test.ts b/tests/cli/brain-explorer.test.ts
index e1e4d10d..931e9c78 100644
--- a/tests/cli/brain-explorer.test.ts
+++ b/tests/cli/brain-explorer.test.ts
@@ -106,8 +106,60 @@ async function readUntil(
}
}
-function pickPort(): number {
- return 30000 + Math.floor(Math.random() * 25000);
+/**
+ * A port the system has just handed out as free (bound to port 0 and let
+ * go), not a guess: a fixed or random high port can sit in a range the
+ * host reserves (Windows excludes whole port blocks) or be taken by
+ * another job on a shared runner.
+ */
+function freePort(): number {
+ const probe = Bun.serve({ hostname: "127.0.0.1", port: 0, fetch: () => new Response("") });
+ const port = probe.port as number;
+ void probe.stop(true);
+ return port;
+}
+
+/**
+ * Start the live explorer for the test vault and wait until it listens.
+ * A port another process took between `freePort` and the bind is retried
+ * on a new one, a few times; any other failure to start is thrown with
+ * what the child printed.
+ */
+async function startExplorer(
+ configPath: string,
+): Promise<{ readonly proc: ReturnType<typeof Bun.spawn>; readonly port: number }> {
+ for (let attempt = 0; ; attempt++) {
+ const port = freePort();
+ const proc = Bun.spawn(
+ [
+ "bun",
+ "run",
+ "src/cli/main.ts",
+ "brain",
+ "explorer",
+ "--vault",
+ vault,
+ "--port",
+ String(port),
+ ],
+ {
+ cwd: process.cwd(),
+ env: { ...process.env, OPEN_SECOND_BRAIN_CONFIG: configPath },
+ stdout: "pipe",
+ stderr: "pipe",
+ },
+ );
+ // Each attempt waits on the child before the next: nothing to batch.
+ // oxlint-disable-next-line no-await-in-loop
+ const banner = await readUntil(proc.stdout as ReadableStream<Uint8Array>, "Live explorer at ");
+ if (banner.found) return { proc, port };
+ // oxlint-disable-next-line no-await-in-loop
+ const stderr = await new Response(proc.stderr as ReadableStream<Uint8Array>).text();
+ // oxlint-disable-next-line no-await-in-loop
+ await proc.exited;
+ if (attempt < 4 && /in use/i.test(stderr)) continue;
+ throw new Error(`explorer exited before listening:\n${banner.text}${stderr}`);
+ }
}
describe("o2b brain explorer --help", () => {
@@ -357,32 +409,8 @@ describe("o2b brain explorer (live) store group", () => {
mkdirSync(dirname(lockPath), { recursive: true });
symlinkSync(lockPath, lockPath);
- const port = pickPort();
- const proc = Bun.spawn(
- [
- "bun",
- "run",
- "src/cli/main.ts",
- "brain",
- "explorer",
- "--vault",
- vault,
- "--port",
- String(port),
- ],
- {
- cwd: process.cwd(),
- env: { ...process.env, OPEN_SECOND_BRAIN_CONFIG: config },
- stdout: "pipe",
- stderr: "pipe",
- },
- );
+ const { proc, port } = await startExplorer(config);
try {
- const banner = await readUntil(proc.stdout, "Live explorer at ");
- if (!banner.found) {
- const stderr = await new Response(proc.stderr).text();
- throw new Error(`explorer exited before listening:\n${banner.text}${stderr}`);
- }
const res = await fetch(`http://127.0.0.1:${port}/status.json`);
expect(res.ok).toBe(true);
const status = JSON.parse(await res.text()) as {
@@ -414,42 +442,14 @@ describe("o2b brain explorer (live)", () => {
async () => {
await bootstrap();
seedOnePref();
- const port = pickPort();
- // Spawn the CLI manually so we can poll the server and send SIGINT.
- // `cwd: process.cwd()` instead of a hard-coded path so the test
- // works from any checkout (CI, local clone, contributor laptop).
- const isolatedConfig = config;
- const proc = Bun.spawn(
- [
- "bun",
- "run",
- "src/cli/main.ts",
- "brain",
- "explorer",
- "--vault",
- vault,
- "--port",
- String(port),
- ],
- {
- cwd: process.cwd(),
- env: { ...process.env, OPEN_SECOND_BRAIN_CONFIG: isolatedConfig },
- stdout: "pipe",
- stderr: "pipe",
- },
- );
+ // Spawned so the test can poll the server and send SIGINT. It waits
+ // for the CLI to say it is listening, not for a clock: the line is
+ // printed only once the server is bound, so the first fetch cannot
+ // race the boot (a fixed poll lost to a cold start on the Windows
+ // runner, and WSL's mirrored loopback drops a SYN to an unbound port
+ // instead of refusing it).
+ const { proc, port } = await startExplorer(config);
try {
- // Wait for the CLI to say it is listening, not for a clock. It prints
- // the line only after the server is bound, so the first fetch cannot
- // race the boot. The fixed 3 s poll this replaces lost to a cold
- // `bun run src/cli/main.ts` on the Windows runner, and polling a port
- // nothing is bound to yet is not even a clean refusal everywhere
- // (WSL's mirrored loopback drops the SYN instead of refusing it).
- const banner = await readUntil(proc.stdout, "Live explorer at ");
- if (!banner.found) {
- const stderr = await new Response(proc.stderr).text();
- throw new Error(`explorer exited before listening:\n${banner.text}${stderr}`);
- }
const r = await fetch(`http://127.0.0.1:${port}/`);
expect(r.ok).toBe(true);
const mainBody = await r.text();
diff --git a/tests/core/architecture/state-surface-census.test.ts b/tests/core/architecture/state-surface-census.test.ts
index 0cf5388a..d1a36758 100644
--- a/tests/core/architecture/state-surface-census.test.ts
+++ b/tests/core/architecture/state-surface-census.test.ts
@@ -133,7 +133,10 @@ const SWEPT_POPULATION_SIZE = 33;
// 58 -> 61: the embedding and rerank provider registries and the search
// activation history join the catalogue as device-local rows, so the
// migration moves them (task 2.10 review).
-const DECLARED_SURFACE_COUNT = 61;
+// 61 -> 64: the procedural usage counters, graph and hints join the
+// catalogue as device-local rows, so a usage tick appends no store record
+// and the migration moves the counters (task 3.10).
+const DECLARED_SURFACE_COUNT = 64;
/** An exclusion reason has to be an argument, not a label. */
const MIN_REASON_LENGTH = 80;
diff --git a/tests/core/architecture/write-site-census.test.ts b/tests/core/architecture/write-site-census.test.ts
index 26a85d3c..87edbae6 100644
--- a/tests/core/architecture/write-site-census.test.ts
+++ b/tests/core/architecture/write-site-census.test.ts
@@ -1647,8 +1647,13 @@ const DIRECT_WRITE_ROWS = 82;
* 112 -> 113: the legacy-tree removal journals its archive
* (`removal.json`, device-local migration folder) before the first move,
* so an interrupted removal finishes into the same archive.
+ * 113 -> 114: the procedural graph, hints and usage counters are machine
+ * state written with the shared atomic writer, not lane records, so a
+ * usage tick appends no store record (task 3.10).
+ * 114 -> 115: the lane-id repair writes its device-local "repaired" marker
+ * with the shared atomic writer, once per store (task 3.9).
*/
-const SHARED_HELPER_ROWS = 113;
+const SHARED_HELPER_ROWS = 115;
// ----- Origin-channel coverage boundary (Unit C) ----------------------------
@@ -1909,8 +1914,12 @@ const UNSTAMPED_DIRECT_ROWS = 81;
* files carry no origin channel.
* 108 -> 109: the legacy-tree removal's device-local journal, machine
* state and no note.
+ * 109 -> 110: the procedural graph, hints and usage counters, machine
+ * state and no note (task 3.10).
+ * 110 -> 111: the lane-id repair's device-local marker, machine state and
+ * no note (task 3.9).
*/
-const UNSTAMPED_SHARED_ROWS = 109;
+const UNSTAMPED_SHARED_ROWS = 111;
describe("in-vault write-site census", () => {
test("every direct-fs write site carries a written exclusion", () => {
diff --git a/tests/core/brain/dream-private-evidence.test.ts b/tests/core/brain/dream-private-evidence.test.ts
new file mode 100644
index 00000000..22963c39
--- /dev/null
+++ b/tests/core/brain/dream-private-evidence.test.ts
@@ -0,0 +1,235 @@
+/**
+ * Private `apply-evidence` in the dream pass on a switched machine (task
+ * 3.18, design "Private evidence"): an event that lands in `private`
+ * because its note names a private page never moves a shared preference's
+ * status or confidence, which every machine reads from `shared`; it does
+ * move a preference that is itself private.
+ */
+import { afterEach, describe, expect, test } from "bun:test";
+import { join } from "node:path";
+
+import { appendApplyEvidence } from "../../../src/core/brain/apply-evidence.ts";
+import { dream } from "../../../src/core/brain/dream.ts";
+import { mergePreferences } from "../../../src/core/brain/merge.ts";
+import { appendRecord } from "../../../src/core/store/appender.ts";
+import { openStore } from "../../../src/core/store/store-open.ts";
+import { writePreference } from "../../../src/core/brain/preference.ts";
+import { withOperationPrivacy } from "../../../src/core/store/operation-scope.ts";
+import { foldPreferences } from "../../../src/core/store/fold-preferences.ts";
+import { readPartition } from "../../../src/core/store/state-digest.ts";
+import { makeStoreEnv, type StoreEnv } from "../store/fixtures/store-env.ts";
+import { switchDevice } from "./store-only/fixtures.ts";
+
+let env: StoreEnv | undefined;
+afterEach(() => {
+ env?.cleanup();
+ env = undefined;
+});
+
+const NOW = new Date("2026-11-10T12:00:00Z");
+
+const prefInput = (slug: string) => ({
+ slug,
+ topic: slug,
+ principle: `principle ${slug}`,
+ created_at: "2026-11-01T00:00:00Z",
+ unconfirmed_until: "2026-12-30T00:00:00Z",
+ status: "unconfirmed" as const,
+ evidenced_by: [],
+});
+
+/** Evidence whose note names a preference the store cannot resolve: judged private. */
+function privateEvidence(e: StoreEnv, slug: string): void {
+ appendApplyEvidence(e.vault, {
+ pref_id: `pref-${slug}`,
+ artifact: "[[notes/work]]",
+ agent: "claude",
+ result: "applied",
+ note: "[[pref-unknown-private]]",
+ });
+}
+
+/** The fields of `pref-<slug>` as a machine that holds only `shared` folds them. */
+function sharedView(e: StoreEnv, slug: string): Record<string, unknown> {
+ const records = readPartition(join(e.storeRoot, "shared")).flatMap((shard) => shard.records);
+ return { ...foldPreferences(records).preferences.get(`pref-${slug}`)?.fields };
+}
+
+describe("private evidence in a dream pass on a switched machine", () => {
+ test("does not confirm a shared preference or move its confidence", () => {
+ env = makeStoreEnv("osb-dream-private-ev-", { dualWrite: false });
+ switchDevice(env.storeRoot);
+ writePreference(env.vault, prefInput("tabs"), { authority: "agent" });
+ // A twin with no evidence at all: what the shared fields must read like.
+ writePreference(env.vault, prefInput("twin"), { authority: "agent" });
+ privateEvidence(env, "tabs");
+ privateEvidence(env, "tabs");
+
+ const summary = dream(env.vault, { now: NOW });
+ expect(summary.confirmed).not.toContain("pref-tabs");
+ const judged = (slug: string) => {
+ const fields = sharedView(env!, slug);
+ return {
+ status: fields["status"],
+ confirmed_at: fields["confirmed_at"] ?? null,
+ confidence: fields["confidence"],
+ confidence_value: fields["confidence_value"] ?? null,
+ last_evidence_at: fields["last_evidence_at"] ?? null,
+ };
+ };
+ expect(judged("tabs")).toEqual(judged("twin"));
+ expect(judged("tabs").status).toBe("unconfirmed");
+ });
+
+ test("a shared event next to it still counts", () => {
+ env = makeStoreEnv("osb-dream-private-ev-shared-", { dualWrite: false });
+ switchDevice(env.storeRoot);
+ writePreference(env.vault, prefInput("tabs"), { authority: "agent" });
+ privateEvidence(env, "tabs");
+ appendApplyEvidence(env.vault, {
+ pref_id: "pref-tabs",
+ artifact: "[[notes/open]]",
+ agent: "claude",
+ result: "applied",
+ });
+ dream(env.vault, { now: NOW });
+ expect(sharedView(env, "tabs")["status"]).toBe("confirmed");
+ });
+
+ test("settles: the pass after the one that read the evidence changes nothing", () => {
+ env = makeStoreEnv("osb-dream-private-ev-settle-", { dualWrite: false });
+ switchDevice(env.storeRoot);
+ writePreference(env.vault, prefInput("tabs"), { authority: "agent" });
+ appendApplyEvidence(env.vault, {
+ pref_id: "pref-tabs",
+ artifact: "[[notes/open]]",
+ agent: "claude",
+ result: "applied",
+ });
+ privateEvidence(env, "tabs");
+ dream(env.vault, { now: NOW });
+ const shared = () => readPartition(join(env!.storeRoot, "shared")).flatMap((s) => s.records);
+ const before = shared().length;
+ const again = dream(env.vault, { now: new Date(NOW.getTime() + 60_000) });
+ expect(again.changed).toBe(false);
+ expect(shared()).toHaveLength(before);
+ });
+
+ test("confirms a preference that is itself private", () => {
+ env = makeStoreEnv("osb-dream-private-ev-own-", { dualWrite: false });
+ switchDevice(env.storeRoot);
+ withOperationPrivacy(true, () =>
+ writePreference(env!.vault, prefInput("hush"), { authority: "agent" }),
+ );
+ privateEvidence(env, "hush");
+ const summary = dream(env.vault, { now: NOW });
+ expect(summary.confirmed).toContain("pref-hush");
+ });
+});
+
+describe("a merge on a switched machine", () => {
+ test("keeps a private use of the drop out of shared, in the copies and in the sums", () => {
+ env = makeStoreEnv("osb-merge-private-ev-", { dualWrite: false });
+ switchDevice(env.storeRoot);
+ writePreference(
+ env.vault,
+ { ...prefInput("keep"), topic: "shared-topic", status: "confirmed" },
+ { authority: "agent" },
+ );
+ writePreference(
+ env.vault,
+ { ...prefInput("drop"), topic: "shared-topic", status: "confirmed" },
+ { authority: "agent" },
+ );
+ appendApplyEvidence(env.vault, {
+ pref_id: "pref-drop",
+ artifact: "[[notes/open]]",
+ agent: "claude",
+ result: "applied",
+ });
+ privateEvidence(env, "drop");
+ mergePreferences(env.vault, "pref-keep", "pref-drop", { bypassEntityGuard: true });
+ const shared = readPartition(join(env.storeRoot, "shared")).flatMap((s) => s.records);
+ expect(JSON.stringify(shared)).not.toContain("notes/work");
+ const merge = shared.find(
+ (r) => r.kind === "log-event" && (r.body["event_type"] as string) === "merge",
+ );
+ expect(JSON.stringify(merge?.body)).toContain("1 (was 0, 1)");
+ // The shared use still counts for the keep on a machine that holds only shared.
+ const keepEvidence = shared.filter(
+ (r) => r.kind === "preference-evidence" && r.body["preference"] === "pref-keep",
+ );
+ expect(keepEvidence.map((r) => r.body["artifact"])).toEqual(["[[notes/open]]"]);
+ });
+});
+
+describe("a merge retried after its copies partly landed", () => {
+ test("counts a copied use once", () => {
+ env = makeStoreEnv("osb-merge-retry-", { dualWrite: false });
+ switchDevice(env.storeRoot);
+ for (const slug of ["keep", "drop"]) {
+ writePreference(
+ env.vault,
+ { ...prefInput(slug), topic: "shared-topic", status: "confirmed" },
+ { authority: "agent" },
+ );
+ }
+ appendApplyEvidence(env.vault, {
+ pref_id: "pref-drop",
+ artifact: "[[notes/open]]",
+ agent: "claude",
+ result: "applied",
+ });
+ const shared = () => readPartition(join(env!.storeRoot, "shared")).flatMap((s) => s.records);
+ const source = shared().find(
+ (r) => r.kind === "preference-evidence" && r.body["preference"] === "pref-drop",
+ )!;
+ // The copy an earlier run wrote before it stopped.
+ appendRecord(openStore({ root: env.storeRoot, device: "dev-a" }), {
+ partition: "shared",
+ stream: "events",
+ kind: "preference-evidence",
+ agent: "merge",
+ body: {
+ preference: "pref-keep",
+ result: "applied",
+ artifact: "[[notes/open]]",
+ merged_from: source.id,
+ },
+ });
+ const plan = mergePreferences(env.vault, "pref-keep", "pref-drop", { bypassEntityGuard: true });
+ expect(plan.applied_sum).toBe(1);
+ const merge = shared().find(
+ (r) => r.kind === "log-event" && (r.body["event_type"] as string) === "merge",
+ );
+ expect(JSON.stringify(merge?.body)).toContain("1 (was 1, 0)");
+ });
+});
+
+describe("a merge into a private keep", () => {
+ test("counts the shared drop's private use, which the keep now holds", () => {
+ env = makeStoreEnv("osb-merge-private-keep-", { dualWrite: false });
+ switchDevice(env.storeRoot);
+ withOperationPrivacy(true, () =>
+ writePreference(
+ env!.vault,
+ { ...prefInput("keep"), topic: "shared-topic", status: "confirmed" },
+ { authority: "agent" },
+ ),
+ );
+ writePreference(
+ env.vault,
+ { ...prefInput("drop"), topic: "shared-topic", status: "confirmed" },
+ { authority: "agent" },
+ );
+ appendApplyEvidence(env.vault, {
+ pref_id: "pref-drop",
+ artifact: "[[notes/open]]",
+ agent: "claude",
+ result: "applied",
+ });
+ privateEvidence(env, "drop");
+ const plan = mergePreferences(env.vault, "pref-keep", "pref-drop", { bypassEntityGuard: true });
+ expect(plan.applied_sum).toBe(2);
+ });
+});
diff --git a/tests/core/brain/procedural-paths.test.ts b/tests/core/brain/procedural-paths.test.ts
index 687b9d30..1caf0eb1 100644
--- a/tests/core/brain/procedural-paths.test.ts
+++ b/tests/core/brain/procedural-paths.test.ts
@@ -6,7 +6,6 @@ import { join } from "node:path";
import {
procedurePath,
proceduralMemoryIndexPath,
- proceduralMemoryUsagePath,
proceduralRecurrencePath,
skillProposalAcceptedPath,
skillProposalPendingPath,
@@ -35,7 +34,6 @@ describe("procedural learning paths", () => {
const rejected = skillProposalRejectedPath(vault, "release-notes");
const procedure = procedurePath(vault, "release-notes");
const index = proceduralMemoryIndexPath(vault);
- const usage = proceduralMemoryUsagePath(vault);
const recurrence = proceduralRecurrencePath(vault);
expect(pending).toBe(
@@ -49,7 +47,6 @@ describe("procedural learning paths", () => {
);
expect(procedure).toBe(join(vault, "Brain", "procedures", "proc-release-notes.md"));
expect(index).toBe(join(vault, "Brain", "procedural-memory", "index.json"));
- expect(usage).toBe(join(vault, "Brain", "procedural-memory", "usage.jsonl"));
expect(recurrence).toBe(join(vault, "Brain", "log", "recurrence-support.jsonl"));
});
diff --git a/tests/core/brain/schema-store-only.test.ts b/tests/core/brain/schema-store-only.test.ts
index 80d55235..c6f88bc3 100644
--- a/tests/core/brain/schema-store-only.test.ts
+++ b/tests/core/brain/schema-store-only.test.ts
@@ -6,7 +6,8 @@
* unswitched machine keeps writing `_brain.yaml`.
*/
import { afterEach, describe, expect, setDefaultTimeout, test } from "bun:test";
-import { readFileSync } from "node:fs";
+import { cpSync, readFileSync, rmSync } from "node:fs";
+import { join } from "node:path";
import { brainConfigPath } from "../../../src/core/brain/paths.ts";
import { applySchemaAdminMutations } from "../../../src/core/brain/schema-admin.ts";
@@ -73,7 +74,8 @@ describe("schema apply on a store-only machine", () => {
]);
// Not from the CLI: an agent wrote these.
expect(records.every((r) => r.body["authority"] === "agent")).toBe(true);
- expect(schemaAuditRows(env)).toHaveLength(1);
+ // The attestation in `shared`, the whole row in `private`.
+ expect(schemaAuditRows(env)).toHaveLength(2);
const source = readSchemaPackSource(env.vault);
expect(source.path).toBe(STORE_SCHEMA_PACK_SOURCE);
@@ -143,6 +145,77 @@ describe("schema apply on a store-only machine", () => {
});
});
+/** A second store-only machine of the same store that holds only `shared`, synced from `from`. */
+function sharedOnlyPeer(from: StoreEnv): StoreEnv {
+ const peer = makeStoreEnv("osb-schema-peer-", { partitions: ["shared"], device: "dev-b" });
+ rmSync(join(peer.storeRoot, "shared"), { recursive: true, force: true });
+ cpSync(join(from.storeRoot, "shared"), join(peer.storeRoot, "shared"), { recursive: true });
+ switchDevice(peer.storeRoot, "dev-b");
+ return peer;
+}
+
+describe("a schema apply seen from a machine that holds only shared", () => {
+ let other: StoreEnv | null = null;
+ afterEach(() => {
+ other?.cleanup();
+ other = null;
+ });
+
+ test("is attested, not modified: the audit row lives with the pack it attests", async () => {
+ env = makeStoreEnv("osb-schema-attest-");
+ switchDevice(env.storeRoot);
+ await applySchemaAdminMutations(env.vault, [ADD_PAPER, ALIAS], {
+ actor: "t",
+ reason: "operator note about the paper type",
+ });
+ // The reason stays where audit rows always went, off the shared row.
+ expect(JSON.stringify(ledgerRows(env.storeRoot, "shared", "reliability-audit"))).not.toContain(
+ "operator note",
+ );
+ expect(JSON.stringify(ledgerRows(env.storeRoot, "private", "reliability-audit"))).toContain(
+ "operator note",
+ );
+ other = sharedOnlyPeer(env);
+ const integrity = assessSchemaPackIntegrity(other.vault);
+ expect(integrity.status).toBe("ok");
+ expect(integrity.mismatches).toEqual([]);
+ expect(loadSchemaPack(other.vault).declarations.page_types).toEqual(["paper"]);
+ });
+
+ test("a reason that names a private page stays off the shared row", async () => {
+ env = makeStoreEnv("osb-schema-attest-private-");
+ switchDevice(env.storeRoot);
+ await applySchemaAdminMutations(env.vault, [ADD_PAPER], {
+ actor: "t",
+ // A preference the store cannot resolve is judged private (fail closed).
+ reason: "[[pref-hidden]]",
+ });
+ const shared = JSON.stringify(ledgerRows(env.storeRoot, "shared", "reliability-audit"));
+ expect(shared).toContain("pack_digest");
+ expect(shared).not.toContain("pref-hidden");
+ // The machine that holds private keeps the batch and the reason on its own row.
+ expect(JSON.stringify(ledgerRows(env.storeRoot, "private", "reliability-audit"))).toContain(
+ "pref-hidden",
+ );
+ other = sharedOnlyPeer(env);
+ expect(assessSchemaPackIntegrity(other.vault).status).toBe("ok");
+ });
+
+ test("a reason with a private region still attests the apply", async () => {
+ env = makeStoreEnv("osb-schema-attest-region-");
+ switchDevice(env.storeRoot);
+ await applySchemaAdminMutations(env.vault, [ADD_PAPER], {
+ actor: "t",
+ reason: "for <private>the board</private>",
+ });
+ const shared = JSON.stringify(ledgerRows(env.storeRoot, "shared", "reliability-audit"));
+ expect(shared).toContain("pack_digest");
+ expect(shared).not.toContain("the board");
+ other = sharedOnlyPeer(env);
+ expect(assessSchemaPackIntegrity(other.vault).status).toBe("ok");
+ });
+});
+
describe("schema apply on an unswitched machine", () => {
test("writes _brain.yaml and no schema settings record", async () => {
env = makeStoreEnv("osb-schema-legacy-");
diff --git a/tests/core/lanes/fixtures/usage-worker.ts b/tests/core/lanes/fixtures/usage-worker.ts
new file mode 100644
index 00000000..3451568c
--- /dev/null
+++ b/tests/core/lanes/fixtures/usage-worker.ts
@@ -0,0 +1,40 @@
+/**
+ * Child process for the two-process procedural usage test, on the machine
+ * the parent's environment names. `tick`: marks the procedure used once
+ * per round. `reconcile`: reconciles the procedures folder once per round.
+ *
+ * Each worker writes `<ready dir>/<role>` once it is up and then waits for
+ * the go file, so the two run at the same time. A go file that never comes
+ * ends the worker after 30 s.
+ *
+ * argv: <vault> <role> <rounds> <entry id> <ready dir> <go file>
+ */
+import { existsSync, writeFileSync } from "node:fs";
+import { join } from "node:path";
+
+import {
+ markProceduralMemoryUsed,
+ reconcileProceduralMemory,
+} from "../../../../src/core/brain/procedural-memory.ts";
+
+const [vault, role, roundsText, id, readyDir, goFile] = process.argv.slice(2) as [
+ string,
+ "tick" | "reconcile",
+ string,
+ string,
+ string,
+ string,
+];
+writeFileSync(join(readyDir, role), "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(roundsText); i++) {
+ if (role === "tick") markProceduralMemoryUsed(vault, id);
+ else reconcileProceduralMemory(vault, { roots: [join(vault, "Brain", "procedures")] });
+}
diff --git a/tests/core/lanes/lane-pages.test.ts b/tests/core/lanes/lane-pages.test.ts
index 055ed504..44616db8 100644
--- a/tests/core/lanes/lane-pages.test.ts
+++ b/tests/core/lanes/lane-pages.test.ts
@@ -340,6 +340,27 @@ describe.each(LANE_MODES.filter((m) => m !== "legacy"))("lane pages in the store
expect(lane.vaultHash()).toBe(before);
expect(lane.laneRecords().filter((r) => r.kind === "lane-entry")).toHaveLength(1);
});
+
+ test("a page and a JSON file of one name stay two entries", () => {
+ lane = makeLaneEnv(mode);
+ const json = join(lane.vault, "Brain", "entities", "x.json");
+ const page = join(lane.vault, "Brain", "entities", "x.json.md");
+ writeLaneText(lane.vault, json, '{"a":1}\n');
+ writeLanePage(lane.vault, page, { kind: "note" }, "Page.\n");
+ expect(readLaneText(lane.vault, json)).toBe('{"a":1}\n');
+ expect(readLanePage(lane.vault, page)?.body).toBe("Page.\n");
+ });
+
+ test("a name that does not map to an entry and back is refused, nothing written", () => {
+ lane = makeLaneEnv(mode);
+ const before = lane.laneRecords().length;
+ for (const rel of ["entities/x.png", "exact-state/x.md"]) {
+ expect(() => writeLaneText(lane!.vault, join(lane!.vault, "Brain", rel), "x\n")).toThrow(
+ "does not map to a lane entry and back",
+ );
+ }
+ expect(lane.laneRecords()).toHaveLength(before);
+ });
});
describe("a removed entry's tombstone", () => {
diff --git a/tests/core/lanes/skill-lanes.test.ts b/tests/core/lanes/skill-lanes.test.ts
index ae677286..7b5b6297 100644
--- a/tests/core/lanes/skill-lanes.test.ts
+++ b/tests/core/lanes/skill-lanes.test.ts
@@ -5,7 +5,7 @@
* records and leave the vault unchanged.
*/
import { afterEach, describe, expect, test } from "bun:test";
-import { existsSync } from "node:fs";
+import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import { appendContinuityRecord } from "../../../src/core/brain/continuity/store.ts";
@@ -25,11 +25,21 @@ import {
import { acquireLockSync } from "../../../src/core/brain/sync-lockfile.ts";
import {
listProceduralMemory,
+ markProceduralMemoryUsed,
+ proceduralEntryId,
reconcileProceduralMemory,
+ recordProceduralOutcome,
} from "../../../src/core/brain/procedural-memory.ts";
import { readProceduralGraph } from "../../../src/core/brain/procedural-graph.ts";
+import { readProceduralHints } from "../../../src/core/brain/procedural-hints.ts";
+import { proceduralGraphPath, proceduralMemoryUsagePath } from "../../../src/core/brain/paths.ts";
import { procedurePath } from "../../../src/core/brain/paths.ts";
-import { laneVaultRoot, lanePageExists } from "../../../src/core/store/lane-pages.ts";
+import {
+ laneVaultRoot,
+ lanePageExists,
+ writeLanePage,
+ writeLaneText,
+} from "../../../src/core/store/lane-pages.ts";
import { LANE_MODES, makeLaneEnv, type LaneEnv } from "./fixtures/lane-env.ts";
let lane: LaneEnv | null = null;
@@ -72,6 +82,106 @@ describe.each(LANE_MODES)("skill and procedure lanes (%s)", (mode) => {
});
});
+describe.each(LANE_MODES.filter((m) => m !== "legacy"))(
+ "procedural usage counters (%s)",
+ (mode) => {
+ test("a usage tick appends no store record, and the counters read back", () => {
+ lane = makeLaneEnv(mode);
+ const { vault } = lane;
+ const procedures = join(vault, "Brain", "procedures");
+ writeLanePage(
+ vault,
+ join(procedures, "proc-deploy.md"),
+ { kind: "brain-procedure", triggers: ["deploy"] },
+ "# Deploy\n",
+ );
+ reconcileProceduralMemory(vault, { roots: [procedures] });
+ const [entry] = listProceduralMemory(vault);
+ const before = lane.laneRecords().length;
+
+ markProceduralMemoryUsed(vault, entry!.id, new Date("2026-11-15T10:00:00Z"));
+ markProceduralMemoryUsed(vault, entry!.id, new Date("2026-11-15T11:00:00Z"));
+ recordProceduralOutcome(vault, entry!.id, "success");
+ expect(lane.laneRecords()).toHaveLength(before);
+
+ const counted = {
+ usedCount: 2,
+ lastUsedAt: "2026-11-15T11:00:00.000Z",
+ successCount: 1,
+ failureCount: 0,
+ };
+ expect(listProceduralMemory(vault)[0]).toMatchObject(counted);
+ // A reconcile with no source change keeps the counters and appends nothing either.
+ reconcileProceduralMemory(vault, { roots: [procedures] });
+ expect(lane.laneRecords()).toHaveLength(before);
+ expect(listProceduralMemory(vault)[0]).toMatchObject(counted);
+ });
+ },
+);
+
+describe.each(LANE_MODES.filter((m) => m !== "legacy"))(
+ "procedural files a machine switched before they became machine state (%s)",
+ (mode) => {
+ test("are read from their store records before the next reconcile, and adopted", () => {
+ lane = makeLaneEnv(mode);
+ const { vault } = lane;
+ const pmem = join(vault, "Brain", "procedural-memory");
+ // What a migration of an earlier release imported: the files as lane entries.
+ const index = {
+ schema_version: 1,
+ entries: [
+ {
+ id: "pmem-1",
+ kind: "procedure",
+ sourcePath: "Brain/procedures/deploy.md",
+ title: "Deploy",
+ triggers: [],
+ tags: [],
+ permissions: [],
+ source: null,
+ version: null,
+ lastUsedAt: null,
+ usedCount: 0,
+ successCount: 0,
+ failureCount: 0,
+ },
+ ],
+ };
+ const graph = {
+ schema_version: 1 as const,
+ generated_at: "2026-11-01T00:00:00.000Z",
+ nodes: [],
+ edges: [],
+ };
+ const hints = {
+ schema_version: 1 as const,
+ generated_at: "2026-11-01T00:00:00.000Z",
+ entries: [],
+ };
+ writeLaneText(vault, join(pmem, "index.json"), `${JSON.stringify(index)}\n`);
+ writeLaneText(
+ vault,
+ join(pmem, "usage.jsonl"),
+ `${JSON.stringify({ id: "pmem-1", usedCount: 7, lastUsedAt: "2026-11-02T00:00:00.000Z" })}\n`,
+ );
+ writeLaneText(vault, join(pmem, "graph.json"), `${JSON.stringify(graph)}\n`);
+ writeLaneText(vault, join(pmem, "hints.json"), `${JSON.stringify(hints)}\n`);
+ const records = lane.laneRecords().length;
+
+ expect(readProceduralGraph(vault)).toEqual(graph);
+ expect(readProceduralHints(vault)).toEqual(hints);
+ expect(listProceduralMemory(vault)[0]).toMatchObject({ id: "pmem-1", usedCount: 7 });
+ // Adopted into this machine's state on the first read, writing no record.
+ expect(readFileSync(proceduralMemoryUsagePath(vault), "utf8")).toContain('"usedCount":7');
+ expect(existsSync(proceduralGraphPath(vault))).toBe(true);
+ expect(lane.laneRecords()).toHaveLength(records);
+ // A tick counts on from the adopted counters.
+ markProceduralMemoryUsed(vault, "pmem-1", new Date("2026-11-15T10:00:00Z"));
+ expect(listProceduralMemory(vault)[0]?.usedCount).toBe(8);
+ });
+ },
+);
+
describe.each(LANE_MODES)("the skill accept journal (%s)", (mode) => {
test("a journal left by an interrupted accept is read back and resolved", () => {
lane = makeLaneEnv(mode);
@@ -222,3 +332,85 @@ function seedCorePatterns(vaultPath: string): void {
});
}
}
+
+describe("procedural usage counted by two processes", () => {
+ test("a reconcile never drops a tick another process counted", async () => {
+ lane = makeLaneEnv("store");
+ const { vault } = lane;
+ const procedures = join(vault, "Brain", "procedures");
+ writeLanePage(
+ vault,
+ join(procedures, "proc-deploy.md"),
+ { kind: "brain-procedure" },
+ "# Deploy\n",
+ );
+ reconcileProceduralMemory(vault, { roots: [procedures] });
+ const [entry] = listProceduralMemory(vault);
+ const TICKS = 60;
+ const readyDir = join(lane.env.parent, "ready");
+ const goFile = join(lane.env.parent, "go");
+ mkdirSync(readyDir, { recursive: true });
+ const worker = join(import.meta.dir, "fixtures", "usage-worker.ts");
+ const children = (
+ [
+ ["tick", TICKS],
+ ["reconcile", 20],
+ ] as const
+ ).map(([role, rounds]) =>
+ Bun.spawn(
+ [process.execPath, worker, vault, role, String(rounds), entry!.id, readyDir, goFile],
+ { stdout: "ignore", stderr: "pipe", env: { ...process.env } },
+ ),
+ );
+ const readyBy = Date.now() + 30_000;
+ while (readdirSync(readyDir).length < 2 && Date.now() < readyBy) await Bun.sleep(5);
+ writeFileSync(goFile, "go\n");
+ 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([0, 0]);
+ expect(listProceduralMemory(vault)[0]?.usedCount).toBe(TICKS);
+ }, 60_000);
+});
+
+describe("a reconcile that fails after the index", () => {
+ test("has already moved the counters an older index carried into the usage file", () => {
+ lane = makeLaneEnv("store");
+ const { vault } = lane;
+ const procedures = join(vault, "Brain", "procedures");
+ writeLanePage(
+ vault,
+ join(procedures, "proc-deploy.md"),
+ { kind: "brain-procedure" },
+ "# Deploy\n",
+ );
+ const id = proceduralEntryId("Brain/procedures/proc-deploy.md");
+ // An index of an earlier release, its counters on the entry itself.
+ const entry = {
+ id,
+ kind: "procedure",
+ sourcePath: "Brain/procedures/proc-deploy.md",
+ title: "Deploy",
+ triggers: [],
+ tags: [],
+ permissions: [],
+ source: null,
+ version: null,
+ lastUsedAt: "2026-11-01T00:00:00.000Z",
+ usedCount: 5,
+ successCount: 0,
+ failureCount: 0,
+ };
+ writeLaneText(
+ vault,
+ join(vault, "Brain", "procedural-memory", "index.json"),
+ `${JSON.stringify({ schema_version: 1, entries: [entry] })}\n`,
+ );
+ // The graph cannot be written: the rebuild after the index fails.
+ mkdirSync(proceduralGraphPath(vault), { recursive: true });
+ expect(() => reconcileProceduralMemory(vault, { roots: [procedures] })).toThrow();
+ expect(listProceduralMemory(vault)[0]).toMatchObject({ id, usedCount: 5 });
+ });
+});
diff --git a/tests/core/state/surfaces.test.ts b/tests/core/state/surfaces.test.ts
index bce59c2f..9a763fe0 100644
--- a/tests/core/state/surfaces.test.ts
+++ b/tests/core/state/surfaces.test.ts
@@ -46,6 +46,9 @@ import {
dreamRunsDir,
hookAuditDir,
prefAuditDir,
+ proceduralGraphPath,
+ proceduralHintsPath,
+ proceduralMemoryUsagePath,
proceduralRecurrencePath,
proposalWatermarkPath,
queryDemandLogPath,
@@ -331,6 +334,9 @@ const RESOLVER_BINDINGS: ReadonlyArray<readonly [StateSurfaceId, (vault: string)
["capture_decision_log", (v) => captureDecisionLogPath(v)],
["capture_watermark", (v) => captureWatermarkPath(v)],
["proposal_watermark", (v) => proposalWatermarkPath(v)],
+ ["procedural_usage", (v) => proceduralMemoryUsagePath(v)],
+ ["procedural_graph", (v) => proceduralGraphPath(v)],
+ ["procedural_hints", (v) => proceduralHintsPath(v)],
["decision_receipts", (v) => receiptsDir(v)],
["lineage_ledger", (v) => sessionLineageLedgerPath(v)],
["freeze_marker", (v) => frozenMarkerPath(v)],
diff --git a/tests/core/store-migration/dry-run.test.ts b/tests/core/store-migration/dry-run.test.ts
index 3324945b..c4df8272 100644
--- a/tests/core/store-migration/dry-run.test.ts
+++ b/tests/core/store-migration/dry-run.test.ts
@@ -138,6 +138,44 @@ describe("planMigrationDryRun", () => {
expect(surface("standing_rules").items).toBe(2);
expect(surface("exact_state").items).toBe(1);
});
+
+ test("two user folders that take one lane are listed, the one spelled as the lane imported", () => {
+ fx.write("Brain/my-notes/a.md", "---\nkind: note\n---\nA.\n");
+ fx.write("Brain/My Notes/b.md", "---\nkind: note\n---\nB.\n");
+ fx.write("Brain/Lone Folder/c.md", "---\nkind: note\n---\nC.\n");
+ const result = planMigrationDryRun(fx.vault);
+ expect(result.unparseable).toContainEqual(
+ expect.objectContaining({
+ path: "Brain/My Notes/b.md",
+ reason: expect.stringContaining("which my-notes also takes"),
+ }),
+ );
+ const listed = result.unparseable.map((u) => u.path);
+ expect(listed).not.toContain("Brain/my-notes/a.md");
+ expect(listed).not.toContain("Brain/Lone Folder/c.md");
+ expect(result.surfaces.find((s) => s.id === "record_lanes")?.items).toBe(4);
+ });
+
+ test("a respelled folder beside a dot-folder of the same name has no rival", () => {
+ fx.write("Brain/.archives/src.txt", "redacted source\n");
+ fx.write("Brain/Archives/a.md", "---\nkind: note\n---\nA.\n");
+ const listed = planMigrationDryRun(fx.vault).unparseable.map((u) => u.path);
+ expect(listed).not.toContain("Brain/Archives/a.md");
+ });
+
+ test("a lane page whose name does not map to an entry and back is listed, not filed", () => {
+ // `exact-state` is the lane of `state/`, so its entry would name another path.
+ fx.write("Brain/exact-state/x.md", "---\nkind: note\n---\nBody.\n");
+ const result = planMigrationDryRun(fx.vault);
+ expect(result.unparseable).toContainEqual(
+ expect.objectContaining({
+ surface: "record_lanes",
+ path: "Brain/exact-state/x.md",
+ reason: expect.stringContaining("does not map to a lane entry and back"),
+ }),
+ );
+ expect(result.surfaces.find((s) => s.id === "record_lanes")?.items).toBe(2);
+ });
});
describe("the dry run writes nothing", () => {
diff --git a/tests/core/store-migration/lane-id-repair.test.ts b/tests/core/store-migration/lane-id-repair.test.ts
new file mode 100644
index 00000000..7b653f3e
--- /dev/null
+++ b/tests/core/store-migration/lane-id-repair.test.ts
@@ -0,0 +1,414 @@
+/**
+ * The repair of lane entry ids an earlier release gave a page named
+ * `x.json.md` (task 3.9, design D15 item 1): its imported record sat under
+ * `x.json`, the id of the file beside it. The repair moves it to the id its
+ * legacy path maps to and gives the old key back the file's own record.
+ */
+import { afterEach, describe, expect, test } from "bun:test";
+import { mkdirSync, renameSync } from "node:fs";
+import { join } from "node:path";
+
+import { runDoctor } from "../../../src/core/brain/doctor.ts";
+import { TRANSPORT_REACH } from "../../../src/core/graph/transport-reach.ts";
+import {
+ LANE_FOLDER_UNIMPORTABLE_CODE,
+ LANE_ID_MISFILED_CODE,
+} from "../../../src/core/brain/doctor/lane-id-check.ts";
+import { readStreamRecords } from "../../../src/core/store/read/stream-read.ts";
+
+import { dream } from "../../../src/core/brain/dream.ts";
+import { appendRecord } from "../../../src/core/store/appender.ts";
+import { readLanePage, readLaneText, removeLanePage } from "../../../src/core/store/lane-pages.ts";
+import { foldLaneEntries } from "../../../src/core/store/lane-records.ts";
+import { readPartition } from "../../../src/core/store/state-digest.ts";
+import { openStore } from "../../../src/core/store/store-open.ts";
+import {
+ planLaneIdRepairs,
+ repairLaneEntryIds,
+} from "../../../src/core/store-migration/lane-id-repair.ts";
+import { makeLaneEnv, type LaneEnv } from "../lanes/fixtures/lane-env.ts";
+
+let lane: LaneEnv | null = null;
+afterEach(() => {
+ lane?.cleanup();
+ lane = null;
+});
+
+/** A lane-entry record as an earlier migration imported it from `key`. */
+function imported(
+ e: LaneEnv,
+ entry: string,
+ key: string,
+ fields: Record<string, unknown>,
+ text: string,
+ authority: "agent" | "human" = "agent",
+ device = "dev-a",
+ partition: "shared" | "private" = "shared",
+): string {
+ return appendRecord(openStore({ root: e.env.storeRoot, device }), {
+ partition,
+ stream: "events",
+ kind: "lane-entry",
+ agent: "o2b",
+ body: {
+ authority,
+ lane: "entities",
+ entry,
+ fields,
+ text,
+ migrated: { key, sum: `sum-of-${key}` },
+ },
+ }).path;
+}
+
+describe("a page filed under the id of the file beside it", () => {
+ test("moves to its own id, and the old id gets the file back", () => {
+ lane = makeLaneEnv("store");
+ const { vault } = lane;
+ imported(lane, "x.json", "Brain/entities/x.json", { a: 1 }, "");
+ imported(lane, "x.json", "Brain/entities/x.json.md", { kind: "note" }, "The page.\n");
+ const json = join(vault, "Brain", "entities", "x.json");
+ const page = join(vault, "Brain", "entities", "x.json.md");
+ // Before: the page reads by no path, and the file reads the page.
+ expect(readLanePage(vault, page)).toBeNull();
+
+ expect(repairLaneEntryIds(vault)).toEqual([
+ { from: "entities/x.json", to: "entities/x.json.md", left: "restored" },
+ ]);
+ expect(readLanePage(vault, page)?.body).toBe("The page.\n");
+ expect(JSON.parse(readLaneText(vault, json) ?? "null")).toEqual({ a: 1 });
+ // The record under the new id still names the legacy path it came from.
+ const moved = lane
+ .laneRecords()
+ .filter((r) => r.kind === "lane-entry" && r.body["entry"] === "x.json.md");
+ expect(moved.map((r) => (r.body["migrated"] as { key: string }).key)).toEqual([
+ "Brain/entities/x.json.md",
+ ]);
+ // Repaired once: a second run finds nothing.
+ const records = lane.laneRecords().length;
+ expect(repairLaneEntryIds(vault)).toEqual([]);
+ expect(lane.laneRecords()).toHaveLength(records);
+ });
+
+ test("with no file beside it the old id is removed, by the dream pass", () => {
+ lane = makeLaneEnv("store");
+ const { vault } = lane;
+ imported(lane, "y.yaml", "Brain/entities/y.yaml.md", { kind: "note" }, "Only a page.\n");
+ dream(vault, { now: new Date("2026-11-15T12:00:00Z") });
+ expect(readLanePage(vault, join(vault, "Brain", "entities", "y.yaml.md"))?.body).toBe(
+ "Only a page.\n",
+ );
+ expect(readLaneText(vault, join(vault, "Brain", "entities", "y.yaml"))).toBeNull();
+ });
+});
+
+/** What the repair would write for the store as this machine holds it now. */
+function planned(e: LaneEnv) {
+ const all = (["shared", "private"] as const).flatMap((partition) =>
+ readPartition(join(e.env.storeRoot, partition))
+ .flatMap((shard) => shard.records)
+ .map((record) => ({ record, partition })),
+ );
+ return planLaneIdRepairs(all);
+}
+
+describe("the repair stays repaired", () => {
+ test("a page removed after its repair is never written back", () => {
+ lane = makeLaneEnv("store");
+ const { vault } = lane;
+ imported(lane, "x.json", "Brain/entities/x.json.md", { kind: "note" }, "The page.\n");
+ repairLaneEntryIds(vault);
+ const page = join(vault, "Brain", "entities", "x.json.md");
+ expect(removeLanePage(vault, page)).toBe(true);
+ expect(planned(lane).records).toEqual([]);
+ expect(readLanePage(vault, page)).toBeNull();
+ });
+
+ test("a page imported with human authority gives its id back to the file", () => {
+ lane = makeLaneEnv("store");
+ const { vault } = lane;
+ imported(lane, "x.json", "Brain/entities/x.json", { a: 1 }, "");
+ imported(lane, "x.json", "Brain/entities/x.json.md", { kind: "note" }, "Mine.\n", "human");
+ repairLaneEntryIds(vault);
+ expect(
+ JSON.parse(readLaneText(vault, join(vault, "Brain", "entities", "x.json")) ?? "null"),
+ ).toEqual({
+ a: 1,
+ });
+ expect(planned(lane).records).toEqual([]);
+ });
+
+ test("a machine without the private partition repairs nothing", () => {
+ lane = makeLaneEnv("store", "osb-lane-", { partitions: ["shared"] });
+ const { vault } = lane;
+ imported(lane, "x.json", "Brain/entities/x.json.md", { kind: "note" }, "The page.\n");
+ const before = lane.laneRecords().length;
+ expect(repairLaneEntryIds(vault)).toEqual([]);
+ expect(lane.laneRecords()).toHaveLength(before);
+ });
+});
+
+describe("a pass that could not read every shard", () => {
+ test("runs again, and repairs a record that arrives with the shard", () => {
+ lane = makeLaneEnv("store");
+ const { vault } = lane;
+ const shard = imported(
+ lane,
+ "x.json",
+ "Brain/entities/x.json.md",
+ { kind: "note" },
+ "Late.\n",
+ "agent",
+ "dev-b",
+ );
+ // Read once, then gone (sync is moving it): this pass cannot see it.
+ readStreamRecords(lane.env.storeRoot, "shared", { stream: "events" });
+ renameSync(shard, `${shard}.away`);
+ expect(repairLaneEntryIds(vault)).toEqual([]);
+ renameSync(`${shard}.away`, shard);
+ expect(repairLaneEntryIds(vault)).toEqual([
+ { from: "entities/x.json", to: "entities/x.json.md", left: "removed" },
+ ]);
+ });
+});
+
+function misfiled(vault: string) {
+ return runDoctor(vault).warnings.filter((w) => w.code === LANE_ID_MISFILED_CODE);
+}
+
+describe("a page mis-filed after a finished pass", () => {
+ test("is repaired by the next pass, as the doctor says", () => {
+ lane = makeLaneEnv("store");
+ const { vault } = lane;
+ imported(lane, "a.json", "Brain/entities/a.json.md", { kind: "note" }, "First.\n");
+ expect(repairLaneEntryIds(vault)).toHaveLength(1);
+ // A machine still on the earlier release imports another one later.
+ imported(
+ lane,
+ "b.json",
+ "Brain/entities/b.json.md",
+ { kind: "note" },
+ "Late.\n",
+ "agent",
+ "dev-b",
+ );
+ expect(misfiled(vault)[0]?.message).toContain("the next `o2b brain dream`");
+ expect(repairLaneEntryIds(vault)).toEqual([
+ { from: "entities/b.json", to: "entities/b.json.md", left: "removed" },
+ ]);
+ expect(misfiled(vault)).toEqual([]);
+ });
+});
+
+describe("the doctor", () => {
+ test("names a mis-filed page on a machine without private, with the remedy", () => {
+ lane = makeLaneEnv("store", "osb-lane-", { partitions: ["shared"] });
+ imported(lane, "x.json", "Brain/entities/x.json.md", { kind: "note" }, "The page.\n");
+ const [finding] = misfiled(lane.vault);
+ expect(finding?.message).toContain("entities/x.json (its own id is entities/x.json.md)");
+ expect(finding?.message).toContain("o2b store init --partitions shared,private");
+ });
+
+ test("is quiet once a machine that holds private repaired it", () => {
+ lane = makeLaneEnv("store");
+ imported(lane, "x.json", "Brain/entities/x.json.md", { kind: "note" }, "The page.\n");
+ expect(misfiled(lane.vault)[0]?.message).toContain("the next `o2b brain dream`");
+ repairLaneEntryIds(lane.vault);
+ expect(misfiled(lane.vault)).toEqual([]);
+ });
+});
+
+describe("the doctor before a migration", () => {
+ test("names legacy folders whose pages no lane takes, not a folder spelled otherwise", () => {
+ lane = makeLaneEnv("legacy");
+ for (const folder of ["My Notes", "my-notes", "brain", "Lone Folder"]) {
+ mkdirSync(join(lane.vault, "Brain", folder), { recursive: true });
+ }
+ const finding = runDoctor(lane.vault).warnings.find(
+ (w) => w.code === LANE_FOLDER_UNIMPORTABLE_CODE,
+ );
+ expect(finding?.message).toContain("My Notes (lane my-notes, also my-notes)");
+ expect(finding?.message).toContain("brain (its name is no lane of its own)");
+ expect(finding?.message).not.toContain("Lone Folder");
+ });
+});
+
+/** A removal of `<entities>/<entry>` as an earlier release or a person wrote it. */
+function removed(e: LaneEnv, entry: string, authority: "agent" | "human"): void {
+ appendRecord(openStore({ root: e.env.storeRoot, device: "dev-a" }), {
+ partition: "shared",
+ stream: "events",
+ kind: "lane-entry-remove",
+ agent: "o2b",
+ body: { authority, lane: "entities", entry },
+ });
+}
+
+describe("review cases of the repair", () => {
+ test("a file removed before the page was filed over it stays removed", () => {
+ lane = makeLaneEnv("store");
+ const { vault } = lane;
+ imported(lane, "x.json", "Brain/entities/x.json", { a: 1 }, "");
+ removed(lane, "x.json", "human");
+ imported(lane, "x.json", "Brain/entities/x.json.md", { kind: "note" }, "Page.\n", "human");
+ expect(repairLaneEntryIds(vault)).toEqual([
+ { from: "entities/x.json", to: "entities/x.json.md", left: "removed" },
+ ]);
+ expect(readLaneText(vault, join(vault, "Brain", "entities", "x.json"))).toBeNull();
+ expect(readLanePage(vault, join(vault, "Brain", "entities", "x.json.md"))?.body).toBe(
+ "Page.\n",
+ );
+ });
+
+ test("a page whose own id holds the next mis-filed page: both reach their own ids", () => {
+ lane = makeLaneEnv("store");
+ const { vault } = lane;
+ imported(lane, "x.json", "Brain/entities/x.json.md", { kind: "note" }, "One.\n");
+ imported(lane, "x.json.md", "Brain/entities/x.json.md.md", { kind: "note" }, "Two.\n");
+ repairLaneEntryIds(vault);
+ const at = (rel: string) => join(vault, "Brain", "entities", rel);
+ expect(readLanePage(vault, at("x.json.md"))?.body).toBe("One.\n");
+ expect(readLanePage(vault, at("x.json.md.md"))?.body).toBe("Two.\n");
+ expect(readLaneText(vault, at("x.json"))).toBeNull();
+ expect(planned(lane).records).toEqual([]);
+ });
+
+ test("a read that misses the file beside the page writes nothing, then restores it", () => {
+ lane = makeLaneEnv("store");
+ const { vault } = lane;
+ const shard = imported(lane, "x.json", "Brain/entities/x.json", { a: 1 }, "", "agent", "dev-b");
+ imported(lane, "x.json", "Brain/entities/x.json.md", { kind: "note" }, "Page.\n", "human");
+ readStreamRecords(lane.env.storeRoot, "shared", { stream: "events" });
+ renameSync(shard, `${shard}.away`);
+ const before = lane.laneRecords().length;
+ expect(repairLaneEntryIds(vault)).toEqual([]);
+ expect(lane.laneRecords()).toHaveLength(before);
+ renameSync(`${shard}.away`, shard);
+ repairLaneEntryIds(vault);
+ expect(
+ JSON.parse(readLaneText(vault, join(vault, "Brain", "entities", "x.json")) ?? "null"),
+ ).toEqual({
+ a: 1,
+ });
+ });
+});
+
+describe("the doctor below local reach", () => {
+ test("names no private mis-filed id, no legacy folder and no partition this machine holds", () => {
+ lane = makeLaneEnv("store");
+ imported(lane, "a.json", "Brain/entities/a.json.md", { kind: "note" }, "Shared.\n");
+ appendRecord(openStore({ root: lane.env.storeRoot, device: "dev-a" }), {
+ partition: "private",
+ stream: "events",
+ kind: "lane-entry",
+ agent: "o2b",
+ body: {
+ authority: "agent",
+ lane: "entities",
+ entry: "secret.json",
+ fields: { kind: "note" },
+ text: "Private.\n",
+ migrated: { key: "Brain/entities/secret.json.md", sum: "s" },
+ },
+ });
+ mkdirSync(join(lane.vault, "Brain", "My Notes"), { recursive: true });
+ mkdirSync(join(lane.vault, "Brain", "my-notes"), { recursive: true });
+ const result = runDoctor(lane.vault, { reach: TRANSPORT_REACH.remote });
+ const text = JSON.stringify(result);
+ expect(text).toContain("entities/a.json");
+ expect(text).not.toContain("secret");
+ // One remedy whatever this machine holds: its partitions are not named.
+ expect(text).toContain("on a machine that holds every partition");
+ expect(text).not.toContain("on this machine repairs them");
+ expect(text).not.toContain("My Notes");
+ expect((result.uncertain ?? []).map((u) => u.code)).toContain(LANE_FOLDER_UNIMPORTABLE_CODE);
+ // Locally both are named.
+ const local = JSON.stringify(runDoctor(lane.vault));
+ expect(local).toContain("entities/secret.json");
+ expect(local).toContain("My Notes");
+ });
+});
+
+describe("the repair resolves each side as the register does", () => {
+ test("the page moved is the one its records resolve to, not the latest", () => {
+ lane = makeLaneEnv("store");
+ const { vault } = lane;
+ imported(lane, "x.json", "Brain/entities/x.json.md", { kind: "note" }, "Approved.\n", "human");
+ imported(lane, "x.json", "Brain/entities/x.json.md", { kind: "note" }, "Draft.\n", "agent");
+ repairLaneEntryIds(vault);
+ expect(readLanePage(vault, join(vault, "Brain", "entities", "x.json.md"))?.body).toBe(
+ "Approved.\n",
+ );
+ });
+
+ test("the file restored is the one its records resolve to, not the latest", () => {
+ lane = makeLaneEnv("store");
+ const { vault } = lane;
+ imported(lane, "x.json", "Brain/entities/x.json", { a: "human" }, "", "human");
+ imported(lane, "x.json", "Brain/entities/x.json", { a: "agent" }, "", "agent");
+ imported(lane, "x.json", "Brain/entities/x.json.md", { kind: "note" }, "Page.\n", "human");
+ repairLaneEntryIds(vault);
+ expect(
+ JSON.parse(readLaneText(vault, join(vault, "Brain", "entities", "x.json")) ?? "null"),
+ ).toEqual({ a: "human" });
+ });
+});
+
+/** The lane entry `entities/<entry>` as a machine that holds only `shared` folds it. */
+function sharedValue(e: LaneEnv, entry: string) {
+ const records = readPartition(join(e.env.storeRoot, "shared")).flatMap((shard) => shard.records);
+ return foldLaneEntries(records).entries.get(`entities/${entry}`)?.value ?? null;
+}
+
+describe("the repair across partitions", () => {
+ test("a file restored in private over a shared page: the page leaves shared too", () => {
+ lane = makeLaneEnv("store");
+ const { vault } = lane;
+ imported(lane, "x.json", "Brain/entities/x.json", { a: 1 }, "", "agent", "dev-a", "private");
+ imported(lane, "x.json", "Brain/entities/x.json.md", { kind: "note" }, "Page.\n");
+ repairLaneEntryIds(vault);
+ expect(sharedValue(lane, "x.json")).toBeNull();
+ expect(
+ JSON.parse(readLaneText(vault, join(vault, "Brain", "entities", "x.json")) ?? "null"),
+ ).toEqual({
+ a: 1,
+ });
+ });
+
+ test("a page moved in private over a shared mis-filed page: that page leaves shared", () => {
+ lane = makeLaneEnv("store");
+ const { vault } = lane;
+ imported(
+ lane,
+ "x.json",
+ "Brain/entities/x.json.md",
+ { kind: "note" },
+ "One.\n",
+ "agent",
+ "dev-a",
+ "private",
+ );
+ imported(lane, "x.json.md", "Brain/entities/x.json.md.md", { kind: "note" }, "Two.\n");
+ repairLaneEntryIds(vault);
+ expect(sharedValue(lane, "x.json.md")).toBeNull();
+ expect(readLanePage(vault, join(vault, "Brain", "entities", "x.json.md"))?.body).toBe("One.\n");
+ expect(readLanePage(vault, join(vault, "Brain", "entities", "x.json.md.md"))?.body).toBe(
+ "Two.\n",
+ );
+ });
+});
+
+describe("the doctor for a caller who may not read a page", () => {
+ test("neither names nor counts a mis-filed page of it", () => {
+ lane = makeLaneEnv("store");
+ imported(lane, "a.json", "Brain/entities/a.json.md", { kind: "note" }, "Open.\n");
+ imported(lane, "b.json", "Brain/entities/b.json.md", { kind: "note" }, "Hidden.\n");
+ const result = runDoctor(lane.vault, {
+ readable: (rel) => !rel.startsWith("Brain/entities/b.json"),
+ });
+ const finding = result.warnings.find((w) => w.code === LANE_ID_MISFILED_CODE);
+ expect(finding?.message).toContain("entities/a.json");
+ expect(finding?.message).toStartWith("1 lane page(s)");
+ expect(finding?.message).not.toContain("entities/b.json");
+ });
+});
diff --git a/tests/core/store-migration/migrate.test.ts b/tests/core/store-migration/migrate.test.ts
index 1010636a..5f24ff1b 100644
--- a/tests/core/store-migration/migrate.test.ts
+++ b/tests/core/store-migration/migrate.test.ts
@@ -63,6 +63,11 @@ import {
type RerankProviderProfile,
} from "../../../src/core/search/rerank/registry.ts";
import { forgetMachineStateCache } from "../../../src/core/state/machine-state.ts";
+import { proceduralMemoryUsagePath } from "../../../src/core/brain/paths.ts";
+import {
+ listProceduralMemory,
+ markProceduralMemoryUsed,
+} from "../../../src/core/brain/procedural-memory.ts";
import { CHMOD_CANNOT_DENY } from "../../helpers/platform.ts";
import { digestVaultTree } from "../../helpers/vault-digest.ts";
import { CLI_SPAWN_BUDGET_MS } from "../../helpers/cli-timeout.ts";
@@ -159,6 +164,50 @@ describe("runMigration", () => {
expect(bench.records().some((r) => JSON.stringify(r.body).includes("my-embed"))).toBe(false);
});
+ test("procedural usage counters move into the device-local state, never into a record", () => {
+ // A legacy machine used the procedure; its counters sit beside the index.
+ const pmem = join(bench.vault, "Brain", "procedural-memory");
+ mkdirSync(pmem, { recursive: true });
+ const id = "pmem-000000000001";
+ const entry = {
+ id,
+ kind: "procedure",
+ sourcePath: "Brain/procedures/deploy.md",
+ title: "Deploy",
+ triggers: [],
+ tags: [],
+ permissions: [],
+ source: null,
+ version: null,
+ lastUsedAt: "2026-11-01T09:00:00.000Z",
+ usedCount: 3,
+ successCount: 2,
+ failureCount: 1,
+ };
+ writeFileSync(
+ join(pmem, "index.json"),
+ `${JSON.stringify({ schema_version: 1, entries: [entry] })}\n`,
+ );
+ writeFileSync(
+ join(pmem, "usage.jsonl"),
+ `${JSON.stringify({ id, usedCount: 3, lastUsedAt: entry.lastUsedAt, successCount: 2, failureCount: 1 })}\n`,
+ );
+ expect(runMigration(bench.vault, FAST).ok).toBe(true);
+ forgetMachineStateCache();
+ expect(proceduralMemoryUsagePath(bench.vault).startsWith(bench.vault)).toBe(false);
+ expect(readFileSync(proceduralMemoryUsagePath(bench.vault), "utf8")).toContain(id);
+ expect(listProceduralMemory(bench.vault)).toEqual([
+ expect.objectContaining({ id, usedCount: 3, successCount: 2, failureCount: 1 }),
+ ]);
+ const laneEntries = bench.records().filter((r) => r.kind === "lane-entry");
+ expect(laneEntries.some((r) => String(r.body["entry"]).startsWith("usage"))).toBe(false);
+ // A tick on the switched machine counts on, and appends no record.
+ const before = bench.records().length;
+ markProceduralMemoryUsed(bench.vault, id, new Date("2026-11-15T10:00:00Z"));
+ expect(bench.records()).toHaveLength(before);
+ expect(listProceduralMemory(bench.vault)[0]?.usedCount).toBe(4);
+ });
+
test("a clean run imports every item once, backs up, archives and records the switch", () => {
const prefsBefore = digestVaultTree(join(bench.vault, "Brain", "preferences"), { mtime: true });
const result = runMigration(bench.vault, FAST);
diff --git a/tests/core/store-migration/removal.test.ts b/tests/core/store-migration/removal.test.ts
index 1f011930..47c60a0b 100644
--- a/tests/core/store-migration/removal.test.ts
+++ b/tests/core/store-migration/removal.test.ts
@@ -8,6 +8,7 @@
import { afterEach, describe, expect, setDefaultTimeout, test } from "bun:test";
import { spawn } from "node:child_process";
import {
+ chmodSync,
existsSync,
mkdirSync,
mkdtempSync,
@@ -19,9 +20,10 @@ import {
writeFileSync,
} from "node:fs";
import { tmpdir } from "node:os";
-import { join } from "node:path";
+import { dirname, join } from "node:path";
import { writeVaultIdentity } from "../../../src/core/brain/vault-identity.ts";
+import { proceduralMemoryUsagePath } from "../../../src/core/brain/paths.ts";
import { runDoctor } from "../../../src/core/brain/doctor.ts";
import {
LEGACY_DEVICES_PENDING_CODE,
@@ -53,6 +55,7 @@ import { RollbackRefusedError } from "../../../src/core/store-migration/rollback
import { makeFleet, type Fleet, type Machine } from "./fixtures/fleet.ts";
import { moveNeverHeld } from "../../helpers/held-partitions.ts";
import { CLI_SPAWN_BUDGET_MS } from "../../helpers/cli-timeout.ts";
+import { CHMOD_CANNOT_DENY } from "../../helpers/platform.ts";
// Tests here spawn processes; see tests/helpers/cli-timeout.ts.
setDefaultTimeout(CLI_SPAWN_BUDGET_MS);
@@ -631,6 +634,68 @@ function switchedAlone(): Machine {
return a;
}
+describe("the store records of files that became machine state", () => {
+ test("are adopted, then retired by the removal, when no rollback can run any more", () => {
+ const a = switchedAlone();
+ // What the migration of an earlier release imported: the procedural
+ // usage counters as a lane entry.
+ const usage = `${JSON.stringify({ id: "pmem-1", usedCount: 3, lastUsedAt: null })}\n`;
+ appendRecord(a.store(), {
+ partition: "shared",
+ stream: "events",
+ kind: "lane-entry",
+ agent: "o2b",
+ body: {
+ authority: "agent",
+ lane: "procedural-memory",
+ entry: "usage.jsonl",
+ fields: {},
+ text: usage,
+ },
+ });
+ const removed = removeLegacy(a.vault, { force: true });
+ if (!removed.removed) throw new Error("not removed");
+ const tombstones = a
+ .records()
+ .filter((r) => r.kind === "lane-entry-remove" && r.body["lane"] === "procedural-memory");
+ expect(tombstones.map((r) => r.body["entry"])).toEqual(["usage.jsonl"]);
+ expect(readFileSync(proceduralMemoryUsagePath(a.vault), "utf8")).toBe(usage);
+ });
+});
+
+describe("a store record this machine could not adopt", () => {
+ test.skipIf(CHMOD_CANNOT_DENY)("stays live through the removal, the one copy there is", () => {
+ const a = switchedAlone();
+ appendRecord(a.store(), {
+ partition: "shared",
+ stream: "events",
+ kind: "lane-entry",
+ agent: "o2b",
+ body: {
+ authority: "agent",
+ lane: "procedural-memory",
+ entry: "usage.jsonl",
+ fields: {},
+ text: `${JSON.stringify({ id: "pmem-1", usedCount: 3, lastUsedAt: null })}\n`,
+ },
+ });
+ // The device-local folder the copy would land in refuses writes.
+ const dir = dirname(proceduralMemoryUsagePath(a.vault));
+ mkdirSync(dir, { recursive: true });
+ chmodSync(dir, 0o500);
+ try {
+ const removed = removeLegacy(a.vault, { force: true });
+ if (!removed.removed) throw new Error("not removed");
+ } finally {
+ chmodSync(dir, 0o700);
+ }
+ const tombstones = a
+ .records()
+ .filter((r) => r.kind === "lane-entry-remove" && r.body["lane"] === "procedural-memory");
+ expect(tombstones).toEqual([]);
+ });
+});
+
describe("a removal while a data shard of the store cannot be seen", () => {
test("an imported record's shard gone since this machine read it refuses, even with --force", () => {
const a = switchedAlone();
diff --git a/tests/core/store-migration/rollback.test.ts b/tests/core/store-migration/rollback.test.ts
index cd7d7101..b26ce181 100644
--- a/tests/core/store-migration/rollback.test.ts
+++ b/tests/core/store-migration/rollback.test.ts
@@ -10,6 +10,7 @@ import {
appendFileSync,
chmodSync,
existsSync,
+ mkdirSync,
readdirSync,
readFileSync,
rmSync,
@@ -32,8 +33,9 @@ import {
MIGRATION_STREAM,
} from "../../../src/core/store-migration/migration-records.ts";
import { rollback } from "../../../src/core/store-migration/outcome.ts";
+import { repairLaneEntryIds } from "../../../src/core/store-migration/lane-id-repair.ts";
import { RollbackRefusedError } from "../../../src/core/store-migration/rollback.ts";
-import { writeLaneText } from "../../../src/core/store/lane-pages.ts";
+import { readLanePage, writeLaneText } from "../../../src/core/store/lane-pages.ts";
import { readVaultIdentity } from "../../../src/core/brain/vault-identity.ts";
import { readVaultBindings } from "../../../src/core/vault-adapter/vault-binding.ts";
import { CHMOD_CANNOT_DENY } from "../../helpers/platform.ts";
@@ -267,6 +269,90 @@ describe("rollback", () => {
expect(readFileSync(bad, "utf8")).toBe("{bad");
});
+ test("after a lane-id repair, the page and the file beside it come back at their own paths", () => {
+ fleet = makeFleet(["dev-a"]);
+ const a = fleet.machine("dev-a");
+ a.use();
+ const file = join(a.vault, "Brain", "entities", "x.json");
+ const page = join(a.vault, "Brain", "entities", "x.json.md");
+ mkdirSync(join(a.vault, "Brain", "entities"), { recursive: true });
+ writeFileSync(file, '{"a":1}\n');
+ expect(runMigration(a.vault, FAST).ok).toBe(true);
+ // What an earlier release's import made of the page beside it: a record
+ // under the file's id that names the page as its legacy path.
+ appendRecord(a.store(), {
+ partition: "shared",
+ stream: "events",
+ kind: "lane-entry",
+ agent: "o2b",
+ body: {
+ authority: "agent",
+ lane: "entities",
+ entry: "x.json",
+ fields: { kind: "note" },
+ text: "The page.\n",
+ migrated: { key: "Brain/entities/x.json.md", sum: "page-sum" },
+ },
+ });
+ expect(repairLaneEntryIds(a.vault)).toHaveLength(1);
+ rollback(a.vault);
+ expect(JSON.parse(readFileSync(file, "utf8"))).toEqual({ a: 1 });
+ expect(parseFrontmatterText(readFileSync(page, "utf8"))[1].trim()).toBe("The page.");
+ });
+
+ test("after a lane-id repair of a page with no file beside it, the page survives", () => {
+ fleet = makeFleet(["dev-a"]);
+ const a = fleet.machine("dev-a");
+ a.use();
+ const page = join(a.vault, "Brain", "entities", "x.json.md");
+ mkdirSync(join(a.vault, "Brain", "entities"), { recursive: true });
+ writeFileSync(page, "---\nkind: note\n---\nThe page.\n");
+ expect(runMigration(a.vault, FAST).ok).toBe(true);
+ // An earlier release's import of the same page, under the id `x.json`.
+ appendRecord(a.store(), {
+ partition: "shared",
+ stream: "events",
+ kind: "lane-entry",
+ agent: "o2b",
+ body: {
+ authority: "agent",
+ lane: "entities",
+ entry: "x.json",
+ fields: { kind: "note" },
+ text: "The page.\n",
+ migrated: { key: "Brain/entities/x.json.md", sum: "page-sum" },
+ },
+ });
+ expect(repairLaneEntryIds(a.vault)).toEqual([
+ { from: "entities/x.json", to: "entities/x.json.md", left: "removed" },
+ ]);
+ rollback(a.vault);
+ expect(parseFrontmatterText(readFileSync(page, "utf8"))[1].trim()).toBe("The page.");
+ expect(existsSync(join(a.vault, "Brain", "entities", "x.json"))).toBe(false);
+ });
+
+ test("a user's folder spelled otherwise than its lane is imported and rolls back in place", () => {
+ fleet = makeFleet(["dev-a"]);
+ const a = fleet.machine("dev-a");
+ a.use();
+ const original = join(a.vault, "Brain", "My Notes", "idea.md");
+ mkdirSync(join(a.vault, "Brain", "My Notes"), { recursive: true });
+ writeFileSync(original, "---\nkind: note\n---\nAn idea.\n");
+ expect(runMigration(a.vault, FAST).ok).toBe(true);
+ // Read under its lane on the switched machine.
+ const stored = readLanePage(a.vault, join(a.vault, "Brain", "my-notes", "idea.md"));
+ expect(stored?.body.trim()).toBe("An idea.");
+ // Changed after the switch, then rolled back: the change lands at the user's own path.
+ writeLaneText(
+ a.vault,
+ join(a.vault, "Brain", "my-notes", "idea.md"),
+ "---\nkind: note\n---\nA better idea.\n",
+ );
+ rollback(a.vault);
+ expect(parseFrontmatterText(readFileSync(original, "utf8"))[1].trim()).toBe("A better idea.");
+ expect(existsSync(join(a.vault, "Brain", "my-notes"))).toBe(false);
+ });
+
test("puts post-switch and late remote records back once, in fold order", () => {
fleet = makeFleet(["dev-a", "dev-b"]);
const [a, b] = [fleet.machine("dev-a"), fleet.machine("dev-b")];
diff --git a/tests/core/store/fixtures/seen-ledger-worker.ts b/tests/core/store/fixtures/seen-ledger-worker.ts
new file mode 100644
index 00000000..c71aa08c
--- /dev/null
+++ b/tests/core/store/fixtures/seen-ledger-worker.ts
@@ -0,0 +1,118 @@
+/**
+ * Child process for the two-process seen-shards ledger test. Both roles
+ * run on one machine (the environment the parent passes) against one store.
+ *
+ * `track`: for every round i, appends a record of device `track-<i>` to
+ * `shared`, reads the stream (recording the new shard as seen) and removes
+ * the shard again, as a sync tool taking it away would. A later read
+ * names it only if the ledger kept it. Prints each removed shard's
+ * partition-relative path on its own line, after `kept` when the ledger
+ * held it right after the read, `skipped` when the best-effort update gave
+ * way to a busy lock, then the round's milliseconds. The leaver prints its
+ * round count and run time at the end, for a failure message.
+ * `leave`: reads the `private` shard of device `leave-0` (recording it) and
+ * clears the partition's entries again, round after round, until the stop
+ * file appears; then it clears them one last time. It gives up only when
+ * the tracker's round count (`<stop file>.progress`) has not moved for two
+ * minutes, so a slow runner never ends it early.
+ *
+ * Each worker writes `<ready dir>/<role>` once it is up and then waits for
+ * the go file, so the two run at the same time. A go or stop file that
+ * never comes ends the worker after 30 s.
+ *
+ * argv: <root> <role> <rounds> <ready dir> <go file> <stop file>
+ */
+import { existsSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { basename, join } from "node:path";
+
+import { appendRecord } from "../../../../src/core/store/appender.ts";
+import { readStreamRecords } from "../../../../src/core/store/read/stream-read.ts";
+import {
+ forgetSeenPartition,
+ withoutSeenRecording,
+} from "../../../../src/core/store/seen-shards.ts";
+import { openStore, readStoreId } from "../../../../src/core/store/store-open.ts";
+import { partitionDir } from "../../../../src/core/store/store-paths.ts";
+
+const [root, role, roundsText, readyDir, goFile, stopFile] = process.argv.slice(2) as [
+ string,
+ "track" | "leave",
+ string,
+ string,
+ string,
+ string,
+];
+writeFileSync(join(readyDir, role), "ready\n");
+const deadline = Date.now() + 30_000;
+function giveUpLate(what: string): void {
+ if (Date.now() <= deadline) return;
+ process.stderr.write(`the ${what} file never came\n`);
+ process.exit(2);
+}
+while (!existsSync(goFile)) {
+ giveUpLate("go");
+ Bun.sleepSync(1);
+}
+const storeId = readStoreId(partitionDir(root, "shared")) as string;
+const progressFile = `${stopFile}.progress`;
+const STALL_MS = 120_000;
+function readProgress(): string {
+ try {
+ return readFileSync(progressFile, "utf8");
+ } catch {
+ return "";
+ }
+}
+if (role === "track") {
+ for (let i = 0; i < Number(roundsText); i++) {
+ const started = Date.now();
+ const { path } = appendRecord(openStore({ root, device: `track-${i}` }), {
+ partition: "shared",
+ stream: "events",
+ kind: "note",
+ agent: role,
+ body: { i },
+ });
+ readStreamRecords(root, "shared", { stream: "events" });
+ rmSync(path);
+ // Whether the ledger kept the shard: a read that records nothing names
+ // it gone only if it is in the ledger. A tracking update is best
+ // effort (it skips on a busy lock), so only a kept shard is a claim.
+ const rel = `events/track-${i}/${basename(path)}`;
+ const kept = withoutSeenRecording(
+ () =>
+ readStreamRecords(root, "shared", { stream: "events" }, { device: `track-${i}` })
+ .unreadable,
+ ).includes(rel);
+ process.stdout.write(`${kept ? "kept" : "skipped"} ${rel} ${Date.now() - started}\n`);
+ // The round count, which keeps the other process going: it stops when
+ // the parent writes the stop file and gives up only when this count
+ // stops moving, never after a fixed time.
+ writeFileSync(progressFile, `${i + 1}\n`);
+ }
+} else {
+ let rounds = 0;
+ const began = Date.now();
+ let progress = "";
+ let movedAt = Date.now();
+ while (!existsSync(stopFile)) {
+ rounds += 1;
+ // Bounded by the tracker's progress, not by a clock: a slow runner only
+ // makes the rounds longer. Given up after two minutes without one.
+ const now = readProgress();
+ if (now !== progress) {
+ progress = now;
+ movedAt = Date.now();
+ } else if (Date.now() - movedAt > STALL_MS) {
+ process.stderr.write(`the tracker made no progress for ${STALL_MS} ms (at round ${now})\n`);
+ process.exit(2);
+ }
+ readStreamRecords(root, "private", { stream: "events" }, { device: "leave-0" });
+ forgetSeenPartition(root, storeId, "private");
+ // A short yield between rounds, so the tracker's lock retries find a
+ // free window; the rounds still overlap the tracker's on every pass.
+ Bun.sleepSync(1);
+ }
+ forgetSeenPartition(root, storeId, "private");
+ process.stdout.write(`leaver rounds=${rounds} ms=${Date.now() - began}\n`);
+}
diff --git a/tests/core/store/lane-paths.test.ts b/tests/core/store/lane-paths.test.ts
new file mode 100644
index 00000000..c8074501
--- /dev/null
+++ b/tests/core/store/lane-paths.test.ts
@@ -0,0 +1,85 @@
+/**
+ * Lane entry ids and legacy paths (`store/lane-paths.ts`, design D14 item
+ * 2): every path the mapping accepts turns back into itself (so no two
+ * paths share an entry), and a name that would not round-trip is refused.
+ */
+import { describe, expect, test } from "bun:test";
+
+import {
+ brainRelOfEntry,
+ laneNameRefusal,
+ lanePlaceOf,
+} from "../../../src/core/store/lane-paths.ts";
+
+/** Paths that name an entry: every row of the lane path table, and every kept extension. */
+const ACCEPTED = [
+ "about.md",
+ "lexicon.json",
+ "standing-rules.md",
+ "dead-ends/de-x.md",
+ "dead-ends/archive/de-x.md",
+ "entities/lexicon.json",
+ "entities/rows.jsonl",
+ "entities/schema.yaml",
+ "entities/schema.yml",
+ "entities/notes.txt",
+ "entities/view.base",
+ "entities/table.csv",
+ "state/exact.md",
+ "skill-benchmarks/bench.md",
+ "standing-rules/team.md",
+ ".sessions/s-1.json",
+ ".archives/src.txt",
+ // A page whose name without `.md` reads as a kept file keeps its whole name.
+ "entities/x.json.md",
+ "entities/x.md.md",
+ "x.yaml.md",
+];
+
+/** Paths that would not map back to themselves. */
+const REFUSED = [
+ // An extension that is neither a page nor a kept file, or none.
+ "entities/x.png",
+ "entities/README",
+ "image.png",
+ // A top folder that is not a lane name, or is another folder's lane name.
+ "My Notes/x.md",
+ "exact-state/exact.md",
+ "skill-benchmark/bench.md",
+ "standing-rule/team.md",
+ "write-session/s-1.json",
+ "brain/about.md",
+ // The place of a root file with a lane.
+ "standing-rules/standing-rules.md",
+ // An entry with no name.
+ "entities/.md",
+];
+
+describe("lane entry ids and legacy paths", () => {
+ test("every accepted path maps to an entry and back to itself", () => {
+ for (const path of ACCEPTED) {
+ const place = lanePlaceOf(path);
+ expect({ path, place: place !== null }).toEqual({ path, place: true });
+ expect(brainRelOfEntry(place!.lane, place!.entry)).toBe(path);
+ expect(laneNameRefusal(path)).toBeNull();
+ }
+ });
+
+ test("a page and a kept file of one name are two entries", () => {
+ expect(lanePlaceOf("entities/x.json")).toEqual({ lane: "entities", entry: "x.json" });
+ expect(lanePlaceOf("entities/x.json.md")).toEqual({ lane: "entities", entry: "x.json.md" });
+ });
+
+ test("a name that does not round-trip is refused, with the reason", () => {
+ for (const path of REFUSED) {
+ expect({ path, place: lanePlaceOf(path) }).toEqual({ path, place: null });
+ expect(laneNameRefusal(path)).toContain(path);
+ }
+ expect(laneNameRefusal("exact-state/exact.md")).toContain("state/exact.md");
+ });
+
+ test("the Brain root names no entry", () => {
+ expect(lanePlaceOf("")).toBeNull();
+ expect(laneNameRefusal("")).not.toBeNull();
+ });
+});
diff --git a/tests/core/store/seen-shards.test.ts b/tests/core/store/seen-shards.test.ts
index 2d8d88d4..ca275565 100644
--- a/tests/core/store/seen-shards.test.ts
+++ b/tests/core/store/seen-shards.test.ts
@@ -4,8 +4,8 @@
* stream reader and the partition reader, unless a compaction replaced it
* or a human retired the device that wrote it.
*/
-import { afterEach, describe, expect, test } from "bun:test";
-import { readdirSync, rmSync } from "node:fs";
+import { afterEach, describe, expect, setDefaultTimeout, test } from "bun:test";
+import { mkdirSync, readdirSync, rmSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import {
@@ -20,9 +20,14 @@ import { readStreamRecords } from "../../../src/core/store/read/stream-read.ts";
import { withoutSeenRecording } from "../../../src/core/store/seen-shards.ts";
import { readPartition } from "../../../src/core/store/state-digest.ts";
import { initStore } from "../../../src/core/store/store-init.ts";
-import { openStore } from "../../../src/core/store/store-open.ts";
-import { partitionDir } from "../../../src/core/store/store-paths.ts";
+import { openStore, readStoreId } from "../../../src/core/store/store-open.ts";
+import { deviceStateDirFor, partitionDir } from "../../../src/core/store/store-paths.ts";
+import { processDirsEnv } from "../../../src/core/platform-dirs.ts";
import { makeStoreEnv, type StoreEnv } from "./fixtures/store-env.ts";
+import { CLI_SPAWN_BUDGET_MS } from "../../helpers/cli-timeout.ts";
+
+// Tests here spawn processes; see tests/helpers/cli-timeout.ts.
+setDefaultTimeout(CLI_SPAWN_BUDGET_MS);
let env: StoreEnv | null = null;
afterEach(() => {
@@ -36,7 +41,13 @@ const OCT = Date.UTC(2026, 9, 6, 9);
function note(e: StoreEnv, device: string, at = NOV): string {
return appendRecord(
openStore({ root: e.storeRoot, device }),
- { partition: "shared", stream: "events", kind: "note", agent: "t", body: { device } },
+ {
+ partition: "shared",
+ stream: "events",
+ kind: "note",
+ agent: "t",
+ body: { device },
+ },
{ now: () => at },
).path;
}
@@ -46,7 +57,9 @@ const events = (e: StoreEnv, options = {}) =>
function partitionUnreadable(e: StoreEnv): string[] {
const out: string[] = [];
- readPartition(partitionDir(e.storeRoot, "shared"), { onUnreadable: ({ rel }) => out.push(rel) });
+ readPartition(partitionDir(e.storeRoot, "shared"), {
+ onUnreadable: ({ rel }) => out.push(rel),
+ });
return out;
}
@@ -135,7 +148,10 @@ describe("a shard removed on purpose is not reported", () => {
stream: "events",
kind: COMPACTED_KIND,
agent: "o2b",
- body: { replaces: ["events/dev-b/2026-10.jsonl"], into: ["events/dev-b/2026-11.jsonl"] },
+ body: {
+ replaces: ["events/dev-b/2026-10.jsonl"],
+ into: ["events/dev-b/2026-11.jsonl"],
+ },
},
{ now: () => NOV },
);
@@ -146,7 +162,10 @@ describe("a shard removed on purpose is not reported", () => {
describe("the decision ledger, an accountability ledger", () => {
test("a shard of it gone since this machine read it throws, never reads as no decision", () => {
- env = makeStoreEnv("osb-seen-decisions-", { legacyTree: false, configureVault: false });
+ env = makeStoreEnv("osb-seen-decisions-", {
+ legacyTree: false,
+ configureVault: false,
+ });
const row: DecisionLedgerRow = {
ts: "2026-11-06T10:00:00Z",
actor: "codex",
@@ -164,3 +183,134 @@ describe("the decision ledger, an accountability ledger", () => {
expect(() => queryDecisionLedger(null)).toThrow(LedgerUnreadableError);
});
});
+
+describe("two processes on one machine", () => {
+ test("a shard one tracks and a partition clearing the other runs both survive", async () => {
+ env = makeStoreEnv("osb-seen-two-proc-", { legacyTree: false });
+ const ROUNDS = 200;
+ appendRecord(openStore({ root: env.storeRoot, device: "leave-0" }), {
+ partition: "private",
+ stream: "events",
+ kind: "note",
+ agent: "t",
+ body: {},
+ });
+ const readyDir = join(env.parent, "ready");
+ const goFile = join(env.parent, "go");
+ const stopFile = join(env.parent, "stop");
+ mkdirSync(readyDir, { recursive: true });
+ const worker = join(import.meta.dir, "fixtures", "seen-ledger-worker.ts");
+ const [tracker, leaver] = (["track", "leave"] as const).map((role) =>
+ Bun.spawn(
+ [
+ process.execPath,
+ worker,
+ env!.storeRoot,
+ role,
+ String(ROUNDS),
+ readyDir,
+ goFile,
+ stopFile,
+ ],
+ { stdout: "pipe", stderr: "pipe", env: { ...process.env } },
+ ),
+ ) as [Bun.Subprocess<"ignore", "pipe", "pipe">, Bun.Subprocess<"ignore", "pipe", "pipe">];
+ const readyBy = Date.now() + 30_000;
+ while (readdirSync(readyDir).length < 2 && Date.now() < readyBy) await Bun.sleep(5);
+ writeFileSync(goFile, "go\n");
+ // The pipes are drained while waiting, so a noisy worker cannot block on a full pipe.
+ const errors = Promise.all([tracker, leaver].map((child) => new Response(child.stderr).text()));
+ const removed = new Response(tracker.stdout).text();
+ const leaverOut = new Response(leaver.stdout).text();
+ const trackCode = await tracker.exited;
+ writeFileSync(stopFile, "stop\n");
+ const leaveCode = await leaver.exited;
+ expect((await errors).filter((e) => e.trim() !== "")).toEqual([]);
+ expect([trackCode, leaveCode]).toEqual([0, 0]);
+
+ // The tracking process removed every shard right after reading it. A
+ // shard the ledger held then (`kept`) must still be named gone after
+ // all the clearings of the other process; one whose best-effort update
+ // gave way to a busy lock (`skipped`) makes no claim. Most rounds keep
+ // theirs, so the check is never empty.
+ const lines = (await removed).split("\n").filter((line) => line !== "");
+ expect(lines).toHaveLength(ROUNDS);
+ const rounds = lines.map((line) => {
+ const [state, rel, ms] = line.split(" ");
+ return { kept: state === "kept", rel: rel!, ms: Number(ms) };
+ });
+ const kept = rounds.filter((r) => r.kept).map((r) => r.rel);
+ if (kept.length < ROUNDS / 2) {
+ // What a slow runner needs to say: how often the update gave way, how
+ // long a skipped round took (about the lock budget: it waited; about
+ // nothing: it was backed off), and how hard the other process ran.
+ const skipped = rounds.filter((r) => !r.kept);
+ const ms = skipped.map((r) => r.ms).toSorted((a, b) => a - b);
+ throw new Error(
+ `tracking kept ${kept.length} of ${ROUNDS} rounds on ${process.platform}; ` +
+ `first skipped round ${rounds.findIndex((r) => !r.kept)}, skipped round ms ` +
+ `min ${ms[0]} median ${ms[Math.floor(ms.length / 2)]} max ${ms.at(-1)}; ` +
+ `kept round ms max ${Math.max(0, ...rounds.filter((r) => r.kept).map((r) => r.ms))}; ` +
+ `${(await leaverOut).trim()}`,
+ );
+ }
+ const gone = new Set(withoutSeenRecording(() => events(env!).unreadable));
+ expect(kept.filter((rel) => !gone.has(rel))).toEqual([]);
+ rmSync(join(env.storeRoot, "private", "events"), {
+ recursive: true,
+ force: true,
+ });
+ // The last clearing held: no private entry came back.
+ const priv = withoutSeenRecording(
+ () => readStreamRecords(env!.storeRoot, "private", { stream: "events" }).unreadable,
+ );
+ expect(priv).toEqual([]);
+ // Rounds, not a clock, bound the workers; this only stops a hang.
+ }, 300_000);
+});
+
+describe("a ledger lock a crashed process left behind", () => {
+ test("costs the tracking reads of a process one bounded wait, not one per read", () => {
+ env = makeStoreEnv("osb-seen-busy-", { legacyTree: false });
+ note(env, "dev-a");
+ events(env);
+ const storeId = readStoreId(partitionDir(env.storeRoot, "shared")) as string;
+ const dir = deviceStateDirFor(storeId, processDirsEnv());
+ const ledger = readdirSync(dir).find(
+ (n) => n.startsWith("seen-shards-") && n.endsWith(".json"),
+ );
+ // A fresh lock directory, as a holder that died mid-update leaves it.
+ mkdirSync(join(dir, `${ledger!}.lock`));
+ // The first tracking read waits out its budget once.
+ note(env, "dev-b");
+ expect(events(env).unreadable).toEqual([]);
+ // The next eight skip without waiting. Timed apart from the first, the
+ // bound separates no wait from one half-second wait per read (at least
+ // four seconds) with room for a slow runner's appends and listings.
+ const started = Date.now();
+ for (const device of ["dev-c", "dev-d", "dev-e", "dev-f", "dev-g", "dev-h", "dev-i", "dev-j"]) {
+ note(env, device);
+ expect(events(env).unreadable).toEqual([]);
+ }
+ expect(Date.now() - started).toBeLessThan(2_500);
+ });
+});
+
+describe("a tracking update that gave way to a busy lock", () => {
+ test("keeps the shard it saw, so its loss is still named", () => {
+ env = makeStoreEnv("osb-seen-queued-", { legacyTree: false });
+ note(env, "dev-a");
+ events(env);
+ const storeId = readStoreId(partitionDir(env.storeRoot, "shared")) as string;
+ const dir = deviceStateDirFor(storeId, processDirsEnv());
+ const ledger = readdirSync(dir).find(
+ (n) => n.startsWith("seen-shards-") && n.endsWith(".json"),
+ );
+ // A lock directory a crashed process left: the next update gives way.
+ mkdirSync(join(dir, `${ledger!}.lock`));
+ const peer = note(env, "dev-b");
+ expect(events(env).unreadable).toEqual([]);
+ rmSync(peer);
+ expect(events(env).unreadable).toEqual(["events/dev-b/" + peer.split(/[\\/]/).at(-1)]);
+ });
+});
diff --git a/tests/mcp/evidence-counters-reach.test.ts b/tests/mcp/evidence-counters-reach.test.ts
new file mode 100644
index 00000000..91393deb
--- /dev/null
+++ b/tests/mcp/evidence-counters-reach.test.ts
@@ -0,0 +1,183 @@
+/**
+ * The evidence counters of a shared preference at each reach on a
+ * switched machine (task 3.18, design D15 item 4): the counters fold every
+ * partition the machine holds, so a local caller sees its private
+ * evidence counted, and a caller below local reach is shown what a
+ * machine that holds only `shared` folds.
+ */
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+
+import { appendApplyEvidence } from "../../src/core/brain/apply-evidence.ts";
+import { writePreference } from "../../src/core/brain/preference.ts";
+import { indexVault, resolveSearchConfig } from "../../src/core/search/index.ts";
+import { TRANSPORT_REACH, type TransportReach } from "../../src/core/graph/transport-reach.ts";
+import { JSONRPC_VERSION, MCPServer, PROTOCOL_VERSION } from "../../src/mcp/index.ts";
+import { switchDevice } from "../core/brain/store-only/fixtures.ts";
+import { makeStoreEnv, type StoreEnv } from "../core/store/fixtures/store-env.ts";
+
+let env: StoreEnv;
+beforeEach(() => {
+ env = makeStoreEnv("osb-evidence-reach-", { dualWrite: false });
+ switchDevice(env.storeRoot);
+ writePreference(
+ env.vault,
+ {
+ slug: "tabs",
+ topic: "tabs",
+ principle: "principle tabs",
+ created_at: "2026-11-01T00:00:00Z",
+ unconfirmed_until: "2026-12-30T00:00:00Z",
+ status: "confirmed",
+ evidenced_by: [],
+ },
+ { authority: "agent" },
+ );
+ appendApplyEvidence(env.vault, {
+ pref_id: "pref-tabs",
+ artifact: "[[notes/open]]",
+ agent: "claude",
+ result: "applied",
+ });
+ // Its note names a preference the store cannot resolve: judged private.
+ appendApplyEvidence(env.vault, {
+ pref_id: "pref-tabs",
+ artifact: "[[notes/work]]",
+ agent: "claude",
+ result: "applied",
+ note: "[[pref-unknown-private]]",
+ });
+});
+afterEach(() => env.cleanup());
+
+/** The whole JSON-RPC response, error included. */
+async function callRaw(reach: TransportReach, method: string, params: Record<string, unknown>) {
+ const server = new MCPServer({ vault: env.vault, configPath: env.configPath }, { reach });
+ return JSON.stringify(
+ await server.handleRequest({ jsonrpc: JSONRPC_VERSION, id: 2, method, params }),
+ );
+}
+
+async function call(reach: TransportReach, method: string, params: Record<string, unknown>) {
+ const server = new MCPServer({ vault: env.vault, configPath: env.configPath }, { reach });
+ await server.handleRequest({
+ jsonrpc: JSONRPC_VERSION,
+ id: 1,
+ method: "initialize",
+ params: {
+ protocolVersion: PROTOCOL_VERSION,
+ capabilities: {},
+ clientInfo: { name: "t", version: "0" },
+ },
+ });
+ const response = (await server.handleRequest({
+ jsonrpc: JSONRPC_VERSION,
+ id: 2,
+ method,
+ params,
+ })) as {
+ result?: unknown;
+ error?: unknown;
+ };
+ expect(response.error).toBeUndefined();
+ return JSON.stringify(response.result);
+}
+
+function read(reach: TransportReach): Promise<string> {
+ return call(reach, "resources/read", { uri: "osb://preference/tabs" });
+}
+
+/** The text payload of a tool call. */
+async function toolText(reach: TransportReach, name: string, args: Record<string, unknown>) {
+ const result = JSON.parse(await call(reach, "tools/call", { name, arguments: args })) as {
+ content: Array<{ text: string }>;
+ };
+ return result.content[0]!.text;
+}
+
+async function applied(reach: TransportReach): Promise<number> {
+ const text = await toolText(reach, "brain_query", { preference: "pref-tabs" });
+ return (JSON.parse(text) as { preference: { applied_count: number } }).preference.applied_count;
+}
+
+function content(reach: TransportReach): Promise<string> {
+ return toolText(reach, "brain_context", {});
+}
+
+describe("evidence counters of a shared preference", () => {
+ test("the preference resource counts private evidence locally only", async () => {
+ expect(await read(TRANSPORT_REACH.local)).toContain("_applied_count: 2");
+ const remote = await read(TRANSPORT_REACH.remote);
+ expect(remote).toContain("_applied_count: 1");
+ expect(remote).not.toContain("_applied_count: 2");
+ });
+
+ test("brain_query answers the shared count below local reach", async () => {
+ expect(await applied(TRANSPORT_REACH.local)).toBe(2);
+ expect(await applied(TRANSPORT_REACH.remote)).toBe(1);
+ });
+});
+
+async function counted(reach: TransportReach): Promise<number> {
+ const server = new MCPServer({ vault: env.vault, configPath: env.configPath }, { reach });
+ const result = (await server.callTool("brain_query", { preference: "pref-tabs" })) as {
+ content: Array<{ text: string }>;
+ };
+ return (JSON.parse(result.content[0]!.text) as { preference: { applied_count: number } })
+ .preference.applied_count;
+}
+
+describe("the CLI tool bridge", () => {
+ test("callTool answers in the caller's reach too", async () => {
+ expect(await counted(TRANSPORT_REACH.local)).toBe(2);
+ expect(await counted(TRANSPORT_REACH.remote)).toBe(1);
+ });
+});
+
+describe("the brain_context digest", () => {
+ test("states the shared count below local reach", async () => {
+ expect(await content(TRANSPORT_REACH.local)).toContain("applied_in_window: 2");
+ const remote = await content(TRANSPORT_REACH.remote);
+ expect(remote).toContain("applied_in_window: 1");
+ expect(remote).not.toContain("applied_in_window: 2");
+ });
+});
+
+// A regression guard, not proof of task 3.18: indexed reads served this
+// before the change too (the index holds records, never derived counters,
+// and reserves the `private` partition). It pins that the new counters
+// rule did not open a path through the index.
+describe("indexed reads below local reach (regression guard)", () => {
+ test("serve neither the private evidence record nor a counter that counts it", async () => {
+ await indexVault(resolveSearchConfig({ vault: env.vault, configPath: env.configPath }), {});
+ // The index holds records, not the counters derived from them: a
+ // preference record's fields never carry one (FORMAT.md).
+ const hits = async (reach: TransportReach, query: string): Promise<string> =>
+ toolText(reach, "brain_search", { query, limit: 1 });
+ // Only the private evidence names this page: found locally, withheld remotely.
+ expect(await hits(TRANSPORT_REACH.local, "unknown private")).toContain("pref-unknown-private");
+ const remote = await hits(TRANSPORT_REACH.remote, "unknown private");
+ // Its chunk, drilled into by id from below local reach, is withheld too.
+ const local = JSON.parse(await hits(TRANSPORT_REACH.local, "unknown private")) as {
+ results: Array<{ chunkId: number }>;
+ };
+ const chunk = local.results[0]!.chunkId;
+ const expanded = await callRaw(TRANSPORT_REACH.remote, "tools/call", {
+ name: "brain_search_expand",
+ arguments: { chunk_id: chunk },
+ });
+ expect(expanded).not.toContain("pref-unknown-private");
+ const answers = [
+ remote,
+ await hits(TRANSPORT_REACH.remote, "applied"),
+ await hits(TRANSPORT_REACH.remote, "principle tabs"),
+ await toolText(TRANSPORT_REACH.remote, "brain_file_context", {
+ file_path: "notes/work.md",
+ min_bytes: 0,
+ }),
+ ];
+ for (const answer of answers) {
+ expect(answer).not.toContain("applied_count");
+ expect(answer).not.toContain("pref-unknown-private");
+ }
+ });
+});