Skip to content

Commit 5ce84dd

Browse files
committed
Keep automation owners active and release locks after cleanup failures
1 parent ead2978 commit 5ce84dd

8 files changed

Lines changed: 237 additions & 11 deletions

File tree

‎docs/advanced.md‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -101,6 +101,20 @@ uncertain network results. Uncertain initial prompt delivery is not automaticall
101101
resent. Issue replies and helper prompts use deterministic IDs for admission retries.
102102
Merge requests pin the verified head SHA and reconcile an already-merged PR.
103103

104+
The shared service can evict an idle owner location even while an agent works in
105+
a different worktree. Scheduler and dispatcher components therefore refresh the
106+
owner every 30 seconds through the public plugin-list API, after confirming the
107+
service PID matches their own process. Transient heartbeat errors are logged and
108+
retried; requests do not overlap. A standalone server without a matching service
109+
registration skips this mechanism. Keep its owner location in use or use the
110+
shared background service for unattended automation.
111+
112+
Cleanup aborts and settles work before releasing ownership. All cleanup steps
113+
are attempted even when RPC disposal fails; locks are not forcibly removed or
114+
stolen from another owner. A held-lock startup error should be investigated via
115+
plugin details and server logs. Back up the queue and worktree before recovery;
116+
do not assume a failed session means its edits were lost.
117+
104118
Only one issue executes at a time. Checks must succeed before publication. Push
105119
uses the exact verified commit without force. Worktrees remain available for
106120
inspection; automatic cleanup is not implemented.

‎docs/architecture.md‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,5 +42,12 @@ The primary checkout owns scheduling. Worker worktrees do not start additional
4242
schedulers. A shared Git-directory state folder holds the queue and locks; separate
4343
machines require separate test repositories to avoid duplicate execution.
4444

45+
In the shared background service, each scheduler/dispatcher component sends a
46+
periodic request back to its owner location to prevent idle eviction while work
47+
runs elsewhere. It checks the service PID before touching the location, so a
48+
standalone instance cannot activate another owner in a different service.
49+
Shutdown settles work and attempts all cleanup steps, including lock release,
50+
even if an SDK registration fails to dispose after location eviction.
51+
4552
See [advanced configuration](advanced.md) for retry commands, limits, and RPC
4653
settings, and the [README](../README.md) for installation and user-facing behavior.

‎docs/bot-workflow.md‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,12 +35,20 @@ flowchart TD
3535
cancel accepted work or active sessions.
3636
- A scan cannot overlap another scan in the same dispatcher. Only one worker
3737
invocation runs at a time; one scheduler job cannot overlap itself.
38+
- Each component refreshes the owner through the matching background service's
39+
plugin-list API every 30 seconds. A PID check prevents activating a second
40+
owner in another service. Requests do not overlap and have a 15-second deadline.
41+
This heartbeat keeps the owner loaded while execution happens in worktrees;
42+
pausing issue scans does not pause it. Standalone servers without a matching
43+
registered service skip the refresh.
3844
- State is schema-validated and saved through a temporary file, file sync, and
3945
rename. A corrupt state file fails to load rather than resetting the queue.
4046
Local locks prevent duplicate owners sharing this state directory; independent
4147
machines do not share ownership.
4248
- Shutdown clears timers, aborts operations, waits for in-flight work, disposes
43-
registrations, and releases locks. Executor shutdown interrupts its task session.
49+
registrations, and releases locks. Cleanup attempts the remaining steps even
50+
if an earlier step fails, so an evicted RPC registration cannot skip lock
51+
release. Executor shutdown interrupts its task session.
4452

4553
Sources: [index.ts](../src/index.ts), [easy.ts](../src/easy.ts),
4654
[GitHub plugin](../src/plugins/github.ts),

‎docs/runtime.md‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,18 @@ The queue retains waiting questions and accepted replies across restarts.
4545
After restarting the service, load the owner project again to resume polling.
4646
No terminal UI is needed to answer in GitHub.
4747

48+
The automation owner must remain loaded while its worktree sessions run. In the
49+
shared background service, the plugin refreshes the owner location every 30
50+
seconds, independently of issue polling and its pause setting. This prevents
51+
idle owner eviction from disconnecting worker hooks and publication. The refresh
52+
only targets a service whose PID matches the plugin process; standalone servers
53+
without a matching registered service do not receive this heartbeat.
54+
55+
If the plugin reports a held lock or a worker reports unavailable automation RPC,
56+
inspect plugin details, logs, and queue state before retrying. Preserve the
57+
worktree and queue; a failed session can still contain completed changes. Do not
58+
remove an active lock or restart implementation just to recover publication.
59+
4860
## Tabs after PR closure
4961

5062
Each repository scan checks the state of tracked PRs independently of the

