Skip to content

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

TypeScript

feat(store): split the lane page store, keep private log events off exports and remote readers (#293)

Serg Eroshe233b91d1bdc7
diff --git a/openspec/changes/archive/2026-11-09-lane-pages-split/.openspec.yaml b/openspec/changes/archive/2026-11-09-lane-pages-split/.openspec.yaml
new file mode 100644
index 00000000..5c4ac8f6
--- /dev/null
+++ b/openspec/changes/archive/2026-11-09-lane-pages-split/.openspec.yaml
@@ -0,0 +1,2 @@
+schema: osb
+created: 2026-11-09
diff --git a/openspec/changes/archive/2026-11-09-lane-pages-split/brainstorm.md b/openspec/changes/archive/2026-11-09-lane-pages-split/brainstorm.md
new file mode 100644
index 00000000..523f88f2
--- /dev/null
+++ b/openspec/changes/archive/2026-11-09-lane-pages-split/brainstorm.md
@@ -0,0 +1,74 @@
+# Brainstorm
+
+## Problem
+
+Two follow-ups queued by the phase 2 review of `brain-store-and-topics`
+(tasks 3.13 and 3.14 there): `src/core/store/lane-pages.ts` is past the
+700-line limit, and on a switched machine an OKF export carries log events
+of the `private` partition into `log.md` with no privacy marker.
+
+## Related work
+
+None in flight: no open pull request, and no other change under
+`openspec/changes/` touches these modules. Both items were decided as
+work to do in the phase 2 review; this brainstorm settles how.
+
+## Doubts
+
+1. Hidden dependencies of the moved helpers, and an import cycle.
+2. Whether an architecture test pins which file holds which writer.
+3. The partition of a log record present in both partitions.
+4. Whether counting private events by subtracting two reads is exact.
+5. Unreadable log shards in the export.
+6. Other egress paths that carry log events.
+7. Windows, the OpenClaw bundle, the manifest parser.
+
+## Approaches considered
+
+Part A (author): one store-side module; three modules (paths, fold,
+records); a split by reads and writes. Part B (author): leave private
+events out and count them; an inline privacy marker per entry; refuse the
+export while any private event exists; leave them out unless a flag says
+otherwise. Partner: one read of the log counted by partition instead of a
+full read minus a shared-only read; private wins for a record in both
+partitions; fail closed on an unreadable store log shard, as the legacy
+path already does for an unreadable day file.
+
+## Decision
+
+Part A: one module, `lane-entry-store.ts`, with the store side moved
+verbatim. `lanePagesInStore` moves too, because `heldInStore` calls it
+(the partner found this; leaving it behind makes an import cycle), and
+`lane-pages.ts` re-exports it. Every write call stays in `lane-pages.ts`,
+so the write-site census must not change.
+
+Part B: private events leave `log.md` and are counted, from one read of
+the store log that carries each event's partition; private wins when a
+record is in both partitions; the count is taken before the content-class
+filter; the export refuses when a store log shard cannot be read. The
+manifest gains `log_private_omitted`, carried through every function that
+passes the log along (the partner found the `Pick` types that would have
+dropped it on the export verb's path), and the verb names the count
+whatever its content-class flags.
+
+## Rejected
+
+- Three store-side modules: they separate the record builders from the
+ partition test they serve.
+- A reads and writes split: it cuts through the rule that keeps an entry
+ in its partition.
+- A privacy marker per log entry: easy to strip, and no consumer reads it.
+- Refusing the export while any private event exists: the operator loses
+ the whole bundle over one event.
+- A flag that keeps private events: it re-opens the leak.
+- Full read minus shared-only read: not atomic, and it reads the log
+ twice.
+- Shared wins for a record in both partitions: the permissive answer
+ when devices disagree.
+
+## Process
+
+Partner: an agent of a different model family, read-only, one round. It
+confirmed approach A and B, and corrected the design on the import cycle,
+the count, the duplicate rule, unreadable shards, the manifest plumbing
+and the notice placement. No open questions remain.
diff --git a/openspec/changes/archive/2026-11-09-lane-pages-split/design.md b/openspec/changes/archive/2026-11-09-lane-pages-split/design.md
new file mode 100644
index 00000000..fdcccb6b
--- /dev/null
+++ b/openspec/changes/archive/2026-11-09-lane-pages-split/design.md
@@ -0,0 +1,197 @@
+# Design: split the lane page store, and keep private log events out of OKF exports
+
+See proposal.md for why. Two independent parts, built in order: Part A
+(D1, the split) changes no behaviour; Part B (D2, the log rule) changes
+one observable behaviour of the export.
+
+## Context
+
+- `src/core/store/lane-pages.ts` (about 885 lines) is the one place the
+ lane modules read and write their pages. About 60 files import it.
+ Its sections: path helpers (`laneVaultRoot` to `context`, lines 81-162),
+ "The store side" (lines 164-328), "Reads" (330-530), "Writes"
+ (532-802), "Folders of lane files" (804-885). Inside "Writes" sit four
+ private helpers that belong to the store side: `legacyPagePrivate`,
+ `storedEntryPrivate`, `isLaneEntryPath` and `laneTextParts`.
+- `src/core/store/read/log-events.ts` reads `log-event` records from both
+ partitions, deduplicates them by record id (`shared` is read first, so
+ a record present in both counts as shared) and returns
+ `StoreLogEvent { entry, device, hlc }` without the partition.
+- `src/core/brain/log-days.ts` `storeLogDays(vault, context)` groups those
+ events by day; `null` on an unswitched machine. A read pass caches the
+ days per store root and vault.
+- `src/core/brain/portability/okf.ts` `buildLog(vault, filter?)` renders
+ `log.md` from `storeLogDays(vault)` on a switched machine and from the
+ `Brain/log/` day files otherwise, and returns
+ `OkfLog { contents, days, droppedEntries }`. The manifest
+ (`OkfManifest`) carries `log_days`. The import parses the manifest
+ leniently: a missing numeric field reads as 0.
+- `src/cli/brain/verbs/okf-export.ts` writes the bundle and prints the
+ omission notices on standard error (`logOmissionNotice` and others).
+
+## Goals / Non-Goals
+
+Goals: every source file of this change under 700 lines; no caller of
+`lane-pages.ts` edited for Part A; a private log event never reaches
+`log.md`.
+
+Non-goals: tasks 3.8 to 3.12, 3.15 and 3.16 of `brain-store-and-topics`;
+any change to how log events are written; a flag that puts private events
+back into `log.md`. No other egress path carries log events: the
+knowledge pack (`buildOkfSubsetBundle`) has no `log.md` by contract, and
+`buildOkfBundleFromPages` calls `buildLog` by default; the other readers of
+the log days (MCP resources, briefs, status, backlinks) are reads on the
+same machine, not egress.
+
+## Decisions
+
+### D1. The store side moves to `src/core/store/lane-entry-store.ts`
+
+The new module holds, moved verbatim (doc comments included):
+
+1. the path helpers the store side needs: `lanePagesInStore` (lines
+ 95-98; `heldInStore` calls it, so leaving it behind would make an
+ import cycle), `heldInStore`, `insideBrain`, `brainRelOf`, `placeOf`,
+ `isLaneEntryPath`, and the constant `PAGE_OPAQUE_FIELDS`;
+2. everything under "The store side": `storeEntries`, `laneEntryClockMs`,
+ `storeEntry`, `foldIncomplete`, `livesInPrivate`, `laneEntryInPrivate`,
+ `partitionOf`, `tombstoneOf`, `replacedShared`, `fieldsCopy`,
+ `sameEntry`, `authorityFor`, `isPrivateEntry`, `entryRecord`,
+ `PRIVATE_WHEN_HELD_LANES`;
+3. the keep-rule helpers from "Writes": `legacyPagePrivate`,
+ `storedEntryPrivate`, `laneTextParts`, together with the doc comment
+ that explains the two halves of the keep rule.
+
+Functions that `lane-pages.ts` still calls are exported from the new
+module; nothing else changes in their signatures or bodies. The module
+gets a short header comment (what it holds, design D14 of
+`brain-store-and-topics`). `lane-pages.ts` imports them, keeps every
+export it has today, and re-exports `lanePagesInStore`,
+`laneEntryClockMs` and `laneEntryInPrivate`
+(`export { … } from "./lane-entry-store.ts"`) so no caller changes.
+`lane-pages.ts` still needs `statSync` and `existsSync` (for example
+`laneFileBytes`): remove only the imports the compiler reports unused. The new module must not import `lane-pages.ts` (no
+import cycle). `routeLaneWrite`, `guardUserVaultWrite`, `context`,
+`withCreateLock` and the lock helpers stay in `lane-pages.ts`.
+
+Alternative considered: three modules (paths, fold, records). Rejected:
+more files for no reader benefit; one store-side module of about 330
+lines leaves `lane-pages.ts` at about 560.
+
+### D2. `log.md` leaves out events of the `private` partition
+
+One read of the store log, counted by partition; the read refuses when it
+is not whole.
+
+1. `src/core/store/read/log-events.ts`: `StoreLogEvent` gains
+ `readonly partition: StorePartition`. A record id read from both
+ partitions is `private` (private wins: the strict answer when devices
+ disagree). Add
+ `readStoreLogEventsReport(range, context): { events: StoreLogEvent[]; unreadable: ReadonlyArray<string> } | null`
+ (`null` on an unswitched machine), and make `readStoreLogEvents` return
+ its `events`, so existing callers are unchanged.
+2. `src/core/brain/log-days.ts`: export `WHOLE_LOG`, and add
+ `groupLogDays(entries): LogDay[]`, the values of the existing
+ module-private `groupByDay` (oldest first, the same frozen days
+ `storeLogDays` returns). `groupByDay` and `storeLogDays` are unchanged.
+3. `src/core/brain/portability/okf.ts` `buildLog`, on a switched machine:
+ read once with `readStoreLogEventsReport(WHOLE_LOG, { vault })` (the
+ same whole-log range `log-days.ts` uses). When `unreadable` is not
+ empty, throw
+ `okf export: cannot read log shard(s) <names>; the bundle would be short of their events`,
+ the store side of the existing throw for an unreadable day file
+ (okf.ts, "cannot read log shard"). A switched machine whose store
+ cannot be opened reads no events and no unreadable shard, so `buildLog`
+ first asks `protectionStore()` (`src/core/store/read/protection-store.ts`),
+ which throws `StoreUnavailableError` there (added in the code review).
+ Otherwise count the `private` events
+ into `privateEntries`, and render the days of the `shared` events
+ (`groupLogDays`) exactly as today. The content-class filter then applies
+ to the shared events only, so the two counts never overlap. On an
+ unswitched machine `buildLog` is unchanged and `privateEntries` is 0.
+ `OkfLog` gains `readonly privateEntries: number`.
+4. The manifest: `OkfManifest` gains `readonly log_private_omitted: number`.
+ Every place that builds or carries one is updated: the two
+ `Pick<OkfLog, "contents" | "days">` parameters of
+ `buildOkfBundleFromPages` and `assembleOkfBundle` become
+ `Pick<OkfLog, "contents" | "days" | "privateEntries">` (otherwise the
+ export verb, which passes its own log through them, would write 0), the
+ manifest built in `assembleOkfBundle` (`log_private_omitted:
+ log?.privateEntries ?? 0`), `ManifestInput` and the parser (missing or
+ not a finite number reads as 0, like `log_days`), and the literal
+ manifest of `readSpecOkfBundle` (0). `renderOkfManifest` is
+ `JSON.stringify` and needs nothing. `index.md` is unchanged.
+5. `src/cli/brain/verbs/okf-export.ts`: when `log.privateEntries > 0`,
+ print one line on standard error,
+ `okf-export: left N private log entr(y|ies) out of log.md\n`,
+ OUTSIDE the `--include-prompt-derived` branch (that flag is about
+ content class, not partitions), so it prints with and without the flag.
+
+Alternatives considered: a privacy marker inside each private entry of
+`log.md` (rejected: a marker in prose is easy to strip and no consumer
+reads it); refusing the export whenever a private event exists (rejected:
+the operator loses the whole bundle over one event); a flag to keep them
+(rejected: it re-opens the leak); two reads, full minus shared-only
+(rejected: not atomic, so an append between them skews the count, and it
+reads the log twice).
+
+### D3. Private log events are withheld below local reach (added in review)
+
+The final code review found the same leak on the MCP side: the
+`osb://log/{date}` resource and `brain_query` render store log events to a
+remote caller through `logEntriesAtReach`, which judged an event only by
+the records it names, so a private event naming nothing reached a remote
+client. The fix is general rather than per reader:
+
+1. `BrainLogEntry` gains `fromPrivatePartition?: true`, set by
+ `storeLogEvents` (`src/core/store/read/log-events.ts`) on every entry
+ read from the `private` partition.
+2. `ArtifactRefView` gains `withholdsPrivate?: boolean`. `reachView`
+ sets it below local reach; `everyArtifactRefView` keeps it when any
+ constituent has it.
+3. `logEntryAtReach` returns nothing for a marked entry when the view
+ withholds private ones, before its reference rule; `logEntriesAtReach`
+ and every single-entry caller (`brain_event_trace`, the digest's agent
+ summary, the lessons reader) inherit it.
+5. The digest and the lessons reader build their own view from a
+ `readable` predicate, which cannot say the caller is remote (an owner
+ scope at local reach passes one too). Both take `withholdsPrivate`
+ (`readerRefView`'s third argument); `osb://digest/latest`, the lessons
+ resource and `brain_brief` pass it below local reach.
+4. `readLog` in `src/mcp/resources.ts` filters before its empty-day check,
+ so a day of only withheld events reads as absent (no existence
+ oracle).
+
+Readers of the log that may render it to a remote caller without the
+reach helpers (the active-preferences digest's most-applied counts, the
+morning brief, temporal citations, status, backlinks, analytics) are
+audited in task 3.17 of `brain-store-and-topics`.
+
+The same review found that a store-only machine that was never switched
+(no legacy tree) with a corrupt `store.json` still exported an empty log.
+`protectionStore` gains `openErrorFails`: a store that exists but cannot
+be opened throws on any store-only machine; `buildLog` asks with it and
+with the vault it exports (`vault`), so an explicit export vault that is
+store-only is judged as such even when the configured vault still has its
+legacy tree.
+
+## Risks / Trade-offs
+
+- [A moved function keeps a hidden dependency on a `lane-pages.ts`
+ local] → the type check fails on it; move the dependency too only if it
+ belongs to the store side, otherwise pass it in. Report every such case.
+- [The write-site census (`tests/core/architecture/write-site-census.test.ts`)
+ pins which files write] → the moved code only reads the file system, and
+ every write call stays in `lane-pages.ts`, so the census must not change.
+ A census failure means something moved that should not have: undo that
+ move instead of editing the census.
+- [An export that used to succeed now refuses on an unreadable log shard]
+ → the operator gets the shard names and the same remedy as for an
+ unreadable day file; a bundle silently short of events is worse.
+- [The OpenClaw bundle includes a changed module] → rebuild it and commit
+ `openclaw/index.js`; the gate compares it.
+
+## Migration Plan
+
+None: no format on disk changes. A bundle written before this change has
+no `log_private_omitted`, which the parser reads as 0.
diff --git a/openspec/changes/archive/2026-11-09-lane-pages-split/proposal.md b/openspec/changes/archive/2026-11-09-lane-pages-split/proposal.md
new file mode 100644
index 00000000..57c8a735
--- /dev/null
+++ b/openspec/changes/archive/2026-11-09-lane-pages-split/proposal.md
@@ -0,0 +1,56 @@
+# Proposal: split the lane page store, and keep private log events out of OKF exports
+
+## Why
+
+Two follow-ups from the phase 2 review of `brain-store-and-topics` (tasks
+3.13 and 3.14 there) are small, bounded and independent of the topics
+work, so they ship first as their own pull request.
+
+1. `src/core/store/lane-pages.ts` is about 885 lines, past the 700-line
+ limit for a source file. It grew there with the fix that keeps a
+ replaced private entry private, and every later fix in it makes the
+ file harder to review.
+2. On a switched machine, `o2b brain okf-export` renders `log.md` from
+ every `log-event` record the machine holds, the `private` partition
+ included. A page from the private partition gets a
+ `visibility: [private]` stamp in the bundle, but a log entry has no
+ frontmatter to carry it, so a private event leaves the machine
+ unmarked inside `log.md` (review finding F333, log side).
+
+## What Changes
+
+- The store side of the lane page store (the fold accessors, the rule
+ that keeps an entry in its partition, the record builders) moves out of
+ `lane-pages.ts` into a module of its own. No behaviour changes, and
+ every caller keeps importing from `lane-pages.ts`.
+- `log.md` in an OKF bundle built on a switched machine leaves out every
+ log event of the `private` partition. The manifest and the export verb
+ name how many were left out. An unswitched machine is unchanged: its
+ legacy day files carry no partition.
+
+## Capabilities
+
+### New Capabilities
+
+- `remote-log-reads`: what a remote MCP caller may read of the log; a
+ private log event is withheld from it (found in review, design D3).
+- `okf-export`: what an Open Knowledge Format bundle written by
+ `o2b brain okf-export` carries, starting with the rule for private log
+ events.
+
+### Modified Capabilities
+
+None.
+
+## Impact
+
+- Code: `src/core/store/lane-pages.ts` and a new
+ `src/core/store/lane-entry-store.ts`; `src/core/store/read/log-events.ts`
+ (the event's partition), `src/core/brain/log-days.ts` (a shared-only
+ read), `src/core/brain/portability/okf.ts` (`buildLog`, the manifest)
+ and `src/cli/brain/verbs/okf-export.ts` (the notice).
+- The OpenClaw bundle (`openclaw/index.js`) is rebuilt if it includes any
+ of these modules.
+- `openspec/changes/brain-store-and-topics/tasks.md`: tasks 3.13 and 3.14
+ point here.
+- No new dependency, no format change on disk, no migration.
diff --git a/openspec/changes/archive/2026-11-09-lane-pages-split/review.md b/openspec/changes/archive/2026-11-09-lane-pages-split/review.md
new file mode 100644
index 00000000..f13f8571
--- /dev/null
+++ b/openspec/changes/archive/2026-11-09-lane-pages-split/review.md
@@ -0,0 +1,34 @@
+# Independent review
+
+## Reviewer
+
+An agent of a different model family than the author, which had not seen
+the brainstorm, read-only, one round. It checked every file, function,
+type and line reference against the tree.
+
+## Findings
+
+1. tasks.md 0.1: told the executor to edit the write-site census if it
+ failed, against design.md (Risks) and task 1.3, which say to undo the
+ move instead. Fixed: 0.1 now says the census must keep passing
+ unchanged.
+2. tasks.md: no version bump or CHANGELOG step in the workflow follow-up.
+ Rejected: this change belongs to the unreleased store work of
+ `brain-store-and-topics`; the store-only machines it affects exist only
+ after the migration of phase 2, whose release waits for the owner's
+ multi-machine check (task 2.14 there). The bump rides in the pull
+ request that ships that release.
+3. specs/okf-export: "every log event of the `shared` partition
+ unchanged" overstated what the export does, since the content-class
+ policy already drops some shared events. Fixed: the requirement now
+ says shared events are carried as today, under that policy.
+4. design.md Context: "about 80 files" import `lane-pages.ts`; the
+ reviewer counted 63. Fixed: "about 60".
+
+The reviewer noted that `buildLog` reads the store log directly, outside
+the read-pass cache of `log-days.ts`, and agreed this is the intended
+trade: the count and the days come from one read.
+
+## Verdict
+
+Ready for implementation: yes
diff --git a/openspec/changes/archive/2026-11-09-lane-pages-split/specs/okf-export/spec.md b/openspec/changes/archive/2026-11-09-lane-pages-split/specs/okf-export/spec.md
new file mode 100644
index 00000000..4407f60c
--- /dev/null
+++ b/openspec/changes/archive/2026-11-09-lane-pages-split/specs/okf-export/spec.md
@@ -0,0 +1,85 @@
+## Purpose
+
+What an Open Knowledge Format bundle written by `o2b brain okf-export`
+carries out of the machine, and what it must leave behind.
+
+## ADDED Requirements
+
+### Requirement: Private log events stay out of an exported bundle
+
+An OKF bundle built on a machine whose brain lives in the store SHALL NOT
+carry, in `log.md`, any log event that the store holds in its `private`
+partition, and SHALL carry the log events of the `shared` partition as it
+does today, under the content-class policy that already applies to them. A day whose every event is private SHALL NOT count as a log day
+of the bundle. A machine on the legacy layout builds `log.md` as before.
+
+#### Scenario: One private and one shared event on a switched machine
+
+- **GIVEN** a switched machine holding both partitions
+- **AND** one log event appended to the `shared` partition and one to the
+ `private` partition, on two different days
+- **WHEN** the operator runs `o2b brain okf-export`
+- **THEN** `log.md` contains the shared event's text and not the private
+ event's text
+- **AND** the manifest reads one log day
+
+#### Scenario: A record present in both partitions
+
+- **GIVEN** a switched machine where one log event's record is present in
+ both the `shared` and the `private` partition
+- **WHEN** the operator runs `o2b brain okf-export`
+- **THEN** the event is left out of `log.md`
+
+#### Scenario: An unswitched machine
+
+- **GIVEN** a machine still on the legacy layout, with log day files under
+ `Brain/log/`
+- **WHEN** the operator runs `o2b brain okf-export`
+- **THEN** `log.md` is built from the day files exactly as before
+
+### Requirement: The export names how many private log events it left out
+
+The bundle manifest SHALL state how many log events were left out for
+being private, counted before any content-class filtering, and the export
+command SHALL name that count on standard error when it is above zero,
+whatever its content-class flags.
+
+#### Scenario: One private event left out
+
+- **GIVEN** a switched machine holding both partitions, with one private
+ log event
+- **WHEN** the operator runs `o2b brain okf-export`, with or without
+ `--include-prompt-derived`
+- **THEN** the manifest reads one private log event left out
+- **AND** standard error names one private log entry left out
+
+#### Scenario: Nothing private to leave out
+
+- **GIVEN** a switched machine holding only the `shared` partition, or a
+ machine on the legacy layout
+- **WHEN** the operator runs `o2b brain okf-export`
+- **THEN** the manifest reads zero private log events left out
+- **AND** standard error names no private log entries
+
+### Requirement: An export refuses when a store log shard cannot be read
+
+On a machine whose brain lives in the store, the export SHALL refuse,
+writing no bundle, when the store cannot be opened or any log shard of a
+partition the machine holds cannot be read, and SHALL name the shard, so the bundle is never short of
+events and the private count is never a lower bound.
+
+#### Scenario: An unreadable private log shard
+
+- **GIVEN** a switched machine holding both partitions
+- **AND** a log shard of the `private` partition that cannot be read
+- **WHEN** the operator runs `o2b brain okf-export`
+- **THEN** the command fails and names the shard
+- **AND** no bundle is written
+
+#### Scenario: A store that cannot be opened
+
+- **GIVEN** a switched machine whose store no longer opens (a held
+ partition lost its identity file)
+- **WHEN** the operator runs `o2b brain okf-export`
+- **THEN** the command fails and says the store is unavailable
+- **AND** no bundle is written
diff --git a/openspec/changes/archive/2026-11-09-lane-pages-split/specs/remote-log-reads/spec.md b/openspec/changes/archive/2026-11-09-lane-pages-split/specs/remote-log-reads/spec.md
new file mode 100644
index 00000000..d4914860
--- /dev/null
+++ b/openspec/changes/archive/2026-11-09-lane-pages-split/specs/remote-log-reads/spec.md
@@ -0,0 +1,28 @@
+## Purpose
+
+What a caller below local reach (a remote MCP client) may read of the
+operational log of a machine whose brain lives in the store.
+
+## ADDED Requirements
+
+### Requirement: Private log events are withheld below local reach
+
+A reader that renders log events to a caller below local reach SHALL
+withhold every event the store holds in its `private` partition, whatever
+the event names, and SHALL show it to a local caller. A day whose every
+event is withheld SHALL read as a day with no events, the same answer a
+day that was never logged gives.
+
+#### Scenario: A remote caller reads a day with a private event
+
+- **GIVEN** a switched machine with one shared and one private log event
+ on the same day
+- **WHEN** a remote caller reads `osb://log/<that day>`
+- **THEN** the page shows the shared event and not the private one
+- **AND** a local caller reading the same day sees both
+
+#### Scenario: A remote caller reads a day with only private events
+
+- **GIVEN** a switched machine whose only log event of a day is private
+- **WHEN** a remote caller reads `osb://log/<that day>`
+- **THEN** the read fails exactly as for a day with no log events
diff --git a/openspec/changes/archive/2026-11-09-lane-pages-split/tasks.md b/openspec/changes/archive/2026-11-09-lane-pages-split/tasks.md
new file mode 100644
index 00000000..48ced238
--- /dev/null
+++ b/openspec/changes/archive/2026-11-09-lane-pages-split/tasks.md
@@ -0,0 +1,153 @@
+# Tasks: split the lane page store, and keep private log events out of OKF exports
+
+First read `openspec/project.md`, then this change folder: `proposal.md`,
+`design.md`, `specs/okf-export/spec.md`; `brainstorm.md` and `review.md`
+say why the design is what it is. Then work through this list.
+
+Work in order, one section at a time. Before a section, read its part of
+`design.md` and, for Part B, `specs/okf-export/spec.md`. Tick each box
+(`- [x]`) as soon as it is done, so an interrupted run can resume from the
+first open box. Partial edits from an earlier attempt may already be in
+the tree: review them, keep what is right, finish the rest.
+
+For every behaviour: write the failing test first, run it and see it
+fail, then write the code. Part A changes no behaviour, so it adds no
+test: the existing suite is its proof.
+
+## Environment and rules
+
+Work only in this checkout. Set this in every shell before any `bun`
+command:
+
+```sh
+export TMPDIR=$HOME/.cache/osb-lane-pages-split-tmp
+mkdir -p "$TMPDIR"
+```
+
+Never read or write the real `~/.config/open-second-brain`, any real
+vault, or the real `~/.local/state/open-second-brain`; tests get temp
+directories from the test preload. Never stop a process you did not
+start. Do not commit, push or open a pull request. Do not start
+subagents. English only in code and comments, no exclamation marks, and
+the product is written "Open Second Brain" in full.
+
+During a section run only the tests it names
+(`bun test <file> [-t <name>]`). The whole gate runs once, in section 4.
+
+Change nothing this list does not ask for. When the code does not match
+what `design.md` or this list says (a name, a line, a signature), stop at
+that task and explain the mismatch in the report instead of improvising.
+
+## 0. Preconditions
+
+- [x] 0.1 Confirm the tree: `git log --oneline -1` shows the commit
+ "feat(store): migration, vault-free mode and the minimal human view
+ (#292)" (or a later main), and `wc -l src/core/store/lane-pages.ts`
+ prints a number above 700. Run
+ `bun test tests/core/lanes tests/core/store tests/core/brain/store-only tests/core/brain/portability tests/core/architecture tests/mcp/lane-tools-no-vault.test.ts`
+ and note the pass and fail counts as the baseline for Part A
+ (everything should pass; if anything fails here, stop and report it).
+ `tests/core/architecture/write-site-census.test.ts` pins the files that
+ write; it must keep passing unchanged through Part A (see 1.3).
+
+# Part A: the split (D1)
+
+## 1. Move the store side
+
+- [x] 1.1 Create `src/core/store/lane-entry-store.ts` with a short header
+ comment, and move into it verbatim, with their doc comments, every
+ function and constant D1 lists (items 1 to 3, `lanePagesInStore`
+ included). Export the ones `lane-pages.ts` still calls; keep the rest
+ module-private.
+- [x] 1.2 In `lane-pages.ts` delete the moved code, import what it calls
+ from `./lane-entry-store.ts`, and re-export `lanePagesInStore`,
+ `laneEntryClockMs` and `laneEntryInPrivate`. Remove only the imports
+ the compiler reports unused (`statSync` and `existsSync` stay).
+ `lane-entry-store.ts` must not import `lane-pages.ts`.
+- [x] 1.3 Check: `bunx tsc --noEmit -p .` is clean; `wc -l` shows both
+ files under 700 lines; `git diff --stat` touches only these two files;
+ `bun run lint` and `bun run fmt:check` are clean (run `bun run fmt` to
+ fix formatting). Rerun the baseline tests of 0.1: same counts. The
+ write-site census must pass unchanged (design, Risks): if it fails,
+ undo the move that broke it instead of editing the census.
+
+# Part B: private log events (D2, spec `okf-export`)
+
+## 2. The partition of a log event, read once
+
+- [x] 2.1 Test first, in a new
+ `tests/core/store/log-events-partition.test.ts` (copy the switched
+ machine setup of `tests/core/brain/portability/okf-store-only.test.ts`;
+ `appendLogEvent` is in `src/core/brain/log.ts`): an event appended
+ inside `withOperationPrivacy(true, …)` reads back from
+ `readStoreLogEventsReport` with `partition: "private"`, one appended
+ outside it with `partition: "shared"`; a record whose JSONL line is
+ copied into the other partition's shard (same record id in both) reads
+ back once, as `private`; `readStoreLogEvents` returns the same events
+ as the report; on an unswitched vault the report is `null`.
+- [x] 2.2 Implement D2 item 1 (`partition`, private wins,
+ `readStoreLogEventsReport`, `readStoreLogEvents` delegating).
+- [x] 2.3 Implement D2 item 2: export `WHOLE_LOG` and add `groupLogDays`
+ in `src/core/brain/log-days.ts`. Verify: `bun test tests/core/brain/log-days.test.ts`
+ passes unchanged.
+
+## 3. The export
+
+- [x] 3.1 Tests first, in
+ `tests/core/brain/portability/okf-store-only.test.ts`, on a switched
+ machine: (a) one shared and one private event on two days:
+ `buildOkfBundle(vault)` gives `log.md` with the shared text and without
+ the private text, `manifest.log_days` 1 and
+ `manifest.log_private_omitted` 1; (b) a machine holding only `shared`
+ (`neverHeld` from `tests/helpers/held-partitions.ts`):
+ `log_private_omitted` 0; (c) a private log shard made unreadable
+ (`chmod 000`, the test under `test.skipIf(CHMOD_CANNOT_DENY)` from
+ `tests/helpers/platform.ts`, the mode restored in `finally`):
+ `buildOkfBundle` throws an error naming the shard; (d) the duplicate
+ record of 2.1: left out of `log.md` and counted.
+- [x] 3.2 Test first, in `tests/core/brain/portability/okf.test.ts`: an
+ unswitched vault with log day files gives `log_private_omitted` 0 and
+ the same `log.md` as before; a manifest without `log_private_omitted`
+ parses with the value 0 (add a case to the existing manifest parse
+ test).
+- [x] 3.3 Tests first, in `tests/cli/okf-cli.test.ts`, on a switched
+ machine with one private event: the verb's standard error contains
+ `left 1 private log entry out of log.md`, both without and with
+ `--include-prompt-derived`; the written `okf.json` carries
+ `"log_private_omitted": 1` (this proves the count survives
+ `buildOkfBundleFromPages`); with an unreadable private log shard the
+ verb exits non-zero and writes no bundle.
+- [x] 3.4 Implement D2 items 3 to 5: `buildLog`, `OkfLog.privateEntries`,
+ the manifest field in every place D2 item 4 names (the two `Pick`
+ types, `assembleOkfBundle`, `ManifestInput`, the parser,
+ `readSpecOkfBundle`), and the notice in `okf-export.ts` outside the
+ `--include-prompt-derived` branch.
+- [x] 3.5 Check: the tests of 2 and 3 pass, `bunx tsc --noEmit -p .` is
+ clean, and `wc -l` shows every changed source file under 700 lines (if
+ a file was already above 700 before this change, as `okf.ts` is, say so
+ in the report and add no more than the change needs).
+
+## 4. The gate
+
+- [x] 4.1 Run the whole gate from `openspec/project.md` ("The local
+ gate"), each command on its own. All must pass. Then rebuild the
+ OpenClaw bundle (`bunx [email protected] run build:openclaw`) and note whether
+ `openclaw/index.js` changed (`git diff --stat openclaw/index.js`); keep
+ the rebuilt file.
+- [x] 4.2 In `openspec/changes/brain-store-and-topics/tasks.md`, append
+ to the text of tasks 3.13 and 3.14 the sentence
+ "Done in change `lane-pages-split`." and tick both boxes.
+
+## 5. Report
+
+- [x] 5.1 Finish with a report of at most 40 lines: every box ticked or why not; the
+ line counts of `lane-pages.ts` and `lane-entry-store.ts`; every function
+ that needed more than a verbatim move and why; the test counts of the
+ gate; whether `openclaw/index.js` changed; anything in this brief that
+ did not match the code.
+
+## Workflow follow-up
+
+- Independent code review rounds of the result, fixes re-reviewed.
+- Archive the change (`openspec archive lane-pages-split --yes`) inside its
+ pull request, after the whole cycle is green.
diff --git a/openspec/changes/brain-store-and-topics/tasks.md b/openspec/changes/brain-store-and-topics/tasks.md
index 5b6e8406..d79612a7 100644
--- a/openspec/changes/brain-store-and-topics/tasks.md
+++ b/openspec/changes/brain-store-and-topics/tasks.md
@@ -87,10 +87,11 @@ Phases follow design.md D13. Each phase ends in its own release PR, and the vers
- [ ] 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`.
- [ ] 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.
-- [ ] 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.
-- [ ] 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.
+- [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`.
- [ ] 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.
- [ ] 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.
+- [ ] 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.
- [ ] 3.7 Integration. Run the full gate on Linux and Windows. Then the owner checks topics by hand on two machines and in a phone view, including a phone edit. Then open the release PR.
## 4. Phase 4: decision-model uses and agent context
diff --git a/openspec/config.yaml b/openspec/config.yaml
index b22e64f3..e2d33a10 100644
--- a/openspec/config.yaml
+++ b/openspec/config.yaml
@@ -1,32 +1,6 @@
-schema: jeex
+schema: osb
-# Project context (optional)
-# Add only constraints that should guide OpenSpec artifacts and workflows.
-# Include constraints an agent cannot infer by reading the code.
-# Keep general project documentation and discoverable codebase facts out.
-# Example:
-# context: |
-# Designs and tasks must cover Windows, macOS, and Linux
-# Write all artifacts in Spanish
-
-# Per-artifact rules (optional)
-# Add custom rules for specific artifacts.
-# Example:
-# rules:
-# proposal:
-# - Keep proposals under 500 words
-# - Always state what is out of scope
-# tasks:
-# - Break tasks into chunks of max 2 hours
-
-# Per-operation guidance (optional)
-# Add advisory guidance for how apply and archive work should be conducted.
-# This is separate from artifact rules above.
-# Example:
-# operations:
-# apply:
-# guidance:
-# - Keep test summaries concise
-# archive:
-# guidance:
-# - Summarize the archive outcome before finishing
+context: |
+ Read openspec/project.md first: it holds the conventions every change in
+ this repository follows (one change per pull request, archived inside
+ that pull request, test first, English only, the local gate).
diff --git a/openspec/project.md b/openspec/project.md
new file mode 100644
index 00000000..ab3109fe
--- /dev/null
+++ b/openspec/project.md
@@ -0,0 +1,59 @@
+# Project: Open Second Brain
+
+A local-first memory layer for coding agents: a Bun and TypeScript CLI
+(`o2b`), an MCP server, agent plugins (Claude Code, Codex, Hermes,
+OpenClaw) and skills. `CLAUDE.md` and `AGENTS.md` at the repository root
+are the map of versioning, plugin mirrors and gates; read them before any
+change.
+
+This `openspec/` directory is committed with the code. Changes use the
+project schema `osb` (`openspec/schemas/osb/`): brainstorm with an
+independent agent, proposal, specs, design, tasks, independent review of
+the artifacts, then apply. `tasks.md` is a self-contained brief for the
+agent that implements the change, which may be a different agent than
+the author; implementation starts only on the review's "Ready for
+implementation: yes". Each change maps to one pull request. Before the
+pull request of a change is pushed, the change is archived (`openspec archive <change> --yes`) and the archive and
+the updated `openspec/specs/` ship in that pull request, so
+`openspec/specs/` always describes main. The multi-phase change
+`brain-store-and-topics` predates these rules: it keeps the schema it was
+written with and is archived once all its phases are released; its
+remaining tasks move into changes of their own.
+
+Conventions that apply to every change here:
+
+1. English only in code, docs, comments and commit messages. No
+ exclamation marks in docs. The product is written "Open Second Brain"
+ in full, never abbreviated, in anything public.
+2. Test first: write the failing test, run it and see it fail, then the
+ code. A test proves behaviour through public seams; no test-only
+ production seams beyond the existing hook patterns.
+3. Never read or write the real user state in tests: not
+ `~/.config/open-second-brain/config.yaml`, not `~/vault`, not the real
+ `~/.local/state/open-second-brain`. Tests get temp directories (the
+ preload in `tests/` isolates the state dirs).
+4. No personal settings in the repository: no machine paths, host names,
+ model preferences or account names in code, docs, examples or tests.
+5. Every path must work on Linux, macOS and Windows (path separators,
+ locks, fsync, case folding). CI runs the suite on Windows.
+6. Source files stay under 700 lines; split a module before it grows past
+ that.
+7. Version bumps: `package.json` only, then `bun run scripts/sync-version.ts`,
+ inside the pull request that ships the release (see `CLAUDE.md`).
+8. After changing a skill or `hooks/hooks.json`, run
+ `bun run sync-plugin-mirrors`; never edit the mirrored copies.
+
+The local gate, run before a change is called done:
+
+```sh
+bun run test
+bunx tsc --noEmit -p .
+bun run lint
+bun run fmt:check
+bun run check:paths
+bun run sync-plugin-mirrors:check
+bun run scripts/sync-version.ts --check
+```
+
+When `src/` code that the OpenClaw bundle includes changes, rebuild it with
+`bunx [email protected] run build:openclaw` and commit `openclaw/index.js`.
diff --git a/openspec/schemas/osb/schema.yaml b/openspec/schemas/osb/schema.yaml
new file mode 100644
index 00000000..94f62c6e
--- /dev/null
+++ b/openspec/schemas/osb/schema.yaml
@@ -0,0 +1,362 @@
+name: osb
+version: 1
+description: Open Second Brain workflow - brainstorm with an independent agent,
+ proposal, specs, design, tasks as an executor brief, independent review,
+ apply; one change per pull request, archived inside it
+artifacts:
+ - id: brainstorm
+ generates: brainstorm.md
+ description: Joint brainstorm of the change with an independent second agent,
+ before any proposal
+ template: brainstorm.md
+ instruction: |
+ Find the best way to build this change TOGETHER with an independent
+ second agent before writing the proposal. The partner is an agent of a
+ different model family than the author, run read-only; when none is
+ available, a fresh agent of the author's family that has seen nothing of
+ the draft. Name the kind of partner (not a product or account) in the
+ Process section.
+
+ Before the brainstorm, check related work: open pull requests, changes
+ in flight under `openspec/changes/`, and recent commits touching the same
+ modules. The result goes into the "Related work" section.
+
+ Procedure:
+ 1. Write your own short understanding of the problem and 2-3 candidate
+ approaches into a brief, plus the constraints that bind
+ (`openspec/project.md`) and the question: "propose the best approach,
+ attack mine, list what we have not thought of". List your concrete
+ doubts explicitly (edge cases, error output, exit codes, boundaries,
+ privacy leaks, Windows paths): the partner is most useful on them.
+ Never put secrets into a brief.
+ 2. Run the partner read-only; it reads the code itself.
+ 3. Merge: take the best ideas from both, resolve disagreements by
+ evidence from the code. At most two rounds with the partner; a third
+ disagreement goes to Open questions.
+ 4. Open questions for the owner only when the brainstorm could not answer
+ them AND the answer changes the product, the specs, the approach or
+ the task breakdown. Everything else is decided here with the reason.
+
+ A change that only carries follow-ups already decided elsewhere (review
+ findings, a parent change's queued tasks) keeps the brainstorm short:
+ name where each was decided, and let the partner attack the approach.
+
+ Write it neutrally (the repository is public): approaches, evidence,
+ decision, rejected alternatives with one-line reasons. No machine paths,
+ host or session names, account names or internal tool names.
+ requires: []
+
+ - id: proposal
+ generates: proposal.md
+ description: Initial proposal document outlining the change
+ template: proposal.md
+ instruction: |
+ Create the proposal document that establishes WHY this change is needed.
+
+ Sections:
+ - **Why**: 1-2 sentences on the problem or opportunity. What problem does this solve? Why now?
+ - **What Changes**: Bullet list of changes. Be specific about new capabilities, modifications, or removals. Mark breaking changes with **BREAKING**.
+ - **Capabilities**: Identify which specs will be created or modified:
+ - **New Capabilities**: List capabilities being introduced. Each becomes a new `specs/<capability-path>/spec.md`. Name each capability for a durable system behavior (for example, `user-auth`), not the work in this change (for example, `add-login-endpoint`). Choose a cohesive boundary that can own related requirements as the system evolves; avoid broad catch-all capabilities. Use kebab-case for path segments you introduce (e.g., `user-auth` or `identity/user-auth`) and follow the project's existing spec organization.
+ - **Modified Capabilities**: List existing capabilities whose REQUIREMENTS are changing. Only include if spec-level behavior changes (not just implementation details). Each needs a delta spec file. Use the exact existing path under `openspec/specs/`. Leave empty if no requirement changes.
+ - **Impact**: Affected code, APIs, dependencies, or systems.
+
+ IMPORTANT: The Capabilities section is critical. It creates the contract between
+ proposal and specs phases. Research existing specs before filling this in:
+ run `openspec list --specs` for the project's capability inventory, then
+ `openspec show "<spec-id>" --type spec --json --no-scenarios` for any that
+ look related - that returns a capability's purpose and requirement texts
+ without pulling whole spec files into context. Append `--store "<id>"` to
+ both commands only for a registered standalone store, and keep `--type
+ spec`: a change and a spec sharing a name is otherwise an ambiguous-item
+ error. `openspec list` without `--specs` lists in-flight changes, not
+ specs - it never shows what the project already covers. Reuse an existing
+ capability's exact path instead of introducing a near-duplicate name.
+ The filtered read is only an overview. Before deciding what is already
+ covered or what should change, read each relevant spec in full, including
+ scenarios, with `openspec show "<spec-id>" --type spec` (same `--store` rule).
+ Each capability listed here will need a corresponding spec file.
+
+ Every change must either declare at least one capability (new or
+ modified) or explicitly opt out of specs: `openspec validate` rejects a
+ change with zero deltas unless the change's `.openspec.yaml` sets
+ `skip_specs: true`. Use `skip_specs: true` only when no spec-level
+ behavior changes (pure refactor, tooling, docs) - specs describe
+ behavior, so if behavior does not change, no spec should change either.
+ Do not invent a requirement just to satisfy validation.
+
+ Keep it concise (1-2 pages). Focus on the "why" not the "how" -
+ implementation details belong in design.md.
+
+ Build on brainstorm.md: the chosen approach and its reasons are the
+ basis; do not reopen what the brainstorm decided without new evidence.
+
+ This is the foundation - specs, design, and tasks all build on this.
+ requires:
+ - brainstorm
+
+ - id: specs
+ generates: "specs/**/*.md"
+ description: Detailed specifications for the change
+ template: spec.md
+ instruction: |
+ Create specification files that define WHAT the system should do.
+
+ A spec is a behavior contract, not an implementation plan.
+
+ Good spec content:
+ - Observable behavior users or downstream systems rely on
+ - Inputs, outputs, and error conditions
+ - External constraints (security, privacy, reliability, compatibility)
+ - Scenarios that can be tested or explicitly validated
+
+ Avoid in specs:
+ - Internal class/function names
+ - Library or framework choices
+ - Step-by-step implementation details
+ - Detailed execution plans (those belong in design.md or tasks.md)
+
+ Quick test: if the implementation can change without changing externally
+ visible behavior, it likely does not belong in the spec.
+
+ Create one spec file per capability listed in the proposal's Capabilities section.
+ `<capability-path>` is the spec directory relative to `specs/` (for example,
+ `user-auth` or `identity/user-auth`). Preserve the full path:
+ - New capabilities: use the exact path from the proposal at `specs/<capability-path>/spec.md`. Any path segment newly introduced in the proposal must be kebab-case. Follow the project's existing organization; do not add a new domain level when the project uses a flat layout.
+ - Modified capabilities: use the exact existing path from `openspec/specs/<capability-path>/` when creating the delta at `specs/<capability-path>/spec.md`. Run `openspec list --specs` to confirm that path before writing the delta, appending `--store "<id>"` only for a registered standalone store - a mistyped or invented path targets a capability that does not exist rather than the one you meant. Do not move or rename the capability.
+
+ Write the spec files one at a time, so the user sees progress and an
+ interrupted run keeps the files it already wrote:
+ - Before writing anything, compare the capabilities the proposal lists
+ with the `specs/<capability-path>/spec.md` files that already exist,
+ and start with the first capability that has no file. Do not rewrite
+ an existing file unless the user asks you to.
+ - Before each file, say in one line which capability you are writing.
+ - Write each file as soon as you have drafted it. Do not plan every file
+ before writing the first.
+ - Stop when every capability the proposal lists has its file.
+
+ There must be at least one spec file unless the change's `.openspec.yaml`
+ sets `skip_specs: true` (no spec-level behavior change) - `openspec validate`
+ rejects a zero-delta change without that marker. If the proposal lists no
+ capabilities and `skip_specs` is not set, revisit the proposal first.
+
+ Delta operations (use ## headers):
+ - **ADDED Requirements**: New capabilities
+ - **MODIFIED Requirements**: Changed behavior - MUST include full updated content
+ - **REMOVED Requirements**: Deprecated features - MUST include **Reason** and **Migration**
+ - **RENAMED Requirements**: Name changes only - use FROM:/TO: format
+
+ Format requirements:
+ - Each requirement: `### Requirement: <name>` followed by description
+ - Use SHALL/MUST for normative requirements (avoid should/may)
+ - Each scenario: `#### Scenario: <name>` with WHEN/THEN format
+ - **CRITICAL**: Scenarios MUST use exactly 4 hashtags (`####`). Using 3 hashtags or bullets will fail silently.
+ - Every requirement MUST have at least one scenario.
+ - Keep each requirement's description (the text between `### Requirement:` and its first scenario) to 500 characters or fewer. `openspec validate` flags longer descriptions in ADDED requirements and in the main spec. This is a warning: normal validation still passes, but `openspec validate --strict` fails on it. When writing a new requirement, state one behavior per requirement: move examples and edge cases into scenarios, and split a requirement that covers several behaviors into separate `### Requirement:` blocks, each with its own scenarios. Under MODIFIED, keep the existing requirement block whole; never split, trim or rewrite existing text just to meet the length. Split an existing long requirement only when the user asks for it, in a change made for that purpose: under MODIFIED, keep its header and every scenario and cut its description down to one behavior without changing its meaning, then add each behavior you removed as its own ADDED requirement with its own scenarios.
+
+ New capabilities only: the delta spec's first section is `## Purpose` -
+ one or two sentences (50+ characters, or `openspec validate --strict`
+ reports it as too brief) describing what the capability is for. Archive
+ copies it into the main spec it creates; without it the new main spec is
+ left with a `TBD ... Update Purpose after archive` placeholder to fill in
+ by hand. Do NOT add `## Purpose` to a delta for an existing capability -
+ that spec already has one and the delta's is ignored. To change an
+ existing capability's Purpose - including a leftover `TBD` placeholder -
+ edit `<planningHome.root>/openspec/specs/<capability-path>/spec.md`
+ directly. `planningHome.root` comes from the `openspec instructions ...
+ --json` response. Always use it rather than a repo-relative path: it
+ resolves to the store whenever the change lives in one - whether that
+ came from `--store`, a project `store:` pointer, or a global default
+ store - and to the current repository otherwise. Do not try to work out
+ which case applies; the field already has.
+
+ MODIFIED requirements workflow:
+ 1. Locate the existing requirement in `<planningHome.root>/openspec/specs/<capability-path>/spec.md` (the same store-aware root as above)
+ 2. Copy the ENTIRE requirement block (from `### Requirement:` through all scenarios)
+ 3. Paste under `## MODIFIED Requirements` and edit to reflect new behavior
+ 4. Ensure header text matches exactly (whitespace-insensitive)
+
+ Common pitfall: Using MODIFIED with partial content loses detail at archive time.
+ If adding new concerns without changing existing behavior, use ADDED instead.
+
+ Example (a new capability, so its first section is `## Purpose`):
+ ```
+ # Spec Delta
+
+ ## Purpose
+
+ Lets users take their data out of the product in a portable format.
+
+ ## ADDED Requirements
+
+ ### Requirement: User can export data
+ The system SHALL allow users to export their data in CSV format.
+
+ #### Scenario: Successful export
+ - **WHEN** user clicks "Export" button
+ - **THEN** system downloads a CSV file with all user data
+
+ ## REMOVED Requirements
+
+ ### Requirement: Legacy export
+ **Reason**: Replaced by new export system
+ **Migration**: Use new export endpoint at /api/v2/export
+ ```
+
+ Specs should be testable - each scenario is a potential test case.
+ requires:
+ - proposal
+
+ - id: design
+ generates: design.md
+ description: Technical design document with implementation details
+ template: design.md
+ instruction: |
+ Create the design document that explains HOW to implement the change.
+
+ When to include design.md (create only if any apply):
+ - Cross-cutting change (multiple services/modules) or new architectural pattern
+ - New external dependency or significant data model changes
+ - Security, performance, or migration complexity
+ - Ambiguity that benefits from technical decisions before coding
+
+ Sections:
+ - **Context**: Only the current state and constraints needed to explain the approach. Reference the proposal for motivation instead of restating it (e.g., "See proposal.md - Why").
+ - **Goals / Non-Goals**: What this design achieves and explicitly excludes. Don't restate the proposal's scope - add only design-level boundaries.
+ - **Decisions**: Key technical choices with rationale (why X over Y?). Include alternatives considered for each decision.
+ - **Risks / Trade-offs**: Known limitations, things that could go wrong. Format: [Risk] → Mitigation
+ - **Migration Plan**: Steps to deploy, rollback strategy (if applicable)
+ - **Open Questions**: Unknowns that can safely be answered later without
+ changing the specs, the approach, or the task breakdown. Omit if none.
+
+ Open questions are for genuinely deferrable unknowns, not decisions you
+ skipped. If a question would change the specs, the chosen approach, or
+ the task breakdown, resolve it now - ask the user instead of guessing.
+
+ Focus on architecture and approach, not line-by-line implementation.
+ The proposal covers why and what; design covers how. Reference the
+ proposal for motivation and, once written, the specs for requirements -
+ if a section would only restate them, point to them instead.
+
+ Good design docs explain the "why" behind technical decisions.
+ requires:
+ - proposal
+
+ - id: tasks
+ generates: tasks.md
+ description: Implementation checklist with trackable tasks
+ template: tasks.md
+ instruction: |
+ Create the task list. It is a self-contained brief for the agent that
+ implements the change, who may be a different agent with no other
+ context than this change folder and the repository: everything it needs
+ to know is here or in a file this list names.
+
+ Before writing tasks, check design.md for Open Questions. If any of them
+ would change what gets built, resolve them with the user first - do not
+ bake an unstated assumption into the task list.
+
+ **IMPORTANT: Follow the template below for tracked tasks.** The apply
+ phase parses checkbox format to track progress. A box holding only `x`
+ counts as done, upper or lower case and with any spacing. Every other
+ marker, including `- [~]`, `- [-]` and an empty `- []`, reads as
+ unfinished. A line with no checkbox is not tracked at all.
+
+ The executor is started with one line naming this file; nothing the
+ executor needs may live only in that launch prompt.
+
+ Structure:
+ - An opening paragraph: which artifacts to read first (project.md,
+ then the change folder); work in order, one section at a time; read the
+ design section and spec delta a section names before it; tick each box
+ as soon as it is done, so an interrupted run resumes from the first
+ open box; partial edits from an earlier attempt may be in the tree:
+ review them, keep what is right, finish the rest; change nothing
+ the list does not ask for, and on a mismatch between the brief and
+ the code stop at that task and report it.
+ - `## Environment and rules`: the shell setup (a temp dir outside the
+ checkout), and the executor rules: work only in this checkout; never
+ read or write real user state (config, vaults, state dirs); never stop
+ a process you did not start; do not commit, push or open a pull
+ request; do not start subagents; the language and naming rules of
+ `openspec/project.md`. Say which tests to run during a section (only
+ the files it touches) and that the whole gate runs once at the end.
+ - `## 0. Preconditions`: confirm the tree the change was written against
+ (the commit, the sizes or names the design relies on) and take a
+ baseline of the tests the change touches; stop and report when it
+ does not match.
+ - Numbered groups in dependency order. Long changes split into Parts
+ (`# Part A: ...`), each built and passing its own tests before the
+ next starts.
+ - A gate group: the full local gate of `openspec/project.md`, each
+ command on its own, plus any generated artifact the project commits
+ (bundles, mirrors).
+ - A last group `Report`: what the executor reports back (every box
+ ticked or why not, deviations from design.md and why, gate counts,
+ anything in the brief that did not match the code).
+
+ Guidelines:
+ - Each tracked task MUST be a checkbox: `- [ ] X.Y Task description`.
+ - Each task MUST state how to verify completion (a test, command,
+ observable behavior, or delivered artifact) in its own description.
+ - Test first: for every behaviour the task writes the failing test, runs
+ it and sees it fail, then the code. Name the test file (an existing one
+ by path, or the path of a new one) and the cases. A refactor that
+ changes no behaviour adds no test: the existing suite is its proof.
+ - Each task group lands the tests and documentation its own work calls
+ for. Do NOT collect testing or documentation into a final group.
+ - Name every file, function and command by its real name, checked
+ against the tree; never "find the relevant file" when you can name it.
+ - Track only work that can be completed before archive. Archive and
+ integration steps (review, pull request) go as plain bullets into an
+ optional `## Workflow follow-up` section at the end.
+
+ Reference specs for what needs to be built, design for how to build it.
+ requires:
+ - specs
+
+ - id: review
+ generates: review.md
+ description: Independent review of all artifacts before implementation starts
+ template: review.md
+ instruction: |
+ The artifacts are reviewed by an independent second agent before any
+ implementation starts, not by the owner: an agent of a different model
+ family than the author, or, when none is available, a fresh agent that
+ did not write the artifacts. Name the kind of reviewer. Brief it with the
+ change folder path and ask it to check: the proposal solves the stated
+ problem; specs are testable and complete (edge cases, errors,
+ compatibility, privacy, Windows); design decisions are sound for this
+ codebase and every name in them exists in the tree; tasks cover every
+ requirement with a verification, land tests with the work, and are a
+ complete brief for an executor with no other context; nothing
+ contradicts `openspec/project.md` or the brainstorm decision; scope
+ creep.
+
+ Record each finding with a verdict: fixed (artifact updated), rejected
+ (one-line reason). After fixes, one re-review round at most. Findings
+ still disputed after it, and only those that significantly change the
+ product or the development path, go to "Questions for the owner".
+ After the re-review the author decides the verdict on what is left:
+ each remaining finding is fixed or rejected with its reason and named
+ in the Findings list.
+
+ End with the verdict line: "Ready for implementation: yes" or "no" with
+ what blocks. Implementation starts only on "yes" and only with every
+ question for the owner answered.
+ requires:
+ - tasks
+
+apply:
+ requires: [ review ]
+ tracks: tasks.md
+ instruction: |
+ Read the change folder, then work through tasks.md as written: it is
+ the executor brief. Work in a worktree off a fresh main, one change per
+ pull request. When all tasks are done, the integrator runs the
+ project's full quality cycle (the local gate, the independent code
+ review rounds, the security review). Archive the change
+ (`openspec archive <change> --yes`) only after the whole cycle is
+ green, so the pull request carries the archived change and the updated
+ `openspec/specs/`.
diff --git a/openspec/schemas/osb/templates/brainstorm.md b/openspec/schemas/osb/templates/brainstorm.md
new file mode 100644
index 00000000..549ba1a2
--- /dev/null
+++ b/openspec/schemas/osb/templates/brainstorm.md
@@ -0,0 +1,33 @@
+# Brainstorm
+
+## Problem
+
+<!-- What the change must achieve, in 2-4 sentences -->
+
+## Related work
+
+<!-- Work in flight elsewhere that touches this change, open PRs, recent changes; "none found" is a valid answer -->
+
+## Doubts
+
+<!-- Concrete doubts put to the partner: edge cases, error output, exit codes, boundaries, leaks -->
+
+## Approaches considered
+
+<!-- Each approach: idea, evidence from the code, cost, risks. Mark whose idea it was: author or partner -->
+
+## Decision
+
+<!-- The chosen approach and why it beats the others -->
+
+## Rejected
+
+<!-- One line per rejected alternative with the reason -->
+
+## Open questions
+
+<!-- Only questions the brainstorm could not answer AND that change the product, the specs, the approach or the tasks. Omit if none -->
+
+## Process
+
+<!-- Partner used, rounds, anything that limited the brainstorm -->
diff --git a/openspec/schemas/osb/templates/design.md b/openspec/schemas/osb/templates/design.md
new file mode 100644
index 00000000..dc6ca739
--- /dev/null
+++ b/openspec/schemas/osb/templates/design.md
@@ -0,0 +1,21 @@
+# Design
+
+## Context
+
+<!-- Current state and constraints that shape the approach. See proposal.md for motivation - don't restate it -->
+
+## Goals / Non-Goals
+
+**Goals:**
+<!-- What this design aims to achieve -->
+
+**Non-Goals:**
+<!-- What is explicitly out of scope -->
+
+## Decisions
+
+<!-- Key design decisions with rationale and alternatives considered -->
+
+## Risks / Trade-offs
+
+<!-- Known risks and trade-offs -->
diff --git a/openspec/schemas/osb/templates/proposal.md b/openspec/schemas/osb/templates/proposal.md
new file mode 100644
index 00000000..230036b6
--- /dev/null
+++ b/openspec/schemas/osb/templates/proposal.md
@@ -0,0 +1,34 @@
+# Proposal
+
+## Why
+
+<!-- Explain the motivation for this change. What problem does this solve? Why now? -->
+
+## What Changes
+
+<!-- Describe what will change. Be specific about new capabilities, modifications, or removals. -->
+
+## Capabilities
+
+### New Capabilities
+<!-- Capabilities being introduced. Name each capability for a cohesive system
+ behavior that can own related requirements as the system evolves. Do not name
+ implementation tasks or proposal sections. Avoid broad catch-all names. Use
+ kebab-case for path segments you introduce (e.g., user-auth or identity/user-auth)
+ that follow the project's existing spec organization. Each creates
+ specs/<capability-path>/spec.md. -->
+- `<capability-path>`: <brief description of what this capability covers>
+
+### Modified Capabilities
+<!-- Existing capabilities whose REQUIREMENTS are changing (not just implementation).
+ Only list here if spec-level behavior changes. Each needs a delta spec file.
+ Use the exact existing path under openspec/specs/. Leave empty if no requirement
+ changes. A change with no capabilities at all (pure refactor, tooling, docs)
+ must set `skip_specs: true` in its .openspec.yaml - openspec validate rejects
+ a zero-delta change without that marker. Do not invent a requirement just to
+ satisfy validation. -->
+- `<existing-capability-path>`: <what requirement is changing>
+
+## Impact
+
+<!-- Affected code, APIs, dependencies, systems -->
diff --git a/openspec/schemas/osb/templates/review.md b/openspec/schemas/osb/templates/review.md
new file mode 100644
index 00000000..16c24d83
--- /dev/null
+++ b/openspec/schemas/osb/templates/review.md
@@ -0,0 +1,17 @@
+# Independent review
+
+## Reviewer
+
+<!-- Who reviewed (an agent that did not write the artifacts), rounds -->
+
+## Findings
+
+<!-- One line per finding: artifact, finding, verdict (fixed | rejected: reason) -->
+
+## Questions for the owner
+
+<!-- Only disputed findings that significantly change the product or the development path. Omit if none -->
+
+## Verdict
+
+Ready for implementation: <!-- yes | no: what blocks -->
diff --git a/openspec/schemas/osb/templates/spec.md b/openspec/schemas/osb/templates/spec.md
new file mode 100644
index 00000000..da747506
--- /dev/null
+++ b/openspec/schemas/osb/templates/spec.md
@@ -0,0 +1,13 @@
+# Spec Delta
+
+## Purpose
+<!-- New capabilities only: one or two sentences (50+ characters) on what this capability is for. Delete this section for an existing capability. -->
+
+## ADDED Requirements
+
+### Requirement: <!-- requirement name -->
+<!-- requirement text -->
+
+#### Scenario: <!-- scenario name -->
+- **WHEN** <!-- condition -->
+- **THEN** <!-- expected outcome -->
diff --git a/openspec/schemas/osb/templates/tasks.md b/openspec/schemas/osb/templates/tasks.md
new file mode 100644
index 00000000..06c25a88
--- /dev/null
+++ b/openspec/schemas/osb/templates/tasks.md
@@ -0,0 +1,34 @@
+# Tasks: <!-- change title -->
+
+Work in order, one section at a time. Before a section, read its part of
+`design.md` and the spec delta it names. Tick each box (`- [x]`) as soon
+as it is done, so an interrupted run can resume from the first open box.
+Partial edits from an earlier attempt may already be in the tree: review
+them, keep what is right, finish the rest.
+
+For every behaviour: write the failing test first, run it and see it
+fail, then write the code.
+
+## Environment and rules
+
+<!-- Shell setup (temp dir outside the checkout), executor rules (this checkout only; no real user state; no commit, push or pull request; no subagents; language rules), which tests to run during a section -->
+
+## 0. Preconditions
+
+- [ ] 0.1 <!-- Confirm the tree and take the test baseline; stop and report on a mismatch -->
+
+## 1. <!-- Task group -->
+
+- [ ] 1.1 <!-- Test first: file, cases; then the code; how it is verified -->
+
+## N. The gate
+
+- [ ] N.1 <!-- The full local gate of openspec/project.md, each command on its own, plus generated artifacts -->
+
+## N+1. Report
+
+- [ ] N+1.1 <!-- What the executor reports back -->
+
+## Workflow follow-up
+
+- Independent code review rounds, then archive the change inside its pull request.
diff --git a/openspec/specs/okf-export/spec.md b/openspec/specs/okf-export/spec.md
new file mode 100644
index 00000000..372c3802
--- /dev/null
+++ b/openspec/specs/okf-export/spec.md
@@ -0,0 +1,86 @@
+# okf-export Specification
+
+## Purpose
+What an Open Knowledge Format bundle written by `o2b brain okf-export`
+carries out of the machine, and what it must leave behind.
+
+## Requirements
+
+### Requirement: Private log events stay out of an exported bundle
+
+An OKF bundle built on a machine whose brain lives in the store SHALL NOT
+carry, in `log.md`, any log event that the store holds in its `private`
+partition, and SHALL carry the log events of the `shared` partition as it
+does today, under the content-class policy that already applies to them. A day whose every event is private SHALL NOT count as a log day
+of the bundle. A machine on the legacy layout builds `log.md` as before.
+
+#### Scenario: One private and one shared event on a switched machine
+
+- **GIVEN** a switched machine holding both partitions
+- **AND** one log event appended to the `shared` partition and one to the
+ `private` partition, on two different days
+- **WHEN** the operator runs `o2b brain okf-export`
+- **THEN** `log.md` contains the shared event's text and not the private
+ event's text
+- **AND** the manifest reads one log day
+
+#### Scenario: A record present in both partitions
+
+- **GIVEN** a switched machine where one log event's record is present in
+ both the `shared` and the `private` partition
+- **WHEN** the operator runs `o2b brain okf-export`
+- **THEN** the event is left out of `log.md`
+
+#### Scenario: An unswitched machine
+
+- **GIVEN** a machine still on the legacy layout, with log day files under
+ `Brain/log/`
+- **WHEN** the operator runs `o2b brain okf-export`
+- **THEN** `log.md` is built from the day files exactly as before
+
+### Requirement: The export names how many private log events it left out
+
+The bundle manifest SHALL state how many log events were left out for
+being private, counted before any content-class filtering, and the export
+command SHALL name that count on standard error when it is above zero,
+whatever its content-class flags.
+
+#### Scenario: One private event left out
+
+- **GIVEN** a switched machine holding both partitions, with one private
+ log event
+- **WHEN** the operator runs `o2b brain okf-export`, with or without
+ `--include-prompt-derived`
+- **THEN** the manifest reads one private log event left out
+- **AND** standard error names one private log entry left out
+
+#### Scenario: Nothing private to leave out
+
+- **GIVEN** a switched machine holding only the `shared` partition, or a
+ machine on the legacy layout
+- **WHEN** the operator runs `o2b brain okf-export`
+- **THEN** the manifest reads zero private log events left out
+- **AND** standard error names no private log entries
+
+### Requirement: An export refuses when a store log shard cannot be read
+
+On a machine whose brain lives in the store, the export SHALL refuse,
+writing no bundle, when the store cannot be opened or any log shard of a
+partition the machine holds cannot be read, and SHALL name the shard, so the bundle is never short of
+events and the private count is never a lower bound.
+
+#### Scenario: An unreadable private log shard
+
+- **GIVEN** a switched machine holding both partitions
+- **AND** a log shard of the `private` partition that cannot be read
+- **WHEN** the operator runs `o2b brain okf-export`
+- **THEN** the command fails and names the shard
+- **AND** no bundle is written
+
+#### Scenario: A store that cannot be opened
+
+- **GIVEN** a switched machine whose store no longer opens (a held
+ partition lost its identity file)
+- **WHEN** the operator runs `o2b brain okf-export`
+- **THEN** the command fails and says the store is unavailable
+- **AND** no bundle is written
diff --git a/openspec/specs/remote-log-reads/spec.md b/openspec/specs/remote-log-reads/spec.md
new file mode 100644
index 00000000..c6f4ecff
--- /dev/null
+++ b/openspec/specs/remote-log-reads/spec.md
@@ -0,0 +1,29 @@
+# remote-log-reads Specification
+
+## Purpose
+What a caller below local reach (a remote MCP client) may read of the
+operational log of a machine whose brain lives in the store.
+
+## Requirements
+
+### Requirement: Private log events are withheld below local reach
+
+A reader that renders log events to a caller below local reach SHALL
+withhold every event the store holds in its `private` partition, whatever
+the event names, and SHALL show it to a local caller. A day whose every
+event is withheld SHALL read as a day with no events, the same answer a
+day that was never logged gives.
+
+#### Scenario: A remote caller reads a day with a private event
+
+- **GIVEN** a switched machine with one shared and one private log event
+ on the same day
+- **WHEN** a remote caller reads `osb://log/<that day>`
+- **THEN** the page shows the shared event and not the private one
+- **AND** a local caller reading the same day sees both
+
+#### Scenario: A remote caller reads a day with only private events
+
+- **GIVEN** a switched machine whose only log event of a day is private
+- **WHEN** a remote caller reads `osb://log/<that day>`
+- **THEN** the read fails exactly as for a day with no log events
diff --git a/src/cli/brain/verbs/okf-export.ts b/src/cli/brain/verbs/okf-export.ts
index bce682ba..d6123c38 100644
--- a/src/cli/brain/verbs/okf-export.ts
+++ b/src/cli/brain/verbs/okf-export.ts
@@ -180,6 +180,14 @@ export async function cmdBrainOkfExport(argv: string[]): Promise<number> {
`wrote OKF bundle to ${out} (${bundle.manifest.pages.length} page(s), ` +
`${bundle.manifest.log_days} log day(s))\n`,
);
+ // The partition rule, not the content class: the count prints whatever
+ // the operator's flag did with the prompt-derived entries.
+ if (log.privateEntries > 0) {
+ process.stderr.write(
+ `okf-export: left ${log.privateEntries} private log ` +
+ `${log.privateEntries === 1 ? "entry" : "entries"} out of log.md\n`,
+ );
+ }
if (flags["include-prompt-derived"] === true) {
process.stderr.write(EGRESS_CONTENT_CLASS_INCLUDE_NOTICE);
} else {
diff --git a/src/core/brain/artifact-ref-view.ts b/src/core/brain/artifact-ref-view.ts
index 4dd95515..9a14d9ce 100644
--- a/src/core/brain/artifact-ref-view.ts
+++ b/src/core/brain/artifact-ref-view.ts
@@ -62,6 +62,12 @@ export interface ArtifactRefView {
* entitled": the decision is always {@link ArtifactRefView.visible}.
*/
readonly filtersNothing: boolean;
+ /**
+ * True when the caller is below local reach, so records of the store's
+ * `private` partition that carry no reference of their own (log events)
+ * are withheld from it. Absent means false.
+ */
+ readonly withholdsPrivate?: boolean;
/** May the caller see the artifact or page this reference names? */
readonly visible: (ref: ArtifactRef) => boolean;
/**
@@ -142,6 +148,7 @@ export function everyArtifactRefView(...views: ReadonlyArray<ArtifactRefView>):
const visible = (ref: ArtifactRef): boolean => live.every((v) => v.visible(ref));
return Object.freeze({
filtersNothing: false,
+ ...(live.some((v) => v.withholdsPrivate === true) ? { withholdsPrivate: true } : {}),
visible,
row: (...refs: ReadonlyArray<ArtifactRef>) => refs.every(visible),
keep: <T>(rows: ReadonlyArray<T>, refsOf: (r: T) => ReadonlyArray<ArtifactRef>) =>
@@ -151,13 +158,17 @@ export function everyArtifactRefView(...views: ReadonlyArray<ArtifactRefView>):
/**
* The reference view a per-reader render asks: unfiltered when the caller
- * passed no path predicate, the predicate bound to `vault` otherwise.
+ * passed no path predicate and is at local reach, the predicate bound to
+ * `vault` otherwise. `withholdsPrivate`: the caller is below local reach,
+ * so events of the store's `private` partition are withheld from it
+ * (`ArtifactRefView.withholdsPrivate`).
*/
export function readerRefView(
vault: string,
readable: ((rel: string) => boolean) | undefined,
+ withholdsPrivate = false,
): ArtifactRefView {
- return readable === undefined
- ? UNFILTERED_ARTIFACT_REFS
- : artifactRefView(vault, (rel) => readable(rel));
+ if (readable === undefined && !withholdsPrivate) return UNFILTERED_ARTIFACT_REFS;
+ const view = artifactRefView(vault, (rel) => readable?.(rel) ?? true);
+ return withholdsPrivate ? Object.freeze({ ...view, withholdsPrivate: true }) : view;
}
diff --git a/src/core/brain/digest.ts b/src/core/brain/digest.ts
index df2e5b1f..5a29712d 100644
--- a/src/core/brain/digest.ts
+++ b/src/core/brain/digest.ts
@@ -118,6 +118,11 @@ export interface RenderDigestOptions {
* byte-identical to a digest without the option.
*/
readonly readable?: (rel: string) => boolean;
+ /**
+ * The reader is below local reach: log events of the store's `private`
+ * partition are withheld from every section, counts included.
+ */
+ readonly withholdsPrivate?: boolean;
}
export interface RenderDigestResult {
@@ -369,7 +374,7 @@ export function renderDigest(vault: string, opts: RenderDigestOptions = {}): Ren
since,
until,
opts.agentScope,
- readerRefView(vault, opts.readable),
+ readerRefView(vault, opts.readable, opts.withholdsPrivate === true),
);
// A digest rendered for a reader below local reach (a `readable`
// filter) names a failed scan without its raised message, which can
diff --git a/src/core/brain/lessons.ts b/src/core/brain/lessons.ts
index 2e14a895..79b8ec73 100644
--- a/src/core/brain/lessons.ts
+++ b/src/core/brain/lessons.ts
@@ -390,6 +390,11 @@ export interface LessonsReaderOptions {
* nothing is filtered. It never reaches the shared write.
*/
readonly readable?: (rel: string) => boolean;
+ /**
+ * The reader is below local reach: apply-evidence events of the store's
+ * `private` partition are not counted for it.
+ */
+ readonly withholdsPrivate?: boolean;
}
interface RenderLessonsOptions extends LessonsReaderOptions {
@@ -410,11 +415,13 @@ function renderLessons(vault: string | null, opts: RenderLessonsOptions): Lesson
// With no vault every memory path is vault-relative already, and the
// events are judged against the store's records (design D14): a reader
// with a scope never scores an event it could not see.
+ const withholdsPrivate = opts.withholdsPrivate === true;
let refs: ArtifactRefView | null = null;
- if (vault !== null) refs = readerRefView(vault, opts.readable);
- else if (opts.readable !== undefined) {
- const readable = opts.readable;
- refs = storeRecordRefView((page) => readable(page.rel));
+ if (vault !== null) refs = readerRefView(vault, opts.readable, withholdsPrivate);
+ else if (opts.readable !== undefined || withholdsPrivate) {
+ const readable = opts.readable ?? (() => true);
+ const view = storeRecordRefView((page) => readable(page.rel));
+ refs = withholdsPrivate ? Object.freeze({ ...view, withholdsPrivate: true }) : view;
}
const visible = (path: string): boolean =>
vault === null || refs === null
diff --git a/src/core/brain/log-days.ts b/src/core/brain/log-days.ts
index 1e6e910e..04374959 100644
--- a/src/core/brain/log-days.ts
+++ b/src/core/brain/log-days.ts
@@ -38,7 +38,7 @@ export interface LogDaysContext {
}
/** Every date a store log can name; the facade reads only the shards of held months. */
-const WHOLE_LOG = Object.freeze({ from: "1970-01-01", to: "9998-12-31" });
+export const WHOLE_LOG = Object.freeze({ from: "1970-01-01", to: "9998-12-31" });
/** Stores one read pass keeps the days of. */
const PASS_CACHE_LIMIT = 4;
@@ -170,6 +170,15 @@ function groupByDay(entries: ReadonlyArray<BrainLogEntry>): Map<string, LogDay>
);
}
+/**
+ * The entries grouped by the date their timestamp names, oldest first:
+ * the same frozen days `storeLogDays` returns, for a caller that has
+ * already read the events itself (the OKF export's shared-only days).
+ */
+export function groupLogDays(entries: ReadonlyArray<BrainLogEntry>): LogDay[] {
+ return [...groupByDay(entries).values()];
+}
+
/**
* The log of `vault` for a reader that walks it by day: the day files
* (`listLogDates`, `readLogDay`) on an unswitched machine, the store's
diff --git a/src/core/brain/log-events-at-reach.ts b/src/core/brain/log-events-at-reach.ts
index 7c598846..cefe8b80 100644
--- a/src/core/brain/log-events-at-reach.ts
+++ b/src/core/brain/log-events-at-reach.ts
@@ -156,6 +156,9 @@ export function dreamEntryAtReach(
* page once `ret-x` was the reserved page on disk, and passed.
*/
export function logEntryAtReach(refs: ArtifactRefView, entry: BrainLogEntry): BrainLogEntry | null {
+ // An event of the store's `private` partition is withheld below local
+ // reach whatever it names, as a private page is (review finding F333).
+ if (refs.withholdsPrivate === true && entry.fromPrivatePartition === true) return null;
if (refs.filtersNothing) return entry;
const shown = dreamEntryAtReach(refs, entry);
if (shown === null) return null;
@@ -170,6 +173,12 @@ export function logEntriesAtReach(
refs: ArtifactRefView,
entries: ReadonlyArray<BrainLogEntry>,
): ReadonlyArray<BrainLogEntry> {
- if (refs.filtersNothing) return entries;
- return entries.flatMap((entry) => logEntryAtReach(refs, entry) ?? []);
+ // An event of the store's `private` partition is withheld below local
+ // reach whatever it names, as a private page is (review finding F333).
+ const shown =
+ refs.withholdsPrivate === true
+ ? entries.filter((e) => e.fromPrivatePartition !== true)
+ : entries;
+ if (refs.filtersNothing) return shown;
+ return shown.flatMap((entry) => logEntryAtReach(refs, entry) ?? []);
}
diff --git a/src/core/brain/log.ts b/src/core/brain/log.ts
index 57512081..61ce1756 100644
--- a/src/core/brain/log.ts
+++ b/src/core/brain/log.ts
@@ -85,6 +85,12 @@ export interface BrainLogEntry {
readonly eventType: BrainLogEventKind;
readonly agent?: string;
readonly body: BrainLogEntryPayload;
+ /**
+ * Set on an event read from the store's `private` partition: a reader
+ * below local reach withholds it (`logEntriesAtReach`), as it withholds
+ * a private page. Never set on a day file's entry (it has no partition).
+ */
+ readonly fromPrivatePartition?: true;
}
/** Warning surfaced by {@link parseLogDay} for a malformed sub-block. */
diff --git a/src/core/brain/portability/okf.ts b/src/core/brain/portability/okf.ts
index c9c92c9e..e96db0fc 100644
--- a/src/core/brain/portability/okf.ts
+++ b/src/core/brain/portability/okf.ts
@@ -91,7 +91,9 @@ import {
writeLanePage,
} from "../../store/lane-pages.ts";
import { assertNoteVaultForWrite } from "../../vault-adapter/index.ts";
-import { storeLogDays } from "../log-days.ts";
+import { groupLogDays, WHOLE_LOG } from "../log-days.ts";
+import { readStoreLogEventsReport } from "../../store/read/log-events.ts";
+import { protectionStore } from "../../store/read/protection-store.ts";
import { renderLogDayHeader, renderLogEntryBlock } from "../log.ts";
import { pageVisibility, REMOTE_DENY_VISIBILITY_TOKEN } from "../../graph/visibility.ts";
@@ -315,6 +317,12 @@ export interface OkfManifest {
* shards of one day are one day here, not two.
*/
readonly log_days: number;
+ /**
+ * Log events the export left out of `log.md` for being private, counted
+ * before any content-class filtering. Zero on the legacy layout and for
+ * a machine that holds no `private` partition.
+ */
+ readonly log_private_omitted: number;
}
/** A single file in the in-memory bundle write-plan. */
@@ -588,6 +596,12 @@ export interface OkfLog {
readonly days: number;
/** Entries the content-class filter dropped; zero without a filter. */
readonly droppedEntries: number;
+ /**
+ * Log events the store held in its `private` partition, left out of
+ * `log.md` and counted before any content-class filtering; zero on the
+ * legacy layout.
+ */
+ readonly privateEntries: number;
}
/**
@@ -600,10 +614,31 @@ const LOG_BULLET_RE = /^-\s+([A-Za-z_][A-Za-z0-9_-]*)\s*:\s*(.*)$/;
export function buildLog(vault: string, filter?: OkfLogFilter): OkfLog {
const bodiesByDate = new Map<string, string[]>();
let droppedEntries = 0;
- // A store-only machine keeps no day files: each day of the store's log
- // events is rendered the way the day file renders it (header, then one
- // block per entry), so the bundle's `log.md` reads the same.
- const storedDays = storeLogDays(vault);
+ // One read of the store log, counted by partition: a private event never
+ // reaches `log.md` (review finding F333), and the export refuses when a
+ // log shard cannot be read, so the bundle is never silently short of
+ // events and the private count is never a lower bound.
+ const report = readStoreLogEventsReport(WHOLE_LOG, { vault });
+ // A store-only machine whose store cannot be opened reads no events and
+ // no unreadable shard: refuse as a protection reader does, switched or
+ // not, rather than export an empty log that claims nothing private was
+ // left out.
+ if (report !== null) protectionStore(undefined, { openErrorFails: true, vault });
+ if (report !== null && report.unreadable.length > 0) {
+ throw new Error(
+ `okf export: cannot read log shard(s) ${report.unreadable.join(", ")}; the bundle would be short of their events`,
+ );
+ }
+ // Counted before the content-class filter: the partition rule and the
+ // class policy are independent, so the two counts never overlap.
+ const privateEntries = report?.events.filter((e) => e.partition === "private").length ?? 0;
+ // A store-only machine keeps no day files: the days of the shared events
+ // are rendered the way the day file renders it (header, then one block
+ // per entry), so the bundle's `log.md` reads the same.
+ const storedDays =
+ report === null
+ ? null
+ : groupLogDays(report.events.filter((e) => e.partition === "shared").map((e) => e.entry));
for (const day of storedDays ?? []) {
const body = [renderLogDayHeader(day.date), ...day.entries.map(renderLogEntryBlock)]
.join("\n")
@@ -646,7 +681,12 @@ export function buildLog(vault: string, filter?: OkfLogFilter): OkfLog {
const sections = [...bodiesByDate.keys()]
.toSorted()
.map((date) => `## ${date}\n\n${bodiesByDate.get(date)!.join("\n\n")}`);
- return { contents: sections.join("\n\n"), days: bodiesByDate.size, droppedEntries };
+ return {
+ contents: sections.join("\n\n"),
+ days: bodiesByDate.size,
+ droppedEntries,
+ privateEntries,
+ };
}
/**
@@ -991,7 +1031,7 @@ export function buildOkfSubsetBundle(vault: string, pages: ReadonlyArray<OkfPage
export function buildOkfBundleFromPages(
vault: string,
pages: ReadonlyArray<OkfPage>,
- log: Pick<OkfLog, "contents" | "days"> = buildLog(vault),
+ log: Pick<OkfLog, "contents" | "days" | "privateEntries"> = buildLog(vault),
): OkfBundle {
return assembleOkfBundle(vault, pages, log);
}
@@ -999,7 +1039,7 @@ export function buildOkfBundleFromPages(
function assembleOkfBundle(
vault: string,
pages: ReadonlyArray<OkfPage>,
- log: Pick<OkfLog, "contents" | "days"> | null,
+ log: Pick<OkfLog, "contents" | "days" | "privateEntries"> | null,
): OkfBundle {
// ONE instant for the whole bundle: the manifest's `generated_at` and
// every page's `generated.at` share it, so whole-bundle byte equality
@@ -1027,6 +1067,7 @@ function assembleOkfBundle(
producer_meta: page.producer_meta,
})),
log_days: log?.days ?? 0,
+ log_private_omitted: log?.privateEntries ?? 0,
};
const files: OkfBundleFile[] = [
@@ -1099,6 +1140,7 @@ interface ManifestInput {
readonly generated_at?: unknown;
readonly vault_basename?: unknown;
readonly log_days?: unknown;
+ readonly log_private_omitted?: unknown;
readonly pages?: unknown;
}
@@ -1252,6 +1294,7 @@ function readSpecOkfBundle(dir: string): ParsedOkfBundle {
vault_basename: "",
pages: entries,
log_days: 0,
+ log_private_omitted: 0,
},
// No manifest, no own-producer claim to honour: the walk's output is
// foreign by construction - stating it directly instead of resting
@@ -1363,6 +1406,11 @@ export function readOkfBundle(dir: string): ParsedOkfBundle {
typeof parsed.log_days === "number" && Number.isFinite(parsed.log_days)
? parsed.log_days
: 0,
+ log_private_omitted:
+ typeof parsed.log_private_omitted === "number" &&
+ Number.isFinite(parsed.log_private_omitted)
+ ? parsed.log_private_omitted
+ : 0,
},
foreign: producer !== OKF_PRODUCER,
pages,
diff --git a/src/core/brain/reach-view.ts b/src/core/brain/reach-view.ts
index 2b4e2dff..0d55d506 100644
--- a/src/core/brain/reach-view.ts
+++ b/src/core/brain/reach-view.ts
@@ -51,6 +51,7 @@ export function reachView(vault: string | null, reach: TransportReach): ReachVie
return Object.freeze({
reach,
...storeRecordRefView((page) => isStoreRecordReadableAtReach(page, reach)),
+ withholdsPrivate: true,
});
}
// Store-only (task 2.10): a preference or signal is judged by its record.
@@ -62,5 +63,6 @@ export function reachView(vault: string | null, reach: TransportReach): ReachVie
if (page !== undefined) return isStoreRecordReadableAtReach(page, reach);
return isPathReadableAtReach(vault, rel, reach, cache);
}),
+ withholdsPrivate: true,
});
}
diff --git a/src/core/store/lane-entry-store.ts b/src/core/store/lane-entry-store.ts
new file mode 100644
index 00000000..7aa0027a
--- /dev/null
+++ b/src/core/store/lane-entry-store.ts
@@ -0,0 +1,299 @@
+/**
+ * The store side of the lane page store: the path helpers the store side
+ * needs (`lanePagesInStore`, `heldInStore`, `insideBrain`, `brainRelOf`,
+ * `placeOf`, `isLaneEntryPath`), the fold accessors and the record
+ * builders of the lane entry store, and the keep rule that holds a
+ * replaced private entry private. Every write call stays in
+ * `lane-pages.ts`; this module only reads the file system and builds the
+ * records of a write (design D14 of brain-store-and-topics).
+ */
+
+import { existsSync, readFileSync, statSync } from "node:fs";
+import { isAbsolute, join, relative, sep } from "node:path";
+
+import { BRAIN_ROOT_REL } from "../brain/path-constants.ts";
+import { canonicalJson } from "../integrity/digest.ts";
+import type { FrontmatterMap } from "../types.ts";
+import { parseFrontmatterText } from "../vault.ts";
+import { laneStoreFold } from "./lane-fold-cache.ts";
+import { lanePlaceOf } from "./lane-paths.ts";
+import {
+ laneEntryKey,
+ laneEntryRecord,
+ laneEntryRemoveRecord,
+ STANDING_RULE_LANE,
+ type LaneEntryValue,
+} from "./lane-records.ts";
+import { opaqueFields } from "./operation-privacy.ts";
+import { isPrivateFrontmatter } from "./private-page.ts";
+import { rowNamesPrivatePage } from "./reference-privacy.ts";
+import { storeOnlyMode } from "./store-only.ts";
+import type { Authority, StorePartition } from "./constants.ts";
+import { authorityFromOrigin, type DualWriteRecord } from "./dual-write.ts";
+
+/** Whether lane pages of `vault` live in the store on this machine. */
+export function lanePagesInStore(vault: string): boolean {
+ return storeOnlyMode({ vault }).storeOnly;
+}
+
+/** Fields of a lane page that are stamps and ids, never page references. */
+const PAGE_OPAQUE_FIELDS = opaqueFields("slug", "date", "valid_from", "content_hash", "revision");
+
+/**
+ * Does the store hold `path` on this machine: a store-only machine and a
+ * path under `<vault>/Brain/`. Any other path (a user's `skills/` or
+ * `runbooks/` page a lane module also reads) stays a file in both modes.
+ */
+export function heldInStore(vault: string, path: string): boolean {
+ return lanePagesInStore(vault) && insideBrain(vault, path);
+}
+
+/** Whether `path` lies under `<vault>/Brain/` (or is it). */
+export function insideBrain(vault: string, path: string): boolean {
+ const rel = relative(join(vault, BRAIN_ROOT_REL), path);
+ return rel === "" || (!rel.startsWith("..") && !isAbsolute(rel));
+}
+
+export function brainRelOf(vault: string, path: string): string {
+ return relative(join(vault, BRAIN_ROOT_REL), path).split(sep).join("/");
+}
+
+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}`);
+ return place;
+}
+
+function isLaneEntryPath(vault: string, path: string): boolean {
+ return insideBrain(vault, path) && lanePlaceOf(brainRelOf(vault, path)) !== null;
+}
+
+// ----- The store side -----------------------------------------------------------
+
+/** The live lane entries of the configured store, by `<lane>/<entry>`. */
+export function storeEntries(): ReadonlyMap<string, LaneEntryValue> {
+ return laneStoreFold().entries;
+}
+
+/**
+ * The physical time (ms) of the newest record of the live lane entry at
+ * `path`, the store's stand-in for a file's mtime; `null` when there is no
+ * such entry. A file's mtime on a path the store does not hold.
+ */
+export function laneEntryClockMs(vault: string, path: string): number | null {
+ if (!heldInStore(vault, path)) {
+ try {
+ return statSync(path).mtimeMs;
+ } catch {
+ return null;
+ }
+ }
+ const { lane, entry } = placeOf(vault, path);
+ return laneStoreFold().clocks.get(laneEntryKey(lane, entry)) ?? null;
+}
+
+export function storeEntry(vault: string, path: string): LaneEntryValue | null {
+ const { lane, entry } = placeOf(vault, path);
+ return storeEntries().get(laneEntryKey(lane, entry)) ?? null;
+}
+
+/**
+ * Whether the lane fold misses an `events` shard (unreadable, or gone
+ * since this machine read it): an entry's private records may be in it,
+ * so every privacy verdict over the fold fails closed (design D14).
+ */
+export function foldIncomplete(): boolean {
+ return laneStoreFold().unreadable.length > 0;
+}
+
+/** Whether the live entry `value` was written to the `private` partition. */
+export function livesInPrivate(value: LaneEntryValue): boolean {
+ return laneStoreFold().privateKeys.has(laneEntryKey(value.lane, value.entry));
+}
+
+/**
+ * Whether the store holds `path` on this machine as a live entry of the
+ * `private` partition. An entry can be private by partition alone, with no
+ * `visibility:` in its fields, so an exporter that turns entries back into
+ * pages asks here to keep the privacy (review finding F333). A path the
+ * store does not hold is no private entry. While the fold misses a shard,
+ * every lane entry reads as private (fail closed).
+ */
+export function laneEntryInPrivate(vault: string, path: string): boolean {
+ if (!heldInStore(vault, path)) return false;
+ if (lanePlaceOf(brainRelOf(vault, path)) === null) return false;
+ if (foldIncomplete()) return true;
+ const value = storeEntry(vault, path);
+ return value !== null && livesInPrivate(value);
+}
+
+/** The partition the live entry `value` lives in. */
+export function partitionOf(value: LaneEntryValue): StorePartition {
+ return livesInPrivate(value) ? "private" : "shared";
+}
+
+/**
+ * The tombstone of a live entry, in the partition the entry lives in
+ * whatever the rest of its operation is (`Located`, content-free): a
+ * device that holds only `shared` must see a shared entry's tombstone.
+ * `onlyIfApart`: the tombstone of an entry a write replaces, needed only
+ * when the replacement lands in another partition.
+ */
+export function tombstoneOf(value: LaneEntryValue, onlyIfApart = false): DualWriteRecord {
+ const partition = partitionOf(value);
+ return {
+ ...laneEntryRemoveRecord({
+ lane: value.lane,
+ entry: value.entry,
+ authority: authorityFor(value.lane),
+ private: partition === "private",
+ }),
+ located: { partition, content: false, ...(onlyIfApart ? { onlyIfApart: true } : {}) },
+ };
+}
+
+/**
+ * The tombstone a write replacing the entry at `path` adds before its new
+ * record: the old entry lives in `shared`, so if the new value lands in
+ * `private` (a raise), a device that holds only `shared` sees the entry
+ * go rather than keep reading the old value. Nothing when no shared entry
+ * is replaced; the append drops it when the new value stays in `shared`.
+ */
+export function replacedShared(vault: string, path: string): DualWriteRecord[] {
+ if (!isLaneEntryPath(vault, path)) return [];
+ const prior = storeEntry(vault, path);
+ return prior !== null && !livesInPrivate(prior) ? [tombstoneOf(prior, true)] : [];
+}
+
+/** An entry's fields as a fresh map: a caller may edit what it reads. */
+export function fieldsCopy(value: LaneEntryValue): FrontmatterMap {
+ return structuredClone(value.fields) as FrontmatterMap;
+}
+
+/** Whether `value` already holds exactly these fields and text. */
+export function sameEntry(
+ value: LaneEntryValue | null,
+ fields: Readonly<Record<string, unknown>>,
+ text: string,
+): boolean {
+ return (
+ value !== null && value.text === text && canonicalJson(value.fields) === canonicalJson(fields)
+ );
+}
+
+function authorityFor(lane: string): Authority {
+ return lane === STANDING_RULE_LANE ? "human" : authorityFromOrigin();
+}
+
+export function isPrivateEntry(
+ vault: string,
+ fields: Readonly<Record<string, unknown>>,
+ text: string,
+): boolean {
+ return (
+ isPrivateFrontmatter(fields) ||
+ rowNamesPrivatePage(existsSync(vault) ? vault : null, { fields, text }, PAGE_OPAQUE_FIELDS)
+ );
+}
+
+export function entryRecord(
+ vault: string,
+ path: string,
+ fields: Readonly<Record<string, unknown>>,
+ text: string,
+ isPrivate: boolean,
+ /**
+ * `located`: `isPrivate` is where an existing entry lives (a move), and
+ * the record stays there; the lane's private-when-held rule would send
+ * a shared entry's move, its tombstone included, to `private`, where a
+ * device without that partition never sees the old entry removed.
+ */
+ placement: "judged" | "located" = "judged",
+): DualWriteRecord {
+ const { lane, entry } = placeOf(vault, path);
+ const agent =
+ typeof fields["agent"] === "string" && fields["agent"].trim() !== ""
+ ? fields["agent"].trim()
+ : undefined;
+ return laneEntryRecord({
+ lane,
+ entry,
+ fields,
+ text,
+ authority: authorityFor(lane),
+ ...(agent !== undefined ? { agent } : {}),
+ private: isPrivate,
+ // The lanes the migration imports as blobs are private wherever this
+ // machine holds the private partition (`surface-map.ts` `blobLane`).
+ ...(placement === "judged" && PRIVATE_WHEN_HELD_LANES.has(lane)
+ ? { privateWhenHeld: true }
+ : {}),
+ });
+}
+
+/** Lanes whose records go to `private` whenever this machine holds it. */
+const PRIVATE_WHEN_HELD_LANES: ReadonlySet<string> = new Set(["source-archive"]);
+
+/**
+ * Whether a write to `path` replaces a private lane entry (design D14, one
+ * verdict per operation, fail closed). Such an entry stays private whatever
+ * the new content says: an overwrite that drops the visibility field must
+ * never land the entry's text in `shared`. Nothing lowers an entry's
+ * partition; an operator who wants it shared removes it and writes it anew.
+ *
+ * Two halves, because on an unswitched machine the legacy file is replaced
+ * before the dual-write record is built:
+ * - {@link legacyPagePrivate}, read before the write: the legacy page's
+ * own frontmatter (an unswitched machine only; a legacy page has no
+ * partition).
+ * - {@link storedEntryPrivate}, read when the record is built: the live
+ * store entry lives in `private` or its fields reserve it.
+ */
+export function legacyPagePrivate(vault: string, path: string): boolean {
+ if (!isLaneEntryPath(vault, path) || heldInStore(vault, path) || !existsSync(path)) return false;
+ try {
+ return isPrivateFrontmatter(laneTextParts(path, readFileSync(path, "utf8")).fields);
+ } catch {
+ // A page that exists but cannot be read cannot be judged: fail closed.
+ return true;
+ }
+}
+
+/**
+ * See {@link legacyPagePrivate}. While the fold misses a shard, the entry
+ * may be private in it: the write is judged private (on a machine without
+ * the `private` partition, refused).
+ */
+export function storedEntryPrivate(vault: string, path: string): boolean {
+ if (!isLaneEntryPath(vault, path)) return false;
+ if (foldIncomplete()) return true;
+ const value = storeEntry(vault, path);
+ return value !== null && (livesInPrivate(value) || isPrivateFrontmatter(value.fields));
+}
+
+/**
+ * A lane file's text as an entry's fields and text: a page's frontmatter
+ * and body, a JSON object as the fields, anything else (malformed JSON
+ * included, which the legacy writer also writes as it is) as text.
+ */
+export function laneTextParts(
+ path: string,
+ text: string,
+): { fields: Record<string, unknown>; body: string } {
+ if (path.endsWith(".md")) {
+ const [frontmatter, rest] = parseFrontmatterText(text);
+ return { fields: frontmatter, body: rest };
+ }
+ if (path.endsWith(".json")) {
+ let parsed: unknown = null;
+ try {
+ parsed = JSON.parse(text);
+ } catch {
+ return { fields: {}, body: text };
+ }
+ if (parsed !== null && typeof parsed === "object" && !Array.isArray(parsed)) {
+ return { fields: parsed as Record<string, unknown>, body: "" };
+ }
+ }
+ return { fields: {}, body: text };
+}
diff --git a/src/core/store/lane-pages.ts b/src/core/store/lane-pages.ts
index 4bf59a38..5160c143 100644
--- a/src/core/store/lane-pages.ts
+++ b/src/core/store/lane-pages.ts
@@ -40,7 +40,6 @@ import {
FileAlreadyExistsError,
renameWithRetry,
} from "../fs-atomic.ts";
-import { canonicalJson } from "../integrity/digest.ts";
import { noVaultRoot } from "../platform-dirs.ts";
import { containedRecordPath } from "../record-path.ts";
import type { FrontmatterMap } from "../types.ts";
@@ -51,27 +50,37 @@ import {
writeFrontmatterAtomic,
type WriteFrontmatterAtomicOptions,
} from "../vault.ts";
-import type { Authority, StorePartition } from "./constants.ts";
-import { authorityFromOrigin, type DualWriteContext, type DualWriteRecord } from "./dual-write.ts";
-import { laneFingerprintOf, laneLockTarget, laneStoreFold } from "./lane-fold-cache.ts";
-import { brainRelOfEntry, lanePlaceOf } from "./lane-paths.ts";
+import { type DualWriteContext } from "./dual-write.ts";
+import { laneFingerprintOf, laneLockTarget } from "./lane-fold-cache.ts";
import {
- laneEntryKey,
- laneEntryRecord,
- laneEntryRemoveRecord,
- STANDING_RULE_LANE,
- type LaneEntryValue,
-} from "./lane-records.ts";
-import { opaqueFields } from "./operation-privacy.ts";
-import { isPrivateFrontmatter } from "./private-page.ts";
+ brainRelOf,
+ entryRecord,
+ fieldsCopy,
+ foldIncomplete,
+ heldInStore,
+ insideBrain,
+ isPrivateEntry,
+ laneTextParts,
+ legacyPagePrivate,
+ livesInPrivate,
+ lanePagesInStore,
+ partitionOf,
+ replacedShared,
+ sameEntry,
+ storeEntries,
+ storeEntry,
+ storedEntryPrivate,
+ tombstoneOf,
+} from "./lane-entry-store.ts";
+import { brainRelOfEntry, lanePlaceOf } from "./lane-paths.ts";
import { configuredStore } from "./read/store-entities.ts";
-import { rowNamesPrivatePage } from "./reference-privacy.ts";
-import { storeOnlyMode } from "./store-only.ts";
import { acquireDirLock, STORE_LOCK_STALE_MS, withLocalLock } from "./local-lock.ts";
import { assertNoteVaultForWrite } from "../vault-adapter/index.ts";
import { withOperationPrivacy } from "./operation-scope.ts";
import { routeWrite, storeWrite } from "./store-write.ts";
+export { laneEntryClockMs, laneEntryInPrivate, lanePagesInStore } from "./lane-entry-store.ts";
+
/**
* The vault root a lane module works under when no vault is configured.
* Nothing is ever written below it: with no vault the machine is
@@ -92,23 +101,6 @@ export function assertLaneWrite(vault: string): void {
if (!lanePagesInStore(vault)) assertVaultIdentityForWrite(vault);
}
-/** Whether lane pages of `vault` live in the store on this machine. */
-export function lanePagesInStore(vault: string): boolean {
- return storeOnlyMode({ vault }).storeOnly;
-}
-
-/** Fields of a lane page that are stamps and ids, never page references. */
-const PAGE_OPAQUE_FIELDS = opaqueFields("slug", "date", "valid_from", "content_hash", "revision");
-
-/**
- * Does the store hold `path` on this machine: a store-only machine and a
- * path under `<vault>/Brain/`. Any other path (a user's `skills/` or
- * `runbooks/` page a lane module also reads) stays a file in both modes.
- */
-function heldInStore(vault: string, path: string): boolean {
- return lanePagesInStore(vault) && insideBrain(vault, path);
-}
-
/** `routeWrite` for a lane path; a path outside `Brain/` is written as a file. */
function routeLaneWrite(vault: string, path: string, spec: Parameters<typeof routeWrite>[0]): void {
// A path outside `Brain/` is no lane entry in either mode: a file, never
@@ -121,12 +113,6 @@ function routeLaneWrite(vault: string, path: string, spec: Parameters<typeof rou
routeWrite(spec);
}
-/** Whether `path` lies under `<vault>/Brain/` (or is it). */
-function insideBrain(vault: string, path: string): boolean {
- const rel = relative(join(vault, BRAIN_ROOT_REL), path);
- return rel === "" || (!rel.startsWith("..") && !isAbsolute(rel));
-}
-
/**
* The guard of a lane module's write outside `Brain/` on a store-only
* machine. A path in the user's vault (a materialised `skills/` page, a
@@ -147,186 +133,10 @@ function guardUserVaultWrite(vault: string, path: string): void {
);
}
-function brainRelOf(vault: string, path: string): string {
- return relative(join(vault, BRAIN_ROOT_REL), path).split(sep).join("/");
-}
-
-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}`);
- return place;
-}
-
function context(vault: string): DualWriteContext {
return existsSync(vault) ? { vault } : {};
}
-// ----- The store side -----------------------------------------------------------
-
-/** The live lane entries of the configured store, by `<lane>/<entry>`. */
-function storeEntries(): ReadonlyMap<string, LaneEntryValue> {
- return laneStoreFold().entries;
-}
-
-/**
- * The physical time (ms) of the newest record of the live lane entry at
- * `path`, the store's stand-in for a file's mtime; `null` when there is no
- * such entry. A file's mtime on a path the store does not hold.
- */
-export function laneEntryClockMs(vault: string, path: string): number | null {
- if (!heldInStore(vault, path)) {
- try {
- return statSync(path).mtimeMs;
- } catch {
- return null;
- }
- }
- const { lane, entry } = placeOf(vault, path);
- return laneStoreFold().clocks.get(laneEntryKey(lane, entry)) ?? null;
-}
-
-function storeEntry(vault: string, path: string): LaneEntryValue | null {
- const { lane, entry } = placeOf(vault, path);
- return storeEntries().get(laneEntryKey(lane, entry)) ?? null;
-}
-
-/**
- * Whether the lane fold misses an `events` shard (unreadable, or gone
- * since this machine read it): an entry's private records may be in it,
- * so every privacy verdict over the fold fails closed (design D14).
- */
-function foldIncomplete(): boolean {
- return laneStoreFold().unreadable.length > 0;
-}
-
-/** Whether the live entry `value` was written to the `private` partition. */
-function livesInPrivate(value: LaneEntryValue): boolean {
- return laneStoreFold().privateKeys.has(laneEntryKey(value.lane, value.entry));
-}
-
-/**
- * Whether the store holds `path` on this machine as a live entry of the
- * `private` partition. An entry can be private by partition alone, with no
- * `visibility:` in its fields, so an exporter that turns entries back into
- * pages asks here to keep the privacy (review finding F333). A path the
- * store does not hold is no private entry. While the fold misses a shard,
- * every lane entry reads as private (fail closed).
- */
-export function laneEntryInPrivate(vault: string, path: string): boolean {
- if (!heldInStore(vault, path)) return false;
- if (lanePlaceOf(brainRelOf(vault, path)) === null) return false;
- if (foldIncomplete()) return true;
- const value = storeEntry(vault, path);
- return value !== null && livesInPrivate(value);
-}
-
-/** The partition the live entry `value` lives in. */
-function partitionOf(value: LaneEntryValue): StorePartition {
- return livesInPrivate(value) ? "private" : "shared";
-}
-
-/**
- * The tombstone of a live entry, in the partition the entry lives in
- * whatever the rest of its operation is (`Located`, content-free): a
- * device that holds only `shared` must see a shared entry's tombstone.
- * `onlyIfApart`: the tombstone of an entry a write replaces, needed only
- * when the replacement lands in another partition.
- */
-function tombstoneOf(value: LaneEntryValue, onlyIfApart = false): DualWriteRecord {
- const partition = partitionOf(value);
- return {
- ...laneEntryRemoveRecord({
- lane: value.lane,
- entry: value.entry,
- authority: authorityFor(value.lane),
- private: partition === "private",
- }),
- located: { partition, content: false, ...(onlyIfApart ? { onlyIfApart: true } : {}) },
- };
-}
-
-/**
- * The tombstone a write replacing the entry at `path` adds before its new
- * record: the old entry lives in `shared`, so if the new value lands in
- * `private` (a raise), a device that holds only `shared` sees the entry
- * go rather than keep reading the old value. Nothing when no shared entry
- * is replaced; the append drops it when the new value stays in `shared`.
- */
-function replacedShared(vault: string, path: string): DualWriteRecord[] {
- if (!isLaneEntryPath(vault, path)) return [];
- const prior = storeEntry(vault, path);
- return prior !== null && !livesInPrivate(prior) ? [tombstoneOf(prior, true)] : [];
-}
-
-/** An entry's fields as a fresh map: a caller may edit what it reads. */
-function fieldsCopy(value: LaneEntryValue): FrontmatterMap {
- return structuredClone(value.fields) as FrontmatterMap;
-}
-
-/** Whether `value` already holds exactly these fields and text. */
-function sameEntry(
- value: LaneEntryValue | null,
- fields: Readonly<Record<string, unknown>>,
- text: string,
-): boolean {
- return (
- value !== null && value.text === text && canonicalJson(value.fields) === canonicalJson(fields)
- );
-}
-
-function authorityFor(lane: string): Authority {
- return lane === STANDING_RULE_LANE ? "human" : authorityFromOrigin();
-}
-
-function isPrivateEntry(
- vault: string,
- fields: Readonly<Record<string, unknown>>,
- text: string,
-): boolean {
- return (
- isPrivateFrontmatter(fields) ||
- rowNamesPrivatePage(existsSync(vault) ? vault : null, { fields, text }, PAGE_OPAQUE_FIELDS)
- );
-}
-
-function entryRecord(
- vault: string,
- path: string,
- fields: Readonly<Record<string, unknown>>,
- text: string,
- isPrivate: boolean,
- /**
- * `located`: `isPrivate` is where an existing entry lives (a move), and
- * the record stays there; the lane's private-when-held rule would send
- * a shared entry's move, its tombstone included, to `private`, where a
- * device without that partition never sees the old entry removed.
- */
- placement: "judged" | "located" = "judged",
-): DualWriteRecord {
- const { lane, entry } = placeOf(vault, path);
- const agent =
- typeof fields["agent"] === "string" && fields["agent"].trim() !== ""
- ? fields["agent"].trim()
- : undefined;
- return laneEntryRecord({
- lane,
- entry,
- fields,
- text,
- authority: authorityFor(lane),
- ...(agent !== undefined ? { agent } : {}),
- private: isPrivate,
- // The lanes the migration imports as blobs are private wherever this
- // machine holds the private partition (`surface-map.ts` `blobLane`).
- ...(placement === "judged" && PRIVATE_WHEN_HELD_LANES.has(lane)
- ? { privateWhenHeld: true }
- : {}),
- });
-}
-
-/** Lanes whose records go to `private` whenever this machine holds it. */
-const PRIVATE_WHEN_HELD_LANES: ReadonlySet<string> = new Set(["source-archive"]);
-
// ----- Reads --------------------------------------------------------------------
/** One lane page as a lane module reads it. */
@@ -617,74 +427,6 @@ export function writeLaneText(
);
}
-/**
- * Whether a write to `path` replaces a private lane entry (design D14, one
- * verdict per operation, fail closed). Such an entry stays private whatever
- * the new content says: an overwrite that drops the visibility field must
- * never land the entry's text in `shared`. Nothing lowers an entry's
- * partition; an operator who wants it shared removes it and writes it anew.
- *
- * Two halves, because on an unswitched machine the legacy file is replaced
- * before the dual-write record is built:
- * - {@link legacyPagePrivate}, read before the write: the legacy page's
- * own frontmatter (an unswitched machine only; a legacy page has no
- * partition).
- * - {@link storedEntryPrivate}, read when the record is built: the live
- * store entry lives in `private` or its fields reserve it.
- */
-function legacyPagePrivate(vault: string, path: string): boolean {
- if (!isLaneEntryPath(vault, path) || heldInStore(vault, path) || !existsSync(path)) return false;
- try {
- return isPrivateFrontmatter(laneTextParts(path, readFileSync(path, "utf8")).fields);
- } catch {
- // A page that exists but cannot be read cannot be judged: fail closed.
- return true;
- }
-}
-
-/**
- * See {@link legacyPagePrivate}. While the fold misses a shard, the entry
- * may be private in it: the write is judged private (on a machine without
- * the `private` partition, refused).
- */
-function storedEntryPrivate(vault: string, path: string): boolean {
- if (!isLaneEntryPath(vault, path)) return false;
- if (foldIncomplete()) return true;
- const value = storeEntry(vault, path);
- return value !== null && (livesInPrivate(value) || isPrivateFrontmatter(value.fields));
-}
-
-function isLaneEntryPath(vault: string, path: string): boolean {
- return insideBrain(vault, path) && lanePlaceOf(brainRelOf(vault, path)) !== null;
-}
-
-/**
- * A lane file's text as an entry's fields and text: a page's frontmatter
- * and body, a JSON object as the fields, anything else (malformed JSON
- * included, which the legacy writer also writes as it is) as text.
- */
-function laneTextParts(
- path: string,
- text: string,
-): { fields: Record<string, unknown>; body: string } {
- if (path.endsWith(".md")) {
- const [frontmatter, rest] = parseFrontmatterText(text);
- return { fields: frontmatter, body: rest };
- }
- if (path.endsWith(".json")) {
- let parsed: unknown = null;
- try {
- parsed = JSON.parse(text);
- } catch {
- return { fields: {}, body: text };
- }
- if (parsed !== null && typeof parsed === "object" && !Array.isArray(parsed)) {
- return { fields: parsed as Record<string, unknown>, body: "" };
- }
- }
- return { fields: {}, body: text };
-}
-
/**
* Run a create-once write of `path` under a device-local create lock on a
* store-only machine, so the existence check and the record append are one
diff --git a/src/core/store/read/log-events.ts b/src/core/store/read/log-events.ts
index 61b5c2d6..2d49021e 100644
--- a/src/core/store/read/log-events.ts
+++ b/src/core/store/read/log-events.ts
@@ -22,7 +22,7 @@
import { listLogShardFiles, readLogDay, type LogShardFile } from "../../brain/log-jsonl.ts";
import type { BrainLogEntry } from "../../brain/log.ts";
import type { BrainLogEventKind } from "../../brain/types.ts";
-import { LOG_EVENT_KIND, STORE_PARTITIONS } from "../constants.ts";
+import { LOG_EVENT_KIND, STORE_PARTITIONS, type StorePartition } from "../constants.ts";
import { compareRecords, type StoreRecord } from "../envelope.ts";
import { readSource, type ReadContext } from "./read-context.ts";
import { readStreamRecords } from "./stream-read.ts";
@@ -126,6 +126,38 @@ export interface StoreLogEvent {
readonly device: string;
/** The record's clock: grows with every append of its device, whatever the entry's timestamp. */
readonly hlc: string;
+ /**
+ * The partition the record was read from. A record id present in both
+ * partitions reads as `private`: the strict answer when devices disagree.
+ */
+ readonly partition: StorePartition;
+}
+
+/**
+ * {@link readStoreLogEvents} with the store shards that could not be read:
+ * the answer may be short, and `unreadable` names every skipped shard as
+ * `<partition>/<shard>`. `null` on an unswitched machine, whose callers
+ * keep the day files. A caller that must know the answer is whole (an
+ * exporter, the manifest counts) refuses when `unreadable` is not empty.
+ */
+export function readStoreLogEventsReport(
+ range: LogDateRange,
+ context: ReadContext = {},
+): { events: StoreLogEvent[]; unreadable: ReadonlyArray<string> } | null {
+ assertRange(range);
+ const source = readSource(context);
+ if (source.kind === "legacy") return null;
+ if (range.from > range.to) return { events: [], unreadable: [] };
+ const read = storeLogEvents(range, source.store);
+ return {
+ events: read.dated.map((d) => ({
+ entry: d.entry,
+ device: d.record.device,
+ hlc: d.record.hlc,
+ partition: d.partition,
+ })),
+ unreadable: read.unreadable,
+ };
}
/**
@@ -137,29 +169,23 @@ export function readStoreLogEvents(
range: LogDateRange,
context: ReadContext = {},
): StoreLogEvent[] | null {
- assertRange(range);
- const source = readSource(context);
- if (source.kind === "legacy") return null;
- if (range.from > range.to) return [];
- return storeLogEvents(range, source.store).dated.map((d) => ({
- entry: d.entry,
- device: d.record.device,
- hlc: d.record.hlc,
- }));
+ return readStoreLogEventsReport(range, context)?.events ?? null;
}
function storeLogEvents(
range: LogDateRange,
store: Extract<ReturnType<typeof readSource>, { kind: "store" }>["store"],
): {
- dated: Array<{ entry: BrainLogEntry; record: StoreRecord }>;
+ dated: Array<{ entry: BrainLogEntry; record: StoreRecord; partition: StorePartition }>;
unreadable: string[];
} {
if (store === null) return { dated: [], unreadable: [] };
const first = shiftMonth(range.from.slice(0, 7), -1);
- const records: StoreRecord[] = [];
+ // The records of both partitions by record id: a record appended to
+ // `private` and copied (or synced) into `shared` counts once, as
+ // `private` - the strict answer when devices disagree.
+ const byId = new Map<string, { record: StoreRecord; partition: StorePartition }>();
const unreadable: string[] = [];
- const seen = new Set<string>();
for (const partition of STORE_PARTITIONS) {
if (!store.partitions.has(partition)) continue;
const read = readStreamRecords(
@@ -172,17 +198,22 @@ function storeLogEvents(
);
unreadable.push(...read.unreadable.map((rel) => `${partition}/${rel}`));
for (const record of read.records) {
- if (record.kind !== LOG_EVENT_KIND || seen.has(record.id)) continue;
- seen.add(record.id);
- records.push(record);
+ if (record.kind !== LOG_EVENT_KIND) continue;
+ const prior = byId.get(record.id);
+ if (prior !== undefined && (prior.partition === "private" || partition !== "private")) {
+ continue;
+ }
+ byId.set(record.id, { record, partition });
}
}
- const dated: Array<{ entry: BrainLogEntry; record: StoreRecord }> = [];
- for (const record of records) {
- const entry = entryOf(record);
- if (entry === null) continue;
+ const dated: Array<{ entry: BrainLogEntry; record: StoreRecord; partition: StorePartition }> = [];
+ for (const { record, partition } of byId.values()) {
+ const read = entryOf(record);
+ if (read === null) continue;
+ const entry: BrainLogEntry =
+ partition === "private" ? { ...read, fromPrivatePartition: true } : read;
const date = entry.timestamp.slice(0, 10);
- if (date >= range.from && date <= range.to) dated.push({ entry, record });
+ if (date >= range.from && date <= range.to) dated.push({ entry, record, partition });
}
const sorted = dated.toSorted(
(a, b) =>
diff --git a/src/core/store/read/protection-store.ts b/src/core/store/read/protection-store.ts
index ff692e90..3039fd11 100644
--- a/src/core/store/read/protection-store.ts
+++ b/src/core/store/read/protection-store.ts
@@ -43,27 +43,42 @@ function unavailable(reason: string, switched = true): StoreUnavailableError {
* when this machine has none and is not switched to one. Throws
* {@link StoreUnavailableError} on a switched machine whose store cannot
* be opened, or (with `needShared`) does not show its `shared` partition.
+ * With `openErrorFails`, a store that exists but cannot be opened (a
+ * corrupt `store.json`) throws on any store-only machine, switched or not:
+ * a reader that must know its answer is whole (an export) cannot read
+ * "no store" there.
*/
export function protectionStore(
configPath?: string,
- options: { readonly needShared?: boolean } = {},
+ options: {
+ readonly needShared?: boolean;
+ readonly openErrorFails?: boolean;
+ /** The vault the caller reads for, when it is not the configured one. */
+ readonly vault?: string | null;
+ } = {},
): StoreInspection | null {
let store: StoreInspection | null = null;
let reason = "";
let lost = false;
+ let openError = false;
try {
const { root } = resolveConfiguredStoreRoot(configPath);
store = inspectStore(root);
if (store === null) reason = `the store at ${root} cannot be found (no store.json)`;
} catch (err) {
lost = err instanceof HeldPartitionLostError;
+ openError = true;
reason = `the store cannot be opened (${(err as Error).message})`;
}
const context = configPath !== undefined ? { configPath } : {};
const switched = (): boolean => markedSwitched(context);
if (store === null) {
if (switched()) throw unavailable(reason);
- if (lost && isStoreOnly(context)) throw unavailable(reason, false);
+ const storeOnly = (): boolean =>
+ isStoreOnly(options.vault !== undefined ? { ...context, vault: options.vault } : context);
+ if ((lost || (openError && options.openErrorFails === true)) && storeOnly()) {
+ throw unavailable(reason, false);
+ }
return null;
}
if (options.needShared === true && !store.partitions.has("shared") && switched()) {
diff --git a/src/mcp/brain/brief-tools.ts b/src/mcp/brain/brief-tools.ts
index 854ce764..de67fe9b 100644
--- a/src/mcp/brain/brief-tools.ts
+++ b/src/mcp/brain/brief-tools.ts
@@ -230,6 +230,7 @@ async function toolBrainDigest(
linkOutputFormat: resolveLinkOutputFormat(ctx.configPath ?? undefined),
...(agentScope !== undefined ? { agentScope } : {}),
...(readable !== undefined ? { readable } : {}),
+ ...(restricted ? { withholdsPrivate: true } : {}),
});
const result = renderFor(format, readableAtContextReachOrUndefined(ctx));
diff --git a/src/mcp/resources.ts b/src/mcp/resources.ts
index 1bae163c..4186f85b 100644
--- a/src/mcp/resources.ts
+++ b/src/mcp/resources.ts
@@ -460,7 +460,10 @@ function readLessons(ctx: ResourceContext, uri: string, view: RequestView): Reso
const delivery = deliveryFor(ctx, view);
const text = view.refs.filtersNothing
? readMarkdown(uri, path).text
- : renderLessonsForReader(ctx.vault, { readable: view.refs.visible }).document;
+ : renderLessonsForReader(ctx.vault, {
+ readable: view.refs.visible,
+ ...(view.refs.withholdsPrivate === true ? { withholdsPrivate: true } : {}),
+ }).document;
return { uri, mimeType: MIME_MARKDOWN, text: delivery.shape(text, LESSONS_REL) };
}
@@ -468,6 +471,7 @@ function readDigestLatest(ctx: ResourceContext, uri: string, view: RequestView):
const rendered = renderDigest(ctx.vault, {
format: "markdown",
...(view.refs.filtersNothing ? {} : { readable: view.refs.visible }),
+ ...(view.refs.withholdsPrivate === true ? { withholdsPrivate: true } : {}),
// Ownership is pushed into the render's SELECTION as well as its
// row filter, the way `readActive` does: `view.refs` already
// carries the rule on the filter side, and the digest's
@@ -663,13 +667,13 @@ function readLog(
// rendered from its `log-event` records, in the shape a page has.
const log = logDayReader(ctx.vault);
if (log.stored) {
- const entries = log.day(rawDate).entries;
+ // Filtered first: a day whose every event the caller may not see reads
+ // as a day with none, never as an empty page (no existence oracle).
+ const entries = logEntriesAtReach(view.refs, log.day(rawDate).entries);
if (entries.length === 0) {
throw new MCPError(INTERNAL_ERROR, `no log events for date '${rawDate}'`);
}
- const blocks = logEntriesAtReach(view.refs, entries).map((e) =>
- renderLogEntryBlock(e).trimEnd(),
- );
+ const blocks = entries.map((e) => renderLogEntryBlock(e).trimEnd());
const text = [renderLogDayHeader(rawDate).trimEnd(), ...blocks].join(LOG_BLOCK_SEPARATOR);
return { uri, mimeType: MIME_MARKDOWN, text: `${text}\n` };
}
diff --git a/tests/cli/brain-attest.test.ts b/tests/cli/brain-attest.test.ts
index 73da55ea..70f3990e 100644
--- a/tests/cli/brain-attest.test.ts
+++ b/tests/cli/brain-attest.test.ts
@@ -39,7 +39,17 @@ import { acquireLogLock, appendLogEvent } from "../../src/core/brain/log.ts";
import { brainDirs } from "../../src/core/brain/paths.ts";
import { attestationsDir } from "../../src/core/brain/attestation/record.ts";
import { writeVaultIdentity } from "../../src/core/brain/vault-identity.ts";
-import { runCli } from "../helpers/run-cli.ts";
+import { runCli as runCliRaw, type RunCliOptions } from "../helpers/run-cli.ts";
+
+/**
+ * keygen and sign read a passphrase from stdin when stdin is not a
+ * terminal. Run in process they would read the test runner's own stdin,
+ * which a runner started from a background shell holds open forever, so
+ * every run here gets an explicit stdin: empty unless the test pipes one
+ * (the operator who pipes nothing, the raw seed).
+ */
+const runCli = (args: ReadonlyArray<string>, opts: RunCliOptions = {}) =>
+ runCliRaw(args, { stdin: "", ...opts });
import { fakeCredential } from "../helpers/fake-credentials.ts";
/**
diff --git a/tests/cli/okf-cli.test.ts b/tests/cli/okf-cli.test.ts
index aaaa069d..ac26d80b 100644
--- a/tests/cli/okf-cli.test.ts
+++ b/tests/cli/okf-cli.test.ts
@@ -6,10 +6,17 @@
*/
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
-import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { chmodSync, existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
+import { appendLogEvent } from "../../src/core/brain/log.ts";
+import { withOperationPrivacy } from "../../src/core/store/operation-scope.ts";
+import { STORE_ROOT_ENV } from "../../src/core/store/constants.ts";
+import { makeStoreEnv, type StoreEnv } from "../core/store/fixtures/store-env.ts";
+import { switchDevice } from "../core/brain/store-only/fixtures.ts";
+import { CHMOD_CANNOT_DENY } from "../helpers/platform.ts";
+import { logShardsOf } from "../core/store/fixtures/log-shards.ts";
import { runCli } from "../helpers/run-cli.ts";
let tmp: string;
@@ -84,3 +91,79 @@ describe("o2b brain okf-export / okf-import", () => {
expect(r.returncode).not.toBe(0);
});
});
+
+describe("okf-export on a switched machine", () => {
+ let env: StoreEnv;
+ beforeEach(() => {
+ env = makeStoreEnv("o2b-okf-cli-store-");
+ switchDevice(env.storeRoot);
+ });
+ afterEach(() => env.cleanup());
+
+ const cliEnv = (): Record<string, string> => ({
+ OPEN_SECOND_BRAIN_CONFIG: env.configPath,
+ [STORE_ROOT_ENV]: env.storeRoot,
+ });
+
+ test.each([[[]], [["--include-prompt-derived"]]])(
+ "one private event is named on stderr and counted in okf.json (flags %j)",
+ async (flags: string[]) => {
+ withOperationPrivacy(true, () => {
+ appendLogEvent(env.vault, {
+ timestamp: "2026-06-01T09:00:00Z",
+ eventType: "note",
+ body: { text: "private diary event" },
+ });
+ });
+ const out = join(env.parent, "bundle");
+ const r = await runCli(["brain", "okf-export", "--out", out, ...flags], { env: cliEnv() });
+ expect(r.returncode).toBe(0);
+ expect(r.stderr).toContain("left 1 private log entry out of log.md");
+ const manifest = JSON.parse(readFileSync(join(out, "okf.json"), "utf8")) as {
+ log_private_omitted?: unknown;
+ };
+ expect(manifest.log_private_omitted).toBe(1);
+ },
+ );
+
+ test("nothing private: no notice, and okf.json counts zero", async () => {
+ appendLogEvent(env.vault, {
+ timestamp: "2026-06-01T09:00:00Z",
+ eventType: "note",
+ body: { text: "a shared event" },
+ });
+ const out = join(env.parent, "bundle");
+ const r = await runCli(["brain", "okf-export", "--out", out], { env: cliEnv() });
+ expect(r.returncode).toBe(0);
+ expect(r.stderr).not.toContain("private log entr");
+ const manifest = JSON.parse(readFileSync(join(out, "okf.json"), "utf8")) as {
+ log_private_omitted?: unknown;
+ };
+ expect(manifest.log_private_omitted).toBe(0);
+ });
+
+ test.skipIf(CHMOD_CANNOT_DENY)(
+ "an unreadable private log shard fails the verb and writes no bundle",
+ async () => {
+ withOperationPrivacy(true, () => {
+ appendLogEvent(env.vault, {
+ timestamp: "2026-06-01T09:00:00Z",
+ eventType: "note",
+ body: { text: "kept from the bundle" },
+ });
+ });
+ const [shard] = logShardsOf(env.storeRoot, "private");
+ expect(shard).toBeDefined();
+ chmodSync(shard!, 0o000);
+ try {
+ const out = join(env.parent, "bundle");
+ const r = await runCli(["brain", "okf-export", "--out", out], { env: cliEnv() });
+ expect(r.returncode).not.toBe(0);
+ expect(r.stderr).toMatch(/cannot read log shard\(s\) private\/log\/\S+\.jsonl/);
+ expect(existsSync(join(out, "okf.json"))).toBe(false);
+ } finally {
+ chmodSync(shard!, 0o644);
+ }
+ },
+ );
+});
diff --git a/tests/core/brain/lessons-store-only.test.ts b/tests/core/brain/lessons-store-only.test.ts
index a788355d..eb5592c0 100644
--- a/tests/core/brain/lessons-store-only.test.ts
+++ b/tests/core/brain/lessons-store-only.test.ts
@@ -22,6 +22,7 @@ import {
renderLessonsForReader,
} from "../../../src/core/brain/lessons.ts";
import { writePreference } from "../../../src/core/brain/preference.ts";
+import { withOperationPrivacy } from "../../../src/core/store/operation-scope.ts";
import { RULES_BLOCK_ID } from "../../../src/core/install/rules-block.ts";
import { digestVaultTree } from "../../helpers/vault-digest.ts";
import { makeStoreEnv, type StoreEnv } from "../store/fixtures/store-env.ts";
@@ -94,4 +95,33 @@ describe("lessons with no vault", () => {
expect(narrowed.document).toContain("pref-seen");
expect(narrowed.document).not.toContain("pref-hidden");
});
+
+ test("evidence recorded in the private partition is not counted for a remote reader", () => {
+ env = makeStoreEnv("osb-lessons-private-", { legacyTree: false, configureVault: false });
+ writePreference(null, {
+ slug: "quiet",
+ topic: "quiet",
+ principle: "Rule quiet.",
+ created_at: "2026-11-01T00:00:00Z",
+ unconfirmed_until: "2026-11-02T00:00:00Z",
+ status: "confirmed",
+ confirmed_at: "2026-11-02T00:00:00Z",
+ evidenced_by: ["[[sig-x]]"],
+ confidence_value: 0.9,
+ });
+ withOperationPrivacy(true, () => {
+ for (const artifact of ["[[a]]", "[[b]]"]) {
+ appendApplyEvidence(null, {
+ pref_id: "pref-quiet",
+ artifact,
+ result: "applied",
+ agent: "t",
+ });
+ }
+ });
+ expect(renderLessonsForReader(null, {}).document).toContain("pref-quiet");
+ expect(renderLessonsForReader(null, { withholdsPrivate: true }).document).not.toContain(
+ "pref-quiet",
+ );
+ });
});
diff --git a/tests/core/brain/portability/knowledge-pack.test.ts b/tests/core/brain/portability/knowledge-pack.test.ts
index ec154cad..85027388 100644
--- a/tests/core/brain/portability/knowledge-pack.test.ts
+++ b/tests/core/brain/portability/knowledge-pack.test.ts
@@ -346,6 +346,7 @@ describe("install", () => {
generated_at: "2026-06-01T00:00:00Z",
vault_basename: "evil",
log_days: 0,
+ log_private_omitted: 0,
pages: [
{
id: "planted",
@@ -437,6 +438,7 @@ describe("install", () => {
generated_at: "",
vault_basename: "x",
log_days: 0,
+ log_private_omitted: 0,
pages: [
{
id: "n",
diff --git a/tests/core/brain/portability/okf-store-only.test.ts b/tests/core/brain/portability/okf-store-only.test.ts
index e32e38a9..9cce6bbb 100644
--- a/tests/core/brain/portability/okf-store-only.test.ts
+++ b/tests/core/brain/portability/okf-store-only.test.ts
@@ -7,7 +7,7 @@
* `okf.test.ts`.
*/
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
-import { existsSync, mkdirSync, writeFileSync } from "node:fs";
+import { chmodSync, existsSync, mkdirSync, rmSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import { appendLogEvent } from "../../../../src/core/brain/log.ts";
@@ -25,7 +25,11 @@ import { writeLanePage } from "../../../../src/core/store/lane-pages.ts";
import { withOperationPrivacy } from "../../../../src/core/store/operation-scope.ts";
import { parseFrontmatterText } from "../../../../src/core/vault.ts";
import { partitionRecords } from "../store-only/fixtures.ts";
+import { neverHeld } from "../../../helpers/held-partitions.ts";
+import { CHMOD_CANNOT_DENY } from "../../../helpers/platform.ts";
import { digestVaultTree } from "../../../helpers/vault-digest.ts";
+import { StoreUnavailableError } from "../../../../src/core/store/read/protection-store.ts";
+import { copySharedLogIntoPrivate, logShardsOf } from "../../store/fixtures/log-shards.ts";
import { makeStoreEnv, type StoreEnv } from "../../store/fixtures/store-env.ts";
import { switchDevice } from "../store-only/fixtures.ts";
@@ -123,3 +127,109 @@ describe("importOkfBundle on a switched machine", () => {
);
});
});
+
+describe("private log events in the bundle", () => {
+ test("a private event leaves log.md, counted in the manifest", () => {
+ appendLogEvent(env.vault, {
+ timestamp: "2026-06-01T09:00:00Z",
+ eventType: "note",
+ body: { text: "a shared event" },
+ });
+ withOperationPrivacy(true, () => {
+ appendLogEvent(env.vault, {
+ timestamp: "2026-06-02T09:00:00Z",
+ eventType: "note",
+ body: { text: "a private event" },
+ });
+ });
+
+ const bundle = buildOkfBundle(env.vault);
+ const log = fileOf(bundle.files, "log.md");
+ expect(log).toContain("a shared event");
+ expect(log).not.toContain("a private event");
+ expect(bundle.manifest.log_days).toBe(1);
+ expect(bundle.manifest.log_private_omitted).toBe(1);
+ });
+
+ test("a machine that never held private counts zero", () => {
+ neverHeld(env.storeRoot);
+ appendLogEvent(env.vault, {
+ timestamp: "2026-06-01T09:00:00Z",
+ eventType: "note",
+ body: { text: "the only event" },
+ });
+ const bundle = buildOkfBundle(env.vault);
+ expect(bundle.manifest.log_private_omitted).toBe(0);
+ expect(fileOf(bundle.files, "log.md")).toContain("the only event");
+ });
+
+ test.skipIf(CHMOD_CANNOT_DENY)("an unreadable private log shard refuses the export", () => {
+ withOperationPrivacy(true, () => {
+ appendLogEvent(env.vault, {
+ timestamp: "2026-06-01T09:00:00Z",
+ eventType: "note",
+ body: { text: "kept from the bundle" },
+ });
+ });
+ const [shard] = logShardsOf(env.storeRoot, "private");
+ expect(shard).toBeDefined();
+ chmodSync(shard!, 0o000);
+ try {
+ expect(() => buildOkfBundle(env.vault)).toThrow(/cannot read log shard\(s\) private\/log\//);
+ } finally {
+ chmodSync(shard!, 0o644);
+ }
+ });
+
+ test("a record in both partitions is private, out of log.md, counted", () => {
+ appendLogEvent(env.vault, {
+ timestamp: "2026-06-01T09:00:00Z",
+ eventType: "note",
+ body: { text: "in both" },
+ });
+ // The same record id in both partitions, as two devices that disagree
+ // on its partition would leave it.
+ copySharedLogIntoPrivate(env.storeRoot);
+
+ const bundle = buildOkfBundle(env.vault);
+ expect(fileOf(bundle.files, "log.md")).not.toContain("in both");
+ expect(bundle.manifest.log_private_omitted).toBe(1);
+ });
+
+ test("a store that cannot be opened refuses the export", () => {
+ appendLogEvent(env.vault, {
+ timestamp: "2026-06-01T09:00:00Z",
+ eventType: "note",
+ body: { text: "an event" },
+ });
+ // The store opened once, so this machine holds `private`: with its
+ // identity file gone the store no longer opens.
+ rmSync(join(env.storeRoot, "private", "store.json"));
+ expect(() => buildOkfBundle(env.vault)).toThrow(StoreUnavailableError);
+ });
+
+ test("a store-only machine never switched, with a corrupt store, refuses the export", () => {
+ // No switch marker: store-only because the vault has no legacy tree.
+ const plain = makeStoreEnv("osb-okf-unswitched-store-", { legacyTree: false });
+ try {
+ appendLogEvent(plain.vault, {
+ timestamp: "2026-06-01T09:00:00Z",
+ eventType: "note",
+ body: { text: "an event" },
+ });
+ writeFileSync(join(plain.storeRoot, "shared", "store.json"), "{ not json");
+ expect(() => buildOkfBundle(plain.vault)).toThrow(StoreUnavailableError);
+ } finally {
+ plain.cleanup();
+ }
+ });
+
+ test("an explicit vault with no legacy tree, over a corrupt store, refuses the export", () => {
+ // The configured vault still has its legacy tree (env.vault); the
+ // export names another vault, which is store-only by having none.
+ const other = join(env.parent, "other-vault");
+ mkdirSync(other, { recursive: true });
+ writeFileSync(join(env.storeRoot, "shared", "store.json"), "{ not json");
+ expect(() => buildOkfBundle(other)).toThrow(StoreUnavailableError);
+ });
+});
diff --git a/tests/core/brain/portability/okf.test.ts b/tests/core/brain/portability/okf.test.ts
index 06562ae3..745e00eb 100644
--- a/tests/core/brain/portability/okf.test.ts
+++ b/tests/core/brain/portability/okf.test.ts
@@ -1384,6 +1384,7 @@ describe("v0.2 import acceptance", () => {
generated_at: "2026-06-01T00:00:00Z",
vault_basename: "Packed",
log_days: 0,
+ log_private_omitted: 0,
pages: [
{
id: "runbook",
@@ -1862,6 +1863,7 @@ describe("writeOkfBundle", () => {
vault_basename: "Vault",
pages: [],
log_days: 0,
+ log_private_omitted: 0,
},
files: [{ path: `../${outsideName}/pwned.md`, contents: "nope\n" }],
};
@@ -1874,3 +1876,34 @@ describe("writeOkfBundle", () => {
}
});
});
+
+describe("log_private_omitted on the legacy layout", () => {
+ test("an unswitched vault with log day files counts zero", () => {
+ note("Brain/log/2026-06-01.md", "- a plain day entry\n");
+ const bundle = buildOkfBundle(vault);
+ const log = fileOf(bundle.files, "log.md");
+ expect(log).toContain("a plain day entry");
+ expect(bundle.manifest.log_private_omitted).toBe(0);
+ });
+
+ test("a manifest without log_private_omitted parses with zero", () => {
+ const dir = mkdtempSync(join(tmpdir(), "o2b-okf-omit-"));
+ try {
+ mkdirSync(join(dir, "concepts"), { recursive: true });
+ const manifest = {
+ schema: OKF_SCHEMA_VERSION,
+ producer: OKF_PRODUCER,
+ generated_at: "2026-06-01T00:00:00Z",
+ vault_basename: "Parse",
+ log_days: 2,
+ pages: [],
+ };
+ writeFileSync(join(dir, "okf.json"), JSON.stringify(manifest), "utf8");
+ const parsed = readOkfBundle(dir);
+ expect(parsed.manifest.log_days).toBe(2);
+ expect(parsed.manifest.log_private_omitted).toBe(0);
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
+});
diff --git a/tests/core/store/fixtures/log-shards.ts b/tests/core/store/fixtures/log-shards.ts
new file mode 100644
index 00000000..bfc2feaa
--- /dev/null
+++ b/tests/core/store/fixtures/log-shards.ts
@@ -0,0 +1,34 @@
+/**
+ * The JSONL shards of a store partition's `log` stream, for tests that
+ * make a shard unreadable or put one record into both partitions.
+ */
+import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from "node:fs";
+import { dirname, join, relative } from "node:path";
+
+/** Every `log` stream shard of `partition` in the store at `root`, sorted. */
+export function logShardsOf(root: string, partition: "shared" | "private"): string[] {
+ const out: string[] = [];
+ const walk = (dir: string): void => {
+ for (const name of readdirSync(dir).toSorted()) {
+ const path = join(dir, name);
+ if (name.endsWith(".jsonl")) out.push(path);
+ else if (!name.includes(".")) walk(path);
+ }
+ };
+ const base = join(root, partition, "log");
+ if (existsSync(base)) walk(base);
+ return out;
+}
+
+/**
+ * Append every `shared` log line to the same shard under `private/`, so
+ * each of those record ids is present in both partitions.
+ */
+export function copySharedLogIntoPrivate(root: string): void {
+ const shared = join(root, "shared");
+ for (const shard of logShardsOf(root, "shared")) {
+ const target = join(root, "private", relative(shared, shard));
+ mkdirSync(dirname(target), { recursive: true });
+ writeFileSync(target, readFileSync(shard, "utf8"), { flag: "a" });
+ }
+}
diff --git a/tests/core/store/log-events-partition.test.ts b/tests/core/store/log-events-partition.test.ts
new file mode 100644
index 00000000..42056830
--- /dev/null
+++ b/tests/core/store/log-events-partition.test.ts
@@ -0,0 +1,63 @@
+/**
+ * The partition of a store log event (design D2 of lane-pages-split):
+ * every event read from the store carries the partition its record was
+ * read from, and the report is `null` on an unswitched vault. The export
+ * rules built on it (private wins for a record in both partitions, the
+ * refusal on an unreadable shard) are proven at the export, in
+ * `tests/core/brain/portability/okf-store-only.test.ts`.
+ */
+import { beforeEach, afterEach, describe, expect, test } from "bun:test";
+import { appendLogEvent } from "../../../src/core/brain/log.ts";
+import {
+ readStoreLogEvents,
+ readStoreLogEventsReport,
+} from "../../../src/core/store/read/log-events.ts";
+import { withOperationPrivacy } from "../../../src/core/store/operation-scope.ts";
+import { makeStoreEnv, type StoreEnv } from "./fixtures/store-env.ts";
+import { switchDevice } from "../brain/store-only/fixtures.ts";
+
+let env: StoreEnv;
+
+beforeEach(() => {
+ env = makeStoreEnv("osb-log-partition-");
+ switchDevice(env.storeRoot);
+});
+
+afterEach(() => env.cleanup());
+
+/** The whole-log range `log-days.ts` reads. */
+const WHOLE = { from: "1970-01-01", to: "9998-12-31" };
+
+describe("the partition of a store log event", () => {
+ test("an event under withOperationPrivacy(true) is private, one outside it is shared", () => {
+ appendLogEvent(env.vault, {
+ timestamp: "2026-06-01T09:00:00Z",
+ eventType: "note",
+ body: { text: "a shared day" },
+ });
+ withOperationPrivacy(true, () => {
+ appendLogEvent(env.vault, {
+ timestamp: "2026-06-02T09:00:00Z",
+ eventType: "note",
+ body: { text: "a private day" },
+ });
+ });
+ const report = readStoreLogEventsReport(WHOLE, { vault: env.vault });
+ expect(report).not.toBeNull();
+ expect(report?.unreadable).toEqual([]);
+ expect(report?.events.map((e) => [e.entry.body["text"], e.partition])).toEqual([
+ ["a shared day", "shared"],
+ ["a private day", "private"],
+ ]);
+ });
+
+ test("an unswitched vault reads null", () => {
+ const plain = makeStoreEnv("osb-log-unswitched-");
+ try {
+ expect(readStoreLogEventsReport(WHOLE, { vault: plain.vault })).toBeNull();
+ expect(readStoreLogEvents(WHOLE, { vault: plain.vault })).toBeNull();
+ } finally {
+ plain.cleanup();
+ }
+ });
+});
diff --git a/tests/mcp/log-private-reach.test.ts b/tests/mcp/log-private-reach.test.ts
new file mode 100644
index 00000000..e099f651
--- /dev/null
+++ b/tests/mcp/log-private-reach.test.ts
@@ -0,0 +1,97 @@
+/**
+ * A log event of the store's `private` partition below local reach
+ * (review finding F333, the remote side): the `osb://log/{date}` resource
+ * withholds it from a remote caller, whatever it names, and still shows it
+ * to a local one. A shared event of the same day is shown to both.
+ */
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+
+import { appendLogEvent } from "../../src/core/brain/log.ts";
+import { resolveLogEventTraces } from "../../src/core/brain/event-trace.ts";
+import { reachView } from "../../src/core/brain/reach-view.ts";
+import { TRANSPORT_REACH } from "../../src/core/graph/transport-reach.ts";
+import { withOperationPrivacy } from "../../src/core/store/operation-scope.ts";
+import { readResource } from "../../src/mcp/resources.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-log-private-reach-");
+ switchDevice(env.storeRoot);
+});
+afterEach(() => env.cleanup());
+
+describe("osb://log/{date} on a switched machine", () => {
+ test("a private event is withheld from a remote caller, shown to a local one", () => {
+ appendLogEvent(env.vault, {
+ timestamp: "2026-06-01T09:00:00Z",
+ eventType: "note",
+ body: { text: "a shared note" },
+ });
+ withOperationPrivacy(true, () => {
+ appendLogEvent(env.vault, {
+ timestamp: "2026-06-01T10:00:00Z",
+ eventType: "note",
+ body: { text: "a private note that names nothing" },
+ });
+ });
+ const uri = "osb://log/2026-06-01";
+ const remote = readResource({ vault: env.vault, reach: TRANSPORT_REACH.remote }, uri).text;
+ expect(remote).toContain("a shared note");
+ expect(remote).not.toContain("a private note");
+ const local = readResource({ vault: env.vault, reach: TRANSPORT_REACH.local }, uri).text;
+ expect(local).toContain("a shared note");
+ expect(local).toContain("a private note that names nothing");
+ });
+
+ test("a day with only a private event reads as absent to a remote caller", () => {
+ withOperationPrivacy(true, () => {
+ appendLogEvent(env.vault, {
+ timestamp: "2026-06-02T10:00:00Z",
+ eventType: "note",
+ body: { text: "only private" },
+ });
+ });
+ expect(() =>
+ readResource({ vault: env.vault, reach: TRANSPORT_REACH.remote }, "osb://log/2026-06-02"),
+ ).toThrow(/no log events for date/);
+ });
+});
+
+describe("the event trace on a switched machine", () => {
+ test("a private event is withheld from a remote caller, traced for a local one", () => {
+ withOperationPrivacy(true, () => {
+ appendLogEvent(env.vault, {
+ timestamp: "2026-06-03T10:00:00Z",
+ eventType: "note",
+ body: { text: "a private trace that names nothing" },
+ });
+ });
+ const traced = (reach: (typeof TRANSPORT_REACH)[keyof typeof TRANSPORT_REACH]) =>
+ resolveLogEventTraces(env.vault, {
+ date: "2026-06-03",
+ view: reachView(env.vault, reach),
+ });
+ expect(traced(TRANSPORT_REACH.remote)).toEqual([]);
+ expect(traced(TRANSPORT_REACH.local)).toHaveLength(1);
+ });
+});
+
+describe("osb://digest/latest on a switched machine", () => {
+ test("a private event does not reach a remote caller's digest", () => {
+ withOperationPrivacy(true, () => {
+ appendLogEvent(env.vault, {
+ timestamp: new Date().toISOString(),
+ eventType: "note",
+ agent: "@secret-agent",
+ body: { text: "a private note that names nothing" },
+ });
+ });
+ const uri = "osb://digest/latest";
+ const remote = readResource({ vault: env.vault, reach: TRANSPORT_REACH.remote }, uri).text;
+ expect(remote).not.toContain("secret-agent");
+ const local = readResource({ vault: env.vault, reach: TRANSPORT_REACH.local }, uri).text;
+ expect(local).toContain("secret-agent");
+ });
+});
diff --git a/tests/mcp/paths-for-caller.test.ts b/tests/mcp/paths-for-caller.test.ts
index 01feb722..16e922c7 100644
--- a/tests/mcp/paths-for-caller.test.ts
+++ b/tests/mcp/paths-for-caller.test.ts
@@ -9,8 +9,8 @@
*/
import { afterEach, describe, expect, test } from "bun:test";
import { writeFileSync } from "node:fs";
-import { tmpdir } from "node:os";
-import { basename, join, resolve } from "node:path";
+import { homedir, tmpdir } from "node:os";
+import { basename, join, resolve, sep } from "node:path";
import { TRANSPORT_REACH } from "../../src/core/graph/transport-reach.ts";
import { VIEW_TARGET_ENV } from "../../src/core/view/constants.ts";
@@ -45,10 +45,16 @@ describe("pathsForCaller in prose", () => {
test("text that only looks like a path is left as written", () => {
env = makeStoreEnv("osb-paths-lookalike-");
+ // A sibling of the temp root is a lookalike only when the temp root is
+ // not itself under the home root (a `TMPDIR` under `$HOME` makes the
+ // sibling a real home path, which is rewritten as it should be).
+ const tmpUnderHome = resolve(tmpdir()).startsWith(`${resolve(homedir())}${sep}`);
const text = [
"> my old laptop kept it in /home/bob/notes and /Users/alice/x.md",
"GET /v1/models, see /etc/hosts",
- `a sibling of the temp root: ${tmpdir()}x/old.md and ${tmpdir()}-old`,
+ ...(tmpUnderHome
+ ? []
+ : [`a sibling of the temp root: ${tmpdir()}x/old.md and ${tmpdir()}-old`]),
"C:\\Users\\someone\\file.txt",
].join("\n");
expect(remote(env, { body: text })).toEqual({ body: text });