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
26.0 KB
Raw Blame

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/unlock ops, 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/writeIdeaNote refuse an undeclared kind when the vault's pack explicitly declares page_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/divergent fields 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.ts and 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 contract field, 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_link verb 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 model crypto.ts:13-17 already scopes.
  • MCP-surface changes beyond named response extensions. brain_secrets stays list|run (no lock/unlock/export/import over MCP, per the admin-tools.ts:295-299 no-set/get refusal precedent); the divergence fields on brain_session_summary get are additive keys on an existing tool, nothing more; routing src/core/graph/mcp-config.ts env 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. loadOrCreateKey at src/core/brain/secrets/crypto.ts:86-142 with KEY_BYTES = 32 at :36, exclusive-create first-writer handling, per-value encryptValue/decryptValue AES-256-GCM at :144-164; op switch set|list|rm|run at src/cli/brain/verbs/secret.ts:45-48; brain_secrets MCP restriction docblock at src/mcp/brain/admin-tools.ts:294-299.
  • t_e5807974 (resolver plane) β€” confirmed. src/core/secret-ref.ts is 86 lines with parseSecretReference :27-32, resolveSecretReference :34-47, redactKnownSecretValues :67-86; EGRESS_REDACTION_OPTIONS at src/core/egress/guard.ts:140-143, redactForEgress at :181, redactConfigMapping at :241-245; EGRESS_SITES at src/core/egress/registry.ts:108-343; o2b secrets dispatch at src/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 declared out/outdir/dest parameters, 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_RE at src/core/tags.ts:29 with the docblock explicitly reserving itself as this card's seam ("validate against the rule defined HERE, never against a copy"); OBSIDIAN_TAG_RE at src/core/brain/hygiene/detectors/tags.ts:62; schema-vocab TOKEN_RE at src/core/brain/schema-vocab.ts:38 (rejects /, must not be reused); composers verified at src/core/brain/signal.ts:797-822 and src/core/brain/preference.ts:808-825 (raw trimmed topic into brain/topic/); hand-rendered import frontmatter at src/core/brain/claude-memory-render.ts:80. Correction: recon-validation cites the signal tag-assertion tests at tests/core/brain/signal.test.ts; the file is actually tests/core/brain.signal.test.ts (dot-named convention, as recon-sessions spells tests/core/brain.session-summary.test.ts correctly).
  • t_59d4c919 (divergent summaries) β€” confirmed. getSessionSummary returns records[records.length - 1] unannounced at src/core/brain/session-summary.ts:173-180; sort by (createdAt, id) at :215-221; content-hash dedupe key at :139-150; MCP get at src/mcp/brain/synthesis-tools.ts:125-129; CLI get at src/cli/brain/verbs/session-summary.ts:80-103. The serializer drift is real: the MCP serializer includes project (synthesis-tools.ts:84), the CLI serializer omits it (session-summary.ts:136-147).
  • t_151a564c (capture vocabulary) β€” confirmed. BRAIN_CAPTURE_KIND at src/core/brain/capture/capture-note.ts:52, writeCaptureNote at :208, allocateAndCreate at :230, parseCaptureFile kind check at :287; CAPTURED_IDEA_KIND at src/core/brain/capture/inbox-drain.ts:61; absent-config substitution ABSENT_SCHEMA_CONFIG_TEXT at src/core/brain/schema-pack.ts:56 with readSchemaPackSource at :78-83; write-session polarity verified at src/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/manifestVerifies at src/core/state/migrate.ts:186-194; sha256Hex/canonicalJson in src/core/integrity/digest.ts (:43-45, :61-73); planUpgrade at src/core/brain/upgrade.ts:116-134 returns an unsealed frozen plan; byte-drift refusal at :182-193 names re-run --dry-run but nothing seals a caller-supplied plan object.
  • t_dac8bf7e (think-block strip) β€” confirmed. Bare JSON.parse with the refusal payload must be valid JSON verified at src/cli/brain/verbs/extract-signals.ts:129-140 and src/cli/brain/verbs/design-note.ts:105-113.
  • t_586d5d8b (extraction-contract fingerprint) β€” confirmed. SCHEMA_VERSION = 1 at src/core/brain/ingest/content-manifest.ts:41, ContentManifest at :53-58; manifest consultation at src/core/brain/ingest/batch-plan.ts:354-356; computePlanId at src/core/brain/ingest/checkpoint.ts:80-91 folds 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. scryptSync with explicit N = 2^15, r = 8, p = 1, 32-byte output, a random 16-byte salt per envelope, and maxmem set explicitly; parameters are recorded inside the versioned envelope so they can migrate without breaking old stores, and an unknown algo or version refuses with a named error (the readStore bad-version precedent). Wrong-passphrase detection is free and fail-closed: the GCM auth tag over the wrapped DEK throws. timingSafeEqual guards any comparison. This matches the pinning posture (one runtime dependency) and the documented threat model (crypto.ts:13-17 disclaims 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/keyfile is replaced by a schema-versioned JSON envelope { version, kdf: { algo: "scrypt", salt, n, r, p, maxmem }, wrapped: <EncryptedValue> } where wrapped is the encryptValue output 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 (loadOrCreateKey detects 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 the set op's ingestion pattern). The derived key lives only in a module-level unlock holder inside envelope.ts; unlock populates it after a verified unwrap, lock clears 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 gains secret_locked/secret_unlocked records 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 composes parseSecretReference with a read-oriented decrypt over the custody store β€” a new read-only resolve export in src/core/brain/secrets/store.ts (Lane A) that skips the last_used_at stamp and the exec audit, because resolveSecretForExec is 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 in src/core/config.ts, and o2b secrets status/list availability. 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 gives redactKnownSecretValues production 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 in src/core/brain/tag-syntax.ts. At the composers: extraTags entries 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 what deriveSlug already 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 from brain/topic/foo bar to brain/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-in frontmatter-tags hygiene detector (registered through HYGIENE_DETECTOR_IDS/DETECTORS, default-off like tags), which flags and never auto-fixes.
  • Capture vocabulary fail-closed rule and escape hatch. writeCaptureNote and writeIdeaNote consult declaredPageTypes(vault) (new predicate beside schema-pack.ts, null when no pack is active β€” "pack active" means the config is present and declares page_types, since the merged vocabulary always contains note). When active, a stamped kind not in the declaration refuses with the module's typed CaptureContractError before allocateAndCreate, so a refused capture never consumes a name; the error names the kind, the declared set, and the remedy (declare the kind in Brain/_brain.yaml). Absent or declaration-free config fails open β€” the ABSENT_SCHEMA_CONFIG_TEXT substitution precedent, a named declarative policy rather than a silent fallback. The frontmatter key stays kind (judging the stamped kind against page_types without retyping to type: note), because parseCaptureFile reads kind and 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/manifestVerifies lift into src/core/integrity/digest.ts as sealWithDigest(body)/digestVerifies(body, digest) over sha256Hex(canonicalJson(body)); migrate.ts keeps thin aliases so its behavior is untouched. Sealed bodies exclude wall-clock fields (the injected-now rationale from migrate.ts). Claude-memory import: the dry-run result carries the plan digest; --apply accepts --approval-digest, recomputes the plan, seals, and compares before the snapshot/write loop, refusing drift with the re-run --dry-run remedy. Brain upgrade: UpgradePlan gains a digest sealed inside planUpgrade and verified at the top of applyUpgrade, 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: true plus a bounded id/created_at/content_hash list β€” id/hash lists rather than full payload echoes, because MCP_PREVIEW_BUDGET applies to the serialized content. The MCP get result and the CLI get --json object gain the same keys via the conditional-key idiom; { found: false } is untouched; the tool declares no outputSchema, so added keys cannot trip an envelope contract. The CLI serializer's missing project (verified drift) is folded into the same change.
  • Think-block strip as a named step in the result envelope. src/core/brain/payload-json.ts exports a strip-and-note parser: try JSON.parse as-is; on failure, strip one leading <think>...</think> block (fenced-block unwrap following the llm-emulation.ts precedent), 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 the note key 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 is sha256Hex(canonicalJson({ version: EXTRACT_CONTRACT_VERSION, extractable: [...sorted] })).slice(0, 16) computed in a new small module beside the manifest, over the vault's schema extractable allowlist plus a hand-bumped EXTRACT_CONTRACT_VERSION constant (the CHUNKER_VERSION bump-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_VERSION bumps to 2 with a SUPPORTED_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. planBatches compares fingerprints immediately after readManifest; on mismatch, unchanged sources reprocess with a distinct typed reason token so reporting distinguishes "bytes changed" from "contract changed". The fingerprint folds into computePlanId (the computeSessionImportId pattern) 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; modified src/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; modified src/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; modified src/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; modified src/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; modified src/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 sharedRedactor and noVaultContent statuses as-is. The working choice is to run redactForEgress over the envelope's non-ciphertext metadata tree and declare sharedRedactor; 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 bar becomes brain/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-capture existed. Mitigated by the fail-open-unless-declared rule; a vault only breaks captures by explicitly declaring page_types without 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 --yes guard 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.ts resolver 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_types omit build-stamped kinds β€” useful, but not committed scope in this wave; the typed refusal already names the remedy.