Skip to content

feat: add upstream Pi adapter for the shared host interface - #570

Merged
abogartz merged 26 commits into
abogartz:mainfrom
WhollyMindless:feat/554-pi-adapter
Nov 29, 2026
Merged

abogartz merged 26 commits into
abogartz:mainfrom
WhollyMindless:feat/554-pi-adapter

Conversation

@WhollyMindless

@WhollyMindless WhollyMindless commented Nov 28, 2026 •

Copy link
Copy Markdown
Contributor

This adds upstream Pi 1.7.0 support using the shared memory engine and host contract. Pi and oh-my-pi each own their adapter implementation; neither imports the other's helpers. Memories remain portable through the same configured store and project identity.

Related: #554, #571 and #578. The interface/reference harness (#560), OpenCode adapter (#564) and oh-my-pi/shared-runtime work (#561) have merged. This branch includes main 379b3d9b (release 0.39.0); its diff against main is now the Pi layer and the disclosed oh-my-pi usage-accounting correction.

Supported behavior

  • All fourteen shared memory tools, automatic system context, tool-result pulls, usage and native commands are bound to Pi's extension lifecycle.
  • Capture starts at agent_settled, after continuations and retries, using the active branch's original entries. Recent-window extraction preserves source cursor positions beyond turn 40 and after compaction.
  • Memory anchors are added to Pi's native prepared summary inputs; native retries, model/auth routing and read/modified-file bookkeeping remain intact across repeated compactions.
  • Failed shell results retain gate evidence but never receive pulls. Provider errors use allowlisted diagnostics, discarding raw provider prose and credentials.
  • Package discovery, the ./pi entry point, settings and installation instructions are included. Run Pi under Bun as shown at the beginning of README.pi.md.
  • This layer also excludes empty aborted/error assistant receipts from oh-my-pi usage accounting, preserving the reasoning split of real receipts and avoiding fabricated zero-use snapshots. This behavior differs from feat: add oh-my-pi adapter for the shared host interface #561 alone and now has oh-my-pi-specific lifecycle tests.
  • Adapter independence is documented in src/adapters/AGENTS.md and checked by import-boundary tests. The memory engine and common behavioral tests remain shared.

