Skip to content

feat: report gate outcomes for retrieved memories - #439

Merged
abogartz merged 9 commits into
abogartz:mainfrom
WhollyMindless:feat/332-turn-outcomes
Nov 19, 2026
Merged

abogartz merged 9 commits into
abogartz:mainfrom
WhollyMindless:feat/332-turn-outcomes

Conversation

@WhollyMindless

@WhollyMindless WhollyMindless commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

Closes #332. Builds on e70d61f.

Each classified gate appends a receipt to the existing 2 MB rotating ledger. The chat report folds observations by row and turn and only credits gates recorded after retrieval. A failure after a ride is correlation. Equal timestamps with ambiguous order and rides without a usable later check remain unmeasured. Eviction candidates are displayed for human review.

Evidence at 3429370. The restarted-plugin fixture observes one prompt, one retrieved row and two classified gates: 1/1 recorded rides joined, one failed row/turn. This is a scripted hookup test. The fraction on the maintainer's store, live-seat outcome coverage, model benefit and paid-seat costs are unmeasured.

Repeated gate cost. bun bench/runners/gate-outcome-latency.ts times the awaited bash result hook (including evidence and ledger I/O) on an isolated local Windows store, Bun 1.4.4, no model; 20 measured samples and one warm-up per size. Elapsed median / p95:

Starting ledger Prior rewrite Append-only
Single prior receipt 2.85 / 3.19 ms 2.19 / 3.00 ms
1.99 MB 6.83 / 7.66 ms 1.99 / 2.48 ms
2.001 MB, forcing rotation 11.50 / 12.11 ms 6.57 / 7.28 ms

The samples measure uncontended hook latency on this machine. Rotation still rewrites the retained half. Tests cover concurrent ride and gate writes during rotation, reuse after real session eviction, failed writes and older summaries. The report shows a dropped-write count scoped to this process and store. Aggregate counts cover active rows across repositories; detail identifiers follow reader visibility, with at most 20 displayed. README and docs/use-ledger.md include examples and limitations.

Windows unit suite: 1,486 passed, 37 skipped, 0 failed. Typecheck and comment lint passed. The maintainer's intermittent unit failure did not reproduce in this run. Hosted jobs run on the new head.

abogartz and others added 3 commits November 18, 2026 17:32
…tatus line

POC work. Not for merge: the core promise is unverified end-to-end, and an
outcome signal built on an unproven loop is measuring the wrong thing. Kept
locally on 332-outcome-edge, not pushed.

recordHits takes an optional turn (peekTurns, never creates session state).
recordOutcome writes ev=turn_outcome into hits.logfmt from the existing gate
classify. joinUseWithOutcomes scores a ride only against a gate outcome on the
same (sid, turn); unjoinable rides count as rides and nothing else.
summarizeStore reports eviction candidates at >=5 rides with no clean turn.
Nothing supersedes anything.

Gate: 1067 unit + 30 e2e green.
@WhollyMindless

Copy link
Copy Markdown
Contributor Author

Author follow-up after testing the current head (951b17e). I found two correctness issues in the outcome join that I think we should address before merging.

  • A gate fails at 00:00:02, then memory_recall first retrieves a row at 00:00:03 on the same turn. With no subsequent gate, the report still gives that row fail_after=1. The join looks up the worst verdict for the entire turn. Comparing the ride only to the final summary timestamp would also misclassify fail → ride → pass. The summary needs enough ordering information to distinguish these cases.
  • Injecting and then explicitly recalling the same row on one turn before one failing gate gives used=2 and fail_after=2. The two sources can both write legitimately. The issue asks for turns with a failure, so the expected result is two rides and one failing turn. The report should account for unknown rides separately once verdict counts are per turn.

There is also an output-size concern: a synthetic store with 1,200 visible rows, each with one legacy ride and no measured outcome, produced 1,200 detail lines (about 80k characters). A bounded default candidate list with the omitted count would keep routine status calls usable.

@abogartz abogartz left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Verdict: REQUEST_CHANGES

The framing is right, and it is the hard part of #332. "Outcome unknown" instead of "clean", floors stated in the rendered line rather than a footnote, a FAIL treated as correlation that may never supersede alone, turnKey as a per-turn UUID so a reset session cannot join to its old turn numbers, peekTurn reading state without seeding the LRU, the block absent rather than zero when the caller did not look, EVICT_MIN_RIDES = 5 with the throttle reasoning attached — all of that is the discipline this feature needs.

The blockers are the properties the ledger's existing guarantees rest on, and the cost of the write path.

