Skip to content

refactor: isolate injection epoch policy - #172

Merged
abogartz merged 3 commits into
abogartz:mainfrom
WhollyMindless:refactor/injection-epochs
Oct 29, 2026
Merged

abogartz merged 3 commits into
abogartz:mainfrom
WhollyMindless:refactor/injection-epochs

Conversation

@WhollyMindless

Copy link
Copy Markdown
Contributor

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 createInjectionEpochs controller in src/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):

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.

@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.

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 is noteHits("inject", sid, …) → noteHits(sid, …), with index.ts binding "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: epochRecomputes 3→3, latestPrompt 7→7, epoch.get/has/set/delete 3/1/3/2→same, sessionStats 4→4, statsFor 4→4. All three sessions.touch() sites are unchanged, and the event.subscribe measured-usage listener block is identical.
  • The compaction and prompt hooks 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 main and 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 #2 store_changed with the section going 742→987 chars.
  • bench/inject-cost.ts output 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.json files includes src, and the tarball contains package/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 --noEmit clean; biome lint clean on both new files.
  • Your three lifecycle tests do pass on main as 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 main with no conflicts and run 681 pass / 12 skip / 0 fail, which matches your combined number.

Two nits, neither worth holding the merge

  1. measuredTurns is injected as a mutable Pick<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 map index.ts owns. An onEvict(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.
  2. deliver's no-epoch fallback passes { sessionID: sid } where base passed { sessionID: event?.sessionID }. I went looking for a difference and found none: systemDigest guards with typeof … === "string", so a non-string takes the same branch as undefined. 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 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.

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", …) → the noteHits(sid, rows, query) adapter at index.ts:1307, the four event?.system?.push?.(…) sites → the injected push(text), latestPrompt.set → sessions.prompt, and epoch.delete + latestPrompt.delete → sessions.invalidate.
  • 33 module lines have no counterpart in main's index.ts. They are: the InjectionEpochOptions interface, the factory signature and its destructuring (frontierBudget: openBudget), reworded comments, the deliver indirection, 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 "?", "" and undefined all to readerForAmbient();
  • the sid is also the frontierInjectedSessions key (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.

@abogartz
abogartz merged commit d1d8314 into abogartz:main Oct 29, 2026
4 checks passed
@abogartz-opencode-self-improvement

Copy link
Copy Markdown

🎉 This PR is included in version 0.14.19 🎉

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.

2 participants