Fix #12: the final hand-back after an interim stop always gets its line
EV-20 (PR #271) sat 8 h in router_check: after an interim stop in round 3 the Opus dev's final hand-back got no "no verification" line. - An agent that stays idle (waiting for a message, not on its own work) for 2 minutes has handed back. A moment idle between turns does not count; waiting on background work stays an interim stop. - Watches are kept in the store: a plugin reload cancels the timers, and the next event picks the stored watches up again. - /router lists the agents still waiting for a hand-back, and for how long. 5 tests (one old test now goes idle briefly, then runs); 6 mutations, all caught. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01MdqPWvuDpbpRvDEdURoAwo
This commit is contained in:
+61
-8
@@ -25,6 +25,7 @@ import {
|
||||
turnEndKind,
|
||||
WATCH_EVERY_MS,
|
||||
WATCH_FOR_MS,
|
||||
IDLE_HANDBACK_MS,
|
||||
safetyHit,
|
||||
skipReason,
|
||||
validTimeout,
|
||||
@@ -117,8 +118,12 @@ const S = {
|
||||
costs: 'costs',
|
||||
agentTask: 'agentTask',
|
||||
aliases: 'aliases',
|
||||
// turn ends still waiting for their hand-back: kept so a plugin reload resumes them (#12)
|
||||
watching: 'watching',
|
||||
} as const
|
||||
|
||||
type Watch = { wid: string; ended: string; reported?: string; since: number }
|
||||
|
||||
/** Model ids assumed for an alias until an agent run shows what it resolves to. */
|
||||
const ALIAS_DEFAULT: Record<Tier, string> = {
|
||||
haiku: 'claude-haiku-4-5',
|
||||
@@ -692,9 +697,36 @@ async function agentAddressed($: EngineInterface, to: string) {
|
||||
// The newest turn end per agent. A turn end that is only an interim stop (the
|
||||
// agent waits on its own background work) must not post a line or start the
|
||||
// verifier: only the run's end does. Module state: a reload drops the watches.
|
||||
const lastTurn = new Map<string, { token: number; ended: string; reported?: string }>()
|
||||
// The watches are also kept in the store (S.watching): a hot reload cancels
|
||||
// pending timers, and the first event after it resumes them (#12).
|
||||
const lastTurn = new Map<string, { token: number; ended: string; reported?: string; wid: string }>()
|
||||
let tokens = 0
|
||||
|
||||
/** Forgets a stored watch, unless a newer turn end has replaced it. */
|
||||
async function endWatch($: EngineInterface, agentId: string, wid: string) {
|
||||
await updateIn<Watch>($, S.watching, agentId, old => (old?.wid === wid ? undefined : old))
|
||||
}
|
||||
|
||||
/** Starts watching for a tracked agent's hand-back after one of its turns ended. */
|
||||
async function watch($: EngineInterface, agentId: string, w: Omit<Watch, 'wid'>, cfg: Settings) {
|
||||
const token = ++tokens
|
||||
const wid = `${w.since}-${token}-${Math.random().toString(36).slice(2, 8)}`
|
||||
lastTurn.set(agentId, { token, ended: w.ended, reported: w.reported, wid })
|
||||
await putIn<Watch>($, S.watching, agentId, { ...w, wid })
|
||||
$.clock.after(0, () => void awaitHandBack($, agentId, token, cfg, w.since))
|
||||
}
|
||||
|
||||
/** Picks up stored watches nothing in this module watches: the ones a reload cut off. */
|
||||
async function resumeWatches($: EngineInterface, cfg: Settings) {
|
||||
const kept = await getMap<Watch>($, S.watching)
|
||||
for (const [agentId, w] of Object.entries(kept)) {
|
||||
if (!w || lastTurn.has(agentId)) continue
|
||||
const token = ++tokens
|
||||
lastTurn.set(agentId, { token, ended: w.ended, reported: w.reported, wid: w.wid })
|
||||
$.clock.after(0, () => void awaitHandBack($, agentId, token, cfg, w.since))
|
||||
}
|
||||
}
|
||||
|
||||
function pause($: EngineInterface, ms: number) {
|
||||
return new Promise<void>(resolve => {
|
||||
$.clock.after(ms, () => resolve())
|
||||
@@ -713,17 +745,32 @@ async function statusOf($: EngineInterface, agentId: string) {
|
||||
* After a tracked agent's turn ends: runs the round once its run has ended,
|
||||
* and not for an interim stop. A newer turn end of the same agent takes over.
|
||||
*/
|
||||
async function awaitHandBack($: EngineInterface, agentId: string, token: number, cfg: Settings) {
|
||||
const started = await $.clock.now()
|
||||
async function awaitHandBack($: EngineInterface, agentId: string, token: number, cfg: Settings, since: number) {
|
||||
let idleSince: number | undefined
|
||||
for (;;) {
|
||||
if (lastTurn.get(agentId)?.token !== token) return // a newer turn end took over
|
||||
if (turnEndKind(await statusOf($, agentId)) === 'handback') break
|
||||
if ((await $.clock.now()) - started > WATCH_FOR_MS) return
|
||||
const status = await statusOf($, agentId)
|
||||
if (turnEndKind(status) === 'handback') break
|
||||
const now = await $.clock.now()
|
||||
// held idle, not on its own work: it has stopped and waits for a message (#12)
|
||||
if (status === 'idle') {
|
||||
idleSince ??= now
|
||||
if (now - idleSince >= IDLE_HANDBACK_MS) break
|
||||
} else idleSince = undefined
|
||||
if (now - since > WATCH_FOR_MS) {
|
||||
const gone = lastTurn.get(agentId)
|
||||
if (gone?.token === token) {
|
||||
lastTurn.delete(agentId)
|
||||
await endWatch($, agentId, gone.wid)
|
||||
}
|
||||
return
|
||||
}
|
||||
await pause($, WATCH_EVERY_MS)
|
||||
}
|
||||
const turn = lastTurn.get(agentId)
|
||||
if (!turn || turn.token !== token) return
|
||||
lastTurn.delete(agentId)
|
||||
await endWatch($, agentId, turn.wid)
|
||||
// read the record now: an earlier round may have changed it meanwhile
|
||||
const rec = (await getMap<AgentRec>($, S.agents))[agentId]
|
||||
if (rec) await runRound($, agentId, rec, turn.ended, turn.reported, cfg)
|
||||
@@ -750,6 +797,7 @@ export const register: Register = (on, options) => {
|
||||
}
|
||||
|
||||
on('session.start', async ($, e, next) => {
|
||||
await resumeWatches($, cfg)
|
||||
await $.command.register({
|
||||
name: 'router',
|
||||
description: 'Model router: decisions, verdicts and savings vs Opus (`/router savings [Tn]`, `/router clear`)',
|
||||
@@ -890,6 +938,7 @@ export const register: Register = (on, options) => {
|
||||
// Verification: each finished run of a tracked agent, a resumed SendMessage round included.
|
||||
on('turn.complete', async ($, e, next) => {
|
||||
const out = await next(e)
|
||||
await resumeWatches($, cfg)
|
||||
const agentId = e.agentId
|
||||
if (!agentId) return out
|
||||
|
||||
@@ -903,9 +952,7 @@ export const register: Register = (on, options) => {
|
||||
const rec = (await getMap<AgentRec>($, S.agents))[agentId]
|
||||
if (!rec) return out
|
||||
// Only the run's end is a hand-back; wait for it after this event has gone on.
|
||||
const token = ++tokens
|
||||
lastTurn.set(agentId, { token, ended: e.reason, reported: e.usage?.model })
|
||||
$.clock.after(0, () => void awaitHandBack($, agentId, token, cfg))
|
||||
await watch($, agentId, { ended: e.reason, reported: e.usage?.model, since: await $.clock.now() }, cfg)
|
||||
return out
|
||||
})
|
||||
|
||||
@@ -953,6 +1000,11 @@ export const register: Register = (on, options) => {
|
||||
)
|
||||
.join('\n')
|
||||
const pending = Object.keys(await getMap<Pending>($, S.pending))
|
||||
const agents = await getMap<AgentRec>($, S.agents)
|
||||
const now = await $.clock.now()
|
||||
const waiting = Object.entries(await getMap<Watch>($, S.watching)).map(
|
||||
([id, w]) => `${agents[id]?.taskId ?? id} (agent ${id}, ${Math.round((now - w.since) / 60_000)} min)`,
|
||||
)
|
||||
return {
|
||||
text:
|
||||
`model-router - last ${Math.min(15, list.length)} of ${list.length}\n` +
|
||||
@@ -960,6 +1012,7 @@ export const register: Register = (on, options) => {
|
||||
`results: ${count(l => (l.outcome === 'spawned' ? undefined : l.outcome))}\n` +
|
||||
`opus requested on dev briefs: ${list.filter(l => l.opusRequested).length}\n` +
|
||||
(pending.length ? `pending rewrites: ${pending.join(', ')}\n` : '') +
|
||||
(waiting.length ? `waiting for a hand-back: ${waiting.join(', ')}\n` : '') +
|
||||
`\n${rows}\n\n` +
|
||||
savingsReport(await getMap<TaskCost>($, S.costs), 5),
|
||||
}
|
||||
|
||||
@@ -407,6 +407,14 @@ export type LoopStatus = 'pending' | 'running' | 'waiting' | 'idle' | 'completed
|
||||
export const turnEndKind = (status: LoopStatus | undefined): 'handback' | 'interim' =>
|
||||
status === undefined || status === 'completed' || status === 'failed' || status === 'killed' ? 'handback' : 'interim'
|
||||
|
||||
/**
|
||||
* How long an agent may stay `idle` before that counts as its hand-back (#12).
|
||||
* `idle` waits for a message, not on its own work (that is `waiting`): one that
|
||||
* stays idle has stopped and waits for the manager. A moment idle between turns
|
||||
* is not a hand-back.
|
||||
*/
|
||||
export const IDLE_HANDBACK_MS = 2 * 60 * 1000
|
||||
|
||||
/** How often an interim agent's status is checked again, and for how long at most. */
|
||||
export const WATCH_EVERY_MS = 15_000
|
||||
export const WATCH_FOR_MS = 24 * 60 * 60 * 1000
|
||||
|
||||
+108
-3
@@ -310,6 +310,8 @@ type World = {
|
||||
/** Untracked files in the clone; `addDuringTests` joins them while the full run goes. */
|
||||
untracked?: string[]
|
||||
addDuringTests?: string
|
||||
/** What the plugin's store holds at the start. */
|
||||
seed?: Record<string, unknown>
|
||||
/** What `git rev-parse HEAD` answers. */
|
||||
headSha?: string
|
||||
}
|
||||
@@ -320,7 +322,7 @@ const ok = (stdout: string, exitCode = 0) => ({
|
||||
})
|
||||
|
||||
function world(on: On, w: World) {
|
||||
mock.store(on)
|
||||
mock.store(on, w.seed)
|
||||
const clock = mock.clock(on)
|
||||
on('ui.status', async () => ({ value: undefined }))
|
||||
on('ui.toast', async () => ({ value: undefined }))
|
||||
@@ -771,7 +773,7 @@ test('TOOL-12: review and test agents get no hand-back line', async ($, on) => {
|
||||
// ---------- interim stops (TOOL-12 follow-up) ----------
|
||||
|
||||
/** A turn end of the agent while it is still alive: its status says so. */
|
||||
async function interimStop($: Engine, clock: { advance: (ms: number) => Promise<void> }, w: World, agentId: string, status = 'waiting') {
|
||||
async function interimStop($: Engine, clock: { advance: (ms: number) => Promise<void> }, w: World, agentId: string, status = 'waiting', model = 'claude-sonnet-5-5') {
|
||||
w.status[agentId] = status
|
||||
await ($.turn as unknown as { complete: (e: unknown) => Promise<unknown> }).complete({
|
||||
answer: 'Waiting for the test suite.',
|
||||
@@ -780,7 +782,7 @@ async function interimStop($: Engine, clock: { advance: (ms: number) => Promise<
|
||||
turnId: 't',
|
||||
agentId,
|
||||
reason: 'answer',
|
||||
usage: { model: 'claude-sonnet-5-5', input_tokens: 1, output_tokens: 1, cache_creation_input_tokens: 0, cache_read_input_tokens: 0 },
|
||||
usage: { model, input_tokens: 1, output_tokens: 1, cache_creation_input_tokens: 0, cache_read_input_tokens: 0 },
|
||||
})
|
||||
await clock.advance(1)
|
||||
}
|
||||
@@ -814,6 +816,8 @@ test('follow-up: an interim stop of an Opus dev posts nothing; its hand-back pos
|
||||
const id = r.agentId as string
|
||||
await interimStop($, clock, w, id)
|
||||
await interimStop($, clock, w, id, 'idle')
|
||||
await clock.advance(60_000) // a moment idle between turns (under IDLE_HANDBACK_MS) ...
|
||||
w.status[id] = 'running' // ... then its next turn
|
||||
await clock.advance(10 * 60 * 1000)
|
||||
expect(w.all).toEqual([])
|
||||
w.status[id] = 'completed'
|
||||
@@ -1428,3 +1432,104 @@ test('#11: header lines are not doubled, text after the marker is guidance, mid-
|
||||
expect('Call Agent with prompt [router-rewrite T9] now'.match(REWRITE_MARK)).toBe(null)
|
||||
expect('> [router-rewrite T9]'.match(REWRITE_MARK)?.[1]).toBe('T9')
|
||||
})
|
||||
|
||||
// ---------- #12: the last hand-back after an interim stop always gets its line ----------
|
||||
|
||||
const OPUS_DEV = `EV-20: decide how the export ramp should recover. Clone: ${DEV}/`
|
||||
|
||||
test('#12: an Opus dev that ends idle after an interim stop gets its line (EV-20 round 3)', async ($, on) => {
|
||||
const w = fresh()
|
||||
const clock = world(on, w)
|
||||
const r = await $.agent.spawn({ prompt: OPUS_DEV, description: 'EV-20 dev' } as never)
|
||||
const id = r.agentId as string
|
||||
w.status[id] = 'completed'
|
||||
await finish($, clock, id, 'claude-opus-5-5') // round 1
|
||||
await resume($, id, 'round 2')
|
||||
await finish($, clock, id, 'claude-opus-5-5') // round 2
|
||||
expect(w.all.length).toBe(2)
|
||||
|
||||
await resume($, id, 'round 3')
|
||||
await interimStop($, clock, w, id, 'waiting', 'claude-opus-5-5') // on its own background work
|
||||
await clock.advance(30 * 60 * 1000)
|
||||
expect(w.all.length).toBe(2)
|
||||
// its work is done; it ends its turn and stays idle, waiting for the manager
|
||||
await interimStop($, clock, w, id, 'idle', 'claude-opus-5-5')
|
||||
await clock.advance(60_000)
|
||||
expect(w.all.length).toBe(2) // not yet: a moment idle is no hand-back
|
||||
await clock.advance(2 * 60_000)
|
||||
expect(w.all.length).toBe(3)
|
||||
expect(w.all[2]).toBe('[model-router] T1 no verification: dev ran on Opus. Go straight to review.')
|
||||
await clock.advance(60 * 60_000)
|
||||
expect(w.all.length).toBe(3) // once
|
||||
})
|
||||
|
||||
test('#12: a plugin reload during an interim stop does not lose the hand-back', async ($, on) => {
|
||||
const w = fresh()
|
||||
w.diffs = ['diff']
|
||||
// after a hot reload: the watch is in the store, but nothing in the new module watches it
|
||||
w.seed = { watching: { 'agent-1': { wid: 'before-reload', ended: 'answer', reported: 'claude-sonnet-5-5', since: 0 } } }
|
||||
const clock = world(on, w)
|
||||
const r = await $.agent.spawn({ prompt: devBrief(), description: 'dev' } as never)
|
||||
const id = r.agentId as string
|
||||
expect(id).toBe('agent-1')
|
||||
w.status[id] = 'completed'
|
||||
await clock.advance(60_000)
|
||||
expect(w.all).toEqual([])
|
||||
// the next event after the reload (here a main-loop turn) picks the stored watch up
|
||||
await ($.turn as unknown as { complete: (e: unknown) => Promise<unknown> }).complete({
|
||||
answer: 'ok', durationMs: 1, isAborted: false, turnId: 'main', reason: 'answer',
|
||||
})
|
||||
await clock.advance(1)
|
||||
expect(w.handBacks).toEqual(['[model-router] T1 verifying on Opus...'])
|
||||
expect(w.verifier).toEqual(['opus'])
|
||||
await clock.advance(60 * 60_000)
|
||||
expect(w.handBacks.length).toBe(1)
|
||||
})
|
||||
|
||||
test('#12: a watch that ran its course is not resumed after a reload', async ($, on) => {
|
||||
const w = fresh()
|
||||
w.diffs = ['diff']
|
||||
const clock = world(on, w)
|
||||
const r = await $.agent.spawn({ prompt: devBrief(), description: 'dev' } as never)
|
||||
const id = r.agentId as string
|
||||
w.status[id] = 'completed'
|
||||
await finish($, clock, id, 'claude-sonnet-5-5')
|
||||
expect(w.handBacks.length).toBe(1)
|
||||
await ($.turn as unknown as { complete: (e: unknown) => Promise<unknown> }).complete({
|
||||
answer: 'ok', durationMs: 1, isAborted: false, turnId: 'main', reason: 'answer',
|
||||
})
|
||||
await clock.advance(60_000)
|
||||
expect(w.handBacks.length).toBe(1)
|
||||
expect(w.verifier.length).toBe(1)
|
||||
})
|
||||
|
||||
test('#12: idle only counts when it is held: idle, running, idle again starts the clock over', async ($, on) => {
|
||||
const w = fresh()
|
||||
const clock = world(on, w)
|
||||
const r = await $.agent.spawn({ prompt: OPUS_DEV, description: 'EV-20 dev' } as never)
|
||||
const id = r.agentId as string
|
||||
await interimStop($, clock, w, id, 'idle', 'claude-opus-5-5')
|
||||
await clock.advance(90_000)
|
||||
w.status[id] = 'running'
|
||||
await clock.advance(30_000)
|
||||
w.status[id] = 'idle'
|
||||
await clock.advance(90_000) // 3 min idle in all, never 2 in a row
|
||||
expect(w.all).toEqual([])
|
||||
await clock.advance(60_000)
|
||||
expect(w.all).toEqual(['[model-router] T1 no verification: dev ran on Opus. Go straight to review.'])
|
||||
})
|
||||
|
||||
test('#12: /router lists the agents still waiting for a hand-back', async ($, on) => {
|
||||
const w = fresh()
|
||||
const clock = world(on, w)
|
||||
const r = await $.agent.spawn({ prompt: OPUS_DEV, description: 'EV-20 dev' } as never)
|
||||
const id = r.agentId as string
|
||||
await interimStop($, clock, w, id, 'waiting', 'claude-opus-5-5')
|
||||
await clock.advance(30 * 60_000)
|
||||
const during = (await $.command.run({ command: 'router', args: '' } as never)).text ?? ''
|
||||
expect(during).toContain(`waiting for a hand-back: T1 (agent ${id}, 30 min)`)
|
||||
w.status[id] = 'completed'
|
||||
await clock.advance(16_000)
|
||||
const after = (await $.command.run({ command: 'router', args: '' } as never)).text ?? ''
|
||||
expect(after).not.toContain('waiting for a hand-back')
|
||||
})
|
||||
|
||||
Reference in New Issue
Block a user