Skip to content

Commit d4dbd0e

Browse files
Sean SmithSean Smith
authored andcommitted
session/attachment: gate supplemental borrow on scope resolution (CP-032 R-08)
A scope that has published its resolution stays registered until `closeNow` unregisters it, and `locate` returned it to `executeSupplement` as borrowable. Borrowing one loses the supplement's answer silently: `own()` returned on the `state.closed` guard before reaching the throw, so no typed refusal was minted, and `result()` short-circuits on `state.resolution` and replays the earlier resolution and fallback. The run then files the earlier controlling position, which `ledger.filed` already holds, and its own distinct answer disappears with no note and no error. Once CP-032 B-1 parks an owner run inside `Scope.result()` that window covers every concurrent supplemental sequence rather than a few fiber hops. Adds `AttachmentCoordinator.locateBorrowable`, which answers the borrow question only. Raw `locate` is deliberately unchanged: of its three production consumers, `tool/task.ts:289` reconciles the carried parent scope by object identity and fails the call on disagreement, and `session/attachment/participant.ts:124` reports covered edges for closure proof and must not narrow the proven set. A global resolved-filter inside `locate` would regress both. `open` now replaces a RESOLVED incumbent in place instead of failing, via a private `resolved()` thunk on the registry entry rather than a new field on `AttachmentContract.Current`. The check-and-swap is one `Effect.sync` critical section and `closeNow` runs inside `transition`, so it is atomic without a new lock. A live incumbent still loses the exclusive open, so a degraded-but- unresolved scope keeps throwing from `own()` and keeps producing CP-031's recoverable admission failure. `Scope.own` now returns whether ownership was taken. A borrow check cannot rule out resolution by itself: `promptAdmitted` yields through `revert.cleanup` and `createUserMessage` between discovery and ownership, so a scope live at lookup can resolve before the claim. Returning false lets that boundary raise `SessionScopeOwnRefused` before `onAdmitted` fires, routing the supplement to the sanctioned pre-admission note instead of a stale replay. The no-op itself is preserved and load-bearing -- taking ownership would `invalidate()` a settled candidate and let `result()` fall through to a different fallback -- so the non-admission callers at prompt.ts:525 and prompt.ts:1235 ignore the result and "ownership arriving after the successful gate closes is a no-op" passes unchanged. Fence bindings are deliberately untouched. A ref authorizes the exact scope generation it was captured on; replacement rewrites only `registry.scopes`, so an old ref keeps cancelling its own generation and never reaches the successor. Files: packages/opencode/src/session/attachment/coordinator.ts, packages/opencode/src/session/prompt.ts, packages/opencode/src/tool/task.ts
1 parent 8094d33 commit d4dbd0e

6 files changed

Lines changed: 344 additions & 8 deletions

File tree

‎packages/opencode/src/session/attachment/coordinator.ts‎

Lines changed: 93 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,16 @@ export type ObserverClaim =
4444