Verified on 951b17e against main at ebc083a: typecheck clean, lint clean, comment-lint clean over 101 added comment lines, e2e 35 pass / 0 fail, CI 4/4 green. Unit was 1496 pass / 21 skip, except that my first full run reported one failure I could not reproduce in nine further full runs and five targeted runs of hits, status, lock, injection-accounting and complete-store-reads. Unreproduced is not dismissed — if you have seen it, name it.


P1 — the ledger is no longer append-only

recordOutcome reads the whole file, splices out the previous (sid, turn, turnKey) line, and rewrites with writeAtomic. Two shipped documents state the opposite as a property:

  • README, "The store keeps score": "It is append-only, never ingested as a memory."
  • docs/use-ledger.md: "The ledger is <memory-root>/hits.logfmt: append-only, rotated at 2 MB."

Append-only is also what makes a concurrent telemetry write cheap and what makes the file safe to read while another session writes. Either update both documents to describe a ledger that rewrites its own outcome lines, or make the outcome append-only and fold the aggregate at read time — joinUseWithOutcomes already reduces per turn, so a reader can take the worst outcome across several lines for one turn and the calls/fails counters become derived rather than stored.

P1 — cost and lock contention on the gate path

src/capture/triggers.ts:217 awaits recordOutcome for every gate command. Each call reads the entire ledger and rewrites the entire ledger, under LOCK_WRITE — the same lock that memory writes take. A fix loop that runs bun test twenty times rewrites a file that grows to 2 MB, twenty times, and each rewrite queues against memory writes.

Nothing in the PR measures this, and bun run bench:write does not cover it: that bench measures the GATE-1/GATE-2 tree walk, not the ledger. Please add a measurement for the gate-command path with a ledger at rotation size, or take the write off the awaited path. If the answer is "gate commands are rare enough", say so with the number.

P1 — a lost outcome line is invisible

The since fileIdentity guard makes the rewrite fail when another writer moved the file, and the catch returns false with nothing recorded. Two sessions gating on one store will lose outcome lines, and joined silently shrinks. The code comments are honest that every count is a floor, but a floor nobody can observe is not a floor — a reader cannot tell "few turns ran a gate" from "the writes were dropped".

Emit one evidence line for a failed telemetry write, or carry a drop counter into the useOutcome block so the surface can print the difference between measured and lost.

P2 — useOutcome aggregates are machine-wide while details is reader-scoped

