-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathruntime.ts
More file actions
2130 lines (1895 loc) · 87.5 KB
/
runtime.ts
File metadata and controls
2130 lines (1895 loc) · 87.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import type { PluginInput } from '@opencode-ai/plugin'
import type { OpencodeClient } from '@opencode-ai/sdk/v2'
import type { LoopChangeNotifier } from './service'
import { createLoopService, MAX_RETRIES } from './service'
import { generateUniqueName } from './name-uniqueness'
import type { LoopState } from './state'
import type { Logger, PluginConfig, LoopConfig } from '../types'
import type { LoopsRepo } from '../storage/repos/loops-repo'
import type { PlansRepo } from '../storage/repos/plans-repo'
import type { ReviewFindingsRepo, ReviewFindingRow } from '../storage/repos/review-findings-repo'
import type { SectionPlansRepo, SectionPlanRow } from '../storage/repos/section-plans-repo'
import type { LoopSessionUsageRepo } from '../storage/repos/loop-session-usage-repo'
import { createLoopWatchdog, type LoopWatchdogStallInfo, type LoopWatchdogRecoveryContext } from '../hooks/watchdog'
import { retryWithModelFallback } from '../utils/model-fallback'
import { resolveLoopModel, resolveLoopAuditorModel } from '../utils/loop-helpers'
import type { createSandboxManager } from '../sandbox/manager'
// worktree-completion imports moved to hooks/loop.ts (termination side-effects)
import { buildLoopPermissionRuleset, buildAuditSessionPermissionRuleset } from '../constants/loop'
import { createLoopSessionWithWorkspace, publishWorkspaceDetachedToast } from '../utils/loop-session'
// worktree-cleanup imports moved to hooks/loop.ts (termination side-effects)
import { createAuditSession, promptAuditSession } from '../utils/audit-session'
import { formatAuditSessionTitle, formatLoopSessionTitle } from '../utils/session-titles'
import { bindSessionToWorkspace } from '../workspace/forge-worktree'
import { markPromptSent, clearPromptPending, sessionsAwaitingBusy, isAwaitingBusy, isAwaitingBusyExpired } from './idle-gate'
import {
clearPromptInFlight,
clearPromptInFlightBySession,
withInFlightGuard,
ConcurrentPromptError,
} from './in-flight-guard'
import type { TerminationReason } from './termination'
import { terminationStatusFor, terminationReasonToString } from './termination'
import { nextTransition } from './transitions'
import { summarizeAssistantUsage, type UsageAttribution } from './token-usage'
import { loopRegistry } from '../utils/loop-registry'
export interface LoopEvent {
type: string
properties?: Record<string, unknown>
}
/**
* Callback invoked after the core state-machine portion of termination completes.
* Host-specific side-effects (teardown, toast, completion-log, sandbox-stop) live here.
*/
export type OnTerminatedCallback = (state: LoopState, reason: TerminationReason) => Promise<void>
export interface LoopRuntimeDeps {
loopsRepo: LoopsRepo
plansRepo: PlansRepo
reviewFindingsRepo: ReviewFindingsRepo
projectId: string
client: PluginInput['client']
v2Client: OpencodeClient
logger: Logger
getConfig: () => PluginConfig
sandboxManager?: ReturnType<typeof createSandboxManager>
dataDir?: string
onTerminated?: OnTerminatedCallback
notify?: LoopChangeNotifier
loopConfig?: LoopConfig
sectionPlansRepo?: SectionPlansRepo
loopSessionUsageRepo?: LoopSessionUsageRepo
}
export interface StartLoopInput {
state: LoopState
}
export interface Loop {
tick(event: LoopEvent): Promise<void>
start(input: StartLoopInput): void
cancel(name: string): Promise<void>
inspect(name: string): LoopState | null
listActive(): LoopState[]
listRecent(): LoopState[]
findMatchByName(name: string): { match: LoopState | null; candidates: LoopState[] }
hasOutstandingFindings(loopName?: string, severity?: 'bug' | 'warning'): boolean
terminateAll(): Promise<void>
terminate(name: string, reason: TerminationReason): Promise<boolean>
cancelBySessionId(sessionId: string): Promise<boolean>
runExclusive<T>(name: string, fn: () => Promise<T>): Promise<T>
clearLoopTimers(name: string): Promise<void>
clearAllRetryTimeouts(): void
recordActivity(name: string, source?: string): void
startWatchdog(name: string): void
getStallInfo(name: string): LoopWatchdogStallInfo | null
restart(name: string, params: { newState: LoopState; newSessionId: string }): void
generateUniqueLoopName(baseName: string): string
/** Transition a running loop's phase. */
setPhase(name: string, phase: LoopState['phase']): void
// State management methods (from LoopService)
resolveLoopName(sessionId: string): string | null
getActiveState(name: string): LoopState | null
getAnyState(name: string): LoopState | null
setState(name: string, state: LoopState): void
deleteState(name: string): void
registerLoopSession(sessionId: string, loopName: string): void
replaceSession(name: string, opts: { newSessionId: string; phase: LoopState['phase']; iteration?: number; resetError?: boolean; auditCount?: number; lastAuditResult?: string | null }): void
setStatus(name: string, status: 'running' | 'completed' | 'cancelled' | 'errored' | 'stalled'): void
setPhaseAndResetError(name: string, phase: LoopState['phase']): void
setModelFailed(name: string, failed: boolean): void
setLastAuditResult(name: string, text: string): void
clearLastAuditResult(name: string): void
setSandboxContainer(name: string, containerName: string | null): void
clearWorkspaceId(name: string): void
setWorkspaceId(name: string, workspaceId: string): void
incrementError(name: string): number
resetError(name: string): void
terminateLoop(name: string, opts: { status: 'completed' | 'cancelled' | 'errored' | 'stalled'; reason: string; completedAt: number; summary?: string }): void
getOutstandingFindings(loopName?: string, severity?: 'bug' | 'warning'): ReviewFindingRow[]
getStallTimeoutMs(): number
getMaxConsecutiveStalls(): number
// Prompt building methods
buildContinuationPrompt(state: LoopState, auditFindings?: string): string
buildAuditPrompt(state: LoopState): string
buildSectionInitialPrompt(state: LoopState): string
buildSectionAuditPrompt(state: LoopState): string
buildSectionContinuationPrompt(state: LoopState, auditText: string): string
buildFinalAuditPrompt(state: LoopState): string
// Plan and section methods
getPlanText(loopName: string, sessionId: string): string | null
getSectionPlan(state: LoopState, index: number): SectionPlanRow | null
getNextIncompleteSectionPlan(state: LoopState): SectionPlanRow | null
getCompletedSectionDigest(state: LoopState): { index: number; title: string; summaryDone: string | null; summaryDeviations: string | null; summaryFollowUps: string | null }[]
parseSectionSummary(text: string): { done: string | null; deviations: string | null; followUps: string | null } | null
completeSection(loopName: string, index: number, summary: { done: string | null; deviations: string | null; followUps: string | null }): void
incrementSectionAttempts(loopName: string, index: number): void
resetSectionForRewind(loopName: string, index: number): void
setCurrentSectionIndex(loopName: string, index: number): void
setFinalAuditDone(loopName: string, done: boolean): void
startSection(loopName: string, index: number): void
bulkInsertSections(loopName: string, sections: { index: number; title: string; content: string }[]): void
setTotalSections(loopName: string, total: number): void
}
export function isWorkspaceNotFoundError(err: unknown): boolean {
const msg = err instanceof Error ? err.message : typeof err === 'string' ? err : JSON.stringify(err ?? '')
return /Workspace not found/i.test(msg)
}
export function createLoop(deps: LoopRuntimeDeps): Loop {
const { loopsRepo, plansRepo, reviewFindingsRepo, projectId, client, v2Client, logger, getConfig, onTerminated, notify, loopConfig, sectionPlansRepo, loopSessionUsageRepo } = deps
const loopService = createLoopService(loopsRepo, plansRepo, reviewFindingsRepo, projectId, logger, loopConfig, notify, undefined, sectionPlansRepo)
const retryTimeouts = new Map<string, NodeJS.Timeout>()
const idleRetryTimeouts = new Map<string, NodeJS.Timeout>()
const idleRetryAttempts = new Map<string, number>()
const stateLocks = new Map<string, Promise<unknown>>()
const IDLE_RETRY_DELAY_MS = 1500
const MAX_IDLE_RETRIES = 1
const MAX_CODE_LAUNCH_RECOVERIES = MAX_RETRIES
const codingLaunchRecoveryAttempts = new Map<string, number>()
// Loops currently in "fix → re-final-audit" mode. When a final audit comes back dirty
// we rotate to a coding session with the findings, then on coding idle we transition
// straight back to final_auditing (skipping the per-section audit).
const pendingFinalAuditFix = new Set<string>()
interface RetainedSessionMeta {
sessionId: string
role: 'code' | 'auditor'
fallbackModel: string | undefined
directory: string
}
const loopRetainedSessions = new Map<string, RetainedSessionMeta[]>()
const SESSION_RETENTION = 0
function withStateLock<T>(loopName: string, fn: () => Promise<T>): Promise<T> {
const prev = stateLocks.get(loopName) ?? Promise.resolve()
const nextPromise = prev.catch(() => undefined).then(() => fn())
stateLocks.set(loopName, nextPromise)
void nextPromise.finally(() => {
if (stateLocks.get(loopName) === nextPromise) {
stateLocks.delete(loopName)
}
})
return nextPromise
}
async function sendPromptWithFallback(input: {
loopName: string
sessionId: string
promptText: string
agent: 'code' | 'auditor-loop'
model?: { providerID: string; modelID: string } | null
variant?: string
}): Promise<{ error?: unknown; usedModel?: { providerID: string; modelID: string } | undefined }> {
const { loopName, sessionId, promptText, agent } = input
if (agent === 'auditor-loop') {
const auditorModel = input.model != null ? input.model : undefined
const sendFn = async (model?: { providerID: string; modelID: string }) => {
const freshState = loopService.getActiveState(loopName)
if (!freshState?.active) throw new Error('loop_cancelled')
try {
return await withInFlightGuard(loopName, sessionId, 'auditor-loop', logger, async () => {
markPromptSent(loopName, sessionId, logger)
const result = await promptAuditSessionWithFallback({
sessionId,
worktreeDir: freshState.worktreeDir,
workspaceId: freshState.workspaceId,
prompt: promptText,
...(model ? { auditorModel: model, ...(input.variant ? { auditorVariant: input.variant } : {}) } : {}),
})
return result.ok ? { data: true } : { error: result.error }
})
} catch (err) {
if (err instanceof ConcurrentPromptError) return { error: err }
throw err
}
}
const { result, usedModel } = await retryWithModelFallback(() => sendFn(auditorModel), () => sendFn(undefined), auditorModel, logger)
if (result.error) {
if (result.error instanceof ConcurrentPromptError) {
return { error: result.error, usedModel }
}
clearPromptPending(loopName, logger)
}
return { error: result.error, usedModel }
}
const effectiveModel = input.model != null ? input.model : resolveLoopModel(getConfig(), loopService, loopName)
const sendFn = async (model?: { providerID: string; modelID: string }) => {
const freshState = loopService.getActiveState(loopName)
if (!freshState?.active) throw new Error('loop_cancelled')
try {
return await withInFlightGuard(loopName, sessionId, 'code', logger, async () => {
markPromptSent(loopName, sessionId, logger)
return await v2Client.session.promptAsync({
sessionID: sessionId,
directory: freshState.worktreeDir,
...(freshState.workspaceId ? { workspace: freshState.workspaceId } : {}),
agent: 'code',
parts: [{ type: 'text' as const, text: promptText }],
...(model ? { model, ...(input.variant ? { variant: input.variant } : {}) } : {}),
})
})
} catch (err) {
if (err instanceof ConcurrentPromptError) return { error: err }
throw err
}
}
const { result, usedModel } = await retryWithModelFallback(() => sendFn(effectiveModel), () => sendFn(undefined), effectiveModel, logger)
if (result.error) {
if (result.error instanceof ConcurrentPromptError) {
return { error: result.error, usedModel }
}
clearPromptPending(loopName, logger)
}
return { error: result.error, usedModel }
}
async function getLastAssistantInfo(sessionId: string, worktreeDir: string): Promise<{ text: string | null; error: string | null; lastMessageRole: string }> {
try {
let messagesResult = await v2Client.session.messages({
sessionID: sessionId,
directory: worktreeDir,
limit: 4,
})
if (messagesResult.error || !messagesResult.data?.length) {
try {
logger.log(`Loop: falling back to plugin client for session messages (${sessionId})`)
const legacyResult = await client.session.messages({
path: { id: sessionId },
query: { directory: worktreeDir, limit: 4 },
})
if (!legacyResult.error) {
messagesResult = legacyResult as typeof messagesResult
}
} catch (fallbackErr) {
logger.error(`Loop: plugin client session messages fallback failed for ${sessionId}`, fallbackErr)
}
}
const messages = (messagesResult.data ?? []) as Array<{
info: { role: string; finish?: string; error?: { name?: string; data?: { message?: string } } }
parts: Array<{ type: string; text?: string }>
}>
const lastMessage = messages.length > 0 ? messages[messages.length - 1] : null
if (!lastMessage) {
return { text: null, error: null, lastMessageRole: 'none' }
}
if (lastMessage.info.role !== 'assistant') {
logger.log(`Loop: no assistant message found in session ${sessionId}, last message role: ${lastMessage.info.role ?? 'unknown'}`)
return { text: null, error: null, lastMessageRole: lastMessage.info.role ?? 'unknown' }
}
const lastAssistant = lastMessage
if (lastAssistant.info.finish && lastAssistant.info.finish !== 'stop') {
logger.log(`Loop: assistant message in session ${sessionId} is not final yet (finish=${lastAssistant.info.finish})`)
return { text: null, error: null, lastMessageRole: `assistant:${lastAssistant.info.finish}` }
}
const text = lastAssistant.parts
.filter((p) => p.type === 'text' && typeof p.text === 'string')
.map((p) => p.text as string)
.join('\n') || null
const error = lastAssistant.info.error?.data?.message ?? lastAssistant.info.error?.name ?? null
return { text, error, lastMessageRole: 'assistant' }
} catch (err) {
logger.error(`Loop: could not read session messages`, err)
return { text: null, error: null, lastMessageRole: 'error' }
}
}
/**
* Determine the fallback model for a session based on phase and loop state.
* For code sessions: state.executionModel > config.executionModel > config.loop.model
* For audit/final-audit sessions: state.auditorModel > state.executionModel > config.auditorModel > config.executionModel
*/
function getFallbackModelForSession(state: LoopState, phase: LoopState['phase']): string | undefined {
const config = getConfig()
if (phase === 'auditing' || phase === 'final_auditing') {
return (
state.auditorModel ??
state.executionModel ??
config.auditorModel ??
config.executionModel
)
}
// Code session
return (
state.executionModel ??
config.executionModel ??
config.loop?.model
)
}
/**
* Capture and persist token usage for a loop session.
* Non-fatal: logs errors but does not block deletion or termination.
*/
async function captureLoopSessionUsage(input: {
loopName: string
sessionId: string
directory: string
role: 'code' | 'auditor' | 'unknown'
fallbackModel?: string
}): Promise<void> {
if (!loopSessionUsageRepo) {
return
}
try {
const messagesResult = await v2Client.session.messages({
sessionID: input.sessionId,
directory: input.directory,
})
const messages = (messagesResult.data ?? []) as Array<{
info: {
role: string
cost?: number
tokens?: { input: number; output: number; reasoning: number; cache: { read: number; write: number } }
model?: string
modelID?: string
modelId?: string
provider?: string
providerID?: string
model_name?: string
}
}>
const attribution: UsageAttribution = {
role: input.role,
fallbackModel: input.fallbackModel,
}
const usageSummary = summarizeAssistantUsage(messages, attribution)
if (usageSummary.perModel.length === 0) {
logger.debug(`Loop: no assistant usage to capture for session ${input.sessionId}`)
return
}
const rows = usageSummary.perModel.map((modelUsage) => ({
projectId,
loopName: input.loopName,
sessionId: input.sessionId,
role: input.role,
model: modelUsage.model,
cost: modelUsage.cost,
inputTokens: modelUsage.tokens.input,
outputTokens: modelUsage.tokens.output,
reasoningTokens: modelUsage.tokens.reasoning,
cacheReadTokens: modelUsage.tokens.cacheRead,
cacheWriteTokens: modelUsage.tokens.cacheWrite,
messageCount: modelUsage.messageCount,
capturedAt: Date.now(),
}))
loopSessionUsageRepo.upsertSessionUsage(rows)
logger.debug(`Loop: captured usage for session ${input.sessionId} (${input.role})`)
} catch (err) {
logger.error(`Loop: failed to capture usage for session ${input.sessionId}`, err)
}
}
function detachFromWorkspace(
loopName: string,
state: LoopState,
context?: string,
): void {
loopService.clearWorkspaceId(loopName)
state.workspaceId = undefined
publishWorkspaceDetachedToast({
v2: v2Client,
directory: state.projectDir ?? state.worktreeDir,
loopName,
logger,
context,
})
}
async function recoverFromMissingWorkspace(
loopName: string,
state: LoopState,
sessionId: string,
contextLabel: string,
bindError?: unknown,
): Promise<{ workspaceId?: string; recovered: boolean }> {
if (!state.workspaceId) {
return { recovered: false }
}
if (bindError && !isWorkspaceNotFoundError(bindError)) {
logger.log(`Loop: skipping workspace re-provision for ${loopName} because bind error is not "workspace not found"`)
return { recovered: false }
}
detachFromWorkspace(loopName, state, contextLabel)
const { createBuiltinWorktreeWorkspace } = await import('../workspace/forge-worktree')
const projectDirectory = state.projectDir ?? state.worktreeDir
if (!projectDirectory) {
logger.log(`Loop: cannot recover workspace for ${loopName}: no projectDir/worktreeDir`)
return { recovered: false }
}
const newWorkspace = await createBuiltinWorktreeWorkspace(
v2Client,
{
loopName,
directory: projectDirectory,
},
logger,
)
if (!newWorkspace) {
logger.error(`Loop: workspace re-provision failed for ${loopName}, continuing without workspace backing`)
return { recovered: false }
}
try {
await bindSessionToWorkspace(v2Client, newWorkspace.workspaceId, sessionId, logger, { loopName })
loopService.setWorkspaceId(loopName, newWorkspace.workspaceId)
state.workspaceId = newWorkspace.workspaceId
if (newWorkspace.directory) state.worktreeDir = newWorkspace.directory
if (newWorkspace.branch) state.worktreeBranch = newWorkspace.branch
logger.log(`Loop: re-provisioned workspace ${newWorkspace.workspaceId} for ${loopName} after stale id`)
return { workspaceId: newWorkspace.workspaceId, recovered: true }
} catch (err) {
logger.error(`Loop: failed to bind session to re-provisioned workspace ${newWorkspace.workspaceId}`, err)
return { recovered: false }
}
}
async function ensureWorkspaceForLoop(
loopName: string,
state: LoopState,
contextLabel: string,
): Promise<{ workspaceId?: string }> {
if (state.workspaceId) {
return { workspaceId: state.workspaceId }
}
if (!state.worktree) {
return {}
}
const { createBuiltinWorktreeWorkspace } = await import('../workspace/forge-worktree')
const projectDirectory = state.projectDir ?? state.worktreeDir
if (!projectDirectory) {
logger.log(`Loop: cannot provision workspace for ${loopName} (${contextLabel}): no projectDir/worktreeDir`)
return {}
}
const workspace = await createBuiltinWorktreeWorkspace(
v2Client,
{
loopName,
directory: projectDirectory,
},
logger,
)
if (!workspace) {
logger.log(`Loop: workspace creation failed for ${loopName} (${contextLabel}), continuing without workspace backing`)
return {}
}
loopService.setWorkspaceId(loopName, workspace.workspaceId)
state.workspaceId = workspace.workspaceId
if (workspace.directory) state.worktreeDir = workspace.directory
if (workspace.branch) state.worktreeBranch = workspace.branch
logger.log(`Loop: provisioned workspace ${workspace.workspaceId} for ${loopName} (${contextLabel})`)
return { workspaceId: workspace.workspaceId }
}
/**
* Rotates to a new session in the same workspace. Creates and binds the new session FIRST,
* then fire-and-forget deletes the old session. This ordering ensures the workspace always
* has at least one bound session, preventing the host from pruning it from non-focused TUIs.
*/
async function rotateSession(
loopName: string,
state: LoopState,
titleContext?: { iteration?: number; currentSectionIndex?: number },
): Promise<string> {
const oldSessionId = state.sessionId
const sessionDir = state.worktreeDir
clearPromptPending(loopName, logger)
logger.log(
`Loop: [perm-diag] rotate loop=${loopName} state.worktree=${String(state.worktree)} state.sandbox=${String(state.sandbox)}`
)
const permissionRuleset = buildLoopPermissionRuleset({ sandbox: state.sandbox ?? false })
const ensured = await ensureWorkspaceForLoop(loopName, state, 'during session rotation')
const createResult = await createLoopSessionWithWorkspace({
v2: v2Client,
title: formatLoopSessionTitle(state.loopName, {
iteration: titleContext?.iteration ?? state.iteration ?? 0,
currentSectionIndex: titleContext?.currentSectionIndex ?? state.currentSectionIndex ?? 0,
totalSections: state.totalSections ?? 0,
}),
directory: sessionDir,
permission: permissionRuleset,
workspaceId: ensured.workspaceId ?? state.workspaceId,
loopName: loopName,
logPrefix: 'Loop',
logger,
})
if (!createResult) {
throw new Error('Failed to create new session.')
}
const newSessionId = createResult.sessionId
if (createResult.bindFailed) {
detachFromWorkspace(loopName, state, 'during session rotation')
}
const oldRetryTimeout = retryTimeouts.get(loopName)
if (oldRetryTimeout) {
clearTimeout(oldRetryTimeout)
retryTimeouts.delete(loopName)
}
loopService.registerLoopSession(newSessionId, loopName)
watchdog.stop(loopName)
watchdog.start(loopName)
void scheduleSessionDelete({ loopName, sessionId: oldSessionId, directory: sessionDir, context: 'after session rotation', phase: state.phase, state })
logger.log(`Loop: rotated session ${oldSessionId} → ${newSessionId}`)
return newSessionId
}
/**
* Shared: handle assistant error detection and model failure.
* Returns null if the loop was terminated (caller should return).
* Returns updated { assistantErrorDetected, currentState }.
*/
async function detectAndHandleAssistantError(
loopName: string,
currentState: LoopState,
assistantError: string | null,
phase: string,
): Promise<{ assistantErrorDetected: boolean; currentState: LoopState } | null> {
if (!assistantError) {
return { assistantErrorDetected: false, currentState }
}
logger.error(`Loop: assistant error detected in ${phase} phase: ${assistantError}`)
const isModelError = /provider|auth|model|api\s*error/i.test(assistantError)
if (isModelError) {
const nextErrorCount = loopService.incrementError(loopName)
if (nextErrorCount >= MAX_RETRIES) {
await terminateLoop(loopName, currentState, { kind: 'error_max_retries', message: `assistant error: ${assistantError}` })
return null
}
loopService.setModelFailed(loopName, true)
logger.log(`Loop: marking model as failed, will fall back to default model (error ${nextErrorCount}/${MAX_RETRIES})`)
return { assistantErrorDetected: true, currentState: loopService.getActiveState(loopName)! }
}
return { assistantErrorDetected: true, currentState }
}
/**
* Shared: check audit clear and terminate if ready.
* Returns true if the loop was terminated (caller should return).
*/
async function checkAuditClearAndTerminate(
loopName: string,
currentState: LoopState,
): Promise<boolean> {
logger.debug(`Loop: checking audit clear loop=${loopName} auditCount=${currentState.auditCount ?? 0} loopName=${currentState.loopName ?? '(none)'}`)
if ((currentState.auditCount ?? 0) < 1) {
logger.debug(`Loop: audit clear gate blocked by auditCount<1`)
return false
}
// For sectioned loops, require finalAuditDone === true before terminating
if (currentState.totalSections > 0 && !currentState.finalAuditDone) {
logger.debug(`Loop: audit clear gate blocked for sectioned loop — finalAuditDone=false`)
return false
}
const findings = loopService.getOutstandingFindings(currentState.loopName)
if (findings.length > 0) {
logger.log(`Loop: audit complete but ${findings.length} review finding(s) remain, continuing`)
return false
}
const bugFindings = loopService.getOutstandingFindings(currentState.loopName, 'bug')
if (bugFindings.length > 0) {
logger.log(`Loop: refused completion — ${bugFindings.length} bug finding(s) still open`)
return false
}
logger.log(`Loop: audit all-clear, terminating loop=${loopName} iteration=${currentState.iteration} audits=${currentState.auditCount ?? 0}`)
await terminateLoop(loopName, currentState, { kind: 'completed' })
logger.log(`Loop completed: auditor all-clear at iteration ${currentState.iteration} (audits=${currentState.auditCount ?? 0})`)
return true
}
/**
* Shared: reset error count after a successful (non-error) iteration.
*/
function resetErrorCountIfNeeded(loopName: string, currentState: LoopState, assistantErrorDetected: boolean, phase: string): LoopState {
if (!assistantErrorDetected && currentState.errorCount && currentState.errorCount > 0) {
loopService.resetError(loopName)
loopService.setModelFailed(loopName, false)
logger.log(`Loop: resetting error count after successful retry in ${phase} phase`)
return loopService.getActiveState(loopName)!
}
return currentState
}
/**
* Shared: rotate session and send continuation prompt with model fallback.
*/
async function rotateAndSendContinuation(
loopName: string,
currentState: LoopState,
stateUpdates: Partial<LoopState>,
continuationPrompt: string,
assistantErrorDetected: boolean,
errorContext: string,
): Promise<void> {
let activeSessionId = currentState.sessionId
try {
activeSessionId = await rotateSession(loopName, currentState, {
iteration: stateUpdates.iteration ?? currentState.iteration,
currentSectionIndex: stateUpdates.currentSectionIndex ?? currentState.currentSectionIndex,
})
} catch (err) {
logger.error(`Loop: session rotation failed, continuing with existing session`, err)
}
loopService.replaceSession(loopName, {
newSessionId: activeSessionId,
phase: stateUpdates.phase ?? 'coding',
iteration: stateUpdates.iteration ?? currentState.iteration,
resetError: !assistantErrorDetected && currentState.errorCount > 0,
auditCount: stateUpdates.auditCount,
lastAuditResult: stateUpdates.lastAuditResult ?? null,
})
const nextIteration = stateUpdates.iteration ?? currentState.iteration
logger.log(`Loop iteration ${nextIteration} for session ${activeSessionId}`)
const currentConfig = getConfig()
const loopModel = resolveLoopModel(currentConfig, loopService, loopName)
if (!loopModel) {
logger.log(`Loop: configured model previously failed, using default model`)
}
const { error: promptResultError, usedModel: actualModel } = await sendPromptWithFallback({
loopName,
sessionId: activeSessionId,
promptText: continuationPrompt,
agent: 'code',
model: loopModel,
variant: currentState.executionVariant,
})
if (promptResultError) {
const retryFn = async () => {
const freshState = loopService.getActiveState(loopName)
if (!freshState?.active) throw new Error('loop_cancelled')
try {
await withInFlightGuard(loopName, activeSessionId, 'code', logger, async () => {
const result = await v2Client.session.promptAsync({
sessionID: activeSessionId,
directory: freshState.worktreeDir,
...(freshState.workspaceId ? { workspace: freshState.workspaceId } : {}),
agent: 'code',
parts: [{ type: 'text' as const, text: continuationPrompt }],
})
if (result.error) {
await handlePromptError(loopName, currentState, `retry failed ${errorContext}`, result.error)
return
}
})
} catch (err) {
if (err instanceof ConcurrentPromptError) { logger.log(`Loop: ${errorContext} — retry rejected as concurrent prompt (prior guard active), skipping`); return }
throw err
}
}
await handlePromptError(loopName, currentState, `failed to send continuation prompt ${errorContext}`, promptResultError, retryFn)
return
}
if (actualModel) {
logger.log(`${errorContext} using model: ${actualModel.providerID}/${actualModel.modelID}`)
} else {
logger.log(`${errorContext} using default model (fallback)`)
}
watchdog.recordActivity(loopName, 'phase-activity')
}
async function rotateToCodingAfterAuditFailure(loopName: string, state: LoopState, reason: string): Promise<void> {
const newSessionId = await rotateSession(loopName, state)
loopService.replaceSession(loopName, {
newSessionId,
phase: 'coding',
resetError: false,
})
loopService.setLastAuditResult(loopName, state.lastAuditResult ?? '')
const isModelError = /provider|auth|model|api\s*error/i.test(reason)
if (isModelError) {
loopService.setModelFailed(loopName, true)
}
const continuationPrompt = loopService.buildContinuationPrompt(
{ ...state, iteration: state.iteration ?? 0 },
`\n[Auditor session failed: ${reason}. Continuing without new findings.]`,
)
const loopModel = resolveLoopModel(getConfig(), loopService, loopName)
const { error } = await sendPromptWithFallback({
loopName,
sessionId: newSessionId,
promptText: continuationPrompt,
agent: 'code',
model: loopModel,
variant: state.executionVariant,
})
if (error) {
logger.error(`rotateToCodingAfterAuditFailure: failed to send continuation prompt`, error)
}
}
function buildCodingPromptForCurrentState(state: LoopState): string {
if (pendingFinalAuditFix.has(state.loopName)) {
return loopService.buildFinalAuditFixPrompt(state, state.lastAuditResult || '')
}
if (state.totalSections > 0) {
if (state.lastAuditResult) {
return loopService.buildSectionContinuationPrompt(state, state.lastAuditResult)
}
return loopService.buildSectionInitialPrompt(state)
}
return loopService.buildContinuationPrompt(state, state.lastAuditResult || undefined)
}
async function recoverCodeLaunchWithoutAssistant(loopName: string, state: LoopState, lastMessageRole: string): Promise<void> {
const attempts = (codingLaunchRecoveryAttempts.get(loopName) ?? 0) + 1
codingLaunchRecoveryAttempts.set(loopName, attempts)
if (attempts > MAX_CODE_LAUNCH_RECOVERIES) {
logger.error(`Loop: coding launch failed after ${attempts} no-assistant idle events for ${loopName} (last=${lastMessageRole})`)
await terminateLoop(loopName, state, { kind: 'coding_no_assistant' })
return
}
const recoveryPrompt = buildCodingPromptForCurrentState(state)
logger.log(`Loop: recovering code launch for ${loopName} (attempt ${attempts}/${MAX_CODE_LAUNCH_RECOVERIES}, last=${lastMessageRole})`)
const codeSessionId = state.sessionId
try {
const freshState = loopService.getActiveState(loopName)
if (!freshState?.active || freshState.phase !== 'coding' || freshState.sessionId !== codeSessionId) return
const currentConfig = getConfig()
const { error: promptResultError } = await sendPromptWithFallback({
loopName,
sessionId: codeSessionId,
promptText: recoveryPrompt,
agent: 'code',
model: resolveLoopModel(currentConfig, loopService, loopName),
variant: freshState.executionVariant,
})
if (promptResultError) {
clearPromptPending(loopName, logger)
logger.error(`Loop: failed to send recovery prompt for ${loopName}`, promptResultError)
const retryFn = async () => {
const fresh = loopService.getActiveState(loopName)
if (!fresh?.active || fresh.phase !== 'coding' || fresh.sessionId !== codeSessionId) throw new Error('loop_cancelled')
try {
await withInFlightGuard(loopName, codeSessionId, 'code', logger, async () => {
const result = await v2Client.session.promptAsync({
sessionID: codeSessionId,
directory: fresh.worktreeDir,
...(fresh.workspaceId ? { workspace: fresh.workspaceId } : {}),
agent: 'code',
parts: [{ type: 'text' as const, text: recoveryPrompt }],
})
if (result.error) throw result.error
})
} catch (err) {
if (err instanceof ConcurrentPromptError) { logger.log('Loop: failed to recover code launch — retry rejected as concurrent prompt (prior guard active), skipping'); return }
throw err
}
}
await handlePromptError(loopName, freshState ?? state, 'failed to recover code launch', promptResultError, retryFn)
}
} catch (err) {
logger.error(`Loop: failed to recover code launch for ${loopName}`, err)
await handlePromptError(loopName, state, 'failed to recover code launch', err)
}
}
async function scheduleSessionDelete(input: {
loopName: string
sessionId: string
directory: string
context: string
phase?: LoopState['phase']
state?: LoopState
}): Promise<void> {
const { loopName, sessionId, directory, context, phase, state } = input
const queue = loopRetainedSessions.get(loopName) ?? []
// Check if already queued by sessionId
if (queue.some(entry => entry.sessionId === sessionId)) return
// Determine role and fallback model at queue time
const role: 'code' | 'auditor' = phase && (phase === 'auditing' || phase === 'final_auditing') ? 'auditor' : 'code'
const fallbackModel = phase && state ? getFallbackModelForSession(state, phase) : undefined
queue.push({ sessionId, role, fallbackModel, directory })
loopRetainedSessions.set(loopName, queue)
logger.debug(`Loop: queued session ${sessionId} for retention (loop=${loopName}, context=${context}, queue=${queue.length})`)
while (queue.length > SESSION_RETENTION) {
const oldest = queue.shift()!
logger.log(`Loop: trimming session ${oldest.sessionId} (loop=${loopName}, retention=${SESSION_RETENTION})`)
// Capture usage before deletion using stored metadata
await captureLoopSessionUsage({
loopName,
sessionId: oldest.sessionId,
directory: oldest.directory,
role: oldest.role,
fallbackModel: oldest.fallbackModel,
})
void v2Client.session.delete({ sessionID: oldest.sessionId, directory: oldest.directory }).catch((err: unknown) => {
logger.error(`Loop: failed to delete trimmed session ${oldest.sessionId} (loop=${loopName})`, err)
})
}
}
async function terminateLoop(loopName: string, state: LoopState, reason: TerminationReason): Promise<void> {
const sessionId = state.sessionId
watchdog.stop(loopName)
loopRegistry.remove(loopName)
const retryTimeout = retryTimeouts.get(loopName)
if (retryTimeout) {
clearTimeout(retryTimeout)
retryTimeouts.delete(loopName)
}
const idleRetryTimeout = idleRetryTimeouts.get(loopName)
if (idleRetryTimeout) {
clearTimeout(idleRetryTimeout)
idleRetryTimeouts.delete(loopName)
}
idleRetryAttempts.delete(loopName)
codingLaunchRecoveryAttempts.delete(loopName)
pendingFinalAuditFix.delete(loopName)
clearPromptPending(loopName, logger)
clearPromptInFlight(loopName)
const retained = loopRetainedSessions.get(loopName)
if (retained) {
// Capture usage for retained sessions before deletion using stored metadata
for (const entry of retained) {
if (entry.sessionId === sessionId) continue
await captureLoopSessionUsage({
loopName,
sessionId: entry.sessionId,
directory: entry.directory,
role: entry.role,
fallbackModel: entry.fallbackModel,
}).catch((err: unknown) => {
logger.error(`Loop: failed to capture usage for retained session ${entry.sessionId} on terminate (loop=${loopName})`, err)
})
void v2Client.session.delete({ sessionID: entry.sessionId, directory: entry.directory }).catch((err: unknown) => {
logger.error(`Loop: failed to delete retained session ${entry.sessionId} on terminate (loop=${loopName})`, err)
})
}
loopRetainedSessions.delete(loopName)
}
// Capture usage for the final active session before termination
const fallbackModel = getFallbackModelForSession(state, state.phase)
const role: 'code' | 'auditor' = state.phase === 'auditing' || state.phase === 'final_auditing' ? 'auditor' : 'code'
await captureLoopSessionUsage({
loopName,
sessionId: state.sessionId,
directory: state.worktreeDir,
role,
fallbackModel,
})
const now = Date.now()
loopService.terminate(loopName, {
status: terminationStatusFor(reason),
reason: terminationReasonToString(reason),
completedAt: now,
})
try {
await v2Client.session.abort({ sessionID: sessionId })
} catch {
// Session may already be idle
}
logger.log(`Loop terminated: reason="${terminationReasonToString(reason)}", loop="${state.loopName}", iteration=${state.iteration}`)
logger.debug(`Loop: terminateLoop reason=${terminationReasonToString(reason)} worktree=${!!state.worktree} logEligible=${reason.kind === 'completed' && !!state.worktree}`)
// Delegate host-specific side-effects to the provided callback.
// This keeps worktree teardown, completion log, sandbox stop, TUI toast outside the core module.
if (onTerminated) {
await onTerminated(state, reason)
}
}
async function handlePromptError(loopName: string, _state: LoopState, context: string, err: unknown, retryFn?: () => Promise<void>): Promise<void> {
if (err instanceof ConcurrentPromptError) {
logger.log(`Loop: ${context} — rejected as concurrent prompt (prior guard active), skipping retry/termination`)
return
}
const currentState = loopService.getActiveState(loopName)
if (!currentState?.active) {
logger.log(`Loop: loop ${loopName} already terminated, ignoring error: ${context}`)
return
}
const nextErrorCount = (currentState.errorCount ?? 0) + 1
if (nextErrorCount < MAX_RETRIES) {
logger.error(`Loop: ${context} (attempt ${nextErrorCount}/${MAX_RETRIES}), will retry`, err)
loopService.incrementError(loopName)
if (retryFn) {
const retryTimeout = setTimeout(async () => {
const freshState = loopService.getActiveState(loopName)
if (!freshState?.active) {
logger.log(`Loop: loop cancelled, skipping retry`)
retryTimeouts.delete(loopName)
return
}
try {
await retryFn()
} catch (retryErr) {
await handlePromptError(loopName, freshState, context, retryErr, retryFn)
}