Skip to content

Commit d9eb0d1

Browse files
committed
fix: reconcile resumed sessions and add workflow recovery
1 parent 90bf913 commit d9eb0d1

15 files changed

Lines changed: 358 additions & 22 deletions

‎CHANGELOG.md‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,18 @@ include the full version, for example `## 0.7.0-beta.1`.
88

99
## Unreleased
1010

11+
### Fixed
12+
13+
- Reconcile timed-out or interrupted sessions completed manually after a blocked
14+
task or service restart. Verify and publish through the dispatcher, then process
15+
queued issue feedback on the same branch and PR, including legacy checkpoints.
16+
17+
### Added
18+
19+
- `/restartworkflow` and the matching CLI/RPC command resume a stopped task from
20+
its saved stage, preserving worktrees, sessions, PRs, and feedback. Checkpoint
21+
continuation requests across restarts without bypassing checks or permissions.
22+
1123
## 0.6.5
1224

1325
### Fixed

‎docs/advanced.md‎

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,7 @@ node dist/manage.js run /absolute/path/to/owner-project github-issues
7171
node dist/manage.js pause /absolute/path/to/owner-project github-issues
7272
node dist/manage.js resume /absolute/path/to/owner-project github-issues
7373
node dist/manage.js retry /absolute/path/to/owner-project 'owner/repository#123'
74+
node dist/manage.js restartworkflow /absolute/path/to/owner-project 'owner/repository#123'
7475
```
7576

7677
`pause` stops scheduled scans and manual scheduler runs. It does not cancel queued
@@ -88,11 +89,21 @@ and already-published acknowledgement comments. An issue edited after analysis
8889
remains blocked for review. A new authorized comment after completion starts a
8990
follow-up round and updates the same open PR.
9091

92+
`restartworkflow` (also available as `/restartworkflow` in the owner TUI) queues
93+
recovery at the saved phase, without interrupting active execution or clearing
94+
the session. An interrupted session receives one checkpointed continuation
95+
request after it becomes idle; a completed session proceeds to verification.
96+
The request survives owner restarts. Uncertain delivery blocks inspection rather
97+
than replaying the continuation. Repeated requests while ready/running are no-ops.
98+
Questions, permissions, closed PRs, and missing execution routes remain guarded.
99+
Unlike `retry`, recovery can be queued while a different task is working.
100+
91101
## Persistence and reconciliation
92102

93103
The queue stores analysis decisions and clarification dialogue, comment ID, session ID, phase, pinned base branch,
94104
worktree, base commit, pending questions, replies, permission decisions, helper
95-
IDs, check results, PR title, publication time, PR, and merge status. Writes are
105+
IDs, session-stop classification, recovery request and admission checkpoint, check
106+
results, PR title, publication time, PR, and merge status. Writes are
96107
atomic; heartbeat locks prevent multiple owners of the same state directory.
97108

98109
After a crash, allow 30 seconds for an abandoned lock to expire. Do not remove
@@ -119,6 +130,14 @@ error should be investigated via plugin details and server logs. Back up the que
119130
worktree, and session database before recovery. Reconcile an already-published PR
120131
and saved session instead of restarting implementation or deleting the worktree.
121132

133+
A blocked session stop is rechecked on worker passes (no more than once every
134+
30 seconds after an unsuccessful probe). A matching saved session with a successful
135+
final assistant response re-enters normal execution validation, checks, and
136+
publication automatically, including legacy timeout/interruption checkpoints.
137+
Failed checks, pending questions, and uncertain prompt delivery are not cleared.
138+
Queued feedback is retained until publication completes. The stop itself never
139+
automatically prompts the model; continue it manually or request workflow recovery.
140+
122141
Only one issue executes at a time. Checks must succeed before publication. Push
123142
uses the exact verified commit without force. Worktrees remain available for
124143
inspection; automatic cleanup is not implemented.

‎docs/architecture.md‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ loads a generic scheduler, a GitHub dispatcher, and a terminal UI component.
1313
isolated Git worktree, verifies changes, and pushes the verified commit.
1414
- **Terminal UI:** subscribes to activity events and polls for missed updates.
1515
Opens background tabs, closes task tabs after PR closure while retaining
16-
session history, and exposes the `/bot` task selector.
16+
session history, and exposes `/bot` and `/restartworkflow` task selectors.
1717

1818
## Workflow
1919

@@ -29,7 +29,9 @@ loads a generic scheduler, a GitHub dispatcher, and a terminal UI component.
2929

3030
A failure retains the current phase and retry state. A possibly running session
3131
is reconciled before starting another issue. Unknown prompt delivery is blocked
32-
for inspection. RPC events are ephemeral; they are not the durable queue.
32+
for inspection. Stopped sessions completed manually are detected automatically and
33+
rejoin verification/publication before queued feedback runs. Explicit workflow
34+
recovery preserves checkpoints and continues the same session when needed. RPC events are ephemeral; they are not the durable queue.
3335

3436
## Configuration and ownership
3537

‎docs/bot-workflow.md‎

Lines changed: 24 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -396,7 +396,7 @@ An error normally preserves the phase so retry continues from its checkpoint.
396396
| `ready` | Eligible for worker selection when due. |
397397
| `waiting` | Awaiting an issue answer; no implementation or publication while unresolved. |
398398
| `retry_wait` | Transient failure; automatic retry after `nextAt`. |
399-
| `blocked` | Explicit `Blocked` error or GitHub HTTP 401, 404, or 422; requires inspection and manual retry. |
399+
| `blocked` | Explicit `Blocked` error or GitHub HTTP 401, 404, or 422; requires inspection/retry, except a stopped session completed manually is reconciled automatically. |
400400
| `failed` | Other errors reached `maxAttempts`; manual retry required. |
401401
| `done` | PR publication/reconciliation completed; feedback and merge monitoring remain possible. |
402402

@@ -408,6 +408,16 @@ flowchart LR
408408
Error -->|Other failure below attempt limit| Retry[retry_wait; preserve phase]
409409
Retry -->|nextAt elapsed| Work
410410
Error -->|Other failure at attempt limit| Fail[failed]
411+
Block --> Completed{Stopped session now completed successfully?}
412+
Completed -->|Yes| Rejoin[Resume saved session validation then checks and publication]
413+
Rejoin --> Work
414+
Completed -->|No| Remain[Retain block and queued feedback]
415+
Block --> Recover[restartworkflow preserves saved stage and work]
416+
Fail --> Recover
417+
Recover --> Safe{No pending question or unsafe session error?}
418+
Safe -->|No| Remain
419+
Safe -->|Yes| Resume[Queue recovery, reconnect and continue same session if stopped]
420+
Resume --> Work
411421
Block --> Manual[Manual retry while worker idle]
412422
Fail --> Manual
413423
Manual --> Restart{restartSession requested?}
@@ -432,10 +442,22 @@ flowchart LR
432442
- `retry` accepts only blocked or failed tasks and is rejected while the worker
433443
or maintenance is busy. `restartSession` does not delete the worktree or changes;
434444
it restarts session execution from the appropriate earlier phase.
445+
- Session-stop blocks are probed on worker passes, at most once per 30 seconds
446+
after an unsuccessful probe. Successful saved sessions re-enter `running`
447+
validation, then configured checks and publication. This recognizes legacy
448+
timeout/outcome errors as well as the persisted `sessionStopped` classification.
449+
It never infers success from a clean worktree or an already-pushed commit.
450+
- `/restartworkflow` queues a durable recovery request for a stopped task without
451+
resetting its phase, worktree, branch, PR, or feedback. It can be queued while
452+
another task works. For a stopped execution, the executor waits for idleness,
453+
verifies the original task marker, and sends a checkpointed continuation only
454+
if still incomplete. A lost response never replays that prompt blindly. Active
455+
sessions are not interrupted; unresolved questions and unsafe errors remain
456+
blocked. Already scheduled/running/completed tasks are no-ops.
435457
- Merge errors use `mergeError` and `mergeNextAt`; they do not turn a published
436458
task into an implementation failure.
437459
- Reloading the owner project after restart restores polling from durable state.
438460
Activity events are notifications, not the durable queue.
439461

440-
Sources: [dispatcher.ts — workOnce, retryOnce](../src/dispatcher.ts),
462+
Sources: [dispatcher.ts — workOnce, restartWorkflow, retryOnce](../src/dispatcher.ts),
441463
[scheduler.ts](../src/scheduler.ts), [state.ts](../src/state.ts).

‎docs/runtime.md‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -200,8 +200,32 @@ cd /absolute/path/to/your-project
200200
"$HOME/.local/bin/opencode2-automation" scan
201201
"$HOME/.local/bin/opencode2-automation" pause
202202
"$HOME/.local/bin/opencode2-automation" resume
203+
"$HOME/.local/bin/opencode2-automation" restartworkflow 'owner/repository#123'
203204
```
204205

