Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
034ecf1df4 | ||
|
|
fade3b8bba | ||
|
|
2184024fe7 | ||
|
|
df6e0d1694 | ||
|
|
908cd7866d | ||
|
|
c88884c54a | ||
|
|
3cd69762be | ||
|
|
86bb9d79cc | ||
|
|
d5c762b339 | ||
|
|
fd75c183ba |
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "model-router",
|
"name": "model-router",
|
||||||
"version": "0.4.7",
|
"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.",
|
"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": {
|
"author": {
|
||||||
"name": "Glenn Schrooyen"
|
"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.",
|
"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
|
"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": {
|
"defaultBaseBranch": {
|
||||||
"type": "string",
|
"type": "string",
|
||||||
"title": "Base branch when the brief names none",
|
"title": "Base branch when the brief names none",
|
||||||
|
|||||||
@@ -6,22 +6,25 @@ A Claude Code plugin that picks a model for every subagent, checks dev work on a
|
|||||||
|
|
||||||
| Step | Behaviour |
|
| 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). |
|
| 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. |
|
||||||
| 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. |
|
| 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. |
|
||||||
| 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)`. |
|
| 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. |
|
||||||
| 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. |
|
| 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. |
|
| Savings | `/router savings` prices every run on the model it ran on and compares it with the same tokens on Opus 5.5. |
|
||||||
|
|
||||||
## Briefs
|
## Briefs
|
||||||
|
|
||||||
Every dev, review and test brief carries one line:
|
Every pipeline brief carries these lines:
|
||||||
|
|
||||||
```
|
```
|
||||||
|
Pipeline-Role: dev
|
||||||
Clone: /home/homelab/projects/goodwe/clones/<TICKET>-dev/
|
Clone: /home/homelab/projects/goodwe/clones/<TICKET>-dev/
|
||||||
```
|
```
|
||||||
|
|
||||||
Add `(Role: dev|review|test)` when the path does not end in the role. Tickets with extra parts (`OPT-11-P4`) are fine. Name the base branch (`Base branch: release/1.0`).
|
The role comes from `Pipeline-Role:` first, then `(Role: ...)` on the `Clone:` line, then the folder name (which must end in `-dev`, `-review` or `-test`). Any other role (`test-design`, ...) is never a dev, whatever other clones the brief mentions; neither is a `test-designer` or `release-reviewer` agent. With a `## Test plan` section, the verifier checks that every T-id and N-id is covered. Tickets with extra parts (`OPT-11-P4`) are fine. Name the base branch (`Base branch: release/1.0`).
|
||||||
|
|
||||||
## Install
|
## Install
|
||||||
|
|
||||||
@@ -38,6 +41,11 @@ Or for development: `claude --plugin-dir /path/to/model-router`.
|
|||||||
|---|---|---|
|
|---|---|---|
|
||||||
| `testCommand` | empty | Run in the agent's clone; output goes to the verifier |
|
| `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 |
|
| `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 |
|
| `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 |
|
| `prBaseCommand` | empty | Optional command that prints the PR's base branch |
|
||||||
| `maxRewrites` | 2 | Failed verdicts before handing back |
|
| `maxRewrites` | 2 | Failed verdicts before handing back |
|
||||||
@@ -59,7 +67,7 @@ claude plugin validate .
|
|||||||
claude plugin test .
|
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).
|
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
|
## Known limits
|
||||||
|
|
||||||
|
|||||||
+2
-1
@@ -150,7 +150,8 @@ export const usd = (n: number) => (Math.abs(n) < 0.01 && n !== 0 ? `$${n.toFixed
|
|||||||
export const savingsReport = (costs: Readonly<Record<string, TaskCost>>, limit: number, only?: string): string => {
|
export const savingsReport = (costs: Readonly<Record<string, TaskCost>>, limit: number, only?: string): string => {
|
||||||
const ids = Object.keys(costs)
|
const ids = Object.keys(costs)
|
||||||
.filter(id => !only || id === only)
|
.filter(id => !only || id === only)
|
||||||
.sort((a, b) => Number(b.slice(1)) - Number(a.slice(1)))
|
// dev tasks (T) first, then other agents (A); newest first within each
|
||||||
|
.sort((a, b) => b.charAt(0).localeCompare(a.charAt(0)) || Number(b.slice(1)) - Number(a.slice(1)))
|
||||||
if (ids.length === 0) return only ? `model-router: no costs recorded for ${only}.` : 'savings: no agent runs recorded yet.'
|
if (ids.length === 0) return only ? `model-router: no costs recorded for ${only}.` : 'savings: no agent runs recorded yet.'
|
||||||
|
|
||||||
const row = (id: string, t: TaskCost) => {
|
const row = (id: string, t: TaskCost) => {
|
||||||
|
|||||||
+294
-42
@@ -12,11 +12,12 @@ import {
|
|||||||
} from './pricing'
|
} from './pricing'
|
||||||
import {
|
import {
|
||||||
REWRITE_MARK,
|
REWRITE_MARK,
|
||||||
|
rewritePrompt,
|
||||||
asTier,
|
asTier,
|
||||||
clip,
|
clip,
|
||||||
decide,
|
decide,
|
||||||
onFail,
|
onFail,
|
||||||
parseBrief,
|
briefFor,
|
||||||
parsePatterns,
|
parsePatterns,
|
||||||
parseVerdict,
|
parseVerdict,
|
||||||
handBackLine,
|
handBackLine,
|
||||||
@@ -24,9 +25,19 @@ import {
|
|||||||
turnEndKind,
|
turnEndKind,
|
||||||
WATCH_EVERY_MS,
|
WATCH_EVERY_MS,
|
||||||
WATCH_FOR_MS,
|
WATCH_FOR_MS,
|
||||||
|
IDLE_HANDBACK_MS,
|
||||||
safetyHit,
|
safetyHit,
|
||||||
skipReason,
|
skipReason,
|
||||||
validTimeout,
|
validTimeout,
|
||||||
|
fileCommand,
|
||||||
|
isSafeFile,
|
||||||
|
issueRegex,
|
||||||
|
parseIssueLine,
|
||||||
|
positiveInt,
|
||||||
|
rerunTable,
|
||||||
|
type FileKind,
|
||||||
|
type FileRun,
|
||||||
|
type RerunRow,
|
||||||
verifierFor,
|
verifierFor,
|
||||||
type Role,
|
type Role,
|
||||||
type Tier,
|
type Tier,
|
||||||
@@ -39,9 +50,15 @@ type AgentRec = {
|
|||||||
taskId: string
|
taskId: string
|
||||||
/** The model the last round actually ran on (the routing choice until a round reports one). */
|
/** The model the last round actually ran on (the routing choice until a round reports one). */
|
||||||
tier: Tier
|
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
|
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
|
role?: Role
|
||||||
|
/** The role as the brief wrote it, for non-dev roles (test-design). */
|
||||||
|
roleName?: string
|
||||||
clone?: string
|
clone?: string
|
||||||
baseBranch?: string
|
baseBranch?: string
|
||||||
critical: boolean
|
critical: boolean
|
||||||
@@ -70,6 +87,7 @@ type Outcome =
|
|||||||
| 'verdict-unreadable'
|
| 'verdict-unreadable'
|
||||||
| 'test-agent'
|
| 'test-agent'
|
||||||
| 'review-agent'
|
| 'review-agent'
|
||||||
|
| 'non-dev-agent'
|
||||||
| 'no-clone'
|
| 'no-clone'
|
||||||
| 'opus-unverified'
|
| 'opus-unverified'
|
||||||
| 'agent-ended'
|
| 'agent-ended'
|
||||||
@@ -81,6 +99,8 @@ type LogEntry = {
|
|||||||
task: string
|
task: string
|
||||||
tier: Tier
|
tier: Tier
|
||||||
role?: Role
|
role?: Role
|
||||||
|
/** The role as the brief wrote it, for non-dev roles (test-design). */
|
||||||
|
roleName?: string
|
||||||
reason: string
|
reason: string
|
||||||
round?: number
|
round?: number
|
||||||
verifier?: Tier
|
verifier?: Tier
|
||||||
@@ -90,14 +110,20 @@ type LogEntry = {
|
|||||||
|
|
||||||
const S = {
|
const S = {
|
||||||
counter: 'counter',
|
counter: 'counter',
|
||||||
|
// other agents (review, test, test-design, no role) count apart, as A1, A2, ...
|
||||||
|
counterOther: 'counter-other',
|
||||||
pending: 'pending',
|
pending: 'pending',
|
||||||
agents: 'agents',
|
agents: 'agents',
|
||||||
log: 'log',
|
log: 'log',
|
||||||
costs: 'costs',
|
costs: 'costs',
|
||||||
agentTask: 'agentTask',
|
agentTask: 'agentTask',
|
||||||
aliases: 'aliases',
|
aliases: 'aliases',
|
||||||
|
// turn ends still waiting for their hand-back: kept so a plugin reload resumes them (#12)
|
||||||
|
watching: 'watching',
|
||||||
} as const
|
} 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. */
|
/** Model ids assumed for an alias until an agent run shows what it resolves to. */
|
||||||
const ALIAS_DEFAULT: Record<Tier, string> = {
|
const ALIAS_DEFAULT: Record<Tier, string> = {
|
||||||
haiku: 'claude-haiku-4-5',
|
haiku: 'claude-haiku-4-5',
|
||||||
@@ -122,6 +148,9 @@ 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.
|
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.
|
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.
|
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.
|
||||||
|
When the task has a "## Test plan" section with T-ids and N-ids: every T-id must be implemented by a test that can fail, and every N-id asserted somewhere, unless the developer says why not. A missing or untestable T-id/N-id is a FAIL issue naming the id. A test that cannot fail on the old code where the plan says "red on base" is a FAIL issue.
|
||||||
Do not fail a change for style alone. A later PR review and mutation testing follow you; you are the cheap first gate.
|
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:
|
Reply with JSON only:
|
||||||
@@ -129,11 +158,13 @@ Reply with JSON only:
|
|||||||
|
|
||||||
const ORCHESTRATOR_NOTE = `## Model router (model-router mod)
|
const ORCHESTRATOR_NOTE = `## Model router (model-router mod)
|
||||||
The model-router mod picks each subagent's model and verifies dev work before it reaches a PR.
|
The model-router mod picks each subagent's model and verifies dev work before it reaches a PR.
|
||||||
- Every dev, review and test brief carries one line \`Clone: <path>\` (add \`(Role: dev|review|test)\` if the path does not end in the role). The router reads the role from that line only; a brief naming several clones without it runs on Opus, unverified.
|
- Every pipeline brief carries \`Pipeline-Role: <role>\` and one line \`Clone: <path>\` (add \`(Role: <role>)\` if the folder name does not end in -dev, -review or -test). The role comes from Pipeline-Role, then (Role: ...), then the folder name. Only dev briefs are routed and verified; any other role (test-design, ...) keeps the model you name, gets no "[model-router]" line and an A number, not a T number. A brief naming several clones and no Clone: line runs on Opus, unverified.
|
||||||
- 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.
|
- 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).
|
- Review and test agents keep the model you name (Opus when you name none); other non-dev agents (test-design, test-designer, release-reviewer) too, but never Haiku.
|
||||||
- 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.
|
- 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.
|
||||||
|
- With ems-dev-tooling: record every verdict with \`ticket\` first (PASS: \`ticket advance <T> --to review --sha <sha>\`; FAIL: \`ticket fail <T> --stage router\`), then resume or rewrite. pipeline-guard refuses a resume while the ticket is not back in development.`
|
||||||
|
|
||||||
// ---------- store helpers (top-level, as the engine requires for `$`) ----------
|
// ---------- store helpers (top-level, as the engine requires for `$`) ----------
|
||||||
|
|
||||||
@@ -168,11 +199,13 @@ async function putIn<T>($: EngineInterface, key: string, id: string, value: T |
|
|||||||
await updateIn<T>($, key, id, () => value)
|
await updateIn<T>($, key, id, () => value)
|
||||||
}
|
}
|
||||||
|
|
||||||
async function nextId($: EngineInterface) {
|
/** T numbers are for dev agents only; every other agent gets an A number. */
|
||||||
|
async function nextId($: EngineInterface, isDev: boolean) {
|
||||||
|
const key = isDev ? S.counter : S.counterOther
|
||||||
return serial(async () => {
|
return serial(async () => {
|
||||||
const n = Number((await $.store.get(S.counter)) ?? 0) + 1
|
const n = Number((await $.store.get(key)) ?? 0) + 1
|
||||||
await $.store.set(S.counter, n)
|
await $.store.set(key, n)
|
||||||
return `T${n}`
|
return `${isDev ? 'T' : 'A'}${n}`
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -198,6 +231,8 @@ async function untracked($: EngineInterface, cwd: string) {
|
|||||||
return r.ok ? r.out.split('\n').filter(Boolean) : []
|
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). */
|
/** A commit holding the clone's tree as it is now (HEAD when clean). */
|
||||||
async function snapshot($: EngineInterface, cwd: string) {
|
async function snapshot($: EngineInterface, cwd: string) {
|
||||||
const stash = await sh($, ['git', 'stash', 'create'], cwd)
|
const stash = await sh($, ['git', 'stash', 'create'], cwd)
|
||||||
@@ -254,18 +289,37 @@ async function chargeOverhead($: EngineInterface, taskId: string, alias: Tier, u
|
|||||||
await updateIn<TaskCost>($, S.costs, taskId, old => addOverhead(old ?? emptyTask(taskId), modelId, u, prices))
|
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
|
* 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.
|
* 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.
|
* 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 started = await $.clock.now()
|
||||||
const seconds = async () => Math.round(((await $.clock.now()) - started) / 1000)
|
const seconds = async () => Math.round(((await $.clock.now()) - started) / 1000)
|
||||||
let out = ''
|
let out = ''
|
||||||
let errTail = ''
|
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 {
|
try {
|
||||||
const stream = $.process.spawn({
|
const stream = $.process.spawn({
|
||||||
argv: ['timeout', '--verbose', '--kill-after=30', String(Math.max(1, Math.round(timeoutSec))), 'sh', '-c', cmd],
|
argv: ['timeout', '--verbose', '--kill-after=30', String(Math.max(1, Math.round(timeoutSec))), 'sh', '-c', cmd],
|
||||||
@@ -274,7 +328,10 @@ async function runTests($: EngineInterface, cmd: string, cwd: string, timeoutSec
|
|||||||
for await (const piece of stream) {
|
for await (const piece of stream) {
|
||||||
out = (out + piece.text).slice(-65_536)
|
out = (out + piece.text).slice(-65_536)
|
||||||
if (piece.stream === 'stderr') errTail = (errTail + 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.
|
// 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.
|
// Read from the joined stderr, so a line split across pieces still counts.
|
||||||
const isFired = errTail.includes('timeout: sending signal')
|
const isFired = errTail.includes('timeout: sending signal')
|
||||||
@@ -283,17 +340,81 @@ async function runTests($: EngineInterface, cmd: string, cwd: string, timeoutSec
|
|||||||
const took = await seconds()
|
const took = await seconds()
|
||||||
// Only a timeout that fired is a timeout: a 137 without it is the code's own
|
// 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.
|
// (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 (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 }
|
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 }
|
return { status: 'ran', code: end.code, tail, seconds: took, issues }
|
||||||
} catch (err) {
|
} 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 = {
|
type Settings = {
|
||||||
testCommand: string
|
testCommand: string
|
||||||
testTimeoutSec: number
|
testTimeoutSec: number
|
||||||
|
testFileCommand: string
|
||||||
|
testFileTimeoutSec: number
|
||||||
|
testRerunJobs: number
|
||||||
|
testRerunMax: number
|
||||||
|
testIssueRe: RegExp
|
||||||
prBaseCommand: string
|
prBaseCommand: string
|
||||||
defaultBaseBranch: string
|
defaultBaseBranch: string
|
||||||
maxFails: number
|
maxFails: number
|
||||||
@@ -318,7 +439,11 @@ async function verifyRound($: EngineInterface, agentId: string, rec: AgentRec, c
|
|||||||
}
|
}
|
||||||
const head = `[model-router] ${rec.taskId} (agent ${agentId}, ${rec.tier}, round ${round})`
|
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 base = rec.lastSnap
|
||||||
let baseLabel = 'the previous verified round'
|
let baseLabel = 'the previous verified round'
|
||||||
if (!base) {
|
if (!base) {
|
||||||
@@ -334,7 +459,7 @@ async function verifyRound($: EngineInterface, agentId: string, rec: AgentRec, c
|
|||||||
}
|
}
|
||||||
const diff = await sh($, ['git', 'diff', base], cwd, 60_000)
|
const diff = await sh($, ['git', 'diff', base], cwd, 60_000)
|
||||||
const known = new Set(rec.lastUntracked ?? [])
|
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 = ''
|
let added = ''
|
||||||
for (const f of fresh.slice(0, 20)) {
|
for (const f of fresh.slice(0, 20)) {
|
||||||
try {
|
try {
|
||||||
@@ -347,7 +472,12 @@ async function verifyRound($: EngineInterface, agentId: string, rec: AgentRec, c
|
|||||||
if (!changes) {
|
if (!changes) {
|
||||||
entry.outcome = 'no-changes'
|
entry.outcome = 'no-changes'
|
||||||
await log($, entry)
|
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
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -355,7 +485,7 @@ async function verifyRound($: EngineInterface, agentId: string, rec: AgentRec, c
|
|||||||
let tests = ''
|
let tests = ''
|
||||||
if (cfg.testCommand) {
|
if (cfg.testCommand) {
|
||||||
$.ui.status(`router: ${rec.taskId} round ${round} running tests`)
|
$.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') {
|
if (t.status !== 'ran') {
|
||||||
// No verdict on the code: no verifier call, no fail counted, no rewrite.
|
// No verdict on the code: no verifier call, no fail counted, no rewrite.
|
||||||
entry.outcome = t.status === 'timeout' ? 'tests-timeout' : 'tests-error'
|
entry.outcome = t.status === 'timeout' ? 'tests-timeout' : 'tests-error'
|
||||||
@@ -372,6 +502,13 @@ async function verifyRound($: EngineInterface, agentId: string, rec: AgentRec, c
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
tests = `exit code ${t.code} after ${t.seconds} s\n${t.tail}`
|
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.
|
// 3. The verdict, from another model.
|
||||||
@@ -380,6 +517,11 @@ async function verifyRound($: EngineInterface, agentId: string, rec: AgentRec, c
|
|||||||
$.ui.status(`router: ${rec.taskId} round ${round} verifying on ${verifier}`)
|
$.ui.status(`router: ${rec.taskId} round ${round} verifying on ${verifier}`)
|
||||||
const question = [
|
const question = [
|
||||||
`## Task\n${clip(rec.prompt, 12_000)}`,
|
`## 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
|
rec.lastIssues?.length
|
||||||
? `## Issues raised last round (check they are fixed)\n${rec.lastIssues.map(i => `- ${i}`).join('\n')}`
|
? `## Issues raised last round (check they are fixed)\n${rec.lastIssues.map(i => `- ${i}`).join('\n')}`
|
||||||
: '',
|
: '',
|
||||||
@@ -433,8 +575,8 @@ async function verifyRound($: EngineInterface, agentId: string, rec: AgentRec, c
|
|||||||
const after: AgentRec = {
|
const after: AgentRec = {
|
||||||
...rec,
|
...rec,
|
||||||
rounds: round,
|
rounds: round,
|
||||||
lastSnap: (await snapshot($, cwd)) ?? rec.lastSnap,
|
lastSnap: snapNow ?? rec.lastSnap,
|
||||||
lastUntracked: await untracked($, cwd),
|
lastUntracked: untrackedNow,
|
||||||
lastIssues: verdict.pass ? [] : verdict.issues,
|
lastIssues: verdict.pass ? [] : verdict.issues,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -506,6 +648,7 @@ async function skipRound($: EngineInterface, agentId: string, rec: AgentRec, out
|
|||||||
task: rec.prompt.split('\n')[0]?.slice(0, 60) ?? '',
|
task: rec.prompt.split('\n')[0]?.slice(0, 60) ?? '',
|
||||||
tier: rec.tier,
|
tier: rec.tier,
|
||||||
role: rec.role,
|
role: rec.role,
|
||||||
|
roleName: rec.roleName,
|
||||||
reason: outcome,
|
reason: outcome,
|
||||||
outcome,
|
outcome,
|
||||||
})
|
})
|
||||||
@@ -526,14 +669,64 @@ async function runRound($: EngineInterface, agentId: string, rec: AgentRec, ende
|
|||||||
else await verifyRound($, agentId, round, cfg)
|
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 ----------
|
// ---------- waiting for the real hand-back ----------
|
||||||
|
|
||||||
// The newest turn end per agent. A turn end that is only an interim stop (the
|
// 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
|
// 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.
|
// 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
|
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) {
|
function pause($: EngineInterface, ms: number) {
|
||||||
return new Promise<void>(resolve => {
|
return new Promise<void>(resolve => {
|
||||||
$.clock.after(ms, () => resolve())
|
$.clock.after(ms, () => resolve())
|
||||||
@@ -552,17 +745,32 @@ async function statusOf($: EngineInterface, agentId: string) {
|
|||||||
* After a tracked agent's turn ends: runs the round once its run has ended,
|
* 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.
|
* 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) {
|
async function awaitHandBack($: EngineInterface, agentId: string, token: number, cfg: Settings, since: number) {
|
||||||
const started = await $.clock.now()
|
let idleSince: number | undefined
|
||||||
for (;;) {
|
for (;;) {
|
||||||
if (lastTurn.get(agentId)?.token !== token) return // a newer turn end took over
|
if (lastTurn.get(agentId)?.token !== token) return // a newer turn end took over
|
||||||
if (turnEndKind(await statusOf($, agentId)) === 'handback') break
|
const status = await statusOf($, agentId)
|
||||||
if ((await $.clock.now()) - started > WATCH_FOR_MS) return
|
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)
|
await pause($, WATCH_EVERY_MS)
|
||||||
}
|
}
|
||||||
const turn = lastTurn.get(agentId)
|
const turn = lastTurn.get(agentId)
|
||||||
if (!turn || turn.token !== token) return
|
if (!turn || turn.token !== token) return
|
||||||
lastTurn.delete(agentId)
|
lastTurn.delete(agentId)
|
||||||
|
await endWatch($, agentId, turn.wid)
|
||||||
// read the record now: an earlier round may have changed it meanwhile
|
// read the record now: an earlier round may have changed it meanwhile
|
||||||
const rec = (await getMap<AgentRec>($, S.agents))[agentId]
|
const rec = (await getMap<AgentRec>($, S.agents))[agentId]
|
||||||
if (rec) await runRound($, agentId, rec, turn.ended, turn.reported, cfg)
|
if (rec) await runRound($, agentId, rec, turn.ended, turn.reported, cfg)
|
||||||
@@ -576,6 +784,11 @@ export const register: Register = (on, options) => {
|
|||||||
const cfg: Settings = {
|
const cfg: Settings = {
|
||||||
testCommand: String(options.testCommand ?? '').trim(),
|
testCommand: String(options.testCommand ?? '').trim(),
|
||||||
testTimeoutSec: validTimeout(options.testTimeoutSec),
|
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(),
|
prBaseCommand: String(options.prBaseCommand ?? '').trim(),
|
||||||
defaultBaseBranch: String(options.defaultBaseBranch ?? 'release/1.0').trim(),
|
defaultBaseBranch: String(options.defaultBaseBranch ?? 'release/1.0').trim(),
|
||||||
maxFails: Number(options.maxRewrites ?? 2),
|
maxFails: Number(options.maxRewrites ?? 2),
|
||||||
@@ -584,6 +797,7 @@ export const register: Register = (on, options) => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
on('session.start', async ($, e, next) => {
|
on('session.start', async ($, e, next) => {
|
||||||
|
await resumeWatches($, cfg)
|
||||||
await $.command.register({
|
await $.command.register({
|
||||||
name: 'router',
|
name: 'router',
|
||||||
description: 'Model router: decisions, verdicts and savings vs Opus (`/router savings [Tn]`, `/router clear`)',
|
description: 'Model router: decisions, verdicts and savings vs Opus (`/router savings [Tn]`, `/router clear`)',
|
||||||
@@ -601,6 +815,14 @@ export const register: Register = (on, options) => {
|
|||||||
on('agent.spawn', async ($, e, next) => {
|
on('agent.spawn', async ($, e, next) => {
|
||||||
if (e.fork || e.isTeammate || e.workflow) return next(e)
|
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 taskId: string
|
||||||
let prompt = e.prompt
|
let prompt = e.prompt
|
||||||
let tier: Tier
|
let tier: Tier
|
||||||
@@ -617,19 +839,25 @@ export const register: Register = (on, options) => {
|
|||||||
|
|
||||||
if (markId && pending) {
|
if (markId && pending) {
|
||||||
taskId = markId
|
taskId = markId
|
||||||
const extra = e.prompt.replace(REWRITE_MARK, '').trim()
|
prompt = rewritePrompt(e.prompt, pending.prompt)
|
||||||
prompt = pending.prompt + (extra ? `\n\nAdditional guidance from the orchestrator:\n${extra}` : '')
|
|
||||||
tier = pending.tier
|
tier = pending.tier
|
||||||
fails = pending.fails
|
fails = pending.fails
|
||||||
critical = pending.critical
|
critical = pending.critical
|
||||||
reason = `new agent after ${fails} failed verdicts`
|
reason = `rewrite of ${markId} after ${fails} failed verdicts`
|
||||||
await putIn<Pending>($, S.pending, markId, undefined)
|
} 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 {
|
} else {
|
||||||
taskId = await nextId($)
|
const brief = briefFor(e.prompt, e.subagentType)
|
||||||
const brief = parseBrief(e.prompt)
|
taskId = await nextId($, brief.role === 'dev')
|
||||||
critical = safetyHit(`${e.description}\n${e.prompt}`, patterns) !== undefined
|
critical = safetyHit(`${e.description}\n${e.prompt}`, patterns) !== undefined
|
||||||
const d = decide({
|
const d = decide({
|
||||||
role: brief.role,
|
role: brief.role,
|
||||||
|
roleName: brief.roleName,
|
||||||
named: asTier(e.model),
|
named: asTier(e.model),
|
||||||
subagentType: e.subagentType,
|
subagentType: e.subagentType,
|
||||||
prompt: e.prompt,
|
prompt: e.prompt,
|
||||||
@@ -640,6 +868,7 @@ export const register: Register = (on, options) => {
|
|||||||
isRouted =
|
isRouted =
|
||||||
brief.role !== 'review' &&
|
brief.role !== 'review' &&
|
||||||
brief.role !== 'test' &&
|
brief.role !== 'test' &&
|
||||||
|
brief.role !== 'other' &&
|
||||||
!(d.kind === 'fixed' && d.reason === 'model chosen by orchestrator')
|
!(d.kind === 'fixed' && d.reason === 'model chosen by orchestrator')
|
||||||
if (d.kind === 'fixed') {
|
if (d.kind === 'fixed') {
|
||||||
tier = d.tier
|
tier = d.tier
|
||||||
@@ -652,9 +881,14 @@ export const register: Register = (on, options) => {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const brief = parseBrief(prompt)
|
const brief = briefFor(prompt, e.subagentType)
|
||||||
const ran = await next({ ...e, prompt, model: tier })
|
const ran = await next({ ...e, prompt, model: tier })
|
||||||
if (ran.deny !== undefined || !ran.agentId) return ran
|
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.
|
// 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)
|
if (ran.model && ran.model !== tier && ran.model.includes(tier)) await putIn($, S.aliases, tier, ran.model)
|
||||||
@@ -668,9 +902,11 @@ export const register: Register = (on, options) => {
|
|||||||
if (brief.role)
|
if (brief.role)
|
||||||
await putIn<AgentRec>($, S.agents, ran.agentId, {
|
await putIn<AgentRec>($, S.agents, ran.agentId, {
|
||||||
taskId,
|
taskId,
|
||||||
tier,
|
tier: resolved,
|
||||||
routed: tier,
|
routed: resolved,
|
||||||
|
name: e.name,
|
||||||
role: brief.role,
|
role: brief.role,
|
||||||
|
roleName: brief.roleName,
|
||||||
clone: brief.clone,
|
clone: brief.clone,
|
||||||
baseBranch: brief.baseBranch,
|
baseBranch: brief.baseBranch,
|
||||||
critical,
|
critical,
|
||||||
@@ -684,13 +920,14 @@ export const register: Register = (on, options) => {
|
|||||||
agentId: ran.agentId,
|
agentId: ran.agentId,
|
||||||
at: await $.clock.now(),
|
at: await $.clock.now(),
|
||||||
task: e.description,
|
task: e.description,
|
||||||
tier,
|
tier: resolved,
|
||||||
role: brief.role,
|
role: brief.role,
|
||||||
|
roleName: brief.roleName,
|
||||||
reason,
|
reason,
|
||||||
outcome: 'spawned',
|
outcome: 'spawned',
|
||||||
opusRequested,
|
opusRequested,
|
||||||
})
|
})
|
||||||
$.ui.status(`router: ${taskId} ${brief.role ?? 'agent'} → ${tier}`)
|
$.ui.status(`router: ${taskId} ${brief.roleName ?? brief.role ?? 'agent'} → ${tier}`)
|
||||||
return ran
|
return ran
|
||||||
}).catch(($, e, next) => {
|
}).catch(($, e, next) => {
|
||||||
// Fail open: a router bug must never block delegation.
|
// Fail open: a router bug must never block delegation.
|
||||||
@@ -701,6 +938,7 @@ export const register: Register = (on, options) => {
|
|||||||
// Verification: each finished run of a tracked agent, a resumed SendMessage round included.
|
// Verification: each finished run of a tracked agent, a resumed SendMessage round included.
|
||||||
on('turn.complete', async ($, e, next) => {
|
on('turn.complete', async ($, e, next) => {
|
||||||
const out = await next(e)
|
const out = await next(e)
|
||||||
|
await resumeWatches($, cfg)
|
||||||
const agentId = e.agentId
|
const agentId = e.agentId
|
||||||
if (!agentId) return out
|
if (!agentId) return out
|
||||||
|
|
||||||
@@ -714,9 +952,17 @@ export const register: Register = (on, options) => {
|
|||||||
const rec = (await getMap<AgentRec>($, S.agents))[agentId]
|
const rec = (await getMap<AgentRec>($, S.agents))[agentId]
|
||||||
if (!rec) return out
|
if (!rec) return out
|
||||||
// Only the run's end is a hand-back; wait for it after this event has gone on.
|
// Only the run's end is a hand-back; wait for it after this event has gone on.
|
||||||
const token = ++tokens
|
await watch($, agentId, { ended: e.reason, reported: e.usage?.model, since: await $.clock.now() }, cfg)
|
||||||
lastTurn.set(agentId, { token, ended: e.reason, reported: e.usage?.model })
|
return out
|
||||||
$.clock.after(0, () => void awaitHandBack($, agentId, token, cfg))
|
})
|
||||||
|
|
||||||
|
// 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
|
return out
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -750,17 +996,23 @@ export const register: Register = (on, options) => {
|
|||||||
.slice(-15)
|
.slice(-15)
|
||||||
.map(
|
.map(
|
||||||
l =>
|
l =>
|
||||||
`${l.id.padEnd(5)} ${(l.role ?? '-').padEnd(6)} ${l.tier.padEnd(6)} ${(l.verifier ? '→' + l.verifier : '').padEnd(8)} ${l.outcome.padEnd(17)} ${(l.task ?? '').slice(0, 40)}${l.opusRequested ? ' [opus requested]' : ''}`,
|
`${l.id.padEnd(5)} ${(l.roleName ?? l.role ?? '-').padEnd(6)} ${l.tier.padEnd(6)} ${(l.verifier ? '→' + l.verifier : '').padEnd(8)} ${l.outcome.padEnd(17)} ${(l.task ?? '').slice(0, 40)}${l.opusRequested ? ' [opus requested]' : ''}`,
|
||||||
)
|
)
|
||||||
.join('\n')
|
.join('\n')
|
||||||
const pending = Object.keys(await getMap<Pending>($, S.pending))
|
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 {
|
return {
|
||||||
text:
|
text:
|
||||||
`model-router - last ${Math.min(15, list.length)} of ${list.length}\n` +
|
`model-router - last ${Math.min(15, list.length)} of ${list.length}\n` +
|
||||||
`writers: ${count(l => (l.outcome === 'spawned' ? `${l.role ?? 'other'}:${l.tier}` : undefined))}\n` +
|
`writers: ${count(l => (l.outcome === 'spawned' ? `${l.roleName ?? l.role ?? 'none'}:${l.tier}` : undefined))}\n` +
|
||||||
`results: ${count(l => (l.outcome === 'spawned' ? undefined : l.outcome))}\n` +
|
`results: ${count(l => (l.outcome === 'spawned' ? undefined : l.outcome))}\n` +
|
||||||
`opus requested on dev briefs: ${list.filter(l => l.opusRequested).length}\n` +
|
`opus requested on dev briefs: ${list.filter(l => l.opusRequested).length}\n` +
|
||||||
(pending.length ? `pending rewrites: ${pending.join(', ')}\n` : '') +
|
(pending.length ? `pending rewrites: ${pending.join(', ')}\n` : '') +
|
||||||
|
(waiting.length ? `waiting for a hand-back: ${waiting.join(', ')}\n` : '') +
|
||||||
`\n${rows}\n\n` +
|
`\n${rows}\n\n` +
|
||||||
savingsReport(await getMap<TaskCost>($, S.costs), 5),
|
savingsReport(await getMap<TaskCost>($, S.costs), 5),
|
||||||
}
|
}
|
||||||
|
|||||||
+176
-16
@@ -1,7 +1,8 @@
|
|||||||
// Pure routing logic: no `$`, so every rule here is unit-tested.
|
// Pure routing logic: no `$`, so every rule here is unit-tested.
|
||||||
|
|
||||||
export type Tier = 'haiku' | 'sonnet' | 'opus' | 'fable'
|
export type Tier = 'haiku' | 'sonnet' | 'opus' | 'fable'
|
||||||
export type Role = 'dev' | 'review' | 'test'
|
/** `other`: any pipeline role the router does not know (test-design, ...): never a dev. */
|
||||||
|
export type Role = 'dev' | 'review' | 'test' | 'other'
|
||||||
|
|
||||||
export const TIERS: readonly Tier[] = ['haiku', 'sonnet', 'opus', 'fable']
|
export const TIERS: readonly Tier[] = ['haiku', 'sonnet', 'opus', 'fable']
|
||||||
|
|
||||||
@@ -31,6 +32,8 @@ export type Brief = {
|
|||||||
clone?: string
|
clone?: string
|
||||||
ticket?: string
|
ticket?: string
|
||||||
role?: Role
|
role?: Role
|
||||||
|
/** The role as the brief wrote it (`test-design`), when it is not dev, review or test. */
|
||||||
|
roleName?: string
|
||||||
baseBranch?: string
|
baseBranch?: string
|
||||||
/** Several clone paths and no `Clone:` line: the role cannot be told. */
|
/** Several clone paths and no `Clone:` line: the role cannot be told. */
|
||||||
isAmbiguous?: boolean
|
isAmbiguous?: boolean
|
||||||
@@ -38,40 +41,56 @@ export type Brief = {
|
|||||||
|
|
||||||
// A ticket is LETTERS-digits plus any extra parts (OPT-11-P4); the role is the last part.
|
// A ticket is LETTERS-digits plus any extra parts (OPT-11-P4); the role is the last part.
|
||||||
const TICKET = '[A-Za-z]+-\\d+(?:-[A-Za-z0-9]+)*?'
|
const TICKET = '[A-Za-z]+-\\d+(?:-[A-Za-z0-9]+)*?'
|
||||||
const CLONE_PATH = new RegExp(`(\\S*?\\/clones\\/(${TICKET})-(dev|review|test))\\/?`)
|
// The role must end the folder name: EV-05-design and EV-05-test-design are no -test clone.
|
||||||
|
const CLONE_PATH = new RegExp(`(\\S*?\\/clones\\/(${TICKET})-(dev|review|test))(?![A-Za-z0-9_-])\\/?`)
|
||||||
const CLONE_PATHS = new RegExp(CLONE_PATH.source, 'g')
|
const CLONE_PATHS = new RegExp(CLONE_PATH.source, 'g')
|
||||||
// The explicit line every brief carries: `Clone: <path>` with an optional `(Role: dev)`.
|
// The explicit line every brief carries: `Clone: <path>` with an optional `(Role: dev)`.
|
||||||
const CLONE_LINE = /^[ \t>*-]*Clone:[ \t]*`?([^\s`]+?)\/?`?[ \t]*(?:\(Role:[ \t]*(dev|review|test)\))?[ \t]*$/im
|
const CLONE_LINE = /^[ \t>*-]*Clone:[ \t]*`?([^\s`]+?)\/?`?[ \t]*(?:\(Role:[ \t]*([A-Za-z][\w-]*)\))?[ \t]*$/im
|
||||||
|
// The pipeline's own header, which decides over everything else.
|
||||||
|
const PIPELINE_ROLE = /^[ \t>*-]*Pipeline-Role:[ \t]*`?([A-Za-z][\w-]*)`?[ \t]*$/im
|
||||||
const BASE =
|
const BASE =
|
||||||
/\b(?:base(?:\s+branch)?|target(?:\s+branch)?|merge\s+into|PR\s+(?:against|into))\s*[:=]?\s*`?((?:release|main|master|develop)[\w./-]*)/i
|
/\b(?:base(?:\s+branch)?|target(?:\s+branch)?|merge\s+into|PR\s+(?:against|into))\s*[:=]?\s*`?((?:release|main|master|develop)[\w./-]*)/i
|
||||||
|
|
||||||
|
/** A role as written in a brief: dev, review and test as they are, anything else `other`. */
|
||||||
|
export const asRole = (written: string | undefined): { role?: Role; roleName?: string } => {
|
||||||
|
if (!written) return {}
|
||||||
|
const w = written.toLowerCase()
|
||||||
|
if (w === 'dev' || w === 'review' || w === 'test') return { role: w }
|
||||||
|
return { role: 'other', roleName: w }
|
||||||
|
}
|
||||||
|
|
||||||
const trimPath = (p: string) => p.replace(/^[`'"(]+/, '').replace(/[`'")]+$/, '').replace(/\/+$/, '')
|
const trimPath = (p: string) => p.replace(/^[`'"(]+/, '').replace(/[`'")]+$/, '').replace(/\/+$/, '')
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Reads the clone path, ticket, role and base branch out of a brief.
|
* Reads the clone path, ticket, role and base branch out of a brief.
|
||||||
*
|
*
|
||||||
* The `Clone:` line decides when present: its `(Role: ...)`, else the role in
|
* The role: `Pipeline-Role:` first, then `(Role: ...)` on the `Clone:` line,
|
||||||
* its path. Without one, a brief that names one clone is read from that path;
|
* then the role in the clone's folder name. A role other than dev, review or
|
||||||
* one that names several is ambiguous and gets no role.
|
* test is `other`, never a dev. Without a `Clone:` line, a brief that names
|
||||||
|
* one clone is read from that path; several are ambiguous. A brief whose
|
||||||
|
* header names a non-dev role is never read from other paths it mentions.
|
||||||
*/
|
*/
|
||||||
export const parseBrief = (prompt: string): Brief => {
|
export const parseBrief = (prompt: string): Brief => {
|
||||||
const b = prompt.match(BASE)
|
const b = prompt.match(BASE)
|
||||||
// a sentence's full stop or a trailing slash is no part of the branch
|
// a sentence's full stop or a trailing slash is no part of the branch
|
||||||
const baseBranch = b?.[1]?.replace(/[./-]+$/, '')
|
const baseBranch = b?.[1]?.replace(/[./-]+$/, '')
|
||||||
|
const header = asRole(prompt.match(PIPELINE_ROLE)?.[1])
|
||||||
|
|
||||||
const line = prompt.match(CLONE_LINE)
|
const line = prompt.match(CLONE_LINE)
|
||||||
if (line?.[1]) {
|
if (line?.[1]) {
|
||||||
const clone = trimPath(line[1])
|
const clone = trimPath(line[1])
|
||||||
const fromPath = clone.match(CLONE_PATH)
|
const fromPath = clone.match(CLONE_PATH)
|
||||||
const role = (line[2] ?? fromPath?.[3]) as Role | undefined
|
const stated = header.role ? header : line[2] ? asRole(line[2]) : asRole(fromPath?.[3])
|
||||||
return { clone, ticket: fromPath?.[2], role, baseBranch }
|
// A pipeline agent with a clone the router cannot place is no dev: keep its model.
|
||||||
|
return { clone, ticket: fromPath?.[2], role: 'other', ...stated, baseBranch }
|
||||||
}
|
}
|
||||||
|
if (header.role && header.role !== 'dev') return { ...header, baseBranch }
|
||||||
|
|
||||||
const paths = [...new Set([...prompt.matchAll(CLONE_PATHS)].map(m => trimPath(m[1] ?? '')))]
|
const paths = [...new Set([...prompt.matchAll(CLONE_PATHS)].map(m => trimPath(m[1] ?? '')))]
|
||||||
if (paths.length > 1) return { baseBranch, isAmbiguous: true }
|
if (paths.length > 1) return { baseBranch, isAmbiguous: true }
|
||||||
const only = paths[0]?.match(CLONE_PATH)
|
const only = paths[0]?.match(CLONE_PATH)
|
||||||
if (!only) return { baseBranch }
|
if (!only) return { ...header, baseBranch }
|
||||||
return { clone: trimPath(only[1] ?? ''), ticket: only[2], role: only[3] as Role, baseBranch }
|
return { clone: trimPath(only[1] ?? ''), ticket: only[2], ...(header.role ? header : asRole(only[3])), baseBranch }
|
||||||
}
|
}
|
||||||
|
|
||||||
// ---------- routing ----------
|
// ---------- routing ----------
|
||||||
@@ -95,19 +114,63 @@ const HEAVY = [
|
|||||||
|
|
||||||
export type Route = { tier: Tier; reason: string }
|
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). */
|
/** A clear signal from the text, or undefined (ask the classifier). */
|
||||||
export const heuristic = (subagentType: string | undefined, prompt: string, role?: Role): Route | undefined => {
|
export const heuristic = (subagentType: string | undefined, prompt: string, role?: Role): Route | undefined => {
|
||||||
if (!role && subagentType && READ_ONLY_TYPES.test(subagentType))
|
if (!role && subagentType && READ_ONLY_TYPES.test(subagentType))
|
||||||
return { tier: 'haiku', reason: `read-only agent type ${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))
|
const heavy = HEAVY.find(r => r.test(lower))
|
||||||
if (heavy) return { tier: 'opus', reason: 'approach still open' }
|
if (heavy) return { tier: 'opus', reason: 'approach still open' }
|
||||||
if (role) return undefined // dev briefs never take the light path
|
if (role) return undefined // dev briefs never take the light path
|
||||||
const light = LIGHT.find(r => r.test(lower))
|
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
|
return undefined
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Agent types that gate rather than write: never routed down, never verified. */
|
||||||
|
export const KEEP_MODEL_TYPES = /^(test-designer|release-reviewer)$/i
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The brief as the router treats it: a gate agent type (test-designer,
|
||||||
|
* release-reviewer) is never a dev, nor an unplaced agent, whatever paths
|
||||||
|
* its brief names. Review and test roles stay as they are.
|
||||||
|
*/
|
||||||
|
export const briefFor = (prompt: string, subagentType?: string): Brief => {
|
||||||
|
const b = parseBrief(prompt)
|
||||||
|
if (!subagentType || !KEEP_MODEL_TYPES.test(subagentType)) return b
|
||||||
|
if (b.role === 'review' || b.role === 'test') return b
|
||||||
|
return { ...b, role: 'other', roleName: b.role === 'other' ? b.roleName : subagentType.toLowerCase(), isAmbiguous: undefined }
|
||||||
|
}
|
||||||
|
|
||||||
export type Decision =
|
export type Decision =
|
||||||
| { kind: 'fixed'; tier: Tier; reason: string; opusRequested?: boolean }
|
| { kind: 'fixed'; tier: Tier; reason: string; opusRequested?: boolean }
|
||||||
| { kind: 'classify'; opusRequested?: boolean }
|
| { kind: 'classify'; opusRequested?: boolean }
|
||||||
@@ -126,15 +189,25 @@ export const decide = (args: {
|
|||||||
prompt: string
|
prompt: string
|
||||||
respectExplicit: boolean
|
respectExplicit: boolean
|
||||||
isAmbiguous?: boolean
|
isAmbiguous?: boolean
|
||||||
|
/** The role as written, for an `other` role (test-design). */
|
||||||
|
roleName?: string
|
||||||
}): Decision => {
|
}): Decision => {
|
||||||
const { role, named, subagentType, prompt, respectExplicit, isAmbiguous } = args
|
const { role, named, subagentType, prompt, respectExplicit, isAmbiguous } = args
|
||||||
|
const who = args.roleName ?? role
|
||||||
// Could be a test or review agent: never risk a weaker model on it.
|
// Could be a test or review agent: never risk a weaker model on it.
|
||||||
if (isAmbiguous)
|
if (isAmbiguous)
|
||||||
return { kind: 'fixed', tier: named && named !== 'haiku' && named !== 'sonnet' ? named : 'opus', reason: 'several clone paths and no Clone: line' }
|
return { kind: 'fixed', tier: named && named !== 'haiku' && named !== 'sonnet' ? named : 'opus', reason: 'several clone paths and no Clone: line' }
|
||||||
if (role === 'review' || role === 'test')
|
if (role === 'review' || role === 'test')
|
||||||
return named
|
return named
|
||||||
? { kind: 'fixed', tier: named, reason: `named model kept for ${role} agent` }
|
? { kind: 'fixed', tier: named, reason: `named model kept for ${who} agent` }
|
||||||
: { kind: 'fixed', tier: 'opus', reason: `${role} agent default` }
|
: { kind: 'fixed', tier: 'opus', reason: `${who} agent default` }
|
||||||
|
// Pipeline gates (test design, release review, any other non-dev role) judge, they do not
|
||||||
|
// write code: they keep a named model, never Haiku, and run on Opus when none is named.
|
||||||
|
const gate = role === 'other' ? (args.roleName ?? subagentType ?? 'other') : !role && subagentType && KEEP_MODEL_TYPES.test(subagentType) ? subagentType : undefined
|
||||||
|
if (gate)
|
||||||
|
return named && named !== 'haiku'
|
||||||
|
? { kind: 'fixed', tier: named, reason: `named model kept for ${gate}` }
|
||||||
|
: { kind: 'fixed', tier: 'opus', reason: `${gate} default` }
|
||||||
if (!role && respectExplicit && named) return { kind: 'fixed', tier: named, reason: 'model chosen by orchestrator' }
|
if (!role && respectExplicit && named) return { kind: 'fixed', tier: named, reason: 'model chosen by orchestrator' }
|
||||||
const opusRequested = role === 'dev' && (named === 'opus' || named === 'fable')
|
const opusRequested = role === 'dev' && (named === 'opus' || named === 'fable')
|
||||||
const h = heuristic(subagentType, prompt, role)
|
const h = heuristic(subagentType, prompt, role)
|
||||||
@@ -143,13 +216,14 @@ export const decide = (args: {
|
|||||||
|
|
||||||
// ---------- verification ----------
|
// ---------- verification ----------
|
||||||
|
|
||||||
export type Skip = 'test-agent' | 'review-agent' | 'no-clone' | 'opus-unverified' | 'agent-ended'
|
export type Skip = 'test-agent' | 'review-agent' | 'non-dev-agent' | 'no-clone' | 'opus-unverified' | 'agent-ended'
|
||||||
|
|
||||||
/** Why an agent run is not verified, or undefined when it is. */
|
/** Why an agent run is not verified, or undefined when it is. */
|
||||||
export const skipReason = (rec: { role?: Role; clone?: string; tier: Tier }, ended: string): Skip | undefined => {
|
export const skipReason = (rec: { role?: Role; clone?: string; tier: Tier }, ended: string): Skip | undefined => {
|
||||||
if (ended !== 'answer') return 'agent-ended'
|
if (ended !== 'answer') return 'agent-ended'
|
||||||
if (rec.role === 'test') return 'test-agent'
|
if (rec.role === 'test') return 'test-agent'
|
||||||
if (rec.role === 'review') return 'review-agent'
|
if (rec.role === 'review') return 'review-agent'
|
||||||
|
if (rec.role === 'other') return 'non-dev-agent'
|
||||||
if (!rec.clone) return 'no-clone'
|
if (!rec.clone) return 'no-clone'
|
||||||
if (rank(rec.tier) >= rank('opus')) return 'opus-unverified'
|
if (rank(rec.tier) >= rank('opus')) return 'opus-unverified'
|
||||||
return undefined
|
return undefined
|
||||||
@@ -251,7 +325,26 @@ export const parseVerdict = (text: string): Reading => {
|
|||||||
return { isReadable: false, preview: text.slice(0, 300) }
|
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) =>
|
export const clip = (s: string, n: number) =>
|
||||||
s.length <= n ? s : s.slice(0, n) + `\n... [${s.length - n} more characters cut]`
|
s.length <= n ? s : s.slice(0, n) + `\n... [${s.length - n} more characters cut]`
|
||||||
@@ -314,6 +407,73 @@ export type LoopStatus = 'pending' | 'running' | 'waiting' | 'idle' | 'completed
|
|||||||
export const turnEndKind = (status: LoopStatus | undefined): 'handback' | 'interim' =>
|
export const turnEndKind = (status: LoopStatus | undefined): 'handback' | 'interim' =>
|
||||||
status === undefined || status === 'completed' || status === 'failed' || status === 'killed' ? '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. */
|
/** 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_EVERY_MS = 15_000
|
||||||
export const WATCH_FOR_MS = 24 * 60 * 60 * 1000
|
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
|
||||||
|
}
|
||||||
|
|||||||
+776
-6
@@ -4,14 +4,22 @@ import { expect, mock, test, type Engine } from 'claude-code/testing'
|
|||||||
import {
|
import {
|
||||||
decide,
|
decide,
|
||||||
heuristic,
|
heuristic,
|
||||||
|
taskText,
|
||||||
|
rewritePrompt,
|
||||||
onFail,
|
onFail,
|
||||||
parseBrief,
|
parseBrief,
|
||||||
parseVerdict,
|
parseVerdict,
|
||||||
rewriteTier,
|
rewriteTier,
|
||||||
|
REWRITE_MARK,
|
||||||
skipReason,
|
skipReason,
|
||||||
validTimeout,
|
validTimeout,
|
||||||
verifierFor,
|
verifierFor,
|
||||||
handBackLine,
|
handBackLine,
|
||||||
|
isSafeFile,
|
||||||
|
issueRegex,
|
||||||
|
parseIssueLine,
|
||||||
|
rerunVerdict,
|
||||||
|
fileCommand,
|
||||||
ranTier,
|
ranTier,
|
||||||
turnEndKind,
|
turnEndKind,
|
||||||
} from '../hooks/router'
|
} from '../hooks/router'
|
||||||
@@ -61,6 +69,46 @@ test('fix 2: several clones and no Clone: line gives no role, and routes to opus
|
|||||||
expect(parseBrief(`Work in ${DEV}/. Commit in ${DEV}.`).role).toBe('dev')
|
expect(parseBrief(`Work in ${DEV}/. Commit in ${DEV}.`).role).toBe('dev')
|
||||||
})
|
})
|
||||||
|
|
||||||
|
// ---------- non-dev roles (#7, EV-05) ----------
|
||||||
|
|
||||||
|
const EV05_DEV = '/home/homelab/projects/goodwe/clones/EV-05-dev'
|
||||||
|
const EV05_DESIGN = '/home/homelab/projects/goodwe/clones/EV-05-design'
|
||||||
|
const designBrief = (devClone = EV05_DEV) =>
|
||||||
|
`Pipeline-Role: test-design\nClone: ${EV05_DESIGN} (Role: test-design)\n\n` +
|
||||||
|
`Design the EV-05 tests. The developer works in ${devClone}/; do not touch it.`
|
||||||
|
|
||||||
|
test('#7: a test-design brief is a non-dev role, even when it names the dev clone', async () => {
|
||||||
|
expect(parseBrief(designBrief())).toMatchObject({ clone: EV05_DESIGN, role: 'other', roleName: 'test-design' })
|
||||||
|
// the header alone: other paths in the brief are never read for a role
|
||||||
|
const b = parseBrief(`Pipeline-Role: test-design\nThe developer works in ${EV05_DEV}/.`)
|
||||||
|
expect(b.role).toBe('other')
|
||||||
|
expect(b.clone).toBe(undefined)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('#7: Pipeline-Role decides over (Role: ...) and the path', async () => {
|
||||||
|
expect(parseBrief(`Pipeline-Role: review\nClone: ${EV05_DEV} (Role: dev)`).role).toBe('review')
|
||||||
|
expect(parseBrief(`Pipeline-Role: dev\nClone: ${EV05_DESIGN}`).role).toBe('dev')
|
||||||
|
expect(parseBrief(`Pipeline-Role: Dev\nWork in ${EV05_DEV}/.`).role).toBe('dev')
|
||||||
|
// without the header, (Role: ...) still wins over the path
|
||||||
|
expect(parseBrief(`Clone: ${EV05_DEV} (Role: test-design)`)).toMatchObject({ role: 'other', roleName: 'test-design' })
|
||||||
|
})
|
||||||
|
|
||||||
|
test('#7: the role must end the folder name', async () => {
|
||||||
|
expect(parseBrief('Work in /x/clones/EV-05-test-design/.').role).toBe(undefined)
|
||||||
|
expect(parseBrief('Work in /x/clones/EV-05-dev-notes/.').role).toBe(undefined)
|
||||||
|
expect(parseBrief('Work in /x/clones/EV-05-dev/.').role).toBe('dev')
|
||||||
|
// a Clone: line the router cannot place keeps its model, unverified
|
||||||
|
expect(parseBrief('Clone: /x/clones/EV-05-test-design').role).toBe('other')
|
||||||
|
})
|
||||||
|
|
||||||
|
test('#7: other roles keep the named model, opus when none is named, and are never verified', async () => {
|
||||||
|
expect(decide({ role: 'other', roleName: 'test-design', named: 'sonnet', prompt: 'x', respectExplicit: false }))
|
||||||
|
.toEqual({ kind: 'fixed', tier: 'sonnet', reason: 'named model kept for test-design' })
|
||||||
|
expect(decide({ role: 'other', prompt: 'x', respectExplicit: false })).toMatchObject({ kind: 'fixed', tier: 'opus' })
|
||||||
|
expect(decide({ role: 'other', roleName: 'test-design', named: 'haiku', prompt: 'x', respectExplicit: false })).toMatchObject({ tier: 'opus' })
|
||||||
|
expect(skipReason({ role: 'other', clone: EV05_DESIGN, tier: 'sonnet' }, 'answer')).toBe('non-dev-agent')
|
||||||
|
})
|
||||||
|
|
||||||
// ---------- who picks the writer (C4) ----------
|
// ---------- who picks the writer (C4) ----------
|
||||||
|
|
||||||
test('C4: review and test agents keep the model they are given', async () => {
|
test('C4: review and test agents keep the model they are given', async () => {
|
||||||
@@ -219,6 +267,27 @@ type World = {
|
|||||||
handBacks: string[]
|
handBacks: string[]
|
||||||
/** Every message in the order it was sent. */
|
/** Every message in the order it was sent. */
|
||||||
all: string[]
|
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. */
|
/** Each agent's loop status as $.agent.list() reports it; absent means completed. */
|
||||||
status: Record<string, string>
|
status: Record<string, string>
|
||||||
diffs: string[]
|
diffs: string[]
|
||||||
@@ -234,6 +303,17 @@ type World = {
|
|||||||
/** A test itself prints the timeout line, on stdout. */
|
/** A test itself prints the timeout line, on stdout. */
|
||||||
testLineOnStdout?: boolean
|
testLineOnStdout?: boolean
|
||||||
snap: number
|
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 }
|
const USAGE = { input_tokens: 1, output_tokens: 1, cache_creation_input_tokens: 0, cache_read_input_tokens: 0 }
|
||||||
@@ -242,13 +322,15 @@ const ok = (stdout: string, exitCode = 0) => ({
|
|||||||
})
|
})
|
||||||
|
|
||||||
function world(on: On, w: World) {
|
function world(on: On, w: World) {
|
||||||
mock.store(on)
|
mock.store(on, w.seed)
|
||||||
const clock = mock.clock(on)
|
const clock = mock.clock(on)
|
||||||
on('ui.status', async () => ({ value: undefined }))
|
on('ui.status', async () => ({ value: undefined }))
|
||||||
on('ui.toast', async () => ({ value: undefined }))
|
on('ui.toast', async () => ({ value: undefined }))
|
||||||
on('model.complete', async (_$, e) => {
|
on('model.complete', async (_$, e) => {
|
||||||
if (e.system?.startsWith('You route')) return { value: { isAnswered: true as const, text: 'sonnet', usage: USAGE } }
|
if (e.system?.startsWith('You route')) return { value: { isAnswered: true as const, text: 'sonnet', usage: USAGE } }
|
||||||
w.verifier.push(e.model)
|
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 } }
|
return { value: { isAnswered: true as const, text: w.verdicts.shift() ?? '{"verdict":"PASS"}', usage: USAGE } }
|
||||||
})
|
})
|
||||||
on('process.run', async (_$, e) => {
|
on('process.run', async (_$, e) => {
|
||||||
@@ -256,20 +338,44 @@ function world(on: On, w: World) {
|
|||||||
const cwd = String(e.init?.cwd ?? '')
|
const cwd = String(e.init?.cwd ?? '')
|
||||||
if (cwd !== DEV) return ok('', 128) // not a git repo: the session folder
|
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 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 ')) {
|
if (a.startsWith('git diff ')) {
|
||||||
w.diffBases.push(e.argv[2] ?? '')
|
w.diffBases.push(e.argv[2] ?? '')
|
||||||
return ok(w.diffs.shift() ?? '')
|
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('')
|
return ok('')
|
||||||
})
|
})
|
||||||
on('process.spawn', async function* (_$, e) {
|
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.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])
|
w.testArgv.push([...e.argv])
|
||||||
const end = w.testEnds.shift() ?? 0
|
const end = w.testEnds.shift() ?? 0
|
||||||
const fired = w.testFired.shift() ?? false
|
const fired = w.testFired.shift() ?? false
|
||||||
if (end === 'throw') throw new Error('docker: not found')
|
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' }
|
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 (fired) yield { stream: 'stderr' as const, text: "timeout: sending signal TERM to command 'sh'\n" }
|
||||||
if (w.testSplitLine) {
|
if (w.testSplitLine) {
|
||||||
yield { stream: 'stderr' as const, text: 'timeout: sending sig' }
|
yield { stream: 'stderr' as const, text: 'timeout: sending sig' }
|
||||||
@@ -279,9 +385,20 @@ function world(on: On, w: World) {
|
|||||||
return { value: { code: end, signal: null } }
|
return { value: { code: end, signal: null } }
|
||||||
})
|
})
|
||||||
on('agent.spawn', async (_$, e) => {
|
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 })
|
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('turn.complete', async (_$, e) => ({ text: e.answer }))
|
||||||
on('agent.list', async () => ({
|
on('agent.list', async () => ({
|
||||||
value: w.spawned
|
value: w.spawned
|
||||||
@@ -298,7 +415,7 @@ function world(on: On, w: World) {
|
|||||||
return clock
|
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') {
|
async function finish($: Engine, clock: { advance: (ms: number) => Promise<void> }, agentId: string, ranModel?: string, reason = 'answer') {
|
||||||
const usage = ranModel
|
const usage = ranModel
|
||||||
@@ -656,7 +773,7 @@ test('TOOL-12: review and test agents get no hand-back line', async ($, on) => {
|
|||||||
// ---------- interim stops (TOOL-12 follow-up) ----------
|
// ---------- interim stops (TOOL-12 follow-up) ----------
|
||||||
|
|
||||||
/** A turn end of the agent while it is still alive: its status says so. */
|
/** 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
|
w.status[agentId] = status
|
||||||
await ($.turn as unknown as { complete: (e: unknown) => Promise<unknown> }).complete({
|
await ($.turn as unknown as { complete: (e: unknown) => Promise<unknown> }).complete({
|
||||||
answer: 'Waiting for the test suite.',
|
answer: 'Waiting for the test suite.',
|
||||||
@@ -665,7 +782,7 @@ async function interimStop($: Engine, clock: { advance: (ms: number) => Promise<
|
|||||||
turnId: 't',
|
turnId: 't',
|
||||||
agentId,
|
agentId,
|
||||||
reason: 'answer',
|
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)
|
await clock.advance(1)
|
||||||
}
|
}
|
||||||
@@ -699,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
|
const id = r.agentId as string
|
||||||
await interimStop($, clock, w, id)
|
await interimStop($, clock, w, id)
|
||||||
await interimStop($, clock, w, id, 'idle')
|
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)
|
await clock.advance(10 * 60 * 1000)
|
||||||
expect(w.all).toEqual([])
|
expect(w.all).toEqual([])
|
||||||
w.status[id] = 'completed'
|
w.status[id] = 'completed'
|
||||||
@@ -763,3 +882,654 @@ test('follow-up: each agent is judged by its own status, not by that of another
|
|||||||
expect(w.all).toEqual([])
|
expect(w.all).toEqual([])
|
||||||
expect(w.verifier).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')
|
||||||
|
})
|
||||||
|
|
||||||
|
// ---------- ems-dev-tooling (test design, test-plan check) ----------
|
||||||
|
|
||||||
|
test('pipeline: a test designer keeps Opus; a named Sonnet is kept, Haiku never', async () => {
|
||||||
|
expect(decide({ subagentType: 'test-designer', prompt: 'Write the test plan', respectExplicit: false })).toEqual({ kind: 'fixed', tier: 'opus', reason: 'test-designer default' })
|
||||||
|
expect(decide({ subagentType: 'test-designer', named: 'sonnet', prompt: 'x', respectExplicit: false }).kind).toBe('fixed')
|
||||||
|
expect(decide({ subagentType: 'test-designer', named: 'haiku', prompt: 'find x', respectExplicit: false })).toEqual({ kind: 'fixed', tier: 'opus', reason: 'test-designer default' })
|
||||||
|
// a design clone path is no dev clone: a non-dev role, so never verified as dev work (0.5.1: was no role)
|
||||||
|
expect(parseBrief('Clone: /home/homelab/projects/goodwe/clones/EV-15-design').role).toBe('other')
|
||||||
|
})
|
||||||
|
|
||||||
|
test('pipeline: the verifier is told to check every T-id and N-id of the test plan', async ($, on) => {
|
||||||
|
const w = fresh()
|
||||||
|
w.diffs = ['diff --git a/x.py']
|
||||||
|
const clock = world(on, w)
|
||||||
|
const r = await $.agent.spawn({ prompt: devBrief('\n## Test plan\n| T1 | boundary | batteries above house | no alarm | yes |'), description: 'ev15' } as never)
|
||||||
|
await finish($, clock, r.agentId as string)
|
||||||
|
expect(w.verifierSystems[0]).toContain('every T-id must be implemented')
|
||||||
|
expect(w.verifierPrompts[0]).toContain('## Test plan')
|
||||||
|
})
|
||||||
|
|
||||||
|
// ---------- non-dev roles end to end (#7, EV-05) ----------
|
||||||
|
|
||||||
|
test('#7 acceptance: the test designer gets no line, also after a resume; the real dev gets T1 and a verdict', async ($, on) => {
|
||||||
|
const w = fresh()
|
||||||
|
w.diffs = ['diff --git a/ev.py']
|
||||||
|
const clock = world(on, w)
|
||||||
|
// the mock git answers in DEV only: the designer names that clone, so a misread would diff it
|
||||||
|
const d = await $.agent.spawn({ prompt: designBrief(DEV), description: 'EV-05 test design', model: 'opus' } as never)
|
||||||
|
expect(w.spawned[0]?.model).toBe('opus')
|
||||||
|
await finish($, clock, d.agentId as string, 'claude-opus-5-5')
|
||||||
|
await resume($, d.agentId as string, 'Add a case for a missing meter.')
|
||||||
|
await finish($, clock, d.agentId as string, 'claude-opus-5-5')
|
||||||
|
expect(w.all).toEqual([])
|
||||||
|
expect(w.verifier).toEqual([])
|
||||||
|
|
||||||
|
const dev = await $.agent.spawn({
|
||||||
|
prompt: `Pipeline-Role: dev\nClone: ${DEV} (Role: dev)\nBase branch: release/1.0.\nEV-05: add the meter staleness check as specified.`,
|
||||||
|
description: 'EV-05 dev',
|
||||||
|
} as never)
|
||||||
|
expect(w.spawned[1]?.model).toBe('sonnet')
|
||||||
|
await finish($, clock, dev.agentId as string, 'claude-sonnet-5-5')
|
||||||
|
expect(w.all[0]).toBe('[model-router] T1 verifying on Opus...')
|
||||||
|
expect(w.all[1]).toContain('PASS from verifier opus')
|
||||||
|
expect(w.all.length).toBe(2)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('#7: a test-designer agent type that only names the dev clone is no dev either', async ($, on) => {
|
||||||
|
const w = fresh()
|
||||||
|
w.diffs = ['diff']
|
||||||
|
const clock = world(on, w)
|
||||||
|
const d = await $.agent.spawn({ prompt: `Write the tests for the work in ${DEV}/.`, description: 'design', subagentType: 'test-designer', model: 'haiku' } as never)
|
||||||
|
expect(w.spawned[0]?.model).toBe('opus') // never Haiku
|
||||||
|
await finish($, clock, d.agentId as string, 'claude-opus-5-5')
|
||||||
|
expect(w.all).toEqual([])
|
||||||
|
expect(w.verifier).toEqual([])
|
||||||
|
const log = (await $.command.run({ command: 'router', args: '' } as never)).text ?? ''
|
||||||
|
expect(log).toContain('A1')
|
||||||
|
expect(log).toContain('A1 test-designer opus')
|
||||||
|
expect(log).not.toMatch(/\bother\b/)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('#7: an unnamed test designer runs on opus, unverified', async ($, on) => {
|
||||||
|
const w = fresh()
|
||||||
|
w.diffs = ['diff']
|
||||||
|
const clock = world(on, w)
|
||||||
|
const d = await $.agent.spawn({ prompt: designBrief(), description: 'EV-05 test design' } as never)
|
||||||
|
expect(w.spawned[0]?.model).toBe('opus')
|
||||||
|
await finish($, clock, d.agentId as string, 'claude-sonnet-5-5')
|
||||||
|
expect(w.all).toEqual([])
|
||||||
|
expect(w.verifier).toEqual([])
|
||||||
|
})
|
||||||
|
|
||||||
|
test('#7: a test designer is no saving and gets an A number; the log shows its role', async ($, on) => {
|
||||||
|
const w = fresh()
|
||||||
|
const clock = world(on, w)
|
||||||
|
const d = await $.agent.spawn({ prompt: designBrief(), description: 'EV-05 test design', model: 'opus' } as never)
|
||||||
|
await finish($, clock, d.agentId as string, 'claude-opus-5-5')
|
||||||
|
const savings = (await $.command.run({ command: 'router', args: 'savings' } as never)).text ?? ''
|
||||||
|
expect(savings).toBe('savings: no agent runs recorded yet.')
|
||||||
|
const log = (await $.command.run({ command: 'router', args: '' } as never)).text ?? ''
|
||||||
|
expect(log).toContain('A1')
|
||||||
|
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')
|
||||||
|
})
|
||||||
|
|||||||
Reference in New Issue
Block a user