Repository navigation
refactor: isolate injection epoch policy - #172
Conversation
abogartz
left a comment
There was a problem hiding this comment.
Approved — the "no change to injected bytes" claim verified, not taken on trust
A refactor that claims to move policy without changing behavior is the one kind of PR whose central claim can be checked mechanically, so I checked it rather than reading it. Re-verified against 2aabf9d0e17ea8dffa23baae2bd0c23e58566075.
The move is a move
- Every moved function is byte-identical after whitespace normalization:
statsFor,buildPayload,injectableRows,buildMemorySection,refreshEpoch. The only edit inside them isnoteHits("inject", sid, …)→noteHits(sid, …), withindex.tsbinding"inject"in the injected closure — so the use-ledger source label survives. That single line is the whole semantic surface of the extraction, and it is the one I'd have expected to break. - No call site was dropped. Reference counts reconcile against base exactly:
epochRecomputes3→3,latestPrompt7→7,epoch.get/has/set/delete3/1/3/2→same,sessionStats4→4,statsFor4→4. All threesessions.touch()sites are unchanged, and theevent.subscribemeasured-usage listener block is identical. - The
compactionandprompthooks differ from base only by the expected one-line substitutions (sessions.invalidate(...),await sessions.prompt(...)).
Two independent measurements, both byte-identical
- I scripted one session against both trees — first epoch → repeat → self-authored write → foreign write → compaction — and dumped normalized byte hashes plus bust decisions. Identical on
mainand on the merged tree, and the probe has teeth: the self-write produces no bust (the #165 riding-bytes rule survives the move), the foreign write produces bust #2store_changedwith the section going 742→987 chars. bench/inject-cost.tsoutput is byte-identical between the two trees (arm D still 12.3% fewer characters than naive).
Merge safety against current main, checked rather than assumed
This branch is 13 commits behind main and rewrites the same file #158 rewrote, so "GitHub says MERGEABLE" was not enough. The base lines #172 removes (1069–1402) and the lines #158 edited (486–664) have zero overlap, so the auto-merge cannot resurrect a pre-#158 copy of any code. I'll add that my first pass at this check reported zero overlap for the wrong reason — my parser didn't advance the base counter past deletions, so it saw 17 removed lines where there are 277. Fixed and re-run before drawing the conclusion; noting it because "the script said so" is exactly how a false green gets through.
Also checked
- The new module ships:
package.jsonfilesincludessrc, and the tarball containspackage/src/injection-epochs.ts. A source file that isn't packaged would break every user at setup, and nothing in CI would notice. - Merged tree (main + this branch): 647 pass / 12 skip / 0 fail; our cache-injection pins (
epoch,status,injection-framing,gated-injection,frontier) 97 pass / 0 fail;tsc --noEmitclean;biome lintclean on both new files. - Your three lifecycle tests do pass on
mainas well as on the branch, as the body says — genuine characterization tests rather than tests written to fit the new shape. - All four sibling PRs (#172 + #170 + #171 + #169) stack onto current
mainwith no conflicts and run 681 pass / 12 skip / 0 fail, which matches your combined number.
Two nits, neither worth holding the merge
measuredTurnsis injected as a mutablePick<Map, "get" | "delete">that the controller deletes from during eviction. Behaviorally identical to before, but the coupling is inverted: the epoch controller reaches into a mapindex.tsowns. AnonEvict(sid)callback would make the dependency one-directional. Not worth churn now — flagging it only so the shape is a decision rather than an accident.deliver's no-epoch fallback passes{ sessionID: sid }where base passed{ sessionID: event?.sessionID }. I went looking for a difference and found none:systemDigestguards withtypeof … === "string", so a non-string takes the same branch asundefined. Recorded here so the next reader doesn't spend the ten minutes I did.
On the extraction itself
This is the third index.ts split after #170 and #171, and it's the one I'd most have wanted: the epoch policy is the subtlest code in the repo and it carries the reasoning for #127, #162 and #165 in its comments, which read much better in a 313-line module behind a four-field interface than they did inside setup(). It is also the lowest-risk of the six currently open, precisely because a pure move is checkable in a way a behavior change isn't. test/epoch.test.ts stays where it is and keeps pinning the behavior across the boundary.
abogartz
left a comment
There was a problem hiding this comment.
APPROVE — moved-not-changed proven mechanically; the whole four-PR stack integrates at 681 green
Reviewed at head 80d7200. git merge-base --is-ancestor origin/main pr-172-r → YES, so this branch is current with 20bb57e (v0.14.18) and there is no merge risk to evaluate — the head tree is the merged tree.
For an extraction of the cache-critical path I was not willing to take "no change to injected bytes or invalidation policy" on reading, so I attacked it three ways.
1. Moved, not changed — line-level proof
I compared the 274 lines this PR deletes from src/index.ts against the 306 lines of src/injection-epochs.ts, trimmed and set-differenced both directions.
- 20 deleted lines have no verbatim counterpart in the module. All 20 are accounted for: 5 import-name lines, 4 reworded comments, and the 6 deliberate seam changes —
buildPayload→sessions.buildPayload,noteHits("inject", …)→ thenoteHits(sid, rows, query)adapter atindex.ts:1307, the fourevent?.system?.push?.(…)sites → the injectedpush(text),latestPrompt.set→sessions.prompt, andepoch.delete + latestPrompt.delete→sessions.invalidate. - 33 module lines have no counterpart in main's
index.ts. They are: theInjectionEpochOptionsinterface, the factory signature and its destructuring (frontierBudget: openBudget), reworded comments, thedeliverindirection, and the returned surface (touch/prompt/deliver/invalidate/buildPayload/flushStatus).
That means no new conditional, no new arithmetic, no new ordering anywhere in the moved policy — including the three subtle ones: the cached?.version === version pre-check, the cached.prefix === built.prefix ride, and the mine.has(m.ts) && !cached.ownRows.has(m.ts) counterfactual with its cached.prompt re-score.
2. The one place the code is genuinely not identical — checked, and inert
The no-epoch fallback digest changed from systemDigest({ sessionID: event?.sessionID }, …) to systemDigest({ sessionID: sid }, …) (module :276). Those differ only if the host sends a non-string sessionID, because the hook computes sid as typeof event?.sessionID === "string" ? … : undefined. I followed both values through:
systemDigest(src/inject.ts:283-288) normalises any non-string to"?", so old passes"?"and new passes"?";readerFromSid(src/memory.ts:705-709) maps"?",""andundefinedall toreaderForAmbient();- the
sidis also thefrontierInjectedSessionskey (inject.ts:322-323), and both paths yield the same key, so frontier de-duplication cannot fork.
Every case is identical. Worth saying explicitly because "it's just a variable rename" is how a fallback silently changes identity scope, and this is the #127 file.
3. Mutation probe of the new lifecycle tests — 5 of 7 killed, 2 survivors (pre-existing, filed as #177)
The new tests drive real hooks through loadPlugin rather than poking the controller, which is the right level. I mutated the controller and re-ran:
| mutation | result |
|---|---|
invalidate keeps latestPrompt |
1 fail — killed |
eviction keeps measuredTurns (the body's "measurements are evicted with the epoch state") |
1 fail — killed |
touch becomes a no-op |
2 fail — killed |
drop the storeVersion cheap pre-check |
2 fail — killed |
epoch stores prompt: "" (breaks the #165 re-score counterfactual) |
2 fail — killed |
delete the injection-side noteHits credit |
full suite green |
abstained counted unconditionally |
full suite green |
I did not stop there: both survivors reproduce on main's inline code (644 pass / 0 fail each), so the move did not weaken anything — the two invariants were already untested, and #172 merely inherits them into a new file with a new test next door. Details, why each matters (neverRetrieved/useSignals ranking; the user-visible abstained line at status.ts:369), and suggested pins are in #177. Please don't read that as work for this PR.
The kill list is also what makes the file's own claims checkable: epoch-lifecycle.test.ts:113 (resumed?.measured is null after eviction) is the reason the eviction sentence in your body is a verified fact rather than intent, and the session.execution.started + getCalls barrier at :104-105 to synchronise on the event queue is a strictly better discipline than a sleep.
4. Gates, and the four-PR integration you predicted
On head: tsc clean; biome histogram identical to main (410 warnings / 119 infos, per-file-per-rule diff empty) while checking two more files — so the new module and the lifecycle tests really do lint clean, as claimed. Unit 647 pass / 12 skip / 0 fail = main's 644 plus exactly your 3 new tests; e2e 11 pass / 0 fail; bun run gate exit 0.
Because you listed a trial merge with the other reviewable PRs, I did it for real rather than sampling: main → #169 → #170 → #171 → #172 = ff7b974, four clean merges, full gate 681 pass / 12 skip / 0 fail, e2e 11 pass, exit 0. That is your 681 exactly (644 + 34 + 3), and it means the merge order is not a dependency puzzle.
Nit — the isolated validation number in the body drifted behind the pushed tree
"623 unit tests pass, 12 skipped" is 620 (the v0.14.17 base, the same number #169 and #171 measured there) + 3, i.e. captured before 80d7200 merged main in. The pushed tree measures 647 (main itself is 644). Your combined figure is right — 681 = 644 + 34 (#170) + 3 — which tells me the combined run really was against current main and only the isolated number is stale. Worth a one-line edit so the next reader doesn't diff 623 against 647 and wonder whether tests went missing; I ran the isolated head, so the current tree is independently verified green either way.
|
🎉 This PR is included in version 0.14.19 🎉 The release is available on: Your semantic-release bot 📦🚀 |
Plugin setup currently keeps injection epochs, prompt state, refresh decisions, and their status snapshots in the same closure as host parsing, tools, and capture. Extract that policy into a per-setup
createInjectionEpochscontroller insrc/injection-epochs.ts, leaving setup to bind identity and wire prompt, context, compaction, and status calls.The controller owns frozen bytes, prompt state, counters, and LRU eviction. Budgets, measured-usage access, and the injection-hit callback are explicit inputs. The existing host listener continues to parse and record usage; its measurements are evicted with the epoch state. Capture scheduling and process-shared cooldowns stay in setup. No change to injected bytes, invalidation policy, tool responses, or persistence is intended.
Related to #168: this implements only its suggested epoch boundary and leaves the broader proposal open. #170 already handles host compatibility parsing; this PR preserves that listener wiring and can merge independently. #158's tool fixes, #169's cleanup, and #171's outcome typing are also separate.
Validation (Windows, Bun 1.4.4):
bun run gate: typecheck and lint pass; 623 unit tests pass, 12 skipped; 11 real-host end-to-end tests pass. Existing lint warnings remain; the new module and lifecycle tests lint cleanly.0a6999e), chore: remove stale scaffolding and correct comments #169 (913adc0), refactor: isolate host compatibility parsing #170 (d890334), and refactor: express gate outcomes as a discriminated union #171 (a3a17ae) succeeds without conflicts. The combined full gate passes: 681 unit tests, 12 skipped, 11 end-to-end tests, typecheck, and lint. The trial merge was aborted; this PR contains only the three-file epoch extraction on main.This is an optional proposal. Please feel free to close it without merging if this extraction does not fit your preferred organization or plans for the project.