1- import { createHash } from "node:crypto" ;
1+ import { createHash , randomUUID } from "node:crypto" ;
22import { z } from "zod" ;
33import { type GithubOptions , type Repository , Route , matchRoute } from "./config.js" ;
44import { 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>;
3840export const Queue = z . object ( { version : z . literal ( 1 ) , tasks : z . array ( Task ) } ) ;
3941export type Queue = z . infer < typeof Queue > ;
4042export class Blocked extends Error { }
43+ export class SessionStopped extends Blocked { }
4144export 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+
4354export 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
6577export 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