In summarizeStore, rowsMeasured, joined, clean, failAfter and evictCandidates accumulate for every active row, and only details passes through use.visible. That is defensible — aggregate STORE counts are machine-wide by decision (#213 B) and content surfaces follow reader visibility (#306) — but payload.ts does not say which side of that line the new block sits on, and no test pins it. The file's own header says "Callers own I/O and visibility policy; this summarizes exactly their rows", which now reads as inconsistent with the aggregates.

State the decision in the comment and add a two-repository test: a row visible only to the other repo must move the aggregate and must not appear in details.

P2 — three paths are untested

The new tests cover the join semantics well, including worst-outcome-wins, cross-session turn-number isolation, and "omitting the join leaves the block absent, not zero". Missing:

  • Rotation with outcome lines present. A 2 MB rotation can drop the outcome line a ride needs to join. Nothing pins what the surface says after that.
  • The rewrite racing a concurrent recordHits append. This is the exact case the since guard exists for, and the case that loses data today.
  • A session LRU eviction followed by a reused turn number. turnKey is what saves it, and the reset path is what would break it.

P2 — no documentation for a new user-visible surface

memory_status and /memory-report gain a line. docs/use-ledger.md and the README STORE sample are the two places a reader learns what those surfaces print, and neither is touched. The eviction-candidate concept especially needs a sentence: the phrase invites people to act on it, and the whole design says they should not.

P2 — the body carries no evidence

"Closes #332." is the entire description. The repository rule in the README's cost-claim list applies to PR bodies: name the n, the seat and the metric, and say what is not measured. Here that would be short: how many turns on the maintainer's store actually record an outcome, what share of rides join at all, and the explicit statement that a FAIL on the ride's own turn is correlation — which the code comments already make well and the body does not.

Nits

  • The rendered line is about 330 characters. The honesty belongs in the output; it could be two lines, which would also diff cleanly later.
  • Two vocabularies for one fact: the file stores outcome=clean|fail while TurnOutcome exposes PASS/FAIL, and readOutcomes maps between them. One name in both places removes a translation step.
  • crypto.randomUUID() relies on the global. That is fine under Bun and under the host, and worth an explicit node:crypto import for the library route where the plugin runs outside the plugin host.

@abogartz

Copy link
Copy Markdown
Owner

Re-review of d055510

Re-ran the branch. Typecheck clean, lint clean, 1519 tests / 0 fail. The new commit is a real correctness fix and it improves the surface: only gates that ran after the ride are counted, lastFail carries the ordering the join needs, same-millisecond ambiguity is refused rather than guessed, verdicts are once per row per turn, details is bounded to 20 with eviction candidates first, and the report line is shorter. The two new tests cover the ordering rule and the bound.

Keeping CHANGES_REQUESTED. What follows is what is left, not a re-litigation of the design.

Still open

1. The ledger is no longer append-only, and two shipped documents say it is.
recordOutcome reads the whole file, splices out the previous (sid, turn, turnKey) line and rewrites with writeAtomic. README ("It is append-only, never ingested as a memory") and docs/use-ledger.md ("append-only, rotated at 2 MB") both state the opposite. This is a documentation fix or a design change, and it is the cheapest of the four.

2. Cost and lock contention on the gate path is still unmeasured.
src/capture/triggers.ts:217 awaits recordOutcome for every gate command. Each call is a full read plus a full rewrite under LOCK_WRITE, the same lock memory writes take, against a file that grows to 2 MB. d055510 adds a little more work inside that same rewrite. A fix loop that runs bun test twenty times pays this twenty times. bun run bench:write does not cover it. Either add a measurement at rotation size, or take the write off the awaited path, or state the number that makes this acceptable.

3. A lost outcome line is still invisible.
The since fileIdentity guard makes the rewrite fail when another writer moved the file; the catch returns false and nothing is recorded. Two sessions gating on one store will drop outcome lines and joined will silently shrink. The comments are honest that the counts are floors — a reader cannot tell a floor from a failure to measure. One evidence line per failed telemetry write, or a drop counter in the useOutcome block.

4. useOutcome aggregates are machine-wide while details is reader-scoped, and nothing pins it.
summarizeStore still accumulates rowsMeasured, joined, clean, failAfter and evictCandidates over every active row and filters only details through use.visible. That is consistent with #213 B for STORE counts and #306 for content, but payload.ts does not say which side the new block sits on, the file's own header ("this summarizes exactly their rows") now reads as inconsistent, and no test pins it. A comment plus a two-repository test closes this one.

5. Three paths remain untested.
Rotation with outcome lines present (a 2 MB rotate can drop the outcome a ride needs to join), the rewrite racing a concurrent recordHits append, and a session LRU eviction followed by a reused turn number.

6. No documentation.
memory_status and /memory-report gained a line. docs/use-ledger.md and the README STORE sample are where a reader learns what those surfaces print. The eviction-candidate phrase in particular needs one sentence, because it invites action and the whole design says do not act on it.

One nit

joinUseWithOutcomes now keys turns with JSON.stringify([sid, turn, turnKey]). That is correct, and it quietly relies on JSON.stringify turning undefined into null so a turn-less ride can never match an outcome. A one-line comment would keep a later refactor from "simplifying" that back into a template string, which is what the previous version used.

Not blocking, but worth a line in the body

The body now states that counts are lower bounds and that a later gate failure is correlation only. The remaining gap is scale: how many turns on a real store record any outcome at all, and what share of rides join. Without that number a reader cannot tell whether the block is measuring the feature or the sampling hole.

@WhollyMindless

Copy link
Copy Markdown
Contributor Author

Ready for another look at 3429370. The gate path now appends one observation, and the reader folds those into distinct outcomes after a ride. The revised body includes near-rotation hook timings, the dropped-write counter's scope and the unmeasured live-store coverage. Added regression coverage for rotation under concurrent writes, actual session eviction/reuse, and two-repository report visibility. My Windows unit run completed with 1,486 passes and no failures.

@abogartz abogartz left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Verdict: APPROVE

Re-reviewed at 3429370. All four blockers from my review are resolved, and the three untested paths are now tested. What is left is nits.

The append-only property is back

recordOutcome now appends one ev=gate_outcome line per classified gate and nothing else — no read, no splice, no writeAtomic. The verdict aggregation moved into joinUseWithOutcomes, which folds per turn at read time. That is the second option I suggested, and it is the better one: README's "It is append-only" and docs/use-ledger.md's "append-only, rotated at 2 MB" are true again, and a concurrent telemetry writer no longer has to win a whole-file rewrite. readOutcomes accepts the legacy turn_outcome event alongside the new one, and the new test "legacy summaries retain only verdicts with known timing" pins that old mixed summaries contribute only where the ordering is recoverable.

The gate-path cost is measured, with a before-and-after

bench/runners/gate-outcome-latency.ts times the awaited afterTool hook at three ledger sizes, with a prior receipt on the same turn so the repeated test/fix case is the one being measured. I ran it on Apple Silicon, Bun 1.4.4, uncontended:

Starting ledger median p95
single prior receipt 0.63 ms 0.93 ms
1.99 MB 0.76 ms 1.13 ms
2.001 MB, forcing rotation 2.69 ms 3.42 ms

Same direction as your Windows table, and the append-only column beats the prior rewrite column at every size, which is the claim that mattered. Rotation is the only case that still costs anything, and the body says plainly that rotation still rewrites the retained half. The runner also verifies its own receipt — it throws if the line did not land or if rotation did not shrink the file — so the numbers cannot be produced by a run that silently did nothing.

A lost write is now visible

droppedOutcomes counts failed writes per store file, getDroppedOutcomeWrites() exposes it, and the report prints outcome writes dropped for this store by this process: N. The three tests cover counting per store rather than globally, and the report rendering one lost write. docs/use-ledger.md states the boundary correctly: it resets on restart and excludes other processes, so a zero does not establish complete history. That is the honest version of a floor.

The scoping split is documented and pinned

payload.ts now says counts cover active rows across all repositories and only details are reader-scoped, and the store-summary.ts header no longer claims the aggregates follow the caller's rows. The status test now rides two rows and asserts both halves of the rule: outcome-linked 2 rides over 2 rows in the aggregate, and not.toContain(ids[1]) in the details. That is the two-repository test I asked for.

The three untested paths are tested

concurrent gates and a hit survive rotation together, an evicted session can reuse turn one without joining its old ride, and failed outcome writes are counted only for the current store. The eviction test exercises a real session-LRU eviction rather than a hand-written state, which is what makes it worth having.

Docs

docs/use-ledger.md gained the outcome lines in the sample STORE block, a "What happens after retrieval" section stating that multiple rides on one turn can contribute one measured turn, and a paragraph on eviction candidates that says to inspect the row before retiring it and that the report makes no store changes. The README needs no change and correctly does not get one — line 159 defers the sample output to docs/use-ledger.md. One of your edits there is a real correction rather than an addition: the old sentence said credit "requires ≥2 shared terms with the query", and no code implements that; the throttle key is source|sid|ids, so the new wording about identical row sets is the accurate one.

The body now carries evidence

The restarted-plugin fixture states 1/1 recorded rides joined and one failed row/turn, and names what is not measured: the fraction on a real store, live-seat outcome coverage, model benefit, paid-seat cost. That is the gap I said a reader needed in order to tell the feature from the sampling hole.

Verification on this head: typecheck clean, lint clean, comment-lint clean over 105 added comment lines, 1524 unit pass / 21 skip / 0 fail, e2e 35 pass / 0 fail.

Nits, none blocking

  1. memory_status parses the whole ledger three times per call — readLedger() at src/tools/status-tool.ts:52, readRides() at :61, readOutcomes() at :62, each a full readLines pass. At rotation size that is three reads and three parses of up to 2 MB for one report. One pass returning all three shapes would remove it, and it is contained to a path a human invokes deliberately, so it is a cleanup rather than a defect.
  2. JSON.stringify([o.sid, o.turn, o.turnKey]) is correct and quietly relies on JSON.stringify turning undefined into null, so a turn-less ride can never match an outcome. A one-line comment would keep a later refactor from "simplifying" it back into a template string, which is what the previous version used.
  3. The new runner has no package.json script, while bench, bench:recall, bench:write and bench:availability each have one. Direct bun bench/runners/<name>.ts matches how bench/RESULTS.md documents its runner, so either is defensible — but docs/use-ledger.md does not name the command at all, so a reader of the limits paragraph cannot find how the numbers were produced. One line in the doc, or a bench:gate script.
  4. droppedOutcomes is a module-level Map keyed by the store file and never pruned. Bounded by the number of stores a process touches, so it is not a leak in practice; worth knowing it is the one piece of ledger state that lives only in memory.

@abogartz
abogartz merged commit 6bbbfcb into abogartz:main Nov 19, 2026
4 checks passed
@abogartz-opencode-self-improvement

Copy link
Copy Markdown

🎉 This PR is included in version 0.32.0 🎉

The release is available on:

Your semantic-release bot 📦🚀

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.

Record what happened after a memory rode: a row-to-outcome edge, so usefulness is measurable

2 participants