Skip to content

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

Swarm routing: simple work goes to cheaper grid models first, with model and first-review stats (#1808)

0xken150b7bef85edc7
diff --git a/backend/integration/superTabs.test.ts b/backend/integration/superTabs.test.ts
index 5b2cc52df..b644314e0 100644
--- a/backend/integration/superTabs.test.ts
+++ b/backend/integration/superTabs.test.ts
@@ -797,6 +797,40 @@ describe('since when a worker is down', () => {
})
describe('Super Tabs on a real Mongo replica set', () => {
+ it('records a grid worker\'s model on every assignment, after its start is finished and no longer loaded', async () => {
+ // Review of #1808: the run read the start, which a command does not load once the start is finished, so an assigned or
+ // reused Kimi worker counted as a subscription run.
+ const tab = (await store.create(owner, randomUUID(), 'Grid pool')).id
+ const invitation = await run(tab, { type: 'invite.create', email: host.email, role: 'collaborator', conversationId: 'lead' })
+ await run(tab, { type: 'invite.accept', inviteId: invitation.result.inviteId as string }, host)
+ await db.machine.create({ data: { machineId: 'grid-host', userId: host.sub, apiKey: 'fixture-grid-host', managerId: 'fixture', autonomousEnv: 'prod', authMode: 'remote' } })
+ const team = await teamMachine('grid-host')
+ await run(tab, { type: 'machine.contribute', machineId: 'grid-host', name: 'Grid laptop', cwd: '/project', engines: ['claude'], maxAgents: 2 }, host)
+ const grid = (await store.read(owner, tab)).state.localModels!.grid
+ const generation = (await poolRows(store, host, 'grid-host'))[0]!.machine.generation
+ await store.observeMachine(team.session, tab, 'grid-host', { generation, resources: { cpuPercent: 10, memoryTotalBytes: 32e9, memoryUsedBytes: 4e9,
+ diskFreeBytes: 120e9, diskTotalBytes: 500e9, projectDiskFreeBytes: 120e9, deviceType: 'Laptop', chip: 'Fixture CPU', os: 'macOS', gpuPercent: null },
+ quotas: [], tools: { git: true }, runningHarnessIds: [], stoppedHarnessIds: [], privacy: team.privacy,
+ localModels: [{ grid, model: 'moonshotai/kimi-k3', name: 'Kimi K3', kind: 'api' }] })
+ const group = String((await run(tab, { type: 'conversation.create', title: 'Small fix', brief: 'Fix it.',
+ checks: [{ description: 'Independent review', independent: true }] })).result.conversationId)
+ const startId = String((await run(tab, { type: 'agent.start', request: { conversationId: group, machineId: 'grid-host', engine: 'claude', name: 'Builder',
+ cwd: '/project', worktree: true, gridModel: 'moonshotai/kimi-k3', gridName: grid,
+ requirements: { memoryBytes: 0, diskBytes: 0, maxCpuPercent: 100, tools: [], devices: [], quotaRequired: false } } })).result.startId)
+ const hostRun = (command: Command) => store.execute(host, tab, { operationId: randomUUID(), command }, undefined, 'grid-host')
+ await hostRun({ type: 'agent.startDispatch', startId })
+ const agentId = String((await hostRun({ type: 'agent.started', startId, harnessId: 'grid-builder',
+ configuration: { engine: 'claude', model: null, effort: null, contextWindow: null, engineVersion: null } })).result.agentId)
+ await hostRun({ type: 'agent.startSettled', startId, warning: null })
+ const runs = async () => (await storedState(tab)).conversations.find(c => c.id === group)!.ledger!.runs!.map(r => [r.model, r.grid])
+ await run(tab, { type: 'work.assign', conversationId: group, agentId })
+ expect(await runs()).toEqual([['moonshotai/kimi-k3', true]])
+ const first = (await store.read(owner, tab)).state.conversations.find(c => c.id === group)!.assignment!.id
+ await run(tab, { type: 'work.cancel', conversationId: group, assignmentId: first, reason: 'Again.' })
+ await run(tab, { type: 'work.assign', conversationId: group, agentId })
+ expect(await runs()).toEqual([['moonshotai/kimi-k3', true], ['moonshotai/kimi-k3', true]])
+ })
+
it('contributes project capacity without sharing the computer and fences host execution', async () => {
const tab = (await store.create(owner, randomUUID(), 'Machine pool')).id
const invitation = await run(tab, { type: 'invite.create', email: host.email, role: 'collaborator', conversationId: 'lead' })
diff --git a/backend/src/superTabs/commands.test.ts b/backend/src/superTabs/commands.test.ts
index a6e8bf73d..21c0efe19 100644
--- a/backend/src/superTabs/commands.test.ts
+++ b/backend/src/superTabs/commands.test.ts
@@ -1645,6 +1645,13 @@ describe('the owner\'s rules, after review', () => {
expect(byHand.messages[0]).toMatchObject({ text: 'owner added worker anyway. The owner\'s rule "No test model." rules out Codex test-model.' })
expect(f.run({ type: 'conversation.agent', conversationId: 'lead', agentId: f.worker, present: false, lead: false }, f.leadActor).messages).toEqual([])
})
+ it('keeps the owner\'s opt-out from grid models first, which only ranks and refuses no start', () => {
+ const f = routed()
+ f.run(set({ kind: 'noGridFirst' }, 'Subscriptions first.'))
+ expect(f.state.rules!.map(r => r.rule)).toEqual([{ kind: 'noGridFirst' }])
+ expect(f.run({ type: 'agent.start', request: request(), ...via } as Command, f.leadActor, { contribution: f.contribution, ...decisionIn() }).result.startId).toEqual(expect.any(String))
+ expect(() => f.run(set({ kind: 'noGridFirst', engine: 'claude' }))).toThrow()
+ })
it('does not launch a start recorded before a rule, unless a person chose it', () => {
const f = routed()
const startId = f.run({ type: 'agent.start', request: request(), ...via } as Command, f.leadActor, { contribution: f.contribution, ...decisionIn() }).result.startId as string
diff --git a/backend/src/superTabs/commands.ts b/backend/src/superTabs/commands.ts
index c845ed611..4ae571b40 100644
--- a/backend/src/superTabs/commands.ts
+++ b/backend/src/superTabs/commands.ts
@@ -17,7 +17,7 @@ import { loseTasks, renewLease, renewOwnTask } from './liveness.js'
import { digestStartsAfter, knownTimeZone } from './digest.js'
import { credentialResult, redactCredentials, type CredentialKind } from './credentials.js'
import { dirtyGroups, reportGroups, summarize } from './projectUpdates.js'
-import { LEDGER_WEEKS, PULL_REQUEST_URL, recordAnswer, recordAsked, recordMerged, recordStatus } from './leaderboard/record.js'
+import { LEDGER_WEEKS, PULL_REQUEST_URL, recordAnswer, recordAsked, recordMerged, recordReview, recordRun, recordStatus } from './leaderboard/record.js'
import { WEEK_MS } from './leaderboard/week.js'
import { agentKind, agentProjectId, audienceOf, agentSetRole, canReadProject, deleteProject, markConfidential, requireSingleRegistration, groupProject, inviteLanding, ledProject, manageProject, MAX_ROLES, mutableProjects, placeRules, projectMembers, projectOf, projectRules, projectsOf, readAgent, readConversation, readProject, roleVersion, sameProject, sharedWithLeads, SKILL_SET_NAMES, skillSetOf, type ProjectRole, type RoleKind, type SwarmProject } from './projects.js'
@@ -1291,6 +1291,7 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
machineOwnerId: start.machineOwnerId, contributorId: start.contributorId, membershipGeneration: start.membershipGeneration,
hostGrant: start.hostGrant, name: start.request.name, configuration: command.configuration, configurationVersion: operationId,
...(start.request.role ? { role: start.request.role } : {}), ...(start.request.roleId ? { roleId: start.request.roleId } : {}),
+ ...(start.request.gridModel ? { gridModel: start.request.gridModel } : {}),
...(command.startedSession ? { startedSession: { ...command.startedSession, creationId: start.creationId } } : {}) })
group.agentIds.push(agentId)
start.harnessId = command.harnessId
@@ -1328,8 +1329,9 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
}
target.harnessId = command.harnessId
target.replacement = { previousHarnessId: command.previousHarnessId, harnessId: command.harnessId }
- // A new terminal is not the session that lost its task.
+ // A new terminal is not the session that lost its task, nor one started on a grid model: it reports its own.
delete target.lostTask
+ delete target.gridModel
target.configuration = command.configuration
target.configurationVersion = operationId
if (command.startedSession) target.startedSession = command.startedSession
@@ -1672,6 +1674,7 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
group.assignment = { id: operationId, agentId: worker.id, status: 'working', configuration: structuredClone(worker.configuration),
execution: { machineId: worker.machineId, harnessId: worker.harnessId, machineOwnerId: worker.machineOwnerId }, result: null }
renewLease(group.assignment, context.now)
+ recordRun(state, group, group.assignment, worker, context.now)
group.checks.forEach(c => { c.evidence = null; c.passedBy = null })
result.assignmentId = operationId
let routeNote: { decisionId: string; text: string } | null = null, personChose = false
@@ -1793,6 +1796,7 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
if (check.independent && actor.kind === 'agent' && actor.agentId === group.assignment.agentId) fail('INDEPENDENT_REVIEW', 'Another agent or a person must perform this check.')
check.evidence = command.evidence
check.passedBy = command.passed ? actorKey(actor) : null
+ recordReview(group, check, command.passed)
if (actor.kind === 'agent') renewOwnTask(group, actor.agentId, context.now)
break
}
diff --git a/backend/src/superTabs/leaderboard/contract.ts b/backend/src/superTabs/leaderboard/contract.ts
index a5affbe30..fdd3ed5a4 100644
--- a/backend/src/superTabs/leaderboard/contract.ts
+++ b/backend/src/superTabs/leaderboard/contract.ts
@@ -23,6 +23,11 @@ export interface PersonScore {
export interface WeekGoal { shipped: number; points: number; medianAskToShipMs: number | null }
+/** A week's attempts at requests (never reviews) and how many ran on a model served on the Swarm's grid; of those whose
+ * work had a review verdict, how many passed the first one, grid and subscription apart (roadmap, Dec: about 30% of work on
+ * cheaper models without lower quality). */
+export interface ModelShare { attempts: number; grid: number; reviewed: { grid: number; subscription: number }; passedFirst: { grid: number; subscription: number } }
+
export interface Leaderboard {
projectId: string
week: number
@@ -32,4 +37,6 @@ export interface Leaderboard {
people: PersonScore[]
/** Agents waiting on a person now: how many per person, in name order. Never ranked, never in the points. */
waiting: { total: number; people: Array<{ personId: string; count: number; conversationIds: string[] }> }
+ /** Absent from a backend before it. */
+ models: { thisWeek: ModelShare; lastWeek: ModelShare }
}
diff --git a/backend/src/superTabs/leaderboard/record.test.ts b/backend/src/superTabs/leaderboard/record.test.ts
index d0b1b17af..42bc13f77 100644
--- a/backend/src/superTabs/leaderboard/record.test.ts
+++ b/backend/src/superTabs/leaderboard/record.test.ts
@@ -381,3 +381,87 @@ describe('who unblocks waiting work', () => {
expect(f.group(id).ledger?.unblocks?.map(u => u.at)).toEqual([4 * week + 2_000, 6 * week + 2_000])
})
})
+
+describe('the model behind each assignment, and its first review (roadmap, Dec: about 30% of work on cheaper models)', () => {
+ const independent = [{ description: 'Works', independent: false }, { description: 'Independent review', independent: true }]
+ /** Reads a check by its kind, so the order of the checks does not matter. */
+ const verdict = (f: ReturnType<typeof fixture>, id: string, assignmentId: string, passed: boolean, isIndependent = true, actor: Actor = owner) => {
+ const check = f.group(id).checks.find(c => c.independent === isIndependent)!
+ f.run({ type: 'work.check', conversationId: id, assignmentId, checkId: check.id, passed, evidence: 'rev abc' }, actor)
+ }
+
+ it('records the engine and model each assignment runs on', () => {
+ const f = fixture()
+ f.at(5_000)
+ const id = f.create(owner, { checks: independent })
+ const { assignmentId } = f.assign(id)
+ expect(f.group(id).ledger!.runs).toEqual([{ assignmentId, engine: 'claude', model: 'opus', at: 5_000 }])
+ })
+
+ it('names the grid model from the start of an agent from before agents kept it, while that start is loaded', () => {
+ const f = fixture()
+ const id = f.create(owner, { checks: independent })
+ const worker = f.add('grid-worker', id)
+ f.state.starts = [{ id: 's1', creationId: 'c1', actorKey: 'agent:lead', contributorId: 'owner', membershipGeneration: 'g', machineOwnerId: 'host-owner',
+ hostGrant: null, harnessId: 'grid-worker', dispatched: true, error: null,
+ request: { conversationId: id, machineId: 'host', engine: 'claude', model: 'default', effort: 'default', name: 'Builder', cwd: '/repo', worktree: true,
+ gridModel: 'moonshotai/kimi-k3', gridName: 'swarm-0123456789ab',
+ requirements: { memoryBytes: 1, diskBytes: 1, maxCpuPercent: 80, tools: [], devices: [], quotaRequired: false } } }]
+ const { assignmentId } = f.assign(id, worker)
+ expect(f.group(id).ledger!.runs).toEqual([{ assignmentId, engine: 'claude', model: 'moonshotai/kimi-k3', grid: true, at: 1_000 }])
+ })
+
+ it('keeps the first verdict on an independent check as the assignment\'s first review, and ignores later and other checks', () => {
+ const f = fixture()
+ const id = f.create(owner, { checks: independent })
+ const { assignmentId } = f.assign(id)
+ verdict(f, id, assignmentId, true, false)
+ expect(f.group(id).ledger!.runs![0]).not.toHaveProperty('firstReview')
+ verdict(f, id, assignmentId, false)
+ verdict(f, id, assignmentId, true)
+ expect(f.group(id).ledger!.runs![0]).toMatchObject({ assignmentId, firstReview: false })
+ // A new attempt is reviewed on its own.
+ f.run({ type: 'work.cancel', conversationId: id, assignmentId, reason: 'Again.' })
+ const second = f.assign(id)
+ verdict(f, id, second.assignmentId, true)
+ expect(f.group(id).ledger!.runs!.map(r => [r.assignmentId, r.firstReview])).toEqual([[assignmentId, false], [second.assignmentId, true]])
+ })
+
+ it('passes a first review only when every independent check passed its first verdict, and later repairs never rewrite a failure', () => {
+ // Review of #1808: two independent checks, the first passed and the second failed, counted as a pass.
+ const two = [{ description: 'Code review', independent: true }, { description: 'Security review', independent: true }]
+ const f = fixture()
+ const id = f.create(owner, { checks: two })
+ const { assignmentId } = f.assign(id)
+ const [code, security] = f.group(id).checks
+ const check = (checkId: string, passed: boolean) =>
+ f.run({ type: 'work.check', conversationId: id, assignmentId, checkId, passed, evidence: 'rev abc' })
+ check(code!.id, true)
+ // One check still waits for its verdict: the review is not over.
+ expect(f.group(id).ledger!.runs![0]).not.toHaveProperty('firstReview')
+ check(security!.id, false)
+ check(security!.id, true)
+ check(code!.id, false)
+ check(code!.id, true)
+ expect(f.group(id).ledger!.runs![0]).toMatchObject({ firstReview: false, firstVerdicts: { [code!.id]: true, [security!.id]: false } })
+ const g = fixture()
+ const both = g.create(owner, { checks: two })
+ const attempt = g.assign(both).assignmentId
+ for (const c of g.group(both).checks) g.run({ type: 'work.check', conversationId: both, assignmentId: attempt, checkId: c.id, passed: true, evidence: 'rev abc' })
+ expect(g.group(both).ledger!.runs![0]).toMatchObject({ firstReview: true })
+ })
+
+ it('keeps the last 20 assignments of a group', () => {
+ const f = fixture()
+ const id = f.create(owner, { checks: independent })
+ const worker = f.add('worker', id)
+ let first = ''
+ for (let i = 0; i < 21; i++) {
+ const { assignmentId } = f.assign(id, worker)
+ if (i === 0) first = assignmentId
+ f.run({ type: 'work.cancel', conversationId: id, assignmentId, reason: 'Again.' })
+ }
+ expect(f.group(id).ledger!.runs).toHaveLength(20)
+ expect(f.group(id).ledger!.runs!.map(r => r.assignmentId)).not.toContain(first)
+ })
+})
diff --git a/backend/src/superTabs/leaderboard/record.ts b/backend/src/superTabs/leaderboard/record.ts
index 901f2b9dd..23a23b164 100644
--- a/backend/src/superTabs/leaderboard/record.ts
+++ b/backend/src/superTabs/leaderboard/record.ts
@@ -2,11 +2,17 @@
* What the leaderboard counts, recorded as it happens on the group it happened in (docs/swarms.md, Leaderboard): when a
* request was asked and first shipped, which item waits on a person, and who answered it. Only facts and times, never text.
*/
-import type { Actor, Assignment, Conversation, SuperTabState, WorkStatus } from '../model.js'
+import type { Actor, Agent, Assignment, Check, Conversation, SuperTabState, WorkStatus } from '../model.js'
import { groupProject } from '../projects.js'
import { WEEK_MS } from './week.js'
export interface Unblock { personId: string; at: number; waitedMs: number }
+/** One attempt at a group's work: what it ran on and whether its first review passed (roadmap, Dec: about 30% of work on
+ * cheaper models without lower quality). `grid`: a model served on the Swarm's grid, named by its start, since the engine
+ * reports none of its own. `firstVerdicts`: each independent check's first verdict during this attempt, by check id.
+ * `firstReview`: false once any of them failed, true once every independent check passed its first, absent until then. */
+export interface Run { assignmentId: string; engine: string; model: string | null; grid?: true; at: number
+ firstVerdicts?: Record<string, boolean>; firstReview?: boolean }
/** A group's leaderboard bookkeeping; readers never get it whole (read/views.ts groupView). */
export interface GroupLedger {
askedAt?: number
@@ -20,10 +26,14 @@ export interface GroupLedger {
waiting?: { assignmentId: string; since: number; messageId: string; answeredAt?: number }
/** Answers within the last LEDGER_WEEKS, oldest first. */
unblocks?: Unblock[]
+ /** The last MAX_RUNS attempts, oldest first. */
+ runs?: Run[]
}
/** The leaderboard reads this week and last; a little more keeps a streak and week boundaries safe. */
export const LEDGER_WEEKS = 5
+/** A group is one request; more attempts than this are a stuck task, and the oldest say nothing new. */
+export const MAX_RUNS = 20
/** A shared group is asked when it is opened. A private conversation is chat only and never counts. */
export function recordAsked(group: Conversation, requesterId: string | undefined, now: number): void {
@@ -78,3 +88,27 @@ export function waitsNow(group: Conversation): boolean {
const waiting = group.ledger?.waiting
return group.assignment?.status === 'needs_human' && !(waiting?.assignmentId === group.assignment.id && waiting.answeredAt != null)
}
+
+/** An assignment records the model its agent runs: the grid model its start named, else what its engine reports. An agent
+ * started before it kept its grid model has it only on its start, which is here while that start is not finished. */
+export function recordRun(state: SuperTabState, group: Conversation, assignment: Assignment, worker: Agent, now: number): void {
+ const gridModel = worker.gridModel
+ ?? state.starts?.find(s => s.harnessId === worker.harnessId && s.request.machineId === worker.machineId)?.request.gridModel
+ const run: Run = { assignmentId: assignment.id, engine: assignment.configuration.engine,
+ model: gridModel ?? assignment.configuration.model, ...(gridModel ? { grid: true as const } : {}), at: now }
+ const ledger = group.ledger ??= {}
+ ledger.runs = [...ledger.runs ?? [], run].slice(-MAX_RUNS)
+}
+
+/** Each independent check's first verdict during an attempt is its first review; later verdicts are repairs and never
+ * rewrite it. The attempt passed its first review only when every independent check passed the first time (review of
+ * #1808: one check passing first used to count as a pass while another failed). */
+export function recordReview(group: Conversation, check: Check, passed: boolean): void {
+ const run = group.ledger?.runs?.find(r => r.assignmentId === group.assignment?.id)
+ if (!check.independent || !run) return
+ const verdicts = run.firstVerdicts ??= {}
+ verdicts[check.id] ??= passed
+ const firsts = group.checks.filter(c => c.independent).map(c => verdicts[c.id])
+ if (firsts.includes(false)) run.firstReview = false
+ else if (firsts.every(v => v === true)) run.firstReview = true
+}
diff --git a/backend/src/superTabs/leaderboard/stats.test.ts b/backend/src/superTabs/leaderboard/stats.test.ts
index 9941e696d..9d1f32ee9 100644
--- a/backend/src/superTabs/leaderboard/stats.test.ts
+++ b/backend/src/superTabs/leaderboard/stats.test.ts
@@ -190,3 +190,22 @@ describe('the week asked for', () => {
expect(person(view, 'dee').shipped.count).toBe(1)
})
})
+
+describe('Models: the share of work on the Swarm\'s grid, and how often it passes its first review', () => {
+ const run = (at: number, grid: boolean, firstReview?: boolean) =>
+ ({ assignmentId: `r${++n}`, engine: 'claude', model: grid ? 'moonshotai/kimi-k3' : 'opus', ...(grid ? { grid: true as const } : {}), at,
+ ...(firstReview === undefined ? {} : { firstReview }) })
+ it('counts the week\'s attempts, those on the grid, and first-review passes by kind', () => {
+ const view = board(swarm(), [
+ group({ status: 'done', ledger: { runs: [run(WEEK + HOUR, true, false), run(WEEK + 2 * HOUR, false, true)] } }),
+ group({ status: 'done', ledger: { runs: [run(WEEK + HOUR, true, true), run(LAST + HOUR, true, true)] } }),
+ group({ status: 'working', ledger: { runs: [run(WEEK + HOUR, false)] } }),
+ // A review group's attempts are reviews, not work.
+ group({ status: 'done', reviewOf: 'g0', ledger: { runs: [run(WEEK + HOUR, false, true)] } }),
+ ])
+ expect(view.models).toEqual({
+ thisWeek: { attempts: 4, grid: 2, reviewed: { grid: 2, subscription: 1 }, passedFirst: { grid: 1, subscription: 1 } },
+ lastWeek: { attempts: 1, grid: 1, reviewed: { grid: 1, subscription: 0 }, passedFirst: { grid: 1, subscription: 0 } },
+ })
+ })
+})
diff --git a/backend/src/superTabs/leaderboard/stats.ts b/backend/src/superTabs/leaderboard/stats.ts
index 4fcfacd01..439014891 100644
--- a/backend/src/superTabs/leaderboard/stats.ts
+++ b/backend/src/superTabs/leaderboard/stats.ts
@@ -8,7 +8,7 @@ import { isLeads, type Conversation, type SuperTabState } from '../model.js'
import { canReadProject, projectOf } from '../projects.js'
import { waitedOn, waitsNow } from './record.js'
import { DAY_MS, WEEK_MS } from './week.js'
-import type { Leaderboard, Medal, PersonScore, WeekGoal } from './contract.js'
+import type { Leaderboard, Medal, ModelShare, PersonScore, WeekGoal } from './contract.js'
export const SHIPPED_POINTS = 3
export const UNBLOCK_POINTS = 1
@@ -69,9 +69,20 @@ export function leaderboard({ state, groups, machines: visibleMachines, projectI
goal: { openRequests: requests.filter(open).length, thisWeek: goal(week), lastWeek: goal(week - WEEK_MS) },
people,
waiting: waitingNow(state, shared),
+ models: { thisWeek: modelShare(requests, week), lastWeek: modelShare(requests, week - WEEK_MS) },
}
}
+/** The attempts started in the week starting [start], by the kind of model they ran on. */
+function modelShare(requests: Conversation[], start: number): ModelShare {
+ const runs = requests.flatMap(g => g.ledger?.runs ?? []).filter(r => r.at >= start && r.at < start + WEEK_MS)
+ const reviewed = runs.filter(r => r.firstReview !== undefined)
+ const count = (list: typeof runs, grid: boolean) => list.filter(r => !!r.grid === grid).length
+ const passed = reviewed.filter(r => r.firstReview)
+ return { attempts: runs.length, grid: count(runs, true), reviewed: { grid: count(reviewed, true), subscription: count(reviewed, false) },
+ passedFirst: { grid: count(passed, true), subscription: count(passed, false) } }
+}
+
/** Shared work still to land: not shipped, cancelled, stopped or archived. */
const open = (group: Conversation): boolean => !group.archived && group.ledger?.shippedAt == null
&& !['done', 'cancelled', 'stopped'].includes(group.assignment?.status ?? '')
diff --git a/backend/src/superTabs/model.ts b/backend/src/superTabs/model.ts
index 0f219b037..6aaf36d77 100644
--- a/backend/src/superTabs/model.ts
+++ b/backend/src/superTabs/model.ts
@@ -39,6 +39,9 @@ export interface Agent {
releaseId?: string
/** Captured from the original Swarm launch, never inferred from a later live session with the same id. */
startedSession?: { creationId: string; sessionId: string; createdAt: string }
+ /** The model on the Swarm's grid its start named, which its engine never reports. Kept here because a command does not
+ * load a finished start (parts/load.ts loadActive), and the leaderboard counts every assignment by it (review of #1808). */
+ gridModel?: string
configuration: AgentConfiguration
/** The last configuration operation fences delayed observations, including re-contribution. */
configurationVersion?: string
diff --git a/backend/src/superTabs/rebind.test.ts b/backend/src/superTabs/rebind.test.ts
index b396fb7a8..c42e254a9 100644
--- a/backend/src/superTabs/rebind.test.ts
+++ b/backend/src/superTabs/rebind.test.ts
@@ -29,6 +29,11 @@ describe('Change agent keeps the Swarm member', () => {
expect(changed.cancelledAgents).toEqual([])
expect(f.state.agents[0]!.harnessId).toBe('old')
})
+ it('forgets the grid model the old terminal was started on, since the new one reports its own (review of #1808)', () => {
+ const f = fixture()
+ f.state.agents[0]!.gridModel = 'moonshotai/kimi-k3'
+ expect(f.run().state.agents[0]).not.toHaveProperty('gridModel')
+ })
it('repeating the same replacement is a no-op and cannot roll back newer configuration', () => {
const f = fixture(), changed = f.run().state
changed.agents[0]!.configuration.model = 'opus'
diff --git a/backend/src/superTabs/rules.ts b/backend/src/superTabs/rules.ts
index dd03890ff..30374a78c 100644
--- a/backend/src/superTabs/rules.ts
+++ b/backend/src/superTabs/rules.ts
@@ -14,6 +14,8 @@ export const ruleSchema = z.discriminatedUnion('kind', [
z.object({ kind: z.literal('minEffort'), engine: engine.optional(), effort: z.enum(EFFORTS) }).strict(),
z.object({ kind: z.literal('preferEngine'), taskKind: z.string().regex(/^[a-z][a-z0-9-]{0,39}$/).nullable(), engine }).strict(),
z.object({ kind: z.literal('preferIdle') }).strict(),
+ // Simple work goes to a model on the Swarm's grid first (cli/src/superTabs/route.ts softOf); this owner says not to.
+ z.object({ kind: z.literal('noGridFirst') }).strict(),
])
export const ruleTextSchema = z.string().trim().min(1).max(200)
export const askedInSchema = z.object({ conversationId: id, messageId: id }).strict()
diff --git a/cli/src/superTabs/route.spec.ts b/cli/src/superTabs/route.spec.ts
index d7d98364a..23ed39df2 100644
--- a/cli/src/superTabs/route.spec.ts
+++ b/cli/src/superTabs/route.spec.ts
@@ -589,6 +589,32 @@ describe('local models on the Swarm\'s grid', () => {
expect(LOCAL_NONE).toContain('Manage models')
})
+ describe('first for simple work (roadmap, Dec: about 30% of work on cheaper models)', () => {
+ const simple = a({ difficulty: 'low', risk: 'low', size: 'small' })
+ // Opus on an account whose 5-hour window resets in 20 minutes costs nothing in effect, so it ranked above a free model.
+ const expiring = probe({ machineName: 'mac', model: 'opus', effort: 'high', quality: 3, cost: 3, quota: windows([60, 20 * M], [60, 2 * D]) })
+ const haiku = probe({ machineName: 'mac', model: 'haiku', effort: 'auto', quality: 1, cost: 1, quota: windows([90, 4 * H], [80, 5 * D]) })
+ const idle = probe({ kind: 'member', agentId: 'a1', name: 'Idle', model: 'sonnet', quota: windows([90, 4 * H], [80, 5 * D]) })
+ const grid = local({ machineName: 'mac' })
+ const firstOf = (r: ReturnType<typeof choose>) => ok(r).shown[0]!.gridModel ?? ok(r).shown[0]!.model
+ it('ranks a model on the Swarm\'s grid first for low-difficulty, low-risk work', () => {
+ expect(firstOf(choose([expiring, haiku, grid], policy, simple, NOW))).toBe('qwen3')
+ expect(firstOf(choose([idle, grid], policy, simple, NOW, [], [{ rule: { kind: 'preferIdle' }, text: 'Idle first.' }]))).toBe('qwen3')
+ })
+ it('keeps the policy order for anything harder, riskier or a review', () => {
+ expect(firstOf(choose([expiring, haiku, grid], policy, { ...simple, risk: 'medium' }, NOW))).toBe('opus')
+ expect(firstOf(choose([expiring, haiku, grid], policy, { ...simple, difficulty: 'medium' }, NOW))).toBe('opus')
+ expect(firstOf(choose([expiring, haiku, grid], policy, { ...simple, kind: 'review' }, NOW))).toBe('opus')
+ })
+ it('still puts the owner\'s preferred engine first, and stops when the owner opts out', () => {
+ const codex = probe({ machineName: 'mac', engine: 'codex', model: 'default', effort: 'default', quality: 3, cost: 2, quota: windows([90, 4 * H], [80, 5 * D]) })
+ const prefer = [{ rule: { kind: 'preferEngine', taskKind: null, engine: 'codex' }, text: 'Codex.' } as SwarmRule]
+ expect(firstOf(choose([codex, grid], policy, simple, NOW, [], prefer))).toBe('default')
+ expect(firstOf(choose([codex, local({ machineName: 'mac', engine: 'codex' })], policy, simple, NOW, [], prefer))).toBe('qwen3')
+ expect(firstOf(choose([expiring, grid], policy, simple, NOW, [], [{ rule: { kind: 'noGridFirst' }, text: 'Subscriptions first.' }]))).toBe('opus')
+ })
+ })
+
it('says why a named model the Swarm has is never offered to Builders, rather than to share it', () => {
const llama = { model: 'llama3.2:3b', label: 'llama3.2:3b', kind: 'local' as const, holders: [],
refused: 'llama3.2:3b is too small for a coding agent (about 3B parameters; Builders need 7B or more).' }
diff --git a/cli/src/superTabs/route.ts b/cli/src/superTabs/route.ts
index dcecca03e..10373e33f 100644
--- a/cli/src/superTabs/route.ts
+++ b/cli/src/superTabs/route.ts
@@ -21,6 +21,7 @@ export type Rule =
| { kind: 'minEffort'; engine?: string; effort: string }
| { kind: 'preferEngine'; taskKind: string | null; engine: string }
| { kind: 'preferIdle' }
+ | { kind: 'noGridFirst' }
export interface SwarmRule { rule: Rule; text: string }
export interface PolicyModel { engine: 'claude' | 'codex'; model: string; effort: string; quality: number; cost: number; enabled: boolean }
export interface Policy { version: 1; models: PolicyModel[]; floor: Record<Level, number>; quotaReserve: number; notes: string;
@@ -111,13 +112,17 @@ export function liftEffort(rules: SwarmRule[], engine: string, effort: string):
const least = Math.max(-1, ...rules.flatMap(({ rule }) => rule.kind === 'minEffort' && applies(rule, engine) ? [rank(rule.effort)] : []))
return least < 0 ? effort : EFFORTS[least]
}
-/** The soft rules for this task: the engine preferred for its kind (a rule for the kind before one for every task), and
- * whether idle agents come first. */
-interface Soft { engine: string | null; idle: boolean }
-function softOf(rules: SwarmRule[], kind: string | undefined): Soft {
+/** The soft rules for this task: the engine preferred for its kind (a rule for the kind before one for every task),
+ * whether idle agents come first, and whether a model on the Swarm's grid comes first. */
+interface Soft { engine: string | null; idle: boolean; grid: boolean }
+function softOf(rules: SwarmRule[], a: Assessment): Soft {
const prefer = rules.flatMap(({ rule }) => rule.kind === 'preferEngine' ? [rule] : [])
- const engine = (prefer.find(r => kind && r.taskKind === kind) ?? prefer.find(r => r.taskKind === null))?.engine ?? null
- return { engine, idle: rules.some(r => r.rule.kind === 'preferIdle') }
+ const engine = (prefer.find(r => a.kind && r.taskKind === a.kind) ?? prefer.find(r => r.taskKind === null))?.engine ?? null
+ // Simple work goes to the free models first (roadmap, Dec: about 30% of work on cheaper models without lower quality).
+ // A grid model counts as cost 1 like Haiku, so an expiring 5-hour window or an idle member ranked above it and it was
+ // rarely picked. Reviews keep the other model family, and the owner can opt out.
+ const grid = a.difficulty === 'low' && a.risk === 'low' && a.kind !== 'review' && !rules.some(r => r.rule.kind === 'noGridFirst')
+ return { engine, idle: rules.some(r => r.rule.kind === 'preferIdle'), grid }
}
export function parseAssessment(value: unknown): Assessment | string {
@@ -332,19 +337,20 @@ const runsOut = (w: Measured) => `The ${w.name} window is expected to run out ${
const UNREAD = 'Its quota could not be read in full, and another candidate\'s quota fits this task.'
export const LOCAL_NONE = 'No local model is being served on this Swarm\'s grid. Ask a member to run one or share an API (Manage models, in the Swarm\'s sidebar).'
-/** The fixed order: the owner's preferred engine, an idle member before a new agent and a less busy machine first when the
- * owner prefers idle agents; then the policy order: cheaper in effect, stronger, a model that runs on a machine before one
- * reached through a shared API or another grid, more room on the tightest window, an idle member in the task's repository
- * before a new agent, then by title. */
+/** The fixed order: the owner's preferred engine, a model on the Swarm's grid for simple work, an idle member before a new
+ * agent and a less busy machine first when the owner prefers idle agents; then the policy order: cheaper in effect,
+ * stronger, a model that runs on a machine before one reached through a shared API or another grid, more room on the
+ * tightest window, an idle member in the task's repository before a new agent, then by title. */
function compare(x: Probe & Sized, y: Probe & Sized, soft: Soft): number {
const placed = (p: Probe) => p.kind === 'member' && (p.repo ?? 'same') === 'same' ? 0 : 1
const preferred = (p: Probe) => soft.engine && p.engine !== soft.engine ? 1 : 0
+ const subscription = (p: Probe) => soft.grid && !p.gridModel ? 1 : 0
const fresh = (p: Probe) => soft.idle && p.kind === 'new' ? 1 : 0
const busy = (p: Probe) => soft.idle && p.kind === 'new' ? p.load?.agents ?? 1000 : 0
// On-machine first (owner, 2026-10-24): an API spends a member's key and credits, and a model shared on another grid is
// someone else's machine; at equal cost and strength the Swarm's own engine goes first.
const remote = (p: Probe) => p.gridModel && (p.gridKind === 'api' || p.gridKind === 'shared') ? 1 : 0
- return preferred(x) - preferred(y) || fresh(x) - fresh(y) || busy(x) - busy(y)
+ return preferred(x) - preferred(y) || subscription(x) - subscription(y) || fresh(x) - fresh(y) || busy(x) - busy(y)
|| x.fit.effectiveCost - y.fit.effectiveCost
|| y.quality - x.quality
|| remote(x) - remote(y)
@@ -401,7 +407,7 @@ export function choose(probes: Probe[], policy: Policy, a: Assessment, now: numb
const status = (['fits', 'unknown', 'short'] as const).find(s => sized.some(p => p.fit.status === s))!
excluded.push(...sized.filter(p => p.fit.status !== status).map(p => ({ title: titleOf(p), reason: p.fit.status === 'unknown' ? UNREAD : runsOut(p.tight!) })))
// When every candidate is short, the one expected to get furthest goes first.
- const soft = softOf(rules, a.kind)
+ const soft = softOf(rules, a)
const set = sized.filter(p => p.fit.status === status).sort((x, y) => status === 'short' ? y.fit.coverage! - x.fit.coverage! || compare(x, y, soft) : compare(x, y, soft))
const shown = withEveryMachine(set).map(({ tight, text, ...p }, i) => ({ ...p, id: `c${i}`, title: titleOf(p), label: labelOf({ ...p, tight, text }, now) }))
const first = set[0].tight!
diff --git a/cli/src/superTabs/service.spec.ts b/cli/src/superTabs/service.spec.ts
index 1a2998b7c..436ba29a0 100644
--- a/cli/src/superTabs/service.spec.ts
+++ b/cli/src/superTabs/service.spec.ts
@@ -591,6 +591,12 @@ it('says a server from before rules does not support them, and passes a malforme
expect(await send({ type: 'rule.set', rule: { kind: 'minEffort', effort: 'huge' }, text: 'x' })).not.toMatchObject({ error: 'RULES_UNSUPPORTED' })
})
+it('tells the Lead that simple work ranks grid models first, and how the owner opts out', async () => {
+ const help = (await setup().ask({ action: 'help' }, owner)).help as { commands: unknown[]; command: string }
+ expect(help.commands).toContainEqual(expect.objectContaining({ type: 'rule.set', rule: { kind: 'noGridFirst' } }))
+ expect(help.command).toContain('ranks models on the Swarm\'s grid first unless the owner set noGridFirst')
+})
+
it('documents finished worker decisions and explains an older backend without release support', async () => {
const t = setup()
const help = (await t.ask({ action: 'help' }, owner)).help as { commands: unknown[]; release: string }
diff --git a/cli/src/superTabs/service.ts b/cli/src/superTabs/service.ts
index 1864d16c6..1f95e59f5 100644
--- a/cli/src/superTabs/service.ts
+++ b/cli/src/superTabs/service.ts
@@ -49,7 +49,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. 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. A start, assignment or route that breaks a hard rule (forbidModel, machines, minEffort) is refused for agents; preferEngine and preferIdle only rank.',
+ command: 'command OPERATION_ID JSON: send one of the commands below. 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. A start, assignment or route that breaks a hard rule (forbidModel, machines, minEffort) is refused for agents; preferEngine, preferIdle and noGridFirst only rank. Low-difficulty, low-risk work that is not a review ranks models on the Swarm\'s grid first unless the owner set noGridFirst.',
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' },
@@ -70,6 +70,7 @@ const HELP = {
{ type: 'rule.set', rule: { kind: 'machines', machineIds: ['MACHINE'] }, text: 'Only these machines.', askedIn: { conversationId: 'GROUP', messageId: 'OWNER_MESSAGE' } },
{ type: 'rule.set', rule: { kind: 'preferEngine', taskKind: 'ui', engine: 'codex' }, text: 'Codex for UI work.', askedIn: { conversationId: 'GROUP', messageId: 'OWNER_MESSAGE' } },
{ type: 'rule.set', rule: { kind: 'preferIdle' }, text: 'Reuse idle agents first.', askedIn: { conversationId: 'GROUP', messageId: 'OWNER_MESSAGE' } },
+ { type: 'rule.set', rule: { kind: 'noGridFirst' }, text: 'Subscriptions first, even for simple work.', askedIn: { conversationId: 'GROUP', messageId: 'OWNER_MESSAGE' } },
{ type: 'rule.remove', ruleId: 'RULE', askedIn: { conversationId: 'GROUP', messageId: 'OWNER_MESSAGE' } },
{ type: 'work.assign', conversationId: 'GROUP', agentId: 'AGENT', routeDecisionId: 'DECISION' },
{ type: 'work.status', conversationId: 'GROUP', assignmentId: 'ATTEMPT', status: 'working', result: null },
diff --git a/docs/plans/2026-10-22-swarm-rules-routing.md b/docs/plans/2026-10-22-swarm-rules-routing.md
index 2847cec64..35374c1de 100644
--- a/docs/plans/2026-10-22-swarm-rules-routing.md
+++ b/docs/plans/2026-10-22-swarm-rules-routing.md
@@ -22,6 +22,7 @@ interface Rule {
| { kind: 'minEffort'; engine?: 'claude' | 'codex'; effort: Effort } // hard
| { kind: 'preferEngine'; taskKind: string | null; engine: 'claude' | 'codex' } // soft
| { kind: 'preferIdle' } // soft
+ | { kind: 'noGridFirst' } // soft (2026-10-27)
text: string // the owner's words, 1–200 characters, e.g. "No Haiku, ever."
askedBy: string // the owner's user id
askedIn: { conversationId: string; messageId: string } | null // the owner's message, when a Lead relays it
@@ -49,6 +50,10 @@ The meaning of each rule:
(`"kind":"ui"`). A review group's kind is always `review`.
- **preferIdle** (soft): an idle member ranks before a new agent. Among new agents, a machine with fewer
running agents ranks first.
+- **noGridFirst** (soft, 2026-10-27): turns off grid models first. By default a low-difficulty, low-risk
+ task that is not a review ranks models served on the Swarm's grid (Kimi K3, DeepSeek) before subscription
+ candidates, right after the preferred engine (roadmap, Dec: about 30% of work on cheaper models). The owner
+ opts out with this rule.
Routing already removes an offline machine, a stopping agent (it is busy or refused) and an exhausted
quota. Those stay as they are and are not rules.
diff --git a/docs/plans/2026-10-23-swarm-local-models.md b/docs/plans/2026-10-23-swarm-local-models.md
index fb750a665..50807ae58 100644
--- a/docs/plans/2026-10-23-swarm-local-models.md
+++ b/docs/plans/2026-10-23-swarm-local-models.md
@@ -59,3 +59,43 @@ The ⌘I Models picker made for the Swarm (`SwarmModelsTarget` on `SwarmSearchCo
whose fresh reading lists the model.
- A shared API is never counted as a running local model, so your models can run for the Swarm beside shared APIs.
- A click only selects a row; the preview's button (or Return) acts.
+
+## Grid models first for simple work (2026-10-27)
+
+Roadmap (Dec): about 30% of work runs on cheaper models without lower quality.
+
+- **Routing** (`cli/src/superTabs/route.ts` `softOf`, `compare`): a task of low difficulty and low risk that is not a
+ review ranks a model served on the Swarm's grid above every subscription candidate. Only the owner's preferred engine
+ comes before it, since those are the owner's own words, and a grid model runs on Claude Code or Codex anyway. Hard
+ rules and the policy floor apply first, as before. Without this, a grid model (cost 1, like Haiku) lost to an
+ account whose 5-hour window was about to reset (effective cost 0) and to idle members under `preferIdle`.
+- **Opt-out:** the owner's soft rule `noGridFirst` (backend `rules.ts`). It only ranks and never refuses a start.
+ To stop using grid models entirely, the owner still has the policy's `localModels.enabled`.
+- **Recording** (backend `leaderboard/record.ts`): every `work.assign` appends a run to its group's ledger: the
+ assignment, the engine, the model and the time. The model is the grid model the agent was started on, else the one
+ its engine reports. An agent keeps its grid model from its start (`Agent.gridModel`), because a command does not load
+ a finished start, and loses it when Change agent gives it a new terminal. Each independent check's first verdict
+ during the attempt is kept (`firstVerdicts`), and later repairs never rewrite it. `firstReview` becomes false once any
+ first verdict fails, and true once every independent check passed its first.
+- **Report:** the leaderboard read returns `models` for this week and last week: the attempts at requests, how many
+ ran on the grid, and how many of each kind passed their first review.
+
+### Design
+
+- **Growth:** at most 20 runs per group (`MAX_RUNS`, the oldest are dropped), about 150 bytes each. The runs live and
+ go with their group's ledger. Reviews and private conversations are never counted.
+- **Concurrency:** written inside the command that assigns or checks, under the group part's existing lock. There is
+ no new lock.
+- **Read cost:** the leaderboard already reads the project's groups. Counting their runs adds no read.
+- **Scale:** at 10x (about 3,000 attempts a week) it is still one pass over at most 20 runs per group. The group part
+ size (4 MB limit) would warn first, and 20 runs use under 0.1% of it.
+- **Compatibility:** `models` is a new field in the leaderboard response, and Desktop's parser ignores fields it does
+ not know. A CLI from before this change does not know `noGridFirst` and ranks as before. A backend from before it
+ refuses the rule as invalid.
+- **Migration + rollback:** none. Old groups have no `runs` and count as zero. A rollback leaves `runs` in ledgers,
+ where the old code never reads them.
+- **Audience:** the ledger is never sent to clients (`read/views.ts` strips it). The leaderboard read keeps its
+ per-project access check.
+- **Identity:** N/A because no work runs as anyone. Only the agent's own configuration and start are read.
+- **Failure:** a start the backend no longer holds is recorded with the model its engine reports, never dropped.
+- **Platforms:** backend and CLI only. Desktop shows nothing new yet.