5 Commits
Author SHA1 Message Date
adminandClaude Opus 5.5 034ecf1df4 0.5.2: README for #9-#12
116 tests; all 21 mutations for #9-#12 and the 16 for #7 caught.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MdqPWvuDpbpRvDEdURoAwo
2026-11-24 02:08:24 +00:00
adminandClaude Opus 5.5 fade3b8bba 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
2026-11-24 02:08:24 +00:00
adminandClaude Opus 5.5 2184024fe7 Fix #11: a rewrite prompt keeps its FAIL issues under hook header lines
The rewrite marker was only recognised as the first thing in the prompt.
pipeline-guard put header lines above it, so the router started the agent as a
new brief: header lines and a bare marker, no issues (EV-13 T9).

- [router-rewrite Tn] is recognised at the start of any line (also after > - *).
- Lines above it stay on top, once (lines the stored prompt has are dropped);
  the stored prompt with the issues follows; text after it is guidance.
- The rewrite keeps its task number and tier.

2 tests; 5 mutations, all caught.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MdqPWvuDpbpRvDEdURoAwo
2026-11-24 02:08:16 +00:00
adminandClaude Opus 5.5 df6e0d1694 Fix #10: the next round diffs from the tree that was verified
The "previous verified round" snapshot was taken after the round's tests and
verifier, up to 45 min later. A fix committed meanwhile became the base of the
next round: never verified, and the next hand-back got "no changes ... nothing
to verify" (EV-13 T10, PR #269).

- The snapshot and the untracked-file list are taken when the round reads the
  tree; the next round diffs from there.
- "No changes" names what it compared (base, current tree, HEAD).
- After a FAIL it adds that the FAIL stands, and to resume the agent with its
  issues or review the change.

4 tests; 5 mutations, all caught.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MdqPWvuDpbpRvDEdURoAwo
2026-11-24 02:08:15 +00:00
adminandClaude Opus 5.5 908cd7866d Fix #9: boilerplate sections never pick the model
pipeline-guard appends a "## Standing constraints" block to every brief; its
"flaky" matched HEAVY, so every guarded dev brief ran on Opus, unclassified.

- HEAVY/LIGHT match only the task text: a heading named Standing constraints,
  Constraints, Rules, House rules or Pipeline guard, and everything under it up
  to the next heading of the same or a higher level, is skipped.
- The light path's length limit counts the task text only.
- The same words in the task itself still route to Opus.

