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.
Implementation plan β memory-signal provenance and lifecycle integrity
Branch: feat/memory-signal-provenance-lifecycle. Cards are driven ONE AT A
TIME on this shared branch. Each worker MUST git pull / build on the commits
previously-driven in-scope cards already landed, and must not duplicate or
conflict with sibling tasks. Follow TDD: write the failing test first.
Combined design: docs/brainstorm/memory-signal-provenance-lifecycle/design.md.
Variants + rationale: docs/brainstorm/memory-signal-provenance-lifecycle/variants.md.
Drive order: A1 β C1 β A2 β D2 β D1 β E1 β C2 β C3 β C5 β C6 β A3 β C4 β D3
In-scope cards (ship together in this one release):
t_c5184fd8(A1, p4) β content-hash skip-unchanged manifestt_213f356b(C1, p3) β idempotent writes via client idempotency keyst_7526e8d3(A2, p4) β per-row event-time on batch remember/importt_11e3db8b(D2, p3) β note-position contradiction detectiont_4678a91a(D1, p4) β signed source-diversity grounding scoret_1c894c19(E1, p4) β session-bracketing memory wrapper for Aidert_2c6cf3e2(C2, p3) β dry-run extraction previewt_92317f91(C3, p3) β bounded verbatim last-N-turns buffer surviving compactiont_a82b674e(C5, p3) β caller-settable per-memory expiration datet_edde2198(C6, p3) β delete and search by exact source filet_9eeb8ca2(A3, p2) β batch-plan step (depends on A1)t_1a3a9eba(C4, p3) β batch checkpoint save for whole sessions (depends on C1)t_74d29363(D3, p2) β declared-thesis register monitor (depends on D2)
Engineering rules: SOLID / KISS / DRY; no misleading fallbacks; no hardcoding; English-only strings, abstract multi-language. The kernel calls no LLM.
A1 β t_c5184fd8 β Content-hash skip-unchanged manifest (driven first)
Files
src/core/brain/ingest/content-manifest.tsβ NEW.hashFile(absPath)/hashTree(dir)β SHA-256 hex over file BYTES (reuses thecreateHash("sha256")primitive ofsourceIdentityHash, but over content, not source-path identity β a distinct artifact from identity dedup).readManifest(vault)/writeManifestAtomic(vault, entries)against<vault>/.open-second-brain/ingest-manifest.json(machine artifact, NOT underBrain/).classifyPaths(vault, paths, manifest)β{ new, modified, unchanged, missing }.updateManifest(vault, paths)records post-ingest hashes; a no-op rerun (all unchanged) rewrites nothing.src/core/brain/ingest/ingest.tsβ callclassifyPathsbefore the extraction pass; skip the LLM/extraction forunchangedsources (still idempotently rewrite the summary page only if its own bytes would change).tests/core/brain/ingest/content-manifest.test.tsβ NEW.
Acceptance (passing test)
A test in tests/core/brain/ingest/content-manifest.test.ts that:
- After ingesting a source, re-ingesting an UNCHANGED file (same bytes) classifies
it
unchangedand the summary page is NOT rewritten (no-op-rerun invariant). - Touching/restat-ing the file (mtime change, byte-identical) still classifies
unchanged(timestamp-independent β the regression this card exists to fix). - Modifying bytes classifies
modified; deleting classifiesmissing; a new path classifiesnew. - Asserts the manifest is written atomically and a no-op rerun leaves it byte-identical.
Depends on
None. Lands the shared manifest module that A3 consumes. Driven first (opens the ingest axis).
C1 β t_213f356b β Idempotent writes via client idempotency keys
Files
src/core/brain/idempotency-ledger.tsβ NEW.rememberKey(vault, { key, contentHash })βinserted | duplicate_match | payload_mismatch. Keyed by client key β content hash, stored under<vault>/Brain/logs/idempotency/(month-sharded JSONL, mirroring the continuity store's append/list model). Same key + same hash β deduped no-op; same key + different hash βpayload_mismatch(explicit throw, never silent overwrite).lookupKey(vault, key)for audit/C6.src/core/brain/signal.tswriteSignalβ add optionalidempotency_key?(additive; absent β existing behavior byte-identical). When present, hash the would-be payload and consult the ledger before writing.src/core/brain/preference.tswritePreferenceβ add optionalidempotency_key?(same shape).src/core/brain/apply-evidence.tsappendApplyEvidenceβ add optionalidempotency_key?(same shape).src/mcp/brain/feedback-tools.tstoolBrainFeedbackβ forward an optionalidempotency_keyarg to the underlying writers.tests/core/brain/idempotency-ledger.test.tsβ NEW; extend writer tests.
Acceptance (passing test)
A test that:
- With NO
idempotency_key, a write is byte-identical to the old path (the bit-identity guard). - Two writes with the SAME key + SAME payload β second is deduped (returns duplicate_match, no file appended, no duplicate signal).
- Two writes with the SAME key + DIFFERENT payload β second THROWS payload_mismatch (explicit error, never silent overwrite).
- A retried write (same key, same payload) after a simulated crash is safe (deduped, not duplicated) β the multi-runtime retry case.
Depends on
None. Lands the shared idempotency-ledger module that C4 consumes. Driven second (opens the write-integrity axis).
A2 β t_7526e8d3 β Per-row event-time on batch remember/import
Files
src/core/brain/signal.tsWriteSignalInputβ add optionalvalid_from?andrecorded_at?(additive; absent β existing signals byte-identical). These flow into the SAME frontmatter keysreadBiTemporalSlots()already parses (valid_from/valid_until/recorded_at), so the read-side needs no change.src/core/brain/sessions/import.tsemitβ preferSessionTurn.timestamp(when present and parseable) forcreated_at/recorded_at, falling back tonowonly when absent or unparseable. Guard against future-dated turn timestamps during backfill (clamp/skip deterministically; document the choice).src/mcp/brain/feedback-tools.ts+ batch import path β forward an optional per-rowevent_time.tests/core/brain/sessions/import-event-time.test.tsβ NEW.
Acceptance (passing test)
A test in the import test suite that:
- Backfilling an old session log stamps each signal's
created_at/recorded_atwith the turn's ORIGINAL timestamp, NOT the import wall-clock. - A turn with NO timestamp falls back to
now(backward-compatible). - A turn with an UNPARSEABLE or FUTURE-dated timestamp is handled deterministically
(falls back to
nowor clamps β no throw, no corrupt future-dated signal). - Asserts existing imports (no
event_time) are byte-identical.
Depends on
None (orthogonal to C1). Driven third. NOTE: this card touches import.ts
emit; C2 (later) adds a dry-run short-circuit to the same path β sequenced.
D2 β t_11e3db8b β Note-position contradiction detection over prose
Files
src/core/brain/health/contradiction.tsβ adddetectNoteContradictions(notes, opts)that pairs same-subject permanent notes asserting opposite stances. Reuses the existing language-agnostic machinery:similarity.tsfindSimilarPairs/tokenisefor token-overlap subject pairing and a sign derivation from note PROSE (notevidenced_bysignals). Emitsask_userfindings that quote the relevant span from each note; never auto-resolves. New result typeNoteContradictionFindingalongside the existingContradictionFinding.tests/core/brain/health/contradiction-notes.test.tsβ NEW.
Acceptance (passing test)
A test that:
- Two same-subject permanent notes with opposite stances are paired and surfaced as a contradiction finding, each with its quoted span.
- Notes that merely ADD complexity (same stance) are NOT flagged.
- Unrelated-subject notes are not paired (token-overlap threshold).
- Detection is deterministic and language-agnostic (no English wordlist); a negation/stance derived structurally.
Depends on
None. Driven fourth. NOTE: this card touches contradiction.ts; D3 (later) adds
the thesis monitor on top β sequenced.
D1 β t_4678a91a β Signed source-diversity grounding score
Files
src/core/brain/truth/grounding.tsβ NEW.computeGroundingScore(slot, events)β{ score: number (-1.0..+1.0), confidence: "high"|"medium"|"low", band: "strongly_supported"|"mixed"| "contested"|"contradicted", supportingSources, contradictingSources }. Pure projection over theClaimEvents that feed the slot (same eventscomputeTruthStatefolds). Source-DIVERSITY weighting: confirming vs contradicting evidence counted across INDEPENDENT sources (distinctsource+agent), N mentions in one doc << N mentions across N independent sources (document a weight ceiling); relationship strength weights the contribution. Signed (+ confirming, β contradicting); separate confidence/sufficiency dimension. Deterministic, order-insensitive (sort internally like the fold). Never writes/mutates the append-only ledger.src/core/brain/truth/{fold,conflicts}.tsβ surface the projection alongsidecomputeTruthStateWithConflictsoutput (additive; CONTESTED flag stays, the score quantifies it). No mutation of the fold.tests/core/brain/truth/grounding.test.tsβ NEW.
Acceptance (passing test)
A test that:
- A slot agreed by N independent sources scores strongly positive; agreed by 1 source scores weaker (source-diversity weighting is the part o2b lacks).
- A contested slot (independent sources disagree) gets a score whose SIGN points to the better-supported side and whose magnitude reflects the balance.
- N mentions in ONE document weigh far less than N mentions across N independent sources.
- The score is deterministic and order-insensitive (shuffled input events β identical score), and the append-only ledger is not mutated.
Depends on
None (owns truth/ alone). Driven fifth.
E1 β t_1c894c19 β Session-bracketing memory wrapper for Aider
Files
scripts/o2b-aider(oro2b aider wrap) β NEW CLI wrapper process. At start, runs the load-half (regenerate the context sidecar via the existing Aider adapter's snapshot logic, mirroring Hermesprefetch()); execs the Aider binary with the injectedread:context; at session end runs the write-back half (capture the session and persist into the Brain, mirroring Hermessync_turn()/on_session_end()). Wrapper-process design because Aider has no native MCP.src/core/install/adapters/aider.tsβ keep as the documented fallback (static sidecar for users who do not run through the wrapper). Extract reusable snapshot/capture helpers so the wrapper and the adapter share one source of truth (DRY).tests/for the wrapper lifecycle (load/persist bracketing, fallback path).- Lifecycle shape mirrors
plugins/hermes/provider.pyprefetch/sync_turn/on_session_end.
Acceptance (passing test)
A test (and/or an integration smoke) that:
- The wrapper loads the memory context at session start (the load-half fires before Aider is exec'd) and persists the session back at session end (the write-back half fires after Aider exits).
- The static sidecar fallback path still works unchanged for users who do not run through the wrapper (byte-identical adapter output).
- An interrupted session (non-zero exit / signal) is handled honestly (captured
as interrupted, mirroring
pre_compact_extract'sinterruptedflag).
Depends on
None (fully isolated; no shared file with any other card). Driven sixth.
C2 β t_2c6cf3e2 β Dry-run extraction preview
Files
src/core/brain/pre-compact-extract.tsextractPreCompactRecordsβ add optionaldryRun?: booleanmirroring the EXISTINGopts.dryRunidiom inimport.ts. When true, return the candidate records it WOULD extract WITHOUT callingappendContinuityRecord(no vault mutation, no log event, no dream/retire trigger). The returned records are the exact objects the real path would append.src/core/brain/sessions/import.tsβ already hasopts.dryRun; ensure the pre-compact path generalizes the same short-circuit. No global wrapper.src/mcp/brain/pack-tools.ts(or the relevant extract surface) β expose the preview as a non-destructive MCP/CLI verb.tests/core/brain/pre-compact-extract-dry-run.test.tsβ NEW.
Acceptance (passing test)
A test that:
dryRun: truereturns the candidate records but writes NOTHING to the vault (noappendContinuityRecordcall, no dream/retire trigger).- A parity assertion: the dry-run candidate records are deeply equal to the records the real path appends for the same input (preview faithfully predicts real extraction).
dryRunabsent/false is byte-identical to today.
Depends on
A2 (touches the same import.ts emit path; A2 settles event-time first, then
C2 gates it). Driven seventh.
C3 β t_92317f91 β Bounded verbatim last-N-turns buffer surviving compaction
Files
src/core/brain/continuity/types.tsβ addrecent_turntoContinuityRecordKind(additive; legacy records read as v1).src/core/brain/recent-turns.tsβ NEW. Bounded verbatim ring buffer of the last N turns (hard cap, default 20).appendRecentTurn(vault, turn)evicts oldest beyond N;listRecentTurns(vault, { limit })for reads. Persisted via the continuity store. Ephemeral scaffolding β its own kind + reader, clearly separated from curated memory.- Optional post-compaction re-surface (opt-in flag, default off β byte-identical) appends the buffer to the post-compaction context.
tests/core/brain/recent-turns.test.tsβ NEW.
Acceptance (passing test)
A test that:
- Appending N+1 turns evicts the oldest (hard cap enforced); the buffer never grows beyond N.
- After a simulated compaction,
listRecentTurnsreturns the exact recent wording (the continuity-store artifact survives). - The buffer is clearly separated from curated memory (its own kind; reads do not leak into preference/signal/provenance surfaces).
- Post-compaction re-surface is default-off β byte-identical context when off.
Depends on
None. Driven eighth.
C5 β t_a82b674e β Caller-settable per-memory expiration date
Files
src/core/brain/preference.tsWritePreferenceInputβ add optional ISOexpiration_date?(additive; absent β byte-identical). Flow into frontmatter.src/core/brain/signal.tsWriteSignalInputβ add optionalexpiration_date?(same shape).- Read path (search/list) β default silently drops anything past its
expiration_date; an opt-inshowExpiredflag re-includes them for audit. - Orthogonal to dream's heuristic retirement: an expired-by-date memory is
FILTERED, not moved to
Brain/retired/(audit trail preserved). tests/core/brain/{preference,signal}-expiration.test.tsβ NEW.
Acceptance (passing test)
A test that:
- Writing a preference with
expiration_datestamps the frontmatter; a write WITHOUT it is byte-identical to today. - Default search/list DROPS memories past their
expiration_date. - With
showExpired: true, expired memories are included (audit path). - An expired-by-date memory is NOT moved to
Brain/retired/(orthogonal to dream; audit trail preserved).
Depends on
None. Driven ninth.
C6 β t_edde2198 β Delete and search by exact source file
Files
- Search: add exact
source_filefilter (matches[[source-ref]]/session_ref/ ingest source-link frontmatter). src/core/brain/source-cleanup.ts(or extend an existing surface) β NEWdeleteBySource(vault, sourceFile, { confirm, includeOriginals })that is DRY-RUN BY DEFAULT: reports the blast radius (derived signals/preferences/ index entries/summary pages tracing to the source) WITHOUT deleting. An explicitconfirmdeletes the derived entries (and index artifacts); original user notes removed ONLY with an explicitincludeOriginalsflag. Writes auditable (continuity record of the cleanup).- CLI/MCP reader surfaces search-by-source and the dry-run blast-radius report.
tests/core/brain/source-cleanup.test.tsβ NEW.
Acceptance (passing test)
A test that:
source_filesearch filter returns only entries derived from that exact source.deleteBySourcewith NOconfirmreports the blast radius and deletes NOTHING.- With
confirm(noincludeOriginals), derived entries + index artifacts are deleted but ORIGINAL user notes are preserved. - With
confirm+includeOriginals, originals are also removed. Cleanup is auditable (a continuity record is written).
Depends on
None. Driven tenth.
A3 β t_9eeb8ca2 β Batch-plan step (depends on A1)
Files
src/core/brain/ingest/batch-plan.tsβ NEW.planBatches(vault, sourceDir, { maxBatchBytes, maxBatchFiles })discovers ingestible files, calls A1'sclassifyPathsto skipunchanged, then splits the remainder into size+count-bounded batches (deterministic: sort by path, fill greedily to the byte cap then the count cap). Returns the batch list for the caller (agent/CLI) to dispatch as parallel subagents. No parallel execution inside the kernel.- CLI/MCP reader surfaces the plan.
tests/core/brain/ingest/batch-plan.test.tsβ NEW.
Acceptance (passing test)
A test that:
planBatchesskipsunchangedfiles (via A1's manifest) and plans batches only overnew/modifiedfiles.- Batches respect BOTH the byte cap and the file-count cap (no batch exceeds either).
- The plan is deterministic (same dir β same batch list, stable ordering).
- An empty/all-unchanged dir yields an empty plan (no spurious batches).
Depends on
A1 (t_c5184fd8) β consumes the content-hash manifest's classifyPaths.
Driven eleventh. Pull before starting (A1's commits must be present).
C4 β t_1a3a9eba β Batch checkpoint save for whole sessions (depends on C1)
Files
src/mcp/brain/synthesis-tools.ts(or a new checkpoint module) β NEWbrain_session_checkpointtool that saves a whole session's signals + learning- summary in ONE idempotent MCP round-trip. Idempotency is session-id + content-
hash, reusing C1's idempotency ledger (
rememberKey). If some writes need review (payload mismatch / validation failure), returns{ status: "ok" | "mixed", partial: [...] }β never silently drops items.
- summary in ONE idempotent MCP round-trip. Idempotency is session-id + content-
hash, reusing C1's idempotency ledger (
tests/mcp/session-checkpoint.test.tsβ NEW.
Acceptance (passing test)
A test that:
- A checkpoint with a fresh session-id writes all items once; a RETRY with the same session-id + same content is deduped (idempotent, no duplicates) via C1's ledger.
- A checkpoint where some items need review returns
status: "mixed"with the partial list (never silently drops). - A retry with the same session-id but DIFFERENT content throws payload_mismatch (explicit error, no silent overwrite).
Depends on
C1 (t_213f356b) β reuses the idempotency-key ledger. Driven twelfth. Pull
before starting (C1's commits must be present).
D3 β t_74d29363 β Declared-thesis register with new-note monitor (depends on D2)
Files
src/core/brain/health/thesis.tsβ NEW. A declared-thesis register (operator-recorded positions: statement, supporting evidence, counter-evidence, last-updated, falsification "what would make me wrong"), stored as a dedicated frontmatter kind underBrain/theses/. A monitor evaluates each newly-ingested note against active theses, flagging support/contradiction (builds on D2's note-position base). Reusesobligations.tscadence machinery for the "not updated in N days" staleness check and the thesis-graveyard pass (flag theses with no supporting evidence in N days for formal closing). Suppresses mere added-complexity per the article. Alerts when incoming evidence matches a thesis's documented falsification scenario.tests/core/brain/health/thesis.test.tsβ NEW.
Acceptance (passing test)
A test that:
- Recording a thesis and ingesting a note that CONTRADICTS it raises a conflict flag (quoting the thesis note); a note that SUPPORTS it raises a support flag.
- A thesis not updated within the cadence is flagged stale (via the obligations machinery); a thesis with no supporting evidence in N days is flagged for the graveyard.
- Incoming evidence matching a thesis's falsification field raises an alert.
- A note that merely adds complexity is NOT flagged. Never auto-resolves.
Depends on
D2 (t_11e3db8b) β builds on the note-position detector. Driven last (closes
the honesty axis). Pull before starting (D2's commits must be present).