Capture completion (#578)

Pi's cooperative shutdown now awaits accepted capture work, local writes and terminal evidence without a cleanup timer. Generation remains background work during normal turns. The shared request owns its abort signal and captureRequestTimeoutMs deadline (default 60,000 ms); a hung request ends by timeout, and a late answer cannot write.

The real Pi print CLI awaits this shutdown handler. A provider response delayed 3.4 seconds now persists before exit; a never-answering provider is aborted by its configured request deadline and leaves request_timeout evidence. Queue overflow and dropped work also have attributed reasons.

Inherited #561 changes independently handle oh-my-pi's finite shutdown grant: background unanswered requests are cancelled on exit, answered writes are joined, and print/JSON requests are refused before generation unless their deadline fits the verified host allowance. The allowance comes from the installed SDK. Failed lifetime verification disables oh-my-pi capture with a safe diagnostic while retaining memory tools, commands, recall and injection; upstream Pi does not use this probe.

Validation

Windows, Bun 1.4.4, Pi 1.7.0 and oh-my-pi 19.2.1:

  • Current review coverage at d98a5d52: 2,104 unit tests passed, 34 skipped, zero failures; both native Pi shutdown scenarios pass. The new native-callback shutdown test holds an active answer, queues a second session, and requires both rows and completion receipts at handler return. Replacing await capture.settle() with void capture.settle() loses the queued row and fails this test; the unmodified test also passes ten consecutive runs. Four oh-my-pi lifecycle tests independently pin empty aborted/error receipts before and after real usage, plus the no-real-usage case. Root typecheck, changed-file lint/formatting and comment policy pass. Production code is unchanged by this delta.
  • Previous startup-degradation delta: 58 shared-runtime, boundary and lifetime tests passed on the combined branch; root and both SDK typechecks, lint/formatting and comment policy pass. The feat: add oh-my-pi adapter for the shared host interface #561 full unit suite passes 2,082 tests with 34 skips; all 39 oh-my-pi native scenarios pass across the full run and corrected false-grant fixture rerun.
  • Prior full combined-branch validation at 96a6cac: 2,093 unit tests passed, 34 skipped, zero failures.
  • Prior Pi SDK/CLI validation at 96a6cac: 40 scenarios passed across the full run and corrected packed-install test rerun. This delta changes no Pi adapter or shared-core implementation.
  • Root and both SDK typechecks, lint/formatting and comment policy pass.
  • The packed Pi CLI test observes the delayed provider, saves its row, and recalls it after restart. Its hung-provider case observes transport abort and persisted timeout evidence. Real SDK disposal separately covers both outcomes.
  • All nine shared runtime scenarios run through the reference host and each production adapter. A queue regression checks that closing does not acknowledge unfinished active work. Restoring a numeric cleanup bound fails a named structural contract test.
  • Existing native tests cover long sessions, repeated compaction file tracking, native retry/routing, failed-shell pulls, opaque-key error safety, commands, configuration, usage and scoped cross-harness sharing.
  • Real OpenCode capture checks: four pass; the Windows standalone persistence assertion fails identically on unchanged pre-fix ec07ba3 and this implementation under OpenCode 2.4.2. Cooperative-server capture passes. The assertion remains enabled; upstream tracking is anomalyco/opencode#66868.

Integration uses scripted local providers. The reviewer approved d98a5d52 after independently verifying the shutdown mutation. The main merge at d377dc14 changes only the package version from 0.38.2 to 0.39.0; all 12 selected shutdown, usage and boundary tests pass. CI is rerunning for the merge commit.

Limits

Forced process termination can still interrupt work. This does not change the broader single-shot product-policy question in #571; it fixes completion when capture is admitted. Live provider billing/authentication, later transformations and interactive rendering remain unverified. Usage is retained-history accounting.

This is not an npm release or a stable public adapter SDK. External packaging, version selection and trust remain separate design work.

@WhollyMindless
WhollyMindless marked this pull request as draft November 28, 2026 06:34
@WhollyMindless
WhollyMindless marked this pull request as ready for review November 28, 2026 16:47

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

In this setup, the pi and oh-my-pi adaptors share a lot of files. This brings up a few hygiene questions: 1. Should adaptors live in their own repos? If an external user wants to create their own, the current arch means they need to post a PR. Is that the wrong config? 2. If they DO live in this repo, they should have clear subfolders, and Opencode should have the same set of folders as the "external" harnesses. If this is truly agnostic, then it ought to be treated that way. PI and OhMYPi are just as much first class as Opencode, if this approach is going to work. So let's discuss pros/cons of moving all adaptors to their own repo (one repo for each) and then decide how to refactor this repo if we opt not to take that route.

@WhollyMindless

Copy link
Copy Markdown
Contributor Author

Note

🤖 gpt-6-astra responding on behalf of WhollyMindless

@abogartz We agree that OpenCode, Pi and oh-my-pi should be first-class consumers of the same interface, and that an external adapter author should not need to submit a PR here.

Our preference is to let the current architecture bake while we work through real Pi-family usage and bugs. That may expose interface changes we should make before promising external compatibility. We would like to avoid combining that stabilization with a repository split.

Could we take this in stages?

  1. Keep the maintained adapters here for now, with clear per-harness directories and the same contract and conformance obligations for OpenCode. Shared Pi-family helpers should have an explicit common home; neither Pi adapter should depend on the other adapter's private implementation.
  2. Once that usage has informed the interface, publish supported adapter entry points with an explicit interface version and compatibility policy, including reusable conformance-test utilities. The maintained adapters should use that same public surface.
  3. Provide a separate example repository that installs the published package and implements/tests an adapter without private source imports or local checkout links. A dsh adapter could be a useful real example, subject to checking its extension capabilities; a minimal reference adapter could establish the external integration first.

One repository keeps contract changes and cross-harness verification coordinated while the interface is settling. Separate repositories would offer independent ownership and release schedules, but also introduce compatibility and release coordination work. Publishing the interface and proving an external consumer would give us evidence for that decision without requiring every maintained adapter to move immediately.

Would that sequencing address your concern? In particular, what minimum directory/dependency cleanup would you want in the current Pi PRs before allowing that stabilization period? This is a proposed follow-up direction, not a claim that the current internal interface is already a supported external SDK.

@abogartz

Copy link
Copy Markdown
Owner

Note

🤖 gpt-6-astra responding on behalf of WhollyMindless

@abogartz We agree that OpenCode, Pi and oh-my-pi should be first-class consumers of the same interface, and that an external adapter author should not need to submit a PR here.

Our preference is to let the current architecture bake while we work through real Pi-family usage and bugs. That may expose interface changes we should make before promising external compatibility. We would like to avoid combining that stabilization with a repository split.

Could we take this in stages?

  1. Keep the maintained adapters here for now, with clear per-harness directories and the same contract and conformance obligations for OpenCode. Shared Pi-family helpers should have an explicit common home; neither Pi adapter should depend on the other adapter's private implementation.
  2. Once that usage has informed the interface, publish supported adapter entry points with an explicit interface version and compatibility policy, including reusable conformance-test utilities. The maintained adapters should use that same public surface.
  3. Provide a separate example repository that installs the published package and implements/tests an adapter without private source imports or local checkout links. A dsh adapter could be a useful real example, subject to checking its extension capabilities; a minimal reference adapter could establish the external integration first.

One repository keeps contract changes and cross-harness verification coordinated while the interface is settling. Separate repositories would offer independent ownership and release schedules, but also introduce compatibility and release coordination work. Publishing the interface and proving an external consumer would give us evidence for that decision without requiring every maintained adapter to move immediately.

Would that sequencing address your concern? In particular, what minimum directory/dependency cleanup would you want in the current Pi PRs before allowing that stabilization period? This is a proposed follow-up direction, not a claim that the current internal interface is already a supported external SDK.

@WhollyMindless yes, that works. For the current PRs, let's just make sure we isolate each harness adaptor so there's no comingling. In this case, DRY is not desired since we will plan to extract to external sources. This adds some complexity but in the long run allows us to scale to endless harnesses without us having to change things here.

@WhollyMindless

Copy link
Copy Markdown
Contributor Author

Note

🤖 gpt-6-astra responding on behalf of WhollyMindless

@abogartz Agreed. The current PRs now keep the maintained adapters in separate implementation directories, including OpenCode.

  • Removed the shared pi-family implementation. Pi and oh-my-pi each own their capture queue, transcript decoding, delivery, configuration and usage helpers.
  • Provider-error sanitization is local to each adapter too, with credential-redaction tests for both copies.
  • Added a boundary assertion covering the adapter source trees: relative imports/re-exports cannot reach another adapter, a shared adapter-helper directory, or the package entry forwarders. Local helper and shared host-contract imports remain allowed. The existing core-to-adapter rule remains in place.
  • The shared memory engine and behavioral conformance suite remain common; this intentionally duplicates adapter implementation, not memory policy.

This is the requested isolation cleanup, not an external SDK release or repository split. The reason for letting the interface bake is to avoid breaking external adapter authors while real usage still reveals necessary contract changes. External installation/version selection and the trust model for third-party executable adapters remain decisions to work out before publication; conformance is a compatibility check, not a security certification.

Pushed as #561 3d43139b and #570 bc730d92, synchronized with main 052ca880. Local Windows/Bun 1.4.4 verification: 2,078 unit tests passed, 34 skipped; 40 Pi and 36 oh-my-pi native integration tests passed. Root and both SDK typechecks, lint/formatting and comment policy pass. Injecting import "../oh-my-pi/completion-error.ts" into Pi's runtime makes the adapter-boundary assertion fail; restoring the source passes. New-head CI is pending. Please recheck the isolation requirement.

@ocsi-reviewer ocsi-reviewer Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Verdict

Request changes — one blocking contract violation, everything else non-blocking.

The blocking item is the new capture.settle(500) drain on the Pi-family shutdown path. It contradicts the amended design statement, it contradicts the adapter's own capability declaration, and the suite cannot catch a fix because the adapter's own test asserts the drain's time window rather than its outcome.

Reviewed across the moving head: findings were built on da69447, re-verified on d406e1f, and confirmed present unchanged at the final head ec07ba3 (the two newest commits touch only oh-my-pi workflow-test timing; settle(500) sits at src/adapters/pi/runtime.ts:87 and src/adapters/oh-my-pi/extension.ts:103 at the final head). Independent re-verification on this machine at d406e1f: unit 2089 pass / 0 fail / 23 skip, simulator 77/0, e2e against real OpenCode 62 pass / 701 expects, typecheck exit 0, lint exit 0, lint:comments clean; integration/pi and integration/oh-my-pi green. GitHub CI is fully green at the final head including the pi and oh-my-pi ubuntu/windows matrix jobs. The numbers in the PR body (2,067 pass / 34 skip) are stale relative to the current head but directionally right.

The blocker: a teardown-duration constant deciding whether a capture survives

Where.

  • src/adapters/pi/runtime.ts:87 — shutdown: if (!config.capture) await capture.settle(500);
  • src/adapters/oh-my-pi/extension.ts:103 — dispose: same expression.
  • src/adapters/{pi,oh-my-pi}/capture.ts:121-136 — settle(timeoutMs) is a Promise.race against setTimeout(resolve, timeoutMs): on timeout it returns without awaiting the in-flight pass and without cancelling or reporting it.
  • src/adapters/{pi,oh-my-pi}/capture.ts:152 — publish() resolves as a no-op when the queue holds 64 items, silently; the caller cannot distinguish "captured" from "dropped".

Why it blocks. The design statement is explicit: the cleanup path waits for the pass it started; the cleanup path has no duration constant; a bound that lives on the request belongs to the request and carries its own abort. settle(500) is exactly the forbidden shape — a number on the cleanup path, chosen to guess the host's patience instead of being derived from it.

The consequence is a decided-but-unrecorded loss. Measured on a real Pi CLI (1.7.0 under Bun 1.4.4, isolated PI_CODING_AGENT_DIR, isolated OPENCODE_MEMORY_DIR, scripted provider so no real credentials): with the capture provider answering 2 s after agent_settled, the process exits 0 in ~1.6 s and the row is never written; the same harness with a provider that answers inside the window writes the row and exits 0. A provider that never answers behaves the same way (10 requests observed, exit 0, no row). On the forfeited runs the evidence log carries the auto_capture_start line but no completion or dispose line — the operator has nothing to attribute the loss to. The difference between "remembered" and "lost" is invisible from outside. (Row-loss re-confirmed at d406e1f; the no-receipt store scan was made at da69447.)

The contract says this must not happen. src/adapters/pi/capabilities.ts declares shutdown: { cooperative: "awaited", forcedExit: "no-cleanup" } — "awaited" is the contract's word for "the host waits for me, so I may await the pass" — yet the runtime forfeits after 500 ms. The oh-my-pi declaration says "best-effort" and its comment states the host's two-second handler budget; the adapter then picks 500 ms, a third of the budget it just documented. #571 measured that Pi print mode awaits handlers with no timeout at all (3,000 ms honored exactly) and oh-my-pi 19.2.1 enforces 2,000 ms per handler. Both hosts therefore tolerate a longer (or unbounded, with a request-side abort) wait than the adapters grant themselves.

Why the suite cannot fix it. The test that owns this behavior asserts the forfeit as the contract. integration/pi/capture-shutdown-runner.ts:42 requires the whole dispose to finish under 1,900 ms (assert.ok(duration < 1900, ...)), and :47-48 requires that a capture whose provider has not answered by dispose leaves zero rows (scenario === "unanswered" ? [] : [fact]), with no assertion of any receipt for the lost pass. The oh-my-pi runner has the same two lines. An honest fix — await the pass, cancel it through the request's own abort — breaks the duration assertion and the empty-rows expectation simultaneously. The PR body itself says "the suite currently fails any real fix," and that is confirmed from the shipped test, not inferred. (No shipped test was edited to prove this; the claims are read directly from the assertions and reproduce.)

Mutation evidence (clean worktree at d406e1f, single-statement mutations, full unit suite each time, plus the owning integration file where the unit signal was silent):

Mutation Unit (2089 baseline) Killed by
settle(500) → settle(0) in Pi runtime 2089 pass, 0 fail only integration/pi/capture-shutdown.test.ts ("answered" case)
same in oh-my-pi extension 2089 pass, 0 fail only integration/oh-my-pi/capture-shutdown.test.ts
declared capability lied: pi compaction: "split" → "combined" 2089 pass, 0 fail full survivor — also passes integration/pi/compaction.test.ts (10/10); no install-time verification of declared capability vs host behavior exists
drop compaction capture hook 2089 pass, 0 fail only integration/pi/compaction.test.ts
capture reports success without running the pass (publish resolves done immediately) 2 fails unit tests added in the head-final refactor, and both integration shutdown scenarios hang to the 30 s kill
context injection made a no-op 3 fails runtime-contract tests (good)

At the intermediate head the "success without write" mutant was a unit survivor; the refactor between heads added tests that now catch it. The two findings that remain open: capability declarations are asserted as data but never verified against the host (the only full survivor), and the forfeited-capture case still has no terminal receipt — the tests that exercise the forfeit assert the absence of a row (see above), never the presence of an explanatory line.

What a fix looks like (aligns with the deferred core work, so it is small here): drop the constant from both shutdown paths; await the tracked pass to completion; let the model request own any timeout via its abort signal (the pass already receives controller.signal); emit a terminal evidence line (completion, or abandon-with-reason) for every started pass so a forfeit — if one remains anywhere — is attributable. For oh-my-pi, derive the bound from the declared host budget rather than a literal, or drop it and register with the host's own teardown.

Non-blocking findings

  1. Duplicated teardown code across the two adapters (by the new ownership design — but the defect doubles with it). At the intermediate head da69447 the per-adapter helper split left src/adapters/pi-family/ orphaned-but-shipped; the current head fixes that before this review posts, so it is withdrawn here. What remains is that settle, the queue cap and the drop semantics are now byte-equivalent logic in both src/adapters/pi/capture.ts and src/adapters/oh-my-pi/capture.ts (their delivery.ts and config.ts copies are byte-identical). Independent-adapter ownership is the maintainer's chosen answer to the repo-hygiene discussion, so this is not a finding against the structure — but it does mean the blocker fix and both shutdown runners must move together in every future change.
  2. Bun-only entry contradicts its own README. createPiMemory() throws unless typeof Bun !== "undefined", but the stock pi launcher is a node-exec'd shim, so pi -p after a plain pi install hits the throw. The documented workaround (bun .../dist/bundle/cli.js) is correct — I used it for all real-host runs — but the README should lead with it at the install snippet, not the integration notes.
  3. Silent queue-overflow drop. publish() returns success at queue length ≥ 64 with no reason line. Report the drop (and its reason) so the operator can tell saturation from a quiet session.
  4. PR body counts stale. Body says unit 2,067 pass / 34 skip and "29 runtime-contract files, 66 cases"; measured on the current head: 2,085 pass / 23 skip, 28 runtime-contract files / 65 cases. CI was still pending on three jobs (pi windows, oh-my-pi ubuntu/windows) when I checked; the ubuntu matrix rows that completed passed.
  5. The "known accepted" memory_status byte difference did not materialize. I diffed the delivered wire bytes (tool schemas, system channel, pull-channel tool results) between base bb60476 and the PR through real request captures, at both da69447 and the final head: all 26 tool schemas byte-identical — 14 memory tools (e.g. memory_remember 2116 B, d391790164264dd5) and 12 host tools — with normalized context and pull request digests matching (ctx tools 194c03fd9f8a4e4f, pull tools 74234e98afe7498f). That is good news, but it means the parity note describing a deliberate memory_status description difference now describes nothing.
  6. agent_before_settle claim needs a pointer. The claim that Pi print mode fires the full lifecycle including agent_before_settle rests on a linked architect comment; the token exists in the pinned SDK bundle (dist/bundle/chunks/chunk-Q6QBNASS.js) but I did not independently observe the adapter acting on it in print mode. Worth a one-line test reference where the claim appears.
  7. Contract coverage. Of ~57 declared members of the shared host contract, the Pi adapter exercises all but: LifecycleHandlers.error (never subscribed by either Pi-family adapter), SessionDirectories.fromTranscript/fromSession (the adapters pass directories: {}), MemoryHost.installCommands (opencode-only), and MemoryRuntime.capabilities is never read by the Pi runtime — which is how finding (contract-table) item 1's "survivor" capability mutation went unnoticed. Roughly 52/57, and the five gaps are exactly the "verified at install" surface.

State/surface matrix (real host unless noted)

State / surface Observation
Fresh store, fast capture row written, exit 0, completion + cost lines present (isolated dirs, scripted provider)
Existing store, restart recall across two CLI processes works (integration/pi/installation.test.ts, re-run green)
Second harness same store pi and OpenCode share one store root and repo scoping works as designed (shared-store e2e green)
Cross-tree store copy project rows invisible to a different repo path by design (repo-key scoping) — expected, not a defect
Provider never answers real-host scenario: exit 0 in ~1.6 s, no row, capture requests observed at the scripted provider — the pass ends by forfeit, no terminal receipt
Slow provider (2 s) measured loss: exit 0, no row, no completion line
Forced exit (SIGKILL mid-capture) documented "no-cleanup"; consistent with declaration
Compaction on the real CLI uncovered by real-host runs (SDK-driven, covered by driver tests)
Commands (/memory-report) in print mode not dispatched as commands by pi -p; turn proceeds as a normal message — matches host, noted for docs

Corrections to my own intermediate reports

  • One earlier integration/pi run showed 39 pass / 1 fail; that was my harness missing bun install --cwd integration/oh-my-pi, not the PR. Corrected runs: 40/40 and 36/36 at da69447; at d406e1f, integration/oh-my-pi 36/36 and integration/pi 48/48 (48 includes eight real-host scenario tests I added in the scratch worktree; the shipped forty pass within it).
  • One mid-review rerun at d406e1f showed mass failures (283 unit) and lint exit 1; that worktree had never had its root bun install run and the two lint errors were my own scratch probe files. The numbers quoted in this review come from the repaired, dependency-complete worktree.
  • An intermediate mutation battery ran against a copy-mid-refactor tree (pi-family paths); results there were superseded by the clean-head table above.

Overall: the mechanical hygiene is genuinely good — schema-first, byte-stable delivery, imports verified by a boundary test, per-adapter copies after the review discussion. The only thing standing between this and approval is the 500 ms constant deciding memory survival, and a test that currently punishes the honest fix.

@WhollyMindless

Copy link
Copy Markdown
Contributor Author

Note

🤖 GPT-6 responding on behalf of WhollyMindless

The blocking cleanup race is removed in 96a6cac7, inheriting the shared request-lifetime fix from #561 8d83b28d. Pi's cooperative shutdown awaits capture completion, local writes and terminal evidence. The request deadline—not a shutdown grace period—bounds a hung provider.

The packed, real Pi print CLI now saves a response delayed 3.4 seconds and recalls it after restart. A never-answering provider exits through its configured request deadline, with transport abort observed and request_timeout persisted. The SDK shutdown scenarios independently check those outcomes. Queue overflow is reported, and closing cannot acknowledge an unfinished active pass.

Verification: all 40 Pi native scenarios pass across the full run and corrected packed-install rerun; the full oh-my-pi suite passes 39. The combined unit suite passes 2,093 tests with 34 platform skips. Typechecks, lint/formatting and comment policy pass. A mutation restoring a numeric cleanup race fails the named contract assertion.

The existing OpenCode standalone Windows persistence check fails on both unchanged ec07ba3 and this implementation under OpenCode 2.4.2; cooperative-server capture passes. No assertion was removed. Both PR bodies now describe current behavior, counts and limits. Please re-review the blocker; new-head CI is pending.

@abogartz
abogartz dismissed their stale review November 29, 2026 00:58

Dismissing my request-changes: phase 1 is folder organization only, verified at d697c9c.

@abogartz

Copy link
Copy Markdown
Owner

Reviewer: abogartz (maintainer), dismissing own request-changes

Dismissing my own request-changes. My blocker here was about where adapter code lives, and we settled it as two phases: this phase organizes by folder only, and whether adapters move to separate repositories or a published versioned shared module is assessed later, once the host contract and a conformance kit exist. The later question stays open; it is no longer a gate on this pull request.

Verified at d697c9c rather than assumed:

  • src/adapters/ holds exactly one folder per harness — opencode 13 files, oh-my-pi 11, pi 11 — with no shared pi-family directory, and the only file at that level is AGENTS.md, which is instructions rather than implementation.
  • No adapter imports another adapter's internals, and that rule is pinned by a test (each adapter owns its implementation without cross-adapter imports in test/host/import-boundary.test.ts), not left to prose.
  • Each harness has its own entry point in the published exports: ./tui, ./oh-my-pi, ./pi, alongside the root.
  • Per-harness setup docs are present: README.pi.md and README.oh-my-pi.md.

Two notes for follow-up, neither a blocker on the folder question. Pi has a README but no docs/reference/pi.md counterpart to docs/reference/oh-my-pi.md, so the reference-doc layer is not yet at parity across the three harnesses; I will track that separately. And the CHANGES_REQUESTED from ocsi-reviewer[bot] on this PR still stands on its own terms — the capture-lifetime failure mode — which is being handled on #561 (the oh-my-pi adapter and the shared capture fix) that this branch inherits from, so do not read this dismissal as clearing that.

@ocsi-reviewer ocsi-reviewer Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Verdict: request changes

One ground, proven: the cleanup join added by 96a6cac has no fail-before test anywhere in the suite. Removing it is invisible to CI.

$ sed -i '' 's/    await capture.settle();/    void capture.settle();/' src/adapters/pi/runtime.ts
$ bun test ./integration/pi/capture-shutdown.test.ts   # run 1,2,3
 2 pass  0 fail      2 pass  0 fail      2 pass  0 fail
$ bun test ./test/host/ ./test/runtime/
 271 pass  0 fail
$ bun x tsc --noEmit -p tsconfig.json
 exit 0

src/adapters/pi/runtime.ts:87 is the entire fix — await capture.settle() in the session_shutdown handler. Replacing the await with a fire-and-forget (void) keeps every test green, so nothing in this PR would catch a future refactor that drops the join. The same runner does kill a neighbouring weakening (M2 below), so this is a gap in coverage of the join specifically, not a broken runner. Please add the pin that fails when the drain is not joined — the shape that works is a shutdown that returns before the held answer is written, asserting both the row and ev=auto_capture_finish land before the handler returns.

Everything else on the Pi side checks out. Details below.


1–2. The src/adapters/oh-my-pi/ divergence: yes, it changes reported numbers, and #561-alone is the wrong side

delivery.ts is a no-op at runtime. PiContent is structurally identical to OmpContent, the import was type-only, and the two files are now byte-identical to their src/adapters/pi/ twins. Verified by the byte table below; no emitted behaviour changes.

usage.ts is not a no-op. The guard fires on any assistant entry with stopReason aborted/error whose four usage counters are all present and sum to zero. Ran both blobs over identical histories (sessionUsage(ctx, sessionID), the exact call shape at src/adapters/oh-my-pi/extension.ts:122):

history #561 blob 76026c5 #570 blob d8d937a
aborted-empty, then real receipt {in:100,read:200,write:10,out:40,reasoningTokens:25} output:40, no reasoning output:15, reasoning:25
real receipt, then aborted-empty output:40, no reasoning output:15, reasoning:25
aborted-empty only input:0,read:0,write:0,output:0 undefined
error-zero, then real receipt without a split input:50,output:20 input:50,output:20 (same)
two real receipts, no abort input:107,output:43 input:107,output:43 (same)
all-zero endTurn, then real receipt input:100,output:40 input:100,output:40 (same)

Totals are preserved either way; the split is what differs. On #561 an aborted entry carrying no usage has no reasoningTokens key, so split flips to false and the final output stops subtracting reasoning — the reasoning split of the earlier real receipt is erased and billed as answer tokens. The last three rows show the guard is keyed on stopReason, not on zero usage, so a genuine zero-cost turn is still counted.

Which side is correct: #570, and the argument is not mine. test/host/pi.test.ts:77 asserts {input:11, output:5, reasoning:2} for a real receipt followed by an aborted all-zero assistant. Feeding that fixture to each blob:

561 => {"input":11,"read":3,"write":2,"output":7}
570 => {"input":11,"read":3,"write":2,"output":5,"reasoning":2}

#561's copy fails the assertion #570 wrote. So the third row above is the worse outcome too: #561 emits a fabricated all-zero usage snapshot where #570 emits no snapshot.

Two consequences to land with this PR, neither of which I think blocks it:

  • The guard now lives in the oh-my-pi adapter as well, because the two files are byte-identical copies, but its only pin is test/host/pi.test.ts. The oh-my-pi suite is byte-identical between the two heads (cffa7a8) and contains no all-zero aborted fixture — test/host/oh-my-pi-usage.test.ts:122 deliberately gives its aborted and error entries real usage. So the change is inert against every oh-my-pi fixture in this repo (its 28 tests pass here), and is untested for the harness that is now also carrying the code. Please add the oh-my-pi-side pin, since src/adapters/AGENTS.md says to fix copies independently and verify each affected adapter.
  • Worth a line in the PR description: this PR changes bytes the oh-my-pi adapter reports, on a path #561 does not test.

3. The merge resolution was correct — there was nothing to resolve

$ git log --oneline 30d3605..7263375 -- src/adapters/oh-my-pi/{delivery,usage}.ts
(no output)
$ git log --oneline 30d3605..998f5fd -- src/adapters/oh-my-pi/{delivery,usage}.ts
bc730d9 refactor(pi): give each adapter independent helper implementations
02247ed feat(pi): add upstream Pi adapter with shared family helpers

d697c9c's parents are 998f5fd (#570) and 7263375 (#561); their merge-base is 30d3605. #561 never touched either file after the fork point, so only one side changed and ort took it automatically. No #561-side change was silently discarded. The resolution should have taken, and did take, #570's side.

4. Duplication at d697c9c — bc730d9 satisfies the rule and did not reduce the cost

src/adapters/AGENTS.md is explicit: "Duplicate equivalent adapter helpers deliberately. DRY does not take precedence over adapter independence." No adapter imports another (grep for cross-adapter relative imports returns nothing; test/host/import-boundary.test.ts passes). So bc730d9 satisfies the rule — local types are required by it, not merely permitted.

Cost of phase-1 folder-only organization, re-measured at this head (ratio = multiset intersection of non-blank lines / smaller side):

shared file bytes byte-identical pi omp shared ratio
capabilities.ts 625 no 16 18 14 87.5%
capture.ts 6400 no 174 198 162 93.1%
completion-error.ts 867 YES 31 31 31 100%
completion.ts 2375 no 66 73 55 83.3%
config.ts 1444 YES 43 43 43 100%
delivery.ts 1708 YES 53 53 53 100%
extension.ts 16250 no 14 413 4 28.6%
transcript.ts 1195 YES 37 37 37 100%
usage.ts 2493 YES 76 76 76 100%

Pi-only: compaction.ts, runtime.ts. oh-my-pi-only: context.ts, lifetime.ts. Across the nine shared filenames, 475 of 510 non-blank lines (93.1%) appear in both folders, and the byte-identical set is still exactly five files — the same five as at the earlier head. The decoupling bought independence at zero duplication reduction: delivery.ts and usage.ts moved from "distinct files sharing a type" to "verbatim copies", and the oh-my-pi copy now declares a type named PiContent inside src/adapters/oh-my-pi/, which is a copy artifact rather than an independent implementation. That is an acceptable price under the current rule and consistent with "folders now, packaging later"; the number to carry into the packaging decision is that a bug on this surface costs two edits plus two verifications 93% of the time, and today the usage.ts bug landed with a pin on only one side.

5. Clause 8 graded against the Pi adapter specifically

clause-8 sentence grade evidence
Turn completion and teardown are events the core awaits pass src/adapters/pi/capture.ts:27 subscribes agent_settled; real-host evidence line: ev=plugin_load … capabilities="[agent_settled,bound completion,snapshot]" subscribed=[agent_settled]. Teardown is the session_shutdown handler at src/adapters/pi/runtime.ts:76.
No teardown duration may be encoded as a constant in core or an adapter pass grep over src/adapters/pi/ for setTimeout, Promise.race, Timeout, *MS and any bare numeric literal ≥100: zero hits. DRAIN_LIMIT_MS is absent from src/ entirely.
A Promise.race against a timer on the teardown path is a defect pass no Promise.race anywhere in src/adapters/pi/; cleanup is three sequential awaits (runtime.ts:86-88).
Cleanup awaits the pass; the handler returns only when the work is finished, failed or cancelled pass in code, unenforced runtime.ts:87 → capture.ts:137 awaits every active and queued done plus every compaction. This is the sentence the M1 finding attacks.
The only bound belongs to the request pass Pi declares neither lifetime nor requestGrantMs; the bound is core's per-pass createCaptureRequest(requestTimeoutMs, …) (src/capture/request.ts:28-44) — its own AbortController and setTimeout, default 60 000 ms via captureRequestTimeoutMs. settle() therefore terminates on answer, error or request timeout.
A host's cap is declared data, verified at install time pass, vacuously and correctly Pi has no handler budget to declare. src/host/capture-lifetime.ts:2: "Null means the host joins cooperative cleanup without a handler deadline."
Review consequence: a new numeric bound on the cleanup path is a finding pass none introduced.
Review consequence: an await that cannot be proven to terminate is a finding pass proven live, not by reading: the never-answering run finished exit=0 at the declared 1500 ms deadline and the provider observed the client abort.

One stale doc: docs/adr/0005-capture-teardown-phases.md:18 still describes a drain "bounded by DRAIN_LIMIT_MS (1000 ms)" and the parked/past-model two-phase teardown that clause 8 removed. No code constant, so it decides nothing — but it documents machinery that no longer exists.

6. Pi cannot silence memory the way #561 just fixed: it declares no lifetime at all

src/adapters/pi/ has no lifetime.ts and never mentions CaptureLifetime or verifyCaptureLifetime. createPiCapture() builds MemoryCaptureHost at src/adapters/pi/capture.ts:56-110 with subscribedEvents, capabilityLabels, turnEndEvents, readTranscript, defaultModel, generateText — and no lifetime key, no requestGrantMs key. The install-time verification is therefore a no-op:

src/runtime/setup.ts:52   if (host.capture.lifetime) await verifyCaptureLifetime(host.capture.lifetime);
src/runtime/setup.ts:53   if (host.capture.requestGrantMs && !host.capture.lifetime) throw …

Both guards are false for Pi, so no grant mismatch can throw, and a host that stops exporting a constant cannot stop the adapter registering. Pi is structurally immune, and correctly so: per the amendment's own measured ceilings, Pi awaits extension handlers with no deadline, so there is nothing to declare and pin.

The immunity is conditional on Pi staying silent, though — that is what M3 measures. Adding a lifetime whose verify() disagrees with the declaration makes the adapter fail to register outright (the wrong-grant run fails capture-shutdown.test.ts), because setupMemory awaits verifyCaptureLifetime with no try and src/adapters/pi/runtime.ts:163-166 rethrows, with no degraded fallback equivalent to src/adapters/oh-my-pi/extension.ts:55-68. If a later change gives Pi a declared grant, it re-imports the exact defect just fixed on the oh-my-pi side. Worth a comment on createPiCapture saying why the field is deliberately absent, so the next person does not "helpfully" add it.

7. Real-host Pi, isolated

Installed @earendil-works/pi-coding-agent 1.7.0 dist/bundle/cli.js under bun 1.4.4, loaded from this head via -e …/src/adapters/pi/extension.ts. HOME, all four XDG_* dirs, PI_CODING_AGENT_DIR, --agent-dir, --session-dir and OPENCODE_MEMORY_DIR all point under scratch; PI_OFFLINE=1; the model is a local fake OpenAI-compatible endpoint I control, so no host credentials are read. Repo identity comes from a scratch git repo whose origin is a scratch bare repo.

cd <scratch>/host/proj && HOME=<scratch>/host/home \
  XDG_CONFIG_HOME=… XDG_DATA_HOME=… XDG_STATE_HOME=… XDG_CACHE_HOME=… \
  OPENCODE_MEMORY_DIR=<scratch>/host/store PI_CODING_AGENT_DIR=<scratch>/host/agent \
  PI_OFFLINE=1 OPENAI_API_KEY=fake-key \
  bun <head>/integration/pi/node_modules/@earendil-works/pi-coding-agent/dist/bundle/cli.js \
    --agent-dir <scratch>/host/agent --session-dir <scratch>/host/sessions \
    -e <head>/src/adapters/pi/extension.ts --model fixture/scripted \
    --offline --mode json -p "<turn prose>"
scenario result
turn-end capture, provider answers at once exit=0 wall_ms=10411 rows=1
provider delayed 3400 ms exit=0 wall_ms=16127 rows=1, fake logged capture_delayed
provider never answers (captureRequestTimeoutMs:1500) exit=0 wall_ms=16660 rows=0, reason=capture_threw, provider logged the client abort
restart survival, same store run1 rows=1 → process exits → fresh session rows=1, and run2's outbound request bodies contain run1's fact verbatim

Row landed verbatim in the scratch store, attributed to the scratch repo:

scope=project ts=2026-11-29T06:28:38.583Z … content="The nightly archive job keeps exactly fourteen days of tarballs." … tags="auto-capture"
repoPath=/private/var/folders/…/r570/host/proj

The 3.4-second claim holds on the installed CLI. A delayed answer is saved, not lost. The never-answering case exits cleanly with a reason-tagged terminal receipt rather than silence — one honest caveat: through the real CLI the tag is reason=capture_threw error="Capture completion failed (provider_error)", whereas integration/pi/capture-shutdown-runner.ts:83 asserts reason=request_timeout through its own SDK-level driver. The store records a reason either way, so nothing vanishes, but the CLI path labels the same event more coarsely than the runner claims. ~/.pi and ~/.config/opencode/memory were not written by these runs; I ran no real omp, so nothing was appended to ~/.omp/logs/.

8. The Pi integration runners do not pin abandonment

integration/pi/capture-shutdown.test.ts asserts exactly three things per scenario: child exit === 0, stdout contains CAPTURE-SHUTDOWN-PASS <scenario>, stderr lacks timed out. No duration assertion survives — the old duration < 1900 form is gone and nothing measures elapsed time at all. The only timers are harness watchdogs (30 s kill in the test, 5 s abort-observation in the runner) that fail on slowness, never on speed.

integration/pi/capture-shutdown-runner.ts requires the slow answer to be saved: rows must equal [fact] with tags containing auto-capture for answered (lines 69-73), plus ev=auto_capture_finish reason=completed harness=pi. For unanswered it expects [] rows and reason=request_timeout plus proof the provider observed the abort — a reason-tagged receipt, not silence. A better implementation (always await, never race) produces exactly those outcomes and passes; the only implementations that fail are ones that drop an answered pass or that cannot terminate. bun test ./integration/pi/capture-shutdown.test.ts → 2 pass 0 fail [6.08s]; full bun run test:pi → 40 pass 0 fail (after bun install --cwd integration/pi --frozen-lockfile, plus integration/oh-my-pi for the cross-harness test). These three files (session.ts, capture-shutdown-runner.ts, capture-shutdown.test.ts) exist only on this head — absent at 7263375, added by 02247ed.

9. Pi-side mutations

# mutation caught by result
M1 void capture.settle() — drop the join (runtime.ts:87) nothing 2/2 integration ×3 runs, 271/271 unit, tsc clean → SURVIVES
M2 settle() returns immediately (capture.ts:137) integration only capture-shutdown.test.ts fails; unit silent
M3 Pi declares a wrong grant (lifetime + disagreeing verify()) integration only capture-shutdown.test.ts fails — adapter never registers
M4 drop the zero-usage abort guard (pi/usage.ts) unit only test/host/pi.test.ts fails; would not be caught by the Pi integration runners

M2 and M3 failing the same runner while M1 passes it is the point: the runner exercises the drain's effect but not the await, so the fix that is the subject of this PR is the one thing it cannot see. Worktree restored clean after each mutation.

10. Docs and packaging

README.pi.md exists; docs/reference/pi.md does not — docs/reference/ holds flags.md, install.md, oh-my-pi.md, options.md, surfaces.md, troubleshooting.md. Nothing links the missing file: grep -rIn "docs/reference/pi\.md" . outside node_modules returns 0 matches, so this is a plain gap rather than a dead link, and test/host/doc-links.test.ts passes 6/6. Asymmetry with oh-my-pi (which has both) stands as follow-up work.

package.json entry points all resolve at this head: . → index.ts, ./tui, ./oh-my-pi → src/adapters/oh-my-pi/extension.ts, ./pi → src/adapters/pi/extension.ts; pi.extensions → ./src/adapters/pi/extension.ts; omp.extensions → ./src/adapters/oh-my-pi/extension.ts; all exists=True. test:pi is wired in package.json and in .github/workflows/ci.yml:165.


Not verified

  • M1's real-host consequence. I did not get a trustworthy real-host measurement under void capture.settle() — that run finished in 1145 ms, far too fast to have completed a turn, so its rows=0 is a harness artifact and I am discarding it. What I proved is only that removing the join passes the suite.
  • Whether the aborted-all-zero assistant entry is reachable in a real oh-my-pi install. Every fixture here models oh-my-pi aborts as carrying real usage; the divergence is demonstrated on scripted histories, not on a captured real oh-my-pi history.
  • reason=capture_threw versus reason=request_timeout on the CLI never-answers path: observed, not root-caused. I did not determine whether the CLI's provider surfaces an abort differently from the runner's proxy, or whether a different CLI transport (non-streaming) would tag it correctly.
  • I ran no real omp and made no attempt to reproduce the oh-my-pi delivered-byte capture; that is the concurrent review's scope, and src/runtime/capture.ts, src/capture/request.ts, src/host/capture-lifetime.ts, src/host/runtime.ts are byte-identical between the two heads (0909afb, f8afd1d, a3e6d83, 19bdbf4), so nothing there needed re-measurement.
  • Full bun run test and bun run lint were not run — out of scope per the split. I ran the Pi unit files (28/28), test/host + test/runtime (271/271), doc-links, import-boundary, and the complete test:pi (40/40).

Rescan before posting: #570 head still d697c9c, #561 head still 7263375, live seat untouched at main 052ca88 and clean.

@WhollyMindless

Copy link
Copy Markdown
Contributor Author

Note

🤖 gpt-6-astra responding on behalf of WhollyMindless

The cleanup-join coverage request is addressed in d98a5d52 without changing production code.

test/host/pi-shutdown.test.ts drives the native extension callbacks with the real memory runtime. It holds one capture's answer, queues a second session, starts shutdown, then releases the answer. At handler return it requires both stored facts and both auto_capture_finish reason=completed receipts, with no shutdown-dropped work. Replacing await capture.settle() with your exact void capture.settle() mutation fails: the queued fact is missing. The unchanged test passes ten consecutive runs. A single active pass is also joined by core; the adapter join is load-bearing for accepted work still in its queue.

Four new oh-my-pi lifecycle tests cover empty aborted/error receipts before and after real usage, plus an empty-only history. Disabling that adapter's zero-usage guard fails all four. The PR description now discloses this usage-accounting difference from #561 alone.

Validation: 2,104 unit tests passed, 34 skipped, zero failures; both native Pi shutdown scenarios pass. Root typecheck, changed-file lint/formatting and comment policy pass. The tests are also carried into the downstream public-API experiment #601 (f3f1de21), where all 24 selected regression/boundary/version tests and typecheck pass. New-head CI is pending.

One documentation clarification: ADR 0005 already begins with “Status: superseded” and describes the current timer-free behavior before its historical decision. The old bound remains only in that historical section.

Please re-review the join coverage.

@ocsi-reviewer ocsi-reviewer Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🤖 GPT-6 responding on behalf of ocsi-reviewer[bot]

Re-review at the new head. The blocker from the previous review on this pull request is cleared, and I verified it myself rather than accepting the reply.

The prior finding was that the teardown join had no fail-before test: deleting await capture.settle() left every suite green. That is no longer true. test/host/pi-shutdown.test.ts drives the native extension callbacks with the real runtime, holds one capture's answer while a second session's work is queued, starts shutdown, then releases — and the mutation dies on it.

My own runs, on this head, isolated store, unmodified unless stated:

Configuration Result
New shutdown and usage tests, unmodified 9 pass, 0 fail
void capture.settle() — the join deleted 1 fail — killed
Core in-flight drain disabled, adapter join intact 1 pass
Both guards disabled 1 fail — killed
New oh-my-pi usage tests, unmodified 8 pass, 0 fail

The middle row is the interesting one and it agrees with the author's characterization. The two guards are not equal: for work still sitting in the adapter queue the join is what saves it, while for a single active pass the core drain also suffices. That is why my earlier measurement on the integration runner alone was misleading — that runner exercises one active pass, where either guard hides the other, so removing one looks invisible. A runner that queues a second session is what makes the join observable, and that is what this commit adds. No production code changed, which is the correct shape for a coverage gap.

The usage-accounting concern from the previous review is also addressed on this branch by the new oh-my-pi usage tests, including the controls that the guard keys on the stop reason rather than on zero usage alone. One thing does not follow from that, and it is not a defect in this pull request: the guard itself and the tests that pin it land only when this branch lands, and the branch that must merge first still ships the oh-my-pi usage reader without them and without any test that fails. Whether that is reachable on a real install of that host is still unestablished, so it is tracked as latent with the reachability question stated, not as a measured loss.

Non-blocking follow-ups, filed rather than held here: the teardown architecture record still describes a drain bounded by a deleted constant in a file this pull request already edits, the status tool's parity row describes a difference that does not exist because the implementation is byte-identical across deliveries, and the oh-my-pi readme still ships a pull-request link in reader-facing prose. None of these affect what a user receives.

Approval here is a code verdict only. This branch contains the lower host-contract branch, so landing order still matters and merging is the maintainer's call.

@abogartz
abogartz merged commit e1ae514 into abogartz:main Nov 29, 2026
9 checks passed
@abogartz-opencode-self-improvement

Copy link
Copy Markdown

🎉 This PR is included in version 0.40.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.

2 participants