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.
Delivery trust - tier-keyed quote fencing on remote reads, context-receipt re-hash verification, opencode hook parity and Ed25519-signed attestations
Status: draft Author: ZCode orchestrator (via feature-release-playbook) Audience: implementation
Problem statement
Open Second Brain records rich provenance about its own content - a server-derived origin_channel on every stamped record, a content_class naming prompt-derived text, an untrusted_source intake marker - and bands conclusions by trust (stated > deduced > inferred). None of that provenance is visible at the point of consumption: a remote agent reading a stored record over MCP receives agent-written text in the same voice as operator-written text, because the only reach-keyed egress shaping in the tree is error-message redaction. The untrusted-source fence family exists but is applied inside context packs behind an opt-in guardrail, not on the plain read deliveries. Separately, the wave's closing of the loop is missing on both ends: Open Second Brain already emits context receipts with per-item sha256 hashes, but an operator cannot ask whether the memories a past session saw are still what they were - a note silently edited or deleted after the session diverges from the receipt unnoticed. On the lanes, the opencode plugin captures sessions, injects at system-prompt build time and nudges after writes, while the Claude Code lane additionally runs prompt-submit rows (recall, navmap, counterparty, reground) and PreToolUse gating - opencode users have no per-prompt recall timing and no read-orientation gate. And beneath all of it, the hash-chained Brain log is never bound to the store it describes: o2b brain log verify checks each shard's chain, snapshots are unsigned recovery points, and no asymmetric signing exists anywhere in the tree, so an out-of-band edit to the log or the vault content after a known point is undetectable and unattributable.
Premise verification
Verdicts from targeted reads against this tree at 285cb9a8, recorded with the corrections from the four recon reports. All four premises held; nothing is dropped. The full anchor-by-anchor table lives in variants.md; the corrections below are binding for the plan.
- t_1af24938 - premise_confirmed with two registry-anchor corrections. Every mechanism the card names exists at the validator-refreshed anchors (
wrapUntrustedSourceat src/core/brain/untrusted-source.ts:219,fenceUntrustedContentat :238, the guard site withdelimitUntrustedat src/core/brain/context-pack.ts:799-807,untrusted_source_delimiting: falseat guardrails.ts:86,untrusted_source_provenanceat retrieval-gate.ts:66,quote_unverifiedat tool-error-codes.ts:136). No tier-keyed fence exists on any read delivery, and no per-page verified/unverified flag exists on disk. Corrections:VISIBILITY_SURFACE_REGISTRYis at src/core/search/visibility-surface-registry.ts:86 (recon said :81) andCONTENT_CLASSat src/core/brain/provenance/content-class.ts:89 (recon said :69); both field constants and registries are otherwise exact. - t_4300e5fd - premise_confirmed. All anchors exact (
ContextReceiptFilter.receiptIdat context-receipts.ts:101; the hash payload at :155-163;getContextReceiptat :474; docs rows at cli-reference.md:473/:534 and mcp.md:407). Two emit-site line drifts of 2-3 lines (pre-compress-pack.ts:297,hooks/active-inject.ts:592/:599); symbols exact. The v1.95.0 answer-side join audits quoted answers, not store-side drift - the verify gap is real. - t_eaf760a6 - premise_confirmed. The plugin (549 lines) has exactly three hook families (capture :393, system-prompt inject :404/:479, post-write nudge :415/:488) and no
tool.execute.before/tool.hook("execute.before")and no prompt hook anywhere; the Claude Code rows are at hooks.json UserPromptSubmit :80 and PreToolUse :117 (recon anchors exact; the card's :62/:93 were the stale spellings the validator already corrected). The dual V1/V2 plugin API is shipped, so the parity work is internal. - t_3bdb82b0 - premise_confirmed. Zero hits for
ed25519/createSign/createVerify/generateKeyPairacross src/ and plugins/.verifyLogChainat log-chain.ts:156 is report-only and binds nothing; the snapshots family is unsigned. Two load-bearing facts beyond the card:lastChainHash(log.ts:568) is module-private, so the wave must add an exported head collector, and there is no whole-store digest function anywhere in the tree.
Scope
- Lane A (t_1af24938): a closed delivery-treatment vocabulary plus the fail-closed derivation of "unverified / agent-origin" from the existing stamps, a cached frontmatter provenance probe, and the quote fence applied to stored-record bodies on remote reads across the search family (
brain_searchrows,brain_search_expand,brain_file_context), the report-shaped reads through one shared delivery binding (brain_querypreference/topic payloads,brain_agent_query,brain_agent_diff,brain_decision), and the whole-document surfaces (brain_contextactive body,brain_pinned_context, the osb:// resource readers for preference, topic, active, lessons and backlinks). A failSoft doctor check names how many delivered pages carry no derivable provenance. Local reach is a byte-identical no-op everywhere. - Lane B (t_4300e5fd): a pure verify kernel over the context receipts family - per item MATCH / CHANGED / NOT AVAILABLE by re-hashing the delivered text with the recorded digest algorithm, re-applying the delivery-time transforms so trimmed items do not false-CHANGED - with a
verifyoperation on the existingbrain_context_receiptsMCP tool, ano2b brain context-receipts verifyCLI subcommand, and a failSoft doctor check aggregating drift over recent receipts. Read-only; no new capture machinery, no persistence. - Lane C (t_eaf760a6): on the opencode plugin, a fail-soft
tool.execute.beforegate that relays the existing pretool shims (orient, host-backup) with synthetic PreToolUse payloads and throws only on an explicit structured deny, and prompt-time injection that observes the prompt, spawns the four UserPromptSubmit shims, and delivers their additionalContext through the existing context hook via a once-per-turn queue. A grok-precedent parity census pins the lane's covered rows and its declared divergences. - Lane D (t_3bdb82b0): an attestation kernel - a store-state manifest of per-shard log heads collected under their own locks plus state-surface stamps, sealed and signed with an operator-managed Ed25519 key, written as one atomic JSON file per attestation;
o2b brain attest keygen|sign|list|verifyoperator verbs; a read-only MCP tool; a failSoft doctor check. Verification recomputes the manifest, walks chain continuity from each attested head, and checks the signature - report-only. - Integrator: reconciliation of the shared registries (doctor registry, classifications, docs), census coherence across lanes, full local gates.
Out of scope
- Log and event-trace bodies (
brain_event_trace, the log resources,brain_writesevent payloads, session transcript lanes): their formats are parsed by heading structure (LOG_EVENT_HEADING) and they are already shaped by the reach view and trimming; fencing them changes consumer contracts. Recorded as the delivery-shaping boundary for this wave. - Generated/rendered content (briefs, digests, claim-graph reports, knowledge packs): the system's own voice, not stored records; distinct problem.
- The context-pack and pre-compress lanes:
guardBrainContextSnippetalready shapes those payloads; the card's gap is the unfenced reads. Re-keying the pack guard on reach is follow-up territory. - The openclaw plugin lane (
src/openclaw/index.tsreturns titles/metadata, no note bodies): out of scope; the visibility-surface registry keeps its existing walker note. - Any write-time change to stored bytes, any backfill of origin stamps onto legacy pages (both stamp modules forbid backfill by design), and any output-schema change (the fence lives in the delivered bytes).
- Session-capture parity for opencode's Stop family and SubagentStart (no carrier exists upstream; already documented known gaps), and any change to the Claude Code hooks lane.
- Receipt verify persistence (a verify continuity kind or sealed results): verify stays read-only this wave; the additive-only schema doctrine makes this a deliberate deferral.
- Per-memory revision chains and stale-write protection (t_7ae24759), per-session consent and trust recheck (t_bce33277), and the opencode client-API tracking card (t_2ce7c95a): related but distinct cards.
- Store-digest coverage of the derived store's bytes (
brain.sqlitewith a live WAL is not meaningfully hashable; the snapshot module documents why) and of the Markdown twins the log writers render. - Version bump, CHANGELOG assembly and the release-wide docs pass: that is the pr-prepare phase, not this plan.
Chosen approach
Variant 2 in variants.md: family-seam shaping over shared pure kernels. Each feature gets one pure kernel and wires it at seams that already exist, so no lane builds infrastructure the tree does not already need: Lane A adds two pure modules (treatment vocabulary with the stamp derivation, cached provenance probe) and wires the shaper at the search windowing site, a new delivery binding beside requestRefView, and the resource readers; Lane B adds a verify kernel over the receipts family with two thin faces; Lane C adds plugin registrations that spawn the existing shims and drain a per-turn queue through the existing context hook; Lane D adds an attestation kernel sharing only sha256Hex / canonicalJson / sealWithDigest with the other lanes. The lanes are disjoint by family; the only shared files are append-only registries (doctor registry, classifications, manifest, docs) governed by the protocol in plan.md.
Design decisions
- "Unverified / agent-origin" is derived from the stamps that already exist, with absence fail-closed to unverified. There is no per-page verified flag on disk and adding one is a backfill the stamp modules forbid. The derivation, in precedence order: an
untrusted_sourcemarker (trust/untrusted-provenance.ts) makes the page unverified;content_class: prompt-derived(provenance/content-class.ts) makes it agent-origin;origin_channelofmcp-toolorimportmakes it agent-origin;origin_channel: cliis the one operator-authored answer; any absence - no channel, theunsetliteral, a pre-stamp page - reads as unverified. Fail-closed is the card's own doctrine (upstream: a missing trust tier reads as unverified) and matches the tree's conventions: both stamp docblocks state that absence means "written before the stamp existed", which is a statement about knowledge, not trust, so the delivery side must not guess operator-authorship it cannot prove. The consequence is stated plainly: a legacy vault's pages are fenced at remote reads until the operator stamps them, and the new doctor check (delivery-provenance-unknown, failSoft) names how many delivered pages carry no derivable provenance so the widening is observable, never silent. Reading the channel is legal (the origin-channel census forbids naming it in inputs, not reading it); the derivation is a closed pure function over three frontmatter values. - One treatment vocabulary, reusing the fence family - no second delimiter.
DELIVERY_TREATMENTis the closed pairplain | fenced, registered in the verdict-vocabulary census with the frozen trio. The fence itself isfenceUntrustedContent(text, origin)from untrusted-source.ts with a delivery origin label naming the derived provenance (for exampleorigin="stored text: agent-authored (content_class=prompt-derived)"), so a downstream model treats a delivery-fenced span exactly as it already treats intake-fenced spans - the same reasoning that bound the frontmatter marker to the delimiter token. The shaper never rewrites the page on disk (read-time only, like the whole fence family) and never introduces invisible characters (the body is the neutralizer's output). - Remote-only, byte-identical at local, identical-to-absent for withheld rows. The shaper is invoked only when
contextReach(ctx)resolvesremote(theredactErrorForCallerbranch shape); at local reach no shaper code runs at all, so the dozens of pinned local-reach shapes and the withheld-as-absent tests stay green untouched. A row the reach view withholds gains no fence and no count - a fence on a withheld row would be an existence leak. - The fence lives in the delivered bytes; zero output-schema changes. Fenced text replaces the text in the same field (
content, body, markdown document), so noToolDefinition.outputSchemagrows a marker field, the output contract is untouched, and the parked artifact copies are fenced by construction: shaping happens in the handlers before results are built, so the preview-budget parking and any laterbrain_artifact_getreplay carry the shaped bytes. - Stored-record bodies only. The fence applies to text read from note bodies: search snippets and chunk text, preference/topic payload bodies, agent contribution bodies, decision pages, the active and pinned bodies, and the whole-document resource readers. The exclusions (log/event bodies, generated reports, transcripts) are the wave's stated delivery-shaping boundary, recorded in out-of-scope with their reasons.
- Provenance probes ride the shared frontmatter cache. The probe (
pageOriginForDelivery) reads the three fields throughreadCachedFrontmatterEntryso a delivery shapes with no uncached per-row file reads; the search family, which already holds aFrontmatterCachein its pipeline, threads the probe through it, and the report/whole-document families probe per request through the same helper. The probe returns the three raw fields plus a resolved treatment; unreadable pages resolve fenced (fail closed) without throwing. - One delivery binding beside the report-shaped reference view. The report-shaped reads (
brain_queryserializers,brain_agent_query,brain_agent_diff,brain_decision) shape through one helper exported besiderequestRefViewin src/mcp/brain/reach-events.ts -deliveryView(ctx)- so the rule is derived once per request and no surface re-derives it. The search family shapes at thewindowContentsite and the expand/file-context handlers; the resource readers shape inreadResource's markdown path. Each family gets a remote-quoted/local-identical pin. - Verify verdicts are about delivered bytes, never liveness, never inferred.
RECEIPT_VERIFY_VERDICTis the closed triplematch | changed | unavailablewith unavailable reasonsno_path | no_hash | file_missing | unreadable. Only items carrying bothpathandtext_hashare verifiable; structural ids (standing-rules,scoped-rules,active-body,lessons-body) and hashless items reportunavailable(no_hash)orunavailable(no_path)- an honest not-verifiable class, never an inferred verdict. A retired note verifies against its retired body: MATCH is a claim about bytes. A path that no longer resolves or escapes the vault maps tounavailable(file_missing)with a note, never a traversal error. - Verify re-applies the delivery-time transforms so trimmed items do not false-CHANGED. The recorded hash covers the delivered text, not the file: body after frontmatter strip, after the context guard (identity under default guardrails), after
applyCharBudgettrimming whenmax_chars_per_memorywas set. The receipt records everything needed to re-derive it (trimmed: true,budget.max_chars_per_memory,bytes), so the kernel re-applies exactly thecontext_packprojection - frontmatter strip, guard, budget cut with the recorded budget - before hashing.pre_compressitems verify only when they carrypathplustext_hash(the active-body item); principle lines reportunavailable(no_hash)rather than a guessed projection.session_injectreceipts carry no text by construction (hooks/active-inject.ts records id/bytes/tokens only), so every item isunavailable(no_hash)and the result header statessessionInjectedwith the by-construction reason - the manifest half exists, the re-hash half is out of scope by construction, and the verb says so instead of pretending. - One hash, one decoder, one resolution rule. Re-hashing calls
sha256Hexfrom src/core/integrity/digest.ts - the exact function the writer used; no second hashing path (the context-pack-evidence doctrine). Paths resolve against the vault defensively: absolute host paths (whatcontext_packreceipts record today) and vault-relative spellings are both accepted throughensureInsideVaultand vault-relative normalization, because the receipt is data, not a contract about path spelling. - Verify is refused where show is refused. Below local reach the verify operation returns the same typed refusal shape the receipts tool already uses (the
brain_receiptslocal-only precedent);record.private || record.redactedreceipts are refused symmetrically with the fold's withholding. The CLI verb is an operator surface and performs the same refusal for consistency. - Two thin faces over one kernel. MCP: the
operationenum onbrain_context_receiptsgrowsverify(list | show | summary | verify) - no new tool name, so the frozen tool-name parity set is untouched and the probe catalogue gains a probe for the new operation. CLI:o2b brain context-receipts verify <receipt-id> [--json]in the existing verb file, with the manifest row, help row, manifest-completeness and help-parity guards updated in the same change. Both faces consume the identicalReceiptVerificationshape. - A failSoft doctor check aggregates drift.
receipt-content-drift(thecontentHashDriftCheckshape) re-verifies a bounded recent window of receipts and reports one warning with per-verdict counts when anything reports CHANGED, namingo2b brain context-receipts verify <id>as the next command. Report-only; legacy receipts without hashes are silent, like the preference-hygiene precedent. - The opencode gate is fail-soft by construction: only an explicit structured deny throws.
tool.execute.before(V1) /ctx.tool.hook("execute.before")(V2) spawn the existingpretool-orientandpretool-host-backupshims with synthetic PreToolUse payloads through the plugin'shookCommand(the Windows-safe argv builder). A shim verdict ofpermissionDecision: "deny"maps to a thrown error carrying the redirect text - the one blocking channel opencode offers; every other outcome (flag off, shim missing, timeout, malformed output, spawn failure) passes the tool call untouched, because a plugin bug must never break operator tool calls on a lane where the wrapper's forced exit-0 safety net does not exist. The Claude Code "nudge on allow" downgrade has no equivalent channel on a tool call and is declared, not improvised: it is recorded in the new parity census'sDECLARED_OPENCODE_DIVERGENCESas a written divergence with its reason. Once-per-session state stays where it lives today - the shim's hook-state stamps - so the plugin holds no new state. - Prompt-time injection is queue-then-context, drained once per turn. The plugin registers
ctx.session.hook("prompt")(V2; V1chat.messagebehind feature detection, since that name no longer appears in current upstream docs) to observe the user prompt and spawn the four UserPromptSubmit shims (recall-inject,nav-inject,counterparty-brief,reground-deliver) with synthetic payloads carrying the opencode session id, so the vault hook-state ledger dedupes exactly as on the Claude Code lane. The returnedadditionalContextis enqueued per turn, and the existing context delivery points (experimental.chat.system.transform/ctx.session.hook("context")) drain the queue beside the TTL-cached active inject on the first model request after the prompt and then mark it delivered - becausecontextfires per model request, a turn with several requests would otherwise double-inject, and the prompt hook itself runs before durable prompt admission and is not a delivery channel. The take-once cursor of the reground carrier is the pattern; the active inject's 5-minute TTL cache semantics are untouched. - A parity census pins the lane with declared divergences. New
tests/core/install/adapters/opencode-hook-parity.test.tson the grok-precedent shape: derive the required row set from hooks/hooks.json, require the plugin to cover it, carryDECLARED_OPENCODE_DIVERGENCES(Stop:<family>,SubagentStart, the nudge channel, and the pre-durable-admission prompt-hook caveat - each with a written reason; a stale declared divergence fails), and floor both sets so a parser regression cannot pass vacuously. The plugin file stays self-contained (node builtins plus Bun globals, no repo imports), all spawns ridehookCommand, and every new registration is stub-tested in the existing plugin harness - opencode is not installed on dev or CI. - The feature noun is "attestation", not "checkpoint". Four live meanings of "checkpoint" already exist (the resume substrate, the batch session-checkpoint,
Safeguard.checkpoint(), dream checkpoints) plus the.snapshotsrecovery family. Code, CLI, files and docs use attestation exclusively: modulesrc/core/brain/attestation/, verbo2b brain attest, state surfaceattestations, files<vault>/.open-second-brain/attestations/attest-<UTC-compact>.json. The card's phrase "signed checkpoint" appears only in docs mapping the feature back to the card, never as a code or file name, and nothing touchesBrain/.snapshots/. - The attestation binds a MAP of per-shard heads, each collected under its own lock - there is no global head. The Brain log shards per device (
<YYYY-MM-DD>[.<deviceId>].jsonl), so a single head is meaningless across devices; the attested body records{shardId: headHash}for every JSONL shard, each head read under the same per-day directory lock the appender takes (a new exported collector in log.ts beside the privatelastChainHash, takingacquireLogLockper shard directory rather than inventing a second locking discipline). The lineage ledger is explicitly excluded: it is a second, independent chain whose head-line exemption reflects its compaction semantics. - The store digest is anchored on state-surface stamps, never raw bytes. The attested manifest is
{vault_identity, log_heads, ledger_inventories, index_stamp}hashed withsha256Hex(canonicalJson(...)): the vault identity id, the per-shard chain heads, the file-name inventory of each doctor-swept ledger directory, and the search index stamp (thecompareStampstoken the indexer already records). No whole-tree byte hash ofBrain/(the Markdown twins and sync-conflict copies make it unreproducible) and neverbrain.sqlitebytes (a live WAL makes them meaningless; the snapshot module's analysis is the precedent). Verification recomputes the manifest and reports per-surface drift, which is exactly the operator question - "did the state these surfaces stamp change since the attestation" - answerable without racy tree walks. The guarantee is exactly as wide as those surfaces and no wider: log heads see shard edits, removals and rewrites; ledger inventories see files vanish outright, and see a file APPEAR as drift unless it is the producer's own growth - a name parsing under the swept directory's ledger grammar (a new audit week, continuity month or metric surface) with the kind the producer writes, or a known ledger subdirectory (a first work-identity directory, a first per-preference trail); the index stamp sees an ABI move. Nothing here hashes note bytes, so an out-of-band edit to an existing note's body that moves no attested surface is outside what the signature vouches for - per-note content questions are the context-receipt verify's (lane B), never the store digest's. - Head continuity is walked, not assumed. At verify, a shard whose current head equals the attested head is
intact; a shard whose head moved is walked forward from the attested head throughprevlinks (reusing the log-chain row grammar): if the walk reaches the current head, the shardappendedlegitimately since the attestation; otherwise itdiverged- an edit, deletion or rewrite after the signed point. A shard file that is gone ismissing. All report-only; the log-chain doctrine (audit surface, never a read gate) is preserved verbatim, and verification remains an operator surface so reach-filtered readers are never affected. - Keys are operator-managed and live under the vault's machine-config area, beside secrets but outside the secrets store. The derived store root
<vault>/.open-second-brain/is where the vault's machine-managed configuration and state already live (config discovery, the secrets store, ledgers, maintenance state), and the gitignore guard seeds its exclusion, so the key directory is<vault>/.open-second-brain/keys/attestation/: the private keyfile created 0600 via theloadOrCreateKeyposture withrestrictToOwnerand a.gitignoremarker so git never carries it (file-syncer exclusion, e.g..stignore, remains the operator's responsibility, and the secrets-sync doctor check names the exact line once a key exists), the public half exported beside it for peers. Not insidesecrets/itself - the secrets store has its own lock and unlock semantics and a signing key must not gate on the store's locked state - and never underBrain/, which syncs across peers. There is no silent default key:signwithout a generated key refuses by name (attestation_key_missing) pointing ato2b brain attest keygen, because a key the operator did not create would be a false sense of attestation. Optional passphrase wrap reuses the envelope'swrapKeyfileshape with$secret:passphrase resolution; key material is never printed, and loss means no recovery, stated like the envelope and bundle modules state it. - The attestation record is sealed, versioned, atomic and registered. The body is sealed with
sealWithDigest(camelCase fields:schemaVersion,id,createdAt,deviceId, and a nestedmanifestcarryingvaultIdentityId,logHeads,ledgerInventories,indexStamp, beside the top-levelstoreDigest) plus the detached Ed25519 signature over the sealed body's canonical JSON; unknown schema versions are refused by name (thereadCheckpointObjectpattern). One atomic JSON file per attestation (not an append-mode ledger, so the append-shard census is not engaged), written under a lock registered in the lock-site census and falling under alockScanRootsroot, with the vault-guard assertion, a newSTATE_SURFACE_ID.attestationsrow (feedingo2b state statusandvault_healthautomatically), the write-site census satisfied byatomicWriteFileSync, and aProgressSink-accepting options type where verification walks the vault (progress census). - Operator verbs on the CLI, read-only on MCP.
o2b brain attest keygen|sign|list|verify(dispatch, manifest, help, completions in the same change; exit-code contract percmdBrainLogVerify) is the full operator surface; MCP getsbrain_attestationsas a read-only list/verify tool registered beside the health tools - thebrain_secretssplit (agent-facing subset read-only, key management CLI-only) applied to signatures. A failSoft doctor check reports a missing key, a stale attestation (older than a named age), and any diverged shard from the last attestation. - Ed25519 comes from node:crypto - no new dependency.
generateKeyPairSync("ed25519"),sign/verifyover the sealed body's canonical JSON; the greenfield asymmetric kernel is three small pure functions in signing.ts so the census-visible crypto surface stays auditable.
File changes
New:
src/core/brain/delivery-shaping.ts-DELIVERY_TREATMENT(plain | fenced),DeliveryTreatment,isDeliveryTreatment,shapeStoredTextForDelivery(text, {treatment, origin})built on the fence family (lane A).src/core/brain/provenance/page-origin.ts-PageOriginForDelivery,pageOriginForDelivery(vault, rel, cache)overreadCachedFrontmatterEntry,storedTextTreatment(the fail-closed derivation),deliveryOriginLabel(lane A).src/core/brain/doctor/delivery-provenance-check.ts- failSoft count of delivered pages with no derivable provenance, codedelivery-provenance-unknown(lane A).src/core/brain/context-receipts-verify.ts-RECEIPT_VERIFY_VERDICT,RECEIPT_VERIFY_UNAVAILABLE_REASON,ReceiptItemVerification,ReceiptVerification,verifyContextReceipt(vault, receipt)(lane B).src/core/brain/doctor/receipt-content-drift-check.ts- failSoft aggregate over a recent window, codereceipt-content-drift(lane B).src/core/brain/attestation/digest.ts-AttestationManifest,collectAttestationManifest(vault, opts),attestationStoreDigest(manifest)(lane D).src/core/brain/attestation/record.ts-ATTESTATION_FILE_SCHEMA_VERSION,AttestationRecord,writeAttestationRecord, attestation file naming and lock (lane D).src/core/brain/attestation/signing.ts-generateAttestationKeypair,signAttestationRecord,verifyAttestationSignature,ATTESTATION_KEY_MISSING, key-directory layout under<vault>/.open-second-brain/keys/attestation/(lane D).src/core/brain/attestation/verify.ts-AttestationVerification,verifyAttestation(vault, record, opts)with per-shardintact | appended | diverged | missing(lane D).src/cli/brain/verbs/attest.ts-cmdBrainAttestkeygen/sign/list/verify (lane D).src/mcp/brain/attest-tools.ts-ATTEST_TOOLS, read-onlybrain_attestations(lane D).- Tests:
tests/core/brain/delivery-shaping.test.ts,tests/core/brain/provenance/page-origin.test.ts,tests/mcp/quote-fencing-search.test.ts,tests/mcp/quote-fencing-reports.test.ts,tests/mcp/quote-fencing-resources.test.ts,tests/core/brain/doctor/delivery-provenance-check.test.ts(lane A);tests/core/brain/context-receipts-verify.test.ts,tests/mcp/context-receipts-verify-tool.test.ts,tests/cli/context-receipts-verify-cli.test.ts,tests/core/brain/doctor/receipt-content-drift-check.test.ts(lane B);tests/core/install/adapters/opencode-hook-parity.test.ts(lane C);tests/core/brain/attestation/digest.test.ts,tests/core/brain/attestation/signing.test.ts,tests/core/brain/attestation/verify.test.ts,tests/cli/brain-attest.test.ts,tests/mcp/attestations-tool.test.ts,tests/core/brain/doctor/attestation-check.test.ts(lane D).
Modified:
src/mcp/search-tools.ts- shape search rows at thewindowContentsite,brain_search_expandandbrain_file_context, remote-only (lane A).src/mcp/brain/reach-events.ts-deliveryView(ctx)besiderequestRefView(lane A).src/mcp/brain/query-tools.ts- shape preference/topic payload bodies, agent contribution bodies, decision pages through the binding (lane A).src/mcp/brain/context-tools.ts- shapebrain_contextactive body and pinned bodies (lane A).src/mcp/resources.ts- shape the preference/topic/active/lessons/backlinks readers' markdown (lane A).src/core/brain/context-receipts-verify.tsconsumers:src/mcp/brain/pack-tools.ts(verifyoperation onbrain_context_receipts, refusal below local reach),src/cli/brain/verbs/context-receipts.ts(verifysubcommand) (lane B).plugins/opencode/open-second-brain.ts-tool.execute.before/tool.hook("execute.before")gate, prompt-observe hook, per-turn queue drained by the existing context hook (lane C).install/opencode.md- capability table rows for the gate and the prompt lane (lane C).src/core/brain/log.ts- exportedcollectLogShardHeads(vault)head collector taking each shard directory lock (lane D).src/core/state/surfaces.ts-STATE_SURFACE_ID.attestationsrow (lane D).src/cli/brain.ts(caseattest),src/cli/command-manifest.ts(attest command row; context-receipts subcommand text),src/cli/brain/help-text.ts(both rows) (lanes B and D, append-only).src/mcp/brain-tools.ts- registerATTEST_TOOLS(lane D).src/core/brain/doctor.ts- three appended checks (shared, append-only).
Shared, append-only (protocol in plan.md):
src/core/brain/doctor.ts(DOCTOR_CHECKS): lane A appendsdeliveryProvenanceCheck, lane B appendsreceiptContentDriftCheck, lane D appendsattestationCheck; named positions, no reordering.src/core/brain/doctor-exits.ts/src/core/brain/diagnostics.ts: each lane classifies its own code.src/core/search/visibility-surface-registry.ts: lane A updates the reasons/rows for the surfaces it wires (the shaper becomes a swept note-content primitive); lane D adds rows for the new verb and tool.tests/core/architecture/verdict-vocabulary-census.test.ts: lane A registers the treatment vocabulary.tests/mcp/brain-tools-parity.test.tsandtests/helpers/tool-probe-catalogue.ts: lane D adds the new tool name and probe; lane B extends the receipts probe for the verify operation.tests/core/brain/sync-lockfile.test.ts(DECLAREDlock map) andtests/core/state/surfaces.test.ts: lane D only.tests/cli/manifest-completeness.test.ts,tests/cli/help-surface-parity.test.ts,tests/cli/completions.test.tsconsumers: lane B (verify subcommand) and lane D (attest verb), append-only.docs/cli-reference.md,docs/mcp.md,install/opencode.md: each lane appends its own rows; the integrator reconciles prose that spans lanes. CHANGELOG and the version bump are the pr-prepare phase, not this plan.
Risks and open questions
- Fail-closed widens fencing to every legacy page. A pre-stamp vault fences nearly everything at remote reads on day one. That is the honest reading of the stamps (the tree forbids backfill) and the doctor check names the population, but it is a visible behavior change for remote consumers of old vaults; documented in the docs rows, and the operator's remediation is stamping, which existing write paths already do going forward.
- Fenced bytes change what remote consumers parse. Any remote tooling that parsed delivered note text by structure now sees fence lines; the fence is neutralizer output (control/bidi-stripped, delimiter-escaped), so the exposure is the fence wrapper itself. Local reach - the operator's own tools - is byte-identical, which is where parsing discipline lives today.
- Opencode API drift.
tool.hook("execute.before")andsession.hook("prompt")are documented but were never registered by this plugin, opencode is absent from dev and CI, and the V1chat.messagename has drifted out of the current docs. The lane ships stub-driven tests, feature detection exactly like the existing V2 guards, and declared divergences; live verification against a released opencode build is an operator QA step recorded in install/opencode.md. - The context-hook queue is the one new concurrency on the opencode lane. A new prompt replaces any payload its session left undelivered (the lose-not-duplicate side, not a stack), and each session owns a slot keyed by its id - the plugin instance is server-wide, so a single shared slot would deliver one session's recalled vault context into another session's model request and let a background request consume the turn's injection. A multi-model-request turn drains its session's slot exactly once. The failure mode if upstream changes delivery semantics is duplicate or missed context - the ledger contract tolerates it, and the parity census keeps the divergence declared rather than silent.
- Attestation window semantics. A manifest taken between appends is still self-consistent (each head is read under its own lock), but two attestations seconds apart can differ legitimately; verify reports per-surface drift rather than pass/fail for the store digest, so a legitimately-advanced store is
appended, not broken. The chain walk is O(shard tail) and bounded by the since-attestation rows. - Key lifecycle is operator burden by design. Key loss makes existing attestations unverifiable (the signature check reports invalid rather than guessing); rotation is keygen plus re-sign, with no re-signing of old records ever. Stated in help text and docs; no recovery path is offered.
- Census overhead. The wave touches seven registries that fail loudly on unregistered newcomers (verdict-vocabulary, visibility-surface, state-surface, lock-site, write-site, manifest-completeness, doctor-exit); every lane lands its registrations with the code that trips them, never retrofitted, or the full gates fail at integration.
- Open: which generated surfaces eventually join the fence. Briefs and digests quote stored text indirectly; the wave draws the boundary at stored-record bodies and records the question for a follow-up decision made on the doctor check's data, not on taste.