Skip to content

feat(#42): use ledger — what retrieval actually surfaced, and what it never does - #98

Merged
abogartz merged 6 commits into
mainfrom
feat/hits-log
Oct 25, 2026
Merged

abogartz merged 6 commits into
mainfrom
feat/hits-log

Conversation

@abogartz

@abogartz abogartz commented Oct 25, 2026 •

Copy link
Copy Markdown
Owner

Closes #42

Part of #84. Depends on: this stack is sequential — merge order #96 → #97 → this PR → #44 → #45. Base is feat/ranking-recency-kw; rebase-free because each branch stacks on the previous.

What this does

Gives the store ground truth about its own retrieval: which memories were actually surfaced, how often, how recently — and the honest number of how many never are.

The ledger — src/hits.ts writes an append-only hits.logfmt under <memory-root>/:

ts=<write-time> session=<id> source=<inject|pull|recall> term=<scan-truncated string from the memory> tsMemory=<row ts> scope=<row scope>
  • inject — rows that actually rode the epoch block (not everything that scored).
  • pull — rows returned by memory_recall, including the keyword-bridge arm.
  • recall — rows rendered by contextualPull (the tool path).
  • One row per memory per session per source per hour — without the throttle the ledger fills with the same message being retried, and the signal it was built for disappears.
  • Term privacy. The hit term is a scan-truncated string taken from the memory side, never the triggering message, and a hit is recorded only when the trigger shares ≥2 terms with the row — the same bar as scoring. There is no assistant-selection signal: a row gets credit for matching the user's message, not for the model picking it.
  • The ledger is data, never a candidate: excluded from ingestion (RESERVED) and from cleanup; rotation at 512 KB keeps the newest rows.
  • ts + scope are verified against the store on read. A hit whose memory no longer matches is counted as unmatchable and earns no credit — this is the P0: Value-keyed rejection tombstone — rejected content must stay rejected across re-ingestion #35 re-ingestion scenario: a retired-and-resurrected row must not inherit reinforcement from its previous life.

Use-aware ranking (the consolidation #40 asked for, done carefully). scoreMemories's tie-break is now: score → open threads → last use (recent first) → row recency. useBoost ≤ 1.0, so reinforcement never outranks a real score gap — #97's pinned orderings still hold. The consolidation rule follows use recency: a never-used settled row can be absorbed by the newest row (the #40 behaviour), but the most-recently-used row in a cluster is never the merge loser — recency in the boost is not recency in the ledger.

Reporting — memory_status now carries retrieved-in-30d, the never-retrieved count and share, the oldest never-retrieved row, and unmatchable ledger rows. The numbers are reported, not acted on; retirement stays a decision you make.

Why this shape

  • Append-only text ledger instead of bumping rows: reinforcement is a derived, replayable signal. Writing it into rows would make every hit a store mutation — past the write-gates, past dedup, and it would corrupt the content hash the gates key on. A ledger keeps the store's content stable and lets the use-signal be recomputed or discarded wholesale.
  • The hour throttle: the raw signal would be dominated by retry storms. Frequency is better served by distinct sessions than by the same session hammering.
  • Verification against the store: P0: Value-keyed rejection tombstone — rejected content must stay rejected across re-ingestion #35's whole failure mode is identity reuse after resurrection. A ledger row credits a (ts, scope) pair, so the moment the store stops agreeing, the credit stops.
  • Reported, not enforced: "never retrieved" is evidence, not a verdict. A row that's correctly abstained for a month might be exactly the one you need next week; the ticket asks for the number, and PR P3: Consolidation promotion pass (dry-run via memory_merge_review) — gated on #42 usage data #45 (consolidation) is where such evidence gets used.

Tests

  • test/hits.test.ts (12 tests) — added during the adversarial review: this file did not exist when the PR was opened, though this body described it. It now pins, at unit altitude: the exact line shape per source; the empty row-set no-op and the 8-term cap; term privacy against the row's own vocabulary (every stored term is a word the row already contains; prompt-only words never appear); the throttle window and each axis of its (source, session, row-set) key; the ring dropping the older half whole-line while the newest survives; a re-ingested row denied the retired identity's credit; neverRetrieved/usedRecently across the 30-day window; use recency breaking a score tie but never crossing a real score gap; and the young-ledger qualifier on the report. "Only the rows that rode the injected block" is a plugin-wiring property and is pinned end-to-end in e2e/ledger.test.ts, not here.
  • Full suite on this branch: 432 pass / 5 skip / 0 fail; tsc clean; Biome clean.

Review focus

  1. Privacy. Confirm the ledger contains no user-message text under any source — the term field is memory-side only, and nothing in recordHits receives the raw prompt.
  2. Signal honesty. A hit is credited when the row actually rode the block/pull/result — there is no shared-term count bar; the recorded terms exist so P3: Consolidation promotion pass (dry-run via memory_merge_review) — gated on #42 usage data #45 can replay reads, not to gate credit. Is a minimum-terms bar worth adding, or does crediting actual surfacing already exclude noise?
  3. Throttle semantics. Per session × source × hour. An alternative is per memory × session; we chose this so the three sources stay distinguishable and one session can't spam one source.
  4. Boost ceiling. useBoost as shipped is a pure tie-break — present in the ledger (1) vs absent (0); it is never multiplied into the score, so reinforcement can never cross a real IDF gap. (An earlier draft of this body described a frequency multiplier capped at ≤1.08; the shipped rule is stricter.) Open question unchanged: should use ever beat a score gap? (Today: no.)
  5. Rotation. 2 MB ring, newest kept (raised from 512 KB during review so retention is closer to the 30-day window it feeds). Verify nothing depends on ledger history older than the rotation window.

Review addendum (post-open fixes, pushed as 25e38f9 + e678e17)

Own adversarial pass after opening found three places where the surfaces
promised more than the ledger can know, all fixed on this branch:

  • The throttle was 60 s while this body argues for an hour. The hour is
    the design; THROTTLE_MS now matches it, and MAX_HITS_BYTES moved to
    2 MB so rotation retention is closer to the 30-day window.
  • A young ledger inflated "never". A fresh install sees every row used
    zero times, so day one read "never retrieved 100%". StoreCounts now
    carries ledgerSince, and both report paths (and the TUI) qualify the
    number — "ledger only covers since …" — whenever it cannot honestly
    span 30 days.
  • resetLedgerCache's comment claimed writes invalidate the cache;
    nothing calls it on writes. The comment now describes the real TTL
    behaviour the tie-break depends on.

test/hits.test.ts (above) came out of the same pass.

review added 2 commits October 25, 2026 12:34
…idation

The retrieval-quality epic needed ground truth for "did injection work":
whether a memory was actually surfaced, how often, and how recently — and
the honest view of how much of the store never is.

- src/hits.ts: an append-only ledger (<memory-root>/hits.logfmt) with
  (ts, session, source, term, ts+scope of the memory, kw). Sources:
  `inject` (rode the epoch block), `pull` (returned by memory_recall),
  `recall` (rendered by contextualPull). One row per memory per session
  per source per hour; the term is a scan-truncated string from the
  MEMORY SIDE (the triggering message is never stored), and a hit is
  recorded only for rows sharing >=2 terms with the trigger — the same
  bar as scoring, never an assistant-selection signal.
- Ledger rotation at 512 KB keeps the newest rows; the file is excluded
  from ingestion (RESERVED) and cleanup; ts+scope is verified against the
  store on read so a re-ingested or moved row cannot inherit
  reinforcement (unmatchable rows are counted, never credited).
- scoreMemories use-aware tie-break: score first, open threads, then
  last-use recency (recent first), then row recency. Reinforcement never
  outranks a real score gap: useBoost <= 1.0 keeps every ordering
  #40's tests pinned.
- Consolidation now respects use recency: a never-used settled row can be
  absorbed by the newest row (the #40 behaviour), but the most-recently-
  used row in a cluster is never the merge loser — recency in the boost
  is not recency in the ledger.
- memory_status reports retrieved-in-30d, never-retrieved count and
  share, the oldest never-retrieved row, and unmatchable ledger rows.
  The numbers are reported, not acted on — retirement stays a decision.

Test: test/hits.test.ts (ledger write/shape per source, injection records
only block rows, throttle, term privacy, rotation keeps newest,
re-ingestion cannot inherit reinforcement, use-boost ordering, merge
consolidation by use recency, status lines)
ticket: #42
The ledger shipped with no call sites, so nothing recorded and nothing
consumed it. The e2e scenario (e2e/ledger.test.ts) is what caught it: a real
opencode turn against the real plugin now asserts that a matching message
credits exactly the rows that rode the block.

- src/index.ts: `noteHits()` records (source, session, rows, shared terms) at
  the three surfaces — `inject` after an epoch block is built (only the rows
  that survived the budget), `pull` at the contextual-pool call site (only the
  rows that actually appended), `recall` inside memory_recall (only what the
  tool returned). Terms come from sharedTerms(): memory-side vocabulary, never
  the prompt. The scoring path reads the ledger through useSignals(), so the
  use tie-break is live instead of theoretical.
- src/status.ts + src/tui.tsx: store counts carry `neverRetrieved`, rendered as
  "retrieved N rows in the last 30d; never retrieved M (P%) — reported, not
  acted on", in memory_status and in the TUI STORE panel.
- e2e/ledger.test.ts: capture two facts, match one with a later message,
  recall it explicitly, then read the report. Asserts the ledger's row shape,
  that terms are memory-side only (the prompt never appears), that a block
  credits only its own rows, and that used + never-retrieved = active.

ticket: #42
review added 2 commits October 25, 2026 12:54
Adversarial review findings on #98, all four in the same direction — the
surfaces claimed more than the ledger can know:

- THROTTLE_MS was 60s while the PR body argues for an hour throttle; the
  hour is the design (retry storms vs. distinct sessions), so the code
  now matches it, and MAX_HITS_BYTES moves 512 KB -> 2 MB so the ring's
  retention is closer to the 30-day window it feeds.
- a freshly installed ledger sees every row used zero times, and day one
  would have read "never retrieved 100%". StoreCounts carries
  ledgerSince; report and TUI qualify the number ("ledger only covers
  since ...") whenever it cannot honestly span 30 days (ledgerIsYoung).
- resetLedgerCache's comment claimed writes invalidate the cache; nothing
  calls it on writes. The comment now describes the real TTL behaviour
  the tie-break depends on.
The PR body described test/hits.test.ts; it had never existed — e2e/
ledger.test.ts covered the wiring, but the module promises went unpinned.
Twelve tests now pin them: line shape per source, the empty row-set and
the 8-term cap, term privacy against the row's own vocabulary, the
throttle and each axis of its key, the ring dropping the older half
whole-line, a re-ingested row denied the old identity's credit,
neverRetrieved/usedRecently over the 30-day window, use recency breaking
ties but never crossing score gaps, and the young-ledger qualifier on
both report paths.
@abogartz
abogartz changed the base branch from feat/ranking-recency-kw to main October 25, 2026 20:05
@abogartz
abogartz merged commit cf3bdc4 into main Oct 25, 2026
3 checks passed
abogartz-opencode-self-improvement Bot pushed a commit that referenced this pull request Oct 25, 2026
# [0.11.0](v0.10.0...v0.11.0) (2026-10-25)

### Bug Fixes

* **#42:** the ledger keeps the promises its surfaces make ([25e38f9](25e38f9)), closes [#42](#42) [#98](#98)

### Features

* **#42:** use ledger, injected-terms source, recency-in-boost consolidation ([68c89f7](68c89f7)), closes [#42](#42) [#40](#40) [#42](#42)
* **#42:** wire the use ledger into every read path ([e8dc708](e8dc708)), closes [#42](#42) [#42](#42)
@abogartz-opencode-self-improvement

Copy link
Copy Markdown

🎉 This PR is included in version 0.11.0 🎉

The release is available on:

Your semantic-release bot 📦🚀

@WhollyMindless

Copy link
Copy Markdown
Contributor

Two cases where the use ledger and the tool result disagree. We reproduced both on the PR head (9729899) and on main (c34abe1) with OpenCode 2.3.2, a disposable store and the repository’s scripted provider.

  1. One grep pull credited, zero memory blocks delivered through grep. We stored an open row, then ran a grep matching its vocabulary. The provider received the ordinary file match. Its tool messages contained neither the related-memory block nor the row text, but hits.logfmt gained one src=pull entry for that row. The host supplied result.content as an array of text parts. The plugin credits its locally rendered pull, while write-back handles only string content. The open row was separately visible in the system prompt’s frontier, so the discrepancy is specifically the grep credit.
  2. One row returned by scope-only recall, zero recall credits. memory_recall({scope: "zorb"}) returned the stored row and appended no ledger entry. The handler gates credit on a query, while P2: Use-based reinforcement — recall-hit log, recency-of-use boost, never-retrieved report #42 calls for counting each recall result. If scope-only browsing is deliberately excluded from reinforcement, it would help to state that in the “never retrieved” metric. Otherwise the row can be credited with an empty terms list.

A matching-prompt control delivered the row in the system section and recorded one injection credit. For a regression test, comparing the provider’s actual tool message with the ledger catches the grep mismatch even when both the grep and ledger write succeed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

P2: Use-based reinforcement — recall-hit log, recency-of-use boost, never-retrieved report

2 participants