‎src/lifecycle.ts‎

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
import { OpenCode } from "@opencode/client";
2+
import { Service } from "@opencode/client/service";
3+
4+
// Cleanup must reach the lock release even when an evicted SDK scope can no
5+
// longer dispose its RPC registration. Keep the lock until work has settled.
6+
export async function cleanup(...steps: (() => void | Promise<void>)[]) {
7+
const errors: unknown[] = [];
8+
for (const step of steps) {
9+
try { await step(); } catch (error) { errors.push(error); }
10+
}
11+
if (errors.length) throw new AggregateError(errors, "Automation cleanup failed");
12+
}
13+
14+
export interface OwnerClient {
15+
health: { get(options: { signal: AbortSignal }): Promise<{ pid: number }> };
16+
plugin: { list(input: { location: { directory: string } }, options: { signal: AbortSignal }): Promise<unknown> };
17+
}
18+
19+
export async function touchOwner(directory: string, signal: AbortSignal, connect: () => Promise<OwnerClient | undefined> = async () => {
20+
const endpoint = await Service.discover();
21+
return endpoint ? OpenCode.make({ baseUrl: endpoint.url, headers: Service.headers(endpoint) }) : undefined;
22+
}) {
23+
const client = await connect();
24+
if (!client) return false;
25+
// A standalone server must never activate a second owner in a different
26+
// background service. The public request must return to this exact process.
27+
if ((await client.health.get({ signal })).pid !== process.pid) return false;
28+
await client.plugin.list({ location: { directory } }, { signal });
29+
return true;
30+
}
31+
32+
export function heartbeat(touch: (signal: AbortSignal) => Promise<unknown>, report: (error: unknown) => void, everyMs = 30_000) {
33+
const controller = new AbortController();
34+
let active: Promise<void> | undefined;
35+
const timer = setInterval(() => {
36+
if (active || controller.signal.aborted) return;
37+
active = Promise.resolve().then(() => touch(AbortSignal.any([controller.signal, AbortSignal.timeout(15_000)])))
38+
.then(() => {}, error => { if (!controller.signal.aborted) report(error); })
39+
.finally(() => { active = undefined; });
40+
}, everyMs);
41+
return async () => {
42+
clearInterval(timer);
43+
controller.abort();
44+
await active;
45+
};
46+
}

‎src/plugins/github.ts‎

Lines changed: 22 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ import { GithubRpc } from "../rpc.js";
1010
import { acquire, JsonStore, redact } from "../state.js";
1111
import { githubToken } from "../easy.js";
1212
import type { Activity } from "../activity.js";
13+
import { cleanup, heartbeat, touchOwner } from "../lifecycle.js";
1314

