Skip to content

Commit 68a6754

Browse files
committed
feat(opencode): resume/reconcile recovery control (M6.5)
A fusion_resume model-facing control and /fusion-resume command that present the owned or recovered run - run ID, owner, child session, pending executor request, outstanding-work flags - and name the recovery capability by mirroring the fusion_reconcile guard exactly: - available when uncertain with a pending request and a backgrounded turn or a recorded result (the setttle path vs notification wait is named); - busy while delegating or reconciling; - unavailable elsewhere with the specific cause: retained request with no live turn and no recorded result; unknown outcome with no retained request; nothing unsettled. nextAction routes to fusion_reconcile when exact proof can exist - including after reload, where the notification may already be recorded in the session - and documents explicit operator resolution otherwise, down to the concrete "bun src/workspace/resolve.ts <workspace> <run-id> <request-id | --no-request-id> --confirm-stopped" invocation with the retained request ID. activeTurnReattach is a literal "refused" with its reason rather than an implied capability; healthy runs state no recovery is owed. Unit-pinned across healthy, backgrounded-miss, retained-intent-without- proof, reload continuity, and scout-only states plus non-supervisor refusal; the model-free live smoke shows fusion-resume registered in the installed host's command surface (v2.2.5). Recovery after a restart that lost the completion notification stays blocked pending upstream parent completion (anomalyco/opencode#36349); cross-session presentation and a real restart recovery run join the M6.6 parity coverage list. 371 tests and type checking pass.
1 parent 9b4702a commit 68a6754

3 files changed

Lines changed: 141 additions & 5 deletions

File tree

