Skip to content

refactor: isolate host compatibility parsing - #170

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

abogartz merged 3 commits into
abogartz:mainfrom
WhollyMindless:refactor/host-compatibility

Conversation

@WhollyMindless

Copy link
Copy Markdown
Contributor

Plugin setup currently interprets tool contexts, session identity payloads, and token usage envelopes inline. Extract those reads into src/host.ts, with unknown inputs and typed normalized results, so setup can work with session IDs, directories, and usage counts directly.

The extraction preserves the current envelope precedence, missing-versus-zero usage distinction, and numeric coercion. Repository binding, synchronous ambient identity fallback, API lookup policy, timestamps, and status writes stay in setup. Capture trigger selection is unchanged.

Adds 34 compatibility tests for current and legacy envelopes, precedence, absent/invalid fields, and the unresolved session sentinel. Existing repository-isolation, service-host identity, capture, status, and recorded-event fidelity coverage remains in place.

Related to #168: this implements one small boundary from the proposal and leaves the broader organization decision open. It can be reviewed and merged independently of the scaffolding cleanup.

Validation:

  • bun run gate: typecheck and lint passed; existing lint warnings remain.
  • Unit tests: 654 passed, 12 skipped (the same skips as the baseline).
  • Real-host end-to-end tests: 11 passed.

@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 — equivalence proven differentially, not by eyeball; plus one pre-existing hole this refactor exposes (#176)

Reviewed at head d890334 (merge-base e32327a) on macOS + Bun 1.4.3, and on a local merge with current main 20bb57e (ad8f4ec). For a pure relocation PR the only question that matters is "does the new code read the same bytes the old code read", so I refused to review that by inspection alone.

1. Differential test: 2,655,865 envelopes, zero divergences

I transcribed the logic this PR deletes from e32327a (toolIds, the identity branch of the event loop, the usage branch, the session.context message scan, the session.get row read, and the capture sid read) and ran old-vs-new over a generated space of event/tool/row/message shapes — 8 variants each for sessionID/directory ("s", "", 123, null, true, 0, …), 8 for directories, nesting through data / data.info / properties.info / root location, six event types, plus the data:null / properties-only / wrapped-row shapes:

cases compared: 2655865
VERDICT: 0 divergences — extracted adapters behave exactly like the deleted inline code

The comparison was on decisions, not return values, so it tests what the plugin does: {bound, sid, call} for toolIds (including the ambient getCurrent() fallback), remember:<sid>@<dir> / api:<sid> / continue for identity, the full {sid,input,read,write} record for usage, and remember:<dir> / none for the two directory binds. Your three named preservation claims all hold under it: precedence (data before properties, info before data, nested before root location), missing-vs-zero (!tokens → skip, tokens:{} → {0,0,0}), and numeric coercion ("12" → 12, "bad" → 0).

One difference the extraction does introduce is invisible because of a type-set property: the old identity branch continued unconditionally, while the new caller only continues when sessionIdentityEvent returns a value, so a malformed identity event now falls through to the usage read. That is safe only because the two functions' event-type sets are disjoint — and test/host.test.ts:150-154 already pins exactly that ("unrelated event types do not bind identity or count usage"). Good instinct; I would keep it in mind the day a type is added to both lists.

2. The 34 tests actually have teeth (7/7 mutations killed)

A green 34-test file proves nothing on its own, so I mutated src/host.ts seven ways and re-ran test/host.test.ts each time:

mutation result
capture sid: sessionID root before data 1 fail
usage: drop the role !== "assistant" guard 1 fail
identity: drop session.moved from the type list 1 fail
toolIdentity: accept an empty sessionID 1 fail
row read: stop unwrapping {data: row} 3 fail
usage: Number(x) || 0 → x ?? 0 (kill coercion) 1 fail
messages: accept an empty directory 1 fail

I restored the file afterwards (git status clean, byte-identical to d890334). The count is exactly as advertised: 34 tests, and 12/14 of the file's cases are test.each tables that sweep the envelope space rather than a single happy path.

3. Gates, including against #158/#162/#165-moved main

tsc clean, biome exit 0, unit 678 pass / 12 skip / 0 fail, e2e 11 pass, exit 0. The arithmetic is the tell: main is 644, and 644 + 34 = 678 — every existing test still runs, and the only delta is the new file.

Lint is the rare refactor that pays rent: grouped per file+rule, the whole histogram delta is

-  15 src/index.ts lint/suspicious/noExplicitAny
+  10 src/index.ts lint/suspicious/noExplicitAny

Five as Record<string, any> casts gone, and src/host.ts contributes zero diagnostics of its own (it appears nowhere in the head histogram).

4. The boundary is drawn in the right place

What stays inline in src/index.ts — event.sessionID at :1335, :1356, :1434, :1442 — is the typed V2 hook payload (session.context / session.prompt / compaction), not the cross-version SSE/session.get stream. So host.ts is the compatibility layer for exactly the reads that have drifted between host versions, and there is no second copy of the legacy envelope logic left behind. captureTriggerFor(event: unknown) already took unknown, so captureTriggerFor(raw) at :1627 is honest rather than a cast. And the unresolved-sentinel policy stays where it belongs — the caller (index.ts:386 fromCtx && fromCtx !== "?"), with host.test.ts:18 pinning that the adapter passes "?" through instead of silently dropping it.


Finding (non-blocking, filed as #176)

session.moved has never been observed on a live host, and the fidelity net structurally cannot catch it. I checked all three identity names against both sources of truth:

name declared in @opencode/schema in test/fixtures/host-events.jsonl in the raw SSE captures of 2026-10-26
session.created yes yes, count 4 yes (1 / 1 / 2)
session.execution.started yes yes, count 4 yes (1 / 1 / 2)
session.moved yes no no (0 / 0 / 0)

test/event-fidelity.test.ts asserts observed only for CAPTURE_EVENT_TYPES; for everything else in src/*.ts the source scan (which does read src/host.ts:30-32, :73, :75) requires only declared. So session.moved sails through, while the same file's header calls this category "dead code — which is precisely #136". The consequence if it never fires is silent: workspace-change rebinding would not happen and nothing would say so. This is not introduced by your PR — the three-name check has been inline since the identity path landed — but this PR is what moves it into the file that reads as the proven compatibility boundary, which is the right moment to either record a session.moved line (stream GET /api/event across a workspace move and promote all three names to an observed IDENTITY_EVENT_TYPES), or list it in an explicitly-named unverified set the way message.updated already is in LEGACY_HOST_EVENTS. Details and options in #176.

Nit

host.test.ts:65-66 and :138 document the empty-string pass-through (sessionID: "" → identity with sessionID: "", directory: ""; captureSessionID returns "" in preference to a usable root value). That is exactly right for a behavior-preserving refactor — you pinned the quirk instead of quietly changing it — and my harness confirms old and new agree. It does mean rememberSessionDir(sid, "") and a capture keyed on "" remain reachable, so if we ever want that tightened it must be its own change with its own red test. No action needed here.

@abogartz
abogartz merged commit 58d2530 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