1415
export default Plugin.define({
1516
id: "automation.github",
@@ -23,14 +24,25 @@ export default Plugin.define({
2324
let publish: (activity: Activity) => Promise<void> = async () => {};
2425
const dispatcher = new Dispatcher(options, new JsonStore(join(options.stateDirectory, "queue.json"), Queue, () => ({ version: 1, tasks: [] })), new Github(token, controller.signal, fetch, options.signature), executor, controller.signal, [token], Date.now, activity => publish(activity));
2526
let releaseBridge: (() => void) | undefined;
27+
let registration: { dispose(): Promise<void> } | undefined;
28+
let stopHeartbeat: (() => Promise<void>) | undefined;
29+
let timer: ReturnType<typeof setInterval> | undefined;
30+
const stop = () => cleanup(
31+
() => { clearInterval(timer); controller.abort(); },
32+
() => stopHeartbeat?.(),
33+
() => dispatcher.settle(),
34+
() => registration?.dispose(),
35+
() => releaseBridge?.(),
36+
release,
37+
);
2638
try {
2739
await dispatcher.init();
2840
releaseBridge = registerRuntimeBridge(options.ownerDirectory, {
2941
runtime: async ({ sessionID }) => dispatcher.runtime(sessionID),
3042
question: async ({ sessionID, id, text, permission }) => dispatcher.question(sessionID, id, text, permission),
3143
helper: async ({ sessionID, callID, capability }) => dispatcher.helper(sessionID, callID, capability),
3244
});
33-
const registration = await ctx.rpc.register(GithubRpc, {
45+
const rpc = await ctx.rpc.register(GithubRpc, {
3446
runtime: async ({ sessionID }) => JSON.parse(JSON.stringify(dispatcher.runtime(sessionID))),
3547
question: async ({ sessionID, id, text, permission }) => dispatcher.question(sessionID, id, text, permission),
3648
helper: async ({ sessionID, callID, capability }) => dispatcher.helper(sessionID, callID, capability),
@@ -43,11 +55,16 @@ export default Plugin.define({
4355
activity: async () => dispatcher.activity(),
4456
retry: async ({ key, restartSession }) => { controller.signal.throwIfAborted(); return { accepted: await dispatcher.retry(key, restartSession) }; },
4557
});
46-
publish = activity => registration.events.emit("activity", activity);
58+
registration = rpc;
59+
publish = activity => rpc.events.emit("activity", activity);
4760
const tick = () => { if (!controller.signal.aborted) void dispatcher.tick().catch(error => { console.error("Dispatcher stopped", redact(error, [token])); controller.abort(error); }); };
48-
const timer = setInterval(tick, options.workerEverySeconds * 1000);
61+
timer = setInterval(tick, options.workerEverySeconds * 1000);
62+
stopHeartbeat = heartbeat(signal => touchOwner(options.ownerDirectory, signal), error => console.error("Automation owner heartbeat failed", redact(error, [token])));
4963
tick();
50-
return async () => { clearInterval(timer); controller.abort(); await registration.dispose(); await dispatcher.settle(); releaseBridge?.(); await release(); };
51-
} catch (error) { controller.abort(); releaseBridge?.(); await release(); throw error; }
64+
return stop;
65+
} catch (error) {
66+
await stop().catch(cause => console.error("Automation cleanup failed", redact(cause, [token])));
67+
throw error;
68+
}
5269
},
5370
});

‎src/plugins/scheduler.ts‎

Lines changed: 20 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,8 @@ import { join } from "node:path";
44
import { SchedulerOptions } from "../config.js";
55
import { Scheduler, SchedulerState } from "../scheduler.js";
66
import { SchedulerRpc, handlerRpc } from "../rpc.js";
7-
import { acquire, JsonStore } from "../state.js";
7+
import { acquire, JsonStore, redact } from "../state.js";
8+
import { cleanup, heartbeat, touchOwner } from "../lifecycle.js";
89

910
export default Plugin.define({
1011
id: "automation.scheduler",
@@ -18,17 +19,31 @@ export default Plugin.define({
1819
const method = ctx.rpc(handlerRpc(job.rpcID, job.method))[job.method]!;
1920
return method(job.input, { signal: AbortSignal.any([controller.signal, AbortSignal.timeout(120_000)]) });
2021
});
22+
let registration: { dispose(): Promise<void> } | undefined;
23+
let stopHeartbeat: (() => Promise<void>) | undefined;
24+
let timer: ReturnType<typeof setInterval> | undefined;
25+
const stop = () => cleanup(
26+
() => { clearInterval(timer); controller.abort(); },
27+
() => stopHeartbeat?.(),
28+
() => scheduler.settle(),
29+
() => registration?.dispose(),
30+
release,
31+
);
2132
try {
2233
await scheduler.init();
23-
const registration = await ctx.rpc.register(SchedulerRpc, {
34+
registration = await ctx.rpc.register(SchedulerRpc, {
2435
status: async () => JSON.parse(JSON.stringify(scheduler.status())),
2536
run: async ({ id }) => { controller.signal.throwIfAborted(); return { started: await scheduler.run(id) }; },
2637
pause: async ({ id, paused }) => { controller.signal.throwIfAborted(); await scheduler.pause(id, paused); return { ok: true }; },
2738
});
2839
const tick = () => { if (!controller.signal.aborted) void scheduler.tick().catch(error => { console.error("Scheduler stopped", error); controller.abort(error); }); };
29-
const timer = setInterval(tick, 1000);
40+
timer = setInterval(tick, 1000);
41+
stopHeartbeat = heartbeat(signal => touchOwner(options.ownerDirectory, signal), error => console.error("Scheduler owner heartbeat failed", redact(error)));
3042
tick();
31-
return async () => { clearInterval(timer); controller.abort(); await registration.dispose(); await scheduler.settle(); await release(); };
32-
} catch (error) { controller.abort(); await release(); throw error; }
43+
return stop;
44+
} catch (error) {
45+
await stop().catch(cause => console.error("Scheduler cleanup failed", redact(cause)));
46+
throw error;
47+
}
3348
},
3449
});

‎test/lifecycle.test.ts‎

Lines changed: 107 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,107 @@
1+
import test from "node:test";
2+
import assert from "node:assert/strict";
3+
import { mkdtemp, realpath, rm } from "node:fs/promises";
4+
import { tmpdir } from "node:os";
5+
import { join } from "node:path";
6+
import { setImmediate } from "node:timers/promises";
7+
import type { Plugin } from "@opencode/plugin";
8+
import { cleanup, heartbeat, touchOwner, type OwnerClient } from "../src/lifecycle.js";
9+
import github from "../src/plugins/github.js";
10+
import scheduler from "../src/plugins/scheduler.js";
11+
import { acquire } from "../src/state.js";
12+
import { runtimeBridge } from "../src/bridge.js";
13+
14+
test("cleanup settles work and releases ownership even after disposal failures", async () => {
15+
const steps: string[] = [];
16+
const failure = new Error("SDK scope was evicted");
17+
await assert.rejects(cleanup(
18+
async () => { steps.push("settled"); },
19+
() => { steps.push("dispose"); throw failure; },
20+
() => { steps.push("bridge removed"); },
21+
() => { steps.push("lock released"); },
22+
), (error: AggregateError) => error.errors[0] === failure);
23+
assert.deepEqual(steps, ["settled", "dispose", "bridge removed", "lock released"]);
24+
});
25+
26+
for (const kind of ["github", "scheduler"] as const) {
27+
test(`${kind} plugin releases its actual lock when RPC disposal rejects`, async () => {
28+
const directory = await realpath(await mkdtemp(join(tmpdir(), "oc2-lifecycle-")));
29+
const tokenName = "OC2_LIFECYCLE_TEST_TOKEN";
30+
process.env[tokenName] = "test-token";
31+
const rpc = Object.assign(() => ({ scan: async () => ({}) }), {
32+
register: async () => ({ dispose: async () => { throw new Error("evicted registration"); }, events: { emit: async () => {} } }),
33+
});
34+
const options = kind === "github" ? {
35+
tokenEnv: tokenName, ownerDirectory: directory, stateDirectory: directory,
36+
autoMerge: { enabled: false },
37+
repositories: [{ repo: "owner/repo", directory, baseBranch: "main", allowedAuthors: ["alice"], checks: [] }],
38+
routes: { "@bot": { model: { providerID: "test", id: "model" } } },
39+
} : { ownerDirectory: directory, stateDirectory: directory, jobs: [{ id: "scan", everySeconds: 60 }] };
40+
try {
41+
const plugin = kind === "github" ? github : scheduler;
42+
const stop = await plugin.setup({ location: { directory }, options, rpc } as unknown as Plugin.Context);
43+
assert.ok(stop);
44+
await assert.rejects(async () => stop(), /Automation cleanup failed/);
45+
const release = await acquire(directory, kind, () => {});
46+
await release();
47+
assert.equal(runtimeBridge(directory), undefined);
48+
} finally {
49+
delete process.env[tokenName];
50+
await rm(directory, { recursive: true, force: true });
51+
}
52+
});
53+
}
54+
55+
test("owner heartbeat only touches the matching service process and owner directory", async () => {
56+
const calls: string[] = [];
57+
let pid = process.pid + 1;
58+
const client: OwnerClient = {
59+
health: { get: async () => ({ pid }) },
60+
plugin: { list: async ({ location }) => { calls.push(location.directory); } },
61+
};
62+
const signal = new AbortController().signal;
63+
assert.equal(await touchOwner("/owner", signal, async () => undefined), false);
64+
assert.equal(await touchOwner("/owner", signal, async () => client), false);
65+
assert.deepEqual(calls, []);
66+
pid = process.pid;
67+
assert.equal(await touchOwner("/owner", signal, async () => client), true);
68+
assert.deepEqual(calls, ["/owner"]);
69+
});
70+
71+
test("heartbeat does not overlap requests and aborts pending work on cleanup", async t => {
72+
t.mock.timers.enable({ apis: ["setInterval"] });
73+
let calls = 0;
74+
let pendingSignal: AbortSignal | undefined;
75+
const errors: unknown[] = [];
76+
const stop = heartbeat(signal => {
77+
calls++;
78+
pendingSignal = signal;
79+
return new Promise((_, reject) => signal.addEventListener("abort", () => reject(signal.reason), { once: true }));
80+
}, error => errors.push(error));
81+
t.mock.timers.tick(30_000);
82+
await setImmediate();
83+
t.mock.timers.tick(60_000);
84+
await setImmediate();
85+
assert.equal(calls, 1);
86+
await stop();
87+
assert.equal(pendingSignal?.aborted, true);
88+
assert.deepEqual(errors, []);
89+
t.mock.timers.tick(60_000);
90+
await setImmediate();
91+
assert.equal(calls, 1);
92+
});
93+
94+
test("heartbeat retries after a transient failure", async t => {
95+
t.mock.timers.enable({ apis: ["setInterval"] });
96+
let calls = 0;
97+
const errors: unknown[] = [];
98+
const stop = heartbeat(async () => { if (++calls === 1) throw new Error("connection lost"); }, error => errors.push(error));
99+
try {
100+
t.mock.timers.tick(30_000);
101+
await setImmediate();
102+
t.mock.timers.tick(30_000);
103+
await setImmediate();
104+
assert.equal(calls, 2);
105+
assert.equal(errors.length, 1);
106+
} finally { await stop(); }
107+
});

0 commit comments

Comments
 (0)