3 tests; 5 mutations, all caught.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MdqPWvuDpbpRvDEdURoAwo
2026-11-24 02:08:07 +00:00
5 changed files with 417 additions and 28 deletions
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "model-router",
"version": "0.5.1",
"version": "0.5.2",
"description": "Routes each subagent to Haiku, Sonnet or Opus by how well-defined its brief is, verifies dev work below Opus in its own clone on a different model, sends failures back to the same agent then a stronger one, and estimates the savings against Opus.",
"author": {
"name": "Glenn Schrooyen"
+5 -5
View File
@@ -6,12 +6,12 @@ A Claude Code plugin that picks a model for every subagent, checks dev work on a
| Step | Behaviour |
|---|---|
| Route | Dev agents run on **Sonnet** when the brief decides the approach (Expected / acceptance criteria), on **Opus** when the design is still open. Review and test agents keep the model they are given (Opus when none). Other non-dev agents (a `test-design` role, or the `test-designer` / `release-reviewer` agent types) do too, but never Haiku. None of them get a hand-back line or verification. |
| Route | Dev agents run on **Sonnet** when the brief decides the approach (Expected / acceptance criteria), on **Opus** when the design is still open. Sections a tool adds to every brief (`## Standing constraints`, `Constraints`, `Rules`, `Pipeline guard`) are not read for this. Review and test agents keep the model they are given (Opus when none). Other non-dev agents (a `test-design` role, or the `test-designer` / `release-reviewer` agent types) do too, but never Haiku. None of them get a hand-back line or verification. |
| Rerun reported files | With `testFileCommand` set, every file the full run reports as `TIMEOUT` or `FAIL` is rerun alone in the clone. A file that still fails or times out alone runs again on the base branch, in a worktree next to the clone (`<clone>-verifier-base`, removed afterwards). The verifier gets a table: a file that passes alone does not count, one that also fails on base is not caused by the change. |
| Later instructions | Every message sent to a dev agent after its brief (a SendMessage, or the message that resumes it) reaches the verifier as part of the task, so scope added later is judged as in scope. A resumed agent keeps its task number, routing and failure count. |
| Verify | When a dev agent below Opus finishes a round, the router diffs its clone against the merge base, runs the test command in that clone, and has **Opus** judge the change. |
| Hand-back line | Only dev agents get `T` numbers and lines; other agents are logged as `A1`, `A2`, ... Every dev hand-back gets one line at once: `[model-router] Tn verifying on Opus...` (a verdict follows), or `[model-router] Tn no verification: dev ran on Opus. Go straight to review.` Only the real hand-back counts: an interim stop while the dev waits on its own background work (e.g. a long test suite) posts nothing and starts no verifier. Decided by the model the run actually used, not only the routing choice; a difference is shown as `(routed to X, ran on Y)`. |
| On FAIL | 1st: resume the same agent with the issues. 2nd: a new agent one model up, in the same clone. After that: handed back to the manager. |
| Verify | When a dev agent below Opus finishes a round, the router diffs its clone against the merge base, runs the test command in that clone, and has **Opus** judge the change. The next round diffs from the tree this round read, so work done while tests and the verifier run is verified next time. "No changes" names the trees it compared; after a FAIL it says the FAIL stands. |
| Hand-back line | Only dev agents get `T` numbers and lines; other agents are logged as `A1`, `A2`, ... Every dev hand-back gets one line at once: `[model-router] Tn verifying on Opus...` (a verdict follows), or `[model-router] Tn no verification: dev ran on Opus. Go straight to review.` Only the real hand-back counts: an interim stop while the dev waits on its own background work (e.g. a long test suite) posts nothing and starts no verifier. A dev that stays `idle` (waiting for a message) for 2 minutes has handed back. Watches survive a plugin reload; `/router` lists the agents still waiting for a hand-back. Decided by the model the run actually used, not only the routing choice; a difference is shown as `(routed to X, ran on Y)`. |
| On FAIL | 1st: resume the same agent with the issues. 2nd: a new agent one model up, in the same clone, started with `[router-rewrite Tn]` (also below header lines a hook adds); its prompt carries the issues. After that: handed back to the manager. |
| Not verified | A test timeout, a test command that cannot run, a missing clone or merge base, or a verdict that cannot be read even after asking once more: reported as NOT VERIFIED, never as a FAIL. |
| Savings | `/router savings` prices every run on the model it ran on and compares it with the same tokens on Opus 5.5. |
@@ -67,7 +67,7 @@ claude plugin validate .
claude plugin test .
```
102 tests. Every routing, verification, cost and timeout rule was also checked by breaking it on purpose (66 mutations in v0.4.4, plus 13 for the verdict reader in v0.4.5 12 for the hand-back line in v0.4.6 10 for interim stops in v0.4.7 14 for resumes, later instructions and rewrites in v0.4.8 23 for file reruns in v0.4.9 and 16 for non-dev roles and gate agent types in v0.5.1; all caught by a test).
116 tests. Every routing, verification, cost and timeout rule was also checked by breaking it on purpose (66 mutations in v0.4.4, plus 13 for the verdict reader in v0.4.5 12 for the hand-back line in v0.4.6 10 for interim stops in v0.4.7 14 for resumes, later instructions and rewrites in v0.4.8 23 for file reruns in v0.4.9 16 for non-dev roles and gate agent types in v0.5.1 and 21 for #9-#12 in v0.5.2; all caught by a test).
## Known limits
+79 -15
View File
@@ -12,6 +12,7 @@ import {
} from './pricing'
import {
REWRITE_MARK,
rewritePrompt,
asTier,
clip,
decide,
@@ -24,6 +25,7 @@ import {
turnEndKind,
WATCH_EVERY_MS,
WATCH_FOR_MS,
IDLE_HANDBACK_MS,
safetyHit,
skipReason,
validTimeout,
@@ -116,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',
@@ -225,6 +231,8 @@ async function untracked($: EngineInterface, cwd: string) {
return r.ok ? r.out.split('\n').filter(Boolean) : []
}
const short = (sha: string | undefined) => (sha ? sha.slice(0, 8) : '?')
/** A commit holding the clone's tree as it is now (HEAD when clean). */
async function snapshot($: EngineInterface, cwd: string) {
const stash = await sh($, ['git', 'stash', 'create'], cwd)
@@ -431,7 +439,11 @@ async function verifyRound($: EngineInterface, agentId: string, rec: AgentRec, c
}
const head = `[model-router] ${rec.taskId} (agent ${agentId}, ${rec.tier}, round ${round})`
// 1. What this round changed.
// 1. What this round changed. The tree is read now, and this is the tree the
// verdict is about: the next round diffs from here, so work done while this
// round's tests and verifier run is never taken as already verified (#10).
const snapNow = await snapshot($, cwd)
const untrackedNow = await untracked($, cwd)
let base = rec.lastSnap
let baseLabel = 'the previous verified round'
if (!base) {
@@ -447,7 +459,7 @@ async function verifyRound($: EngineInterface, agentId: string, rec: AgentRec, c
}
const diff = await sh($, ['git', 'diff', base], cwd, 60_000)
const known = new Set(rec.lastUntracked ?? [])
const fresh = (await untracked($, cwd)).filter(f => !known.has(f))
const fresh = untrackedNow.filter(f => !known.has(f))
let added = ''
for (const f of fresh.slice(0, 20)) {
try {
@@ -460,7 +472,12 @@ async function verifyRound($: EngineInterface, agentId: string, rec: AgentRec, c
if (!changes) {
entry.outcome = 'no-changes'
await log($, entry)
await tell($, `${head}: no changes since ${baseLabel}; nothing to verify.`)
const headSha = (await sh($, ['git', 'rev-parse', 'HEAD'], cwd)).out.trim()
const compared = `compared ${short(base)} with ${short(snapNow)}, HEAD ${short(headSha)}`
const stands = rec.lastIssues?.length
? ` The FAIL of round ${rec.rounds ?? round - 1} stands: resume the agent with its issues, or review the change yourself.`
: ''
await tell($, `${head}: no changes since ${baseLabel} (${compared}); nothing to verify.${stands}`)
return
}
@@ -558,8 +575,8 @@ async function verifyRound($: EngineInterface, agentId: string, rec: AgentRec, c
const after: AgentRec = {
...rec,
rounds: round,
lastSnap: (await snapshot($, cwd)) ?? rec.lastSnap,
lastUntracked: await untracked($, cwd),
lastSnap: snapNow ?? rec.lastSnap,
lastUntracked: untrackedNow,
lastIssues: verdict.pass ? [] : verdict.issues,
}
@@ -680,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())
@@ -701,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)
@@ -738,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`)',
@@ -779,8 +839,7 @@ export const register: Register = (on, options) => {
if (markId && pending) {
taskId = markId
const extra = e.prompt.replace(REWRITE_MARK, '').trim()
prompt = pending.prompt + (extra ? `\n\nAdditional guidance from the orchestrator:\n${extra}` : '')
prompt = rewritePrompt(e.prompt, pending.prompt)
tier = pending.tier
fails = pending.fails
critical = pending.critical
@@ -879,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
@@ -892,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
})
@@ -942,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` +
@@ -949,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),
}
+59 -3
View File
@@ -114,16 +114,45 @@ const HEAVY = [
export type Route = { tier: Tier; reason: string }
// Standing text that tools add to every brief (pipeline-guard's constraints block):
// it says how to work, not what the task is, so it never picks a model (#9).
const BOILERPLATE_HEADING = /^(standing constraints?|constraints|house rules|rules|pipeline[- ]guard\b.*)\b/i
const HEADING = /^(#{1,6})[ \t]+(.*?)[ \t#]*$/
/**
* The brief without boilerplate sections: a heading named Standing constraints
* (or Constraints, Rules, House rules, Pipeline guard ...) and everything under
* it, up to the next heading of the same or a higher level.
*/
export const taskText = (prompt: string): string => {
const kept: string[] = []
let skipLevel = 0
for (const line of prompt.split(/\r?\n/)) {
const h = line.match(HEADING)
if (h) {
const level = h[1]!.length
if (skipLevel && level <= skipLevel) skipLevel = 0
if (!skipLevel && BOILERPLATE_HEADING.test(h[2]!.replace(/[*_`]/g, '').trim())) {
skipLevel = level
continue
}
}
if (!skipLevel) kept.push(line)
}
return kept.join('\n')
}
/** A clear signal from the text, or undefined (ask the classifier). */
export const heuristic = (subagentType: string | undefined, prompt: string, role?: Role): Route | undefined => {
if (!role && subagentType && READ_ONLY_TYPES.test(subagentType))
return { tier: 'haiku', reason: `read-only agent type ${subagentType}` }
const lower = prompt.toLowerCase()
const task = taskText(prompt)
const lower = task.toLowerCase()
const heavy = HEAVY.find(r => r.test(lower))
if (heavy) return { tier: 'opus', reason: 'approach still open' }
if (role) return undefined // dev briefs never take the light path
const light = LIGHT.find(r => r.test(lower))
if (light && prompt.length < 1500) return { tier: 'haiku', reason: 'light task' }
if (light && task.length < 1500) return { tier: 'haiku', reason: 'light task' }
return undefined
}
@@ -296,7 +325,26 @@ export const parseVerdict = (text: string): Reading => {
return { isReadable: false, preview: text.slice(0, 300) }
}
export const REWRITE_MARK = /^\s*\[router-rewrite (T\d+)\]/
// At the start of any line: hooks such as pipeline-guard put header lines above it (#11).
export const REWRITE_MARK = /^[ \t>*-]*\[router-rewrite (T\d+)\][ \t]*/m
/**
* The prompt for a router rewrite: lines a hook put above the marker stay on
* top (once: lines the stored prompt already has are dropped), the stored
* prompt with the FAIL issues follows, and text after the marker is guidance.
*/
export const rewritePrompt = (given: string, stored: string): string => {
const m = given.match(REWRITE_MARK)
if (!m || m.index === undefined) return stored
const has = new Set(stored.split('\n').map(l => l.trim()).filter(Boolean))
const header = given
.slice(0, m.index)
.split('\n')
.filter(l => l.trim() && !has.has(l.trim()))
.join('\n')
const extra = given.slice(m.index + m[0].length).trim()
return [header, stored, extra ? `Additional guidance from the orchestrator:\n${extra}` : ''].filter(Boolean).join('\n\n')
}
export const clip = (s: string, n: number) =>
s.length <= n ? s : s.slice(0, n) + `\n... [${s.length - n} more characters cut]`
@@ -359,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
+273 -4
View File
@@ -4,10 +4,13 @@ import { expect, mock, test, type Engine } from 'claude-code/testing'
import {
decide,
heuristic,
taskText,
rewritePrompt,
onFail,
parseBrief,
parseVerdict,
rewriteTier,
REWRITE_MARK,
skipReason,
validTimeout,
verifierFor,
@@ -300,6 +303,17 @@ type World = {
/** A test itself prints the timeout line, on stdout. */
testLineOnStdout?: boolean
snap: number
/** When set, a snapshot names the tree version (tree1, tree2, ...) instead of counting calls. */
tree?: number
/** The dev commits while the full test run is going: the tree version goes up. */
commitDuringTests?: boolean
/** 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
}
const USAGE = { input_tokens: 1, output_tokens: 1, cache_creation_input_tokens: 0, cache_read_input_tokens: 0 }
@@ -308,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 }))
@@ -324,7 +338,9 @@ function world(on: On, w: World) {
const cwd = String(e.init?.cwd ?? '')
if (cwd !== DEV) return ok('', 128) // not a git repo: the session folder
if (a === 'git merge-base origin/release/1.0 HEAD') return ok('mergebase\n')
if (a === 'git stash create') return ok(`snap${++w.snap}\n`)
if (a === 'git stash create') return ok(w.tree !== undefined ? `tree${w.tree}\n` : `snap${++w.snap}\n`)
if (a === 'git rev-parse HEAD') return ok(`${w.headSha ?? ''}\n`)
if (a === 'git ls-files --others --exclude-standard') return ok((w.untracked ?? []).join('\n'))
if (a.startsWith('git diff ')) {
w.diffBases.push(e.argv[2] ?? '')
return ok(w.diffs.shift() ?? '')
@@ -351,6 +367,8 @@ function world(on: On, w: World) {
return { value: { code: outcome === 'pass' ? 0 : outcome === 'timeout' ? 124 : 1, signal: null } }
}
w.testCwd.push(String(e.cwd ?? ''))
if (w.commitDuringTests && w.tree !== undefined) w.tree++
if (w.addDuringTests) w.untracked = [...(w.untracked ?? []), w.addDuringTests]
w.testArgv.push([...e.argv])
const end = w.testEnds.shift() ?? 0
const fired = w.testFired.shift() ?? false
@@ -755,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.',
@@ -764,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)
}
@@ -798,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'
@@ -1264,3 +1284,252 @@ test('#7: a test designer is no saving and gets an A number; the log shows its r
expect(log).toContain('test-design')
expect(log).not.toContain('T1')
})
// ---------- #9: boilerplate never picks the model ----------
const GUARD_BLOCK =
'\n\n## Standing constraints\n' +
'- A rerun only for a named, reproduced flaky test, never a blanket retry.\n' +
'- Do not redesign shared fixtures; propose an approach in the PR if one is needed.\n'
const SONNET_BRIEF = `Pipeline-Role: dev\nClone: ${DEV} (Role: dev)\nBase branch: release/1.0.\nEV-19: clamp the export setpoint to the grid limit as specified. Expected: test_export_clamp passes.`
test('#9: the guard block appended to a Sonnet-shaped dev brief goes to the classifier, not Opus', async () => {
expect(heuristic(undefined, SONNET_BRIEF + GUARD_BLOCK, 'dev')).toBe(undefined)
expect(decide({ role: 'dev', prompt: SONNET_BRIEF + GUARD_BLOCK, respectExplicit: false }).kind).toBe('classify')
// the same words in the task itself still mean the approach is open
expect(heuristic(undefined, SONNET_BRIEF + '\nFind out why test_export_clamp is flaky.' + GUARD_BLOCK, 'dev')?.tier).toBe('opus')
})
test('#9: a skipped section ends at the next heading of the same or a higher level', async () => {
const t = taskText('# EV-19\nclamp it\n## Standing constraints\n- flaky\n### sub\n- design\n## Task\nredesign the loop\n')
expect(t).not.toContain('flaky')
expect(t).not.toContain('- design')
expect(t).toContain('redesign the loop')
expect(t).toContain('clamp it')
// headings in other styles and levels
expect(taskText('x\n### **Constraints**\n- intermittent\n')).not.toContain('intermittent')
expect(taskText('x\n## Pipeline guard (v3)\n- trade-offs\n')).not.toContain('trade-offs')
expect(taskText('x\n## Constraints on the design\n- keep it\n')).not.toContain('keep it')
// the heading line goes too: its words are no task either
expect(taskText('x\n## Constraints on the design\n- keep it\n')).not.toContain('design')
// a heading that only starts with the word is no boilerplate
expect(taskText('## Rulesets to design\nnew ruleset')).toContain('new ruleset')
})
test('#9 end to end: a guarded dev brief is classified, and the light path stays closed', async ($, on) => {
const w = fresh()
world(on, w)
await $.agent.spawn({ prompt: SONNET_BRIEF + GUARD_BLOCK, description: 'ev19' } as never)
expect(w.spawned[0]?.model).toBe('sonnet')
// boilerplate is not counted toward the light path's length either
expect(heuristic(undefined, 'Find where the MQTT discovery payload is built' + GUARD_BLOCK + 'x'.repeat(2000))?.tier).toBe('haiku')
})
// ---------- #10: the next round diffs from the tree that was verified ----------
test('#10: a fix committed while round 1 is verified is verified in round 2 (EV-13)', { options: { testCommand: 'run-tests' } }, async ($, on) => {
const w = fresh()
w.tree = 1
w.commitDuringTests = true // the dev commits 57a9f56 while round 1's suite runs
w.diffs = ['diff --git a/one.py', 'diff --git a/fix.py']
w.verdicts = ['{"verdict":"FAIL","issues":["named_absence missing"]}', '{"verdict":"PASS"}']
const clock = world(on, w)
const r = await $.agent.spawn({ prompt: devBrief(), description: 'ev13' } as never)
await finish($, clock, r.agentId as string)
expect(w.all.some(l => l.includes('FAIL'))).toBe(true)
await resume($, r.agentId as string, 'Fix: named_absence missing')
await finish($, clock, r.agentId as string)
// round 2 diffs from the tree round 1 read (tree1), not the one after its tests (tree2)
expect(w.diffBases[1]).toBe('tree1')
expect(w.verifier.length).toBe(2)
expect(w.all.some(l => l.includes('nothing to verify'))).toBe(false)
})
test('#10: "no changes" names the trees it compared, and says a FAIL stands', { options: { testCommand: 'run-tests' } }, async ($, on) => {
const w = fresh()
w.tree = 7
w.headSha = '0774d1e0aaaabbbb'
w.diffs = ['diff --git a/one.py', '']
w.verdicts = ['{"verdict":"FAIL","issues":["P4 not argued"]}']
const clock = world(on, w)
const r = await $.agent.spawn({ prompt: devBrief(), description: 'ev13' } as never)
await finish($, clock, r.agentId as string)
await resume($, r.agentId as string, 'Fix: P4 not argued')
await finish($, clock, r.agentId as string)
const line = w.all.find(l => l.includes('nothing to verify')) ?? ''
expect(line).toContain('compared tree7 with tree7, HEAD 0774d1e0')
expect(line).toContain('The FAIL of round 1 stands: resume the agent with its issues')
})
test('#10: after a PASS, "no changes" adds no FAIL note', { options: { testCommand: 'run-tests' } }, async ($, on) => {
const w = fresh()
w.tree = 1
w.diffs = ['diff --git a/one.py', '']
const clock = world(on, w)
const r = await $.agent.spawn({ prompt: devBrief(), description: 'x' } as never)
await finish($, clock, r.agentId as string)
await resume($, r.agentId as string, 'one more thing')
await finish($, clock, r.agentId as string)
const line = w.all.find(l => l.includes('nothing to verify')) ?? ''
expect(line).toContain('compared tree1 with tree1')
expect(line).not.toContain('stands')
})
test('#10: a new file created while round 1 is verified counts as new in round 2', { options: { testCommand: 'run-tests' } }, async ($, on) => {
const w = fresh()
w.tree = 1
w.untracked = ['old_notes.md']
w.addDuringTests = 'tests/test_named_absence.py'
w.diffs = ['diff --git a/one.py', '']
w.verdicts = ['{"verdict":"FAIL","issues":["named_absence missing"]}', '{"verdict":"PASS"}']
const clock = world(on, w)
const r = await $.agent.spawn({ prompt: devBrief(), description: 'ev13' } as never)
await finish($, clock, r.agentId as string)
w.addDuringTests = undefined
await resume($, r.agentId as string, 'Fix: named_absence missing')
await finish($, clock, r.agentId as string)
expect(w.verifier.length).toBe(2)
expect(w.verifierPrompts[1]).toContain('new file: tests/test_named_absence.py')
expect(w.verifierPrompts[1]).not.toContain('new file: old_notes.md')
})
// ---------- #11: the rewrite prompt keeps its issues under hook header lines ----------
const GUARD_HEADER = 'Pipeline-Role: dev\nPipeline-Guard: v3 (EV-13)\n'
test('#11: a rewrite marker under guard header lines starts the stored rewrite, issues and all (EV-13 T9)', async ($, on) => {
const w = fresh()
w.diffs = ['d1', 'd2']
w.verdicts = [
'{"verdict":"FAIL","issues":["P1/P2 not in the N2 check"]}',
'{"verdict":"FAIL","issues":["P4 arm-at-send assert","R1 kill not shown"]}',
]
const clock = world(on, w)
const r = await $.agent.spawn({ prompt: devBrief(), description: 'ev13' } as never)
await finish($, clock, r.agentId as string)
await finish($, clock, r.agentId as string)
expect(w.told[1]).toContain('[router-rewrite T1]')
await $.agent.spawn({ prompt: `${GUARD_HEADER}[router-rewrite T1]`, description: 'rewrite' } as never)
const p = w.spawned[1]?.prompt ?? ''
expect(p).toContain('- P4 arm-at-send assert')
expect(p).toContain('- R1 kill not shown')
expect(p).toContain(`Their work is in the clone ${DEV}`)
expect(p.startsWith('Pipeline-Role: dev\nPipeline-Guard: v3 (EV-13)')).toBe(true)
expect(w.spawned[1]?.model).toBe('opus') // the rewrite's tier, not a fresh routing
const log = (await $.command.run({ command: 'router', args: '' } as never)).text ?? ''
expect(log).not.toContain('T2') // the same task, no new number
})
test('#11: header lines are not doubled, text after the marker is guidance, mid-line mentions are no marker', async () => {
const stored = 'Pipeline-Role: dev\nClone: /x/clones/EV-13-dev\nDo it.\n\n## Previous attempts rejected\nIssues:\n- a'
const p = rewritePrompt('Pipeline-Role: dev\nPipeline-Guard: v3\n\n[router-rewrite T9]\nKeep the P4 test.', stored)
expect(p.split('Pipeline-Role: dev').length).toBe(2) // once
expect(p.startsWith('Pipeline-Guard: v3\n\nPipeline-Role: dev')).toBe(true)
expect(p).toContain('- a')
expect(p.endsWith('Additional guidance from the orchestrator:\nKeep the P4 test.')).toBe(true)
expect(rewritePrompt('[router-rewrite T9]', stored)).toBe(stored)
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')
})