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.
Write-side trust: identity, permission, review - named agent tokens, one permissions document with an approval door and a decision ledger, staged review for every writer, an owner-write gate, open decisions, opt-in ambient capture
Status: draft Author: design orchestrator (feature-release-playbook, phases 0-1) Audience: implementation
Problem statement
An operator who lets agents write into an Open Second Brain vault today cannot say, for any given write, who made it, what rule allowed it, or how to stop the next one. The gaps stack in order. Identity: the HTTP transport compares one shared bearer key (src/mcp/http.ts:367-371), and the only "who is calling" behind the endpoint is the process's configured agent name (src/mcp/server.ts:249-251 resolves resolveAgentName per access) - two agents behind one endpoint are indistinguishable, and the code says so itself (src/mcp/http.ts:355-361, "identity and scope are process-global"). Authorization: trust checks are scattered point checks with no shared policy - one enforced role check (apply-evidence.ts:197), a force_confirmed argument that writes a confirmed preference past both the role matrix and the dream trial window (src/mcp/brain/feedback-tools.ts:268-306), and per-feature toggles living in three different config homes. Review: the staged-review gate covers exactly two extraction callers (extract-signals.ts:602-603, fact-extract.ts:350-362); every MCP writer tool and every bulk-ingest lane publishes straight to its final lane, and - a correction this design treats as load-bearing - a staged document is not out of recall today, because the search index admits every in-scope .md including Brain/pending/ (src/core/vault-scope/index-admission.ts:39-52 has no pending exclusion). Accountability: five partial trails exist (Brain log, pref-audit, idempotency ledger, trigger ledger, ephemeral retrieval receipts) but no queryable record of which rule allowed, asked, or denied which operation. Judgment: a decision can only be recorded after it is made (recordDecision requires chosen, record.ts:400-401); there is no artifact that parks an open question with enumerated options. Ambient capture: the extraction lane writes whenever a session classifies as capture, with no operator consent handle and no TTL.
Scope
Seven cards, one spine, one PR on feat/write-side-trust:
- Identity (t_85059d6d) - named per-agent MCP auth tokens: an operator-minted token per agent, caller identity resolved from the credential at the transport, threaded per request into the server. Identity comes from the credential, never from a caller-supplied argument. The shared
--api-keystays valid as the operator master credential. - Authorization (t_29798f41) - one permissions document (
Brain/_permissions.yaml, allow/ask/deny, operator-defined roles, per-agent entries, target-scoped exceptions), resolved at one chokepoint every gate consumes, plus a queryable decision ledger (Brain/logs/decisions/, JSONL shards) that records ask/deny verdicts with the rule that produced them. Document absent: every check behaves exactly as today. - Review (t_6ff73d61) - the staged-review gate extends from the two extract callers to all writer tools and bulk ingest: signals at the
writeSignalchokepoint, note creates and the ingest summary page into a multi-lane pending queue, recall closed behind the gate by an index-admission exclusion. Unreviewed agent-generated documents stay inBrain/pending/until an operator applies or rejects them. - Owner writes (t_107cac80) - an opt-in
integrity.owner_scope_writesgate (off/warn/fail) that refuses a caller-named owner different from the resolved identity on the preference and note lanes, with warn rows landing in the decision ledger. - Bootstrap (t_89e1f601) -
o2b bootstrap --target <harness>: one idempotent command that provisions a named token, MCP registration through the existing adapter apply, and a receipt, with rotation that takes effect on the next request. - Open decisions (t_8913c934) - a durable open-decision artifact at
Brain/decisions/open-<slug>.mdwith enumerated options, modeled on the trigger store lifecycle, resolved into a realtype: decisionpage. - Ambient capture (t_af5e252f, reshaped) - operator consent and TTL for the existing ambient extraction lane (
guardrails.ambient_writeback,guardrails.ambient_ttl_days), riding the staged-review gate. The managed-instruction-block installer and the Stop-hook backstop are deferred with a recorded verdict (see Out of scope).
Out of scope
- Stop-hook backstop (deferred from t_af5e252f). Session capture already runs on Stop (
hooks/hooks.json:112-121) and banks the turn's durable artifacts; the recon could not name a state a new deterministic backstop would bank that per-prompt capture misses, and the runtimes where a Stop nudge is visible are the ones wheredecision: "block"buys a forced continuation turn, whichhooks/README.md:33forbids for opt-in hooks. Revisit only with a named delta over session-capture-on-Stop. - Managed-instruction-block installer (deferred from t_af5e252f).
writeback-contract.ts:29-33states "NO INSTALLER LIVES HERE" deliberately; the natural home is bootstrap provisioning after token identity has shipped and operated for a cycle. The check-only contract already audits the files; writing them is the deferred half. - Staging the remaining generator lanes (design notes, decisions, research reports, distillations, derived facts, session summaries, lifecycle moves). The multi-lane pending store is built so a generator lane is one registry row plus one call at its write site; wave 1 stages the three lanes the card names (signals, notes, ingest summary) and the registry is the documented extension point.
- An MCP surface for the pending queue. The human approval door stays CLI-only (
o2b brain pending list|apply|reject), matching today's shape; agents see staged receipts with apending_idand the next command. - Subsuming the read-side gates (owner-scope delivery, visibility, reach, retrieval trust) into the document. They keep their modules and modes; the document composes most-restrictive-wins with them. Mechanical cutover is a later wave, per the migration order in
docs/brainstorm/who-wrote-what/design.md. - Per-call consent records. Nothing in the tree models one; the closest shape (v1.78's digest-sealed import approval) needs an MCP transport story callers cannot hold. Consent this wave is standing configuration.
- Scope metadata on tokens. A token mints identity only; policy lives in the permissions document. Token-borne tool profiles or reach ceilings would duplicate
mcp_tool_profileand the transport-reach rule ("a token must mint identity, never reach",src/mcp/http.ts:106-110). - stdio tokens. One caller per process that already owns the process tree; identity stays config-derived on stdio. Token authentication is an HTTP-transport feature.
- Chaining the decision ledger. The idempotency-ledger precedent (
src/core/brain/idempotency-ledger.ts) is unchained; tamper evidence exists where the repo chose to pay for it (the Brain log chain). Revisit only if the ledger becomes a security boundary rather than an accountability record. - Pre-approval policy writes into harness configs (Claude Code
permissions.allowentries, Codex approval tables).o2b brain protectowns that surface; bootstrap does not grow a second policy writer this wave.
Chosen approach
One spine, landed substrate-first: identity (tokens) feeds authorization (the permissions document and its resolver) which feeds the action gates (staged review per lane, the owner-write gate) which feed accountability (the decision ledger, open decisions), with ambient capture strictly behind all of it. The permissions document is the substrate: it is a vault file (Brain/_permissions.yaml) so it rides Syncthing like the freeze marker and the operator hand-edits it as trust state, with a strict loader modeled on the _brain.yaml block machinery (field-named errors, unknown-key warnings, a version key with a hard-refuse gate). Its resolver is a pure leaf module; every gate consults it through one disposition function, so "which rule decided this" has exactly one answer and the ledger can record it.
Default posture is byte-identity: no document, no tokens, no gate keys, no flags - every existing write path and every existing test stays green with zero config. A document present is a closed world (its default_action is a required, explicit key); deny wins ties; the document composes most-restrictive-wins with the built-in gates.
The lanes are ordered so the substrate lane commits pure modules first; the gate lanes build against the pinned signatures (tests first) and rebase when the substrate commit lands. No new MCP tool is added in this wave - every surface change is an action on an existing tool, a field on an existing receipt, or a CLI verb - so the tool-count pins do not move and the lanes stay mergeable. Refusals are never silent and never prose-only: typed errors and named refusal tokens (owner-write-refused, force-confirmed-requires-allow, the admission reason review-pending) join the existing closed vocabulary, each with a next command, recorded in the decision ledger by the gate that produced them (the ledger is a leaf module, so the guard can record without the cycle that forced frozen refusals to the dispatcher).
Design decisions
- Tokens are hash-at-rest, not custody ciphertext. The store keeps
sha256(token)beside a non-secret prefix for listings; verification hashes the presented credential and compares in constant time. A plaintext-equivalent token never exists after mint (the material is shown exactly once, on stdout, with a shown-once notice), so rotation and verification do not depend on the passphrase envelope - locking the custody store must not be an authentication outage, which rule (a) in the t_85059d6d recon (tokens as custody entries) cannot satisfy. The store file sits besidesecrets.jsonunder.open-second-brain/secrets/mcp-tokens.json(0600,icaclsowner ACL on Windows via the custodycustodyTargetsmachinery, writes underwithSecretsLock), and every mint, rotation and revocation appends a no-values custody audit record. Names use underscores (mcp_token_<slug>) so the$secret:NAMEreference grammar (no dashes,src/core/secret-ref.ts:33) can address them. - Identity threads as a parameter, never as instance state. One
MCPServerserves concurrent HTTP requests, so a request-scoped identity cannot live on the instance.handleRequest(request, identity?)threads throughhandleToolsCallandinvokeToolHandlerinto acontextFor(identity)build;agentNameresolves toidentity.agentwhen a credential matched, elseresolveAgentName(configPath)exactly as today. Authentication order atsrc/mcp/http.ts:306: token-map hash lookup first (identity = the token's agent,via: "token"), then the shared key (identity = the process config name,via: "shared-key"), else anonymous and byte-identical behavior. The generic 401 body is unchanged for missing and wrong credentials - no oracle distinguishes revoked from unknown. Underintegrity.owner_scope_delivery: faila token identity makes that gate per-caller real for the first time:refuseOwnerScopeRequestkeeps its code and gets a real per-request identity input. - Token-map presence keeps the shared key valid; enforcement is a separate explicit key. The shared key stays the operator master credential during and after migration. A new device key
mcp_tokens_required(default false, env twinOPEN_SECOND_BRAIN_MCP_TOKENS_REQUIRED) makes the endpoint refuse credential-less requests when a non-empty map exists; default-off keeps every existing posture (loopback keyless, non-loopback keyed) byte-identical. The non-loopback bind rule (startHttp,http.ts:99-104and the CLI pre-checkmain.ts:870-875) learns "key OR non-empty token map". The token store is read per request behind an mtime cache, so rotation and revocation take effect on the next request with no restart - the shared key keeps its launch-time capture, documented. - The permissions document is a vault file, not a
_brain.yamlblock. Trust policy is state the operator hand-edits and syncs to every device, exactly like the freeze marker;_brain.yamlis kernel config with its own strict machinery the document borrows by pattern only (policy/blocks, field-namedPermissionsDocumentError, unknown-key warn,version: 1hard-refuse on anything else). Absent file:{ document: null }and every consumer proceeds as today - the repo's absent-is-inert convention (integrity.ts:53-66,write-binding/index.ts:45-52). Present but unreadable: fail closed with a named error and a doctor finding, never a silent fallback to permissive - the same asymmetry asBRAIN_INTEGRITY_STRICT_FALLBACKand "an unreadable config is not consent to fold" (vault-path-field.ts:251). - Resolution order and composition. Within the document: a target-scoped entry beats the agent's per-action override, which beats the agent's role, which beats
default_action; among entries of equal specificity deny beats ask beats allow. Across systems, most-restrictive-wins: the document can narrow anything, but afailgate (owner_scope_delivery,owner_scope_writes) still refuses what the document would allow - the document may restore only what anoffmode permits. When a document exists it is the only disposition source (thewrite_approval.*lane keys apply only when no document exists), so one write has exactly one deciding rule and the ledger records it. - Roles in the document are principal bundles, not BrainRoles. The built-in
writer|dreamer|appliermatrix (trust/role.ts) stays a tool-side nomination matrix; document roles are operator-defined named bundles of per-action verdicts (reviewer,autonomous, ...). The one enforcement gap the recon proved -force_confirmedwriting a confirmed preference past the matrix - closes only under a document: when a document exists,force_confirmedrequires the caller'swriteverdict to beallow, else the named refusal. Document-absent behavior is unchanged and the hole is documented rather than silently patched. - The decision ledger records decisions, not writes. JSONL month/device shards under
Brain/logs/decisions/on the idempotency-ledger model (ledger-shards.tsgrammar, per-shardproper-lockfile, deterministic merge), one row per non-allow verdict plus resolution rows for applied/rejected staged documents; allow rows only under the document's explicitledger.record_allows. Row shape:ts, actor, via, action, target, verdict, source(entry id / role / default / gate key),reasontoken,tool,correlation_id. Absent document and off gates produce no rows - default-silent like every ledger. The existing trails (Brain log, pref-audit, idempotency) stay; the ledger joins them viacorrelation_idthe wayevent-trace.tsalready joins log events. - Staging is a change of directory, generalized per lane. The A3 invariant holds unchanged: the staged document is byte-for-byte what the publish target would receive, and apply moves it verbatim. Signals keep
Brain/pending/sig-*.mdexactly as today. Notes stage atBrain/pending/notes/<id>.mdwhere the id isnote-<date>-<encoded-target>and<encoded-target>is a reversible percent-encoding of the caller-named vault-relative target without its final.md(Windows-legal characters only, round-trip tested against CJK, spaces and dots; a target that encodes past the 255-character filename bound refuses at stage time by name). The ingest summary page stages atBrain/pending/ingest/<id>.mdwith the deterministic publish basename - the publish path is deterministic from the source identity (ingest.ts:219-223), so the basename suffices. Apply is the existing exclusive-create-then-unlink withPendingApplyConflictErroron an occupied target; reject renders intoBrain/retired/with the retire-shaped frontmatter, adding aosb_pending_lanestamp at reject time only (reject transforms, publish never does). Every generalized move-then-unlink gets aDESTRUCTIVE_SITESdeclaration. - The note-lane review boundary is entry, not mutation. Creates stage; updates and appends to already-published notes stay direct. The thing under review is a document no operator has admitted yet; once admitted, editing it is the ordinary write path with its own record. In the batch kernel this is per-operation: create ops stage and report receipt status
stagedwith the pending id, update/append ops proceed - the validate-all-then-commit kernel is untouched because a staged create never touches the real path.brain_feedbackand every otherwriteSignalcaller inherits the gate at the chokepoint (see next decision), so the signals lane needs no per-tool wiring. - The gate resolves inside
writeSignal, below the pending module. WhentargetDiris absent and the signals lane gate resolves on,writeSignalstages intoBrain/pending/and reportsstaged: trueon its result;stagePendingSignalkeeps passing an explicittargetDirand can never re-enter the gate. The toggle resolution lives in a new leaf modulesrc/core/brain/write-gate.ts(signal.ts cannot import pending.ts - pending imports signal). The two extract callers keep their current injected resolution and are behavior-identical; the six ungatedwriteSignalcall sites (MCP and CLI feedback, inline scan, session import, session lifecycle, session checkpoint) gain the gate with no code change of their own. - Per-lane toggles under one master.
write_approval.notesandwrite_approval.ingest(flat device keys with env twins, matchingwrite_approval.enabled's resolver) default to the master key when absent, so the existing key keeps its meaning ("stage everything") and an operator can gate bulk ingest without gating interactive feedback. Resolution order: lane key, then master, then off. - The owner-write gate is a third behaviour family on a sibling integrity key, not a mode on
owner_scope_delivery.integrity.owner_scope_writes: off|warn|fail(closedGATE_MODEunion, default off, strict fallback fail on unreadable config) keeps read isolation and write trust separable - theirwarnsemantics already differ (stamp-and-allow vs allow-and-log). The check is a pure predicate insrc/core/brain/trust/owner-write-gate.ts: refuse when a caller-named owner differs from the resolved identity, on the preference lane atresolvedOwnerFor's explicit-owner arm (preference.ts:545-546) and on the note lane whereownerjoins the reserved frontmatter keys underfail(write-batch.ts:699-704). Warn allows and logs a ledger row. Global-scope writes need no new gate: the recon refuted the wildcard surface (no wildcard token exists;agent_scope: "*"narrows rather than widens,agent-scope.ts:130-147) and the one genuinely global write, theshared_namespacemirror, is already operator opt-in (config.ts:462-470). - Open decisions follow the trigger store, not the pending queue. One Markdown record per question at
Brain/decisions/open-<slug>.md(thedecision-prefix filter already coexists with design notes in that directory), a frozen key table, JSON-quoted free text, a body of## Question/## Options/## Contextsections, named-unreadable partitioned reads, and a directory lock around transitions. Statuses areopen | resolved | discardedwith no read-time expiry: a parked judgment question is exactly the thing that must not silently expire. Resolution takes the chosen option, mints the realtype: decisionpage throughrecordDecision, stamps the open recordresolvedwith a[[decision-<slug>]]pointer that stays in place (history is a status filter), and appends oneopen_resolvedreceipt to the existing decision-change trail. Creating an open decision is exempt from the write gate by design: accountability lanes stay writable when content lanes are gated, the same principle that keeps the audit lane appending under freeze. - Ambient capture gets a consent handle and a TTL, not a new lane.
guardrails.ambient_writeback: false, when explicitly set, suppresses the ambient extraction lane with a counted, loggedambient-withheldevent - absent keeps today's behavior byte-identically (the lane already writes on capture, so a default-off flag would be default-changing, not default-preserving).guardrails.ambient_ttl_days, when set, stampsexpiration_dateat creation on ambient-extracted signals through the validated chokepoint (feedback-tools.ts:152-162precedent); absent stamps nothing. Both keys live in theguardrailsblock besidemarker_writeback, the direct precedent for a memory-mutating lane. Suppressed-by-consent capture still flows through the capture boundary first, and the staging gate still applies to what is written. - Bootstrap composes existing install machinery; it does not duplicate it.
o2b bootstrap --target <harness>runs the adapter's existing idempotentapply(MCP registration, and hooks for the one adapter that writes them), mints and prints the harness token once when--tokenis passed (never on argv, never in a harness config - the payload env block stays credential-free perpayload.ts:119-124), and writes a receipt at<vault>/.open-second-brain/bootstrap.lock.json(schema 1, owned entries, token name and non-secret prefix,applied_at) modeled onprotect.lock.jsonand the install manifest. Re-apply is a byte-identical no-op;--rotatere-mints under the same name (replaced: trueaudit row) and reprints once;--checkverifies drift fromInstallEnvalone. Wave-1 targets: the config-writing adapters (codex, grok, opencode),genericprint-and-paste, and verify-only for plugin runtimes - Claude Code and ZCode are deliberately not adapter targets (host-facts.ts:170-173,install/zcode.md:3-4). - File ownership keeps the lanes disjoint; a small set of shared-append files absorbs registration. New modules are self-contained (path helpers live in their owning modules - the secrets-store precedent - so
paths.tsgains no rows). The dispatcher switches, verb barrels, help text, command manifest and CLI reference are declared shared-append: each lane appends only its own entries, and the reconciliation task owns the count pins. No new MCP tool means no tool-count pin moves at all.
File changes
New core: src/core/brain/permissions/document.ts (loader, schema, PermissionsDocumentError), src/core/brain/permissions/resolve.ts (resolvePermission, subject/decision types), src/core/brain/permissions/ledger.ts (appendDecisionLedger, queryDecisionLedger, shard handling), src/core/brain/write-gate.ts (lane toggle resolver, leaf module), src/core/brain/pending/pending-lanes.ts (lane registry, staging primitives, encode/decode, generalized list/apply/reject), src/core/brain/trust/owner-write-gate.ts (refuseCrossOwnerWrite predicate), src/core/brain/secrets/token-store.ts (mint/rotate/revoke/list/resolve, hash-at-rest), src/core/brain/decisions/open-store.ts (open-decision records, transitions), src/core/brain/decisions/brief.ts (brief section renderer), src/cli/bootstrap/ (command module, receipt).
Extended core: src/core/brain/signal.ts (gate resolution in writeSignal, staged on the result), src/core/brain/pending.ts (delegate to the lanes module for listing and resolution), src/core/vault-scope/index-admission.ts (Brain/pending exclusion), src/core/brain/notes/create-note.ts (staging seam, owner-frontmatter guard call site), src/core/brain/write-batch.ts (create-op staging, reserved owner key under the gate), src/core/brain/ingest/ingest.ts + source-cleanup.ts (summary-page staging, staged cleanup), src/core/brain/preference.ts (explicit-owner gate arm), src/core/brain/policy/blocks/integrity.ts + guardrails.ts (new keys, resolvers, defaults), src/core/brain/fact-extract.ts (ambient consent + TTL), src/core/brain/types.ts (open-decision log kinds), src/core/brain/decisions/receipts.ts (open_resolved reason), src/core/brain/destructive-sites.ts (generalized queue entries), src/core/state/surfaces.ts (decisions ledger row), MCP: src/mcp/http.ts (authenticateRequest, token map, bind rule), src/mcp/server.ts (identity parameter threading), src/mcp/brain/notes-tools.ts, write-batch-tools.ts, feedback-tools.ts, ingest-tools.ts (staged receipt fields, force_confirmed check), src/mcp/brain/decisions-tools.ts (open/list_open/show_open/resolve/discard actions), src/mcp/brain/brief-tools.ts (open-decisions section); CLI: o2b brain pending widening (src/cli/brain/verbs/pending.ts), o2b brain decision actions (decision.ts), new o2b brain permissions verb, new o2b bootstrap + o2b mcp token arms in src/cli/main.ts; doctor: unreadable-permissions finding; morning brief: open-decisions section.
Tests: tests/core/brain/permissions/{document,resolve,ledger}.test.ts, tests/core/brain/write-gate.test.ts, tests/core/brain/pending-lanes.test.ts (+ existing pending suites stay green), tests/core/brain/trust/owner-write-gate.test.ts, tests/core/brain/secrets/token-store.test.ts, tests/core/brain/decisions/open-store.test.ts, tests/core/brain/fact-extract.ambient.test.ts, tests/core/search/index-admission.test.ts extension, tests/mcp/http-token-auth.test.ts, tests/cli/{brain-permissions,bootstrap,brain-pending-lanes}.test.ts, plus the extensions the plan names per task.
Docs: docs/cli-reference.md, docs/mcp.md, docs/observability.md (ledger), README control section, CHANGELOG [1.79.0].
Risks and open questions
- Identity threading touches the hottest dispatch path. Parameter threading through
handleRequestis mechanical but wide (tools/call, resources,brain_context's no-argument contract). The agent-scope matrix and one-reader censuses (tests/mcp/owner-scope-refusal.test.ts:299-309,agent-scope-matrix.test.ts:237) must pass unmodified except for new identity-positive cases; any census that must change is a design error and stops the lane. default_action: denyis a foot-gun. The validator requires it explicitly (no silent default),o2b brain permissions showprints the effective decisions for a dry-run set of subjects, and the doctor emits a finding when a document denies the locally configured agent. An operator who writes a one-agent document denies everything else by construction; the show output makes that visible before the first refusal does.- Encoded pending filenames inherit filesystem bounds. The 255-character filename bound and Windows reserved names are handled at stage time with named refusals; the round-trip suite covers CJK, spaces, dots, and the percent-encoding of separators. A target that cannot stage refuses the write by name rather than truncating into a collision.
- Two staging sources could disagree. They cannot: the document, when present, is the only disposition source; the
write_approval.*keys apply only when it is absent. One write, one deciding rule, one ledger row. - Pin reconciliation across parallel lanes. The shared-append files (dispatcher, barrels, help text, manifest, CLI reference) and the census counts (verdict vocabulary, state surfaces, destructive sites) are append-only per lane and reconciled by measurement in the final task, per the standing note from the who-wrote-what wave.
- Open question - ledger retention. Month/device shards grow without bound like every ledger in the vault; no prune verb ships this wave. If the ledger becomes operator-visible noise, retention follows the write-image prune precedent in a later wave.
- Open question - bootstrap token delivery for non-print hosts. The token is printed once for the operator to place (env or
$secret:reference). A host that can take a file drop securely would prefer a written pointer; deferred until a host asks.