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.
Trust-Surface Hardening β a nine-card wave making the credential store, the write path, the read path and the resumability artifacts state what they verified, refuse what they cannot, and name what they did
Status: draft
Author: Open Second Brain release wave
Audience: implementation (six lanes with disjoint file ownership; see plan.md)
Problem statement
Every surface an operator or agent has to trust is soft in one of four places: the secret store's key material sits on disk as a raw 32-byte file any same-user process can read, $secret:NAME config references resolve nothing because the resolver has zero production callers, and values resolved from env vars are invisible to the egress redactor. The write path lands tags Obsidian cannot parse (brain/topic/foo bar) and stamps capture kinds no pack vocabulary ever approved, and the read path silently returns the sorted-last session summary when several content-differing digests exist for one session. Agent-authored JSON payloads die on a generic parse error when a model prefixes a reasoning block, and the ingest manifest gates reprocessing on content bytes alone, so changed extraction settings leave unchanged sources answering with extraction shaped by the old contract. Each defect is fixed by making the surface state what it verified, refuse what it cannot, and name what it did β never by adding a silent fallback.
Scope
Nine tracker cards, one release:
- t_e6667a56 β passphrase-wrapped secret-store key: an opt-in scrypt envelope wraps the 32-byte DEK at the existing keyfile path, with
lock/unlockops, memory-only unlock state, and named locked-store refusals. - t_592d9e91 β passphrase-encrypted credential bundles: export/import the store's entries as a single passphrase-encrypted, schema-versioned JSON envelope sharing the card-1 KDF, with a declared egress destination.
- t_e5807974 β named-secret resolver routing: a custody-store-backed provider with env fallback behind the existing
$secret:syntax, routed into the credential consumers, with resolved literals wired into egress redaction. - t_11ee559f β Obsidian tag syntax validation plus a doctor detector: write-time validation in the tag composers against the one rule in
src/core/tags.ts, and an opt-in frontmatter-tags hygiene detector for existing vault content. - t_151a564c β pack vocabulary enforced on capture writes:
writeCaptureNote/writeIdeaNoterefuse an undeclaredkindwhen the vault's pack explicitly declarespage_types, before name allocation; fail-open on absent config per the established substitution precedent. - t_59d4c919 β divergent session summaries surfaced on single-session reads: additive
digest_count/divergentfields plus an id/hash list on the MCP and CLI single-session reads. - t_dac8bf7e β named think-block strip before CLI JSON parse: a shared strip-and-note parser for the four model-answer verbs; the strip is named on the success envelope, failure stays a named exit-1 refusal.
- t_18fda844 β digest-sealed content adoption plans: the state-migration seal generalized into
src/core/integrity/digest.tsand applied to the Claude-memory import dry-run/apply pair and the brain-upgrade plan, including the caller-supplied-plan seam. - t_586d5d8b β extraction-contract fingerprint in the ingest manifest: a manifest-wide
contractfield, schema bump to 2 with a v1 read path, planner comparison, and plan-id folding.
Out of scope
- The link-verb half of the vocabulary card. No
add_linkverb exists in the tree; only schema-mutation ops (add_link_type/add_link_constraint,schema-mutate.ts) do. Link-vocabulary enforcement has no write site to gate and is not built. - Any merge policy for divergent summaries. The continuity store stays append-only; divergence is named (
digest_count,divergent, id/hash list), never merged, deleted, or reconciled. - An argon2 native dependency. The KDF is scrypt from
node:crypto. The repo pins a single runtime dependency (proper-lockfile) and treats even optional native packages cautiously; argon2 would mean a native build or a new crypto package for a threat modelcrypto.ts:13-17already scopes. - MCP-surface changes beyond named response extensions.
brain_secretsstayslist|run(no lock/unlock/export/import over MCP, per theadmin-tools.ts:295-299no-set/get refusal precedent); the divergence fields onbrain_session_summaryget are additive keys on an existing tool, nothing more; routingsrc/core/graph/mcp-config.tsenv blocks through the resolver is deferred (open question below). - Silent fallbacks of any kind. Every fail-open posture in this wave (absent pack config, absent envelope, clean JSON, v1 manifest) is a named, documented declarative policy that predates the wave; no new path falls back quietly. A locked store never falls back to env for a name the store holds; a stripped payload is never silently accepted; a still-invalid payload never passes.
Premise verification
Each card's recon was spot-checked against the live source before design. The anchors cited below were opened and verified across all four recon files, covering the crypto module, the resolver and egress planes, the tag rules and composers, the seal primitives, the session-summary read and its two surfaces, the capture writers, the manifest and planner, and the CLI parse sites. One test-path imprecision was found and is corrected under t_11ee559f. No card is refuted; nothing in the recon's load-bearing claims required correction.
- t_e6667a56 (wrapped keyfile) β confirmed.
loadOrCreateKeyatsrc/core/brain/secrets/crypto.ts:86-142withKEY_BYTES = 32at :36, exclusive-create first-writer handling, per-valueencryptValue/decryptValueAES-256-GCM at :144-164; op switchset|list|rm|runatsrc/cli/brain/verbs/secret.ts:45-48;brain_secretsMCP restriction docblock atsrc/mcp/brain/admin-tools.ts:294-299. - t_e5807974 (resolver plane) β confirmed.
src/core/secret-ref.tsis 86 lines withparseSecretReference:27-32,resolveSecretReference:34-47,redactKnownSecretValues:67-86;EGRESS_REDACTION_OPTIONSatsrc/core/egress/guard.ts:140-143,redactForEgressat :181,redactConfigMappingat :241-245;EGRESS_SITESatsrc/core/egress/registry.ts:108-343;o2b secretsdispatch atsrc/cli/main.ts:1270. - t_592d9e91 (credential bundles) β confirmed. Guard/registry anchors above; census population rules verified in
tests/core/architecture/egress-census.test.ts(rule 1 keys on declaredout/outdir/destparameters, and a declared site's module must be in the population β the destination flag and its registry entry must land in one commit). - t_11ee559f (tag validation) β confirmed, one test-path correction.
TAG_REatsrc/core/tags.ts:29with the docblock explicitly reserving itself as this card's seam ("validate against the rule defined HERE, never against a copy");OBSIDIAN_TAG_REatsrc/core/brain/hygiene/detectors/tags.ts:62; schema-vocabTOKEN_REatsrc/core/brain/schema-vocab.ts:38(rejects/, must not be reused); composers verified atsrc/core/brain/signal.ts:797-822andsrc/core/brain/preference.ts:808-825(raw trimmed topic intobrain/topic/); hand-rendered import frontmatter atsrc/core/brain/claude-memory-render.ts:80. Correction: recon-validation cites the signal tag-assertion tests attests/core/brain/signal.test.ts; the file is actuallytests/core/brain.signal.test.ts(dot-named convention, as recon-sessions spellstests/core/brain.session-summary.test.tscorrectly). - t_59d4c919 (divergent summaries) β confirmed.
getSessionSummaryreturnsrecords[records.length - 1]unannounced atsrc/core/brain/session-summary.ts:173-180; sort by(createdAt, id)at :215-221; content-hash dedupe key at :139-150; MCP get atsrc/mcp/brain/synthesis-tools.ts:125-129; CLI get atsrc/cli/brain/verbs/session-summary.ts:80-103. The serializer drift is real: the MCP serializer includesproject(synthesis-tools.ts:84), the CLI serializer omits it (session-summary.ts:136-147). - t_151a564c (capture vocabulary) β confirmed.
BRAIN_CAPTURE_KINDatsrc/core/brain/capture/capture-note.ts:52,writeCaptureNoteat :208,allocateAndCreateat :230,parseCaptureFilekind check at :287;CAPTURED_IDEA_KINDatsrc/core/brain/capture/inbox-drain.ts:61; absent-config substitutionABSENT_SCHEMA_CONFIG_TEXTatsrc/core/brain/schema-pack.ts:56withreadSchemaPackSourceat :78-83; write-session polarity verified atsrc/core/brain/write-session/validate.ts:178-197(fails closed when a type is named but no vocabulary, fails open when none declared). - t_18fda844 (sealed plans) β confirmed.
sealManifest/manifestVerifiesatsrc/core/state/migrate.ts:186-194;sha256Hex/canonicalJsoninsrc/core/integrity/digest.ts(:43-45, :61-73);planUpgradeatsrc/core/brain/upgrade.ts:116-134returns an unsealed frozen plan; byte-drift refusal at :182-193 namesre-run --dry-runbut nothing seals a caller-supplied plan object. - t_dac8bf7e (think-block strip) β confirmed. Bare
JSON.parsewith the refusalpayload must be valid JSONverified atsrc/cli/brain/verbs/extract-signals.ts:129-140andsrc/cli/brain/verbs/design-note.ts:105-113. - t_586d5d8b (extraction-contract fingerprint) β confirmed.
SCHEMA_VERSION = 1atsrc/core/brain/ingest/content-manifest.ts:41,ContentManifestat :53-58; manifest consultation atsrc/core/brain/ingest/batch-plan.ts:354-356;computePlanIdatsrc/core/brain/ingest/checkpoint.ts:80-91folds only the source dir plus sorted paths.
Chosen approach
The consultant's three variants are reproduced verbatim in variants.md. The recommendation is Variant 3 β forced sharing only, tiered enforcement, additive named keys, and the orchestrator accepts it without override.
Share exactly what the cards force: one src/core/brain/secrets/envelope.ts KDF/wrapped-envelope substrate under cards t_e6667a56 and t_592d9e91 (card 3 shares the KDF with card 1 by card statement), and one sealWithDigest/digestVerifies lift into src/core/integrity/digest.ts under cards t_18fda844 and (as a consumer of the same primitives) t_586d5d8b. Card t_e5807974 is a separate resolver-plane slice composing parseSecretReference with a read-oriented decrypt over the custody store, threading resolved literals into the egress guard policy so redactKnownSecretValues finally gains production callers. Enforcement is tiered by blast radius: tag validation rejects caller-controlled input at the composers (consuming the rule from src/core/tags.ts, never a copy) while capture vocabulary rejects only where the vault made a declaration, with hygiene detectors as the companion for existing vaults. Cards t_59d4c919 and t_dac8bf7e extend the existing response envelopes additively with named tokens, preserving byte-identity when the features are inactive.
This variant was chosen over Variant 1 (which couples all three secrets slices behind an up-front substrate and hard-rejects live feedback topics without a compatibility story) and Variant 2 (which leaves three drifting copies of credential-critical code and leaves the primary single-session read silent). Its enforcement polarities sit exactly where the repo's own precedents sit: declared-vocabulary rejection with fail-open on absent config (write-session/validate.ts:178-197, schema-pack.ts:56), and caller-controlled-input rejection at the composers.
Design decisions
- KDF: scrypt from
node:crypto, per-envelope random salt, stored parameters, no new dependency.scryptSyncwith explicitN = 2^15,r = 8,p = 1, 32-byte output, a random 16-byte salt per envelope, andmaxmemset explicitly; parameters are recorded inside the versioned envelope so they can migrate without breaking old stores, and an unknownalgoor version refuses with a named error (thereadStorebad-version precedent). Wrong-passphrase detection is free and fail-closed: the GCM auth tag over the wrapped DEK throws.timingSafeEqualguards any comparison. This matches the pinning posture (one runtime dependency) and the documented threat model (crypto.ts:13-17disclaims root/same-user attackers, against whom no passphrase KDF helps). - Envelope file format and location. New module
src/core/brain/secrets/envelope.ts. When the operator opts in, the raw 32-byte keyfile at<vault>/.open-second-brain/secrets/keyfileis replaced by a schema-versioned JSON envelope{ version, kdf: { algo: "scrypt", salt, n, r, p, maxmem }, wrapped: <EncryptedValue> }wherewrappedis theencryptValueoutput of the passphrase-derived key over the 32-byte DEK. The envelope file carries the same 0600/owner-only ACL discipline as the keyfile it replaces (loadOrCreateKeydetects the envelope at the same path; the raw-keyfile branch remains the default and behaves byte-identically when no envelope exists). Opt-in is the operator's explicit wrap action, not a config key β presence of an envelope at the keyfile path is the state, and an unwrapped store needs no flag. - Memory-only unlock semantics. The passphrase arrives via stdin or
--passphrase-from-env(there is no TTY password infrastructure in the repo; this follows thesetop's ingestion pattern). The derived key lives only in a module-level unlock holder insideenvelope.ts;unlockpopulates it after a verified unwrap,lockclears it, and the state is strictly process-local β the repo has no daemon, so every CLI invocation and the MCP server unlock separately. The passphrase is never persisted, logged, or audited; the audit trail gainssecret_locked/secret_unlockedrecords with no values (the existing no-values audit discipline). Lock/unlock is not offered over MCP. - Resolver provider interface and consumers.
src/core/secret-resolver.ts(Lane B) exposes a store-backed provider: it composesparseSecretReferencewith a read-oriented decrypt over the custody store β a new read-only resolve export insrc/core/brain/secrets/store.ts(Lane A) that skips thelast_used_atstamp and the exec audit, becauseresolveSecretForExecis read-shaped but a writer, and config reads must not take the write path. Precedence is store first, env fallback so existing setups keep working β except that a name the store holds under a locked envelope surfaces the named locked-store error rather than silently falling back to env (a silent fallback would hide the locked state). Consumers routed through the merged provider: the embeddings registry env probing, the decision-model env-key resolution, the research fetch keys, the Telegram token and installation secret insrc/core/config.ts, ando2b secrets status/listavailability. Resolution happens at use sites, not at config load, keeping plaintext spread no wider than the exec path's one-variable discipline. On the redaction side, Lane B threads a literals list from the resolver into the guard policy (redactForEgress,redactConfigMapping) and the MCP error redaction, which is what finally givesredactKnownSecretValuesproduction callers. - Tag validation fail-vs-flag posture per write site. One spelling of the rule, consumed from
src/core/tags.ts(which gains a value-level predicate derived from the documented rule β never a copy), implemented insrc/core/brain/tag-syntax.ts. At the composers:extraTagsentries that fail the rule are rejected with a typed, field-naming error (caller-controlled input, exactness expected); topic segments are slugified for the tag β matching whatderiveSlugalready does to the same input for the filename β and rejected only if even the slug fails the rule; scope segments are rejected, not rewritten. The Claude-memory import render path validates its derived topic/scope (already slugified today, so this is a pin, not a behavior change). The trade-off is stated honestly: a spaced topic's tag value changes frombrain/topic/foo bartobrain/topic/foo-bar, which is the defect being fixed, deterministic, and consistent with the note's own filename slug. Existing vault content is covered by the new opt-infrontmatter-tagshygiene detector (registered throughHYGIENE_DETECTOR_IDS/DETECTORS, default-off liketags), which flags and never auto-fixes. - Capture vocabulary fail-closed rule and escape hatch.
writeCaptureNoteandwriteIdeaNoteconsultdeclaredPageTypes(vault)(new predicate besideschema-pack.ts, null when no pack is active β "pack active" means the config is present and declarespage_types, since the merged vocabulary always containsnote). When active, a stampedkindnot in the declaration refuses with the module's typedCaptureContractErrorbeforeallocateAndCreate, so a refused capture never consumes a name; the error names the kind, the declared set, and the remedy (declare the kind inBrain/_brain.yaml). Absent or declaration-free config fails open β theABSENT_SCHEMA_CONFIG_TEXTsubstitution precedent, a named declarative policy rather than a silent fallback. The frontmatter key stayskind(judging the stamped kind againstpage_typeswithout retyping totype: note), becauseparseCaptureFilereadskindand a retype would make captures invisible to the drain. No companion detector: the typed refusal is the guidance, and a detector for packs omitting build-stamped kinds is an open question, not committed scope. - Digest-seal format for content plans.
sealManifest/manifestVerifieslift intosrc/core/integrity/digest.tsassealWithDigest(body)/digestVerifies(body, digest)oversha256Hex(canonicalJson(body));migrate.tskeeps thin aliases so its behavior is untouched. Sealed bodies exclude wall-clock fields (the injected-nowrationale frommigrate.ts). Claude-memory import: the dry-run result carries the plan digest;--applyaccepts--approval-digest, recomputes the plan, seals, and compares before the snapshot/write loop, refusing drift with there-run --dry-runremedy. Brain upgrade:UpgradePlangains adigestsealed insideplanUpgradeand verified at the top ofapplyUpgrade, closing the caller-supplied-plan seam (the self-heal worker computes its own plan, which trivially verifies). The interactive TTY prompt remains the human escape hatch for apply-without-digest; scripts must carry the digest. - Divergence report response shape: extend existing envelopes, additive fields only. A divergence-aware core read returns the sorted-latest digest plus
digest_count, and, only when the count exceeds one,divergent: trueplus a bounded id/created_at/content_hashlist β id/hash lists rather than full payload echoes, becauseMCP_PREVIEW_BUDGETapplies to the serialized content. The MCPgetresult and the CLI get--jsonobject gain the same keys via the conditional-key idiom;{ found: false }is untouched; the tool declares nooutputSchema, so added keys cannot trip an envelope contract. The CLI serializer's missingproject(verified drift) is folded into the same change. - Think-block strip as a named step in the result envelope.
src/core/brain/payload-json.tsexports a strip-and-note parser: tryJSON.parseas-is; on failure, strip one leading<think>...</think>block (fenced-block unwrap following thellm-emulation.tsprecedent), retry, and return the payload plus the strip fact (kind,prefixChars) or a named unparseable error. The four model-answer verbs (extract-signals,design-note,skill-proposals,distill) route through it; the strip fact rides thenotekey of the existing{ ok: true }envelope only when a strip happened, and a still-invalid payload keeps today's named exit-1 refusal, with the message naming the strip attempt. Clean JSON produces byte-identical output. The strip never rescues genuinely malformed JSON into a silent pass β it is named or it does not happen. - Extraction contract fingerprint: fields and changed-contract behavior. The manifest gains one manifest-wide field,
contract: { fingerprint: string }β one short hex string total, not per-entry. The fingerprint issha256Hex(canonicalJson({ version: EXTRACT_CONTRACT_VERSION, extractable: [...sorted] })).slice(0, 16)computed in a new small module beside the manifest, over the vault's schemaextractableallowlist plus a hand-bumpedEXTRACT_CONTRACT_VERSIONconstant (theCHUNKER_VERSIONbump-guard convention) covering code-scoped extraction behavior; per-call options (pre_extract,extensions,exclude, caps) stay out, matching the session lane's scope-vs-options split.SCHEMA_VERSIONbumps to 2 with aSUPPORTED_SCHEMA_VERSIONS-style read: a v1 manifest is a known previous version whose contract is treated as changed β every source reprocesses once, then the rewrite lands as v2; genuinely unknown versions still hard-refuse.planBatchescompares fingerprints immediately afterreadManifest; on mismatch,unchangedsources reprocess with a distinct typed reason token so reporting distinguishes "bytes changed" from "contract changed". The fingerprint folds intocomputePlanId(thecomputeSessionImportIdpattern) so a stale checkpoint cannot resume-skip work extracted under the old contract; old checkpoint files orphan harmlessly.source-cleanup's direct manifest write round-trips the field.
File changes
By lane (exact ownership and per-task file lists are pinned in plan.md; lanes never touch another lane's files):
- Lane A (secrets envelope, t_e6667a56 + t_592d9e91): new
src/core/brain/secrets/envelope.ts,src/core/brain/secrets/bundle.ts; modifiedsrc/core/brain/secrets/crypto.ts,src/core/brain/secrets/store.ts,src/cli/brain/verbs/secret.ts,src/cli/command-manifest.ts,src/cli/help-text.ts,src/core/egress/registry.ts(the bundle destination β the wave's only new egress site), and the secrets/CLI/architecture test files listed in the plan. - Lane B (resolver plane, t_e5807974): new
src/core/secret-resolver.ts; modifiedsrc/core/secret-ref.ts,src/core/search/embeddings/registry.ts,src/core/decision-model/config.ts,src/core/brain/research/research.ts,src/core/config.ts,src/cli/main.ts,src/core/egress/guard.ts,src/mcp/error-redaction.ts, and their test files. - Lane C (vault validation, t_11ee559f + t_151a564c): new
src/core/brain/tag-syntax.ts,src/core/brain/hygiene/detectors/frontmatter-tags.ts; modifiedsrc/core/tags.ts,src/core/brain/signal.ts,src/core/brain/preference.ts,src/core/brain/claude-memory-render.ts,src/core/brain/schema-pack.ts,src/core/brain/capture/capture-note.ts,src/core/brain/capture/inbox-drain.ts,src/core/brain/hygiene/types.ts,src/core/brain/hygiene/scan.ts, and their test files. - Lane D (sealed content plans, t_18fda844): modified
src/core/integrity/digest.ts,src/core/state/migrate.ts,src/core/brain/import-claude-memory.ts,src/core/brain/upgrade.ts,src/cli/brain/verbs/import-claude-memory.ts,src/cli/brain/helpers.ts, and their test files. - Lane E (sessions honesty, t_59d4c919 + t_dac8bf7e): new
src/core/brain/payload-json.ts; modifiedsrc/core/brain/session-summary.ts,src/mcp/brain/synthesis-tools.ts,src/cli/brain/verbs/session-summary.ts,src/cli/brain/verbs/extract-signals.ts,src/cli/brain/verbs/design-note.ts,src/cli/brain/verbs/skill-proposals.ts,src/cli/brain/verbs/distill.ts, and their test files. - Lane F (ingest contract, t_586d5d8b): new
src/core/brain/ingest/contract.ts; modifiedsrc/core/brain/ingest/content-manifest.ts,src/core/brain/ingest/batch-plan.ts,src/core/brain/ingest/checkpoint.ts,src/core/brain/source-cleanup.ts,src/mcp/brain/ingest-tools.ts,src/cli/brain/verbs/batch-plan.ts, and their test files.
Risks and open questions
- Passphrase loss is unrecoverable. A forgotten passphrase makes every stored secret permanently unreadable. The verb help and the module header must state this in plain terms; there is no recovery path and none is pretended.
- Multi-process unlock friction. Every CLI invocation and the MCP server unlock separately; an agent-driven workflow hitting a locked store gets a named error and must stop, which is the point. The MCP server holding a derived key for its lifetime would weaken memory-only semantics β resolved by refusing unlock over MCP.
- Bundle egress honesty. The export payload is ciphertext by construction, which defeats both the
sharedRedactorandnoVaultContentstatuses as-is. The working choice is to runredactForEgressover the envelope's non-ciphertext metadata tree and declaresharedRedactor; the exact status wording is a deliberate decision at implementation time (Lane A2), pinned as such in the plan. - Topic tag values change for spaced topics (
brain/topic/foo barbecomesbrain/topic/foo-bar). Deterministic and consistent with the filename slug, but it is a visible byte change on affected writes; the tag-syntax test suite pins the before/after shapes. - Capture rejections in packs authored before
brain-captureexisted. Mitigated by the fail-open-unless-declared rule; a vault only breaks captures by explicitly declaringpage_typeswithout the kinds the build stamps, and the refusal names the remedy. - Approval-digest UX. An operator who applies without dry-running has no digest; interactive TTY apply stays the human escape hatch while non-interactive apply requires the digest, matching the existing
--yesguard asymmetry. - Resolver hot paths. The read-only resolve still reads under the secrets lock; whether config-resolution frequency (embeddings expand runs per index/query) needs lock-free caching is deferred to B1's tests β correctness first, caching only if measured.
- Open:
src/core/graph/mcp-config.tsresolver routing β deferred to keep MCP-surface changes at zero in this wave; revisit once the resolver has production consumers. - Open: v1-ingest-manifest one-time full reprocess lands on every upgraded vault on first plan; acceptable (documented degradation, no error), but worth a CHANGELOG note so operators are not surprised by the first run's cost.
- Open: a hygiene/doctor finding for packs whose declared
page_typesomit build-stamped kinds β useful, but not committed scope in this wave; the typed refusal already names the remedy.