205206
Pausing stops scheduled scans; it does not cancel accepted tasks or active sessions.
206207
Do not run independent bots on two machines against the same issues: they do not
207208
share queue ownership across machines.
209+
210+
## Interrupted sessions and workflow recovery
211+
212+
If you manually continue a timed-out or interrupted bot session in the TUI,
213+
the dispatcher detects its successful completion automatically. It rejoins the
214+
saved execution phase, validates the session result, runs the configured checks,
215+
and publishes the verified changes to the same branch and PR. Pending authorized
216+
issue comments remain queued and start the next round after publication. This
217+
also works after a service restart; opening a TUI is not required.
218+
219+
Use `/restartworkflow` in the owner project's TUI and select the issue to recover
220+
a stopped workflow. The equivalent terminal command is shown above. For a stopped
221+
session, recovery waits for any current execution, then continues the previously
222+
agreed task in that same session if it still needs work. For a verification or
223+
publication failure, it retries that saved stage. It preserves the worktree,
224+
branch, session history, pinned base, PR, and queued feedback. Repeated requests
225+
while recovery is scheduled or running do not start duplicate work.
226+
227+
Recovery does not bypass failing checks, unresolved questions or permissions,
228+
closed PRs, or uncertain prompt delivery. Answer pending questions in the issue.
229+
If a check still fails, fix its cause and retry; the plugin will not publish an
230+
unverified result. A service restart restores the saved state but does not clear
231+
these blocks. To resume paused issue polling, use `resume` separately.

