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.
Tasks: harden the brain store
First read openspec/project.md, then this change folder: proposal.md,
design.md, and the spec deltas under specs/; brainstorm.md says why
the design is what it is. This list has three parts: Part Z (tasks 3.16
and 3.8 of brain-store-and-topics), Part C (tasks 3.17 and 3.15) and
Part I (integration). Two executors build Part Z and Part C at the same
time, each in its own checkout of this branch; an integrator then does
Part I. You were started with one line that names your part: do that part
only, and do not touch a box of another part.
Work in order, one section at a time. Before a section, read the design
decision and the spec delta it names. Tick each box (- [x]) as soon as
it is done, so an interrupted run resumes 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. 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, a test that should fail and passes, or one that
should pass and fails for a reason this list does not name), stop at that
task, write what you found into your report file, and end your run.
Environment and rules
These rules bind both executors.
Work only in the checkout you were started in. Set this in every shell before any
buncommand (zfor Part Z,cfor Part C):export TMPDIR=$HOME/.cache/osb-store-hardening-z-tmp # Part C: ...-c-tmp mkdir -p "$TMPDIR"Delete that folder when your part is done.
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 (mkdtempSync(join(tmpdir(), "osb-<name>-"))) and remove them inafterEach.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, comments, docs and tests; no exclamation marks; the product is written "Open Second Brain" in full. No machine paths, host names or account names anywhere in the repository.
During a section run only the test files that section names, with
bun test <file> [<file> ...](add-t "<name>"for one case). Never run the whole suite (bun run test): the integrator runs it once.A test that runs the CLI goes through
runClifromtests/helpers/run-cli.tsand passes an explicit empty stdin, astests/cli/brain-attest.test.tsdoes:runCli(args, { env: env(), stdin: "" }).Do not add
<!-- doc-test: ... -->markers to any doc.Never rebuild
openclaw/index.js, never editCHANGELOG.md,package.jsonoropenspec/changes/brain-store-and-topics/tasks.md: those belong to Part I.A file that is already past 700 lines (
design.md, Goals) gets call-site edits only: an argument, an option property or an import line. Put any logic into a helper in another module.
Part Z: leaving a partition (3.16) and raw lane text (3.8)
Files Part Z owns: src/core/store/held-ledger.ts,
src/core/store/store-open.ts, src/core/store/seen-shards.ts,
src/core/brain/compiled-digest-path.ts,
src/core/store/partition-leave.ts (new), src/cli/store-partition.ts
(new), src/core/store/lane-raw.ts (new), src/core/store/lane-records.ts,
src/core/store/lane-entry-store.ts, src/core/store/lane-pages.ts,
src/core/store/FORMAT.md, and the test files this part names.
Files shared with Part C, where Part Z adds only the lines named here:
src/cli/store.ts, src/cli/command-manifest.ts,
docs/cli-reference.md, docs/brain-store.md.
Part Z must not touch any other file, in particular src/core/store/reader.ts,
src/core/store-migration/journal.ts, src/core/brain/doctor/store-check.ts,
anything under src/mcp/, and the core log readers of design D2.
Your report file is REPORT-part-z.md at the checkout root.
0. Preconditions (Part Z)
- 0.1 Confirm the tree.
git log --oneline -1shows the commit "feat(store): split the lane page store, keep private log events off exports and remote readers (#293)" or a later main.wc -l src/core/store/lane-pages.tsprints 627, andwc -l src/core/store/held-ledger.tsprints 91. These names exist (check each withgrep -n):markerPathandledgerDirinsrc/core/store/held-ledger.ts;ledgerPathandupdateinsrc/core/store/seen-shards.ts;const DIGESTS_DIR = "digests"insrc/core/brain/compiled-digest-path.ts;export function laneTextPartsandexport function sameEntryinsrc/core/store/lane-entry-store.ts;export function readLaneTextandexport function writeLaneTextinsrc/core/store/lane-pages.ts;case "device":insrc/cli/store.ts. On any mismatch, stop and report. - 0.2 Take the baseline. Run
bun test tests/core/store/held-ledger.test.ts tests/core/store/seen-shards.test.ts tests/core/store/store-open.test.ts tests/core/store/protection-store.test.ts tests/core/store/lane-records.test.ts tests/core/store/format-doc.test.ts tests/core/lanes/lane-pages.test.ts tests/cli/store-device.test.ts tests/core/search/brain-store-catch-up.test.ts tests/cli/manifest-completeness.test.ts tests/cli/help-surface-parity.test.ts tests/cli/completions.test.ts tests/core/architecture/import-cycles.test.tsand write the pass and fail counts into the report. Everything should pass; if anything fails, stop and report.
1. Leaving a partition: the core (design D7 items 1 to 4, 6 and 7; spec held-partitions)
- 1.1 Test first: create
tests/core/store/partition-leave.test.ts. Setup per test:parent = mkdtempSync(join(tmpdir(), "osb-partition-leave-")),root = join(parent, "store"),initStore({ root })(both partitions), thenopenStore({ root, device: "dev-a" })(records both held markers in this process's state directory; the test preload isolates it);afterEachremovesparent. ImportleavePartitionandPartitionLeaveRefusalfromsrc/core/store/partition-leave.ts,HeldPartitionLostErrorandopenStorefromsrc/core/store/store-open.ts. Write these cases:- "refuses the shared partition":
leavePartition({ root, partition: "shared" })throws aPartitionLeaveRefusalwithreason"shared". - "refuses while private/store.json is present": with nothing removed,
leavePartition({ root, partition: "private" })throws with reason"still-held". - "a lost private/store.json without the verb still fails closed":
rmSync(join(root, "private"), { recursive: true, force: true });openStore({ root, device: "dev-a" })throwsHeldPartitionLostErrorwhose message containso2b store partition leave privateand still containsfrom sync or a backup. - "leaving private turns the machine shared-only": remove the
privatefolder as in 3;leavePartition({ root, partition: "private" })returnsleft: trueandcleared.heldMarker: true; thenopenStore({ root, device: "dev-a" }).partitionshassharedand notprivate, with no throw. - "nothing to leave changes nothing": after case 4's
leave, a second
leavePartitionreturnsleft: falseandcleared.heldMarker: false. - "files left refuse without force": remove only
join(root, "private", "store.json");leavePartitionthrows reason"files-left";openStorestill throwsHeldPartitionLostError;leavePartition({ root, partition: "private", force: true })returnsleft: true, andopenStorethen succeeds withsharedonly. - "clears the seen shards and the digest caches": before removing
anything, append one record with
appendRecord(openStore({ root, device: "dev-a" }), { partition: "private", stream: "events", kind: "decision", agent: "t", body: { text: "x" } })and read it withreadStreamRecords(root, "private", { stream: "events" })(src/core/store/read/stream-read.ts; this records the shard as seen); take the store id withreadStoreId(join(root, "shared"))(store-open.ts); createjoin(digestCacheRoot(storeId), "k", "active.md")withmkdirSyncandwriteFileSync. Then remove theprivatefolder and leave:cleared.seenShardsis at least 1 andcleared.digestCachesistrue, anddigestCacheRoot(storeId)no longer exists. - "a store.json that returns is held again": after case 4's leave, run
initStore({ root, partitions: ["shared", "private"] })(it createsprivate/store.jsonwith the shared store id), thenopenStore({ root, device: "dev-a" })(records the marker again), then removejoin(root, "private", "store.json"):openStorethrowsHeldPartitionLostErroragain. - "the search index forgets the partition on its next catch-up": use
makeStoreIndexFixtureandLOCAL_DEVICEfromtests/core/search/fixtures/brain-store-index.tsinstead of the setup above (callfx.cleanup()at the end), and setprocess.env[STORE_CATCH_UP_INTERVAL_ENV] = "0"for the test, restoring it after, astests/core/search/brain-store-catch-up.test.tsdoes. Steps:const store = fx.open(LOCAL_DEVICE); ifstore.partitionslacksprivate, stop and report. AppendappendRecord(store, { partition: "private", stream: "events", kind: "decision", agent: "agent-a", body: { text: "the private heron sighting" } });fx.writeNote("notes/a.md", "# A\n\nplain note\n");await indexVault(fx.config());await catchUpBrainStore(fx.config(), { force: true }); a localsearch(fx.config(), { query: "heron sighting", limit: 10, transportReach: TRANSPORT_REACH.local })returns at least one result. ThenrecordHeldPartitions(fx.root, ["shared", "private"])(process state), removejoin(fx.root, "private"),leavePartition({ root: fx.root, partition: "private" }),await catchUpBrainStore(fx.config(), { force: true }), and the same search returns no result. Imports as intests/core/search/brain-store-catch-up.test.ts. - "an unreadable shared store id refuses and changes nothing": set up
as in case 7 (append, read, take
storeId, create the digest cache file), keepconst sharedId = join(root, "shared", "store.json")and its text (readFileSync(sharedId, "utf8")), remove theprivatefolder, then write"{"tosharedId.leavePartition({ root, partition: "private" })throws aPartitionLeaveRefusalwith reason"no-store-id"whose message containssharedandstore.json;isHeldPartitionMarked(root, "private")(src/core/store/held-ledger.ts) is stilltrue, andjoin(digestCacheRoot(storeId), "k", "active.md")still exists. The same holds withsharedIdremoved (rmSync(sharedId)) instead of corrupted. Then write the saved text back tosharedId: the leave returnsleft: true,cleared.seenShardsat least 1 andcleared.digestCachestrue. Runbun test tests/core/store/partition-leave.test.ts: it fails (the module does not exist). Note the failure in the report.
- "refuses the shared partition":
- 1.2 In
src/core/store/held-ledger.tsadd, belowlostHeldPartitions:export function isHeldPartitionMarked(root: string, partition: StorePartition): booleanreturningexistsSync(markerPath(ledgerDir(), root, partition)), andexport function forgetHeldPartition(root: string, partition: StorePartition): booleanthat returnsfalsewhen the marker does not exist, otherwise removes it withrmSync(marker, { force: true })and returnstrue(importrmSyncfromnode:fs). Replace the docblock paragraph that starts "No command takes a partition off this record" with: "One command takes a partition off this record:o2b store partition leave <partition>(partition-leave.ts), once the partition's identity file is gone. The other remedy is to restore the identity file (sync, or a backup). The list is keyed by the store root as configured, like the switch marker." - 1.3 In
src/core/store/seen-shards.ts: addfunction seenLedgerFile(storeRoot: string, storeId: string): stringholding the file-name lines ofledgerPath(therootKeyhash ofresolve(storeRoot), theSEEN_SHARDS_FILErename, thejoinwithdeviceStateDirFor(storeId, processDirsEnv())), and makeledgerPathcall it withdirname(partitionRoot)(behaviour unchanged). Addexport function forgetSeenPartition(storeRoot: string, storeId: string, partition: StorePartition): number:path = seenLedgerFile(storeRoot, storeId);count = load(path).get(partition)?.size ?? 0; whencount > 0,update(path, (ledger) => { ledger.delete(partition); })and then, becauseupdatenever throws, check that the write landed: when(load(path).get(partition)?.size ?? 0) > 0, thrownew Error(\could not clear the seen-shard entries of the ${partition} partition in ${path}`); returncount. Extend the module docblock with one sentence: leaving a partition (partition-leave.ts`) clears its entries. - 1.4 In
src/core/brain/compiled-digest-path.tsaddexport function digestCacheRoot(storeId: string): stringreturningjoin(deviceStateDirFor(storeId), DIGESTS_DIR), with a one-line doc comment ("The folder of every digest cache of the storestoreId"). - 1.5 Create
src/core/store/partition-leave.tswith a header comment (what it does, design D7 of changestore-hardening, and that astore.jsonthat returns is held again byrecordHeldPartitions). Contents:export class PartitionLeaveRefusal extends Errorwithconstructor(readonly reason: "shared" | "still-held" | "files-left" | "no-store-id" | "clear-failed", message: string)andthis.name = "PartitionLeaveRefusal".export interface LeavePartitionResult { readonly left: boolean; readonly partition: StorePartition; readonly cleared: { readonly heldMarker: boolean; readonly seenShards: number; readonly digestCaches: boolean } }.export function leavePartition(options: { readonly root: string; readonly partition: StorePartition; readonly force?: boolean }): LeavePartitionResult, in exactly this order:partition === "shared": throw reason"shared", messagethe shared partition holds every rule of the brain store; leaving it is leaving the store, which this command does not do.dir = partitionDir(root, partition); whenexistsSync(join(dir, STORE_IDENTITY_FILE))(constant from./constants.ts): throw reason"still-held", message`${join(dir, STORE_IDENTITY_FILE)} is still here, so this machine still holds the ${partition} partition; stop syncing ${dir}, remove the folder, then run the command again`.- When
!isHeldPartitionMarked(root, partition): return{ left: false, partition, cleared: { heldMarker: false, seenShards: 0, digestCaches: false } }. left = existsSync(dir) ? readdirSync(dir) : []; whenleft.length > 0 && options.force !== true: throw reason"files-left", message`${dir} still holds ${left.length} item(s) of the ${partition} partition without its ${STORE_IDENTITY_FILE}; remove the folder, or pass --force to leave the partition anyway (its files are then ignored on this machine)`.- Before anything is removed:
storeId = readStoreId(partitionDir(root, "shared")), treating anullreturn and any thrown error alike (catch every error). When there is no store id: throw reason"no-store-id", message`${join(partitionDir(root, "shared"), STORE_IDENTITY_FILE)} is missing or unreadable, so the device-local state of the ${partition} partition cannot be found; restore the shared partition's identity file first (sync, or a backup), then run the command again`. Nothing has changed at this point. - Clear the device-local state first and the marker last, so a
failure leaves the machine still holding the partition (it fails
closed, and
HeldPartitionLostErrorstill names the verb). Inside onetry:cacheDir = digestCacheRoot(storeId),existed = existsSync(cacheDir),rmSync(cacheDir, { recursive: true, force: true }),digestCaches = existed; thenseenShards = forgetSeenPartition(root, storeId, partition). In itscatch (err): throw reason"clear-failed", message`could not clear this machine's state of the ${partition} partition (${err instanceof Error ? err.message : String(err)}); the partition is still held here; fix the cause, then run the command again`. - Only now
heldMarker = forgetHeldPartition(root, partition). - Return
{ left: true, partition, cleared: { heldMarker, seenShards, digestCaches } }. It must not importsrc/core/store/reader.tsdirectly, nor anything undersrc/mcp/.
- 1.6 In
src/core/store/store-open.ts,HeldPartitionLostError: keep the message as it is and replace its last string piece"from sync or a backup"by`from sync or a backup, or run ${partitions.map((p) => `\`o2b store partition leave ${p}\).join(" and ")} to stop holding ${partitions.length > 1 ? "them" : "it"} on this machine``. Runbun test tests/core/store/partition-leave.test.ts tests/core/store/held-ledger.test.ts tests/core/store/seen-shards.test.ts tests/core/store/store-open.test.ts tests/core/store/protection-store.test.ts`: everything passes. If case 9 of 1.1 fails because the index still returns the record after the catch-up, stop and report (do not change any search module).
2. Leaving a partition: the verb and the docs (design D7 item 5, D9; spec held-partitions)
- 2.1 Test first: create
tests/cli/store-partition.test.ts, with the setup oftests/cli/store-device.test.ts(parent,root) and thisenv():{ [STORE_ROOT_ENV]: root, HOME: join(parent, "home"), XDG_STATE_HOME: join(parent, "state"), LOCALAPPDATA: join(parent, "state"), OPEN_SECOND_BRAIN_CONFIG: join(parent, "config.yaml"), O2B_DEVICE_ID: "dev-a" }. Every test first runsrunCli(["store", "init"], { env: env(), stdin: "" })and expects exit 0 (this records both held markers in the test's state folder). Cases:- "shared is refused":
store partition leave sharedexits 1 and stderr containsshared partition; with--json, stdout parses to{ ok: false, reason: "shared" }(pluserror). - "a present store.json is refused":
store partition leave privateexits 1;--jsonreason"still-held". - "a lost private partition fails closed and names the verb": remove
join(root, "private");store device listexits 1 and stderr containso2b store partition leave private. - "leaving private": after removing the folder,
store partition leave private --jsonexits 0 and stdout parses to an object withok: true,left: true,partition: "private"andcleared.held_marker: true; thenstore device listexits 0. - "the text answer": the same without
--jsonexits 0 and stdout containsLeft the private partition,next catch-upandholds the private partition again. - "leaving twice": a second
--jsonrun exits 0 withleft: false; its text form saysnothing to leave. - "files left": remove only
join(root, "private", "store.json"); the verb exits 1 with--jsonreason"files-left"; with--forceit exits 0 andleft: true. - "usage errors":
store partition leave(no partition),store partition leave bogus,store partition leave private extraandstore partition(no verb) each exit 2 and stderr starts witherror:and containsusage: o2b store partition leave; with--jsoneach prints on stdout an object that parses to{ ok: false, reason: "usage" }with a stringerror. - "an unreadable shared store id is refused": remove
join(root, "private")and write"{"tojoin(root, "shared", "store.json");store partition leave private --jsonexits 1 and stdout parses to{ ok: false, reason: "no-store-id" }with anerrorthat containsrestore the shared partition's identity file first; without--jsonstderr starts witherror:and stdout is empty. Runbun test tests/cli/store-partition.test.ts: it fails. Note it.
- "shared is refused":
- 2.2 Create
src/cli/store-partition.tson the model ofsrc/cli/store-device.ts(itsEXIT,parse,usage,refusehelpers copied and adapted; header comment with the exit codes):export const STORE_PARTITION_USAGE = "usage: o2b store partition leave <partition> [--force] [--config <file>] [--json]".export function cmdStorePartition(argv: ReadonlyArray<string>): number:-h/--helpprints the usage and returns 0; a first argument other thanleave(or none) is a usage error (exit 2, messagemissing store partition verborunknown store partition verb: <verb>).leave: flagsforce(boolean),config(string),json(boolean); exactly one positional, which must be one ofSTORE_PARTITIONS(src/core/store/constants.ts), else a usage errorname the partition to leave (shared or private)orunknown partition: <name>orunexpected argument: <arg>.- Resolve
rootwithresolveConfiguredStoreRoot(configPath).root(src/core/store/store-paths.ts), callleavePartition. Refusals (exit 1):PartitionLeaveRefusal(itsreason:shared,still-held,files-left,no-store-idorclear-failed),StoreRootInsideVaultError("store-root-in-vault"),ConfigReadError("config", fromsrc/core/config.ts). Anything else propagates. - Output shapes, exactly those of
store-device.ts'srefuseandusagehelpers: a refusal writeserror: <message>\nto stderr and, under--json,{ ok: false, reason, error }(withsortedReplacer, two-space indent, a final newline) to stdout; a usage error writeserror: <message>\n<STORE_PARTITION_USAGE>\nto stderr and, when the arguments contain--json,{ ok: false, reason: "usage", error }to stdout. Nothing else is written on a refusal or a usage error. - Text answer when
left:`Left the ${partition} partition of the brain store at ${root} on this machine.\n cleared: held marker, ${seenShards} seen shard entr${seenShards === 1 ? "y" : "ies"}, ${digestCaches ? "digest caches" : "no digest cache"}\nThe search index drops the ${partition} partition's records on its next catch-up. If ${join(root, partition, "store.json")} returns, by sync or a restore, this machine holds the ${partition} partition again from its next store write.\n`. When notleft:`This machine does not hold the ${partition} partition of the brain store at ${root}; nothing to leave. If ${join(root, partition, "store.json")} arrives, by sync or a restore, this machine holds the ${partition} partition again from its next store write.\n`. - JSON answer (with
sortedReplacerfrom./helpers.ts, two-space indent):{ ok: true, left, partition, root, cleared: { held_marker, seen_shards, digest_caches } }.
- 2.3 In
src/cli/store.tsadd exactly: the importimport { cmdStorePartition, STORE_PARTITION_USAGE } from "./store-partition.ts";after thestore-device.tsimport;\n${STORE_PARTITION_USAGE}at the end of theUSAGEtemplate; and, right after thecase "device":return line,case "partition":returningcmdStorePartition(rest). Add one sentence to the file's header comment: "partition leavetakes a partition off this machine (store-partition.ts)." Insrc/cli/command-manifest.ts, inside thestorecommand, right after thedeviceentry, add:command("partition", "Take a partition off this machine on purpose", [flag("config", "string"), flag("json", "boolean")], [command("leave", "Stop holding a partition whose folder is gone (never shared)", [flag("force", "boolean")])]). Runbun test tests/cli/store-partition.test.ts tests/cli/store-device.test.ts tests/cli/manifest-completeness.test.ts tests/cli/help-surface-parity.test.ts tests/cli/completions.test.ts: everything passes. If a manifest or parity test fails, fix only the manifest entry or the usage text; if it needs anything else, stop and report. - 2.4 Docs. In
docs/cli-reference.md, right after the line that startso2b store device list|retire, add one line in the same two-column style:o2b store partition leave Take a partition off this machine on purpose, once its folder no longer carries store.json (stop syncing it and remove the folder first): removes this machine's held marker for it, clears its seen-shard entries and the digest caches, and the search index drops its records on its next catch-up. Refuses shared, a partition whose store.json is still there, a folder that still holds files unless --force, and a store whose shared/store.json is missing or unreadable (restore it first; nothing is changed); leaving a partition this machine does not hold exits 0 and changes nothing. A store.json that returns by sync or a restore makes the machine hold the partition again. --config, --json. Exit 0 for an answer, 1 for a refusal (shared, still-held, files-left, no-store-id, clear-failed, a store root inside the vault, an unreadable config), 2 for a usage error. Indocs/brain-store.md, at the end of the section "## Setup" (right before the heading## Syncing), add a subsection### Leaving a partitionof one or two short paragraphs and one fencedshblock (o2b store partition leave private) that says: a machine that held a partition refuses every store command once that partition'sstore.jsonis gone; to take the partition off on purpose, stop syncing its folder, remove the folder, and run the command; what the command clears; that it refusesshared, and refuses (changing nothing) whileshared/store.jsonis missing or unreadable, so restore that file first; that a returningstore.jsonmakes the machine hold the partition again. Runbun test tests/docsand expect the same result as before your edit (run it once before editing to compare); a new failure that names your text: fix your text.
3. Raw lane text (design D8; spec lane-entry-fidelity)
- 3.1 Test first: create
tests/core/store/lane-raw.test.tsfor the new modulesrc/core/store/lane-raw.ts(functionsrenderLaneText,rawParsesBack,rawToKeep,lanePrivacyRow,laneTextParts). For each case, compute{ fields, body } = laneTextParts(path, raw)first. Cases:- "a page the parts reproduce keeps no raw":
path = "x.md",rawisrenderLaneText("x.md", { kind: "k" }, "Body.\n");rawToKeepreturnsundefined. - "a page without frontmatter keeps its raw":
raw = "Just text.\n";rawToKeep("x.md", raw, fields, body)returnsraw. - "a quoted value keeps its raw":
raw = "---\nid: '123'\n---\nBody.\n";fields.idis the string"123"andrawToKeepreturnsraw(ifrenderLaneTextalready writesid: '123'byte for byte, useid: "123"instead and say so in the report). - "CRLF keeps its raw":
raw = "---\r\nkind: k\r\n---\r\nBody.\r\n";rawToKeepreturnsraw. - "a missing final newline keeps its raw":
raw = "---\nkind: k\n---\nBody.". - "JSON formatting keeps its raw":
path = "x.json",raw = '{"a":1}\n'. - "plain text never needs raw":
path = "x.txt",raw = "a\nb":rawToKeepreturnsundefined. - "a raw that does not parse back is not kept":
rawToKeep("x.md", "---\nkind: other\n---\nBody.\n", { kind: "k" }, "Body.\n")returnsundefined, andrawParsesBackwith the same arguments isfalse. - "renderLaneText is the reader's rendering":
.mdgivesformatFrontmatter(fields, text)(src/core/vault.ts);.jsonwith empty text givesJSON.stringify(fields, null, 2) + "\n";.jsonwith text gives the text; another extension gives the text. - "the privacy row":
lanePrivacyRow({ a: 1 }, "t")deep-equals{ fields: { a: 1 }, text: "t" }, and with a third argument"r"deep-equals{ fields: { a: 1 }, text: "t", raw: "r" }. Runbun test tests/core/store/lane-raw.test.ts: it fails. Note it.
- "a page the parts reproduce keeps no raw":
- 3.2 Create
src/core/store/lane-raw.ts(header comment: what it holds, design D8 of changestore-hardening). MovelaneTextPartsthere verbatim fromsrc/core/store/lane-entry-store.tswith its doc comment, and inlane-entry-store.tsreplace it withexport { laneTextParts } from "./lane-raw.ts";plus animport { laneTextParts } from "./lane-raw.ts";for its own use (remove only imports the compiler then reports unused). Add:export function renderLaneText(path: string, fields: Readonly<Record<string, unknown>>, text: string): string:path.endsWith(".md")givesformatFrontmatter(fields as FrontmatterMap, text);path.endsWith(".json") && text === ""gives`${JSON.stringify(fields, null, 2)}\n`; otherwisetext.export function rawParsesBack(path: string, raw: string, fields: Readonly<Record<string, unknown>>, text: string): boolean:const parts = laneTextParts(path, raw); return parts.body === text && canonicalJson(parts.fields) === canonicalJson(fields);(canonicalJsonfrom../integrity/digest.ts).export function rawToKeep(path: string, raw: string | undefined, fields: Readonly<Record<string, unknown>>, text: string): string | undefined:undefinedwhenraw === undefined, whenrenderLaneText(path, fields, text) === raw, or when!rawParsesBack(path, raw, fields, text); otherwiseraw.export function lanePrivacyRow(fields: Readonly<Record<string, unknown>>, text: string, raw?: string): Record<string, unknown>:raw === undefined ? { fields, text } : { fields, text, raw }.lane-raw.tsimports only fromnode:*,../vault.ts,../integrity/digest.tsand../types.ts. Runbun test tests/core/store/lane-raw.test.ts tests/core/architecture/import-cycles.test.ts: both pass.
- 3.3 Test first, in
tests/core/store/lane-records.test.ts, three cases: "laneEntryRecord writes raw only when given" (body.rawis absent withoutrawand equals it withraw: "x"); "the fold carries a string raw" (foldLaneEntriesover a record built withraw: "x"gives an entry whosevalue.rawis"x"); "the fold ignores a raw that is not a string" (a record whosebody.rawis5folds with no rejection andvalue.rawisundefined). Build the records as that file'sentryhelper does:rec({ physical: 1, kind: LANE_ENTRY_KIND, body: authored("agent", { lane: "obligations", entry: "obl-a", fields: { s: 1 }, text: "t", raw: "x" }) })(recandauthoredfromtests/core/store/fixtures/fold-records.ts;raw: 5for the third case), fold withfoldLaneEntries([record]), read the value with.entries.get(laneEntryKey("obligations", "obl-a"))!.value, and assertfold.rejectedis empty for the third case. For the first case calllaneEntryRecordwith the input of the file's first test ("the builder writes the generic events record"), once without and once withraw: "x". These three cases verify the requirement "The raw field is optional and never rejects a record" of speclane-entry-fidelity. Run the file: the new cases fail. Then insrc/core/store/lane-records.ts:laneEntryRecord's input gainsreadonly raw?: string, and itsbodygains...(input.raw !== undefined ? { raw: input.raw } : {})aftertext;LaneEntryValuegainsreadonly raw?: string(doc comment: "The file's text byte for byte, when the fields and text do not reproduce it; served only when it parses back to them (lane-raw.ts)"); infoldLaneEntriesthe value gains...(typeof record.body["raw"] === "string" ? { raw: record.body["raw"] } : {}).rejectionis not changed. Run the file again: everything passes. - 3.4 Test first, in
tests/core/lanes/lane-pages.test.ts, a newdescribe("raw lane text on a store-only machine", ...)that usesmakeLaneEnv("store")only, with these cases:- "a page without frontmatter reads back verbatim":
writeLaneTextofJust text.\ntojoin(lane.vault, "Brain", "obligations", "obl-raw.md");readLaneTextreturnsJust text.\n. - "a quoted value reads back verbatim": text
---\nid: '123'\n---\nBody.\n(or the variant 3.1 case 3 chose) reads back verbatim, andreadLanePage(...)!.frontmatter.idis the string"123". - "CRLF and a missing final newline read back verbatim".
- "JSON formatting reads back verbatim":
{"a":1}\nto.../obligations/raw.json. - "a rewrite that changes only quoting is written": write
---\nid: '123'\n---\nBody.\n, then---\nid: "123"\n---\nBody.\n:lane.laneRecords().filter((r) => r.kind === "lane-entry")grows by one and the read returns the second text; writing the second text again adds no record. - "a structured write replaces the raw": after case 1's write,
writeLanePage(vault, page, { kind: "k" }, "New.\n", { overwrite: true })thenreadLaneTextreturnsformatFrontmatter({ kind: "k" }, "New.\n"). - "a move keeps the raw": after case 1's write,
moveLanePage(vault, page, join(dir, "obl-moved.md"))and the new path reads backJust text.\n;moveLaneTreeof the folder to another folder keeps it too. - "a private region in a frontmatter comment sends the entry to
private": text
---\n# <private>secret</private>\nkind: k\n---\nBody.\n;lane.laneRecords("shared")is empty andlane.laneRecords("private")has the entry. - "a reference only in the raw text is judged": text
---\n# see [[pref-nowhere-raw]]\nkind: k\n---\nBody.\nlands inprivate(a preference id with no record cannot be judged and counts as private); the same page without the comment line lands inshared. If the second half lands inprivatetoo, or the first inshared, stop and report (do not change the reference judge). - "a raw that does not parse back is not served": append a
lane-entryrecord by hand whosebodyhasfields: { kind: "k" },text: "Body.\n"andraw: "---\nkind: other\n---\nBody.\n", as the test "stays in the shared partition it lives in, tombstone and copy alike" of this file appends one:appendRecord(openStore({ root: lane.env.storeRoot, device: "dev-b" }), { partition: "shared", stream: "events", kind: "lane-entry", agent: "t", body: { authority: "agent", lane: "obligations", entry: "obl-hand", fields: { kind: "k" }, text: "Body.\n", raw: "---\nkind: other\n---\nBody.\n" } });readLaneTextofjoin(lane.vault, "Brain", "obligations", "obl-hand.md")returnsformatFrontmatter({ kind: "k" }, "Body.\n"). - "a hand-appended shared raw with a frontmatter comment is served as
written": append as in case 10 (entry
obl-hand-comment) a record whoserawis---\n# see [[pref-nowhere-raw]]\nkind: k\n---\nBody.\n, withfields: { kind: "k" }andtext: "Body.\n";readLaneTextreturns thatrawbyte for byte, comment included. This pins the trust boundary of design D8 item 5: the writer's judge is the only judge ofraw, as oftext, and the read-side check only proves the raw parses back. If the read returns the rendering instead, stop and report. Runbun test tests/core/lanes/lane-pages.test.ts: the new cases fail (except 8, which may already pass, and 10, whose record already reads as the rendering: say so in the report).
- "a page without frontmatter reads back verbatim":
- 3.5 Implement D8 items 3 and 4.
In
src/core/store/lane-entry-store.ts:sameEntry(value, fields, text, raw?: string)adds&& value.raw === rawto its condition;isPrivateEntry(vault, fields, text, raw?: string)passeslanePrivacyRow(fields, text, raw)torowNamesPrivatePageinstead of{ fields, text };entryRecordgains a last parameterraw?: string(afterplacement), computesconst kept = rawToKeep(path, raw, fields, text)and passes...(kept !== undefined ? { raw: kept } : {})tolaneEntryRecord. Insrc/core/store/lane-pages.ts:readLaneText, store branch: afterif (value === null) return null;useif (value.raw !== undefined && rawParsesBack(path, value.raw, value.fields, value.text)) return value.raw;andreturn renderLaneText(path, value.fields, value.text);(replacing the two former return lines).writeLaneText: in the held-in-store check computeconst raw = rawToKeep(path, text, fields, body);afterlaneTextPartsand callsameEntry(storeEntry(vault, path), fields, body, raw); in thestoreclosure computerawthe same way afterlaneTextParts, pass it as the fourth argument ofisPrivateEntryand as the last argument ofentryRecord(with"judged"as theplacementargument before it).moveLanePage: theentryRecordcall gets the last argumentrewrite === undefined ? value.raw : undefined.moveLaneTree: theentryRecordcall gets the last argumentvalue.raw.writeLanePage: no change. Remove only imports the compiler or the linter reports unused. Runbun test tests/core/lanes/lane-pages.test.ts tests/core/store/lane-records.test.ts tests/core/store/lane-raw.test.ts tests/core/lanes: everything passes.wc -l src/core/store/lane-pages.tsstays under 700 (expected about 630).
- 3.6
src/core/store/FORMAT.md: in thelane-entrybullet, write the shape as{ "authority", "lane": "<lane>", "entry": "<entry id>", "fields": { ... }, "text": "<Markdown>", "raw": "<file text>" (optional) }and add, after the sentence abouttext, these sentences: "raw, when present, is the file's text byte for byte, written only whenfieldsandtextdo not reproduce it (a page without frontmatter, a quoted value, CRLF line ends, the formatting of a JSON file). A reader servesrawonly when it parses back to the record's ownfieldsandtext, and rendersfieldsandtextotherwise; a reader that does not knowrawignores it.rawcounts for the entry's privacy likefieldsandtext, and spills into a blob with the rest of the body." Do not touch the first line (the format version marker). Runbun test tests/core/store/format-doc.test.ts: it passes.
4. Closing checks (Part Z)
- 4.1 Run each, one at a time, and fix what they report in your own
files:
bunx tsc --noEmit -p .,bun run lint,bun run fmt:check(runbun run fmtto fix formatting, then check again),bun run check:paths. - 4.2 Run every test file Part Z touched or created once more, in one
command:
bun test tests/core/store/partition-leave.test.ts tests/cli/store-partition.test.ts tests/core/store/lane-raw.test.ts tests/core/store/lane-records.test.ts tests/core/lanes/lane-pages.test.ts tests/core/store/held-ledger.test.ts tests/core/store/seen-shards.test.ts tests/core/store/store-open.test.ts tests/core/store/protection-store.test.ts tests/core/store/format-doc.test.ts tests/cli/store-device.test.ts tests/core/search/brain-store-catch-up.test.ts tests/cli/manifest-completeness.test.ts tests/cli/help-surface-parity.test.ts tests/cli/completions.test.ts tests/core/architecture/import-cycles.test.ts tests/docs. All pass.wc -lof every source file Part Z changed or created is under 700 (command-manifest.tsexcepted: it was past 700 before).git status --shortlists only Part Z's files (plus.apb/.gitignore, which is not yours: leave it).
5. Report (Part Z)
- 5.1 Write
REPORT-part-z.mdat the checkout root (never commit it; at most 60 lines): every Part Z box ticked or why not; the baseline and final test counts; the line counts oflane-pages.ts,lane-entry-store.ts,lane-raw.ts,partition-leave.ts,store-partition.ts; every place where the code did not match this brief and what you did; the choices this brief left to you (3.1 case 3, 3.4 case 8);git status --short. Then delete yourTMPDIRfolder.
Part C: private log reads (3.17) and partial shards (3.15)
Files Part C owns: every file design D1 to D6 names (D2's core readers
and MCP call sites, src/mcp/brain/reach-events.ts,
src/core/brain/log-events-at-reach.ts, src/core/brain/temporal/types.ts,
src/core/brain/temporal/build-index.ts, src/core/store/reader.ts,
src/core/store/shard-quarantine.ts (new),
src/core/store-migration/journal.ts,
src/core/brain/doctor/store-check.ts,
src/core/brain/doctor/store-gap-check.ts (new), src/cli/store-shard.ts
(new)), and the test files this part names. Files shared with Part Z,
where Part C adds only the lines named here: src/cli/store.ts,
src/cli/command-manifest.ts, docs/cli-reference.md,
docs/brain-store.md. Part C must not touch Part Z's files (Part Z's
list above), in particular src/core/store/held-ledger.ts,
src/core/store/store-open.ts, src/core/store/seen-shards.ts, the
lane modules and FORMAT.md.
Your report file is REPORT-part-c.md at the checkout root.
0. Preconditions (Part C)
- 0.3 Confirm the tree: the commit of 0.1;
wc -lof the files design "Context" lists past 700 lines matches it (record each count in the report: these are the counts the file may not grow past beyond call-site edits);grep -nfindsexport function requestRefViewinsrc/mcp/brain/reach-events.ts,function normaliseLogEntryinsrc/core/brain/temporal/build-index.ts,export function eventAtReachinsrc/core/brain/log-events-at-reach.ts,res.evidence.map(serializeLogEntry)insrc/mcp/brain/query-tools.ts,export function shardReadGapinsrc/core/store/reader.ts,export function readHeldRecordsinsrc/core/store-migration/journal.ts, andif (s.incomplete !== true) unreadable.push(s);insrc/core/brain/doctor/store-check.ts. Searchsrc/for readers of the index'scorrupt_linescolumn (design D4 item 5): if any code treats it as a gap, stop and report. On any mismatch, stop and report. - 0.4 Take the baseline:
bun test tests/mcp/log-private-reach.test.ts tests/mcp/log-readers-reach.test.ts tests/core/store/reader.test.ts tests/core/store/read-gaps.test.ts tests/core/store/state-digest.test.ts tests/core/brain/doctor-store.test.ts tests/cli/store-device.test.ts tests/cli/manifest-completeness.test.ts tests/cli/help-surface-parity.test.ts tests/cli/completions.test.ts tests/core/architectureplus the existing test files of the core readers of design D2 and of the timeline builders:tests/core/brain/most-applied.test.ts tests/core/brain/store-readers/reader-parity.test.ts tests/core/brain/owner-scope-delivery.test.ts tests/core/brain/morning-brief.test.ts tests/core/brain/idea-discovery.test.ts tests/core/brain.agent-source.query.test.ts tests/core/brain.backlinks.test.ts tests/core/brain/backlinks-owner-scope.test.ts tests/core/brain/status-maintenance-debt.test.ts tests/core/brain/store-only-operator-readers.test.ts tests/core/brain/memory-cost-meter.test.ts tests/core/brain/token-footprint.test.ts tests/core/brain/maintenance-collect.test.ts tests/core/brain.operator-snapshot.test.ts tests/core/brain.idea-lineage.test.ts tests/core/brain/notes/write-log.test.ts tests/core/brain/notes/write-destinations.test.ts tests/core/brain/notes/revert.test.ts tests/core/brain/link-graph/concept-cluster.test.ts tests/core/brain/link-graph/moc-audit.test.ts tests/core/brain.doctor.test.ts tests/core/brain/digest-actions.test.ts tests/core/brain/trust/operator-summary.test.ts tests/core/brain/temporal tests/mcp/temporal-mcp-tools.test.ts tests/mcp/consolidated-tools.test.ts(this is "the reader's existing tests" every task of sections 6 and 7 runs: the files of that list whose name matches the reader). Record the counts; on a failure, stop and report.
6. The two roots (design D1; spec remote-log-reads)
- 6.1 Test first: create
tests/mcp/log-private-reach-surfaces.test.tswith the setup oftests/mcp/log-private-reach.test.ts(makeStoreEnv,switchDevice,appendLogEvent,withOperationPrivacy(true, ...)), calling tools throughnew MCPServer({ vault: env.vault, configPath: env.configPath }, { reach })andcallTool(seereachServerintests/helpers/reach-log-fixture.ts). Cases, each with one shared note and one private note that names nothing, in the window:brain_analyticstimeline view,brain_briefdaily, weekly, monthly and today views: the remote answer carries the shared text and not the private text, the local one both. Add a unit case foreventAtReachwith a marked event and a view whosewithholdsPrivateis set (null) and not set (the event). Run the file: the cases fail. - 6.2 Implement D1 items 1, 2 and 4 (
requestRefView,TemporalEvent.fromPrivatePartition,normaliseLogEntry,eventAtReach,withoutPrivateEntries) and item 3 (BuildTimelineIndexOptions.withholdsPrivate,collectLogEvents), with a unit case for item 3 in the same test file. Run it andtests/mcp/log-private-reach.test.ts tests/mcp/log-readers-reach.test.tsand the existing temporal and analytics tests (tests/core/brain/temporal tests/mcp/temporal-mcp-tools.test.ts tests/mcp/consolidated-tools.test.ts): all pass.
7. The readers with a remote surface (design D2; spec remote-log-reads)
For each row: test first in tests/mcp/log-private-reach-surfaces.test.ts
(one describe per row, a remote and a local assertion, one private
event that names nothing unless the row says otherwise), see it fail,
then the code, then that file and the reader's existing tests pass.
- 7.1 Row 1,
brain_querypreference mode: evidence with one shared event, one private event and one shared event naming a page reserved against remote reads (astests/helpers/reach-log-fixture.tsreserves one); the remote evidence is the first only, and the recall telemetry row the call wrote counts 1 (read it the way the existing recall-telemetry tests do). - 7.2 Row 2, most-applied: a shared confirmed preference with one
shared and two private
appliedevidence events: remotebrain_context,osb://activeandosb://digest/latestcount 1, local ones 3. - 7.3 Row 3, morning brief and idea discovery: a private note and a
private open reconcile question are absent from remote
brain_briefview=morning andbrain_idea_discovery, present locally. - 7.4 Row 4, agent provenance: an agent whose only event is private
is absent from remote
brain_agent_queryandbrain_agent_diff(contributions, roster and counts), present locally; no answer, local or remote, carries afromPrivatePartitionfield. - 7.5 Row 5, backlinks: a shared preference referenced only by a
private event: remote
osb://backlinks/<id>andbrain_backlinkslist no log backlink (count 0), the remote digest's inbound count ignores it; local ones list it. On the same fixture: remotebrain_analyticsview=concept_synthesis for that preference lists no linker whosesourceKindstarts withlog-(local lists one); a shared hub note (a MOC body over theauditMocthresholds, astests/core/brain/link-graph/moc-audit.test.tsbuilds one) links that preference, and remotebrain_moc_auditof the hub reports its member withbacklinkCount0, local with 1. A second private event wikilinkspref-missing-target(no such file): remotebrain_doctorhas nobroken-backlinkswarning for it and the remote repair preview (brain_doctorwithrepair: trueand noapply) counts nobroken-backlinksinunfixable; local ones have the warning and the count. Code:buildConceptCluster,auditMoc,RunDoctorOptionsandDoctorCheckContextgain the option;brokenBacklinkCheckandcollectDoctorIssuespass it (applyRepairgives the latterview.withholdsPrivate === true); then the call-site edits inanalytics-tools.ts,knowledge-tools.tsandhealth-tools.ts(design D2 row 5). - 7.6 Row 6, status: the newest apply-evidence, the newest
dreamevent (BRAIN_LOG_EVENT_KIND.dream, appended withappendLogEventinsidewithOperationPrivacy(true, ...)like any other private event) and the only event of the newest day are private, with an older shared apply-evidence and an older shared dream: remotesecond_brain_statusandosb://statusshow the shared apply-evidence time, the shared dream time (last_dream_at;scanLogTimestampsreads both fromstatusLog) and one log day fewer, local ones the private times; thebrain_contextmaintenance flag is computed without the private day. - 7.7 Row 7, cost meter: remote
brain_recall_telemetryoperationcostcounts one write of one shared and one private. - 7.8 Row 8, token footprint: the log bucket of
computeTokenFootprintwithwithholdsPrivate: trueleaves out the private event's tokens and withfalsecounts them. Thebrain_doctorpath offers no way to set the threshold:collectMaintenanceActionscallscomputeTokenFootprint(vault)with no options, so the threshold isTOKEN_WARN_THRESHOLD_DEFAULT(200000 tokens; theBRAIN_TOKEN_WARN_THRESHOLDvariable is read only by the CLI verb). So testcollectMaintenanceActionsdirectly (in the row'sdescribeoftests/mcp/log-private-reach-surfaces.test.ts, with its store setup) at that default: give the private event a text of 8000 characters (about 2000 tokens,estimateTokensis bytes / 4), then fill a bucket the store counts. A store-only machine does not count files underBrain/(theotherbucket is skipped whenmemoryFromStore(vault)is true), so the filler is shared log events: append sharednoteevents (nowithOperationPrivacy), each with a text of at most 60000 characters, untilcomputeTokenFootprint(vault, { withholdsPrivate: true }).totalis betweenTOKEN_WARN_THRESHOLD_DEFAULT - 1000andTOKEN_WARN_THRESHOLD_DEFAULT(measure the total after each append and size the last event from the difference; assert both bounds before going on). If the log bucket does not grow with a shared event's size either (a cap, or the body spilling into a blob that is not counted), use whichever store-counted bucket ofcomputeTokenFootprintdoes grow (read the function), and say which in the report. ThencollectMaintenanceActions(vault, { withholdsPrivate: true })has no action with categorytoken-footprintandcollectMaintenanceActions(vault)has one. Then the call-site edit inhealth-tools.tspasses the option. On the same fixture (filler sized the same way), the two other remote surfaces of the collector: remoteosb://digest/latestandbrain_briefview=digest have notoken-footprintaction, local ones have it (the edit:digest.tspassesrefs.withholdsPrivate === truetocollectMaintenanceActions); remotebrain_briefview=operator has notoken-footprintentry intop_actions, local has it (the edit:BuildOperatorSummaryOptions.withholdsPrivate, passed bysafeTopActionstocollectMaintenanceActionsand bysafeDoctortorunDoctor, andbrief-tools.tspasseswithholdsPrivate: view.withholdsPrivate === trueoutside theview.filtersNothingspread). Callbrain_briefview=operator withinclude_dream: falseso no dry-run dream runs, andtop_actionslarge enough to hold every action of the fixture. - 7.9 Row 9, the unfiltered timeline builders: a private
apply-evidence on a shared preference is absent from remote
brain_idea_lineageof that preference, and does not change the remotebrain_stale_scanorbrain_statusstale counts. The two stale counts take different paths (design D2 row 9):brain_stale_scan(src/mcp/brain/review-tools.ts,toolBrainStaleScan) builds its own index withbuildTimelineIndex(ctx.vault, {})andfindStaleEntries, and gets the option at that call (buildreviewView(ctx)before it and passwithholdsPrivate: view.withholdsPrivate === true);brain_status(health-tools.ts) passes it tobuildOperatorSnapshot, which passes it to its ownbuildTimelineIndexcall and to itsrunDoctorcall (design D2 rows 5 and 9; the doctor-warnings count of remotebrain_statusignores abroken-backlinksfinding raised only by a private event, as in task 7.5). - 7.10 Row 10, note writes: a shared note written inside a private
operation is absent from remote
brain_writesandbrain_write_destinations(lists and counts), present locally. Remotebrain_writesactionplan_revertwith a selector on that note's path lists no write from the private operation and its digest differs from the local plan's digest; the local plan lists it (the edit:PlanNoteRevertOptions.withholdsPrivate, passed to bothlistNoteWritesreads, andquery-tools.tstakes thereachViewbeforeplanNoteRevert).
8. The census (design D3; spec remote-log-reads)
- 8.1 Create
tests/core/architecture/log-reader-census.test.tsas design D3 describes, with the table of D3 (one row per module). Add a case that proves the census fails on an unlisted module (feed the checker a fake module list, aswrite-site-census.test.tsproves its own rule). Run it: it passes; if the walk finds a module the D3 table does not list, stop and report it (do not classify it yourself unless it is plainly CLI-only, and then say so in the report).
9. The quarantine ledger and the reader (design D4; spec store-shard-gaps)
- 9.1 Test first, in a new
tests/core/store/shard-quarantine.test.ts(store set up as intests/core/store/read-gaps.test.ts): a corrupt middle line makesshardReadGapnon-null; afteraddQuarantinefor its partition, shard, offset and line hash, the shard reads whole (shardReadGapnull) and the bytes on disk are unchanged; a different line written at the same offset (rewrite the shard) is a gap again; a second corrupt line at another offset in the same shard is still a gap while the first stays quarantined (the mark needs the offset and the line hash both, for a diagnostic and a pending record alike, design D4 item 3); a pending record whose offset is in the ledger with another line hash still counts; anunknown-versionline is never marked; a pending blob entry stops counting, its record is still left out ofreadStreamRecords, and once the blob file is written the record reads with its body; two concurrentaddQuarantinecalls from two processes both land (spawn astests/core/store/held-ledger.test.tsdoes);releaseQuarantinebrings the gap back;listQuarantinereportsheld,resolvedandstale. A capture case: a corrupt middle line in asharedsettings shard closesbuildCaptureBoundary(src/core/brain/capture-boundary.ts), and the quarantine opens it again. A migration case: a quarantined pending blob still puts its shard intoreadHeldRecords(...).unseen.partial. Run: the cases fail. - 9.2 Implement
src/core/store/shard-quarantine.ts(D4 items 1 and 2), the marks inreadShardand the skip inshardReadGap(item 3), and the pending rule inreadHeldRecords(item 4). Run the new file andtests/core/store/reader.test.ts tests/core/store/read-gaps.test.ts tests/core/store/state-digest.test.ts tests/core/store/seen-shards.test.tsand the store-migration tests (tests/core/store-migration): all pass.
10. Doctor findings (design D5; spec store-shard-gaps)
- 10.1 Test first, in
tests/core/brain/doctor-store.test.ts: one case per finding (store-shard-corrupt-lineerror with the offset and the quarantine command;store-shard-newer-formatwarning with no command;store-shard-blob-pendingwarning when young, error when older than seven days, no command for asettingsshard; a torn line and a quarantined line give no finding). Run: they fail. - 10.2 Implement
src/core/brain/doctor/store-gap-check.tsand the call-site edits instore-check.ts(D5). Updatestore-check.ts's header list with one item for the new findings. Run the doctor tests: all pass.
11. The verb and the docs (design D6, D9; spec store-shard-gaps)
- 11.1 Test first: create
tests/cli/store-shard.test.tswith theenv()oftests/cli/store-partition.test.ts(task 2.1; write the same object),runCli(..., { env: env(), stdin: "" }): quarantine,already, list, release,not-quarantined, each refusal reason of D6 under--json, and usage errors (exit 2). Run: it fails. - 11.2 Create
src/cli/store-shard.ts(D6). Insrc/cli/store.tsadd only: the import ofcmdStoreShardandSTORE_SHARD_USAGE, the usage joined at the end ofUSAGE, andcase "shard":right aftercase "device":'s return line, plus one header comment sentence. Insrc/cli/command-manifest.tsadd only acommand("shard", ...)entry right after thedeviceentry ofstore, withquarantine,listandreleaseand their flags. Run the new test andtests/cli/manifest-completeness.test.ts tests/cli/help-surface-parity.test.ts tests/cli/completions.test.ts tests/cli/store-device.test.ts: all pass. - 11.3 Docs: one line in
docs/cli-reference.mdright after the line that startso2b store device list|retire(the verbs, refusals, exit codes,--json), and indocs/brain-store.mda section## Shards read only in partright before## What the partitions protect, and what they do not: the three doctor findings, what fails closed, the quarantine on one machine, why never a newer-format line or a young or settings blob, that rollback and the late import still refuse on a pending blob, list and release. Runbun test tests/docsbefore and after: no new failure.
12. Closing checks (Part C)
- 12.1 Run each, one at a time, and fix what they report in your own
files:
bunx tsc --noEmit -p .,bun run lint,bun run fmt:check(bun run fmtto fix),bun run check:paths. - 12.2 Run every test file Part C touched or created, and the
baseline of 0.4, once more in one command; all pass.
wc -l: every file Part C created or changed that was under 700 lines stays under 700; every file past 700 grew only by its call-site edits (list the growth per file in the report).git status --shortlists only Part C's files (and.apb/.gitignore, which is not yours).
13. Report (Part C)
- 13.1 Write
REPORT-part-c.mdat the checkout root (never commit it; at most 80 lines): every Part C box ticked or why not; the baseline and final counts; the line growth of each file past 700; every deviation from design.md and why; every module the census found that D3 did not list; anything in this brief that did not match the code;git status --short. Then delete yourTMPDIRfolder.
Part I: integration (the integrator)
- 14.1 Merge Part Z's and Part C's working trees into one checkout of
this branch, and read both reports first. Resolve the overlaps of design
D9 by keeping both parts' lines:
src/cli/store.ts(both imports, both usages,case "partition"thencase "shard"aftercase "device"),src/cli/command-manifest.ts(partitionthenshardafterdevice),docs/cli-reference.md(thepartitionline then theshardline),docs/brain-store.md(each part's own section). DeleteREPORT-part-z.mdandREPORT-part-c.md. Verify:git status --shortshows no report file and no conflict marker (git diff | grep -c '^[<>=]\{7\}'prints 0). - 14.2 Rebuild the OpenClaw bundle once:
bunx [email protected] run build:openclaw; keepopenclaw/index.js. Verify:git diff --stat openclaw/index.jsshows it changed (it carriesreader.ts,held-ledger.tsandstore-open.ts). - 14.3
CHANGELOG.md: one entry naming the four behaviours of the proposal under a## [Unreleased]heading placed above the newest release heading (Keep a Changelog; create it when absent). No version heading and no version bump: this pull request ships no release. Verify:bun run scripts/sync-version.ts --checkpasses,package.jsonis unchanged, andbun test tests/docs tests/scriptspasses; if a test rejects theUnreleasedheading, remove the entry and record that the store work ships its notes with the phase release (task 3.7 ofbrain-store-and-topics), as the three store pull requests before it did. - 14.4 Run the full local gate of
openspec/project.md, each command on its own; all must pass:bun run testbunx tsc --noEmit -p .bun run lintbun run fmt:checkbun run check:pathsbun run sync-plugin-mirrors:checkbun run scripts/sync-version.ts --check - 14.5 In
openspec/changes/brain-store-and-topics/tasks.md, append "Done in changestore-hardening." to tasks 3.8, 3.15, 3.16 and 3.17 and tick them. Tasks 3.18 (dream and evidence over private apply-evidence) and 3.19 (split the files past 700 lines) are already in that file, added with this change: confirm both are present and open (grep -n "^- \[ \] 3.1[89] " openspec/changes/brain-store-and-topics/tasks.mdprints two lines) and leave them open; if either is missing, stop and report. Verify:openspec validate store-hardening --strictpasses.
Workflow follow-up
- Independent code review rounds of the merged result, fixes re-reviewed.
- Archive the change (
openspec archive store-hardening --yes) inside its pull request, after the whole cycle is green.