// Pure routing logic: no `$`, so every rule here is unit-tested. export type Tier = 'haiku' | 'sonnet' | 'opus' | 'fable' /** `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 rank = (t: Tier) => TIERS.indexOf(t) export const asTier = (s: string | undefined): Tier | undefined => { if (!s) return undefined const lower = s.toLowerCase() return TIERS.find(t => lower.includes(t)) } export const parsePatterns = (csv: string): string[] => csv .split(',') .map(s => s.trim().toLowerCase()) .filter(s => s.length > 0) /** The first safety pattern the text mentions, or undefined. */ export const safetyHit = (text: string, patterns: readonly string[]): string | undefined => { const lower = text.toLowerCase() return patterns.find(p => lower.includes(p)) } // ---------- the brief ---------- export type Brief = { clone?: string ticket?: string role?: Role /** The role as the brief wrote it (`test-design`), when it is not dev, review or test. */ roleName?: string baseBranch?: string /** Several clone paths and no `Clone:` line: the role cannot be told. */ isAmbiguous?: boolean } // 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]+)*?' // 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') // The explicit line every brief carries: `Clone: ` with an optional `(Role: dev)`. 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 = /\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(/\/+$/, '') /** * Reads the clone path, ticket, role and base branch out of a brief. * * The role: `Pipeline-Role:` first, then `(Role: ...)` on the `Clone:` line, * then the role in the clone's folder name. A role other than dev, review or * 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 => { const b = prompt.match(BASE) // a sentence's full stop or a trailing slash is no part of the branch const baseBranch = b?.[1]?.replace(/[./-]+$/, '') const header = asRole(prompt.match(PIPELINE_ROLE)?.[1]) const line = prompt.match(CLONE_LINE) if (line?.[1]) { const clone = trimPath(line[1]) const fromPath = clone.match(CLONE_PATH) const stated = header.role ? header : line[2] ? asRole(line[2]) : asRole(fromPath?.[3]) // 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] ?? '')))] if (paths.length > 1) return { baseBranch, isAmbiguous: true } const only = paths[0]?.match(CLONE_PATH) if (!only) return { ...header, baseBranch } return { clone: trimPath(only[1] ?? ''), ticket: only[2], ...(header.role ? header : asRole(only[3])), baseBranch } } // ---------- routing ---------- const READ_ONLY_TYPES = /^(explore|scout|runner|claude-code-guide|statusline-setup)$|:(scout|runner)$/i // Light work, only for tasks outside the dev/review/test roles. No bare // "docs" or "run tests": both appear in nearly every brief. const LIGHT = [ /\b(find|locate|grep|where is|which (files|modules)|summari[sz]e|read and report)\b/, /\b(fix (a |the )?typo|update (the )?(readme|changelog)|add docstrings?)\b/, /\b(run (the )?(unit )?tests? and report|report (the )?test results)\b/, ] // Opus writes only when the approach itself is still open. Domain words // (control loop, asyncio, RS485) are everywhere in this codebase and say nothing. const HEAVY = [ /\b(design|architect|redesign|decide (how|whether)|propose an approach|trade-?offs?)\b/, /\b(root cause|unclear why|no idea why|investigate why|figure out why|intermittent|flaky)\b/, ] export type Route = { tier: Tier; reason: string } // Standing text that tools add to every brief (pipeline-guard's constraints block): // it says how to work, not what the task is, so it never picks a model (#9). const BOILERPLATE_HEADING = /^(standing constraints?|constraints|house rules|rules|pipeline[- ]guard\b.*)\b/i const HEADING = /^(#{1,6})[ \t]+(.*?)[ \t#]*$/ /** * The brief without boilerplate sections: a heading named Standing constraints * (or Constraints, Rules, House rules, Pipeline guard ...) and everything under * it, up to the next heading of the same or a higher level. */ export const taskText = (prompt: string): string => { const kept: string[] = [] let skipLevel = 0 for (const line of prompt.split(/\r?\n/)) { const h = line.match(HEADING) if (h) { const level = h[1]!.length if (skipLevel && level <= skipLevel) skipLevel = 0 if (!skipLevel && BOILERPLATE_HEADING.test(h[2]!.replace(/[*_`]/g, '').trim())) { skipLevel = level continue } } if (!skipLevel) kept.push(line) } return kept.join('\n') } /** A clear signal from the text, or undefined (ask the classifier). */ export const heuristic = (subagentType: string | undefined, prompt: string, role?: Role): Route | undefined => { if (!role && subagentType && READ_ONLY_TYPES.test(subagentType)) return { tier: 'haiku', reason: `read-only agent type ${subagentType}` } const task = taskText(prompt) const lower = task.toLowerCase() const heavy = HEAVY.find(r => r.test(lower)) if (heavy) return { tier: 'opus', reason: 'approach still open' } if (role) return undefined // dev briefs never take the light path const light = LIGHT.find(r => r.test(lower)) if (light && task.length < 1500) return { tier: 'haiku', reason: 'light task' } 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 = | { kind: 'fixed'; tier: Tier; reason: string; opusRequested?: boolean } | { kind: 'classify'; opusRequested?: boolean } /** * Who decides the writer's model. * - review and test agents: a named model is kept; unnamed, they run on Opus * (they are the gates, and a test agent's work has no verifier behind it). * - dev agents: always routed; a named Opus is only logged. * - anything else: routed, unless respectExplicit and a model is named. */ export const decide = (args: { role?: Role named?: Tier subagentType?: string prompt: string respectExplicit: boolean isAmbiguous?: boolean /** The role as written, for an `other` role (test-design). */ roleName?: string }): Decision => { 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. if (isAmbiguous) return { kind: 'fixed', tier: named && named !== 'haiku' && named !== 'sonnet' ? named : 'opus', reason: 'several clone paths and no Clone: line' } if (role === 'review' || role === 'test') return named ? { kind: 'fixed', tier: named, reason: `named model kept for ${who} agent` } : { 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' } const opusRequested = role === 'dev' && (named === 'opus' || named === 'fable') const h = heuristic(subagentType, prompt, role) return h ? { kind: 'fixed', ...h, opusRequested } : { kind: 'classify', opusRequested } } // ---------- verification ---------- 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. */ export const skipReason = (rec: { role?: Role; clone?: string; tier: Tier }, ended: string): Skip | undefined => { if (ended !== 'answer') return 'agent-ended' if (rec.role === 'test') return 'test-agent' if (rec.role === 'review') return 'review-agent' if (rec.role === 'other') return 'non-dev-agent' if (!rec.clone) return 'no-clone' if (rank(rec.tier) >= rank('opus')) return 'opus-unverified' return undefined } /** The verifier never runs on the writer's model; below Opus it is Opus. */ export const verifierFor = (writer: Tier): Tier => (rank(writer) >= rank('opus') ? 'sonnet' : 'opus') /** The model a rewrite runs on: one tier up, never the same model. */ export const rewriteTier = (writer: Tier, allowFable: boolean): Tier | undefined => { if (writer === 'haiku') return 'sonnet' if (writer === 'sonnet') return 'opus' if (writer === 'opus' && allowFable) return 'fable' return undefined } export type FailStep = { kind: 'resume' } | { kind: 'new-agent'; tier: Tier } | { kind: 'hand-back' } /** * After the n-th failed verdict in a task's chain: the first resumes the same * agent, the second starts a new agent one model up in the same clone, and * past maxFails (or with no model above) it goes back to the manager. */ export const onFail = (fails: number, writer: Tier, maxFails: number, allowFable: boolean): FailStep => { if (fails > maxFails) return { kind: 'hand-back' } if (fails === 1) return { kind: 'resume' } const up = rewriteTier(writer, allowFable) return up ? { kind: 'new-agent', tier: up } : { kind: 'hand-back' } } export type Verdict = { pass: boolean; issues: string[]; brief: string } /** A verifier reply: a verdict that could be read, or the reason it could not. */ export type Reading = ({ isReadable: true } & Verdict) | { isReadable: false; preview: string } /** A JSON object with a PASS or FAIL verdict, or undefined. */ const asVerdict = (json: string): Verdict | undefined => { let v: unknown try { v = JSON.parse(json) } catch { return undefined } if (!v || typeof v !== 'object' || Array.isArray(v)) return undefined const o = v as { verdict?: unknown; issues?: unknown; rewrite_brief?: unknown } const word = typeof o.verdict === 'string' ? o.verdict.trim().toUpperCase() : '' if (word !== 'PASS' && word !== 'FAIL') return undefined return { pass: word === 'PASS', issues: Array.isArray(o.issues) ? o.issues.map(String) : [], brief: typeof o.rewrite_brief === 'string' ? o.rewrite_brief : '', } } /** * Every balanced {...} in the text, in order of where it starts. Braces inside * JSON strings do not count, so `"a } b"` stays inside its object. */ export const balancedObjects = (text: string): string[] => { const found: string[] = [] for (let start = text.indexOf('{'); start !== -1; start = text.indexOf('{', start + 1)) { let depth = 0 let isInString = false for (let i = start; i < text.length; i++) { const ch = text[i] if (isInString) { if (ch === '\\') i++ else if (ch === '"') isInString = false continue } if (ch === '"') isInString = true else if (ch === '{') depth++ else if (ch === '}' && --depth === 0) { found.push(text.slice(start, i + 1)) break } } } return found } const FENCE = /```[ \t]*(?:json)?[ \t]*\r?\n([\s\S]*?)```/gi /** * Reads the verifier's reply, tolerating prose before and after: a fenced * ```json block first, then the first balanced {...} that parses and has a * PASS or FAIL verdict. Anything else is unreadable, which is not a FAIL. */ export const parseVerdict = (text: string): Reading => { for (const m of text.matchAll(FENCE)) { const body = m[1] ?? '' const v = asVerdict(body.trim()) ?? balancedObjects(body).map(asVerdict).find(Boolean) if (v) return { isReadable: true, ...v } } for (const candidate of balancedObjects(text)) { const v = asVerdict(candidate) if (v) return { isReadable: true, ...v } } return { isReadable: false, preview: text.slice(0, 300) } } // At the start of any line: hooks such as pipeline-guard put header lines above it (#11). export const REWRITE_MARK = /^[ \t>*-]*\[router-rewrite (T\d+)\][ \t]*/m /** * The prompt for a router rewrite: lines a hook put above the marker stay on * top (once: lines the stored prompt already has are dropped), the stored * prompt with the FAIL issues follows, and text after the marker is guidance. */ export const rewritePrompt = (given: string, stored: string): string => { const m = given.match(REWRITE_MARK) if (!m || m.index === undefined) return stored const has = new Set(stored.split('\n').map(l => l.trim()).filter(Boolean)) const header = given .slice(0, m.index) .split('\n') .filter(l => l.trim() && !has.has(l.trim())) .join('\n') const extra = given.slice(m.index + m[0].length).trim() return [header, stored, extra ? `Additional guidance from the orchestrator:\n${extra}` : ''].filter(Boolean).join('\n\n') } export const clip = (s: string, n: number) => s.length <= n ? s : s.slice(0, n) + `\n... [${s.length - n} more characters cut]` /** A usable test time limit in seconds: anything not a positive number is the default. */ export function validTimeout(raw: unknown): number { const n = Number(raw) return Number.isFinite(n) && n >= 1 ? Math.round(n) : 1800 } // ---------- the hand-back line (TOOL-12) ---------- const LABEL: Record = { haiku: 'Haiku', sonnet: 'Sonnet', opus: 'Opus', fable: 'Fable' } /** * The model a run actually used, from the model id its end reports; the * routing choice only when the run reported none. */ export const ranTier = (reportedModel: string | undefined, routed: Tier): { tier: Tier; isMismatch: boolean } => { const seen = asTier(reportedModel) return seen ? { tier: seen, isMismatch: seen !== routed } : { tier: routed, isMismatch: false } } /** * The one line every dev hand-back gets at once, so silence never stands for * both "still verifying" and "will never verify". Undefined: no line (not a dev). */ export const handBackLine = (args: { taskId: string role?: Role ran: Tier routed: Tier skip?: Skip ended: string }): string | undefined => { const { taskId, role, ran, routed, skip, ended } = args if (role !== 'dev') return undefined const note = ran !== routed ? ` (routed to ${LABEL[routed]}, ran on ${LABEL[ran]})` : '' const head = `[model-router] ${taskId}` if (!skip) return `${head} verifying on ${LABEL[verifierFor(ran)]}...${note}` if (skip === 'opus-unverified') return `${head} no verification: dev ran on ${LABEL[ran]}. Go straight to review.${note}` if (skip === 'agent-ended') return `${head} no verification: the dev run ended without an answer (${ended}).${note}` if (skip === 'no-clone') return `${head} no verification: the brief names no clone path.${note}` return undefined } // ---------- interim stops vs the hand-back (TOOL-12 follow-up) ---------- /** An agent's loop status, as `$.agent.list()` reports it. */ export type LoopStatus = 'pending' | 'running' | 'waiting' | 'idle' | 'completed' | 'failed' | 'killed' /** * What a turn's end means for the agent, read from its status afterwards. * - `handback`: its run ended (completed, failed, killed), or the engine * already dropped it from the list: the report went back to its spawner. * - `interim`: it is held on its own background work (`waiting`), between * turns (`idle`), or already in its next turn (`running`, `pending`). */ export const turnEndKind = (status: LoopStatus | undefined): 'handback' | 'interim' => status === undefined || status === 'completed' || status === 'failed' || status === 'killed' ? 'handback' : 'interim' /** * How long an agent may stay `idle` before that counts as its hand-back (#12). * `idle` waits for a message, not on its own work (that is `waiting`): one that * stays idle has stopped and waits for the manager. A moment idle between turns * is not a hand-back. */ export const IDLE_HANDBACK_MS = 2 * 60 * 1000 /** How often an interim agent's status is checked again, and for how long at most. */ export const WATCH_EVERY_MS = 15_000 export const WATCH_FOR_MS = 24 * 60 * 60 * 1000 // ---------- 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 }