section 6: Phase 6: Goal audit loop: quiet-period audit, continuation a

This commit is contained in:
Chris Scott committed 2026-10-03 10:08:18 -04:00
1 parent 74b00e37f0
commit 40bbe5aff3
7 files changed
+1594 -25

No files matched your search

+138
View File
@@ -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":"<one sentence>"}',
].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
}
+447 -14
View File
@@ -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<T> = { 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<string, number>()
private readonly auditTimers = new Map<string, ReturnType<typeof setTimeout>>()
private readonly auditing = new Set<number>()
private readonly auditRequested = new Set<number>()
private readonly auditGeneration = new Map<string, number>()
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<SessionGoal> {
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<void> {
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<void> {
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<void> {
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<void> {
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<GoalVerdict | null> {
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<void> {
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<void> {
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<T>(
goalId: number,
label: string,
read: () => Promise<T>,
): Promise<PrerequisiteResult<T>> {
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<number> {
const session = await this.openCodeClient.api.session.get({ sessionID: sessionId })
return sessionTokenTotal(session.tokens)
}
private async readSessionTokenTotalOrDefault(sessionId: string): Promise<number> {
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