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

Session mining economy - one per-session mining record, a shadow claim-chain gate, a throttled backlog nudge and the live counts console

Status: draft Author: feature-release-playbook (host wave) Audience: implementation

Problem statement

Open Second Brain spends model effort on session mining without any memory of what mining already concluded: planExtractSignals (src/core/brain/extract-signals.ts:443) is a pure read with no cross-run record, so a session that was mined once and yielded nothing is rebuilt and re-offered to the caller's model on every re-scan, and nothing tells the operator how much imported session backlog was never mined at all. On the recall side, a page-level eligibility gate ships (trustGateAdjuster, src/core/brain/trust/retrieval-gate.ts:97) but has no measure-only middle mode and no per-edge eligibility inside the relational arm, so enforcement cannot be observed before it is turned on. On the operator surface, the recall-telemetry and operator-snapshot data exist with no viewer, because the only local console is the loopback explorer and it serves the rule graph only. This wave ships the four rescoped cards together: a durable per-session mining record with a zero-yield tombstone, a throttled SessionStart undistilled count with ask-once batching, a shadow/enforce claim-chain eligibility gate reusing the shipped trust gate, and live-counts plus ops routes folded into the existing explorer.

Scope

Card t_93617709 (durable zero-yield ledger), recon verdict premise_confirmed:

  • A new shared per-session mining record module, src/core/brain/session-mining-ledger.ts, stored beside session-import-ledger.json in the derived store. Entry: schema version, portable sessionId, mined-content hash (SHA-256 over the mined turn material the plan embeds: turn id, text, timestamp), outcome breakdown (written, staged, deduped, durabilityRejected), recorded_at. Read fail-closed on corrupt or unknown schema; write under acquireLockSyncWithRetry with the vault-identity assertion, atomic, byte-identical no-op short-circuit, pruned of sessions whose turns no longer exist (the discover.ts idioms).
  • Record-at-commit: commitExtractedSignals records the entry only on a successful commit with written.length === 0 && staged === 0, carrying the breakdown. Staging is never barren; a partial write (ExtractSignalsWriteError) never tombstones.
  • Gate-at-plan: the gate runs inside planExtractSignalsPrefiltered before the decision-model prefilter, so a tombstoned session spends no decision-model requests either. The suppression is a typed, named outcome beside the prefilter's skipped outcome, carrying the recorded breakdown as evidence; both the CLI verb and the MCP tool render it symmetrically. An unchanged session stays suppressed; a re-import that changes turns changes the hash and re-opens eligibility with no clearing step.
  • Operator escape hatch: an explicit force/re-mine flag on the CLI verb and a documented tool argument that bypass the gate for one plan call.
  • A named, non-throwing failure field on CommitExtractedSignalsResult (and both surface outputs) when the commit succeeded but the tombstone write failed.

Card t_0358af42 (session-start undistilled count), recon verdict partly_false_rescoped:

  • A distilled/undistilled census derived vault-side from the mining record joined to the import ledger on sessionRefIdentity (portable basename, src/core/brain/sessions/import.ts:315). No log re-hashing; sessions the plan refuses (boundary, zero imported turns, zero user turns) are excluded from the backlog because they can never be distilled.
  • The census surfaced in the import-session verb's coverage output per runtime (--status family, src/cli/brain/verbs/import-session.ts).
  • A default-off SessionStart hook (hooks/backlog-nudge.ts) copying the gap-agenda shape: flag via resolveConfigFlag with an env override, process ceiling, additionalContext count line, fail-open exit 0 with a byte-identical preamble when off, one hooks.json entry in the existing SessionStart block.
  • Throttle state that is vault-global, overwrite-only and change-keyed (the hygiene-digest-state shape, hooks/lib/backlog-nudge-state.ts): the count is injected when the undistilled count has changed since the last injection, never on a timer that re-nags an unchanged backlog; under the 10 s hook budget it degrades to silence, never to a fabricated number.
  • The ask-once batching layer as a pure core function (src/core/brain/distill/backlog-proposals.ts): takes the pending undistilled set plus a loadDedupIndex result, drops candidates whose computeDedupHash already exists in the vault (each drop named in a report), collapses the remainder to one proposal per distinct dedup hash across sessions, and emits a single batched envelope through a flag on the import-session verb for the calling agent to present.

