diff --git a/backend/src/index.ts b/backend/src/index.ts index d8ba7250..1fbca0b8 100644 --- a/backend/src/index.ts +++ b/backend/src/index.ts @@ -233,11 +233,15 @@ const scheduleRunnerInstance = new ScheduleRunner(scheduleService) const notificationService = new NotificationService(db) const sessionPermissionModeService = new SessionPermissionModeService(db, openCodeClient, settingsServiceForSchedules) const sessionGoalService = new SessionGoalService(db, openCodeClient, settingsServiceForSchedules) +sessionGoalService.loadOpenGoals() sseAggregator.onEvent((directory, event) => { sessionPermissionModeService.handleEvent(directory, event).catch((err) => { logger.error('Session permission mode event handling error:', err) }) + sessionGoalService.handleEvent(directory, event).catch((err) => { + logger.error('Session goal event handling error:', err) + }) }) notificationService.addEventSuppressor(async (event, sessionId) => { diff --git a/backend/src/services/session-goal-audit.ts b/backend/src/services/session-goal-audit.ts new file mode 100644 index 00000000..83e96dbe --- /dev/null +++ b/backend/src/services/session-goal-audit.ts @@ -0,0 +1,138 @@ +import { SessionGoalVerdictSchema, type SessionGoalVerdict } from '@opencode-manager/shared/schemas' + +export const GOAL_AUDIT_REPLY_MAX_CHARS = 20000 +export const GOAL_AUDIT_REASON_MAX_CHARS = 500 +export const GOAL_AUDIT_UNPARSED_REASON = 'Auditor response was not understood' + +export interface GoalAuditPromptInput { + objective: string + reply: string | null +} + +export interface GoalContinuationPromptInput { + objective: string + reason: string +} + +export interface GoalVerdict { + verdict: SessionGoalVerdict + reason: string +} + +export function buildGoalAuditPrompt({ objective, reply }: GoalAuditPromptInput): string { + return [ + 'You audit whether an autonomous coding goal has been achieved.', + 'You can only see the goal objective and the agent\'s latest reply. You cannot run tools or read files.', + '', + 'Goal objective:', + objective, + '', + 'Agent\'s latest reply:', + truncateReply(reply), + '', + 'Decide the goal state:', + '- "done": the objective is verifiably achieved based on the reply.', + '- "blocked": the agent needs a user decision or access it cannot obtain.', + '- "continue": anything else, including when the reply is not enough to confirm completion.', + '', + 'Respond with only this JSON and nothing else:', + '{"verdict":"continue"|"done"|"blocked","reason":""}', + ].join('\n') +} + +export function buildGoalContinuationPrompt({ objective, reason }: GoalContinuationPromptInput): string { + return [ + `Continue working toward this goal: ${objective}`, + '', + `Progress check: ${reason}`, + '', + 'Keep working until the goal is achieved. If you need a user decision or access you cannot obtain, stop and state exactly what you need.', + ].join('\n') +} + +export function parseGoalVerdict(text: string): GoalVerdict | null { + const block = extractFirstJsonObject(text) + if (!block) { + return null + } + + let parsed: unknown + try { + parsed = JSON.parse(block) + } catch { + return null + } + + if (typeof parsed !== 'object' || parsed === null) { + return null + } + + const candidate = parsed as { verdict?: unknown; reason?: unknown } + const verdict = SessionGoalVerdictSchema.safeParse(candidate.verdict) + if (!verdict.success) { + return null + } + + if (typeof candidate.reason !== 'string') { + return null + } + + const reason = candidate.reason.trim() + if (!reason) { + return null + } + + return { verdict: verdict.data, reason: reason.slice(0, GOAL_AUDIT_REASON_MAX_CHARS) } +} + +function truncateReply(reply: string | null): string { + if (!reply) { + return '(no reply yet)' + } + if (reply.length <= GOAL_AUDIT_REPLY_MAX_CHARS) { + return reply + } + return `${reply.slice(0, GOAL_AUDIT_REPLY_MAX_CHARS)}\n\n[reply truncated]` +} + +function extractFirstJsonObject(text: string): string | null { + const start = text.indexOf('{') + if (start === -1) { + return null + } + + let depth = 0 + let inString = false + let escaped = false + + for (let index = start; index < text.length; index += 1) { + const char = text[index] + + if (inString) { + if (escaped) { + escaped = false + } else if (char === '\\') { + escaped = true + } else if (char === '"') { + inString = false + } + continue + } + + if (char === '"') { + inString = true + continue + } + + if (char === '{') { + depth += 1 + } else if (char === '}') { + depth -= 1 + if (depth === 0) { + return text.slice(start, index + 1) + } + } + } + + return null +} diff --git a/backend/src/services/session-goals.ts b/backend/src/services/session-goals.ts index 07686560..95a25908 100644 --- a/backend/src/services/session-goals.ts +++ b/backend/src/services/session-goals.ts @@ -3,19 +3,43 @@ import { DEFAULT_SESSION_DEFAULTS, type SessionGoal, type SessionGoalStatus, + type SessionGoalStopReason, + type SessionGoalTurnState, type StartSessionGoalRequest, } from '@opencode-manager/shared/schemas' +import { parseOpenCodeModelRef, sessionIDFromEvent, type ModelRef } from '@opencode-manager/shared/opencode' import { getLatestSessionGoal, getSessionGoalById, insertSessionGoal, + listOpenSessionGoals, transitionSessionGoal, type SessionGoalPatch, type SessionGoalRecord, } from '../db/session-goals' import { logger } from '../utils/logger' +import { + buildGoalAuditPrompt, + buildGoalContinuationPrompt, + GOAL_AUDIT_UNPARSED_REASON, + parseGoalVerdict, + type GoalVerdict, +} from './session-goal-audit' +import { isSessionBusy, readLatestAssistantReply, type AssistantReplyState } from './session-reply' import type { OpenCodeClient } from './opencode/client' import type { SettingsService } from './settings' +import type { SSEEvent } from './sse-aggregator' + +const DEFAULT_QUIET_MS = 3000 +const BLOCKED_LIMIT = 3 +const AUDITOR_ATTEMPTS = 2 + +type PrerequisiteResult = { ok: true; value: T } | { ok: false } + +export interface SessionGoalServiceOptions { + quietMs?: number + onOutcome?: (goal: SessionGoal) => void +} export class SessionGoalError extends Error { status: number @@ -53,18 +77,37 @@ export function toSessionGoal(record: SessionGoalRecord): SessionGoal { } export class SessionGoalService { + private readonly goalBySession = new Map() + private readonly auditTimers = new Map>() + private readonly auditing = new Set() + private readonly auditRequested = new Set() + private readonly auditGeneration = new Map() + private readonly quietMs: number + private readonly onOutcome: (goal: SessionGoal) => void + constructor( private readonly db: Database, private readonly openCodeClient: OpenCodeClient, private readonly settingsService: SettingsService, - ) {} + options: SessionGoalServiceOptions = {}, + ) { + this.quietMs = options.quietMs ?? DEFAULT_QUIET_MS + this.onOutcome = options.onOutcome ?? (() => {}) + } + + loadOpenGoals(): void { + this.goalBySession.clear() + for (const record of listOpenSessionGoals(this.db)) { + this.goalBySession.set(record.sessionId, record.id) + } + } async start(input: StartSessionGoalRequest): Promise { const defaults = this.settingsService.getSettings().preferences.sessionDefaults const maxContinuations = input.maxContinuations ?? defaults?.goalMaxContinuations ?? DEFAULT_SESSION_DEFAULTS.goalMaxContinuations const tokenBudget = input.tokenBudget ?? defaults?.goalTokenBudget ?? null - const tokensAtStart = await this.readSessionTokenTotal(input.sessionId) + const tokensAtStart = await this.readSessionTokenTotalOrDefault(input.sessionId) const record = insertSessionGoal(this.db, { sessionId: input.sessionId, @@ -79,6 +122,7 @@ export class SessionGoalService { throw new SessionGoalError('This session already has an open goal', 409) } + this.goalBySession.set(record.sessionId, record.id) return toSessionGoal(record) } @@ -88,42 +132,431 @@ export class SessionGoalService { } pause(id: number): SessionGoal { - return toSessionGoal(this.transition(id, ['active'], { status: 'paused', stopReason: 'user_paused' })) + return this.transitionWithOutcome(id, ['active'], { status: 'paused', stopReason: 'user_paused' }) } resume(id: number): SessionGoal { - return toSessionGoal(this.transition(id, ['paused'], { + const record = this.transition(id, ['paused'], { status: 'active', stopReason: null, turnState: 'running', finishedAt: null, - })) + }) + + const goal = toSessionGoal(record) + void this.scheduleAuditWhenIdle(goal) + return goal } cancel(id: number): SessionGoal { - return toSessionGoal(this.transition(id, ['active', 'paused'], { + return this.transitionWithOutcome(id, ['active', 'paused'], { status: 'stopped', stopReason: 'cancelled', finishedAt: Date.now(), - })) + }) + } + + async handleEvent(directory: string, event: SSEEvent): Promise { + const sessionId = sessionIDFromEvent(event) + if (!sessionId) { + return + } + + const goalId = this.goalBySession.get(sessionId) + if (goalId === undefined) { + return + } + + switch (event.type) { + case 'session.execution.started': + this.clearAuditTimer(sessionId) + this.applyTransition(goalId, ['active'], { turnState: 'running' }) + return + case 'session.idle': + case 'session.execution.succeeded': + this.scheduleAuditFromEvent(sessionId, goalId) + return + case 'session.status': + if (event.data.status.type === 'idle') { + this.scheduleAuditFromEvent(sessionId, goalId) + } + return + case 'session.execution.failed': + this.clearAuditTimer(sessionId) + this.finishGoal(goalId, 'stopped', 'turn_error') + return + case 'session.execution.interrupted': + this.clearAuditTimer(sessionId) + this.finishGoal(goalId, 'paused', 'interrupted') + return + case 'session.deleted': + this.clearAuditTimer(sessionId) + this.finishGoal(goalId, 'stopped', 'session_deleted', ['active', 'paused']) + return + default: + return + } + } + + private scheduleAuditFromEvent(sessionId: string, goalId: number): void { + const record = getSessionGoalById(this.db, goalId) + if (!record || record.status !== 'active' || record.turnState !== 'running') { + return + } + this.scheduleAudit(sessionId, goalId, this.quietMs) + } + + private async scheduleAuditWhenIdle(goal: SessionGoal): Promise { + const generation = this.currentAuditGeneration(goal.sessionId) + const busy = await this.readPrerequisite(goal.id, 'busy check', () => + isSessionBusy(this.openCodeClient, goal.sessionId), + ) + + if (!busy.ok) { + this.failAudit(goal.id, goal.sessionId, generation) + return + } + if (!this.isAuditCurrent(goal.id, goal.sessionId, generation)) { + return + } + if (busy.value) { + return + } + this.scheduleAudit(goal.sessionId, goal.id, 0) + } + + private scheduleAudit(sessionId: string, goalId: number, delay: number): void { + this.clearAuditTimer(sessionId) + const timer = setTimeout(() => { + this.auditTimers.delete(sessionId) + void this.runAudit(goalId).catch((error) => { + logger.error(`Session goal audit failed for goal ${goalId}:`, error) + }) + }, delay) + this.auditTimers.set(sessionId, timer) + } + + private clearAuditTimer(sessionId: string): void { + const timer = this.auditTimers.get(sessionId) + if (timer !== undefined) { + clearTimeout(timer) + this.auditTimers.delete(sessionId) + } + } + + private async runAudit(goalId: number): Promise { + if (this.auditing.has(goalId)) { + this.auditRequested.add(goalId) + return + } + + this.auditing.add(goalId) + try { + let pending = true + while (pending) { + this.auditRequested.delete(goalId) + await this.performAudit(goalId) + pending = this.auditRequested.has(goalId) + } + } finally { + this.auditing.delete(goalId) + } + } + + private async performAudit(goalId: number): Promise { + const goal = getSessionGoalById(this.db, goalId) + if (!goal || goal.status !== 'active' || goal.turnState !== 'running') { + return + } + + const sessionId = goal.sessionId + const generation = this.currentAuditGeneration(sessionId) + + const busy = await this.readPrerequisite(goalId, 'busy check', () => + isSessionBusy(this.openCodeClient, sessionId), + ) + if (!busy.ok) { + this.failAudit(goalId, sessionId, generation) + return + } + if (!this.isAuditCurrent(goalId, sessionId, generation) || busy.value) { + return + } + + const total = await this.readPrerequisite(goalId, 'token read', () => + this.readSessionTokenTotal(sessionId), + ) + if (!total.ok) { + this.failAudit(goalId, sessionId, generation) + return + } + if (!this.isAuditCurrent(goalId, sessionId, generation)) { + return + } + + const tokensUsed = Math.max(0, total.value - goal.tokensAtStart) + const updated = this.applyTransition(goalId, ['active'], { tokensUsed }) + if (!updated) { + return + } + + if (updated.tokenBudget !== null && tokensUsed >= updated.tokenBudget) { + this.finishGoal(goalId, 'stopped', 'token_budget') + return + } + + const reply = await this.readPrerequisite(goalId, 'reply read', () => + readLatestAssistantReply(this.openCodeClient, sessionId), + ) + if (!reply.ok) { + this.failAudit(goalId, sessionId, generation) + return + } + if (!this.isAuditCurrent(goalId, sessionId, generation)) { + return + } + + if (reply.value?.errorText) { + this.finishGoal(goalId, 'stopped', 'turn_error') + return + } + + const verdict = await this.evaluateAudit(updated, reply.value) + if (!this.isAuditCurrent(goalId, sessionId, generation)) { + return + } + if (!verdict) { + this.finishGoal(goalId, 'paused', 'audit_failed') + return + } + + await this.applyVerdict(goalId, sessionId, generation, updated, verdict) + } + + private async evaluateAudit(goal: SessionGoalRecord, reply: AssistantReplyState | null): Promise { + const prompt = buildGoalAuditPrompt({ objective: goal.objective, reply: reply?.responseText ?? null }) + const model = this.resolveAuditorModel() + + for (let attempt = 0; attempt < AUDITOR_ATTEMPTS; attempt += 1) { + try { + const result = await this.openCodeClient.api.generate.text(model ? { prompt, model } : { prompt }) + return parseGoalVerdict(result.text) ?? { verdict: 'continue', reason: GOAL_AUDIT_UNPARSED_REASON } + } catch (error) { + logger.error(`Goal auditor call failed for goal ${goal.id} (attempt ${attempt + 1}):`, error) + } + } + + return null + } + + private resolveAuditorModel(): ModelRef | undefined { + const configured = this.settingsService.getSettings().preferences.sessionDefaults?.goalAuditorModel + return configured ? parseOpenCodeModelRef(configured) : undefined + } + + private async applyVerdict( + goalId: number, + sessionId: string, + generation: number, + goal: SessionGoalRecord, + verdict: GoalVerdict, + ): Promise { + if (!this.isAuditCurrent(goalId, sessionId, generation)) { + return + } + + if (verdict.verdict === 'done') { + this.finishGoal(goalId, 'completed', null, ['active'], { + lastVerdict: 'done', + lastReason: verdict.reason, + }) + return + } + + if (verdict.verdict === 'blocked') { + const consecutiveBlocked = goal.consecutiveBlocked + 1 + const patch: SessionGoalPatch = { + consecutiveBlocked, + lastVerdict: 'blocked', + lastReason: verdict.reason, + } + + if (consecutiveBlocked >= BLOCKED_LIMIT) { + this.finishGoal(goalId, 'blocked', null, ['active'], patch) + return + } + + await this.continueGoal(goalId, sessionId, generation, goal, verdict.reason, patch) + return + } + + await this.continueGoal(goalId, sessionId, generation, goal, verdict.reason, { + consecutiveBlocked: 0, + lastVerdict: 'continue', + lastReason: verdict.reason, + }) + } + + private async continueGoal( + goalId: number, + sessionId: string, + generation: number, + goal: SessionGoalRecord, + reason: string, + patch: SessionGoalPatch, + ): Promise { + if (!this.isAuditCurrent(goalId, sessionId, generation)) { + return + } + + if (goal.continuationCount >= goal.maxContinuations) { + this.finishGoal(goalId, 'stopped', 'continuation_limit', ['active'], patch) + return + } + + const record = this.applyTransition(goalId, ['active'], { + ...patch, + continuationCount: goal.continuationCount + 1, + turnState: 'waiting', + }) + if (!record) { + return + } + + try { + await this.openCodeClient.api.session.prompt({ + sessionID: record.sessionId, + text: buildGoalContinuationPrompt({ objective: record.objective, reason }), + }) + } catch (error) { + logger.error(`Failed to send continuation for goal ${goalId}:`, error) + if (this.isAuditCurrent(goalId, sessionId, generation, 'waiting')) { + this.finishGoal(goalId, 'stopped', 'turn_error') + } + } + } + + private finishGoal( + goalId: number, + status: SessionGoalStatus, + stopReason: SessionGoalStopReason | null, + fromStatuses: SessionGoalStatus[] = ['active'], + patch: SessionGoalPatch = {}, + ): void { + const record = this.applyTransition(goalId, fromStatuses, { + ...patch, + status, + stopReason, + finishedAt: status === 'paused' ? null : Date.now(), + }) + if (record) { + this.onOutcome(toSessionGoal(record)) + } + } + + private failAudit(goalId: number, sessionId: string, generation: number): void { + if (!this.isAuditCurrent(goalId, sessionId, generation)) { + return + } + this.finishGoal(goalId, 'paused', 'audit_failed') + } + + private async readPrerequisite( + goalId: number, + label: string, + read: () => Promise, + ): Promise> { + for (let attempt = 0; attempt < AUDITOR_ATTEMPTS; attempt += 1) { + try { + return { ok: true, value: await read() } + } catch (error) { + logger.error(`Session goal ${goalId} ${label} failed (attempt ${attempt + 1}):`, error) + } + } + return { ok: false } + } + + private isAuditCurrent( + goalId: number, + sessionId: string, + generation: number, + turnState: SessionGoalTurnState = 'running', + ): boolean { + if (this.currentAuditGeneration(sessionId) !== generation) { + return false + } + const record = getSessionGoalById(this.db, goalId) + return Boolean(record && record.status === 'active' && record.turnState === turnState) + } + + private currentAuditGeneration(sessionId: string): number { + return this.auditGeneration.get(sessionId) ?? 0 + } + + private applyTransition( + goalId: number, + fromStatuses: SessionGoalStatus[], + patch: SessionGoalPatch, + ): SessionGoalRecord | null { + const record = transitionSessionGoal(this.db, goalId, fromStatuses, patch) + if (!record) { + return null + } + + this.syncGoalIndex(record) + this.maybeInvalidateAudits(record, patch) + return record + } + + private transitionWithOutcome( + id: number, + fromStatuses: SessionGoalStatus[], + patch: SessionGoalPatch, + ): SessionGoal { + const goal = toSessionGoal(this.transition(id, fromStatuses, patch)) + this.onOutcome(goal) + return goal } private transition(id: number, fromStatuses: SessionGoalStatus[], patch: SessionGoalPatch): SessionGoalRecord { const record = transitionSessionGoal(this.db, id, fromStatuses, patch) - if (record) { - return record + if (!record) { + if (!getSessionGoalById(this.db, id)) { + throw new SessionGoalError('Session goal not found', 404) + } + throw new SessionGoalError('Session goal cannot transition from its current state', 409) } - if (!getSessionGoalById(this.db, id)) { - throw new SessionGoalError('Session goal not found', 404) + this.syncGoalIndex(record) + this.maybeInvalidateAudits(record, patch) + return record + } + + private syncGoalIndex(record: SessionGoalRecord): void { + if (record.status === 'active' || record.status === 'paused') { + this.goalBySession.set(record.sessionId, record.id) + } else { + this.goalBySession.delete(record.sessionId) + this.clearAuditTimer(record.sessionId) } - throw new SessionGoalError('Session goal cannot transition from its current state', 409) + } + + private maybeInvalidateAudits(record: SessionGoalRecord, patch: SessionGoalPatch): void { + if (patch.status === undefined && patch.turnState !== 'running') { + return + } + this.auditGeneration.set(record.sessionId, this.currentAuditGeneration(record.sessionId) + 1) + this.auditRequested.delete(record.id) } private async readSessionTokenTotal(sessionId: string): Promise { + const session = await this.openCodeClient.api.session.get({ sessionID: sessionId }) + return sessionTokenTotal(session.tokens) + } + + private async readSessionTokenTotalOrDefault(sessionId: string): Promise { try { - const session = await this.openCodeClient.api.session.get({ sessionID: sessionId }) - return sessionTokenTotal(session.tokens) + return await this.readSessionTokenTotal(sessionId) } catch (error) { logger.error(`Failed to read token usage for session ${sessionId}:`, error) return 0 diff --git a/backend/test/helpers/fake-session-goal-client.ts b/backend/test/helpers/fake-session-goal-client.ts index 8158fbbc..1e810305 100644 --- a/backend/test/helpers/fake-session-goal-client.ts +++ b/backend/test/helpers/fake-session-goal-client.ts @@ -1,3 +1,4 @@ +import type { ModelRef, SessionMessageInfo } from '@opencode-manager/shared/opencode' import type { OpenCodeClient } from '../../src/services/opencode/client' export interface FakeSessionGoalTokens { @@ -9,19 +10,78 @@ export interface FakeSessionGoalTokens { export interface FakeSessionGoalClientOptions { tokens?: Record failSessionGet?: boolean + messages?: Record + busySessions?: string[] + auditorReplies?: string[] + failAuditorCalls?: number + failSessionPrompt?: boolean } -export function createFakeSessionGoalClient(options: FakeSessionGoalClientOptions = {}): OpenCodeClient { - const tokens = options.tokens ?? {} +export interface FakeSessionGoalPromptCall { + sessionID: string + text: string +} - return { +export interface FakeSessionGoalAuditorCall { + prompt: string + model: ModelRef | null +} + +export interface FakeSessionGoalAuditorDeferral { + resolve(text: string): void + reject(error?: unknown): void +} + +export interface FakeSessionGoalPromptDeferral { + resolve(): void + reject(error?: unknown): void +} + +export interface FakeSessionGoalClient { + client: OpenCodeClient + promptCalls: FakeSessionGoalPromptCall[] + auditorCalls: FakeSessionGoalAuditorCall[] + pendingAuditorCalls: FakeSessionGoalAuditorDeferral[] + pendingSessionPromptCalls: FakeSessionGoalPromptDeferral[] + readonly maxConcurrentAuditorCalls: number + setTokens(sessionId: string, tokens: FakeSessionGoalTokens): void + setMessages(sessionId: string, messages: SessionMessageInfo[]): void + setBusy(sessionId: string, busy: boolean): void + setAuditorReplies(replies: string[]): void + failNextAuditorCalls(count: number): void + deferNextAuditorCalls(count: number): void + deferNextSessionPrompts(count: number): void + setFailSessionGet(fail: boolean): void + setFailSessionActive(fail: boolean): void + setFailMessageList(fail: boolean): void +} + +export function createFakeSessionGoalClient(options: FakeSessionGoalClientOptions = {}): FakeSessionGoalClient { + const tokens = new Map(Object.entries(options.tokens ?? {})) + const messages = new Map(Object.entries(options.messages ?? {})) + const busySessions = new Set(options.busySessions ?? []) + const promptCalls: FakeSessionGoalPromptCall[] = [] + const auditorCalls: FakeSessionGoalAuditorCall[] = [] + const pendingAuditorCalls: FakeSessionGoalAuditorDeferral[] = [] + const pendingSessionPromptCalls: FakeSessionGoalPromptDeferral[] = [] + let auditorReplies = [...(options.auditorReplies ?? [])] + let auditorFailures = options.failAuditorCalls ?? 0 + let deferAuditorCount = 0 + let deferPromptCount = 0 + let sessionGetFails = options.failSessionGet ?? false + let sessionActiveFails = false + let messageListFails = false + let activeAuditorCalls = 0 + let maxConcurrentAuditorCalls = 0 + + const client = { api: { session: { get: async ({ sessionID }: { sessionID: string }) => { - if (options.failSessionGet) { + if (sessionGetFails) { throw new Error('upstream unavailable') } - const usage = tokens[sessionID] ?? { input: 0, output: 0, reasoning: 0 } + const usage = tokens.get(sessionID) ?? { input: 0, output: 0, reasoning: 0 } return { tokens: { input: usage.input, @@ -31,8 +91,129 @@ export function createFakeSessionGoalClient(options: FakeSessionGoalClientOption }, } }, + active: async () => { + if (sessionActiveFails) { + throw new Error('active lookup failed') + } + const active: Record = {} + for (const sessionId of busySessions) { + active[sessionId] = { type: 'running' } + } + return active + }, + prompt: async (input: { sessionID: string; text: string }) => { + if (options.failSessionPrompt) { + throw new Error('prompt rejected') + } + promptCalls.push({ sessionID: input.sessionID, text: input.text }) + if (deferPromptCount > 0) { + deferPromptCount -= 1 + await new Promise((resolve, reject) => { + pendingSessionPromptCalls.push({ resolve, reject }) + }) + } + return { id: `inbox_${promptCalls.length}` } + }, + }, + message: { + list: async ({ sessionID }: { sessionID: string }) => { + if (messageListFails) { + throw new Error('message list failed') + } + return { + data: messages.get(sessionID) ?? [], + cursor: {}, + } + }, + }, + generate: { + text: async (input: { prompt: string; model?: ModelRef | null }) => { + auditorCalls.push({ prompt: input.prompt, model: input.model ?? null }) + activeAuditorCalls += 1 + maxConcurrentAuditorCalls = Math.max(maxConcurrentAuditorCalls, activeAuditorCalls) + try { + if (deferAuditorCount > 0) { + deferAuditorCount -= 1 + const text = await new Promise((resolve, reject) => { + pendingAuditorCalls.push({ resolve, reject }) + }) + return { text } + } + if (auditorFailures > 0) { + auditorFailures -= 1 + throw new Error('auditor unavailable') + } + const text = auditorReplies.shift() ?? '{"verdict":"continue","reason":"still working"}' + return { text } + } finally { + activeAuditorCalls -= 1 + } + }, }, }, forwardRaw: async () => new Response(), } as unknown as OpenCodeClient + + return { + client, + promptCalls, + auditorCalls, + pendingAuditorCalls, + pendingSessionPromptCalls, + get maxConcurrentAuditorCalls() { + return maxConcurrentAuditorCalls + }, + setTokens: (sessionId, next) => { + tokens.set(sessionId, next) + }, + setMessages: (sessionId, next) => { + messages.set(sessionId, next) + }, + setBusy: (sessionId, next) => { + if (next) { + busySessions.add(sessionId) + } else { + busySessions.delete(sessionId) + } + }, + setAuditorReplies: (replies) => { + auditorReplies = [...replies] + }, + failNextAuditorCalls: (count) => { + auditorFailures = count + }, + deferNextAuditorCalls: (count) => { + deferAuditorCount = count + }, + deferNextSessionPrompts: (count) => { + deferPromptCount = count + }, + setFailSessionGet: (fail) => { + sessionGetFails = fail + }, + setFailSessionActive: (fail) => { + sessionActiveFails = fail + }, + setFailMessageList: (fail) => { + messageListFails = fail + }, + } +} + +export function fakeAssistantMessage( + text: string, + options: { error?: string; completed?: boolean } = {}, +): SessionMessageInfo { + return { + id: 'msg_assistant', + type: 'assistant', + time: { + created: 0, + ...(options.completed === false ? {} : { completed: 1 }), + }, + agent: 'build', + model: { providerID: 'test', id: 'model' }, + content: [{ type: 'text', text }], + ...(options.error ? { error: { type: 'unknown', message: options.error } } : {}), + } as unknown as SessionMessageInfo } diff --git a/backend/test/routes/session-goals.test.ts b/backend/test/routes/session-goals.test.ts index 47883590..82debcf2 100644 --- a/backend/test/routes/session-goals.test.ts +++ b/backend/test/routes/session-goals.test.ts @@ -12,7 +12,11 @@ const DIRECTORY = '/abs/repo' function createTestApp(db: Database): Hono { const app = new Hono() - const service = new SessionGoalService(db, createFakeSessionGoalClient(), new SettingsService(db)) + const service = new SessionGoalService( + db, + createFakeSessionGoalClient({ busySessions: ['ses_1'] }).client, + new SettingsService(db), + ) app.route('/session-goals', createSessionGoalRoutes(service)) return app } diff --git a/backend/test/services/session-goal-audit.test.ts b/backend/test/services/session-goal-audit.test.ts new file mode 100644 index 00000000..c51f74bc --- /dev/null +++ b/backend/test/services/session-goal-audit.test.ts @@ -0,0 +1,86 @@ +import { describe, it, expect } from 'vitest' +import { + buildGoalAuditPrompt, + buildGoalContinuationPrompt, + GOAL_AUDIT_REASON_MAX_CHARS, + GOAL_AUDIT_REPLY_MAX_CHARS, + parseGoalVerdict, +} from '../../src/services/session-goal-audit' + +describe('parseGoalVerdict', () => { + it('parses a plain JSON verdict', () => { + expect(parseGoalVerdict('{"verdict":"done","reason":"The feature shipped."}')).toEqual({ + verdict: 'done', + reason: 'The feature shipped.', + }) + }) + + it('parses a fenced JSON verdict with surrounding prose', () => { + const text = [ + 'Here is my decision:', + '```json', + '{"verdict":"blocked","reason":"Needs a database decision."}', + '```', + 'Let me know.', + ].join('\n') + + expect(parseGoalVerdict(text)).toEqual({ + verdict: 'blocked', + reason: 'Needs a database decision.', + }) + }) + + it('returns null for invalid JSON', () => { + expect(parseGoalVerdict('not json at all')).toBeNull() + expect(parseGoalVerdict('{"verdict":')).toBeNull() + }) + + it('returns null for an unknown verdict', () => { + expect(parseGoalVerdict('{"verdict":"maybe","reason":"unsure"}')).toBeNull() + }) + + it('returns null for a missing or empty reason', () => { + expect(parseGoalVerdict('{"verdict":"done"}')).toBeNull() + expect(parseGoalVerdict('{"verdict":"done","reason":" "}')).toBeNull() + }) + + it('caps the reason length', () => { + const longReason = 'a'.repeat(GOAL_AUDIT_REASON_MAX_CHARS + 50) + const parsed = parseGoalVerdict(`{"verdict":"continue","reason":"${longReason}"}`) + + expect(parsed?.verdict).toBe('continue') + expect(parsed?.reason).toHaveLength(GOAL_AUDIT_REASON_MAX_CHARS) + }) +}) + +describe('buildGoalAuditPrompt', () => { + it('includes the objective and reply and asks for JSON only', () => { + const prompt = buildGoalAuditPrompt({ objective: 'Ship the feature', reply: 'I updated the route.' }) + + expect(prompt).toContain('Ship the feature') + expect(prompt).toContain('I updated the route.') + expect(prompt).toContain('{"verdict":"continue"|"done"|"blocked","reason":""}') + }) + + it('marks a missing reply', () => { + expect(buildGoalAuditPrompt({ objective: 'Ship it', reply: null })).toContain('(no reply yet)') + }) + + it('truncates a long reply with a marker', () => { + const reply = 'x'.repeat(GOAL_AUDIT_REPLY_MAX_CHARS + 100) + const prompt = buildGoalAuditPrompt({ objective: 'Ship it', reply }) + + expect(prompt).toContain('[reply truncated]') + expect(prompt).not.toContain('x'.repeat(GOAL_AUDIT_REPLY_MAX_CHARS + 1)) + }) +}) + +describe('buildGoalContinuationPrompt', () => { + it('includes the objective and the progress reason', () => { + const prompt = buildGoalContinuationPrompt({ objective: 'Ship the feature', reason: 'Tests still fail.' }) + + expect(prompt).toContain('Ship the feature') + expect(prompt).toContain('Tests still fail.') + expect(prompt).toContain('state exactly what you need') + }) +}) diff --git a/backend/test/services/session-goals.test.ts b/backend/test/services/session-goals.test.ts index 0439aa26..0331a2dd 100644 --- a/backend/test/services/session-goals.test.ts +++ b/backend/test/services/session-goals.test.ts @@ -1,11 +1,17 @@ -import { describe, it, expect, beforeEach, afterEach } from 'vitest' +import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest' import { Database } from 'bun:sqlite' import { migrate } from '../../src/db/migration-runner' import { allMigrations } from '../../src/db/migrations' import { getSessionGoalById, listOpenSessionGoals } from '../../src/db/session-goals' -import { SessionGoalService } from '../../src/services/session-goals' +import { SessionGoalService, type SessionGoalServiceOptions } from '../../src/services/session-goals' import { SettingsService } from '../../src/services/settings' -import { createFakeSessionGoalClient } from '../helpers/fake-session-goal-client' +import type { SSEEvent } from '../../src/services/sse-aggregator' +import { + createFakeSessionGoalClient, + fakeAssistantMessage, + type FakeSessionGoalClient, + type FakeSessionGoalClientOptions, +} from '../helpers/fake-session-goal-client' const DIRECTORY = '/abs/repo' @@ -17,20 +23,93 @@ function createTestDb(): Database { function createService( db: Database, - options: Parameters[0] = {}, + options: FakeSessionGoalClientOptions = {}, settingsService: SettingsService = new SettingsService(db), + serviceOptions: SessionGoalServiceOptions = {}, ): SessionGoalService { - return new SessionGoalService(db, createFakeSessionGoalClient(options), settingsService) + return new SessionGoalService(db, createFakeSessionGoalClient(options).client, settingsService, serviceOptions) +} + +function executionStarted(sessionID: string): SSEEvent { + return { + id: `evt_started_${sessionID}`, + created: 0, + type: 'session.execution.started', + location: { directory: DIRECTORY }, + data: { sessionID }, + } as unknown as SSEEvent +} + +function executionSucceeded(sessionID: string): SSEEvent { + return { + id: `evt_succeeded_${sessionID}`, + created: 0, + type: 'session.execution.succeeded', + location: { directory: DIRECTORY }, + data: { sessionID }, + } as unknown as SSEEvent +} + +function sessionIdle(sessionID: string): SSEEvent { + return { + id: `evt_idle_${sessionID}`, + created: 0, + type: 'session.idle', + location: { directory: DIRECTORY }, + data: { sessionID }, + } as unknown as SSEEvent +} + +function sessionStatusIdle(sessionID: string): SSEEvent { + return { + id: `evt_status_${sessionID}`, + created: 0, + type: 'session.status', + location: { directory: DIRECTORY }, + data: { sessionID, status: { type: 'idle' } }, + } as unknown as SSEEvent +} + +function executionFailed(sessionID: string): SSEEvent { + return { + id: `evt_failed_${sessionID}`, + created: 0, + type: 'session.execution.failed', + location: { directory: DIRECTORY }, + data: { sessionID, error: { type: 'unknown', message: 'boom' } }, + } as unknown as SSEEvent +} + +function executionInterrupted(sessionID: string): SSEEvent { + return { + id: `evt_interrupted_${sessionID}`, + created: 0, + type: 'session.execution.interrupted', + location: { directory: DIRECTORY }, + data: { sessionID, reason: 'user' }, + } as unknown as SSEEvent +} + +function sessionDeleted(sessionID: string): SSEEvent { + return { + id: `evt_deleted_${sessionID}`, + created: 0, + type: 'session.deleted', + location: { directory: DIRECTORY }, + data: { sessionID }, + } as unknown as SSEEvent } describe('SessionGoalService', () => { let db: Database beforeEach(() => { + vi.useFakeTimers() db = createTestDb() }) afterEach(() => { + vi.useRealTimers() db.close() }) @@ -162,6 +241,89 @@ describe('SessionGoalService', () => { expect(() => service.pause(999)).toThrowError(expect.objectContaining({ status: 404 }) as Error) }) + it('emits exactly one outcome when pausing an active goal', async () => { + const outcomes: string[] = [] + const service = createService(db, {}, new SettingsService(db), { + onOutcome: (goal) => outcomes.push(goal.status), + }) + const started = await service.start({ sessionId: 'ses_1', directory: DIRECTORY, objective: 'Ship it' }) + + const paused = service.pause(started.id) + + expect(paused.status).toBe('paused') + expect(outcomes).toEqual(['paused']) + }) + + it('emits exactly one outcome when cancelling an active goal', async () => { + const outcomes: string[] = [] + const service = createService(db, {}, new SettingsService(db), { + onOutcome: (goal) => outcomes.push(goal.status), + }) + const started = await service.start({ sessionId: 'ses_1', directory: DIRECTORY, objective: 'Ship it' }) + + const cancelled = service.cancel(started.id) + + expect(cancelled.status).toBe('stopped') + expect(outcomes).toEqual(['stopped']) + }) + + it('emits exactly one outcome when cancelling a paused goal', async () => { + const outcomes: string[] = [] + const service = createService(db, {}, new SettingsService(db), { + onOutcome: (goal) => outcomes.push(goal.status), + }) + const started = await service.start({ sessionId: 'ses_1', directory: DIRECTORY, objective: 'Ship it' }) + service.pause(started.id) + outcomes.length = 0 + + service.cancel(started.id) + + expect(outcomes).toEqual(['stopped']) + }) + + it('does not emit an outcome when a pause transition is rejected', async () => { + const outcomes: string[] = [] + const service = createService(db, {}, new SettingsService(db), { + onOutcome: (goal) => outcomes.push(goal.status), + }) + const started = await service.start({ sessionId: 'ses_1', directory: DIRECTORY, objective: 'Ship it' }) + service.pause(started.id) + outcomes.length = 0 + + expect(() => service.pause(started.id)).toThrowError(expect.objectContaining({ status: 409 }) as Error) + + expect(outcomes).toEqual([]) + }) + + it('does not emit an outcome when a cancel transition is rejected', async () => { + const outcomes: string[] = [] + const service = createService(db, {}, new SettingsService(db), { + onOutcome: (goal) => outcomes.push(goal.status), + }) + const started = await service.start({ sessionId: 'ses_1', directory: DIRECTORY, objective: 'Ship it' }) + service.cancel(started.id) + outcomes.length = 0 + + expect(() => service.cancel(started.id)).toThrowError(expect.objectContaining({ status: 409 }) as Error) + + expect(outcomes).toEqual([]) + }) + + it('does not emit an outcome when resuming a paused goal', async () => { + const outcomes: string[] = [] + const service = createService(db, {}, new SettingsService(db), { + onOutcome: (goal) => outcomes.push(goal.status), + }) + const started = await service.start({ sessionId: 'ses_1', directory: DIRECTORY, objective: 'Ship it' }) + service.pause(started.id) + outcomes.length = 0 + + service.resume(started.id) + await vi.runAllTimersAsync() + + expect(outcomes).toEqual([]) + }) + it('returns the latest goal for a session', async () => { const service = createService(db) @@ -171,4 +333,565 @@ describe('SessionGoalService', () => { expect(service.getLatest('ses_1')?.id).toBe(started.id) }) + + it('loads open goals so events are handled after a restart', async () => { + const started = await createService(db).start({ sessionId: 'ses_1', directory: DIRECTORY, objective: 'Ship it' }) + const fake = createFakeSessionGoalClient() + const restarted = new SessionGoalService(db, fake.client, new SettingsService(db), { quietMs: 0 }) + + restarted.loadOpenGoals() + await restarted.handleEvent(DIRECTORY, executionStarted('ses_1')) + await restarted.handleEvent(DIRECTORY, sessionIdle('ses_1')) + await vi.runAllTimersAsync() + + expect(fake.auditorCalls).toHaveLength(1) + expect(getSessionGoalById(db, started.id)?.turnState).toBe('waiting') + }) +}) + +describe('SessionGoalService audit loop', () => { + let db: Database + let fake: FakeSessionGoalClient + let service: SessionGoalService + + beforeEach(() => { + vi.useFakeTimers() + db = createTestDb() + fake = createFakeSessionGoalClient() + service = new SessionGoalService(db, fake.client, new SettingsService(db), { quietMs: 0 }) + }) + + afterEach(() => { + vi.useRealTimers() + db.close() + }) + + async function runTurn(sessionId: string): Promise { + await service.handleEvent(DIRECTORY, executionStarted(sessionId)) + await service.handleEvent(DIRECTORY, sessionIdle(sessionId)) + await vi.runAllTimersAsync() + } + + it('completes the goal when the auditor says done', async () => { + fake.setMessages('ses_1', [fakeAssistantMessage('The feature is shipped and tested.')]) + fake.setAuditorReplies(['{"verdict":"done","reason":"Objective achieved."}']) + const started = await service.start({ sessionId: 'ses_1', directory: DIRECTORY, objective: 'Ship it' }) + + await runTurn('ses_1') + + const latest = service.getLatest('ses_1') + expect(latest?.status).toBe('completed') + expect(latest?.stopReason).toBeNull() + expect(latest?.lastVerdict).toBe('done') + expect(latest?.lastReason).toBe('Objective achieved.') + expect(latest?.finishedAt).not.toBeNull() + expect(fake.promptCalls).toHaveLength(0) + expect(fake.auditorCalls[0]?.prompt).toContain('Ship it') + expect(fake.auditorCalls[0]?.prompt).toContain('The feature is shipped and tested.') + expect(getSessionGoalById(db, started.id)?.turnState).toBe('running') + }) + + it('sends one continuation prompt and increments the count on continue', async () => { + fake.setMessages('ses_1', [fakeAssistantMessage('Working on the route.')]) + fake.setAuditorReplies(['{"verdict":"continue","reason":"Tests still fail."}']) + await service.start({ sessionId: 'ses_1', directory: DIRECTORY, objective: 'Ship it' }) + + await runTurn('ses_1') + + const latest = service.getLatest('ses_1') + expect(latest?.status).toBe('active') + expect(latest?.turnState).toBe('waiting') + expect(latest?.continuationCount).toBe(1) + expect(fake.promptCalls).toHaveLength(1) + expect(fake.promptCalls[0]?.sessionID).toBe('ses_1') + expect(fake.promptCalls[0]?.text).toContain('Ship it') + expect(fake.promptCalls[0]?.text).toContain('Tests still fail.') + }) + + it('stops the goal at the continuation cap', async () => { + fake.setMessages('ses_1', [fakeAssistantMessage('Still working.')]) + await service.start({ sessionId: 'ses_1', directory: DIRECTORY, objective: 'Ship it', maxContinuations: 1 }) + + await runTurn('ses_1') + await runTurn('ses_1') + + const latest = service.getLatest('ses_1') + expect(latest?.status).toBe('stopped') + expect(latest?.stopReason).toBe('continuation_limit') + expect(latest?.continuationCount).toBe(1) + expect(fake.promptCalls).toHaveLength(1) + }) + + it('continues twice and blocks on the third blocked verdict', async () => { + fake.setMessages('ses_1', [fakeAssistantMessage('I need a decision.')]) + fake.setAuditorReplies([ + '{"verdict":"blocked","reason":"Needs a decision."}', + '{"verdict":"blocked","reason":"Needs a decision."}', + '{"verdict":"blocked","reason":"Needs a decision."}', + ]) + await service.start({ sessionId: 'ses_1', directory: DIRECTORY, objective: 'Ship it' }) + + await runTurn('ses_1') + expect(service.getLatest('ses_1')?.status).toBe('active') + expect(service.getLatest('ses_1')?.consecutiveBlocked).toBe(1) + + await runTurn('ses_1') + expect(service.getLatest('ses_1')?.status).toBe('active') + expect(service.getLatest('ses_1')?.consecutiveBlocked).toBe(2) + + await runTurn('ses_1') + const latest = service.getLatest('ses_1') + expect(latest?.status).toBe('blocked') + expect(latest?.consecutiveBlocked).toBe(3) + expect(fake.promptCalls).toHaveLength(2) + }) + + it('resets the blocked counter on a continue verdict', async () => { + fake.setMessages('ses_1', [fakeAssistantMessage('Back to work.')]) + fake.setAuditorReplies([ + '{"verdict":"blocked","reason":"Needs a decision."}', + '{"verdict":"continue","reason":"Unblocked."}', + '{"verdict":"blocked","reason":"Needs a decision."}', + ]) + await service.start({ sessionId: 'ses_1', directory: DIRECTORY, objective: 'Ship it' }) + + await runTurn('ses_1') + await runTurn('ses_1') + expect(service.getLatest('ses_1')?.consecutiveBlocked).toBe(0) + + await runTurn('ses_1') + expect(service.getLatest('ses_1')?.consecutiveBlocked).toBe(1) + }) + + it('stops on a token budget overrun before calling the auditor', async () => { + fake.setMessages('ses_1', [fakeAssistantMessage('Still working.')]) + await service.start({ sessionId: 'ses_1', directory: DIRECTORY, objective: 'Ship it', tokenBudget: 100 }) + fake.setTokens('ses_1', { input: 250, output: 0, reasoning: 0 }) + + await runTurn('ses_1') + + const latest = service.getLatest('ses_1') + expect(latest?.status).toBe('stopped') + expect(latest?.stopReason).toBe('token_budget') + expect(latest?.tokensUsed).toBe(250) + expect(fake.auditorCalls).toHaveLength(0) + }) + + it('stops with turn_error when the execution fails', async () => { + await service.start({ sessionId: 'ses_1', directory: DIRECTORY, objective: 'Ship it' }) + + await service.handleEvent(DIRECTORY, executionFailed('ses_1')) + + const latest = service.getLatest('ses_1') + expect(latest?.status).toBe('stopped') + expect(latest?.stopReason).toBe('turn_error') + expect(fake.auditorCalls).toHaveLength(0) + }) + + it('stops with turn_error when the latest reply carries an error', async () => { + fake.setMessages('ses_1', [fakeAssistantMessage('Partial output', { error: 'provider crashed' })]) + await service.start({ sessionId: 'ses_1', directory: DIRECTORY, objective: 'Ship it' }) + + await runTurn('ses_1') + + const latest = service.getLatest('ses_1') + expect(latest?.status).toBe('stopped') + expect(latest?.stopReason).toBe('turn_error') + expect(fake.auditorCalls).toHaveLength(0) + }) + + it('pauses with audit_failed after two auditor failures', async () => { + fake.setMessages('ses_1', [fakeAssistantMessage('Still working.')]) + fake.failNextAuditorCalls(2) + await service.start({ sessionId: 'ses_1', directory: DIRECTORY, objective: 'Ship it' }) + + await runTurn('ses_1') + + const latest = service.getLatest('ses_1') + expect(latest?.status).toBe('paused') + expect(latest?.stopReason).toBe('audit_failed') + expect(latest?.finishedAt).toBeNull() + expect(fake.auditorCalls).toHaveLength(2) + }) + + it('treats an unparseable verdict as continue', async () => { + fake.setMessages('ses_1', [fakeAssistantMessage('Still working.')]) + fake.setAuditorReplies(['I am not sure.']) + await service.start({ sessionId: 'ses_1', directory: DIRECTORY, objective: 'Ship it' }) + + await runTurn('ses_1') + + const latest = service.getLatest('ses_1') + expect(latest?.status).toBe('active') + expect(latest?.lastVerdict).toBe('continue') + expect(latest?.lastReason).toBe('Auditor response was not understood') + expect(fake.promptCalls).toHaveLength(1) + }) + + it('does not audit an idle event while the turn is waiting', async () => { + await service.start({ sessionId: 'ses_1', directory: DIRECTORY, objective: 'Ship it' }) + + await service.handleEvent(DIRECTORY, sessionIdle('ses_1')) + await vi.runAllTimersAsync() + + expect(fake.auditorCalls).toHaveLength(0) + }) + + it('audits on execution.succeeded and on a session.status idle event', async () => { + fake.setMessages('ses_1', [fakeAssistantMessage('Done.')]) + fake.setAuditorReplies(['{"verdict":"continue","reason":"keep going"}', '{"verdict":"done","reason":"finished"}']) + await service.start({ sessionId: 'ses_1', directory: DIRECTORY, objective: 'Ship it' }) + + await service.handleEvent(DIRECTORY, executionStarted('ses_1')) + await service.handleEvent(DIRECTORY, executionSucceeded('ses_1')) + await vi.runAllTimersAsync() + expect(fake.auditorCalls).toHaveLength(1) + + await service.handleEvent(DIRECTORY, executionStarted('ses_1')) + await service.handleEvent(DIRECTORY, sessionStatusIdle('ses_1')) + await vi.runAllTimersAsync() + + expect(fake.auditorCalls).toHaveLength(2) + expect(service.getLatest('ses_1')?.status).toBe('completed') + }) + + it('ignores events for a session without an open goal', async () => { + await service.start({ sessionId: 'ses_1', directory: DIRECTORY, objective: 'Ship it' }) + + await service.handleEvent(DIRECTORY, executionStarted('ses_other')) + await service.handleEvent(DIRECTORY, executionFailed('ses_other')) + await vi.runAllTimersAsync() + + expect(service.getLatest('ses_1')?.status).toBe('active') + expect(fake.auditorCalls).toHaveLength(0) + }) + + it('schedules an audit immediately when a paused goal resumes', async () => { + fake.setMessages('ses_1', [fakeAssistantMessage('Back.')]) + fake.setAuditorReplies(['{"verdict":"done","reason":"finished"}']) + const started = await service.start({ sessionId: 'ses_1', directory: DIRECTORY, objective: 'Ship it' }) + service.pause(started.id) + + service.resume(started.id) + await vi.runAllTimersAsync() + + expect(fake.auditorCalls).toHaveLength(1) + expect(service.getLatest('ses_1')?.status).toBe('completed') + }) + + it('does not schedule an audit on resume while the session is busy', async () => { + const started = await service.start({ sessionId: 'ses_1', directory: DIRECTORY, objective: 'Ship it' }) + service.pause(started.id) + fake.setBusy('ses_1', true) + + service.resume(started.id) + await vi.runAllTimersAsync() + + expect(fake.auditorCalls).toHaveLength(0) + expect(service.getLatest('ses_1')?.status).toBe('active') + }) + + it('pauses with interrupted when the execution is interrupted', async () => { + await service.start({ sessionId: 'ses_1', directory: DIRECTORY, objective: 'Ship it' }) + + await service.handleEvent(DIRECTORY, executionInterrupted('ses_1')) + + const latest = service.getLatest('ses_1') + expect(latest?.status).toBe('paused') + expect(latest?.stopReason).toBe('interrupted') + expect(latest?.finishedAt).toBeNull() + }) + + it('stops with session_deleted when the session is deleted', async () => { + const started = await service.start({ sessionId: 'ses_1', directory: DIRECTORY, objective: 'Ship it' }) + service.pause(started.id) + + await service.handleEvent(DIRECTORY, sessionDeleted('ses_1')) + + const latest = service.getLatest('ses_1') + expect(latest?.status).toBe('stopped') + expect(latest?.stopReason).toBe('session_deleted') + }) + + it('stops with turn_error when the continuation prompt fails', async () => { + const failing = createFakeSessionGoalClient({ failSessionPrompt: true }) + const failingService = new SessionGoalService(db, failing.client, new SettingsService(db), { quietMs: 0 }) + failing.setMessages('ses_1', [fakeAssistantMessage('Working.')]) + failing.setAuditorReplies(['{"verdict":"continue","reason":"keep going"}']) + await failingService.start({ sessionId: 'ses_1', directory: DIRECTORY, objective: 'Ship it' }) + + await failingService.handleEvent(DIRECTORY, executionStarted('ses_1')) + await failingService.handleEvent(DIRECTORY, sessionIdle('ses_1')) + await vi.runAllTimersAsync() + + const latest = failingService.getLatest('ses_1') + expect(latest?.status).toBe('stopped') + expect(latest?.stopReason).toBe('turn_error') + }) + + it('discards a late continuation failure after a new execution starts', async () => { + const outcomes: string[] = [] + const tracked = new SessionGoalService(db, fake.client, new SettingsService(db), { + quietMs: 0, + onOutcome: (goal) => outcomes.push(goal.status), + }) + fake.setMessages('ses_1', [fakeAssistantMessage('Working.')]) + fake.setAuditorReplies(['{"verdict":"continue","reason":"keep going"}']) + fake.deferNextSessionPrompts(1) + await tracked.start({ sessionId: 'ses_1', directory: DIRECTORY, objective: 'Ship it' }) + + await tracked.handleEvent(DIRECTORY, executionStarted('ses_1')) + await tracked.handleEvent(DIRECTORY, sessionIdle('ses_1')) + await vi.runAllTimersAsync() + expect(fake.pendingSessionPromptCalls).toHaveLength(1) + expect(tracked.getLatest('ses_1')?.turnState).toBe('waiting') + + await tracked.handleEvent(DIRECTORY, executionStarted('ses_1')) + fake.pendingSessionPromptCalls[0]?.reject(new Error('transport dropped')) + await vi.runAllTimersAsync() + + const latest = tracked.getLatest('ses_1') + expect(latest?.status).toBe('active') + expect(latest?.turnState).toBe('running') + expect(latest?.stopReason).toBeNull() + expect(outcomes).toEqual([]) + }) + + it('discards a late continuation failure across pause and resume', async () => { + const outcomes: string[] = [] + const tracked = new SessionGoalService(db, fake.client, new SettingsService(db), { + quietMs: 0, + onOutcome: (goal) => outcomes.push(goal.status), + }) + fake.setMessages('ses_1', [fakeAssistantMessage('Working.')]) + fake.setAuditorReplies(['{"verdict":"continue","reason":"keep going"}']) + fake.deferNextSessionPrompts(1) + const started = await tracked.start({ sessionId: 'ses_1', directory: DIRECTORY, objective: 'Ship it' }) + + await tracked.handleEvent(DIRECTORY, executionStarted('ses_1')) + await tracked.handleEvent(DIRECTORY, sessionIdle('ses_1')) + await vi.runAllTimersAsync() + expect(fake.pendingSessionPromptCalls).toHaveLength(1) + + tracked.pause(started.id) + tracked.resume(started.id) + await vi.runAllTimersAsync() + expect(outcomes).toEqual(['paused']) + outcomes.length = 0 + + fake.pendingSessionPromptCalls[0]?.reject(new Error('transport dropped')) + await vi.runAllTimersAsync() + + const latest = tracked.getLatest('ses_1') + expect(latest?.status).toBe('active') + expect(latest?.stopReason).toBeNull() + expect(outcomes).toEqual([]) + }) + + it('passes the configured auditor model to the auditor call', async () => { + const settingsService = new SettingsService(db) + settingsService.updateSettings({ sessionDefaults: { permissionMode: 'ask', goalAuditorModel: 'anthropic/claude-x' } }) + const configured = new SessionGoalService(db, fake.client, settingsService, { quietMs: 0 }) + fake.setMessages('ses_1', [fakeAssistantMessage('Done.')]) + fake.setAuditorReplies(['{"verdict":"done","reason":"finished"}']) + await configured.start({ sessionId: 'ses_1', directory: DIRECTORY, objective: 'Ship it' }) + + await configured.handleEvent(DIRECTORY, executionStarted('ses_1')) + await configured.handleEvent(DIRECTORY, sessionIdle('ses_1')) + await vi.runAllTimersAsync() + + expect(fake.auditorCalls[0]?.model).toEqual({ providerID: 'anthropic', id: 'claude-x' }) + }) + + it('calls onOutcome for terminal transitions', async () => { + const outcomes: string[] = [] + const tracked = new SessionGoalService(db, fake.client, new SettingsService(db), { + quietMs: 0, + onOutcome: (goal) => outcomes.push(goal.status), + }) + fake.setMessages('ses_1', [fakeAssistantMessage('Done.')]) + fake.setAuditorReplies(['{"verdict":"done","reason":"finished"}']) + await tracked.start({ sessionId: 'ses_1', directory: DIRECTORY, objective: 'Ship it' }) + + await tracked.handleEvent(DIRECTORY, executionStarted('ses_1')) + await tracked.handleEvent(DIRECTORY, sessionIdle('ses_1')) + await vi.runAllTimersAsync() + + expect(outcomes).toEqual(['completed']) + }) + + it('pauses with audit_failed when the busy check fails', async () => { + const outcomes: string[] = [] + const tracked = new SessionGoalService(db, fake.client, new SettingsService(db), { + quietMs: 0, + onOutcome: (goal) => outcomes.push(goal.status), + }) + fake.setMessages('ses_1', [fakeAssistantMessage('Working.')]) + await tracked.start({ sessionId: 'ses_1', directory: DIRECTORY, objective: 'Ship it' }) + fake.setFailSessionActive(true) + + await tracked.handleEvent(DIRECTORY, executionStarted('ses_1')) + await tracked.handleEvent(DIRECTORY, sessionIdle('ses_1')) + await vi.runAllTimersAsync() + + const latest = tracked.getLatest('ses_1') + expect(latest?.status).toBe('paused') + expect(latest?.stopReason).toBe('audit_failed') + expect(fake.auditorCalls).toHaveLength(0) + expect(fake.promptCalls).toHaveLength(0) + expect(outcomes).toEqual(['paused']) + }) + + it('pauses with audit_failed when the token lookup fails without resetting usage', async () => { + fake.setMessages('ses_1', [fakeAssistantMessage('Working.')]) + fake.setTokens('ses_1', { input: 50, output: 0, reasoning: 0 }) + fake.setAuditorReplies(['{"verdict":"continue","reason":"keep going"}']) + await service.start({ sessionId: 'ses_1', directory: DIRECTORY, objective: 'Ship it', tokenBudget: 100 }) + + fake.setTokens('ses_1', { input: 100, output: 0, reasoning: 0 }) + await runTurn('ses_1') + expect(service.getLatest('ses_1')?.tokensUsed).toBe(50) + + fake.setTokens('ses_1', { input: 250, output: 0, reasoning: 0 }) + fake.setFailSessionGet(true) + await runTurn('ses_1') + + const latest = service.getLatest('ses_1') + expect(latest?.status).toBe('paused') + expect(latest?.stopReason).toBe('audit_failed') + expect(latest?.tokensUsed).toBe(50) + expect(fake.promptCalls).toHaveLength(1) + expect(fake.auditorCalls).toHaveLength(1) + }) + + it('pauses with audit_failed when the reply lookup fails', async () => { + fake.setMessages('ses_1', [fakeAssistantMessage('Working.')]) + await service.start({ sessionId: 'ses_1', directory: DIRECTORY, objective: 'Ship it' }) + fake.setFailMessageList(true) + + await runTurn('ses_1') + + const latest = service.getLatest('ses_1') + expect(latest?.status).toBe('paused') + expect(latest?.stopReason).toBe('audit_failed') + expect(fake.auditorCalls).toHaveLength(0) + expect(fake.promptCalls).toHaveLength(0) + }) + + it('pauses with audit_failed when the resume busy check fails', async () => { + const outcomes: string[] = [] + const tracked = new SessionGoalService(db, fake.client, new SettingsService(db), { + quietMs: 0, + onOutcome: (goal) => outcomes.push(goal.status), + }) + const started = await tracked.start({ sessionId: 'ses_1', directory: DIRECTORY, objective: 'Ship it' }) + tracked.pause(started.id) + outcomes.length = 0 + fake.setFailSessionActive(true) + + tracked.resume(started.id) + await vi.runAllTimersAsync() + + const latest = tracked.getLatest('ses_1') + expect(latest?.status).toBe('paused') + expect(latest?.stopReason).toBe('audit_failed') + expect(fake.auditorCalls).toHaveLength(0) + expect(outcomes).toEqual(['paused']) + }) + + it('discards a stale continue verdict when a new execution starts mid-audit', async () => { + fake.setMessages('ses_1', [fakeAssistantMessage('Working.')]) + fake.deferNextAuditorCalls(1) + await service.start({ sessionId: 'ses_1', directory: DIRECTORY, objective: 'Ship it' }) + + await service.handleEvent(DIRECTORY, executionStarted('ses_1')) + await service.handleEvent(DIRECTORY, sessionIdle('ses_1')) + await vi.runAllTimersAsync() + expect(fake.pendingAuditorCalls).toHaveLength(1) + + await service.handleEvent(DIRECTORY, executionStarted('ses_1')) + fake.setBusy('ses_1', true) + fake.pendingAuditorCalls[0]?.resolve('{"verdict":"continue","reason":"keep going"}') + await vi.runAllTimersAsync() + + const latest = service.getLatest('ses_1') + expect(latest?.status).toBe('active') + expect(latest?.continuationCount).toBe(0) + expect(latest?.turnState).toBe('running') + expect(fake.promptCalls).toHaveLength(0) + }) + + it('discards a stale done verdict when the goal is paused mid-audit', async () => { + fake.setMessages('ses_1', [fakeAssistantMessage('Done.')]) + fake.deferNextAuditorCalls(1) + const started = await service.start({ sessionId: 'ses_1', directory: DIRECTORY, objective: 'Ship it' }) + + await service.handleEvent(DIRECTORY, executionStarted('ses_1')) + await service.handleEvent(DIRECTORY, sessionIdle('ses_1')) + await vi.runAllTimersAsync() + expect(fake.pendingAuditorCalls).toHaveLength(1) + + service.pause(started.id) + fake.pendingAuditorCalls[0]?.resolve('{"verdict":"done","reason":"finished"}') + await vi.runAllTimersAsync() + + const latest = service.getLatest('ses_1') + expect(latest?.status).toBe('paused') + expect(latest?.stopReason).toBe('user_paused') + expect(latest?.lastVerdict).toBeNull() + }) + + it('retains a newer idle audit while an older audit is in flight', async () => { + fake.setMessages('ses_1', [fakeAssistantMessage('Turn 1.')]) + fake.setAuditorReplies(['{"verdict":"continue","reason":"second"}']) + fake.deferNextAuditorCalls(1) + await service.start({ sessionId: 'ses_1', directory: DIRECTORY, objective: 'Ship it' }) + + await service.handleEvent(DIRECTORY, executionStarted('ses_1')) + await service.handleEvent(DIRECTORY, sessionIdle('ses_1')) + await vi.runAllTimersAsync() + expect(fake.pendingAuditorCalls).toHaveLength(1) + + await service.handleEvent(DIRECTORY, executionStarted('ses_1')) + fake.setMessages('ses_1', [fakeAssistantMessage('Turn 2.')]) + await service.handleEvent(DIRECTORY, sessionIdle('ses_1')) + await vi.runAllTimersAsync() + expect(fake.pendingAuditorCalls).toHaveLength(1) + + fake.pendingAuditorCalls[0]?.resolve('{"verdict":"continue","reason":"stale"}') + await vi.runAllTimersAsync() + + expect(fake.auditorCalls).toHaveLength(2) + expect(fake.maxConcurrentAuditorCalls).toBe(1) + expect(fake.promptCalls).toHaveLength(1) + expect(fake.promptCalls[0]?.text).toContain('second') + const latest = service.getLatest('ses_1') + expect(latest?.continuationCount).toBe(1) + expect(latest?.turnState).toBe('waiting') + }) + + it('discards an in-flight audit result across pause and resume', async () => { + fake.setMessages('ses_1', [fakeAssistantMessage('Working.')]) + fake.setAuditorReplies(['{"verdict":"continue","reason":"fresh"}']) + fake.deferNextAuditorCalls(1) + const started = await service.start({ sessionId: 'ses_1', directory: DIRECTORY, objective: 'Ship it' }) + + await service.handleEvent(DIRECTORY, executionStarted('ses_1')) + await service.handleEvent(DIRECTORY, sessionIdle('ses_1')) + await vi.runAllTimersAsync() + expect(fake.pendingAuditorCalls).toHaveLength(1) + + service.pause(started.id) + service.resume(started.id) + await vi.runAllTimersAsync() + + fake.pendingAuditorCalls[0]?.resolve('{"verdict":"done","reason":"stale"}') + await vi.runAllTimersAsync() + + const latest = service.getLatest('ses_1') + expect(latest?.status).toBe('active') + expect(latest?.lastVerdict).toBe('continue') + expect(fake.auditorCalls).toHaveLength(2) + expect(fake.promptCalls).toHaveLength(1) + }) })