Skip to content

fix: capture gate authority before asynchronous work - #186

Merged
abogartz merged 7 commits into
abogartz:mainfrom
WhollyMindless:fix/gate-reader
Oct 30, 2026
Merged

abogartz merged 7 commits into
abogartz:mainfrom
WhollyMindless:fix/gate-reader

Conversation

@WhollyMindless

@WhollyMindless WhollyMindless commented Oct 29, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #183.

A session move during gate_start could make an update inspect another repository and return its competing decision ID in a superseded_overlap hint. GateContext now carries the operation reader; direct callers resolve it synchronously before the gate's first await. Updates retain the reader used to select their target. The append owner is also captured so the gate cannot validate one repository and then stamp a different one.

Capture snapshots authority before context/model awaits, import before file processing, and init before Git probing (including prior-stamp lookup). Named unresolved callers remain global-only readers with no implicit write owner; unnamed callers retain ambient resolution at entry. Explicit candidate ownership and explicit merge-review authorization are unchanged. Audit routing is still session-based; this is not a redesign of evidence attribution.

Validation on Windows / Bun 1.4.4: the blocked-overlap disclosure and moved write-owner regressions both fail against main and pass here. All 14 focused tests pass. Two existing move cases now legitimately complete in the original repository; their assertions verify replacement ownership and no retirement into the foreign survivor. Full gate: typecheck, lint, 709 unit tests (12 existing skips), 11 real-host end-to-end tests.

