Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

Swarm routing phase 1: strong models for hard tasks, quota that fits the task (#1501)

0xken153eda06c1c83f
diff --git a/backend/src/superTabs/commands.test.ts b/backend/src/superTabs/commands.test.ts
index b983bc3ff..126e67ea1 100644
--- a/backend/src/superTabs/commands.test.ts
+++ b/backend/src/superTabs/commands.test.ts
@@ -249,10 +249,13 @@ describe('agent.start on the Swarm\'s listed machines', () => {
expect(f.state.starts ?? []).toEqual([])
})
- it('lets an agent start on the Lead\'s own machine, where an agent of the Swarm runs', () => {
- const f = fixture(), lead = f.add('lead', 'owner', 'lead', true), group = f.group()
+ // A new Lead may be only Claude or Codex, but on any machine: adding it is what lists that machine.
+ it.each(['claude', 'codex'])('lists the machine a %s Lead is added on, so the Lead may start agents there', engine => {
+ const f = fixture()
+ const lead = f.run({ type: 'agent.add', conversationId: 'lead', machineId: 'lead-machine', harnessId: 'lead', name: 'Lead',
+ configuration: { ...config, engine }, lead: true }, owner, { contribution: { machineOwnerId: 'host-owner', contributorId: 'owner' } }).result.agentId as string
const actor: Actor = { kind: 'agent', agentId: lead, machineOwnerId: 'host-owner' }
- f.run({ type: 'agent.start', request: request(group, 'host') }, actor, { contribution: grant })
+ f.run({ type: 'agent.start', request: request(f.group(), 'lead-machine') }, actor, { contribution: grant })
expect(f.state.starts).toHaveLength(1)
})
@@ -335,6 +338,20 @@ describe('route.record and route.override', () => {
expect(() => run(record({ context }))).toThrow()
}
})
+ it('keeps the size and each candidate\'s quota fit, and still takes a record without them', () => {
+ const f = routed()
+ const run = (decision: unknown) => f.run({ type: 'route.record', conversationId: 'lead', decision } as Command, f.leadActor, { recentRoutes: 0 })
+ const fit = { status: 'short', coverage: -0.2, effectiveCost: 1.5, expiring: 0, spend: { '5-hour': 45, weekly: 6 }, account: 'remote-1:codex' }
+ const sized = (size: unknown, patch: Record<string, unknown> = {}) => record({ assessment: { difficulty: 'high', risk: 'low', why: 'Schema change.', size },
+ candidates: [candidate('c0', { fit: { ...fit, ...patch } }), candidate('c1', { model: 'sonnet', quality: 2, cost: 2, fit: { status: 'unknown', coverage: null, effectiveCost: 2, expiring: 0, spend: {} } })] })
+ expect(run(sized('large')).routeDecisions[0]).toMatchObject({ record: { assessment: { size: 'large' }, candidates: [{ fit }, { fit: { status: 'unknown', coverage: null } }] } })
+ expect(run(record()).routeDecisions[0]).toMatchObject({ record: { pick: 'c0' } })
+ expect(() => run(sized('huge'))).toThrow()
+ for (const patch of [{ status: 'maybe' }, { coverage: Infinity }, { effectiveCost: -1 }, { expiring: -1 }, { spend: { daily: 1 } },
+ { spend: { weekly: -1 } }, { account: '' }, { extra: 1 }]) {
+ expect(() => run(sized('small', patch))).toThrow()
+ }
+ })
it('refuses a pick outside the candidates, a non-lead agent and a busy hour', () => {
const f = routed()
const route = (decision: unknown, actor: Actor, context: Partial<CommandContext>) =>
diff --git a/backend/src/superTabs/routeRecord.ts b/backend/src/superTabs/routeRecord.ts
index ed2d02d7a..9b6fd21df 100644
--- a/backend/src/superTabs/routeRecord.ts
+++ b/backend/src/superTabs/routeRecord.ts
@@ -4,6 +4,18 @@ import { z } from 'zod'
const level = z.enum(['low', 'medium', 'high'])
const candidateId = z.string().regex(/^c\d{1,2}$/)
const machine = z.string().min(1).max(160).regex(/^[A-Za-z0-9_-]+$/)
+const amount = z.number().finite().nonnegative()
+/** How the candidate's quota fits the task (phase 1 routing), kept so committed spend and pick quality can be read back. */
+const fit = z.object({
+ status: z.enum(['fits', 'unknown', 'short']),
+ /** Usable over needed on the tightest window; negative when committed spend already exceeds what is left. */
+ coverage: z.number().finite().nullable(),
+ effectiveCost: amount,
+ expiring: amount,
+ spend: z.object({ '5-hour': amount.optional(), weekly: amount.optional() }).strict(),
+ /** The hashed usage key, or `machineId:engine` when the machine reports none. */
+ account: z.string().min(1).max(200).optional(),
+}).strict()
export const routeCandidateSchema = z.object({
id: candidateId,
kind: z.enum(['member', 'new']),
@@ -18,9 +30,11 @@ export const routeCandidateSchema = z.object({
title: z.string().trim().min(1).max(160),
/** The criterion line Jev was shown. */
label: z.string().trim().min(1).max(640),
+ fit: fit.optional(),
}).strict().refine(c => (c.kind === 'member') === !!c.agentId, 'Members name their agent; new agents do not.')
export const routeRecordSchema = z.object({
- assessment: z.object({ difficulty: level, risk: level, why: z.string().trim().min(1).max(300) }).strict(),
+ assessment: z.object({ difficulty: level, risk: level, why: z.string().trim().min(1).max(300),
+ size: z.enum(['small', 'medium', 'large']).optional() }).strict(),
candidates: z.array(routeCandidateSchema).min(1).max(12),
excluded: z.array(z.object({ title: z.string().trim().min(1).max(160), reason: z.string().trim().min(1).max(500) }).strict()).max(200),
floor: z.number().int().min(1).max(3),
diff --git a/cli/src/superTabs/host.ts b/cli/src/superTabs/host.ts
index 009ff6efb..8c4eedf4b 100644
--- a/cli/src/superTabs/host.ts
+++ b/cli/src/superTabs/host.ts
@@ -437,7 +437,7 @@ export class SuperTabHost {
return `You are participating in a shared Super Tab conversation (${group}). Other humans and agents see messages posted there.\n`
+ `Read its state: ${command} status\nRead this conversation: ${command} messages ${shellQuote(group)}\n`
+ `Reply there: ${command} post ${shellQuote(group)} 'your message' UNIQUE_OPERATION_ID --reply-to ${shellQuote(String(message.id))}\n`
- + `Manage agreed work and delegation: ${command} help. Leads: route before starting or assigning: ${command} route GROUP JSON. Use independently verifiable outcomes; local helper subagents need no separate group.\n`
+ + `Manage agreed work and delegation: ${command} help. Leads: route before starting or assigning: ${command} route GROUP JSON. Use independently verifiable outcomes. Leads coordinate: multi-part work or work over about 15 minutes goes to Swarm agents in groups; a Lead does only small work itself and uses its own subagents only to read and look things up.\n`
+ `Ask questions and post results in this conversation. ${SUPER_TAB_REPLY_STYLE} Replies to these delivered instructions must be posted here explicitly.\n\n`
+ native + reply + `Message ${String(message.id)} from ${String(object(message.author).name ?? 'a collaborator')}:\n${message.text}`
+ (files ? `${message.text ? '\n\n' : ''}${files}` : '')
diff --git a/cli/src/superTabs/route.spec.ts b/cli/src/superTabs/route.spec.ts
index 31034f3a2..c1634ee95 100644
--- a/cli/src/superTabs/route.spec.ts
+++ b/cli/src/superTabs/route.spec.ts
@@ -1,7 +1,7 @@
// cli/src/superTabs/route.spec.ts
import { createHash } from 'node:crypto'
import { describe, expect, it } from 'vitest'
-import { choose, contextSize, decide, floorFor, jevQuestion, parseAssessment, quotaOf2, rateFor, recordOf, repoMatch, scrub, type Assessment, type MemberFrame, type Policy, type Probe, type TaskFolder } from './route.js'
+import { choose, contextSize, decide, floorFor, jevQuestion, parseAssessment, quotaOf2, rateFor, recordOf, repoMatch, scrub, type Assessment, type Commitment, type MemberFrame, type Policy, type Probe, type TaskFolder } from './route.js'
const policy: Policy = { version: 1, floor: { low: 1, medium: 2, high: 3 }, quotaReserve: 10, notes: 'Frontend prefers Claude.', models: [
{ engine: 'claude', model: 'opus', effort: 'high', quality: 3, cost: 3, enabled: true },
@@ -9,14 +9,25 @@ const policy: Policy = { version: 1, floor: { low: 1, medium: 2, high: 3 }, quot
{ engine: 'claude', model: 'sonnet', effort: 'medium', quality: 2, cost: 2, enabled: true },
{ engine: 'claude', model: 'haiku', effort: 'auto', quality: 1, cost: 1, enabled: false },
] }
-const a = (patch: Partial<Assessment> = {}): Assessment => ({ difficulty: 'medium', risk: 'low', why: 'API change.', needs: { tools: [], devices: [] }, ...patch })
+const a = (patch: Partial<Assessment> = {}): Assessment => ({ difficulty: 'medium', risk: 'low', size: 'medium', why: 'API change.', needs: { tools: [], devices: [] }, ...patch })
const probe = (patch: Partial<Probe> = {}): Probe => ({ kind: 'new', machineId: 'm1', machineName: 'remote-1', engine: 'claude', model: 'sonnet',
effort: 'medium', quality: 2, cost: 2, quota: { known: true, leftPercent: 50, resetsAt: 1_000 }, activity: 'new', known: true, refusals: [], ...patch })
+const NOW = 1_000_000_000, M = 60_000, H = 3_600_000, D = 86_400_000
+/** A reading with a 5-hour and a weekly window, each as [percent left, resets in] (either may be missing). */
+type Win = [left: number, resetsIn: number | null] | null
+const windows = (five: Win, week: Win, account?: string): Probe['quota'] => {
+ const read = ([['5-hour', five], ['weekly', week]] as const).flatMap(([name, w]) => w ? [{ name, leftPercent: w[0], resetsAt: w[1] === null ? null : NOW + w[1] }] : [])
+ return { known: true, leftPercent: Math.min(...read.map(w => w.leftPercent)), resetsAt: null, windows: read, ...(account ? { account } : {}) }
+}
+const ok = (r: ReturnType<typeof choose>) => { if ('error' in r) throw new Error('x'); return r }
+
describe('assessment and floor', () => {
it('parses a Lead assessment and explains what is wrong', () => {
- expect(parseAssessment({ difficulty: 'high', risk: 'low', why: ' Schema. ', needs: { tools: ['git'] } }))
- .toEqual({ difficulty: 'high', risk: 'low', why: 'Schema.', needs: { tools: ['git'], devices: [] } })
+ expect(parseAssessment({ difficulty: 'high', risk: 'low', size: 'large', why: ' Schema. ', needs: { tools: ['git'] } }))
+ .toEqual({ difficulty: 'high', risk: 'low', size: 'large', why: 'Schema.', needs: { tools: ['git'], devices: [] } })
+ expect(parseAssessment({ difficulty: 'high', risk: 'low', size: 'huge', why: 'x' })).toContain('size')
+ expect(parseAssessment({ difficulty: 'high', risk: 'low', size: 'toString', why: 'x' })).toContain('size')
expect(parseAssessment({ difficulty: 'hard', risk: 'low', why: 'x' })).toContain('difficulty')
expect(parseAssessment({ difficulty: 'low', risk: 'low', why: 'x'.repeat(301) })).toContain('300')
expect(parseAssessment({ difficulty: 'low', risk: 'low', why: 'x', needs: { cwd: 'relative' } })).toContain('absolute')
@@ -37,6 +48,10 @@ describe('quota and rates', () => {
expect(quotaOf2({ known: true, windows: [{ usedPercent: 10, resetsAt: 1_800_000_000_000 }] }).resetsAt).toBe(1_800_000_000_000)
expect(quotaOf2({ known: true, windows: [{ usedPercent: 10, resetsAt: 'soon' }] }).resetsAt).toBeNull()
expect(quotaOf2({ known: false, windows: [] })).toEqual({ known: false, leftPercent: null, resetsAt: null })
+ // The reading's account key goes with it, read or not, so models on one subscription share it.
+ expect(quotaOf2({ known: false, windows: [], account: 'k1' })).toEqual({ known: false, leftPercent: null, resetsAt: null, account: 'k1' })
+ expect(quotaOf2({ known: true, windows: [{ usedPercent: 10, resetsAt: null }], account: 'k1' }).account).toBe('k1')
+ expect(quotaOf2({ known: true, windows: [{ usedPercent: 10, resetsAt: null }], account: null })).not.toHaveProperty('account')
})
it('rates a member by its policy row, then by model, else conservatively', () => {
expect(rateFor(policy, 'claude', 'opus', 'high')).toEqual({ quality: 3, cost: 3 })
@@ -50,37 +65,37 @@ describe('choose', () => {
expect(choose([probe({ refusals: ['Machine is offline.'] })], policy, a())).toEqual({ error: 'NO_CANDIDATE',
excluded: [{ title: 'New agent · Claude sonnet medium · remote-1', reason: 'Machine is offline.' }] })
})
- it('shows only floor-meeting candidates, ordered by cost, quota, reset and member first', () => {
+ it('shows only floor-meeting candidates, ordered by effective cost, quality, room on the tightest window, member first', () => {
const r = choose([
- probe({ model: 'opus', effort: 'high', quality: 3, cost: 3 }),
- probe({ machineId: 'm2', machineName: 'mac', quota: { known: true, leftPercent: 80, resetsAt: 5_000 } }),
- probe({ quota: { known: true, leftPercent: 80, resetsAt: 2_000 } }),
- probe({ kind: 'member', agentId: 'a1', name: 'Multiply', quota: { known: true, leftPercent: 80, resetsAt: 2_000 }, activity: 'idle' }),
+ probe({ model: 'opus', effort: 'high', quality: 3, cost: 3, quota: windows([80, 3 * H], [90, 5 * D]) }),
+ probe({ machineId: 'm2', machineName: 'mac', quota: windows([80, 3 * H], [90, 5 * D], 'B') }),
+ probe({ quota: windows([60, 3 * H], [90, 5 * D]) }),
+ probe({ kind: 'member', agentId: 'a1', name: 'Multiply', quota: windows([60, 3 * H], [90, 5 * D]), activity: 'idle' }),
+ probe({ kind: 'member', agentId: 'a2', name: 'Elsewhere', repo: 'different', quota: windows([60, 3 * H], [90, 5 * D]), activity: 'idle' }),
probe({ model: 'haiku', effort: 'auto', quality: 1, cost: 1 }),
- probe(),
- ], policy, a())
+ ], policy, a(), NOW)
if ('error' in r) throw new Error('unexpected')
expect(r.belowFloor).toBe(false)
+ // A member in another repository saves no start, so it ranks as a new agent would.
expect(r.shown.map(s => s.title)).toEqual([
- 'Multiply · Claude sonnet medium · remote-1',
- 'New agent · Claude sonnet medium · remote-1',
'New agent · Claude sonnet medium · mac',
+ 'Multiply · Claude sonnet medium · remote-1',
+ 'Elsewhere · Claude sonnet medium · remote-1',
'New agent · Claude sonnet medium · remote-1',
'New agent · Claude opus high · remote-1',
])
expect(r.shown.map(s => s.id)).toEqual(['c0', 'c1', 'c2', 'c3', 'c4'])
})
- it('marks belowFloor when nobody meets it, keeps the quota reserve, and prefers known candidates', () => {
- const r = choose([probe({ quality: 1 }), probe({ quality: 1, quota: { known: true, leftPercent: 5, resetsAt: null } })], policy, a({ difficulty: 'high' }))
- if ('error' in r) throw new Error('unexpected')
+ it('marks belowFloor when nobody meets it, and shows those that fit before the unknown and the short', () => {
+ const r = ok(choose([probe({ quality: 1 }), probe({ quality: 1, machineName: 'mac', quota: windows([90, null], [90, null]) })], policy, a({ difficulty: 'high' }), NOW))
expect(r.belowFloor).toBe(true)
- expect(r.shown).toHaveLength(1)
- const onlyReserve = choose([probe({ quota: { known: true, leftPercent: 5, resetsAt: null } })], policy, a())
- if ('error' in onlyReserve) throw new Error('unexpected')
- expect(onlyReserve.shown).toHaveLength(1)
- const unknown = choose([probe({ known: false, quota: { known: false, leftPercent: null, resetsAt: null } }), probe()], policy, a())
- if ('error' in unknown) throw new Error('unexpected')
- expect(unknown.shown.map(s => s.known)).toEqual([true])
+ expect(r.shown.map(s => s.fit.status)).toEqual(['fits'])
+ expect(r.excluded).toEqual([{ title: 'New agent · Claude sonnet medium · remote-1', reason: 'Its quota could not be read in full, and another candidate\'s quota fits this task.' }])
+ // Under the reserve is short, and goes after a candidate that is only partly known.
+ const reserve = ok(choose([probe({ quota: windows([10, null], [90, null]) }), probe({ machineName: 'mac', quota: windows([90, null], null) })], policy, a(), NOW))
+ expect(reserve.shown.map(s => [s.machineName, s.fit.status])).toEqual([['mac', 'unknown']])
+ expect(reserve.excluded[0].reason).toBe('The 5-hour window is expected to run out right away.')
+ expect(reserve.short).toBeUndefined()
})
it('shows at most 12 candidates', () => {
const r = choose(Array.from({ length: 20 }, (_, i) => probe({ machineId: `m${i}`, machineName: `box-${String(i).padStart(2, '0')}` })), policy, a())
@@ -89,9 +104,96 @@ describe('choose', () => {
})
})
+/** The phase 1 examples (docs/plans/2026-10-21-swarm-routing-phase1.md), on the default policy with a 10% reserve. */
+describe('strength, fit and effective cost', () => {
+ const defaults: Policy = { ...policy, notes: '', models: policy.models.map(m => ({ ...m, enabled: true })) }
+ const OPUS = { engine: 'claude', model: 'opus', effort: 'high', quality: 3, cost: 3 } as const
+ const SONNET = { engine: 'claude', model: 'sonnet', effort: 'medium', quality: 2, cost: 2 } as const
+ const HAIKU = { engine: 'claude', model: 'haiku', effort: 'auto', quality: 1, cost: 1 } as const
+ const CODEX = { engine: 'codex', model: 'default', effort: 'default', quality: 3, cost: 2 } as const
+ const on = (row: Partial<Probe>, machine: string, quota: Probe['quota']) => probe({ ...row, machineId: machine, machineName: machine, quota })
+ const route = (probes: Probe[], patch: Partial<Assessment>, now = NOW, open: Commitment[] = []) => ok(choose(probes, defaults, a(patch), now, open))
+ const picks = (r: ReturnType<typeof route>) => r.shown.map(s => `${s.model} on ${s.machineName}`)
+
+ it('1. high, medium: Opus high, though its window resets in 40 minutes, over Sonnet with more left', () => {
+ const r = route([on(OPUS, 'a', windows([70, 40 * M], [80, 5 * D], 'A')), on(SONNET, 'b', windows([90, 3 * H], [80, 5 * D], 'B'))], { difficulty: 'high', size: 'medium' })
+ expect(picks(r)).toEqual(['opus on a'])
+ // Strength filters: the weaker model is neither shown nor excluded.
+ expect(r.excluded).toEqual([])
+ expect(r.shown[0].label).toContain('fits: needs about 30% of the 5-hour window (60% left, resets in 40m, otherwise unused); weekly 6% of 70%')
+ expect(r.shown[0].fit).toEqual({ status: 'fits', coverage: 2, effectiveCost: 0, expiring: 1, spend: { '5-hour': 45, weekly: 6 }, account: 'A' })
+ })
+ it('2. high, large: Codex, because Opus high is expected to run out', () => {
+ const r = route([on(OPUS, 'a', windows([25, 4 * H], [80, 5 * D], 'A')), on(CODEX, 'a', windows([85, 3 * H], [80, 5 * D]))], { difficulty: 'high', size: 'large' })
+ expect(picks(r)).toEqual(['default on a'])
+ expect(r.shown[0].fit.account).toBe('a:codex')
+ expect(r.excluded).toEqual([{ title: 'New agent · Claude opus high · a', reason: 'The 5-hour window is expected to run out about a quarter of the way in; resets in 4h.' }])
+ })
+ it('3. low, small: Haiku on the account whose weekly window has room, not on the one nearly spent for the week', () => {
+ const A = windows([80, 4 * H], [12, 5 * D], 'A'), B = windows([60, 4 * H], [70, 5 * D], 'B')
+ const r = route([OPUS, SONNET, HAIKU].flatMap(row => [on(row, 'a', A), on(row, 'b', B)]), { difficulty: 'low', size: 'small' })
+ expect(picks(r)[0]).toBe('haiku on b')
+ // A's weekly budget is 0.4% a day; Haiku's 0.5% costs it 1 + 1 × 0.5 / 0.4.
+ expect(r.shown.find(s => s.model === 'haiku' && s.machineName === 'a')!.fit.effectiveCost).toBe(2.25)
+ })
+ it('4. low, small: Opus high on the account whose 5-hour window resets in 20 minutes, which would otherwise go unused', () => {
+ const A = windows([60, 20 * M], [60, 2 * D], 'A'), B = windows([90, 4 * H], [80, 5 * D], 'B')
+ const r = route([OPUS, SONNET, HAIKU].flatMap(row => [on(row, 'a', A), on(row, 'b', B)]), { difficulty: 'low', size: 'small' })
+ expect(picks(r).slice(0, 4)).toEqual(['opus on a', 'sonnet on a', 'haiku on a', 'haiku on b'])
+ })
+ it('5. two high, medium routes a minute apart go to two accounts', () => {
+ const probes = [on(OPUS, 'a', windows([60, 3 * H], [80, 5 * D], 'A')), on(OPUS, 'b', windows([58, 3 * H], [80, 5 * D], 'B'))]
+ const first = route(probes, { difficulty: 'high', size: 'medium' })
+ expect(picks(first)[0]).toBe('opus on a')
+ const held: Commitment = { account: first.shown[0].fit.account, spend: first.shown[0].fit.spend, size: 'medium', createdAt: NOW }
+ const second = route(probes, { difficulty: 'high', size: 'medium' }, NOW + M, [held])
+ expect(picks(second)).toEqual(['opus on b'])
+ expect(second.excluded[0]).toMatchObject({ title: 'New agent · Claude opus high · a', reason: expect.stringContaining('expected to run out') })
+ // Once its run time is over a pick holds nothing.
+ expect(picks(route(probes, { difficulty: 'high', size: 'medium' }, NOW + 2 * H, [held]))[0]).toBe('opus on a')
+ })
+ it('6. high, large: a window that resets in an hour needs only the part of the task before the reset', () => {
+ const r = route([on(OPUS, 'a', windows([40, H], [80, 5 * D]))], { difficulty: 'high', size: 'large' })
+ expect(r.shown[0].fit).toMatchObject({ status: 'fits', coverage: 1.2 })
+ expect(r.shown[0].label).toContain('needs about 25% of the 5-hour window')
+ })
+ it('7. high, large: Codex and never Sonnet when every strong candidate is short, and the Lead is told', () => {
+ const r = route([on(OPUS, 'a', windows([30, 4 * H], [80, 5 * D], 'A')), on(CODEX, 'a', windows([40, 4.5 * H], [80, 5 * D])),
+ on(SONNET, 's', windows([95, 4 * H], [80, 5 * D], 'S'))], { difficulty: 'high', size: 'large' })
+ expect(picks(r)).toEqual(['default on a', 'opus on a'])
+ expect(r.shown.map(s => s.fit.status)).toEqual(['short', 'short'])
+ expect(r.short).toBe('No candidate is expected to cover this task; its 5-hour quota is expected to run out partway and resets in 4h30.')
+ })
+ it('8. an assessment without size is taken for medium', () => {
+ const size = parseAssessment({ difficulty: 'high', risk: 'low', why: 'x' }) as Assessment
+ expect(size.size).toBe('medium')
+ expect(ok(choose([on(OPUS, 'a', windows([90, 3 * H], [80, 5 * D]))], defaults, size, NOW)).shown[0].fit.spend).toEqual({ '5-hour': 45, weekly: 6 })
+ })
+ it('reads what a pick holds per window, and leaves the weekly charge to work that is not hard', () => {
+ // A pick logged with only a 5-hour spend holds nothing of the weekly window.
+ const held: Commitment = { account: 'A', spend: { '5-hour': 30 }, size: 'large', createdAt: NOW }
+ const r = route([on(SONNET, 'a', windows([90, 5 * H], [20, 7 * D], 'A'))], { size: 'medium' }, NOW, [held])
+ expect(r.shown[0].fit).toMatchObject({ status: 'fits', coverage: 1.67 })
+ // Weekly use above a day's share costs more, unless the task is hard.
+ expect(r.shown[0].fit.effectiveCost).toBeGreaterThan(2)
+ expect(route([on(SONNET, 'a', windows([90, 5 * H], [20, 7 * D], 'A'))], { difficulty: 'high', size: 'medium' }).shown[0].fit.effectiveCost).toBe(2)
+ // A weekly window with no reset is one day's budget; one with nothing usable is short already, not charged.
+ expect(route([on(SONNET, 'a', windows([90, 5 * H], [20, null]))], {}).shown[0].fit.effectiveCost).toBe(2)
+ const spent = route([on(SONNET, 'a', windows([90, 5 * H], [5, 7 * D]))], {})
+ expect(spent.shown[0].fit).toMatchObject({ status: 'short', effectiveCost: 2 })
+ expect(spent.short).toBe('No candidate is expected to cover this task; its weekly quota is expected to run out partway and resets in 7 days.')
+ })
+ it('orders the short by how far they get, then by the policy order, and says when no reset is known', () => {
+ const r = route([on(SONNET, 'b', windows([25, null], [80, null], 'B')), on(SONNET, 'a', windows([25, null], [80, null], 'A')), on(SONNET, 'c', windows([30, null], [80, null], 'C'))], {})
+ expect(picks(r)).toEqual(['sonnet on c', 'sonnet on a', 'sonnet on b'])
+ expect(r.short).toBe('No candidate is expected to cover this task; its 5-hour quota is expected to run out partway.')
+ expect(r.shown[0].label).toContain('short: needs about 30% of the 5-hour window (20% left); weekly 4% of 70%')
+ expect(route([on(SONNET, 'a', windows(null, [80, null]))], {}).shown[0].label).toContain('unknown: 5-hour window unknown; weekly 4% of 70%')
+ })
+})
+
const base = { title: 'T', brief: '', checks: [] as string[], messages: [] as Array<{ from: string; text: string }> | null, folder: null as TaskFolder | null,
attempts: [] as Array<{ agent: string; outcome: string; result?: string }>, recent: [] as Array<{ title: string; via: string; outcome: string | null }> | null }
-const ok = (r: ReturnType<typeof choose>) => { if ('error' in r) throw new Error('x'); return r }
const frame = (patch: Partial<MemberFrame> = {}): MemberFrame => ({ title: 'Fix auth', project: 'api', cwd: '/w/api', root: '/w/api', remote: 'github.com/acme/api', branch: 'feat/auth', updatedAt: 1_000_000 - 2 * 3_600_000, ...patch })
const folder = (patch: Partial<TaskFolder> = {}): TaskFolder => ({ cwd: '/w/api', kind: 'git', name: 'api', root: '/w/api', remote: 'github.com/acme/api', ...patch })
@@ -125,10 +227,14 @@ describe('Jev context and verdict', () => {
})
it('produces a record the backend schema accepts', () => {
const c = choice(), v = decide(c, { choice: 'c1', probabilities: { c0: 0.2, c1: 0.8 } }, null)
- expect(recordOf(c, v, a(), policy)).toEqual({ assessment: { difficulty: 'medium', risk: 'low', why: 'API change.' },
+ const v1 = { assessment: { difficulty: 'medium', risk: 'low', why: 'API change.' },
candidates: c.shown.map(s => ({ id: s.id, kind: s.kind, ...(s.agentId ? { agentId: s.agentId } : {}), machineId: s.machineId,
engine: s.engine, model: s.model, effort: s.effort, quality: s.quality, cost: s.cost, title: s.title, label: s.label })),
- excluded: [], floor: 2, notes: true, pick: 'c1', via: 'jev', p: 0.8, belowFloor: false, why: v.why })
+ excluded: [], floor: 2, notes: true, pick: 'c1', via: 'jev', p: 0.8, belowFloor: false, why: v.why }
+ expect(recordOf(c, v, a(), policy)).toEqual({ ...v1, assessment: { ...v1.assessment, size: 'medium' },
+ candidates: v1.candidates.map(x => ({ ...x, fit: { status: 'unknown', coverage: null, effectiveCost: 2, expiring: 0, spend: { '5-hour': 30, weekly: 4 }, account: 'm1:claude' } })) })
+ // For a backend from before sizes and fit.
+ expect(recordOf(c, v, a(), policy, undefined, true)).toEqual(v1)
// The policy order says which fallback decided; the other routes carry none.
const order = decide(c, undefined, 'BUSY')
expect(recordOf(c, order, a(), policy)).toMatchObject({ via: 'order', fallback: 'unavailable', why: order.why })
@@ -142,10 +248,10 @@ describe('edges', () => {
expect(parseAssessment({ difficulty: 'low', risk: 'urgent', why: 'x' })).toContain('risk')
expect(parseAssessment({ difficulty: 'low', risk: 'low', why: 7 })).toContain('why')
expect(parseAssessment({ difficulty: 'low', risk: 'low', why: 'x', needs: null }))
- .toEqual({ difficulty: 'low', risk: 'low', why: 'x', needs: { tools: [], devices: [] } })
+ .toEqual({ difficulty: 'low', risk: 'low', size: 'medium', why: 'x', needs: { tools: [], devices: [] } })
expect(parseAssessment({ difficulty: 'low', risk: 'low', why: 'x', needs: { tools: 'git', devices: [1], cwd: 5 } })).toContain('absolute')
expect(parseAssessment({ difficulty: 'low', risk: 'low', why: 'x', needs: { devices: ['cam'], cwd: '/work' } }))
- .toEqual({ difficulty: 'low', risk: 'low', why: 'x', needs: { tools: [], devices: ['cam'], cwd: '/work' } })
+ .toEqual({ difficulty: 'low', risk: 'low', size: 'medium', why: 'x', needs: { tools: [], devices: ['cam'], cwd: '/work' } })
})
it('keeps the tightest window whatever its order and drops an unusable reset', () => {
expect(quotaOf2({ known: true, windows: [{ usedPercent: 70, resetsAt: 1_800_000_000 }, { usedPercent: 20, resetsAt: null }] }))
@@ -175,10 +281,10 @@ describe('edges', () => {
probe({ kind: 'member', agentId: 'a1', quota: { known: true, leftPercent: null, resetsAt: null } }),
probe({ machineName: 'mac', quota: { known: true, leftPercent: 40, resetsAt: null } }),
], policy, a()))
- expect(r.shown.map(s => s.title)).toEqual(['New agent · Claude sonnet medium · mac', 'Member · Claude sonnet medium · remote-1'])
- expect(r.shown[1].label).toContain('Member ·')
- expect(r.shown[1].label).toContain('quota unknown')
- expect(r.shown[0].label).toContain('quota 40% left')
+ expect(r.shown.map(s => s.title)).toEqual(['Member · Claude sonnet medium · remote-1', 'New agent · Claude sonnet medium · mac'])
+ expect(r.shown[0].label).toContain('Member ·')
+ expect(r.shown[0].label).toContain('quota unknown')
+ expect(r.shown[1].label).toContain('quota 40% left')
expect(ok(choose([probe({ known: false, quota: unknownQuota })], policy, a())).shown[0].label).toContain('quota unknown')
expect(ok(choose([probe({ quota: { known: true, leftPercent: 50, resetsAt: 0 } })], policy, a())).shown[0].label).toContain('resets in 1m')
})
@@ -186,6 +292,8 @@ describe('edges', () => {
const label = (resetsAt: number) => ok(choose([probe({ quota: { known: true, leftPercent: 50, resetsAt } })], policy, a(), 1_000_000)).shown[0].label
expect(label(1_000_000 + 30 * 60_000)).toContain('quota 50% left, resets in 30m')
expect(label(1_000_000 + 2 * 3_600_000)).toContain('resets in 2h')
+ expect(label(1_000_000 + 4.5 * 3_600_000)).toContain('resets in 4h30')
+ expect(label(1_000_000 + 20 * 3_600_000)).toContain('resets in 20h')
expect(label(1_000_000 + 5 * 86_400_000)).toContain('resets in 5 days')
expect(label(1_000_000 - 5_000)).toContain('resets in 1m')
// Without a clock argument it reads the real one.
diff --git a/cli/src/superTabs/route.ts b/cli/src/superTabs/route.ts
index 5d4838279..db6ec4c12 100644
--- a/cli/src/superTabs/route.ts
+++ b/cli/src/superTabs/route.ts
@@ -1,4 +1,5 @@
-/** Super Tab routing v1, the pure half (docs/superpowers/specs/2026-10-19-super-tab-routing-v1-design.md).
+/** Super Tab routing v1, the pure half (docs/superpowers/specs/2026-10-19-super-tab-routing-v1-design.md), ordered by
+ * strength, quota fit and effective cost since phase 1 (docs/plans/2026-10-21-swarm-routing-phase1.md).
* The system removes what cannot run the task, Jev chooses among the rest with the full context, and a
* fixed policy order decides when Jev is unsure or unavailable. Jev's acceptance rule is the voice
* router's (`jevPick`), tuned on the owner's desk on 2026-10-10. */
@@ -8,13 +9,15 @@ import { claudeAliasForModel } from '../engines/claude/runtimeProfile.js'
import { jevPick } from '../lib/routeDecide.js'
export type Level = 'low' | 'medium' | 'high'
-export interface Assessment { difficulty: Level; risk: Level; why: string; needs: { tools: string[]; devices: string[]; cwd?: string } }
+export type Size = 'small' | 'medium' | 'large'
+export interface Assessment { difficulty: Level; risk: Level; size: Size; why: string; needs: { tools: string[]; devices: string[]; cwd?: string } }
export interface PolicyModel { engine: 'claude' | 'codex'; model: string; effort: string; quality: number; cost: number; enabled: boolean }
export interface Policy { version: 1; models: PolicyModel[]; floor: Record<Level, number>; quotaReserve: number; notes: string }
/** One usage window, named by the reader (`5-hour`, `weekly`); `leftPercent` is what remains of it. */
export interface QuotaWindow { name: string | null; leftPercent: number; resetsAt: number | null }
-/** `leftPercent` and `resetsAt` are the tightest window's, which ranks candidates; `windows` is every window, for Jev. */
-export interface Quota { known: boolean; leftPercent: number | null; resetsAt: number | null; windows?: QuotaWindow[] }
+/** `leftPercent` and `resetsAt` are the tightest window's; `windows` is every window. `account` is the reading's hashed
+ * account key, which models on one subscription share. */
+export interface Quota { known: boolean; leftPercent: number | null; resetsAt: number | null; windows?: QuotaWindow[]; account?: string }
/** The task's folder as the Lead's machine sees it. `unknown` means it could not be read, `none` that it is not a repository,
* `missing` that the Lead's machine has no such folder (a member elsewhere may). */
export interface TaskFolder { cwd: string; kind: 'git' | 'none' | 'missing' | 'unknown'; name: string | null; root: string | null; remote: string | null }
@@ -33,11 +36,24 @@ export interface Probe {
}
export interface Attempt { agent: string; outcome: string; result?: string }
export interface RecentRoute { title: string; via?: string; outcome: string | null }
-export interface Shown extends Probe { id: string; title: string; label: string }
-export interface Choice { shown: Shown[]; excluded: Array<{ title: string; reason: string }>; floor: number; belowFloor: boolean }
+type Window = '5-hour' | 'weekly'
+/** How a candidate's account would carry the task, as the decision log keeps it. */
+export interface Fit { status: 'fits' | 'unknown' | 'short'; coverage: number | null; effectiveCost: number; expiring: number; spend: Record<Window, number>; account: string }
+/** A pick still at work: it holds part of its account's quota until its run time is over. */
+export interface Commitment { account: string; spend: Partial<Record<Window, number>>; size: Size; createdAt: number }
+export interface Shown extends Probe { id: string; title: string; label: string; fit: Fit }
+/** `short` is set when no candidate is expected to cover the task, to tell the Lead. */
+export interface Choice { shown: Shown[]; excluded: Array<{ title: string; reason: string }>; floor: number; belowFloor: boolean; short?: string }
export interface Verdict { pick: Shown; via: 'jev' | 'order' | 'only'; p: number | null; why: string; fallback?: 'unsure' | 'unavailable' }
const LEVELS: Level[] = ['low', 'medium', 'high']
+/** Run time and spend per window by task size, for a policy row of cost 2 (owner's table, 2026-10-21); not in the policy yet. */
+const SIZES: Record<Size, { minutes: number; spend: Record<Window, number> }> = {
+ small: { minutes: 20, spend: { '5-hour': 10, weekly: 1 } },
+ medium: { minutes: 60, spend: { '5-hour': 30, weekly: 4 } },
+ large: { minutes: 180, spend: { '5-hour': 50, weekly: 8 } },
+}
+const WINDOWS: Window[] = ['5-hour', 'weekly']
const MAX_SHOWN = 12
const ENGINE = { claude: 'Claude', codex: 'Codex' } as const
const cut = (text: string, max: number) => text.length <= max ? text : `${text.slice(0, max - 1)}…`
@@ -79,13 +95,16 @@ export function parseAssessment(value: unknown): Assessment | string {
const v = (value && typeof value === 'object' ? value : {}) as Record<string, unknown>
if (!LEVELS.includes(v.difficulty as Level)) return 'Set difficulty to low, medium or high.'
if (!LEVELS.includes(v.risk as Level)) return 'Set risk to low, medium or high.'
+ // Leads from before sizes send none; their tasks are taken for medium.
+ const size = v.size ?? 'medium'
+ if (!Object.hasOwn(SIZES, String(size))) return 'Set size to small, medium or large.'
const why = typeof v.why === 'string' ? v.why.trim() : ''
if (!why || why.length > 300) return 'Give why in 1 to 300 characters.'
const needs = (v.needs && typeof v.needs === 'object' ? v.needs : {}) as Record<string, unknown>
const list = (x: unknown) => Array.isArray(x) && x.every(i => typeof i === 'string') ? x as string[] : []
const cwd = needs.cwd
if (cwd !== undefined && (typeof cwd !== 'string' || !isAbsolute(cwd))) return 'needs.cwd must be an absolute path.'
- return { difficulty: v.difficulty as Level, risk: v.risk as Level, why, needs: { tools: list(needs.tools), devices: list(needs.devices), ...(cwd ? { cwd } : {}) } }
+ return { difficulty: v.difficulty as Level, risk: v.risk as Level, size: size as Size, why, needs: { tools: list(needs.tools), devices: list(needs.devices), ...(cwd ? { cwd } : {}) } }
}
export const floorFor = (policy: Policy, a: Assessment): number => Math.min(3, policy.floor[a.difficulty] + (a.risk === 'high' ? 1 : 0))
@@ -96,11 +115,12 @@ function resetMs(value: unknown): number | null {
if (typeof value === 'string') { const ms = Date.parse(value); return Number.isFinite(ms) ? ms : null }
return null
}
-export function quotaOf2(q: { known: boolean; windows: Array<{ usedPercent: number; resetsAt: unknown; name?: string }> }): Quota {
- if (!q.known || !q.windows.length) return { known: false, leftPercent: null, resetsAt: null }
+export function quotaOf2(q: { known: boolean; windows: Array<{ usedPercent: number; resetsAt: unknown; name?: string }>; account?: string | null }): Quota {
+ const account = q.account ? { account: q.account } : {}
+ if (!q.known || !q.windows.length) return { known: false, leftPercent: null, resetsAt: null, ...account }
const tightest = q.windows.reduce((x, y) => y.usedPercent > x.usedPercent ? y : x)
return { known: true, leftPercent: Math.max(0, 100 - tightest.usedPercent), resetsAt: resetMs(tightest.resetsAt),
- windows: q.windows.map(w => ({ name: w.name ?? null, leftPercent: Math.max(0, 100 - w.usedPercent), resetsAt: resetMs(w.resetsAt) })) }
+ windows: q.windows.map(w => ({ name: w.name ?? null, leftPercent: Math.max(0, 100 - w.usedPercent), resetsAt: resetMs(w.resetsAt) })), ...account }
}
/** Whether a member's checkout is the task's repository: the same remote wherever it lives, else the same root on one
@@ -134,6 +154,11 @@ const titleOf = (p: Probe) => cut(`${p.kind === 'member' ? p.name ?? 'Member' :
/** Jev does not know the time, so a reset or a last activity is told as how far away it is. */
function span(ms: number): string {
if (ms < 3_600_000) return `${Math.max(1, Math.round(ms / 60_000))}m`
+ // Under ten hours, half an hour decides whether a task fits before the reset, so it keeps its minutes (4h30).
+ if (ms < 10 * 3_600_000) {
+ const tens = Math.round(ms / 600_000), h = Math.floor(tens / 6), m = tens % 6
+ return m ? `${h}h${m}0` : `${h}h`
+ }
if (ms < 48 * 3_600_000) return `${Math.round(ms / 3_600_000)}h`
return `${Math.round(ms / 86_400_000)} days`
}
@@ -162,43 +187,87 @@ function machineText(load: MachineLoad): string[] {
load.freeMemoryBytes === null ? 'free memory unknown' : `${bytes(load.freeMemoryBytes)} memory free`]
}
/** The most telling parts come first and the least last, because the hosted limit cuts the end. */
-const labelOf = (p: Probe, now: number) => fit([
+const labelOf = (p: Probe & Sized, now: number) => fit([
p.kind === 'member' ? `Member ${fit(p.name ?? '', 40)}`.trim() : 'New agent', `${ENGINE[p.engine]} ${p.model} ${p.effort}`, `quality ${p.quality}, cost ${p.cost}`,
- fit(p.machineName, 40), p.activity, ...(p.kind === 'member' ? memberText(p, now) : p.load ? machineText(p.load) : []),
+ p.text, fit(p.machineName, 40), p.activity, ...(p.kind === 'member' ? memberText(p, now) : p.load ? machineText(p.load) : []),
...(p.earlier?.length ? [`earlier here: ${p.earlier.slice(0, 3).map(e => `${fit(e.group, 40)} ${e.outcome}`).join('; ')}`] : []), quotaText(p.quota, now),
].join(' · '), 640)
-/** The fixed policy order (D): cheaper, then more quota left, then an earlier reset, then a member, then by title. */
-function compare(x: Probe, y: Probe): number {
- return x.cost - y.cost
- || (y.quota.leftPercent ?? -1) - (x.quota.leftPercent ?? -1)
- || (x.quota.resetsAt ?? Infinity) - (y.quota.resetsAt ?? Infinity)
- || (x.kind === y.kind ? 0 : x.kind === 'member' ? -1 : 1)
+interface Measured { name: Window; usable: number; needed: number; resetsIn: number | null }
+/** A probe's fit, its tightest window (the one that runs out first) and the sentence Jev reads. */
+interface Sized { fit: Fit; tight: Measured | null; text: string }
+const pct = (n: number) => `${Math.round(n)}%`
+const round = (n: number) => Math.round(n * 100) / 100
+
+/** How the probe's account would carry a task of this size (phase 1 §2–3). */
+function sizeUp(p: Probe, policy: Policy, a: Assessment, now: number, open: Commitment[]): Sized {
+ const { minutes, spend: base } = SIZES[a.size], runMs = minutes * 60_000
+ const account = p.quota.account ?? `${p.machineId}:${p.engine}`
+ const spend = { '5-hour': base['5-hour'] * p.cost / 2, weekly: base.weekly * p.cost / 2 }
+ // Picks still at work hold what they were expected to spend, less the part of their run time already over.
+ const committed = (name: Window) => open.filter(c => c.account === account)
+ .reduce((sum, c) => sum + (c.spend[name] ?? 0) * Math.max(0, 1 - (now - c.createdAt) / (SIZES[c.size].minutes * 60_000)), 0)
+ const windows = WINDOWS.flatMap((name): Measured[] => {
+ const w = p.quota.windows?.find(w => w.name === name)
+ if (!w) return []
+ const resetsIn = w.resetsAt === null ? null : Math.max(60_000, w.resetsAt - now)
+ // A window that refills mid-task carries only the part of the task before its reset.
+ return [{ name, usable: w.leftPercent - policy.quotaReserve - committed(name), resetsIn,
+ needed: resetsIn !== null && resetsIn < runMs ? spend[name] * resetsIn / runMs : spend[name] }]
+ })
+ const status = windows.some(w => w.usable < w.needed) ? 'short' : windows.length === WINDOWS.length ? 'fits' : 'unknown'
+ const tight = windows.length ? windows.reduce((x, y) => y.usable / y.needed < x.usable / x.needed ? y : x) : null
+ const five = windows.find(w => w.name === '5-hour'), week = windows.find(w => w.name === 'weekly')
+ // A 5-hour window that resets before the task ends, or soon after, loses what is left of it: spending it costs nothing.
+ const expiring = five && five.resetsIn !== null && five.resetsIn <= runMs + 3_600_000 ? Math.min(1, Math.max(0, five.usable) / five.needed) : 0
+ let effectiveCost = p.cost * (1 - expiring)
+ // The weekly window has to last until it resets, so work that is not hard pays for taking more than a day's share of it.
+ const dayBudget = week ? week.usable / Math.max(1, (week.resetsIn ?? 0) / 86_400_000) : 0
+ if (week && a.difficulty !== 'high' && dayBudget > 0 && week.needed > dayBudget) effectiveCost += p.cost * week.needed / dayBudget
+ const text = `${status}: ${five ? `needs about ${pct(five.needed)} of the 5-hour window (${pct(five.usable)} left${five.resetsIn === null ? '' : `, resets in ${span(five.resetsIn)}`}${expiring ? ', otherwise unused' : ''})` : '5-hour window unknown'}`
+ + `; weekly ${week ? `${pct(week.needed)} of ${pct(week.usable)}` : 'unknown'}`
+ return { fit: { status, coverage: tight && round(tight.usable / tight.needed), effectiveCost: round(effectiveCost), expiring: round(expiring), spend, account }, tight, text }
+}
+const WAY = ['right away', 'about a quarter of the way in', 'about halfway', 'about three quarters of the way in', 'near the end']
+const runsOut = (w: Measured) => `The ${w.name} window is expected to run out ${WAY[Math.round(Math.max(0, w.usable / w.needed) * 4)]}${w.resetsIn === null ? '' : `; resets in ${span(w.resetsIn)}`}.`
+const UNREAD = 'Its quota could not be read in full, and another candidate\'s quota fits this task.'
+
+/** The fixed policy order: cheaper in effect, stronger, more room on the tightest window, an idle member in the task's
+ * repository before a new agent, then by title. */
+function compare(x: Probe & Sized, y: Probe & Sized): number {
+ const placed = (p: Probe) => p.kind === 'member' && (p.repo ?? 'same') === 'same' ? 0 : 1
+ return x.fit.effectiveCost - y.fit.effectiveCost
+ || y.quality - x.quality
+ || (y.tight?.usable ?? -Infinity) - (x.tight?.usable ?? -Infinity)
+ || placed(x) - placed(y)
|| titleOf(x).localeCompare(titleOf(y))
}
-export function choose(probes: Probe[], policy: Policy, a: Assessment, now: number = Date.now()): Choice | { error: 'NO_CANDIDATE'; excluded: Array<{ title: string; reason: string }> } {
+export function choose(probes: Probe[], policy: Policy, a: Assessment, now: number = Date.now(), open: Commitment[] = []): Choice | { error: 'NO_CANDIDATE'; excluded: Array<{ title: string; reason: string }> } {
const excluded = probes.filter(p => p.refusals.length).map(p => ({ title: titleOf(p), reason: p.refusals.join(' ') }))
const viable = probes.filter(p => !p.refusals.length)
if (!viable.length) return { error: 'NO_CANDIDATE', excluded }
const floor = floorFor(policy, a)
- // Each step narrows only when something is left, so a floor-meeting candidate is never dropped for being
- // unknown or low on quota; those are fallbacks, not filters.
const meeting = viable.filter(p => p.quality >= floor)
const byFloor = meeting.length ? meeting : viable
- const known = byFloor.filter(p => p.known)
- const byKnown = known.length ? known : byFloor
- const funded = byKnown.filter(p => p.quota.leftPercent === null || p.quota.leftPercent >= policy.quotaReserve)
- const set = funded.length ? funded : byKnown
- const shown = [...set].sort(compare).slice(0, MAX_SHOWN)
- .map((p, i) => ({ ...p, id: `c${i}`, title: titleOf(p), label: labelOf(p, now) }))
- return { shown, excluded, floor, belowFloor: !meeting.length }
+ // Strength beats fit (owner, 2026-10-21): a hard task never goes to a weaker model because the strong ones are short of quota.
+ const top = Math.max(...byFloor.map(p => p.quality))
+ const sized = (a.difficulty === 'high' ? byFloor.filter(p => p.quality === top) : byFloor).map(p => ({ ...p, ...sizeUp(p, policy, a, now, open) }))
+ // Only the first group that has anyone is shown: those that fit, then those whose quota is not fully known, then the short.
+ const status = (['fits', 'unknown', 'short'] as const).find(s => sized.some(p => p.fit.status === s))!
+ excluded.push(...sized.filter(p => p.fit.status !== status).map(p => ({ title: titleOf(p), reason: p.fit.status === 'unknown' ? UNREAD : runsOut(p.tight!) })))
+ // When every candidate is short, the one expected to get furthest goes first.
+ const set = sized.filter(p => p.fit.status === status).sort((x, y) => status === 'short' ? y.fit.coverage! - x.fit.coverage! || compare(x, y) : compare(x, y))
+ const shown = set.slice(0, MAX_SHOWN).map(({ tight, text, ...p }, i) => ({ ...p, id: `c${i}`, title: titleOf(p), label: labelOf({ ...p, tight, text }, now) }))
+ const first = set[0].tight!
+ return { shown, excluded, floor, belowFloor: !meeting.length, ...(status === 'short'
+ ? { short: `No candidate is expected to cover this task; its ${first.name} quota is expected to run out partway${first.resetsIn === null ? '' : ` and resets in ${span(first.resetsIn)}`}.` } : {}) }
}
const INSTRUCTIONS = cut([
'Choose the candidate that should do this task.',
'The Lead assessed its difficulty and risk; every candidate shown meets the quality floor unless the policy says none does.',
- 'Prefer lower cost, then more quota left and an earlier reset, unless the task, its history or the policy notes give a clear reason otherwise.',
+ 'The list is already ordered by strength for the difficulty, fit and effective cost. Keep the first unless the task, its history or the policy notes give a clear reason otherwise.',
'A member marked "same repo" already has the task\'s code open, which saves a start; prefer it over an equal candidate.',
'A candidate that already failed or stopped on this task is a worse choice. A member that is idle in the Super Tab saves a start.',
'Unknown means the information could not be read; it is not a bad sign.',
@@ -260,11 +329,12 @@ export function decide(choice: Choice, answer: JevChoiceAnswer | undefined, unav
return { pick: first, via: 'order', p: null, why: `${reason}; first in the policy order.`, fallback: unavailable ? 'unavailable' : 'unsure' }
}
-export function recordOf(choice: Choice, verdict: Verdict, a: Assessment, policy: Policy, context?: { chars: number; missing: string[] }): Record<string, unknown> {
+/** `v1` leaves out size and fit, for a backend from before phase 1, whose strict schema refuses them. */
+export function recordOf(choice: Choice, verdict: Verdict, a: Assessment, policy: Policy, context?: { chars: number; missing: string[] }, v1 = false): Record<string, unknown> {
return {
- assessment: { difficulty: a.difficulty, risk: a.risk, why: a.why },
+ assessment: { difficulty: a.difficulty, risk: a.risk, why: a.why, ...(v1 ? {} : { size: a.size }) },
candidates: choice.shown.map(s => ({ id: s.id, kind: s.kind, ...(s.agentId ? { agentId: s.agentId } : {}), machineId: s.machineId,
- engine: s.engine, model: s.model, effort: s.effort, quality: s.quality, cost: s.cost, title: s.title, label: s.label })),
+ engine: s.engine, model: s.model, effort: s.effort, quality: s.quality, cost: s.cost, title: s.title, label: s.label, ...(v1 ? {} : { fit: s.fit }) })),
excluded: choice.excluded.slice(0, 200).map(e => ({ title: e.title, reason: cut(e.reason, 500) })),
floor: choice.floor, notes: policy.notes.length > 0,
pick: verdict.pick.id, via: verdict.via, ...(verdict.fallback ? { fallback: verdict.fallback } : {}), p: verdict.p, belowFloor: choice.belowFloor, why: cut(verdict.why, 300),
diff --git a/cli/src/superTabs/routeCommand.spec.ts b/cli/src/superTabs/routeCommand.spec.ts
index e2f92baff..97ad65ad8 100644
--- a/cli/src/superTabs/routeCommand.spec.ts
+++ b/cli/src/superTabs/routeCommand.spec.ts
@@ -23,7 +23,7 @@ const conversations = (assignment: unknown = null) => [
{ id: 'g1', title: 'API', leadId: 'lead', agentIds: ['lead'], archived: false, brief: 'Add the endpoint.', checks: [{ description: 'Tests pass' }], assignment },
]
const tab = (assignment: unknown = null) => ({ revision: 3, state: { id: 'tab', agents, conversations: conversations(assignment) } })
-const usage = { providers: [{ provider: 'claude', outcome: 'answered', httpStatus: 200, account: 'acct', body: { five_hour: { utilization: 40, resets_at: '2026-10-19T12:00:00Z' }, seven_day: { utilization: 10 } } }] }
+const usage = { providers: [{ provider: 'claude', outcome: 'answered', httpStatus: 200, account: 'acct', body: { five_hour: { utilization: 40, resets_at: new Date(Date.now() + 3 * 3_600_000).toISOString() }, seven_day: { utilization: 10 } } }] }
function daemon(machineId: string, options: { agents?: string[]; frames?: Record<string, Record<string, unknown>>; capacity?: Record<string, unknown>; terminalAvailable?: boolean; tools?: Record<string, boolean>; devices?: Record<string, boolean>; usage?: unknown; listFails?: boolean; engines?: unknown } = {}) {
return {
machineId, close: vi.fn(),
@@ -245,7 +245,9 @@ describe('routeTask', () => {
const titles = (recorded(s).command.decision.candidates as Array<{ title: string }>).map(c => c.title)
expect(titles.some(t => t.startsWith('Multiply'))).toBe(true)
expect(titles.some(t => t.startsWith('Collab'))).toBe(false)
- expect(recorded(s).command.decision.excluded.some((e: { title: string }) => e.title.startsWith('Collab'))).toBe(false)
+ // Left out because others' quota fits, which the log says.
+ expect(recorded(s).command.decision.excluded).toEqual(expect.arrayContaining([{ title: 'Collab · Claude sonnet medium · theirs',
+ reason: 'Its quota could not be read in full, and another candidate\'s quota fits this task.' }]))
})
it('opens a machine only members know and probes its members, but starts nothing new there', async () => {
const two = tab(); two.state.agents = [{ ...agents[0], machineId: 'theirs' }, agents[1]] as never
@@ -270,6 +272,29 @@ describe('routeTask', () => {
.filter(c => /hand/.test(c.title)).map(c => [c.title.split(' · ')[0], [c.quality, c.cost]]))
expect(rated).toEqual({ 'Opus hand': [3, 3], 'Sonnet hand': [2, 2], 'Codex hand': [3, 2] })
})
+ it('counts the quota open picks hold on the same account, and tells the Lead when nobody is expected to cover the task', async () => {
+ const pick = { conversationId: 'g1', title: 'Pick', outcome: null, assignmentId: 'as1', createdAt: new Date().toISOString(), final: { kind: 'new', engine: 'claude', model: 'opus' } }
+ const decisions = [{ ...pick, id: 'd1', account: 'acct', spend: { '5-hour': 45, weekly: 6 }, size: 'medium' },
+ // A finished pick, one not yet started and one from before phase 1 hold nothing.
+ { ...pick, id: 'd2', account: 'acct', spend: { '5-hour': 45 }, size: 'medium', outcome: 'done' }, { ...pick, id: 'd3', account: 'acct', spend: { '5-hour': 45 }, size: 'medium', final: null }, { ...pick, id: 'd4' }]
+ const s = scoped({ history: { ok: true, value: { messages: [], decisions, attempts: [] } } })
+ const result = await routeTask(input, s, where as never, opener(), () => 'op')
+ // 60% left less the 10% reserve and the 45% the open pick holds leaves 5% for a task that needs 30%.
+ expect(recorded(s).command.decision.candidates.every((c: { fit: { status: string; account: string } }) => c.fit.status === 'short' && c.fit.account === 'acct')).toBe(true)
+ expect(result.warnings).toEqual(['w', expect.stringMatching(/^No candidate is expected to cover this task; its 5-hour quota is expected to run out partway and resets in 3h\.$/)])
+ })
+ it('records again in the shape an older backend knows when it refuses the new fields as invalid', async () => {
+ const s = scoped(), base = s.getMockImplementation()!
+ let refused = 0
+ s.mockImplementation(async payload => payload.action === 'command' && !refused++ ? { error: 'VALIDATION_ERROR', detail: 'decision.candidates.0: Unrecognized key: "fit"', status: 400 } : base(payload))
+ expect(await routeTask(input, s, where as never, opener(), () => 'op')).toMatchObject({ ok: true, routeDecisionId: 'd1' })
+ const [phase1, v1] = s.mock.calls.filter(c => c[0].action === 'command').map(c => c[0])
+ expect(phase1.command.decision.assessment.size).toBe('medium')
+ expect(phase1.command.decision.candidates[0]).toHaveProperty('fit')
+ expect(v1.operationId).toBe(phase1.operationId)
+ expect(v1.command.decision.assessment).not.toHaveProperty('size')
+ expect(v1.command.decision.candidates.some((c: object) => 'fit' in c)).toBe(false)
+ })
it('falls back to the policy order when Jev is unavailable, and still routes when recording fails', async () => {
const result = await routeTask(input, scoped({ jev: { ok: true, value: { unavailable: 'BUSY' } }, record: { error: 'BACKEND_UNAVAILABLE' } }), where as never, opener())
expect(result).toMatchObject({ ok: true, via: 'order', unrecorded: true })
diff --git a/cli/src/superTabs/routeCommand.ts b/cli/src/superTabs/routeCommand.ts
index 63b9e135f..0beb43a97 100644
--- a/cli/src/superTabs/routeCommand.ts
+++ b/cli/src/superTabs/routeCommand.ts
@@ -6,7 +6,7 @@ import { openDaemon, type Daemon, type Where } from '../agentClient/daemon.js'
import { startRequirements } from './capacity.js'
import { inspectCapacity, type ScopedRequest } from './start.js'
import { object, within } from './wire.js'
-import { choose, contextSize, decide, jevQuestion, parseAssessment, quotaOf2, rateFor, recordOf, repoMatch, type Assessment, type Attempt, type MemberFrame, type Policy, type Probe, type TaskFolder } from './route.js'
+import { choose, contextSize, decide, jevQuestion, parseAssessment, quotaOf2, rateFor, recordOf, repoMatch, type Assessment, type Attempt, type Commitment, type MemberFrame, type Policy, type Probe, type TaskFolder } from './route.js'
import { stat } from 'node:fs/promises'
import { describeScmProject } from '../scm/scmProjects.js'
import type { JevChoiceAnswer } from '../lib/jev/jevClient.js'
@@ -160,7 +160,10 @@ export async function routeTask(input: { tabId: string; conversationId: string;
const ended = endedWork(conversations, agents, decisions, attempts, input.conversationId)
const probes = probed.flat().map(p => p.kind === 'member' ? { ...p, repo: repoMatch(folder, p.frame ?? null, p.machineId === where.machineId),
earlier: ended.filter(e => e.agentId === p.agentId).reverse().slice(0, 3).map(e => ({ group: e.group, outcome: e.outcome })) } : p)
- const choice = choose(probes, policy, assessment, Date.now())
+ // Picks started or assigned and still at work hold part of their account's quota; the log, and so this, is per Swarm.
+ const working = (decisions ?? []).filter(d => d.final && d.outcome === null && typeof d.account === 'string')
+ .map(d => ({ account: d.account, spend: object(d.spend), size: d.size, createdAt: Date.parse(String(d.createdAt)) }) as Commitment)
+ const choice = choose(probes, policy, assessment, Date.now(), working)
if ('error' in choice) return choice
// What Jev could not be told, for the decision log: pick quality can later be compared with how complete this was.
const missing = [...(messages ? [] : ['messages']), ...(decisions ? [] : ['route log']), ...(attempts ? [] : ['attempts']), ...(folder && ['unknown', 'missing'].includes(folder.kind) ? ['task folder'] : []),
@@ -181,8 +184,12 @@ export async function routeTask(input: { tabId: string; conversationId: string;
else answer = object(jev.answers).who as JevChoiceAnswer | undefined
}
const verdict = decide(choice, answer, unavailable)
- const recorded = await scoped({ action: 'command', operationId: `route-${newId()}`,
- command: { type: 'route.record', conversationId: input.conversationId, decision: recordOf(choice, verdict, assessment, policy, question && { chars: contextSize(question), missing }) } })
+ const operationId = `route-${newId()}`
+ const record = (v1: boolean) => scoped({ action: 'command', operationId,
+ command: { type: 'route.record', conversationId: input.conversationId, decision: recordOf(choice, verdict, assessment, policy, question && { chars: contextSize(question), missing }, v1) } })
+ let recorded = await record(false)
+ // A backend from before phase 1 refuses the new fields as invalid; the decision is still worth keeping in the shape it knows.
+ if (recorded.error === 'VALIDATION_ERROR') recorded = await record(true)
if (typeof recorded.error === 'string' && !TRANSPORT.has(recorded.error)) return recorded
const routeDecisionId = recorded.ok === true ? object(object(recorded.value).result).routeDecisionId : undefined
const decision = typeof routeDecisionId === 'string' ? `,"routeDecisionId":"${routeDecisionId}"` : ''
@@ -192,7 +199,7 @@ export async function routeTask(input: { tabId: string; conversationId: string;
ok: true, ...(typeof routeDecisionId === 'string' ? { routeDecisionId } : { unrecorded: true }),
pick: publicOf(verdict.pick), via: verdict.via, p: verdict.p, belowFloor: choice.belowFloor, why: verdict.why,
alternatives: choice.shown.filter(s => s.id !== verdict.pick.id).slice(0, 2).map(publicOf),
- warnings: [...(Array.isArray(effective.warnings) ? effective.warnings : []), ...(value.machinesUnreadable === true ? [MACHINES_UNREADABLE] : [])],
+ warnings: [...(Array.isArray(effective.warnings) ? effective.warnings : []), ...(value.machinesUnreadable === true ? [MACHINES_UNREADABLE] : []), ...(choice.short ? [choice.short] : [])],
next: verdict.pick.kind === 'member'
? `Assign with: command OPERATION_ID {"type":"work.assign","conversationId":"${input.conversationId}","agentId":"${verdict.pick.agentId}"${decision}}`
: `Start with: start OPERATION_ID ${JSON.stringify({ conversationId: input.conversationId, name: 'Builder', cwd: text(machines.get(verdict.pick.machineId)?.pool?.cwd) ?? assessment.needs.cwd ?? '/absolute/repo/on/that/machine',
diff --git a/cli/src/superTabs/service.spec.ts b/cli/src/superTabs/service.spec.ts
index a09cd8754..15e873350 100644
--- a/cli/src/superTabs/service.spec.ts
+++ b/cli/src/superTabs/service.spec.ts
@@ -192,6 +192,20 @@ describe('routeHistory for Jev', () => {
expect(JSON.stringify(decisions)).not.toContain('bigbig')
const last = await contextOf(setup(), async path => path.includes('/messages') ? ok({ messages: [] }) : ok([unfinished]))
expect(last.value.decisions).toEqual([{ id: 'dx', conversationId: 'g1', title: 'unknown pick', via: 'order', outcome: 'superseded', assignmentId: null, createdAt: '2026-10-19T09:00:00Z', final: null }])
+ // The pick's account, spend and size go with it, so the route can count what an open pick still holds.
+ const fit = { status: 'fits', coverage: 2, effectiveCost: 3, expiring: 0, spend: { '5-hour': 45, weekly: 6 }, account: 'k1' }
+ const sized = (size?: string) => ({ ...decision(0), record: { pick: 'c1', via: 'jev', assessment: size ? { size } : {}, candidates: [{ id: 'c0', title: 'Other' }, { id: 'c1', title: 'Pick', fit }] } })
+ const phase1 = await contextOf(setup(), async path => path.includes('/messages') ? ok({ messages: [] }) : ok([sized('large'), sized()]))
+ expect(phase1.value.decisions).toMatchObject([{ account: 'k1', spend: { '5-hour': 45, weekly: 6 }, size: 'large' }, { size: 'medium' }])
+ // An override runs another candidate: a person's choice holds its own account; a Lead's choice outside the list holds none.
+ const other = { ...fit, account: 'k0', spend: { '5-hour': 30, weekly: 4 } }
+ const overridden = (override: Record<string, unknown>) => ({ ...sized('large'), override,
+ record: { ...sized('large').record, candidates: [{ id: 'c0', title: 'Other', fit: other }, { id: 'c1', title: 'Pick', fit }] } })
+ const moved = await contextOf(setup(), async path => path.includes('/messages') ? ok({ messages: [] })
+ : ok([overridden({ by: 'person', candidateId: 'c0', reason: 'r' }), overridden({ by: 'lead', reason: 'r' })]))
+ const [person, lead] = moved.value.decisions as Array<Record<string, unknown>>
+ expect(person).toMatchObject({ title: 'Pick', account: 'k0', spend: { '5-hour': 30, weekly: 4 } })
+ expect(lead).not.toHaveProperty('account')
})
it('gives every attempt of the group, newest first, with only what Jev needs and no more than fifty', async () => {
const t = setup()
diff --git a/cli/src/superTabs/service.ts b/cli/src/superTabs/service.ts
index 2259bb1c2..601276fe8 100644
--- a/cli/src/superTabs/service.ts
+++ b/cli/src/superTabs/service.ts
@@ -18,7 +18,7 @@ const HELP = {
post: 'post GROUP TEXT OPERATION_ID [--reply-to MESSAGE_ID] [--attach PATH]...: reply in that conversation. Use a unique ID per message and reuse it after an interrupted request. Answer a message once, with --reply-to its ID. --attach sends a file (a screenshot, a log; up to 10 files of 10 MB each), and TEXT may then be empty.',
start: 'start OPERATION_ID JSON: create one agent in a conversation on a machine in this Swarm\'s Machines list; to use another machine, a person adds it to the Swarm first. Repeat exactly after an interruption; it follows the same native creation receipt. It does not assign work. With worktree true, the agent starts from the repository\'s default branch, fetched first, unless you set branchRef (refs/heads/BRANCH, or refs/remotes/origin/BRANCH to fetch it first) to start from another branch, such as the one this work builds on.',
resume: 'resume START_ID: finish a pending start without creating another agent.',
- route: 'route GROUP JSON: before starting or assigning work, choose who does it. JSON: {"difficulty":"low|medium|high","risk":"low|medium|high","why":"one sentence","needs":{"tools":[],"devices":[],"cwd":"/absolute/repo"}}. Start or assign the pick with its routeDecisionId; to choose otherwise, pass overrideReason.',
+ route: 'route GROUP JSON: before starting or assigning work, choose who does it. JSON: {"difficulty":"low|medium|high","risk":"low|medium|high","size":"small|medium|large","why":"one sentence","needs":{"tools":[],"devices":[],"cwd":"/absolute/repo"}}. size is how long the work runs: small about 20 minutes, medium about an hour, large about three hours. Start or assign the pick with its routeDecisionId; to choose otherwise, pass overrideReason.',
capacity: 'capacity MACHINE_ID JSON: inspect machine, engine and quota headroom. JSON uses the start request fields below. Unknown allowances are not reported as free tokens.',
startRequest: { conversationId: 'GROUP', machineId: 'MACHINE', engine: 'codex', name: 'Builder', cwd: '/absolute/repo/on/that/machine', worktree: true, branchRef: 'refs/remotes/origin/BASE_BRANCH', requirements: START_REQUIREMENTS,
model: 'opus', effort: 'high', routeDecisionId: 'DECISION' },
@@ -162,10 +162,14 @@ export function superTabService(core: CoreApi, options: SuperTabServiceOptions =
return { from: by.kind === 'person' ? 'person' : by.id === group.leadId ? 'Lead' : String(list(state.agents).find(a => a.id === by.id)?.name ?? 'agent'),
text: String(m.text ?? '').slice(0, 1000) }
})
- // The log's records carry every candidate's line; Jev needs only who was picked and how it went.
+ // The log's records carry every candidate's line; Jev needs only who was picked and how it went. The route also
+ // needs the account and expected spend of what actually runs, which an open pick still holds: after an override
+ // that is the person's chosen candidate, and a Lead's own choice outside the list has no known account.
const decisions = Array.isArray(logged) ? logged.slice(0, 50).map(object).map(d => {
- const record = object(d.record), final = object(d.final)
- return { id: d.id, conversationId: d.conversationId, title: String(list(record.candidates).find(c => c.id === record.pick)?.title ?? 'unknown pick'),
+ const record = object(d.record), final = object(d.final), candidates = list(record.candidates), pick = candidates.find(c => c.id === record.pick)
+ const runs = d.override ? candidates.find(c => c.id === object(d.override).candidateId) : pick, fit = object(runs?.fit)
+ return { id: d.id, conversationId: d.conversationId, title: String(pick?.title ?? 'unknown pick'),
+ ...(typeof fit.account === 'string' ? { account: fit.account, spend: object(fit.spend), size: object(record.assessment).size ?? 'medium' } : {}),
...(typeof record.via === 'string' ? { via: record.via } : {}), outcome: d.outcome ?? null, assignmentId: d.assignmentId ?? null, createdAt: d.createdAt,
final: final.kind === 'member' ? { kind: 'member', agentId: final.agentId } : final.kind === 'new' ? { kind: 'new', engine: final.engine, model: final.model } : null }
}) : null
diff --git a/desktop/lib/state/harness_launch_integration.dart b/desktop/lib/state/harness_launch_integration.dart
index 07907037b..3a6e24cd0 100644
--- a/desktop/lib/state/harness_launch_integration.dart
+++ b/desktop/lib/state/harness_launch_integration.dart
@@ -17,10 +17,13 @@ class HarnessLaunchIntegration {
this.projectVisibility,
this.projectVisibilityLocked = false,
this.initialTask,
+ this.engines,
});
final String creationId, actionLabel;
// Restores the person's original request from a destination launch journal.
final String? initialTask;
+ // The only agents this destination may start, or null for any.
+ final List<String>? engines;
String? projectVisibility;
bool projectVisibilityLocked;
final Future<String> Function(String machineId, String task) prepare;
diff --git a/desktop/lib/state/new_harness.dart b/desktop/lib/state/new_harness.dart
index 97a9d55ea..33eda7576 100644
--- a/desktop/lib/state/new_harness.dart
+++ b/desktop/lib/state/new_harness.dart
@@ -456,7 +456,9 @@ class NewHarnessController extends ChangeNotifier {
engine = draft?.engine ?? engine;
// A Finder is chosen as a harness is: by itself, or with its chat's agent.
_finder =
- isFinderEngine(draft?.harnessId ?? harnessId) || isFinderEngine(engine);
+ _allowedEngines == null &&
+ (isFinderEngine(draft?.harnessId ?? harnessId) ||
+ isFinderEngine(engine));
if (isFinderEngine(engine)) engine = null;
_harnessId = _finder
? null
@@ -473,6 +475,11 @@ class NewHarnessController extends ChangeNotifier {
? engine
: _initialEngine(isHarnessId(engine) ? null : engine);
if (_finder) _engine = _finderChat(_engine);
+ // A new Lead opened beside another pane inherits its agent, which may be
+ // one a Lead cannot run (OpenCode); it gives way as a guest's does.
+ if (_allowedEngines != null && !compatibleEngines.contains(_engine)) {
+ _engine = compatibleEngines.first;
+ }
_restorePermissionMode();
_model = _noAgentSetup ? null : draft?.model;
_modelUsage = modelUsage;
@@ -601,7 +608,13 @@ class NewHarnessController extends ChangeNotifier {
final String? _home;
late String _engine;
- String? _harnessId;
+ String? _chosenHarness;
+
+ /// A destination that allows only some agents (integration.engines, a new
+ /// Lead) starts the agent itself, never a Store harness, as a guest does.
+ String? get _harnessId => _allowedEngines == null ? _chosenHarness : null;
+ set _harnessId(String? id) => _chosenHarness = id;
+ List<String>? get _allowedEngines => integration?.engines;
/// What the Harness row answers: a Store harness, the Finder, or null for
/// an agent on its own. Both of the first two run on [engine].
@@ -704,6 +717,8 @@ class NewHarnessController extends ChangeNotifier {
List<String> get compatibleEngines => asGuest
? const ['claude', 'codex']
+ : _allowedEngines != null
+ ? _allowedEngines!
// A Finder's chat runs beside it on this computer: an agent, never
// the cloud or a bare shell.
: _finder
@@ -739,10 +754,12 @@ class NewHarnessController extends ChangeNotifier {
final allowed = compatibleEngines;
final remembered = requested ?? _rememberedChoice;
if (remembered != null &&
- (requested != null ||
- !_desktopChoices ||
- allowed.contains(remembered) ||
- _harnessId == app.agentPreference.successfulLaunch?.harnessId)) {
+ (allowed.contains(remembered) ||
+ _allowedEngines == null &&
+ (requested != null ||
+ !_desktopChoices ||
+ _harnessId ==
+ app.agentPreference.successfulLaunch?.harnessId))) {
return remembered;
}
// Nothing remembered: the agent this person already uses, when the
@@ -1688,10 +1705,10 @@ class NewHarnessController extends ChangeNotifier {
// The machine model has no OS field. Its own home response (or a known
// project path before that response) owns the syntax, never this host.
// A relative query carries no style evidence over the committed project.
- final absoluteHint = hint != null &&
+ final absoluteHint =
+ hint != null &&
(p.posix.isAbsolute(hint) ||
- p.windows.isAbsolute(hint) &&
- !p.windows.isRootRelative(hint))
+ p.windows.isAbsolute(hint) && !p.windows.isRootRelative(hint))
? hint
: null;
final ownerPath =
@@ -2840,7 +2857,7 @@ class NewHarnessController extends ChangeNotifier {
NewHarnessField.harness => [
..._harnessOptions(),
// A guest starts nothing from the Store there (asGuest).
- if (offersStore && !asGuest) _store,
+ if (offersStore && !asGuest && _allowedEngines == null) _store,
],
NewHarnessField.launch ||
NewHarnessField.task ||
@@ -3086,8 +3103,9 @@ class NewHarnessController extends ChangeNotifier {
}
List<NewHarnessOption> _harnessOptions() {
- // A guest there starts Claude Code or Codex, nothing from the Store (asGuest).
- if (asGuest) {
+ // A guest there starts Claude Code or Codex, nothing from the Store (asGuest);
+ // so does a new Lead.
+ if (asGuest || _allowedEngines != null) {
return _ranked([
for (final id in compatibleEngines)
NewHarnessOption(id: id, title: labelOf(id), engine: id),
@@ -3292,8 +3310,7 @@ class NewHarnessController extends ChangeNotifier {
// `~/` keeps its slash: joined with nothing it came back as the home
// folder itself, which then read as "the folder `me` under /home" — the
// list showed one row, your own home, and Tab completed to `~/me/`.
- if (text == '~/' ||
- paths.style == p.Style.windows && text == '~\\') {
+ if (text == '~/' || paths.style == p.Style.windows && text == '~\\') {
return '$home${text.substring(1)}';
}
if (text.startsWith('~/') ||
@@ -3481,7 +3498,8 @@ class NewHarnessController extends ChangeNotifier {
total = 0;
return [_browse, _changeMachine];
}
- final trailing = full.endsWith('/') ||
+ final trailing =
+ full.endsWith('/') ||
paths.style == p.Style.windows && full.endsWith('\\');
final parent = trailing ? paths.normalize(full) : paths.dirname(full);
// While Tab is cycling the candidates, the line holds one of them but the
diff --git a/desktop/lib/super_tabs/launch.dart b/desktop/lib/super_tabs/launch.dart
index 7257c90aa..16c690129 100644
--- a/desktop/lib/super_tabs/launch.dart
+++ b/desktop/lib/super_tabs/launch.dart
@@ -64,6 +64,9 @@ class SuperTabLaunch {
: saved['lead'] == true
? 'New Swarm'
: 'New Harness',
+ // Routing reads quota for Claude Code and Codex only, so a Lead is one
+ // of them; the agents it starts may be anything.
+ engines: saved['lead'] == true ? const ['claude', 'codex'] : null,
projectVisibility: saved['lead'] == true
? saved['visibility'] as String? ?? 'public'
: null,
diff --git a/desktop/lib/super_tabs/launch_prompt.dart b/desktop/lib/super_tabs/launch_prompt.dart
index fe5b936c1..67d1c78f4 100644
--- a/desktop/lib/super_tabs/launch_prompt.dart
+++ b/desktop/lib/super_tabs/launch_prompt.dart
@@ -9,12 +9,13 @@ String superTabLaunchPrompt({
'Harness Swarm agent. '
'${lead ? 'You are the project lead. Discuss first; build when authorized. ' : ''}'
'Use `harness super-tab --tab $tabId` with the subcommands below. '
- 'First: `status`. Retry AGENT_UNAVAILABLE briefly until registered; do not work or post before registration. '
+ 'First: `status`. Retry AGENT_UNAVAILABLE briefly; do not work or post before registration. '
'Read `messages $conversationId` for the full human request; if empty, ask what they want to work on. '
'Reply there using `post GROUP "message" UNIQUE_OPERATION_ID [--reply-to MESSAGE_ID]`. '
'Use --reply-to for existing messages; answer each message once, do not post again. Retry a lost reply with the exact same operation ID and text. '
'Terminal output is not shared chat. If sandbox restrictions block this command, request permission. Use `help` for syntax. '
- '${lead ? 'Before starting or assigning work, use `route GROUP JSON` with difficulty/risk; use its routeDecisionId or an explicit overrideReason. Explain NO_CANDIDATE reasons in chat. ' : ''}'
- 'Reuse agents and groups. Each group needs an assignable outcome and acceptance checks; native helper agents need no group. '
- 'Write like a helpful colleague: answer first, in their language, under about 150 words unless asked for detail. Hide commands, internal IDs and field names. Give results with useful revision/links. '
- '${lead ? 'Keep the Lead chat informed: plan, substantive progress, blockers, next steps. Consolidate workgroup reports every five minutes, following project cadence. Answer questions, serious blockers and completion immediately. On scheduled requests read new reports; use project.report for one update or text:null if nothing new. No per-turn summarizer. Keep workgroups and sessions scoped to this project.' : ''}';
+ '${lead ? 'Before starting or assigning work, use `route GROUP JSON` with difficulty, risk and size (small, medium or large); use its routeDecisionId or an explicit overrideReason. Explain NO_CANDIDATE reasons in chat. ' : ''}'
+ '${lead ? 'Coordinate: put multi-part or 15+ minute work in groups for Swarm agents. Do only answers, lookups and small fixes yourself; your subagents only read and look up. ' : ''}'
+ 'Reuse agents and groups. Each group needs an assignable outcome and acceptance checks. '
+ 'Write like a helpful colleague: answer first, in their language, under about 150 words unless asked. Hide commands, internal IDs and field names. Give results with revision/links. '
+ '${lead ? 'Keep the Lead chat informed: plan, progress, blockers, next steps. Consolidate workgroup reports at the project cadence. Answer questions, serious blockers and completion immediately. On scheduled requests read new reports; use project.report for one update or text:null if nothing new. No per-turn summarizer. Keep workgroups and sessions scoped to this project.' : ''}';
diff --git a/desktop/lib/super_tabs/machines.dart b/desktop/lib/super_tabs/machines.dart
index 2e6457490..315bc4c27 100644
--- a/desktop/lib/super_tabs/machines.dart
+++ b/desktop/lib/super_tabs/machines.dart
@@ -637,7 +637,9 @@ class _SuperTabMachinesState extends State<SuperTabMachines> {
if (accounts.isEmpty && fresh) {
accounts = [
for (final raw in observation['quotas'] as List? ?? [])
- _quotaRow(superTabMap(raw), id),
+ // Routing reads quota for these two only; other engines drew "—".
+ if (const {'claude', 'codex'}.contains(superTabMap(raw)['engine']))
+ _quotaRow(superTabMap(raw), id),
];
}
final usage = WorkspaceSubscriptionUsage.fromRows(online ? accounts : []);
diff --git a/desktop/test/super_tab_launch_test.dart b/desktop/test/super_tab_launch_test.dart
index 2e1ac413e..5267459d5 100644
--- a/desktop/test/super_tab_launch_test.dart
+++ b/desktop/test/super_tab_launch_test.dart
@@ -351,6 +351,7 @@ class SuperTabLaunchFixture {
HarnessAttachments? attachments,
bool newProject = false,
String? task = 'Discuss the architecture.',
+ String? harnessId,
}) async {
final integration = await SuperTabLaunch.open(
app,
@@ -364,6 +365,7 @@ class SuperTabLaunchFixture {
engine: engine,
folder: '/work/project',
task: task,
+ harnessId: harnessId,
integration: integration,
attachments: attachments,
);
@@ -763,11 +765,42 @@ void main() {
.$2['prompt']
as String;
expect(prompt, contains('route GROUP'));
+ expect(prompt, contains('size (small, medium or large)'));
expect(prompt, contains('routeDecisionId'));
expect(prompt, contains('overrideReason'));
expect(prompt, contains('NO_CANDIDATE'));
});
+ test('a new Lead starts Claude Code or Codex; other agents stay open to the rest', () async {
+ final f = SuperTabLaunchFixture();
+ final lead = await f.box(engine: 'opencode');
+ expect(lead.integration!.engines, ['claude', 'codex']);
+ expect(lead.compatibleEngines, ['claude', 'codex']);
+ expect(lead.engine, isIn(['claude', 'codex']));
+ lead.focusField(NewHarnessField.harness);
+ expect(lead.options.map((option) => option.id), ['claude', 'codex']);
+ // Opened beside a Store harness's OpenCode pane, it inherits that agent and still gives way.
+ final inherited = await f.box(
+ engine: 'opencode',
+ harnessId: 'store-harness',
+ );
+ expect(inherited.engine, isIn(['claude', 'codex']));
+
+ f.app.bindSuperTab(f.app.activeSwarmId, tabId, 'Company');
+ final member = NewHarnessController(
+ f.app,
+ machineId: 'm',
+ engine: 'opencode',
+ folder: '/work/project',
+ integration: await SuperTabLaunch.open(f.app, f.app.activeSwarm, 'lead'),
+ );
+ addTearDown(member.dispose);
+ await Future<void>.delayed(Duration.zero);
+ expect(member.integration!.engines, isNull);
+ expect(member.compatibleEngines, contains('opencode'));
+ expect(member.engine, 'opencode');
+ });
+
test('the lead prompt asks for short plain replies, answered once', () async {
final f = SuperTabLaunchFixture();
final box = await f.box(engine: 'claude');
diff --git a/desktop/test/super_tab_machines_test.dart b/desktop/test/super_tab_machines_test.dart
index d20d073b6..1043c8bca 100644
--- a/desktop/test/super_tab_machines_test.dart
+++ b/desktop/test/super_tab_machines_test.dart
@@ -8,6 +8,7 @@ import 'package:harness/state/app_state.dart';
import 'package:harness/super_tabs/machines.dart';
import 'package:harness/super_tabs/model.dart';
import 'package:harness/shared/theme/app_theme.dart' as grid;
+import 'package:harness/widgets/engine_identity.dart';
import 'super_tab_launch_test.dart' show SuperTabLaunchFixture, tabId;
@@ -498,6 +499,62 @@ void main() {
);
}
+ testWidgets('A machine card shows quota for Claude Code and Codex only', (
+ tester,
+ ) async {
+ final f = SuperTabLaunchFixture();
+ f.app.bindSuperTab(f.app.activeSwarmId, tabId, 'Pilot');
+ f.connection.server.state['machines'] = [
+ {
+ 'machineId': 'm',
+ 'contributorId': 'owner',
+ 'observation': {
+ 'receivedAt': DateTime.now().millisecondsSinceEpoch,
+ 'quotas': [
+ for (final engine in ['claude', 'codex', 'opencode', 'cursor'])
+ {
+ 'engine': engine,
+ 'known': engine == 'claude',
+ 'windows': [
+ {'name': '5-hour', 'usedPercent': 40},
+ ],
+ },
+ ],
+ },
+ },
+ ];
+ final c = await f.app.superTabs.open(tabId);
+ await c.refresh();
+ await tester.pumpWidget(
+ MaterialApp(
+ home: Scaffold(
+ body: SizedBox(
+ width: 300,
+ height: 400,
+ child: SuperTabMachines(
+ controller: c,
+ app: f.app,
+ onAddAgent: (_) {},
+ ),
+ ),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ expect(
+ tester
+ .widgetList<EngineMark>(find.byType(EngineMark))
+ .map((mark) => mark.engine)
+ .toSet(),
+ {'claude', 'codex'},
+ );
+
+ await tester.pumpWidget(const SizedBox());
+ await c.flush();
+ f.app.superTabs.dispose();
+ await tester.pump();
+ });
+
testWidgets(
'Configure on a machine card reads as editing: title "Configure machine", button "Save"',
(tester) async {
diff --git a/desktop/test/swarm_launch_recovery_test.dart b/desktop/test/swarm_launch_recovery_test.dart
index 7c39479c2..aa35542f0 100644
--- a/desktop/test/swarm_launch_recovery_test.dart
+++ b/desktop/test/swarm_launch_recovery_test.dart
@@ -4,7 +4,7 @@ import 'package:harness/state/harness_launch_integration.dart';
import 'package:harness/state/new_harness.dart';
import 'package:harness/widgets/new_harness_form.dart';
-import 'super_tab_launch_test.dart' show SuperTabLaunchFixture;
+import 'super_tab_launch_test.dart' show SuperTabLaunchFixture, tabId;
void main() {
for (final resend in [false, true]) {
@@ -74,9 +74,11 @@ void main() {
}
test(
- 'a Swarm rejects a terminal-only lead before creating a native session',
+ 'a Swarm rejects a terminal-only agent before creating a native session',
() async {
+ // A new Lead cannot choose a terminal at all; an agent joining it can.
final f = SuperTabLaunchFixture();
+ f.app.bindSuperTab(f.app.activeSwarmId, tabId, 'Company');
final box = await f.box(engine: 'terminal');
expect(await box.create(), NewHarnessOutcome.failed);
expect(box.error, contains('Choose an agent that runs on a machine'));
diff --git a/docs/plans/2026-10-21-swarm-routing-phase1.md b/docs/plans/2026-10-21-swarm-routing-phase1.md
new file mode 100644
index 000000000..261ed7be3
--- /dev/null
+++ b/docs/plans/2026-10-21-swarm-routing-phase1.md
@@ -0,0 +1,116 @@
+# Swarm routing phase 1: strong models for hard tasks, quota that fits the task
+
+Owner-approved 2026-10-21. Short spec for the implementing agent. The longer reasoning is in
+`docs/superpowers/specs/2026-10-21-swarm-quota-aware-routing-design.md`; where the two differ, this file wins.
+
+## Why
+A Lead routes each task with `harness super-tab route` (`cli/src/superTabs/routeCommand.ts`, `route.ts` `choose`).
+Today it picks the **cheapest** candidate that meets the quality floor, and uses quota and reset time only to break
+ties. So a hard task gets a weaker model, quota that resets unused is lost, a long task can start on a window that
+runs out halfway, and tasks routed a minute apart pile onto one account.
+
+## Scope
+- **Claude and Codex only.** Other engines come later, one at a time (see "Later").
+- In scope: the route's ordering, the Lead's assessment, the decision log, the Lead's prompt and HELP text, two small
+ Desktop changes.
+- Out of scope: learning spend from history, money caps, a dashboard, editing the size table in the policy UI.
+
+## 1. The Lead adds `size`
+`route GROUP JSON` takes `size`: `small` | `medium` | `large`. Missing means `medium` (older Leads keep working).
+Update the HELP `route` line (`cli/src/superTabs/service.ts`) and the Lead prompts (`desktop/lib/super_tabs/launch.dart`,
+`launch_prompt.dart`) to ask for it.
+
+Defaults, as constants in `route.ts` (not in the policy yet):
+
+| size | run time | 5-hour window spend | weekly spend |
+|---|---|---|---|
+| small | 20 min | 10% | 1% |
+| medium | 60 min | 30% | 4% |
+| large | 180 min | 50% | 8% |
+
+These are for a policy row of cost 2. A row's spend = default × `cost / 2` (Opus high, cost 3, medium: 45% of 5-hour).
+
+## 2. Quota belongs to an account, not a model
+Opus and Haiku on one Claude account share its `5-hour` and `weekly` windows. Each candidate gets an **account
+key**: the hashed key from the usage reading (`quotaOf(...).account`) when present, else `machineId:engine`
+(contributed machines carry no key). Candidates with the same key share `left` and committed spend.
+
+## 3. Ordering (replaces v1's cheapest-first)
+Hard filters stay as today (offline, not listed, admission refused, exhausted window, …).
+
+**Step 1: strength (a filter).** Keep candidates that meet the floor (as v1; if none meets it, keep all).
+For `high` difficulty, keep only the highest `quality` among them. For `medium`/`low`, keep all that meet it.
+Strength beats fit (owner decision): a hard task is never handed to a weaker model because the strong ones are
+short of quota.
+
+**Step 2: fit.** For each window W in {5-hour, weekly} the candidate's account reports:
+- `usable = left − quotaReserve − committed(account, W)`
+- `needed = spend(W)`, or `spend(W) × resetsIn / runTime` when `resetsIn < runTime` (the window refills mid-task)
+- W fits when `usable ≥ needed`.
+
+Status: `short` if any reported window does not fit; `fits` if both windows are reported and fit; else `unknown`.
+Show Jev (and choose from) only the first non-empty group of **fits → unknown → short**. Candidates left out go to
+`excluded` with a plain reason ("the 5-hour window is expected to run out about halfway; resets in 3h").
+If only `short` is left, order it by **coverage** = min over reported windows of `usable / needed`, highest first,
+and the route's answer tells the Lead: "No candidate is expected to cover this task; its 5-hour quota is expected to
+run out partway and resets in 4h30." (Resuming after the reset stays manual in phase 1.)
+
+**Step 3: effective cost**, then order within the group by: effective cost ascending → quality descending →
+usable on the tightest window descending → idle member in the same repo before a new agent → title.
+- Start from the row's `cost`.
+- **Expiring quota is cheap:** if the 5-hour window resets within `runTime + 60 min`, its `usable` will be lost.
+ `covered = min(1, usable5h / needed5h)`; `effective = cost × (1 − covered)`. Fully covered → 0, and between rows at
+ 0 the stronger wins (quality descending).
+- **Weekly quota is dear for non-hard work:** `dayBudget = usableWeekly / max(1, daysToWeeklyReset)`. When
+ difficulty is not `high` and `neededWeekly > dayBudget`, add `cost × neededWeekly / dayBudget`.
+
+**Committed spend:** each recorded decision whose pick was started or assigned (`final` set) and whose `outcome` is
+still open reserves, on its account, `spend(W) × max(0, 1 − elapsed / runTime)` (elapsed from `createdAt`). Per
+Swarm only (the decision log is per Swarm). Read it from `routeHistory` (`service.ts`), which already returns the last
+50 decisions; add the pick's account key, spend per window and size.
+
+**Jev:** each candidate's label gains one sentence, e.g. "fits: needs about 30% of the 5-hour window (65% left,
+resets in 50m, otherwise unused); weekly 4% of 61%". New instruction text: "The list is already ordered by strength
+for the difficulty, fit and effective cost. Keep the first unless the task, its history or the policy notes give a
+clear reason otherwise." Jev's 3-second limit and fallback stay.
+
+## 4. Decision log
+`backend/src/superTabs/routeRecord.ts` is strict, so extend it first and keep every new field optional:
+`assessment.size`, and per candidate `fit: { status: 'fits'|'unknown'|'short', coverage: number|null,
+effectiveCost: number, expiring: number, spend: { '5-hour'?: number, weekly?: number }, account?: string }`.
+A record without them stays valid. The CLI must still record against an older backend: if `route.record` is refused
+as invalid, retry once with the v1 shape.
+
+## 5. Desktop
+- **Machines panel:** show quota for Claude and Codex only. Today a contributed machine's row also draws "—" for
+ every other engine it reports (`desktop/lib/super_tabs/machines.dart`, `_machine`, the `observation['quotas']` rows).
+- **A new Lead (new Swarm or + Project) may only be Claude or Codex.** Add an allowed-engines list to
+ `HarnessLaunchIntegration` (`desktop/lib/state/harness_launch_integration.dart`); `SuperTabLaunch.open`
+ (`desktop/lib/super_tabs/launch.dart`) sets `['claude', 'codex']` when `lead` is true; the composer's
+ `compatibleEngines` and engine choices (`desktop/lib/state/new_harness.dart`) honour it, as they already do for a
+ guest (`asGuest`). The machine stays free to choose: it joins the Swarm's Machines list on its own because the Lead
+ runs there (PR #1489's rule). Pin that with a backend test.
+- The decision row already shows each candidate's label, so the new sentence appears without other changes.
+
+## Acceptance examples (unit tests on `choose`; reserve 10%, default policy)
+1. high, medium. Opus high 5-hour 70% left, resets 40m; Sonnet (other account) 90%. → Opus high.
+2. high, large. Opus high 25% left, resets 4h; Codex default 85% left, resets 3h. → Codex.
+3. low, small. Account A: 5-hour 80% (resets 4h), weekly 12% (resets 5 days). Account B: 5-hour 60%, weekly 70%. → Haiku on B.
+4. low, small. Account A: 5-hour 60%, resets 20m; weekly 60%, resets 2 days. Account B: 5-hour 90%, resets 4h. → Opus high on A.
+5. Two high, medium routes a minute apart; Opus accounts A 60%, B 58%, both reset in 3h. → first A, second B.
+6. high, large. Opus high 40% left, resets 1h. → fits (needs 25% before the reset).
+7. high, large. Opus high 30% (resets 4h); Codex 40% (resets 4h30); Sonnet elsewhere 95%. → Codex, never Sonnet;
+ the answer says it is expected to run out.
+8. No `size`. → treated as medium.
+
+## Rules
+- Branch from current `main`. No commit, push, PR or release until the owner asks.
+- Tests never touch port 18473, `~/.harness`, `~/.claude`, `~/.codex` or the real tmux; never call the real Jev,
+ OpenRouter or `gh`. CLI on Node 24; run `npm run test:super-tabs` (100% coverage gate) in cli and backend.
+- Visible copy in English, plain words, per `docs/naming-system.md` (the product is **Swarm**, the role **Lead**).
+- Comments say why. No dead code or debug output.
+
+## Later (not this phase)
+Other engines join routing one at a time when (1) they have a quota reader or are known to have no window,
+(2) the policy rates their quality and cost, and (3) an end-to-end run shows the Lead can start, deliver to and observe
+them. OpenCode first. Then: learn spend and run time from finished work.