Card t_05a0eaa4 (recall-time claim-chain eligibility gate), recon verdict partly_false_rescoped:

  • A tri-state mode off | shadow | enforce on the shipped retrieval trust gate, resolved as search_trust_gate_mode beside search_trust_gate_enabled in src/core/search/index.ts with the parseFusionMode refusal discipline; default off; enforce is today's exclude behavior made explicit; shadow reuses trustGateAdjuster's classification, excludes nothing, and records every would-be refusal with its structural reasons.
  • An edge-level eligibility adjuster inside runRelationalArm (src/core/search/pipeline/relational-arm.ts): per-node and per-edge classification from the same controlled-vocabulary frontmatter signals the page gate reads (epistemic status, contamination and untrusted-source markers, parseValidityWindow at query time, relation polarity), dropped from the arm's contribution under enforce and counted under shadow, with named structural reason tokens.
  • A named extraction-refusals record feeding the existing retrieval_decision_trace and memory_trust_assessment receipts (src/core/brain/trust/retrieval-receipts.ts): counts plus a reason histogram, reported separately for the pool and the arm, never folded into excluded. A record in the outcome, not a durable table.
  • The resolved mode rides the query-cache key (src/core/search/pipeline/cache-slot.ts) and the explain envelope (src/core/search/explain-envelope.ts).

Card t_15ebcfc1 (local memory console), recon verdict partly_false_rescoped:

  • A console collector module (src/core/brain/explorer-console.ts): summarizeRecallTelemetry passthrough, most-recalled top-N from deriveUsageSignals joined to artifact id/path under a named cap, a written-per-day histogram over a named 30-day window bucketed from continuity record createdAt, and the latest report-snapshot date per surface, fail-soft as "disabled" when snapshots are off. Frozen output, deterministic given opts.now.
  • Two new GET routes on buildLiveServer: /counts.json (the collector payload) and /status.json (buildOperatorSnapshot). Loopback-only, re-read-per-GET, no write endpoints; configPath threaded in through an additive options object on buildLiveServer.
  • Template sections for counts and ops in templates/brain-explorer.html, fetched client-side from the new routes; the __GRAPH_JSON__ single-marker invariant is untouched.

Out of scope

  • Any model or network involvement in the mining ledger; any config knob for the ledger itself; mtime-based invalidation; reuse of the import ledger's absolute-path keys or files; clearing or rewriting the import ledger; an expiry or TTL (the content hash is the invalidation); removal of the three existing plan refusals; extensions to fact-extract, dream or other lanes.
  • An interactive prompt loop in the kernel; any change to the write-time dedup gates (verified correct as shipped); a second machine-wide session sweep; a metrics endpoint for the undistilled count (the deferred honcho-PR residue; existing report surfaces first); undeclared-field mutation of session-import-ledger.json.
  • A per-claim grounding status column or any schema migration; a new durable extraction_refusals table; durable cross-install mode persistence; an LLM in the gate; re-entry into relational-fanout.ts traversal internals; enforce-by-default anywhere; a per-call override of the gate mode (config is the only surface this wave).
  • Non-loopback binds or --host widening; write endpoints, telemetry emission from the viewer, or captureReportDelta calls from a read surface; any caching layer, file watcher or Server-Sent Events; new visualization dependencies; a new on-disk schema served by the console; folding the today-dashboard envelope into the explorer; the v1.85.0 storage census and capacity tier on the ops route (deferred).

Chosen approach

Variant 1, seam extension, agreed with the consultant. Every card becomes a strict extension of a mechanism Open Second Brain already ships, which is exactly what the validator-settled rescopes name: reuse trustGateAdjuster rather than build a parallel gate, key the tombstone on content the same way the session import ledger already does, and fold the console into buildLiveServer instead of inventing a surface. Variant 2 is declined because deriving tombstone eligibility from accumulated receipts makes a barren session's eligibility depend on receipt retention policy, and a pruned receipt would silently re-admit a barren session; Variant 3 is declined because an append-only event journal with compaction and projections is a substrate Open Second Brain does not have, against a wave whose every existing store is a locked read-modify-write snapshot.

One mechanism correction to the variant as written: the consultant placed the mining outcome in a schema version bump of session-import-ledger.json. The design instead puts the shared mining record in its own derived-store file, because the import ledger's reader rebuilds entries field-by-field and silently erases undeclared fields on rewrite (src/core/brain/sessions/discover.ts readEntry), and the import ledger's keys are absolute machine paths while the mining lane holds only the portable sessionId with no join back. A separate record keyed on the portable identity inherits the same locked, atomic, fail-closed, pruned idiom without touching a shipped ledger's schema, and serves both mining cards from one home.