The deterministic session.moved harness is not a claim that this event has been observed on a live host (#176 remains separate). Please feel free to decline or close this implementation if you prefer another scope or design.
Review follow-up (cfb6023): an unscoped ambient gate write deliberately stores explicit repo=global. Previously it stored no repo field. Visibility inside the store is unchanged, but the shape and portability semantics differ: the row is indistinguishable from a deliberately global row, and export/import keeps it global rather than adopting the importing repository. Leaving repo undefined would let appendMemory resolve ambient ownership again after awaits. The code comment records this choice; two new regressions pin the stamp with and without an ambient scope change during gate_start, then verify real export/import preserves global ownership. Both fail when the gate implementation is reverted to pre-fix dba2a7a. This follow-up changes comments and tests only; the approved runtime implementation is unchanged.

GateContext now documents named/resolved, named/unbound, and ambient reader contracts in code. The separate evidence-scope attribution boundary is tracked in #188, as requested in review; #121's missing-sid fallback remains separate. Local full gate passes on cfb6023; all four hosted checks now pass on the subsequent comment-only head 72edbb3, including Windows.

CI status: all four checks pass on 72edbb3. The previous Windows capture-wait timeout did not recur; executable code and assertions are unchanged and its root cause remains unconfirmed. The import comment-placement nit from #187 is addressed in this head. The maintainer approval is attached to 70897fe; later commits add documentation and tests only.

@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: APPROVED — leak reproduced on main, resolution mapping is visibility-neutral. One substantive nit about a shape change the diff doesn't mention.

Verified on macOS/arm64, local Bun 1.4.3, one worktree per head plus a combined main + #187 tree.

The leak is real and the fix is at the right seam

Their test file dropped onto origin/main fails 4 of 12, including the two that matter:

  • the superseded_overlap hint naming a rival row that is invisible to the entry reader (its ts and scope both appear in the reply), and
  • the moved-write-owner case stamping repo=7fa55f9da884 where the captured caller's repo is 1a65fd648b29.

On the branch: 12/12. The seam (spyOn(evidence, "record") firing a real session.moved at gate_start) only changes when a genuine event arrives — no fabricated gate verdict, no direct store mutation — and the fact that the file goes red on main proves the spy really drives the gate's own await.

No caller's visibility moves — only the resolution time

Checked the old and new resolution against each other rather than trusting the prose:

caller main this branch
named sid, resolved readerForSession(sid) same
named sid, unresolved readerForSession → global-only same
absent / "?" undefined → loadScope's default readerForAmbient() resolved after the awaits readerForAmbient() resolved at entry

loadScope(scope, reader = readerForAmbient()) is at src/memory.ts:183, readerFromSid at :705-709. And src/gates.ts:386 is the only place gate decisions consume repo visibility, so one threaded reader pins dedup, the stale scans and the blocked-overlap hint together. loadCanonical() (:422) is the unpartitioned registry and is correctly left alone.

Write-owner capture matches the store's own rule

writeAt reproduces appendMemory's rule exactly (writeTarget(input.sessionID ?? getCurrent().sid), memory.ts:306-311), including UnresolvedWriterError for a named-unresolved writer, just resolved before the gate's awaits instead of after them. memory_update still passes an explicit repo: target.repo ?? "global", so it bypasses the new owner object and updating a global row cannot re-house it out of other repos' views.

importMemories hoists only the resolution — the throw stays where it was. I probed the error precedence for an unresolved named session pointed at a non-.jsonl path: identical message on both trees (memory_import file must be a .jsonl export), so no user-facing change there.

Hoisting gateContext for capture and import is behaviorally neutral beyond identity: the session call ledger has exactly one writer (trackCall, fed by tool results), so evidenceCalls / evidenceCallsCount / hasGateCheck / hasEngagement cannot move during a capture's model call or an import loop, and runWriteGate never mutates ctx.

Gates

typecheck clean; lint exit 0 with 16 warnings in the four touched files on both main and the branch — the PR adds none; bun test ./test/ 707 pass / 12 skip / 0 fail; CI 4/4 on 70897fe; and clean on top of current main (with #187 too: 719 pass / 0 fail, e2e 11/11). The two existing move cases whose assertions changed are tightened, not loosened — the "must not name the survivor" assertions are kept and ownership assertions added on top.

Nit N1 — the one thing I'd like addressed (a shape change the body doesn't mention)

An unscoped writer through the gate (no named session, no module repo scope) now stores an explicit repo=global; on main the same write stores no repo field:

origin/main: ts=… type=learning scope=probe content="Unscoped ambient write through the gate"
pr-186:      ts=… type=learning scope=probe content="Unscoped ambient write through the gate" repo=global

Store-internal visibility really is unchanged — isVisibleTo treats !m.repo and m.repo === "global" alike (memory.ts:719) and lineVisibleTo inherits that, so recall, injection and restore all behave identically. Two things are not unchanged:

  1. An accidental unscoped write is now indistinguishable from a deliberate global: true row, forever.
  2. Portability treats them differently. Running both shapes through importMemories under a real module scope: the explicit-global row stays global (never re-stamped to the importing repo), while the unstamped row is adopted by the importing repo. That is the widening portable.ts:330-334 explicitly refuses to do to a row it is importing.

{} is not the remedy — leaving repo undefined hands appendMemory a fresh ambient resolution at append time, which is the leak being closed. So the ask is small: a comment at gates.ts:743-746 recording that entry-time "no owner" is deliberately published as global and why, plus a regression test pinning that stamp. Both new tests use a named session, so the writeAt.scope == null arm of the ternary is currently unpinned.

Nit N2

GateContext.reader is optional, so a future entry point that forgets it silently gets entry-time ambient behavior that is usually right. One line in the GateContext doc comment naming the three contracts (named / unbound / ambient) would make the contract #183 asked for live in the code instead of in this PR body.

Cross-references

  • This shrinks #121 but does not close it: a tool invoked without a sid still falls through sid ?? getCurrent().sid, which is #121's remaining surface.
  • The disclosed evidence boundary (a write stamped A while its audit line routes by the moved session) has no tracking issue. Worth opening one — it is the same module-scope-state family as #149's evidence lines.

@WhollyMindless

Copy link
Copy Markdown
Contributor Author

Thanks for the careful review. Addressed N1 and N2 in cfb6023:

  • Documented that captured unscoped ownership intentionally becomes explicit repo=global, including the export/import adoption difference. The PR description now calls out the shape change and loss of distinction from a deliberately global row.
  • Added two regressions for the previously unpinned arm: no scope at entry, with and without an ambient scope change at gate_start. Both assert the stored global stamp and exercise export/import under a repository scope. They fail with the pre-fix gate implementation and pass here.
  • Added the named/resolved, named/unbound, and ambient contracts beside GateContext.reader.

No runtime logic changed in this follow-up. Local Windows/Bun 1.4.4 full gate: typecheck, lint, 709 unit passes (12 existing skips), and 11 end-to-end passes. Hosted CI is pending for the new head.

Opened #188 for the separate evidence-scope boundary you flagged, with source-confirmed behavior and a dedicated evidence-read regression still to add. #121 and #176 remain separate. Please feel free to decline the implementation if the explicit-global policy is not the contract you want.

@WhollyMindless

WhollyMindless commented Oct 30, 2026 •

Copy link
Copy Markdown
Contributor Author

Windows on cfb6023 failed only the existing capture case dupe collapses via the gate, fresh candidate lands tagged, cooldown holds: its two-second wait at capture.test.ts:409 expired before it observed both auto_capture_collapsed and auto_capture_promoted. The log does not show which event was missing, so I cannot identify the exact cause or call this a confirmed runner-load flake. All #186 identity regressions passed, including the two new unscoped-owner cases; the three required checks also pass.

The original capture case passes 20 local Windows/Bun 1.4.4 repetitions with all 11 assertions exercised (220 total); the full local gate passed before this push. cfb6023 changes only comments and tests from the previously green, approved runtime head.

Could you rerun just the failed Windows job once on the unchanged head? Both available credentials refused the rerun (integration access denied; gh reports repository admin rights required). I have not changed timeouts, assertions, or runtime code. A green retry would establish that the failure is intermittent, not explain its cause; if it repeats, the next step is capturing the observed gate/capture events at the failed wait.

Failed job: https://github.com/abogartz/opencode-self-improvement/actions/runs/41006276296/job/123901784141

Update: pushed comment-only cleanup 72edbb3 at the contributor's request, addressing the import-comment placement nit from #187's review. Fresh CI is now running, including Windows, so the manual rerun request above is superseded. No executable code, timeout, or assertion changed; the previous capture timeout's cause remains unconfirmed.

CI result: all four checks passed on 72edbb3, including Windows. The previous capture wait failure did not recur with unchanged executable code and assertions. Its root cause remains unconfirmed; this is a passing subsequent run, not a runtime fix. No manual rerun is needed now.

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

Round 2: APPROVED at 72edbb3 — follow-ups are what I asked for, and the src/ delta is comments only.

Re-verified against the tree, not the reply:

  • No runtime logic changed since the head I approved. Filtering the diff of changed lines that are not comments gives an empty set: src/gates.ts +6 comment lines (the three GateContext.reader contracts, and the owner-stamping block), src/portable.ts is the #152 comment relocated to where the reasoning now lives. Behaviour is exactly what I approved.
  • The previously unpinned arm is now pinned, and it is red on main. Your file on origin/main: 6 of 14 fail — the four from round 1 plus both parametrizations of the unscoped case. The moves: true arm is the valuable one: an ambient scope acquired at gate_start must not reach the stamp, and on main appendMemory resolves exactly that ambient after the awaits. Branch: 14/14.
  • The export/import half of that test pins the consequence I measured, which is the part a future reader would otherwise have to rediscover: a captured repo=global row stays global instead of being adopted by the importing repository. Good that it is asserted rather than commented.
  • #188 is the right shape — boundary stated as source-confirmed rather than a measured incident, acceptance asks for a real evidence-read regression from both partitions, and it explicitly preserves named-unresolved privacy, scrubbing and attribution. Agreed it is separate from #121 and #176.

Gates at 72edbb3 (macOS/arm64, Bun 1.4.3; CI pins 1.4.4): typecheck clean, lint exit 0, bun test ./test/ 709 pass / 12 skip / 0 fail — matches your number — clean again under a second run and in the combined main + #187 tree (722 pass / 0 fail, real-host e2e 11/11). Hosted CI 4/4 including Windows. The only lint delta in touched files is 8 × lint/style/noNonNullAssertion in the test file, which is the house style here and advisory.

One take-it-or-leave-it nit: test.each([false, true])("… (scope moves: %s)") — this Bun does not substitute %s, and positional $0 is not substituted either. Both arms report the identical name, so a failure in CI tells you nothing about which case died and --test-name-pattern cannot select one. I confirmed the substitution rules on this runtime: only named placeholders with object rows work, e.g. test.each([{ moves: false }, { moves: true }])("… scope moves: $moves", …). Cosmetic; both arms failed on main anyway, so nothing was hidden from this review.

Nothing here blocks a merge.

@WhollyMindless

Copy link
Copy Markdown
Contributor Author

Addressed the optional test-name nit in d3d9e19 using object rows and the named $moves placeholder. Bun now reports distinct scope moves: false and scope moves: true cases. Verified each independently with --test-name-pattern: one pass, 13 filtered out, and all seven assertions exercised for each. Typecheck passes. Only the parameterization/name line changed; assertions and runtime code are unchanged. Fresh CI will validate the new head.

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

Round 3 (branch update): APPROVED at c63a463.

gh pr update-branch landed main into this branch, and the push also carried one new commit — d3d9e19, the test-name fix from my last nit. Verified rather than assumed:

  • d3d9e19 is exactly that one line. test.each now uses object rows with the $moves placeholder, and everything else in the PR's diff versus 72edbb3 is byte-identical apart from blob hashes.
  • The arms are distinguishable now, which was the point: on origin/main they report as … (scope moves: false) and … (scope moves: true), both red, file total 8 pass / 6 fail — same six as before, no arm silently dropped by the signature change from a positional arg to a destructured object.
  • On top of main (this head): typecheck clean, bun test ./test/ 712 pass / 12 skip / 0 fail, hosted CI 4/4 including Windows.
  • With #187 together on main: 722 pass / 12 skip / 0 fail and real-host e2e 11 pass / 0 fail.

Branch is MERGEABLE / CLEAN. Nothing further from me.

@abogartz
abogartz merged commit 6b9494a into abogartz:main Oct 30, 2026
4 checks passed
@abogartz-opencode-self-improvement

Copy link
Copy Markdown

🎉 This PR is included in version 0.14.24 🎉

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.

Capture one reader for gate operations across session moves

2 participants