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 - implementation plan
Four implementation lanes with strictly disjoint file ownership plus one integrator. Each task is TDD-ready: write the failing test first, implement until green, refactor with all tests green, then run the repo formatter (./node_modules/.bin/oxfmt, i.e. what bunx oxfmt resolves locally) and the repo lint (bun run lint, oxlint -c oxlint.json) on the task's own files before every commit, and commit only that task's own files with git commit --only <paths> (never a plain git add + git commit). Each lane runs ONLY its own new or changed test files locally (never the full suite); the integrator runs the full gates. Version bump, CHANGELOG assembly and the release-wide docs pass are the pr-prepare phase and are intentionally absent here.
Cross-lane contracts (frozen before lane work starts)
These are the pinned shapes every lane builds against. A lane that needs to change one stops and renegotiates in this document first; it never narrows an exported shape unilaterally.
- K1 - delivery shaping (Lane A owns, nobody else imports).
src/core/brain/delivery-shaping.ts:export const DELIVERY_TREATMENT = Object.freeze({ plain: "plain", fenced: "fenced" } as const);export type DeliveryTreatment = (typeof DELIVERY_TREATMENT)[keyof typeof DELIVERY_TREATMENT];export function isDeliveryTreatment(value: unknown): value is DeliveryTreatment;export function shapeStoredTextForDelivery(text: string, opts: { treatment: DeliveryTreatment; origin: string }): { text: string; treatment: DeliveryTreatment }-plainreturns the input bytes unchanged;fencedreturnsfenceUntrustedContent(text, origin)fromsrc/core/brain/untrusted-source.ts(same tag, same neutralization; no new delimiter vocabulary).src/core/brain/provenance/page-origin.ts:export interface PageOriginForDelivery { readonly originChannel: OriginChannelStamp | null; readonly contentClass: string | null; readonly untrustedSource: boolean };export function pageOriginForDelivery(vault: string, rel: string, cache: FrontmatterCache): PageOriginForDeliveryreading onlyORIGIN_CHANNEL_FIELD,CONTENT_CLASS_FIELD,UNTRUSTED_SOURCE_FRONTMATTER_KEYviareadCachedFrontmatterEntry;export function storedTextTreatment(origin: PageOriginForDelivery | null): DeliveryTreatment- marker true, orcontent_class: prompt-derived, or channelmcp-tool/import, or ANY absence (null origin, null channel,unset) resolvesfenced; only channelcliwith no other marker resolvesplain;export function deliveryOriginLabel(origin: PageOriginForDelivery): string- the fence'soriginattribute text naming the derived provenance.
- K2 - receipt verify (Lane B owns; MCP and CLI faces consume exactly this).
src/core/brain/context-receipts-verify.ts:export const RECEIPT_VERIFY_VERDICT = Object.freeze({ match: "match", changed: "changed", unavailable: "unavailable" } as const);export type ReceiptVerifyVerdict = ...;export const RECEIPT_VERIFY_UNAVAILABLE_REASON = Object.freeze({ no_path: "no_path", no_hash: "no_hash", file_missing: "file_missing", unreadable: "unreadable" } as const);export interface ReceiptItemVerification { readonly id: string; readonly path: string | null; readonly verdict: ReceiptVerifyVerdict; readonly expectedHash: string | null; readonly observedHash: string | null; readonly unavailableReason: ReceiptVerifyUnavailableReason | null; readonly note: string | null };export interface ReceiptVerification { readonly receiptId: string; readonly createdAt: string; readonly trigger: ContextReceiptTrigger; readonly sessionInjected: boolean; readonly items: ReadonlyArray<ReceiptItemVerification>; readonly counts: { match: number; changed: number; unavailable: number } };export function verifyContextReceipt(vault: string, receipt: ContinuityRecord): ReceiptVerification. Hashing viasha256Hex(src/core/integrity/digest.ts) only; path resolution viaensureInsideVault; transforms re-applied per design.md (frontmatter strip, guard,applyCharBudgetwith the recordedbudget.max_chars_per_memorywhentrimmed).
- K3 - opencode shim relay (Lane C consumes existing shims; no new core exports). The plugin spawns, through its existing
hookCommand,o2b-hook pretool-orient/o2b-hook pretool-host-backupwith synthetic payloads{"hook_event_name":"PreToolUse","session_id":<opencode session id>,"tool_name":<tool>,"tool_input":<args>,"cwd":<dir>}ando2b-hook recall-inject/nav-inject/counterparty-brief/reground-deliverwith{"hook_event_name":"UserPromptSubmit","session_id":<id>,"prompt":<text>,"cwd":<dir>}. It reads exactly three fields from shim stdout:hookSpecificOutput.permissionDecision("deny"blocks by throwing; anything else passes),hookSpecificOutput.permissionDecisionReason(the thrown error text) andhookSpecificOutput.additionalContext(enqueued for the context hook). Nosrc/orhooks/file changes in this lane. - K4 - attestation kernel (Lane D owns; CLI and MCP faces consume exactly this).
src/core/brain/attestation/digest.ts:export interface AttestationManifest { readonly schemaVersion: "o2b.attestation.manifest.v1"; readonly vaultIdentityId: string; readonly logHeads: Readonly<Record<string, string>>; readonly ledgerInventories: Readonly<Record<string, ReadonlyArray<string>>>; readonly indexStamp: string | null };export function collectAttestationManifest(vault: string, opts?: { safeguard?: Safeguard }): AttestationManifest(heads via the K4 log collector, each under its shard-directory lock);export function attestationStoreDigest(manifest: AttestationManifest): string=sha256Hex(canonicalJson(manifest)).src/core/brain/log.tsgains exactly one export:export function collectLogShardHeads(vault: string): Readonly<Record<string, string>>- every*.jsonlshard's chain head, each read underacquireLogLockfor that shard directory; returns{}for a vault with no log. No other change to log.ts.src/core/brain/attestation/record.ts:export const ATTESTATION_FILE_SCHEMA_VERSION = "o2b.attestation.v1";export interface AttestationRecord { readonly schemaVersion: string; readonly id: string; readonly createdAt: string; readonly deviceId: string; readonly manifest: AttestationManifest; readonly storeDigest: string; readonly digest: string; readonly signature: string | null }(sealed viasealWithDigest;signaturenull on an unsigned record is refused by verify);export const ATTESTATIONS_REL = "attestations"underDERIVED_STORE_DIR;export function writeAttestationRecord(vault: string, record: AttestationRecord): { readonly path: string }- one atomic JSON fileattest-<UTC-compact>.jsonunder the lock registered in the lock-site census.src/core/brain/attestation/signing.ts:export const ATTESTATION_KEY_MISSING = "attestation_key_missing";export function generateAttestationKeypair(vault: string, opts?: { passphraseFromEnv?: string }): { readonly privatePath: string; readonly publicPath: string };export function signAttestationRecord(record: AttestationRecord, vault: string, opts?: { passphraseFromEnv?: string }): AttestationRecord(refuses by name when no key exists; never auto-generates);export function verifyAttestationSignature(record: AttestationRecord, vault: string, opts?: { publicPath?: string }): boolean. Keys under<vault>/.open-second-brain/keys/attestation/; private keyfile 0600 withrestrictToOwnerand the sync-exclusion marker; key material never printed.src/core/brain/attestation/verify.ts:export type AttestationShardState = "intact" | "appended" | "diverged" | "missing";export interface AttestationVerification { readonly recordId: string; readonly createdAt: string; readonly signatureValid: boolean; readonly shards: ReadonlyArray<{ readonly shardId: string; readonly state: AttestationShardState }>; readonly storeDigestMatches: boolean };export function verifyAttestation(vault: string, record: AttestationRecord, opts?: { safeguard?: Safeguard; progress?: ProgressSink }): AttestationVerification.
- K5 - shared registries are append-only. Files listed in the shared table below are edited by a lane only in its lane-final task, appends only (never edits, reorders or deletes another lane's entries), and committed in that lane's own final commit via
git commit --only. The integrator re-freezes ordering and prose.
File ownership table
Each file is owned by exactly one lane (or nobody). A lane that needs a file outside its ownership stops and renegotiates this contract; it never reaches into another lane's files.
| Files | Owner |
|---|---|
src/core/brain/delivery-shaping.ts, src/core/brain/provenance/page-origin.ts, src/core/brain/doctor/delivery-provenance-check.ts |
Lane A |
src/mcp/search-tools.ts, src/mcp/brain/reach-events.ts, src/mcp/brain/query-tools.ts, src/mcp/brain/context-tools.ts, src/mcp/resources.ts |
Lane A |
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 |
src/core/brain/context-receipts-verify.ts, src/core/brain/doctor/receipt-content-drift-check.ts, src/mcp/brain/pack-tools.ts, src/cli/brain/verbs/context-receipts.ts |
Lane B |
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 |
plugins/opencode/open-second-brain.ts, tests/plugins/opencode-plugin.test.ts, tests/core/install/adapters/opencode-hook-parity.test.ts, install/opencode.md |
Lane C |
src/core/brain/attestation/**, src/cli/brain/verbs/attest.ts, src/mcp/brain/attest-tools.ts, src/core/brain/log.ts, src/core/state/surfaces.ts |
Lane D |
tests/core/brain/attestation/**, tests/cli/brain-attest.test.ts, tests/mcp/attestations-tool.test.ts, tests/core/brain/doctor/attestation-check.test.ts |
Lane D |
src/core/brain/untrusted-source.ts, src/core/integrity/digest.ts, src/core/brain/log-chain.ts, hooks/**, src/core/brain/secrets/**, src/core/brain/snapshot.ts, src/core/search/visibility-surface-registry.ts (read for row shapes) |
Nobody - read-only precedents; no lane modifies them except through the shared protocol rows below |
src/core/brain/context-receipts.ts |
Renegotiated (fix wave 1): Lane B may modify it. The trigger vocabulary moved to the leaf context-receipt-trigger.ts with a re-export keeping the export surface, so the "Nobody - read-only precedent" row above no longer describes this file; recorded here per K5 instead of edit-and-explain. |
Shared files (K5 append-only protocol): src/core/brain/doctor.ts; src/core/brain/doctor-exits.ts; src/core/brain/diagnostics.ts; src/core/search/visibility-surface-registry.ts; src/cli/command-manifest.ts; src/cli/brain/help-text.ts; tests/core/architecture/verdict-vocabulary-census.test.ts (Lane A only); tests/core/architecture/state-surface-census.test.ts consumers and tests/core/state/surfaces.test.ts (Lane D only); tests/core/brain/sync-lockfile.test.ts DECLARED map (Lane D only); tests/cli/manifest-completeness.test.ts, tests/cli/help-surface-parity.test.ts, tests/cli/completions.test.ts (Lane B and D, each appends its own entries); tests/mcp/brain-tools-parity.test.ts and tests/helpers/tool-probe-catalogue.ts (Lane B extends the receipts probe, Lane D adds the attestations entries); docs/cli-reference.md and docs/mcp.md (each lane appends its own rows).
Lane A - tier-keyed quote fencing on remote read deliveries (t_1af24938)
Task A1: Treatment vocabulary, fail-closed derivation and provenance probe
- Files: new
src/core/brain/delivery-shaping.tsandsrc/core/brain/provenance/page-origin.tsper contract K1; newtests/core/brain/delivery-shaping.test.tsandtests/core/brain/provenance/page-origin.test.ts. - Acceptance: the failing-first tests prove:
storedTextTreatmentresolvesfencedfor anuntrusted_sourcemarker, forcontent_class: prompt-derived, for channelsmcp-toolandimport, and for EVERY absence case (null origin, null channel, theunsetliteral) - andplainonly for channelcliwith no marker and no prompt-derived class; an unreadable page probes to a fenced treatment without throwing;shapeStoredTextForDeliverywithplainreturns byte-identical input and withfencedreturns thefenceUntrustedContentwrapper whose body is neutralized and idempotent under a second application; the fence'soriginattribute is thedeliveryOriginLabeltext and survives a hostile label (attribute-escaped, single line); the vocabulary is a frozen closed set answered byisDeliveryTreatment. - Depends on: none.
Task A2: Search family wiring
- Files: modified
src/mcp/search-tools.ts- intoolBrainSearch, shape each row'scontentafterwindowContent(probe through the pipeline's existingFrontmatterCache, treatment from K1, remote-only viacontextReach(ctx)); same treatment intoolBrainSearchExpand(chunk text) andtoolBrainFileContext(snippets); newtests/mcp/quote-fencing-search.test.ts. - Acceptance: the failing-first tests prove: at
TRANSPORT_REACH.remote, an agent-origin row's deliveredcontentis the fenced text naming the derived provenance, and a legacy row with no stamps is fenced (fail closed); atTRANSPORT_REACH.localevery row is byte-identical to the pre-wave shape (the existing reach pins stay green untouched); a withheld row is dropped exactly as today with no fence and no count;brain_search_expandandbrain_file_contextfollow the same remote-quoted/local-identical rule; no output schema changed (the fence is inside the existing fields). - Depends on: A1.
Task A3: Report-shaped delivery binding
- Files: modified
src/mcp/brain/reach-events.ts(newexport function deliveryView(ctx: ServerContext): { reach: TransportReach; shape(text: string, rel: string): string }deriving treatment once per request - the one binding every report-shaped read shares); modifiedsrc/mcp/brain/query-tools.ts(toolBrainQuerypreference/topic payload bodies,toolBrainAgentQueryandtoolBrainAgentDiffcontribution bodies,toolBrainDecisionpage text shaped through it); newtests/mcp/quote-fencing-reports.test.ts. - Acceptance: the failing-first tests prove: preference and topic payload bodies are fenced at remote reach and byte-identical at local; agent contribution bodies (note-write text) are fenced at remote reach; decision pages are fenced at remote reach; the binding probes provenance through the shared cache (no uncached per-row reads, asserted by a read-count fixture); withheld references stay identical-to-absent through every serializer; log-entry serializers are untouched.
- Depends on: A1.
Task A4: Whole-document surfaces
- Files: modified
src/mcp/brain/context-tools.ts(toolBrainContextactive body andtoolBrainPinnedContextbodies shaped at remote reach); modifiedsrc/mcp/resources.ts(thereadPreference,readTopic,readActive,readLessonsandreadBacklinksreaders shape their markdown at remote reach); newtests/mcp/quote-fencing-resources.test.ts. - Acceptance: the failing-first tests prove:
brain_contextandbrain_pinned_contextdeliver fenced bodies at remote reach and byte-identical bodies at local; each named resource reader delivers fenced markdown at remote reach and unchanged markdown at local;readStatus/readDigestLatestand the log reader are untouched; the fences are validuntrusted_sourcespans (open tag, neutralized body, close tag) on every shaped surface. - Depends on: A1.
Task A5: Doctor check, census registrations and registry reasons (lane final)
- Files: new
src/core/brain/doctor/delivery-provenance-check.ts(failSoft; counts delivered-surface pages whose provenance is not derivable, named-path cap,ctx.readablefilter - the privacy-marker shape; codedelivery-provenance-unknown) andtests/core/brain/doctor/delivery-provenance-check.test.ts; SHARED appends:src/core/brain/doctor.ts(entry afterprivacyMarkerCheck),src/core/brain/doctor-exits.tsorsrc/core/brain/diagnostics.ts(classification for the new code),src/core/search/visibility-surface-registry.ts(lane A's surface rows gain the shaper reason),tests/core/architecture/verdict-vocabulary-census.test.ts(registerDELIVERY_TREATMENTwith the frozen trio), docs rows indocs/cli-reference.mdanddocs/mcp.md. - Acceptance: the failing-first tests prove: a vault of unstamped pages yields one warning with a capped named-path list; a fully stamped vault is silent; unreadable pages are excluded via
ctx.readable; the census accepts the new vocabulary and fails when a member is added without registration; the visibility-surface sweep passes with the updated reasons; the doctor registry-order assertions hold with the appended entry. - Depends on: A1 (A2-A4 for the end-to-end wording only).
Lane B - context-receipt re-hash verification (t_4300e5fd)
Task B1: Verify kernel
- Files: new
src/core/brain/context-receipts-verify.tsper contract K2; newtests/core/brain/context-receipts-verify.test.ts(fixtures emitted withemitContextReceiptagainst temp-vault pages, per the context-receipts suite shape). - Acceptance: the failing-first tests prove: an unmodified page re-hashes to
matchwith equal expected/observed digests; an edited page body yieldschanged; a deleted page yieldsunavailable(file_missing); an unreadable page yieldsunavailable(unreadable); atrimmed: trueitem re-hashes through the re-appliedapplyCharBudgetcut with the receipt's recordedmax_chars_per_memoryand reportsmatch(the false-CHANGED hazard), while the same page edited beyond the cut reportschanged; apre_compressitem withoutpathreportsunavailable(no_hash)and the active-body item withpath+hash verifies; a session_inject receipt returns every itemunavailable(no_hash)withsessionInjected: trueand the by-construction note; structural ids reportunavailablewithout any inferred verdict; an absolute host path recorded by today's emitter and a vault-relative spelling both resolve; a path escaping the vault maps tounavailable(file_missing)with a note and never throws; a retired note's new path verifies against its retired body; verdicts and reasons are a frozen closed vocabulary. - Depends on: none.
Task B2: MCP verify operation
- Files: modified
src/mcp/brain/pack-tools.ts- theoperationenum ofbrain_context_receiptsgrowsverify; unknown receipt id isMCPError(INVALID_PARAMS, ...)mirroring show;record.private || record.redactedrefused symmetrically with the fold; belowTRANSPORT_REACH.localthe typed refusal shape the receipts tool already returns; newtests/mcp/context-receipts-verify-tool.test.ts; SHARED append:tests/helpers/tool-probe-catalogue.ts(probe rows for the verify operation). - Acceptance: the failing-first tests prove:
brain_context_receiptswithoperation: "verify"and a receipt id returns the K2 shape over the JSON-RPC harness with fixtures emitted directly; an unknown id is refused by name with the same error code show uses; a private/redacted receipt is refused; a remote-reach call gets the typed refusal, not a partial verify; the full-table registration and output contract pass unchanged (no schema edit); the probe catalogue entries exist and the frozen tool-name set is untouched. - Depends on: B1.
Task B3: CLI verify subcommand
- Files: modified
src/cli/brain/verbs/context-receipts.ts(verify <receipt-id> [--json]positional dispatch beside list/show; unknown id is aCliErrornaming the id; same refusal rules as the MCP face for private/redacted receipts); SHARED appends:src/cli/command-manifest.ts(context-receipts row gains the verify subcommand text),src/cli/brain/help-text.ts(row update),tests/cli/manifest-completeness.test.ts,tests/cli/help-surface-parity.test.ts,tests/cli/completions.test.ts(verify entries); newtests/cli/context-receipts-verify-cli.test.ts(runCli helper, temp vault). - Acceptance: the failing-first tests prove:
o2b brain context-receipts verify <id>prints per-item verdict lines and a summary, exit 0 when nothing reportschanged; exit 1 with the offending item ids when anything reportschangedor a signature-level refusal fires;--jsonemits the exact K2 shape; an unknown id exits non-zero naming the id; the manifest, help and completion surfaces match the dispatcher (manifest-completeness and help-parity green). - Depends on: B1.
Task B4: Doctor drift check and shared registrations (lane final)
- Files: new
src/core/brain/doctor/receipt-content-drift-check.ts(failSoft; re-verifies a bounded recent window of receipts, one warning with per-verdict counts and the next commando2b brain context-receipts verify <id>; legacy hashless receipts silent; codereceipt-content-drift) andtests/core/brain/doctor/receipt-content-drift-check.test.ts; SHARED appends:src/core/brain/doctor.ts(entry afterreceiptLedgerCheck),src/core/brain/doctor-exits.tsorsrc/core/brain/diagnostics.ts(classification), docs rows indocs/cli-reference.mdanddocs/mcp.md(verify operation and verb rows). - Acceptance: the failing-first tests prove: a window with an edited page yields exactly one warning naming counts and the next command; a clean window is silent; hashless legacy receipts are silent; the window is bounded (a large ledger does not scan unbounded); the doctor never mutates and never throws; registry-order and exit-census assertions hold.
- Depends on: B1 (B2/B3 for the next-command wording only).
Lane C - opencode tool gating and prompt-time injection (t_eaf760a6)
Task C1: Fail-soft execute.before gate
- Files: modified
plugins/opencode/open-second-brain.ts- V1tool.execute.beforeand V2ctx.tool.hook("execute.before")registrations feature-detected exactly like the existingexecute.afterguards; spawno2b-hook pretool-orientandpretool-host-backupwith synthetic PreToolUse payloads throughhookCommandper contract K3; map onlyhookSpecificOutput.permissionDecision === "deny"to a thrown error carryingpermissionDecisionReason; every other outcome (flag off, spawn failure, timeout withinHOOK_TIMEOUT_MS, malformed stdout) passes untouched; extendedtests/plugins/opencode-plugin.test.ts(harness captures the new registrations; stub shim processes emit controlled verdicts). - Acceptance: the failing-first tests prove: a shim deny verdict throws with the redirect text and the tool call is blocked; a shim allow verdict, a missing shim binary, a timeout, and malformed JSON all pass the tool call through untouched (fail-soft matrix); the opt-in flags off mean zero spawns; V1 and V2 paths register symmetrically under their respective capability detections; the plugin file still imports only node builtins and Bun globals (a source-scanning assertion).
- Depends on: none.
Task C2: Prompt-time injection with queue-then-context delivery
- Files: modified
plugins/opencode/open-second-brain.ts- V2ctx.session.hook("prompt")(V1chat.messagebehind feature detection) observes the prompt and spawns the four UserPromptSubmit shims with session-id-carrying payloads per K3; returnedadditionalContextenters a single-slot per-turn queue; the existing context delivery points (experimental.chat.system.transformandctx.session.hook("context")) drain the queue beside the TTL-cached active inject on the first model request of the turn and mark it delivered; extendedtests/plugins/opencode-plugin.test.ts(multi-model-request turn fixture: two context-hook fires after one prompt deliver the queued text exactly once). - Acceptance: the failing-first tests prove: one prompt enqueues one payload and the next context hook delivers it exactly once even when the context hook fires twice in the turn; a second prompt replaces any undelivered payload (single-slot) and dedupe still holds through the vault ledger via the synthetic payloads carrying the opencode session id; the TTL cache of the active inject is unaffected (its cache key and window unchanged); the four shims spawn with
UserPromptSubmitevent names and the flags off means zero spawns; all spawns ridehookCommand(no second argv builder). - Depends on: C1.
Task C3: Parity census and lane docs (lane final)
- Files: new
tests/core/install/adapters/opencode-hook-parity.test.ts- derive the required<event>:<hook>row set fromhooks/hooks.json(the grok-precedent parser shape), require the plugin source to cover it, carryDECLARED_OPENCODE_DIVERGENCESfrozen map with written reasons for at least:Stop:stop-log-guardrail,Stop:answer-quote-check,Stop:hygiene-digest,SubagentStart:subagent-inject,PreToolUse:nudge-channel(no additionalContext channel on tool calls),UserPromptSubmit:pre-admission-caveat(the prompt hook observes before durable admission; delivery rides the context hook) - a stale declared divergence fails, and both the required set and the divergence set have non-vacuous size floors; modifiedinstall/opencode.md(capability table rows for the gate and the prompt lane, the live-verification QA note). - Acceptance: the failing-first tests prove: removing an
execute.beforeregistration from the plugin source fails the census; removing a divergence entry while the gap persists fails; adding a hooks.json row without an opencode decision fails; the floors prevent a vacuous pass after a parser regression; the docs table names the gate, the prompt lane and every declared divergence. - Depends on: C1, C2.
Lane D - Ed25519-signed attestations (t_3bdb82b0)
Task D1: Manifest digest kernel and the log head collector
- Files: new
src/core/brain/attestation/digest.tsper contract K4 (collectAttestationManifest,attestationStoreDigest); modifiedsrc/core/brain/log.ts(exportcollectLogShardHeadsexactly per K4 - per-shard-directoryacquireLogLock, backward scan per shard,{}when no log); newtests/core/brain/attestation/digest.test.ts. - Acceptance: the failing-first tests prove: the manifest records one head per JSONL shard keyed by shard id, each matching
lastChainHash's value for that shard; heads are collected under the appender's per-day lock (a concurrent-append fixture shows the collector never claims a head the appender already superseded); a vault with no log yields an empty head map; the ledger inventories list exactly the doctor-swept ledger directories' files; the index stamp is the search store's current stamp token or null when absent; the store digest is stable across two collections with no intervening writes and changes when a shard head moves; the digest issha256Hex(canonicalJson(manifest))byte-for-byte. - Depends on: none.
Task D2: Attestation record and signing kernel
- Files: new
src/core/brain/attestation/record.ts(schema constant, sealedAttestationRecord, atomicattest-<UTC-compact>.jsonwrite under a lock registered per Task D4, hard refusal on unknownschema_version) andsrc/core/brain/attestation/signing.ts(keygen 0600 +restrictToOwner+ sync-exclusion marker under<vault>/.open-second-brain/keys/attestation/, sign refusing by name withATTESTATION_KEY_MISSINGwhen no key exists, verify against the public half, optional envelope passphrase wrap,$secret:resolution viaresolveNamedSecret); newtests/core/brain/attestation/signing.test.ts. - Acceptance: the failing-first tests prove: a written record re-reads and
digestVerifiesholds (seal doctrine); a tampered body fails the seal; an unknown schema_version is refused by name; keygen creates a 0600 private keyfile and a public half with the sync-exclusion marker and owner ACL (asserted by mode and content); sign without keygen refuses withATTESTATION_KEY_MISSINGand never creates a key; sign produces a signature that verifies, and any body mutation invalidates it; the passphrase-wrapped path unlocks and signs; no code path prints key material (a stdout-scanning assertion); the state-surface vault-guard assertion fires on the write path. - Depends on: D1.
Task D3: Verification kernel - signature, head continuity, store drift
- Files: new
src/core/brain/attestation/verify.tsper contract K4 (verifyAttestation: signature check; per-shard stateintact/appended/diverged/missingby walking the shard chain forward from the attested head throughprevlinks using the log-chain row grammar; store-digest recomputation and comparison); newtests/core/brain/attestation/verify.test.ts. - Acceptance: the failing-first tests prove: no writes after signing yields every shard
intactandstoreDigestMatches: true; legitimate appends after signing yieldappendedon exactly the appended shards and an unchanged store-digest verdict reported honestly (recomputed manifest differs, reported asstoreDigestMatches: falsewith the appended shards explaining it - the record's own digest still verifies); an edited chained line after the attested head yieldsdivergedon that shard; a deleted shard yieldsmissing; a tampered signature yieldssignatureValid: false; verification performs no writes and never throws (fail-soft report); an optionsSafeguard/ProgressSinkis accepted and consulted on long walks. - Depends on: D1, D2.
Task D4: State surface and census registrations
- Files: modified
src/core/state/surfaces.ts(STATE_SURFACE_ID.attestations = "attestations"plus theSTATE_SURFACESentry followingingest_checkpoints' shape: derived, tier, override_env, carries_memory false, sources naming the attestation kernel); modified the attestation record's lock registration intests/core/brain/sync-lockfile.test.tsDECLAREDmap (the lock site under alockScanRootsroot); SHARED:tests/core/state/surfaces.test.tsextension. - Acceptance: the failing-first tests prove: the surfaces census binds
INSTALL-style registry equality with the new id in both directions;o2b state statusand thevault_healthMCP field render the new row (existing suites extended); the lock-site census passes only with theDECLAREDentry (a deliberately unregistered run fails); the write-site census accepts the atomic writer without an exclusion entry. - Depends on: D2 (the write path whose lock and surface are registered).
Task D5: Operator CLI verbs
- Files: new
src/cli/brain/verbs/attest.ts(cmdBrainAttestdispatchingkeygen | sign | list | verify,--jsonshapes, passphrase ingestion via--passphrase-from-envor stdin never argv, exit-code contract percmdBrainLogVerify: 0 intact/appended, 1 diverged or invalid signature, 2 usage); modifiedsrc/cli/brain.ts(case "attest"); SHARED appends:src/cli/command-manifest.ts(attest command row with flags),src/cli/brain/help-text.ts(attest row),tests/cli/manifest-completeness.test.ts,tests/cli/help-surface-parity.test.ts,tests/cli/completions.test.ts; newtests/cli/brain-attest.test.ts(runCli helper, temp vault, the secret-verb passphrase ladder shape). - Acceptance: the failing-first tests prove:
attest keygencreates the key pair and prints paths only;attest signwithout keygen exits non-zero namingattestation_key_missingand the keygen command;attest signwrites one file andattest listshows it newest-first with id, created_at, device;attest verifyon an untouched vault exits 0 reporting per-shardintact; after an append it exits 0 withappendednamed; after a forged edit it exits 1 naming the diverged shard and the invalid verdict path;--jsonemits the K4 shapes; manifest, help and completions match the dispatcher. - Depends on: D3, D4.
Task D6: Read-only MCP tool, doctor check and shared registrations (lane final)
- Files: new
src/mcp/brain/attest-tools.ts(ATTEST_TOOLSexporting read-onlybrain_attestationswithoperation: list | verify,kind: "read", no keygen/sign surface - thebrain_secretssplit) andsrc/core/brain/doctor/attestation-check.ts(failSoft; reports a missing key only when attestations exist, a stale last attestation beyond a named age, and diverged shards from the newest attestation; codeattestation-stale-or-diverged); modifiedsrc/mcp/brain-tools.ts(registerATTEST_TOOLS); newtests/mcp/attestations-tool.test.tsandtests/core/brain/doctor/attestation-check.test.ts; SHARED appends:src/core/brain/doctor.ts(entry afterlogChainCheck),src/core/brain/doctor-exits.tsorsrc/core/brain/diagnostics.ts(classification),tests/mcp/brain-tools-parity.test.ts(new frozen name + read partition entry),tests/helpers/tool-probe-catalogue.ts(attestations probe),tests/core/architecture/visibility-surface-registry.tsrows via the shared protocol, docs rows indocs/cli-reference.mdanddocs/mcp.md. - Acceptance: the failing-first tests prove: the tool is registered in the full table, absent from writer surfaces, and list/verify work over the JSON-RPC harness with fixture attestations; signing has no MCP face (the tool input schema has no mutation operation); a clean vault with attestations and a fresh key is silent in the doctor; a stale attestation or a diverged shard yields one warning naming the next command; exit-census and registry-order assertions hold; the parity test pins the new name in the read partition.
- Depends on: D3, D4, D5 (registry positions only).
Integrator
Task I1: Reconciliation and full gates
- Files: the shared files if any lane overlap needs re-freezing (
src/core/brain/doctor.tsfinal registry order, the classification files,tests/cli/*shared guards,tests/helpers/tool-probe-catalogue.ts,src/core/search/visibility-surface-registry.ts,docs/cli-reference.mdanddocs/mcp.mdcoherence pass). - Acceptance: the full local gates pass in CI order - formatter check,
bun run lint,bun run typecheck, and the FULL test suite (the only place the full suite runs); the doctor registry order reflects the three appended checks in their named positions; every user-visible surface added by lanes A-D has a docs row; the opencode parity census passes with its declared divergences; no placeholders anywhere; the branch contains only lane commits plus this reconciliation. - Depends on: A5, B4, C3, D6.
Commit shape
- Lane commits use conventional messages on this branch, each committing only its own files via
git commit --only <paths>:feat(mcp): fence unverified stored text on remote read deliveries(lane A),feat(brain): re-hash verification for context receipts(lane B),feat(opencode): tool gating and prompt-time injection parity(lane C),feat(brain): Ed25519-signed store attestations(lane D). Shared-registry appends ride each lane's final task commit through the same--onlyrule. - The brainstorm artifacts commit separately as
chore(brainstorm): delivery-trustbefore any lane work. - Review gates beyond tests: any diff showing a fence applied at local reach, a new output-schema field on a touched tool, a new
checkpoint-named file or symbol, a signature verification that gates a read, or an opencode code path that throws on anything but an explicit shim deny is a defect regardless of test outcome.