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 β Context-pack memory-economics & observability
Branch: feat/context-pack-economics-observability. 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/context-pack-economics-observability/design.md.
Drive order: C2 β C1 β C3 β C4 β C5.
In-scope cards (ship together in this one release):
t_6c9a3e5c(C2, p4) β route-level latency metrics for MCP toolst_affa3bd9(C1, p4) β value-per-token density ranking in context-packt_a8926bd0(C3, p3) β durable token-impact + context-pack-quality ledgert_dfda8adb(C4, p3) β proactive active-memory budget-pressure watermarkt_f2140bae(C5, p2) β agent-operable context-pack outcome loop
C2 β t_6c9a3e5c β Route-level latency metrics for MCP tools (driven first)
Files
src/core/brain/continuity/types.tsβ addmcp_route_latencytoContinuityRecordKind. (Shared-kernel commit; also lands thetoken_impact+context_pack_outcomekinds so C3/C5 don't re-touch this file.)src/core/brain/continuity/readers.tsβ NEW sharedlistRecordsByKind(vault, kind, filter)+summarizeCounters(records, keys)helpers (pure, deterministic; composes the continuity store's existing month-shard list + reverse/limit/filter).src/core/brain/mcp-route-latency.tsβ NEW.emitRouteLatency(vault, {tool, durationMs, status, argShapeHash?})βContinuityRecord(kindmcp_route_latency);listRouteLatency(vault, filter);summarizeRouteLatency(vault, filter)(top slow tools, p95-ish counters, by status). Payload: tool name, duration_ms, status, optional arg-shape hash over KEYS only (structural), never raw prompt/note content. Redaction throughsafeContinuityPayload.src/mcp/tools.tsβ inbuildToolTable, wrap eachToolDefinition.handlerwith a timing+status collector emitting onemcp_route_latencyrecord per call. Gated by config flagmcp_route_latency_enabled(default false). On emission failure the tool result is unchanged (fail-open).src/mcp/...(or CLIo2b) β add a reader verb exposing the summary.tests/core/brain/mcp-route-latency.test.ts+tests/mcp/tools-latency.test.ts.
Acceptance (passing test)
A test in tests/mcp/tools-latency.test.ts that:
- With
mcp_route_latency_enabled=false, calling a tool produces byte-identical output and writes NOmcp_route_latencyrecord (bit-identity + zero-write guard). - With the flag true, calling a slow tool emits one record with the correct tool name, a positive duration, and status; the summary reader returns it;
- Asserts the payload contains NO argument VALUES (only a key-shape hash at most) β a redaction/privacy assertion.
Depends on
None. Isolated in tools.ts. Driven first (opens the shared-kernel commit).
C1 β t_affa3bd9 β Value-per-token density ranking in context-pack
Files
src/core/brain/context-density.tsβ NEW.densityScore({body, evidenceRefs, topic, principle}, tokens)β number; computed from structural signals (evidence-ref/wikilink density, signal markers) per estimated token. Language-agnostic (no wordlists; same construction asderiveEpistemicStatus). Pure, deterministic.src/core/brain/context-pack.tsβ adddensityRanking?: booleantoContextPackOptions. When true, compute adensityScoreper candidate into adensityScoremap and insert a density comparator INTO the existingcandidates.sort(...), AFTERsessionFocus(full chain: tier β sessionFocus β density β recency β id; map empty β default sort byte-identical). Tier stays the coarse gate; tie-break recency β id. Optionally adddensity?toContextPackItem(absent when off β byte-identical).tests/core/brain/context-density.test.ts+ extendcontext-packordering tests.
Acceptance (passing test)
A test in tests/core/brain/context-pack.test.ts (or density test) that:
- Asserts the pack with
densityRankingOFF is byte-identical to a pack with the option absent entirely (the bit-identity guard); - With
densityRankingON, a denser lower-recency entry ranks above a sparser recent one WITHIN the same tier; - Asserts a peripheral page NEVER outranks a core page regardless of density (tier remains the coarse gate).
Depends on
None (orthogonal). Driven second. NOTE: this card touches the
candidates.sort(...) region of context-pack.ts; C3 (later) touches the
finalizeContextPackReport region β disjoint, but pull before starting.
C3 β t_a8926bd0 β Durable token-impact + context-pack-quality ledger
Files
src/core/brain/token-impact-ledger.tsβ NEW.emitTokenImpact(vault, {packReceiptId, exactTokens, modeledAvoidance?, counterfactual?, basis})wherebasis: "tokenizer_exact" | "fallback_est". Strict schema separation:exact.prompt_token_deltavsmodeled.inference_avoidance(confidence-banded) never merged. Persisted via continuity store (kindtoken_impact, added in the C2 shared-kernel commit), reloaded on startup through the shared reader.src/core/brain/context-pack.tsβ infinalizeContextPackReport, when a new opt-in flag is set (token_impact_ledger_enabled/ option), emit onetoken_impactrecord: tokenizer-exact delta of the packed body vs an un-packed baseline, withbasisset honestly. Default-off β no record, byte-identical.- CLI/MCP
brain_token_impact_outcomeβ outcome-calibration endpoint: posts first-pass/repair/retry outcomes to recalibrate the modeled band (the passive endpoint C5 writes into). ReadersummarizeTokenImpact(vault, filter). tests/core/brain/token-impact-ledger.test.ts.
Acceptance (passing test)
A test in tests/core/brain/token-impact-ledger.test.ts that:
- Emits a token_impact record with
basis: "tokenizer_exact"and asserts exact and modeled fields are stored SEPARATELY (no merged field); - Emits with
basis: "fallback_est"and asserts the fallback label is present; - Asserts the record survives a reload (persisted, listable) and contains NO raw prompt/recalled text (privacy assertion);
- With the flag off,
finalizeContextPackReportwrites no record (bit-identity).
Depends on
C2's shared-kernel commit (the token_impact kind + shared reader). Driven
third.
C4 β t_dfda8adb β Proactive active-memory budget-pressure watermark
Files
src/core/brain/active-budget-pressure.tsβ NEW.computeActiveBudgetPressure(body, budgetChars)β{fillRate, status: "healthy"|"elevated"|"critical", candidates: Array<{sectionKey, bytes, priority}>}. ReusesSECTION_PRIORITIESfromactive-budget.ts(extract to a shared constant intext-budget.tsoractive-budget.tsif not already exported) and the same section-split logic.src/core/brain/active-budget.tsβ exportSECTION_PRIORITIES(and the split helper if shared) for reuse; no behavior change.src/core/brain/doctor.tsβ add a proactive pressure check: whenfillRateexceeds the warn threshold, list ranked eviction CANDIDATES (highest-priority- to-drop first) as suggestions; "empty output = healthy" (quiet on healthy vaults). Never auto-deletes.tests/core/brain/active-budget-pressure.test.ts.
Acceptance (passing test)
A test in tests/core/brain/active-budget-pressure.test.ts that:
- With
fillRate <= threshold,statusishealthyand the doctor check emits NOTHING (quiet-on-healthy contract); - With a body over budget,
statusis elevated/critical and candidates are returned ranked by drop-priority (retired before confirmed); - Asserts the term "active budget pressure" / does NOT collide with
WatermarkStateinskill-proposals.ts(grep guard); - Asserts no vault content is mutated (suggestions only).
Depends on
None. Driven fourth. (If SECTION_PRIORITIES extraction touches
active-budget.ts, that is the only shared-file seam; pull before starting.)
C5 β t_f2140bae β Agent-operable context-pack outcome loop (capstone)
Files
src/core/brain/context-pack-outcome.tsβ NEW.emitContextPackOutcome(vault, {sampleId, firstPassSuccess, repairRequired?, retryCount?, followUpTokens?, providerTokens?, tokenSignal})wheretokenSignal: "exact" | "modeled" | "observed"keeps the three token signals strictly separate (never merged into one field). Writes acontext_pack_outcomecontinuity record AND posts to C3's calibration endpoint. Compact counters only; agent omits a field rather than inventing it.src/core/brain/context-pack.ts(or the receipt/report path) β carry the latest sample id as bounded local state in the pack report/receipt (not a daemon). On completion the agent posts the outcome row.- MCP/CLI surface to post the outcome row.
tests/core/brain/context-pack-outcome.test.ts.
Acceptance (passing test)
A test in tests/core/brain/context-pack-outcome.test.ts that:
- Posts an outcome row and asserts the three token signals (exact/modeled/ observed) are stored as SEPARATE fields, never merged;
- Asserts the record contains only compact counters β NO raw prompts, completions, source text, or secrets (privacy assertion);
- Asserts a missing field is OMITTED, not invented (omit-don't-invent guard);
- Asserts the outcome also appears in C3's ledger calibration (composes C3).
Depends on
C3 (hard dependency β the outcome loop writes into C3's ledger). Driven last.