‎docs/opencode-testing.md‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -39,13 +39,15 @@ Checked 2026-10-28 against locally installed OpenCode v2.2.0.
3939
| Configure and model validation (M6.2) | `fusion_configure` validates provider/model/variant against the live catalog; configured model reaches scout and executor submissions; shared price/cohort metadata reported | Unit tests; model-free live catalog + configure-unknown-refused/real-applied (v2.2.3); live scout child ran on the configured model (`opencode-go/glm-5.3-flash`), child session model observed |
4040
| Commands, persistent mode, clean (M6.3) | `fusion-run`, `fusion-mode`, `fusion-status`, `fusion-stats`, `fusion-clean` native commands; mode gates mutation tools per session; clean releases settled resources only | Unit tests (registration, /fusion-run prompt injection, mode gating + persistence, clean settled/foreign/uncertain); model-free live: all five commands in `/api/command` and `fusion-status` invoked through the command API (v2.2.3) |
4141
| Completion hooks, bounded nudges (M6.4) | Turn-end bus events feed the shared completion policy; nudges sent via session.prompt; interrupted/failed never nudge; runs settle per mode. Review follow-ups: Fusion-turn binding, event dedupe, persisted budget, incomplete reporting, retryable delivery, final-part summary detection; unresolved-work hold across all terminals (interrupt/fail included); budget + settlement + incomplete persist across reload; missing-prompt hosts consume nothing | Channel pinned live (v2.2.3 execution/text event shapes); unit-pinned nudge bound (2), summary suppression, backgrounded suppression, interrupt settle, agent binding, dedupe, reload persistence (incomplete + completed phase), delivery-failure retry and persistence-failure hold; live early-settle observation deferred to the M6.6 parity run |
42+
| Resume/reconcile control (M6.5) | `fusion_resume` tool and `/fusion-resume` command present owner, pending request, outstanding work, and reconciliation capability (available/busy/unavailable mirroring the `fusion_reconcile` guard); routes to `fusion_reconcile` when exact proof can exist (across reload too); documents concrete operator resolution (`bun src/workspace/resolve.ts ... --confirm-stopped`) otherwise; `activeTurnReattach` refused with reason | Unit-pinned across healthy, backgrounded-miss, retained-intent-without-proof, reload continuity, and scout-only states, plus non-supervisor refusal; model-free live command registration on the installed host (v2.2.5). Recovery after a restart that lost the completion notification stays blocked pending upstream (#36349); cross-session "not attached" presentation and a real restart recovery run join M6.6 parity coverage |
4243
| Complete OpenCode Fusion workflow | No | Not ready to install/use |
4344

4445
The core extraction is partial: the shared controller owns task transitions,
4546
pending and uncertain state, delegation guards, and the main delegation sequence;
4647
the adapters still own native worker handles, persistence, and presentation.
47-
The experimental OpenCode entrypoint exposes delegate, scout, status, reset,
48-
and reconciliation tools, native commands, and example agent files. OpenCode
48+
The experimental OpenCode entrypoint exposes delegate, scout, status, stats,
49+
resume/reconciliation, and reset tools, native commands, and example agent
50+
files. OpenCode
4951
plugin storage and the shared ownership registry retain the workspace owner,
5052
original task, budgets, child ID and pending turn across reloads. The SQLite
5153
workspace coordinator excludes concurrent owners across processes. The package

‎src/opencode/index.ts‎

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -712,6 +712,44 @@ export default {
712712
: "Review the working tree and audit the original task; reset when the run is finished.";
713713
return JSON.stringify({ ...run.controller.state, runId: run.runId, owner: run.handle.owner, workspaceClaimed: !!run.lease, model: run.model, pending: run.controller.pending, promptDelivery: promptDelivery?.state, nudgeDelivery, settlementWrite, incomplete: !!run.incomplete, childSessionID: run.handle.reference?.id, capabilities: run.runtime.capabilities, uncertain: run.controller.uncertain, backgroundPending: status.backgroundPending, reconciling: !!run.reconciling, nextAction });
714714
}
715+
/** Resume presentation: recovery surface for the owned or adopted run.
716+
* Routed to fusion_reconcile only when exact completion proof can exist;
717+
* operator resolution is documented textually, never implied. */
718+
async function resumeContent(sessionID: string): Promise<string> {
719+
const run = runs.get(sessionID);
720+
if (!run) {
721+
const owned = await registry.inspect(workspace);
722+
if (!owned) return "No Fusion run in this session.";
723+
return JSON.stringify({
724+
message: "The workspace Fusion record is not attached to this session; recovery happens in its owning session or through explicit operator resolution.",
725+
runId: owned.manifest.runId, owner: owned.manifest.owner, recovery: owned.manifest.recovery, pending: owned.manifest.pending,
726+
activeTurnReattach: "refused",
727+
reattachReason: "Fusion never reattaches another session's executor turn into this session.",
728+
nextAction: `Call fusion_resume in the owning session (${owned.manifest.owner.supervisorId}), or after inspecting the worker and workspace run: bun src/workspace/resolve.ts ${workspace} ${owned.manifest.runId} ${owned.manifest.pending?.requestId ?? "--no-request-id"} --confirm-stopped`,
729+
});
730+
}
731+
const status = run.runtime.status(run.handle);
732+
const outstanding = { backgroundPending: status.backgroundPending, recordedResult: !!status.unsettled, reconciling: !!run.reconciling, delegating: !!run.controller.state.delegating, scoutInFlight, backgroundScout: hasBackgroundScout() };
733+
const pendingRequest = run.controller.pending;
734+
// The capability mirrors the fusion_reconcile guard; the detail names
735+
// which proof reconcile would adopt, or why none can exist.
736+
const resolveCommand = run.runId ? `bun src/workspace/resolve.ts ${workspace} ${run.runId} ${pendingRequest?.requestId ?? "--no-request-id"} --confirm-stopped` : "bun src/workspace/resolve.ts --confirm-stopped";
737+
let reconcile: { capability: "available" | "busy" | "unavailable"; detail: string };
738+
if (outstanding.delegating || outstanding.reconciling) reconcile = { capability: "busy", detail: "another executor transition is in progress" };
739+
else if (run.controller.uncertain && pendingRequest && (outstanding.backgroundPending || outstanding.recordedResult)) reconcile = { capability: "available", detail: outstanding.recordedResult ? "the executor's recorded result can be settled into the run" : "the executor's completion notification is awaited, or may already be recorded in this session" };
740+
else if (run.controller.uncertain && pendingRequest) reconcile = { capability: "unavailable", detail: "the retained executor request has no live turn and no recorded result; automatic retry stays disabled while the outcome is unknown" };
741+
else reconcile = { capability: "unavailable", detail: run.controller.uncertain ? "the outcome is unknown with no retained request" : "nothing is unsettled; the run owes no recovery" };
742+
const nextAction = reconcile.capability === "available"
743+
? "Call fusion_reconcile to adopt the executor's exact completion. If it reports no matching notification, inspect the worker and workspace, and after confirming the worker stopped run: " + resolveCommand
744+
: reconcile.capability === "busy"
745+
? "Wait for the in-flight executor transition to finish, then call fusion_resume again."
746+
: run.incomplete
747+
? "The Fusion run is incomplete: the supervisor stopped before finishing. Take over the task yourself, or call fusion_reset to finish the run."
748+
: run.controller.uncertain
749+
? "No exact completion proof can be adopted. Inspect the worker session and the working tree, and after confirming the worker stopped run: " + resolveCommand
750+
: "No recovery is owed; the run is active in this session. Continue the protocol and call fusion_reset when it finishes.";
751+
return JSON.stringify({ ...run.controller.state, runId: run.runId, owner: run.handle.owner, model: run.model, childSessionID: run.handle.reference?.id, pendingRequest, outstanding, uncertain: run.controller.uncertain, reconcile: reconcile.capability, reconcileDetail: reconcile.detail, activeTurnReattach: "refused", reattachReason: "OpenCode cannot reattach a live or interrupted executor turn back into this session; recovery routes through the completion notification (fusion_reconcile) or explicit operator resolution.", incomplete: !!run.incomplete, nextAction });
752+
}
715753
function statsContent(sessionID: string): string {
716754
const run = runs.get(sessionID);
717755
if (!run) return "No Fusion run in this session.";
@@ -1000,6 +1038,13 @@ export default {
10001038
} finally { run.reconciling = false; }
10011039
},
10021040
});
1041+
editor.add({
1042+
name: "fusion_resume", description: "Show this Fusion run's recovery state: owner, pending request, reconciliation capability, and the next valid action. Refuses outright anything it cannot honestly promise, including mid-turn reattachment.", input: { type: "object", properties: {}, additionalProperties: false }, options: { codemode: false },
1043+
async execute(_input, context) {
1044+
requireSupervisor(context);
1045+
return { content: await resumeContent(context.sessionID) };
1046+
},
1047+
});
10031048
editor.add({
10041049
name: "fusion_status", description: "Show the current Fusion run state.", input: { type: "object", properties: {}, additionalProperties: false }, options: { codemode: false },
10051050
async execute(_input, context) {
@@ -1109,6 +1154,11 @@ export default {
11091154
description: "Show the current Fusion run's budgets",
11101155
execute: async (args) => await reportCommand(args.sessionID, "Fusion stats", statsContent(args.sessionID)),
11111156
});
1157+
editor.add({
1158+
name: "fusion-resume",
1159+
description: "Show the Fusion run's recovery state",
1160+
execute: async (args) => await reportCommand(args.sessionID, "Fusion resume", await resumeContent(args.sessionID)),
1161+
});
11121162
editor.add({
11131163
name: "fusion-clean",
11141164
description: "Release settled Fusion resources for this workspace",

‎test/opencode-plugin.test.ts‎

Lines changed: 87 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -633,7 +633,7 @@ describe("OpenCode Fusion plugin", () => {
633633
transform: async (callback) => { callback({ add: (tool) => tools.set(tool.name, tool) }); },
634634
},
635635
}, storage);
636-
expect(commands.map((command) => command.name)).toEqual(["fusion-run", "fusion-mode", "fusion-status", "fusion-stats", "fusion-clean"]);
636+
expect(commands.map((command) => command.name)).toEqual(["fusion-run", "fusion-mode", "fusion-status", "fusion-stats", "fusion-resume", "fusion-clean"]);
637637
await expect(commands[0].execute({ sessionID: "one", prompt: { text: " " } })).rejects.toThrow("Provide a task");
638638
await commands[0].execute({ sessionID: "one", prompt: { text: "Build the thing" } });
639639
expect(prompts).toHaveLength(1);
@@ -644,7 +644,7 @@ describe("OpenCode Fusion plugin", () => {
644644
expect(status.originalTask).toBe("Build the thing");
645645
expect(status.runActive).toBe(true);
646646
expect(status.workspaceClaimed).toBe(true);
647-
await expect(commands[4].execute({ sessionID: "one" })).rejects.toThrow("run is still active");
647+
await expect(commands[5].execute({ sessionID: "one" })).rejects.toThrow("run is still active");
648648
await expect(commands[0].execute({ sessionID: "one", prompt: { text: "Another" } })).rejects.toThrow("Finish and reset");
649649
// /fusion-status command reports the same payload as the tool.
650650
const commandStatus = JSON.parse(String(await commands[2].execute({ sessionID: "one" })));
@@ -1142,6 +1142,90 @@ describe("OpenCode Fusion plugin", () => {
11421142
await setupTest(makeContext(afterReset), storage);
11431143
expect((await afterReset.get("fusion_status")!.execute({}, context("one"))).content).toContain("No Fusion run");
11441144
});
1145+
test("fusion_resume routes recovery honestly for every run condition", async () => {
1146+
// Uncertain run with a retained write-ahead intent but no live turn and
1147+
// no recorded result: reconciliation is unavailable; operator resolution
1148+
// is documented textually.
1149+
{
1150+
const tools = new Map<string, Tool>();
1151+
await setupTest({ location: { directory: "/workspace" }, session: { context: async () => [], hook: async () => {} }, tool: {
1152+
hook: async () => {}, list: async () => [{ id: "subagent", execute: async () => { throw new Error("must not be called"); } }],
1153+
transform: async (callback) => { callback({ add: (tool) => tools.set(tool.name, tool) }); },
1154+
} }, { get: async () => undefined, set: async () => { throw new Error("storage unavailable"); }, remove: async () => {} });
1155+
await expect(tools.get("fusion_delegate")!.execute({ action: "execute", brief: "work" }, context("one"))).rejects.toThrow("storage unavailable");
1156+
const resume = JSON.parse((await tools.get("fusion_resume")!.execute({}, context("one"))).content);
1157+
expect(resume.reconcile).toBe("unavailable");
1158+
expect(resume.reconcileDetail).toContain("no live turn and no recorded result");
1159+
expect(resume.pendingRequest?.requestId).toBeString();
1160+
expect(resume.owner.supervisorId).toBe("one");
1161+
expect(resume.nextAction).toContain("bun src/workspace/resolve.ts");
1162+
expect(resume.nextAction).toContain(resume.pendingRequest?.requestId as string);
1163+
expect(resume.nextAction).toContain("--confirm-stopped");
1164+
expect(resume.activeTurnReattach).toBe("refused");
1165+
}
1166+
// A failed executor submission leaves the turn pending on its completion
1167+
// notification: exact proof can exist and fusion_reconcile is the route,
1168+
// across a reload too, with operator resolution documented as fallback.
1169+
{
1170+
const tools = new Map<string, Tool>();
1171+
const storage = memoryStorage();
1172+
let messages: unknown[] = [];
1173+
let description = "";
1174+
const makeContext = (fresh: Map<string, Tool>): TestContext => ({
1175+
location: { directory: "/workspace" }, session: { context: async () => messages, hook: async () => {} }, tool: {
1176+
hook: async () => {}, list: async () => [{ id: "subagent", execute: async (input, ctx) => {
1177+
await ctx.progress({ sessionID: "child-r" });
1178+
description = input.description;
1179+
throw new Error("connection lost");
1180+
} }], transform: async (callback) => { callback({ add: (tool) => fresh.set(tool.name, tool) }); },
1181+
},
1182+
});
1183+
await setupTest(makeContext(tools), storage);
1184+
await tools.get("fusion_start")!.execute({ task: "Task" }, context("one"));
1185+
let resume = JSON.parse((await tools.get("fusion_resume")!.execute({}, context("one"))).content);
1186+
expect(resume.reconcile).toBe("unavailable");
1187+
expect(resume.nextAction).toContain("No recovery is owed");
1188+
await expect(tools.get("fusion_delegate")!.execute({ action: "execute", brief: "build" }, context("one"))).rejects.toThrow("connection lost");
1189+
resume = JSON.parse((await tools.get("fusion_resume")!.execute({}, context("one"))).content);
1190+
expect(resume.reconcile).toBe("available");
1191+
expect(resume.pendingRequest?.requestId).toBe(description);
1192+
expect(resume.outstanding.backgroundPending).toBe(true);
1193+
expect(resume.childSessionID).toBe("child-r");
1194+
expect(resume.nextAction).toContain("Call fusion_reconcile");
1195+
const restored = new Map<string, Tool>();
1196+
await setupTest(makeContext(restored), storage);
1197+
resume = JSON.parse((await restored.get("fusion_resume")!.execute({}, context("one"))).content);
1198+
expect(resume.reconcile).toBe("available");
1199+
expect(resume.pendingRequest?.requestId).toBe(description);
1200+
expect(resume.nextAction).toContain("If it reports no matching notification");
1201+
expect(resume.nextAction).toContain("--confirm-stopped");
1202+
expect(resume.activeTurnReattach).toBe("refused");
1203+
expect(resume.reattachReason).toContain("cannot reattach");
1204+
// Once the recorded notification exists, reconcile adopts it and the
1205+
// run owes no recovery again.
1206+
messages = [{ type: "synthetic", description, metadata: { source: "subagent", childID: "child-r", agent: "fusion-executor", state: "completed" }, text: `<subagent sessionID="child-r" state="completed" description="${description}">\nfixed\n</subagent>` }];
1207+
expect((await restored.get("fusion_reconcile")!.execute({}, context("one"))).content).toContain("fixed");
1208+
resume = JSON.parse((await restored.get("fusion_resume")!.execute({}, context("one"))).content);
1209+
expect(resume.reconcile).toBe("unavailable");
1210+
expect(resume.nextAction).toContain("No recovery is owed");
1211+
}
1212+
// Healthy ephemeral experiment: a scout-only run (no workspace claim) still
1213+
// presents recovery state and never implies reattachment.
1214+
{
1215+
const tools = new Map<string, Tool>();
1216+
await setupTest({ location: { directory: "/workspace" }, session: { context: async () => [], hook: async () => {} }, tool: {
1217+
hook: async () => {}, list: async () => [{ id: "subagent", execute: async () => ({ output: { sessionID: "child", status: "completed", output: "answer" } }) }],
1218+
transform: async (callback) => { callback({ add: (tool) => tools.set(tool.name, tool) }); },
1219+
} });
1220+
await tools.get("fusion_scout")!.execute({ questions: ["Where?"] }, context("one"));
1221+
const resume = JSON.parse((await tools.get("fusion_resume")!.execute({}, context("one"))).content);
1222+
expect(resume.uncertain).toBe(false);
1223+
expect(resume.reconcile).toBe("unavailable");
1224+
expect(resume.reconcileDetail).toContain("nothing is unsettled");
1225+
expect(resume.activeTurnReattach).toBe("refused");
1226+
expect(resume.nextAction).toContain("No recovery is owed");
1227+
}
1228+
});
11451229
test("blocks direct subagent calls only for the Fusion supervisor", async () => {
11461230
const tools = new Map<string, Tool>();
11471231
let before!: (event: { tool: string; agent: string }) => void;
@@ -1169,7 +1253,7 @@ describe("OpenCode Fusion plugin", () => {
11691253
list: async () => [{ id: "subagent", execute: async () => ({ output: { sessionID: "child", status: "completed", output: "done" } }) }],
11701254
transform: async (callback) => { callback({ add: (tool) => tools.set(tool.name, tool) }); },
11711255
} });
1172-
for (const name of ["fusion_delegate", "fusion_status", "fusion_reconcile", "fusion_reset"]) {
1256+
for (const name of ["fusion_delegate", "fusion_status", "fusion_resume", "fusion_reconcile", "fusion_reset"]) {
11731257
await expect(tools.get(name)!.execute(name === "fusion_delegate" ? { action: "execute", brief: "recursion" } : {}, context("one", "fusion-executor"))).rejects.toThrow("only to the fusion primary agent");
11741258
await expect(tools.get(name)!.execute(name === "fusion_delegate" ? { action: "execute", brief: "recursion" } : {}, context("one", "general"))).rejects.toThrow("only to the fusion primary agent");
11751259
}

0 commit comments

Comments
 (0)