Design decisions

  • One shared per-session mining record serves both mining cards. The 2026-09-12 validator pairing directed the zero-yield tombstone (t_93617709) and the distilled/undistilled key (t_0358af42) onto one ledger home; the record's outcome breakdown answers both. Distilled means mined with accepted yield on the current content (written + staged > 0); a session whose items all deduped or all durability-rejected is known-nothing-new (tombstoned), which is a different state from undistilled backlog; never-mined sessions and sessions whose content changed since the last mining are the undistilled count.
  • The tombstone is keyed on a SHA-256 of the mined turn material itself (turn id, text, timestamp - exactly the envelope's inputs), not on the discover ledger's source-file byte hash. The import ledger hashes file bytes keyed by absolute machine paths; session_turn continuity records carry neither a source path nor a hash, and sessionRefIdentity shows the mining lane's key is the portable basename. Hashing the turn material yields the invalidation semantics for free: a re-import that changes turns changes the hash and re-opens eligibility with no explicit clearing step.
  • The plan gate lives inside planExtractSignalsPrefiltered, not inside planExtractSignals. Both surfaces already route through the wrapper, so one choke point covers the CLI and MCP lanes, the core plan contract gains no second non-throwing outcome class, and the gate runs before the prefilter so a tombstoned session spends no decision-model requests. The outcome type lives beside the prefilter's skipped outcome; the suppression reason widens into a typed union of literals (the prefilter reasons plus the tombstone reason) so there is one "no envelope, and why" channel, and MCP and CLI outputs stay symmetric. Every suppression carries the recorded breakdown as evidence; an empty plan that reads as a clean run is the failure the existing refusals were shaped to avoid.
  • Tombstone-write failure on an otherwise-successful commit surfaces as a named field on CommitExtractedSignalsResult and in both surface outputs, never a throw and never a silent drop. The signals are already on disk, so a throw would misreport a successful write as a failure, while swallowing would hide a ledger that is no longer trustworthy.
  • Plan-to-commit race semantics are accepted and documented rather than engineered around. The commit recomputes the mined-content hash from the turns present at commit time; an import landing between plan and commit can record a tombstone over content the model never saw, which is wrong only for the never-mined tail and self-heals on the next edit. The window is one caller turn wide.
  • The undistilled census is derived vault-side from the two ledgers joined on sessionRefIdentity, with no log re-hashing inside the hook path. Sessions the plan refuses are excluded because they can never be distilled; counting them would nag forever about unparsable material. The hook answers from this census; if the budget runs out it exits 0 silently.
  • The SessionStart nudge is default-off and change-keyed. The card's fixed-interval wording is superseded: an interval that re-nags an unchanged backlog repeats the nag the card exists to kill, so the throttle is once per unchanged backlog, held in a vault-global, overwrite-only, size-one state file beside hygiene-digest.hash (the shipped precedent for vault-wide state whose lifetime is not per-session). The hook follows gap-agenda: flag via resolveConfigFlag with an env override, process ceiling, fail-open exit 0, byte-identical preamble when off.
  • The ask-once batching layer is a pure core function; the kernel stays LLM-free and never runs an interactive loop. Dedup happens before the ask, not before the write: candidates whose computeDedupHash is already in the vault index are dropped from the ask and named in a report, the remainder is grouped under one proposal per distinct dedup hash across sessions, and the single batched envelope is emitted through the import-session verb for the calling agent to present.
  • The claim-chain gate's default is off, and measure-only (shadow) is the default mode whenever the gate is enabled without an explicit mode. Resolution order: explicit search_trust_gate_mode wins (invalid values refused naming the key, parseFusionMode precedent); absent the mode key, the legacy search_trust_gate_enabled boolean maps true to shadow and false to off; the default with neither set is off. Upstream's shadow-on-every-install is not copied - every recall knob in Open Second Brain defaults off with an explicit enable, and shadow is non-destructive precisely so enablement can be the first step. A vault that wants today's excluding behavior names enforce explicitly; the explain envelope names the resolved mode so the change is visible. There is no per-call override this wave. Amended after the v1.86.0 review: the legacy boolean maps true to enforce, so a vault that opted in before the mode existed keeps excluding across the upgrade, and shadow is reached only by naming it.
  • Shadow mechanics add no verdict kind to the kernel. applyRankAdjusters keeps its single-pass keep | multiply | exclude contract; under shadow the mode-aware gate reuses trustGateAdjuster's classification and returns keep for every item while the would-be refusals flow into the receipt build beside the existing flag-gated receipt path in post-rank. Only off is byte-identical: shadow adds receipt fields by design, so the query-cache key includes the resolved mode and the explain envelope reports it.
  • Edge eligibility is decided at the arm boundary, not inside the fan-out. Each walked node is classified from the same controlled-vocabulary frontmatter signals as the page gate; an edge passes when both endpoints pass, its validity window covers query time (parseValidityWindow, the closedSupersessionTip grammar) and its polarity is not a counted exclusion (the existing relation-polarity vocabulary, not upstream's claim-status integers). Eligibility refusals are reportable - removed from the contribution set and counted with named structural reason tokens - which is a different act from the relational arm's identical-to-absent provenance convention, and the design keeps the two conventions distinct.
  • Refusals surface as an extension of the two existing receipts, not a third receipt type and not a table. excluded keeps meaning actually dropped; shadow would-be counts and arm-level refusals are reported beside it, pool and arm reported separately so neither lane's numbers blur.
  • The console payload is delivered by client-side fetch, keeping the template's single substituted marker. The graph stays server-side injected through __GRAPH_JSON__ (the export mode's single-file property survives); the counts and ops sections fetch /counts.json and /status.json per render, which makes live refresh a re-fetch and a re-read. Two routes, of a piece with the explorer's existing two-route shape. The written-per-day window is a named 30-day constant, not a query parameter. Each /status.json GET re-runs the dry-run dream inside buildOperatorSnapshot - the most expensive read in the snapshot - and the design accepts that bounded, read-only cost rather than introducing a cache that would break the re-read-per-GET invariant and go stale silently.
  • Premise corrections recorded from the recons (the design follows the recon wherever a recon corrects a card):
    • t_93617709 premise confirmed, with a keying correction: the discover ledger's content hash runs over source-log file bytes keyed by absolute machine paths, and there is no join back to the mining lane, so the tombstone hashes the mined turn material itself. Anchors drifted: planExtractSignals :340 to :443; the refusal block :347-380 to :449-479; CommitExtractedSignalsResult :229-241 to :244-269.
    • t_0358af42 premise partly false: vault-wide cross-session dedup already ships (buildDedupIndex over inbox, processed and archived, applied in commitExtractedSignals before the durability gate), and the machine-wide session census already ships (discoverSessions plus the content-hash import ledger, built for cheap reruns). The residue is the distillation keying, the SessionStart surface and the ask-once layer. The hook premise is stale in detail too: SessionStart wires three hooks (active-inject, opt-in gap-agenda, session-capture), none an undistilled count. Anchors drifted: buildDedupIndex :55-70 to :98; commitExtractedSignals :433-455 to :578; the SessionStart block :27 to :43-67.
    • t_05a0eaa4 premise partly false: a recall-time eligibility gate already ships for pages (trustGateAdjuster mounted in post-rank, config-gated, receipted, byte-identical when off), so the missing work is exactly the measure-only middle mode, per-edge eligibility on the relational arm and the refusals record. The card's own anchors were wrong and stay wrong: store/state.ts:212 is a docblock region (the real schema-mismatch refusal is store/lifecycle.ts:229 and :243) and cli/search/verbs/check.ts:69 is an import line (the verdict mechanism is recordVerdict at :289). Upstream's shadow-on-every-install default is rejected.
    • t_15ebcfc1 premise false: buildLiveServer (src/core/brain/explorer.ts:354, the card said :355) is exactly the local console surface - loopback-only, read-only, re-reads the vault per GET - and the interactive-graph half the card called missing already ships over the rule graph. The residue is the live-counts half plus the ops route. The card also conflated two stores: report-snapshot writes per-day JSON under Brain/reports, while the Brain/metrics JSONL contract is the separate metrics.ts module; this design reads the report-snapshot dates only.

File changes

New files:

  • src/core/brain/session-mining-ledger.ts - the shared per-session mining record (read, record, gate, prune, lock, atomic write, mined-turn hash helper).
  • src/core/brain/sessions/mining-census.ts - the distilled/undistilled census over the mining record joined to the import ledger.
  • src/core/brain/distill/backlog-proposals.ts - the ask-once batching pure function.
  • hooks/backlog-nudge.ts - the default-off SessionStart count hook.
  • hooks/lib/backlog-nudge-state.ts - the vault-global, overwrite-only, change-keyed throttle state.
  • src/core/brain/explorer-console.ts - the console collector (telemetry summary, most-recalled top-N, per-day histogram, report-snapshot dates).
  • tests/core/brain/session-mining-ledger.test.ts, tests/core/brain/sessions/mining-census.test.ts, tests/core/brain/distill/backlog-proposals.test.ts, tests/hooks/backlog-nudge.test.ts, tests/core/brain/explorer-console.test.ts.

Modified files:

  • src/core/brain/extract-signals.ts - record-at-commit on the tombstone trigger; the ledger-failure field on CommitExtractedSignalsResult; the mined-turn hash call.
  • src/core/brain/extract-signals-prefilter.ts - the plan gate ordered before the prefilter; the widened typed suppression outcome.
  • src/mcp/brain/extract-tools.ts - suppressed-plan response fields, tool description, force argument.
  • src/cli/brain/verbs/extract-signals.ts - suppressed-plan output, ledger-failure line, force flag.
  • src/core/config.ts - the backlog nudge flag resolver beside resolveGapLoopEnabled.
  • hooks/hooks.json - one SessionStart entry.
  • src/cli/brain/verbs/import-session.ts - distilled/undistilled per runtime in the coverage output; the propose-backlog flag emitting the batched envelope.
  • src/core/brain/trust/retrieval-gate.ts - the mode-aware gate reusing the shipped classification.
  • src/core/brain/trust/retrieval-receipts.ts - the refusals section on both receipts.
  • src/core/search/pipeline/post-rank.ts - mount the mode-aware gate; build receipts from the shadow outcome.
  • src/core/search/pipeline/relational-arm.ts - the edge-level eligibility adjuster.
  • src/core/search/types.ts, src/core/search/index.ts - the mode type and its resolution beside search_trust_gate_enabled.
  • src/core/search/pipeline/cache-slot.ts, src/core/search/explain-envelope.ts - the mode in the cache key and the envelope.
  • src/core/brain/explorer.ts - the two new GET routes; the additive options object carrying configPath.
  • templates/brain-explorer.html - the counts and ops sections fetched client-side.
  • src/cli/brain/verbs/explorer.ts - thread configPath; boot banner mentions the new routes.
  • tests/core/config.test.ts, tests/core/brain/extract-signals.test.ts, tests/core/brain/extract-signals-prefilter.test.ts, tests/cli/brain-extract-signals.test.ts, tests/mcp/extract-signals-tool.test.ts, tests/cli/session-discovery.test.ts, tests/hooks/hooks-json-shape.test.ts, tests/core/brain/trust/retrieval-gate.test.ts, tests/core/brain/trust/retrieval-receipts.test.ts, tests/core/search/retrieval-trust-gate.test.ts, tests/core/search/relational-arm.test.ts, tests/core/search/config.test.ts, tests/core/brain/explorer.test.ts, tests/cli/brain-explorer.test.ts - extended per the plan.
  • docs/cli-reference.md, docs/mcp.md, docs/how-it-works.md - the new surfaces documented on their existing entries.

Risks and open questions

  • SessionStart budget: the hook entry allows 10 s and discoverSessions' own docblock measures about 6 s cold over a large fixture, which is why the census is answered from the vault-side ledgers with no log hashing, and the hook degrades to silence rather than sweeping under deadline. The hook test asserts the fail-open path.
  • The mining record must stay size-bounded: entries are tens of bytes, pruning removes sessions whose turns no longer exist, and the v1.85.0 doctor checks name derived-ledger growth regardless.
  • Only off is byte-identical on the recall lane. Shadow changes the outcome shape by adding receipt fields; the cache key and the explain envelope must both carry the resolved mode or a cached off result could be served for a shadow query.
  • The tombstone race window (plan and commit observing different turn sets) is accepted and documented; if it ever matters in practice, the recorded turn count is the additive remedy, and it is recorded in the entry breakdown from the start.
  • The relational arm's identical-to-absent provenance convention and the reportable-refusal convention now coexist in one file; the arm tests must pin the distinction (a refusal is counted, a provenance omission is not reported).
  • The explorer's per-GET dry-run dream cost is accepted and must be stated in the route's docs; if it ever needs relief, the remedy is an explicit operator action, not a silent cache.
  • The config-template ratchet only fires for keys added to the resolver default tables; both new keys ride resolveConfigFlag and the envOrConfig path beside their existing siblings, so no template entry is expected - the ratchet test stays the guard.