Skip to content

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

TypeScript
35.1 KB
Raw Blame

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 } - plain returns the input bytes unchanged; fenced returns fenceUntrustedContent(text, origin) from src/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): PageOriginForDelivery reading only ORIGIN_CHANNEL_FIELD, CONTENT_CLASS_FIELD, UNTRUSTED_SOURCE_FRONTMATTER_KEY via readCachedFrontmatterEntry; export function storedTextTreatment(origin: PageOriginForDelivery | null): DeliveryTreatment - marker true, or content_class: prompt-derived, or channel mcp-tool/import, or ANY absence (null origin, null channel, unset) resolves fenced; only channel cli with no other marker resolves plain; export function deliveryOriginLabel(origin: PageOriginForDelivery): string - the fence's origin attribute 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 via sha256Hex (src/core/integrity/digest.ts) only; path resolution via ensureInsideVault; transforms re-applied per design.md (frontmatter strip, guard, applyCharBudget with the recorded budget.max_chars_per_memory when trimmed).
  • 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-backup with synthetic payloads {"hook_event_name":"PreToolUse","session_id":<opencode session id>,"tool_name":<tool>,"tool_input":<args>,"cwd":<dir>} and o2b-hook recall-inject / nav-inject / counterparty-brief / reground-deliver with {"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) and hookSpecificOutput.additionalContext (enqueued for the context hook). No src/ or hooks/ 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.ts gains exactly one export: export function collectLogShardHeads(vault: string): Readonly<Record<string, string>> - every *.jsonl shard's chain head, each read under acquireLogLock for 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 via sealWithDigest; signature null on an unsigned record is refused by verify); export const ATTESTATIONS_REL = "attestations" under DERIVED_STORE_DIR; export function writeAttestationRecord(vault: string, record: AttestationRecord): { readonly path: string } - one atomic JSON file attest-<UTC-compact>.json under 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 with restrictToOwner and 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.ts and src/core/brain/provenance/page-origin.ts per contract K1; new tests/core/brain/delivery-shaping.test.ts and tests/core/brain/provenance/page-origin.test.ts.
  • Acceptance: the failing-first tests prove: storedTextTreatment resolves fenced for an untrusted_source marker, for content_class: prompt-derived, for channels mcp-tool and import, and for EVERY absence case (null origin, null channel, the unset literal) - and plain only for channel cli with no marker and no prompt-derived class; an unreadable page probes to a fenced treatment without throwing; shapeStoredTextForDelivery with plain returns byte-identical input and with fenced returns the fenceUntrustedContent wrapper whose body is neutralized and idempotent under a second application; the fence's origin attribute is the deliveryOriginLabel text and survives a hostile label (attribute-escaped, single line); the vocabulary is a frozen closed set answered by isDeliveryTreatment.
  • Depends on: none.

Task A2: Search family wiring

  • Files: modified src/mcp/search-tools.ts - in toolBrainSearch, shape each row's content after windowContent (probe through the pipeline's existing FrontmatterCache, treatment from K1, remote-only via contextReach(ctx)); same treatment in toolBrainSearchExpand (chunk text) and toolBrainFileContext (snippets); new tests/mcp/quote-fencing-search.test.ts.
  • Acceptance: the failing-first tests prove: at TRANSPORT_REACH.remote, an agent-origin row's delivered content is the fenced text naming the derived provenance, and a legacy row with no stamps is fenced (fail closed); at TRANSPORT_REACH.local every 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_expand and brain_file_context follow 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 (new export 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); modified src/mcp/brain/query-tools.ts (toolBrainQuery preference/topic payload bodies, toolBrainAgentQuery and toolBrainAgentDiff contribution bodies, toolBrainDecision page text shaped through it); new tests/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 (toolBrainContext active body and toolBrainPinnedContext bodies shaped at remote reach); modified src/mcp/resources.ts (the readPreference, readTopic, readActive, readLessons and readBacklinks readers shape their markdown at remote reach); new tests/mcp/quote-fencing-resources.test.ts.
  • Acceptance: the failing-first tests prove: brain_context and brain_pinned_context deliver 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/readDigestLatest and the log reader are untouched; the fences are valid untrusted_source spans (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.readable filter - the privacy-marker shape; code delivery-provenance-unknown) and tests/core/brain/doctor/delivery-provenance-check.test.ts; SHARED appends: src/core/brain/doctor.ts (entry after privacyMarkerCheck), src/core/brain/doctor-exits.ts or src/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 (register DELIVERY_TREATMENT with the frozen trio), docs rows in docs/cli-reference.md and docs/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.ts per contract K2; new tests/core/brain/context-receipts-verify.test.ts (fixtures emitted with emitContextReceipt against temp-vault pages, per the context-receipts suite shape).
  • Acceptance: the failing-first tests prove: an unmodified page re-hashes to match with equal expected/observed digests; an edited page body yields changed; a deleted page yields unavailable(file_missing); an unreadable page yields unavailable(unreadable); a trimmed: true item re-hashes through the re-applied applyCharBudget cut with the receipt's recorded max_chars_per_memory and reports match (the false-CHANGED hazard), while the same page edited beyond the cut reports changed; a pre_compress item without path reports unavailable(no_hash) and the active-body item with path+hash verifies; a session_inject receipt returns every item unavailable(no_hash) with sessionInjected: true and the by-construction note; structural ids report unavailable without 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 to unavailable(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 - the operation enum of brain_context_receipts grows verify; unknown receipt id is MCPError(INVALID_PARAMS, ...) mirroring show; record.private || record.redacted refused symmetrically with the fold; below TRANSPORT_REACH.local the typed refusal shape the receipts tool already returns; new tests/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_receipts with operation: "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 a CliError naming 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); new tests/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 reports changed; exit 1 with the offending item ids when anything reports changed or a signature-level refusal fires; --json emits 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 command o2b brain context-receipts verify <id>; legacy hashless receipts silent; code receipt-content-drift) and tests/core/brain/doctor/receipt-content-drift-check.test.ts; SHARED appends: src/core/brain/doctor.ts (entry after receiptLedgerCheck), src/core/brain/doctor-exits.ts or src/core/brain/diagnostics.ts (classification), docs rows in docs/cli-reference.md and docs/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 - V1 tool.execute.before and V2 ctx.tool.hook("execute.before") registrations feature-detected exactly like the existing execute.after guards; spawn o2b-hook pretool-orient and pretool-host-backup with synthetic PreToolUse payloads through hookCommand per contract K3; map only hookSpecificOutput.permissionDecision === "deny" to a thrown error carrying permissionDecisionReason; every other outcome (flag off, spawn failure, timeout within HOOK_TIMEOUT_MS, malformed stdout) passes untouched; extended tests/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 - V2 ctx.session.hook("prompt") (V1 chat.message behind feature detection) observes the prompt and spawns the four UserPromptSubmit shims with session-id-carrying payloads per K3; returned additionalContext enters a single-slot per-turn queue; the existing context delivery points (experimental.chat.system.transform and ctx.session.hook("context")) drain the queue beside the TTL-cached active inject on the first model request of the turn and mark it delivered; extended tests/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 UserPromptSubmit event names and the flags off means zero spawns; all spawns ride hookCommand (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 from hooks/hooks.json (the grok-precedent parser shape), require the plugin source to cover it, carry DECLARED_OPENCODE_DIVERGENCES frozen 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; modified install/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.before registration 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.ts per contract K4 (collectAttestationManifest, attestationStoreDigest); modified src/core/brain/log.ts (export collectLogShardHeads exactly per K4 - per-shard-directory acquireLogLock, backward scan per shard, {} when no log); new tests/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 is sha256Hex(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, sealed AttestationRecord, atomic attest-<UTC-compact>.json write under a lock registered per Task D4, hard refusal on unknown schema_version) and src/core/brain/attestation/signing.ts (keygen 0600 + restrictToOwner + sync-exclusion marker under <vault>/.open-second-brain/keys/attestation/, sign refusing by name with ATTESTATION_KEY_MISSING when no key exists, verify against the public half, optional envelope passphrase wrap, $secret: resolution via resolveNamedSecret); new tests/core/brain/attestation/signing.test.ts.
  • Acceptance: the failing-first tests prove: a written record re-reads and digestVerifies holds (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 with ATTESTATION_KEY_MISSING and 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.ts per contract K4 (verifyAttestation: signature check; per-shard state intact / appended / diverged / missing by walking the shard chain forward from the attested head through prev links using the log-chain row grammar; store-digest recomputation and comparison); new tests/core/brain/attestation/verify.test.ts.
  • Acceptance: the failing-first tests prove: no writes after signing yields every shard intact and storeDigestMatches: true; legitimate appends after signing yield appended on exactly the appended shards and an unchanged store-digest verdict reported honestly (recomputed manifest differs, reported as storeDigestMatches: false with the appended shards explaining it - the record's own digest still verifies); an edited chained line after the attested head yields diverged on that shard; a deleted shard yields missing; a tampered signature yields signatureValid: false; verification performs no writes and never throws (fail-soft report); an options Safeguard/ProgressSink is 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 the STATE_SURFACES entry following ingest_checkpoints' shape: derived, tier, override_env, carries_memory false, sources naming the attestation kernel); modified the attestation record's lock registration in tests/core/brain/sync-lockfile.test.ts DECLARED map (the lock site under a lockScanRoots root); SHARED: tests/core/state/surfaces.test.ts extension.
  • Acceptance: the failing-first tests prove: the surfaces census binds INSTALL-style registry equality with the new id in both directions; o2b state status and the vault_health MCP field render the new row (existing suites extended); the lock-site census passes only with the DECLARED entry (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 (cmdBrainAttest dispatching keygen | sign | list | verify, --json shapes, passphrase ingestion via --passphrase-from-env or stdin never argv, exit-code contract per cmdBrainLogVerify: 0 intact/appended, 1 diverged or invalid signature, 2 usage); modified src/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; new tests/cli/brain-attest.test.ts (runCli helper, temp vault, the secret-verb passphrase ladder shape).
  • Acceptance: the failing-first tests prove: attest keygen creates the key pair and prints paths only; attest sign without keygen exits non-zero naming attestation_key_missing and the keygen command; attest sign writes one file and attest list shows it newest-first with id, created_at, device; attest verify on an untouched vault exits 0 reporting per-shard intact; after an append it exits 0 with appended named; after a forged edit it exits 1 naming the diverged shard and the invalid verdict path; --json emits 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_TOOLS exporting read-only brain_attestations with operation: list | verify, kind: "read", no keygen/sign surface - the brain_secrets split) and src/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; code attestation-stale-or-diverged); modified src/mcp/brain-tools.ts (register ATTEST_TOOLS); new tests/mcp/attestations-tool.test.ts and tests/core/brain/doctor/attestation-check.test.ts; SHARED appends: src/core/brain/doctor.ts (entry after logChainCheck), src/core/brain/doctor-exits.ts or src/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.ts rows via the shared protocol, docs rows in docs/cli-reference.md and docs/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.ts final 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.md and docs/mcp.md coherence 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 --only rule.
  • The brainstorm artifacts commit separately as chore(brainstorm): delivery-trust before 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.