4545
export interface Scope extends AttachmentContract.Scope {
4646
readonly sessionID: SessionID
47-
readonly own: (messageID: MessageID) => Effect.Effect<void>
47+
/**
48+
* Claims a message for this scope, invalidating the turn's prior evidence.
49+
*
50+
* Returns whether ownership was taken. `false` means the scope had already published its
51+
* resolution and can no longer accept one — the admission boundary converts that into the typed
52+
* `SessionScopeOwnRefused`, while non-admission callers ignore it and keep the historical no-op.
53+
* A degraded or cancelled scope that has NOT resolved still throws, which is CP-031's existing
54+
* recoverable admission failure and is deliberately unchanged.
55+
*/
56+
readonly own: (messageID: MessageID) => Effect.Effect<boolean>
4857
readonly owns: (messageID: MessageID) => boolean
4958
readonly reserve: (jobID: SessionID) => Effect.Effect<Reservation>
5059
readonly reject: (reservation: Reservation) => Effect.Effect<void>
@@ -75,6 +84,20 @@ export interface TaskInterface {
7584
* is necessarily an effectful read.
7685
*/
7786
readonly locate: (sessionID: SessionID) => Effect.Effect<Scope | undefined>
87+
/**
88+
* CP-032 R-08: the BORROW lookup, deliberately distinct from `locate`.
89+
*
90+
* A scope that has published its resolution stays registered until `closeNow` unregisters it, and
91+
* in that window it is unusable: `reserve` throws, `own` returns silently on the `closed` guard
92+
* (so no typed refusal is minted), and `result` hands back the EARLIER resolution and fallback. A
93+
* supplement that borrowed one would therefore file the earlier position, which the filing guard
94+
* already holds, and lose its own answer with no note and no error.
95+
*
96+
* `locate` keeps returning it on purpose. `tool/task.ts` reconciles the carried parent scope
97+
* against the registry by object identity and treats disagreement as a coordination fault, so
98+
* hiding a resolved scope there would fail delegated calls rather than protect them.
99+
*/
100+
readonly locateBorrowable: (sessionID: SessionID) => Effect.Effect<Scope | undefined>
78101
readonly claim: (sessionID: SessionID) => Effect.Effect<Claim>
79102
readonly settleClaim: (claim: Claim, active: boolean) => Effect.Effect<void>
80103
readonly awaitClaim: (claim: Claim) => Effect.Effect<boolean>
@@ -164,6 +187,16 @@ type RegistryState = {
164187
{
165188
readonly scope: Scope
166189
readonly captureFence: (ref: Ports.ParticipantFenceRef) => boolean
190+
/**
191+
* CP-032 R-08: this scope has published its resolution, which is the ONLY replaceable state.
192+
* Kept as a private thunk over the owning scope's `state` rather than exposed on `Current`,
193+
* so no public contract widens and no existing `current()` consumer changes.
194+
*
195+
* Deliberately NOT `closed`: `closeNow` already unregisters, so a closed scope is absent from
196+
* this map. Deliberately NOT `degraded`/`cancelled` while unresolved — those still throw from
197+
* `own()` and remain CP-031's recoverable admission failure, which R-23 preserves.
198+
*/
199+
readonly resolved: () => boolean
167200
}
168201
>
169202
/** Core owns each ref's strong fence-lifetime root; historical snapshots therefore key weakly. */
@@ -296,12 +329,26 @@ export const make = Effect.gen(function* () {
296329

297330
const own: Scope["own"] = (messageID) =>
298331
apply(() => {
299-
if (state.closed) return
332+
// CP-032 R-08. Ownership is REFUSED here, not silently dropped, and the caller learns which.
333+
//
334+
// A resolved scope reaches this branch (`gate()` sets `closed` at every resolution), and a
335+
// borrow check performed earlier cannot have caught it: the admission path yields through
336+
// `revert.cleanup` and `createUserMessage` between discovery and this call, so a scope that
337+
// was live at lookup can resolve before ownership. Returning `false` — rather than the
338+
// former bare `return` — is what lets the admission boundary convert that into the typed
339+
// refusal instead of proceeding onto a dead scope and replaying its earlier answer.
340+
//
341+
// The no-op itself is preserved and load-bearing: taking ownership here would `invalidate()`
342+
// a settled candidate and let a later `result()` fall through to a different fallback, so a
343+
// completed scope's selected answer must stay immutable. Non-admission callers ignore the
344+
// result and keep exactly that behaviour.
345+
if (state.closed) return false
300346
if (state.degraded || state.cancelled || state.resolution) {
301347
throw new Error(`Attachment scope ${state.scopeID} cannot own another message`)
302348
}
303349
state.messages.add(messageID)
304350
invalidate()
351+
return true
305352
})
306353

307354
const owns: Scope["owns"] = (messageID) => transition(() => state.messages.has(messageID))
@@ -536,9 +583,36 @@ export const make = Effect.gen(function* () {
536583
close,
537584
}
538585

586+
const entry = {
587+
scope: handle,
588+
captureFence,
589+
resolved: () => state.resolution !== undefined,
590+
}
591+
592+
// CP-032 R-08. One synchronous critical section, so check-and-replace is atomic by
593+
// construction: `Effect.sync` cannot yield, and `closeNow`'s delete runs inside `transition`,
594+
// which cannot either. No new lock is needed.
595+
//
596+
// A LIVE incumbent still refuses the open — CP-031's exclusivity, unchanged, and the path that
597+
// keeps producing the typed `SessionScopeOwnRefused` note for a degraded-but-unresolved scope.
598+
// A RESOLVED incumbent is replaced in place: it can no longer serve a borrower, and leaving it
599+
// registered is exactly what made a later supplement's distinct answer vanish into the earlier
600+
// filed position with no note and no error.
601+
//
602+
// The predecessor is not closed here; its own finalizer still runs and is identity-safe.
603+
// `closeNow` deletes only while the registered scope id is still its own, and `scopeID` is a
604+
// fresh UUID per open, so the predecessor cannot evict the successor.
539605
const registered = yield* Effect.sync(() => {
540-
if (registry.scopes.has(sessionID)) return false
541-
registry.scopes.set(sessionID, { scope: handle, captureFence })
606+
const incumbent = registry.scopes.get(sessionID)
607+
if (incumbent && !incumbent.resolved()) return false
608+
// The predecessor's fence snapshot is deliberately left bound to the predecessor. A fence ref
609+
// authorizes the exact scope generation it was captured on, never the session's future
610+
// successor — the standing contract proved by "captureFence and claimCancellationAtFence bind
611+
// exact scope generations". Deleting or forwarding it here would manufacture authority over a
612+
// generation the ref never named. The successor stays fence-capable because `captureFence`
613+
// resolves an unretained ref through `registry.scopes.get(sessionID)`, which is now the
614+
// successor.
615+
registry.scopes.set(sessionID, entry)
542616
return true
543617
})
544618
if (!registered) return yield* Effect.fail(new Error(`Attachment scope already open for session ${sessionID}`))
@@ -579,6 +653,20 @@ export const make = Effect.gen(function* () {
579653
return registry.scopes.get(sessionID)?.scope
580654
})
581655

656+
// CP-032 R-08. Raw `locate` stays raw because two of its three production consumers need registry
657+
// truth rather than usability: `tool/task.ts` reconciles the carried parent scope by object
658+
// identity and fails the call on disagreement, and `attachment/participant.ts` reports covered
659+
// edges for closure proof and must not narrow the proven set. Only `executeSupplement`'s borrow
660+
// needs the qualified answer, so the qualification lives here rather than inside `locate`.
661+
const locateBorrowable: Interface["locateBorrowable"] = Effect.fn("AttachmentCoordinator.locateBorrowable")(
662+
function* (sessionID) {
663+
const registry = yield* InstanceState.get(registries)
664+
const entry = registry.scopes.get(sessionID)
665+
if (!entry || entry.resolved()) return undefined
666+
return entry.scope
667+
},
668+
)
669+
582670
const captureFence: Interface["captureFence"] = Effect.fn("AttachmentCoordinator.captureFence")(
583671
function* (sessionID, ref) {
584672
const registry = yield* InstanceState.get(registries)
@@ -601,6 +689,7 @@ export const make = Effect.gen(function* () {
601689
return Service.of({
602690
open,
603691
locate,
692+
locateBorrowable,
604693
captureFence,
605694
claimCancellationAtFence,
606695
claim,

‎packages/opencode/src/session/prompt.ts‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1182,6 +1182,24 @@ const layer = Layer.effect(
11821182
}),
11831183
)
11841184
}),
1185+
// CP-032 R-08. A degraded or cancelled scope throws above; a scope that has already
1186+
// published its resolution refuses by returning false, and that case has to fail here too.
1187+
// It cannot be ruled out by checking borrowability before the prompt: this site runs after
1188+
// `revert.cleanup` and `createUserMessage`, so the scope can resolve in between. Without
1189+
// this arm the supplement would proceed on a dead scope, `result()` would replay the
1190+
// earlier resolution, and its own distinct answer would file into a position the guard
1191+
// already holds — lost with no note and no error. Refusing pre-admission instead routes it
1192+
// to the sanctioned supplemental note, because `onAdmitted` has not run yet.
1193+
Effect.flatMap((owned) =>
1194+
owned
1195+
? Effect.void
1196+
: Effect.fail(
1197+
new ScopeOwnRefused({
1198+
sessionID: input.sessionID,
1199+
reason: "attachment scope had already resolved its return",
1200+
}),
1201+
),
1202+
),
11851203
)
11861204
// Admission has happened: the user message and its parts are persisted and the conditional
11871205
// claim succeeded. This runs before the runner is entered.

‎packages/opencode/src/tool/task.ts‎

Lines changed: 14 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -394,9 +394,11 @@ export const TaskTool = Tool.define(
394394
* A supplemental prompt: a second call naming a running task's `task_id` joins that task's
395395
* conversation rather than starting another one.
396396
*
397-
* With the feature on it resolves the child scope once - borrowing the live scope so claiming
398-
* the message invalidates the turn's evidence, or opening and finalizing its own when none is
399-
* live. With it off no scope exists and it prompts without one.
397+
* With the feature on it resolves the child scope once - borrowing a live UNRESOLVED scope so
398+
* claiming the message invalidates the turn's evidence, or opening and finalizing its own when
399+
* there is no live unresolved scope. A registered scope that has already published its
400+
* resolution is not borrowable (CP-032 R-08): the open atomically replaces it. With the
401+
* feature off no scope exists and it prompts without one.
400402
*
401403
* Classification consults an `admitted` flag set by its own hook, which fires after the prompt
402404
* is durably persisted and the conditional claim succeeds. An interrupt rethrows; a failure
@@ -455,7 +457,15 @@ export const TaskTool = Tool.define(
455457
return toDetected(outcome.result)
456458
})
457459
if (!flags.experimentalBackgroundSubagents) return yield* attempt()
458-
const located = yield* attachments.locate(nextSession.id)
460+
// CP-032 R-08: BORROW, so this asks `locateBorrowable`, not raw `locate`. A scope that has
461+
// published its resolution stays registered until its finalizer unregisters it, and once
462+
// eligibility parks the owner run inside `Scope.result()` that window covers every
463+
// concurrent sequence. Borrowing one is silent loss: `own()` returns on the `closed` guard
464+
// without minting a refusal, and `result()` replays the earlier resolution, so this run
465+
// files the earlier position the guard already holds and its own answer disappears.
466+
// Raw `locate` keeps registry truth for the parent identity check above and for closure
467+
// participant discovery; only the borrow is qualified.
468+
const located = yield* attachments.locateBorrowable(nextSession.id)
459469
if (located) return yield* attempt(located)
460470
const opened = yield* attachments.open(nextSession.id).pipe(Effect.exit)
461471
if (Exit.isFailure(opened)) {

‎packages/opencode/test/lib/attachment.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -77,6 +77,8 @@ export const settleTerminal = Effect.fn("AttachmentTest.settleTerminal")(functio
7777
export function inertCoordinator(): AttachmentCoordinator.Interface {
7878
return {
7979
locate: () => Effect.succeed(undefined),
80+
locateBorrowable: () =>
81+
Effect.die("inertCoordinator: locateBorrowable() reached — this fixture needs a real coordinator"),
8082
captureFence: () => Effect.succeed(false),
8183
claimCancellationAtFence: () => Effect.succeed(false),
8284
open: () => Effect.die("inertCoordinator: open() reached — this fixture needs a real coordinator"),

0 commit comments

Comments
 (0)