fix(core): preserve subagent notifications across location eviction (#54072)

This commit is contained in:
Kit Langton
2026-10-08 23:49:30 -07:00
committed by GitHub
Unverified
parent 93a7c8404f
commit ee0e614221
10 changed files with 428 additions and 25 deletions
+69
View File
@@ -0,0 +1,69 @@
# Background completion after parent-location eviction
`subagent-eviction.ts` drives an isolated server and its real TUI. It starts a
background subagent, moves the child to another directory, leaves the parent
idle, evicts and rebuilds the parent location, then lets the child finish.
Only the LLM responses and a `fixture_hold` tool are simulated. Session movement,
job scopes, completion delivery, SQLite persistence, and the parent wake are real.
The existing `DELETE /api/debug/location` endpoint invalidates the same location
graph as inactivity eviction, so the proof does not wait for the 60-minute TTL.
It does not change the server clock or restart the server.
## Run
Use Bun 1.4.2, an available `opencode-drive` 2.1.3 installation on the module path,
and a dependency-installed V2 checkout. The script is an Effect program, run with
`opencode-drive run` (which typechecks before launch).
```sh
OPENCODE_DRIVE_DB=proof.sqlite \
OPENCODE_DRIVE_MEDIA_DIR=$PWD/.drive-output \
DEMO_LABEL=AFTER \
opencode-drive run script/drive/subagent-eviction.ts
```
Run that same script against an immutable base checkout:
```sh
OPENCODE_DEV=/path/to/base-checkout \
OPENCODE_DRIVE_DB=proof.sqlite \
OPENCODE_DRIVE_MEDIA_DIR=$PWD/.drive-output \
DEMO_LABEL=BEFORE \
opencode-drive run script/drive/subagent-eviction.ts
```
`DEMO_LABEL=BEFORE` asserts the known missing wake; `AFTER` asserts successful
delivery. `DEMO_EVICT=false` is a control and must wake even on the base.
The script checks the child's completed answer, counts the parent's synthetic
notifications, and reads only its isolated database's background marker. It
writes `proof.json` inside the reported artifacts directory, saves a screenshot,
and exports an annotated recording. Another location eviction/rebuild must not
duplicate the notification.
| Check | Base with eviction | Fixed / no-eviction control |
| -------------------- | ------------------------- | --------------------------- |
| Child completed | true | true |
| Parent resumed | false | true |
| Parent notifications | 0 | 1 |
| Background marker | completed, unacknowledged | absent |
The dynamic hold tool avoids the static adapter loading issue in
[opencode-drive#116](https://github.com/anomalyco/opencode-drive/issues/116).
## History
- `94e3a29d2f` (#34320, June 28): the original V2 subagent tool registered at the
global application root, so its completion observer shared that lifetime.
- `194b0615e0` (#34619, June 30): plugin-provided tools moved it into the
location-scoped plugin layer while retaining its captured-scope observer.
- `282b644cde` (#44275, August 22): location expiry became driven by durable
session activity. A moved child's activity cannot refresh the idle parent's
original location.
- `7819e7f503` (#47081, September 3): command subagents reused `SubagentJob.make`,
preserving the same activation-scoped observer in both entry points.
This is source-history attribution of the lifetime mismatch, not a claim that
every historical revision has been executed. The before proof runs V2
`93a7c8404fdc4fdb182eb6bbef7d925cb81e8306`.
+153
View File
@@ -0,0 +1,153 @@
import { Deferred, Effect, Stream } from "effect"
import { Llm, OpenCodeDriver } from "opencode-drive"
import { AbsolutePath } from "../../packages/schema/src/schema"
import { Database } from "bun:sqlite"
const label = process.env.DEMO_LABEL ?? "AFTER"
const evict = process.env.DEMO_EVICT !== "false"
// Run with OPENCODE_DRIVE_DB=proof.sqlite. Only model output and fixture_hold are
// simulated. The debug endpoint closes the real graph without waiting an hour.
// Dynamic tools avoid the static adapter issue: anomalyco/opencode-drive#116.
export default OpenCodeDriver.use(
{
opencode: { dev: process.env.OPENCODE_DEV ?? process.cwd() },
keepArtifacts: true,
tui: { recording: true, viewport: { cols: 100, rows: 30 } },
config: {
autoupdate: false,
username: "Demo",
agents: { reviewer: { mode: "subagent", description: "Review the fixture" } },
},
tuiConfig: { theme: { name: "opencode", mode: "dark" }, animations: false, tabs: { mode: "off" } },
project: { git: true, files: { "README.md": "# Parent fixture\n", "child/README.md": "# Child fixture\n" } },
},
({ ui, llm, tui, opencode, artifacts, tools }) =>
Effect.gen(function* () {
const release = yield* Deferred.make<void>()
const held = yield* Deferred.make<void>()
yield* tools.attach({
tools: [
{
name: "fixture_hold",
description: "Wait for the fixture",
inputSchema: { type: "object", properties: {} },
options: { codemode: false },
},
],
})
let parentRequests = 0
let childRequests = 0
yield* llm.serve((request) => {
const body = JSON.stringify(request)
if (body.includes("You are a subagent spawned")) {
childRequests++
if (childRequests === 1)
return Stream.make(
Llm.toolCall({ index: 0, id: "call_hold", name: "fixture_hold", input: {} }),
Llm.finish("tool-calls"),
)
return Stream.fromEffect(
Deferred.succeed(held, undefined).pipe(Effect.andThen(Deferred.await(release))),
).pipe(Stream.flatMap(() => Stream.make(Llm.text("CHILD_REVIEW_COMPLETE"))))
}
parentRequests++
if (parentRequests === 1)
return Stream.make(
Llm.toolCall({
index: 0,
id: "call_review",
name: "subagent",
input: {
agent: "reviewer",
description: "Review fixture",
prompt: "Review the child fixture",
background: true,
},
}),
Llm.finish("tool-calls"),
)
return Stream.make(
Llm.text(
parentRequests === 2 ? "Review is running in the background." : "Review received. All checks passed.",
),
)
})
yield* ui.waitFor("Simulated Model", { timeout: 30000 })
yield* ui.submit("Run the fixture review in the background.")
yield* ui.waitFor("Review is running in the background.", { timeout: 30000 })
const parent = (yield* opencode.session.list({ limit: 20 })).data.find((session) => !session.parentID)
if (!parent) return yield* Effect.fail(new Error("Parent missing"))
const child = (yield* opencode.session.list({ parentID: parent.id })).data[0]
if (!child) return yield* Effect.fail(new Error("Child missing"))
const hold = yield* tools.take("call_hold")
yield* opencode.session.move({ sessionID: child.id, directory: AbsolutePath.make(`${artifacts}/files/child`) })
yield* hold.finish({ structured: {}, content: [{ type: "text", text: "Fixture ready" }] })
yield* Deferred.await(held).pipe(Effect.timeout("30 seconds"))
const moved = yield* opencode.session.get({ sessionID: child.id })
if (moved.location.directory !== `${artifacts}/files/child`)
return yield* Effect.fail(new Error("Child did not move"))
yield* opencode.session.wait({ sessionID: parent.id })
if (evict) {
yield* opencode.debug.location.evict({ location: { directory: parent.location.directory } })
yield* opencode.location.get({ location: { directory: parent.location.directory } })
}
if (tui.recording)
yield* tui.recording.mark(`${label}: parent idle${evict ? ", original location evicted" : " (control)"}`)
yield* Deferred.succeed(release, undefined)
yield* opencode.session.wait({ sessionID: child.id })
const resumed = yield* ui.waitFor("Review received. All checks passed.", { timeout: 5000 }).pipe(
Effect.as(true),
Effect.catchTag("UiWaitTimeoutError", () => Effect.succeed(false)),
)
const messages = yield* opencode.message.list({ sessionID: parent.id })
const childMessages = yield* opencode.message.list({ sessionID: child.id })
const completed = childMessages.data.some(
(message) =>
message.type === "assistant" &&
message.finish === "stop" &&
message.content.some((part) => part.type === "text" && part.text === "CHILD_REVIEW_COMPLETE"),
)
const notifications = messages.data.filter(
(message) => message.type === "synthetic" && message.metadata?.source === "subagent",
).length
const marker = yield* Effect.acquireUseRelease(
Effect.sync(() => new Database(`${artifacts}/logs/opencode/proof.sqlite`, { readonly: true })),
(database) =>
Effect.sync(() =>
database
.query<
{ status: string; output: string },
[string]
>("SELECT json_extract(value, '$.status') AS status, json_extract(value, '$.output') AS output FROM kv WHERE key LIKE 'job.background/%' AND json_extract(value, '$.recovery.childSessionID') = ?")
.get(child.id),
),
(database) => Effect.sync(() => database.close()),
)
const proof = { label, evict, resumed, completed, notifications, parentRequests, childRequests, marker }
console.log(JSON.stringify(proof, null, 2))
yield* Effect.promise(() => Bun.write(`${artifacts}/proof.json`, JSON.stringify(proof, null, 2)))
if (
!completed ||
notifications !== (resumed ? 1 : 0) ||
(resumed ? marker !== null : marker?.status !== "completed")
)
return yield* Effect.fail(new Error("Inconsistent completion evidence"))
if (evict) {
yield* opencode.debug.location.evict({ location: { directory: parent.location.directory } })
yield* opencode.location.get({ location: { directory: parent.location.directory } })
const rebuilt = yield* opencode.message.list({ sessionID: parent.id })
if (rebuilt.data.filter((message) => message.type === "synthetic").length !== notifications)
return yield* Effect.fail(new Error("Location rebuild duplicated notification"))
}
if (tui.recording)
yield* tui.recording.mark(
`${label}: ${resumed ? "completion resumes parent" : "child finished; parent never resumed"}`,
)
yield* Effect.sleep("2 seconds")
console.log("screenshot", yield* ui.screenshot("completion"))
if (tui.recording) console.log("video", yield* tui.recording.finish())
if (resumed !== (label === "AFTER" || !evict))
return yield* Effect.fail(new Error("Unexpected completion delivery"))
}),
)