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.

Combined merge 10-30 D: five reviewed PRs (#2313 #2311 #2276 #2260 #2315) (#2321)

0xken152024f42f5a78
diff --git a/backend/integration/superTabBuddies.test.ts b/backend/integration/superTabBuddies.test.ts
index 18c4d483d..d701875ba 100644
--- a/backend/integration/superTabBuddies.test.ts
+++ b/backend/integration/superTabBuddies.test.ts
@@ -270,6 +270,46 @@ describe('a Buddy through the store', () => {
await expect(f.store.costSummary(peer, f.tab, 7, agentId)).rejects.toThrow('A Buddy reads no routing')
})
+ it('never reads the nightly routing reflection, which says what each engine and model cost: routing too', async () => {
+ const f = await swarm()
+ const { agentId } = await buddy(f)
+ const group = String((await f.execute({ type: 'conversation.create', projectId: 'lead', title: 'Parser', brief: '', checks: [] })).result.conversationId)
+ const at = Date.now() - 60 * 60_000
+ await db.superTabRouteDecision.create({ data: { id: randomUUID(), tabId: f.tab, conversationId: group, assignmentId: randomUUID(), outcome: 'done',
+ createdAt: new Date(at), final: { kind: 'member' }, record: { assessment: { kind: 'parser' } }, run: { machineId: 'peer-mac', harnessId: 'h',
+ engine: 'claude', model: 'opus', effort: 'high', billing: 'subscription', startedAt: at, start: {}, endedAt: at + 60_000, end: {} } } })
+ expect(await f.store.postReflection(f.tab, 'lead', '2026-10-30')).toBe('posted')
+ const report = (await f.store.messages(peer, f.tab, 'lead', {})).messages.find(m => (m.source as { kind?: unknown } | null)?.kind === 'routing-reflection')
+ expect(report?.text).toContain('- claude opus high, parser: 1 attempt, 0 shipped')
+ expect((await f.store.messages(peer, f.tab, 'lead', {}, agentId)).messages.map(m => m.id)).not.toContain(report!.id)
+ await expect(f.store.messages(peer, f.tab, 'lead', { messageId: report!.id }, agentId)).resolves.toMatchObject({ messages: [] })
+ })
+
+ it('never reads the routing proposals asked of its person: not in its decisions, nor as the PM\'s line when its person leaves one to the PM (review of #2276)', async () => {
+ const f = await swarm()
+ const { agentId, chat } = await buddy(f)
+ // Two proposals as the nightly reflection asks them (store.ts postReflection): of peer, by the PM, in the project chat, tagged.
+ const proposal = (title: string) => ({ id: randomUUID(), tabId: f.tab, batchId: randomUUID(), projectId: 'lead', conversationId: 'lead', assignmentId: null,
+ personId: peer.sub, askerAgentId: f.lead, question: `${title}? Expected saving: about $10.00 a week at API prices.`,
+ options: ['Yes: the Lead routes this way from now on', 'No: keep routing as it is', 'Not yet: ask again when there is more evidence'],
+ recommended: 0, unblocks: 'If you say yes, the Lead routes parser work this way.', createdAt: new Date(), kind: 'routing-reflection' })
+ const routing = [proposal('Route parser work to claude sonnet medium instead of claude opus high'), proposal('Stop routing ui work to codex gpt-6.1-sol high')]
+ await db.superTabDecision.createMany({ data: routing })
+ await f.execute({ type: 'decision.ask', conversationId: 'lead', personId: peer.sub, questions: [{ question: 'Which week?',
+ options: ['This week', 'Next week'], recommended: 0, unblocks: 'The plan' }] }, owner, f.lead)
+ const theirs = (await f.store.decisions(peer, f.tab, 'open')).decisions
+ expect(theirs.map(d => d.question).sort()).toEqual([...routing.map(r => r.question), 'Which week?'].sort())
+ expect((await f.store.decisions(peer, f.tab, 'open', agentId)).decisions.map(d => d.question)).toEqual(['Which week?'])
+ // Left to the PM: the plain one's line reaches the Buddy chat, the proposal's never does, and the Buddy's answered list holds no proposal.
+ await f.execute({ type: 'decision.answer', decisionId: routing[0]!.id, delegate: true }, peer)
+ await f.execute({ type: 'decision.answer', decisionId: theirs.find(d => d.question === 'Which week?')!.id, delegate: true }, peer)
+ const lines = (await f.store.messages(peer, f.tab, chat, {})).messages.map(m => m.text)
+ expect(lines).toContain('PM decided: This week — Which week?')
+ expect(lines.join('\n')).not.toContain('Route parser work')
+ expect((await f.store.decisions(peer, f.tab, 'settled', agentId)).decisions.map(d => d.question)).toEqual(['Which week?'])
+ expect((await f.store.decisions(peer, f.tab, 'settled')).decisions.map(d => d.question)).toContain(routing[0]!.question)
+ })
+
it('still reads a task archived before the PM reported on it, until it leaves the active set (security review 1 of #2115)', async () => {
const f = await swarm()
const { agentId } = await buddy(f)
diff --git a/backend/integration/superTabReflection.test.ts b/backend/integration/superTabReflection.test.ts
new file mode 100644
index 000000000..888ef5f59
--- /dev/null
+++ b/backend/integration/superTabReflection.test.ts
@@ -0,0 +1,310 @@
+import { randomUUID } from 'node:crypto'
+import { execFile } from 'node:child_process'
+import { promisify } from 'node:util'
+import { join } from 'node:path'
+import { tmpdir } from 'node:os'
+import { afterAll, beforeAll, describe, expect, it } from 'vitest'
+import { MongoMemoryReplSet } from 'mongodb-memory-server-core'
+import { PrismaClient } from '@prisma/client'
+import type { AuthUser } from '../src/lib/ssoAuth.js'
+import { SuperTabStore } from '../src/superTabs/store.js'
+import type { Command } from '../src/superTabs/commands.js'
+import type { TokensByModel } from '../src/superTabs/costs/tokens.js'
+import { reflectNightly } from '../src/lib/routingReflection.js'
+import { proposalTitle } from '../src/superTabs/costs/reflection.js'
+import { poolRows } from './hostRows.test-support.js'
+
+// The nightly routing reflection (Scholes's roadmap, piece 2, 10-30): at 23:00 in the project's zone the worker posts what its
+// routed work cost and how it went, and asks its owner about routing changes. A fresh loopback replica set, created here.
+let replica: MongoMemoryReplSet
+let db: PrismaClient
+const owner: AuthUser = { sub: '310000000000000000000001', email: '[email protected]', autonomousEnv: 'prod', role: 'user' }
+const host: AuthUser = { sub: '310000000000000000000003', email: '[email protected]', autonomousEnv: 'prod', role: 'user' }
+const config = { engine: 'claude', model: 'opus', effort: 'high', contextWindow: 200000, engineVersion: 'fixture' }
+const MINUTE = 60_000, HOUR = 60 * MINUTE, DAY = 24 * HOUR
+const plan = [{ engine: 'claude', known: true, windows: [{ name: '5-hour', usedPercent: 10, resetsAt: null }] }]
+const opus = (input: number): TokensByModel => ({ 'claude-opus-5-5': { input, output: 0, cacheRead: 0, cacheWrite: 0 } })
+/** 17:00 in Vietnam on 2026-10-30, and 23:10 that evening. */
+const AFTERNOON = Date.UTC(2026, 9, 30, 10, 0)
+const NIGHT = Date.UTC(2026, 9, 30, 16, 10)
+const GRID = 'deepseek/deepseek-v4.1-flash-1017'
+
+beforeAll(async () => {
+ replica = await MongoMemoryReplSet.create({ binary: { version: '7.0.24', downloadDir: join(tmpdir(), 'harness-super-tab-mongodb-binaries') },
+ replSet: { count: 1, ip: '127.0.0.1', storageEngine: 'wiredTiger' } })
+ const uri = replica.getUri(`swarm_reflection_test_${randomUUID().replaceAll('-', '_')}`)
+ await promisify(execFile)(join(process.cwd(), 'node_modules/.bin/prisma'), ['db', 'push', '--skip-generate'], {
+ env: { ...process.env, DATABASE_URL: uri }, timeout: 60000,
+ })
+ db = new PrismaClient({ datasources: { db: { url: uri } } })
+ for (const user of [owner, host]) await db.user.create({ data: { id: user.sub, externalId: `fixture-${user.sub}`, email: user.email, autonomousEnv: user.autonomousEnv } })
+ for (const machineId of ['lead-host', 'test-host']) {
+ await db.machine.create({ data: { machineId, userId: host.sub, apiKey: `fixture-${machineId}`, managerId: 'fixture', autonomousEnv: 'prod', authMode: 'remote' } })
+ await db.machineShare.create({ data: { machineId, ownerId: host.sub, autonomousEnv: 'prod', emails: [owner.email] } })
+ }
+})
+afterAll(async () => {
+ await db?.$disconnect()
+ await replica?.stop()
+})
+
+/** A Swarm whose Lead routes "Ship the parser" (kind `parser`) to a worker, which ships it in 12 minutes on Opus for $4. */
+async function swarm() {
+ let now = AFTERNOON
+ const store = new SuperTabStore(db, () => now, null)
+ const tab = (await store.create(owner, randomUUID(), 'Reflection', 'public')).id
+ const execute = (command: Command, user = owner, asAgentId?: string) => store.execute(user, tab, { operationId: randomUUID(), command }, asAgentId)
+ const invitation = await execute({ type: 'invite.create', email: host.email, role: 'collaborator', conversationId: 'lead' })
+ await execute({ type: 'invite.accept', inviteId: invitation.result.inviteId as string }, host)
+ for (const [machineId, name] of [['lead-host', 'Lead Mac'], ['test-host', 'Worker Mac']]) {
+ await execute({ type: 'machine.contribute', machineId: machineId!, name: name!, cwd: '/repo', engines: ['claude'], maxAgents: 4 }, host)
+ }
+ const generations = new Map<string, string>()
+ for (const machineId of ['lead-host', 'test-host']) generations.set(machineId, (await poolRows(store, host, machineId)).find(p => p.tabId === tab)!.machine.generation)
+ const harness = { lead: randomUUID(), worker: randomUUID() }
+ const lead = String((await execute({ type: 'agent.add', conversationId: 'lead', machineId: 'lead-host', harnessId: harness.lead, name: 'Lead',
+ configuration: config, lead: true })).result.agentId)
+ const group = String((await execute({ type: 'conversation.create', title: 'Secret parser plan', brief: 'Implement it',
+ checks: [{ description: 'Verified', independent: false }] })).result.conversationId)
+ const worker = String((await execute({ type: 'agent.add', conversationId: group, machineId: 'test-host', harnessId: harness.worker, name: 'Worker',
+ configuration: config, lead: false })).result.agentId)
+ const beat = async (tokens: TokensByModel) => {
+ for (const [machineId, running] of [['lead-host', [harness.lead]], ['test-host', [harness.worker]]] as const) {
+ await store.observeMachine(host, tab, machineId, { generation: generations.get(machineId)!, resources: { cpuPercent: 10, memoryTotalBytes: 32e9,
+ memoryUsedBytes: 4e9, diskFreeBytes: 120e9, diskTotalBytes: 500e9, projectDiskFreeBytes: 120e9, deviceType: 'Laptop', chip: 'Fixture', os: 'macOS',
+ gpuPercent: null }, quotas: plan, tools: {}, runningHarnessIds: [...running], stoppedHarnessIds: [],
+ ...machineId === 'test-host' ? { harnessTokens: { [harness.worker]: tokens }, harnessProgress: { [harness.worker]: now } } : {} })
+ }
+ }
+ /** Routes, assigns and ships the parser task: its evidence row is what makes the project a candidate. */
+ const ship = async () => {
+ await beat(opus(0))
+ const decision = { assessment: { difficulty: 'medium', risk: 'low', why: 'Parser work.', size: 'medium', kind: 'parser' },
+ candidates: [{ id: 'c0', kind: 'member', agentId: worker, machineId: 'test-host', engine: 'claude', model: 'opus', effort: 'high',
+ quality: 3, cost: 3, title: 'Worker', label: 'Worker' }],
+ excluded: [], floor: 1, notes: false, pick: 'c0', via: 'only', p: null, belowFloor: false, why: 'Only candidate.' }
+ const routeDecisionId = String((await execute({ type: 'route.record', conversationId: group, decision } as Command, host, lead)).result.routeDecisionId)
+ const assignmentId = String((await execute({ type: 'work.assign', conversationId: group, agentId: worker, routeDecisionId } as Command, host, lead)).result.assignmentId)
+ now += 12 * MINUTE
+ const checkId = (await store.read(owner, tab)).state.conversations.find(c => c.id === group)!.checks[0]!.id
+ await execute({ type: 'work.check', conversationId: group, assignmentId, checkId, passed: true, evidence: 'npm test, 0 failures' } as Command, host, worker)
+ await execute({ type: 'work.status', conversationId: group, assignmentId, status: 'done', result: 'Shipped.', tokens: opus(1_000_000) } as Command, host, worker)
+ }
+ /** A task of `projectId` whose grid attempt failed and stepped up to Sonnet, as their route decisions keep them. */
+ const stepUpFromGrid = async (projectId = 'lead', title = 'Secret grid task') => {
+ const id = String((await execute({ type: 'conversation.create', projectId, title, brief: '', checks: [] })).result.conversationId)
+ await seed(id, { grid: true, at: now - 3 * HOUR })
+ await seed(id, { stepUp: true, at: now - HOUR })
+ return id
+ }
+ const seed = (conversationId: string, o: { grid?: boolean; stepUp?: boolean; at: number; outcome?: string }) => db.superTabRouteDecision.create({ data: {
+ id: randomUUID(), tabId: tab, conversationId, assignmentId: randomUUID(), outcome: o.outcome ?? 'done', createdAt: new Date(o.at), final: { kind: 'member' },
+ record: { assessment: { kind: 'parser' }, ...o.stepUp ? { stepUp: { attempt: 2, reason: 'Its first review said Ready no.' } } : {} },
+ run: o.grid ? { machineId: 'test-host', harnessId: 'h', engine: 'claude', model: 'opus', effort: 'low', grid: GRID, billing: 'own-hardware',
+ startedAt: o.at, start: {}, endedAt: o.at + HOUR, end: {} }
+ : { machineId: 'test-host', harnessId: 'h', engine: 'claude', model: 'sonnet', effort: 'medium', billing: 'subscription', startedAt: o.at, start: {},
+ endedAt: o.at + HOUR, end: { 'claude-sonnet-5-5': { input: 1_000_000, output: 0, cacheRead: 0, cacheWrite: 0 } } } } })
+ const reports = async (conversationId = 'lead') => (await db.superTabMessage.findMany({ where: { tabId: tab, conversationId } }))
+ // The people's report: the Lead's own reminder of the same kind has the Lead as its recipient.
+ .filter(m => (m.source as { kind?: unknown } | null)?.kind === 'routing-reflection' && !m.recipientIds.length)
+ return { store, tab, execute, lead, group, ship, stepUpFromGrid, seed, reports,
+ clock: { get now() { return now }, set now(value: number) { now = value } } }
+}
+
+describe('the nightly routing reflection', () => {
+ it('posts a seeded day once in the project chat at 23:00, under the Lead, and asks the owner each proposal once', async () => {
+ const f = await swarm()
+ await f.ship()
+ for (let i = 0; i < 3; i++) await f.stepUpFromGrid()
+ f.clock.now = NIGHT - 3 * HOUR
+ // Before 23:00 in Vietnam, nothing.
+ await reflectNightly(db, f.store, f.clock.now)
+ expect(await f.reports()).toEqual([])
+ f.clock.now = NIGHT
+ // Two passes at once, as two workers in a rolling deploy: one report.
+ await Promise.all([reflectNightly(db, f.store, NIGHT), reflectNightly(db, f.store, NIGHT)])
+ await reflectNightly(db, f.store, NIGHT + 15 * MINUTE)
+ const [report, ...more] = await f.reports()
+ expect(more).toEqual([])
+ expect(report!.author).toMatchObject({ kind: 'agent', id: f.lead })
+ expect(report!.recipientIds).toEqual([])
+ const lines = report!.text.split('\n')
+ expect(lines).toContain('Last day: 7 attempts, 1 shipped. Last 7 days: 7 attempts, 1 shipped.')
+ expect(lines).toContain('- claude opus high, parser: 1 attempt, 1 shipped, median 12 min to ship, $4.00 per shipped change, no first review')
+ expect(lines).toContain(`- claude ${GRID} low, parser: 3 attempts, 0 shipped, no first review`)
+ expect(lines).toContain('- claude sonnet medium, parser: 3 attempts, 0 shipped, no first review, 3 step-ups')
+ expect(lines).toContain('1. Start parser work on a subscription model instead of the grid: about 3 hours to ship a week. '
+ + '3 of 3 parser tasks started on the grid stepped up after their grid attempt failed. Only 3 tasks. Asked of the project owner.')
+ // Counts only: no task title, machine or person.
+ for (const secret of ['Secret', 'Worker Mac', 'test-host', owner.email, host.email]) expect(report!.text).not.toContain(secret)
+ const decisions = await db.superTabDecision.findMany({ where: { tabId: f.tab } })
+ expect(decisions).toEqual([expect.objectContaining({ personId: owner.sub, askerAgentId: f.lead, conversationId: 'lead', assignmentId: null,
+ question: 'Start parser work on a subscription model instead of the grid? Expected saving: about 3 hours to ship a week. '
+ + '3 of 3 parser tasks started on the grid stepped up after their grid attempt failed. Only 3 tasks.',
+ options: ['Yes: the Lead is reminded each night and routes this way; nothing changes by itself', 'No: keep routing as it is',
+ 'Not yet: ask again when there is more evidence'],
+ // Three tasks are too few to recommend Yes (review of #2276).
+ recommended: 2, kind: 'routing-reflection' })])
+ expect(await f.store.postReflection(f.tab, 'lead', '2026-10-30')).toBe('already')
+ // The next night, the same proposal still waits: it is not asked again.
+ expect(await f.store.postReflection(f.tab, 'lead', '2026-10-31')).toBe('posted')
+ expect(await db.superTabDecision.count({ where: { tabId: f.tab } })).toBe(1)
+ expect((await f.reports()).at(-1)!.text).toContain("Only 3 tasks. Waiting for the owner's answer since 2026-10-30.")
+ // People read it; it is a notice for people, not a wake for the Lead.
+ expect((await f.store.messages(host, f.tab, 'lead', {})).messages.map(m => m.id)).toContain(report!.id)
+ })
+
+ it('asks an answered proposal again only after 14 days, and lists an approved one each night for 30 days, to people and to the Lead (reviews of #2276)', async () => {
+ const f = await swarm()
+ await f.ship()
+ for (let i = 0; i < 3; i++) await f.stepUpFromGrid()
+ const GRID_TITLE = 'Start parser work on a subscription model instead of the grid'
+ /** The report [days] after the first night, with an attempt in its last day. */
+ const night = async (on: string, days: number) => {
+ f.clock.now = NIGHT + days * DAY
+ await f.seed(f.group, { at: f.clock.now - HOUR })
+ expect(await f.store.postReflection(f.tab, 'lead', on)).toBe('posted')
+ return (await f.reports()).at(-1)!.text
+ }
+ expect(await night('2026-10-30', 0)).toContain('Asked of the project owner.')
+ const [first] = await db.superTabDecision.findMany({ where: { tabId: f.tab } })
+ await f.execute({ type: 'decision.answer', decisionId: first!.id, choice: 1 })
+ // The owner said No: the next night neither asks nor proposes it.
+ expect(await night('2026-10-31', 1)).toContain('No change proposed.')
+ expect(await db.superTabDecision.count({ where: { tabId: f.tab } })).toBe(1)
+ // Fifteen days after that answer it is asked again.
+ await db.superTabDecision.update({ where: { id: first!.id }, data: { answeredAt: new Date(NIGHT - 15 * DAY) } })
+ expect(await night('2026-11-01', 2)).toContain(`${GRID_TITLE}: about 3 hours`)
+ const again = (await db.superTabDecision.findMany({ where: { tabId: f.tab, OR: [{ answeredAt: null }, { answeredAt: { isSet: false } }] } }))
+ expect(again.map(d => proposalTitle(d.question))).toEqual([GRID_TITLE])
+ // Approved after midnight in Vietnam (18:10 UTC): every later night lists it under the local date, to people and to the Lead.
+ f.clock.now = NIGHT + 2 * DAY + 2 * HOUR
+ await f.execute({ type: 'decision.answer', decisionId: again[0]!.id, choice: 0 })
+ const approved = await night('2026-11-02', 3)
+ expect(approved.split('\n')).toEqual(expect.arrayContaining([
+ 'Approved changes: the Lead is reminded each night and routes this way; each is listed for 30 days:',
+ `- ${GRID_TITLE} (approved 2026-11-02)`, 'No change proposed.']))
+ expect(await db.superTabDecision.count({ where: { tabId: f.tab } })).toBe(2)
+ // The Lead's own reminder (delta review of #2276): to it alone, not a line people read.
+ const reminder = `Approved routing changes: route this way until routing does it by itself. This reminder repeats each night for 30 days `
+ + `after each approval.\n- ${GRID_TITLE} (approved 2026-11-02)`
+ const toLead = (await db.superTabMessage.findMany({ where: { tabId: f.tab, conversationId: 'lead', text: reminder } }))
+ expect(toLead.map(m => m.recipientIds)).toEqual([[f.lead]])
+ expect((await f.store.messages(host, f.tab, 'lead', {})).messages.map(m => m.id)).not.toContain(toLead[0]!.id)
+ expect((await f.store.messages(host, f.tab, 'lead', {}, f.lead)).messages.map(m => m.id)).toContain(toLead[0]!.id)
+ // Thirty days on, the approval is no longer listed or reminded, and the change may be proposed again.
+ await db.superTabDecision.update({ where: { id: again[0]!.id }, data: { answeredAt: new Date(NIGHT - 28 * DAY) } })
+ const later = await night('2026-11-03', 4)
+ expect(later).not.toContain('Approved changes')
+ expect(later).toContain(`${GRID_TITLE}: about 3 hours`)
+ expect(await db.superTabMessage.count({ where: { tabId: f.tab, conversationId: 'lead', recipientIds: { has: f.lead }, text: { startsWith: 'Approved routing' } } })).toBe(1)
+ // Left to the PM, an approval says the PM decided, never the owner.
+ const [third] = (await db.superTabDecision.findMany({ where: { tabId: f.tab, OR: [{ answeredAt: null }, { answeredAt: { isSet: false } }] } }))
+ await db.superTabDecision.update({ where: { id: third!.id }, data: { choice: 0, delegated: true, answeredAt: new Date(f.clock.now) } })
+ expect(await night('2026-11-04', 5)).toContain(`- ${GRID_TITLE} (PM decided 2026-11-03)`)
+ })
+
+ it('keeps at most three proposals open, says when one was not asked, and lets one unanswered for 7 days expire (review of #2276)', async () => {
+ const f = await swarm()
+ await f.ship()
+ for (let i = 0; i < 3; i++) await f.stepUpFromGrid()
+ const open = (title: string) => ({ id: randomUUID(), tabId: f.tab, batchId: 'earlier', projectId: 'lead', conversationId: 'lead', assignmentId: null,
+ personId: owner.sub, askerAgentId: f.lead, question: `${title}? Expected saving: about $1.00 a week at API prices.`, options: ['Yes', 'No', 'Not yet'],
+ recommended: 2, unblocks: 'If you say yes.', createdAt: new Date(NIGHT - 6 * DAY), kind: 'routing-reflection' })
+ await db.superTabDecision.createMany({ data: ['ui', 'docs', 'tests'].map(kind => open(`Stop routing ${kind} work to claude opus high`)) })
+ f.clock.now = NIGHT
+ expect(await f.store.postReflection(f.tab, 'lead', '2026-10-30')).toBe('posted')
+ expect(await db.superTabDecision.count({ where: { tabId: f.tab } })).toBe(3)
+ expect((await f.reports()).at(-1)!.text).toContain("Only 3 tasks. Not asked: at most 3 proposals wait for the owner's answer at once.")
+ // Two days on, the three are 8 days old. The owner also has 17 other open decisions from the Lead: 20 with the three, the
+ // most one asker may hold. The three expire before they are counted, so the proposal is asked (delta review of #2276).
+ await db.superTabDecision.createMany({ data: Array.from({ length: 17 }, (_, i) => ({ id: randomUUID(), tabId: f.tab, batchId: 'plain', projectId: 'lead',
+ conversationId: 'lead', personId: owner.sub, askerAgentId: f.lead, question: `Question ${i}?`, options: ['Yes', 'No'], recommended: 0, unblocks: 'x',
+ createdAt: new Date(NIGHT) })) })
+ f.clock.now = NIGHT + 2 * DAY
+ await f.seed(f.group, { at: f.clock.now - HOUR })
+ expect(await f.store.postReflection(f.tab, 'lead', '2026-11-01')).toBe('posted')
+ const proposals = () => db.superTabDecision.findMany({ where: { tabId: f.tab, kind: 'routing-reflection' } })
+ expect((await proposals()).map(d => proposalTitle(d.question))).toEqual(['Start parser work on a subscription model instead of the grid'])
+ expect((await f.reports()).at(-1)!.text).toContain('Only 3 tasks. Asked of the project owner.')
+ // Unanswered for 8 days, it expires on a night with nothing to report too.
+ f.clock.now = NIGHT + 10 * DAY
+ expect(await f.store.postReflection(f.tab, 'lead', '2026-11-09')).toBe('empty')
+ expect(await proposals()).toEqual([])
+ expect(await db.superTabDecision.count({ where: { tabId: f.tab } })).toBe(17)
+ })
+
+ it('posts nothing for a day with no attempt, and skips a project with no routed work', async () => {
+ const f = await swarm()
+ const quiet = (await f.execute({ type: 'project.create', name: 'Quiet', visibility: 'public', brief: '' })).result as { projectId: string; conversationId: string }
+ await f.execute({ type: 'agent.add', conversationId: quiet.conversationId, machineId: 'lead-host', harnessId: randomUUID(), name: 'Quiet Lead',
+ configuration: config, lead: true })
+ await f.ship()
+ // Two days later the evidence is still this week's, but the last day had no attempt.
+ f.clock.now = NIGHT + 2 * DAY
+ const pass = await reflectNightly(db, f.store, f.clock.now)
+ expect(await f.reports()).toEqual([])
+ expect(await f.reports(quiet.conversationId)).toEqual([])
+ expect(pass.posted).toBe(0)
+ expect(await f.store.postReflection(f.tab, 'lead', '2026-11-01')).toBe('empty')
+ // The quiet project has no evidence, so no pass reads it; asked directly, it has nothing to say.
+ expect(await f.store.postReflection(f.tab, quiet.projectId, '2026-11-01')).toBe('empty')
+ expect(await db.superTabDecision.count({ where: { tabId: f.tab } })).toBe(0)
+ })
+
+ it('counts only its own project: never another project’s tasks, a private chat or the Leads conversation, and posts each where its people read it', async () => {
+ const f = await swarm()
+ await f.ship()
+ // A private project of the owner's alone, with its own Lead and a stepped-up task.
+ const hidden = (await f.execute({ type: 'project.create', name: 'Hidden', visibility: 'private', brief: '' })).result as { projectId: string; conversationId: string }
+ const hiddenLead = String((await f.execute({ type: 'agent.add', conversationId: hidden.conversationId, machineId: 'lead-host', harnessId: randomUUID(),
+ name: 'Hidden Lead', configuration: config, lead: true })).result.agentId)
+ await f.stepUpFromGrid(hidden.projectId, 'Hidden grid task')
+ await db.superTabModelEvidence.create({ data: { id: randomUUID(), tabId: f.tab, projectId: hidden.projectId, engine: 'claude', model: 'opus', kind: 'feature',
+ week: new Date(Date.UTC(2026, 9, 26)), updatedAt: new Date(f.clock.now) } })
+ // Attempts in a private chat and in the Leads conversation of this project's Swarm.
+ const chat = String((await f.execute({ type: 'buddy.chat', projectId: 'lead' }, host)).result.conversationId)
+ const leads = (await f.store.read(owner, f.tab)).state.leadsConversationId!
+ for (const conversationId of [chat, leads, 'lead', hidden.conversationId]) await f.seed(conversationId, { at: f.clock.now - HOUR })
+ f.clock.now = NIGHT
+ const pass = await reflectNightly(db, f.store, NIGHT)
+ expect(pass.failed).toBe(0)
+ const [mine] = await f.reports(), [theirs] = await f.reports(hidden.conversationId)
+ expect(mine!.text).toContain('Last day: 1 attempt, 1 shipped.')
+ expect(mine!.text).not.toContain('step-up')
+ expect(theirs!.text).toContain('Last day: 2 attempts, 0 shipped.')
+ expect(theirs!.author).toMatchObject({ id: hiddenLead })
+ // Someone outside the private project reads neither its chat nor its report; asking by another Swarm's id finds nothing.
+ await expect(f.store.messages(host, f.tab, hidden.conversationId, {})).rejects.toMatchObject({ code: 'NOT_FOUND' })
+ await expect(f.store.messages(host, f.tab, hidden.conversationId, { messageId: theirs!.id })).rejects.toMatchObject({ code: 'NOT_FOUND' })
+ const other = await swarm()
+ expect(await other.store.postReflection(other.tab, hidden.projectId, '2026-10-30')).toBe('skipped')
+ expect(await f.store.postReflection(f.tab, 'no-such-project', '2026-10-30')).toBe('skipped')
+ expect(await other.reports(hidden.conversationId)).toEqual([])
+ })
+
+ it('tries a failed report again on the next pass, and the other projects still get theirs', async () => {
+ const f = await swarm()
+ await f.ship()
+ // A second project of the same Swarm, with its own Lead and a day of routed work.
+ const web = (await f.execute({ type: 'project.create', name: 'Web', visibility: 'public', brief: '' })).result as { projectId: string; conversationId: string }
+ await f.execute({ type: 'agent.add', conversationId: web.conversationId, machineId: 'lead-host', harnessId: randomUUID(), name: 'Web Lead',
+ configuration: config, lead: true })
+ await f.stepUpFromGrid(web.projectId, 'Web grid task')
+ await db.superTabModelEvidence.create({ data: { id: randomUUID(), tabId: f.tab, projectId: web.projectId, engine: 'claude', model: 'opus', kind: 'feature',
+ week: new Date(Date.UTC(2026, 9, 26)), updatedAt: new Date(f.clock.now) } })
+ f.clock.now = NIGHT
+ let failures = 1
+ const flaky = { postReflection: async (...args: Parameters<SuperTabStore['postReflection']>) => {
+ if (args[0] === f.tab && args[1] === 'lead' && failures-- > 0) throw new Error('The database read timed out')
+ return f.store.postReflection(...args)
+ } }
+ const warned: unknown[] = []
+ expect(await reflectNightly(db, flaky, NIGHT, { warn: (...a: unknown[]) => { warned.push(a) } })).toMatchObject({ failed: 1 })
+ expect(await f.reports()).toEqual([])
+ expect(await f.reports(web.conversationId)).toHaveLength(1)
+ expect(warned).toHaveLength(1)
+ await reflectNightly(db, flaky, NIGHT + 15 * MINUTE)
+ expect(await f.reports()).toHaveLength(1)
+ })
+})
diff --git a/backend/integration/superTabRouteDecisions.test.ts b/backend/integration/superTabRouteDecisions.test.ts
index 8278b5a84..c900845d3 100644
--- a/backend/integration/superTabRouteDecisions.test.ts
+++ b/backend/integration/superTabRouteDecisions.test.ts
@@ -199,6 +199,47 @@ describe('what the route-decision list gives each reader', () => {
}
})
+ it('finds the reader\'s older decisions in a group the newest 500 never name, when it reads between 1 and 99 of them', async () => {
+ const w = await world(5)
+ // Newest last: 70 in a quiet public group, then 480 the collaborator and the workers of Web cannot read, then 30 in Web.
+ await decide(w, [[w.finished[0]!, 70], [w.secretGroup, 480], [w.web, 30]])
+ const got = await sameAnswers(w)
+ for (const reader of ['a collaborator', 'a worker', 'the Lead']) expect(ids(got[reader]), reader).toHaveLength(100)
+ expect(new Set((got['a collaborator']!.value as Array<{ conversationId: string }>).map(d => d.conversationId))).toEqual(new Set([w.web, w.finished[0]]))
+ })
+
+ it('finds a quiet group stored with no project in a default-project agent\'s project, when the newest 500 name none of it', async () => {
+ const w = await world(5)
+ const quiet = w.finished[0]!
+ // A group from before projects: no project in its data or its listing, which belongs to the Swarm's first (groupProject).
+ await db.$runCommandRaw({ update: 'SwarmGroup', updates: [{ q: { tabId: w.tabId, key: quiet }, u: { $set: { projectId: null }, $unset: { 'data.projectId': '' } } }] })
+ await decide(w, [[quiet, 20], [w.secretGroup, 600]])
+ const got = await sameAnswers(w)
+ expect(ids(got['a worker']), 'the worker of the default project reads it').toHaveLength(20)
+ expect(ids(got['the Lead'])).toHaveLength(20)
+ expect(ids(got['the Secret project\'s worker'])).toHaveLength(100)
+ })
+
+ it('checks access on the light groups of quiet conversations too: a closed Chat with PM, a Buddy chat and a private project\'s group, all dormant', async () => {
+ const w = await world(5)
+ // The conversations a reader must be kept out of are quiet, so they come through the light read, not the Swarm's active groups.
+ await db.$runCommandRaw({ update: 'SwarmGroup', updates: [{ q: { tabId: w.tabId, key: { $in: [w.peerChat, w.buddyChat, w.secretGroup] } },
+ u: { $set: { dormant: true, 'data.dormant': true } }, multi: true }] })
+ // Oldest first: the hidden ones on both sides of 600 secret decisions, so some are in the newest 500 and some only a fallback finds.
+ await decide(w, [[w.web, 3], [w.peerChat, 5], [w.buddyChat, 5], [w.secretGroup, 600], [w.peerChat, 5], [w.buddyChat, 5], [w.web, 3]],
+ [w.peerChat, w.buddyChat])
+ const got = await sameAnswers(w)
+ const seen = (name: string) => new Set((got[name]!.value as Array<{ conversationId: string }>).map(d => d.conversationId))
+ // The answers tell readers apart, or "same as before" proves little: the collaborator reads its Buddy chat and nobody the closed
+ // Chat with PM, which differ only in the kind and the audience the light group keeps.
+ expect(seen('a collaborator').has(w.buddyChat)).toBe(true)
+ for (const name of ['a collaborator', 'the owner', 'a member outside the private project', 'a worker', 'the Lead']) expect(seen(name).has(w.peerChat), name).toBe(false)
+ for (const name of ['the owner', 'a member outside the private project', 'a worker', 'the Lead']) expect(seen(name).has(w.buddyChat), name).toBe(false)
+ expect(seen('a member outside the private project').has(w.secretGroup)).toBe(false)
+ expect(seen('the owner').has(w.secretGroup)).toBe(true)
+ expect(JSON.stringify(got['a member outside the private project'])).not.toContain('hidden-text-of-')
+ })
+
it('stops at one window of decisions when the Swarm holds no more than that, even if the reader reads fewer than a hundred of them', async () => {
const w = await world(5)
await decide(w, [[w.secretGroup, 60], [w.web, 40]], [w.secretGroup])
@@ -238,7 +279,9 @@ async function profiled<T>(read: () => Promise<T>): Promise<[T, Record<string, P
await db.$runCommandRaw({ profile: 2 })
const result = await read()
await db.$runCommandRaw({ profile: 0 })
- const found = await db.$runCommandRaw({ find: 'system.profile', filter: { 'command.profile': { $exists: false } }, batchSize: 10000 }) as
+ const found = await db.$runCommandRaw({ find: 'system.profile', filter: { 'command.profile': { $exists: false } },
+ // Only the fields read: a pipeline in the profile can hold a `$type` expression, which Prisma reads back as a tagged value.
+ projection: { ns: 1, planSummary: 1, docsExamined: 1, nreturned: 1, responseLength: 1, 'command.hint': 1 }, batchSize: 10000 }) as
unknown as { cursor: { firstBatch: Array<{ ns: string; planSummary?: string; docsExamined?: number; nreturned?: number; responseLength?: number; command?: { hint?: unknown } }> } }
await db.$runCommandRaw({ drop: 'system.profile' })
const by: Record<string, Profiled> = {}
@@ -272,4 +315,16 @@ describe('what the route-decision list costs the database', () => {
// The answer is what it was.
expect(answer).toEqual(await listedBefore(w, owner, w.lead))
})
+
+ it('reads the groups the decisions name with only the fields access needs, not their briefs and tasks', async () => {
+ const w = await world(QUIET)
+ const brief = 'x'.repeat(4000)
+ await db.$runCommandRaw({ update: 'SwarmGroup', updates: [{ q: { tabId: w.tabId }, u: { $set: { 'data.brief': brief } }, multi: true }] })
+ await decide(w, w.finished.slice(0, 300).map(group => [group, 1] as [string, number]))
+ const [answer, profile] = await profiled(() => store.routeDecisions(owner, w.tabId, w.lead))
+ expect(answer).toHaveLength(100)
+ // A hundred groups with a 4 KB brief each are 400 KB whole; the live groups come whole with the Swarm's base.
+ expect(profile.SwarmGroup!.bytes).toBeLessThan(200_000)
+ expect(answer).toEqual(await listedBefore(w, owner, w.lead))
+ })
})
diff --git a/backend/integration/workerIndexPlans.test.ts b/backend/integration/workerIndexPlans.test.ts
index 0b5ba6f8e..3a9576483 100644
--- a/backend/integration/workerIndexPlans.test.ts
+++ b/backend/integration/workerIndexPlans.test.ts
@@ -68,3 +68,61 @@ describe('the minute billing sync', () => {
expect(rows[0]!.planSummary).toMatch(/externalSubscriptionEndAt/)
})
})
+
+describe('the nightly routing reflection', () => {
+ // Which projects it reads: a $group in Mongo over the evidence week index, never Prisma's groupBy (Lead, 10-30).
+ it('finds the projects with routed work in the last two weeks by the evidence week index, reading only those weeks', async () => {
+ const { reflectionCandidates } = await import('../src/lib/routingReflection.js')
+ const { weekStart } = await import('../src/superTabs/leaderboard/week.js')
+ const row = (tabId: string, projectId: string, week: number, kind: string) => ({ id: randomUUID(), tabId, projectId, engine: 'claude', model: 'opus',
+ kind, week: new Date(week), updatedAt: new Date(week) })
+ await db.superTabModelEvidence.createMany({ data: [
+ // Weeks long past, which a read not bounded by week examines too.
+ ...Array.from({ length: 20 }, (_, i) => row(`old-tab-${i}`, 'lead', weekStart(NOW - 60 * DAY), 'feature')),
+ row('tab-a', 'lead', weekStart(NOW), 'feature'), row('tab-a', 'lead', weekStart(NOW), 'docs'), row('tab-a', 'web', weekStart(NOW - 7 * DAY), 'fix'),
+ ] })
+ let candidates: Map<string, string[]> | undefined
+ const entries = await profiled(db, async () => { candidates = await reflectionCandidates(db, NOW) })
+ expect(candidates).toEqual(new Map([['tab-a', expect.arrayContaining(['lead', 'web'])]]))
+ expect(candidates!.get('tab-a')).toHaveLength(2)
+ const rows = reads(entries, 'SuperTabModelEvidence', ['week'])
+ expect(rows, JSON.stringify(plan(rows))).toHaveLength(1)
+ expect(rows[0]!.docsExamined, JSON.stringify(plan(rows))).toBeLessThanOrEqual(3)
+ expect(rows[0]!.planSummary, JSON.stringify(plan(rows))).toMatch(/IXSCAN \{ week: 1/)
+ })
+
+ it('reads a Swarm’s failed starts of the last 7 days by its tabId+createdAt index', async () => {
+ const { failedStarts } = await import('../src/superTabs/costs/read.js')
+ const decision = (createdAt: number, outcome: string | null) => ({ id: randomUUID(), tabId: 'tab-f', conversationId: 'g1', record: {},
+ final: { kind: 'new', startId: randomUUID(), machineId: 'secret-mac', engine: 'codex', model: 'gpt-6.1-sol', effort: 'high' }, outcome, createdAt: new Date(createdAt) })
+ await db.superTabRouteDecision.createMany({ data: [
+ ...Array.from({ length: 20 }, () => decision(NOW - 30 * DAY, 'failed')),
+ decision(NOW - DAY, 'failed'), decision(NOW - 2 * DAY, 'done'), decision(NOW - 3 * DAY, null),
+ ] })
+ let found: Awaited<ReturnType<typeof failedStarts>> = []
+ const entries = await profiled(db, async () => { found = await failedStarts(db, 'tab-f', NOW - 7 * DAY) })
+ expect(found).toEqual([{ conversationId: 'g1', engine: 'codex', model: 'gpt-6.1-sol', effort: 'high', at: NOW - DAY }])
+ const rows = reads(entries, 'SuperTabRouteDecision', ['tabId', 'createdAt'])
+ expect(rows, JSON.stringify(plan(rows))).toHaveLength(1)
+ expect(rows[0]!.docsExamined, JSON.stringify(plan(rows))).toBeLessThanOrEqual(3)
+ expect(rows[0]!.planSummary, JSON.stringify(plan(rows))).toMatch(/IXSCAN \{ tabId: 1, createdAt: 1/)
+ })
+
+ it('reads a project’s reflection decisions by the decisions’ project index, never another project’s (review of #2276)', async () => {
+ const { reflectionDecisions } = await import('../src/superTabs/decisions.js')
+ const decision = (projectId: string, kind?: string) => ({ id: randomUUID(), tabId: 'tab-d', batchId: 'b', projectId, conversationId: 'c', personId: 'p',
+ askerAgentId: 'a', question: `${kind ?? 'Plain'}? Saving.`, options: ['Yes', 'No'], recommended: 0, unblocks: 'x', createdAt: new Date(NOW), ...kind ? { kind } : {} })
+ await db.superTabDecision.createMany({ data: [
+ ...Array.from({ length: 20 }, () => decision('other', 'routing-reflection')),
+ decision('lead'), decision('lead', 'routing-reflection'), decision('lead', 'routing-reflection'),
+ ] })
+ let found: Awaited<ReturnType<typeof reflectionDecisions>> = []
+ const entries = await profiled(db, async () => { found = await reflectionDecisions(db, 'tab-d', 'lead') })
+ expect(found).toHaveLength(2)
+ const rows = reads(entries, 'SuperTabDecision', ['tabId', 'projectId'])
+ expect(rows, JSON.stringify(plan(rows))).toHaveLength(1)
+ // The project's decisions, its plain ones too: no other project's.
+ expect(rows[0]!.docsExamined, JSON.stringify(plan(rows))).toBeLessThanOrEqual(3)
+ expect(rows[0]!.planSummary, JSON.stringify(plan(rows))).toMatch(/IXSCAN \{ tabId: 1, projectId: 1, createdAt: 1/)
+ })
+})
diff --git a/backend/prisma/schema.prisma b/backend/prisma/schema.prisma
index 9776002d8..928dcff75 100644
--- a/backend/prisma/schema.prisma
+++ b/backend/prisma/schema.prisma
@@ -1186,6 +1186,9 @@ model SuperTabDecision {
note String?
/// The person asked left it to the PM, who took the recommended option: never shown as their own choice.
delegated Boolean?
+ /// "routing-reflection" for a proposal of the nightly routing reflection (costs/reflection.ts): never a Buddy's to read,
+ /// and an approved one is kept past the ledger's weeks. Absent on every other decision.
+ kind String?
@@index([tabId, personId, createdAt])
@@index([tabId, askerAgentId, createdAt])
diff --git a/backend/src/lib/routingReflection.test.ts b/backend/src/lib/routingReflection.test.ts
new file mode 100644
index 000000000..72e5dbd60
--- /dev/null
+++ b/backend/src/lib/routingReflection.test.ts
@@ -0,0 +1,101 @@
+import type { PrismaClient } from '@prisma/client'
+import { describe, expect, it } from 'vitest'
+import { reflectionMessageId } from '../superTabs/costs/reflection.js'
+import { MAX_CANDIDATES, PLAN_EVERY_MS, reflectionCache, reflectionDue, reflectNightly } from './routingReflection.js'
+
+const utc = (day: number, hour: number, minute = 0) => Date.UTC(2026, 9, day, hour, minute)
+
+describe('when the nightly routing reflection is due', () => {
+ it('is due from 23:00 to 23:59 in Vietnam for a project with no digest zone, for that local date', () => {
+ expect(reflectionDue({}, utc(30, 16, 0))).toBe('2026-10-30')
+ expect(reflectionDue({}, utc(30, 16, 59))).toBe('2026-10-30')
+ expect(reflectionDue({}, utc(30, 15, 59))).toBeNull()
+ // Midnight in Vietnam is the next day: a pass that missed 23:xx does not report a day late.
+ expect(reflectionDue({}, utc(30, 17, 0))).toBeNull()
+ })
+
+ it('follows the project digest time zone', () => {
+ const berlin = { digest: { time: '08:00', timeZone: 'Europe/Berlin' } }
+ expect(reflectionDue(berlin, utc(30, 22, 30))).toBe('2026-10-30')
+ expect(reflectionDue(berlin, utc(30, 16, 30))).toBeNull()
+ })
+
+ it('falls back to Vietnam for a zone this runtime does not know', () => {
+ expect(reflectionDue({ digest: { time: '08:00', timeZone: 'Mars/Olympus' } }, utc(30, 16, 30))).toBe('2026-10-30')
+ })
+
+ it('posts one report a project a local date', () => {
+ expect(reflectionMessageId('tab', 'p1', '2026-10-30')).toBe(reflectionMessageId('tab', 'p1', '2026-10-30'))
+ expect(reflectionMessageId('tab', 'p1', '2026-10-30')).not.toBe(reflectionMessageId('tab', 'p1', '2026-10-31'))
+ expect(reflectionMessageId('tab', 'p1', '2026-10-30')).not.toBe(reflectionMessageId('tab', 'p2', '2026-10-30'))
+ })
+})
+
+/** A database with [candidates] (Swarm, project) pairs and these heads, counting what a pass reads. */
+function fakeDb(candidates: Array<[string, string]>, heads: Record<string, unknown>) {
+ const reads = { candidates: 0, heads: 0 }
+ const db = {
+ superTabModelEvidence: { aggregateRaw: async () => { reads.candidates++; return candidates.map(([tabId, projectId]) => ({ _id: { tabId, projectId } })) } },
+ swarmHead: { findUnique: async ({ where: { id } }: { where: { id: string } }) => { reads.heads++; return heads[id] ?? null } },
+ }
+ return { db: db as unknown as PrismaClient, reads }
+}
+const NIGHT = utc(30, 16, 10)
+const store = () => {
+ const asked: string[] = []
+ return { asked, postReflection: async (tabId: string, projectId: string, on: string) => { asked.push(`${tabId} ${projectId} ${on}`); return 'posted' as const } }
+}
+
+describe('a pass of the nightly routing reflection (review of #2276)', () => {
+ it('reports the one project of a Swarm with no projects list', async () => {
+ const { db } = fakeDb([['old', 'lead']], { 'old:head': { deleted: false, data: { name: 'Old', ownerId: 'u1' } } })
+ const s = store()
+ expect(await reflectNightly(db, s, NIGHT)).toMatchObject({ posted: 1, failed: 0 })
+ expect(s.asked).toEqual(['old lead 2026-10-30'])
+ })
+
+ it('reads the projects and their time zones once every few hours, not on every pass, and asks each settled report once', async () => {
+ const { db, reads } = fakeDb([['t1', 'p1']], { 't1:head': { deleted: false, data: { projects: [{ id: 'p1', leadConversationId: 'c1' }] } } })
+ const s = store(), cache = reflectionCache()
+ for (let pass = 0; pass < 4; pass++) await reflectNightly(db, s, NIGHT + pass * 15 * 60_000, undefined, cache)
+ expect(reads).toEqual({ candidates: 1, heads: 1 })
+ expect(s.asked).toEqual(['t1 p1 2026-10-30'])
+ // The next night, after the plan is old: read again, and that night's report asked.
+ await reflectNightly(db, s, NIGHT + 24 * 3_600_000, undefined, cache)
+ expect(PLAN_EVERY_MS).toBeLessThan(24 * 3_600_000)
+ expect(reads).toEqual({ candidates: 2, heads: 2 })
+ expect(s.asked).toEqual(['t1 p1 2026-10-30', 't1 p1 2026-10-31'])
+ })
+
+ it('reads the plan again on the next pass when a Swarm read failed, and asks a failed report again', async () => {
+ const { db, reads } = fakeDb([['t1', 'p1']], {})
+ let fail = true
+ const swarmHead = (db as unknown as { swarmHead: { findUnique: (a: unknown) => Promise<unknown> } }).swarmHead
+ const read = swarmHead.findUnique
+ swarmHead.findUnique = async a => {
+ await read(a)
+ if (fail) { fail = false; throw new Error('timed out') }
+ return { deleted: false, data: { projects: [{ id: 'p1' }] } }
+ }
+ const warned: unknown[] = [], cache = reflectionCache()
+ let failures = 1
+ const flaky = { postReflection: async () => { if (failures-- > 0) throw new Error('busy'); return 'posted' as const } }
+ expect(await reflectNightly(db, flaky, NIGHT, { warn: (...a: unknown[]) => { warned.push(a) } }, cache)).toMatchObject({ failed: 1, posted: 0 })
+ expect(await reflectNightly(db, flaky, NIGHT + 15 * 60_000, { warn: (...a: unknown[]) => { warned.push(a) } }, cache)).toMatchObject({ failed: 1, posted: 0 })
+ expect(await reflectNightly(db, flaky, NIGHT + 30 * 60_000, { warn: (...a: unknown[]) => { warned.push(a) } }, cache)).toMatchObject({ failed: 0, posted: 1 })
+ expect(reads.heads).toBe(2)
+ expect(warned).toHaveLength(2)
+ })
+
+ it('says when it read as many projects as a pass reads', async () => {
+ const pairs = Array.from({ length: MAX_CANDIDATES }, (_, i): [string, string] => [`t${i}`, 'lead'])
+ const { db } = fakeDb(pairs, {})
+ const warned: unknown[][] = []
+ await reflectNightly(db, store(), NIGHT, { warn: (...a: unknown[]) => { warned.push(a) } })
+ expect(warned).toEqual([['[routing-reflection] read the most projects a pass reads; some may get no report', { limit: MAX_CANDIDATES }]])
+ const few = fakeDb([['t1', 'lead']], {})
+ warned.length = 0
+ await reflectNightly(few.db, store(), NIGHT, { warn: (...a: unknown[]) => { warned.push(a) } })
+ expect(warned).toEqual([])
+ })
+})
diff --git a/backend/src/lib/routingReflection.ts b/backend/src/lib/routingReflection.ts
new file mode 100644
index 000000000..5de5ac16d
--- /dev/null
+++ b/backend/src/lib/routingReflection.ts
@@ -0,0 +1,134 @@
+import type { PrismaClient } from '@prisma/client'
+import type { SuperTabState } from '../superTabs/model.js'
+import { projectsOf, type SwarmProject } from '../superTabs/projects.js'
+import type { SuperTabStore } from '../superTabs/store.js'
+import { weekStart } from '../superTabs/leaderboard/week.js'
+import { DEFAULT_TIME_ZONE } from '../superTabs/costs/reflection.js'
+import { logger } from '../utils/logger.js'
+
+/**
+ * The nightly routing reflection (Scholes's roadmap, piece 2, 2026-10-30): at 23:00 in each project's time zone, the singleton
+ * worker posts in the project chat what its routed work cost and how it went, with at most three routing changes asked of
+ * its owner (superTabs/costs/reflection.ts, store.ts postReflection). Nothing changes routing without the owner's answer.
+ *
+ * - Which projects: those with evidence rows (superTabs/evidence/store.ts) from the last two weeks, grouped in Mongo by the
+ * evidence collection's week index; a project with no routed work has none and is never read. Then one head per Swarm,
+ * for each project's time zone. That plan is read again every PLAN_EVERY_MS, not on each of the 96 passes a day (review
+ * of #2276): a project whose first routed work or new time zone is newer than the plan gets its first report a night later.
+ * - When: a pass every 15 minutes; a project is due during its local 23:00 hour, once a local date (the report's id). A
+ * project whose report this process already settled for a date is not asked again for it.
+ * - Failure: a pass that fails for a project writes nothing and is tried again on the next pass, at most four times a night;
+ * a Swarm whose head read fails makes the next pass read the plan again.
+ */
+export const REFLECTION_EVERY_MS = 15 * 60_000
+export { DEFAULT_TIME_ZONE }
+const HOUR = '23'
+/** (Swarm, project) pairs one pass reads at most: far more than projects route in two weeks. */
+export const MAX_CANDIDATES = 5000
+const WEEK_MS = 7 * 24 * 60 * 60_000
+/** How long a pass reuses the projects and time zones it read. */
+export const PLAN_EVERY_MS = 3 * 60 * 60_000
+
+function localNow(timeZone: string, now: number): { date: string; hour: string } {
+ const parts = Object.fromEntries(new Intl.DateTimeFormat('en-CA', { timeZone, year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit',
+ hourCycle: 'h23' }).formatToParts(now).map(p => [p.type, p.value]))
+ return { date: `${parts.year}-${parts.month}-${parts.day}`, hour: parts.hour! }
+}
+
+/** The local date whose report is due at `now`, or null outside the project's 23:00 hour. A zone the runtime does not know
+ * counts as the default one. */
+export function reflectionDue(project: Pick<SwarmProject, 'digest'>, now: number): string | null {
+ let local: ReturnType<typeof localNow>
+ try { local = localNow(project.digest?.timeZone ?? DEFAULT_TIME_ZONE, now) } catch { local = localNow(DEFAULT_TIME_ZONE, now) }
+ return local.hour === HOUR ? local.date : null
+}
+
+/** The Swarms and projects with evidence from the week holding 7 days ago on: one $group in Mongo over the week index, never
+ * Prisma's groupBy (it crashed the engine on Mongo here). Says so when it reads MAX_CANDIDATES: some projects may be left out. */
+export async function reflectionCandidates(db: PrismaClient, now: number, log: Pick<typeof logger, 'warn'> = logger): Promise<Map<string, string[]>> {
+ const rows = await db.superTabModelEvidence.aggregateRaw({ pipeline: [
+ { $match: { week: { $gte: { $date: new Date(weekStart(now - WEEK_MS)).toISOString() } } } },
+ { $group: { _id: { tabId: '$tabId', projectId: '$projectId' } } },
+ { $limit: MAX_CANDIDATES },
+ ] }) as unknown as Array<{ _id: { tabId: string; projectId: string } }>
+ if (rows.length >= MAX_CANDIDATES) log.warn('[routing-reflection] read the most projects a pass reads; some may get no report', { limit: MAX_CANDIDATES })
+ const byTab = new Map<string, string[]>()
+ for (const { _id: { tabId, projectId } } of rows) byTab.set(tabId, [...byTab.get(tabId) ?? [], projectId])
+ return byTab
+}
+
+/** A project that may get a report, with what tells when: its digest's time zone. */
+export interface ReflectionTarget { tabId: string; projectId: string; digest?: SwarmProject['digest'] }
+
+/** The candidates, each with its project's time zone from its Swarm's head. A Swarm with no projects list has its one project
+ * (projects.ts projectsOf). A Swarm whose head read fails is logged and counted in `failed`. */
+export async function reflectionPlan(db: PrismaClient, now: number, log: Pick<typeof logger, 'warn'> = logger): Promise<{ targets: ReflectionTarget[]; failed: number }> {
+ const targets: ReflectionTarget[] = []
+ let failed = 0
+ for (const [tabId, projectIds] of await reflectionCandidates(db, now, log)) {
+ try {
+ const head = await db.swarmHead.findUnique({ where: { id: `${tabId}:head` }, select: { deleted: true, data: true } })
+ if (!head || head.deleted) continue
+ for (const project of projectsOf(head.data as unknown as SuperTabState).filter(p => projectIds.includes(p.id))) {
+ targets.push({ tabId, projectId: project.id, ...project.digest ? { digest: project.digest } : {} })
+ }
+ } catch (error) {
+ failed++
+ log.warn('[routing-reflection] reading a Swarm failed; trying again on the next pass', { tabId, error: error instanceof Error ? error.message : String(error) })
+ }
+ }
+ return { targets, failed }
+}
+
+export interface ReflectionPass { posted: number; already: number; empty: number; skipped: number; failed: number }
+/** What passes in one process share: the plan and when it was read, and the reports settled since. */
+export interface ReflectionCache { plan: ReflectionTarget[] | null; readAt: number; settled: Set<string> }
+export const reflectionCache = (): ReflectionCache => ({ plan: null, readAt: 0, settled: new Set() })
+
+/** One pass: each planned project whose report is due gets it. A failure is one project's: logged, the others go on. */
+export async function reflectNightly(db: PrismaClient, store: Pick<SuperTabStore, 'postReflection'>, now: number,
+ log: Pick<typeof logger, 'warn'> = logger, cache: ReflectionCache = reflectionCache()): Promise<ReflectionPass> {
+ const pass: ReflectionPass = { posted: 0, already: 0, empty: 0, skipped: 0, failed: 0 }
+ if (!cache.plan || now - cache.readAt >= PLAN_EVERY_MS) {
+ const { targets, failed } = await reflectionPlan(db, now, log)
+ pass.failed += failed
+ Object.assign(cache, { plan: failed ? null : targets, readAt: now, settled: new Set() })
+ return run(targets)
+ }
+ return run(cache.plan)
+
+ async function run(targets: ReflectionTarget[]): Promise<ReflectionPass> {
+ for (const target of targets) {
+ const on = reflectionDue(target, now)
+ const key = JSON.stringify([target.tabId, target.projectId, on])
+ if (!on || cache.settled.has(key)) continue
+ try {
+ pass[await store.postReflection(target.tabId, target.projectId, on)]++
+ cache.settled.add(key)
+ } catch (error) {
+ pass.failed++
+ log.warn('[routing-reflection] a report failed; trying again on the next pass', { tabId: target.tabId, projectId: target.projectId,
+ error: error instanceof Error ? error.message : String(error) })
+ }
+ }
+ return pass
+ }
+}
+
+/** Runs a pass every [everyMs] in the singleton worker, never two at once. */
+export function startRoutingReflection(db: PrismaClient, store: Pick<SuperTabStore, 'postReflection'>, everyMs = REFLECTION_EVERY_MS,
+ now: () => number = Date.now): () => void {
+ let running = false
+ const cache = reflectionCache()
+ const run = () => {
+ if (running) return
+ running = true
+ void reflectNightly(db, store, now(), logger, cache).then(pass => { if (pass.posted || pass.failed) logger.info('[routing-reflection] pass', { ...pass }) })
+ .catch(error => logger.warn('[routing-reflection] pass failed', { error: error instanceof Error ? error.message : String(error) }))
+ .finally(() => { running = false })
+ }
+ run()
+ const timer = setInterval(run, everyMs)
+ timer.unref()
+ return () => clearInterval(timer)
+}
diff --git a/backend/src/superTabs/autoReview.ts b/backend/src/superTabs/autoReview.ts
index 51d4a8f65..f0185e6fd 100644
--- a/backend/src/superTabs/autoReview.ts
+++ b/backend/src/superTabs/autoReview.ts
@@ -5,6 +5,7 @@ import { agentProjectId, groupProject, skillSetOf } from './projects.js'
import { recordAsked, recordRun } from './leaderboard/record.js'
import { renewLease } from './liveness.js'
import { downSince } from './machines.js'
+import { canStart, standing } from './reviewSeats.js'
// Reviews start the moment work is ready (Dee, 2026-10-28). The Lead hand-opened about 30 review groups that day, and one
// review request sat unanswered until its group was archived, so a privacy fix waited hours with no verdict. Now an
@@ -51,24 +52,31 @@ export const verdictPending = (state: SuperTabState, review: Conversation): bool
const free = (state: SuperTabState, agent: Agent) =>
!state.conversations.some(c => c.leadId === agent.id || (activeWork(c) && c.assignment!.agentId === agent.id))
+/** Whether [agent] cannot work now: a usage limit holds it, or its machine reports readings by which its engine could not start
+ * (reviewSeats.ts standing). A machine with no readings (a host outside the contributions) is judged by the limit alone. */
+function unable(state: SuperTabState, agent: Agent, now: number): boolean {
+ if (agent.limitedUntil && Date.parse(agent.limitedUntil) > now) return true
+ const pool = state.machines?.find(m => m.machineId === agent.machineId)
+ return !!pool && !canStart(standing(state, pool, agent.configuration.engine, now))
+}
+
/**
* The Reviewer for [group]'s review: the one that reviewed its earlier head while it is still free (a delta review), else
- * a free Reviewer of the project: one at least as strong as the Engineer ([strength], up to the top tier) first, as the CLI's
- * route holds a Reviewer to the Builder's strength (review of #2274), and among those one on another engine than the
- * Engineer's first; else the weaker ones in that order. Never one that is stopping, waiting to
- * resume a lost task, down (its session gone or its machine silent), or (`mayWork`) not allowed to take this work: on its
- * machine, or by the owner's rules (#610 review).
+ * the strongest free Reviewer of the project ([strength]), of any engine (Ken, 2026-10-30), so one at least as strong as the
+ * Engineer goes first, as the CLI's route holds a Reviewer to the Builder's strength (review of #2274). Never one that is
+ * stopping, waiting to resume a lost task, down (its session gone or its machine silent), [unable] to work now (held by a usage
+ * limit, or its machine reports its engine out of quota, signed out, suspended or paused: review of #2313, as ties at the top
+ * tier are common and an idle Codex Reviewer out of quota came first), or (`mayWork`) not allowed to take this work: on its
+ * machine, by the owner's rules (#610 review), or as the review rule (rules.ts reviewRefusal) has it.
*/
function pickReviewer(state: SuperTabState, group: Conversation, engineer: Agent | undefined, earlier: Conversation | undefined,
mayWork: (agent: Agent) => boolean, strength: (agent: Agent) => number, now: number): Agent | null {
const projectId = groupProject(state, group).id
- const candidates = state.agents.filter(a => agentRole(a) === 'reviewer' && agentProjectId(state, a) === projectId &&
- a.workDecision !== 'stop' && !a.lostTask && !downSince(state, a, now) && free(state, a) && mayWork(a))
+ const candidates = state.agents.filter(a => a.id !== engineer?.id && agentRole(a) === 'reviewer' && agentProjectId(state, a) === projectId &&
+ a.workDecision !== 'stop' && !a.lostTask && !downSince(state, a, now) && !unable(state, a, now) && free(state, a) && mayWork(a))
const previous = candidates.find(a => a.id === earlier?.assignment?.agentId)
- const floor = engineer ? Math.min(3, strength(engineer)) : 0
- const strong = candidates.filter(a => strength(a) >= floor), weaker = candidates.filter(a => strength(a) < floor)
- const otherEngine = (list: Agent[]) => list.find(a => a.configuration.engine !== engineer?.configuration.engine) ?? list[0]
- return previous ?? otherEngine(strong) ?? otherEngine(weaker) ?? null
+ // Strongest first; at equal strength the roster's order stands (sort is stable).
+ return previous ?? [...candidates].sort((a, b) => strength(b) - strength(a))[0] ?? null
}
function briefOf(group: Conversation, handoff: string, pullRequest: string, earlier: Conversation | undefined): string {
@@ -97,8 +105,7 @@ export interface OpenedReview { review: Conversation; reviewer: Agent | null; me
* notices are (liveness.ts), never as the Engineer (#610 review); [engineer] writes them only in a group with no Lead.
*/
export function openReview(state: SuperTabState, group: Conversation, handoff: string, pullRequest: string,
- context: { operationId: string; now: number; engineer: Author; mayWork: (agent: Agent) => boolean; strength: (agent: Agent) => number;
- sameEngine?: (agent: Agent) => string | null }): OpenedReview | null {
+ context: { operationId: string; now: number; engineer: Author; mayWork: (agent: Agent) => boolean; strength: (agent: Agent) => number }): OpenedReview | null {
const project = groupProject(state, group)
// On Custom skills without a reviewer role there are no review groups (commands.ts requireCustomRole).
if (state.paused || (skillSetOf(project) === 'custom' && !project.roles?.some(r => r.kind === 'reviewer'))) return null
@@ -131,9 +138,7 @@ export function openReview(state: SuperTabState, group: Conversation, handoff: s
execution: { machineId: reviewer.machineId, harnessId: reviewer.harnessId, machineOwnerId: reviewer.machineOwnerId }, result: null }
renewLease(review.assignment, context.now)
recordRun(state, review, review.assignment, reviewer, context.now)
- // A review on its Builder's own engine says so first, as work.assign does (rules.ts sameEngineReview).
- const sameEngine = context.sameEngine?.(reviewer)
- messages.push(row('assign', `${sameEngine ? `${sameEngine}\n\n` : ''}${brief}\n\nAcceptance checks:\n- ${VERDICT_CHECK}`, [reviewer.id]))
+ messages.push(row('assign', `${brief}\n\nAcceptance checks:\n- ${VERDICT_CHECK}`, [reviewer.id]))
}
const name = reviewer && (reviewer.displayName ?? reviewer.name)
if (leadId) messages.push(row('lead', reviewer
diff --git a/backend/src/superTabs/buddies.ts b/backend/src/superTabs/buddies.ts
index 796081a18..e2dc87bc2 100644
--- a/backend/src/superTabs/buddies.ts
+++ b/backend/src/superTabs/buddies.ts
@@ -20,7 +20,8 @@ export function buddyReads(buddy: Agent, group: Conversation, leadConversationId
/** The rows that tell how work is routed: a route and its override name the machines that could run a task and why others
* could not, and a rule row the routing rules. A Buddy reads none of them, as its Swarm read has no machines or rules. */
-const ROUTING_ROWS: ReadonlySet<string> = new Set(['route', 'route-override', 'rule'])
+/** The nightly routing reflection (lib/routingReflection.ts) says what each engine and model cost and how it went: routing too. */
+const ROUTING_ROWS: ReadonlySet<string> = new Set(['route', 'route-override', 'rule', 'routing-reflection'])
export const routingRow = (source: unknown): boolean => ROUTING_ROWS.has(String((source as { kind?: unknown } | null | undefined)?.kind))
/** Whether [actor] is a Buddy, which reads no routing (no route rows, routing decisions, policy or costs) and no machines. */
diff --git a/backend/src/superTabs/commands.test.ts b/backend/src/superTabs/commands.test.ts
index d49271122..a56cc9453 100644
--- a/backend/src/superTabs/commands.test.ts
+++ b/backend/src/superTabs/commands.test.ts
@@ -1355,7 +1355,7 @@ describe('Reviewer role', () => {
return { f, lead, leadActor, group, reviewer, builder }
}
- it('refuses an agent\'s review pick on the grid, below quality 2 or on the Builder\'s engine, whatever the soft rules; a person gets a warning', () => {
+ it('refuses an agent\'s review pick on the grid, below quality 2 or by the Builder itself, whatever the soft rules; a person gets a warning', () => {
const { f, leadActor, group, reviewer, builder } = reviewed()
f.run({ type: 'work.assign', conversationId: group, agentId: builder })
f.run({ type: 'rule.set', rule: { kind: 'preferEngine', taskKind: 'review', engine: 'codex' }, text: 'Codex reviews.' } as Command)
@@ -1365,9 +1365,11 @@ describe('Reviewer role', () => {
expect(() => route({ model: 'default', effort: 'default', quality: 2, cost: 1, gridModel: 'moonshotai/kimi-k3', gridName: 'swarm-g' }))
.toThrow('A review never runs on a model served on the Swarm\'s grid. Route again.')
expect(() => route({ model: 'haiku', effort: 'auto', quality: 3 })).toThrow('A review needs a model of quality 2 or more, and Claude haiku is 1. Route again.')
- // The Builder runs Codex.
- expect(() => route({ engine: 'codex', model: 'default', effort: 'default' })).toThrow('A review runs on another engine than the reviewed Builder\'s, Codex. Route again.')
+ // The Builder runs Codex, and Codex may review it as Claude may (Ken, 2026-10-30).
+ expect(route({ engine: 'codex', model: 'default', effort: 'default' }).result.routeDecisionId).toBeTruthy()
expect(route({}).result.routeDecisionId).toBeTruthy()
+ // Never the Builder itself.
+ expect(() => route({ kind: 'member', agentId: builder, machineId: 'host' })).toThrow('A review group is assigned only to a Reviewer.')
// A model the policy does not name is rated 1.
expect(() => route({ model: 'default', effort: 'default' })).toThrow('Claude default is 1.')
// A person assigning a grid Reviewer by hand is told.
@@ -1376,51 +1378,62 @@ describe('Reviewer role', () => {
expect(byHand.result.warnings).toEqual(['A review never runs on a model served on the Swarm\'s grid.'])
})
- it('lets a Claude-only Swarm review a Claude Builder\'s work on Opus, never below the top tier, and records why on the decision', () => {
+ // Ken, 2026-10-30: reviews of Claude builds waited all morning for Codex quota. Any strong engine reviews any build now.
+ it('lets a Claude Builder\'s work be reviewed on Claude Opus at once while a Codex Reviewer could start, with no same-engine note', () => {
const { f, leadActor, group, builder, reviewer } = reviewed()
- // Every agent runs Claude and no machine offers Codex: no Reviewer of another engine can run here.
for (const a of f.state.agents) a.configuration = { ...a.configuration, engine: 'claude' }
+ f.state.agents.find(a => a.id === reviewer)!.configuration.model = 'claude-opus-4-7'
f.run({ type: 'work.assign', conversationId: group, agentId: builder })
const review = f.run({ type: 'conversation.create', title: 'Review', brief: 'Review it.', reviewOf: group, checks: [{ description: 'Verdict', independent: false }] },
leadActor).result.conversationId as string
- const route = (pick: Record<string, unknown>) => f.run({ type: 'route.record', conversationId: review, decision: record({ candidates: [candidate('c0', pick)], pick: 'c0' }) } as Command, leadActor)
- const same = 'same-engine review: no Reviewer of another engine has quota, so the review runs on Claude, the Builder\'s engine, at its top tier.'
+ const route = (pick: Record<string, unknown>, extra: Record<string, unknown> = {}) =>
+ f.run({ type: 'route.record', conversationId: review, decision: record({ candidates: [candidate('c0', pick)], pick: 'c0', ...extra }) } as Command, leadActor)
+ // A Codex machine with quota now: before, it refused every Claude review.
+ const codexBox = () => {
+ f.state.machines = [{ machineId: 'codex-box', contributorId: 'owner', engines: ['codex'], observation: { receivedAt: 1000,
+ quotas: [{ engine: 'codex', known: true, windows: [{ name: 'weekly', usedPercent: 10, resetsAt: null }] }] } } as never]
+ }
+ codexBox()
const routed = route({})
- expect(routed.routeDecisions[0]).toMatchObject({ record: { sameEngine: same } })
- // Its route line says so (Lead, 2026-10-30).
- expect(routed.messages.find(m => m.conversationId === review)!.text).toMatch(/ · same-engine review: no Reviewer of another engine has quota$/)
- expect(() => route({ model: 'sonnet', effort: 'medium', quality: 2 }))
- .toThrow('A review on the reviewed Builder\'s engine, Claude, needs its top tier (quality 3): no Reviewer on another engine can start soon in this Swarm. Route again.')
+ expect(routed.routeDecisions[0]).not.toHaveProperty('record.sameEngine')
+ expect(routed.messages.find(m => m.conversationId === review)!.text).not.toContain('same-engine')
+ // Sonnet is rated 2: strong enough to review, as any engine's row of 2 is.
+ codexBox()
+ expect(route({ model: 'sonnet', effort: 'medium', quality: 2 }).result.routeDecisionId).toBeTruthy()
+ // An older CLI's same-engine note is not kept on the decision.
+ codexBox()
+ expect(route({}, { sameEngine: 'same-engine review: no Reviewer of another engine has quota' }).routeDecisions[0]).not.toHaveProperty('record.sameEngine')
+ // Nor at the start of its why (review of #2313).
+ codexBox()
+ expect(route({}, { why: 'same-engine review: no Reviewer of another engine has quota. First by the owner\'s rules and the policy order.' }).routeDecisions[0])
+ .toMatchObject({ record: { why: 'First by the owner\'s rules and the policy order.' } })
+ codexBox()
expect(() => route({ model: 'default', effort: 'default' })).toThrow('Claude default is 1.')
expect(() => route({ model: 'default', effort: 'default', gridModel: 'moonshotai/kimi-k3', gridName: 'swarm-g' })).toThrow('never runs on a model served on the Swarm\'s grid')
- // A machine that offers Codex makes the other engine available, and the same engine is refused again.
- // Each run hands back a new state, so the machine is set afresh before each.
- const codexBox = (reading: Record<string, unknown> = {}) => {
- f.state.machines = [{ machineId: 'codex-box', contributorId: 'owner', engines: ['codex'], observation: { receivedAt: 1000, quotas: [], ...reading } } as never]
- }
- const weekly = (resetsIn: number) => ({ quotas: [{ engine: 'codex', known: true, windows: [{ name: 'weekly', usedPercent: 100, resetsAt: new Date(1000 + resetsIn).toISOString() }] }] })
- codexBox()
- expect(() => route({})).toThrow('A review runs on another engine than the reviewed Builder\'s, Claude. Route again.')
- // Unless it could not start within the start window: out of quota for days (2026-10-30), or offline.
- codexBox(weekly(3 * 86_400_000))
- expect(route({}).routeDecisions[0]).toMatchObject({ record: { sameEngine: same } })
- codexBox(weekly(10 * 60_000))
- expect(() => route({})).toThrow('A review runs on another engine than the reviewed Builder\'s, Claude. Route again.')
- codexBox({ receivedAt: -3_600_000 })
- expect(route({}).routeDecisions[0]).toMatchObject({ record: { sameEngine: same } })
+ // The Reviewer's brief starts with the brief itself, assigned by hand too.
codexBox()
- // Unless that machine may not run the review: the owner's rules, or the task's own machine (review of ee4ee6c9a).
- f.run({ type: 'rule.set', rule: { kind: 'machines', machineIds: ['host', 'machine'] }, text: 'Only our machines.' } as Command)
- expect(route({}).routeDecisions[0]).toMatchObject({ record: { sameEngine: expect.stringContaining('top tier') } })
- f.run({ type: 'rule.remove', ruleId: f.state.rules!.at(-1)!.id } as Command)
- f.state.conversations.find(c => c.id === review)!.task = { goal: 'g', changes: 'c', constraints: 'k', owns: [], requires: { machines: ['machine'] } }
- expect(route({}).routeDecisions[0]).toMatchObject({ record: { sameEngine: expect.stringContaining('top tier') } })
- // The Reviewer's brief says it first, assigned by hand too.
- delete f.state.conversations.find(c => c.id === review)!.task
- codexBox(weekly(3 * 86_400_000))
const assigned = f.run({ type: 'work.assign', conversationId: review, agentId: reviewer })
expect(assigned.result.warnings).toBeUndefined()
- expect(assigned.messages.find(m => m.recipients.includes(reviewer))!.text).toMatch(new RegExp(`^${same.replace(/[.()]/g, '\\$&')}\n\nReview it\.`))
+ expect(assigned.messages.find(m => m.recipients.includes(reviewer))!.text).toMatch(/^Review it\./)
+ })
+
+ it('lets the Builder join its own review group: joining is not reviewing (review of #2313)', () => {
+ const { f, leadActor, group, builder, reviewer } = reviewed()
+ f.run({ type: 'work.assign', conversationId: group, agentId: builder })
+ const review = f.run({ type: 'conversation.create', title: 'Review', brief: 'Review it.', reviewOf: group, checks: [{ description: 'Verdict', independent: false }] },
+ leadActor).result.conversationId as string
+ const added = f.run({ type: 'conversation.agent', conversationId: review, agentId: builder, present: true, lead: false }, leadActor)
+ expect(added.result.warnings).toBeUndefined()
+ expect(f.state.conversations.find(c => c.id === review)!.agentIds).toContain(builder)
+ // Sitting in the review group, it still never passes the review's verdict (re-review of #2313).
+ f.run({ type: 'work.assign', conversationId: review, agentId: reviewer })
+ const verdict = f.state.conversations.find(c => c.id === review)!
+ const check = { type: 'work.check', conversationId: review, assignmentId: verdict.assignment!.id, checkId: verdict.checks[0]!.id, passed: true, evidence: 'Looks fine.' } as Command
+ expect(() => f.run(check, { kind: 'agent', agentId: builder, machineOwnerId: 'host-owner' })).toThrow('does not give its review\'s verdict')
+ expect(f.state.conversations.find(c => c.id === review)!.checks[0]!.passedBy).toBeNull()
+ // Its Reviewer still does.
+ f.run(check, { kind: 'agent', agentId: reviewer, machineOwnerId: 'target-owner' })
+ expect(f.state.conversations.find(c => c.id === review)!.checks[0]!.passedBy).toBeTruthy()
})
it('never lets a small or unnamed model review: a review needs a model the policy names at quality 2 or more', () => {
@@ -1647,15 +1660,21 @@ describe('Reviewer role', () => {
return { ...setup, fresh, built, builderActor, markReady, reviews }
}
- // Overnight 2026-10-30 reviews waited hours with every other-engine Reviewer out of quota, and nobody was told.
- it('tells the project chat once when no new Reviewer on another engine than the Builder\'s can start, tagging who can fix it', () => {
+ // Overnight 2026-10-30 reviews waited hours with every Codex Reviewer out of quota, and nobody was told. Since any strong
+ // engine reviews (Ken, 2026-10-30), the chat hears only when no machine can start one of any engine.
+ it('tells the project chat once when no new Reviewer of any engine can start, tagging who can fix it', () => {
const { f, markReady } = ready()
teamMachine(f, 'owner')
- f.state.machines![0]!.observation!.quotas = [{ engine: 'claude', known: true, windows: [{ name: 'weekly', usedPercent: 100, resetsAt: null }] }]
- const said = markReady(`Ready: yes.\n${pr}`).messages.filter(m => m.source?.kind === 'review-capacity')
+ f.state.machines![0]!.engines = ['claude', 'codex']
+ f.state.machines![0]!.observation!.quotas = [{ engine: 'claude', known: true, windows: [{ name: 'weekly', usedPercent: 10, resetsAt: null }] },
+ { engine: 'codex', known: true, windows: [{ name: 'weekly', usedPercent: 100, resetsAt: null }] }]
+ // Codex is out, but Claude can review the Codex build: nothing to say.
+ expect(markReady(`Ready: yes.\n${pr}`).messages.filter(m => m.source?.kind === 'review-capacity')).toEqual([])
+ f.state.machines![0]!.observation!.quotas[0]!.windows[0]!.usedPercent = 100
+ const said = markReady(`Ready: yes, head 2.\n${pr}`).messages.filter(m => m.source?.kind === 'review-capacity')
expect(said).toMatchObject([{ conversationId: f.state.projects![0]!.leadConversationId, recipients: [], mentions: ['owner'] }])
- expect(said[0]!.text).toBe('Reviews of Codex builds cannot start a new Reviewer: Claude Code is unavailable on every machine this project may use (Studio: out of quota). '
- + 'More Claude Code quota, Claude Code signed in on another machine, a paused machine resumed, or another machine in the Swarm would unblock them. @owner can fix it.')
+ expect(said[0]!.text).toBe('Reviews cannot start a new Reviewer: no machine this project may use can run Claude Code or Codex now (Studio: out of quota). '
+ + 'More Claude Code or Codex quota, an engine signed in on another machine, a paused machine resumed, or another machine in the Swarm would unblock them. @owner can fix it.')
expect(markReady(`Ready: yes, again.\n${pr}`).messages.filter(m => m.source?.kind === 'review-capacity')).toEqual([])
})
@@ -1686,12 +1705,16 @@ describe('Reviewer role', () => {
.toEqual([['agent', lead, 'auto-review'], ['agent', lead, 'auto-review'], ['agent', lead, 'auto-review']])
})
- it('prefers a free Reviewer on another engine than the Engineer\'s', () => {
- // The Engineer runs on Codex (config). `reviewer` comes first but runs on Codex too; `fresh` runs on Claude.
+ it('gives the review to the first free strong Reviewer, on the Engineer\'s own engine too (Ken, 2026-10-30)', () => {
+ // The Engineer runs on Codex (config). `reviewer` comes first and runs Codex at the top tier; `fresh` runs Claude Opus.
const { f, fresh, reviewer, markReady, reviews } = ready('claude')
- f.state.agents.find(a => a.id === reviewer)!.configuration.engine = 'codex'
- markReady(`Ready. ${pr}`)
- expect(reviews()[0]!.assignment!.agentId).toBe(fresh)
+ f.state.agents.find(a => a.id === reviewer)!.configuration = { ...config, engine: 'codex', model: 'gpt-6.1-sol' }
+ const effects = markReady(`Ready. ${pr}`)
+ expect(reviews()[0]!.assignment!.agentId).toBe(reviewer)
+ expect(fresh).toBeTruthy()
+ // No same-engine note: the brief opens with the review itself.
+ const brief = effects.messages.find(m => m.conversationId === reviews()[0]!.id && m.recipients.includes(reviewer))!.text
+ expect(brief).toMatch(/^Give an independent verdict/)
})
it('prefers a free Reviewer at least as strong as the Builder, and falls back to a weaker one (review of #2274)', () => {
@@ -1815,7 +1838,6 @@ describe('Reviewer role', () => {
it.each([
['on the grid', { gridModel: 'moonshotai/kimi-k3' }],
['below quality 2', { configuration: { ...config, engine: 'claude', model: 'claude-haiku-4-5' } }],
- ['on the Engineer\'s own engine', { configuration: { ...config, engine: 'codex' } }],
])('never gives the review to a Reviewer %s (Ken, 2026-10-29), and leaves it for the Lead', (_, patch) => {
// The Engineer runs Codex; `fresh` is the only free Reviewer.
const { f, leadActor, reviewer, fresh, markReady, reviews } = ready()
@@ -1825,16 +1847,35 @@ describe('Reviewer role', () => {
expect(reviews()[0]!.assignment).toBeNull()
})
- it('gives a Claude-only Swarm\'s review to its free Opus Reviewer, and to no weaker one of the same engine', () => {
+ // Review of #2313: ties at the top tier are common (Codex default and Opus are both 3), and right after the deploy most
+ // Reviewers are Codex; one out of quota came first and took the review.
+ it('passes over a free Reviewer whose machine reads its engine out of quota', () => {
+ const { f, fresh, reviewer, markReady, reviews } = ready('claude')
+ f.state.agents.find(a => a.id === reviewer)!.configuration = { ...config, engine: 'codex', model: 'gpt-6.1-sol' }
+ teamMachine(f, 'owner')
+ f.state.machines![0]!.engines = ['claude', 'codex']
+ f.state.machines![0]!.observation!.quotas = [{ engine: 'codex', known: true, windows: [{ name: 'weekly', usedPercent: 100, resetsAt: null }] }]
+ markReady(`Ready. ${pr}`)
+ expect(reviews()[0]!.assignment!.agentId).toBe(fresh)
+ })
+
+ it('passes over a Reviewer a usage limit holds, on a machine that reports nothing', () => {
+ const { f, fresh, reviewer, markReady, reviews } = ready('claude')
+ Object.assign(f.state.agents.find(a => a.id === reviewer)!, { configuration: { ...config, engine: 'codex', model: 'gpt-6.1-sol' },
+ limitedUntil: new Date(Date.now() + 86_400_000).toISOString() })
+ markReady(`Ready. ${pr}`)
+ expect(reviews()[0]!.assignment!.agentId).toBe(fresh)
+ })
+
+ it('gives a Claude build\'s review to the strongest free Claude Reviewer, before a weaker one that comes first', () => {
const { f, reviewer, fresh, markReady, reviews } = ready()
for (const a of f.state.agents) a.configuration = { ...a.configuration, engine: 'claude' }
f.state.agents.find(a => a.id === reviewer)!.configuration.model = 'claude-sonnet-4-5'
f.state.agents.find(a => a.id === fresh)!.configuration.model = 'claude-opus-4-7'
const effects = markReady(`Ready. ${pr}`)
expect(reviews()[0]!.assignment!.agentId).toBe(fresh)
- // Its brief says first why it reviews on the Builder's engine (Lead, 2026-10-30).
const brief = effects.messages.find(m => m.conversationId === reviews()[0]!.id && m.recipients.includes(fresh))!.text
- expect(brief).toMatch(/^same-engine review: no Reviewer of another engine has quota, so the review runs on Claude, the Builder's engine, at its top tier\.\n\nGive an independent verdict/)
+ expect(brief).toMatch(/^Give an independent verdict/)
})
it('gives the review to a strong Reviewer on another engine, and to an Engineer on the grid even a Reviewer on its relay engine', () => {
diff --git a/backend/src/superTabs/commands.ts b/backend/src/superTabs/commands.ts
index 68fb787fb..acf414141 100644
--- a/backend/src/superTabs/commands.ts
+++ b/backend/src/superTabs/commands.ts
@@ -11,7 +11,7 @@ import {
import { jobKindOf } from './evidence/jobKind.js'
import { routeRecordSchema, routeTitle, startedAs, type RouteCandidate, type RouteDecision, type RouteFinal, type RouteOverride } from './routeRecord.js'
import { DEFAULT_ROUTING_POLICY, routingOverrideSaveSchema, type RoutingPolicy } from './routingPolicy.js'
-import { agentQuality, agentTarget, askedInSchema, broken, MAX_RULES, reviewRefusal, RULE_MESSAGE_MS, SAME_ENGINE, sameEngineReview, ruleSchema, ruleTextSchema, startTarget, unmet, type RunTarget } from './rules.js'
+import { agentQuality, agentTarget, askedInSchema, broken, MAX_RULES, reviewRefusal, RULE_MESSAGE_MS, ruleSchema, ruleTextSchema, startTarget, unmet, type RunTarget } from './rules.js'
import { MAX_ATTACHMENTS, type Attachment } from './attachments.js'
import { checkMentions, MAX_MENTIONS, namedIn, saysName, textTags, withTags, type MentionTarget } from './mentions.js'
import { answerDecision, askDecisions, checkAsker, decisionChoices, decisionQuestion, MAX_OPEN_DECISIONS, MAX_QUESTIONS, type DecisionTarget } from './decisions.js'
@@ -70,6 +70,8 @@ const maxAgents = z.number().int().min(1).max(1024)
const roleId = z.string().regex(/^([0-9a-f]{12}|lead|dev|review)$/)
/** A role's default engine, model and effort (projects.ts RoleDefaults). */
/** What a launch may be asked to run, one short word each, as the CLI checks it (cli lib/launchModel.ts MODEL and EFFORT). */
+/** How a CLI from before 2026-10-30 starts the why of a review on its Builder's own engine (cli superTabs/route.ts, removed). */
+const OLD_SAME_ENGINE = /^same-engine review: no Reviewer of another engine has quota\. /
const LAUNCH_MODEL = /^[A-Za-z0-9][A-Za-z0-9._:\-[\]]{0,63}$/
const LAUNCH_EFFORT = /^[a-z]{1,16}$/
const roleDefaultsSchema = z.object({ engine: z.enum(['claude', 'codex']), model: z.string().trim().min(1).max(200).optional(),
@@ -701,23 +703,24 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
* an owner's rule from where the task can be done at all. */
const policy = context.routingPolicy ?? DEFAULT_ROUTING_POLICY
/** Whether a new agent may run [target] for group [conversationId]: the owner's rules, the task's own machine
- * ([requirement]) and team access. Whether another engine could review is judged by it (rules.ts reviewRefusal). */
+ * ([requirement]) and team access. Whether a new Reviewer could start is judged by it (reviewCapacity.ts). */
const mayRun = (conversationId: string, requirement: boolean) => (target: RunTarget, contributorId: string) =>
!broken(groupRules(conversationId), target, machineName, macOf) && (!requirement || !unmet(conversation(state, conversationId).task?.requires, target, macOf))
&& !teamWorkCheck(state, target.machineId, contributorId, groupProject(state, conversation(state, conversationId)), context.now, context.teamMachines, context.otherWorkspaceMachines)
- /** [builds]: the target would do the group's work, so a step up's floor holds too (stepUp.ts). */
- const refusal = (target: RunTarget, conversationId: string, builds = true): { code: string; why: string } | null => {
+ /** [builds]: the target would do the group's work, so a step up's floor holds too (stepUp.ts). [reviews]: it would review
+ * the group's work, so the review rule holds (rules.ts reviewRefusal); merely joining a review group is not reviewing. */
+ const refusal = (target: RunTarget, conversationId: string, builds = true, reviews = true): { code: string; why: string } | null => {
const rule = broken(groupRules(conversationId), target, machineName, macOf)
if (rule) return { code: 'RULE_BROKEN', why: rule }
const requirement = unmet(conversation(state, conversationId).task?.requires, target, macOf)
if (requirement) return { code: 'REQUIREMENT_UNMET', why: requirement }
- const review = reviewRefusal(state, conversation(state, conversationId).reviewOf, target, policy, mayRun(conversationId, true), context.now)
+ const review = reviews ? reviewRefusal(state, conversation(state, conversationId).reviewOf, target, policy) : null
if (review) return { code: 'REVIEW_REFUSED', why: review }
const stepped = builds ? stepUpRefusal(conversation(state, conversationId), target, policy) : null
return stepped ? { code: 'STEPPED_UP', why: stepped } : null
}
- const ruled = (target: RunTarget, conversationId: string, done: string, personChose = false, builds = true) => {
- const refused = refusal(target, conversationId, builds)
+ const ruled = (target: RunTarget, conversationId: string, done: string, personChose = false, builds = true, reviews = true) => {
+ const refused = refusal(target, conversationId, builds, reviews)
if (!refused) return
const { code, why } = refused
if (actor.kind === 'agent' && !personChose) fail(code, `${why} Route again.`, 403)
@@ -1916,7 +1919,8 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
}
// A Reviewer added to a group is handed its review, as an assignment hands a Builder its task.
if (reviewer) requireTeamWork(state, member.machineId, member.contributorId, groupProject(state, group), context.now, context.teamMachines, context.otherWorkspaceMachines)
- ruled(agentTarget(state, member), group.id, `${who} added ${member.name}`, false, false)
+ // Only a Reviewer added here is handed the review; anyone else joining is not reviewing (review of #2313).
+ ruled(agentTarget(state, member), group.id, `${who} added ${member.name}`, false, false, reviewer)
if (!group.agentIds.includes(command.agentId)) group.agentIds.push(command.agentId)
// Adding a Reviewer to a group reuses it, as assigning work reuses a Builder.
if (reviewer) delete member.workDecision
@@ -2088,18 +2092,18 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
requireWorkerDecisions(state, actor, open(state, command.conversationId), chosen.kind === 'member' ? chosen.agentId : undefined)
const via = decision.via === 'jev' ? `Jev ${Math.round((decision.p ?? 0) * 100)}%`
: decision.via === 'only' ? 'only candidate' : 'by policy order'
- // The step this attempt is comes from the group alone (stepUp.ts), and why a review stays on its Builder's engine from
- // the server's own judgement (rules.ts).
+ // The step this attempt is comes from the group alone (stepUp.ts). An older CLI's same-engine note, as a field or at the
+ // start of its why, is not kept: any engine reviews now (rules.ts reviewRefusal).
const step = conversation(state, command.conversationId).stepUp
- const sameEngine = sameEngineReview(state, conversation(state, command.conversationId).reviewOf, member ? agentTarget(state, member) : chosen, policy, mayRun(command.conversationId, true), context.now)
- const { stepUp: _sent, sameEngine: _said, jobKind: _kind, ...made } = decision
+ const { stepUp: _sent, sameEngine: _said, jobKind: _kind, ...sent } = decision
+ const made = { ...sent, why: sent.why.replace(OLD_SAME_ENGINE, '') || sent.why }
const jobKind = jobKindOf(conversation(state, command.conversationId), decision.assessment.kind)
effects.routeDecisions.push({ op: 'create', id: operationId, conversationId: command.conversationId,
- record: { ...made, ...step ? { stepUp: { attempt: step.attempt, reason: step.reason } } : {}, ...sameEngine ? { sameEngine } : {}, jobKind } })
+ record: { ...made, ...step ? { stepUp: { attempt: step.attempt, reason: step.reason } } : {}, jobKind } })
result.routeDecisionId = operationId
// The row quotes the Lead's reason for the task; the verdict's own text stays in the decision record.
const reason = decision.assessment.why
- message(command.conversationId, `Routed to ${chosen.title} — ${via} · "${reason}"${sameEngine ? ` · ${SAME_ENGINE}` : ''}`, [], null, bookkeeping(command.conversationId, {
+ message(command.conversationId, `Routed to ${chosen.title} — ${via} · "${reason}"`, [], null, bookkeeping(command.conversationId, {
kind: 'route', decisionId: operationId, via: decision.via, p: decision.p, belowFloor: decision.belowFloor, why: reason,
...(decision.via === 'order' && decision.fallback ? { fallback: decision.fallback } : {}),
pick: { id: chosen.id, title: chosen.title },
@@ -2211,9 +2215,7 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
personChose = !override && decision.override?.by === 'person'
}
ruled(agentTarget(state, worker), group.id, `${who} assigned ${worker.name}`, personChose)
- // A review on its Builder's own engine says so first, so its Reviewer knows why (rules.ts sameEngineReview).
- const sameEngine = sameEngineReview(state, group.reviewOf, agentTarget(state, worker), policy, mayRun(group.id, true), context.now)
- message(group.id, `${sameEngine ? `${sameEngine}\n\n` : ''}${group.brief}${carryOver(group)}\n\nAcceptance checks:\n${group.checks.map(c => `- ${c.description}`).join('\n')}`, [worker.id], null, SYSTEM_ROW)
+ message(group.id, `${group.brief}${carryOver(group)}\n\nAcceptance checks:\n${group.checks.map(c => `- ${c.description}`).join('\n')}`, [worker.id], null, SYSTEM_ROW)
const news = assignedNotice(state, group, sender, operationId)
if (news) effects.messages.push(news)
if (routeNote) effects.messages.push({ id: stableId(operationId, 'route-override'), conversationId: group.id, author: sender,
@@ -2276,11 +2278,10 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
const opened = pullRequest && openReview(state, group, command.result!, pullRequest, { operationId, now: context.now, engineer: sender,
// The owner's hard rules hold as for work.assign; the reviewed task's own requirement is its Engineer's, not its Reviewer's.
mayWork: a => !teamWorkCheck(state, a.machineId, a.contributorId, groupProject(state, group), context.now, context.teamMachines, context.otherWorkspaceMachines)
- && !broken(groupRules(group.id), agentTarget(state, a), machineName, macOf) && !reviewRefusal(state, group.id, agentTarget(state, a), policy, mayRun(group.id, false), context.now),
- strength: a => agentQuality(state, policy, a),
- sameEngine: a => sameEngineReview(state, group.id, agentTarget(state, a), policy, mayRun(group.id, false), context.now) })
+ && !broken(groupRules(group.id), agentTarget(state, a), machineName, macOf) && !reviewRefusal(state, group.id, agentTarget(state, a), policy),
+ strength: a => agentQuality(state, policy, a) })
if (opened) effects.messages.push(...opened.messages)
- // No new Reviewer on another engine can start, or soon none will: the project's chat hears it once (reviewCapacity.ts).
+ // No new strong Reviewer of any engine can start, or soon none will: the project's chat hears it once (reviewCapacity.ts).
const short = command.status === 'review' && !group.reviewOf ? reviewCapacityNotice(state, group, policy, mayRun(group.id, false), context.now) : null
// A row of its own beside the command's, as the ship notice is: written as the Engineer who handed over.
if (short) effects.messages.push({ id: stableId(operationId, 'review-capacity', short.source.engine), conversationId: short.conversationId, author: sender,
@@ -2355,6 +2356,10 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
const check = group.checks.find(c => c.id === command.checkId) ?? fail('NOT_FOUND', 'This acceptance check is unavailable.', 404)
if (actor.kind === 'agent' && !group.agentIds.includes(actor.agentId)) fail('FORBIDDEN', 'This agent does not participate in the review.', 403)
if (check.independent && actor.kind === 'agent' && actor.agentId === group.assignment.agentId) fail('INDEPENDENT_REVIEW', 'Another agent or a person must perform this check.')
+ // The Builder of the reviewed work may sit in its review group, but never gives that review's verdict (review of #2313).
+ if (group.reviewOf && actor.kind === 'agent' && actor.agentId === state.conversations.find(c => c.id === group.reviewOf)?.assignment?.agentId) {
+ fail('INDEPENDENT_REVIEW', 'The Builder of the reviewed work does not give its review\'s verdict.')
+ }
check.evidence = command.evidence
check.passedBy = command.passed ? actorKey(actor) : null
const run = group.ledger?.runs?.find(r => r.assignmentId === group.assignment!.id), reviewed = run?.firstReview
diff --git a/backend/src/superTabs/costs/read.ts b/backend/src/superTabs/costs/read.ts
index cf09efd09..1ebc2d2b1 100644
--- a/backend/src/superTabs/costs/read.ts
+++ b/backend/src/superTabs/costs/read.ts
@@ -6,6 +6,7 @@
*/
import type { Prisma } from '@prisma/client'
import type { Conversation } from '../model.js'
+import { ms } from '../parts/light.js'
import { attemptTokens, type Billing, type RouteRun } from './attempts.js'
import { attemptCost } from './cost.js'
import { priceOf } from './prices.js'
@@ -43,6 +44,20 @@ export async function costRows(tx: Tx, tabId: string, since: number): Promise<{
return { rows, truncated: found.length > MAX_ROWS }
}
+/** The starts routed since `since` that failed before any work was assigned (routeDecisions.ts closeUnassignedStart), with
+ * the engine, model and effort they were to run: by the same tabId+createdAt index as costRows, at most MAX_ROWS. Only
+ * those fields leave the database. */
+export async function failedStarts(tx: Tx, tabId: string, since: number): Promise<Array<{ conversationId: string; engine: string; model: string; effort: string; at: number }>> {
+ const found = await tx.superTabRouteDecision.aggregateRaw({ pipeline: [
+ { $match: { tabId, createdAt: { $gte: { $date: new Date(since).toISOString() } }, outcome: 'failed' } },
+ { $sort: { createdAt: -1 } }, { $limit: MAX_ROWS },
+ { $project: { conversationId: 1, createdAt: 1, 'final.engine': 1, 'final.model': 1, 'final.effort': 1 } },
+ ] }) as unknown as Array<{ conversationId: string; createdAt: unknown; final?: { engine?: unknown; model?: unknown; effort?: unknown } }>
+ const text = (value: unknown) => typeof value === 'string' ? value : 'unknown'
+ return found.map(row => ({ conversationId: String(row.conversationId), engine: text(row.final?.engine), model: text(row.final?.model),
+ effort: text(row.final?.effort), at: ms(row.createdAt) }))
+}
+
export interface CostSummaryRow {
engine: string; model: string; effort: string; kind: string
attempts: number
diff --git a/backend/src/superTabs/costs/reflection.test.ts b/backend/src/superTabs/costs/reflection.test.ts
new file mode 100644
index 000000000..e9049721f
--- /dev/null
+++ b/backend/src/superTabs/costs/reflection.test.ts
@@ -0,0 +1,196 @@
+import { describe, expect, it } from 'vitest'
+import type { Conversation } from '../model.js'
+import type { ModelKindEvidence } from '../evidence/store.js'
+import type { RouteRun } from './attempts.js'
+import type { CostRow } from './read.js'
+import { approvedReminder, localDate, proposalQuestion, proposalTitle, routingReflection, wilson, type FailedStart, type ReflectionInput } from './reflection.js'
+
+const MINUTE = 60_000, HOUR = 60 * MINUTE, DAY = 24 * HOUR
+const NOW = 10 * DAY
+const tokens = (model: string, input: number) => ({ [model]: { input, output: 0, cacheRead: 0, cacheWrite: 0 } })
+/** An attempt [startedAt] ago that ran an hour and used 1M input tokens of [model]: $4 on Opus, $2 on Sonnet and gpt-6.1-sol. */
+const run = (engine: string, model: string, effort: string, startedAt: number, over: Partial<RouteRun> = {}): RouteRun => ({ machineId: 'm', harnessId: 'h',
+ engine, model, effort, billing: 'subscription', startedAt, start: {}, endedAt: startedAt + HOUR, end: tokens(model === 'opus' ? 'claude-opus-5-5'
+ : model === 'sonnet' ? 'claude-sonnet-5-5' : model, 1e6), ...over })
+const row = (assignmentId: string, conversationId: string, kind: string, r: RouteRun, stepUp?: CostRow['stepUp']): CostRow =>
+ ({ conversationId, assignmentId, outcome: 'done', kind, fresh: false, run: r, ...stepUp ? { stepUp } : {} })
+const group = (id: string, runs: Array<{ assignmentId: string; firstReview?: boolean }>, shipped?: { by: string; at: number }) => ({ id,
+ title: 'Secret plan for Acme', ledger: { runs: runs.map(r => ({ engine: 'claude', model: 'opus', at: 0, ...r })),
+ ...shipped ? { shippedAt: shipped.at, shippedBy: { assignmentId: shipped.by } } : {} } }) as unknown as Conversation
+const evidence = (engine: string, model: string, kind: string, over: Partial<ModelKindEvidence>) => ({ engine, model, kind, attempts: 0, firstReviews: 0,
+ firstReviewPassed: 0, reworkRounds: 0, shipped: 0, minutesToShipSum: 0, minutesToShipCount: 0, fixesAfterMerge: 0, tokensInput: 0, tokensOutput: 0,
+ tokensCacheRead: 0, tokensCacheWrite: 0, tokensKnown: 0, apiCost: 0, costKnown: 0, costUnknown: 0, spend: 0, spendKnown: 0, firstReviewPassRate: null,
+ averageMinutesToShip: null, costPerShipped: null, recent: [], ...over }) as ModelKindEvidence
+
+/**
+ * A seeded week of one project:
+ * - parser on Opus high: 5 attempts, all shipped, 4 of 5 first reviews passed, $4 each. Two of them in the last day.
+ * - parser on Sonnet medium: 5 attempts, all shipped, 4 of 5 passed, $2 each: as good for half the price.
+ * - ui on codex gpt-6.1-sol high: 6 attempts, 0 of 6 passed, one shipped later, $2 each.
+ * - docs: three tasks whose grid attempt (deepseek, own hardware, 1, 1.5 and 0.5 h) failed and stepped up to Sonnet, which shipped.
+ */
+function seededWeek(): ReflectionInput {
+ const rows: CostRow[] = [], groups: Conversation[] = []
+ const at = (daysAgo: number) => NOW - daysAgo * DAY
+ ;['p1', 'p2', 'p3', 'p4', 'p5'].forEach((id, i) => {
+ rows.push(row(id, `g-${id}`, 'parser', run('claude', 'opus', 'high', at(i < 2 ? 0.5 : 3))))
+ groups.push(group(`g-${id}`, [{ assignmentId: id, firstReview: i !== 4 }], { by: id, at: at(i < 2 ? 0.5 : 3) + HOUR }))
+ })
+ ;['s1', 's2', 's3', 's4', 's5'].forEach((id, i) => {
+ rows.push(row(id, `g-${id}`, 'parser', run('claude', 'sonnet', 'medium', at(4))))
+ groups.push(group(`g-${id}`, [{ assignmentId: id, firstReview: i !== 4 }], { by: id, at: at(4) + HOUR }))
+ })
+ ;['u1', 'u2', 'u3', 'u4', 'u5', 'u6'].forEach((id, i) => {
+ rows.push(row(id, `g-${id}`, 'ui', run('codex', 'gpt-6.1-sol', 'high', at(5))))
+ groups.push(group(`g-${id}`, [{ assignmentId: id, firstReview: false }], i === 5 ? { by: id, at: at(5) + HOUR } : undefined))
+ })
+ const grid = (minutes: number, daysAgo: number) => run('claude', 'deepseek/deepseek-v4.1-flash-1017', 'low', at(daysAgo),
+ { grid: 'deepseek/deepseek-v4.1-flash-1017', billing: 'own-hardware', endedAt: at(daysAgo) + minutes * MINUTE })
+ ;([[60, 6], [90, 2], [30, 1.5]] as const).forEach(([minutes, daysAgo], i) => {
+ const g = `g-d${i}`
+ rows.push(row(`d${i}`, g, 'docs', grid(minutes, daysAgo)),
+ row(`d${i}b`, g, 'docs', run('claude', 'sonnet', 'medium', at(daysAgo) + 2 * HOUR), { attempt: 2, reason: 'Its first review said Ready no.' }))
+ groups.push(group(g, [{ assignmentId: `d${i}`, firstReview: false }], { by: `d${i}b`, at: at(daysAgo) + 3 * HOUR }))
+ })
+ const failed: FailedStart = { engine: 'codex', model: 'gpt-6.1-sol', effort: 'high', at: at(0.2) }
+ return { now: NOW, rows, groups, failedStarts: [failed, { ...failed, at: at(3) }], truncated: false,
+ evidence: [evidence('claude', 'opus', 'feature', { reworkRounds: 1, fixesAfterMerge: 1 }), evidence('codex', 'gpt-6.1-sol', 'ui', { reworkRounds: 2 })] }
+}
+/** [n] more first reviews of a kind on a model, all as [passed], each shipped at $[cost]. */
+function more(week: ReflectionInput, kind: string, engine: string, model: string, effort: string, n: number, passed: boolean) {
+ for (let i = 0; i < n; i++) {
+ const id = `${kind}-${model}-${i}`
+ week.rows.push(row(id, `g-${id}`, kind, run(engine, model, effort, NOW - 3 * DAY)))
+ week.groups.push(group(`g-${id}`, [{ assignmentId: id, firstReview: passed }], { by: id, at: NOW - 3 * DAY + HOUR }))
+ }
+}
+const UI = 'Stop routing ui work to codex gpt-6.1-sol high'
+const PARSER = 'Route parser work to claude sonnet medium instead of claude opus high'
+const DOCS = 'Start docs work on a subscription model instead of the grid'
+
+describe('the nightly routing reflection', () => {
+ it('reports a seeded week: what shipped, time to ship, cost per shipped change and first-review pass rate per engine, model, effort and kind, and rework per model', () => {
+ const report = routingReflection(seededWeek())!
+ const lines = report.text.split('\n')
+ expect(lines).toContain('Last day: 2 attempts, 2 shipped. Last 7 days: 22 attempts, 14 shipped.')
+ expect(lines).toContain('- claude opus high, parser: 5 attempts, 5 shipped, median 60 min to ship, $4.00 per shipped change, first review passed 4 of 5 (80%)')
+ expect(lines).toContain('- claude sonnet medium, parser: 5 attempts, 5 shipped, median 60 min to ship, $2.00 per shipped change, first review passed 4 of 5 (80%)')
+ expect(lines).toContain('- codex gpt-6.1-sol high, ui: 6 attempts, 1 shipped, median 60 min to ship, $12.00 per shipped change, first review passed 0 of 6 (0%)')
+ expect(lines).toContain('- claude deepseek/deepseek-v4.1-flash-1017 low, docs: 3 attempts, 0 shipped, first review passed 0 of 3 (0%)')
+ expect(lines).toContain('- claude sonnet medium, docs: 3 attempts, 3 shipped, median 60 min to ship, $2.00 per shipped change, no first review, 3 step-ups')
+ expect(lines).toContain('Waste in the last 7 days: 2 failed starts (codex gpt-6.1-sol high: 2), 3 step-ups after a failed grid attempt '
+ + '(docs: 3, 3 hours), 3 rework rounds (codex gpt-6.1-sol ui: 2, claude opus feature: 1), 1 fix after merge (claude opus feature: 1).')
+ })
+
+ it('proposes at most three changes, the largest saving first, each with its counts, its uncertainty and its API-equivalent saving', () => {
+ const report = routingReflection(seededWeek())!
+ expect(report.proposals.map(({ title, why, saving, dollars, hours, strong }) => ({ title, why, saving, dollars, hours, strong }))).toEqual([
+ { title: UI, why: 'Its first review passed 0 of 6 (0%); even the top of its 95% range is 39%. Only 6 first reviews.',
+ saving: 'about $12.00 a week at API prices of attempts that failed their first review', dollars: 12, hours: 0, strong: false },
+ { title: PARSER, why: 'Its first review passed 4 of 5 (80%) against 4 of 5 (80%), at $2.00 instead of $4.00 per shipped change at API prices. '
+ + 'Small samples (5 and 5 first reviews): the difference may be chance.', saving: 'about $10.00 a week at API prices', dollars: 10, hours: 0, strong: false },
+ { title: DOCS, why: '3 of 3 docs tasks started on the grid stepped up after their grid attempt failed. Only 3 tasks.',
+ saving: 'about 3 hours to ship a week', dollars: 0, hours: 3, strong: false },
+ ])
+ expect(report.text).toContain('Proposed changes (advice: no rule or setting changes by itself):')
+ expect(report.text).toContain(`2. ${PARSER}: about $10.00 a week at API prices. Its first review passed 4 of 5`)
+ })
+
+ it('asks plainly what a Yes does, and recommends Yes only on strong evidence, else Not yet', () => {
+ const [ui] = routingReflection(seededWeek())!.proposals
+ expect(proposalQuestion(ui!)).toEqual({ question: `${UI}? Expected saving: ${ui!.saving}. ${ui!.why}`,
+ options: ['Yes: the Lead is reminded each night and routes this way; nothing changes by itself', 'No: keep routing as it is',
+ 'Not yet: ask again when there is more evidence'],
+ recommended: 2, unblocks: 'If you say yes, the Lead is reminded each night for 30 days and routes ui work this way. No rule or setting changes.' })
+ expect(proposalTitle(proposalQuestion(ui!).question)).toBe(UI)
+ // Ten first reviews on each side: strong enough to recommend Yes, with no small-sample warning.
+ const week = seededWeek()
+ more(week, 'parser', 'claude', 'opus', 'high', 5, true)
+ more(week, 'parser', 'claude', 'sonnet', 'medium', 5, true)
+ const parser = routingReflection(week)!.proposals.find(p => p.title === PARSER)!
+ expect(parser).toMatchObject({ strong: true, why: 'Its first review passed 9 of 10 (90%) against 9 of 10 (90%), at $2.00 instead of $4.00 per shipped change at API prices.' })
+ expect(proposalQuestion(parser).recommended).toBe(0)
+ })
+
+ it('proposes to stop a model only when even the top of its 95% range is under half', () => {
+ expect(wilson(0, 6).high).toBeCloseTo(0.39, 2)
+ expect(wilson(1, 6).high).toBeGreaterThan(0.5)
+ const week = seededWeek()
+ // One of the six passed: it may still pass half the time, so nothing is proposed for it.
+ week.groups = week.groups.map(g => g.id === 'g-u1' ? group('g-u1', [{ assignmentId: 'u1', firstReview: true }]) : g)
+ expect(routingReflection(week)!.proposals.map(p => p.title)).toEqual([PARSER, DOCS])
+ })
+
+ it('keeps only the three largest savings', () => {
+ const week = seededWeek()
+ // A fourth: test work on codex xhigh whose first review passed 0 of 7, at $2 each: $14 a week, the largest.
+ more(week, 'test', 'codex', 'gpt-6.1-sol', 'xhigh', 7, false)
+ expect(routingReflection(week)!.proposals.map(p => p.title)).toEqual(['Stop routing test work to codex gpt-6.1-sol xhigh', UI, PARSER])
+ })
+
+ it('leaves out what the owner answered lately, approved or a rule already does, without spending a slot on it, and lists what was approved', () => {
+ const week = seededWeek()
+ more(week, 'test', 'codex', 'gpt-6.1-sol', 'xhigh', 7, false)
+ expect(routingReflection({ ...week, decided: ['Stop routing test work to codex gpt-6.1-sol xhigh'] })!.proposals.map(p => p.title)).toEqual([UI, PARSER, DOCS])
+ const approved = routingReflection({ ...week, approved: [{ title: UI, on: '2026-10-28', by: 'owner' }, { title: DOCS, on: '2026-10-29', by: 'pm' }] })!
+ expect(approved.proposals.map(p => p.title)).toEqual(['Stop routing test work to codex gpt-6.1-sol xhigh', PARSER])
+ expect(approved.text.split('\n')).toEqual(expect.arrayContaining([
+ 'Approved changes: the Lead is reminded each night and routes this way; each is listed for 30 days:',
+ `- ${UI} (approved 2026-10-28)`,
+ // Left to the PM by the owner: never shown as the owner's own approval (delta review of #2276).
+ `- ${DOCS} (PM decided 2026-10-29)`]))
+ expect(approvedReminder([{ title: UI, on: '2026-10-28', by: 'owner' }])).toBe('Approved routing changes: route this way until routing does it '
+ + `by itself. This reminder repeats each night for 30 days after each approval.\n- ${UI} (approved 2026-10-28)`)
+ // A project rule forbidding the model, or no grid first, already makes the change.
+ expect(routingReflection({ ...seededWeek(), rules: [{ kind: 'forbidModel', engine: 'codex', model: 'gpt-6.1-sol' }] })!.proposals.map(p => p.title)).toEqual([PARSER, DOCS])
+ expect(routingReflection({ ...seededWeek(), rules: [{ kind: 'noGridFirst' }] })!.proposals.map(p => p.title)).toEqual([UI, PARSER])
+ })
+
+ it('dates in the project\'s time zone, the default one for none or an unknown one', () => {
+ const late = Date.UTC(2026, 9, 30, 18, 0)
+ expect(localDate(late)).toBe('2026-10-31')
+ expect(localDate(late, 'Europe/Berlin')).toBe('2026-10-30')
+ expect(localDate(late, 'Mars/Olympus')).toBe('2026-10-31')
+ })
+
+ it('says after each proposal what happened to it', () => {
+ const text = routingReflection(seededWeek())!.render(p => p.title === UI ? 'Asked of the project owner.' : null)
+ expect(text).toContain(`1. ${UI}: about $12.00 a week at API prices of attempts that failed their first review. Its first review passed 0 of 6 (0%); `
+ + 'even the top of its 95% range is 39%. Only 6 first reviews. Asked of the project owner.')
+ expect(text.split('\n')).toContain('3. Start docs work on a subscription model instead of the grid: about 3 hours to ship a week. 3 of 3 docs tasks started on '
+ + 'the grid stepped up after their grid attempt failed. Only 3 tasks.')
+ })
+
+ it('proposes nothing from too few first reviews, shipped changes or grid step-ups', () => {
+ const week = seededWeek()
+ week.rows = week.rows.filter(r => !['p5', 'u6', 'd2', 'd2b'].includes(r.assignmentId))
+ week.groups = week.groups.map(g => g.id === 'g-u1' ? group('g-u1', [{ assignmentId: 'u1', firstReview: true }]) : g)
+ expect(routingReflection(week)!.proposals).toEqual([])
+ expect(routingReflection(week)!.text).toContain('No change proposed.')
+ })
+
+ it('proposes no cheaper model on fewer than five first reviews, however well they went', () => {
+ const week = seededWeek()
+ // Without its one failed review, Sonnet passed 4 of 4: better and cheaper, but on four reviews.
+ week.rows = week.rows.filter(r => r.assignmentId !== 's5')
+ expect(routingReflection(week)!.proposals.map(p => p.title)).not.toContain(PARSER)
+ more(week, 'parser', 'claude', 'sonnet', 'medium', 1, true)
+ expect(routingReflection(week)!.proposals.map(p => p.title)).toContain(PARSER)
+ })
+
+ it('is empty for a day with no attempt and no failed start: nothing is posted', () => {
+ const week = seededWeek()
+ week.rows = week.rows.filter(r => r.run.startedAt < NOW - DAY)
+ week.failedStarts = week.failedStarts.filter(f => f.at < NOW - DAY)
+ expect(routingReflection(week)).toBeNull()
+ })
+
+ it('says only aggregates: no task title, assignment or conversation id', () => {
+ const text = routingReflection(seededWeek())!.text
+ for (const secret of ['Secret plan', 'g-p1', 'p1', 'u3']) expect(text).not.toContain(secret)
+ })
+
+ it('says when the newest attempts were all it could read', () => {
+ expect(routingReflection({ ...seededWeek(), truncated: true })!.text).toContain('Only the newest 3000 attempts were read.')
+ })
+})
diff --git a/backend/src/superTabs/costs/reflection.ts b/backend/src/superTabs/costs/reflection.ts
new file mode 100644
index 000000000..646fb875a
--- /dev/null
+++ b/backend/src/superTabs/costs/reflection.ts
@@ -0,0 +1,266 @@
+/**
+ * The nightly routing reflection (Scholes's roadmap, piece 2, 2026-10-30): what one project's routed work cost and how it went
+ * in the last day and the last 7 days, the waste, and at most three routing changes for its owner to approve, each with its
+ * expected saving. Pure: lib/routingReflection.ts reads the attempts (costs/read.ts costRows), failed starts and evidence, and
+ * posts the text. Counts only: engines, models, efforts and kinds of work, never a task's title, a message or an id.
+ * Nothing here changes routing: a proposal is advice asked of the owner, and an approved one is listed every night until
+ * routing applies it by itself (piece 3). No rule kind can express a change per kind of work (rules.ts).
+ */
+import { stableId, type Conversation } from '../model.js'
+import { modelMatches, type SwarmRule } from '../rules.js'
+import type { ModelKindEvidence } from '../evidence/store.js'
+import { attemptCost } from './cost.js'
+import { MAX_ROWS, summarizeCosts, type CostRow, type CostSummaryRow } from './read.js'
+
+const MINUTE = 60_000, DAY = 24 * 60 * MINUTE
+/** At most this many proposals a night (brief). */
+export const MAX_PROPOSALS = 3
+/** Rows of the per-model table the report lists; the rest are counted. */
+const MAX_LINES = 12
+/** A cheaper model is proposed only with this much evidence on each side: fewer first reviews or shipped changes say too
+ * little (review of #2276: 3 and 2 gave confident proposals from a handful of tasks). */
+const MIN_FIRST_REVIEWS = 5
+const MIN_SHIPPED = 3
+/** A model is proposed to stop taking a kind of work only when even the top of its pass rate's 95% range is under this. */
+const LOW_PASS_RATE = 0.5
+/** Tasks of a kind that must have stepped up from the grid before the grid is proposed to stop taking it. */
+const MIN_GRID_STEP_UPS = 3
+/** Yes is recommended only on this many first reviews (grid tasks for the grid) on every side; on fewer, "Not yet". */
+export const STRONG_SAMPLE = 10
+/** 95%. */
+const Z = 1.96
+
+/** The Wilson score interval of `passed` of `n` at 95%: where the true rate likely is, honest about small samples. */
+export function wilson(passed: number, n: number): { low: number; high: number } {
+ if (!n) return { low: 0, high: 1 }
+ const p = passed / n, z2 = Z * Z
+ const centre = p + z2 / (2 * n), spread = Z * Math.sqrt(p * (1 - p) / n + z2 / (4 * n * n)), scale = 1 + z2 / n
+ return { low: Math.max(0, (centre - spread) / scale), high: Math.min(1, (centre + spread) / scale) }
+}
+
+/** A start that failed (routeDecisions.ts closeUnassignedStart), on what it was to run, and when it was routed. */
+export interface FailedStart { engine: string; model: string; effort: string; at: number }
+
+export interface ReflectionInput {
+ now: number
+ /** The project's attempts routed in the last 7 days. */
+ rows: CostRow[]
+ /** Their groups, for their ledgers' first reviews and ships. */
+ groups: Conversation[]
+ /** The project's failed starts in the last 7 days. */
+ failedStarts: FailedStart[]
+ /** The project's evidence since the week holding 7 days ago: rework rounds and fixes after merge. */
+ evidence: ModelKindEvidence[]
+ /** More attempts than one read takes: only the newest were read. */
+ truncated: boolean
+ /** Titles of proposals the owner answered in the last REASK_DAYS days: not proposed again until then. */
+ decided?: readonly string[]
+ /** Proposals approved in the last APPROVED_DAYS days, with the local date and who decided: the owner, or the PM when the
+ * owner left it to the PM. Listed every night, and not proposed again while listed. */
+ approved?: readonly Approved[]
+ /** The project's routing rules: a change one already makes is not proposed. */
+ rules?: ReadonlyArray<SwarmRule['rule']>
+}
+
+type RanOn = Pick<CostSummaryRow, 'engine' | 'model' | 'effort'>
+/** What a proposal changes, for telling whether a rule already does. */
+export type Change = { kind: 'cheaper'; taskKind: string; from: RanOn; to: RanOn } | { kind: 'stop'; taskKind: string; from: RanOn }
+ | { kind: 'grid'; taskKind: string }
+/** A routing change for the owner: what, why, what it would save a week in dollars (API-equivalent) and hours to ship, and
+ * whether its evidence is strong enough to recommend Yes. */
+export interface Proposal { title: string; why: string; saving: string; dollars: number; hours: number; strong: boolean; change: Change }
+export interface Reflection {
+ /** The report with no note on its proposals. */
+ text: string
+ proposals: Proposal[]
+ /** The report with a note after each proposal: whether it was asked, and if not, why (store.ts postReflection). */
+ render(note: (p: Proposal) => string | null): string
+}
+/** Days an answered proposal is not proposed again. */
+export const REASK_DAYS = 14
+/** Days an approved proposal is listed and reminded each night; after that it may be proposed again (Lead's ruling). */
+export const APPROVED_DAYS = 30
+export interface Approved { title: string; on: string; by: 'owner' | 'pm' }
+/** The zone of a project that set no digest: the owner's time zone is stored nowhere; the digest's is the one a project sets. */
+export const DEFAULT_TIME_ZONE = 'Asia/Ho_Chi_Minh'
+/** The local date of [at] in [timeZone], or in the default zone for none or one this runtime does not know. */
+export function localDate(at: number, timeZone: string = DEFAULT_TIME_ZONE): string {
+ const format = (zone: string) => new Intl.DateTimeFormat('en-CA', { timeZone: zone, year: 'numeric', month: '2-digit', day: '2-digit' }).format(at)
+ try { return format(timeZone) } catch { return format(DEFAULT_TIME_ZONE) }
+}
+const decidedBy = (a: Approved) => `${a.by === 'pm' ? 'PM decided' : 'approved'} ${a.on}`
+/** The Lead's nightly reminder of what was approved: it routes this way until routing does it by itself. */
+export const approvedReminder = (approved: readonly Approved[]): string =>
+ ['Approved routing changes: route this way until routing does it by itself. This reminder repeats each night for 30 days after each approval.',
+ ...approved.map(a => `- ${a.title} (${decidedBy(a)})`)].join('\n')
+
+const plural = (n: number, one: string, many = `${one}s`) => `${n} ${n === 1 ? one : many}`
+const usd = (n: number) => `$${n.toFixed(2)}`
+const percent = (rate: number) => `${Math.round(rate * 100)}%`
+const cents = (n: number) => Math.round(n * 100) / 100
+const tenths = (n: number) => Math.round(n * 10) / 10
+const ranOn = (r: RanOn) => `${r.engine} ${r.model} ${r.effort}`
+const passed = (r: CostSummaryRow) => `${r.firstReviewPassed} of ${r.firstReviews} (${percent(r.firstReviewPassRate!)})`
+const atApi = 'a week at API prices'
+
+function line(r: CostSummaryRow): string {
+ return `- ${ranOn(r)}, ${r.kind}: ${plural(r.attempts, 'attempt')}, ${r.shipped} shipped`
+ + (r.medianMinutesToShip !== null ? `, median ${Math.round(r.medianMinutesToShip)} min to ship` : '')
+ + (r.costPerShipped !== null ? `, ${usd(r.costPerShipped)} per shipped change` : '')
+ + (r.firstReviews ? `, first review passed ${r.firstReviewPassed} of ${r.firstReviews} (${percent(r.firstReviewPassRate!)})` : ', no first review')
+ + (r.stepUps ? `, ${plural(r.stepUps, 'step-up')}` : '')
+}
+
+/** Per kind, the tasks whose grid attempt failed and stepped up: how many, and the grid attempts' hours and cost. Also how
+ * many tasks of the kind started on the grid. A step up is the attempt that carries it (stepUp.ts); the grid attempts
+ * before it in its task are what it replaced. */
+function gridStepUps(rows: CostRow[], now: number) {
+ const byGroup = new Map<string, CostRow[]>()
+ for (const r of rows) byGroup.set(r.conversationId, [...byGroup.get(r.conversationId) ?? [], r])
+ const kinds = new Map<string, { tasks: number; stepped: number; hours: number; dollars: number }>()
+ for (const attempts of byGroup.values()) {
+ attempts.sort((a, b) => a.run.startedAt - b.run.startedAt)
+ const onGrid = attempts.filter(r => r.run.grid)
+ if (!onGrid.length) continue
+ const kind = onGrid[0]!.kind ?? 'unspecified'
+ const k = kinds.get(kind) ?? { tasks: 0, stepped: 0, hours: 0, dollars: 0 }
+ k.tasks++
+ const step = attempts.find(r => r.stepUp && r.run.startedAt >= onGrid[0]!.run.startedAt)
+ if (step) {
+ k.stepped++
+ for (const r of onGrid.filter(g => g.run.startedAt <= step.run.startedAt)) {
+ k.hours += ((r.run.endedAt ?? now) - r.run.startedAt) / (60 * MINUTE)
+ k.dollars += attemptCost(r.run, r.fresh).apiCost ?? 0
+ }
+ }
+ kinds.set(kind, k)
+ }
+ return kinds
+}
+
+function proposals(rows: CostSummaryRow[], grid: ReturnType<typeof gridStepUps>): Proposal[] {
+ const found: Proposal[] = []
+ const known = rows.filter(r => r.kind !== 'unspecified')
+ // A cheaper model on the same kind whose first review passes at least as often.
+ const priced = known.filter(r => r.firstReviews >= MIN_FIRST_REVIEWS && r.shipped >= MIN_SHIPPED && r.costPerShipped !== null)
+ const moved = new Set<CostSummaryRow>()
+ for (const kind of new Set(priced.map(r => r.kind))) {
+ let best: { dear: CostSummaryRow; cheap: CostSummaryRow; dollars: number } | null = null
+ for (const dear of priced.filter(r => r.kind === kind)) {
+ for (const cheap of priced.filter(r => r.kind === kind && r !== dear)) {
+ if (cheap.costPerShipped! >= dear.costPerShipped! || cheap.firstReviewPassRate! < dear.firstReviewPassRate!) continue
+ const dollars = cents((dear.costPerShipped! - cheap.costPerShipped!) * dear.shipped)
+ if (!best || dollars > best.dollars) best = { dear, cheap, dollars }
+ }
+ }
+ if (!best) continue
+ const { dear, cheap, dollars } = best
+ const strong = Math.min(dear.firstReviews, cheap.firstReviews) >= STRONG_SAMPLE
+ moved.add(dear)
+ found.push({ title: `Route ${kind} work to ${ranOn(cheap)} instead of ${ranOn(dear)}`,
+ why: `Its first review passed ${passed(cheap)} against ${passed(dear)}, at ${usd(cheap.costPerShipped!)} instead of `
+ + `${usd(dear.costPerShipped!)} per shipped change at API prices.`
+ + (strong ? '' : ` Small samples (${dear.firstReviews} and ${cheap.firstReviews} first reviews): the difference may be chance.`),
+ saving: `about ${usd(dollars)} ${atApi}`, dollars, hours: 0, strong,
+ change: { kind: 'cheaper', taskKind: kind, from: pick(dear), to: pick(cheap) } })
+ }
+ // A model whose first review clearly fails more often than it passes on a kind of work: even the top of its range is low.
+ for (const r of known) {
+ if (moved.has(r) || r.firstReviews < MIN_FIRST_REVIEWS || wilson(r.firstReviewPassed, r.firstReviews).high >= LOW_PASS_RATE) continue
+ const failed = r.firstReviews - r.firstReviewPassed, strong = r.firstReviews >= STRONG_SAMPLE
+ const dollars = r.apiCost !== null && r.costKnown ? cents(r.apiCost / r.costKnown * failed) : 0
+ found.push({ title: `Stop routing ${r.kind} work to ${ranOn(r)}`,
+ why: `Its first review passed ${passed(r)}; even the top of its 95% range is ${percent(wilson(r.firstReviewPassed, r.firstReviews).high)}.`
+ + (strong ? '' : ` Only ${r.firstReviews} first reviews.`),
+ saving: dollars ? `about ${usd(dollars)} ${atApi} of attempts that failed their first review`
+ : `${plural(failed, 'attempt')} a week that failed their first review`, dollars, hours: 0, strong,
+ change: { kind: 'stop', taskKind: r.kind, from: pick(r) } })
+ }
+ // A kind whose tasks keep stepping up from the grid.
+ for (const [kind, k] of grid) {
+ if (kind === 'unspecified' || k.stepped < MIN_GRID_STEP_UPS || k.stepped * 2 < k.tasks) continue
+ const hours = tenths(k.hours), dollars = cents(k.dollars), strong = k.tasks >= STRONG_SAMPLE
+ found.push({ title: `Start ${kind} work on a subscription model instead of the grid`,
+ why: `${k.stepped} of ${k.tasks} ${kind} tasks started on the grid stepped up after their grid attempt failed.`
+ + (strong ? '' : ` Only ${k.tasks} tasks.`),
+ saving: `about ${dollars ? `${usd(dollars)} at API prices and ` : ''}${hours} hours to ship a week`, dollars, hours, strong,
+ change: { kind: 'grid', taskKind: kind } })
+ }
+ return found.sort((a, b) => b.dollars - a.dollars || b.hours - a.hours)
+}
+
+const pick = (r: RanOn): RanOn => ({ engine: r.engine, model: r.model, effort: r.effort })
+
+/** Whether one of the project's rules already makes this change: a forbidden model it moves work away from, or no grid first. */
+function ruled(change: Change, rules: ReadonlyArray<SwarmRule['rule']>): boolean {
+ return rules.some(rule => change.kind === 'grid' ? rule.kind === 'noGridFirst'
+ : rule.kind === 'forbidModel' && (!rule.engine || rule.engine === change.from.engine) && modelMatches(rule.model, change.from.model))
+}
+
+function waste(input: ReflectionInput, grid: ReturnType<typeof gridStepUps>, stepUps: number): string {
+ const failed = new Map<string, number>()
+ for (const f of input.failedStarts) failed.set(ranOn(f), (failed.get(ranOn(f)) ?? 0) + 1)
+ const stepped = [...grid].filter(([, k]) => k.stepped)
+ const fromGrid = stepped.reduce((n, [, k]) => n + k.stepped, 0)
+ /** A count over the evidence, with each model and kind that has some, the most first. */
+ const byModel = (count: (m: ModelKindEvidence) => number, one: string, many?: string) => {
+ const has = input.evidence.filter(m => count(m) > 0).sort((x, y) => count(y) - count(x))
+ const total = has.reduce((n, m) => n + count(m), 0)
+ return total ? [`${plural(total, one, many)} (${has.map(m => `${m.engine} ${m.model} ${m.kind}: ${count(m)}`).join(', ')})`] : []
+ }
+ const parts = [
+ ...input.failedStarts.length ? [`${plural(input.failedStarts.length, 'failed start')} (${[...failed].sort((a, b) => b[1] - a[1])
+ .map(([on, n]) => `${on}: ${n}`).join(', ')})`] : [],
+ ...fromGrid ? [`${plural(fromGrid, 'step-up')} after a failed grid attempt (${stepped.map(([kind, k]) => `${kind}: ${k.stepped}, ${tenths(k.hours)} hours`).join('; ')})`] : [],
+ ...stepUps > fromGrid ? [`${plural(stepUps - fromGrid, 'other step-up')}`] : [],
+ ...byModel(m => m.reworkRounds, 'rework round'),
+ ...byModel(m => m.fixesAfterMerge, 'fix after merge', 'fixes after merge'),
+ ]
+ return `Waste in the last 7 days: ${parts.length ? parts.join(', ') : 'none'}.`
+}
+
+/** The night's report, or null when the last day had no attempt and no failed start: then nothing is posted. At most
+ * MAX_PROPOSALS proposals, the largest saving first, leaving out those the owner answered lately, approved, or a rule makes. */
+export function routingReflection(input: ReflectionInput): Reflection | null {
+ const since = input.now - DAY
+ const dayRows = input.rows.filter(r => r.run.startedAt >= since)
+ if (!dayRows.length && !input.failedStarts.some(f => f.at >= since)) return null
+ const week = summarizeCosts(input.rows, input.groups), day = summarizeCosts(dayRows, input.groups)
+ const grid = gridStepUps(input.rows, input.now)
+ const approved = input.approved ?? []
+ const settled = new Set([...input.decided ?? [], ...approved.map(a => a.title)])
+ const proposed = proposals(week.rows, grid).filter(p => !settled.has(p.title) && !ruled(p.change, input.rules ?? [])).slice(0, MAX_PROPOSALS)
+ const table = [...week.rows].sort((a, b) => b.attempts - a.attempts)
+ const render = (note: (p: Proposal) => string | null) => [
+ 'Routing reflection: what routed work cost and how it went. Counts only; routing changes only as the project owner approves.',
+ `Last day: ${plural(day.totals.attempts, 'attempt')}, ${day.totals.shipped} shipped. Last 7 days: ${plural(week.totals.attempts, 'attempt')}, ${week.totals.shipped} shipped.`,
+ 'By engine, model and effort, per kind of work (last 7 days; cost is what the tokens would cost on the API):',
+ ...table.slice(0, MAX_LINES).map(line),
+ ...table.length > MAX_LINES ? [`- and ${table.length - MAX_LINES} more`] : [],
+ waste(input, grid, week.totals.stepUps),
+ ...approved.length ? ['Approved changes: the Lead is reminded each night and routes this way; each is listed for 30 days:',
+ ...approved.map(a => `- ${a.title} (${decidedBy(a)})`)] : [],
+ ...proposed.length ? ['Proposed changes (advice: no rule or setting changes by itself):',
+ ...proposed.map((p, i) => { const n = note(p); return `${i + 1}. ${p.title}: ${p.saving}. ${p.why}${n ? ` ${n}` : ''}` })]
+ : ['No change proposed.'],
+ ...input.truncated ? [`Only the newest ${MAX_ROWS} attempts were read.`] : [],
+ ].join('\n')
+ return { text: render(() => null), proposals: proposed, render }
+}
+
+/** The id of a project's report for one local date: one a night, so a second pass or a second worker writes none. */
+export const reflectionMessageId = (tabId: string, projectId: string, on: string): string => stableId('routing-reflection', tabId, projectId, on)
+
+/** The answer that approves a proposal. */
+export const APPROVE = 0
+/** A proposal asked of the project owner as a decision. The question starts with the proposal's title, so a proposal waiting
+ * for an answer, answered lately or approved is told by it (proposalTitle). It says plainly what Yes does: nothing changes
+ * by itself; the Lead is reminded each night and routes this way (reviews of #2276). */
+export const proposalQuestion = (p: Proposal) => ({ question: `${p.title}? Expected saving: ${p.saving}. ${p.why}`,
+ options: ['Yes: the Lead is reminded each night and routes this way; nothing changes by itself', 'No: keep routing as it is',
+ 'Not yet: ask again when there is more evidence'],
+ recommended: p.strong ? APPROVE : 2,
+ unblocks: `If you say yes, the Lead is reminded each night for ${APPROVED_DAYS} days and routes ${p.change.taskKind} work this way. `
+ + 'No rule or setting changes.' })
+/** The proposal a decision asked, by the title its question starts with. */
+export const proposalTitle = (question: string): string => question.slice(0, Math.max(0, question.indexOf('?')))
diff --git a/backend/src/superTabs/decisions.ts b/backend/src/superTabs/decisions.ts
index e585d99b5..c67bc6d44 100644
--- a/backend/src/superTabs/decisions.ts
+++ b/backend/src/superTabs/decisions.ts
@@ -27,9 +27,16 @@ export const decisionChoices = z.object({ options: z.array(line(200)).min(2).max
export const decisionQuestion = decisionChoices.extend({ question: line(1000) }).strict()
type Question = z.infer<typeof decisionQuestion>
+/** The kind of a decision the nightly routing reflection asks (costs/reflection.ts): about the project's routing, so its
+ * owner's Buddy never reads it, and an approved one stays until routing applies it (review of #2276). */
+export const REFLECTION_DECISION = 'routing-reflection'
+/** Not a routing reflection's: rows written before `kind` have none. */
+const notReflection: Prisma.SuperTabDecisionWhereInput = { OR: [{ kind: { isSet: false } }, { kind: null }, { kind: { not: REFLECTION_DECISION } }] }
+
/** A decision as asked, written by the store. */
export interface DecisionDraft extends Question {
id: string; batchId: string; conversationId: string; projectId: string; personId: string; askerAgentId: string; assignmentId: string | null
+ kind?: typeof REFLECTION_DECISION
}
/** The decision `decision.answer` names, read from SuperTabDecision by the store. */
export interface DecisionTarget {
@@ -38,13 +45,14 @@ export interface DecisionTarget {
recommended: number; answeredAt: number | null
/** When it was asked, and the task whose needs_human asked it: the leaderboard credits the answer (leaderboard/record.ts). */
createdAt: number; assignmentId: string | null
+ kind?: string | null
}
/** `delegated`: the person asked left it to the PM, who took the recommended option. */
export interface DecisionAnswer { id: string; choice: number; note: string | null; delegated?: true }
/** Questions for one person in one conversation they read, from `asker`. One batch: one id ties them, no ping per question. */
export function askDecisions(state: SuperTabState, group: Conversation, personId: string, questions: Question[],
- from: { operationId: string; askerAgentId: string; assignmentId: string | null }): DecisionDraft[] {
+ from: { operationId: string; askerAgentId: string; assignmentId: string | null; kind?: typeof REFLECTION_DECISION }): DecisionDraft[] {
const asked = state.people.find(p => p.id === personId) ?? fail('INVALID_PERSON', 'Ask a person in this Swarm.', 400)
if (!canReadGroup(state, { kind: 'person', userId: asked.id, email: asked.email }, group)) {
fail('INVALID_PERSON', `${asked.email} cannot read this conversation.`, 400)
@@ -52,7 +60,7 @@ export function askDecisions(state: SuperTabState, group: Conversation, personId
for (const q of questions) if (q.recommended >= q.options.length) fail('INVALID_DECISION', 'A question must recommend one of its options.', 400)
const projectId = groupProject(state, group).id
return questions.map((q, index) => ({ ...q, id: stableId(from.operationId, 'decision', String(index)), batchId: from.operationId,
- conversationId: group.id, projectId, personId, askerAgentId: from.askerAgentId, assignmentId: from.assignmentId }))
+ conversationId: group.id, projectId, personId, askerAgentId: from.askerAgentId, assignmentId: from.assignmentId, ...from.kind ? { kind: from.kind } : {} }))
}
/** Only the project's Lead asks with `decision.ask`, in its own project's conversations (a worker asks through needs_human). */
@@ -109,7 +117,8 @@ export function answerDecision(state: SuperTabState, actor: Actor, decision: Dec
const notice = given.delegate ? closed ? CLOSED_CHAT_DELEGATED_NOTICE : DELEGATED_NOTICE : closed ? CLOSED_CHAT_ANSWERED_NOTICE : ANSWERED_NOTICE
const recipients = [...new Set([asked.askerAgentId, ...lead ? [lead] : []])].filter(id => noticeIn.agentIds.includes(id))
const answer: DecisionAnswer = { id: asked.id, choice, note: given.note, ...given.delegate ? { delegated: true as const } : {} }
- const line = given.delegate && lead ? delegatedLine(state, project.id, lead, asked, choice) : null
+ // A routing reflection's never reaches the Buddy chat: the person's Buddy reads it (review of #2276).
+ const line = given.delegate && lead && asked.kind !== REFLECTION_DECISION ? delegatedLine(state, project.id, lead, asked, choice) : null
return { answer, noticeIn: noticeIn.id, notice, recipients, source: { ...AGENT_ONLY, decisionId: asked.id }, line }
}
@@ -183,10 +192,26 @@ export async function fullFor(tx: Tx, tabId: string, ask: { personId: string; as
return asked < MAX_OPEN_DECISIONS ? null : asked
}
+/** A project's routing reflection decisions, newest first, through the project index: at most MAX_PROPOSALS are asked a
+ * night, and answered ones go after the ledger's weeks (store.ts postReflection). */
+export async function reflectionDecisions(tx: Tx, tabId: string, projectId: string) {
+ return tx.superTabDecision.findMany({ where: { tabId, projectId, kind: REFLECTION_DECISION },
+ select: { id: true, question: true, choice: true, answeredAt: true, createdAt: true, delegated: true }, orderBy: { createdAt: 'desc' }, take: 500 })
+}
+
+/** Days a routing reflection's proposal stays open unanswered: its week's numbers are stale by then (review of #2276). */
+export const REFLECTION_OPEN_DAYS = 7
+/** Removes a project's routing proposals left unanswered for REFLECTION_OPEN_DAYS, through the project index. Run on every
+ * night the project's report is due, a report or not (delta review of #2276). */
+export async function expireReflections(tx: Tx, tabId: string, projectId: string, now: number): Promise<void> {
+ await tx.superTabDecision.deleteMany({ where: { tabId, projectId, kind: REFLECTION_DECISION,
+ createdAt: { lt: new Date(now - REFLECTION_OPEN_DAYS * 24 * 3_600_000) }, ...waiting } })
+}
+
export async function readAskedDecision(tx: Tx, tabId: string, id: string): Promise<DecisionTarget | undefined> {
const row = await tx.superTabDecision.findFirst({ where: { id, tabId },
select: { id: true, personId: true, conversationId: true, projectId: true, askerAgentId: true, question: true, options: true, recommended: true,
- answeredAt: true, createdAt: true, assignmentId: true } })
+ answeredAt: true, createdAt: true, assignmentId: true, kind: true } })
return row ? { ...row, answeredAt: row.answeredAt?.getTime() ?? null, createdAt: row.createdAt.getTime(), assignmentId: row.assignmentId ?? null } : undefined
}
@@ -204,7 +229,8 @@ function readerWhere(state: SuperTabState, actor: Actor): Prisma.SuperTabDecisio
// A Buddy reads its person's own decisions in its project, by the person's index; each one's conversation is still
// checked as the Buddy reads it (readableIn), so none in a private chat or after its person left (buddies.ts).
const buddy = state.agents.find(a => a.id === actor.agentId && isBuddy(a))
- if (buddy) return { personId: buddy.buddyOf!.personId, projectId: agentProjectId(state, buddy) }
+ // Never a routing reflection's: those are about the project's routing, for its people (review of #2276).
+ if (buddy) return { personId: buddy.buddyOf!.personId, projectId: agentProjectId(state, buddy), AND: [notReflection] }
const led = ledProject(state, actor.agentId)
return { OR: [{ askerAgentId: actor.agentId }, ...led ? [{ projectId: led.id }] : []] }
}
diff --git a/backend/src/superTabs/model.ts b/backend/src/superTabs/model.ts
index 95fb25e5e..076eec320 100644
--- a/backend/src/superTabs/model.ts
+++ b/backend/src/superTabs/model.ts
@@ -415,6 +415,8 @@ export const NOTICE_READERS = {
rule: 'people', 'project-report': 'people', route: 'people', 'route-override': 'people', 'buddy-proposal': 'people',
'decision-delegated': 'people', 'machine-removed': 'people', 'machine-left': 'people', ship: 'people', 'auto-review': 'people',
'auto-archive': 'people', native: 'people',
+ // The nightly routing reflection, for the project's people; never a Buddy's (buddies.ts routingRow).
+ 'routing-reflection': 'people',
// No new Reviewer can start, or soon none will, tagging who can fix it (reviewCapacity.ts).
'review-capacity': 'people',
// #2177's rulings: a failed start and a terminal's alert or typed input stay the people's to see.
diff --git a/backend/src/superTabs/parts/index.ts b/backend/src/superTabs/parts/index.ts
index 9d68f6c69..632e32e70 100644
--- a/backend/src/superTabs/parts/index.ts
+++ b/backend/src/superTabs/parts/index.ts
@@ -8,5 +8,5 @@ export { clock, createClock } from './clock.js'
export { knownKind, reassemble, split, toLegacyState } from './shape.js'
export { DORMANT_PAGE, insertParts, lastChangedAt, loadActive, loadAll, loadChanged, loadDormant, loadGroups, loadMachines, loadObserved, loadReadBase, loadStartsOfAgents } from './load.js'
-export { loadLight } from './light.js'
+export { loadLight, loadLightGroups } from './light.js'
export { guardedWrite, PartConflict, type PartWrite } from './write.js'
diff --git a/backend/src/superTabs/parts/light.test.ts b/backend/src/superTabs/parts/light.test.ts
index 1a6f1db80..c2258bfc1 100644
--- a/backend/src/superTabs/parts/light.test.ts
+++ b/backend/src/superTabs/parts/light.test.ts
@@ -1,5 +1,7 @@
import { describe, expect, it } from 'vitest'
-import { activeWork, type Assignment, type Conversation, type WorkStatus } from '../model.js'
+import { activeWork, type Actor, type Assignment, type Conversation, type WorkStatus } from '../model.js'
+import { canReadGroup } from '../projects.js'
+import { outsider, owner, peer, swarm } from '../read/fixture.test-support.js'
import { FINISHED, GROUP_FIELDS } from './light.js'
/** Every field a conversation and its assignment can carry: adding one to model.ts fails this file's typecheck until it is
@@ -33,4 +35,33 @@ describe('the light conversation projection (parts/light.ts)', () => {
expect([status, !FINISHED.includes(status)]).toEqual([status, activeWork({ ...conversation, assignment: { ...assignment, status } })])
}
})
+
+ it('keeps the fields the access check reads: every reader reads a light conversation as they read the whole one', () => {
+ // The route-decision list asks canReadGroup of light groups (store.ts readableDecisions): a field dropped here opens a private one.
+ expect(GROUP_FIELDS.always).toEqual(expect.arrayContaining(['id', 'kind', 'projectId', 'audience', 'agentIds']))
+ const s = swarm()
+ s.join(peer)
+ s.join(outsider)
+ const lead = s.add('lead-harness', 'lead', true)
+ const secret = s.run({ type: 'project.create', name: 'Secret', visibility: 'private', brief: '' }).projectId as string
+ const [web, hidden, closedChat, buddyChat] = [s.group('Web'), s.group('Secret work', secret), s.group('Peer and PM'), s.group('Peer\'s Buddy')]
+ s.edit(state => {
+ const audience = { people: [{ id: peer.userId, generation: state.people.find(p => p.id === peer.userId)!.generation }] }
+ state.conversations.find(c => c.id === closedChat)!.audience = audience
+ Object.assign(state.conversations.find(c => c.id === buddyChat)!, { kind: 'buddy', leadId: null, agentIds: [], audience })
+ })
+ const state = s.state
+ const kept = GROUP_FIELDS.always.filter(field => !field.includes('.'))
+ const light = (group: Conversation) => Object.fromEntries(kept.filter(field => field in group).map(field => [field, group[field as keyof Conversation]])) as unknown as Conversation
+ const leadActor: Actor = { kind: 'agent', agentId: lead, machineOwnerId: state.agents.find(a => a.id === lead)!.machineOwnerId }
+ const readers: Actor[] = [owner, peer, outsider, leadActor]
+ const reads = readers.flatMap(actor => [web, hidden, closedChat, buddyChat].map(id => {
+ const group = state.conversations.find(c => c.id === id)!
+ expect(canReadGroup(state, actor, light(group)), `${actor.kind} ${id}`).toBe(canReadGroup(state, actor, group))
+ return canReadGroup(state, actor, group)
+ }))
+ // The readers differ over the groups, or "the same" proves little.
+ expect(reads).toContain(true)
+ expect(reads).toContain(false)
+ })
})
diff --git a/backend/src/superTabs/parts/light.ts b/backend/src/superTabs/parts/light.ts
index e61c85a20..ac10d8a10 100644
--- a/backend/src/superTabs/parts/light.ts
+++ b/backend/src/superTabs/parts/light.ts
@@ -102,6 +102,12 @@ export async function loadDeliveryParts(tx: Transaction, tabId: string, groupIds
sequenceBase: head.sequenceBase, visibilityEpoch: head.visibilityEpoch, groupCounter: head.groupCounter } as SwarmParts
}
+/** A Swarm's live groups that `match` finds through `index`, light as `loadLight` keeps them: for a read that only checks who may
+ * read them (the route-decision list), where a brief or a task is bytes sent for nothing. Never committed as state. */
+export async function loadLightGroups(tx: Transaction, tabId: string, index: GroupIndex, match: Record<string, unknown>): Promise<Part<GroupData>[]> {
+ return (await groupsBy(tx, index, [{ $match: { tabId, deleted: false, ...match } as Prisma.InputJsonValue }, { $project: LIGHT_GROUP }])).map(lightGroup)
+}
+
/**
* The live parts of one Swarm with conversations light. Conversations: every active one (`groups: 'active'`, as
* `loadActive`), or only the Lead conversations and those with running work (`'working'`: what visibility and derived
diff --git a/backend/src/superTabs/parts/touches.test.ts b/backend/src/superTabs/parts/touches.test.ts
index c1fda1219..169f47ce6 100644
--- a/backend/src/superTabs/parts/touches.test.ts
+++ b/backend/src/superTabs/parts/touches.test.ts
@@ -54,7 +54,7 @@ describe('the parts a command touches (design section 1.2, column T)', () => {
it('makes two reviews the Swarm opens at once meet on the Reviewer both would take, and on the head that numbers them', () => {
const f = swarm(), a = f.group('A')
- // On another engine than the Engineer's: a review never runs on the reviewed Builder's own (rules.ts reviewRefusal).
+ // A strong Reviewer of either engine reviews (rules.ts reviewRefusal).
const reviewer = f.run({ type: 'agent.add', conversationId: 'lead', machineId: 'host', harnessId: 'reviewer', name: 'Reviewer', configuration: { ...config, engine: config.engine === 'claude' ? 'codex' : 'claude', model: config.engine === 'claude' ? 'default' : 'opus' }, lead: false },
owner, { contribution: { machineOwnerId: 'host-owner', contributorId: 'owner' } }).effects.result.agentId as string
f.state.agents.find(x => x.id === reviewer)!.role = 'reviewer'
diff --git a/backend/src/superTabs/projects.ts b/backend/src/superTabs/projects.ts
index 163a846da..c66093cbc 100644
--- a/backend/src/superTabs/projects.ts
+++ b/backend/src/superTabs/projects.ts
@@ -56,9 +56,9 @@ export interface SwarmProject {
roles?: ProjectRole[]
/** Its Product Manager started by the Swarm on one of its machines, or waiting for one (leadStart.ts). */
lead?: import('./leadStart.js').LeadPlacement
- /** What its chat was last told of new Reviewers per engine (reviewCapacity.ts): none can start, or they soon will not.
- * Absent once a machine is usable again, so the next shortage is told. */
- reviewCapacity?: Partial<Record<'claude' | 'codex', 'out' | 'low'>>
+ /** What its chat was last told of new Reviewers (reviewCapacity.ts), under `any`: none can start, or they soon will not.
+ * Absent once a machine is usable again, so the next shortage is told. Per engine before 2026-10-30, never read since. */
+ reviewCapacity?: Partial<Record<'any' | 'claude' | 'codex', 'out' | 'low'>>
}
export const skillModeOf = (project: SwarmProject): SkillMode => project.skillMode ?? 'orchestration'
diff --git a/backend/src/superTabs/reviewCapacity.test.ts b/backend/src/superTabs/reviewCapacity.test.ts
index 82550f587..593c73b10 100644
--- a/backend/src/superTabs/reviewCapacity.test.ts
+++ b/backend/src/superTabs/reviewCapacity.test.ts
@@ -3,31 +3,36 @@ import type { ContributedMachine } from './machines.js'
import { createSuperTab, type Conversation, type SuperTabState } from './model.js'
import { DEFAULT_ROUTING_POLICY } from './routingPolicy.js'
import { RELAYED_QUOTA, reviewCapacityNotice } from './reviewCapacity.js'
-import { reviewRefusal } from './rules.js'
-// Overnight 2026-10-30, 12 pull requests waited hours for a review: every Codex Reviewer was out of weekly quota, a Claude
-// Reviewer may not check a Claude build, and nobody was told until people noticed in the morning (Tony: "don't let the
-// workflow get stuck"). The notice says so in the project chat, once per cause, tagging who can fix it.
+// Overnight 2026-10-30, 12 pull requests waited hours for a review while every Codex Reviewer was out of weekly quota, and
+// nobody was told until people noticed in the morning (Tony: "don't let the workflow get stuck"). Since Ken's ruling the same
+// day any strong engine reviews any build, so the notice speaks only when no Reviewer of any engine can start: once per cause,
+// in the project chat, tagging who can fix it.
const NOW = 10_000_000
const HOUR = 3_600_000
type Window = { name: string; usedPercent: number }
-function machine(id: string, name: string, contributorId: string, codex: { windows?: Window[]; known?: boolean; signedIn?: boolean } | null,
+/** An engine's reading on a machine: its windows, `unknown` when it cannot be read, or signed out. */
+type Reading = Window[] | 'unknown' | { signedOut: Window[] }
+function machine(id: string, name: string, contributorId: string, engines: { claude?: Reading; codex?: Reading },
extra: Partial<ContributedMachine> = {}): ContributedMachine {
- return { machineId: id, name, contributorId, membershipGeneration: 'g', generation: 'g1', cwd: '/swarm', scope: 'swarm', engines: codex ? ['claude', 'codex'] : ['claude'],
+ const names = (['claude', 'codex'] as const).filter(e => engines[e] !== undefined)
+ const windows = (r: Reading) => (Array.isArray(r) ? r : r === 'unknown' ? [] : r.signedOut).map(w => ({ ...w, resetsAt: null as string | null }))
+ return { machineId: id, name, contributorId, membershipGeneration: 'g', generation: 'g1', cwd: '/swarm', scope: 'swarm', engines: names,
maxAgents: 4, paused: false, ...extra,
observation: { generation: 'g1', receivedAt: NOW - 1000, sessionKind: 'computer',
resources: { cpuPercent: null, memoryTotalBytes: null, memoryUsedBytes: null, diskFreeBytes: null, diskTotalBytes: null, projectDiskFreeBytes: null,
deviceType: null, chip: null, os: null, gpuPercent: null },
tools: {}, runningHarnessIds: [], stoppedHarnessIds: [],
- readiness: { engines: [{ engine: 'claude', installed: true, signedIn: true }, ...codex ? [{ engine: 'codex', installed: true, signedIn: codex.signedIn ?? true }] : []] },
- quotas: codex ? [{ engine: 'codex', known: codex.known ?? true, windows: (codex.windows ?? []).map(w => ({ ...w, resetsAt: null })) }] : [],
+ readiness: { engines: names.map(e => ({ engine: e, installed: true, signedIn: !(typeof engines[e] === 'object' && !Array.isArray(engines[e])) })) },
+ quotas: names.map(e => ({ engine: e, known: engines[e] !== 'unknown', windows: windows(engines[e]!) })),
...extra.observation } as ContributedMachine['observation'] }
}
const out = [{ name: 'weekly', usedPercent: 100 }]
const low = [{ name: 'weekly', usedPercent: 85 }]
const plenty = [{ name: '5-hour', usedPercent: 10 }, { name: 'weekly', usedPercent: 15 }]
+const both = (w: Reading) => ({ claude: w, codex: w })
/** A Swarm whose project has a build group [built] on [engine] and machines [machines]; Ken's project, Tony a teammate. */
function swarm(machines: ContributedMachine[], engine = 'claude', visibility: 'public' | 'private' = 'public') {
@@ -41,65 +46,61 @@ function swarm(machines: ContributedMachine[], engine = 'claude', visibility: 'p
return { state, built, project: state.projects![0]! }
}
const anyMachine = () => true
-const notice = (state: SuperTabState, group: Conversation, mayRun: (machineId: string) => boolean = anyMachine, now = NOW) =>
- reviewCapacityNotice(state, group, DEFAULT_ROUTING_POLICY, target => mayRun(target.machineId), now)
+const notice = (state: SuperTabState, group: Conversation, mayRun: (machineId: string, engine: string) => boolean = anyMachine, now = NOW) =>
+ reviewCapacityNotice(state, group, DEFAULT_ROUTING_POLICY, target => mayRun(target.machineId, target.engine), now)
+const FIXES = 'More Claude Code or Codex quota, an engine signed in on another machine, a paused machine resumed, or another machine in the Swarm'
describe('the notice that new Reviewers cannot start', () => {
- it('says once in the project chat that no Codex Reviewer can start, naming each machine and tagging its owner', () => {
- const { state, built, project } = swarm([machine('studio', 'Mac Studio', 'ken', { windows: out }), machine('huy-mac', 'MacBookPro2021', 'huy', { windows: plenty, signedIn: false }),
- machine('tony-mac', 'MacBook Pro 19', 'tony', { windows: [{ name: '5-hour', usedPercent: 100 }, { name: 'weekly', usedPercent: 40 }] })])
+ it('says nothing for a Claude build while Codex is out everywhere but Claude can review (Ken, 2026-10-30)', () => {
+ // The morning of 10-30: every Codex out of weekly quota, Claude fine. Claude reviews the Claude build now, so nobody is told.
+ const { state, built, project } = swarm([machine('studio', 'Mac Studio', 'ken', { claude: plenty, codex: out }),
+ machine('tony-mac', 'MacBook Pro 19', 'tony', { claude: plenty, codex: out })])
+ expect(notice(state, built)).toBeNull()
+ expect(project.reviewCapacity).toBeUndefined()
+ })
+
+ it('says once in the project chat that no Reviewer of any engine can start, naming each machine and tagging its owner', () => {
+ const { state, built, project } = swarm([machine('studio', 'Mac Studio', 'ken', both(out)), machine('huy-mac', 'MacBookPro2021', 'huy', both({ signedOut: plenty })),
+ machine('tony-mac', 'MacBook Pro 19', 'tony', { claude: out, codex: [{ name: '5-hour', usedPercent: 100 }, { name: 'weekly', usedPercent: 40 }] })])
const first = notice(state, built)
- expect(first).toMatchObject({ conversationId: project.leadConversationId, mentions: ['ken', 'huy', 'tony'], source: { kind: 'review-capacity', engine: 'codex', cause: 'out' } })
- // Claude Opus can still start on these machines, so reviews fall back to it (rules.ts judgeReview).
- expect(first!.text).toBe('Reviews of Claude Code builds fall back to Claude Code at its top tier: Codex is unavailable on every machine this project may use '
- + '(Mac Studio: out of quota; MacBookPro2021: signed out; MacBook Pro 19: out of quota). More Codex quota, Codex signed in on another machine, '
- + 'a paused machine resumed, or another machine in the Swarm would bring back reviews on another engine. @ken15 @huy @tony can fix it.')
+ expect(first).toMatchObject({ conversationId: project.leadConversationId, mentions: ['ken', 'huy', 'tony'], source: { kind: 'review-capacity', engine: 'any', cause: 'out' } })
+ expect(first!.text).toBe('Reviews cannot start a new Reviewer: no machine this project may use can run Claude Code or Codex now '
+ + `(Mac Studio: out of quota; MacBookPro2021: signed out; MacBook Pro 19: out of quota). ${FIXES} would unblock them. @ken15 @huy @tony can fix it.`)
// A person's own numbers are never shown to the others.
expect(first!.text).not.toMatch(/\d+ ?%/)
expect(notice(state, built, anyMachine, NOW + HOUR)).toBeNull()
})
- it('says reviews cannot start when no top-tier Reviewer of the Builder\'s own engine can start either', () => {
- const studio = machine('studio', 'Mac Studio', 'ken', { windows: out })
- studio.observation!.readiness!.engines![0]!.signedIn = false
- const { state, built } = swarm([studio])
- expect(notice(state, built)!.text).toBe('Reviews of Claude Code builds cannot start a new Reviewer: Codex is unavailable on every machine this project may use '
- + '(Mac Studio: out of quota). More Codex quota, Codex signed in on another machine, a paused machine resumed, or another machine in the Swarm would unblock them. @ken15 can fix it.')
- })
-
- it('says reviews fall back only when the server would let them: not while it counts a Codex agent on a host outside the contributions', () => {
- // Re-review of #2275: the notice said "fall back to Claude Code" while rules.ts refused it.
- const { state, built } = swarm([machine('studio', 'Mac Studio', 'ken', { windows: out })])
- state.agents.push({ id: 'codex-elsewhere', name: 'Codex', machineId: 'elsewhere', harnessId: 'hx', contributorId: 'ken',
- configuration: { engine: 'codex', model: 'default', effort: 'high' } } as never)
- const reviewer = { machineId: 'studio', engine: 'claude', model: 'claude-opus-4-7', effort: 'high' }
- expect(reviewRefusal(state, built.id, reviewer, DEFAULT_ROUTING_POLICY, anyMachine, NOW)).not.toBeNull()
- expect(notice(state, built)!.text).toMatch(/^Reviews of Claude Code builds cannot start a new Reviewer: /)
+ it('takes each machine at its best engine: one engine usable anywhere is enough', () => {
+ const { state, built } = swarm([machine('studio', 'Mac Studio', 'ken', { claude: out, codex: plenty })])
+ expect(notice(state, built)).toBeNull()
+ const codexOnly = swarm([machine('studio', 'Mac Studio', 'ken', { codex: plenty }), machine('tony-mac', 'MacBook Pro 19', 'tony', { claude: out })])
+ expect(notice(codexOnly.state, codexOnly.built)).toBeNull()
})
it('counts a paused machine as unable to start a Reviewer, as the route does', () => {
- const { state, built } = swarm([machine('studio', 'Mac Studio', 'ken', { windows: plenty }, { paused: true })])
+ const { state, built } = swarm([machine('studio', 'Mac Studio', 'ken', both(plenty), { paused: true })])
expect(notice(state, built)!.text).toContain('(Mac Studio: paused)')
})
- it('warns once when every Codex machine is close to running out of weekly quota, and again when it runs out', () => {
- const { state, built } = swarm([machine('studio', 'Mac Studio', 'ken', { windows: low }), machine('tony-mac', 'MacBook Pro 19', 'tony', { windows: out })])
+ it('warns once when every machine is close to running out of weekly quota, and again when it runs out', () => {
+ const { state, built } = swarm([machine('studio', 'Mac Studio', 'ken', { claude: low, codex: out }), machine('tony-mac', 'MacBook Pro 19', 'tony', both(out))])
const warned = notice(state, built)
- expect(warned).toMatchObject({ mentions: ['ken', 'tony'], source: { kind: 'review-capacity', engine: 'codex', cause: 'low' } })
- expect(warned!.text).toBe('Codex quota for reviewing Claude Code builds is close to running out on every machine this project may use '
- + '(Mac Studio: close to running out; MacBook Pro 19: out of quota). More Codex quota, Codex signed in on another machine, '
- + 'a paused machine resumed, or another machine in the Swarm would keep reviews going. @ken15 @tony can fix it.')
+ expect(warned).toMatchObject({ mentions: ['ken', 'tony'], source: { kind: 'review-capacity', engine: 'any', cause: 'low' } })
+ expect(warned!.text).toBe('Quota for new Reviewers is close to running out on every machine this project may use '
+ + `(Mac Studio: close to running out; MacBook Pro 19: out of quota). ${FIXES} would keep reviews going. @ken15 @tony can fix it.`)
expect(notice(state, built)).toBeNull()
state.machines![0]!.observation!.quotas[0]!.windows[0]!.usedPercent = 100
expect(notice(state, built)).toMatchObject({ source: { cause: 'out' } })
expect(notice(state, built)).toBeNull()
})
- it('says nothing while one Codex machine has quota, and once it recovers, says it again the next time it runs out', () => {
- const { state, built, project } = swarm([machine('studio', 'Mac Studio', 'ken', { windows: out }), machine('tony-mac', 'MacBook Pro 19', 'tony', { windows: plenty })])
+ it('says nothing while one machine has quota, and once it recovers, says it again the next time it runs out', () => {
+ const { state, built, project } = swarm([machine('studio', 'Mac Studio', 'ken', both(out)), machine('tony-mac', 'MacBook Pro 19', 'tony', { codex: plenty })])
expect(notice(state, built)).toBeNull()
state.machines![1]!.observation!.quotas[0]!.windows = out.map(w => ({ ...w, resetsAt: null }))
expect(notice(state, built)).toMatchObject({ source: { cause: 'out' } })
+ expect(project.reviewCapacity).toEqual({ any: 'out' })
state.machines![0]!.observation!.quotas[0]!.windows = plenty.map(w => ({ ...w, resetsAt: null }))
expect(notice(state, built)).toBeNull()
expect(project.reviewCapacity).toBeUndefined()
@@ -107,45 +108,57 @@ describe('the notice that new Reviewers cannot start', () => {
expect(notice(state, built)).toMatchObject({ source: { cause: 'out' } })
})
- it('counts a quota it cannot read as usable, as starts do, and says nothing with no Codex machine at all (Claude reviews at its top tier)', () => {
- const unread = swarm([machine('studio', 'Mac Studio', 'ken', { windows: out }), machine('x', 'Unread', 'tony', { known: false })])
+ it('writes the project only when what it said changes, and drops a marker kept per engine before 2026-10-30', () => {
+ const { state, built, project } = swarm([machine('studio', 'Mac Studio', 'ken', both(out))])
+ project.reviewCapacity = { codex: 'out' }
+ // An old server's marker says nothing of this rule, so the shortage is told once more, and the old key goes.
+ expect(notice(state, built)).toMatchObject({ source: { cause: 'out' } })
+ expect(project.reviewCapacity).toEqual({ any: 'out' })
+ const kept = project.reviewCapacity
+ expect(notice(state, built)).toBeNull()
+ expect(project.reviewCapacity).toBe(kept)
+ })
+
+ it('counts a quota it cannot read as usable, as starts do, and says nothing with no machine for Reviewers at all', () => {
+ const unread = swarm([machine('studio', 'Mac Studio', 'ken', both(out)), machine('x', 'Unread', 'tony', { codex: 'unknown' })])
expect(notice(unread.state, unread.built)).toBeNull()
- const { state, built } = swarm([machine('studio', 'Mac Studio', 'ken', null)])
+ const { state, built } = swarm([])
expect(notice(state, built)).toBeNull()
})
it('reads a Team account\'s quota from its Mac when the account spends that subscription through the relay', () => {
- const mac = machine('tony-mac', 'MacBook Pro 19', 'tony', { windows: out })
- const team = machine('tony-team', 'MacBook Pro 19', 'tony', { known: false }, { hostMachineId: 'tony-mac' })
+ const mac = machine('tony-mac', 'MacBook Pro 19', 'tony', { codex: out })
+ const team = machine('tony-team', 'MacBook Pro 19', 'tony', { codex: 'unknown' }, { hostMachineId: 'tony-mac' })
team.observation!.quotaReasons = { codex: RELAYED_QUOTA }
- const { state, built } = swarm([machine('studio', 'Mac Studio', 'ken', { windows: out }), mac, team])
+ const { state, built } = swarm([machine('studio', 'Mac Studio', 'ken', both(out)), mac, team])
// The Mac is named once: the account is that Mac.
expect(notice(state, built)!.text).toContain('(Mac Studio: out of quota; MacBook Pro 19: out of quota)')
// Unknown for another reason, the account stays usable, as a start there is.
team.observation!.quotaReasons = { codex: 'The allowance reader on this machine did not answer.' }
- const again = swarm([machine('studio', 'Mac Studio', 'ken', { windows: out }), mac, team])
+ const again = swarm([machine('studio', 'Mac Studio', 'ken', both(out)), mac, team])
expect(notice(again.state, again.built)).toBeNull()
})
- it('says nothing while a used-up window resets inside the start window, as the review rule waits for it (rules.ts)', () => {
- const { state, built } = swarm([machine('studio', 'Mac Studio', 'ken', { windows: out })])
+ it('says nothing while a used-up window resets inside the start window', () => {
+ const { state, built } = swarm([machine('studio', 'Mac Studio', 'ken', { codex: out })])
state.machines![0]!.observation!.quotas[0]!.windows[0]!.resetsAt = new Date(NOW + 10 * 60_000).toISOString()
expect(notice(state, built)).toBeNull()
state.machines![0]!.observation!.quotas[0]!.windows[0]!.resetsAt = new Date(NOW + 3 * 24 * HOUR).toISOString()
expect(notice(state, built)).toMatchObject({ source: { cause: 'out' } })
})
- it('counts an offline machine as unavailable, and leaves out machines this project may not use', () => {
- const offline = machine('tony-mac', 'MacBook Pro 19', 'tony', { windows: plenty })
+ it('counts an offline machine as unavailable, and leaves out machines and engines this project may not use', () => {
+ const offline = machine('tony-mac', 'MacBook Pro 19', 'tony', both(plenty))
offline.observation!.receivedAt = NOW - HOUR
- const { state, built } = swarm([machine('studio', 'Mac Studio', 'ken', { windows: out }), offline, machine('ruled', 'Ruled out', 'huy', { windows: plenty })])
- const said = notice(state, built, id => id !== 'ruled')
+ const { state, built } = swarm([machine('studio', 'Mac Studio', 'ken', { claude: out, codex: plenty }), offline, machine('ruled', 'Ruled out', 'huy', both(plenty))])
+ // The owner's rules leave out Codex on the Studio and the third machine altogether.
+ const said = notice(state, built, (id, engine) => id !== 'ruled' && !(id === 'studio' && engine === 'codex'))
expect(said!.text).toContain('(Mac Studio: out of quota; MacBook Pro 19: offline)')
expect(said!.mentions).toEqual(['ken', 'tony'])
})
it('tags only people who read the project, and names no machine of someone who does not', () => {
- const { state, built } = swarm([machine('studio', 'Mac Studio', 'ken', { windows: out }), machine('tony-mac', 'Tony private Mac', 'tony', { windows: out })], 'claude', 'private')
+ const { state, built } = swarm([machine('studio', 'Mac Studio', 'ken', both(out)), machine('tony-mac', 'Tony private Mac', 'tony', both(out))], 'claude', 'private')
const said = notice(state, built)
expect(said!.mentions).toEqual(['ken'])
expect(said!.text).not.toContain('tony')
@@ -154,25 +167,20 @@ describe('the notice that new Reviewers cannot start', () => {
})
it('neither counts nor names a Buddy-only machine, which is its person\'s alone', () => {
- const buddy = machine('buddy', 'Huy private laptop', 'huy', { windows: plenty }, { buddyOnly: true })
- const { state, built } = swarm([machine('studio', 'Mac Studio', 'ken', { windows: out }), buddy])
+ const buddy = machine('buddy', 'Huy private laptop', 'huy', both(plenty), { buddyOnly: true })
+ const { state, built } = swarm([machine('studio', 'Mac Studio', 'ken', both(out)), buddy])
const said = notice(state, built)
expect(said).toMatchObject({ mentions: ['ken'], source: { cause: 'out' } })
expect(said!.text).not.toContain('Huy private laptop')
})
- it('says nothing for a build on a grid model, which any strong engine reviews, or a group with no build', () => {
- const { state, built } = swarm([machine('studio', 'Mac Studio', 'ken', { windows: out })])
- const grid = swarm([machine('studio', 'Mac Studio', 'ken', { windows: out })])
- grid.state.agents.push({ id: 'builder', gridModel: 'moonshotai/kimi-k3' } as never)
- expect(notice(grid.state, grid.built)).toBeNull()
+ it('judges a Codex build and a grid build the same way, and says nothing for a group with no build', () => {
+ const codex = swarm([machine('studio', 'Mac Studio', 'ken', { claude: plenty, codex: out })], 'codex')
+ expect(notice(codex.state, codex.built)).toBeNull()
+ const grid = swarm([machine('studio', 'Mac Studio', 'ken', both(out))])
+ grid.state.agents.push({ id: 'builder', name: 'Builder', gridModel: 'moonshotai/kimi-k3' } as never)
+ expect(notice(grid.state, grid.built)).toMatchObject({ source: { cause: 'out' } })
+ const { state, built } = swarm([machine('studio', 'Mac Studio', 'ken', both(out))])
expect(notice(state, { ...built, assignment: null })).toBeNull()
})
-
- it('reviews a Codex build with Claude, the same way', () => {
- const { state, built } = swarm([machine('studio', 'Mac Studio', 'ken', { windows: plenty })], 'codex')
- state.machines![0]!.observation!.quotas = [{ engine: 'claude', known: true, windows: [{ name: 'weekly', usedPercent: 100, resetsAt: null }] }]
- expect(notice(state, built)).toMatchObject({ source: { engine: 'claude', cause: 'out' } })
- expect(notice(state, built)).toBeNull()
- })
})
diff --git a/backend/src/superTabs/reviewCapacity.ts b/backend/src/superTabs/reviewCapacity.ts
index 620d67159..704dbe653 100644
--- a/backend/src/superTabs/reviewCapacity.ts
+++ b/backend/src/superTabs/reviewCapacity.ts
@@ -1,68 +1,62 @@
/** Whether new Reviewers can still start for a project's builds, said once in its chat when they cannot or soon will not.
- * Overnight 2026-10-30, 12 pull requests waited hours for a review: every Codex Reviewer was out of weekly quota, a Claude
- * Reviewer may not check a Claude build (rules.ts judgeReview), and nobody was told until people noticed in the morning
- * (Tony: "don't let the workflow get stuck"). Checked when an Engineer hands work over for review (commands.ts work.status). */
+ * Overnight 2026-10-30, 12 pull requests waited hours for a review while every Codex Reviewer was out of weekly quota, and
+ * nobody was told until people noticed in the morning (Tony: "don't let the workflow get stuck"). Any engine reviews any
+ * build now (Ken, 2026-10-30; rules.ts reviewRefusal), so the notice speaks only when no strong Reviewer of any engine can
+ * start. Checked when an Engineer hands work over for review (commands.ts work.status). */
import type { Conversation, SuperTabState } from './model.js'
import { canReadProject, groupProject, projectRules } from './projects.js'
-import { canStart, STANDING, standing, type Standing } from './reviewSeats.js'
-import { liftEffort, otherFamilyReviews, type MayRun } from './rules.js'
+import { STANDING, standing, type Standing } from './reviewSeats.js'
+import { liftEffort, type MayRun } from './rules.js'
import type { RoutingPolicy } from './routingPolicy.js'
import { usernameOf } from './usernames.js'
export { RELAYED_QUOTA } from './reviewSeats.js'
const ENGINES = ['claude', 'codex'] as const
-const NAME: Record<string, string> = { claude: 'Claude Code', codex: 'Codex' }
+/** The key the project keeps what it last said under. Before 2026-10-30 it kept one per engine (`claude`, `codex`); those
+ * are dropped the next time it writes. */
+const ANY = 'any'
export type Cause = 'out' | 'low'
export interface ReviewCapacityNotice { conversationId: string; text: string; mentions: string[]; source: { kind: 'review-capacity'; engine: string; cause: Cause } }
-/** Each machine the project may start a Reviewer of [engine] on, on a policy row of [quality] or more, as one: a Mac and its
- * Harness Team account are one machine (machines.ts teamStartRequest), standing as the better of the two. */
-function seats(state: SuperTabState, group: Conversation, engine: string, policy: RoutingPolicy, mayRun: MayRun, now: number, quality = 2) {
+/** Each machine the project may start a strong Reviewer on, of either engine, on a policy row of quality 2 or more, as one:
+ * a Mac and its Harness Team account are one machine (machines.ts teamStartRequest), standing as the best of its engines
+ * and accounts. */
+function seats(state: SuperTabState, group: Conversation, policy: RoutingPolicy, mayRun: MayRun, now: number) {
const rules = projectRules(state, groupProject(state, group).id)
- const rows = policy.models.filter(row => row.enabled && row.engine === engine && row.quality >= quality)
const byMac = new Map<string, { name: string; contributorId: string; standing: Standing }>()
for (const pool of state.machines ?? []) {
- if (pool.buddyOnly || pool.removal || !pool.engines.includes(engine)) continue
- if (!rows.some(row => mayRun({ machineId: pool.machineId, engine, model: row.model, effort: liftEffort(rules, engine, row.effort) }, pool.contributorId))) continue
- const key = pool.hostMachineId ?? pool.machineId, here = standing(state, pool, engine, now), seen = byMac.get(key)
- if (!seen) byMac.set(key, { name: pool.name, contributorId: pool.contributorId, standing: here })
- else if (STANDING.indexOf(here) < STANDING.indexOf(seen.standing)) seen.standing = here
+ if (pool.buddyOnly || pool.removal) continue
+ for (const engine of ENGINES) {
+ if (!pool.engines.includes(engine)) continue
+ const rows = policy.models.filter(row => row.enabled && row.engine === engine && row.quality >= 2)
+ if (!rows.some(row => mayRun({ machineId: pool.machineId, engine, model: row.model, effort: liftEffort(rules, engine, row.effort) }, pool.contributorId))) continue
+ const key = pool.hostMachineId ?? pool.machineId, here = standing(state, pool, engine, now), seen = byMac.get(key)
+ if (!seen) byMac.set(key, { name: pool.name, contributorId: pool.contributorId, standing: here })
+ else if (STANDING.indexOf(here) < STANDING.indexOf(seen.standing)) seen.standing = here
+ }
}
return [...byMac.values()]
}
/**
- * The notice for [group]'s review when no new Reviewer on another engine than its Builder's can start on any machine the
- * project may use (cause `out`), or when each is close to running out of weekly quota (`low`); null otherwise. Said once
- * per cause and engine: the project keeps which it last said, and forgets it once a machine is usable again. With no
- * machine of the other engine at all the Builder's own engine reviews at its top tier (rules.ts), so nothing is said; nor
- * for a build on a grid model, which either engine reviews. While a top-tier Reviewer of the Builder's own engine can start,
- * reviews fall back to it (rules.ts judgeReview), and the notice says so rather than that they cannot start. Tags the
- * owners of those machines who read the project and have a username.
+ * The notice for [group]'s review when no new strong Reviewer of any engine can start on any machine the project may use
+ * (cause `out`), or when each one that could is close to running out of weekly quota (`low`); null otherwise. Said once
+ * per cause: the project keeps which it last said, and forgets it once a machine is usable again. With no machine at all
+ * that may run a Reviewer nothing is said, as before: a Swarm whose agents run on hosts outside the contributions reports
+ * no readings to judge. Tags the owners of those machines who read the project and have a username.
*/
export function reviewCapacityNotice(state: SuperTabState, group: Conversation, policy: RoutingPolicy, mayRun: MayRun, now: number): ReviewCapacityNotice | null {
- const assignment = group.assignment
- if (!assignment) return null
- const worker = state.agents.find(a => a.id === assignment.agentId)
- if (worker?.gridModel) return null
- const built = worker?.configuration.engine ?? assignment.configuration.engine
- const engine = ENGINES.find(e => e !== built)
- if (!engine) return null
+ if (!group.assignment) return null
const project = groupProject(state, group)
- const places = seats(state, group, engine, policy, mayRun, now)
- const said = project.reviewCapacity?.[engine]
- const forget = () => {
- if (!said) return
- const { [engine]: _gone, ...others } = project.reviewCapacity!
- if (Object.keys(others).length) project.reviewCapacity = others
- else delete project.reviewCapacity
- }
- if (!places.length || places.some(p => p.standing === 'usable')) { forget(); return null }
+ const places = seats(state, group, policy, mayRun, now)
+ const said = project.reviewCapacity?.[ANY]
+ // Written only when it changes, so an ordinary Ready for review writes nothing to the project.
+ if (!places.length || places.some(p => p.standing === 'usable')) { if (project.reviewCapacity) delete project.reviewCapacity; return null }
const cause: Cause = places.some(p => p.standing === 'close to running out') ? 'low' : 'out'
+ if (said !== cause || Object.keys(project.reviewCapacity ?? {}).length !== 1) project.reviewCapacity = { [ANY]: cause }
// Out after low is news; low after out is not, but is kept so running out again is.
- if (said === cause || (said === 'out' && cause === 'low')) { project.reviewCapacity = { ...project.reviewCapacity, [engine]: cause }; return null }
- project.reviewCapacity = { ...project.reviewCapacity, [engine]: cause }
+ if (said === cause || (said === 'out' && cause === 'low')) return null
const person = (id: string) => state.people.find(p => p.id === id)
const reads = (id: string) => { const p = person(id); return !!p && canReadProject(state, { kind: 'person', userId: p.id, email: p.email }, project) }
@@ -71,16 +65,10 @@ export function reviewCapacityNotice(state: SuperTabState, group: Conversation,
// A tag is a username; someone without one is not tagged, never named by their email (review of #2275).
const mentions = [...new Set(places.map(p => p.contributorId))].filter(id => reads(id) && usernameOf(state, id))
const who = mentions.map(id => `@${usernameOf(state, id)}`).join(' ')
- const fixes = `More ${NAME[engine]} quota, ${NAME[engine]} signed in on another machine, a paused machine resumed, or another machine in the Swarm`
- // Reviews fall back only as the server's own judgement lets them (rules.ts judgeReview): it also counts an agent of the
- // other engine on a host outside the contributions, which the machines above leave out (re-review of #2275).
- const fallback = cause === 'out' && !otherFamilyReviews(state, { engine: built }, policy, mayRun, now)
- && seats(state, group, built, policy, mayRun, now, 3).some(p => canStart(p.standing))
+ const fixes = 'More Claude Code or Codex quota, an engine signed in on another machine, a paused machine resumed, or another machine in the Swarm'
const text = (cause === 'low'
- ? `${NAME[engine]} quota for reviewing ${NAME[built]} builds is close to running out on every machine this project may use (${list}). ${fixes} would keep reviews going.`
- : fallback
- ? `Reviews of ${NAME[built]} builds fall back to ${NAME[built]} at its top tier: ${NAME[engine]} is unavailable on every machine this project may use (${list}). ${fixes} would bring back reviews on another engine.`
- : `Reviews of ${NAME[built]} builds cannot start a new Reviewer: ${NAME[engine]} is unavailable on every machine this project may use (${list}). ${fixes} would unblock them.`)
+ ? `Quota for new Reviewers is close to running out on every machine this project may use (${list}). ${fixes} would keep reviews going.`
+ : `Reviews cannot start a new Reviewer: no machine this project may use can run Claude Code or Codex now (${list}). ${fixes} would unblock them.`)
+ (who ? ` ${who} can fix it.` : '')
- return { conversationId: project.leadConversationId, text, mentions, source: { kind: 'review-capacity', engine, cause } }
+ return { conversationId: project.leadConversationId, text, mentions, source: { kind: 'review-capacity', engine: ANY, cause } }
}
diff --git a/backend/src/superTabs/reviewRules.test.ts b/backend/src/superTabs/reviewRules.test.ts
index bc530cea9..0ad3b738f 100644
--- a/backend/src/superTabs/reviewRules.test.ts
+++ b/backend/src/superTabs/reviewRules.test.ts
@@ -1,6 +1,6 @@
import { describe, it, expect } from 'vitest'
import { DEFAULT_ROUTING_POLICY as policy } from './routingPolicy.js'
-import { agentTarget, broken, reviewRefusal, SAME_ENGINE, sameEngineReview, startTarget, targetQuality } from './rules.js'
+import { agentTarget, broken, reviewRefusal, startTarget, targetQuality } from './rules.js'
import { effectivePolicy } from './routingPolicy.js'
import { cheapAttempt } from './stepUp.js'
import { recordRun } from './leaderboard/record.js'
@@ -35,60 +35,48 @@ describe('reviews and step-ups by what each attempt runs on', () => {
})
})
-// 2026-10-30: every Codex Reviewer was out of weekly quota for days, yet a Claude build's top-tier Claude review was refused
-// because Codex machines existed, and reviews waited all morning (Tony). Another engine counts only where a Reviewer of it
-// could start within the start window: on a machine the review may use, online, with quota now or once a window resets
-// inside the window.
-describe('a review on its Builder\'s own engine when no Reviewer of another engine could start soon', () => {
- const NOW = Date.parse('2026-10-30T09:00:00Z'), MIN = 60_000, DAY = 86_400_000
+// Ken, 2026-10-30: drop the rule that a review runs on another engine than its Builder's. Nearly every Builder is Claude, so
+// reviews went to Codex and waited all morning while Codex was out of quota. A Reviewer is a session of its own with fresh
+// context, so a strong model is what counts: any engine reviews any build, at once, with no note.
+describe('a review on any strong engine', () => {
+ const NOW = Date.parse('2026-10-30T09:00:00Z')
const opus = { id: 'reviewer', machineId: 'allowed', harnessId: 'hr', contributorId: 'owner', configuration: { engine: 'claude', model: 'opus', effort: 'high' } }
- const codexBox = (resetsIn: number | null, usedPercent = 100, extra: Record<string, unknown> = {}) => ({ machineId: 'codex-box', contributorId: 'tony', engines: ['codex'],
+ // A Codex machine with quota now: before, it made a Claude build's Claude review wait for it.
+ const codexBox = { machineId: 'codex-box', contributorId: 'tony', engines: ['codex'],
observation: { receivedAt: NOW - 1000, readiness: { engines: [{ engine: 'codex', installed: true, signedIn: true }] },
- quotas: [{ engine: 'codex', known: true, windows: [{ name: 'weekly', usedPercent, resetsAt: resetsIn === null ? null : new Date(NOW + resetsIn).toISOString() }] }] }, ...extra })
- const judge = (machines: unknown[], rules: unknown[] = []) => {
- const state = stateOf(opus)
- Object.assign(state, { machines, rules })
- const target = agentTarget(state, opus as any)
- return { refusal: reviewRefusal(state, 'work', target, policy, undefined, NOW), note: sameEngineReview(state, 'work', target, policy, undefined, NOW) }
- }
+ quotas: [{ engine: 'codex', known: true, windows: [{ name: 'weekly', usedPercent: 10, resetsAt: null }] }] } }
- it('lets Claude Opus review a Claude build while every Codex machine is out of quota for days, and says why', () => {
- expect(judge([codexBox(3 * DAY)])).toEqual({ refusal: null, note: expect.stringMatching(new RegExp(`^${SAME_ENGINE}`)) })
- expect(SAME_ENGINE).toBe('same-engine review: no Reviewer of another engine has quota')
- // Nor does an exhausted window that never says when it resets count.
- expect(judge([codexBox(null)]).refusal).toBeNull()
+ it('lets Claude Opus review a Claude build at once while a Codex Reviewer could start', () => {
+ const state = stateOf(opus)
+ state.machines = [codexBox]
+ expect(reviewRefusal(state, 'work', agentTarget(state, opus as any), policy)).toBeNull()
+ // A new Claude Reviewer the route would start, too.
+ expect(reviewRefusal(state, 'work', startTarget({ machineId: 'allowed', engine: 'claude', model: 'opus', effort: 'high' }), policy)).toBeNull()
})
- it('still refuses Claude while Codex resets inside the start window, or has quota now', () => {
- expect(judge([codexBox(10 * MIN)])).toEqual({ refusal: 'A review runs on another engine than the reviewed Builder\'s, Claude.', note: null })
- expect(judge([codexBox(3 * DAY, 40)]).refusal).toBe('A review runs on another engine than the reviewed Builder\'s, Claude.')
- // A quota it cannot read stays usable, as a start there is.
- const unread = codexBox(3 * DAY); unread.observation.quotas[0]!.known = false
- expect(judge([unread]).refusal).not.toBeNull()
+ it('lets Codex review a Claude build, and Claude a Codex build', () => {
+ const codex = { id: 'reviewer', machineId: 'allowed', harnessId: 'hr', configuration: { engine: 'codex', model: 'default', effort: 'high' } }
+ expect(reviewRefusal(stateOf(codex), 'work', agentTarget(stateOf(codex), codex as any), policy)).toBeNull()
+ // A Codex Builder, without touching the shared Claude one.
+ const state = stateOf(opus), codexBuild = { engine: 'codex', model: 'default', effort: 'high' }
+ state.agents[0] = { ...builder, configuration: codexBuild }
+ state.conversations[0].assignment = { agentId: 'builder', configuration: codexBuild }
+ expect(reviewRefusal(state, 'work', agentTarget(state, opus as any), policy)).toBeNull()
})
- it('lets Claude review when Codex runs only on a machine the owner left out, or one that is offline, signed out or suspended', () => {
- const owners = [{ projectId: 'p', rule: { kind: 'machines', machineIds: ['allowed'] }, text: 'Only the approved machine.' }]
- expect(judge([codexBox(3 * DAY, 40)], owners)).toEqual({ refusal: null, note: expect.stringMatching(new RegExp(`^${SAME_ENGINE}`)) })
- const offline = codexBox(3 * DAY, 40); offline.observation.receivedAt = NOW - 10 * MIN
- expect(judge([offline]).refusal).toBeNull()
- const signedOut = codexBox(3 * DAY, 40); signedOut.observation.readiness.engines[0]!.signedIn = false
- expect(judge([signedOut]).refusal).toBeNull()
- expect(judge([codexBox(3 * DAY, 40, { engineSuspensions: { codex: { at: NOW - MIN, fine: true } } })]).refusal).toBeNull()
- // Paused by its owner, as the CLI's route reads it (review of #2275: the route offered Claude, the server refused it).
- expect(judge([codexBox(3 * DAY, 40, { paused: true })])).toEqual({ refusal: null, note: expect.stringMatching(new RegExp(`^${SAME_ENGINE}`)) })
+ it('still never reviews on a grid model or one rated below 2, whatever the Builder ran', () => {
+ const state = stateOf(opus)
+ expect(reviewRefusal(state, 'work', { ...startTarget({ machineId: 'allowed', engine: 'claude', model: 'opus', effort: 'high' }), gridModel: 'kimi-k3' }, policy))
+ .toBe('A review never runs on a model served on the Swarm\'s grid.')
+ expect(reviewRefusal(state, 'work', startTarget({ machineId: 'allowed', engine: 'claude', model: 'haiku', effort: 'high' }), policy))
+ .toBe('A review needs a model of quality 2 or more, and Claude haiku is 1.')
})
- it('counts a Codex agent on a machine outside the contributions while it is up, and not once a usage limit holds it past the window', () => {
- const codexAgent = { id: 'codex', machineId: 'elsewhere', harnessId: 'hx', contributorId: 'owner', configuration: { engine: 'codex', model: 'default', effort: 'high' } } as any
+ it('never lets the agent that built the work review it', () => {
const state = stateOf(opus)
- state.agents.push(codexAgent)
- const target = agentTarget(state, opus as any)
- expect(reviewRefusal(state, 'work', target, policy, undefined, NOW)).not.toBeNull()
- codexAgent.limitedUntil = new Date(NOW + 5 * MIN).toISOString()
- expect(reviewRefusal(state, 'work', target, policy, undefined, NOW)).not.toBeNull()
- codexAgent.limitedUntil = new Date(NOW + 2 * DAY).toISOString()
- expect(reviewRefusal(state, 'work', target, policy, undefined, NOW)).toBeNull()
+ expect(reviewRefusal(state, 'work', agentTarget(state, state.agents[0]), policy)).toBe('A Reviewer never reviews work it built.')
+ // Another agent on the same engine, model and machine may.
+ expect(reviewRefusal(state, 'work', agentTarget(state, opus as any), policy)).toBeNull()
})
})
diff --git a/backend/src/superTabs/reviewSeats.ts b/backend/src/superTabs/reviewSeats.ts
index 86271fb23..959115a26 100644
--- a/backend/src/superTabs/reviewSeats.ts
+++ b/backend/src/superTabs/reviewSeats.ts
@@ -1,7 +1,6 @@
-/** Whether a new Reviewer of an engine could start on a contributed machine soon: what both the review rule (rules.ts
- * judgeReview) and the project chat's notice (reviewCapacity.ts) read. On 2026-10-30 every Codex Reviewer was out of weekly
- * quota for days, yet a Claude build's top-tier Claude review was refused because Codex machines existed; reviews waited
- * all morning (Tony). */
+/** Whether a new Reviewer of an engine could start on a contributed machine soon: what the project chat's notice
+ * (reviewCapacity.ts) reads. On 2026-10-30 every Codex Reviewer was out of weekly quota for days and reviews waited all
+ * morning (Tony); since Ken's ruling that day any strong engine reviews any build (rules.ts reviewRefusal). */
import { suspendedEngines } from './engineHealth.js'
import { MACHINE_FRESH_MS, type ContributedMachine } from './machines.js'
import type { SuperTabState } from './model.js'
@@ -12,7 +11,7 @@ import type { SuperTabState } from './model.js'
export const RELAYED_QUOTA = "This account runs on its owner's subscription; its allowance is read on the owner's machine."
/** How soon a Reviewer has to be able to start to count: a start still not running after this long is abandoned
* (store.ts ABANDONED_START_MS), so a review waiting longer than that is stuck. A window that resets inside it counts as
- * quota; one out for longer does not (cli superTabs/route.ts REVIEW_START_MS). */
+ * quota; one out for longer does not. */
export const REVIEW_START_MS = 15 * 60_000
/** Weekly allowance left, in percent, at or below which an engine is close to running out: the route keeps the policy's
* reserve (10) back, so about one more day of reviews is left. */
diff --git a/backend/src/superTabs/routeRecord.ts b/backend/src/superTabs/routeRecord.ts
index 4a824be06..2bb811416 100644
--- a/backend/src/superTabs/routeRecord.ts
+++ b/backend/src/superTabs/routeRecord.ts
@@ -58,7 +58,7 @@ export const routeRecordSchema = z.object({
context: z.object({ chars: z.number().int().min(0).max(30_000), missing: z.array(z.string().min(1).max(40)).max(10) }).strict().optional(),
/** The step up this attempt is (stepUp.ts), written by the server from its group, never taken from the route. */
stepUp: z.object({ attempt: z.number().int().min(2).max(3), reason: z.string().min(1).max(200) }).strict().optional(),
- /** Why a review runs on its Builder's own engine (rules.ts sameEngineReview), written by the server, never taken from the route. */
+ /** Why a review ran on its Builder's own engine, on records from before 2026-10-30, when another engine had to review when it could. Never written since, never taken from the route. */
sameEngine: z.string().min(1).max(300).optional(),
/** The job's kind from the fixed list (evidence/jobKind.ts), written by the server from its group, never taken from the route. */
jobKind: z.enum(JOB_KINDS).optional(),
diff --git a/backend/src/superTabs/rules.ts b/backend/src/superTabs/rules.ts
index 3cd14bdac..c9aabb3c9 100644
--- a/backend/src/superTabs/rules.ts
+++ b/backend/src/superTabs/rules.ts
@@ -5,8 +5,6 @@
import { z } from 'zod'
import type { Agent, SuperTabState, TaskRequirement } from './model.js'
import { gridQuality, type RoutingPolicy } from './routingPolicy.js'
-import { downSince } from './machines.js'
-import { canStart, REVIEW_START_MS, standing } from './reviewSeats.js'
const id = z.string().min(1).max(160).regex(/^[A-Za-z0-9_-]+$/)
const engine = z.enum(['claude', 'codex'])
@@ -45,7 +43,9 @@ export interface SwarmRule {
* start is checked when it is made. `gridModel`: a model served on the Swarm's grid that its engine drives. */
export interface RunTarget { machineId: string; engine: string; model: string | null; effort: string | null; devices?: string[]; gridModel?: string
/** An agent its start launched on the engine's own model: rated by the policy's `default` row (targetQuality). */
- launchedDefault?: true }
+ launchedDefault?: true
+ /** The agent itself, for a target that is one already here (agentTarget): a Reviewer never reviews its own build. */
+ agentId?: string }
const ENGINE: Record<string, string> = { claude: 'Claude', codex: 'Codex' }
/** `default` and `auto` say nothing about the effort, so they never meet a minimum. */
@@ -103,7 +103,7 @@ export function agentTarget(state: SuperTabState, worker: Agent): RunTarget {
const reported = worker.configuration.effort
const start = state.starts?.find(s => s.harnessId === worker.harnessId && s.request.machineId === worker.machineId)
const launched = start?.request.effort
- return { machineId: worker.machineId, engine: worker.configuration.engine, model: worker.configuration.model,
+ return { agentId: worker.id, machineId: worker.machineId, engine: worker.configuration.engine, model: worker.configuration.model,
effort: reported && reported !== 'auto' ? reported : launched ?? reported, devices: start?.request.requirements?.devices ?? [],
...(worker.gridModel ? { gridModel: worker.gridModel } : {}), ...(!worker.gridModel && (worker.launchedDefault || (start && !start.request.gridModel && (start.request.model ?? 'default') === 'default'))
? { launchedDefault: true as const } : {}) }
@@ -130,32 +130,9 @@ export const targetQuality = (policy: RoutingPolicy, t: RunTarget) => policyQual
export const agentQuality = (state: SuperTabState, policy: RoutingPolicy, worker: Agent): number =>
worker.gridModel ? gridQuality(policy, worker.gridModel, state.starts?.find(s => s.harnessId === worker.harnessId && s.request.machineId === worker.machineId)?.request.gridName ?? '')
: targetQuality(policy, agentTarget(state, worker))
-/** A model family: a grid model's own, else its engine's. */
-const familyOf = (t: { engine: string; gridModel?: string }) => t.gridModel ? `grid:${t.gridModel}` : t.engine
-
/** Whether a new Reviewer may run [target] for [contributorId]'s machine: its owner's rules, the task's machine and team
- * access, as the command judges them. Whether it could start soon is judged apart (reviewSeats.ts). */
+ * access, as the command judges them (reviewCapacity.ts). */
export type MayRun = (target: RunTarget, contributorId: string) => boolean
-/** Whether a strong Reviewer of another family than [builder]'s could start in this Swarm within REVIEW_START_MS: with an
- * engine other than the Builder's and an enabled policy row of quality 2 or more that [mayRun] allows there (review of
- * ee4ee6c9a: an engine the owner rules out blocked the fallback), on a contributed machine that is online, signed in, not
- * suspended and has that engine's quota now or once a window resets inside the start window, or on a machine an agent of
- * that engine runs on that is up and not held by a usage limit past it. Busy still counts: a Reviewer frees up. One out of
- * quota for days, offline or left out by the owner's machines does not (2026-10-30: reviews of Claude builds waited all
- * morning on Codex machines out of weekly quota). */
-export function otherFamilyReviews(state: SuperTabState, builder: { engine: string; gridModel?: string }, policy: RoutingPolicy, mayRun: MayRun, now: number): boolean {
- const pool = (machineId: string) => state.machines?.find(m => m.machineId === machineId)
- const soon = (agent: Agent) => !downSince(state, agent, now) && !(agent.limitedUntil && Date.parse(agent.limitedUntil) - now > REVIEW_START_MS)
- const places = [...state.agents.filter(a => !a.gridModel && !a.buddyOf && soon(a)).map(a => ({ machineId: a.machineId, contributorId: a.contributorId, engines: [a.configuration.engine] })),
- ...(state.machines ?? []).filter(m => !m.buddyOnly && !m.removal).map(m => ({ machineId: m.machineId, contributorId: m.contributorId, engines: m.engines }))]
- // A machine that reports its readings is judged by them; one that does not (an agent's host outside the contributions)
- // by its agent alone, whatever its quota, which nothing reports there. Stricter than the CLI's route on purpose: an
- // unknown counts as a Reviewer that could start, so the same-engine fallback is never taken on a guess.
- const starts = (machineId: string, engine: string) => { const m = pool(machineId); return !m || canStart(standing(state, m, engine, now)) }
- return places.some(place => place.engines.some(engine => familyOf({ engine }) !== familyOf(builder) && starts(place.machineId, engine)
- && policy.models.some(row => row.enabled && row.engine === engine && row.quality >= 2
- && mayRun({ machineId: place.machineId, engine, model: row.model, effort: liftEffort(state.rules, engine, row.effort) }, place.contributorId))))
-}
/** The effort a new agent on a row starts at: the row's, or the owner's minimum when the row leaves it to the engine (cli
* superTabs/route.ts liftEffort). */
export function liftEffort(rules: SwarmRule[] | undefined, engine: string, effort: string): string {
@@ -164,43 +141,17 @@ export function liftEffort(rules: SwarmRule[] | undefined, engine: string, effor
return least < 0 ? effort : EFFORTS[least]!
}
-/** How a review on its Builder's own engine starts its route line and its brief (Lead, 2026-10-30; cli superTabs/route.ts). */
-export const SAME_ENGINE = 'same-engine review: no Reviewer of another engine has quota'
-/** How [target] may review the work of group [reviewed] (Ken, 2026-10-29: a small model never reviews again): never on a model
- * served on the Swarm's grid or one the policy rates below 2, and on another model family than the reviewed Builder's while
- * a strong Reviewer of another family can run here. With none, the Builder's own engine at its top tier, noted (Lead,
- * 2026-10-29: a Swarm of one engine keeps its automatic reviews). */
-function judgeReview(state: SuperTabState, reviewed: string | undefined, target: RunTarget, policy: RoutingPolicy, mayRun: MayRun, now: number): { refusal: string } | { note: string } | null {
+/** Why [target] may not review the work of group [reviewed]; null when it may, or nothing is reviewed. Ken, 2026-10-29: a
+ * small model never reviews again, so never a model served on the Swarm's grid or one the policy rates below 2. Any engine
+ * may review any build (Ken, 2026-10-30: reviews of Claude builds waited all morning for Codex quota; a Reviewer is a
+ * session of its own with fresh context, so its strength is what counts), and never the agent that built it (cli
+ * superTabs/route.ts reviewRefusals). */
+export function reviewRefusal(state: SuperTabState, reviewed: string | undefined, target: RunTarget, policy: RoutingPolicy): string | null {
if (!reviewed) return null
- if (target.gridModel) return { refusal: 'A review never runs on a model served on the Swarm\'s grid.' }
+ if (target.gridModel) return 'A review never runs on a model served on the Swarm\'s grid.'
const quality = targetQuality(policy, target)
- const engine = ENGINE[target.engine] ?? target.engine
- if (quality < 2) return { refusal: `A review needs a model of quality 2 or more, and ${engine} ${target.model} is ${quality}.` }
- const assignment = state.conversations.find(c => c.id === reviewed)?.assignment
- const worker = assignment && state.agents.find(a => a.id === assignment.agentId)
- const builder = worker ? agentTarget(state, worker) : assignment ? { engine: assignment.configuration.engine } : null
- // A grid target was refused above, so the same family is the target's engine.
- if (!builder || familyOf(builder) !== familyOf(target)) return null
- if (otherFamilyReviews(state, builder, policy, mayRun, now)) return { refusal: `A review runs on another engine than the reviewed Builder's, ${engine}.` }
- return quality === 3 ? { note: `${SAME_ENGINE}, so the review runs on ${engine}, the Builder's engine, at its top tier.` }
- : { refusal: `A review on the reviewed Builder's engine, ${engine}, needs its top tier (quality 3): no Reviewer on another engine can start soon in this Swarm.` }
-}
-/** Why [target] may not review the work of group [reviewed]; null when it may, or nothing is reviewed. */
-/** Without the command's own judgement, a machine may run a review where the owner's rules for the reviewed group's project
- * allow it. */
-const ownerAllows = (state: SuperTabState, reviewed: string | undefined): MayRun => {
- const projectId = state.conversations.find(c => c.id === reviewed)?.projectId
- const rules = (state.rules ?? []).filter(r => !r.projectId || !projectId || r.projectId === projectId)
- return target => !broken(rules, target)
-}
-export function reviewRefusal(state: SuperTabState, reviewed: string | undefined, target: RunTarget, policy: RoutingPolicy, mayRun: MayRun = ownerAllows(state, reviewed),
- now = Date.now()): string | null {
- const judged = judgeReview(state, reviewed, target, policy, mayRun, now)
- return judged && 'refusal' in judged ? judged.refusal : null
-}
-/** Why [target] reviews on the reviewed Builder's own engine, when it may only because no other engine can; null otherwise. */
-export function sameEngineReview(state: SuperTabState, reviewed: string | undefined, target: RunTarget, policy: RoutingPolicy, mayRun: MayRun = ownerAllows(state, reviewed),
- now = Date.now()): string | null {
- const judged = judgeReview(state, reviewed, target, policy, mayRun, now)
- return judged && 'note' in judged ? judged.note : null
+ if (quality < 2) return `A review needs a model of quality 2 or more, and ${ENGINE[target.engine] ?? target.engine} ${target.model} is ${quality}.`
+ const builder = state.conversations.find(c => c.id === reviewed)?.assignment?.agentId
+ if (target.agentId && target.agentId === builder) return 'A Reviewer never reviews work it built.'
+ return null
}
diff --git a/backend/src/superTabs/store.ts b/backend/src/superTabs/store.ts
index 1108bac0e..e45268b53 100644
--- a/backend/src/superTabs/store.ts
+++ b/backend/src/superTabs/store.ts
@@ -31,7 +31,7 @@ import { answersRequest, dirtyGroups, noteProjectReports, projectUpdateRequest,
import { digestDue, digestMessageId, digestRequest, digestSince } from './digest.js'
import { judgedMachines, loseTasks, sweepForLead, sweepLiveness, SWEEP_EVERY_MS } from './liveness.js'
import { archivable, archiveLine, ASLEEP_FIELDS, asleepMatch, stopIdleWorkers, stoppedMachines, type GroupActivity } from './tidy.js'
-import { clock, insertParts, loadActive, loadGroups, loadObserved, reassemble, split, type GroupData, type HeadData, type Part, type SwarmParts } from './parts/index.js'
+import { clock, insertParts, loadActive, loadLightGroups, loadObserved, reassemble, split, type GroupData, type HeadData, type Part, type SwarmParts } from './parts/index.js'
import { groupsBy, listingDrops, quietSince, readBy, withoutHints } from './parts/indexed.js'
import { memberSwarms } from './swarmRows.js'
import { commitParts, indexesOf, numberMessages, type Touch, type Written } from './parts/commit.js'
@@ -45,7 +45,7 @@ import { activeMember, addMember, hasWorkspaceAccess, listWorkspaces, memberId,
import { WORKSPACE_LABEL, type WorkspaceRole } from './workspaces.js'
import {
activeWork, actorKey, agent, agentOnly, agentRole, appendPullRequestUrls, author, conversation, createSuperTab, fail, person, stableId, visibleState, finishWorker,
- SuperTabError, isLeads, knownKind, parkLaterConversations, syncLeads, type Actor, type Agent, type Assignment, type Author, type Conversation, type MessageDraft, type Person, type SuperTabState,
+ SuperTabError, forRecipients, isLeads, knownKind, parkLaterConversations, syncLeads, type Actor, type Agent, type Assignment, type Author, type Conversation, type MessageDraft, type Person, type SuperTabState,
} from './model.js'
import type { HoldReason } from './holdReason.js'
import { stuck } from './deliverySettle.js'
@@ -53,11 +53,12 @@ import { agentDisplayName } from './agentNames.js'
import { endedHolds, HOLDING, startedHolds, type WorkHold } from '../github/holds.js'
import { accrueLent } from './leaderboard/lent.js'
import { mayDrive, TERMINAL_ANSWER_MS, TERMINAL_EXPIRY_MS, TERMINAL_PICKUP_MS, TERMINAL_RECHECK_MS, type TerminalEffect } from './terminal.js'
-import { costRows, summarizeCosts } from './costs/read.js'
-import { recordEvidence } from './evidence/store.js'
+import { costRows, failedStarts, summarizeCosts } from './costs/read.js'
+import { APPROVE, APPROVED_DAYS, approvedReminder, localDate, MAX_PROPOSALS, proposalQuestion, proposalTitle, REASK_DAYS, reflectionMessageId, routingReflection, type Approved, type Proposal, type ReflectionInput } from './costs/reflection.js'
+import { readEvidence, recordEvidence } from './evidence/store.js'
import { closeAssignment, closeUnassignedStart, LIST_SIZE, newestConversations, newestDecisions, readDecision, recentDecisions, recordAttempts, timedDecisionOf, writeRouteEffects } from './routeDecisions.js'
import { dropHeldTags, listMentions, markDone, mentionsWaiting, openTags, readMention, resolveByReply, resolveWhenWorked, writeMentions } from './mentions.js'
-import { answerable, fullFor, listDecisions, type DecisionList, readAskedDecision, recordAnswer, repeatOf, waitingFor, waitingIn, waitingInProject, writeDecisions } from './decisions.js'
+import { answerable, askDecisions, MAX_OPEN_DECISIONS, REFLECTION_DECISION, reflectionDecisions, expireReflections, fullFor, listDecisions, type DecisionList, readAskedDecision, recordAnswer, repeatOf, waitingFor, waitingIn, waitingInProject, writeDecisions } from './decisions.js'
import { CATCH_UP_SCAN, catchUpSummary, type CatchUp } from './catchUp.js'
import { DEFAULT_ROUTING_POLICY, effectivePolicy, routingPolicySaveSchema, type RoutingPolicy } from './routingPolicy.js'
import { invitedSwarms } from './invitedSwarms.js'
@@ -150,6 +151,15 @@ export async function loadRow(tx: Transaction, row: SwarmRow, named: Named = {})
return loadedFrom(row, await loadActive(tx, row.id, named))
}
+const DAY_MS = 24 * 60 * 60_000
+/** Where a project's routing reflection goes: its project chat, under its Lead. None in a paused Swarm or without a Lead. */
+function reflectionPlace(state: SuperTabState, projectId: string) {
+ const project = projectsOf(state).find(p => p.id === projectId)
+ const chat = project && state.conversations.find(c => c.id === project.leadConversationId)
+ const lead = chat?.leadId ? state.agents.find(a => a.id === chat.leadId) : undefined
+ return state.paused || !project || !chat || !lead ? null : { project, chat, lead }
+}
+
function loadedFrom(row: SwarmRow, parts: SwarmParts): Loaded {
freeze(parts)
const state = reassemble(parts, { share: true })
@@ -2104,7 +2114,7 @@ export class SuperTabStore {
const check = async (ids: string[]) => {
const unchecked = [...new Set(ids)].filter(id => !reads.has(id))
const missing = unchecked.filter(id => !groups.has(id))
- if (missing.length) adopt(await loadGroups(tx, tabId, 'key', { key: { $in: missing } }))
+ if (missing.length) adopt(await loadLightGroups(tx, tabId, 'key', { key: { $in: missing } }))
for (const id of unchecked) reads.set(id, groups.has(id) && canReadGroup(state, actor, groups.get(id)!))
}
// An agent stored with no project (a Swarm from before projects) takes its project from its first conversation, quiet ones
@@ -2123,11 +2133,11 @@ export class SuperTabStore {
// conversations, by key); a person's can be any.
if (target) {
const project = target.projectId!
- adopt(await loadGroups(tx, tabId, 'project', { projectId: { $in: project === 'lead' ? ['lead', null] : [project] }, dormant: true }))
+ adopt(await loadLightGroups(tx, tabId, 'project', { projectId: { $in: project === 'lead' ? ['lead', null] : [project] }, dormant: true }))
const leads = [state.leadsConversationId, ...projectsOf(state).map(p => p.leadConversationId)].filter((id): id is string => !!id && !groups.has(id))
- if (leads.length) adopt(await loadGroups(tx, tabId, 'key', { key: { $in: leads } }))
+ if (leads.length) adopt(await loadLightGroups(tx, tabId, 'key', { key: { $in: leads } }))
} else {
- adopt(await loadGroups(tx, tabId, 'dormancy', { dormant: true }))
+ adopt(await loadLightGroups(tx, tabId, 'dormancy', { dormant: true }))
}
return recentDecisions(tx, tabId, [...groups.values()].filter(c => canReadGroup(state, actor, c)).map(c => c.id))
}
@@ -2665,6 +2675,84 @@ export class SuperTabStore {
return { held: true }
}
+ /**
+ * Posts a project's nightly routing reflection for local date `on` (lib/routingReflection.ts) in its project chat under its
+ * Lead's name, and asks each new proposal of the project owner as a decision from the Lead; nothing changes routing by
+ * itself. Counts only the attempts and failed starts of the project's own task groups, never a private or Buddy chat, the
+ * Leads conversation or another project. Reads first, outside any transaction (the week's attempts, failed starts, their
+ * groups and evidence); then one short transaction re-checks, reads the project's reflection decisions and writes. The
+ * report's id is the project's and date's, so a second pass or worker writes nothing ('already'). 'empty': no attempt and
+ * no failed start in the last day. 'skipped': no such Swarm or project, a paused Swarm, or a project with no Lead.
+ * Decisions (reviews of #2276): at most MAX_PROPOSALS open, each expiring after 7 days unanswered (every due night, a
+ * report or not); one answered in the last REASK_DAYS days is not asked again; one approved in the last APPROVED_DAYS days
+ * is listed each night, to the people and to the Lead.
+ */
+ async postReflection(tabId: string, projectId: string, on: string): Promise<'posted' | 'already' | 'empty' | 'skipped'> {
+ const id = reflectionMessageId(tabId, projectId, on)
+ if (await this.db.superTabMessage.findUnique({ where: { id }, select: { id: true } })) return 'already'
+ const read = await this.db.superTab.findUnique({ where: { id: tabId }, select: SWARM_ROW })
+ if (!read) return 'skipped'
+ const now = this.now(), since = now - 7 * DAY_MS
+ const { rows, truncated } = await costRows(this.db, tabId, since)
+ const failed = await failedStarts(this.db, tabId, since)
+ const seen = (await loadRow(this.db, requireParts(read), { groupIds: [...new Set([...rows, ...failed].map(r => r.conversationId))] })).state
+ const at = reflectionPlace(seen, projectId)
+ if (!at) return 'skipped'
+ const ids = new Set(seen.conversations.filter(g => !g.audience && !isLeads(g) && g.id !== at.chat.id && groupProject(seen, g).id === projectId).map(g => g.id))
+ const input: ReflectionInput = { now, rows: rows.filter(r => ids.has(r.conversationId)), groups: seen.conversations.filter(g => ids.has(g.id)),
+ failedStarts: failed.filter(f => ids.has(f.conversationId)), evidence: (await readEvidence(this.db, tabId, since, [projectId])).models, truncated,
+ rules: (seen.rules ?? []).filter(r => !r.projectId || r.projectId === projectId).map(r => r.rule) }
+ // A quiet night still expires the proposals left unanswered (delta review of #2276).
+ if (!routingReflection(input)) { await expireReflections(this.db, tabId, projectId, now); return 'empty' }
+ return transaction(this.db, async tx => {
+ if (await tx.superTabMessage.findUnique({ where: { id }, select: { id: true } })) return 'already'
+ const row = await tx.superTab.findUnique({ where: { id: tabId }, select: SWARM_ROW })
+ if (!row) return 'skipped'
+ const loaded = await loadRow(tx, requireParts(row), { groupIds: [at.chat.id] })
+ const state = structuredClone(loaded.state)
+ const place = reflectionPlace(state, projectId)
+ if (!place) return 'skipped'
+ const { project, chat, lead } = place
+ // Expired first, so neither the open proposals nor the owner's open decisions count them.
+ await expireReflections(tx, tabId, projectId, now)
+ const asked = await reflectionDecisions(tx, tabId, projectId)
+ const open = asked.filter(d => !d.answeredAt)
+ const zone = project.digest?.timeZone
+ // Approved in the last APPROVED_DAYS days, the newest per proposal, saying who decided: listed and reminded each night.
+ const approved = new Map<string, Approved>()
+ for (const d of asked) if (d.answeredAt && d.choice === APPROVE && d.answeredAt.getTime() >= now - APPROVED_DAYS * DAY_MS
+ && !approved.has(proposalTitle(d.question))) {
+ approved.set(proposalTitle(d.question), { title: proposalTitle(d.question), on: localDate(d.answeredAt.getTime(), zone), by: d.delegated ? 'pm' : 'owner' })
+ }
+ const decided = asked.filter(d => d.answeredAt && d.answeredAt.getTime() >= now - REASK_DAYS * DAY_MS).map(d => proposalTitle(d.question))
+ const report = routingReflection({ ...input, decided, approved: [...approved.values()] })!
+ const owner = state.people.find(p => p.id === project.ownerId)
+ const reads = !!owner && canReadGroup(state, { kind: 'person', userId: owner.id, email: owner.email }, chat)
+ const waitingSince = new Map(open.map(d => [proposalTitle(d.question), localDate(d.createdAt.getTime(), zone)]))
+ const held = reads ? await tx.superTabDecision.count({ where: { tabId, personId: project.ownerId, askerAgentId: lead.id,
+ OR: [{ answeredAt: null }, { answeredAt: { isSet: false } }] } }) : 0
+ const room = Math.max(0, Math.min(MAX_PROPOSALS - open.length, MAX_OPEN_DECISIONS - held))
+ const fresh = reads ? report.proposals.filter(p => !waitingSince.has(p.title)).slice(0, room) : []
+ // Says of each proposal only what happened to it: asked, waiting, or why not (review of #2276).
+ const note = (p: Proposal) => waitingSince.has(p.title) ? `Waiting for the owner's answer since ${waitingSince.get(p.title)}.`
+ : fresh.includes(p) ? 'Asked of the project owner.' : !reads ? 'Not asked: the project owner does not read this chat.'
+ : held + fresh.length >= MAX_OPEN_DECISIONS ? 'Not asked: the owner has too many open decisions.'
+ : `Not asked: at most ${MAX_PROPOSALS} proposals wait for the owner's answer at once.`
+ const author: Author = { kind: 'agent', id: lead.id, name: lead.name, displayName: agentDisplayName(state.agents, lead.id), membershipGeneration: lead.membershipGeneration }
+ const rows: MessageDraft[] = [{ id, conversationId: chat.id, replyTo: null, recipients: [], author, text: report.render(note),
+ source: { kind: 'routing-reflection', projectId, on } }]
+ // The approved changes, to the Lead too, so a Yes never rests on its memory (delta review of #2276): its alone.
+ if (approved.size) rows.push({ id: stableId(id, 'lead'), conversationId: chat.id, replyTo: null, recipients: [lead.id], author,
+ text: approvedReminder([...approved.values()]), source: forRecipients({ kind: 'routing-reflection', projectId, on }) })
+ const sequences = numberMessages(state, rows, now)
+ await this.save(tx, loaded, state, clock.next())
+ await this.writeMessages(tx, tabId, state, rows, sequences)
+ if (fresh.length) await writeDecisions(tx, tabId, askDecisions(state, chat, project.ownerId, fresh.map(proposalQuestion),
+ { operationId: id, askerAgentId: lead.id, assignmentId: null, kind: REFLECTION_DECISION }), now)
+ return 'posted'
+ })
+ }
+
/** Archives a finished group whose pull requests `checked` were all read merged or closed (archive.ts), only if it still
* qualifies inside this write: no message since, no decision waiting and no pull request linked since the read. Its
* waiting deliveries end, as a person's archive ends them. True when it archived. */
diff --git a/backend/src/worker.ts b/backend/src/worker.ts
index fdb91c4c3..3055d228d 100644
--- a/backend/src/worker.ts
+++ b/backend/src/worker.ts
@@ -29,6 +29,7 @@ import { env } from './config/env.js'
import { machineBillingWorkerService } from './services/MachineBillingWorkerService.js'
import { productUsagePeopleRollupService } from './services/ProductUsagePeopleRollupService.js'
import { startReceiptSweep } from './lib/productUsageReceiptSweep.js'
+import { startRoutingReflection } from './lib/routingReflection.js'
import { logger } from './utils/logger.js'
// Singleton background process. HTTP/WS server.ts runs as a PM2 cluster and must never own schema
@@ -63,6 +64,7 @@ async function start(): Promise<void> {
let stopArchive = (): void => {}
let stopDeliveries = (): void => {}
let stopReceiptSweep = (): void => {}
+ let stopReflection = (): void => {}
const shutdown = (signal: string): void => {
logger.info(`Received ${signal}, stopping backend worker...`)
const hardExit = setTimeout(() => process.exit(0), 5000)
@@ -74,6 +76,7 @@ async function start(): Promise<void> {
stopArchive()
stopDeliveries()
stopReceiptSweep()
+ stopReflection()
// The last partial minute, before the database closes.
stopQueryStats()
void Promise.allSettled([prisma.$disconnect(), closeBus()]).finally(() => process.exit(0))
@@ -100,6 +103,9 @@ async function start(): Promise<void> {
stopArchive = startSwarmArchive(prisma, swarms, () => githubApp ? appPullRequests(githubApp) : unknownPullRequests)
// A delivery that can no longer move ends as Not sent, instead of waiting for good (superTabs/deliverySettle.ts).
stopDeliveries = startDeliverySettle(prisma, swarms)
+ // At 23:00 in each project's time zone, what its routed work cost and how it went, with routing changes asked of its owner
+ // (lib/routingReflection.ts).
+ stopReflection = startRoutingReflection(prisma, swarms)
// PM2 wait_ready gates the singleton worker's "online" state on schema/catalog/backfill startup.
// Plain node/tsx runs do not provide process.send and simply continue.
process.send?.('ready')
diff --git a/backend/vitest.super-tabs.config.ts b/backend/vitest.super-tabs.config.ts
index b500539bd..85a57bf9a 100644
--- a/backend/vitest.super-tabs.config.ts
+++ b/backend/vitest.super-tabs.config.ts
@@ -6,5 +6,5 @@ export default defineConfig({ test: { include: ['integration/superTabs.test.ts',
'integration/superTabHotReads.test.ts', 'integration/swarmSweepStarts.test.ts', 'integration/superTabGroupPlans.test.ts', 'integration/superTabInvitationPlans.test.ts', 'integration/superTabCache.test.ts',
'integration/superTabObserver.test.ts', 'integration/productUsageConflicts.test.ts', 'integration/productUsageReceipts.test.ts', 'integration/schemaRelease.test.ts', 'integration/superTabBuddies.test.ts',
'integration/superTabBuddyProbes.test.ts', 'integration/superTabCosts.test.ts', 'integration/harnessSharesList.test.ts', 'integration/atlasSnapshot.test.ts', 'integration/queryStats.test.ts',
- 'integration/superTabEvidence.test.ts', 'integration/superTabNamedReads.test.ts', 'integration/swarmSweepPlans.test.ts', 'integration/workerIndexPlans.test.ts'], hookTimeout: 120000, testTimeout: 30000, setupFiles: ['integration/cacheOn.test-support.ts'],
+ 'integration/superTabEvidence.test.ts', 'integration/superTabNamedReads.test.ts', 'integration/swarmSweepPlans.test.ts', 'integration/workerIndexPlans.test.ts', 'integration/superTabReflection.test.ts'], hookTimeout: 120000, testTimeout: 30000, setupFiles: ['integration/cacheOn.test-support.ts'],
fileParallelism: false, env: { NODE_ENV: 'test', HARNESS_CREDENTIAL_ENCRYPTION_KEY: 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=' } } })
diff --git a/cli/src/core/agents/restoreLaunch.spec.ts b/cli/src/core/agents/restoreLaunch.spec.ts
index fc0ed3a9e..475424e85 100644
--- a/cli/src/core/agents/restoreLaunch.spec.ts
+++ b/cli/src/core/agents/restoreLaunch.spec.ts
@@ -6,11 +6,14 @@ import { WindowsBatchLaunchRefused } from '../../lib/windows/launch.js'
import { createLaunchHelpers } from './launch.js'
import { createLaunchAuthority } from './launchAuthority.js'
import type { NativeLaunch } from '../../engines/nativeLaunch.js'
+import type { SwarmSkillGrant } from '../../lib/swarmSkills.js'
+import { createSwarmSkillAdoption } from '../../superTabs/inCore/adoption.js'
const entry = { agentId: 'agent', sessionId: 'conversation', cwd: '/workspace' } as RegisteredSession
const built: Extract<LaunchOverridesResult, { ok: true }> = { ok: true, overrides: { env: {}, extraArgs: [], clearEnv: [] } }
-const setup = () => {
+const setup = (adoptSwarmSkill?: ReturnType<typeof createSwarmSkillAdoption>) => {
const deps = {
+ ...(adoptSwarmSkill ? { adoptSwarmSkill } : {}),
workspaceMissing: vi.fn((): { error: string; detail: string } | null => null),
relaunchOverrides: vi.fn(async (): Promise<LaunchOverridesResult> => built),
downgradedPermission: vi.fn(async () => ({ bypassPermission: false })),
@@ -20,6 +23,52 @@ const setup = () => {
return { deps, build: createRestoreLaunch(deps) }
}
+// Security review 1 of #2255: boot restore and a host move relaunched an old Buddy with no saved role without asking the
+// Swarm, so it came back without its guard.
+describe('an old Swarm session with no saved role', () => {
+ const legacyBuddy = { ...entry, engine: 'claude', startedBy: 'agent' } as RegisteredSession
+ const swarm = (grant: SwarmSkillGrant | null | undefined) => {
+ const save = vi.fn()
+ const role = vi.fn(async () => grant)
+ return { save, role, adopt: createSwarmSkillAdoption({ role, save, authority: () => () => true, candidate: () => false }) }
+ }
+ it('is restored with its Buddy role, saved on its row before the launch is built', async () => {
+ const s = swarm({ role: 'buddy' }), { deps, build } = setup(s.adopt)
+ expect(await build(legacyBuddy, { current: () => true })).toEqual({ argv: ['engine'] })
+ const tagged = expect.objectContaining({ swarmSkill: { role: 'buddy', key: 'agent' } })
+ expect(deps.relaunchOverrides).toHaveBeenCalledWith(tagged, tagged, expect.any(Function))
+ expect(deps.launch).toHaveBeenCalledWith(tagged, {}, built.overrides, { bypassPermission: false })
+ expect(s.save).toHaveBeenCalledWith('agent', { role: 'buddy', key: 'agent' })
+ })
+ it('is held, never launched, while its role cannot be read', async () => {
+ const { deps, build } = setup(swarm(undefined).adopt)
+ // What its pane shows the person while it waits: plain words, no ids.
+ expect(await build(legacyBuddy, { current: () => true })).toEqual({ held: 'superTabs',
+ detail: 'Waiting for the Swarm to confirm this agent\'s role. It starts by itself once the Swarm answers.' })
+ expect(deps.relaunchOverrides).not.toHaveBeenCalled()
+ expect(deps.launch).not.toHaveBeenCalled()
+ })
+ it('is left alone when the restore is cancelled while its role is read', async () => {
+ let current = true
+ const role = vi.fn(async () => { current = false; return { role: 'buddy' as const } })
+ const { deps, build } = setup(createSwarmSkillAdoption({ role, save: vi.fn(), authority: () => () => true, candidate: () => false }))
+ expect(await build(legacyBuddy, { current: () => current })).toEqual({ cancelled: true })
+ expect(deps.relaunchOverrides).not.toHaveBeenCalled()
+ })
+ it('moves to another host with its Buddy role, writing nothing while its old engine runs', async () => {
+ const s = swarm({ role: 'buddy' }), { deps, build } = setup(s.adopt)
+ expect(await build(legacyBuddy, { resumeSessionId: 'conversation', current: () => true, prepare: false })).toMatchObject({ argv: ['engine'] })
+ expect(deps.launch).toHaveBeenCalledWith(expect.objectContaining({ swarmSkill: { role: 'buddy', key: 'agent' } }),
+ { resumeSessionId: 'conversation' }, built.overrides, { bypassPermission: false })
+ expect(s.save).not.toHaveBeenCalled()
+ })
+ it('does not move while its role cannot be read', async () => {
+ const { deps, build } = setup(swarm(undefined).adopt)
+ expect(await build(legacyBuddy, { resumeSessionId: 'conversation', current: () => true, prepare: false })).toMatchObject({ held: 'superTabs' })
+ expect(deps.launch).not.toHaveBeenCalled()
+ })
+})
+
describe('a restore launch Windows refuses', () => {
it('fails that row alone, with its reason; any other error is thrown on', async () => {
const { deps, build } = setup()
diff --git a/cli/src/core/agents/restoreLaunch.ts b/cli/src/core/agents/restoreLaunch.ts
index afaf4ac37..8043db48e 100644
--- a/cli/src/core/agents/restoreLaunch.ts
+++ b/cli/src/core/agents/restoreLaunch.ts
@@ -4,6 +4,10 @@ import type { RegisteredSession } from '../../lib/registry.js'
import type { LaunchOverrides, LaunchOverridesResult } from '../../lib/launchOverrides.js'
import type { RestoreAgentsDeps, RestoreLaunch } from '../../lib/restoreAgents.js'
import { windowsLaunchRefusal } from '../../lib/windows/launch.js'
+import type { AdoptSwarmSkill } from '../api.js'
+
+/** What a harness held for its Swarm role says in its pane, in the person's words. */
+export const SWARM_ROLE_HELD = 'Waiting for the Swarm to confirm this agent\'s role. It starts by itself once the Swarm answers.'
interface RestoreLaunchDeps {
workspaceMissing(cwd: string | null | undefined): { error: string; detail: string } | null
@@ -13,14 +17,30 @@ interface RestoreLaunchDeps {
refreshGridWebSearch(agentId: string, overrides: LaunchOverrides): void
launch(entry: RegisteredSession, opts: { resumeSessionId?: string }, overrides: LaunchOverrides,
permission: { permissionMode?: string | null; bypassPermission?: boolean }): RestoreLaunch
+ /** An older Swarm session's role, read before it is relaunched (superTabs/inCore/adoption.ts). Absent while the Swarm is off. */
+ adoptSwarmSkill?: AdoptSwarmSkill
}
export function createRestoreLaunch(deps: RestoreLaunchDeps): RestoreAgentsDeps['buildLaunch'] {
- return async (entry, { current, prepare, ...opts }) => {
- if (externalResumePending(entry.externalResume)) return { held: 'search', holdScope: 'workspace',
- detail: entry.launch?.state === 'held' ? entry.launch.detail : 'Waiting to verify this external conversation.' }
- const missing = deps.workspaceMissing(entry.cwd)
+ return async (given, { current, prepare, ...opts }) => {
+ if (externalResumePending(given.externalResume)) return { held: 'search', holdScope: 'workspace',
+ detail: given.launch?.state === 'held' ? given.launch.detail : 'Waiting to verify this external conversation.' }
+ const missing = deps.workspaceMissing(given.cwd)
if (missing) return missing
+ // An older Swarm session comes back with its role, or waits for it: boot restore and a host move relaunched an old
+ // Buddy with no saved role as an ordinary session, without its guard (security review 1 of #2255). A held one waits in
+ // its pane, and the held pass launches it once the Swarm answers (core/agents/heldLaunches.ts); a move does not happen.
+ let entry = given
+ const looked = await deps.adoptSwarmSkill?.lookup?.(given, current)
+ if (looked !== undefined) {
+ // The lookup answers null once this launch no longer owns the row.
+ if (looked === null) return { cancelled: true }
+ if (looked === 'unavailable') return { held: 'superTabs', detail: SWARM_ROLE_HELD }
+ // A move builds this while the old engine still runs and writes the row only once it has stopped: it launches with the
+ // role and leaves the record to the agent's next start, which reads it again.
+ if (prepare !== false) looked.commit()
+ entry = looked.row
+ }
const built = await deps.relaunchOverrides(entry, entry, current)
if (!current()) return { cancelled: true }
if (!built.ok && built.error === 'AGENT_CHANGED') return { cancelled: true }
diff --git a/cli/src/core/agents/retarget.spec.ts b/cli/src/core/agents/retarget.spec.ts
index 894b0a004..5ffe77499 100644
--- a/cli/src/core/agents/retarget.spec.ts
+++ b/cli/src/core/agents/retarget.spec.ts
@@ -15,6 +15,9 @@ import { terminalRouteKey } from '../../lib/terminalRuntime.js'
import { createAgentRetargeter, type RetargetDeps } from './retarget.js'
import type { NativeLaunch } from '../../engines/nativeLaunch.js'
import { GUEST_HARNESS_REFUSAL } from '../guestPolicy.js'
+import { createSwarmSkillAdoption } from '../../superTabs/inCore/adoption.js'
+import { createLaunchAuthority } from './launchAuthority.js'
+import type { SwarmSkillGrant } from '../../lib/swarmSkills.js'
vi.mock('../../engines/launchControl.js', async (real) => ({
...await real<object>(),
@@ -337,6 +340,53 @@ describe('retargeting an agent', () => {
})
})
+ // Security review 1 of #2255: a model switch relaunched an old Buddy with no saved role without asking the Swarm, so it
+ // came back without its guard.
+ describe('an old Swarm session with no saved role', () => {
+ const switchWith = (grant: SwarmSkillGrant | null | undefined) => {
+ const row = agent({ startedBy: 'agent' })
+ const adoptSwarmSkill = createSwarmSkillAdoption({ role: async () => grant, candidate: () => false,
+ authority: createLaunchAuthority({ byAgent: () => row, revision: () => 0, cancelled: () => false }),
+ save: (_id, skill) => { row.swarmSkill = skill; return true } })
+ return { row, ...setup(row, { adoptSwarmSkill }) }
+ }
+ it('switches its model with its Buddy role, saved on its row', async () => {
+ const run = switchWith({ role: 'buddy' })
+ expect(await run.retarget({ agentId: 'a1', grid })).toMatchObject({ ok: true })
+ expect(run.deps.relaunchOverrides).toHaveBeenCalledWith(expect.objectContaining({ swarmSkill: { role: 'buddy', key: 'a1' } }),
+ expect.anything(), expect.any(Function), undefined)
+ expect(run.row.swarmSkill).toEqual({ role: 'buddy', key: 'a1' })
+ expect(restartAgent).toHaveBeenCalledOnce()
+ })
+ it('does not switch a session that changed while its role was read', async () => {
+ const row = agent({ startedBy: 'agent' })
+ const adoptSwarmSkill = createSwarmSkillAdoption({ candidate: () => false, save: vi.fn(),
+ role: async () => { row.cwd = '/replacement'; return { role: 'buddy' as const } },
+ authority: createLaunchAuthority({ byAgent: () => row, revision: () => 0, cancelled: () => false }) })
+ const run = setup(row, { adoptSwarmSkill })
+ expect(await run.retarget({ agentId: 'a1', grid })).toMatchObject({ ok: false, error: 'AGENT_CHANGED' })
+ expect(restartAgent).not.toHaveBeenCalled()
+ })
+ it('switches the person\'s own session as before, with no role and no Swarm read', async () => {
+ const role = vi.fn(async () => ({ role: 'buddy' as const }))
+ const row = agent()
+ const run = setup(row, { adoptSwarmSkill: createSwarmSkillAdoption({ role, candidate: () => false, save: vi.fn(),
+ authority: createLaunchAuthority({ byAgent: () => row, revision: () => 0, cancelled: () => false }) }) })
+ expect(await run.retarget({ agentId: 'a1', grid })).toMatchObject({ ok: true })
+ expect(role).not.toHaveBeenCalled()
+ expect(run.deps.relaunchOverrides).toHaveBeenCalledWith(expect.not.objectContaining({ swarmSkill: expect.anything() }),
+ expect.anything(), expect.any(Function), undefined)
+ })
+ it('refuses the switch, saying why, and leaves the running engine alone while its role cannot be read', async () => {
+ const run = switchWith(undefined)
+ expect(await run.retarget({ agentId: 'a1', grid })).toEqual({ ok: false, error: 'SWARM_ROLE_UNAVAILABLE',
+ detail: 'This agent\'s Swarm role could not be confirmed, so its model was not switched. Try again once the Swarm can be reached.' })
+ expect(run.deps.relaunchOverrides).not.toHaveBeenCalled()
+ expect(run.deps.acquireTerminalControl).not.toHaveBeenCalled()
+ expect(restartAgent).not.toHaveBeenCalled()
+ })
+ })
+
describe('a move that goes ahead', () => {
// Codex 0.166 refuses to resume a conversation on another provider (thread/resume → ModelProviderMismatch);
// a move between a grid and its own login changes provider, so the conversation goes on in a fork of it.
diff --git a/cli/src/core/agents/retarget.ts b/cli/src/core/agents/retarget.ts
index 56579c789..fbc67dc4a 100644
--- a/cli/src/core/agents/retarget.ts
+++ b/cli/src/core/agents/retarget.ts
@@ -32,6 +32,7 @@ import { workspaceMissing } from '../../lib/workspaceCheck.js'
import type { createLaunchHelpers } from './launch.js'
import type { PaneSwap } from './swap.js'
import { createLaunchAuthority } from './launchAuthority.js'
+import type { AdoptSwarmSkill } from '../api.js'
import { nativeOpencodeStore } from '../../engines/kit/nativeLocations.js'
import { GUEST_HARNESS_REFUSAL } from '../guestPolicy.js'
@@ -63,12 +64,14 @@ export interface RetargetDeps {
refreshGridAssignment: (session: RegisteredSession) => void
/** OpenCode's store, whose rows a resumed session takes its model from. */
opencodeDb: string
+ /** An older Swarm session's role, read before it is relaunched (superTabs/inCore/adoption.ts). Absent while the Swarm is off. */
+ adoptSwarmSkill?: AdoptSwarmSkill
}
export function createAgentRetargeter({
sessionTurnOpen, purgeBusy, terminals, registry, runtimeProfiles, launchOverridesDeps, acquireTerminalControl,
relaunchOverrides, downgradedPermission, agentReconciler, restartJobs, paneSwapDeps, liveBypassPermission,
- announceSession, refreshGridAssignment, opencodeDb, noBackendCode = 'TMUX_UNAVAILABLE',
+ announceSession, refreshGridAssignment, opencodeDb, noBackendCode = 'TMUX_UNAVAILABLE', adoptSwarmSkill,
}: RetargetDeps) {
const authority = createLaunchAuthority({ byAgent: id => registry.byAgent(id),
revision: id => restartJobs.revision(id), cancelled: () => false })
@@ -106,6 +109,20 @@ export function createAgentRetargeter({
// validate, and respawning over a pane whose occupant we cannot identify is how you replace
// something that was not ours.
if (!session.processIdentity) return { ok: false, error: 'NO_ACTIVE_PROCESS' }
+ // An older Swarm session switches with its role, or not at all while the role cannot be read: a switch relaunched an old
+ // Buddy with no saved role as an ordinary session, without its guard (security review 1 of #2255). Nothing has touched
+ // the pane yet, so a refusal leaves the running engine as it is.
+ const looked = await adoptSwarmSkill?.lookup?.(session, current)
+ if (looked !== undefined) {
+ // The lookup answers null once this switch no longer owns the row.
+ if (looked === null) return changed()
+ if (looked === 'unavailable') return { ok: false, error: 'SWARM_ROLE_UNAVAILABLE',
+ detail: 'This agent\'s Swarm role could not be confirmed, so its model was not switched. Try again once the Swarm can be reached.' }
+ // Recording the role changes the row this switch owns: it owns the recorded one, taken in the same step.
+ looked.commit()
+ if (looked.row.swarmSkill) session.swarmSkill = looked.row.swarmSkill
+ current = captureAuthority()
+ }
// Leaving for a grid is the LAST moment this agent's own model is observable: once the pane is on
// the grid, the engine reports the grid's model and the previous choice exists nowhere. So it is
// read now and kept, and a later move back returns the person to it rather than to whatever
diff --git a/cli/src/core/api.ts b/cli/src/core/api.ts
index 87cbf49e9..b84ddfbec 100644
--- a/cli/src/core/api.ts
+++ b/cli/src/core/api.ts
@@ -1215,7 +1215,14 @@ export interface SwarmLaunch {
/** Fill a missing Swarm role of an older Swarm session at its restart or resume (superTabs/inCore/adoption.ts): the row
* to launch, or null when the launch is no longer this one's. Absent while the Swarm is off. */
-export type AdoptSwarmSkill = (session: RegisteredSession, current: () => boolean) => Promise<RegisteredSession | null>
+export type AdoptSwarmSkill = ((session: RegisteredSession, current: () => boolean) => Promise<RegisteredSession | null>) & {
+ /** One role read, for a relaunch that cannot wait (boot restore, a model switch, a host move): the row to launch with
+ * its role, written to the registry only by `commit`; `unavailable` when the role could not be read, which the caller
+ * holds or refuses, never launching without it; null when the launch is no longer this one's. */
+ lookup?(session: RegisteredSession, current: () => boolean): Promise<{ row: RegisteredSession; commit(): void } | 'unavailable' | null>
+ /** Whether a relaunch of this row asks the Swarm for its role first (restore's `needs`). */
+ needed?(session: RegisteredSession): boolean
+}
export type LeadState = 'ask' | 'stuck' | 'work' | 'done'
/** One Swarm's Lead on a Harness Pro's card (superTabs/cards.ts). `order`: the project's index in the Swarm (the app's
diff --git a/cli/src/core/main.ts b/cli/src/core/main.ts
index b06478f00..174df2a4a 100644
--- a/cli/src/core/main.ts
+++ b/cli/src/core/main.ts
@@ -2491,6 +2491,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {
label: (engine) => buildHarnessSessionLabel(engine),
})
const restoreLaunch = createRestoreLaunch({
+ adoptSwarmSkill,
workspaceMissing, relaunchOverrides, prepareSessionResume, refreshGridWebSearch,
downgradedPermission: (entry, native) => downgradedPermission(entry, entry.bypassPermission === true, 'restore', native),
launch: (entry, opts, overrides, permission) => {
@@ -2572,7 +2573,8 @@ async function runForeground(session: AuthSession | null): Promise<void> {
triggerHint: async (runtime, engine) => { await agentReconciler.triggerHint(runtime, engine) },
log: (message) => console.log(message),
// A grid's or a saved API's launch asks models: not before the core is ready (core/agents/heldLaunches.ts).
- needs: (entry) => [...(externalResumePending(entry.externalResume) ? ['search'] : []), ...(entry.gridLaunch ? ['models'] : []), ...(entry.dsh ? ['store'] : []), ...(!isTerminalEngine(entry.engine) ? ['native'] : [])],
+ // An older Swarm session's role (core/agents/restoreLaunch.ts): one unanswered read holds the rest of the pass unasked.
+ needs: (entry) => [...(externalResumePending(entry.externalResume) ? ['search'] : []), ...(entry.gridLaunch ? ['models'] : []), ...(entry.dsh ? ['store'] : []), ...(!isTerminalEngine(entry.engine) ? ['native'] : []), ...(adoptSwarmSkill?.needed?.(entry) ? ['superTabs'] : [])],
waitingLaunch: (entry, held) => ({ argv: heldPaneArgv(held.detail, entry.externalResume?.token ?? held.nativeToken) }),
killPane: restoreOn.killPane,
}
@@ -2810,6 +2812,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {
// Moving a running agent onto a grid, or back to its own login (core/agents/retarget.ts).
backend.onRetargetAgent = createAgentRetargeter({
noBackendCode: createUnavailable,
+ adoptSwarmSkill,
sessionTurnOpen,
// A retarget swaps the engine too: not of an agent a stopped move may still run beside (`moveHeld`).
purgeBusy: (agentId) => restorePanes.busy(agentId) || backend.purgeAgentService?.busy(agentId) || moveHeld.has(registry.resolve(agentId)?.agentId ?? agentId),
diff --git a/cli/src/lib/hostMove/moveAgent.spec.ts b/cli/src/lib/hostMove/moveAgent.spec.ts
index 87f818b92..df237ce79 100644
--- a/cli/src/lib/hostMove/moveAgent.spec.ts
+++ b/cli/src/lib/hostMove/moveAgent.spec.ts
@@ -137,6 +137,15 @@ describe('moveAgent', () => {
expect(h.events).not.toContain('hold')
})
+ // Security review 1 of #2255: an old Buddy whose Swarm role cannot be read is never relaunched without its guard; its
+ // move does not happen and its engine goes on where it is (core/agents/restoreLaunch.ts).
+ it('a launch held for the Swarm\'s role leaves the agent where it is', async () => {
+ const h = harness({ buildLaunch: vi.fn(async () => ({ held: 'superTabs', detail: 'Waiting for the Swarm to confirm this agent\'s role.' })) })
+ expect(await run(h.deps)).toEqual({ moved: false, reason: expect.stringContaining('superTabs'), fellBack: false })
+ expect(h.deps.createSeeded).not.toHaveBeenCalled()
+ expect(h.events).not.toContain('stop')
+ })
+
it('a new engine that never appears falls back to the old pane', async () => {
const h = harness({
probeProcess: vi.fn(async () => null),
diff --git a/cli/src/lib/productUsageSignals.spec.ts b/cli/src/lib/productUsageSignals.spec.ts
index fa886bf4c..06e78d536 100644
--- a/cli/src/lib/productUsageSignals.spec.ts
+++ b/cli/src/lib/productUsageSignals.spec.ts
@@ -380,6 +380,10 @@ it.each([
expect(names.filter(name => name.endsWith('_error_other'))).toEqual([])
})
+it('counts a model switch held for an unreadable Swarm role as unavailable, which a retry once the Swarm answers clears', () => {
+ expect(failureKind('SWARM_ROLE_UNAVAILABLE')).toBe('unavailable')
+})
+
it('keeps every refusal a Store install or update can answer in the code list', () => {
const codes = new Set<string>()
for (const path of ['../dsh/install.ts', '../dsh/update.ts', '../dsh/lock.ts', '../dsh/service.ts', '../services/store.ts']) {
diff --git a/cli/src/lib/productUsageSignals.ts b/cli/src/lib/productUsageSignals.ts
index 3b0067b54..553a746dc 100644
--- a/cli/src/lib/productUsageSignals.ts
+++ b/cli/src/lib/productUsageSignals.ts
@@ -17,7 +17,7 @@ const setup = new Set(['TMUX_UNAVAILABLE', 'PTY_HOST_UNAVAILABLE', 'TMUX_TOO_OLD
'ENGINE_UNAVAILABLE', 'NATIVE_LAUNCH_HELD', 'DSH_MATERIALIZE_FAILED', 'SWARM_SKILL_FAILED', 'SPAWN_FAILED', 'REGISTRATION_FAILED', 'GRID_CONFIG_FAILED'])
const auth = new Set(['UNAUTHORIZED', 'AUTH_REQUIRED', 'LOGIN_REQUIRED', 'OWNER_REQUIRED', 'E2EE_REQUIRED'])
const unavailable = new Set(['SERVICE_UNAVAILABLE', 'SERVICE_FAILED', 'GRID_UNAVAILABLE', 'API_UNAVAILABLE',
- 'UNSUPPORTED', 'UNSUPPORTED_ON_REMOTE', 'TIMEOUT', 'NATIVE_UNAVAILABLE'])
+ 'UNSUPPORTED', 'UNSUPPORTED_ON_REMOTE', 'TIMEOUT', 'NATIVE_UNAVAILABLE', 'SWARM_ROLE_UNAVAILABLE'])
// A history page read for no session, or one this computer's index does not hold (services/search.ts): until
// 2026-10-28 both were `other`, 2,225 that day, a Desktop list re-reading a conversation that had left the index.
const invalid = new Set(['INVALID_ENGINE', 'INVALID_CWD', 'CWD_NOT_FOUND', 'INVALID_GRID', 'INVALID_DSH', 'INVALID_SWARM_ROLE',
diff --git a/cli/src/lib/swarmSkills.spec.ts b/cli/src/lib/swarmSkills.spec.ts
index 5907cfb4b..93a2df185 100644
--- a/cli/src/lib/swarmSkills.spec.ts
+++ b/cli/src/lib/swarmSkills.spec.ts
@@ -104,7 +104,7 @@ describe('built-in Swarm skills', () => {
// The review the Swarm opens by itself (#610, Dee 2026-10-28: reviews start the moment work is ready): each line replaces
// one the owner approved, which the byte-for-byte checks below put back. [mode, role, new line, approved line].
const autoReview: Array<['orchestration' | 'default', 'lead' | 'dev', string, string]> = [
- ['orchestration', 'lead', "- When a Builder marks ready for review with a pull request of the project's repository, the Swarm opens \"Review: <group>\" by itself: its brief holds the goal, constraints, owned code, checks, the Builder's handoff and the pull request, privacy first when the work touches sharing or access. A free Reviewer gets it (the one that reviewed the earlier head, for a re-review) and joins the Builder's group to pass the independent check. You get one line there; cancel the review if it is not needed, and post what its brief lacks (the spec's constraints copied verbatim, the most-likely-wrong list). When the line says no Reviewer is free, route the review group, start a Reviewer (prefer a different engine than the Builder, with a model at least as strong), assign it and add it to the Builder's group. Work marked ready without a pull request link gets the same group from you, by hand. A review with no verdict stays open while the work it reviews goes on.\n",
+ ['orchestration', 'lead', "- When a Builder marks ready for review with a pull request of the project's repository, the Swarm opens \"Review: <group>\" by itself: its brief holds the goal, constraints, owned code, checks, the Builder's handoff and the pull request, privacy first when the work touches sharing or access. A free Reviewer gets it (the one that reviewed the earlier head, for a re-review) and joins the Builder's group to pass the independent check. You get one line there; cancel the review if it is not needed, and post what its brief lacks (the spec's constraints copied verbatim, the most-likely-wrong list). When the line says no Reviewer is free, route the review group, start a Reviewer (on any engine, with a model at least as strong as the Builder's), assign it and add it to the Builder's group. Work marked ready without a pull request link gets the same group from you, by hand. A review with no verdict stays open while the work it reviews goes on.\n",
"- When a Builder marks ready for review, create a group \"Review: <group>\" whose brief holds only: goal, constraints, the spec's constraints copied verbatim, checks, the most-likely-wrong list, the Builder's rulings, the revision range and the Builder's handoff. Route it, assign it to a Reviewer (reuse an idle one first; prefer a different engine than the Builder, with a model at least as strong), and add the Reviewer to the Builder's group so it can pass the independent check.\n"],
['orchestration', 'dev', "No merge, and no push but your own work branch: at least every 30 minutes, and when the group needs review, with a pull request for it. Never start a reviewer for your own work.",
"No merge, PR or push, except pushing your own work branch: at least every 30 minutes, and when the group needs review. Never start a reviewer for your own work."],
diff --git a/cli/src/lib/swarmSkills.ts b/cli/src/lib/swarmSkills.ts
index a2d8295db..ae382659f 100644
--- a/cli/src/lib/swarmSkills.ts
+++ b/cli/src/lib/swarmSkills.ts
@@ -130,7 +130,7 @@ For large work, post the group plan and get the owner's ok before assigning; onc
## 8. Review
- Independent review is required when risk or difficulty is medium or higher, when the work touches security, data, defaults or a release, or when the result will be merged. Also bring in a Reviewer when a Builder is stuck, before a large refactor, or after a hard bug fix.
- Read the Builder's doubts first; settle any doubt about correctness or scope before the review starts.
-- When a Builder marks ready for review with a pull request of the project's repository, the Swarm opens "Review: <group>" by itself: its brief holds the goal, constraints, owned code, checks, the Builder's handoff and the pull request, privacy first when the work touches sharing or access. A free Reviewer gets it (the one that reviewed the earlier head, for a re-review) and joins the Builder's group to pass the independent check. You get one line there; cancel the review if it is not needed, and post what its brief lacks (the spec's constraints copied verbatim, the most-likely-wrong list). When the line says no Reviewer is free, route the review group, start a Reviewer (prefer a different engine than the Builder, with a model at least as strong), assign it and add it to the Builder's group. Work marked ready without a pull request link gets the same group from you, by hand. A review with no verdict stays open while the work it reviews goes on.
+- When a Builder marks ready for review with a pull request of the project's repository, the Swarm opens "Review: <group>" by itself: its brief holds the goal, constraints, owned code, checks, the Builder's handoff and the pull request, privacy first when the work touches sharing or access. A free Reviewer gets it (the one that reviewed the earlier head, for a re-review) and joins the Builder's group to pass the independent check. You get one line there; cancel the review if it is not needed, and post what its brief lacks (the spec's constraints copied verbatim, the most-likely-wrong list). When the line says no Reviewer is free, route the review group, start a Reviewer (on any engine, with a model at least as strong as the Builder's), assign it and add it to the Builder's group. Work marked ready without a pull request link gets the same group from you, by hand. A review with no verdict stays open while the work it reviews goes on.
- Never tell a Reviewer what not to flag or how to grade it.
- Do not review the diff yourself: same blind spots, and it burns the context you need to coordinate.
- Re-grade each finding by what a user gets if it ships, not by its label or by the spec's silence. Critical findings are fixed now, Important ones before you accept, Minor ones recorded for later.
diff --git a/cli/src/superTabs/inCore/adoption.spec.ts b/cli/src/superTabs/inCore/adoption.spec.ts
index 0fed364c8..e9fa19f12 100644
--- a/cli/src/superTabs/inCore/adoption.spec.ts
+++ b/cli/src/superTabs/inCore/adoption.spec.ts
@@ -150,6 +150,55 @@ describe('old Swarm role adoption', () => {
}
})
})
+ // The relaunch paths that cannot wait (boot restore, model switch, host move): one read, then the caller holds or refuses.
+ describe('one role read for a relaunch that cannot wait', () => {
+ it('gives the row with its role, and writes it only when the caller commits', async () => {
+ const t = setup(row({ startedBy: 'agent' })); t.role.mockResolvedValue({ role: 'buddy' })
+ const looked = await t.adopt.lookup!(t.saved, t.current)
+ if (!looked || looked === 'unavailable') throw new Error('expected a row')
+ expect(looked.row).toMatchObject({ swarmSkill: { role: 'buddy', key: 'old-session' } })
+ expect(t.saved.swarmSkill).toBeUndefined()
+ looked.commit()
+ expect(t.saved.swarmSkill).toEqual({ role: 'buddy', key: 'old-session' })
+ })
+ it.each(['offline', 'unregistered'] as const)('answers unavailable at once when the role is %s, without waiting', async unavailable => {
+ const t = setup(row({ startedBy: 'agent' }))
+ if (unavailable === 'offline') t.role.mockRejectedValue(new Error('Offline')); else t.role.mockResolvedValue(undefined)
+ expect(await t.adopt.lookup!(t.saved, t.current)).toBe('unavailable')
+ expect(t.role).toHaveBeenCalledOnce()
+ expect(t.wait).not.toHaveBeenCalled()
+ })
+ it('answers null when the relaunch is cancelled or the session rebound while it reads', async () => {
+ const cancelled = setup(); cancelled.role.mockImplementation(async () => { cancelled.cancel(); return { role: 'buddy' as const } })
+ expect(await cancelled.adopt.lookup!(cancelled.saved, cancelled.current)).toBeNull()
+ const rebound = setup(); rebound.role.mockImplementation(async () => { rebound.change(); return { role: 'buddy' as const } })
+ expect(await rebound.adopt.lookup!(rebound.saved, rebound.current)).toBeNull()
+ expect(rebound.saved.swarmSkill).toBeUndefined()
+ })
+ it('gives the row as it is for a session in no Swarm, one already tagged, or the person\'s own outside the roster', async () => {
+ const none = setup(); none.role.mockResolvedValue(null)
+ expect(await none.adopt.lookup!(none.saved, none.current)).toMatchObject({ row: none.saved })
+ const tagged = setup(row({ swarmSkill: { role: 'buddy', key: 'old-session' } }))
+ expect(await tagged.adopt.lookup!(tagged.saved, tagged.current)).toMatchObject({ row: tagged.saved })
+ const own = setup()
+ const adopt = createSwarmSkillAdoption({ role: own.role, authority: () => () => true, save: vi.fn(), candidate: () => false })
+ expect(await adopt.lookup!(own.saved, own.current)).toMatchObject({ row: own.saved })
+ expect([tagged.role, own.role].map(role => role.mock.calls.length)).toEqual([0, 0])
+ })
+ it('says which rows a relaunch must ask the Swarm about first', async () => {
+ const t = setup()
+ const adopt = createSwarmSkillAdoption({ role: t.role, authority: () => () => true, save: vi.fn(), candidate: id => id === 'member' })
+ expect(adopt.needed!(row({ agentId: 'member' }))).toBe(true)
+ expect(adopt.needed!(row({ startedBy: 'agent' }))).toBe(true)
+ expect(adopt.needed!(row())).toBe(false)
+ expect(adopt.needed!(row({ agentId: 'member', swarmSkill: { role: 'dev', key: 'member' } }))).toBe(false)
+ expect(adopt.needed!(row({ agentId: 'member', engine: 'opencode' }))).toBe(false)
+ // A confirmed "in no Swarm" is not asked again.
+ t.role.mockResolvedValue(null)
+ await adopt(row({ agentId: 'member' }), t.current)
+ expect(adopt.needed!(row({ agentId: 'member' }))).toBe(false)
+ })
+ })
it('can adopt after a local roster snapshot first excludes the session', async () => {
const t = setup()
let present = false
diff --git a/cli/src/superTabs/inCore/adoption.ts b/cli/src/superTabs/inCore/adoption.ts
index 85b7e6066..a3eec9deb 100644
--- a/cli/src/superTabs/inCore/adoption.ts
+++ b/cli/src/superTabs/inCore/adoption.ts
@@ -25,39 +25,66 @@ export function createSwarmSkillAdoption(deps: {
const noRole = new Set<string>()
const wait = deps.wait ?? pause
const log = deps.log ?? (message => console.log(message))
- return async (session, current) => {
- if (!current()) return null
- if (session.swarmSkill || session.guest || !session.cwd || (session.engine !== 'claude' && session.engine !== 'codex')) return session
- if (noRole.has(session.agentId)) return session
+ /** Whether this row's role must come from the Swarm before it launches. */
+ const needed = (session: RegisteredSession): boolean => {
+ if (session.swarmSkill || session.guest || !session.cwd || (session.engine !== 'claude' && session.engine !== 'codex')) return false
+ if (noRole.has(session.agentId)) return false
// The host's last confirmed roster is only a cheap candidate filter for the person's own sessions; the live backend
// remains authoritative. One that cannot be read cannot clear a session as personal, so the backend is asked. A session
// the Swarm started is always asked: the roster lapses after a week nobody confirms it and leaves out a member of only
// archived chats, and its "not a member" opened an old Buddy without its role (security review 2 of #2255). Every
// Buddy is one (superTabs/start.ts); a harness another agent opened names that agent, and the person's own is not one.
- if (!swarmStarted(session)) try { if (!deps.candidate(session.agentId)) return session } catch { /* asked below */ }
+ if (swarmStarted(session)) return true
+ try { return deps.candidate(session.agentId) } catch { return true }
+ }
+ const read = async (agentId: string): Promise<SwarmSkillGrant | null | undefined> => {
+ try { return await deps.role(agentId) } catch { return undefined /* An unreadable roster is no answer. */ }
+ }
+ /** The row with its role, and the write that records it; a confirmed "in no Swarm" is remembered. */
+ const adopted = (session: RegisteredSession, grant: SwarmSkillGrant | null) => {
+ if (grant === null) {
+ noRole.add(session.agentId)
+ return { row: session, commit: () => {} }
+ }
+ // With its project's mode, so the relaunch writes that text and the host owes it no reload.
+ const swarmSkill = { ...grant, key: session.agentId }
+ return { row: { ...session, swarmSkill }, commit: () => { deps.save(session.agentId, swarmSkill) } }
+ }
+ const adopt = async (session: RegisteredSession, current: () => boolean): Promise<RegisteredSession | null> => {
+ if (!current()) return null
+ if (!needed(session)) return session
const owns = deps.authority(session.agentId)
const saved = structuredClone(session)
// A Swarm session whose role cannot be read is held, never resumed without it: an old Buddy came back without its guard
// (security reviews of #2248). It goes on as soon as a read answers, so failing closed never means staying down.
let grant: SwarmSkillGrant | null | undefined
for (let delay = HOLD_FIRST_MS; ; delay = Math.min(delay * 2, HOLD_MAX_MS)) {
- grant = undefined
- try { grant = await deps.role(saved.agentId) } catch { /* An unreadable roster is no answer. */ }
+ grant = await read(saved.agentId)
if (!current()) return null
if (grant !== undefined) break
if (delay === HOLD_FIRST_MS) log(`[swarm] ${saved.agentId.slice(0, 8)} held · its Swarm role could not be read; it opens once a read answers`)
await wait(delay)
if (!current()) return null
}
- if (grant === null) {
- noRole.add(saved.agentId)
- return session
- }
+ if (grant === null) return adopted(session, grant).row
if (!owns()) return null
- // With its project's mode, so the relaunch writes that text and the host owes it no reload.
- const swarmSkill = { ...grant, key: saved.agentId }
// A stopped row is not live yet: resumePendingAgent persists the returned copy when dispatch allocates its pane.
- deps.save(saved.agentId, swarmSkill)
- return { ...saved, swarmSkill }
+ const { row, commit } = adopted(saved, grant)
+ commit()
+ return row
+ }
+ // Boot restore, a model switch and a host move cannot wait inside one launch (security review 1 of #2255): one read, and
+ // the caller holds the agent in its pane or refuses, never launching it without its role.
+ const lookup: NonNullable<AdoptSwarmSkill['lookup']> = async (session, current) => {
+ if (!current()) return null
+ if (!needed(session)) return { row: session, commit: () => {} }
+ const owns = deps.authority(session.agentId)
+ const saved = structuredClone(session)
+ const grant = await read(saved.agentId)
+ if (!current()) return null
+ if (grant === undefined) return 'unavailable'
+ if (grant !== null && !owns()) return null
+ return grant === null ? adopted(session, grant) : adopted(saved, grant)
}
+ return Object.assign(adopt, { lookup, needed })
}
diff --git a/cli/src/superTabs/planInput.spec.ts b/cli/src/superTabs/planInput.spec.ts
index 723ec08d8..075e90afc 100644
--- a/cli/src/superTabs/planInput.spec.ts
+++ b/cli/src/superTabs/planInput.spec.ts
@@ -92,12 +92,12 @@ describe('planSetup', () => {
expect(s.effortFor('g1', 'codex-default-default')).toBe('high')
})
- it('puts a review after its open build on another family, and keeps a review of finished work off its build\'s family', () => {
+ it('puts a review after its open build, and lets a review of finished work run on its build\'s family (Ken, 2026-10-30)', () => {
const s = setup(state({ conversations: [group('b1'), group('r1', { reviewOf: 'b1' }),
group('b2', { assignment: { id: 'a', agentId: 'x', status: 'done', configuration: { engine: 'codex', model: 'gpt-6.1-sol', effort: 'auto' } } }),
group('r2', { reviewOf: 'b2' })].map((g, i) => i === 2 ? { ...g, assignment: { ...(g.assignment as Json), status: 'working' } } : g) }))
expect(taskOf(s, 'r1')).toMatchObject({ kind: 'review', deps: ['b1'], independent_of: ['b1'], avoid_families: [] })
- expect(taskOf(s, 'r2')).toMatchObject({ kind: 'review', deps: [], independent_of: [], avoid_families: ['codex'] })
+ expect(taskOf(s, 'r2')).toMatchObject({ kind: 'review', deps: [], independent_of: [], avoid_families: [] })
})
it('adds the groups the Lead says a group waits for, and lists one that is not open', () => {
diff --git a/cli/src/superTabs/planInput.ts b/cli/src/superTabs/planInput.ts
index 542fab8da..cea76ffb4 100644
--- a/cli/src/superTabs/planInput.ts
+++ b/cli/src/superTabs/planInput.ts
@@ -66,13 +66,6 @@ export function parsePlanRequest(value: unknown): PlanRequest | string {
return out
}
-/** The model family a finished build used, so its review avoids it: a grid model is its own, any other the engine's. */
-function familyOf(configuration: Json, gridModels: Set<string>): string | null {
- const engine = configuration.engine, model = String(configuration.model ?? '')
- if (gridModels.has(model)) return model
- return engine === 'claude' || engine === 'codex' ? engine : null
-}
-
export function planSetup(input: { state: Json; policy: Policy; leadId: string; request: PlanRequest; githubApp: boolean; now: number }): PlanSetup {
const { state, policy, leadId, request, githubApp, now } = input
const conversations = list(state.conversations)
@@ -144,7 +137,6 @@ export function planSetup(input: { state: Json; policy: Policy; leadId: string;
concurrency: (s.kind === 'api' ? API_BUILDERS : 1) - s.holders.length, subscription: false, remote: s.kind === 'api' || s.kind === 'shared',
family: s.model, label: `Claude on ${s.label} (${KIND_WORD[s.kind]})`, ...(s.machines ? { machines: [...s.machines].filter(m => pools.has(m)) } : {}) })
}
- const gridModels = new Set(served.map(s => s.model))
// Tasks: each open group, with its assessment, dependencies, and the machines and models its project's rules leave.
const estimates: string[] = [], ignored: string[] = [], titles: Record<string, string> = {}
@@ -160,7 +152,6 @@ export function planSetup(input: { state: Json; policy: Policy; leadId: string;
const after = (a.after ?? []).filter(d => openIds.has(d))
ignored.push(...(a.after ?? []).filter(d => !openIds.has(d) && !conversations.some(x => x.id === d)))
const deps = [...new Set([...(buildOpen ? [String(build!.id)] : []), ...after])]
- const builtWith = build && !buildOpen ? familyOf(object(object(build.assignment).configuration), gridModels) : null
const projectOwner = project?.ownerId ?? state.ownerId
// One machine (routeTask): a Mac's owner's own projects start on the Mac, a teammate's in its team account, so only one of
// the two is offered for this group.
@@ -188,7 +179,8 @@ export function planSetup(input: { state: Json; policy: Policy; leadId: string;
const { minutes, spend } = SIZES[a.size]
return { id, title: titles[id], minutes, floor: floorFor(policy, a as unknown as Assessment), kind: review ? 'review' : a.kind ?? 'default',
difficulty: a.difficulty, spend: { ...spend }, deps, independent_of: buildOpen ? [String(build!.id)] : [],
- avoid_families: builtWith ? [builtWith] : [], machines: allowed, models: allowedModels }
+ // Any strong engine reviews any build (Ken, 2026-10-30), so a review avoids no model family.
+ avoid_families: [], machines: allowed, models: allowedModels }
})
// Accounts: each machine's quota readings, shared where two machines report one account (route.ts accountOf).
diff --git a/cli/src/superTabs/route.spec.ts b/cli/src/superTabs/route.spec.ts
index fb8838390..02bc0d4c6 100644
--- a/cli/src/superTabs/route.spec.ts
+++ b/cli/src/superTabs/route.spec.ts
@@ -1,6 +1,6 @@
// cli/src/superTabs/route.spec.ts
import { describe, expect, it } from 'vitest'
-import { API_BUILDERS, LOCAL_NONE, breaks, choose, gridQuality, otherFamilyReviews, reviewRefusals, decide, floorFor, parseAssessment, quotaOf2, rateFor, recordOf, repoMatch, repositoryKey, type Assessment, type Commitment, type MemberFrame, type Policy, type Probe, type SwarmRule, type TaskFolder } from './route.js'
+import { API_BUILDERS, LOCAL_NONE, breaks, choose, gridQuality, reviewRefusals, decide, floorFor, parseAssessment, quotaOf2, rateFor, recordOf, repoMatch, repositoryKey, type Assessment, type Commitment, type MemberFrame, type Policy, type Probe, type SwarmRule, type TaskFolder } from './route.js'
const object = (v: unknown) => v as Record<string, unknown>
@@ -676,27 +676,22 @@ describe('local models on the Swarm\'s grid', () => {
expect(gridQuality({ ...policy, localModels: { quality: 2, enabled: true } }, 'moonshotai/kimi-k3')).toBe(2)
expect(gridQuality(policy, 'moonshotai/kimi-k3')).toBe(1)
})
- it('never lets a grid model, a model below quality 2 or the reviewed Builder\'s own family review (Ken, 2026-10-29)', () => {
- const codex = { engine: 'codex' }
- expect(reviewRefusals(local({ quality: 2 }), codex, true)).toEqual(['A review never runs on a model served on the Swarm\'s grid.'])
- expect(reviewRefusals(probe({ model: 'haiku', quality: 1 }), codex, true)).toEqual(['A review needs a model of quality 2 or more, and Claude haiku is 1.'])
- expect(reviewRefusals(probe({ engine: 'codex', model: 'default', quality: 3 }), codex, true)).toEqual(['A review runs on another engine than the reviewed Builder\'s, Codex.'])
- // A Builder on a grid model is its own family: Claude reviews it, even though Claude Code drove it.
- expect(reviewRefusals(probe(), { engine: 'claude', gridModel: 'moonshotai/kimi-k3' }, true)).toEqual([])
- expect(reviewRefusals(probe(), { engine: 'claude' }, true)).toEqual(['A review runs on another engine than the reviewed Builder\'s, Claude.'])
- expect(reviewRefusals(probe(), null, true)).toEqual([])
- // Another engine counts only where the owner's rules let it run, at the effort a new agent starts at (review of ee4ee6c9a).
- const codexElsewhere = probe({ machineId: 'm2', engine: 'codex', model: 'default', effort: 'default', quality: 3 })
- const only = (machineIds: string[]) => [{ rule: { kind: 'machines', machineIds }, text: 'Only ours.' } as SwarmRule]
- expect(otherFamilyReviews([probe(), codexElsewhere], { engine: 'claude' }, [])).toBe(true)
- expect(otherFamilyReviews([probe(), codexElsewhere], { engine: 'claude' }, only(['m1']))).toBe(false)
- expect(otherFamilyReviews([probe(), codexElsewhere], { engine: 'claude' }, [{ rule: { kind: 'minEffort', effort: 'high' }, text: 'High.' }])).toBe(true)
- expect(otherFamilyReviews([probe(), probe({ engine: 'codex', model: 'gpt-5.5-mini', quality: 1 })], { engine: 'claude' }, [])).toBe(false)
- expect(otherFamilyReviews([codexElsewhere], null, [])).toBe(false)
- // With no Reviewer of another engine anywhere, the Builder's own engine reviews at its top tier only (Lead, 2026-10-29).
- expect(reviewRefusals(probe({ model: 'opus', quality: 3 }), { engine: 'claude' }, false)).toEqual([])
- expect(reviewRefusals(probe(), { engine: 'claude' }, false))
- .toEqual(['A review on the reviewed Builder\'s engine, Claude, needs its top tier (quality 3): no Reviewer on another engine can start soon in this Swarm.'])
+ it('never lets a grid model, a model below quality 2 or the Builder itself review (Ken, 2026-10-29)', () => {
+ const codex = { engine: 'codex', agentId: 'builder' }
+ expect(reviewRefusals(local({ quality: 2 }), codex)).toEqual(['A review never runs on a model served on the Swarm\'s grid.'])
+ expect(reviewRefusals(probe({ model: 'haiku', quality: 1 }), codex)).toEqual(['A review needs a model of quality 2 or more, and Claude haiku is 1.'])
+ expect(reviewRefusals(probe({ kind: 'member', agentId: 'builder', model: 'opus', quality: 3 }), codex)).toEqual(['A Reviewer never reviews work it built.'])
+ expect(reviewRefusals(probe({ kind: 'member', agentId: 'other', model: 'opus', quality: 3 }), codex)).toEqual([])
+ expect(reviewRefusals(probe(), null)).toEqual([])
+ })
+
+ // Ken, 2026-10-30: reviews of Claude builds waited all morning for Codex quota. Any strong engine reviews any build now.
+ it('lets the Builder\'s own engine review at once, at any strength of 2 or more, with Reviewers of another engine free', () => {
+ const claude = { engine: 'claude', agentId: 'builder', quality: 3 }
+ expect(reviewRefusals(probe({ model: 'opus', quality: 3 }), claude)).toEqual([])
+ expect(reviewRefusals(probe({ model: 'sonnet', quality: 2 }), claude)).toEqual([])
+ expect(reviewRefusals(probe({ engine: 'codex', model: 'default', quality: 3 }), { engine: 'codex' })).toEqual([])
+ expect(reviewRefusals(probe(), { engine: 'claude', gridModel: 'moonshotai/kimi-k3' })).toEqual([])
})
it('says why a named model the Swarm has is never offered to Builders, rather than to share it', () => {
diff --git a/cli/src/superTabs/route.ts b/cli/src/superTabs/route.ts
index 872333e06..4dedcd7d1 100644
--- a/cli/src/superTabs/route.ts
+++ b/cli/src/superTabs/route.ts
@@ -53,9 +53,6 @@ export interface Probe {
/** Members: the frame (null when it could not be read), whether the member is in the task's repository, and its earlier work in this Super Tab. */
frame?: MemberFrame | null; repo?: 'same' | 'different' | 'unknown'; earlier?: Array<{ group: string; outcome: string }>
terminalUnverified?: boolean
- /** Why no agent of its engine starts on its machine within REVIEW_START_MS, whatever its quota: offline, paused, signed out,
- * suspended, or a member held by a usage limit past it. Read by [otherFamilyReviews]. */
- cannotStart?: string
/** New agents: what the machine has. */
load?: MachineLoad
/** A new agent on a model served on the Swarm's grid: free, reached through the grid relay, `model`/`effort` `default`.
@@ -232,45 +229,18 @@ export function rateFor(policy: Policy, engine: string, model: string | null, ef
/** A small variant by its name: a mini or a nano (backend superTabs/rules.ts). */
const SMALL = /(^|[^a-z0-9])(mini|nano)([^a-z0-9]|$)/i
-/** What a reviewed Builder ran: its engine, and the grid model its engine drove. */
-export interface Reviewed { engine: string; gridModel?: string; quality?: number }
-/** A model family: a grid model's own, else its engine's. */
-const familyOf = (t: Reviewed) => t.gridModel ? `grid:${t.gridModel}` : t.engine
-/** Why [p] may not review (Ken, 2026-10-29: a small model never reviews again): a model served on the Swarm's grid, one rated
- * below 2, or the reviewed Builder's own model family while a strong Reviewer of another family can run here ([otherFamily]).
- * With none, the Builder's own engine at its top tier (Lead, 2026-10-29). The server judges the same (backend
- * superTabs/rules.ts reviewRefusal). */
-export function reviewRefusals(p: Probe, builder: Reviewed | null, otherFamily: boolean): string[] {
+/** What a reviewed Builder ran: its agent, its engine, the grid model its engine drove, and how strong that was. */
+export interface Reviewed { engine: string; gridModel?: string; quality?: number; agentId?: string }
+/** Why [p] may not review: a model served on the Swarm's grid or one rated below 2 (Ken, 2026-10-29: a small model never
+ * reviews again), or the agent that built the work. Any engine reviews any build (Ken, 2026-10-30: reviews of Claude builds
+ * waited all morning for Codex quota; a Reviewer is a session of its own with fresh context, so its strength is what counts).
+ * The server judges the same (backend superTabs/rules.ts reviewRefusal). */
+export function reviewRefusals(p: Probe, builder: Reviewed | null): string[] {
if (p.gridModel) return ['A review never runs on a model served on the Swarm\'s grid.']
if (p.quality < 2) return [`A review needs a model of quality 2 or more, and ${ENGINE[p.engine]} ${p.model} is ${p.quality}.`]
- if (!builder || familyOf(builder) !== familyOf(p)) return []
- if (otherFamily) return [`A review runs on another engine than the reviewed Builder's, ${ENGINE[p.engine]}.`]
- return p.quality < 3 ? [`A review on the reviewed Builder's engine, ${ENGINE[p.engine]}, needs its top tier (quality 3): no Reviewer on another engine can start soon in this Swarm.`] : []
+ if (p.kind === 'member' && builder?.agentId && p.agentId === builder.agentId) return ['A Reviewer never reviews work it built.']
+ return []
}
-/** How soon a Reviewer has to be able to start to count: a start still not running after this long is abandoned (backend
- * superTabs/store.ts ABANDONED_START_MS). A window that resets inside it counts as quota; one out for longer does not (backend
- * superTabs/reviewSeats.ts REVIEW_START_MS). */
-export const REVIEW_START_MS = 15 * 60_000
-/** How the route line and the brief of a review on its Builder's own engine start (Lead, 2026-10-30; backend superTabs/rules.ts). */
-export const SAME_ENGINE = 'same-engine review: no Reviewer of another engine has quota'
-/** Whether [q] has quota now, or once each used-up window resets within REVIEW_START_MS. One it cannot read, or metered, does,
- * as a start there does. */
-export function quotaWithin(q: Quota, now: number): boolean {
- if (!q.known || q.metered) return true
- const soon = (resetsAt: number | null) => resetsAt !== null && resetsAt - now <= REVIEW_START_MS
- return q.windows?.length ? q.windows.every(w => w.leftPercent > 0 || soon(w.resetsAt)) : q.leftPercent === null || q.leftPercent > 0 || soon(q.resetsAt)
-}
-/** Whether a strong Reviewer of another family than [builder]'s could start within REVIEW_START_MS: a candidate off the grid,
- * rated 2 or more, of another family, that the owner's [rules] let run at the effort it would start at, whose machine is up
- * ([Probe.cannotStart]) with quota now or once a window resets inside the window. Busy still counts: a Reviewer frees up. One
- * out of quota for days or offline does not (2026-10-30: reviews of Claude builds waited all morning on Codex machines out of
- * weekly quota); the caller leaves out the machines the task or its access rules out (review of ee4ee6c9a: an engine the
- * owner ruled out blocked the fallback). */
-export const otherFamilyReviews = (probes: Probe[], builder: Reviewed | null, rules: SwarmRule[], now: number = Date.now()) =>
- !!builder && probes.some(p => !p.gridModel && p.quality >= 2 && familyOf(p) !== familyOf(builder) && !p.cannotStart && quotaWithin(p.quota, now)
- && !breaks(rules, lifted(rules, p)))
-/** Whether [p] reviews on [builder]'s own model family. */
-export const sameFamily = (p: Probe, builder: Reviewed | null) => !!builder && familyOf(builder) === familyOf(p)
/** A task that stepped up from a cheaper model takes no grid model and nothing below the step's floor; the server refuses
* the same (backend superTabs/stepUp.ts stepUpRefusal). */
diff --git a/cli/src/superTabs/routeCommand.spec.ts b/cli/src/superTabs/routeCommand.spec.ts
index 24c0bb99f..1100f6dbe 100644
--- a/cli/src/superTabs/routeCommand.spec.ts
+++ b/cli/src/superTabs/routeCommand.spec.ts
@@ -249,29 +249,23 @@ describe('routeTask', () => {
expect(fresh.next).toContain('"name":"Reviewer","role":"reviewer"')
expect((await offered(false, false)).next).not.toContain('"role"')
})
- it('leaves out of a review the reviewed Builder\'s engine while another engine can review, and says why', async () => {
- const t = tab(); t.state.agents = agents.map(a => a.id === 'a1' ? { ...a, role: 'reviewer' } : a)
+ // Ken, 2026-10-30: reviews of Claude builds waited all morning for Codex quota. Any strong engine reviews any build now.
+ it('offers a review the reviewed Builder\'s own engine at once while another engine could review, with no same-engine note', async () => {
+ const t = tab(); t.state.agents = agents.map(a => a.id === 'a1' ? { ...a, role: 'reviewer', configuration: { engine: 'claude', model: 'opus', effort: 'high' } } : a)
t.state.conversations.push({ id: 'g0', title: 'Built', leadId: 'lead', agentIds: ['lead'], archived: false, brief: '', checks: [],
- assignment: { id: 'b', agentId: 'gone', status: 'review', configuration: { engine: 'claude' } } } as never)
+ assignment: { id: 'b', agentId: 'gone', status: 'review', configuration: { engine: 'claude', model: 'opus', effort: 'high' } } } as never)
Object.assign(t.state.conversations[1]!, { reviewOf: 'g0' })
- // Codex is on in the policy, so a Codex Reviewer can run.
+ // Codex is on in the policy and signed in with quota, so a Codex Reviewer could start too.
const both = { ...policy, models: policy.models.map(m => ({ ...m, enabled: true })) }
const context = { ok: true, value: { agentId: 'lead', tab: t, policy: { policy: both, warnings: [] }, machines: [{ machineId: 'm1', name: 'remote-1' }] } }
- const twoEngines = await routeTask(input, scoped({ context }), where as never, opener(id => daemon(id, { agents: ['h1'],
+ const s = scoped({ context })
+ const result = await routeTask(input, s, where as never, opener(id => daemon(id, { agents: id === 'm1' ? ['h1'] : [],
engines: [{ engine: 'claude', installed: true, signedIn: true }, { engine: 'codex', installed: true, signedIn: true }] })), () => 'op')
- expect(twoEngines).toMatchObject({ ok: true, pick: { engine: 'codex' } })
- // A Claude-only Swarm reviews a Claude Builder's work on its top tier alone.
- const s = scoped({ tab: t })
- expect(await routeTask(input, s, where as never, opener(), () => 'op')).toMatchObject({ ok: true, pick: { kind: 'new', engine: 'claude', model: 'opus' } })
- expect(recorded(s).command.decision.excluded).toEqual(expect.arrayContaining([{ title: 'Multiply · Claude sonnet medium · remote-1',
- reason: 'A review on the reviewed Builder\'s engine, Claude, needs its top tier (quality 3): no Reviewer on another engine can start soon in this Swarm.' }]))
- // A Builder still in the Swarm is read from its agent: on a grid model, Claude may review it.
- t.state.agents.push({ id: 'b1', name: 'Kimi', machineId: 'm1', harnessId: 'hb', configuration: { engine: 'claude', model: 'default', effort: 'default' }, gridModel: 'moonshotai/kimi-k3' } as never)
- Object.assign(t.state.conversations[2]!, { assignment: { id: 'b', agentId: 'b1', status: 'review' } })
- expect(await routeTask(input, scoped({ tab: t }), where as never, opener(), () => 'op')).toMatchObject({ ok: true, pick: { kind: 'member', agentId: 'a1' } })
- // Nothing reviewed yet, nothing to keep apart.
- Object.assign(t.state.conversations[2]!, { assignment: null })
- expect(await routeTask(input, scoped({ tab: t }), where as never, opener(), () => 'op')).toMatchObject({ ok: true })
+ // The idle Claude Opus Reviewer takes it at once.
+ expect(result).toMatchObject({ ok: true, pick: { kind: 'member', agentId: 'a1' } })
+ const decision = recorded(s).command.decision
+ expect(decision.why).not.toMatch(/same-engine/)
+ expect(JSON.stringify(decision.excluded)).not.toMatch(/another engine|same-engine|top tier/)
})
it('holds a review to the reviewed Builder\'s strength: a top-tier Codex Builder is reviewed at the top tier, a grid Builder at its own', async () => {
const t = tab(); t.state.agents = agents.map(a => a.id === 'a1' ? { ...a, role: 'reviewer' } : a)
@@ -299,77 +293,44 @@ describe('routeTask', () => {
expect(await routeTask(input, s, where as never, opener(), () => 'op')).toMatchObject({ ok: true, pick: { kind: 'new', engine: 'claude', model: 'opus' } })
expect(recorded(s).command.decision).toMatchObject({ floor: 3, belowFloor: false })
})
- it('lets the Builder\'s engine review at its top tier when the only other engine is on a machine the task may not use', async () => {
- const pool = (machineId: string, engines: string[], patch: Record<string, unknown> = {}) => ({ machineId, name: machineId, cwd: '/w', engines, paused: false, contributorId: 'owner',
- observation: { receivedAt: Date.now(), resources: { memoryTotalBytes: 32e9, memoryUsedBytes: 2e9, projectDiskFreeBytes: 200e9 }, tools: { git: true }, runningHarnessIds: [],
- quotas: engines.map(engine => ({ engine, known: true, windows: [{ name: '5-hour', usedPercent: 20, resetsAt: Date.now() + 3600000 }, { name: 'weekly', usedPercent: 10, resetsAt: Date.now() + 5 * 86400000 }] })) }, ...patch })
- const both = { ...policy, models: policy.models.map(m => ({ ...m, enabled: true })) }
- const routeWith = async (codexBox: Record<string, unknown>, requires?: string[]) => {
- const t = tab(); t.state.agents = [agents[1]] as never
- t.state.conversations.push({ id: 'g0', title: 'Built', leadId: 'lead', agentIds: ['lead'], archived: false, brief: '', checks: [],
- assignment: { id: 'b', agentId: 'gone', status: 'review', configuration: { engine: 'claude' } } } as never)
- Object.assign(t.state.conversations[1]!, { reviewOf: 'g0', ...requires ? { task: { goal: 'g', changes: 'c', constraints: 'k', owns: [], requires: { machines: requires } } } : {} })
- Object.assign(t.state, { machines: [pool('m1', ['claude']), codexBox] })
- const s = scoped({ context: { ok: true, value: { agentId: 'lead', tab: t, policy: { policy: both, warnings: [] }, machines: [] } } })
- return routeTask(input, s, where as never, opener(), () => 'op')
- }
- // Codex on m2 reviews, so Claude may not.
- expect(await routeWith(pool('m2', ['codex']))).toMatchObject({ ok: true, pick: { engine: 'codex', machineId: 'm2' } })
- // The task runs only on m1, or m2 may not take a teammate's project: Claude reviews at its top tier on m1.
- expect(await routeWith(pool('m2', ['codex']), ['m1'])).toMatchObject({ ok: true, pick: { engine: 'claude', model: 'opus', machineId: 'm1' } })
- expect(await routeWith(pool('m2', ['codex'], { contributorId: 'mate', teamWork: { allowed: false, code: 'TEAM_ACCOUNT_REQUIRED', reason: 'Not a Team machine.' } })))
- .toMatchObject({ ok: true, pick: { engine: 'claude', model: 'opus', machineId: 'm1' } })
- })
- // 2026-10-30: every Codex Reviewer was out of weekly quota for days, yet Claude builds' top-tier Claude reviews were refused
- // because Codex machines existed; reviews waited all morning (Tony). Another engine counts only where a Reviewer could start
- // within the start window: on an allowed machine, online, with quota now or once a window resets inside it.
- describe('a review on its Builder\'s own engine when no Reviewer of another engine could start soon', () => {
+ // 2026-10-30: every Codex Reviewer was out of weekly quota for days, and Claude builds' reviews waited all morning for it.
+ // Since Ken's ruling that day the review takes whichever strong Reviewer can start, and waits for no other engine.
+ describe('a review while Codex is short of quota', () => {
const DAY = 86_400_000, MIN = 60_000
- const pool = (machineId: string, engines: string[], weekly: { usedPercent: number; resetsIn: number } = { usedPercent: 10, resetsIn: 5 * DAY }, patch: Record<string, unknown> = {}) => ({
+ const pool = (machineId: string, engines: string[], weekly: { usedPercent: number; resetsIn: number } = { usedPercent: 10, resetsIn: 5 * DAY }) => ({
machineId, name: machineId, cwd: '/w', engines, paused: false, contributorId: 'owner',
observation: { receivedAt: Date.now(), resources: { memoryTotalBytes: 32e9, memoryUsedBytes: 2e9, projectDiskFreeBytes: 200e9 }, tools: { git: true }, runningHarnessIds: [],
quotas: engines.map(engine => ({ engine, known: true, windows: [{ name: '5-hour', usedPercent: 20, resetsAt: Date.now() + 3600000 },
- { name: 'weekly', usedPercent: engine === 'codex' ? weekly.usedPercent : 10, resetsAt: Date.now() + (engine === 'codex' ? weekly.resetsIn : 5 * DAY) }] })) }, ...patch })
+ { name: 'weekly', usedPercent: engine === 'codex' ? weekly.usedPercent : 10, resetsAt: Date.now() + (engine === 'codex' ? weekly.resetsIn : 5 * DAY) }] })) } })
const both = { ...policy, models: policy.models.map(m => ({ ...m, enabled: true })) }
const routeWith = async (codexBox: Record<string, unknown>, rules: unknown[] = []) => {
const t = tab(); t.state.agents = [agents[1]] as never
t.state.conversations.push({ id: 'g0', title: 'Built', leadId: 'lead', agentIds: ['lead'], archived: false, brief: '', checks: [],
- assignment: { id: 'b', agentId: 'gone', status: 'review', configuration: { engine: 'claude' } } } as never)
+ assignment: { id: 'b', agentId: 'gone', status: 'review', configuration: { engine: 'claude', model: 'opus', effort: 'high' } } } as never)
Object.assign(t.state.conversations[1]!, { reviewOf: 'g0' })
Object.assign(t.state, { machines: [pool('m1', ['claude']), codexBox], rules })
const s = scoped({ context: { ok: true, value: { agentId: 'lead', tab: t, policy: { policy: both, warnings: [] }, machines: [] } } })
const result = await routeTask(input, s, where as never, opener(), () => 'op')
return { result, decision: 'error' in result ? null : recorded(s).command.decision }
}
- const sameEngine = { ok: true, pick: { engine: 'claude', model: 'opus', machineId: 'm1' }, why: expect.stringMatching(/^same-engine review: no Reviewer of another engine has quota\. /) }
+ const opusNow = { ok: true, pick: { engine: 'claude', model: 'opus', machineId: 'm1' } }
- it('lets Claude Opus review a Claude build while Codex is out of quota for days, and its route line says why', async () => {
+ it('starts Claude Opus at once for a Claude build while Codex is out of quota for days, with no note', async () => {
const { result, decision } = await routeWith(pool('m2', ['codex'], { usedPercent: 100, resetsIn: 3 * DAY }))
- expect(result).toMatchObject(sameEngine)
- expect(decision.why).toMatch(/^same-engine review: no Reviewer of another engine has quota\. /)
- // Still never below the top tier.
- expect(decision.excluded).toEqual(expect.arrayContaining([expect.objectContaining({ title: expect.stringContaining('Claude sonnet'),
- reason: expect.stringContaining('needs its top tier (quality 3): no Reviewer on another engine can start soon in this Swarm.') })]))
+ expect(result).toMatchObject(opusNow)
+ expect(decision.why).not.toMatch(/same-engine/)
})
- it('still refuses Claude while Codex resets inside the start window, so the review waits for it', async () => {
- const { result } = await routeWith(pool('m2', ['codex'], { usedPercent: 100, resetsIn: 10 * MIN }))
- expect(result).toMatchObject({ error: 'NO_CANDIDATE' })
- expect((result as { excluded: Array<{ title: string; reason: string }> }).excluded).toEqual(expect.arrayContaining([
- expect.objectContaining({ title: expect.stringContaining('Claude opus'), reason: 'A review runs on another engine than the reviewed Builder\'s, Claude.' })]))
- // And with quota now, Codex reviews.
- expect((await routeWith(pool('m2', ['codex']))).result).toMatchObject({ ok: true, pick: { engine: 'codex', machineId: 'm2' } })
+ it('waits for no Codex window that resets soon', async () => {
+ const { result, decision } = await routeWith(pool('m2', ['codex'], { usedPercent: 100, resetsIn: 10 * MIN }))
+ expect(result).toMatchObject(opusNow)
+ expect(JSON.stringify(decision.excluded)).not.toMatch(/another engine/)
})
- it('lets Claude review when Codex runs only on a machine the owner left out, or one that is offline or signed out', async () => {
- const ownersMachines = [{ id: 'r1', rule: { kind: 'machines', machineIds: ['m1'] }, text: 'Only m1.' }]
- expect((await routeWith(pool('m2', ['codex']), ownersMachines)).result).toMatchObject(sameEngine)
- const offline = pool('m2', ['codex']); (offline.observation as { receivedAt: number }).receivedAt = Date.now() - 10 * MIN
- expect((await routeWith(offline)).result).toMatchObject(sameEngine)
- const signedOut = pool('m2', ['codex']); Object.assign(signedOut.observation, { readiness: { engines: [{ engine: 'codex', installed: true, signedIn: false }] } })
- expect((await routeWith(signedOut)).result).toMatchObject(sameEngine)
- // Paused by its owner, as the server reads it (backend superTabs/reviewSeats.ts; review of #2275).
- expect((await routeWith(pool('m2', ['codex'], undefined, { paused: true }))).result).toMatchObject(sameEngine)
+ it('lets the owner\'s preferred engine for reviews decide between two that can start', async () => {
+ const prefer = (engine: string) => [{ id: 'r1', rule: { kind: 'preferEngine', taskKind: 'review', engine }, text: `${engine} reviews.` }]
+ expect((await routeWith(pool('m2', ['codex']), prefer('claude'))).result).toMatchObject(opusNow)
+ expect((await routeWith(pool('m2', ['codex']), prefer('codex'))).result).toMatchObject({ ok: true, pick: { engine: 'codex', machineId: 'm2' } })
})
})
it('tells the Lead how to assign a member or start a new agent with the decision', async () => {
diff --git a/cli/src/superTabs/routeCommand.ts b/cli/src/superTabs/routeCommand.ts
index 495ed31c3..97bb1b0b3 100644
--- a/cli/src/superTabs/routeCommand.ts
+++ b/cli/src/superTabs/routeCommand.ts
@@ -7,7 +7,7 @@ import { openDaemon, type Daemon, type Where } from '../agentClient/daemon.js'
import { RELAYED_QUOTA, requiredToolReason, startRequirements } from './capacity.js'
import { inspectCapacity, type ScopedRequest } from './start.js'
import { ENDED_WORK, object, within } from './wire.js'
-import { accountOf, API_BUILDERS, choose, decide, gridQuality, parseAssessment, quotaOf2, rateFor, recordOf, otherFamilyReviews, repoMatch, repositoryKey, REVIEW_START_MS, reviewRefusals, SAME_ENGINE, sameFamily, stepUpRefusals, type Assessment, type Reviewed, type RecordShape, type Commitment, type Excluded, type HeldModel, type MemberFrame, type Policy, type Probe, type SwarmRule, type TaskFolder } from './route.js'
+import { accountOf, API_BUILDERS, choose, decide, gridQuality, parseAssessment, quotaOf2, rateFor, recordOf, repoMatch, repositoryKey, reviewRefusals, stepUpRefusals, type Assessment, type Reviewed, type RecordShape, type Commitment, type Excluded, type HeldModel, type MemberFrame, type Policy, type Probe, type SwarmRule, type TaskFolder } from './route.js'
import { stat } from 'node:fs/promises'
import { describeScmProject } from '../scm/scmProjects.js'
@@ -305,11 +305,9 @@ export async function routeTask(input: { tabId: string; conversationId: string;
// The backend writes the mark with its loss's reason (backend superTabs/liveness.ts loseTask).
return marked ? [`It lost its last task (${String(object(marked).reason)}). It takes work again once a person assigns it by hand or the Lead replaces it.`] : []
}
- // A member held by a usage limit past the start window, or anything on a machine that is offline, starts nothing soon.
- const heldPast = (agentId: string | undefined) => Date.parse(String(members.find(m => m.id === agentId)?.limitedUntil)) - Date.now() > REVIEW_START_MS
- const probes = probed.flat().map(p => p.cannotStart || !p.refusals.includes(OFFLINE) ? p : { ...p, cannotStart: OFFLINE })
+ const probes = probed.flat()
.map(p => p.kind === 'member' ? { ...p, repo: repoMatch(folder, p.frame ?? null, p.machineId === where.machineId),
- refusals: [...p.refusals, ...limited(p.agentId), ...lostTask(p.agentId)], ...(!p.cannotStart && heldPast(p.agentId) ? { cannotStart: limited(p.agentId)[0] } : {}),
+ refusals: [...p.refusals, ...limited(p.agentId), ...lostTask(p.agentId)],
earlier: ended.filter(e => e.agentId === p.agentId).reverse().slice(0, 3).map(e => ({ group: e.group, outcome: e.outcome })) } : p)
probes.push(...localProbes(state, policy, probes, assessment, review))
// A Mac's Harness Team account is that Mac, as for the owner's machines rule.
@@ -323,13 +321,10 @@ export async function routeTask(input: { tabId: string; conversationId: string;
return required.devices.every(d => Array.isArray(devices) && devices.includes(d))
}
const builder = review ? reviewedBuilder(conversations.find(c => c.id === group.reviewOf), agents, list(state.starts), policy) : null
- // Another engine counts only on a machine the task may run on, and that its access lets take this project's work.
- const teamRefused = (p: Probe) => { const why = machines.get(p.machineId)?.pool?.teammatesRefused; return typeof why === 'string' && p.refusals.includes(why) }
- const otherFamily = otherFamilyReviews(probes.filter(p => !outside(p.machineId) && !teamRefused(p)), builder, rules, Date.now())
const step = finite(object(group.stepUp).floor) ? { floor: object(group.stepUp).floor as number } : null
for (const [i, p] of probes.entries()) {
const refusals = [...(outside(p.machineId) ? [ELSEWHERE] : []), ...(p.kind === 'member' && !checked(p.agentId) ? [UNCHECKED_DEVICE] : []),
- ...(review ? reviewRefusals(p, builder, otherFamily) : []), ...stepUpRefusals(p, step)]
+ ...(review ? reviewRefusals(p, builder) : []), ...stepUpRefusals(p, step)]
if (refusals.length) probes[i] = { ...p, refusals: [...p.refusals, ...refusals] }
}
// Picks started or assigned and still at work hold part of their account's quota; the log, and so this, is per Swarm.
@@ -346,9 +341,7 @@ export async function routeTask(input: { tabId: string; conversationId: string;
choice.excluded.push(...offlineModels(state, policy, assessment, review))
// The task stays in the Lead's queue rather than going where it cannot be done.
if ('error' in choice) return { ...choice, leftOut: leftOut(choice.excluded, []), ...required.machines || required.devices.length ? { waiting: true, detail: WAITING } : {} }
- const decided = decide(choice)
- // A review on its Builder's own engine says why first (Lead, 2026-10-30); the server writes it on the decision and the brief.
- const verdict = review && !otherFamily && sameFamily(decided.pick, builder) ? { ...decided, why: `${SAME_ENGINE}. ${decided.why}` } : decided
+ const verdict = decide(choice)
const operationId = `route-${newId()}`
const record = (shape: RecordShape) => scoped({ action: 'command', operationId,
command: { type: 'route.record', conversationId: input.conversationId, decision: recordOf(choice, verdict, assessment, policy, shape) } })
@@ -405,7 +398,7 @@ function reviewedBuilder(reviewed: Json | undefined, agents: Json[], starts: Jso
const ran = object(agent?.configuration ?? assignment.configuration), engine = String(ran.engine)
const quality = gridModel ? gridQuality(policy, gridModel, text(agent?.gridName) ?? '')
: rateFor(policy, engine, text(ran.model), text(ran.effort), agent?.engineDefault === true).quality
- return { engine, ...(gridModel ? { gridModel } : {}), quality }
+ return { engine, ...(gridModel ? { gridModel } : {}), quality, ...(typeof assignment.agentId === 'string' ? { agentId: assignment.agentId } : {}) }
}
/** The next two rows, and the best row of every other machine, so the Lead can choose another machine with an overrideReason. */
@@ -556,20 +549,18 @@ async function probeMachine(machineId: string, { name: machineName, status, acco
...needs.tools.map(t => requiredToolReason(t, tools[t], object(observed.toolProbeErrors)[t])).filter((reason): reason is string => reason !== null),
...(needs.devices.length ? ['Required devices have not been reported.'] : []),
...unready.all, ...(unready.push ? [unready.push] : []), ...(stuck ? [STALLED] : [])]
- // What keeps any agent of an engine from starting here soon, whatever its quota (route.ts otherFamilyReviews).
- const unable = (engine: string) => { const why = blocked[0] ?? unready.engines[engine]; return why ? { cannotStart: why } : {} }
return [...members.map(m => {
const engine = String(object(m.configuration).engine), allowance = quota(engine)
const running = Array.isArray(observed.runningHarnessIds) ? observed.runningHarnessIds.includes(m.harnessId) : null
return { ...memberProbe(m, fresh ? [...memberRefusals(running, allowance, needs.tools, needs.devices, tools, object(observed.devices), object(observed.toolProbeErrors)),
...teammates(m.contributorId), ...(unready.push ? [unready.push] : [])] : [OFFLINE],
- allowance, null, fresh && running === null), ...unable(engine) }
+ allowance, null, fresh && running === null) }
}),
...models.map(m => ({ ...newProbe(m, [...newReasons, ...(unready.engines[m.engine] ? [unready.engines[m.engine]!] : []),
...(quota(m.engine).leftPercent === 0 ? ['Subscription exhausted.'] : [])], quota(m.engine), fresh && quota(m.engine).known,
{ agents: Array.isArray(observed.runningHarnessIds) ? observed.runningHarnessIds.length : null,
freeMemoryBytes: finite(resources.memoryTotalBytes) && finite(resources.memoryUsedBytes) ? resources.memoryTotalBytes - resources.memoryUsedBytes : null,
- hasFolder: finite(resources.projectDiskFreeBytes) }), ...unable(m.engine) }))]
+ hasFolder: finite(resources.projectDiskFreeBytes) }) }))]
}
// The account says this machine is off, so nothing there can run or be asked.
if (account && status === 'offline') return [...members.map(m => memberProbe(m, [OFFLINE])), ...offline()]
diff --git a/cli/src/superTabs/service.ts b/cli/src/superTabs/service.ts
index 0ecdff4f4..1e066e68e 100644
--- a/cli/src/superTabs/service.ts
+++ b/cli/src/superTabs/service.ts
@@ -73,7 +73,7 @@ const HELP = {
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' },
- command: 'command OPERATION_ID JSON: send one of the commands below. The JSON is one argument: when it holds quotes, put - in its place and send it on stdin (command OPERATION_ID - <<\'JSON\' … JSON). Reuse exactly the same ID and JSON after an interrupted request. On Custom skills, work.assign takes "roleId" too, a role of the agent\'s kind. When your assignment needs a person to decide, set work.status needs_human; when you cannot go on, blocked. Set working again once it moves. rule.set and rule.remove change one project\'s routing rules: only the project owner does (naming projectId), or that project\'s Lead passing on the project owner\'s request, with askedIn naming the project owner\'s message in that project\'s chat. project.skills switches a project between the Default, Harness orchestration and Custom skills (Custom once its owner has made the project\'s roles): only its project owner does, or its Lead passing on that owner\'s own chat message, with askedIn naming it. tab.tidy turns off, or back on, the Swarm\'s tidying: workers idle for 15 minutes stop and finished groups archive once their pull requests are merged or closed. Only the Swarm owner does, or a Lead passing on the owner\'s own chat message, with askedIn naming it. Two failed starts in a row suspend an engine on a machine for up to 6 hours (the route says so); machine.engineResume offers it there again: only the machine\'s owner does, or the Lead passing on the owner\'s chat message, with askedIn naming it. A start, assignment or route that breaks a hard rule (forbidModel, machines, minEffort) is refused for agents; preferEngine, preferIdle and noGridFirst only rank. Low-risk work that is not a review ranks models on the Swarm\'s grid first unless the owner set noGridFirst: low-difficulty work, and medium work of kind docs, copy, tests, fixtures, fix or refactor (a grid model rated 2, such as Kimi K3 or DeepSeek v4.1). A review never runs on a grid model, below quality 2 or on the reviewed Builder\'s engine. When a grid attempt\'s first review says Ready no, or its grid host never starts the agent, the Swarm closes it and steps the task up (no grid and quality 2, then quality 3, at most twice) and tells you: route it again, and the route and the server keep to the new floor.',
+ command: 'command OPERATION_ID JSON: send one of the commands below. The JSON is one argument: when it holds quotes, put - in its place and send it on stdin (command OPERATION_ID - <<\'JSON\' … JSON). Reuse exactly the same ID and JSON after an interrupted request. On Custom skills, work.assign takes "roleId" too, a role of the agent\'s kind. When your assignment needs a person to decide, set work.status needs_human; when you cannot go on, blocked. Set working again once it moves. rule.set and rule.remove change one project\'s routing rules: only the project owner does (naming projectId), or that project\'s Lead passing on the project owner\'s request, with askedIn naming the project owner\'s message in that project\'s chat. project.skills switches a project between the Default, Harness orchestration and Custom skills (Custom once its owner has made the project\'s roles): only its project owner does, or its Lead passing on that owner\'s own chat message, with askedIn naming it. tab.tidy turns off, or back on, the Swarm\'s tidying: workers idle for 15 minutes stop and finished groups archive once their pull requests are merged or closed. Only the Swarm owner does, or a Lead passing on the owner\'s own chat message, with askedIn naming it. Two failed starts in a row suspend an engine on a machine for up to 6 hours (the route says so); machine.engineResume offers it there again: only the machine\'s owner does, or the Lead passing on the owner\'s chat message, with askedIn naming it. A start, assignment or route that breaks a hard rule (forbidModel, machines, minEffort) is refused for agents; preferEngine, preferIdle and noGridFirst only rank. Low-risk work that is not a review ranks models on the Swarm\'s grid first unless the owner set noGridFirst: low-difficulty work, and medium work of kind docs, copy, tests, fixtures, fix or refactor (a grid model rated 2, such as Kimi K3 or DeepSeek v4.1). A review never runs on a grid model or below quality 2, and never by the agent that built the work; any engine reviews any build. When a grid attempt\'s first review says Ready no, or its grid host never starts the agent, the Swarm closes it and steps the task up (no grid and quality 2, then quality 3, at most twice) and tells you: route it again, and the route and the server keep to the new floor.',
commands: [
{ type: 'project.report', projectId: 'PROJECT', through: { GROUP: 214031 }, text: 'What changed, what is blocked, and what comes next. Use null when nothing merits repeating.' },
{ type: 'project.repository', projectId: 'PROJECT', repositoryUrl: 'https://github.com/OWNER/REPOSITORY' },
diff --git a/docs/swarms.md b/docs/swarms.md
index 1ece74fe3..7e036a78d 100644
--- a/docs/swarms.md
+++ b/docs/swarms.md
@@ -439,13 +439,14 @@ number and why) is kept on the attempt and its route decision.
**Reviews.** A review never runs on a grid model or on a model the policy rates
below 2. A model the policy does not name, a small Codex variant such as a mini
or nano among them, is rated 1; an agent launched on its engine's own model is
-rated by that engine's `default` row. A review runs on another engine than the
-reviewed Builder's while a strong Reviewer of another engine can run in the
-Swarm (a Builder on a grid model counts as that model's family). A Swarm with
-one engine keeps its automatic reviews: the Builder's own engine reviews at its
-top tier (quality 3) only, and the route decision records why. The server
-refuses such a start, assignment or pick from an agent, whatever the soft rules
-say, and lets a person through with a warning.
+rated by that engine's `default` row. Any engine reviews any build, the
+Builder's own included (Ken, 2026-10-30: a Reviewer is a session of its own
+with fresh context, so its strength is what counts), and a review never waits
+for another engine's quota. The agent that built the work never reviews it.
+The route holds a Reviewer to the Builder's strength where one can run, and the
+owner's preferred engine for kind `review` ranks the rest. The server refuses
+such a start, assignment or pick from an agent, whatever the soft rules say,
+and lets a person through with a warning.
Design:
diff --git a/mobile/test/swarm/swarm_fixture.dart b/mobile/test/swarm/swarm_fixture.dart
index 3da74de94..d4f251d3e 100644
--- a/mobile/test/swarm/swarm_fixture.dart
+++ b/mobile/test/swarm/swarm_fixture.dart
@@ -370,6 +370,14 @@ class MemorySwarmHomeKey implements SwarmHomeKey {
}
}
+/// Waits until every save [cache] has under way is done: an inbox keeps its
+/// Home in the background (a temp file, then a rename), so a test that ends
+/// right after a read would have its folder deleted mid-save. The cache does
+/// one thing at a time, so a read of [account]'s Home answers after them.
+/// Real time only: under a widget test's fake clock it would never answer.
+Future<void> homeSaved(SwarmHomeCache cache, {String account = me}) =>
+ cache.read(account);
+
/// A kept Home in a folder of its own, gone after the test.
SwarmHomeCache memoryHomeCache() {
final dir = Directory.systemTemp.createTempSync('swarm-home');
diff --git a/mobile/test/swarm/swarm_home_inbox_test.dart b/mobile/test/swarm/swarm_home_inbox_test.dart
index 956fd2bd0..0c21c62e4 100644
--- a/mobile/test/swarm/swarm_home_inbox_test.dart
+++ b/mobile/test/swarm/swarm_home_inbox_test.dart
@@ -210,6 +210,8 @@ void main() {
expect(i.needs.whereType<SwarmWorkNeed>(), hasLength(2));
expect(news, isEmpty);
+ // The read is kept in the background: its folder goes only after.
+ await homeSaved(cache);
});
test('a Swarm off the list leaves the Home kept at once', () async {