Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d5c762b339 | ||
|
|
fd75c183ba |
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "model-router",
|
||||
"version": "0.4.7",
|
||||
"version": "0.4.9",
|
||||
"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"
|
||||
@@ -18,6 +18,36 @@
|
||||
"description": "How long the test command may run in the clone. A run that times out is reported as NOT VERIFIED, never as a FAIL.",
|
||||
"default": 1800
|
||||
},
|
||||
"testFileCommand": {
|
||||
"type": "string",
|
||||
"title": "Command that runs one test file",
|
||||
"description": "Run in the clone, with {file} replaced by a file the full run reported as TIMEOUT or FAIL. Each such file is rerun alone, and on the base branch if it still fails. Empty: no reruns.",
|
||||
"default": ""
|
||||
},
|
||||
"testFileTimeoutSec": {
|
||||
"type": "number",
|
||||
"title": "Time limit per rerun file (seconds)",
|
||||
"description": "A file still running after this counts as timing out alone.",
|
||||
"default": 900
|
||||
},
|
||||
"testRerunJobs": {
|
||||
"type": "number",
|
||||
"title": "Reruns at a time",
|
||||
"description": "How many reported files are rerun in parallel.",
|
||||
"default": 6
|
||||
},
|
||||
"testRerunMax": {
|
||||
"type": "number",
|
||||
"title": "Most files to rerun",
|
||||
"description": "Reported files beyond this are listed as not rerun.",
|
||||
"default": 40
|
||||
},
|
||||
"testIssuePattern": {
|
||||
"type": "string",
|
||||
"title": "Pattern of a reported file line",
|
||||
"description": "Regular expression: group 1 is TIMEOUT or FAIL, group 2 the file. Empty: ^(TIMEOUT|FAIL)\\s+(\\S+)",
|
||||
"default": ""
|
||||
},
|
||||
"defaultBaseBranch": {
|
||||
"type": "string",
|
||||
"title": "Base branch when the brief names none",
|
||||
|
||||
@@ -7,6 +7,8 @@ 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). |
|
||||
| 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 | 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. |
|
||||
@@ -38,6 +40,11 @@ Or for development: `claude --plugin-dir /path/to/model-router`.
|
||||
|---|---|---|
|
||||
| `testCommand` | empty | Run in the agent's clone; output goes to the verifier |
|
||||
| `testTimeoutSec` | 1800 | Wrapped in GNU `timeout --verbose`; a timeout is NOT VERIFIED |
|
||||
| `testFileCommand` | empty | Runs one file, `{file}` replaced by a reported file name; only names of letters, digits, `_ . - /` are run |
|
||||
| `testFileTimeoutSec` | 900 | Limit per rerun file |
|
||||
| `testRerunJobs` | 6 | Reruns at a time |
|
||||
| `testRerunMax` | 40 | Most files rerun per round |
|
||||
| `testIssuePattern` | `^(TIMEOUT\|FAIL)\s+(\S+)` | Group 1 the kind, group 2 the file |
|
||||
| `defaultBaseBranch` | `release/1.0` | After the PR lookup and the brief's own base branch |
|
||||
| `prBaseCommand` | empty | Optional command that prints the PR's base branch |
|
||||
| `maxRewrites` | 2 | Failed verdicts before handing back |
|
||||
@@ -59,7 +66,7 @@ claude plugin validate .
|
||||
claude plugin test .
|
||||
```
|
||||
|
||||
69 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 and 10 for interim stops in v0.4.7; all caught by a test).
|
||||
92 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 and 23 for file reruns in v0.4.9; all caught by a test).
|
||||
|
||||
## Known limits
|
||||
|
||||
|
||||
+186
-14
@@ -27,6 +27,15 @@ import {
|
||||
safetyHit,
|
||||
skipReason,
|
||||
validTimeout,
|
||||
fileCommand,
|
||||
isSafeFile,
|
||||
issueRegex,
|
||||
parseIssueLine,
|
||||
positiveInt,
|
||||
rerunTable,
|
||||
type FileKind,
|
||||
type FileRun,
|
||||
type RerunRow,
|
||||
verifierFor,
|
||||
type Role,
|
||||
type Tier,
|
||||
@@ -39,8 +48,12 @@ type AgentRec = {
|
||||
taskId: string
|
||||
/** The model the last round actually ran on (the routing choice until a round reports one). */
|
||||
tier: Tier
|
||||
/** The model the router chose at spawn; tier can differ when the run used another. */
|
||||
/** The model the engine resolved at spawn; tier can differ when the run used another. */
|
||||
routed?: Tier
|
||||
/** The name the Agent call gave it, which SendMessage may address it by. */
|
||||
name?: string
|
||||
/** Later instructions to this agent (resumes, SendMessage), oldest first: part of its task. */
|
||||
followUps?: string[]
|
||||
role?: Role
|
||||
clone?: string
|
||||
baseBranch?: string
|
||||
@@ -122,6 +135,8 @@ When unsure between sonnet and opus, pick sonnet: a failed verification escalate
|
||||
const VERIFIER_SYSTEM = `You are an adversarial verifier. Another model wrote the change below. You did not.
|
||||
Judge only whether the change correctly and completely does the task, without breaking anything nearby.
|
||||
Look for: requirements or acceptance criteria missed, wrong logic, unhandled edge cases, tests that cannot fail, tests weakened or deleted, safety checks bypassed, unrelated changes.
|
||||
Scope added in "Later instructions" was asked for after the brief: judge it as in scope, not as unrequested work.
|
||||
When a table of files rerun one by one is given: a file that passes alone does not count against the change (the full run was overloaded or flaky); one that also fails or times out on base is not caused by this change: mention it, do not fail for it. Name every file you count against the change in issues.
|
||||
Do not fail a change for style alone. A later PR review and mutation testing follow you; you are the cheap first gate.
|
||||
|
||||
Reply with JSON only:
|
||||
@@ -133,7 +148,8 @@ The model-router mod picks each subagent's model and verifies dev work before it
|
||||
- Dev agents are routed: Sonnet when the brief decides the approach (Expected / acceptance criteria), Opus when the design is still open. Naming a model on a dev brief has no effect. Give each dev brief its clone path and base branch.
|
||||
- Review and test agents keep the model you name (Opus when you name none).
|
||||
- Every dev hand-back gets one "[model-router] Tn" line at once; an interim stop while the dev waits on its own background work gets none. "verifying on Opus...": wait for the verdict before advancing the PR. "no verification: dev ran on Opus. Go straight to review.": no verdict will come. Lines are decided by the model the dev actually ran on.
|
||||
- On "[model-router] ... FAIL ... resume agent", resume that same agent with SendMessage, passing the issues. On "start a new agent ... [router-rewrite Tn]", stop the old agent and call Agent with exactly that prompt. On "handed back", stop and show the issues to the person. Do not fix rejected work yourself.`
|
||||
- On "[model-router] ... FAIL ... resume agent", resume that same agent with SendMessage, passing the issues. On "start a new agent ... [router-rewrite Tn]", stop the old agent and call Agent with exactly that prompt. On "handed back", stop and show the issues to the person.
|
||||
- Scope or decisions added after the brief: send them to the dev agent with SendMessage. The verifier sees every later message to that agent and treats it as in scope. A resumed agent keeps its task number. Do not fix rejected work yourself.`
|
||||
|
||||
// ---------- store helpers (top-level, as the engine requires for `$`) ----------
|
||||
|
||||
@@ -254,18 +270,37 @@ async function chargeOverhead($: EngineInterface, taskId: string, alias: Tier, u
|
||||
await updateIn<TaskCost>($, S.costs, taskId, old => addOverhead(old ?? emptyTask(taskId), modelId, u, prices))
|
||||
}
|
||||
|
||||
type TestRun = { status: 'ran' | 'timeout' | 'error'; code: number | null; tail: string; seconds: number }
|
||||
type TestRun = {
|
||||
status: 'ran' | 'timeout' | 'error'
|
||||
code: number | null
|
||||
tail: string
|
||||
seconds: number
|
||||
/** Files the run reported as TIMEOUT or FAIL, in order, each once. */
|
||||
issues: { kind: FileKind; file: string }[]
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs the test command in the clone, streamed: `$.process.run` stops at ten
|
||||
* minutes, a stream has no limit of its own. GNU `timeout` does the kill.
|
||||
* A timeout or a run that could not start is no verdict on the code.
|
||||
*/
|
||||
async function runTests($: EngineInterface, cmd: string, cwd: string, timeoutSec: number): Promise<TestRun> {
|
||||
async function runTests($: EngineInterface, cmd: string, cwd: string, timeoutSec: number, issueRe?: RegExp): Promise<TestRun> {
|
||||
const started = await $.clock.now()
|
||||
const seconds = async () => Math.round(((await $.clock.now()) - started) / 1000)
|
||||
let out = ''
|
||||
let errTail = ''
|
||||
// reported files are read line by line as the run streams, not from the kept tail
|
||||
const issues: TestRun['issues'] = []
|
||||
const partial: Record<string, string> = { stdout: '', stderr: '' }
|
||||
const readLines = (stream: string, text: string, isLast = false) => {
|
||||
if (!issueRe) return
|
||||
const lines = ((partial[stream] ?? '') + text).split('\n')
|
||||
partial[stream] = isLast ? '' : lines.pop() ?? ''
|
||||
for (const line of lines) {
|
||||
const hit = parseIssueLine(line, issueRe)
|
||||
if (hit && !issues.some(i => i.file === hit.file)) issues.push(hit)
|
||||
}
|
||||
}
|
||||
try {
|
||||
const stream = $.process.spawn({
|
||||
argv: ['timeout', '--verbose', '--kill-after=30', String(Math.max(1, Math.round(timeoutSec))), 'sh', '-c', cmd],
|
||||
@@ -274,7 +309,10 @@ async function runTests($: EngineInterface, cmd: string, cwd: string, timeoutSec
|
||||
for await (const piece of stream) {
|
||||
out = (out + piece.text).slice(-65_536)
|
||||
if (piece.stream === 'stderr') errTail = (errTail + piece.text).slice(-65_536)
|
||||
readLines(piece.stream, piece.text)
|
||||
}
|
||||
readLines('stdout', '', true)
|
||||
readLines('stderr', '', true)
|
||||
// GNU timeout --verbose says so on stderr when, and only when, it fires.
|
||||
// Read from the joined stderr, so a line split across pieces still counts.
|
||||
const isFired = errTail.includes('timeout: sending signal')
|
||||
@@ -283,17 +321,81 @@ async function runTests($: EngineInterface, cmd: string, cwd: string, timeoutSec
|
||||
const took = await seconds()
|
||||
// Only a timeout that fired is a timeout: a 137 without it is the code's own
|
||||
// (e.g. out of memory) and goes to the verifier as a failed run.
|
||||
if (isFired) return { status: 'timeout', code: end.code, tail, seconds: took }
|
||||
if (end.code === 126 || end.code === 127) return { status: 'error', code: end.code, tail, seconds: took }
|
||||
return { status: 'ran', code: end.code, tail, seconds: took }
|
||||
if (isFired) return { status: 'timeout', code: end.code, tail, seconds: took, issues }
|
||||
if (end.code === 126 || end.code === 127) return { status: 'error', code: end.code, tail, seconds: took, issues }
|
||||
return { status: 'ran', code: end.code, tail, seconds: took, issues }
|
||||
} catch (err) {
|
||||
return { status: 'error', code: null, tail: String(err).slice(0, 500), seconds: await seconds() }
|
||||
return { status: 'error', code: null, tail: String(err).slice(0, 500), seconds: await seconds(), issues }
|
||||
}
|
||||
}
|
||||
|
||||
/** The result of one file run alone. */
|
||||
function fileRunOf(t: TestRun): FileRun {
|
||||
if (t.status === 'timeout') return 'timeout'
|
||||
if (t.status === 'error') return 'error'
|
||||
return t.code === 0 ? 'pass' : 'fail'
|
||||
}
|
||||
|
||||
/** Runs `work` over the items, at most `jobs` at a time, keeping their order. */
|
||||
async function inPool<T, R>(items: readonly T[], jobs: number, work: (item: T) => Promise<R>): Promise<R[]> {
|
||||
const out: R[] = new Array(items.length)
|
||||
let next = 0
|
||||
const lane = async () => {
|
||||
while (next < items.length) {
|
||||
const i = next++
|
||||
out[i] = await work(items[i] as T)
|
||||
}
|
||||
}
|
||||
await Promise.all(Array.from({ length: Math.max(1, Math.min(jobs, items.length)) }, lane))
|
||||
return out
|
||||
}
|
||||
|
||||
/**
|
||||
* Reruns the files a full run reported, one by one in the clone; those that
|
||||
* still fail or time out alone run again on the base, checked out next to the
|
||||
* clone (`<clone>-verifier-base`, removed afterwards).
|
||||
*/
|
||||
async function rerunReported($: EngineInterface, rec: AgentRec, issues: TestRun['issues'], cfg: Settings): Promise<RerunRow[]> {
|
||||
const cwd = rec.clone as string
|
||||
const picked = issues.filter(i => isSafeFile(i.file)).slice(0, cfg.testRerunMax)
|
||||
const rows: RerunRow[] = picked.map(i => ({ file: i.file, full: i.kind, head: 'not run', base: 'not run' }))
|
||||
const runAll = (dir: string, which: RerunRow[]) =>
|
||||
inPool(which, cfg.testRerunJobs, async r =>
|
||||
fileRunOf(await runTests($, fileCommand(cfg.testFileCommand, r.file), dir, cfg.testFileTimeoutSec)),
|
||||
)
|
||||
|
||||
$.ui.status(`router: ${rec.taskId} rerunning ${rows.length} reported file(s) alone`)
|
||||
const head = await runAll(cwd, rows)
|
||||
rows.forEach((r, i) => (r.head = head[i] ?? 'error'))
|
||||
|
||||
const onBase = rows.filter(r => r.head === 'fail' || r.head === 'timeout')
|
||||
if (onBase.length === 0) return rows
|
||||
const { base } = await firstBase($, rec, cfg.prBaseCommand, cfg.defaultBaseBranch)
|
||||
if (!base) return rows
|
||||
const tree = `${cwd.replace(/\/+$/, '')}-verifier-base`
|
||||
await sh($, ['git', '-C', cwd, 'worktree', 'remove', '--force', tree], cwd)
|
||||
await sh($, ['git', '-C', cwd, 'worktree', 'prune'], cwd)
|
||||
const added = await sh($, ['git', '-C', cwd, 'worktree', 'add', '--detach', tree, base], cwd, 120_000)
|
||||
if (!added.ok) return rows
|
||||
try {
|
||||
$.ui.status(`router: ${rec.taskId} rerunning ${onBase.length} file(s) on base`)
|
||||
const results = await runAll(tree, onBase)
|
||||
onBase.forEach((r, i) => (r.base = results[i] ?? 'error'))
|
||||
} finally {
|
||||
await sh($, ['git', '-C', cwd, 'worktree', 'remove', '--force', tree], cwd, 120_000)
|
||||
await sh($, ['git', '-C', cwd, 'worktree', 'prune'], cwd)
|
||||
}
|
||||
return rows
|
||||
}
|
||||
|
||||
type Settings = {
|
||||
testCommand: string
|
||||
testTimeoutSec: number
|
||||
testFileCommand: string
|
||||
testFileTimeoutSec: number
|
||||
testRerunJobs: number
|
||||
testRerunMax: number
|
||||
testIssueRe: RegExp
|
||||
prBaseCommand: string
|
||||
defaultBaseBranch: string
|
||||
maxFails: number
|
||||
@@ -355,7 +457,7 @@ async function verifyRound($: EngineInterface, agentId: string, rec: AgentRec, c
|
||||
let tests = ''
|
||||
if (cfg.testCommand) {
|
||||
$.ui.status(`router: ${rec.taskId} round ${round} running tests`)
|
||||
const t = await runTests($, cfg.testCommand, cwd, cfg.testTimeoutSec)
|
||||
const t = await runTests($, cfg.testCommand, cwd, cfg.testTimeoutSec, cfg.testIssueRe)
|
||||
if (t.status !== 'ran') {
|
||||
// No verdict on the code: no verifier call, no fail counted, no rewrite.
|
||||
entry.outcome = t.status === 'timeout' ? 'tests-timeout' : 'tests-error'
|
||||
@@ -372,6 +474,13 @@ async function verifyRound($: EngineInterface, agentId: string, rec: AgentRec, c
|
||||
return
|
||||
}
|
||||
tests = `exit code ${t.code} after ${t.seconds} s\n${t.tail}`
|
||||
if (cfg.testFileCommand && t.issues.length > 0) {
|
||||
const rows = await rerunReported($, rec, t.issues, cfg)
|
||||
const skipped = t.issues.length - rows.length
|
||||
tests +=
|
||||
`\n\n### Files the full run reported, rerun one by one\n${rerunTable(rows)}` +
|
||||
(skipped > 0 ? `\n(${skipped} more reported file(s) not rerun: unsafe name or over testRerunMax.)` : '')
|
||||
}
|
||||
}
|
||||
|
||||
// 3. The verdict, from another model.
|
||||
@@ -380,6 +489,11 @@ async function verifyRound($: EngineInterface, agentId: string, rec: AgentRec, c
|
||||
$.ui.status(`router: ${rec.taskId} round ${round} verifying on ${verifier}`)
|
||||
const question = [
|
||||
`## Task\n${clip(rec.prompt, 12_000)}`,
|
||||
rec.followUps?.length
|
||||
? `## Later instructions to this agent (after the brief; part of the task, in scope)\n${rec.followUps
|
||||
.map((f, i) => `${i + 1}. ${f}`)
|
||||
.join('\n\n')}`
|
||||
: '',
|
||||
rec.lastIssues?.length
|
||||
? `## Issues raised last round (check they are fixed)\n${rec.lastIssues.map(i => `- ${i}`).join('\n')}`
|
||||
: '',
|
||||
@@ -526,6 +640,29 @@ async function runRound($: EngineInterface, agentId: string, rec: AgentRec, ende
|
||||
else await verifyRound($, agentId, round, cfg)
|
||||
}
|
||||
|
||||
// ---------- later instructions (#6) ----------
|
||||
|
||||
const FOLLOW_UPS_KEPT = 12
|
||||
|
||||
/** Adds a later instruction to a tracked agent's record; the same text twice counts once. */
|
||||
async function noteFollowUp($: EngineInterface, agentId: string, text: string) {
|
||||
const t = text.trim()
|
||||
if (!t) return
|
||||
await updateIn<AgentRec>($, S.agents, agentId, old => {
|
||||
if (!old) return undefined
|
||||
const list = old.followUps ?? []
|
||||
if (list.includes(clip(t, 4000))) return old
|
||||
return { ...old, followUps: [...list, clip(t, 4000)].slice(-FOLLOW_UPS_KEPT) }
|
||||
})
|
||||
}
|
||||
|
||||
/** The tracked agent a SendMessage `to` names: its id, or the name its Agent call gave it. */
|
||||
async function agentAddressed($: EngineInterface, to: string) {
|
||||
const recs = await getMap<AgentRec>($, S.agents)
|
||||
if (recs[to]) return to
|
||||
return Object.keys(recs).find(id => recs[id]?.name === to)
|
||||
}
|
||||
|
||||
// ---------- waiting for the real hand-back ----------
|
||||
|
||||
// The newest turn end per agent. A turn end that is only an interim stop (the
|
||||
@@ -576,6 +713,11 @@ export const register: Register = (on, options) => {
|
||||
const cfg: Settings = {
|
||||
testCommand: String(options.testCommand ?? '').trim(),
|
||||
testTimeoutSec: validTimeout(options.testTimeoutSec),
|
||||
testFileCommand: String(options.testFileCommand ?? '').trim(),
|
||||
testFileTimeoutSec: positiveInt(options.testFileTimeoutSec, 900),
|
||||
testRerunJobs: positiveInt(options.testRerunJobs, 6),
|
||||
testRerunMax: positiveInt(options.testRerunMax, 40),
|
||||
testIssueRe: issueRegex(String(options.testIssuePattern ?? '')),
|
||||
prBaseCommand: String(options.prBaseCommand ?? '').trim(),
|
||||
defaultBaseBranch: String(options.defaultBaseBranch ?? 'release/1.0').trim(),
|
||||
maxFails: Number(options.maxRewrites ?? 2),
|
||||
@@ -601,6 +743,14 @@ export const register: Register = (on, options) => {
|
||||
on('agent.spawn', async ($, e, next) => {
|
||||
if (e.fork || e.isTeammate || e.workflow) return next(e)
|
||||
|
||||
// A resume continues a known agent: same task, same routing, same counts.
|
||||
// Its message is a later instruction the verifier must see (#4, #6).
|
||||
if (e.resume) {
|
||||
const resumed = await next(e)
|
||||
if (resumed.deny === undefined) await noteFollowUp($, e.resume.agentId, e.prompt)
|
||||
return resumed
|
||||
}
|
||||
|
||||
let taskId: string
|
||||
let prompt = e.prompt
|
||||
let tier: Tier
|
||||
@@ -622,8 +772,14 @@ export const register: Register = (on, options) => {
|
||||
tier = pending.tier
|
||||
fails = pending.fails
|
||||
critical = pending.critical
|
||||
reason = `new agent after ${fails} failed verdicts`
|
||||
await putIn<Pending>($, S.pending, markId, undefined)
|
||||
reason = `rewrite of ${markId} after ${fails} failed verdicts`
|
||||
} else if (markId) {
|
||||
// Starting it would hand an agent nothing but the marker.
|
||||
return {
|
||||
deny:
|
||||
`model-router: no stored rewrite for ${markId} (already started, or cleared). ` +
|
||||
'Start the agent with the full brief instead, or check /router.',
|
||||
}
|
||||
} else {
|
||||
taskId = await nextId($)
|
||||
const brief = parseBrief(e.prompt)
|
||||
@@ -655,6 +811,11 @@ export const register: Register = (on, options) => {
|
||||
const brief = parseBrief(prompt)
|
||||
const ran = await next({ ...e, prompt, model: tier })
|
||||
if (ran.deny !== undefined || !ran.agentId) return ran
|
||||
// the stored rewrite is used up only once its agent has started
|
||||
if (markId && pending) await putIn<Pending>($, S.pending, markId, undefined)
|
||||
// label against what the engine resolved, not what the router asked for
|
||||
const resolved = asTier(ran.model) ?? tier
|
||||
if (resolved !== tier) reason += ` (asked ${tier}, engine resolved ${resolved})`
|
||||
|
||||
// Learn what the alias resolves to, so router calls are priced on the real model.
|
||||
if (ran.model && ran.model !== tier && ran.model.includes(tier)) await putIn($, S.aliases, tier, ran.model)
|
||||
@@ -668,8 +829,9 @@ export const register: Register = (on, options) => {
|
||||
if (brief.role)
|
||||
await putIn<AgentRec>($, S.agents, ran.agentId, {
|
||||
taskId,
|
||||
tier,
|
||||
routed: tier,
|
||||
tier: resolved,
|
||||
routed: resolved,
|
||||
name: e.name,
|
||||
role: brief.role,
|
||||
clone: brief.clone,
|
||||
baseBranch: brief.baseBranch,
|
||||
@@ -684,7 +846,7 @@ export const register: Register = (on, options) => {
|
||||
agentId: ran.agentId,
|
||||
at: await $.clock.now(),
|
||||
task: e.description,
|
||||
tier,
|
||||
tier: resolved,
|
||||
role: brief.role,
|
||||
reason,
|
||||
outcome: 'spawned',
|
||||
@@ -720,6 +882,16 @@ export const register: Register = (on, options) => {
|
||||
return out
|
||||
})
|
||||
|
||||
// A message to a running agent is a later instruction too (#6).
|
||||
on('tool.call', { tool: 'SendMessage' }, async ($, e, next) => {
|
||||
const out = await next(e)
|
||||
if (out.deny !== undefined || out.isError) return out
|
||||
const to = typeof e.to === 'string' ? e.to : ''
|
||||
const id = to ? await agentAddressed($, to) : undefined
|
||||
if (id && typeof e.message === 'string') await noteFollowUp($, id, e.message)
|
||||
return out
|
||||
})
|
||||
|
||||
on('command.run', { command: 'router' }, async ($, e) => {
|
||||
if (e.args.trim() === 'clear') {
|
||||
await serial(async () => {
|
||||
|
||||
@@ -317,3 +317,62 @@ export const turnEndKind = (status: LoopStatus | undefined): 'handback' | 'inter
|
||||
/** 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
|
||||
|
||||
// ---------- rerunning the files a full run reported (#5) ----------
|
||||
|
||||
export type FileKind = 'TIMEOUT' | 'FAIL'
|
||||
export type FileRun = 'pass' | 'fail' | 'timeout' | 'error' | 'not run'
|
||||
|
||||
/** How the runner marks a file; group 1 the kind, group 2 the file. */
|
||||
export const DEFAULT_ISSUE_PATTERN = '^(TIMEOUT|FAIL)\\s+(\\S+)'
|
||||
|
||||
/** A compiled issue pattern, or the default when the setting is empty or broken. */
|
||||
export const issueRegex = (pattern: string): RegExp => {
|
||||
try {
|
||||
return new RegExp(pattern.trim() || DEFAULT_ISSUE_PATTERN)
|
||||
} catch {
|
||||
return new RegExp(DEFAULT_ISSUE_PATTERN)
|
||||
}
|
||||
}
|
||||
|
||||
/** One output line the runner wrote about a file, or undefined. */
|
||||
export const parseIssueLine = (line: string, re: RegExp): { kind: FileKind; file: string } | undefined => {
|
||||
const m = line.trim().match(re)
|
||||
const kind = m?.[1]?.toUpperCase()
|
||||
const file = m?.[2]
|
||||
if (!file || (kind !== 'TIMEOUT' && kind !== 'FAIL')) return undefined
|
||||
return { kind, file }
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a file name from the runner's output may go into a shell command:
|
||||
* letters, digits, `_ . - /` only, no `..` part, not starting with `-`.
|
||||
*/
|
||||
export const isSafeFile = (file: string) =>
|
||||
/^[A-Za-z0-9_./-]+$/.test(file) && !file.startsWith('-') && !file.split('/').includes('..')
|
||||
|
||||
export const fileCommand = (cmd: string, file: string) => cmd.split('{file}').join(file)
|
||||
|
||||
export type RerunRow = { file: string; full: FileKind; head: FileRun; base: FileRun }
|
||||
|
||||
/** What a rerun row means for the change under review. */
|
||||
export const rerunVerdict = (r: RerunRow): string => {
|
||||
if (r.head === 'pass') return 'passes alone: does not count against the change'
|
||||
if (r.head === 'error' || r.head === 'not run') return 'could not be rerun: judge from the full run'
|
||||
if (r.base === 'fail' || r.base === 'timeout') return `also ${r.base === 'fail' ? 'fails' : 'times out'} on base: not caused by this change`
|
||||
if (r.base === 'pass') return `${r.head === 'fail' ? 'fails' : 'times out'} alone, passes on base: counts against the change`
|
||||
return `${r.head === 'fail' ? 'fails' : 'times out'} alone; base not checked`
|
||||
}
|
||||
|
||||
export const rerunTable = (rows: readonly RerunRow[]): string =>
|
||||
[
|
||||
'| file | full run | alone on head | on base | meaning |',
|
||||
'|---|---|---|---|---|',
|
||||
...rows.map(r => `| ${r.file} | ${r.full} | ${r.head} | ${r.base} | ${rerunVerdict(r)} |`),
|
||||
].join('\n')
|
||||
|
||||
/** A positive whole number from a setting, else the fallback. */
|
||||
export const positiveInt = (raw: unknown, fallback: number): number => {
|
||||
const n = Number(raw)
|
||||
return Number.isFinite(n) && n >= 1 ? Math.round(n) : fallback
|
||||
}
|
||||
|
||||
+378
-2
@@ -12,6 +12,11 @@ import {
|
||||
validTimeout,
|
||||
verifierFor,
|
||||
handBackLine,
|
||||
isSafeFile,
|
||||
issueRegex,
|
||||
parseIssueLine,
|
||||
rerunVerdict,
|
||||
fileCommand,
|
||||
ranTier,
|
||||
turnEndKind,
|
||||
} from '../hooks/router'
|
||||
@@ -219,6 +224,27 @@ type World = {
|
||||
handBacks: string[]
|
||||
/** Every message in the order it was sent. */
|
||||
all: string[]
|
||||
/** Resumes that reached the spawn hook. */
|
||||
resumed: { agentId: string; prompt: string; model?: string }[]
|
||||
/** How many coming new spawns the engine refuses. */
|
||||
denySpawns: number
|
||||
/** The model the engine resolves for new spawns, whatever was asked. */
|
||||
engineModel?: string
|
||||
verifierPrompts: string[]
|
||||
verifierSystems: string[]
|
||||
/** SendMessage calls fail (nothing delivered). */
|
||||
sendFails?: boolean
|
||||
/** Pieces the full test run prints to stdout. */
|
||||
fullRunOutput: string[]
|
||||
/** How a file run alone ends, keyed `head:<file>` or `base:<file>`; absent: pass. */
|
||||
fileOutcomes: Record<string, 'pass' | 'fail' | 'timeout'>
|
||||
/** Files run alone, as `head:<file>` or `base:<file>`. */
|
||||
fileRuns: string[]
|
||||
/** git worktree commands run. */
|
||||
worktree: string[]
|
||||
worktreeFails?: boolean
|
||||
running: number
|
||||
maxParallel: number
|
||||
/** Each agent's loop status as $.agent.list() reports it; absent means completed. */
|
||||
status: Record<string, string>
|
||||
diffs: string[]
|
||||
@@ -249,6 +275,8 @@ function world(on: On, w: World) {
|
||||
on('model.complete', async (_$, e) => {
|
||||
if (e.system?.startsWith('You route')) return { value: { isAnswered: true as const, text: 'sonnet', usage: USAGE } }
|
||||
w.verifier.push(e.model)
|
||||
w.verifierPrompts.push(e.prompt)
|
||||
w.verifierSystems.push(e.system ?? '')
|
||||
return { value: { isAnswered: true as const, text: w.verdicts.shift() ?? '{"verdict":"PASS"}', usage: USAGE } }
|
||||
})
|
||||
on('process.run', async (_$, e) => {
|
||||
@@ -261,15 +289,35 @@ function world(on: On, w: World) {
|
||||
w.diffBases.push(e.argv[2] ?? '')
|
||||
return ok(w.diffs.shift() ?? '')
|
||||
}
|
||||
if (a.includes(' worktree ')) {
|
||||
w.worktree.push(a)
|
||||
if (a.includes(' worktree add ') && w.worktreeFails) return ok('', 128)
|
||||
}
|
||||
return ok('')
|
||||
})
|
||||
on('process.spawn', async function* (_$, e) {
|
||||
const cmd = e.argv[e.argv.length - 1] ?? ''
|
||||
if (cmd.startsWith('runone ')) {
|
||||
// one file alone: `runone <file>`, in the clone or in the base worktree
|
||||
const file = cmd.slice('runone '.length)
|
||||
const where = String(e.cwd ?? '').endsWith('-verifier-base') ? 'base' : 'head'
|
||||
w.fileRuns.push(`${where}:${file}`)
|
||||
w.running++
|
||||
w.maxParallel = Math.max(w.maxParallel, w.running)
|
||||
for (let i = 0; i < 5; i++) await Promise.resolve() // let other reruns start
|
||||
w.running--
|
||||
const outcome = w.fileOutcomes[`${where}:${file}`] ?? 'pass'
|
||||
if (outcome === 'timeout') yield { stream: 'stderr' as const, text: "timeout: sending signal TERM to command 'sh'\n" }
|
||||
return { value: { code: outcome === 'pass' ? 0 : outcome === 'timeout' ? 124 : 1, signal: null } }
|
||||
}
|
||||
w.testCwd.push(String(e.cwd ?? ''))
|
||||
w.testArgv.push([...e.argv])
|
||||
const end = w.testEnds.shift() ?? 0
|
||||
const fired = w.testFired.shift() ?? false
|
||||
if (end === 'throw') throw new Error('docker: not found')
|
||||
yield { stream: 'stdout' as const, text: end === 0 ? '67 passed\n' : 'test_modes_p4 ... still running\n' }
|
||||
// the full run's report comes last, so a last line without a newline stays last
|
||||
for (const piece of w.fullRunOutput) yield { stream: 'stdout' as const, text: piece }
|
||||
if (fired) yield { stream: 'stderr' as const, text: "timeout: sending signal TERM to command 'sh'\n" }
|
||||
if (w.testSplitLine) {
|
||||
yield { stream: 'stderr' as const, text: 'timeout: sending sig' }
|
||||
@@ -279,9 +327,20 @@ function world(on: On, w: World) {
|
||||
return { value: { code: end, signal: null } }
|
||||
})
|
||||
on('agent.spawn', async (_$, e) => {
|
||||
if (e.resume) {
|
||||
w.resumed.push({ agentId: e.resume.agentId, prompt: e.prompt, model: e.model })
|
||||
return { model: 'claude-opus-5-5', agentId: e.resume.agentId }
|
||||
}
|
||||
if (w.denySpawns > 0) {
|
||||
w.denySpawns--
|
||||
return { deny: 'spawn failed' }
|
||||
}
|
||||
w.spawned.push({ model: e.model, prompt: e.prompt })
|
||||
return { model: e.model ?? 'inherit', agentId: `agent-${w.spawned.length}` }
|
||||
return { model: w.engineModel ?? e.model ?? 'inherit', agentId: `agent-${w.spawned.length}` }
|
||||
})
|
||||
on('tool.call', { tool: 'SendMessage' }, async () =>
|
||||
(w.sendFails ? { result: 'No agent by that name is running', isError: true } : { result: { success: true } }) as never,
|
||||
)
|
||||
on('turn.complete', async (_$, e) => ({ text: e.answer }))
|
||||
on('agent.list', async () => ({
|
||||
value: w.spawned
|
||||
@@ -298,7 +357,7 @@ function world(on: On, w: World) {
|
||||
return clock
|
||||
}
|
||||
|
||||
const fresh = (): World => ({ spawned: [], verifier: [], verdicts: [], told: [], handBacks: [], all: [], status: {}, diffs: [], diffBases: [], testCwd: [], testArgv: [], testEnds: [], testFired: [], snap: 0 })
|
||||
const fresh = (): World => ({ spawned: [], verifier: [], verdicts: [], told: [], handBacks: [], all: [], resumed: [], denySpawns: 0, verifierPrompts: [], verifierSystems: [], fullRunOutput: [], fileOutcomes: {}, fileRuns: [], worktree: [], running: 0, maxParallel: 0, status: {}, diffs: [], diffBases: [], testCwd: [], testArgv: [], testEnds: [], testFired: [], snap: 0 })
|
||||
|
||||
async function finish($: Engine, clock: { advance: (ms: number) => Promise<void> }, agentId: string, ranModel?: string, reason = 'answer') {
|
||||
const usage = ranModel
|
||||
@@ -763,3 +822,320 @@ test('follow-up: each agent is judged by its own status, not by that of another
|
||||
expect(w.all).toEqual([])
|
||||
expect(w.verifier).toEqual([])
|
||||
})
|
||||
|
||||
// ---------- resumes, follow-ups and rewrites (#4, #6) ----------
|
||||
|
||||
const sendMessage = ($: Engine, to: string, message: string) =>
|
||||
$.tool.call({ tool: 'SendMessage', to, message } as never)
|
||||
|
||||
const resume = ($: Engine, agentId: string, prompt: string) =>
|
||||
$.agent.spawn({ prompt, description: 'resume', resume: { agentId }, model: 'sonnet' } as never)
|
||||
|
||||
test('#4: a resume keeps its task, routing and counts: no new Tn, no new routing', async ($, on) => {
|
||||
const w = fresh()
|
||||
w.diffs = ['d1', 'd2']
|
||||
w.verdicts = ['{"verdict":"FAIL","issues":["x"]}', '{"verdict":"FAIL","issues":["y"]}']
|
||||
const clock = world(on, w)
|
||||
const r = await $.agent.spawn({ prompt: devBrief(), description: 'clamp' } as never)
|
||||
const id = r.agentId as string
|
||||
await finish($, clock, id, 'claude-sonnet-5-5')
|
||||
expect(w.told[0]).toContain(`Resume agent ${id}`)
|
||||
await resume($, id, 'Fix the issues: x')
|
||||
expect(w.resumed[0]?.model).toBe('sonnet') // passed through untouched
|
||||
expect(w.spawned.length).toBe(1)
|
||||
await finish($, clock, id, 'claude-sonnet-5-5')
|
||||
expect(w.handBacks[1]).toBe('[model-router] T1 verifying on Opus...')
|
||||
expect(w.diffBases[1]).toBe('snap1') // round 2 diffs from the last verified round
|
||||
expect(w.told[1]).toContain('round 2')
|
||||
expect(w.told[1]).toContain('[router-rewrite T1]') // second fail counted: escalates
|
||||
})
|
||||
|
||||
test('#4: a resumed Opus dev is labelled as Opus, with no "routed to" note', async ($, on) => {
|
||||
const w = fresh()
|
||||
const clock = world(on, w)
|
||||
const r = await $.agent.spawn({ prompt: `SAFETY-135: decide how the guard should recover. Clone: ${DEV}/`, description: 'dev' } as never)
|
||||
const id = r.agentId as string
|
||||
await finish($, clock, id, 'claude-opus-5-5')
|
||||
await resume($, id, 'Docs-only round: update the README.')
|
||||
await finish($, clock, id, 'claude-opus-5-5')
|
||||
expect(w.handBacks).toEqual([
|
||||
'[model-router] T1 no verification: dev ran on Opus. Go straight to review.',
|
||||
'[model-router] T1 no verification: dev ran on Opus. Go straight to review.',
|
||||
])
|
||||
})
|
||||
|
||||
test('#4: the label compares with what the engine resolved at start, not what the router asked', async ($, on) => {
|
||||
const w = fresh()
|
||||
w.engineModel = 'claude-opus-5-5' // e.g. the agent type sets its own model
|
||||
const clock = world(on, w)
|
||||
const r = await $.agent.spawn({ prompt: devBrief(), description: 'clamp' } as never)
|
||||
expect(w.spawned[0]?.model).toBe('sonnet')
|
||||
await finish($, clock, r.agentId as string, 'claude-opus-5-5')
|
||||
expect(w.handBacks).toEqual(['[model-router] T1 no verification: dev ran on Opus. Go straight to review.'])
|
||||
const log = (await $.command.run({ command: 'router', args: '' } as never)).text ?? ''
|
||||
expect(log).toContain('opus')
|
||||
})
|
||||
|
||||
test('#4: a router rewrite keeps the task number and its model', async ($, on) => {
|
||||
const w = fresh()
|
||||
w.diffs = ['d1', 'd2']
|
||||
w.verdicts = ['{"verdict":"FAIL","issues":["x"]}', '{"verdict":"FAIL","issues":["y"]}']
|
||||
const clock = world(on, w)
|
||||
const r = await $.agent.spawn({ prompt: devBrief(), description: 'clamp' } as never)
|
||||
await finish($, clock, r.agentId as string, 'claude-sonnet-5-5')
|
||||
await finish($, clock, r.agentId as string, 'claude-sonnet-5-5')
|
||||
const rw = await $.agent.spawn({ prompt: '[router-rewrite T1]', description: 'rewrite', model: 'opus' } as never)
|
||||
expect(w.spawned[1]?.model).toBe('opus')
|
||||
await finish($, clock, rw.agentId as string, 'claude-opus-5-5')
|
||||
expect(w.handBacks[2]).toBe('[model-router] T1 no verification: dev ran on Opus. Go straight to review.')
|
||||
})
|
||||
|
||||
test('#4: a rewrite whose first start fails can be started again', async ($, on) => {
|
||||
const w = fresh()
|
||||
w.diffs = ['d1', 'd2']
|
||||
w.verdicts = ['{"verdict":"FAIL","issues":["x"]}', '{"verdict":"FAIL","issues":["y"]}']
|
||||
const clock = world(on, w)
|
||||
const r = await $.agent.spawn({ prompt: devBrief(), description: 'clamp' } as never)
|
||||
await finish($, clock, r.agentId as string, 'claude-sonnet-5-5')
|
||||
await finish($, clock, r.agentId as string, 'claude-sonnet-5-5')
|
||||
w.denySpawns = 1
|
||||
const first = await $.agent.spawn({ prompt: '[router-rewrite T1]', description: 'rewrite' } as never)
|
||||
expect(first.deny).toBe('spawn failed')
|
||||
const second = await $.agent.spawn({ prompt: '[router-rewrite T1]', description: 'rewrite' } as never)
|
||||
expect(second.deny).toBe(undefined)
|
||||
expect(w.spawned[1]?.model).toBe('opus')
|
||||
expect(w.spawned[1]?.prompt).toContain('Previous attempts rejected')
|
||||
})
|
||||
|
||||
test('#4: a rewrite marker with nothing stored is refused, not started without a brief', async ($, on) => {
|
||||
const w = fresh()
|
||||
world(on, w)
|
||||
const r = await $.agent.spawn({ prompt: '[router-rewrite T325]', description: 'rewrite', model: 'opus' } as never)
|
||||
expect(r.deny).toContain('no stored rewrite for T325')
|
||||
expect(w.spawned).toEqual([])
|
||||
})
|
||||
|
||||
test('#6: a resume message reaches the verifier as a later instruction, in scope', async ($, on) => {
|
||||
const w = fresh()
|
||||
w.diffs = ['d1', 'd2']
|
||||
w.verdicts = ['{"verdict":"FAIL","issues":["x"]}']
|
||||
const clock = world(on, w)
|
||||
const r = await $.agent.spawn({ prompt: devBrief(), description: 'MAINT-24' } as never)
|
||||
const id = r.agentId as string
|
||||
await finish($, clock, id, 'claude-sonnet-5-5')
|
||||
await resume($, id, 'Owner: add MAINT-25 to this PR as well.')
|
||||
await finish($, clock, id, 'claude-sonnet-5-5')
|
||||
const p = w.verifierPrompts[1] ?? ''
|
||||
expect(p).toContain('## Later instructions to this agent')
|
||||
expect(p).toContain('1. Owner: add MAINT-25 to this PR as well.')
|
||||
expect(p).toContain('SAFETY-95: clamp the integrator') // the original brief stays
|
||||
})
|
||||
|
||||
test('#6: SendMessage to a running agent, by id or by name, is a later instruction too', async ($, on) => {
|
||||
const w = fresh()
|
||||
w.diffs = ['d1']
|
||||
const clock = world(on, w)
|
||||
const r = await $.agent.spawn({ prompt: devBrief(), description: 'MAINT-28', name: 'maint28-dev' } as never)
|
||||
const id = r.agentId as string
|
||||
await sendMessage($, id, 'Owner decided: cap is 1.')
|
||||
await sendMessage($, 'maint28-dev', 'Also cover the empty list.')
|
||||
await sendMessage($, 'maint28-dev', 'Also cover the empty list.') // the same text counts once
|
||||
await sendMessage($, 'someone-else', 'Not for this agent.')
|
||||
await finish($, clock, id, 'claude-sonnet-5-5')
|
||||
const p = w.verifierPrompts[0] ?? ''
|
||||
expect(p).toContain('1. Owner decided: cap is 1.')
|
||||
expect(p).toContain('2. Also cover the empty list.')
|
||||
expect(p).not.toContain('3.')
|
||||
expect(p).not.toContain('Not for this agent.')
|
||||
})
|
||||
|
||||
test('#6: without later instructions the section is left out', async ($, on) => {
|
||||
const w = fresh()
|
||||
w.diffs = ['d1']
|
||||
const clock = world(on, w)
|
||||
const r = await $.agent.spawn({ prompt: devBrief(), description: 'clamp' } as never)
|
||||
await finish($, clock, r.agentId as string, 'claude-sonnet-5-5')
|
||||
expect(w.verifierPrompts[0] ?? '').not.toContain('Later instructions')
|
||||
})
|
||||
|
||||
test('#4: a rewrite that started is used up: the same marker again is refused', async ($, on) => {
|
||||
const w = fresh()
|
||||
w.diffs = ['d1', 'd2']
|
||||
w.verdicts = ['{"verdict":"FAIL","issues":["x"]}', '{"verdict":"FAIL","issues":["y"]}']
|
||||
const clock = world(on, w)
|
||||
const r = await $.agent.spawn({ prompt: devBrief(), description: 'clamp' } as never)
|
||||
await finish($, clock, r.agentId as string, 'claude-sonnet-5-5')
|
||||
await finish($, clock, r.agentId as string, 'claude-sonnet-5-5')
|
||||
await $.agent.spawn({ prompt: '[router-rewrite T1]', description: 'rewrite' } as never)
|
||||
const again = await $.agent.spawn({ prompt: '[router-rewrite T1]', description: 'rewrite' } as never)
|
||||
expect(again.deny).toContain('no stored rewrite for T1')
|
||||
expect(w.spawned.length).toBe(2)
|
||||
})
|
||||
|
||||
test('#6: a SendMessage that was not delivered is not a later instruction', async ($, on) => {
|
||||
const w = fresh()
|
||||
w.diffs = ['d1']
|
||||
w.sendFails = true
|
||||
const clock = world(on, w)
|
||||
const r = await $.agent.spawn({ prompt: devBrief(), description: 'clamp' } as never)
|
||||
await sendMessage($, r.agentId as string, 'Never arrived.')
|
||||
await finish($, clock, r.agentId as string, 'claude-sonnet-5-5')
|
||||
expect(w.verifierPrompts[0] ?? '').not.toContain('Never arrived.')
|
||||
})
|
||||
|
||||
// ---------- reruns of reported files (#5) ----------
|
||||
|
||||
const RERUN = { testCommand: 'make t', testFileCommand: 'runone {file}' }
|
||||
const T307_OUTPUT = [
|
||||
'PASS test_a.py 12s\nTIMEOUT test_tariff24_weather.py 230s\nFAIL test_loop.py\nTIME',
|
||||
'OUT test_slow.py 1500s\n', // a line split across pieces
|
||||
'--- test_tariff24_weather.py (TIMEOUT)\n<tail>\n77 pass, 1 fail, 2 timeout (limit 1500 s)\n',
|
||||
]
|
||||
|
||||
test('#5: reported lines are read, also when split across pieces; one entry per file', async () => {
|
||||
const re = issueRegex('')
|
||||
expect(parseIssueLine('TIMEOUT test_tariff24_weather.py 230s', re)).toEqual({ kind: 'TIMEOUT', file: 'test_tariff24_weather.py' })
|
||||
expect(parseIssueLine('FAIL test_loop.py', re)).toEqual({ kind: 'FAIL', file: 'test_loop.py' })
|
||||
expect(parseIssueLine('--- test_tariff24_weather.py (TIMEOUT)', re)).toBe(undefined)
|
||||
expect(parseIssueLine('77 pass, 0 fail, 30 timeout (limit 1500 s)', re)).toBe(undefined)
|
||||
expect(parseIssueLine('PASS test_a.py', re)).toBe(undefined)
|
||||
// a custom pattern, and a broken one falls back to the default
|
||||
expect(parseIssueLine('[timeout] x.py', issueRegex('^\\[(timeout|fail)\\]\\s+(\\S+)'))?.file).toBe('x.py')
|
||||
expect(parseIssueLine('TIMEOUT y.py', issueRegex('(unclosed'))?.file).toBe('y.py')
|
||||
})
|
||||
|
||||
test('#5: only safe file names reach the shell', async () => {
|
||||
for (const ok of ['test_a.py', 'tests/test_b.py', 'a-b.c_d.py']) expect(isSafeFile(ok)).toBe(true)
|
||||
for (const bad of ['a;rm -rf ~', '$(id).py', '../x.py', 'a/../b.py', '-rf', 'a b.py', 'x`y`.py', "a'.py"]) expect(isSafeFile(bad)).toBe(false)
|
||||
expect(fileCommand('docker run img python3 {file} && echo {file}', 'test_a.py')).toBe('docker run img python3 test_a.py && echo test_a.py')
|
||||
})
|
||||
|
||||
test('#5: what each rerun outcome means', async () => {
|
||||
expect(rerunVerdict({ file: 'f', full: 'TIMEOUT', head: 'pass', base: 'not run' })).toContain('does not count')
|
||||
expect(rerunVerdict({ file: 'f', full: 'FAIL', head: 'fail', base: 'fail' })).toContain('not caused by this change')
|
||||
expect(rerunVerdict({ file: 'f', full: 'TIMEOUT', head: 'timeout', base: 'timeout' })).toContain('also times out on base')
|
||||
expect(rerunVerdict({ file: 'f', full: 'FAIL', head: 'fail', base: 'pass' })).toContain('counts against the change')
|
||||
expect(rerunVerdict({ file: 'f', full: 'FAIL', head: 'fail', base: 'not run' })).toContain('base not checked')
|
||||
expect(rerunVerdict({ file: 'f', full: 'FAIL', head: 'error', base: 'not run' })).toContain('could not be rerun')
|
||||
})
|
||||
|
||||
test('#5 acceptance: timed-out and failed files are rerun alone, failures again on base, and the verifier gets the table', { options: RERUN }, async ($, on) => {
|
||||
const w = fresh()
|
||||
w.diffs = ['diff']
|
||||
w.testEnds = [1]
|
||||
w.fullRunOutput = T307_OUTPUT
|
||||
w.fileOutcomes = { 'head:test_loop.py': 'fail', 'base:test_loop.py': 'fail', 'head:test_slow.py': 'timeout', 'base:test_slow.py': 'pass' }
|
||||
const clock = world(on, w)
|
||||
const r = await $.agent.spawn({ prompt: devBrief(), description: 'MAINT-28' } as never)
|
||||
await finish($, clock, r.agentId as string, 'claude-sonnet-5-5')
|
||||
expect([...w.fileRuns].sort()).toEqual([
|
||||
'base:test_loop.py',
|
||||
'base:test_slow.py',
|
||||
'head:test_loop.py',
|
||||
'head:test_slow.py',
|
||||
'head:test_tariff24_weather.py',
|
||||
])
|
||||
const p = w.verifierPrompts[0] ?? ''
|
||||
expect(p).toContain('### Files the full run reported, rerun one by one')
|
||||
expect(p).toContain('| test_tariff24_weather.py | TIMEOUT | pass | not run | passes alone: does not count against the change |')
|
||||
expect(p).toContain('| test_loop.py | FAIL | fail | fail | also fails on base: not caused by this change |')
|
||||
expect(p).toContain('| test_slow.py | TIMEOUT | timeout | pass | times out alone, passes on base: counts against the change |')
|
||||
// the base worktree sits next to the clone, and is removed and pruned afterwards
|
||||
expect(w.worktree).toContain(`git -C ${DEV} worktree add --detach ${DEV}-verifier-base mergebase`)
|
||||
expect(w.worktree.at(-2)).toBe(`git -C ${DEV} worktree remove --force ${DEV}-verifier-base`)
|
||||
expect(w.worktree.at(-1)).toBe(`git -C ${DEV} worktree prune`)
|
||||
})
|
||||
|
||||
test('#5: when every reported file passes alone, no base worktree is made', { options: RERUN }, async ($, on) => {
|
||||
const w = fresh()
|
||||
w.diffs = ['diff']
|
||||
w.testEnds = [1]
|
||||
w.fullRunOutput = ['TIMEOUT test_tariff24_weather.py 230s\n']
|
||||
const clock = world(on, w)
|
||||
const r = await $.agent.spawn({ prompt: devBrief(), description: 'dev' } as never)
|
||||
await finish($, clock, r.agentId as string, 'claude-sonnet-5-5')
|
||||
expect(w.fileRuns).toEqual(['head:test_tariff24_weather.py'])
|
||||
expect(w.worktree.filter(c => c.includes(' add '))).toEqual([])
|
||||
})
|
||||
|
||||
test('#5: a base worktree that cannot be made leaves base as not run', { options: RERUN }, async ($, on) => {
|
||||
const w = fresh()
|
||||
w.diffs = ['diff']
|
||||
w.testEnds = [1]
|
||||
w.worktreeFails = true
|
||||
w.fullRunOutput = ['FAIL test_loop.py\n']
|
||||
w.fileOutcomes = { 'head:test_loop.py': 'fail' }
|
||||
const clock = world(on, w)
|
||||
const r = await $.agent.spawn({ prompt: devBrief(), description: 'dev' } as never)
|
||||
await finish($, clock, r.agentId as string, 'claude-sonnet-5-5')
|
||||
expect(w.fileRuns).toEqual(['head:test_loop.py'])
|
||||
expect(w.verifierPrompts[0]).toContain('| test_loop.py | FAIL | fail | not run | fails alone; base not checked |')
|
||||
})
|
||||
|
||||
test('#5: unsafe names and files past testRerunMax are not rerun, and said so', { options: { ...RERUN, testRerunMax: 1 } }, async ($, on) => {
|
||||
const w = fresh()
|
||||
w.diffs = ['diff']
|
||||
w.testEnds = [1]
|
||||
w.fullRunOutput = ['FAIL a;rm.py\nTIMEOUT test_a.py 1s\nTIMEOUT test_b.py 1s\n']
|
||||
const clock = world(on, w)
|
||||
const r = await $.agent.spawn({ prompt: devBrief(), description: 'dev' } as never)
|
||||
await finish($, clock, r.agentId as string, 'claude-sonnet-5-5')
|
||||
expect(w.fileRuns).toEqual(['head:test_a.py'])
|
||||
expect(w.verifierPrompts[0]).toContain('(2 more reported file(s) not rerun')
|
||||
})
|
||||
|
||||
test('#5: without testFileCommand nothing is rerun', { options: { testCommand: 'make t' } }, async ($, on) => {
|
||||
const w = fresh()
|
||||
w.diffs = ['diff']
|
||||
w.testEnds = [1]
|
||||
w.fullRunOutput = T307_OUTPUT
|
||||
const clock = world(on, w)
|
||||
const r = await $.agent.spawn({ prompt: devBrief(), description: 'dev' } as never)
|
||||
await finish($, clock, r.agentId as string, 'claude-sonnet-5-5')
|
||||
expect(w.fileRuns).toEqual([])
|
||||
expect(w.verifierPrompts[0] ?? '').not.toContain('rerun one by one')
|
||||
})
|
||||
|
||||
test('#5: reruns run at most testRerunJobs at a time', { options: { ...RERUN, testRerunJobs: 2 } }, async ($, on) => {
|
||||
const w = fresh()
|
||||
w.diffs = ['diff']
|
||||
w.testEnds = [1]
|
||||
w.fullRunOutput = ['TIMEOUT t1.py 1s\nTIMEOUT t2.py 1s\nTIMEOUT t3.py 1s\nTIMEOUT t4.py 1s\nTIMEOUT t5.py 1s\n']
|
||||
const clock = world(on, w)
|
||||
const r = await $.agent.spawn({ prompt: devBrief(), description: 'dev' } as never)
|
||||
await finish($, clock, r.agentId as string, 'claude-sonnet-5-5')
|
||||
expect(w.fileRuns.length).toBe(5)
|
||||
expect(w.maxParallel).toBe(2)
|
||||
})
|
||||
|
||||
test('#5: a custom pattern that also matches other lines still keeps only TIMEOUT and FAIL', async () => {
|
||||
const re = issueRegex('^(\\w+)\\s+(\\S+)')
|
||||
expect(parseIssueLine('PASS test_a.py', re)).toBe(undefined)
|
||||
expect(parseIssueLine('timeout test_b.py', re)).toEqual({ kind: 'TIMEOUT', file: 'test_b.py' })
|
||||
})
|
||||
|
||||
test('#5: a last line without a newline is read; a file reported twice is rerun once', { options: RERUN }, async ($, on) => {
|
||||
const w = fresh()
|
||||
w.diffs = ['diff']
|
||||
w.testEnds = [1]
|
||||
w.fullRunOutput = ['FAIL test_twice.py\nFAIL test_twice.py\n', 'TIMEOUT test_last.py 1500s']
|
||||
const clock = world(on, w)
|
||||
const r = await $.agent.spawn({ prompt: devBrief(), description: 'dev' } as never)
|
||||
await finish($, clock, r.agentId as string, 'claude-sonnet-5-5')
|
||||
expect([...w.fileRuns].sort()).toEqual(['head:test_last.py', 'head:test_twice.py'])
|
||||
})
|
||||
|
||||
test('#5: the verifier is told how to read the rerun table', { options: RERUN }, async ($, on) => {
|
||||
const w = fresh()
|
||||
w.diffs = ['diff']
|
||||
w.testEnds = [1]
|
||||
w.fullRunOutput = ['TIMEOUT test_a.py 1s\n']
|
||||
const clock = world(on, w)
|
||||
const r = await $.agent.spawn({ prompt: devBrief(), description: 'dev' } as never)
|
||||
await finish($, clock, r.agentId as string, 'claude-sonnet-5-5')
|
||||
const sys = w.verifierSystems[0] ?? ''
|
||||
expect(sys).toContain('When a table of files rerun one by one is given')
|
||||
expect(sys).toContain('a file that passes alone does not count against the change')
|
||||
expect(sys).toContain('not caused by this change')
|
||||
expect(sys).toContain('Name every file you count against the change')
|
||||
})
|
||||
|
||||
Reference in New Issue
Block a user