‎src/dispatcher.ts‎

Lines changed: 50 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { createHash } from "node:crypto";
1+
import { createHash, randomUUID } from "node:crypto";
22
import { z } from "zod";
33
import { type GithubOptions, type Repository, Route, matchRoute } from "./config.js";
44
import { GithubError, Issue, Comment, type Pull } from "./github.js";
@@ -24,6 +24,8 @@ export const Task = z.object({
2424
helpers: z.array(z.object({ id: z.string(), parentID: z.string(), capability: z.enum(["vision", "audio"]) })).optional(),
2525
branch: z.string(), worktree: z.string().optional(), baseSha: z.string().optional(),
2626
sessionID: z.string().optional(), promptAttempted: z.boolean().optional(),
27+
sessionStopped: z.boolean().optional(),
28+
recovery: z.object({ id: z.string(), attempted: z.boolean().optional() }).optional(),
2729
sessionIDs: z.array(z.string()).optional(),
2830
sessionReady: z.boolean().optional(), round: z.number().int().positive().optional(),
2931
source: z.enum(["issue", "comment"]).optional(),
@@ -38,8 +40,17 @@ export type Task = z.infer<typeof Task>;
3840
export const Queue = z.object({ version: z.literal(1), tasks: z.array(Task) });
3941
export type Queue = z.infer<typeof Queue>;
4042
export class Blocked extends Error {}
43+
export class SessionStopped extends Blocked {}
4144
export class WaitingForAnswer extends Error {}
4245

46+
function stoppedSession(task: Task) {
47+
// Recognize checkpoints from releases before sessionStopped was persisted.
48+
return task.sessionStopped || [
49+
"Error: Session timed out and was interrupted; inspect it before retrying",
50+
"Error: Session did not complete successfully; inspect its outcome and permissions",
51+
].includes(task.error ?? "");
52+
}
53+
4354
export interface GithubPort {
4455
mergeApproved?(repo: string, number: number, commit: string, since: number, authors: string[], options: GithubOptions["autoMerge"]): Promise<boolean>;
4556
issues(repo: string): Promise<Issue[]>;
@@ -60,6 +71,7 @@ export interface Executor {
6071
verify(task: Task, repo: Repository): Promise<{ checks: string[]; commit: string }>;
6172
push(task: Task, repo: Repository): Promise<void>;
6273
cancel(task: Task): Promise<void>;
74+
completed?(task: Task): Promise<boolean>;
6375
}
6476

6577
export class Dispatcher {
@@ -171,6 +183,22 @@ export class Dispatcher {
171183
return this.working;
172184
}
173185
private async workOnce() {
186+
// A person can finish a stopped session in the TUI while the durable task
187+
// still says blocked. Rejoin normal verification/publication, never infer
188+
// completion from Git changes or discard pending issue feedback.
189+
for (const task of this.queue.tasks.filter(t => t.phase === "running" && t.sessionID && stoppedSession(t) && ["blocked", "failed"].includes(t.status) && t.nextAt <= this.now() && (!t.question || t.question.delivered))) {
190+
try {
191+
const completed = await this.executor.completed?.(structuredClone(task));
192+
await this.serial.run(async () => {
193+
this.signal.throwIfAborted();
194+
if (!["blocked", "failed"].includes(task.status)) return;
195+
Object.assign(task, completed
196+
? { status: "ready", attempts: 0, nextAt: this.now(), error: undefined }
197+
: { nextAt: this.now() + 30_000 });
198+
await this.store.save(this.queue);
199+
});
200+
} catch { if (this.signal.aborted) return; await this.update(task, { nextAt: this.now() + 30_000 }); }
201+
}
174202
// A lost comment response must not strand a waiting question after a restart.
175203
for (const pending of this.queue.tasks.filter(t => t.status === "waiting" && t.question && !t.question.commentID && t.nextAt <= this.now())) {
176204
const q = pending.question!;
@@ -183,7 +211,7 @@ export class Dispatcher {
183211
Object.assign(finished, { round: (finished.round ?? 1) + 1, feedback: finished.pendingFeedback, pendingFeedback: [], previousSessionID: finished.sessionID,
184212
phase: "queued", status: "ready", attempts: 0, nextAt: this.now(), analysis: undefined, commentID: undefined,
185213
analysisDecision: undefined, analysisDialogue: undefined, question: undefined,
186-
sessionID: undefined, sessionReady: false, promptAttempted: false, checks: undefined, commit: undefined, error: undefined });
214+
sessionID: undefined, sessionReady: false, promptAttempted: false, sessionStopped: undefined, recovery: undefined, checks: undefined, commit: undefined, error: undefined });
187215
await this.store.save(this.queue);
188216
});
189217
const resumable = this.queue.tasks.filter(t => ["ready", "retry_wait"].includes(t.status));
@@ -231,7 +259,7 @@ export class Dispatcher {
231259
if (task.phase === "running") {
232260
await this.executor.run(task, patch => this.update(task, patch));
233261
if (task.question && !task.question.delivered) throw new WaitingForAnswer("Waiting for a reply in the GitHub issue");
234-
await this.update(task, { phase: "verifying", attempts: 0 });
262+
await this.update(task, { phase: "verifying", attempts: 0, sessionStopped: undefined, recovery: undefined });
235263
}
236264
if (task.phase === "verifying") {
237265
const result = await this.executor.verify(task, repo);
@@ -254,7 +282,7 @@ export class Dispatcher {
254282
if (error instanceof WaitingForAnswer) { await this.update(task, { status: task.question?.answer ? "ready" : "waiting", error: undefined }); return; }
255283
const attempts = task.attempts + 1;
256284
const blocked = error instanceof Blocked || error instanceof GithubError && [401, 404, 422].includes(error.status);
257-
await this.update(task, { attempts, error: redact(error, this.secrets), status: blocked ? "blocked" : attempts >= this.options.maxAttempts ? "failed" : "retry_wait", nextAt: Math.max(this.now() + Math.min(3600, 5 * 2 ** attempts) * 1000, error instanceof GithubError ? error.retryAt ?? 0 : 0) });
285+
await this.update(task, { attempts, sessionStopped: error instanceof SessionStopped, error: redact(error, this.secrets), status: blocked ? "blocked" : attempts >= this.options.maxAttempts ? "failed" : "retry_wait", nextAt: Math.max(this.now() + Math.min(3600, 5 * 2 ** attempts) * 1000, error instanceof GithubError ? error.retryAt ?? 0 : 0) });
258286
}
259287
}
260288
private async resolveAnalysis(task: Task, repo: Repository) {
@@ -386,6 +414,24 @@ export class Dispatcher {
386414
try { return await this.maintenance; }
387415
finally { this.maintenance = undefined; }
388416
}
417+
async restartWorkflow(key: string) {
418+
return this.serial.run(async () => {
419+
this.signal.throwIfAborted();
420+
const task = this.queue.tasks.find(t => t.key === key);
421+
if (!task) throw new Error("Task not found in this project");
422+
if (task.question && !task.question.delivered) throw new Error("Answer the pending question or permission request in the GitHub issue first");
423+
if (task.merged || task.pr?.state === "closed") throw new Error("The original PR is closed or merged; reopen it or create a new issue");
424+
if (!["blocked", "failed"].includes(task.status)) return false;
425+
if (task.phase === "running" && !stoppedSession(task)) throw new Error("Inspect the session error before retrying; workflow restart cannot bypass uncertain prompt delivery or execution configuration errors");
426+
if (!task.route) throw new Error("Fix the execution route and use retry before restarting the workflow");
427+
Object.assign(task, {
428+
status: "ready", attempts: 0, nextAt: this.now(), error: undefined,
429+
...(task.phase === "running" ? { recovery: { id: randomUUID() } } : {}),
430+
});
431+
await this.store.save(this.queue);
432+
return true;
433+
});
434+
}
389435
private async retryOnce(key: string, restartSession: boolean) {
390436
const task = this.queue.tasks.find(t => t.key === key);
391437
if (!task || !["blocked", "failed"].includes(task.status)) return false;

0 commit comments

Comments
 (0)