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 v2 (#1784)

0xken1531e49f6b8d63
diff --git a/backend/integration/superTabLeaderboard.test.ts b/backend/integration/superTabLeaderboard.test.ts
new file mode 100644
index 000000000..0f5583b47
--- /dev/null
+++ b/backend/integration/superTabLeaderboard.test.ts
@@ -0,0 +1,146 @@
+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 Fastify, { type FastifyInstance } from 'fastify'
+import type { AuthUser } from '../src/lib/ssoAuth.js'
+import { SuperTabStore } from '../src/superTabs/store.js'
+import { superTabRoutes } from '../src/routes/superTabs.js'
+import { errorHandler } from '../src/middlewares/errorHandler.js'
+import { migrateSwarm } from '../src/superTabs/migration/migrate.js'
+import { SwarmReads } from '../src/superTabs/read/service.js'
+import type { SuperTabState } from '../src/superTabs/model.js'
+import { WEEK_MS, weekStart } from '../src/superTabs/leaderboard/week.js'
+import { writeLegacySwarm } from '../scripts/swarm-parts/legacy.js'
+import { NOW, outsider as outsiderActor, owner as ownerActor, peer as peerActor, swarm } from '../src/superTabs/read/fixture.test-support.js'
+
+// A fresh loopback replica set, created here. This suite never reads DATABASE_URL or an existing database.
+let replica: MongoMemoryReplSet
+let db: PrismaClient
+let app: FastifyInstance
+const user = (actor: { userId: string; email: string }): AuthUser => ({ sub: actor.userId, email: actor.email, autonomousEnv: 'prod', role: 'user' })
+const [owner, peer, outsider] = [ownerActor, peerActor, outsiderActor].map(user) as [AuthUser, AuthUser, AuthUser]
+const WEEK = weekStart(NOW), HOUR = 3_600_000
+const PR = 'https://github.com/o/r/pull/9'
+
+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_leaderboard_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 each of [owner, peer, outsider]) await db.user.create({ data: { id: each.sub, externalId: `fixture-${each.sub}`, email: each.email, autonomousEnv: 'prod' } })
+ const store = new SuperTabStore(db)
+ app = Fastify()
+ app.setErrorHandler(errorHandler)
+ // External SSO is replaced with fixture accounts; every permission and transaction below is real.
+ app.addHook('onRequest', async (request, reply) => {
+ const found = [owner, peer, outsider].find(u => `Bearer ${u.sub}` === request.headers.authorization)
+ if (!found) return reply.code(401).send({ success: false })
+ request.user = found
+ })
+ await app.register(superTabRoutes, { store, github: null, reads: new SwarmReads(store, { now: () => NOW }) })
+ await app.ready()
+})
+afterAll(async () => {
+ await app?.close()
+ await db?.$disconnect()
+ await replica?.stop()
+})
+
+/** A Swarm in parts: peer's request shipped this week, peer's request shipped last week and gone dormant, a private chat
+ * that carries a ship record, a private project with its own shipped request, and the owner's work waiting on them. */
+async function scene() {
+ const s = swarm(NOW)
+ s.join(peerActor)
+ s.join(outsiderActor)
+ const lead = s.add('lead-harness', 'lead', true)
+ const secret = s.run({ type: 'project.create', name: 'Secret', visibility: 'private', brief: '' }).projectId as string
+ const fresh = s.group('Fresh'), old = s.group('Old'), chat = s.group('Peer and PM'), hidden = s.group('Hidden', secret), waiting = s.group('Waiting')
+ const worker = s.add('worker-harness', waiting)
+ s.run({ type: 'work.assign', conversationId: waiting, agentId: worker })
+ s.run({ type: 'work.status', conversationId: waiting, assignmentId: s.state.conversations.find(c => c.id === waiting)!.assignment!.id,
+ status: 'needs_human', result: 'Flag?' }, { kind: 'agent', agentId: worker, machineOwnerId: `${owner.sub}-machine` })
+ s.edit(state => {
+ const done = { id: 'done', agentId: worker, status: 'done' as const, result: PR, configuration: state.agents[0]!.configuration,
+ execution: { machineId: 'host', harnessId: 'h', machineOwnerId: owner.sub } }
+ const ship = (id: string, shippedAt: number) => Object.assign(state.conversations.find(c => c.id === id)!,
+ { requesterId: peer.sub, assignment: done, pullRequestUrls: [PR], ledger: { askedAt: shippedAt - 2 * HOUR, shippedAt } })
+ ship(fresh, NOW - HOUR)
+ ship(old, WEEK - 2 * 86_400_000)
+ ship(chat, NOW - HOUR)
+ ship(hidden, NOW - HOUR)
+ const generation = state.people.find(p => p.id === peer.sub)!.generation
+ state.conversations.find(c => c.id === chat)!.audience = { people: [{ id: peer.sub, generation }] }
+ Object.assign(state.conversations.find(c => c.id === old)!, { dormant: true, lastActivityAt: new Date(WEEK - 2 * 86_400_000).toISOString() })
+ })
+ const tabId = `tab-${randomUUID()}`
+ const state = { ...structuredClone(s.state), id: tabId } as SuperTabState
+ await writeLegacySwarm(db, { state, revision: 50 })
+ const report = await migrateSwarm(db, tabId, { now: () => NOW - 60_000 })
+ if (!report.ok) throw new Error(report.error)
+ return { tabId, lead, secret, fresh, old, chat, waiting }
+}
+const get = async (url: string, as: AuthUser = owner) => {
+ const response = await app.inject({ method: 'GET', url, headers: { authorization: `Bearer ${as.sub}` } })
+ return { status: response.statusCode, body: response.json() as { data: any; error?: { code: string; message: string } } }
+}
+const score = (body: { data: { people: Array<{ personId: string }> } }, id: string) => body.data.people.find(p => p.personId === id) as any
+
+describe('the leaderboard read', () => {
+ it('counts this week\'s shipped request for its requester, never a private chat\'s', async () => {
+ const s = await scene()
+ const { status, body } = await get(`/api/super-tabs/${s.tabId}/leaderboard?projectId=lead`, peer)
+ expect(status).toBe(200)
+ expect(body.data).toMatchObject({ projectId: 'lead', week: WEEK })
+ expect(score(body, peer.sub)).toMatchObject({ points: 3, medal: 'gold', shipped: { count: 1, medianAskToShipMs: 2 * HOUR } })
+ expect(body.data.goal.thisWeek.shipped).toBe(1)
+ expect(JSON.stringify(body.data)).not.toContain(s.chat)
+ })
+
+ it('reads last week from the groups that went dormant since', async () => {
+ const s = await scene()
+ const { body } = await get(`/api/super-tabs/${s.tabId}/leaderboard?projectId=lead&week=${WEEK - WEEK_MS}`)
+ expect(score(body, peer.sub).shipped.count).toBe(1)
+ expect(body.data.goal.thisWeek.shipped).toBe(1)
+ })
+
+ it('shows who agents wait on as a count, with the conversation to answer in', async () => {
+ const s = await scene()
+ const { body } = await get(`/api/super-tabs/${s.tabId}/leaderboard?projectId=lead`, outsider)
+ expect(body.data.waiting).toEqual({ total: 1, people: [{ personId: owner.sub, count: 1, conversationIds: [s.waiting] }] })
+ })
+
+ it('keeps a private project\'s board to the people who read it', async () => {
+ const s = await scene()
+ expect((await get(`/api/super-tabs/${s.tabId}/leaderboard?projectId=${s.secret}`, outsider)).status).toBe(404)
+ const own = await get(`/api/super-tabs/${s.tabId}/leaderboard?projectId=${s.secret}`, owner)
+ expect(own.body.data.people.map((p: { personId: string }) => p.personId)).toEqual([owner.sub])
+ })
+
+ it('is for people: an agent reading as itself is refused', async () => {
+ const s = await scene()
+ expect((await get(`/api/super-tabs/${s.tabId}/leaderboard?projectId=lead&asAgentId=${s.lead}`)).status).toBe(400)
+ })
+
+ it('refuses a week that is not a Monday, or older than the weeks kept', async () => {
+ const s = await scene()
+ expect((await get(`/api/super-tabs/${s.tabId}/leaderboard?projectId=lead&week=${WEEK + 1}`)).status).toBe(400)
+ expect((await get(`/api/super-tabs/${s.tabId}/leaderboard?projectId=lead&week=${WEEK - 5 * WEEK_MS}`)).status).toBe(400)
+ expect((await get(`/api/super-tabs/${s.tabId}/leaderboard?projectId=lead&week=${WEEK + WEEK_MS}`)).status).toBe(400)
+ })
+
+ it('leaves the ledger out of the groups every reader loads', async () => {
+ const s = await scene()
+ const { body } = await get(`/api/super-tabs/${s.tabId}/parts`, peer)
+ const fresh = body.data.groups.find((g: { key: string }) => g.key === s.fresh)
+ expect(fresh.data.requesterId).toBe(peer.sub)
+ expect(fresh.data).not.toHaveProperty('ledger')
+ })
+})
diff --git a/backend/integration/superTabLiveness.test.ts b/backend/integration/superTabLiveness.test.ts
index b56218d03..8d6e61d34 100644
--- a/backend/integration/superTabLiveness.test.ts
+++ b/backend/integration/superTabLiveness.test.ts
@@ -11,7 +11,7 @@ import { SuperTabStore } from '../src/superTabs/store.js'
import type { Command } from '../src/superTabs/commands.js'
import type { MachineObservation } from '../src/superTabs/machines.js'
import * as parts from '../src/superTabs/parts/index.js'
-import { poolRows } from './hostRows.test-support.js'
+import { assignmentRows, poolRows, rosterRows } from './hostRows.test-support.js'
import { beforeFirstWrite } from './interleave.test-support.js'
import { SwarmReads } from '../src/superTabs/read/service.js'
@@ -159,6 +159,27 @@ describe('work that loses its owner', () => {
expect(await f.lostRows()).toEqual([])
})
+ it('is not lost for a failing model when its host says the model recovered between the time checks\' read and their write', async () => {
+ const f = await swarm()
+ await f.beat(f.clock.now)
+ // An agent whose model alert is on before it has a task: the time checks, not the alert, would lose its next task.
+ const group = String((await f.execute({ type: 'conversation.create', title: 'Second task', brief: 'Do it', checks: [{ description: 'Done', independent: false }] })).result.conversationId)
+ const other = await f.add(group, 'test-host', f.harness.other, 'Other')
+ await f.observe('test-host', [f.harness.worker, f.harness.other])
+ await f.execute({ type: 'agent.alert', agentId: other, alert: 'model', active: true }, host, other)
+ await f.execute({ type: 'work.assign', conversationId: group, agentId: other })
+ // The Lead's poll reads the alert as on; just before it writes the loss, the host reports the model answering again.
+ let raced = false
+ const racing = new SuperTabStore(beforeFirstWrite(db, async () => {
+ if (raced) return
+ raced = true
+ await f.execute({ type: 'agent.alert', agentId: other, alert: 'model', active: false }, host, other)
+ }), () => f.clock.now)
+ await racing.deliveries(host, f.tab, f.lead)
+ expect(raced).toBe(true)
+ expect((await f.timed.read(owner, f.tab)).state.conversations.find(c => c.id === group)!.assignment!.status).toBe('working')
+ })
+
it('is lost at once when the host reports its session stopped, and the Lead is woken with who, why and the last result', async () => {
const f = await swarm()
await f.beat(f.clock.now)
@@ -180,6 +201,55 @@ describe('work that loses its owner', () => {
expect((await f.leadInbox()).some(m => (m.source as { kind?: string }).kind === 'work-lost')).toBe(true)
})
+ // Night shift: a task lost to a usage limit whose screen gave a reset time resumes in that same session after the reset.
+ it('tells the worker\'s host when its lost task resumes, and gives it back to the same session after the reset', async () => {
+ const f = await swarm()
+ const resetAt = new Date(f.clock.now + 30 * MINUTE).toISOString(), lostAt = f.clock.now
+ await f.execute({ type: 'agent.alert', agentId: f.worker, alert: 'limit', active: true, resetAt }, host, f.worker)
+ const row = async () => (await rosterRows(f.timed, host, 'test-host')).find(t => t.tabId === f.tab && t.agent?.id === f.worker)!
+ expect((await row()).resume).toEqual({ conversationId: f.group, assignmentId: f.assignmentId, lostAt, at: resetAt })
+ const resume = () => f.execute({ type: 'work.resume', conversationId: f.group, assignmentId: f.assignmentId, lostAt }, host, f.worker)
+ await expect(resume()).rejects.toThrow('Its usage limit has not reset yet.')
+ f.clock.now += 30 * MINUTE
+ await resume()
+ expect(await f.assignment()).toMatchObject({ id: f.assignmentId, agentId: f.worker, status: 'working' })
+ expect((await row()).resume).toBeNull()
+ expect((await f.leadInbox()).map(m => m.text)).toContain(`${await f.name(f.worker)} resumed its task after its usage limit reset.`)
+ })
+
+ // #1757 review, 2: a receipt replays the first answer, so it never says who holds the task now; the host's assignment
+ // rows do (cli superTabs/limitResume.ts reads them before typing).
+ it('replays a resume whose answer was lost even after a takeover, while its host\'s assignment rows no longer list it', async () => {
+ const f = await swarm()
+ const lostAt = f.clock.now
+ await f.execute({ type: 'agent.alert', agentId: f.worker, alert: 'limit', active: true, resetAt: new Date(f.clock.now + 30 * MINUTE).toISOString() }, host, f.worker)
+ f.clock.now += 30 * MINUTE
+ const resume = { operationId: `limit-resume-${f.assignmentId}-${lostAt}`, command: { type: 'work.resume', conversationId: f.group, assignmentId: f.assignmentId, lostAt } as Command }
+ const listed = async () => (await assignmentRows(f.timed, host, 'test-host')).some(a => a.tabId === f.tab && a.assignmentId === f.assignmentId && a.harnessId === f.harness.worker)
+ await f.timed.execute(host, f.tab, resume, f.worker)
+ expect(await listed()).toBe(true)
+ // Its answer never reached the host. The Product Manager cancels the task and hands it to another agent.
+ await f.execute({ type: 'work.cancel', conversationId: f.group, assignmentId: f.assignmentId, reason: 'Moving it on' })
+ const other = await f.add(f.group, 'test-host', f.harness.other, 'Other')
+ await f.execute({ type: 'work.assign', conversationId: f.group, agentId: other })
+ expect((await f.timed.execute(host, f.tab, resume, f.worker)).result).toEqual({})
+ expect(await listed()).toBe(false)
+ })
+
+ it('does not resume a task handed to another agent before the reset, and its host is no longer asked to', async () => {
+ const f = await swarm()
+ const lostAt = f.clock.now
+ await f.execute({ type: 'agent.alert', agentId: f.worker, alert: 'limit', active: true, resetAt: new Date(f.clock.now + 30 * MINUTE).toISOString() }, host, f.worker)
+ const other = await f.add(f.group, 'test-host', f.harness.other, 'Other')
+ const handedOn = String((await f.execute({ type: 'work.assign', conversationId: f.group, agentId: other })).result.assignmentId)
+ const row = async () => (await rosterRows(f.timed, host, 'test-host')).find(t => t.tabId === f.tab && t.agent?.id === f.worker)!
+ expect((await row()).resume).toBeNull()
+ f.clock.now += 30 * MINUTE
+ await expect(f.execute({ type: 'work.resume', conversationId: f.group, assignmentId: f.assignmentId, lostAt }, host, f.worker))
+ .rejects.toThrow('This task was handed on or closed, so it does not resume.')
+ expect(await f.assignment()).toMatchObject({ id: handedOn, agentId: other, status: 'working' })
+ })
+
it('is lost when its lease runs out with no progress, though its machine keeps reporting', async () => {
const f = await swarm()
const assigned = f.clock.now
@@ -436,3 +506,53 @@ describe('a start that never runs', () => {
.rejects.toMatchObject({ code: 'START_FAILED' })
})
})
+
+describe('the morning digest', () => {
+ it('is sent once when two of the Lead\'s polls run at the same moment', async () => {
+ const f = await swarm()
+ const projectId = (await f.timed.read(owner, f.tab)).state.projects![0]!.id
+ await f.execute({ type: 'project.digest', projectId, time: '03:00', timeZone: 'UTC' })
+ f.clock.now = 3 * 60 * 60_000
+ await Promise.all([f.leadInbox(), f.leadInbox()])
+ expect((await db.superTabMessage.findMany({ where: { tabId: f.tab } })).filter(m => (m.source as { kind?: string } | null)?.kind === 'digest-request')).toHaveLength(1)
+ })
+
+ it('lists work that shipped and was archived before the digest (#1757 review, 4)', async () => {
+ const f = await swarm()
+ const projectId = (await f.timed.read(owner, f.tab)).state.projects![0]!.id
+ await f.execute({ type: 'project.digest', projectId, time: '03:00', timeZone: 'UTC' })
+ const checkId = (await f.timed.read(owner, f.tab)).state.conversations.find(c => c.id === f.group)!.checks[0]!.id
+ await f.execute({ type: 'work.check', conversationId: f.group, assignmentId: f.assignmentId, checkId, passed: true, evidence: 'Verified' })
+ await f.execute({ type: 'work.status', conversationId: f.group, assignmentId: f.assignmentId, status: 'done',
+ result: 'Merged https://github.com/example/project/pull/9' }, host, f.worker)
+ await f.execute({ type: 'conversation.archive', conversationId: f.group, archived: true })
+ // Overnight the sweep puts it to sleep (sweeps.ts sleepQuietGroups, once its Lead acknowledged its reports): ordinary
+ // loads no longer read it.
+ await db.swarmGroup.updateMany({ where: { tabId: f.tab, key: f.group }, data: { dormant: true } })
+ expect((await f.timed.read(owner, f.tab)).state.conversations.some(c => c.id === f.group)).toBe(false)
+ f.clock.now = 3 * 60 * 60_000
+ await f.leadInbox()
+ const digest = (await db.superTabMessage.findMany({ where: { tabId: f.tab } })).find(m => (m.source as { kind?: string } | null)?.kind === 'digest-request')!
+ expect(digest.text.split('\n\n')[1]).toBe('Shipped:\n- #1 Ship the parser: https://github.com/example/project/pull/9')
+ })
+
+ it('wakes the Lead once at the project\'s local time with what its work is doing, and again the next day', async () => {
+ const f = await swarm()
+ const projectId = (await f.timed.read(owner, f.tab)).state.projects![0]!.id
+ // The swarm's clock starts at 02:46 UTC.
+ await f.execute({ type: 'project.digest', projectId, time: '03:00', timeZone: 'UTC' })
+ const digests = async () => (await db.superTabMessage.findMany({ where: { tabId: f.tab }, orderBy: { sequence: 'asc' } }))
+ .filter(m => (m.source as { kind?: string } | null)?.kind === 'digest-request')
+ await f.leadInbox()
+ expect(await digests()).toEqual([])
+ f.clock.now = 3 * 60 * 60_000
+ const inbox = await f.leadInbox()
+ await f.leadInbox()
+ // The same poll's time checks ran first: 13 minutes without progress lost the task, so the digest names it held up.
+ expect((await digests()).map(m => m.text.split('\n\n')[1])).toEqual([`Blocked:\n- #1 Ship the parser: lost (${await f.name(f.worker)}): no progress for 13 minutes`])
+ expect(inbox.map(m => m.id)).toContain((await digests())[0]!.id)
+ f.clock.now += 24 * 60 * 60_000
+ await f.leadInbox()
+ expect(await digests()).toHaveLength(2)
+ })
+})
diff --git a/backend/integration/superTabRead.test.ts b/backend/integration/superTabRead.test.ts
index 087b2808c..7edc3054e 100644
--- a/backend/integration/superTabRead.test.ts
+++ b/backend/integration/superTabRead.test.ts
@@ -561,6 +561,184 @@ describe('a real command through the store by parts (design 4.7)', () => {
})
})
+describe('decisions asked of one person (v2)', () => {
+ const post = async (tabId: string, command: Record<string, unknown>, as: AuthUser = owner, asAgentId?: string) => {
+ const response = await app.inject({ method: 'POST', url: `/api/super-tabs/${tabId}/commands`, headers: { authorization: `Bearer ${as.sub}` },
+ payload: { operationId: randomUUID(), command, ...(asAgentId ? { asAgentId } : {}) } })
+ return { status: response.statusCode, body: response.json() as { data: { result: Record<string, unknown> }; error?: { code: string } } }
+ }
+ const decisions = async (tabId: string, as: AuthUser, state = 'open', agent?: string) =>
+ (await get(`/api/super-tabs/${tabId}/decisions?state=${state}${agent ? `&asAgentId=${agent}` : ''}`, as)).body.data.decisions as Array<Record<string, any>>
+ const question = (text: string) => ({ question: text, options: ['Behind a flag', 'To everyone'], recommended: 0, unblocks: 'The release' })
+
+ it('shows a decision only to the person asked and the agent that asked, and counts it on their first load', async () => {
+ const s = await scene()
+ clock = Date.now()
+ const asked = await post(s.tabId, { type: 'decision.ask', conversationId: s.web, personId: peer.sub, questions: [question('Ship how?'), question('Name it?')] }, owner, s.lead)
+ expect(asked.status, JSON.stringify(asked.body)).toBe(200)
+ const seen = await decisions(s.tabId, peer)
+ expect(seen.map(d => d.question).sort()).toEqual(['Name it?', 'Ship how?'])
+ for (const d of seen) expect(d).toMatchObject({ options: ['Behind a flag', 'To everyone'], recommended: 0, unblocks: 'The release', conversationTitle: 'Web', askerAgentId: s.lead })
+ expect(new Set(seen.map(d => d.batchId)).size).toBe(1)
+ // Not the Swarm's owner, another member, or another agent; the asking Lead does.
+ expect(await decisions(s.tabId, owner)).toEqual([])
+ expect(await decisions(s.tabId, outsider)).toEqual([])
+ expect(await decisions(s.tabId, owner, 'open', s.worker)).toEqual([])
+ expect((await decisions(s.tabId, owner, 'open', s.lead)).length).toBe(2)
+ expect((await get(`/api/super-tabs/${s.tabId}/parts`, peer)).body.data.derived.decisionsWaiting).toBe(2)
+ expect((await get(`/api/super-tabs/${s.tabId}/parts`, owner)).body.data.derived.decisionsWaiting).toBe(0)
+ })
+
+ it('takes the person\'s one-tap answer once, and the answer reaches the asking worker and the Lead', async () => {
+ const s = await scene()
+ clock = Date.now()
+ const assignmentId = (await get(`/api/super-tabs/${s.tabId}/parts`, owner)).body.data.groups.find((g: { key: string }) => g.key === s.web).data.assignment.id
+ const needs = await post(s.tabId, { type: 'work.status', conversationId: s.web, assignmentId, status: 'needs_human', result: 'Ship to everyone?',
+ ask: { personId: peer.sub, options: ['Behind a flag', 'To everyone'], recommended: 0, unblocks: 'Turning it on' } }, owner, s.worker)
+ expect(needs.status, JSON.stringify(needs.body)).toBe(200)
+ const [open] = await decisions(s.tabId, peer)
+ expect(open).toMatchObject({ assignmentId, askerAgentId: s.worker, question: 'Ship to everyone?' })
+ const answered = await post(s.tabId, { type: 'decision.answer', decisionId: open!.id, choice: 1, note: 'Go.' }, peer)
+ expect(answered.status, JSON.stringify(answered.body)).toBe(200)
+ expect(await decisions(s.tabId, peer)).toEqual([])
+ expect(await decisions(s.tabId, peer, 'answered')).toEqual([expect.objectContaining({ id: open!.id, choice: 1, note: 'Go.' })])
+ expect(await decisions(s.tabId, owner, 'answered', s.worker)).toEqual([expect.objectContaining({ id: open!.id, choice: 1 })])
+ const notice = await db.superTabMessage.findUnique({ where: { id: answered.body.data.result.messageId as string } })
+ expect(notice).toMatchObject({ conversationId: s.web, recipientIds: [s.worker, s.lead], source: { kind: 'agent-only', decisionId: open!.id } })
+ expect((await db.superTabDelivery.findMany({ where: { tabId: s.tabId, messageId: notice!.id } })).map(d => d.agentId).sort()).toEqual([s.lead, s.worker].sort())
+ // Once only, and only by the person asked.
+ expect((await post(s.tabId, { type: 'decision.answer', decisionId: open!.id, choice: 0 }, peer)).body.error?.code).toBe('DECISION_ANSWERED')
+ expect((await post(s.tabId, { type: 'decision.answer', decisionId: open!.id, choice: 0 }, owner)).status).toBe(404)
+ })
+
+ it('tells the asker and the Lead with a notice only they read, and puts nothing of the answer where other readers look', async () => {
+ const s = await scene()
+ clock = Date.now()
+ const asked = await post(s.tabId, { type: 'decision.ask', conversationId: s.web, personId: peer.sub, questions: [question('Secret plan?')] }, owner, s.lead)
+ const id = (asked.body.data.result.decisionIds as string[])[0]!
+ const before = (await get(`/api/super-tabs/${s.tabId}/parts`, owner)).body.data
+ const answered = await post(s.tabId, { type: 'decision.answer', decisionId: id, choice: 1, note: 'Only for the Lead.' }, peer)
+ expect(answered.status, JSON.stringify(answered.body)).toBe(200)
+ const leaks = ['Secret plan?', 'To everyone', 'Only for the Lead.', 'decided']
+ const shows = (value: unknown) => leaks.filter(text => JSON.stringify(value).includes(text))
+ // Another member who reads the conversation: its messages, a first load and a change read show none of it, and no unread mark.
+ const messages = (await get(`/api/super-tabs/${s.tabId}/conversations/${s.web}/messages`, owner)).body.data
+ expect(shows(messages)).toEqual([])
+ const first = (await get(`/api/super-tabs/${s.tabId}/parts`, owner)).body.data
+ expect(shows(first)).toEqual([])
+ expect(first.groups.find((g: { key: string }) => g.key === s.web).data.lastMessageSequence)
+ .toBe(before.groups.find((g: { key: string }) => g.key === s.web).data.lastMessageSequence)
+ clock = Date.now()
+ expect(shows((await get(`/api/super-tabs/${s.tabId}/changes?cursor=${before.cursor}`, owner)).body.data)).toEqual([])
+ // Nor the person who answered, beyond their own decision; nor the worker, which neither asked nor leads.
+ expect(shows((await get(`/api/super-tabs/${s.tabId}/conversations/${s.web}/messages`, peer)).body.data)).toEqual([])
+ expect(shows((await get(`/api/super-tabs/${s.tabId}/conversations/${s.web}/messages?asAgentId=${s.worker}`, owner)).body.data)).toEqual([])
+ // The Lead gets a notice with no content, pointing to the decisions read, which has the answer.
+ const lead = (await get(`/api/super-tabs/${s.tabId}/conversations/${s.web}/messages?asAgentId=${s.lead}`, owner)).body.data.messages as Array<{ id: string; text: string }>
+ const notice = lead.find(m => m.id === answered.body.data.result.messageId)!
+ expect(shows(notice)).toEqual([])
+ expect(notice.text).toContain('harness super-tab decisions --answered')
+ expect(await decisions(s.tabId, owner, 'answered', s.lead)).toEqual([expect.objectContaining({ id, choice: 1, note: 'Only for the Lead.' })])
+ })
+
+ it('refuses an answer from a person who can no longer read the conversation, also when the answer is retried', async () => {
+ const s = await scene()
+ clock = Date.now()
+ const ask = async (questions: string[]) => ((await post(s.tabId, { type: 'decision.ask', conversationId: s.privateId, personId: peer.sub,
+ questions: questions.map(question) }, owner, s.lead)).body.data.result.decisionIds as string[])
+ const [first, second] = await ask(['Keep it?', 'Ship it?'])
+ const retry = { operationId: randomUUID(), command: { type: 'decision.answer', decisionId: first, choice: 0 } }
+ const send = (body: unknown) => app.inject({ method: 'POST', url: `/api/super-tabs/${s.tabId}/commands`, headers: { authorization: `Bearer ${peer.sub}` }, payload: body as object })
+ expect((await send(retry)).statusCode).toBe(200)
+ // The peer stays in the Swarm but leaves the private conversation's audience.
+ await writeGroup(s.tabId, s.privateId, Date.now(), group => { group.audience = { people: [] } })
+ expect((await post(s.tabId, { type: 'decision.answer', decisionId: second, choice: 0 }, peer)).status).toBe(404)
+ expect((await send(retry)).statusCode).toBe(404)
+ expect(await decisions(s.tabId, owner, 'open', s.lead)).toEqual([expect.objectContaining({ id: second })])
+ })
+
+ it('takes an answer in a conversation that went quiet and was archived, counts it on a fresh first load, and tells both agents', async () => {
+ const s = await scene()
+ clock = Date.now()
+ const assignmentId = (await get(`/api/super-tabs/${s.tabId}/parts`, owner)).body.data.groups.find((g: { key: string }) => g.key === s.web).data.assignment.id
+ await post(s.tabId, { type: 'work.status', conversationId: s.web, assignmentId, status: 'needs_human', result: 'Ship to everyone?',
+ ask: { personId: peer.sub, options: ['Behind a flag', 'To everyone'], recommended: 0, unblocks: 'Turning it on' } }, owner, s.worker)
+ await writeGroup(s.tabId, s.web, Date.now(), group => { group.assignment = { ...group.assignment!, status: 'done' }; group.archived = true; group.dormant = true })
+ const first = (await get(`/api/super-tabs/${s.tabId}/parts`, peer)).body.data
+ expect(first.groups.map((g: { key: string }) => g.key)).not.toContain(s.web)
+ expect(first.derived.decisionsWaiting).toBe(1)
+ const [open] = await decisions(s.tabId, peer)
+ const answered = await post(s.tabId, { type: 'decision.answer', decisionId: open!.id, choice: 0 }, peer)
+ expect(answered.status, JSON.stringify(answered.body)).toBe(200)
+ expect((await db.superTabDelivery.findMany({ where: { tabId: s.tabId, messageId: answered.body.data.result.messageId as string } }))
+ .map(d => d.agentId).sort()).toEqual([s.lead, s.worker].sort())
+ expect((await get(`/api/super-tabs/${s.tabId}/parts`, peer)).body.data.derived.decisionsWaiting).toBe(0)
+ })
+
+ it('keeps one answer when two arrive at once, returns the same receipt for a retried answer, and refuses a person removed from the Swarm', async () => {
+ const s = await scene()
+ clock = Date.now()
+ const [one, two] = (await post(s.tabId, { type: 'decision.ask', conversationId: s.web, personId: peer.sub,
+ questions: [question('First?'), question('Second?')] }, owner, s.lead)).body.data.result.decisionIds as string[]
+ const answer = (choice: number, operationId = randomUUID(), decisionId = one) => app.inject({ method: 'POST', url: `/api/super-tabs/${s.tabId}/commands`,
+ headers: { authorization: `Bearer ${peer.sub}` }, payload: { operationId, command: { type: 'decision.answer', decisionId, choice } } })
+ const both = await Promise.all([answer(0), answer(1)])
+ expect(both.map(r => r.statusCode).sort()).toEqual([200, 409])
+ const [kept] = await decisions(s.tabId, peer, 'answered')
+ expect((await db.superTabMessage.count({ where: { tabId: s.tabId, source: { equals: { kind: 'agent-only', decisionId: one } } } }))).toBe(1)
+ // A lost reply retried with the same operation: the same receipt, nothing written twice.
+ const op = randomUUID()
+ const first = await answer(0, op, two), again = await answer(0, op, two)
+ expect([first.statusCode, again.statusCode]).toEqual([200, 200])
+ expect(again.json().data.result).toEqual(first.json().data.result)
+ expect(await decisions(s.tabId, peer, 'answered')).toHaveLength(2)
+ expect(kept!.choice).toBe(both[0]!.statusCode === 200 ? 0 : 1)
+ // Removed from the Swarm, the person can no longer answer, nor retry a saved answer.
+ const [three] = (await post(s.tabId, { type: 'decision.ask', conversationId: s.web, personId: peer.sub, questions: [question('Third?')] }, owner, s.lead))
+ .body.data.result.decisionIds as string[]
+ expect((await post(s.tabId, { type: 'member.remove', userId: peer.sub })).status).toBe(200)
+ expect([403, 404]).toContain((await answer(0, randomUUID(), three)).statusCode)
+ expect([403, 404]).toContain((await answer(0, op, two)).statusCode)
+ })
+
+ it('asks a person an open question once, however often the same ask is repeated', async () => {
+ const s = await scene()
+ clock = Date.now()
+ const ask = async () => (await post(s.tabId, { type: 'decision.ask', conversationId: s.web, personId: peer.sub, questions: [question('Ship how?')] }, owner, s.lead))
+ .body.data.result.decisionIds as string[]
+ const [first] = await ask()
+ expect(await ask()).toEqual([first])
+ expect(await decisions(s.tabId, peer)).toEqual([expect.objectContaining({ id: first })])
+ })
+
+ it('keeps a decision of its own for another asker, another task, or other options with the same question text', async () => {
+ const s = await scene()
+ clock = Date.now()
+ const [lead] = (await post(s.tabId, { type: 'decision.ask', conversationId: s.web, personId: peer.sub, questions: [question('Ship how?')] }, owner, s.lead))
+ .body.data.result.decisionIds as string[]
+ const [other] = (await post(s.tabId, { type: 'decision.ask', conversationId: s.web, personId: peer.sub,
+ questions: [{ ...question('Ship how?'), options: ['Today', 'Next week'] }] }, owner, s.lead)).body.data.result.decisionIds as string[]
+ const assignmentId = (await get(`/api/super-tabs/${s.tabId}/parts`, owner)).body.data.groups.find((g: { key: string }) => g.key === s.web).data.assignment.id
+ expect((await post(s.tabId, { type: 'work.status', conversationId: s.web, assignmentId, status: 'needs_human', result: 'Ship how?',
+ ask: { personId: peer.sub, options: ['Behind a flag', 'To everyone'], recommended: 0, unblocks: 'The release' } }, owner, s.worker)).status).toBe(200)
+ const open = await decisions(s.tabId, peer)
+ expect(open).toHaveLength(3)
+ expect(new Set([lead, other, ...open.map(d => d.id)]).size).toBe(3)
+ // The worker reads its own question, and its answer reaches it.
+ const [mine] = await decisions(s.tabId, owner, 'open', s.worker)
+ expect(mine).toMatchObject({ askerAgentId: s.worker, assignmentId, options: ['Behind a flag', 'To everyone'] })
+ })
+
+ it('counts an open decision in a quiet conversation on a change read, which loads only some conversations', async () => {
+ const s = await scene()
+ clock = Date.now()
+ expect((await post(s.tabId, { type: 'decision.ask', conversationId: s.done, personId: peer.sub, questions: [question('Reopen it?')] }, owner, s.lead)).status).toBe(200)
+ const first = (await get(`/api/super-tabs/${s.tabId}/parts`, peer)).body.data
+ clock = Date.now()
+ expect((await get(`/api/super-tabs/${s.tabId}/changes?cursor=${first.cursor}`, peer)).body.data.derived.decisionsWaiting).toBe(1)
+ })
+})
+
describe('routes given only a store', () => {
it('read from that store\'s database, not the app-wide client', async () => {
const s = await scene()
diff --git a/backend/prisma/schema.prisma b/backend/prisma/schema.prisma
index ae8bcc454..03e4db518 100644
--- a/backend/prisma/schema.prisma
+++ b/backend/prisma/schema.prisma
@@ -1078,6 +1078,33 @@ model SuperTabMention {
@@index([tabId, conversationId, personId])
}
+/// A question to one person, with options and a recommendation (backend/src/superTabs/decisions.ts). Kept out of the tab
+/// state, as mentions are: an asking agent and the asked person read it, and the person answers it once.
+model SuperTabDecision {
+ id String @id @map("_id")
+ tabId String
+ /// The ask that put several questions to one person together.
+ batchId String
+ projectId String
+ conversationId String
+ /// The task whose needs_human asked it, or null for the Lead's decision.ask.
+ assignmentId String?
+ personId String
+ askerAgentId String
+ question String
+ options String[]
+ recommended Int
+ unblocks String
+ createdAt DateTime
+ answeredAt DateTime?
+ choice Int?
+ note String?
+
+ @@index([tabId, personId, createdAt])
+ @@index([tabId, askerAgentId, createdAt])
+ @@index([tabId, projectId, createdAt])
+}
+
/// One uploaded file, which one message of the actor that uploaded it can send once.
model SuperTabAttachment {
id String @id @map("_id")
diff --git a/backend/src/lib/teamSession.test.ts b/backend/src/lib/teamSession.test.ts
index 6c99b00ad..709a671c0 100644
--- a/backend/src/lib/teamSession.test.ts
+++ b/backend/src/lib/teamSession.test.ts
@@ -239,7 +239,7 @@ describe('a team session reaching past its own machine', () => {
it('cannot read or speak as the person: every agent route needs one of its agents', async () => {
for (const url of ['/api/super-tabs/tab-1', '/api/super-tabs/tab-1/starts/start-1', '/api/super-tabs/tab-1/routing-policy',
- '/api/super-tabs/tab-1/route-decisions', '/api/super-tabs/tab-1/route-decisions/decision-1',
+ '/api/super-tabs/tab-1/route-decisions', '/api/super-tabs/tab-1/route-decisions/decision-1', '/api/super-tabs/tab-1/decisions?state=open',
'/api/super-tabs/tab-1/conversations/lead/messages', '/api/super-tabs/tab-1/conversations/lead/attempts',
'/api/super-tabs/tab-1/terminal/request-1', '/api/super-tabs/tab-1?asAgentId=', '/api/super-tabs/tab-1/parts',
'/api/super-tabs/tab-1/changes?cursor=eyJ2IjoyfQ', '/api/super-tabs/tab-1/groups?dormant=1', '/api/super-tabs/tab-1/groups/group-1']) limited(await call('GET', url))
diff --git a/backend/src/lib/teamSession.ts b/backend/src/lib/teamSession.ts
index 65f253382..d5c723462 100644
--- a/backend/src/lib/teamSession.ts
+++ b/backend/src/lib/teamSession.ts
@@ -129,6 +129,8 @@ export const TEAM_ROUTES: readonly TeamRoute[] = [
{ method: 'GET', url: '/api/super-tabs/:tabId/routing-policy', scope: 'agent' },
{ method: 'GET', url: '/api/super-tabs/:tabId/route-decisions', scope: 'agent' },
{ method: 'GET', url: '/api/super-tabs/:tabId/route-decisions/:decisionId', scope: 'agent' },
+ // The decisions its agent asked of people, and their answers (superTabs/decisions.ts).
+ { method: 'GET', url: '/api/super-tabs/:tabId/decisions', scope: 'agent' },
{ method: 'GET', url: '/api/super-tabs/:tabId/conversations/:conversationId/messages', scope: 'agent' },
{ method: 'GET', url: '/api/super-tabs/:tabId/conversations/:conversationId/attempts', scope: 'agent' },
{ method: 'GET', url: '/api/super-tabs/:tabId/terminal/:requestId', scope: 'agent' },
diff --git a/backend/src/routes/superTabs.ts b/backend/src/routes/superTabs.ts
index 52dbd1b16..d484107fd 100644
--- a/backend/src/routes/superTabs.ts
+++ b/backend/src/routes/superTabs.ts
@@ -31,6 +31,7 @@ const operation = operationSchema.extend({ asAgentId: id.optional() })
const listQuery = z.object({ after: id.optional() }).strict()
const cursor = z.string().min(1).max(512).regex(/^[A-Za-z0-9_-]+$/)
const changesQuery = agentQuery.extend({ cursor })
+const leaderboardQuery = z.object({ projectId: id, week: z.coerce.number().int().nonnegative().safe().optional() }).strict()
const dormantQuery = agentQuery.extend({ dormant: z.literal('1'), projectId: id.optional(), before: cursor.optional() })
const groupParams = tabParams.extend({ conversationId: id })
const hostChangesQuery = z.object({ cursor: cursor.optional(), full: z.literal('1').optional() }).strict()
@@ -59,6 +60,7 @@ const deliveryAction = z.discriminatedUnion('type', [
z.object({ type: z.literal('hold'), claimId: id, reason: holdReason }).strict(),
])
const mentionQuery = z.object({ state: z.enum(['waiting', 'earlier']) }).strict()
+const personDecisionQuery = agentQuery.extend({ state: z.enum(['open', 'answered']) }).strict()
const savePolicy = z.object({ revision: z.number().int().nonnegative().safe(), policy: routingPolicySchema }).strict()
const stop = z.object({ assignmentId: id, receipt: z.string().min(1).max(2000) }).strict()
const githubToken = z.object({ machineId: id }).strict()
@@ -180,6 +182,9 @@ export async function superTabRoutes(app: FastifyInstance, options: { store?: Su
app.get<{ Params: z.infer<typeof tabParams>; Querystring: z.infer<typeof changesQuery> }>('/api/super-tabs/:tabId/changes',
{ preHandler: [validateParams(tabParams), validateQuery(changesQuery)] },
(req, reply) => respond(reply, () => reads.changes(req.user!, req.params.tabId, req.query.cursor, req.query.asAgentId)))
+ app.get<{ Params: z.infer<typeof tabParams>; Querystring: z.infer<typeof leaderboardQuery> }>('/api/super-tabs/:tabId/leaderboard',
+ { preHandler: [validateParams(tabParams), validateQuery(leaderboardQuery)] },
+ (req, reply) => respond(reply, () => reads.leaderboard(req.user!, req.params.tabId, req.query.projectId, req.query.week)))
app.get<{ Params: z.infer<typeof tabParams>; Querystring: z.infer<typeof dormantQuery> }>('/api/super-tabs/:tabId/groups',
{ preHandler: [validateParams(tabParams), validateQuery(dormantQuery)] },
(req, reply) => respond(reply, () => reads.dormant(req.user!, req.params.tabId, { projectId: req.query.projectId, before: req.query.before }, req.query.asAgentId)))
@@ -241,6 +246,9 @@ export async function superTabRoutes(app: FastifyInstance, options: { store?: Su
app.get<{ Params: z.infer<typeof tabParams>; Querystring: z.infer<typeof mentionQuery> }>('/api/super-tabs/:tabId/mentions',
{ preHandler: [validateParams(tabParams), validateQuery(mentionQuery)] },
(req, reply) => respond(reply, () => store.mentions(req.user!, req.params.tabId, req.query.state)))
+ app.get<{ Params: z.infer<typeof tabParams>; Querystring: z.infer<typeof personDecisionQuery> }>('/api/super-tabs/:tabId/decisions',
+ { preHandler: [validateParams(tabParams), validateQuery(personDecisionQuery)] },
+ (req, reply) => respond(reply, () => store.decisions(req.user!, req.params.tabId, req.query.state, req.query.asAgentId)))
app.get<{ Params: z.infer<typeof startParams>; Querystring: z.infer<typeof agentQuery> }>('/api/super-tabs/:tabId/starts/:startId',
{ preHandler: [validateParams(startParams), validateQuery(agentQuery)] },
(req, reply) => respond(reply, () => store.start(req.user!, req.params.tabId, req.params.startId, req.query.asAgentId)))
diff --git a/backend/src/superTabs/commands.test.ts b/backend/src/superTabs/commands.test.ts
index c1bc96f9f..73928808a 100644
--- a/backend/src/superTabs/commands.test.ts
+++ b/backend/src/superTabs/commands.test.ts
@@ -1124,11 +1124,11 @@ describe('Reviewer role', () => {
const checkId = f.state.conversations.find(c => c.id === group)!.checks[0]!.id
f.run({ type: 'work.check', conversationId: group, assignmentId: built, checkId, passed: true, evidence: 'Ready: yes — revision abc' }, reviewerActor)
expect(f.state.conversations.find(c => c.id === group)!.checks[0]!.passedBy).toBe(`agent:${reviewer}`)
- // While its review is active it is busy; when it is done, the Lead decides its fate like a Builder's.
+ // While its own review is active it is busy; when it is done it is kept, waiting for no decision, until the Lead stops it.
expect(() => f.run({ type: 'agent.release', agentId: reviewer, decision: 'stop' }, leadActor)).toThrow('active work')
f.run({ type: 'work.status', conversationId: review, assignmentId, status: 'stopped', result: null }, owner, { confirmedStopped: true })
f.run({ type: 'work.cancel', conversationId: group, assignmentId: built, reason: 'Obsolete' }, leadActor)
- expect(f.state.agents.find(a => a.id === reviewer)).toHaveProperty('workDecision', 'awaiting')
+ expect(f.state.agents.find(a => a.id === reviewer)).toHaveProperty('workDecision', 'keep')
f.run({ type: 'agent.release', agentId: reviewer, decision: 'stop' }, leadActor)
})
@@ -1156,15 +1156,40 @@ describe('Reviewer role', () => {
expect(ready.messages[0]!.recipients).toEqual([lead])
})
- it('refuses to keep or stop a Reviewer while a group it is in has active work', () => {
+ it('lets the Lead keep or stop a Reviewer that only sits in a group with active work: only its own active work refuses', () => {
const { f, leadActor, group, reviewer, builder } = reviewed()
- const assignmentId = f.run({ type: 'work.assign', conversationId: group, agentId: builder }).result.assignmentId as string
- for (const decision of ['keep', 'stop'] as const) {
- expect(() => f.run({ type: 'agent.release', agentId: reviewer, decision }, leadActor)).toThrow('reviewing active work')
- }
- f.run({ type: 'work.cancel', conversationId: group, assignmentId, reason: 'Obsolete' }, leadActor)
+ f.run({ type: 'work.assign', conversationId: group, agentId: builder })
+ f.run({ type: 'agent.release', agentId: reviewer, decision: 'keep' }, leadActor)
+ expect(f.state.agents.find(a => a.id === reviewer)).toHaveProperty('workDecision', 'keep')
f.run({ type: 'agent.release', agentId: reviewer, decision: 'stop' }, leadActor)
expect(f.state.agents.find(a => a.id === reviewer)).toHaveProperty('workDecision', 'stop')
+ expect(() => f.run({ type: 'agent.release', agentId: builder, decision: 'stop' }, leadActor)).toThrow('active work')
+ })
+
+ it('loses a Reviewer\'s review when its model keeps failing, and keeps the Reviewer out of the decision queue', () => {
+ const { f, leadActor, group, reviewer } = reviewed()
+ const review = f.run({ type: 'conversation.create', title: 'Review', brief: 'Review it.', reviewOf: group, checks: [{ description: 'Verdict', independent: false }] },
+ leadActor).result.conversationId as string
+ f.run({ type: 'work.assign', conversationId: review, agentId: reviewer })
+ f.run({ type: 'agent.alert', agentId: reviewer, alert: 'model', active: true }, { kind: 'agent', agentId: reviewer, machineOwnerId: 'target-owner' })
+ expect(f.state.conversations.find(c => c.id === review)!.assignment).toMatchObject({ status: 'lost', lost: { reason: 'its model keeps failing' } })
+ expect(f.state.agents.find(a => a.id === reviewer)!.lostTask).toMatchObject({ conversationId: review })
+ })
+
+ it('never makes the Lead decide about a finished Reviewer before routing, starting or assigning, even one stored as waiting', () => {
+ const { f, lead, leadActor, group, reviewer, builder } = reviewed()
+ const checks = [{ description: 'Verdict', independent: false }]
+ const review = f.run({ type: 'conversation.create', title: 'Review', brief: 'Review it.', reviewOf: group, checks }, leadActor).result.conversationId as string
+ const reviewing = f.run({ type: 'work.assign', conversationId: review, agentId: reviewer }).result.assignmentId as string
+ f.run({ type: 'work.status', conversationId: review, assignmentId: reviewing, status: 'stopped', result: null }, owner, { confirmedStopped: true })
+ expect(f.state.agents.find(a => a.id === reviewer)!.workDecision).toBe('keep')
+ // A Reviewer a release from before this left waiting for a decision.
+ f.state.agents.find(a => a.id === reviewer)!.workDecision = 'awaiting'
+ const next = f.group()
+ f.run({ type: 'conversation.agent', conversationId: next, agentId: lead, present: true, lead: true })
+ const pick = record({ candidates: [candidate('c0', { kind: 'member', agentId: builder, machineId: 'host' })], pick: 'c0' })
+ expect(f.run({ type: 'route.record', conversationId: next, decision: pick } as Command, leadActor).routeDecisions).toHaveLength(1)
+ f.run({ type: 'work.assign', conversationId: next, agentId: builder, ...via }, leadActor, decisionIn(next))
})
it('lets the Lead keep or stop a Reviewer that never had work, but not such a Builder', () => {
@@ -1176,7 +1201,7 @@ describe('Reviewer role', () => {
expect(() => f.run({ type: 'agent.release', agentId: builder, decision: 'stop' }, leadActor)).toThrow('no finished assignment')
})
- it('makes the group\'s idle Reviewers await the Lead\'s decision when its work ends, and counts adding one to a group as reuse', () => {
+ it('keeps the group\'s idle Reviewers when its work ends, waiting for no decision, and counts adding one to a group as reuse', () => {
const { f, leadActor, group, reviewer, builder } = reviewed()
const other = f.group(), busy = f.group(), otherBuilder = f.add('other-builder', 'owner', busy)
f.run({ type: 'conversation.agent', conversationId: busy, agentId: leadActor.agentId, present: true, lead: true })
@@ -1185,19 +1210,18 @@ describe('Reviewer role', () => {
const assignmentId = f.run({ type: 'work.assign', conversationId: g, agentId: worker }).result.assignmentId as string
return () => f.run({ type: 'work.cancel', conversationId: g, assignmentId, reason: 'Obsolete' }, leadActor)
}
- // Still reviewing another group's active work: not awaiting yet.
+ // Still reviewing another group's active work: not kept yet.
f.run({ type: 'conversation.agent', conversationId: busy, agentId: reviewer, present: true, lead: false })
const endBusy = finish(busy, otherBuilder)
finish(group, builder)()
expect(decision(reviewer)).toBeUndefined()
endBusy()
- expect(decision(reviewer)).toBe('awaiting')
- expect(visibleState(f.state, owner).agents.find(a => a.id === reviewer)).toHaveProperty('workDecision', 'awaiting')
- // Start, route and assign elsewhere wait for the decision (the Builders are decided first).
+ expect(decision(reviewer)).toBe('keep')
+ expect(visibleState(f.state, owner).agents.find(a => a.id === reviewer)).toHaveProperty('workDecision', 'keep')
+ // Assigning elsewhere waits only for the Builders' decisions, never for the Reviewer's.
f.run({ type: 'agent.release', agentId: builder, decision: 'keep' }, leadActor)
f.run({ type: 'agent.release', agentId: otherBuilder, decision: 'keep' }, leadActor)
f.run({ type: 'work.define', conversationId: other, brief: 'Next', checks: [{ description: 'Done', independent: false }] })
- expect(() => f.run({ type: 'work.assign', conversationId: other, agentId: builder, ...via }, leadActor, decisionIn(other))).toThrow('reuse, keep or stop')
// Adding it to that group reuses it.
f.run({ type: 'conversation.agent', conversationId: other, agentId: reviewer, present: true, lead: false })
expect(decision(reviewer)).toBeUndefined()
@@ -1208,7 +1232,7 @@ describe('Reviewer role', () => {
const { f, leadActor, group, reviewer, builder } = reviewed()
const assignmentId = f.run({ type: 'work.assign', conversationId: group, agentId: builder }).result.assignmentId as string
f.run({ type: 'work.status', conversationId: group, assignmentId, status: 'stopped', result: null }, owner, { confirmedStopped: true })
- expect(f.state.agents.find(a => a.id === reviewer)!.workDecision).toBe('awaiting')
+ expect(f.state.agents.find(a => a.id === reviewer)!.workDecision).toBe('keep')
f.run({ type: 'work.define', conversationId: group, brief: 'Again', checks: [{ description: 'Done', independent: false }] })
f.run({ type: 'work.assign', conversationId: group, agentId: builder, ...via }, leadActor, decisionIn(group))
expect(f.state.agents.find(a => a.id === reviewer)).not.toHaveProperty('workDecision')
@@ -2363,6 +2387,17 @@ describe('lost work (liveness.ts)', () => {
return { f, lead, group, worker, other, as, task, limit }
}
+ it('loses a worker\'s task once its host says the model kept failing (its ten-minute alert); an ended alert loses nothing', () => {
+ const { f, worker, as, task } = lostFixture()
+ const model = (active: boolean) => f.run({ type: 'agent.alert', agentId: worker, alert: 'model', active }, as(worker))
+ model(false)
+ expect(task().assignment!.status).toBe('working')
+ model(true)
+ expect(task().assignment).toMatchObject({ status: 'lost', lost: { reason: 'its model keeps failing' } })
+ // Where it failed stays on the group, for routing the work again even once its agent is gone (cli routeCommand.ts).
+ expect(task().lostAttempt).toEqual({ id: task().assignment!.id, agentId: worker, machineId: 'host', engine: config.engine })
+ })
+
it('lets the Lead hand lost work to another agent without first deciding about the lost one', () => {
const { f, lead, group, other, as, task, limit } = lostFixture()
limit()
@@ -2394,7 +2429,8 @@ describe('lost work (liveness.ts)', () => {
})
it('keeps the lost worker marked when the Lead cancels its task or hands it to another agent (final review, Important 3)', () => {
- const marked = { conversationId: expect.any(String), assignmentId: expect.any(String), reason: expect.stringContaining('usage limit'), at: 1000 }
+ const marked = { conversationId: expect.any(String), assignmentId: expect.any(String), reason: expect.stringContaining('usage limit'), at: 1000,
+ resumeAt: '1970-01-01T01:00:00.000Z' }
for (const close of ['cancel', 'reassign'] as const) {
const { f, lead, group, worker, other, as, task, limit } = lostFixture()
limit()
@@ -2439,6 +2475,98 @@ describe('lost work (liveness.ts)', () => {
expect(f.state.conversations.find(c => c.id === group)!.lostAttempt).toMatchObject({ agentId: worker })
})
+ it('records when a task lost to a usage limit with a reset time resumes, and tells the Lead it resumes then unless handed on', () => {
+ const { f, worker, task, limit } = lostFixture()
+ const lead = limit().messages.find(m => m.source?.kind === 'work-lost' && !m.recipients.includes(worker))!
+ expect(task().assignment!.lost).toEqual({ reason: expect.stringContaining('usage limit'), at: 1000, resumeAt: '1970-01-01T01:00:00.000Z' })
+ expect(f.state.agents.find(a => a.id === worker)!.lostTask).toMatchObject({ resumeAt: '1970-01-01T01:00:00.000Z' })
+ expect(lead.text).toContain('It resumes by itself when its limit resets at 01:00 UTC, unless you hand it on first.')
+ expect(lead.text).not.toContain('Assign it to another agent now')
+ })
+
+ it('records no resume time for a task lost to a model that keeps failing, though its alert names a reset time', () => {
+ const { f, worker, as, task } = lostFixture()
+ f.run({ type: 'agent.alert', agentId: worker, alert: 'model', active: true, resetAt: new Date(3_600_000).toISOString() }, as(worker))
+ expect(task().assignment).toMatchObject({ status: 'lost', lost: { reason: 'its model keeps failing' } })
+ expect(task().assignment!.lost).not.toHaveProperty('resumeAt')
+ expect(f.state.agents.find(a => a.id === worker)!.lostTask).not.toHaveProperty('resumeAt')
+ })
+
+ it('records no resume time for a usage limit whose screen gave no reset time', () => {
+ const { f, worker, as, task } = lostFixture()
+ const rows = f.run({ type: 'agent.alert', agentId: worker, alert: 'limit', active: true }, as(worker)).messages
+ expect(task().assignment!.lost).not.toHaveProperty('resumeAt')
+ expect(f.state.agents.find(a => a.id === worker)!.lostTask).not.toHaveProperty('resumeAt')
+ expect(rows.find(m => m.source?.kind === 'work-lost' && !m.recipients.includes(worker))!.text).toContain('Assign it to another agent now, or cancel it.')
+ })
+
+ it('gives the worker its own lost task back once its limit has reset, and accepts its status again', () => {
+ const { f, lead, group, worker, as, task, limit } = lostFixture()
+ limit()
+ const assignmentId = task().assignment!.id
+ const resumed = f.run({ type: 'work.resume', conversationId: group, assignmentId, lostAt: 1000 }, as(worker), { now: 3_600_000 })
+ expect(task().assignment).toMatchObject({ id: assignmentId, agentId: worker, status: 'working', leaseUntil: 3_600_000 + 5 * 60_000 })
+ expect(task().assignment).not.toHaveProperty('lost')
+ expect(task().lostAttempt).toBeUndefined()
+ expect(f.state.agents.find(a => a.id === worker)!.lostTask).toBeUndefined()
+ expect(resumed.messages).toEqual([expect.objectContaining({ conversationId: group, recipients: [lead],
+ text: 'worker resumed its task after its usage limit reset.' })])
+ f.run({ type: 'work.status', conversationId: group, assignmentId, status: 'review', result: 'Ready' }, as(worker), { now: 3_600_001 })
+ expect(task().assignment!.status).toBe('review')
+ })
+
+ it('resumes each loss of one task once: a second usage limit is a new loss, and the first one\'s resume no longer applies (#1757 review, 1)', () => {
+ const { f, group, worker, as, task, limit } = lostFixture()
+ limit()
+ const assignmentId = task().assignment!.id
+ f.run({ type: 'work.resume', conversationId: group, assignmentId, lostAt: 1000 }, as(worker), { now: 3_600_000 })
+ // The limit screen goes, the task runs, and the engine hits its limit again an hour later.
+ f.run({ type: 'agent.alert', agentId: worker, alert: 'limit', active: false }, as(worker), { now: 3_600_100 })
+ f.run({ type: 'agent.alert', agentId: worker, alert: 'limit', active: true, resetAt: new Date(9_000_000).toISOString() }, as(worker), { now: 7_200_000 })
+ expect(task().assignment).toMatchObject({ id: assignmentId, status: 'lost', lost: { at: 7_200_000, resumeAt: '1970-01-01T02:30:00.000Z' } })
+ expect(f.state.agents.find(a => a.id === worker)!.lostTask).toMatchObject({ assignmentId, at: 7_200_000, resumeAt: '1970-01-01T02:30:00.000Z' })
+ expect(() => f.run({ type: 'work.resume', conversationId: group, assignmentId, lostAt: 1000 }, as(worker), { now: 9_000_000 }))
+ .toThrow('This task was handed on or closed, so it does not resume.')
+ f.run({ type: 'work.resume', conversationId: group, assignmentId, lostAt: 7_200_000 }, as(worker), { now: 9_000_000 })
+ expect(task().assignment).toMatchObject({ id: assignmentId, agentId: worker, status: 'working' })
+ })
+
+ it('does not resume a lost task before its limit resets', () => {
+ const { f, group, worker, as, task, limit } = lostFixture()
+ limit()
+ expect(() => f.run({ type: 'work.resume', conversationId: group, assignmentId: task().assignment!.id, lostAt: 1000 }, as(worker), { now: 3_599_999 }))
+ .toThrow('Its usage limit has not reset yet.')
+ expect(task().assignment!.status).toBe('lost')
+ })
+
+ it('does not resume a lost task the Lead cancelled or handed to another agent before the reset', () => {
+ for (const close of ['cancel', 'reassign'] as const) {
+ const { f, lead, group, worker, other, as, task, limit } = lostFixture()
+ limit()
+ const lostId = task().assignment!.id
+ if (close === 'cancel') f.run({ type: 'work.cancel', conversationId: group, assignmentId: lostId, reason: 'Not needed' }, as(lead))
+ else f.run({ type: 'work.assign', conversationId: group, agentId: other, ...via }, as(lead), decisionIn(group))
+ const before = structuredClone(task().assignment)
+ expect(() => f.run({ type: 'work.resume', conversationId: group, assignmentId: lostId, lostAt: 1000 }, as(worker), { now: 3_600_000 }))
+ .toThrow('This task was handed on or closed, so it does not resume.')
+ expect(task().assignment).toEqual(before)
+ }
+ })
+
+ it('resumes a lost task only for its own worker, and only after a loss that gave a reset time', () => {
+ const { f, lead, group, worker, other, as, task, limit } = lostFixture()
+ limit()
+ const assignmentId = task().assignment!.id
+ for (const actor of [as(other), as(lead), owner]) {
+ expect(() => f.run({ type: 'work.resume', conversationId: group, assignmentId, lostAt: 1000 }, actor, { now: 3_600_000 }))
+ .toThrow('Only the agent that lost this task resumes it.')
+ }
+ const plain = lostFixture()
+ plain.f.run({ type: 'agent.alert', agentId: plain.worker, alert: 'limit', active: true }, plain.as(plain.worker))
+ expect(() => plain.f.run({ type: 'work.resume', conversationId: plain.group, assignmentId: plain.task().assignment!.id, lostAt: 1000 }, plain.as(plain.worker), { now: 99_000_000 }))
+ .toThrow('This task was not lost to a usage limit with a reset time.')
+ })
+
it('does not lose work a Lead holds: Leads are not covered here', () => {
const { f, lead, as } = lostFixture()
const own = f.group()
@@ -2447,3 +2575,33 @@ describe('lost work (liveness.ts)', () => {
expect(f.state.conversations.find(c => c.id === own)!.assignment!.status).toBe('working')
})
})
+
+describe('the morning digest setting (digest.ts)', () => {
+ const setup = () => {
+ const f = fixture()
+ const lead = f.add('lead', 'owner', 'lead', true), worker = f.add('worker', 'owner', f.group())
+ const as = (agentId: string): Actor => ({ kind: 'agent', agentId, machineOwnerId: 'host-owner' })
+ const digest = () => f.state.projects?.find(p => p.id === 'lead')?.digest
+ return { f, lead, worker, as, digest }
+ }
+
+ it('sets the project\'s local digest time for a person or its Lead, from tomorrow once today\'s has passed, and clears it', () => {
+ const { f, lead, as, digest } = setup()
+ // 07:00 on 27 October in Vietnam.
+ const at = { now: Date.UTC(2026, 9, 27, 0, 0) }
+ f.run({ type: 'project.digest', projectId: 'lead', time: '08:00', timeZone: 'Asia/Ho_Chi_Minh' }, owner, at)
+ expect(digest()).toEqual({ time: '08:00', timeZone: 'Asia/Ho_Chi_Minh' })
+ f.run({ type: 'project.digest', projectId: 'lead', time: '06:30', timeZone: 'Asia/Ho_Chi_Minh' }, as(lead), at)
+ expect(digest()).toEqual({ time: '06:30', timeZone: 'Asia/Ho_Chi_Minh', lastOn: '2026-10-27' })
+ f.run({ type: 'project.digest', projectId: 'lead', time: null, timeZone: 'Asia/Ho_Chi_Minh' }, owner, at)
+ expect(digest()).toBeUndefined()
+ })
+
+ it('refuses a worker, an unknown time zone and a time that is not a time of day', () => {
+ const { f, worker, as, digest } = setup()
+ expect(() => f.run({ type: 'project.digest', projectId: 'lead', time: '08:00', timeZone: 'UTC' }, as(worker))).toThrow('A person or the project’s Lead sets its morning digest.')
+ expect(() => f.run({ type: 'project.digest', projectId: 'lead', time: '08:00', timeZone: 'Mars/Olympus' })).toThrow('Name a time zone such as Asia/Ho_Chi_Minh.')
+ expect(() => f.run(commandSchema.parse({ type: 'project.digest', projectId: 'lead', time: '24:00', timeZone: 'UTC' }))).toThrow()
+ expect(digest()).toBeUndefined()
+ })
+})
diff --git a/backend/src/superTabs/commands.ts b/backend/src/superTabs/commands.ts
index 9fc274e86..76eb55952 100644
--- a/backend/src/superTabs/commands.ts
+++ b/backend/src/superTabs/commands.ts
@@ -11,11 +11,14 @@ import { routingOverrideSchema } from './routingPolicy.js'
import { agentTarget, askedInSchema, broken, MAX_RULES, RULE_MESSAGE_MS, ruleSchema, ruleTextSchema, startTarget, type RunTarget } from './rules.js'
import { MAX_ATTACHMENTS, type Attachment } from './attachments.js'
import { checkMentions, MAX_MENTIONS, type MentionTarget } from './mentions.js'
-import { TERMINAL_KEYS, terminalAlert, terminalRequest, terminalResult, type TerminalRequest } from './terminal.js'
+import { ANSWERED_NOTICE, answerDecision, askDecisions, checkAsker, decisionChoices, decisionQuestion, MAX_QUESTIONS, type DecisionTarget } from './decisions.js'
+import { TERMINAL_KEYS, terminalAlert, terminalRequest, terminalResult, toLead, type TerminalRequest } from './terminal.js'
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 { agentKind, agentProjectId, audienceOf, agentSetRole, 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'
+import { recordAnswer, recordAsked, recordStatus } from './leaderboard/record.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'
const id = z.string().min(1).max(160).regex(/^[A-Za-z0-9_-]+$/)
const title = z.string().trim().min(1).max(160)
@@ -81,6 +84,8 @@ export const commandSchema = z.discriminatedUnion('type', [
z.object({ type: z.literal('project.delete'), projectId: id }).strict(),
z.object({ type: z.literal('project.sharing'), projectId: id, visibility: z.enum(['public', 'private']), memberIds: z.array(id).max(200) }).strict(),
z.object({ type: z.literal('project.cadence'), projectId: id, minutes: z.union([z.literal(1), z.literal(5), z.literal(15), z.literal(30)]) }).strict(),
+ // A local time of day ("08:00") in an IANA zone; null turns the digest off.
+ z.object({ type: z.literal('project.digest'), projectId: id, time: z.string().regex(/^(?:[01]\d|2[0-3]):[0-5]\d$/).nullable(), timeZone: z.string().min(1).max(64) }).strict(),
// `through`: each conversation's sequence the Lead read, as its wake-up names them. `throughRevision` is the tab revision a
// wake-up from before the store by parts named; it is accepted only up to that split (projectUpdates.ts).
z.object({ type: z.literal('project.report'), projectId: id, through: z.record(id, z.number().int().nonnegative().safe()).optional(),
@@ -94,12 +99,13 @@ export const commandSchema = z.discriminatedUnion('type', [
z.object({ type: z.literal('project.roles.reset'), projectId: id, roles: roleSet }).strict(),
// `audience`: a private conversation that only these people and the project's Lead read (projects.ts canReadGroup).
z.object({ type: z.literal('conversation.create'), projectId: id.optional(), title, brief: z.string().trim().max(8000).optional(), task: task.optional(), reviewOf: id.optional(), checks: z.array(check).max(40),
- audience: z.object({ personIds: z.array(id).max(200) }).strict().optional() }).strict()
+ audience: z.object({ personIds: z.array(id).max(200) }).strict().optional(), requesterId: id.optional() }).strict()
.refine(c => c.task !== undefined || c.brief !== undefined, 'Provide a task or brief.')
.refine(c => !c.task || renderWorkTask(c.task).length <= 8000, 'Keep the rendered task within 8,000 characters.'),
z.object({ type: z.literal('conversation.rename'), conversationId: id, title }).strict(),
z.object({ type: z.literal('conversation.archive'), conversationId: id, archived: z.boolean() }).strict(),
z.object({ type: z.literal('conversation.audience'), conversationId: id, personIds: z.array(id).max(200) }).strict(),
+ z.object({ type: z.literal('conversation.requester'), conversationId: id, personId: id.nullable() }).strict(),
z.object({ type: z.literal('agent.add'), conversationId: id, machineId: id, harnessId: id, name: title, configuration, lead: z.boolean(), project: project.optional(), roleId: roleId.optional(), initialMessage: text.optional() }).strict(),
z.object({ type: z.literal('agent.start'), request: startRequestSchema, routeDecisionId: id.optional(), overrideReason: reason.optional() }).strict(),
z.object({ type: z.literal('agent.startDispatch'), startId: id }).strict(),
@@ -124,14 +130,20 @@ export const commandSchema = z.discriminatedUnion('type', [
z.object({ type: z.literal('message.send'), conversationId: id, text: z.string().trim().max(32_000), replyTo: id.nullable(), recipientIds: z.array(id).max(16),
attachmentIds: z.array(id).max(MAX_ATTACHMENTS).optional(), mentions: z.array(id).max(MAX_MENTIONS).optional(), agentOnly: z.literal(true).optional() }).strict(),
z.object({ type: z.literal('mention.done'), mentionId: id }).strict(),
+ z.object({ type: z.literal('decision.ask'), conversationId: id, personId: id, questions: z.array(decisionQuestion).min(1).max(MAX_QUESTIONS) }).strict(),
+ z.object({ type: z.literal('decision.answer'), decisionId: id, choice: z.number().int().min(0), note: z.string().trim().min(1).max(2000).optional() }).strict(),
z.object({ type: z.literal('delivery.resolve'), deliveryId: id, resolution: z.enum(['received', 'resend', 'cancel']) }).strict(),
z.object({ type: z.literal('work.define'), conversationId: id, brief: text.optional(), task: task.optional(), checks: z.array(check).min(1).max(40) }).strict()
.refine(c => c.task !== undefined || c.brief !== undefined, 'Provide a task or brief.')
.refine(c => !c.task || renderWorkTask(c.task).length <= 32_000, 'Keep the rendered task within 32,000 characters.'),
z.object({ type: z.literal('work.assign'), conversationId: id, agentId: id, roleId: roleId.optional(), routeDecisionId: id.optional(), overrideReason: reason.optional() }).strict(),
z.object({ type: z.literal('work.status'), conversationId: id, assignmentId: id,
- status: z.enum(['working', 'needs_human', 'blocked', 'review', 'done', 'stopped']), result: text.nullable() }).strict(),
+ status: z.enum(['working', 'needs_human', 'blocked', 'review', 'done', 'stopped']), result: text.nullable(),
+ // A worker's question for one named person, opened as a decision (decisions.ts); the result is the question.
+ ask: decisionChoices.extend({ personId: id }).strict().optional() }).strict(),
z.object({ type: z.literal('work.cancel'), conversationId: id, assignmentId: id, reason }).strict(),
+ // `lostAt` names the loss being resumed (Assignment.lost.at): one task can be lost to a limit, resumed and lost again.
+ z.object({ type: z.literal('work.resume'), conversationId: id, assignmentId: id, lostAt: z.number().int().nonnegative().safe() }).strict(),
z.object({ type: z.literal('route.record'), conversationId: id, decision: routeRecordSchema }).strict(),
z.object({ type: z.literal('route.override'), decisionId: id, candidateId: z.string().regex(/^c\d{1,2}$/), reason }).strict(),
z.object({ type: z.literal('route.modelResult'), decisionId: id, startId: id, model: z.string().min(1).max(200), effort: z.string().min(1).max(80) }).strict(),
@@ -233,6 +245,8 @@ export interface CommandContext {
terminalRequest?: TerminalRequest
/** The mention `mention.done` names, read from SuperTabMention by the store. */
mention?: MentionTarget
+ /** The decision `decision.answer` names, read from SuperTabDecision by the store. */
+ decision?: DecisionTarget
/** The tab's contributed machines whose account row is signed in as a Harness Team account (`Machine.sessionKind`),
* read by the store for the commands that start, assign or route work (machines.ts teamWorkCheck). */
teamMachines?: string[]
@@ -346,7 +360,8 @@ function dropClosing(state: SuperTabState, keep: (request: NonNullable<SuperTabS
export function authorizeCommandAccess(state: SuperTabState, actor: Actor, command: Command, context: Partial<CommandContext> = {}) {
if (command.type === 'invite.accept' || command.type === 'agent.sessionClosed' || command.type === 'machine.cleaned') return
// Marking one's own tag done changes only one's own list, so a viewer may do it too.
- if (command.type === 'mention.done') return void author(state, actor)
+ // Answering a decision asked of oneself changes only that decision, so a viewer may do it too.
+ if (command.type === 'mention.done' || command.type === 'decision.answer') return void author(state, actor)
const leaving = command.type === 'member.remove' && actor.kind === 'person' && command.userId === actor.userId
author(state, actor, !leaving)
// An invitation's group is only where the person lands, and invite.create replaces a deleted one (inviteLanding).
@@ -381,6 +396,12 @@ export function postable(state: SuperTabState, actor: Actor, conversationId: str
function owner(state: SuperTabState, actor: Actor): void {
if (actor.kind !== 'person' || actor.userId !== state.ownerId) fail('OWNER_REQUIRED', 'Only the Super Tab owner can manage invitations.', 403)
}
+/** A requester is a member who can read the project the work is in. */
+function requester(state: SuperTabState, project: SwarmProject, personId: string): string {
+ const member = person(state, personId)
+ if (!canReadProject(state, { kind: 'person', userId: member.id, email: member.email }, project)) fail('REQUESTER_UNAVAILABLE', 'Name a person who can read this project.', 400)
+ return member.id
+}
function open(state: SuperTabState, conversationId: string) {
const group = conversation(state, conversationId)
if (group.archived) fail('ARCHIVED', 'Reopen this conversation before changing its work.')
@@ -448,7 +469,7 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
}
const leaving = command.type === 'member.remove' && actor.kind === 'person' && command.userId === actor.userId
- const sender = author(state, actor, !leaving)
+ const sender = author(state, actor, !leaving && command.type !== 'decision.answer')
authorizeCommandAccess(state, actor, command, context)
const rememberAttempt = (group: ReturnType<typeof conversation>) => {
if (group.assignment) effects.previousAttempts.push(structuredClone({ conversationId: group.id,
@@ -664,7 +685,13 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
break
case 'agent.alert': {
effects.messages.push(...terminalAlert(state, actor, sender, operationId, context.now, command))
- if (command.alert === 'limit' && command.active) effects.messages.push(...loseTasks(state, context.now, worker => worker.id === command.agentId))
+ // A usage limit or a model that keeps failing loses its task at once (liveness.ts); a waiting prompt does not.
+ if (command.alert !== 'prompt' && command.active) {
+ // A reset time the limit screen gave is when the task resumes in this same session unless it is handed on first.
+ const resumeAt = command.alert === 'limit' && command.resetAt && Date.parse(command.resetAt) > context.now
+ ? agent(state, command.agentId).limitedUntil ?? undefined : undefined
+ effects.messages.push(...loseTasks(state, context.now, worker => worker.id === command.agentId, resumeAt))
+ }
break
}
case 'project.report': {
@@ -803,6 +830,21 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
projectOf(state, project.id).updateMinutes = command.minutes
break
}
+ case 'project.digest': {
+ const project = readProject(state, actor, command.projectId)
+ const lead = conversation(state, project.leadConversationId).leadId
+ if (actor.kind !== 'person' && !(actor.kind === 'agent' && actor.agentId === lead)) fail('FORBIDDEN', 'A person or the project’s Lead sets its morning digest.', 403)
+ if (!knownTimeZone(command.timeZone)) fail('TIME_ZONE', 'Name a time zone such as Asia/Ho_Chi_Minh.', 400)
+ mutableProjects(state)
+ const stored = projectOf(state, project.id)
+ if (command.time === null) delete stored.digest
+ else {
+ // Set after today's time, the first digest comes tomorrow rather than at once.
+ const lastOn = digestStartsAfter(command.time, command.timeZone, context.now)
+ stored.digest = { time: command.time, timeZone: command.timeZone, ...lastOn ? { lastOn } : {} }
+ }
+ break
+ }
case 'tab.project': {
controls(state, actor)
if (actor.kind === 'person') owner(state, actor)
@@ -949,7 +991,7 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
if (state.paused) fail('PAUSED', 'New work is paused in this Super Tab.')
if (command.audience) {
// A private conversation is chat only: no task, checks or review, so private work never reaches other Leads.
- if (command.task || command.checks.length || command.reviewOf) fail('AUDIENCE_CHAT_ONLY', 'A private conversation is chat only.', 400)
+ if (command.task || command.checks.length || command.reviewOf || command.requesterId) fail('AUDIENCE_CHAT_ONLY', 'A private conversation is chat only.', 400)
if (actor.kind === 'person' && !command.audience.personIds.includes(actor.userId)) {
fail('AUDIENCE_SELF', 'Open a private conversation with yourself in it.', 403)
}
@@ -965,6 +1007,7 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
}
requireCustomRole(project, 'reviewer')
}
+ const requesterId = command.requesterId ? requester(state, project, command.requesterId) : actor.kind === 'person' ? actor.userId : undefined
const number = nextConversationNumber(state)
state.groupCounter = number
state.conversations.push({ id: operationId, ...(state.projects ? { projectId: project.id } : {}),
@@ -974,15 +1017,38 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
assignment: null, lastMessageSequence: 0,
checks: command.checks.map((c, i) => ({ ...c, id: stableId(operationId, String(i)), evidence: null, passedBy: null })),
})
+ recordAsked(state.conversations.at(-1)!, requesterId, context.now)
result.conversationId = operationId
result.number = number
if (brief) message(operationId, brief, [], null, SYSTEM_ROW)
break
}
+ case 'decision.ask': {
+ const group = open(state, command.conversationId)
+ effects.decisions = askDecisions(state, group, command.personId, command.questions,
+ { operationId, askerAgentId: checkAsker(state, actor, group), assignmentId: null })
+ result.decisionIds = effects.decisions.map(d => d.id)
+ break
+ }
+ case 'decision.answer': {
+ const { answer, recipients, source } = answerDecision(state, actor, context.decision, command.choice, command.note ?? null)
+ effects.decisionAnswer = answer
+ if (recipients.length) message(context.decision!.conversationId, ANSWERED_NOTICE, recipients, null, source)
+ result.decisionId = answer.id
+ break
+ }
case 'conversation.rename':
controls(state, actor, command.conversationId)
open(state, command.conversationId).title = command.title
break
+ case 'conversation.requester': {
+ chatOnly(command.conversationId)
+ controls(state, actor, command.conversationId)
+ const group = open(state, command.conversationId)
+ if (command.personId) group.requesterId = requester(state, groupProject(state, group), command.personId)
+ else delete group.requesterId
+ break
+ }
case 'conversation.audience': {
// Who may read it already passed (readConversation): only its listed people and the project's Lead get here.
const group = open(state, command.conversationId)
@@ -1222,8 +1288,8 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
if (!isLead && !isOwner) fail('FORBIDDEN', 'Only this project’s Lead, the contributor or tab owner can release a worker.', 403)
protectLead(state, target.id)
if (state.conversations.some(c => c.leadId === target.id)) fail('LEAD_REQUIRED', 'Release workers only; keep the Lead running.')
+ // Only its own active work holds a decision back, not the active work of a group it sits in (a Reviewer's).
if (state.conversations.some(c => activeWork(c) && c.assignment?.agentId === target.id)) fail('WORK_ACTIVE', 'Finish active work before releasing this worker.')
- if (reviewing(state, target.id)) fail('WORK_ACTIVE', 'This Reviewer is reviewing active work. Remove it from that group or wait for the work to end.')
// A Reviewer is never assigned work, so the Lead may keep or stop it at any time.
if (!target.workDecision && agentRole(target) !== 'reviewer' && !state.conversations.some(c => c.assignment?.agentId === target.id)) {
fail('WORK_REQUIRED', 'This worker has no finished assignment to release.')
@@ -1383,6 +1449,7 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
}
// The transcript still accepts a human message while the lead is unavailable. The UI can say why no delivery was created.
message(group.id, command.text, recipients, command.replyTo, command.agentOnly ? AGENT_ONLY : undefined, attachments, mentions)
+ recordAnswer(state, group, actor, command.replyTo, context.now)
if (actor.kind === 'agent') renewOwnTask(group, actor.agentId, context.now)
break
}
@@ -1558,9 +1625,18 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
if (command.status === 'done' && (!command.result || !group.checks.every(c => c.passedBy && c.evidence))) {
fail('CHECKS_PENDING', 'Completion needs a result and evidence for every acceptance check.')
}
- const changed = assignment.status !== command.status || assignment.result !== command.result
+ if (command.ask) {
+ if (command.status !== 'needs_human' || !command.result || actor.kind !== 'agent') {
+ fail('INVALID_DECISION', 'An agent asks a person for a decision only when its work needs a human, with the question as its result.', 400)
+ }
+ const { personId, ...choices } = command.ask
+ effects.decisions = askDecisions(state, group, personId, [{ question: command.result, ...choices }],
+ { operationId, askerAgentId: actor.agentId, assignmentId: assignment.id })
+ }
+ const changed = assignment.status !== command.status || assignment.result !== command.result || !!command.ask, previous = assignment.status
assignment.status = command.status
assignment.result = command.result
+ recordStatus(group, assignment, previous, context.now, changed ? operationId : null)
if (['done', 'stopped'].includes(command.status)) finishWorker(state, assignment.agentId, group)
// Finished work shows the worker recovered from a task it lost before.
if (command.status === 'done') delete state.agents.find(a => a.id === assignment.agentId)?.lostTask
@@ -1573,7 +1649,8 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
// Ready for review also wakes the group's Reviewers, whoever marked it.
const reviewers = command.status !== 'review' ? [] : group.agentIds.filter(id => id !== lead &&
(actor.kind !== 'agent' || id !== actor.agentId) && state.agents.some(a => a.id === id && agentRole(a) === 'reviewer' && a.workDecision !== 'stop'))
- message(group.id, `${label}${command.result ? `\n\n${command.result}` : ''}`, [...(tellLead ? [lead] : []), ...reviewers], null, SYSTEM_ROW)
+ const asked = command.ask ? `\n\nAsked ${person(state, command.ask.personId).email}.` : ''
+ message(group.id, `${label}${command.result ? `\n\n${command.result}` : ''}${asked}`, [...(tellLead ? [lead] : []), ...reviewers], null, SYSTEM_ROW)
}
if (actor.kind === 'agent') renewOwnTask(group, actor.agentId, context.now)
break
@@ -1601,6 +1678,31 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
gone ? [] : [assignment.agentId], null, SYSTEM_ROW)
break
}
+ case 'work.resume': {
+ // Its usage limit has reset: the session that lost this task to it takes it back, unless it was handed on first. Its
+ // host asks here before typing into the session (cli superTabs/limitResume.ts), so a task handed on never resumes.
+ const group = open(state, command.conversationId)
+ const assignment = group.assignment
+ if (assignment?.id !== command.assignmentId || assignment.status !== 'lost' || assignment.lost?.at !== command.lostAt) {
+ fail('TASK_MOVED', 'This task was handed on or closed, so it does not resume.')
+ }
+ if (actor.kind !== 'agent' || actor.agentId !== assignment.agentId) fail('FORBIDDEN', 'Only the agent that lost this task resumes it.', 403)
+ const worker = agent(state, assignment.agentId)
+ const resumeAt = assignment.lost?.resumeAt
+ if (!resumeAt) fail('NO_RESUME', 'This task was not lost to a usage limit with a reset time.')
+ if (context.now < Date.parse(resumeAt)) fail('LIMIT_NOT_RESET', 'Its usage limit has not reset yet.')
+ if (worker.harnessId !== assignment.execution.harnessId) fail('SESSION_CHANGED', 'This agent runs in another session now, so the task does not resume.')
+ if (state.conversations.some(c => activeWork(c) && c.assignment?.agentId === worker.id)) fail('AGENT_BUSY', 'This agent already owns an active assignment.')
+ assignment.status = 'working'
+ delete assignment.lost
+ delete group.lostAttempt
+ delete worker.lostTask
+ renewLease(assignment, context.now)
+ effects.messages.push(...toLead(state, worker, { id: stableId(operationId, 'resumed'), conversationId: group.id, author: sender, replyTo: null,
+ recipients: [], text: `${worker.displayName ?? worker.name} resumed its task after its usage limit reset.`,
+ source: { kind: 'work-resumed', agentId: worker.id, assignmentId: assignment.id } }))
+ break
+ }
case 'work.check': {
const group = open(state, command.conversationId)
fenceLost(group, command.assignmentId)
diff --git a/backend/src/superTabs/decisions.test.ts b/backend/src/superTabs/decisions.test.ts
new file mode 100644
index 000000000..ff8a0b364
--- /dev/null
+++ b/backend/src/superTabs/decisions.test.ts
@@ -0,0 +1,110 @@
+import { describe, expect, it } from 'vitest'
+import { applyCommand, commandSchema, type Command, type CommandContext } from './commands.js'
+import { createSuperTab, type Actor, type AgentConfiguration } from './model.js'
+import type { DecisionTarget } from './decisions.js'
+
+const owner: Extract<Actor, { kind: 'person' }> = { kind: 'person', userId: 'owner', email: '[email protected]' }
+const peer: Extract<Actor, { kind: 'person' }> = { kind: 'person', userId: 'peer', email: '[email protected]' }
+const config: AgentConfiguration = { engine: 'codex', model: 'test-model', effort: 'high', contextWindow: 200000, engineVersion: 'fixture' }
+const asAgent = (agentId: string): Actor => ({ kind: 'agent', agentId, machineOwnerId: 'host-owner' })
+const question = (text: string, recommended = 0) => ({ question: text, options: ['Behind a flag', 'To everyone'], recommended, unblocks: 'The release' })
+
+/** A Swarm with the peer in it, a Lead, and a worker assigned to one group. */
+function swarm() {
+ let state = createSuperTab('tab', 'Pilot', { id: 'owner', email: owner.email }, 'prod')
+ let sequence = 0
+ const run = (command: Command, actor: Actor = owner, context: Partial<CommandContext> = {}) => {
+ const effects = applyCommand(state, actor, command, { now: 1000, operationId: `op-${++sequence}`, ...context })
+ state = effects.state
+ return effects
+ }
+ const invited = run({ type: 'invite.create', email: peer.email, role: 'collaborator', conversationId: 'lead' })
+ run({ type: 'invite.accept', inviteId: invited.result.inviteId as string }, peer)
+ const add = (harnessId: string, group: string, lead = false) => run({ type: 'agent.add', conversationId: group, machineId: 'host', harnessId,
+ name: harnessId, configuration: config, lead }, owner, { contribution: { machineOwnerId: 'host-owner', contributorId: 'owner' } }).result.agentId as string
+ const lead = add('lead', 'lead', true)
+ const group = run({ type: 'conversation.create', title: 'Offline editing', brief: 'Save edits while offline.',
+ checks: [{ description: 'Reconnect preserves the edits.', independent: true }] }).result.conversationId as string
+ const worker = add('worker', group)
+ const assignmentId = run({ type: 'work.assign', conversationId: group, agentId: worker }).result.assignmentId as string
+ return { run, lead, group, worker, assignmentId, get state() { return state } }
+}
+
+describe('asking a person for decisions', () => {
+ it('lets the Lead ask one person several questions at once, each with options, a recommendation and what it unblocks', () => {
+ const s = swarm()
+ const asked = s.run({ type: 'decision.ask', conversationId: s.group, personId: 'peer', questions: [question('Ship how?'), question('Which name?', 1)] }, asAgent(s.lead))
+ expect(asked.decisions).toHaveLength(2)
+ expect(asked.decisions![0]).toMatchObject({ conversationId: s.group, projectId: 'lead', personId: 'peer', askerAgentId: s.lead, assignmentId: null,
+ question: 'Ship how?', options: ['Behind a flag', 'To everyone'], recommended: 0, unblocks: 'The release' })
+ expect(asked.decisions![1]).toMatchObject({ question: 'Which name?', recommended: 1 })
+ // One batch for the person: one id ties the questions together, and nobody is pinged in the transcript.
+ expect(new Set(asked.decisions!.map(d => d.batchId)).size).toBe(1)
+ expect(new Set(asked.decisions!.map(d => d.id)).size).toBe(2)
+ expect(asked.messages).toEqual([])
+ expect(asked.result.decisionIds).toEqual(asked.decisions!.map(d => d.id))
+ })
+
+ it('refuses a question from anyone but the project\'s Lead, to someone outside the Swarm, or with a recommendation that is not an option', () => {
+ const s = swarm()
+ const ask = (actor: Actor, personId = 'peer', recommended = 0) =>
+ () => s.run({ type: 'decision.ask', conversationId: s.group, personId, questions: [question('Ship how?', recommended)] }, actor)
+ expect(ask(asAgent(s.worker))).toThrow('Lead')
+ expect(ask(owner)).toThrow('Lead')
+ expect(ask(asAgent(s.lead), 'stranger')).toThrow('person in this Swarm')
+ expect(ask(asAgent(s.lead), 'peer', 2)).toThrow('recommend one of its options')
+ expect(commandSchema.safeParse({ type: 'decision.ask', conversationId: s.group, personId: 'peer',
+ questions: [{ ...question('One option only'), options: ['Yes'] }] }).success).toBe(false)
+ expect(commandSchema.safeParse({ type: 'decision.ask', conversationId: s.group, personId: 'peer',
+ questions: Array.from({ length: 11 }, (_, i) => question(`Question ${i}`)) }).success).toBe(false)
+ })
+
+ it('opens a decision for the named person when a worker needs one on its own task, and still tells the Lead', () => {
+ const s = swarm()
+ const needs = s.run({ type: 'work.status', conversationId: s.group, assignmentId: s.assignmentId, status: 'needs_human', result: 'Ship to everyone, or behind a flag?',
+ ask: { personId: 'peer', options: ['Behind a flag', 'To everyone'], recommended: 0, unblocks: 'Turning the feature on' } }, asAgent(s.worker))
+ expect(needs.decisions).toEqual([expect.objectContaining({ personId: 'peer', askerAgentId: s.worker, assignmentId: s.assignmentId,
+ question: 'Ship to everyone, or behind a flag?', recommended: 0, unblocks: 'Turning the feature on' })])
+ expect(needs.messages[0]).toMatchObject({ text: 'Needs a human\n\nShip to everyone, or behind a flag?\n\nAsked [email protected].', recipients: [s.lead] })
+ // Without a person and options it reaches the Lead as before, who asks.
+ const plain = s.run({ type: 'work.status', conversationId: s.group, assignmentId: s.assignmentId, status: 'needs_human', result: 'Which database?' }, asAgent(s.worker))
+ expect(plain.decisions ?? []).toEqual([])
+ expect(() => s.run({ type: 'work.status', conversationId: s.group, assignmentId: s.assignmentId, status: 'blocked', result: 'Stuck',
+ ask: { personId: 'peer', options: ['A', 'B'], recommended: 0, unblocks: 'X' } }, asAgent(s.worker))).toThrow('needs a human')
+ })
+})
+
+describe('answering a decision', () => {
+ const open = (s: ReturnType<typeof swarm>, overrides: Partial<DecisionTarget> = {}): DecisionTarget => ({ id: 'decision-1', personId: 'peer',
+ conversationId: s.group, askerAgentId: s.worker, question: 'Ship how?', options: ['Behind a flag', 'To everyone'], answeredAt: null, ...overrides })
+
+ it('records the asked person\'s choice and tells the asking agent and the Lead with a notice only they read, carrying none of it', () => {
+ const s = swarm()
+ const answered = s.run({ type: 'decision.answer', decisionId: 'decision-1', choice: 1, note: 'We are confident.' }, peer, { decision: open(s) })
+ expect(answered.decisionAnswer).toEqual({ id: 'decision-1', choice: 1, note: 'We are confident.' })
+ expect(answered.messages).toEqual([expect.objectContaining({ conversationId: s.group, recipients: [s.worker, s.lead],
+ source: { kind: 'agent-only', decisionId: 'decision-1' } })])
+ for (const text of ['Ship how?', 'To everyone', 'We are confident.']) expect(answered.messages[0]!.text).not.toContain(text)
+ })
+
+ it('takes an answer only from the person asked, once, and only for one of its options', () => {
+ const s = swarm()
+ const answer = (actor: Actor, decision: DecisionTarget | undefined, choice = 0) =>
+ () => s.run({ type: 'decision.answer', decisionId: 'decision-1', choice }, actor, decision ? { decision } : {})
+ expect(answer(owner, open(s))).toThrow('unavailable')
+ expect(answer(peer, undefined)).toThrow('unavailable')
+ expect(answer(peer, open(s, { answeredAt: 5 }))).toThrow('already answered')
+ expect(answer(peer, open(s), 2)).toThrow('Choose one of its options')
+ // A person who can no longer read its conversation cannot answer it, though they stay in the Swarm.
+ const hidden = s.run({ type: 'conversation.create', title: 'Owner only', brief: '', checks: [], audience: { personIds: ['owner'] } }).result.conversationId as string
+ expect(answer(peer, open(s, { conversationId: hidden }))).toThrow('unavailable')
+ expect(answer(peer, open(s, { conversationId: 'gone' }))).toThrow('unavailable')
+ })
+
+ it('still records the answer when the asker has left the conversation, telling whoever of them is left', () => {
+ const s = swarm()
+ const answered = s.run({ type: 'decision.answer', decisionId: 'decision-1', choice: 0 }, peer, { decision: open(s, { askerAgentId: 'gone' }) })
+ expect(answered.decisionAnswer).toEqual({ id: 'decision-1', choice: 0, note: null })
+ expect(answered.messages[0]!.recipients).toEqual([s.lead])
+ })
+})
diff --git a/backend/src/superTabs/decisions.ts b/backend/src/superTabs/decisions.ts
new file mode 100644
index 000000000..be62c5c6e
--- /dev/null
+++ b/backend/src/superTabs/decisions.ts
@@ -0,0 +1,157 @@
+/** A person's decisions (design: decisions in one place). The Lead, or a worker on its own task through needs_human, asks
+ * one person a batch of questions, each with options, a recommendation and what it unblocks; the person answers each
+ * with one tap, and the answer reaches the asking agent and the Lead in the conversation it came from. Decisions live in
+ * SuperTabDecision, never in the tab state, as mentions do. A decision is not a private channel: anything private goes
+ * through Chat with PM. Called inside SuperTabStore's transactions. */
+import type { Prisma } from '@prisma/client'
+import { z } from 'zod'
+import { AGENT_ONLY, fail, isLeads, person, stableId, type Actor, type Conversation, type SuperTabState } from './model.js'
+import { canReadGroup, groupProject, ledProject, projectOf } from './projects.js'
+
+type Tx = Prisma.TransactionClient
+export const MAX_QUESTIONS = 10
+
+const line = (max: number) => z.string().trim().min(1).max(max)
+/** What a question offers besides itself: 2–5 distinct options, the index of the recommended one, and what an answer unblocks. */
+export const decisionChoices = z.object({ options: z.array(line(200)).min(2).max(5).refine(o => new Set(o).size === o.length, 'Give distinct options.'),
+ recommended: z.number().int().min(0), unblocks: line(300) }).strict()
+export const decisionQuestion = decisionChoices.extend({ question: line(1000) }).strict()
+type Question = z.infer<typeof decisionQuestion>
+
+/** 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
+}
+/** The decision `decision.answer` names, read from SuperTabDecision by the store. */
+export interface DecisionTarget {
+ id: string; personId: string; conversationId: string; askerAgentId: string; question: string; options: string[]; answeredAt: number | null
+}
+export interface DecisionAnswer { id: string; choice: number; note: string | null }
+
+/** 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[] {
+ 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)
+ }
+ 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 }))
+}
+
+/** Only the project's Lead asks with `decision.ask`, in its own project's conversations (a worker asks through needs_human). */
+export function checkAsker(state: SuperTabState, actor: Actor, group: Conversation): string {
+ const led = actor.kind === 'agent' ? ledProject(state, actor.agentId) : undefined
+ if (!led || isLeads(group) || groupProject(state, group).id !== led.id) {
+ fail('DECISION_FORBIDDEN', 'Only a project’s Lead asks for decisions in its own project’s conversations.', 403)
+ }
+ return (actor as Extract<Actor, { kind: 'agent' }>).agentId
+}
+
+/** The conversation a decision was asked in, while the person asked is still in the Swarm and still reads it: checked on
+ * every answer and on every retry of one (review of #1753). Anyone else is told it does not exist. */
+export function answerable(state: SuperTabState, actor: Actor, decision: DecisionTarget | undefined): Conversation {
+ const asked = actor.kind === 'person' && decision?.personId === actor.userId && state.people.some(p => p.id === actor.userId)
+ const group = asked ? state.conversations.find(c => c.id === decision.conversationId) : undefined
+ if (!group || !canReadGroup(state, actor, group)) fail('NOT_FOUND', 'This decision is unavailable.', 404)
+ return group
+}
+
+/** What tells the asking agent and the Lead, whichever of them is still in the conversation. A notice only they read, with
+ * none of the answer in it: the decisions read, which checks who reads it, has the answer (review of #1753). */
+export const ANSWERED_NOTICE = 'A decision asked in this conversation was answered. Read the answer with: harness super-tab decisions --answered'
+
+/** The asked person's one answer, and the notice for the asking agent and the Lead. */
+export function answerDecision(state: SuperTabState, actor: Actor, decision: DecisionTarget | undefined, choice: number, note: string | null) {
+ const group = answerable(state, actor, decision)
+ if (decision!.answeredAt !== null) fail('DECISION_ANSWERED', 'This decision is already answered.')
+ if (choice >= decision!.options.length) fail('INVALID_DECISION', 'Choose one of its options.', 400)
+ const lead = state.conversations.find(c => c.id === groupProject(state, group).leadConversationId)?.leadId
+ const recipients = [...new Set([decision!.askerAgentId, ...lead ? [lead] : []])].filter(id => group.agentIds.includes(id))
+ return { answer: { id: decision!.id, choice, note }, recipients, source: { ...AGENT_ONLY, decisionId: decision!.id } }
+}
+
+/** Mongo omits unset fields, so `answeredAt: null` alone would miss a row written without it. */
+const waiting: Prisma.SuperTabDecisionWhereInput = { OR: [{ answeredAt: null }, { answeredAt: { isSet: false } }] }
+
+/** What makes an ask a repeat: the same asker, task, person, conversation, question, options, recommendation and what it
+ * unblocks. Another asker, another task or other options with the same text is a decision of its own (review of #1753). */
+const repeatKey = (d: Pick<DecisionDraft, 'askerAgentId' | 'assignmentId' | 'personId' | 'conversationId' | 'question' | 'options' | 'recommended' | 'unblocks'>) =>
+ JSON.stringify([d.askerAgentId, d.assignmentId ?? null, d.personId, d.conversationId, d.question, d.options, d.recommended, d.unblocks])
+
+/** Writes the questions asked and returns the decision each one is: an open decision that this ask exactly repeats is that
+ * decision again, not a second one. Read and written in the command's transaction; two identical asks committing at the
+ * same moment can still both be written. */
+export async function writeDecisions(tx: Tx, tabId: string, drafts: DecisionDraft[], now: number): Promise<string[]> {
+ if (!drafts.length) return []
+ const open = await tx.superTabDecision.findMany({ where: { tabId, personId: drafts[0]!.personId, conversationId: drafts[0]!.conversationId,
+ askerAgentId: drafts[0]!.askerAgentId, question: { in: drafts.map(d => d.question) }, ...waiting } })
+ const held = new Map(open.map(o => [repeatKey(o), o.id]))
+ const fresh = drafts.filter(d => !held.has(repeatKey(d)))
+ if (fresh.length) await tx.superTabDecision.createMany({ data: fresh.map(d => ({ ...d, tabId, createdAt: new Date(now) })) })
+ return drafts.map(d => held.get(repeatKey(d)) ?? d.id)
+}
+
+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, askerAgentId: true, question: true, options: true, answeredAt: true } })
+ return row ? { ...row, answeredAt: row.answeredAt?.getTime() ?? null } : undefined
+}
+
+/** Conflicts with a concurrent answer of the same decision: only the first one counts. */
+export async function recordAnswer(tx: Tx, tabId: string, answer: DecisionAnswer, now: number): Promise<void> {
+ const taken = await tx.superTabDecision.updateMany({ where: { id: answer.id, tabId, ...waiting },
+ data: { choice: answer.choice, note: answer.note, answeredAt: new Date(now) } })
+ if (!taken.count) fail('DECISION_ANSWERED', 'This decision is already answered.')
+}
+
+/** Whose decisions a reader sees: a person, those asked of them in conversations they still read; an agent, those it asked,
+ * and a Lead also those asked in its project. Nobody else, owners included. */
+function readerWhere(state: SuperTabState, actor: Actor): Prisma.SuperTabDecisionWhereInput {
+ if (actor.kind === 'person') return { personId: person(state, actor.userId).id }
+ const led = ledProject(state, actor.agentId)
+ return { OR: [{ askerAgentId: actor.agentId }, ...led ? [{ projectId: led.id }] : []] }
+}
+
+/** The conversations [ids] names: those the read loaded, and the rest (quiet, archived, or left out of a light read) read
+ * here, so a decision in one still counts. A deleted conversation is none. */
+async function conversationsOf(tx: Tx, tabId: string, state: SuperTabState, ids: string[]): Promise<Map<string, Conversation>> {
+ const found = new Map(state.conversations.filter(c => ids.includes(c.id)).map(c => [c.id, c]))
+ const missing = [...new Set(ids.filter(id => !found.has(id)))]
+ if (missing.length) {
+ for (const row of await tx.swarmGroup.findMany({ where: { tabId, key: { in: missing }, deleted: false }, select: { key: true, data: true } })) {
+ found.set(row.key, row.data as unknown as Conversation)
+ }
+ }
+ return found
+}
+
+/** ponytail: capped at 200 per state, newest first; page it if a reader ever has more. */
+async function readable(tx: Tx, tabId: string, state: SuperTabState, actor: Actor, open: boolean) {
+ const rows = await tx.superTabDecision.findMany({ where: { tabId, AND: [readerWhere(state, actor), open ? waiting : { answeredAt: { not: null } }] },
+ orderBy: { createdAt: 'desc' }, take: 200 })
+ const groups = await conversationsOf(tx, tabId, state, rows.map(r => r.conversationId))
+ return rows.flatMap(row => {
+ const group = groups.get(row.conversationId)
+ // Checked at every read, for agents too: a reader who can no longer read the conversation no longer reads its decisions.
+ return group && canReadGroup(state, actor, group) ? [{ row, group }] : []
+ })
+}
+
+export async function decisionsWaiting(tx: Tx, tabId: string, state: SuperTabState, actor: Extract<Actor, { kind: 'person' }>): Promise<number> {
+ return (await readable(tx, tabId, state, actor, true)).length
+}
+
+export async function listDecisions(tx: Tx, tabId: string, state: SuperTabState, actor: Actor, open: boolean) {
+ return (await readable(tx, tabId, state, actor, open)).map(({ row, group }) => {
+ const asker = state.agents.find(a => a.id === row.askerAgentId)
+ return { id: row.id, batchId: row.batchId, projectId: row.projectId, projectName: projectOf(state, row.projectId).name,
+ conversationId: row.conversationId, conversationTitle: group.title, assignmentId: row.assignmentId ?? null,
+ personId: row.personId, personEmail: state.people.find(p => p.id === row.personId)?.email ?? null,
+ askerAgentId: row.askerAgentId, askerName: asker?.displayName ?? asker?.name ?? 'Agent',
+ question: row.question, options: row.options, recommended: row.recommended, unblocks: row.unblocks,
+ createdAt: row.createdAt, answeredAt: row.answeredAt ?? null, choice: row.choice ?? null, note: row.note ?? null }
+ })
+}
diff --git a/backend/src/superTabs/digest.test.ts b/backend/src/superTabs/digest.test.ts
new file mode 100644
index 000000000..fa56f2e54
--- /dev/null
+++ b/backend/src/superTabs/digest.test.ts
@@ -0,0 +1,99 @@
+import { describe, expect, it } from 'vitest'
+import type { Agent, Assignment, Conversation, SuperTabState, WorkStatus } from './model.js'
+import { digestDue, digestRequest, projectDigest } from './digest.js'
+
+const HOUR = 60 * 60_000
+/** 08:00 on 27 October in Vietnam (UTC+7), the project's digest time. */
+const EIGHT = Date.UTC(2026, 9, 27, 1, 0)
+const LAST = EIGHT - 24 * HOUR
+
+const agent = (id: string, name: string): Agent => ({ id, name, contributorId: 'owner', membershipGeneration: 'g', machineId: 'mac', harnessId: `h-${id}`,
+ machineOwnerId: 'owner', configuration: { engine: 'claude', model: 'opus', effort: 'high', contextWindow: null, engineVersion: null } } as unknown as Agent)
+const work = (agentId: string, status: WorkStatus, over: Partial<Assignment> = {}): Assignment => ({ id: `w-${agentId}-${status}`, agentId, status,
+ configuration: { engine: 'claude', model: 'opus', effort: 'high', contextWindow: null, engineVersion: null },
+ execution: { machineId: 'mac', harnessId: `h-${agentId}`, machineOwnerId: 'owner' }, result: null, ...over })
+const group = (number: number, title: string, assignment: Assignment | null, over: Partial<Conversation> = {}): Conversation => ({ id: `g${number}`,
+ projectId: 'p1', number, title, leadId: 'lead', agentIds: ['lead', ...assignment ? [assignment.agentId] : []], archived: false, brief: 'Do it.', checks: [],
+ assignment, lastMessageSequence: 1, lastActivityAt: new Date(LAST + HOUR).toISOString(), ...over })
+
+/** lampOS overnight: one task merged, one merged before the last digest, two running, three held up, and another project's work. */
+function fixture(): SuperTabState {
+ return {
+ version: 1, id: 'tab', name: 'Swarm', ownerId: 'owner', environment: 'prod', paused: false, invitations: [],
+ people: [{ id: 'owner', email: '[email protected]', role: 'owner', generation: 'g' }] as SuperTabState['people'],
+ agents: [agent('lead', 'Lead'), agent('nico', 'Nico'), agent('ana', 'Ana'), agent('bo', 'Bo'), agent('cy', 'Cy'), agent('di', 'Di'), agent('ed', 'Ed')],
+ projects: [
+ { id: 'p1', name: 'lampOS', ownerId: 'owner', leadConversationId: 'lead-p1', visibility: 'public', members: [], updateMinutes: 5,
+ digest: { time: '08:00', timeZone: 'Asia/Ho_Chi_Minh', lastAt: LAST, lastOn: '2026-10-26' } },
+ { id: 'p2', name: 'Firmware', ownerId: 'owner', leadConversationId: 'lead-p2', visibility: 'public', members: [], updateMinutes: 5 },
+ ],
+ conversations: [
+ { ...group(0, 'Lead', null), id: 'lead-p1', number: undefined },
+ { ...group(0, 'Lead', null, { projectId: 'p2', leadId: 'lead-2' }), id: 'lead-p2', number: undefined },
+ group(1, 'Night shift', work('nico', 'done', { result: 'Merged.' }), { pullRequestUrls: ['https://github.com/example/lampos/pull/12'] }),
+ group(2, 'Old parser', work('ana', 'done'), { lastActivityAt: new Date(LAST - HOUR).toISOString(), pullRequestUrls: ['https://github.com/example/lampos/pull/3'] }),
+ group(3, 'Lexer', work('ana', 'working')),
+ group(4, 'Docs', work('bo', 'review'), { pullRequestUrls: ['https://github.com/example/lampos/pull/14'] }),
+ group(5, 'Deploy', work('cy', 'blocked', { result: 'No access to staging.' })),
+ group(6, 'Cache', work('di', 'lost', { lost: { reason: 'its machine Studio has been offline for 2 minutes', at: LAST + 2 * HOUR } })),
+ group(7, 'Pricing', work('ed', 'needs_human', { result: 'Which plan do we launch with?' })),
+ group(8, 'Archived spike', work('ed', 'working'), { archived: true }),
+ // Merged and archived overnight: it still shipped (#1757 review, 4).
+ group(10, 'Release notes', work('bo', 'done'), { archived: true, dormant: true, pullRequestUrls: ['https://github.com/example/lampos/pull/15'] }),
+ group(9, 'Bootloader', work('nico', 'working'), { projectId: 'p2', leadId: 'lead-2' }),
+ ],
+ } as SuperTabState
+}
+const lampOS = (state: SuperTabState) => state.projects!.find(p => p.id === 'p1')!
+
+describe('a project\'s morning digest', () => {
+ it('lists what shipped since the last digest, what is in progress and what is held up, from the project\'s own state', () => {
+ expect(projectDigest(fixture(), lampOS(fixture()), LAST)).toBe([
+ 'Shipped:',
+ '- #1 Night shift: https://github.com/example/lampos/pull/12',
+ '- #10 Release notes: https://github.com/example/lampos/pull/15',
+ 'In progress:',
+ '- #3 Lexer: working (Ana)',
+ '- #4 Docs: ready for review (Bo), https://github.com/example/lampos/pull/14',
+ 'Blocked:',
+ '- #5 Deploy: stuck (Cy): No access to staging.',
+ '- #6 Cache: lost (Di): its machine Studio has been offline for 2 minutes',
+ '- #7 Pricing: waits for a person (Ed): Which plan do we launch with?',
+ ].join('\n'))
+ })
+
+ it('shows the decisions waiting only when there are some', () => {
+ expect(projectDigest(fixture(), lampOS(fixture()), LAST, ['Ship the night shift to every Swarm?'])).toMatch(/\nDecisions waiting:\n- Ship the night shift to every Swarm\?$/)
+ expect(projectDigest(fixture(), lampOS(fixture()), LAST, [])).not.toContain('Decisions waiting')
+ })
+
+ it('says so when nothing moved', () => {
+ const state = fixture()
+ state.conversations = state.conversations.filter(c => !c.number || c.projectId !== 'p1')
+ expect(projectDigest(state, lampOS(state), LAST)).toBe('Nothing shipped, in progress or blocked.')
+ })
+
+ it('wakes the project\'s Lead once a day at the project\'s local time, with the digest and what to do with it', () => {
+ const state = fixture(), lead = state.agents.find(a => a.id === 'lead')!
+ expect(digestRequest(state, lead, EIGHT - 60_000)).toBeNull()
+ const wake = digestRequest(state, lead, EIGHT)!
+ expect(wake).toMatchObject({ conversationId: 'lead-p1', recipients: ['lead'], source: { kind: 'digest-request', projectId: 'p1', on: '2026-10-27' } })
+ expect(wake.text).toBe('Morning digest for project "lampOS" (08:00, Asia/Ho_Chi_Minh). This is a scheduled request, not a new task. '
+ + 'Check that each pull request under Shipped is merged, and move one that is not to In progress. Then post one message to the people in this chat '
+ + 'with these parts, in plain words, without commands or internal IDs.\n\n' + projectDigest(state, lampOS(state), LAST))
+ expect(digestDue(lampOS(state), EIGHT)).toBe('2026-10-27')
+ lampOS(state).digest!.lastOn = '2026-10-27'
+ expect(digestRequest(state, lead, EIGHT + 12 * HOUR)).toBeNull()
+ expect(digestRequest(state, lead, EIGHT + 24 * HOUR)).not.toBeNull()
+ })
+
+ it('wakes nobody for a project with no digest time, in a paused Swarm, or for an agent that is not the Lead', () => {
+ const state = fixture()
+ expect(digestRequest(state, state.agents.find(a => a.id === 'nico')!, EIGHT)).toBeNull()
+ state.paused = true
+ expect(digestRequest(state, state.agents.find(a => a.id === 'lead')!, EIGHT)).toBeNull()
+ state.paused = false
+ delete lampOS(state).digest
+ expect(digestRequest(state, state.agents.find(a => a.id === 'lead')!, EIGHT)).toBeNull()
+ })
+})
diff --git a/backend/src/superTabs/digest.ts b/backend/src/superTabs/digest.ts
new file mode 100644
index 000000000..37771cc62
--- /dev/null
+++ b/backend/src/superTabs/digest.ts
@@ -0,0 +1,84 @@
+import { activeWork, author, stableId, type Agent, type Conversation, type MessageDraft, type SuperTabState } from './model.js'
+import { agentDisplayName } from './agentNames.js'
+import { ledProject, type SwarmProject } from './projects.js'
+import { reportGroups } from './projectUpdates.js'
+
+// Night shift (v2 B): people wake to one message per project saying what the Swarm did overnight. At the project's local
+// digest time its Lead's poll wakes the Lead with the lists below, built from state; the Lead checks each pull request is
+// merged and posts them to the people.
+
+/** The first digest covers the day before it. */
+const FIRST_SPAN_MS = 24 * 60 * 60_000
+const IN_PROGRESS: Record<string, string> = { planned: 'planned', working: 'working', review: 'ready for review', reconciling: 'being reconciled' }
+const HELD_UP: Record<string, string> = { blocked: 'stuck', lost: 'lost', needs_human: 'waits for a person' }
+
+/** The project's local date and time ("2026-10-27", "08:00") at `now`. */
+function localNow(timeZone: string, now: number): { date: string; time: string } {
+ const parts = Object.fromEntries(new Intl.DateTimeFormat('en-CA', { timeZone, year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit',
+ minute: '2-digit', hourCycle: 'h23' }).formatToParts(now).map(p => [p.type, p.value]))
+ return { date: `${parts.year}-${parts.month}-${parts.day}`, time: `${parts.hour}:${parts.minute}` }
+}
+
+/** Whether the zone is one this runtime knows. */
+export function knownTimeZone(timeZone: string): boolean {
+ try { localNow(timeZone, 0); return true } catch { return false }
+}
+
+/** The local date of a digest due at `now`, or null: none set, not yet its time today, or today's already sent. */
+export function digestDue(project: SwarmProject, now: number): string | null {
+ const digest = project.digest
+ if (!digest) return null
+ const local = localNow(digest.timeZone, now)
+ return local.time >= digest.time && digest.lastOn !== local.date ? local.date : null
+}
+
+/** Where a project's digest starts: its last one, or the day before the first. */
+export const digestSince = (project: SwarmProject, now: number): number => project.digest?.lastAt ?? now - FIRST_SPAN_MS
+
+/** The date a newly set digest counts as sent for: today, when today's time has already passed, so it starts tomorrow. */
+export function digestStartsAfter(time: string, timeZone: string, now: number): string | undefined {
+ const local = localNow(timeZone, now)
+ return local.time >= time ? local.date : undefined
+}
+
+/**
+ * A project's digest: what shipped since `since` (finished with a pull request; the Lead checks each is merged), what is
+ * in progress, what is held up, and the decisions waiting for people. Each part is left out when it is empty, so the
+ * decisions part appears only once there are decisions to list.
+ */
+export function projectDigest(state: SuperTabState, project: SwarmProject, since: number, decisions: string[] = []): string {
+ // Work that shipped and was archived since still shipped (#1757 review, 4); only open work is in progress or held up.
+ const groups = reportGroups(state, project).filter(g => g.number !== undefined).sort((a, b) => a.number! - b.number!)
+ const open = groups.filter(g => !g.archived)
+ const named = (g: Conversation) => `#${g.number} ${g.title}`
+ const who = (g: Conversation) => agentDisplayName(state.agents, g.assignment!.agentId)
+ const pr = (g: Conversation) => g.pullRequestUrls?.at(-1)
+ const shipped = groups.filter(g => g.assignment?.status === 'done' && Date.parse(g.lastActivityAt ?? '') >= since)
+ .map(g => `- ${named(g)}: ${pr(g) ?? 'done, no pull request'}`)
+ const moving = open.filter(g => activeWork(g) && IN_PROGRESS[g.assignment!.status])
+ .map(g => `- ${named(g)}: ${IN_PROGRESS[g.assignment!.status]} (${who(g)})${pr(g) ? `, ${pr(g)}` : ''}`)
+ const held = open.filter(g => g.assignment && HELD_UP[g.assignment.status]).map(g => {
+ const why = g.assignment!.status === 'lost' ? g.assignment!.lost?.reason : g.assignment!.result
+ return `- ${named(g)}: ${HELD_UP[g.assignment!.status]} (${who(g)})${why ? `: ${why.replace(/\s+/g, ' ').slice(0, 300)}` : ''}`
+ })
+ const parts = [['Shipped', shipped], ['In progress', moving], ['Blocked', held], ['Decisions waiting', decisions.map(d => `- ${d}`)]] as const
+ const text = parts.filter(([, lines]) => lines.length).map(([title, lines]) => [`${title}:`, ...lines].join('\n')).join('\n')
+ return text || 'Nothing shipped, in progress or blocked.'
+}
+
+/** The Lead's wake-up for its project's digest when one is due, or null. The caller records it as sent (store.ts). */
+export function digestRequest(state: SuperTabState, target: Agent, now: number): MessageDraft | null {
+ if (state.paused) return null
+ const project = ledProject(state, target.id)
+ const on = project && digestDue(project, now)
+ if (!project || !on) return null
+ const digest = project.digest!
+ const text = `Morning digest for project ${JSON.stringify(project.name)} (${digest.time}, ${digest.timeZone}). This is a scheduled request, not a new task. `
+ + 'Check that each pull request under Shipped is merged, and move one that is not to In progress. Then post one message to the people in this chat '
+ + 'with these parts, in plain words, without commands or internal IDs.\n\n'
+ // Decision packets (Echo's group) are not stored yet: until they are, the decisions part is left out.
+ + projectDigest(state, project, digestSince(project, now))
+ return { id: stableId('digest', state.id, project.id, on), conversationId: project.leadConversationId,
+ author: author(state, { kind: 'agent', agentId: target.id, machineOwnerId: target.machineOwnerId }),
+ text, replyTo: null, recipients: [target.id], source: { kind: 'digest-request', projectId: project.id, on } }
+}
diff --git a/backend/src/superTabs/leaderboard/contract.ts b/backend/src/superTabs/leaderboard/contract.ts
new file mode 100644
index 000000000..a5affbe30
--- /dev/null
+++ b/backend/src/superTabs/leaderboard/contract.ts
@@ -0,0 +1,35 @@
+/**
+ * The leaderboard read's response (`GET /api/super-tabs/:tabId/leaderboard?projectId=&week=`), the `data` of the usual
+ * envelope. Desktop/web (`desktop/lib/super_tabs/leaderboard`) mirror it by hand. Times are epoch milliseconds; people are
+ * member ids, which clients name from the members they already read. No text from any conversation is ever in it.
+ */
+export type Medal = 'gold' | 'silver' | 'bronze'
+
+export interface PersonScore {
+ personId: string
+ points: number
+ /** 1 for the most points; people with the same points share a rank. */
+ rank: number
+ /** For the top three ranks with points; null otherwise. */
+ medal: Medal | null
+ shipped: { count: number; medianAskToShipMs: number | null }
+ /** `agentMs`: the agent time the answers freed; `medianAnswerMs`: how long an item waited for the person's answer. */
+ unblocked: { count: number; agentMs: number; medianAnswerMs: number | null }
+ /** Machines that ran Swarm agents this week, and the agent time they ran. */
+ lent: { machines: number; agentMs: number }
+ /** Days in a row, up to today, with a shipped request. */
+ streakDays: number
+}
+
+export interface WeekGoal { shipped: number; points: number; medianAskToShipMs: number | null }
+
+export interface Leaderboard {
+ projectId: string
+ week: number
+ /** The team's goal: everyone's points count toward it. */
+ goal: { openRequests: number; thisWeek: WeekGoal; lastWeek: WeekGoal }
+ /** Every person who reads the project, most points first. */
+ 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[] }> }
+}
diff --git a/backend/src/superTabs/leaderboard/lent.test.ts b/backend/src/superTabs/leaderboard/lent.test.ts
new file mode 100644
index 000000000..56609cfda
--- /dev/null
+++ b/backend/src/superTabs/leaderboard/lent.test.ts
@@ -0,0 +1,81 @@
+import { describe, expect, it } from 'vitest'
+import { MACHINE_FRESH_MS, type ContributedMachine } from '../machines.js'
+import { createSuperTab, type Agent, type Conversation, type SuperTabState } from '../model.js'
+import { accrueLent } from './lent.js'
+import { weekStart } from './week.js'
+
+// Monday 2026-10-26 00:00 UTC.
+const MONDAY = Date.UTC(2026, 9, 26)
+
+function machine(running: string[], receivedAt: number): ContributedMachine {
+ return { machineId: 'mac', name: 'Studio', contributorId: 'owner', membershipGeneration: 'tab', generation: 'g1', cwd: '/repo', engines: ['claude'],
+ maxAgents: 4, paused: false, observation: { generation: 'g1', receivedAt, resources: { cpuPercent: null, memoryTotalBytes: null, memoryUsedBytes: null,
+ diskFreeBytes: null, diskTotalBytes: null, projectDiskFreeBytes: null, deviceType: null, chip: null, os: null, gpuPercent: null },
+ tools: {}, quotas: [], runningHarnessIds: running, stoppedHarnessIds: [] } }
+}
+const agent = (id: string, extra: Partial<Agent> = {}): Agent => ({ id, machineId: 'mac', harnessId: `h-${id}`, machineOwnerId: 'owner', contributorId: 'owner',
+ membershipGeneration: 'tab', name: id, configuration: { engine: 'claude', model: 'opus', effort: 'high', contextWindow: null, engineVersion: null }, ...extra })
+function swarm(pool: ContributedMachine, agents: Agent[], conversations: Conversation[] = []): SuperTabState {
+ const state = createSuperTab('tab', 'Pilot', { id: 'owner', email: '[email protected]' }, 'prod')
+ return { ...state, agents, machines: [pool], conversations: [...state.conversations, ...conversations] }
+}
+
+describe('the week a moment belongs to', () => {
+ it('starts each week on Monday 00:00 UTC', () => {
+ expect(weekStart(MONDAY)).toBe(MONDAY)
+ expect(weekStart(MONDAY + 6 * 86_400_000 + 86_399_999)).toBe(MONDAY)
+ expect(weekStart(MONDAY - 1)).toBe(MONDAY - 7 * 86_400_000)
+ })
+})
+
+describe('lent agent-hours from machine readings', () => {
+ it('adds the time since the last reading for each Swarm agent the machine was running', () => {
+ const pool = machine(['h-a', 'h-b'], MONDAY + 1_000), state = swarm(pool, [agent('a'), agent('b')])
+ accrueLent(state, pool, MONDAY + 31_000)
+ expect(pool.lent).toEqual([{ week: MONDAY, agentMs: 60_000 }])
+ })
+
+ it('counts at most one fresh reading\'s worth across a gap, so a machine back from sleep earns no phantom hours', () => {
+ const pool = machine(['h-a'], MONDAY), state = swarm(pool, [agent('a')])
+ accrueLent(state, pool, MONDAY + 3_600_000)
+ expect(pool.lent).toEqual([{ week: MONDAY, agentMs: MACHINE_FRESH_MS }])
+ })
+
+ it('ignores sessions that are not Swarm agents on this machine', () => {
+ const pool = machine(['h-a', 'someone-else'], MONDAY), state = swarm(pool, [agent('a'), agent('b', { machineId: 'other' })])
+ accrueLent(state, pool, MONDAY + 10_000)
+ expect(pool.lent).toEqual([{ week: MONDAY, agentMs: 10_000 }])
+ })
+
+ it('leaves out an agent of a private conversation: private chats never count', () => {
+ const chat: Conversation = { id: 'chat', title: 'Chat', leadId: null, agentIds: ['pm'], archived: false, brief: '', checks: [], assignment: null,
+ lastMessageSequence: 0, audience: { people: [{ id: 'owner', generation: 'tab' }] } }
+ const pool = machine(['h-pm'], MONDAY), state = swarm(pool, [agent('pm')], [chat])
+ accrueLent(state, pool, MONDAY + 10_000)
+ expect(pool.lent).toBeUndefined()
+ })
+
+ it('leaves out a project\'s Lead: its session is confidential coordination, not lent build work (review of #1762)', () => {
+ const pool = machine(['h-lead-agent', 'h-builder'], MONDAY), state = swarm(pool, [agent('lead-agent'), agent('builder')])
+ state.conversations.find(c => c.id === 'lead')!.leadId = 'lead-agent'
+ accrueLent(state, pool, MONDAY + 10_000)
+ expect(pool.lent).toEqual([{ week: MONDAY, agentMs: 10_000 }])
+ })
+
+ it('adds nothing on the first reading', () => {
+ const pool = machine([], 0), state = swarm(pool, [agent('a')])
+ delete pool.observation
+ accrueLent(state, pool, MONDAY)
+ expect(pool.lent).toBeUndefined()
+ })
+
+ it('starts a new week on Monday and keeps only the last five weeks', () => {
+ const pool = machine(['h-a'], 0), state = swarm(pool, [agent('a')])
+ for (let week = 0; week < 7; week++) {
+ pool.observation!.receivedAt = MONDAY + week * 7 * 86_400_000
+ accrueLent(state, pool, pool.observation!.receivedAt + 5_000)
+ }
+ expect(pool.lent?.map(l => (l.week - MONDAY) / (7 * 86_400_000))).toEqual([2, 3, 4, 5, 6])
+ expect(pool.lent?.every(l => l.agentMs === 5_000)).toBe(true)
+ })
+})
diff --git a/backend/src/superTabs/leaderboard/lent.ts b/backend/src/superTabs/leaderboard/lent.ts
new file mode 100644
index 000000000..1bc6e0c46
--- /dev/null
+++ b/backend/src/superTabs/leaderboard/lent.ts
@@ -0,0 +1,30 @@
+/**
+ * Lent: agent-hours Swarm agents ran on a person's contributed machine, added up from that machine's readings and kept on
+ * its contribution by week (docs/swarms.md, Leaderboard). Agents of private chats never count, nor Leads: a Lead's session is
+ * confidential coordination, not lent build work (Lead's ruling on the review of #1762).
+ */
+import { MACHINE_FRESH_MS, type ContributedMachine } from '../machines.js'
+import type { SuperTabState } from '../model.js'
+import { ledProject } from '../projects.js'
+import { LEDGER_WEEKS } from './record.js'
+import { WEEK_MS, weekStart } from './week.js'
+
+export interface LentWeek { week: number; agentMs: number }
+
+/** Credits the time since the machine's previous reading, at most one fresh reading's worth, to each Swarm agent that
+ * reading showed running. Call it before the new reading replaces the previous one. */
+export function accrueLent(state: SuperTabState, pool: ContributedMachine, now: number): void {
+ const previous = pool.observation
+ if (!previous) return
+ const elapsed = Math.min(Math.max(0, now - previous.receivedAt), MACHINE_FRESH_MS)
+ const running = new Set(previous.runningHarnessIds)
+ const privateChats = state.conversations.filter(c => c.audience)
+ const counted = state.agents.filter(a => a.machineId === pool.machineId && running.has(a.harnessId)
+ && !ledProject(state, a.id) && !privateChats.some(c => c.agentIds.includes(a.id)))
+ if (!elapsed || !counted.length) return
+ const week = weekStart(now)
+ const kept = (pool.lent ?? []).filter(l => l.week > week - LEDGER_WEEKS * WEEK_MS)
+ const current = kept.find(l => l.week === week) ?? kept[kept.push({ week, agentMs: 0 }) - 1]!
+ current.agentMs += elapsed * counted.length
+ pool.lent = kept
+}
diff --git a/backend/src/superTabs/leaderboard/read.ts b/backend/src/superTabs/leaderboard/read.ts
new file mode 100644
index 000000000..11d537d86
--- /dev/null
+++ b/backend/src/superTabs/leaderboard/read.ts
@@ -0,0 +1,24 @@
+/** Loading for the leaderboard read (read/service.ts): the dormant groups of the weeks it sums. */
+import type { Prisma } from '@prisma/client'
+import type { Conversation } from '../model.js'
+import { fail } from '../model.js'
+import { LEDGER_WEEKS } from './record.js'
+import { WEEK_MS, weekStart } from './week.js'
+
+/** The weeks a reader can ask for: this one and the ones before it whose records are still kept. */
+export function readableWeek(week: number | undefined, now: number): number {
+ const current = weekStart(now)
+ if (week === undefined) return current
+ if (weekStart(week) !== week) fail('INVALID_WEEK', 'Ask for a week by its Monday 00:00 UTC.', 400)
+ if (week > current || week <= current - (LEDGER_WEEKS - 1) * WEEK_MS) fail('INVALID_WEEK', 'Ask for this week or one of the three before it.', 400)
+ return week
+}
+
+/** Dormant groups of one project active since [since]: a request shipped in a week the board sums wrote its Done row then. */
+export async function recentDormantGroups(tx: Prisma.TransactionClient, tabId: string, projectId: string, since: number): Promise<Conversation[]> {
+ // A group stored with no project belongs to the default one (projects.ts groupProject), as in a Swarm from before projects.
+ const project = projectId === 'lead' ? { OR: [{ projectId: 'lead' }, { projectId: null }, { projectId: { isSet: false } }] } : { projectId }
+ const rows = await tx.swarmGroup.findMany({ where: { tabId, deleted: false, dormant: true, lastActivityAt: { gte: new Date(since) }, ...project },
+ select: { data: true } })
+ return rows.map(row => row.data as unknown as Conversation)
+}
diff --git a/backend/src/superTabs/leaderboard/record.test.ts b/backend/src/superTabs/leaderboard/record.test.ts
new file mode 100644
index 000000000..b05ce1084
--- /dev/null
+++ b/backend/src/superTabs/leaderboard/record.test.ts
@@ -0,0 +1,224 @@
+import { describe, expect, it } from 'vitest'
+import { applyCommand, commandSchema, type Command, type CommandContext } from '../commands.js'
+import { createSuperTab, type Actor, type AgentConfiguration, type Conversation } from '../model.js'
+
+const owner: Extract<Actor, { kind: 'person' }> = { kind: 'person', userId: 'owner', email: '[email protected]' }
+const peer: Extract<Actor, { kind: 'person' }> = { kind: 'person', userId: 'peer', email: '[email protected]' }
+const config: AgentConfiguration = { engine: 'claude', model: 'opus', effort: 'high', contextWindow: null, engineVersion: null }
+const checks = [{ description: 'Works', independent: false }]
+
+function fixture() {
+ let state = createSuperTab('tab', 'Pilot', { id: 'owner', email: owner.email }, 'prod')
+ let sequence = 0, now = 1_000
+ const run = (command: Command, actor: Actor = owner, context: Partial<CommandContext> = {}) => {
+ const effects = applyCommand(state, actor, command, { now, operationId: `op-${++sequence}`, ...context })
+ state = effects.state
+ return effects
+ }
+ const invitePeer = () => {
+ const invited = run({ type: 'invite.create', email: peer.email, role: 'collaborator', conversationId: 'lead' })
+ run({ type: 'invite.accept', inviteId: invited.result.inviteId as string }, peer)
+ }
+ const add = (harnessId: string, group = 'lead', lead = false) => run({ type: 'agent.add', conversationId: group, machineId: 'host', harnessId,
+ name: harnessId, configuration: config, lead }, owner, { contribution: { machineOwnerId: 'host-owner', contributorId: 'owner' } }).result.agentId as string
+ const asAgent = (agentId: string): Actor => ({ kind: 'agent', agentId, machineOwnerId: 'host-owner' })
+ const create = (actor: Actor = owner, extra: Record<string, unknown> = {}) =>
+ run(commandSchema.parse({ type: 'conversation.create', title: 'Offline editing', brief: 'Save edits.', checks, ...extra }), actor).result.conversationId as string
+ const group = (id: string): Conversation => state.conversations.find(c => c.id === id)!
+ /** A worker on [id] with its task assigned, returning the assignment id. */
+ const assign = (id: string, worker = add(`worker-${id}`, id)) => {
+ run({ type: 'work.assign', conversationId: id, agentId: worker })
+ return { worker, assignmentId: group(id).assignment!.id }
+ }
+ const status = (id: string, assignmentId: string, worker: string, next: 'working' | 'needs_human' | 'review' | 'done', result: string | null = null) =>
+ run({ type: 'work.status', conversationId: id, assignmentId, status: next, result }, asAgent(worker))
+ const passChecks = (id: string, assignmentId: string) => {
+ for (const check of group(id).checks) run({ type: 'work.check', conversationId: id, assignmentId, checkId: check.id, passed: true, evidence: 'ok' })
+ }
+ const say = (id: string, actor: Actor, text = 'Go with the flag.', replyTo: string | null = null, reply?: CommandContext['reply']) =>
+ run({ type: 'message.send', conversationId: id, text, replyTo, recipientIds: [] }, actor, reply ? { reply } : {})
+ return { run, invitePeer, add, asAgent, create, group, assign, status, passChecks, say,
+ get state() { return state }, at(ms: number) { now = ms } }
+}
+
+describe('who asked for a group', () => {
+ it('records the person who opens a group as its requester, with when they asked', () => {
+ const f = fixture()
+ f.at(5_000)
+ const id = f.create()
+ expect(f.group(id).requesterId).toBe('owner')
+ expect(f.group(id).ledger).toEqual({ askedAt: 5_000 })
+ })
+
+ it('records the person a Lead names when it opens a group for them', () => {
+ const f = fixture()
+ f.invitePeer()
+ const lead = f.add('lead', 'lead', true)
+ const id = f.create(f.asAgent(lead), { requesterId: 'peer' })
+ expect(f.group(id).requesterId).toBe('peer')
+ })
+
+ it('leaves the requester unknown when a Lead names nobody, rather than guessing', () => {
+ const f = fixture(), lead = f.add('lead', 'lead', true)
+ const id = f.create(f.asAgent(lead))
+ expect(f.group(id).requesterId).toBeUndefined()
+ expect(f.group(id).ledger).toEqual({ askedAt: 1_000 })
+ })
+
+ it('refuses a requester who is not a member of the Swarm', () => {
+ const f = fixture(), lead = f.add('lead', 'lead', true)
+ expect(() => f.create(f.asAgent(lead), { requesterId: 'stranger' })).toThrow('no longer have access')
+ })
+
+ it('lets the Lead set or clear the requester of a group already open', () => {
+ const f = fixture()
+ f.invitePeer()
+ const lead = f.add('lead', 'lead', true), id = f.create(f.asAgent(lead))
+ f.run(commandSchema.parse({ type: 'conversation.requester', conversationId: id, personId: 'peer' }), f.asAgent(lead))
+ expect(f.group(id).requesterId).toBe('peer')
+ f.run(commandSchema.parse({ type: 'conversation.requester', conversationId: id, personId: null }), f.asAgent(lead))
+ expect(f.group(id).requesterId).toBeUndefined()
+ })
+
+ it('keeps the requester to the Lead: a worker in the group cannot change it', () => {
+ const f = fixture(), id = f.create(), worker = f.add('worker', id)
+ expect(() => f.run({ type: 'conversation.requester', conversationId: id, personId: null }, f.asAgent(worker))).toThrow('coordinating lead')
+ })
+
+ it('opens a private conversation without a requester: private chats never count', () => {
+ const f = fixture()
+ const id = f.run(commandSchema.parse({ type: 'conversation.create', title: 'Chat', brief: '', checks: [], audience: { personIds: ['owner'] } })).result.conversationId as string
+ expect(f.group(id).requesterId).toBeUndefined()
+ expect(f.group(id).ledger).toBeUndefined()
+ expect(() => f.run({ type: 'conversation.requester', conversationId: id, personId: 'owner' })).toThrow('chat only')
+ })
+})
+
+describe('when a request ships', () => {
+ it('records the first time its work is done', () => {
+ const f = fixture(), id = f.create(), { worker, assignmentId } = f.assign(id)
+ f.passChecks(id, assignmentId)
+ f.at(9_000)
+ f.status(id, assignmentId, worker, 'done', 'Merged https://github.com/o/r/pull/7')
+ expect(f.group(id).ledger?.shippedAt).toBe(9_000)
+ })
+
+ it('keeps the first ship time when the same group finishes again', () => {
+ const f = fixture(), id = f.create()
+ const first = f.assign(id)
+ f.passChecks(id, first.assignmentId)
+ f.at(9_000)
+ f.status(id, first.assignmentId, first.worker, 'done', 'Merged')
+ f.run({ type: 'work.define', conversationId: id, brief: 'More', checks })
+ const second = f.assign(id, first.worker)
+ f.passChecks(id, second.assignmentId)
+ f.at(20_000)
+ f.status(id, second.assignmentId, second.worker, 'done', 'Merged again')
+ expect(f.group(id).ledger?.shippedAt).toBe(9_000)
+ })
+})
+
+describe('who unblocks waiting work', () => {
+ it('credits the person the item waits on with their answer and how long the agent waited', () => {
+ const f = fixture(), id = f.create(), { worker, assignmentId } = f.assign(id)
+ f.at(10_000)
+ f.status(id, assignmentId, worker, 'needs_human', 'Flag or everyone?')
+ expect(f.group(id).ledger?.waiting).toEqual({ assignmentId, since: 10_000, messageId: expect.any(String) })
+ f.at(10_000 + 3 * 3_600_000)
+ f.say(id, owner)
+ expect(f.group(id).ledger?.unblocks).toEqual([{ personId: 'owner', at: 10_000 + 3 * 3_600_000, waitedMs: 3 * 3_600_000 }])
+ expect(f.group(id).ledger?.waiting).toEqual({ assignmentId, since: 10_000, messageId: expect.any(String), answeredAt: 10_000 + 3 * 3_600_000 })
+ })
+
+ it('opens a new wait when the agent asks again after an answer', () => {
+ const f = fixture(), id = f.create(), { worker, assignmentId } = f.assign(id)
+ f.status(id, assignmentId, worker, 'needs_human', 'Flag?')
+ f.say(id, owner)
+ f.at(50_000)
+ f.status(id, assignmentId, worker, 'needs_human', 'And the default?')
+ expect(f.group(id).ledger?.waiting).toEqual({ assignmentId, since: 50_000, messageId: expect.any(String) })
+ f.say(id, owner, 'Off.')
+ expect(f.group(id).ledger?.unblocks).toHaveLength(2)
+ })
+
+ it('counts one answer per wait: a second post earns nothing more', () => {
+ const f = fixture(), id = f.create(), { worker, assignmentId } = f.assign(id)
+ f.status(id, assignmentId, worker, 'needs_human', 'Flag?')
+ f.say(id, owner)
+ f.say(id, owner, 'And one more thing.')
+ expect(f.group(id).ledger?.unblocks).toHaveLength(1)
+ })
+
+ it('ignores a passer-by who neither is waited on nor replies to the question', () => {
+ const f = fixture()
+ f.invitePeer()
+ const id = f.create(), { worker, assignmentId } = f.assign(id)
+ f.status(id, assignmentId, worker, 'needs_human', 'Flag?')
+ f.say(id, peer, 'Lunch at noon?')
+ expect(f.group(id).ledger?.unblocks).toBeUndefined()
+ expect(f.group(id).ledger?.waiting).toBeDefined()
+ })
+
+ it('credits anyone who replies to the waiting question itself', () => {
+ const f = fixture()
+ f.invitePeer()
+ const id = f.create(), { worker, assignmentId } = f.assign(id)
+ const asked = f.status(id, assignmentId, worker, 'needs_human', 'Flag?').messages[0]!
+ f.say(id, peer, 'Flag.', asked.id, { id: asked.id, conversationId: id, author: asked.author })
+ expect(f.group(id).ledger?.unblocks).toEqual([expect.objectContaining({ personId: 'peer' })])
+ })
+
+ it('waits on the project owner when the group has no requester', () => {
+ const f = fixture(), lead = f.add('lead', 'lead', true), id = f.create(f.asAgent(lead))
+ const { worker, assignmentId } = f.assign(id)
+ f.status(id, assignmentId, worker, 'needs_human', 'Flag?')
+ f.say(id, owner)
+ expect(f.group(id).ledger?.unblocks).toEqual([expect.objectContaining({ personId: 'owner' })])
+ })
+
+ it('stops waiting when the agent moves on by itself, so a later post earns nothing', () => {
+ const f = fixture(), id = f.create(), { worker, assignmentId } = f.assign(id)
+ f.status(id, assignmentId, worker, 'needs_human', 'Flag?')
+ f.status(id, assignmentId, worker, 'working')
+ f.say(id, owner)
+ expect(f.group(id).ledger?.waiting).toBeUndefined()
+ expect(f.group(id).ledger?.unblocks).toBeUndefined()
+ })
+
+ it('earns nothing for a post after the waiting task was cancelled', () => {
+ const f = fixture(), id = f.create(), { worker, assignmentId } = f.assign(id)
+ f.status(id, assignmentId, worker, 'needs_human', 'Flag?')
+ f.run({ type: 'work.cancel', conversationId: id, assignmentId, reason: 'Not needed' })
+ f.say(id, owner)
+ expect(f.group(id).ledger?.unblocks).toBeUndefined()
+ })
+
+ it('credits nothing against a wait left from an earlier attempt', () => {
+ const f = fixture(), id = f.create(), { worker, assignmentId } = f.assign(id)
+ f.status(id, assignmentId, worker, 'needs_human', 'Flag?')
+ // As a group from before answers were recorded reads: the wait on record is another attempt's.
+ f.group(id).ledger!.waiting!.assignmentId = 'earlier-attempt'
+ f.say(id, owner)
+ expect(f.group(id).ledger?.unblocks).toBeUndefined()
+ })
+
+ it('does not credit an agent that posts while work waits', () => {
+ const f = fixture(), id = f.create(), { worker, assignmentId } = f.assign(id)
+ f.status(id, assignmentId, worker, 'needs_human', 'Flag?')
+ f.say(id, f.asAgent(worker), 'Still waiting.')
+ expect(f.group(id).ledger?.unblocks).toBeUndefined()
+ })
+
+ it('keeps only the last five weeks of answers, so a group part stays small', () => {
+ const f = fixture(), id = f.create(), { worker, assignmentId } = f.assign(id)
+ const week = 7 * 86_400_000
+ for (const at of [0, 4 * week, 6 * week]) {
+ f.at(at + 1_000)
+ f.status(id, assignmentId, worker, 'needs_human', `Ask at ${at}`)
+ f.at(at + 2_000)
+ f.say(id, owner)
+ f.status(id, assignmentId, worker, 'working')
+ }
+ expect(f.group(id).ledger?.unblocks?.map(u => u.at)).toEqual([4 * week + 2_000, 6 * week + 2_000])
+ })
+})
diff --git a/backend/src/superTabs/leaderboard/record.ts b/backend/src/superTabs/leaderboard/record.ts
new file mode 100644
index 000000000..8ce4235ba
--- /dev/null
+++ b/backend/src/superTabs/leaderboard/record.ts
@@ -0,0 +1,66 @@
+/**
+ * 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 { groupProject } from '../projects.js'
+import { WEEK_MS } from './week.js'
+
+export interface Unblock { personId: string; at: number; waitedMs: number }
+/** A group's leaderboard bookkeeping; readers never get it whole (read/views.ts groupView). */
+export interface GroupLedger {
+ askedAt?: number
+ /** The first time its work was done; a group is one request, so finishing it again ships nothing new. */
+ shippedAt?: number
+ /** The item waiting on a person: the attempt, since when, the "Needs a human" row it posted, and once a person answered it,
+ * when. An answered item no longer waits, though its worker has not moved on yet. */
+ waiting?: { assignmentId: string; since: number; messageId: string; answeredAt?: number }
+ /** Answers within the last LEDGER_WEEKS, oldest first. */
+ unblocks?: Unblock[]
+}
+
+/** The leaderboard reads this week and last; a little more keeps a streak and week boundaries safe. */
+export const LEDGER_WEEKS = 5
+
+/** 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 {
+ if (group.audience) return
+ if (requesterId) group.requesterId = requesterId
+ group.ledger = { askedAt: now }
+}
+
+/** A status change opens, closes or ships: needs_human starts a wait (again, when the agent asks anew after an answer), any
+ * other status ends it, done ships once. */
+export function recordStatus(group: Conversation, assignment: Assignment, previous: WorkStatus, now: number, messageId: string | null): void {
+ const ledger = group.ledger ??= {}
+ const open = ledger.waiting?.assignmentId === assignment.id && ledger.waiting.answeredAt == null
+ if (assignment.status === 'needs_human' && messageId && (previous !== 'needs_human' || !open)) {
+ ledger.waiting = { assignmentId: assignment.id, since: now, messageId }
+ } else if (assignment.status !== 'needs_human') delete ledger.waiting
+ if (assignment.status === 'done') ledger.shippedAt ??= now
+}
+
+/** The person a waiting item waits on: its requester while still a member, otherwise the project's owner. */
+export function waitedOn(state: SuperTabState, group: Conversation): string {
+ const requester = group.requesterId && state.people.some(p => p.id === group.requesterId) ? group.requesterId : undefined
+ return requester ?? groupProject(state, group).ownerId
+}
+
+/** A person's post answers the waiting item when they are the one it waits on, or when it replies to the question itself;
+ * a passer-by's chat earns nothing (Lead, 2026-10-27). One answer per wait. */
+export function recordAnswer(state: SuperTabState, group: Conversation, actor: Actor, replyTo: string | null, now: number): void {
+ const waiting = group.ledger?.waiting
+ if (actor.kind !== 'person' || !waitsNow(group) || waiting?.assignmentId !== group.assignment!.id) return
+ if (actor.userId !== waitedOn(state, group) && replyTo !== waiting.messageId) return
+ const ledger = group.ledger!
+ waiting.answeredAt = now
+ const kept = (ledger.unblocks ?? []).filter(u => now - u.at < LEDGER_WEEKS * WEEK_MS)
+ ledger.unblocks = [...kept, { personId: actor.userId, at: now, waitedMs: Math.max(0, now - waiting.since) }]
+}
+
+/** Whether the group's work waits on a person now: needs a human and not yet answered. An item from before answers were
+ * recorded has no wait on record and still waits. */
+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)
+}
diff --git a/backend/src/superTabs/leaderboard/stats.test.ts b/backend/src/superTabs/leaderboard/stats.test.ts
new file mode 100644
index 000000000..9941e696d
--- /dev/null
+++ b/backend/src/superTabs/leaderboard/stats.test.ts
@@ -0,0 +1,192 @@
+import { describe, expect, it } from 'vitest'
+import type { ContributedMachine } from '../machines.js'
+import { createSuperTab, type Assignment, type Conversation, type SuperTabState, type WorkStatus } from '../model.js'
+import type { GroupLedger } from './record.js'
+import { leaderboard } from './stats.js'
+import { DAY_MS, WEEK_MS } from './week.js'
+
+// Monday 2026-10-26 00:00 UTC; "now" is Thursday noon of that week.
+const WEEK = Date.UTC(2026, 9, 26), LAST = WEEK - WEEK_MS, NOW = WEEK + 3 * DAY_MS + 12 * 3_600_000
+const HOUR = 3_600_000
+
+/** A fixture Swarm: Ken owns it; Dee, Tony and Scholes are members. */
+function swarm(): SuperTabState {
+ const state = createSuperTab('tab', 'Pilot', { id: 'ken', email: '[email protected]' }, 'prod')
+ state.people.push(...['dee', 'tony', 'scholes'].map(id => ({ id, email: `${id}@example.com`, role: 'collaborator' as const, generation: 'g' })))
+ return state
+}
+let n = 0
+function group(extra: Partial<Conversation> & { ledger?: GroupLedger; status?: WorkStatus } = {}): Conversation {
+ const { status, ...rest } = extra
+ const id = `g${++n}`
+ const assignment: Assignment | null = status ? { id: `a-${id}`, agentId: 'worker', status, result: null,
+ configuration: { engine: 'claude', model: 'opus', effort: 'high', contextWindow: null, engineVersion: null },
+ execution: { machineId: 'mac', harnessId: 'h', machineOwnerId: 'ken' } } : null
+ return { id, projectId: 'lead', title: `Group ${id}`, leadId: null, agentIds: [], archived: false, brief: 'Do it', checks: [], assignment,
+ lastMessageSequence: 0, ...rest }
+}
+/** A request by [requesterId] asked at [askedAt] and shipped at [shippedAt] with a linked PR. */
+const shipped = (requesterId: string, askedAt: number, shippedAt: number, extra: Partial<Conversation> = {}) =>
+ group({ requesterId, status: 'done', pullRequestUrls: ['https://github.com/o/r/pull/1'], ledger: { askedAt, shippedAt }, ...extra })
+const answered = (...unblocks: Array<[personId: string, at: number, waitedMs: number]>) =>
+ group({ status: 'working', ledger: { unblocks: unblocks.map(([personId, at, waitedMs]) => ({ personId, at, waitedMs })) } })
+function machine(contributorId: string, lent: Array<[week: number, agentMs: number]>, machineId = `mac-${contributorId}`): ContributedMachine {
+ return { machineId, name: machineId, contributorId, membershipGeneration: 'g', generation: 'g1', cwd: '/repo', scope: 'swarm', engines: ['claude'],
+ maxAgents: 2, paused: false, lent: lent.map(([week, agentMs]) => ({ week, agentMs })) }
+}
+const board = (state: SuperTabState, groups: Conversation[], week = WEEK, now = NOW, machines = state.machines ?? []) =>
+ leaderboard({ state, groups, machines, projectId: 'lead', week, now })
+const person = (view: ReturnType<typeof board>, id: string) => view.people.find(p => p.personId === id)!
+
+describe('Shipped: requests a person asked for, done with a linked PR, 3 points each', () => {
+ it('counts each shipped request of the week for its requester', () => {
+ const view = board(swarm(), [shipped('dee', WEEK, WEEK + HOUR), shipped('dee', WEEK - DAY_MS, WEEK + 2 * HOUR), shipped('ken', LAST, LAST + HOUR)])
+ expect(person(view, 'dee')).toMatchObject({ points: 6, shipped: { count: 2 } })
+ expect(person(view, 'ken')).toMatchObject({ points: 0, shipped: { count: 0 } })
+ })
+
+ it('needs a linked PR: done work without one has not landed', () => {
+ const view = board(swarm(), [shipped('dee', WEEK, WEEK + HOUR, { pullRequestUrls: [] })])
+ expect(person(view, 'dee').shipped.count).toBe(0)
+ })
+
+ it('counts a request, not its review group, and never a group nobody asked for', () => {
+ const view = board(swarm(), [shipped('dee', WEEK, WEEK + HOUR, { reviewOf: 'g0' }), shipped('', WEEK, WEEK + HOUR, { requesterId: undefined })])
+ expect(view.people.map(p => [p.personId, p.shipped.count])).toEqual([['dee', 0], ['ken', 0], ['scholes', 0], ['tony', 0]])
+ })
+
+ it('never counts a private conversation, even one carrying a ship record', () => {
+ const view = board(swarm(), [shipped('dee', WEEK, WEEK + HOUR, { audience: { people: [{ id: 'dee', generation: 'g' }] } })])
+ expect(person(view, 'dee').shipped.count).toBe(0)
+ expect(view.goal.thisWeek.shipped).toBe(0)
+ })
+
+ it('still counts a shipped request once its group is archived', () => {
+ expect(person(board(swarm(), [shipped('dee', WEEK, WEEK + HOUR, { archived: true })]), 'dee').shipped.count).toBe(1)
+ })
+
+ it('gives each person the median time from asking to shipping', () => {
+ const view = board(swarm(), [shipped('dee', WEEK, WEEK + HOUR), shipped('dee', WEEK, WEEK + 3 * HOUR), shipped('dee', WEEK, WEEK + 8 * HOUR)])
+ expect(person(view, 'dee').shipped.medianAskToShipMs).toBe(3 * HOUR)
+ })
+})
+
+describe('Unblocked: waiting items a person answered, 1 point each plus 1 per 2 agent-hours waited', () => {
+ it('adds the answers and the agent-hours they freed', () => {
+ const view = board(swarm(), [answered(['tony', WEEK + HOUR, 3 * HOUR], ['tony', WEEK + 2 * HOUR, 90 * 60_000]), answered(['tony', LAST, 10 * HOUR])])
+ // Two answers this week, 4.5 agent-hours between them: 2 + 2.
+ expect(person(view, 'tony')).toMatchObject({ points: 4, unblocked: { count: 2, agentMs: 4.5 * HOUR, medianAnswerMs: 2.25 * HOUR } })
+ })
+})
+
+describe('Lent: agent-hours run on a person\'s machines, 1 point per 10', () => {
+ it('counts this week\'s agent-hours on every machine the person contributed', () => {
+ const state = swarm()
+ state.machines = [machine('scholes', [[WEEK, 14 * HOUR], [LAST, 50 * HOUR]]), machine('scholes', [[WEEK, 7 * HOUR]], 'gpu'), machine('ken', [[LAST, 40 * HOUR]])]
+ const view = board(state, [])
+ expect(person(view, 'scholes')).toMatchObject({ points: 2, lent: { machines: 2, agentMs: 21 * HOUR } })
+ expect(person(view, 'ken')).toMatchObject({ points: 0, lent: { machines: 0, agentMs: 0 } })
+ })
+
+ it('sums only the machines the reader may see', () => {
+ const state = swarm()
+ state.machines = [machine('scholes', [[WEEK, 14 * HOUR]]), machine('scholes', [[WEEK, 30 * HOUR]], 'project-mac')]
+ expect(person(board(state, [], WEEK, NOW, [state.machines[0]!]), 'scholes').lent).toEqual({ machines: 1, agentMs: 14 * HOUR })
+ })
+})
+
+describe('ranking and medals', () => {
+ it('ranks by points with medals for the top three, ties sharing a place', () => {
+ const view = board(swarm(), [shipped('ken', WEEK, WEEK + HOUR), shipped('ken', WEEK, WEEK + HOUR), shipped('dee', WEEK, WEEK + HOUR),
+ shipped('tony', WEEK, WEEK + HOUR), answered(['scholes', WEEK + HOUR, 0])])
+ expect(view.people.map(p => [p.personId, p.points, p.rank, p.medal])).toEqual([
+ ['ken', 6, 1, 'gold'], ['dee', 3, 2, 'silver'], ['tony', 3, 2, 'silver'], ['scholes', 1, 4, null]])
+ })
+
+ it('gives no medal to a person with no points', () => {
+ const view = board(swarm(), [shipped('ken', WEEK, WEEK + HOUR)])
+ expect(view.people.filter(p => p.medal).map(p => p.personId)).toEqual(['ken'])
+ })
+
+ it('lists only people who can read the project', () => {
+ const state = swarm()
+ state.projects![0] = { ...state.projects![0]!, visibility: 'private', members: [{ id: 'dee', generation: 'g' }] }
+ expect(board(state, []).people.map(p => p.personId).sort()).toEqual(['dee', 'ken'])
+ })
+})
+
+describe('a shipping streak', () => {
+ it('counts the days in a row, up to today, with a shipped request', () => {
+ const today = WEEK + 3 * DAY_MS
+ const view = board(swarm(), [shipped('dee', LAST, today + HOUR), shipped('dee', LAST, today - DAY_MS + HOUR), shipped('dee', LAST, today - 2 * DAY_MS),
+ shipped('dee', LAST, today - 4 * DAY_MS)])
+ expect(person(view, 'dee').streakDays).toBe(3)
+ })
+
+ it('keeps yesterday\'s streak alive until today ends', () => {
+ const today = WEEK + 3 * DAY_MS
+ const view = board(swarm(), [shipped('dee', LAST, today - DAY_MS), shipped('dee', LAST, today - 2 * DAY_MS)])
+ expect(person(view, 'dee').streakDays).toBe(2)
+ })
+
+ it('is zero after a day without shipping', () => {
+ const today = WEEK + 3 * DAY_MS
+ expect(person(board(swarm(), [shipped('dee', LAST, today - 2 * DAY_MS)]), 'dee').streakDays).toBe(0)
+ })
+})
+
+describe('the team goal', () => {
+ it('compares shipped requests, points and the median ask-to-ship time with last week', () => {
+ const view = board(swarm(), [shipped('dee', WEEK, WEEK + 2 * HOUR), shipped('ken', WEEK, WEEK + 4 * HOUR),
+ shipped('dee', LAST, LAST + 10 * HOUR), answered(['tony', LAST + HOUR, 0])])
+ expect(view.goal.thisWeek).toEqual({ shipped: 2, points: 6, medianAskToShipMs: 3 * HOUR })
+ expect(view.goal.lastWeek).toEqual({ shipped: 1, points: 4, medianAskToShipMs: 10 * HOUR })
+ })
+
+ it('counts the project\'s open requests: shared work not yet shipped, cancelled or archived', () => {
+ const view = board(swarm(), [group({ status: 'working', requesterId: 'dee' }), group({}), group({ status: 'cancelled' }), group({ archived: true }),
+ group({ reviewOf: 'g0', status: 'working' }), shipped('dee', WEEK, WEEK + HOUR), group({ audience: { people: [] } })])
+ expect(view.goal.openRequests).toBe(2)
+ })
+})
+
+describe('agents waiting on a person now', () => {
+ it('shows how many items wait on each person, in name order, never ranked', () => {
+ const view = board(swarm(), [group({ status: 'needs_human', requesterId: 'tony' }), group({ status: 'needs_human' }), group({ status: 'needs_human' }),
+ group({ status: 'working', requesterId: 'tony' })])
+ expect(view.waiting).toEqual({ total: 3, people: [
+ { personId: 'ken', count: 2, conversationIds: [expect.any(String), expect.any(String)] },
+ { personId: 'tony', count: 1, conversationIds: [expect.any(String)] }] })
+ expect(Object.keys(view.waiting.people[0]!).sort()).toEqual(['conversationIds', 'count', 'personId'])
+ })
+
+ it('drops an answered item at once, though its worker has not moved on yet (review of #1762)', () => {
+ const answered = group({ status: 'needs_human' }), open = group({ status: 'needs_human' })
+ answered.ledger = { waiting: { assignmentId: answered.assignment!.id, since: WEEK, messageId: 'm', answeredAt: WEEK + HOUR } }
+ expect(board(swarm(), [answered, open]).waiting).toEqual({ total: 1, people: [{ personId: 'ken', count: 1, conversationIds: [open.id] }] })
+ })
+
+ it('keeps showing an item that was waiting before answers were recorded', () => {
+ expect(board(swarm(), [group({ status: 'needs_human', ledger: { askedAt: WEEK } })]).waiting.total).toBe(1)
+ })
+
+ it('waits on the project owner once the requester has left the Swarm', () => {
+ const state = swarm()
+ state.people = state.people.filter(p => p.id !== 'tony')
+ const view = board(state, [group({ status: 'needs_human', requesterId: 'tony' })])
+ expect(view.waiting.people.map(p => p.personId)).toEqual(['ken'])
+ })
+
+ it('never includes a private conversation', () => {
+ const view = board(swarm(), [group({ status: 'needs_human', audience: { people: [{ id: 'ken', generation: 'tab' }] } })])
+ expect(view.waiting).toEqual({ total: 0, people: [] })
+ })
+})
+
+describe('the week asked for', () => {
+ it('reads last week as its own week, with the week before for comparison', () => {
+ const view = board(swarm(), [shipped('dee', LAST, LAST + HOUR)], LAST)
+ expect(view).toMatchObject({ week: LAST, goal: { thisWeek: { shipped: 1 }, lastWeek: { shipped: 0 } } })
+ expect(person(view, 'dee').shipped.count).toBe(1)
+ })
+})
diff --git a/backend/src/superTabs/leaderboard/stats.ts b/backend/src/superTabs/leaderboard/stats.ts
new file mode 100644
index 000000000..4fcfacd01
--- /dev/null
+++ b/backend/src/superTabs/leaderboard/stats.ts
@@ -0,0 +1,106 @@
+/**
+ * The leaderboard of one project and week (docs/swarms.md, Leaderboard): three numbers per person, Shipped, Unblocked and
+ * Lent, their points, a shipping streak, the team goal, and who agents wait on now. Pure: the read decides who may see it and
+ * hands in only the groups that reader may read. Private conversations are left out here too.
+ */
+import type { ContributedMachine } from '../machines.js'
+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'
+
+export const SHIPPED_POINTS = 3
+export const UNBLOCK_POINTS = 1
+const HOUR_MS = 3_600_000
+/** One more point per this many agent-hours an answer freed, and per this many agent-hours lent. */
+export const UNBLOCK_HOURS_PER_POINT = 2
+export const LENT_HOURS_PER_POINT = 10
+const MEDALS: Medal[] = ['gold', 'silver', 'bronze']
+
+export interface LeaderboardInput {
+ state: SuperTabState
+ /** Every group of the Swarm the reader may read, dormant ones of the last weeks included. */
+ groups: Conversation[]
+ /** The contributed machines the reader may see (model.ts visibleState): Lent sums no other. */
+ machines: ContributedMachine[]
+ projectId: string
+ /** The Monday 00:00 UTC the week starts (week.ts). */
+ week: number
+ now: number
+}
+
+export function leaderboard({ state, groups, machines: visibleMachines, projectId, week, now }: LeaderboardInput): Leaderboard {
+ const project = projectOf(state, projectId)
+ const shared = groups.filter(g => !isLeads(g) && !g.audience && (g.projectId ?? 'lead') === projectId && g.id !== project.leadConversationId)
+ const requests = shared.filter(g => !g.reviewOf)
+ const landed = requests.filter(g => g.requesterId && g.ledger?.shippedAt != null && (g.pullRequestUrls?.length ?? 0) > 0)
+ const players = state.people.filter(p => canReadProject(state, { kind: 'person', userId: p.id, email: p.email }, project))
+ const inWeek = (at: number, start = week) => at >= start && at < start + WEEK_MS
+ const score = (personId: string, start: number) => {
+ const shippedHere = landed.filter(g => g.requesterId === personId && inWeek(g.ledger!.shippedAt!, start))
+ const answers = shared.flatMap(g => g.ledger?.unblocks ?? []).filter(u => u.personId === personId && inWeek(u.at, start))
+ const machines = visibleMachines.filter(m => m.contributorId === personId)
+ .map(m => m.lent?.find(l => l.week === start)?.agentMs ?? 0).filter(ms => ms > 0)
+ const freedMs = sum(answers.map(u => u.waitedMs)), lentMs = sum(machines)
+ const points = shippedHere.length * SHIPPED_POINTS + answers.length * UNBLOCK_POINTS
+ + Math.floor(freedMs / (UNBLOCK_HOURS_PER_POINT * HOUR_MS)) + Math.floor(lentMs / (LENT_HOURS_PER_POINT * HOUR_MS))
+ return {
+ points,
+ shipped: { count: shippedHere.length, medianAskToShipMs: median(askToShip(shippedHere)) },
+ unblocked: { count: answers.length, agentMs: freedMs, medianAnswerMs: median(answers.map(u => u.waitedMs)) },
+ lent: { machines: machines.length, agentMs: lentMs },
+ }
+ }
+ const goal = (start: number): WeekGoal => {
+ const shippedHere = landed.filter(g => inWeek(g.ledger!.shippedAt!, start))
+ return { shipped: shippedHere.length, points: sum(players.map(p => score(p.id, start).points)), medianAskToShipMs: median(askToShip(shippedHere)) }
+ }
+ const today = Math.floor(Math.min(now, week + WEEK_MS - 1) / DAY_MS)
+ const scored = players.map(p => ({ personId: p.id, email: p.email, ...score(p.id, week),
+ streakDays: streak(new Set(landed.filter(g => g.requesterId === p.id).map(g => Math.floor(g.ledger!.shippedAt! / DAY_MS))), today) }))
+ .sort((a, b) => b.points - a.points || a.email.localeCompare(b.email))
+ const people: PersonScore[] = scored.map(({ email: _email, ...entry }) => {
+ const rank = 1 + scored.filter(other => other.points > entry.points).length
+ return { ...entry, rank, medal: entry.points > 0 ? MEDALS[rank - 1] ?? null : null }
+ })
+ return {
+ projectId, week,
+ goal: { openRequests: requests.filter(open).length, thisWeek: goal(week), lastWeek: goal(week - WEEK_MS) },
+ people,
+ waiting: waitingNow(state, shared),
+ }
+}
+
+/** 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 ?? '')
+
+/** Who agents wait on now and how many items each: in name order, never ranked (the mockup's "Kind" rule). */
+function waitingNow(state: SuperTabState, shared: Conversation[]): Leaderboard['waiting'] {
+ const byPerson = new Map<string, string[]>()
+ for (const group of shared.filter(g => !g.archived && waitsNow(g))) {
+ const personId = waitedOn(state, group)
+ byPerson.set(personId, [...byPerson.get(personId) ?? [], group.id])
+ }
+ const email = (id: string) => state.people.find(p => p.id === id)?.email ?? id
+ const people = [...byPerson].map(([personId, conversationIds]) => ({ personId, count: conversationIds.length, conversationIds }))
+ .sort((a, b) => email(a.personId).localeCompare(email(b.personId)))
+ return { total: sum(people.map(p => p.count)), people }
+}
+
+/** Days in a row with a shipped request, ending today; a streak that reached yesterday still stands until today ends. */
+function streak(days: Set<number>, today: number): number {
+ let day = days.has(today) ? today : today - 1, count = 0
+ while (days.has(day)) { count++; day-- }
+ return count
+}
+
+const askToShip = (groups: Conversation[]): number[] =>
+ groups.flatMap(g => g.ledger?.askedAt != null ? [g.ledger.shippedAt! - g.ledger.askedAt] : [])
+const sum = (values: number[]): number => values.reduce((total, value) => total + value, 0)
+function median(values: number[]): number | null {
+ if (!values.length) return null
+ const sorted = [...values].sort((a, b) => a - b), middle = Math.floor(sorted.length / 2)
+ return sorted.length % 2 ? sorted[middle]! : (sorted[middle - 1]! + sorted[middle]!) / 2
+}
diff --git a/backend/src/superTabs/leaderboard/week.ts b/backend/src/superTabs/leaderboard/week.ts
new file mode 100644
index 000000000..59dc4e380
--- /dev/null
+++ b/backend/src/superTabs/leaderboard/week.ts
@@ -0,0 +1,7 @@
+/** Leaderboard weeks run Monday 00:00 to Monday 00:00 UTC (Lead ruling, 2026-10-27). */
+export const DAY_MS = 86_400_000
+export const WEEK_MS = 7 * DAY_MS
+/** 1970-01-05, the first Monday after the epoch. */
+const FIRST_MONDAY = 4 * DAY_MS
+
+export const weekStart = (ms: number): number => Math.floor((ms - FIRST_MONDAY) / WEEK_MS) * WEEK_MS + FIRST_MONDAY
diff --git a/backend/src/superTabs/liveness.ts b/backend/src/superTabs/liveness.ts
index e13194f62..18752acab 100644
--- a/backend/src/superTabs/liveness.ts
+++ b/backend/src/superTabs/liveness.ts
@@ -87,14 +87,21 @@ function lastProgress(state: SuperTabState, worker: Agent, assignment: Assignmen
return seen.length ? Math.max(...seen) : undefined
}
+function limitReason(worker: Agent, now: number): string | null {
+ return worker.alerting?.includes('limit') && worker.limitedUntil && Date.parse(worker.limitedUntil) > now
+ ? `it hit a usage limit until ${worker.limitedUntil.slice(11, 16)} UTC` : null
+}
+
/** Why a worker has lost its task now, or null while it still holds it. Only a machine that has reported can be offline. */
function lostReason(state: SuperTabState, group: Conversation, worker: Agent, assignment: Assignment, now: number): string | null {
const pool = state.machines?.find(m => m.machineId === worker.machineId)
if (pool?.observation?.stoppedHarnessIds.includes(worker.harnessId)) return `its session on ${pool.name} stopped`
if (pool?.observation && now - pool.observation.receivedAt > OFFLINE_LOST_MS) return `its machine ${pool.name} has been offline for 2 minutes`
- if (worker.alerting?.includes('limit') && worker.limitedUntil && Date.parse(worker.limitedUntil) > now) {
- return `it hit a usage limit until ${worker.limitedUntil.slice(11, 16)} UTC`
- }
+ const limited = limitReason(worker, now)
+ if (limited) return limited
+ // Its host alerts only after ten minutes of retries without an answer (cli superTabs/terminal.ts MODEL_WAIT_MS), so a
+ // short burst of failures that recovers never gets here.
+ if (worker.alerting?.includes('model')) return 'its model keeps failing'
const end = leaseEnd(group, assignment, reportRenewedAt(state, worker))
if (end !== undefined && now > end) {
const progress = lastProgress(state, worker, assignment)
@@ -105,12 +112,13 @@ function lostReason(state: SuperTabState, group: Conversation, worker: Agent, as
/** Marks a worker's task lost and fences its agent. The Lead hears who, why, how long since progress and the last result;
* the old agent hears that its task moved. Rows are written as the Lead, or as the worker when the project has none. */
-function loseTask(state: SuperTabState, group: Conversation, worker: Agent, reason: string, now: number): MessageDraft[] {
+function loseTask(state: SuperTabState, group: Conversation, worker: Agent, reason: string, now: number, resumeAt?: string): MessageDraft[] {
const assignment = group.assignment!
+ const resume = resumeAt ? { resumeAt } : {}
assignment.status = 'lost'
- assignment.lost = { reason, at: now }
- group.lostAttempt = { id: assignment.id, agentId: worker.id }
- worker.lostTask = { conversationId: group.id, assignmentId: assignment.id, reason, at: now }
+ assignment.lost = { reason, at: now, ...resume }
+ group.lostAttempt = { id: assignment.id, agentId: worker.id, machineId: assignment.execution.machineId, engine: assignment.configuration.engine }
+ worker.lostTask = { conversationId: group.id, assignmentId: assignment.id, reason, at: now, ...resume }
const sender = writtenBy(state, leadOf(state, worker) ?? worker)
const progress = lastProgress(state, worker, assignment)
const since = progress === undefined ? 'unknown' : `${plural(Math.max(0, Math.floor((now - progress) / 60_000)), 'minute')} ago`
@@ -118,7 +126,10 @@ function loseTask(state: SuperTabState, group: Conversation, worker: Agent, reas
const pr = group.pullRequestUrls?.at(-1)
const source = { kind: 'work-lost', agentId: worker.id, assignmentId: assignment.id, reason }
const wake = `${worker.displayName ?? worker.name} lost its task "${group.title}": ${reason}. Last progress ${since}. `
- + `Last result: ${result || 'none'}.${pr && !result?.includes(pr) ? ` Pull request: ${pr}.` : ''} Assign it to another agent now, or cancel it.`
+ + `Last result: ${result || 'none'}.${pr && !result?.includes(pr) ? ` Pull request: ${pr}.` : ''} `
+ + (resumeAt ? `It resumes by itself when its limit resets at ${resumeAt.slice(11, 16)} UTC, unless you hand it on first. `
+ + 'If another account or engine has allowance now, assign it there now with its branch and last progress note, or cancel it.'
+ : 'Assign it to another agent now, or cancel it.')
return [...toLead(state, worker, { id: stableId('work-lost', assignment.id), conversationId: group.id, author: sender, replyTo: null, recipients: [], text: wake, source }),
{ id: stableId('work-lost', assignment.id, 'agent'), conversationId: group.id, author: sender, replyTo: null, recipients: [worker.id], source,
text: `Your task "${group.title}" moved: ${reason}. Stop working on it; your status and results for it are no longer accepted.` }]
@@ -126,11 +137,12 @@ function loseTask(state: SuperTabState, group: Conversation, worker: Agent, reas
}
/** Loses at once the tasks of the workers `which` picks that have a reason now: an agent that just reported a usage limit,
- * the agents of a machine that just reported. */
-export function loseTasks(state: SuperTabState, now: number, which: (worker: Agent) => boolean = () => true): MessageDraft[] {
+ * the agents of a machine that just reported. A task lost to that limit resumes at `resumeAt` when its screen said when the
+ * limit resets (the host types into the same session then, cli superTabs/limitResume.ts). */
+export function loseTasks(state: SuperTabState, now: number, which: (worker: Agent) => boolean = () => true, resumeAt?: string): MessageDraft[] {
return workerTasks(state).filter(t => which(t.worker)).flatMap(({ group, assignment, worker }) => {
const reason = lostReason(state, group, worker, assignment, now)
- return reason ? loseTask(state, group, worker, reason, now) : []
+ return reason ? loseTask(state, group, worker, reason, now, resumeAt && reason === limitReason(worker, now) ? resumeAt : undefined) : []
})
}
diff --git a/backend/src/superTabs/machines.ts b/backend/src/superTabs/machines.ts
index 25434a2a9..6abfce307 100644
--- a/backend/src/superTabs/machines.ts
+++ b/backend/src/superTabs/machines.ts
@@ -28,6 +28,8 @@ export interface ContributedMachine {
* the host says it cleaned up (machine.cleaned) or REMOVAL_FALLBACK_MS passes. An offline one leaves the list at once and
* its cleanup waits for its host (expireRemovals). */
removal?: { id: string; state: 'cleaning'; requestedAt: string }
+ /** Agent-time Swarm agents ran here, by leaderboard week, kept by its readings (leaderboard/lent.ts). */
+ lent?: import('./leaderboard/lent.js').LentWeek[]
}
/** A removed machine whose host never acknowledged in time: its records are gone, its host still cleans up on its next poll. */
export interface MachineCleanup { machineId: string; removalId: string; machineOwnerId: string }
diff --git a/backend/src/superTabs/model.ts b/backend/src/superTabs/model.ts
index 3b73428d6..ec069d0ab 100644
--- a/backend/src/superTabs/model.ts
+++ b/backend/src/superTabs/model.ts
@@ -45,7 +45,7 @@ export interface Agent {
downNamed?: string
/** Its last task was lost (liveness.ts): routing leaves it out, even once that task is cancelled or reassigned, until it
* finishes a new task, a person assigns it work by hand, or its terminal is replaced (commands.ts). */
- lostTask?: { conversationId: string; assignmentId: string; reason: string; at: number }
+ lostTask?: { conversationId: string; assignmentId: string; reason: string; at: number; resumeAt?: string }
/** A usage limit seen on its terminal; routing skips the agent until then. Shown as null once passed (terminal.ts). */
limitedUntil?: string | null
/** Terminal alert episodes in progress, so each one posts a single row (terminal.ts). */
@@ -116,8 +116,9 @@ export interface Assignment {
leaseUntil?: number
/** Its agent's last progress the lease saw, for the Lead's wake-up when it is lost. */
progressAt?: number
- /** Why and when it was lost (status `lost`). */
- lost?: { reason: string; at: number }
+ /** Why and when it was lost (status `lost`); after a usage limit whose screen gave a reset time, when its own agent may
+ * take it back (work.resume) unless it was handed on first. */
+ lost?: { reason: string; at: number; resumeAt?: string }
}
export interface WorkTask {
goal: string
@@ -160,8 +161,13 @@ export interface Conversation {
lastActivityAt?: string
/** A private conversation: only these people and the project's Lead read it (projects.ts canReadGroup). */
audience?: import('./parts/types.js').Audience
- /** The last attempt here that was lost: its agent's status and checks for it are refused, even after reassignment. */
- lostAttempt?: { id: string; agentId: string }
+ /** The last attempt here that was lost: its agent's status and checks for it are refused, even after reassignment. Where it
+ * ran (machine and engine) stays too, so routing the work again avoids that account even once its agent is gone. */
+ lostAttempt?: { id: string; agentId: string; machineId?: string; engine?: string }
+ /** The person who asked for this work: whoever opened it, or the person its Lead named (leaderboard/record.ts). */
+ requesterId?: string
+ /** What the leaderboard counts here (leaderboard/record.ts); bookkeeping readers never get whole. */
+ ledger?: import('./leaderboard/record.js').GroupLedger
}
export function appendPullRequestUrls(group: Conversation, texts: Iterable<string | null | undefined>): void {
@@ -275,6 +281,9 @@ export interface CommandEffects {
result: Record<string, unknown>
/** A terminal request or its answer, written outside the tab state by the store (terminal.ts). */
terminal?: import('./terminal.js').TerminalEffect
+ /** Decisions asked, and a decision answered, written outside the tab state by the store (decisions.ts). */
+ decisions?: import('./decisions.js').DecisionDraft[]
+ decisionAnswer?: import('./decisions.js').DecisionAnswer
}
export class SuperTabError extends Error {
constructor(readonly code: string, message: string, readonly status = 409) {
@@ -291,8 +300,10 @@ export const activeWork = (group: Conversation): boolean => !!group.assignment &
/** Old states derive pending decisions from their closed assignments; new states persist them on the worker. */
export function awaitingWorkers(state: SuperTabState, projectId: string): Agent[] {
return state.agents.filter(a => {
- if (state.conversations.some(c => c.leadId === a.id) || state.conversations.some(c => activeWork(c) && c.assignment?.agentId === a.id)
- || reviewing(state, a.id)) return false
+ // A Reviewer never waits for a decision: a finished one is kept until the Lead stops it (finishWorker), and one an older
+ // release left waiting must not hold up routing either.
+ if (agentRole(a) === 'reviewer' || state.conversations.some(c => c.leadId === a.id)
+ || state.conversations.some(c => activeWork(c) && c.assignment?.agentId === a.id)) return false
// A lost task's agent is not waiting for a decision, even once the task is cancelled: it may be gone, and it must not
// hold up the next assignment.
const groups = state.conversations.filter(c => c.assignment?.agentId === a.id && !c.assignment.lost)
@@ -307,12 +318,14 @@ export function requireWorkerDecisions(state: SuperTabState, actor: Actor, group
.filter(a => a.id !== reuseId && !(agentRole(a) === 'reviewer' && group.agentIds.includes(a.id)))
if (waiting.length) fail('WORKER_DECISION_REQUIRED', `Decide what to do with ${waiting.map(a => a.displayName ?? a.name).join(', ')}: reuse, keep or stop. Prefer stop unless more work is coming soon.`)
}
-/** A group's work ended: its worker, and each of its Reviewers not reviewing other active work, await the Lead's decision. */
+/** A group's work ended: its worker awaits the Lead's decision. A finished Reviewer, and each of the group's Reviewers not
+ * reviewing other active work, is kept instead: the Lead never has to decide about one, only stop it when it wants. */
export function finishWorker(state: SuperTabState, workerId: string, group?: Conversation): void {
const ids = [workerId, ...(group?.agentIds ?? []).filter(id => id !== workerId &&
state.agents.some(a => a.id === id && agentRole(a) === 'reviewer') && !reviewing(state, id))]
for (const target of state.agents.filter(a => ids.includes(a.id))) {
- if (!state.conversations.some(c => c.leadId === target.id) && target.workDecision !== 'stop') target.workDecision = 'awaiting'
+ if (state.conversations.some(c => c.leadId === target.id) || target.workDecision === 'stop') continue
+ target.workDecision = agentRole(target) === 'reviewer' ? 'keep' : 'awaiting'
}
}
/** A Reviewer is busy while any group it is in has active work. */
diff --git a/backend/src/superTabs/parts/light.test.ts b/backend/src/superTabs/parts/light.test.ts
index 5f84bc67f..d2476a3c0 100644
--- a/backend/src/superTabs/parts/light.test.ts
+++ b/backend/src/superTabs/parts/light.test.ts
@@ -13,6 +13,7 @@ const conversation: Required<Conversation> = {
id: 'g', kind: 'leads', projectId: 'p', number: 1, title: 't', leadId: null, agentIds: [], archived: false, brief: '',
task: { goal: '', changes: '', constraints: '', owns: [] }, reviewOf: 'r', checks: [], assignment, lastMessageSequence: 0, pullRequestUrls: [],
messageSeq: 0, reportSeq: 0, dormant: false, lastActivityAt: '', audience: { people: [] }, lostAttempt: { id: 'w', agentId: 'a' },
+ requesterId: 'p', ledger: {},
}
describe('the light conversation projection (parts/light.ts)', () => {
diff --git a/backend/src/superTabs/parts/light.ts b/backend/src/superTabs/parts/light.ts
index d742786d1..54b97b7e5 100644
--- a/backend/src/superTabs/parts/light.ts
+++ b/backend/src/superTabs/parts/light.ts
@@ -17,14 +17,16 @@ export const FINISHED: readonly string[] = ['done', 'stopped', 'cancelled', 'los
const running = { $and: [{ $ne: [{ $type: '$data.assignment.status' }, 'missing'] }, { $not: [{ $in: ['$data.assignment.status', FINISHED] }] }] }
/**
* Which conversation fields a light load keeps. `always`: who reads it and who is in it, and how its work ended (a lost
- * task's worker awaits no decision, model.ts awaitingWorkers). `whenRunning`: what other projects' work and host rows read of
+ * task's worker awaits no decision, model.ts awaitingWorkers), with the work's id: a host row tells whether a task lost to a
+ * usage limit is still that one before its host resumes it (read/hostRows.ts). `whenRunning`: what other projects' work and host rows read of
* running work. `unread`: what visibility checks, derived values and host rows never read. light.test.ts fails when
* model.ts gains a field this does not place.
*/
export const GROUP_FIELDS = {
- always: ['id', 'kind', 'projectId', 'leadId', 'agentIds', 'archived', 'audience', 'dormant', 'assignment.agentId', 'assignment.status', 'assignment.lost'],
- whenRunning: ['title', 'task.owns', 'assignment.id', 'assignment.execution', 'assignment.result'],
- unread: ['number', 'brief', 'reviewOf', 'checks', 'lastMessageSequence', 'pullRequestUrls', 'messageSeq', 'reportSeq', 'lastActivityAt', 'lostAttempt',
+ always: ['id', 'kind', 'projectId', 'leadId', 'agentIds', 'archived', 'audience', 'dormant', 'assignment.id', 'assignment.agentId', 'assignment.status',
+ 'assignment.lost'],
+ whenRunning: ['title', 'task.owns', 'assignment.execution', 'assignment.result'],
+ unread: ['number', 'brief', 'reviewOf', 'checks', 'lastMessageSequence', 'pullRequestUrls', 'messageSeq', 'reportSeq', 'lastActivityAt', 'lostAttempt', 'requesterId', 'ledger',
'assignment.configuration', 'assignment.recordingProgress', 'assignment.leaseUntil', 'assignment.progressAt'],
} as const
const LIGHT_GROUP = {
@@ -44,7 +46,7 @@ function ms(value: unknown): number {
function lightGroup(row: Record<string, unknown>): Part<GroupData> {
const raw = (row.data ?? {}) as Partial<GroupData> & { task?: { owns?: string[] } }
// A conversation with no work has nothing to project there; never read it as having work.
- // Finished work comes without its id, machine or result: placeholders keep the shape, and nothing reads them.
+ // Finished work comes without its machine or result: placeholders keep the shape, and nothing reads them.
const work = raw.assignment?.status ? raw.assignment as Partial<NonNullable<GroupData['assignment']>> : null
const assignment = work && { id: '', execution: { machineId: '', harnessId: '', machineOwnerId: '' }, result: null, ...work }
const data = { title: '', ...raw, brief: '', checks: [], assignment,
diff --git a/backend/src/superTabs/parts/touches.test.ts b/backend/src/superTabs/parts/touches.test.ts
index c5d7841de..2209bb9da 100644
--- a/backend/src/superTabs/parts/touches.test.ts
+++ b/backend/src/superTabs/parts/touches.test.ts
@@ -57,6 +57,27 @@ describe('the parts a command touches (design section 1.2, column T)', () => {
expect(has(f.run({ type: 'work.assign', conversationId: next, agentId: a.worker }).touches, 'progress', 'lead')).toBe(true)
})
+ it('makes naming a requester meet that person\'s removal on their member part', () => {
+ const f = swarm()
+ const invited = f.run({ type: 'invite.create', email: '[email protected]', role: 'collaborator', conversationId: 'lead' }).effects.result.inviteId as string
+ f.run({ type: 'invite.accept', inviteId: invited }, { kind: 'person', userId: 'peer', email: '[email protected]' })
+ const opened = f.run({ type: 'conversation.create', title: 'R', brief: 'Do it', checks: [{ description: 'Done', independent: false }], requesterId: 'peer' },
+ f.agentActor(f.lead))
+ expect(has(opened.touches, 'member', 'peer')).toBe(true)
+ const id = opened.effects.result.conversationId as string
+ const named = f.run({ type: 'conversation.requester', conversationId: id, personId: 'peer' }, f.agentActor(f.lead))
+ expect(has(named.touches, 'member', 'peer')).toBe(true)
+ expect(has(named.touches, 'group', 'lead')).toBe(true)
+ })
+
+ it('makes an answer to waiting work meet a change to whom it waits on', () => {
+ const f = swarm(), a = f.group('A')
+ f.run({ type: 'conversation.requester', conversationId: a.id, personId: 'owner' })
+ f.run({ type: 'work.status', conversationId: a.id, assignmentId: a.assignmentId, status: 'needs_human', result: 'Flag?' }, f.agentActor(a.worker))
+ const answer = f.run({ type: 'message.send', conversationId: a.id, text: 'Flag.', replyTo: null, recipientIds: [] }, f.agentActor(f.lead))
+ expect(has(answer.touches, 'member', 'owner')).toBe(true)
+ })
+
it('makes two starts on one machine meet on its slot ledger and on the head', () => {
const f = swarm()
const request = { conversationId: 'lead', machineId: 'host', engine: 'codex', name: 'New', cwd: '/w', worktree: false,
diff --git a/backend/src/superTabs/parts/touches.ts b/backend/src/superTabs/parts/touches.ts
index f2cbe926d..c46dda976 100644
--- a/backend/src/superTabs/parts/touches.ts
+++ b/backend/src/superTabs/parts/touches.ts
@@ -4,6 +4,7 @@ import { agentRole } from '../model.js'
import type { ContributedMachine } from '../machines.js'
import { agentProjectId, canReadProject, groupProject, projectsOf } from '../projects.js'
import type { Touch } from './commit.js'
+import { waitsNow } from '../leaderboard/record.js'
/**
* The parts a command relies on without writing them (design section 1.2, column T). A part the command also writes is
@@ -69,6 +70,18 @@ export function touchesFor(command: Command, actor: Actor, before: SuperTabState
const projectId = command.projectId ?? (actor.kind === 'agent' ? agentProject(actor.agentId) : 'lead')
group(leadGroupOf(projectId))
group(command.reviewOf)
+ member(command.requesterId)
+ break
+ }
+ case 'conversation.requester':
+ leadCheck(projectOfGroup(command.conversationId)?.id)
+ member(command.personId ?? undefined)
+ break
+ case 'message.send': {
+ // An answer to waiting work is credited to the person it waits on (leaderboard/record.ts): a concurrent change to who
+ // that is meets the answer here.
+ const waiting = before.conversations.find(c => c.id === command.conversationId)
+ if (waiting && waitsNow(waiting)) member(waiting.requesterId)
break
}
case 'agent.add': {
diff --git a/backend/src/superTabs/projects.ts b/backend/src/superTabs/projects.ts
index 241581fc0..854b1949f 100644
--- a/backend/src/superTabs/projects.ts
+++ b/backend/src/superTabs/projects.ts
@@ -23,6 +23,8 @@ export interface SwarmProject {
visibility: ProjectVisibility
members: Array<{ id: string; generation: string }>
updateMinutes: 1 | 5 | 15 | 30
+ /** The morning digest (digest.ts): its local time ("08:00") and zone, and the local date and time of the last one sent. */
+ digest?: { time: string; timeZone: string; lastOn?: string; lastAt?: number }
/** Report watermark per conversation (projectUpdates.ts); kept in its own part (store by parts). */
progress?: import('./parts/types.js').ProgressData
repository?: { machineId: string; cwd: string; repositoryUrl: string | null }
diff --git a/backend/src/superTabs/read/contract.ts b/backend/src/superTabs/read/contract.ts
index 0523fff98..dab895c05 100644
--- a/backend/src/superTabs/read/contract.ts
+++ b/backend/src/superTabs/read/contract.ts
@@ -33,7 +33,7 @@ export type AgentView = Omit<Agent, 'downNamed' | 'downSince' | 'limitedUntil' |
export interface Audience { people: Array<{ id: string; generation: string }> }
/** A conversation with its own message counter (`lastMessageSequence` and message sequences compare within one group).
* `dormant` is set only on a dormant group fetched on demand; `audience` only on a private conversation. */
-export type GroupView = Omit<Conversation, 'messageSeq' | 'reportSeq' | 'dormant' | 'lastActivityAt' | 'audience'>
+export type GroupView = Omit<Conversation, 'messageSeq' | 'reportSeq' | 'dormant' | 'lastActivityAt' | 'audience' | 'ledger'>
& { messageSeq: number; dormant?: true; audience?: Audience }
/** A contribution as `state.machines[]` has it, privacy detail only for its contributor, harness ids cut to what the
* reader can see. Machines without a contribution are never sent. */
@@ -60,6 +60,8 @@ export interface Derived {
otherProjectsWork?: OtherProjectWorkView[]
/** A person only. */
mentionsWaiting?: number
+ /** A person only: decisions asked of them, still open. */
+ decisionsWaiting?: number
}
export interface OtherProjectWorkView {
conversationId: string; projectName: string; title: string; owns: string[]; status: WorkStatus; agentName: string; pr: string | null
@@ -182,6 +184,9 @@ export interface HostAgentRow {
paused: boolean
active: boolean
attention: { assignmentId: string; status: WorkStatus; result: string | null } | null
+ /** Its task lost to a usage limit, still waiting for it: when its host types it back into the same session. `lostAt`
+ * names that loss, since one task can be lost, resumed and lost again. */
+ resume: { conversationId: string; assignmentId: string; lostAt: number; at: string } | null
agent: Agent
joinSwarm: boolean
skillMode: 'default' | 'orchestration'
diff --git a/backend/src/superTabs/read/hostRows.ts b/backend/src/superTabs/read/hostRows.ts
index 9699f8604..651fea904 100644
--- a/backend/src/superTabs/read/hostRows.ts
+++ b/backend/src/superTabs/read/hostRows.ts
@@ -57,6 +57,12 @@ function agentRow(tabId: string, state: SuperTabState, machineId: string, user:
const closed = lookups.confidential.has(target.id)
const waiting = state.conversations.find(c => activeWork(c) && c.assignment!.agentId === target.id &&
c.assignment!.execution.machineId === machineId && ['needs_human', 'blocked'].includes(c.assignment!.status))?.assignment
+ // A task it lost to a usage limit that gave a reset time, while nobody has handed it on: its host resumes it then
+ // (cli superTabs/limitResume.ts), and the backend still decides (commands.ts work.resume).
+ const marked = target.lostTask
+ const lost = marked?.resumeAt ? state.conversations.find(c => c.id === marked.conversationId)?.assignment : undefined
+ const resume = marked?.resumeAt && lost?.id === marked.assignmentId && lost.status === 'lost' && lost.lost?.at === marked.at
+ ? { conversationId: marked.conversationId, assignmentId: marked.assignmentId, lostAt: marked.at, at: marked.resumeAt } : null
const home = projectsOf(state).find(p => p.id === agentProjectId(state, target))
const custom = home && skillSetOf(home) === 'custom' ? home : null
const chosen = custom ? agentSetRole(state, custom, target) : null
@@ -65,6 +71,7 @@ function agentRow(tabId: string, state: SuperTabState, machineId: string, user:
// `active` lets the host release members that are only in archived groups to automatic cleanup.
active: state.conversations.some(c => !c.archived && c.agentIds.includes(target.id)),
attention: waiting ? { assignmentId: waiting.id, status: waiting.status, result: waiting.result?.slice(0, 500) ?? null } : null,
+ resume,
agent: target,
joinSwarm: state.ownerId === user.sub && target.contributorId === user.sub && !state.machines?.some(m => m.machineId === machineId)
&& state.conversations.some(c => !c.archived && c.leadId === target.id),
diff --git a/backend/src/superTabs/read/service.ts b/backend/src/superTabs/read/service.ts
index d2c736585..54169bb68 100644
--- a/backend/src/superTabs/read/service.ts
+++ b/backend/src/superTabs/read/service.ts
@@ -5,13 +5,19 @@
import type { Prisma, PrismaClient } from '@prisma/client'
import type { AuthUser } from '../../lib/ssoAuth.js'
import { isTeamSession, TEAM_SESSION_LIMITED, TEAM_SESSION_MESSAGE } from '../../lib/teamSession.js'
-import { author, fail, type Actor, type AgentStart } from '../model.js'
+import { author, fail, isLeads, visibleState, type Actor, type AgentStart } from '../model.js'
import { mentionsWaiting } from '../mentions.js'
+import { decisionsWaiting } from '../decisions.js'
import { transaction, type SuperTabStore } from '../store.js'
import { migrateSwarm } from '../migration/migrate.js'
import * as parts from '../parts/index.js'
import type { SwarmParts } from '../parts/index.js'
-import { canReadGroup } from '../projects.js'
+import { canReadGroup, readProject } from '../projects.js'
+import type { Leaderboard } from '../leaderboard/contract.js'
+import { readableWeek, recentDormantGroups } from '../leaderboard/read.js'
+import { LEDGER_WEEKS } from '../leaderboard/record.js'
+import { leaderboard } from '../leaderboard/stats.js'
+import { WEEK_MS } from '../leaderboard/week.js'
import { READ_FORMAT, SWARM_MIGRATING, type Changes, type DormantGroups, type FirstLoad, type OneGroup, type SwarmList } from './contract.js'
import { cursorFor, readCursor } from './cursor.js'
import { changesFor } from './changes.js'
@@ -45,6 +51,7 @@ export class SwarmReads {
return this.read(user, tabId, async tx => {
// Light (parts/light.ts): changed parts come whole from the change feed; the rest is read only to check visibility and
// derive values: the Lead conversations, those with running work, and those a person's mentions are in (their count).
+ // Open decisions count their conversations themselves (decisions.ts).
const mentioned = asAgentId ? [] : (await tx.superTabMention.findMany({ where: { tabId, personId: user.sub }, select: { conversationId: true },
distinct: ['conversationId'] })).map(m => m.conversationId)
const light = { includeRecentStarts: true, groups: 'working' as const, groupIds: mentioned }
@@ -88,6 +95,21 @@ export class SwarmReads {
})
}
+ /** One project's leaderboard for a week (leaderboard/stats.ts), for the people who read the project. It sums only the
+ * groups the reader may read, dormant ones of the kept weeks included, and never a private conversation. */
+ async leaderboard(user: AuthUser, tabId: string, projectId: string, week?: number): Promise<Leaderboard> {
+ if (isTeamSession(user)) fail(TEAM_SESSION_LIMITED, TEAM_SESSION_MESSAGE, 403)
+ const now = this.now(), start = readableWeek(week, now)
+ return this.read(user, tabId, async tx => {
+ const state = parts.reassemble(await parts.loadActive(tx, tabId))
+ const actor = await this.store.actor(tx, user, state)
+ readProject(state, actor, projectId)
+ const dormant = await recentDormantGroups(tx, tabId, projectId, now - LEDGER_WEEKS * WEEK_MS)
+ const groups = [...state.conversations.filter(g => !g.dormant), ...dormant].filter(g => !isLeads(g) && canReadGroup(state, actor, g))
+ return leaderboard({ state, groups, machines: visibleState(state, actor, now).machines ?? [], projectId, week: start, now })
+ })
+ }
+
async list(user: AuthUser, after?: string): Promise<SwarmList> {
if (isTeamSession(user)) fail(TEAM_SESSION_LIMITED, TEAM_SESSION_MESSAGE, 403)
const rows = await this.db.superTab.findMany({ where: { autonomousEnv: user.autonomousEnv, memberIds: { has: user.sub },
@@ -119,12 +141,12 @@ export class SwarmReads {
const loaded = await loader(tx, tabId, opts)
const state = parts.reassemble(loaded)
const actor = await this.store.actor(tx, user, state, asAgentId)
- const [teamMachines, mentions, newest] = await Promise.all([
+ const [teamMachines, counts, newest] = await Promise.all([
state.machines?.length ? this.store.teamMachines(tx, state) : [],
- actor.kind === 'person' ? mentionsWaiting(tx, tabId, state, actor, t0) : undefined,
+ actor.kind === 'person' ? Promise.all([mentionsWaiting(tx, tabId, state, actor, t0), decisionsWaiting(tx, tabId, state, actor)]) : undefined,
parts.lastChangedAt(tx, [tabId]),
])
return { parts: loaded, actor, lastChangedAt: newest.get(tabId) ?? null,
- view: readerView(loaded, actor, t0, { teamMachines, ...(mentions !== undefined ? { mentionsWaiting: mentions } : {}) }) }
+ view: readerView(loaded, actor, t0, { teamMachines, ...(counts ? { mentionsWaiting: counts[0], decisionsWaiting: counts[1] } : {}) }) }
}
}
diff --git a/backend/src/superTabs/read/views.ts b/backend/src/superTabs/read/views.ts
index f13204e0d..345238d69 100644
--- a/backend/src/superTabs/read/views.ts
+++ b/backend/src/superTabs/read/views.ts
@@ -30,6 +30,8 @@ export interface ReadExtras {
teamMachines: string[]
/** A person's open mentions, counted by the store. */
mentionsWaiting?: number
+ /** A person's open decisions (decisions.ts). */
+ decisionsWaiting?: number
}
const HEAD_FIELDS = ['version', 'id', 'name', 'project', 'projects', 'leadsConversationId', 'ownerId', 'environment',
@@ -38,9 +40,10 @@ const HEAD_FIELDS = ['version', 'id', 'name', 'project', 'projects', 'leadsConve
export const envelope = <T>(part: Pick<Part, 'key' | 'version' | 'changedAt'>, data: T): LivePart<T> =>
({ key: part.key, version: part.version, changedAt: part.changedAt, data })
-/** A group as readers get it: its message counter, a dormant flag only when dormant, never the store's bookkeeping. */
+/** A group as readers get it: its message counter, a dormant flag only when dormant, never the store's bookkeeping or the
+ * leaderboard's (the leaderboard read sums it). */
export function groupView(group: Conversation): GroupView {
- const { messageSeq, reportSeq: _report, lastActivityAt: _activity, dormant, audience, ...rest } = group
+ const { messageSeq, reportSeq: _report, lastActivityAt: _activity, ledger: _ledger, dormant, audience, ...rest } = group
return { ...rest, messageSeq: messageSeq ?? 0, ...(dormant ? { dormant: true as const } : {}), ...(audience ? { audience } : {}) }
}
@@ -97,5 +100,6 @@ function derive(state: SuperTabState, visible: SuperTabState, actor: Actor, now:
machines: Object.fromEntries((visible.machines ?? []).map(machine)),
...(visible.otherProjectsWork ? { otherProjectsWork: visible.otherProjectsWork } : {}),
...(actor.kind === 'person' && extras.mentionsWaiting !== undefined ? { mentionsWaiting: extras.mentionsWaiting } : {}),
+ ...(actor.kind === 'person' && extras.decisionsWaiting !== undefined ? { decisionsWaiting: extras.decisionsWaiting } : {}),
}
}
diff --git a/backend/src/superTabs/store.ts b/backend/src/superTabs/store.ts
index 18e02c707..08ba1a3ab 100644
--- a/backend/src/superTabs/store.ts
+++ b/backend/src/superTabs/store.ts
@@ -12,10 +12,11 @@ import { attachmentMime, attachmentName, AttachmentTooLarge, checkedType, MAX_AT
import { randomBytes } from 'node:crypto'
import type { Readable } from 'node:stream'
import { logger } from '../utils/logger.js'
-import { canReadAgent, canReadGroup, canWatchAgent, groupProject, ledProject, projectsOf, agentProjectId, readConversation, roleVersion, type ProjectVisibility } from './projects.js'
+import { canReadAgent, canReadGroup, canWatchAgent, groupProject, ledProject, projectOf, projectsOf, agentProjectId, readConversation, roleVersion, type ProjectVisibility } from './projects.js'
import { bindSession, makeProjectPrivate } from './sessionScope.js'
import { confidentialSessions, otherRegistrations, recordConfidential } from './confidential.js'
import { answersRequest, noteProjectReports, projectUpdateRequest } from './projectUpdates.js'
+import { digestDue, digestRequest, digestSince } from './digest.js'
import { judgedMachines, loseTasks, sweepLiveness, SWEEP_EVERY_MS } from './liveness.js'
import { clock, insertParts, lastChangedAt, loadActive, reassemble, split, type HeadData, type SwarmParts } from './parts/index.js'
import { commitParts, indexesOf, numberMessages, type Touch, type Written } from './parts/commit.js'
@@ -28,9 +29,11 @@ import {
import { holdNoticeText, type HoldReason } from './holdNotice.js'
import { agentDisplayName } from './agentNames.js'
import { endedHolds, HOLDING, type WorkHold } from '../github/holds.js'
+import { accrueLent } from './leaderboard/lent.js'
import { mayDrive, TERMINAL_ANSWER_MS, TERMINAL_EXPIRY_MS, TERMINAL_PICKUP_MS, type TerminalEffect } from './terminal.js'
import { closeAssignment, closeUnassignedStart, readDecision, recentRoutes, timedDecisionOf, writeRouteEffects } from './routeDecisions.js'
import { listMentions, markDone, mentionsWaiting, readMention, resolveByReply, writeMentions } from './mentions.js'
+import { answerable, listDecisions, readAskedDecision, recordAnswer, writeDecisions } from './decisions.js'
import { DEFAULT_ROUTING_POLICY, effectivePolicy, routingPolicySchema, type RoutingPolicy } from './routingPolicy.js'
import { authenticatedEmail, authorizeSwarmJoin, configureSharing, joinSwarmSchema, requireSharingOwner,
saveSharingSchema, sharingDetails, type JoinSwarm, type SaveSharing } from './sharing.js'
@@ -169,6 +172,10 @@ export interface SuperTabStoreHooks {
}
/** Persistent coordination. Host adapters own execution and must confirm their local session grants. */
+/** The routing decision a command names. `decision.answer` names a person's decision instead (decisions.ts). */
+const routeDecisionOf = (command: Command): string | undefined => command.type === 'decision.answer' ? undefined
+ : 'decisionId' in command ? command.decisionId : 'routeDecisionId' in command ? command.routeDecisionId : undefined
+
export class SuperTabStore {
readonly native: SuperTabNativeStore
constructor(readonly db: PrismaClient, readonly now: () => number = Date.now,
@@ -322,12 +329,17 @@ export class SuperTabStore {
const groupIds = [...named.groupIds ?? []], startIds = [...named.startIds ?? []], agentIds: string[] = [], startAgentIds: string[] = []
const start = 'startId' in command ? state.starts?.find(s => s.id === command.startId) : undefined
if (start) groupIds.push(start.request.conversationId)
- const decisionId = 'decisionId' in command ? command.decisionId : 'routeDecisionId' in command ? command.routeDecisionId : undefined
+ const decisionId = routeDecisionOf(command)
if (decisionId) {
const decision = await readDecision(tx, tabId, decisionId)
if (decision) groupIds.push(decision.conversationId)
if (decision?.final?.kind === 'new') startIds.push(decision.final.startId)
}
+ // A person's decision may sit in a quiet or archived conversation: it is loaded to answer it (review of #1753).
+ if (command.type === 'decision.answer') {
+ const asked = await readAskedDecision(tx, tabId, command.decisionId)
+ if (asked) groupIds.push(asked.conversationId)
+ }
if (command.type === 'delivery.resolve') {
const delivery = await tx.superTabDelivery.findFirst({ where: { id: command.deliveryId, tabId }, select: { conversationId: true } })
if (delivery) groupIds.push(delivery.conversationId)
@@ -651,7 +663,9 @@ export class SuperTabStore {
if (!delivery) fail('NOT_FOUND', 'This delivery is unavailable.', 404)
readConversation(original, actor, delivery.conversationId)
}
- if ('decisionId' in command) {
+ // A retried answer is checked again: the person must still read the decision's conversation (review of #1753).
+ if (command.type === 'decision.answer') answerable(original, actor, await readAskedDecision(tx, tabId, command.decisionId))
+ else if ('decisionId' in command) {
const decision = await readDecision(tx, tabId, command.decisionId) ?? fail('NOT_FOUND', 'This routing decision is unavailable.', 404)
readConversation(original, actor, decision.conversationId)
}
@@ -720,6 +734,7 @@ export class SuperTabStore {
proof.harnessId === execution.harnessId && proof.machineOwnerId === execution.machineOwnerId
}
if (command.type === 'mention.done') context.mention = await readMention(tx, tabId, command.mentionId)
+ if (command.type === 'decision.answer') context.decision = await readAskedDecision(tx, tabId, command.decisionId)
if (command.type === 'message.send' && command.attachmentIds?.length) context.attachments = await this.sendable(tx, tabId, actor, command)
if (command.type === 'route.record') context.recentRoutes = await recentRoutes(tx, tabId, context.now)
if (TEAM_WORK_COMMANDS.has(command.type)) {
@@ -908,6 +923,11 @@ export class SuperTabStore {
if (command.type === 'message.send' && actor.kind === 'person') await resolveByReply(tx, tabId, command.conversationId, actor.userId, context.now)
await writeMentions(tx, tabId, effects.state, effects.messages, context.now)
if (command.type === 'mention.done') await markDone(tx, tabId, command.mentionId, context.mention!.personId, context.now)
+ if (effects.decisions) {
+ const ids = await writeDecisions(tx, tabId, effects.decisions, context.now)
+ if (command.type === 'decision.ask') effects.result.decisionIds = ids
+ }
+ if (effects.decisionAnswer) await recordAnswer(tx, tabId, effects.decisionAnswer, context.now)
if (context.attachments?.length) {
// Conflicts with a concurrent send of the same file: only one message can take it.
const taken = await tx.superTabAttachment.updateMany({ where: { tabId, id: { in: context.attachments.map(a => a.id) }, ...unused },
@@ -1312,6 +1332,17 @@ export class SuperTabStore {
})
}
+ /** The caller's decisions in this Swarm, newest first: a person's asked of them, an agent's asked by it (a Lead's also
+ * those asked in its project), still open or answered. */
+ async decisions(user: AuthUser, tabId: string, state: 'open' | 'answered', asAgentId?: string) {
+ return transaction(this.db, async tx => {
+ const { state: tab } = await this.load(tx, user, tabId, { allGroups: true })
+ const actor = await this.actor(tx, user, tab, asAgentId)
+ author(tab, actor)
+ return { decisions: await listDecisions(tx, tabId, tab, actor, state === 'open') }
+ })
+ }
+
/**
* Every earlier attempt of one group. `work.define` takes a stopped assignment out of the state, so this is the
* only place a reader (the Lead choosing an agent for a retry) can still see who tried and how it ended
@@ -1443,6 +1474,7 @@ export class SuperTabStore {
const { privacy: reported, harnessProgress, ...reading } = observation
const progress = harnessProgress && Object.fromEntries(Object.entries(harnessProgress).filter(([id]) => observation.runningHarnessIds.includes(id)))
const privacy = observedPrivacy(pool.observation?.privacy, reported, team, now)
+ accrueLent(state, pool, now)
pool.observation = { ...reading, quotas: observation.quotas.filter(q => contributedEngines(pool, observation).includes(q.engine)), receivedAt: now,
// How the machine is signed in, from the session that reported and never from the report (lib/teamSession.ts).
sessionKind: team ? 'team' : 'computer', ...(privacy ? { privacy } : {}), ...(progress ? { harnessProgress: progress } : {}) }
@@ -1520,7 +1552,16 @@ export class SuperTabStore {
async deliveries(user: AuthUser, tabId: string, agentId: string) {
return transaction(this.db, async tx => {
- const loaded = await this.load(tx, user, tabId), state = structuredClone(loaded.state)
+ let loaded = await this.load(tx, user, tabId)
+ // Work finished since the last digest and archived or asleep since still shipped, but ordinary loads leave it out
+ // (#1757 review, 4): a due digest loads it.
+ const led = ledProject(loaded.state, agentId)
+ if (led && digestDue(led, this.now())) {
+ const finished = await tx.swarmGroup.findMany({ where: { tabId, deleted: false, dormant: true, lastActivityAt: { gte: new Date(digestSince(led, this.now())) },
+ OR: [{ projectId: led.id }, ...led.id === 'lead' ? [{ projectId: null }] : []] }, select: { key: true } })
+ if (finished.length) loaded = await this.ensure(tx, loaded, { groupIds: finished.map(g => g.key) })
+ }
+ const state = structuredClone(loaded.state)
author(state, await this.actor(tx, user, state, agentId), true)
const target = agent(state, agentId)
// A Lead's poll runs the time checks (liveness.ts): lost work wakes it in this same poll.
@@ -1541,13 +1582,20 @@ export class SuperTabStore {
woken = true
}
}
+ // The morning digest is due once a day; recording it as sent is part of this same write, so it is sent once.
+ const digest = digestRequest(state, target, this.now())
+ if (digest) {
+ const project = projectOf(state, digest.source!.projectId as string)
+ project.digest = { ...project.digest!, lastOn: digest.source!.on as string, lastAt: this.now() }
+ written.push(digest)
+ }
// The poll also frees agents whose task the checks just lost, and any an older server left marked running (each poll; a
// second finds none).
await this.endRuns(tx, tabId, loaded.state, state)
if (ledProject(state, agentId)) {
await this.releaseRuns(tx, tabId, await this.staleRuns(tx, tabId, state))
}
- // One write for both: the time checks' changes and the wake-up's.
+ // One write for all: the time checks' changes, the digest and the wake-ups'.
const sequences = numberMessages(state, written, this.now())
await this.save(tx, loaded, state, clock.next(), [...judgedMachines(state, written), ...woken ? [{ kind: 'agent' as const, key: agentId }] : []])
await this.writeMessages(tx, tabId, state, written, sequences)
diff --git a/backend/vitest.super-tabs.config.ts b/backend/vitest.super-tabs.config.ts
index e2da28ad8..ccf87c4f3 100644
--- a/backend/vitest.super-tabs.config.ts
+++ b/backend/vitest.super-tabs.config.ts
@@ -1,5 +1,5 @@
import { defineConfig } from 'vitest/config'
export default defineConfig({ test: { include: ['integration/superTabs.test.ts', 'integration/superTabSharing.test.ts', 'integration/superTabGithub.test.ts', 'integration/superTabTeam.test.ts',
- 'integration/superTabRead.test.ts', 'integration/superTabMigration.test.ts', 'integration/superTabLiveness.test.ts'], hookTimeout: 120000, testTimeout: 30000,
+ 'integration/superTabRead.test.ts', 'integration/superTabLeaderboard.test.ts', 'integration/superTabMigration.test.ts', 'integration/superTabLiveness.test.ts'], hookTimeout: 120000, testTimeout: 30000,
fileParallelism: false, env: { NODE_ENV: 'test', HARNESS_CREDENTIAL_ENCRYPTION_KEY: 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=' } } })
diff --git a/cli/build-bundle.mjs b/cli/build-bundle.mjs
index c6123c355..294983375 100644
--- a/cli/build-bundle.mjs
+++ b/cli/build-bundle.mjs
@@ -12,7 +12,7 @@
*/
import * as esbuild from 'esbuild'
import { createHash } from 'node:crypto'
-import { appendFileSync, readFileSync, copyFileSync, rmSync, writeFileSync } from 'fs'
+import { appendFileSync, readFileSync, readdirSync, copyFileSync, rmSync, writeFileSync } from 'fs'
import { readDshRegistry } from './scripts/lib/dshRegistry.mjs'
import { readBuiltinBundle, readHarnessMonitorBundle, readMemoriesBundle, readModelManagerBundle } from './scripts/lib/modelManagerBundle.mjs'
import { readProcessImageBundle } from './scripts/lib/processImageBundle.mjs'
@@ -68,6 +68,9 @@ const options = {
// The guest helper and its sudoers drop-in (src/lib/guestHelperAssets.ts): the installed CLI is cli.js alone.
__GUEST_HELPER__: JSON.stringify(readFileSync('assets/guest-helper/guest-helper.sh', 'utf8')),
__GUEST_SUDOERS__: JSON.stringify(readFileSync('assets/guest-helper/sudoers', 'utf8')),
+ // The scheduler's Python package (src/superTabs/planCommand.ts), which `harness super-tab plan` writes out and runs.
+ __SCHEDULER_FILES__: JSON.stringify(Object.fromEntries(readdirSync('../tools/scheduler/scheduler').filter(f => f.endsWith('.py')).sort()
+ .map(f => [f, readFileSync(`../tools/scheduler/scheduler/${f}`, 'utf8')]))),
__BUILTIN_REVISIONS__: JSON.stringify(builtinRevisions),
__DARWIN_PROCESS_IMAGES__: processImages ? JSON.stringify(processImages) : 'undefined',
},
diff --git a/cli/build.mjs b/cli/build.mjs
index e98623fe3..6cf2f48bc 100644
--- a/cli/build.mjs
+++ b/cli/build.mjs
@@ -52,6 +52,9 @@ try {
// The guest helper and its sudoers drop-in (src/lib/guestHelperAssets.ts): the installed CLI is cli.js alone.
__GUEST_HELPER__: JSON.stringify(readFileSync('assets/guest-helper/guest-helper.sh', 'utf8')),
__GUEST_SUDOERS__: JSON.stringify(readFileSync('assets/guest-helper/sudoers', 'utf8')),
+ // The scheduler's Python package (src/superTabs/planCommand.ts), which `harness super-tab plan` writes out and runs.
+ __SCHEDULER_FILES__: JSON.stringify(Object.fromEntries(readdirSync('../tools/scheduler/scheduler').filter(f => f.endsWith('.py')).sort()
+ .map(f => [f, readFileSync(`../tools/scheduler/scheduler/${f}`, 'utf8')]))),
},
logLevel: 'info',
})
diff --git a/cli/src/lib/swarmSkills.spec.ts b/cli/src/lib/swarmSkills.spec.ts
index cc93773f5..093cbacd2 100644
--- a/cli/src/lib/swarmSkills.spec.ts
+++ b/cli/src/lib/swarmSkills.spec.ts
@@ -54,10 +54,24 @@ describe('built-in Swarm skills', () => {
// The lost-work and checkpoint lines (Lead's brief for v1 liveness, 2026-10-26; docs: swarm-never-stops): the Lead's and
// the Builder's alone, in both modes.
const lost = '- When you are told a task is lost, hand it on at once: route it and assign it to another agent, avoiding what failed (another machine if its machine died, another account or engine if it hit a usage limit). The new brief tells the successor to continue from the lost attempt\'s pushed branch and last result, not to start over.\n'
+ // The night-shift lines (v2 B, 2026-10-27): a task lost to a usage limit resumes by itself unless an account or engine
+ // with allowance can take it now, and the morning digest. The Lead's alone, in both modes, right after the lost-work line.
+ const limit = '- A task lost to a usage limit resumes by itself in the same session when the limit resets (its wake-up says when). Hand it on at once only to another account or engine with allowance now, with its pushed branch and last progress note.\n'
+ const digest = '- Morning digest: when a person asks for one, set the project\'s digest to their local time and time zone ("project.digest" with time "08:00" and timeZone "Asia/Ho_Chi_Minh"). When it wakes you, check that each pull request under Shipped is merged, then post one message to the people in the project chat.\n'
const checkpoint = '- Push your work branch at least every 30 minutes, and set your work status to working with a one-line note of what is done and what is next, so another agent can continue if you stop.\n'
+ // The plan line (Lead's brief for v2 M, 2026-10-27; docs/plans/2026-10-27-swarm-scheduler.md): the Lead's alone, in both modes.
+ const plan = '- With 3 or more groups waiting, run plan first: it places them all at once on the best machines and models. Then route each group in the plan\'s order and start the plan\'s pick, with overrideReason "scheduler plan" when the route picks otherwise. If plan cannot run here, route as usual.\n'
+ // The decision lines (Lead's brief for v2 decisions, 2026-10-27): the Lead's and the Builder's alone, in both modes.
+ const decision = '- Ask people for decisions in one place: decision.ask puts up to 10 questions to one person at once, each with 2 to 5 options, the one you recommend and what the answer unblocks. Keep working on your recommendation, marked provisional, until they answer: a notice in that conversation tells you, and harness super-tab decisions --answered shows the answer. A decision is not a private channel: anything private goes through Chat with PM.\n'
+ const ask = '- When you know who decides, add ask to that needs-human (the person, 2 to 5 options, the one you recommend, what it unblocks) and keep working on your recommendation, marked provisional, until a notice says it was answered; read the answer with harness super-tab decisions --answered.\n'
+ // The requests section (Lead's ruling for v2 G, the human leaderboard, 2026-10-27): the Lead's alone, in both modes, in a
+ // section of its own so other groups' edits to the Lead text merge cleanly.
+ const requests = '## Requests and Done\n- When you open a group for a person\'s request, asked in the project chat or in their Chat with PM, name them as its requester: requesterId on conversation.create, or conversation.requester for a group already open. It records only that they asked, never what they wrote.\n- Mark a group Done only after its pull request has merged: the leaderboard counts a request as shipped once its group is Done with a linked PR.\n\n'
+ // Last in the Default Lead text, which has no red flags: after a blank line, ending the text.
+ const requestsLast = `\n${requests.trimEnd()}\n`
const twoHours = '- A Builder or Reviewer that has been down for 2 hours (machine offline, session gone or stopped): cancel its task with the reason, route it, and assign it to another agent with what the first one left (branch, last revision, last report).\n'
it.each([
- ['lead', '5fc83d8c43b66b44cdab27b48235dbc86b7ab11a57153edc1ae7e92831642a8e'],
+ ['lead', 'b9254e4bb5c633a73e1b87e6ca6690915e1c3a7bb55db0d3d093e6710dd719db'],
['dev', 'e78ce31a71f169d8956a2acd46e8bb43b79bd654b80b0fe3c33dbced9d2c3c75'],
['review', '424dc9db5642ed7093128525f30877ffc301eb6957b33e8234916de0f0eaa208'],
] as const)('writes the owner\'s Harness orchestration %s skill byte for byte', (role, sha256) => {
@@ -71,10 +85,17 @@ describe('built-in Swarm skills', () => {
expect(text.split(terminal)).toHaveLength(role === 'lead' ? 2 : 1)
expect(text.split(overlap)).toHaveLength(role === 'lead' ? 2 : 1)
expect(text.split(local)).toHaveLength(role === 'lead' ? 2 : 1)
+ expect(text.split(plan)).toHaveLength(role === 'lead' ? 2 : 1)
expect(text.split(mention)).toHaveLength(role === 'lead' ? 2 : 1)
expect(text.split(lost)).toHaveLength(role === 'lead' ? 2 : 1)
expect(text.split(checkpoint)).toHaveLength(role === 'dev' ? 2 : 1)
- expect(sha(text.replace(twoHours, '').replace(terminal, '').replace(overlap, '').replace(local, '').replace(mention, '').replace(lost, '').replace(checkpoint, ''))).toBe(sha256)
+ expect(text.split(limit)).toHaveLength(role === 'lead' ? 2 : 1)
+ expect(text.split(digest)).toHaveLength(role === 'lead' ? 2 : 1)
+ expect(text.split(mention + decision)).toHaveLength(role === 'lead' ? 2 : 1)
+ expect(text.split(ask)).toHaveLength(role === 'dev' ? 2 : 1)
+ expect(text.split(requests)).toHaveLength(role === 'lead' ? 2 : 1)
+ expect(sha(text.replace(twoHours, '').replace(terminal, '').replace(overlap, '').replace(local, '').replace(mention, '').replace(lost, '').replace(checkpoint, '')
+ .replace(limit, '').replace(digest, '').replace(decision, '').replace(ask, '').replace(requests, ''))).toBe(sha256)
}
})
it('adds the 2-hour line to section 7 right after the 6-hour rule', () => {
@@ -83,7 +104,7 @@ describe('built-in Swarm skills', () => {
})
it('adds the terminal line where each Lead skill keeps work moving, right after the silent-worker rule', () => {
const orchestration = readFileSync(prepareSwarmSkill(fixture(), { role: 'lead', key: 'session' }).file, 'utf8')
- expect(orchestration).toContain(`naming the machine owner who can answer.\n${twoHours}${lost}${terminal}- Keep each worker supplied`)
+ expect(orchestration).toContain(`naming the machine owner who can answer.\n${twoHours}${lost}${limit}${digest}${terminal}- Keep each worker supplied`)
const plain = readFileSync(prepareSwarmSkill(fixture(), { role: 'lead', key: 'session', mode: 'default' }).file, 'utf8')
expect(plain).toContain(`- A worker with active work that has said nothing for 20 minutes: ask it.\n${terminal}- A Builder or Reviewer`)
})
@@ -93,17 +114,40 @@ describe('built-in Swarm skills', () => {
const plain = readFileSync(prepareSwarmSkill(fixture(), { role: 'lead', key: 'session', mode: 'default' }).file, 'utf8')
expect(plain).toContain(`- The brief is all a Builder gets; never rely on chat history.\n${overlap}\n## 4. Keep work moving`)
})
+ it('adds the plan line right after each Lead skill\'s first routing rule', () => {
+ const orchestration = readFileSync(prepareSwarmSkill(fixture(), { role: 'lead', key: 'session' }).file, 'utf8')
+ expect(orchestration).toContain(`- Route each group before starting or assigning: difficulty, risk, size, why, needs. Use the pick, or override with a reason.\n${plan}`)
+ const plain = readFileSync(prepareSwarmSkill(fixture(), { role: 'lead', key: 'session', mode: 'default' }).file, 'utf8')
+ expect(plain).toContain(`- Route each group; reuse an idle agent before starting one; start only on the Swarm's machines.\n${plan}`)
+ })
it('adds the mention line right after each Lead skill\'s needs-a-person rule', () => {
const orchestration = readFileSync(prepareSwarmSkill(fixture(), { role: 'lead', key: 'session' }).file, 'utf8')
- expect(orchestration).toContain(`- Needs-human: get the person's decision now.\n${mention}- Blocked: change something.`)
+ expect(orchestration).toContain(`- Needs-human: get the person's decision now.\n${mention}${decision}- Blocked: change something.`)
+ const plain = readFileSync(prepareSwarmSkill(fixture(), { role: 'lead', key: 'session', mode: 'default' }).file, 'utf8')
+ expect(plain).toContain(`- Needs a person: get the decision now. Blocked: change something (context, model, size or plan); never resend the same thing.\n${mention}${decision}- Settle ambiguities`)
+ })
+ it('adds the decision lines right after the mention line for the Lead, and after the needs-human rule for the Builder', () => {
+ for (const mode of ['orchestration', 'default'] as const) {
+ const builder = readFileSync(prepareSwarmSkill(fixture(), { role: 'dev', key: 'session', mode }).file, 'utf8')
+ expect(builder).toContain(`- A person's decision: mark needs-human with one short question.\n${ask}- Can't go on`)
+ }
+ })
+ it('gives each Lead skill its requests section of its own: before the red flags, or last where there are none', () => {
+ const orchestration = readFileSync(prepareSwarmSkill(fixture(), { role: 'lead', key: 'session' }).file, 'utf8')
+ expect(orchestration).toContain(`\n\n${requests}## Red flags`)
const plain = readFileSync(prepareSwarmSkill(fixture(), { role: 'lead', key: 'session', mode: 'default' }).file, 'utf8')
- expect(plain).toContain(`- Needs a person: get the decision now. Blocked: change something (context, model, size or plan); never resend the same thing.\n${mention}- Settle ambiguities`)
+ expect(plain.endsWith(`Call the roles Product Manager, Engineer and Reviewer.\n${requestsLast}`)).toBe(true)
})
it('adds the lost-work line right after each Lead skill\'s 2-hour rule', () => {
const orchestration = readFileSync(prepareSwarmSkill(fixture(), { role: 'lead', key: 'session' }).file, 'utf8')
expect(orchestration).toContain(`${twoHours}${lost}`)
const plain = readFileSync(prepareSwarmSkill(fixture(), { role: 'lead', key: 'session', mode: 'default' }).file, 'utf8')
- expect(plain).toContain(`assign it to another agent with what the first one left (branch, last revision, last report).\n${lost}- Work with no progress`)
+ expect(plain).toContain(`assign it to another agent with what the first one left (branch, last revision, last report).\n${lost}${limit}${digest}- Work with no progress`)
+ })
+ it('adds the usage-limit and digest lines right after each Lead skill\'s lost-work line', () => {
+ for (const mode of ['orchestration', 'default'] as const) {
+ expect(readFileSync(prepareSwarmSkill(fixture(), { role: 'lead', key: 'session', mode }).file, 'utf8')).toContain(`${lost}${limit}${digest}`)
+ }
})
it('adds the checkpoint line where each Builder skill keeps others able to resume its work', () => {
const orchestration = readFileSync(prepareSwarmSkill(fixture(), { role: 'dev', key: 'session' }).file, 'utf8')
@@ -116,7 +160,7 @@ describe('built-in Swarm skills', () => {
})
// The owner's approved Default texts (attached to the spec, 2026-10-23), byte for byte.
it.each([
- ['lead', 'a7b8aed240f38edda8a461d87ce83499696588b2da41ed261821985caa63e415'],
+ ['lead', '8de53bf338b564fe1cec581a302280b778d1e62e788f8e310b36b5ad1d8f3309'],
['dev', '9294ae0dfe48a5c9185638ecb8f7cb2c2903253e5e823eb69592f3eb85455f12'],
['review', '56c1a9bfbe7cf2ff9ded4c83cebe9e801f8846250ec80849aa6afe41685db7d9'],
] as const)('writes the owner\'s Default %s skill byte for byte, with a prompt line that fits it', (role, sha256) => {
@@ -126,10 +170,17 @@ describe('built-in Swarm skills', () => {
expect(text.split(terminal)).toHaveLength(role === 'lead' ? 2 : 1)
expect(text.split(overlap)).toHaveLength(role === 'lead' ? 2 : 1)
expect(text.split(localDefault)).toHaveLength(role === 'lead' ? 2 : 1)
+ expect(text.split(plan)).toHaveLength(role === 'lead' ? 2 : 1)
expect(text.split(mention)).toHaveLength(role === 'lead' ? 2 : 1)
expect(text.split(lost)).toHaveLength(role === 'lead' ? 2 : 1)
expect(text.split(checkpoint)).toHaveLength(role === 'dev' ? 2 : 1)
- expect(sha(text.replace(terminal, '').replace(overlap, '').replace(localDefault, '').replace(mention, '').replace(lost, '').replace(checkpoint, ''))).toBe(sha256)
+ expect(text.split(limit)).toHaveLength(role === 'lead' ? 2 : 1)
+ expect(text.split(digest)).toHaveLength(role === 'lead' ? 2 : 1)
+ expect(text.split(mention + decision)).toHaveLength(role === 'lead' ? 2 : 1)
+ expect(text.split(ask)).toHaveLength(role === 'dev' ? 2 : 1)
+ expect(text.split(requestsLast)).toHaveLength(role === 'lead' ? 2 : 1)
+ expect(sha(text.replace(terminal, '').replace(overlap, '').replace(localDefault, '').replace(mention, '').replace(lost, '').replace(checkpoint, '')
+ .replace(limit, '').replace(digest, '').replace(decision, '').replace(ask, '').replace(requestsLast, ''))).toBe(sha256)
expect(prepared.instructions).toBe(`Use the swarm-${role} skill for this session: the team process; otherwise work your usual way. Before working, read ${JSON.stringify(prepared.file)} with your file or shell tool.`)
})
diff --git a/cli/src/lib/swarmSkills.ts b/cli/src/lib/swarmSkills.ts
index d6383ac94..1ec915d10 100644
--- a/cli/src/lib/swarmSkills.ts
+++ b/cli/src/lib/swarmSkills.ts
@@ -109,6 +109,7 @@ For large work, post the group plan and get the owner's ok before assigning; onc
## 6. Route, start, assign
- Route each group before starting or assigning: difficulty, risk, size, why, needs. Use the pick, or override with a reason.
+- With 3 or more groups waiting, run plan first: it places them all at once on the best machines and models. Then route each group in the plan's order and start the plan's pick, with overrideReason "scheduler plan" when the route picks otherwise. If plan cannot run here, route as usual.
- Match strength to work: mechanical → cheaper; integration and judgment → standard; design or subtle risk → strongest. A review is at least as strong as the build. Don't go below the standard tier for Reviewers, or for Builders working from prose; the cheapest models take more turns and end up costing more.
- Reuse an idle agent before starting a new one. Start only on the Swarm's listed machines, from the branch the work builds on.
- Local models: when the Swarm serves one (a member's model, a shared API, a model shared with a member), the route may pick it for low-difficulty, well-specified work; it costs no subscription. Set "local":true in the route only when a person asks for a local model. When a person names a model, set "model" to their words ("deepseek 4.1 flash"): the route then offers that model alone. Start the pick with the gridModel and gridName the route gives, never a model or effort.
@@ -119,11 +120,14 @@ For large work, post the group plan and get the owner's ok before assigning; onc
- When a restart interrupts active work, read the recovery notice and its last recorded checkpoint, then check the agent’s actual session and saved work. Ask it to continue from that checkpoint and report working; either you or the assigned agent can clear the recovery block. Never replay old input or commands: they may already have taken effect. A delayed recording gap after fresh progress is not a new interruption. Keep work already in review in review while you inspect the session. Ordinary typed input, an expired recording view, a missing recorded prompt, or an unclassified gap from an older recorder does not establish that work was interrupted.
- Needs-human: get the person's decision now.
- When you need a person to act or decide, tag them in the message.
+- Ask people for decisions in one place: decision.ask puts up to 10 questions to one person at once, each with 2 to 5 options, the one you recommend and what the answer unblocks. Keep working on your recommendation, marked provisional, until they answer: a notice in that conversation tells you, and harness super-tab decisions --answered shows the answer. A decision is not a private channel: anything private goes through Chat with PM.
- Blocked: change something. Give more context, re-route to a stronger model, cut the work smaller, or fix the plan. Never resend the same thing to the same model.
- Rulings, not stalls: when a Builder hits an ambiguity you can settle, settle it and record "Ruling: what — why — cost if wrong". Ask the person only what changes what gets built.
- Each time you are woken, look at active work. Ask a worker with active work that has said nothing for 20 minutes; reassign work that has not moved for 6 hours; report on-screen trust, sign-in or permission questions in chat, naming the machine owner who can answer.
- A Builder or Reviewer that has been down for 2 hours (machine offline, session gone or stopped): cancel its task with the reason, route it, and assign it to another agent with what the first one left (branch, last revision, last report).
- When you are told a task is lost, hand it on at once: route it and assign it to another agent, avoiding what failed (another machine if its machine died, another account or engine if it hit a usage limit). The new brief tells the successor to continue from the lost attempt's pushed branch and last result, not to start over.
+- A task lost to a usage limit resumes by itself in the same session when the limit resets (its wake-up says when). Hand it on at once only to another account or engine with allowance now, with its pushed branch and last progress note.
+- Morning digest: when a person asks for one, set the project's digest to their local time and time zone ("project.digest" with time "08:00" and timeZone "Asia/Ho_Chi_Minh"). When it wakes you, check that each pull request under Shipped is merged, then post one message to the people in the project chat.
- When a worker seems stuck, read its terminal; answer prompts within its task; ask the owner before approving anything risky.
- Keep each worker supplied: have its next group ready before it finishes, so nobody waits for you.
- Cancel a duplicate, obsolete or wrong task with a reason.
@@ -159,6 +163,10 @@ For large work, post the group plan and get the owner's ok before assigning; onc
- Write like a colleague: short, in their language, without commands or internal IDs. Lead with what matters: give the most important points and offer the rest. Use their words, not Swarm's process terms; ask your question rather than explain the process.
- When talking to people, call the roles Product Manager, Engineer and Reviewer.
+## Requests and Done
+- When you open a group for a person's request, asked in the project chat or in their Chat with PM, name them as its requester: requesterId on conversation.create, or conversation.requester for a group already open. It records only that they asked, never what they wrote.
+- Mark a group Done only after its pull request has merged: the leaderboard counts a request as shipped once its group is Done with a linked PR.
+
## Red flags
| Thought | Reality |
|---|---|
@@ -237,6 +245,7 @@ With several clearly separate failures, you may start read-only subagents to inv
## 5. Blocked
- A person's decision: mark needs-human with one short question.
+- When you know who decides, add ask to that needs-human (the person, 2 to 5 options, the one you recommend, what it unblocks) and keep working on your recommendation, marked provisional, until a notice says it was answered; read the answer with harness super-tab decisions --answered.
- Can't go on: mark blocked with why, and what would unblock you.
- Post a "Needs:" line, continue the independent parts, and mark working again once it moves.
- Stop for a decision only for an irreversible or destructive step, a security-sensitive action, an effect outside your worktree, or a brief so broken that every path is a guess. Settle other ambiguity with the narrowest safe reading and a Ruling, and keep going. A missing machine, test data, or a person's hands is still a "Needs:" line; continue the independent parts.
@@ -389,6 +398,7 @@ Keep each Builder's list a few tasks deep; do the easy, self-contained parts fir
## 3. Route, start, assign
- Route each group; reuse an idle agent before starting one; start only on the Swarm's machines.
+- With 3 or more groups waiting, run plan first: it places them all at once on the best machines and models. Then route each group in the plan's order and start the plan's pick, with overrideReason "scheduler plan" when the route picks otherwise. If plan cannot run here, route as usual.
- Local models: the route may pick one for low-difficulty, well-specified work; set "local":true only when a person asks for one, set "model" to a model a person names, and start it with the route's gridModel and gridName.
- The brief is all a Builder gets; never rely on chat history.
- Before assigning, look at other projects' active work; if your task touches the same code, say so in the Leads conversation and agree an order first.
@@ -399,9 +409,12 @@ Keep each Builder's list a few tasks deep; do the easy, self-contained parts fir
- When a worker seems stuck, read its terminal; answer prompts within its task; ask the owner before approving anything risky.
- A Builder or Reviewer that has been down for 2 hours (its machine offline, its session gone, or stopped): cancel its task with the reason, route it, and assign it to another agent with what the first one left (branch, last revision, last report).
- When you are told a task is lost, hand it on at once: route it and assign it to another agent, avoiding what failed (another machine if its machine died, another account or engine if it hit a usage limit). The new brief tells the successor to continue from the lost attempt's pushed branch and last result, not to start over.
+- A task lost to a usage limit resumes by itself in the same session when the limit resets (its wake-up says when). Hand it on at once only to another account or engine with allowance now, with its pushed branch and last progress note.
+- Morning digest: when a person asks for one, set the project's digest to their local time and time zone ("project.digest" with time "08:00" and timeZone "Asia/Ho_Chi_Minh"). When it wakes you, check that each pull request under Shipped is merged, then post one message to the people in the project chat.
- Work with no progress for 6 hours goes back to you: reassign it or cut it smaller.
- Needs a person: get the decision now. Blocked: change something (context, model, size or plan); never resend the same thing.
- When you need a person to act or decide, tag them in the message.
+- Ask people for decisions in one place: decision.ask puts up to 10 questions to one person at once, each with 2 to 5 options, the one you recommend and what the answer unblocks. Keep working on your recommendation, marked provisional, until they answer: a notice in that conversation tells you, and harness super-tab decisions --answered shows the answer. A decision is not a private channel: anything private goes through Chat with PM.
- Settle ambiguities you can and record "Ruling: what — why — cost if wrong".
- When a worker finishes: reuse, keep or stop. Prefer stop.
@@ -419,6 +432,10 @@ When the project owner asks in chat to switch this project's skills (Default or
- Answer questions, blockers and completions at once.
- Every post carries a result, a decision asked for with your recommendation, a question, or a fault; never an acknowledgement alone.
- Write like a colleague: short, in their language, no commands or internal ids. Call the roles Product Manager, Engineer and Reviewer.
+
+## Requests and Done
+- When you open a group for a person's request, asked in the project chat or in their Chat with PM, name them as its requester: requesterId on conversation.create, or conversation.requester for a group already open. It records only that they asked, never what they wrote.
+- Mark a group Done only after its pull request has merged: the leaderboard counts a request as shipped once its group is Done with a linked PR.
`,
dev: `---
name: swarm-dev
@@ -452,6 +469,7 @@ You finish one group's work completely, inside its brief, as if nobody will come
## 3. Blocked
- A person's decision: mark needs-human with one short question.
+- When you know who decides, add ask to that needs-human (the person, 2 to 5 options, the one you recommend, what it unblocks) and keep working on your recommendation, marked provisional, until a notice says it was answered; read the answer with harness super-tab decisions --answered.
- Can't go on: mark blocked with why and what would unblock you, then do the independent parts.
- Stop and ask before anything irreversible, security-sensitive, outside your worktree, visible or audible on a real device, or moving hardware.
diff --git a/cli/src/superTabs/command.spec.ts b/cli/src/superTabs/command.spec.ts
index aef76134d..c96f38362 100644
--- a/cli/src/superTabs/command.spec.ts
+++ b/cli/src/superTabs/command.spec.ts
@@ -59,6 +59,23 @@ it('routes through the caller and prints the decision, or the parse failure as a
expect(await superTabCommand(['--tab', 'tab', 'route', 'g1', '{nope'], deps)).toBe(1)
expect(JSON.parse(print.mock.calls.at(-1)![0]).error).toMatch(/JSON/)
})
+it('parses plan, with or without the Lead\'s assessments, and refuses anything more', () => {
+ expect(parseSuperTabArgs([...prefix, 'plan'], where).payload).toMatchObject({ action: 'plan' })
+ expect(parseSuperTabArgs([...prefix, 'plan', '{"groups":{}}'], where).payload).toMatchObject({ action: 'plan', request: { groups: {} } })
+ expect(() => parseSuperTabArgs([...prefix, 'plan', '{}', 'extra'], where)).toThrow('harness super-tab')
+})
+it('plans through the caller with its data folder, and prints the plan or why there is none', async () => {
+ const print = vi.fn(), close = vi.fn()
+ const request = vi.fn(async (type: string, payload: Record<string, unknown> = {}) => {
+ if (type === 'agents_list') return { agents: [{ id: 'native', engine: 'claude', tmuxPane: '%42', status: 'active' }] }
+ if (payload.action === 'routeContext') return { error: 'LEAD_REQUIRED', detail: 'x' }
+ return { ok: true }
+ })
+ const deps = { where: () => where, pane: '%42', open: async () => ({ request, close, machineId: 'machine' }), print }
+ expect(await superTabCommand(['--tab', 'tab', 'plan'], deps)).toBe(1)
+ expect(request).toHaveBeenCalledWith('super_tabs', expect.objectContaining({ action: 'routeContext', tabId: 'tab', harnessId: 'native' }), 30_000)
+ expect(JSON.parse(print.mock.calls.at(-1)![0])).toMatchObject({ error: 'LEAD_REQUIRED' })
+})
it('posts a reply to one message with --reply-to, and rejects a bad id', () => {
expect(parseSuperTabArgs([...prefix, 'post', 'lead', 'Ready', 'op-1', '--reply-to', 'msg-1'], where).payload.command)
.toMatchObject({ type: 'message.send', conversationId: 'lead', text: 'Ready', replyTo: 'msg-1' })
@@ -249,3 +266,10 @@ it('keeps the mentioned people on a post that sends files', async () => {
expect(request.mock.calls.at(-1)![1]).toMatchObject({ action: 'command', command: { type: 'message.send', attachmentIds: ['f1'], mentions: ['person-ken'] } })
} finally { rmSync(dir, { recursive: true, force: true }) }
})
+
+// Decisions (v2): the Lead, or a worker, reads the decisions it asked and their answers.
+it('reads the caller\'s open decisions, or with --answered the answered ones', () => {
+ expect(parseSuperTabArgs([...prefix, 'decisions'], where).payload).toMatchObject({ action: 'decisions', state: 'open' })
+ expect(parseSuperTabArgs([...prefix, 'decisions', '--answered'], where).payload).toMatchObject({ action: 'decisions', state: 'answered' })
+ for (const argv of [[...prefix, 'decisions', 'extra'], [...prefix, 'decisions', '--answered', 'extra']]) expect(() => parseSuperTabArgs(argv, where)).toThrow('harness super-tab')
+})
diff --git a/cli/src/superTabs/command.ts b/cli/src/superTabs/command.ts
index 9f8baa2ef..1cfea03c1 100644
--- a/cli/src/superTabs/command.ts
+++ b/cli/src/superTabs/command.ts
@@ -1,6 +1,7 @@
import { inspectCapacity, startAgent } from './start.js'
import { object } from './host.js'
import { routeTask } from './routeCommand.js'
+import { planWork } from './planCommand.js'
import { openDaemon, whereFor, type Daemon, type Where } from '../agentClient/daemon.js'
import { callerOf, outsideCaller, type Frame } from '../agentClient/model.js'
import { identifier } from './host.js'
@@ -9,7 +10,7 @@ import { uploadAttachments } from './attach.js'
import { keyName } from './terminal.js'
import { randomUUID } from 'node:crypto'
-const USAGE = 'harness super-tab --tab ID [--agent ID] [--port N --machine ID] status | messages GROUP | message GROUP MESSAGE_ID | post GROUP TEXT OPERATION_ID [--reply-to MESSAGE_ID] [--attach PATH]... [--mention PERSON]... | command OPERATION_ID JSON | start OPERATION_ID JSON | resume START_ID | capacity MACHINE_ID JSON | route GROUP JSON | remove-machine MACHINE_ID [--yes] | screen AGENT [--scrollback N] | type AGENT [TEXT] [--key K]... | help'
+const USAGE = 'harness super-tab --tab ID [--agent ID] [--port N --machine ID] status | messages GROUP | message GROUP MESSAGE_ID | decisions [--answered] | post GROUP TEXT OPERATION_ID [--reply-to MESSAGE_ID] [--attach PATH]... [--mention PERSON]... | command OPERATION_ID JSON | start OPERATION_ID JSON | resume START_ID | capacity MACHINE_ID JSON | route GROUP JSON | plan [JSON] | remove-machine MACHINE_ID [--yes] | screen AGENT [--scrollback N] | type AGENT [TEXT] [--key K]... | help'
export function parseSuperTabArgs(argv: readonly string[], where: Where) {
const positional: string[] = []
let tabId = '', agentId = ''
@@ -27,6 +28,7 @@ export function parseSuperTabArgs(argv: readonly string[], where: Where) {
if (action !== 'help' && (!identifier(tabId) || (agentId && !identifier(agentId)))) throw new Error(USAGE)
const payload: Record<string, unknown> = { action, tabId, agentId }
if (action === 'messages' && identifier(first) && positional.length === 2) payload.conversationId = first
+ else if (action === 'decisions' && (positional.length === 1 || (positional.length === 2 && first === '--answered'))) payload.state = first ? 'answered' : 'open'
else if (action === 'message' && identifier(first) && identifier(second) && positional.length === 3) {
Object.assign(payload, { conversationId: first, messageId: second })
}
@@ -61,6 +63,8 @@ export function parseSuperTabArgs(argv: readonly string[], where: Where) {
: { action: 'backend', method: 'GET', path: `/api/super-tabs/${tabId}/machines/${first}/removal` })
} else if (action === 'route' && identifier(first) && second && positional.length === 3) {
Object.assign(payload, { conversationId: first, assessment: JSON.parse(second) })
+ } else if (action === 'plan' && positional.length <= 2) {
+ if (first !== undefined) payload.request = JSON.parse(first)
} else if (action === 'screen' && identifier(first) && (positional.length === 2
|| positional.length === 4 && second === '--scrollback' && /^[1-9]\d*$/.test(third ?? '') && Number(third) <= 200)) {
// The id names this one read; a read sent twice is only read twice.
@@ -138,6 +142,9 @@ export async function superTabCommand(argv: readonly string[], deps: {
} else if (request.payload.action === 'route') {
result = await routeTask({ tabId: String(request.payload.tabId), conversationId: String(request.payload.conversationId),
assessment: request.payload.assessment }, scoped, request.where, deps.open)
+ } else if (request.payload.action === 'plan') {
+ // Advisory: the plan records nothing, and the solver runs here, on the Lead's machine.
+ result = await planWork({ request: request.payload.request }, scoped, { dataDir: request.where.dataDir })
} else {
const { attach, ...payload } = request.payload
// Each file goes to the daemon's local upload route, which streams it to the backend with the account's token;
diff --git a/cli/src/superTabs/configuration.spec.ts b/cli/src/superTabs/configuration.spec.ts
index ed2690fd0..04f14d79a 100644
--- a/cli/src/superTabs/configuration.spec.ts
+++ b/cli/src/superTabs/configuration.spec.ts
@@ -41,3 +41,21 @@ it('refuses an unknown, mismatched, unavailable or unrelated native reading', ()
core.agents.terminalAvailable = () => false
expect(configurationObservation(core, 'machine', row)).toBeNull()
})
+
+// Builders started with opus and effort high read as effort 'auto' (Dee, 2026-10-27): Claude Code never reports an effort
+// it was launched with (--effort), so its reading falls back to 'auto', and that overwrote the effort the start stored.
+it('keeps a known effort when the same model reads as auto, and reports auto only with another model', () => {
+ const core = fixture()
+ vi.mocked(core.agents.runtimeProfile).mockReturnValue('runtime-v1:harness:claude:opus@auto')
+ expect(configurationObservation(core, 'machine', row)).toBeNull()
+ // A real change of effort is still reported.
+ vi.mocked(core.agents.runtimeProfile).mockReturnValue('runtime-v1:harness:claude:opus@max')
+ expect(configurationObservation(core, 'machine', row)!.body.command.configuration.effort).toBe('max')
+ // Another model: the stored effort was that model's, so the reading stands as it is.
+ vi.mocked(core.agents.runtimeProfile).mockReturnValue('runtime-v1:harness:claude:sonnet@auto')
+ expect(configurationObservation(core, 'machine', row)!.body.command.configuration).toMatchObject({ model: 'sonnet', effort: 'auto' })
+ // Nothing known yet: auto is all there is to say.
+ const unknown = { ...row, agent: { ...row.agent, configuration: { ...previous, effort: 'auto' } } }
+ vi.mocked(core.agents.runtimeProfile).mockReturnValue('runtime-v1:harness:claude:opus@auto')
+ expect(configurationObservation(core, 'machine', unknown)).toBeNull()
+})
diff --git a/cli/src/superTabs/configuration.ts b/cli/src/superTabs/configuration.ts
index 9c775f031..338dc8945 100644
--- a/cli/src/superTabs/configuration.ts
+++ b/cli/src/superTabs/configuration.ts
@@ -14,8 +14,11 @@ export function configurationObservation(core: CoreApi, machineId: string, value
const profile = parseRuntimeProfile(core.agents.runtimeProfile(native))
if (!profile || profile.sessionId !== native.agentId || profile.engine !== native.engine || profile.model.length > 200) return null
const sameModel = previous.engine === native.engine && previous.model === profile.model
+ // Claude Code never reports an effort it was launched with (--effort), so its reading falls back to 'auto': for the same
+ // model, that is no news about a known effort. Builders started with opus high read as auto until 2026-10-27.
+ const unread = profile.effort === 'auto' && sameModel && typeof previous.effort === 'string'
const configuration = {
- engine: native.engine, model: profile.model, effort: profile.effort,
+ engine: native.engine, model: profile.model, effort: unread ? previous.effort : profile.effort,
contextWindow: sameModel && Number.isSafeInteger(previous.contextWindow) && Number(previous.contextWindow) > 0 ? previous.contextWindow : null,
engineVersion: previous.engine === native.engine && typeof previous.engineVersion === 'string' ? previous.engineVersion : null,
}
diff --git a/cli/src/superTabs/fixtures/planState.ts b/cli/src/superTabs/fixtures/planState.ts
new file mode 100644
index 000000000..a6c401ac8
--- /dev/null
+++ b/cli/src/superTabs/fixtures/planState.ts
@@ -0,0 +1,41 @@
+/** A Swarm state as the status read gives it, trimmed to what `harness super-tab plan` reads (planInput.spec.ts, planCommand.spec.ts). */
+import type { Policy } from '../route.js'
+
+export const NOW = Date.parse('2026-10-27T01:00:00Z')
+export const policy: Policy = { version: 1, floor: { low: 1, medium: 2, high: 3 }, quotaReserve: 10, notes: '', localModels: { quality: 1, enabled: true }, models: [
+ { engine: 'claude', model: 'opus', effort: 'high', quality: 3, cost: 3, enabled: true },
+ { engine: 'codex', model: 'default', effort: 'default', quality: 3, cost: 2, enabled: true },
+ { engine: 'claude', model: 'sonnet', effort: 'medium', quality: 2, cost: 2, enabled: true },
+ { engine: 'claude', model: 'haiku', effort: 'auto', quality: 1, cost: 1, enabled: false },
+] }
+export type Json = Record<string, unknown>
+
+/** A contributed machine as the status read gives it (a real reading, trimmed of fields the plan does not read). */
+export function machine(id: string, extra: Json = {}, observation: Json = {}): Json {
+ return {
+ machineId: id, name: `${id}.local`, cwd: `/Users/x/.harness/cli/data/swarm-projects/tab`, engines: ['claude', 'codex', 'cursor'], maxAgents: 8,
+ scope: 'swarm', contributorId: 'owner', paused: false, availableSlots: 2, teamWork: { allowed: true }, ...extra,
+ observation: {
+ receivedAt: NOW - 5_000, tools: { git: true, node: true, gh: true, python3: true },
+ resources: { memoryTotalBytes: 68_719_476_736, memoryUsedBytes: 36_894_949_376, projectDiskFreeBytes: 132_155_797_504, os: 'macOS' },
+ quotas: [
+ { engine: 'claude', known: true, windows: [{ name: '5-hour', usedPercent: 2, resetsAt: '2026-10-27T03:30:00+00:00' }, { name: 'weekly', usedPercent: 30, resetsAt: '2026-11-01T19:00:00+00:00' }] },
+ { engine: 'codex', known: true, windows: [{ name: 'weekly', usedPercent: 40, resetsAt: 1793592000 }] },
+ ],
+ localModels: [], ...observation,
+ },
+ }
+}
+const task = { goal: 'g', changes: 'c', constraints: 'k', owns: ['x/**'] }
+export function group(id: string, extra: Json = {}): Json {
+ return { id, projectId: 'p1', title: `Group ${id}`, leadId: 'lead1', agentIds: ['lead1'], archived: false, task, assignment: null, ...extra }
+}
+export function state(extra: Json = {}): Json {
+ return {
+ id: 'tab', ownerId: 'owner', agents: [], starts: [], rules: [], localModels: { grid: 'swarm-g', enabled: true, ready: true },
+ projects: [{ id: 'p1', ownerId: 'owner', repository: { machineId: 'm1', cwd: '/repo', repositoryUrl: 'https://github.com/o/r' } }],
+ machines: [machine('m1'), machine('m2')],
+ conversations: [{ id: 'lead', leadId: 'lead1', title: 'Lead' }, group('g1'), group('g2')],
+ ...extra,
+ }
+}
diff --git a/cli/src/superTabs/host.spec.ts b/cli/src/superTabs/host.spec.ts
index 20887f0a5..f4f3accf9 100644
--- a/cli/src/superTabs/host.spec.ts
+++ b/cli/src/superTabs/host.spec.ts
@@ -8,6 +8,7 @@ import type { CoreApi, TurnDelivery } from '../core/api.js'
import { fakeCore } from '../testing/fakeCore.js'
import { backend, swarmRoleFor, hostJournalFile, SuperTabHost, type SuperTabHostOptions } from './host.js'
import { hostForm, swarmReply } from './fixtures/read/index.js'
+import { CONTINUE } from './limitResume.js'
import { HostFeed } from './hostFeed.js'
import { SwarmReads } from './swarmReads.js'
import { retainedHarnesses, retentionFile } from './retention.js'
@@ -1060,6 +1061,75 @@ describe('a Lead\'s terminal requests', () => {
})
})
+describe('a task lost to a usage limit', () => {
+ it('is resumed in its session from the roster row once the limit has reset', async () => {
+ const t = setup()
+ Object.assign(t.core, { superTabs: { attention: vi.fn(), cards: vi.fn(), cardRecap: vi.fn(), shareObservers: vi.fn(),
+ input: vi.fn(async () => ({ ok: true as const })), screen: vi.fn(async () => ({ ok: true as const, text: '❯ ', hold: null })) } })
+ Object.assign(t.row, { resume: { conversationId: 'group', assignmentId: 'work', lostAt: 3, at: new Date(0).toISOString() } })
+ // Once the backend gave the task back, this machine's assignment rows list it running in this session.
+ const roster = vi.mocked(t.call).getMockImplementation()!
+ let resumed = false
+ vi.mocked(t.call).mockImplementation(async (method, path, body) => {
+ if ((body as { command?: { type?: string } } | undefined)?.command?.type === 'work.resume') resumed = true
+ return path.includes('/hosts/machine-1/changes')
+ ? { status: 200, body: { success: true, data: hostForm([t.row], { assignments: resumed ? [{ tabId: 'tab', assignmentId: 'work', harnessId: 'harness' }] : [] }) } }
+ : roster(method, path, body)
+ })
+ await t.open().tick()
+ await vi.waitFor(() => expect(t.core.superTabs!.input).toHaveBeenCalledWith('harness', CONTINUE, ['Enter']))
+ expect(t.call).toHaveBeenCalledWith('POST', '/api/super-tabs/tab/commands',
+ { operationId: 'limit-resume-work-3', asAgentId: 'agent', command: { type: 'work.resume', conversationId: 'group', assignmentId: 'work', lostAt: 3 } })
+ })
+ // #1757 re-check: a feed read already running when the backend answered was sent before it, and may predate a takeover.
+ it('checks ownership with a feed read that starts after the backend answered, never one already running', async () => {
+ const t = setup()
+ Object.assign(t.core, { superTabs: { attention: vi.fn(), cards: vi.fn(), cardRecap: vi.fn(), shareObservers: vi.fn(),
+ input: vi.fn(async () => ({ ok: true as const })), screen: vi.fn(async () => ({ ok: true as const, text: '❯ ', hold: null })) } })
+ Object.assign(t.row, { resume: { conversationId: 'group', assignmentId: 'work', lostAt: 3, at: new Date(0).toISOString() } })
+ const roster = vi.mocked(t.call).getMockImplementation()!
+ const listed = { tabId: 'tab', assignmentId: 'work', harnessId: 'harness' }
+ let reads = 0, answer!: () => void, stale!: () => void
+ vi.mocked(t.call).mockImplementation(async (method, path, body) => {
+ if ((body as { command?: { type?: string } } | undefined)?.command?.type === 'work.resume') {
+ await new Promise<void>(resolve => { answer = resolve })
+ return { status: 200, body: { success: true, data: { result: {} } } }
+ }
+ if (!path.includes('/hosts/machine-1/changes')) return roster(method, path, body)
+ const read = ++reads
+ // The second read, an ordinary poll, was sent while the backend was answering: what it says predates the takeover.
+ if (read === 2) await new Promise<void>(resolve => { stale = resolve })
+ return { status: 200, body: { success: true, data: hostForm([t.row], { assignments: read === 2 ? [listed] : [] }) } }
+ })
+ const host = t.open()
+ await host.tick()
+ await vi.waitFor(() => expect(answer).toBeDefined())
+ const polling = host.tick()
+ await vi.waitFor(() => expect(stale).toBeDefined())
+ answer()
+ // The answer is in while the old poll is still out; once it lands, the check reads again.
+ await new Promise(resolve => setImmediate(resolve))
+ stale()
+ await polling
+ // Either it typed on the stale read, or it read again and found the task handed on.
+ await vi.waitFor(() => expect(vi.mocked(t.core.superTabs!.input).mock.calls.length
+ || vi.mocked(t.log).mock.calls.some(([message]) => String(message).startsWith('limit resume of work'))).toBeTruthy())
+ expect(t.core.superTabs!.input).not.toHaveBeenCalled()
+ expect(t.log).toHaveBeenCalledWith('limit resume of work: the task is no longer this session\'s')
+ expect(reads).toBe(3)
+ })
+
+ it('does not type when its assignment rows do not list the task in this session after the backend answered', async () => {
+ const t = setup()
+ Object.assign(t.core, { superTabs: { attention: vi.fn(), cards: vi.fn(), cardRecap: vi.fn(), shareObservers: vi.fn(),
+ input: vi.fn(async () => ({ ok: true as const })), screen: vi.fn(async () => ({ ok: true as const, text: '❯ ', hold: null })) } })
+ Object.assign(t.row, { resume: { conversationId: 'group', assignmentId: 'work', lostAt: 3, at: new Date(0).toISOString() } })
+ await t.open().tick()
+ await vi.waitFor(() => expect(t.log).toHaveBeenCalledWith('limit resume of work: the task is no longer this session\'s'))
+ expect(t.core.superTabs!.input).not.toHaveBeenCalled()
+ })
+})
+
describe('the progress a host reports', () => {
it('sends with its machine\'s reading when each agent\'s screen last changed', async () => {
const t = setup()
diff --git a/cli/src/superTabs/host.ts b/cli/src/superTabs/host.ts
index 7704cdd89..79c6c8c6b 100644
--- a/cli/src/superTabs/host.ts
+++ b/cli/src/superTabs/host.ts
@@ -19,6 +19,7 @@ import { prepareContribution, prepareTeamContribution } from './contribution.js'
import { hostname } from 'node:os'
import { replacementObservations } from './replacements.js'
import { TerminalHost } from './terminal.js'
+import { LimitResume } from './limitResume.js'
import { HostFeed } from './hostFeed.js'
import { SwarmReads } from './swarmReads.js'
import { UPDATE_REQUIRED } from './readContract.js'
@@ -239,6 +240,8 @@ export class SuperTabHost {
private updateSaid = false
/** A Lead's reads of and typing into this machine's agents' terminals, and the stuck and usage-limit alerts. */
private readonly terminal: TerminalHost
+ /** Gives a task lost to a usage limit back to its session once the limit has reset. */
+ private readonly limitResume: LimitResume
constructor(private readonly core: CoreApi, readonly machineId: string, options: SuperTabHostOptions = {}) {
if (!identifier(machineId)) throw new SuperTabHostError('MACHINE_UNAVAILABLE', 'This machine is not signed in.')
@@ -254,6 +257,9 @@ export class SuperTabHost {
this.write = options.write ?? writeJournal
this.log = options.log ?? (message => console.warn(`[super-tabs] ${message}`))
this.terminal = new TerminalHost(core, machineId, { now: this.now, log: this.log })
+ this.limitResume = new LimitResume(core, machineId, { now: this.now, log: this.log,
+ owns: async (tabId, assignmentId, harnessId) => (await this.sources.feed.fresh()).assignments
+ .some(a => a.tabId === tabId && a.assignmentId === assignmentId && a.harnessId === harnessId) })
this.sources = options.sources ?? { feed: new HostFeed(core, machineId, { now: this.now }), reads: new SwarmReads(core) }
this.journal = { version: 1, machineId, entries: {} }
if (existsSync(this.file)) {
@@ -538,7 +544,7 @@ export class SuperTabHost {
this.joinTeams(data)
this.cleanRemoved(data)
// Off the poll: a screen read waits on the core, and never delays the input leases below.
- if (this.core.superTabs) void this.terminal.tick(data)
+ if (this.core.superTabs) { void this.terminal.tick(data); void this.limitResume.tick(data) }
// Recovery can wait on a native receipt. Run it beside leases, so another worker's input
// never expires while an old Change agent is being reconciled.
if (!this.replacementsRunning && this.now() >= this.nextReplacementsAt) {
diff --git a/cli/src/superTabs/hostFeed.spec.ts b/cli/src/superTabs/hostFeed.spec.ts
index b010bacbc..b0e1c9994 100644
--- a/cli/src/superTabs/hostFeed.spec.ts
+++ b/cli/src/superTabs/hostFeed.spec.ts
@@ -93,6 +93,18 @@ describe('the host form of a machine\'s Swarms', () => {
expect(paths()).toEqual([FULL, SINCE(C0)])
})
+ it('gives a caller that must see what happened before it asked a read sent after it, never one already out', async () => {
+ const { feed, paths } = feedOf([ok(readFixture('host-full')), ok(readFixture('host-quiet'))])
+ const out = feed.refresh()
+ const fresh = feed.fresh()
+ await Promise.all([out, fresh])
+ expect(paths()).toEqual([FULL, SINCE(C0)])
+ // With none out, it reads at once.
+ await feed.fresh()
+ expect(paths()).toHaveLength(3)
+ expect(paths()[2]).toMatch(/^POST since /)
+ })
+
it('takes no rows from a Swarm whose lists are malformed, and still those of the others', async () => {
const form = readFixture<{ tabs: Json[] }>('host-full')
const { feed } = feedOf([ok({ ...form, tabs: [{ tabId: 'odd', roster: {}, pool: 'none', assignments: null }, ...form.tabs] })])
diff --git a/cli/src/superTabs/hostFeed.ts b/cli/src/superTabs/hostFeed.ts
index 895bca0f6..4eb6bc290 100644
--- a/cli/src/superTabs/hostFeed.ts
+++ b/cli/src/superTabs/hostFeed.ts
@@ -35,6 +35,13 @@ export class HostFeed {
return this.running ??= this.read().finally(() => { this.running = null })
}
+ /** A read sent after this call. One already out may have been sent before what the caller must see, such as a takeover
+ * before a resume's answer (cli limitResume.ts, #1757 re-check), so it is waited out, never joined. */
+ async fresh(): Promise<HostRead> {
+ await this.running?.catch(() => {})
+ return this.refresh()
+ }
+
/** The last read while it is at most `maxAgeMs` old, else a new one: for readers off the host's own one-second tick. */
current(maxAgeMs: number): Promise<HostRead> {
if (!this.running && this.now() - this.readAt < maxAgeMs) return Promise.resolve(this.snapshot())
diff --git a/cli/src/superTabs/limitResume.spec.ts b/cli/src/superTabs/limitResume.spec.ts
new file mode 100644
index 000000000..7eafd91cb
--- /dev/null
+++ b/cli/src/superTabs/limitResume.spec.ts
@@ -0,0 +1,160 @@
+import { readFileSync } from 'node:fs'
+import { describe, expect, it, vi } from 'vitest'
+import type { CoreApi, SuperTabScreen } from '../core/api.js'
+import { screen as claudeScreen } from '../engines/claude/screen.js'
+import { screen as codexScreen } from '../engines/codex/screen.js'
+import { fakeCore } from '../testing/fakeCore.js'
+import { CONTINUE, LimitResume } from './limitResume.js'
+
+const RESET = 1_000_000 + 30 * 60_000
+const resume = { conversationId: 'g1', assignmentId: 'w1', lostAt: 5, at: new Date(RESET).toISOString() }
+const row = (over: Record<string, unknown> = {}) => ({ tabId: 'tab', agent: { id: 'a1', harnessId: 'h1', machineId: 'm1' }, resume, ...over })
+/** A screen as the engine draws it (fixtures/screens). */
+const fixture = (name: string) => readFileSync(new URL(`./fixtures/screens/${name}.txt`, import.meta.url), 'utf8')
+
+function setup(options: { live?: string[]; reply?: () => { status: number; body: Record<string, unknown> }; screen?: () => SuperTabScreen; owns?: () => boolean } = {}) {
+ let clock = 1_000_000
+ const steps: string[] = []
+ const backend: CoreApi['account']['backend'] = vi.fn(async (_method, _path, body) => {
+ steps.push(`ask ${(body as { command: { type: string } }).command.type}`)
+ return options.reply?.() ?? { status: 200, body: { success: true, data: { result: {} } } }
+ })
+ const core = fakeCore({
+ account: { backend },
+ agents: { byAgent: vi.fn((id: string) => (options.live ?? ['h1']).includes(id) ? { agentId: id } as never : undefined) },
+ superTabs: { attention: vi.fn(), cards: vi.fn(), cardRecap: vi.fn(), shareObservers: vi.fn(), screen: vi.fn(async () => options.screen?.() ?? { ok: true as const, text: '❯ ', hold: null }),
+ input: vi.fn(async (_harnessId: string, text: string) => { steps.push(`type ${text}`); return { ok: true as const } }) },
+ })
+ // The host's current assignment rows, read after the backend answered (host.ts reads its feed).
+ const owns = vi.fn(async (tabId: string, assignmentId: string, harnessId: string) => { steps.push(`check ${tabId} ${assignmentId} ${harnessId}`); return options.owns?.() ?? true })
+ const resumer = new LimitResume(core, 'm1', { now: () => clock, log: vi.fn(), owns })
+ return { core, backend, steps, resumer, wait: (ms: number) => { clock += ms } }
+}
+
+describe('a host resuming a task its agent lost to a usage limit', () => {
+ it('waits for the reset, then asks the backend to give the task back before typing continue into the same session', async () => {
+ const t = setup()
+ await t.resumer.tick([row()])
+ expect(t.steps).toEqual([])
+ t.wait(30 * 60_000)
+ await t.resumer.tick([row()])
+ expect(t.steps).toEqual(['ask work.resume', 'check tab w1 h1', `type ${CONTINUE}`])
+ expect(t.backend).toHaveBeenCalledWith('POST', '/api/super-tabs/tab/commands', { operationId: 'limit-resume-w1-5', asAgentId: 'a1',
+ command: { type: 'work.resume', conversationId: 'g1', assignmentId: 'w1', lostAt: 5 } })
+ expect(t.core.superTabs!.input).toHaveBeenCalledWith('h1', CONTINUE, ['Enter'])
+ })
+
+ it('never types into the session when the backend says the task was handed on first, and does not ask again', async () => {
+ const t = setup({ reply: () => ({ status: 409, body: { success: false, error: { code: 'TASK_MOVED', message: 'This task was handed on or closed, so it does not resume.' } } }) })
+ t.wait(30 * 60_000)
+ await t.resumer.tick([row()])
+ await t.resumer.tick([row()])
+ expect(t.steps).toEqual(['ask work.resume'])
+ expect(t.core.superTabs!.input).not.toHaveBeenCalled()
+ })
+
+ it('does not type when this session no longer holds the task though the backend said yes: a replayed yes after a takeover (#1757 review, 2)', async () => {
+ const t = setup({ owns: () => false })
+ t.wait(30 * 60_000)
+ await t.resumer.tick([row()])
+ t.wait(15_000)
+ await t.resumer.tick([row()])
+ expect(t.steps).toEqual(['ask work.resume', 'check tab w1 h1'])
+ expect(t.core.superTabs!.input).not.toHaveBeenCalled()
+ })
+
+ it('asks again on a later read when the backend could not be reached or its clock has not reached the reset yet', async () => {
+ const replies = [{ status: 503, body: { success: false, error: { code: 'BACKEND_UNAVAILABLE', message: 'Down.' } } },
+ { status: 409, body: { success: false, error: { code: 'LIMIT_NOT_RESET', message: 'Its usage limit has not reset yet.' } } }]
+ const t = setup({ reply: () => replies.shift() ?? { status: 200, body: { success: true, data: { result: {} } } } })
+ t.wait(30 * 60_000)
+ for (let i = 0; i < 3; i++) {
+ await t.resumer.tick([row()])
+ await t.resumer.tick([row()])
+ t.wait(15_000)
+ }
+ expect(t.steps).toEqual(['ask work.resume', 'ask work.resume', 'ask work.resume', 'check tab w1 h1', `type ${CONTINUE}`])
+ })
+
+ it('types continue once, though a roster read from before the resume still lists it', async () => {
+ const t = setup()
+ t.wait(30 * 60_000)
+ await t.resumer.tick([row()])
+ await t.resumer.tick([row()])
+ expect(t.steps).toEqual(['ask work.resume', 'check tab w1 h1', `type ${CONTINUE}`])
+ })
+
+ it('resumes the same task again when it is lost to a limit a second time (#1757 review, 1)', async () => {
+ const t = setup()
+ t.wait(30 * 60_000)
+ await t.resumer.tick([row()])
+ t.wait(60 * 60_000)
+ await t.resumer.tick([row({ resume: { ...resume, lostAt: 9, at: new Date(RESET + 30 * 60_000).toISOString() } })])
+ expect(t.steps).toEqual(['ask work.resume', 'check tab w1 h1', `type ${CONTINUE}`, 'ask work.resume', 'check tab w1 h1', `type ${CONTINUE}`])
+ expect(vi.mocked(t.backend).mock.calls.map(([, , body]) => (body as { operationId: string }).operationId)).toEqual(['limit-resume-w1-5', 'limit-resume-w1-9'])
+ })
+
+ it('leaves alone an agent of another machine, one not running here, one stopping, and one with nothing to resume', async () => {
+ const t = setup({ live: ['h1', 'h3'] })
+ t.wait(30 * 60_000)
+ await t.resumer.tick([row({ agent: { id: 'a2', harnessId: 'h2', machineId: 'm2' } }), row({ agent: { id: 'a4', harnessId: 'h4', machineId: 'm1' } }),
+ row({ agent: { id: 'a3', harnessId: 'h3', machineId: 'm1' }, stopRequested: true }), row({ resume: null }), { tabId: 'tab', cleanup: { machineId: 'm1', removalId: 'x' } }])
+ expect(t.steps).toEqual([])
+ })
+
+ it('holds back the typing while a prompt or a menu is open, where Enter would choose something, and types once it is gone', async () => {
+ let hold: SuperTabScreen = { ok: true, text: 'Allow edit? 1. Yes 2. No', hold: 'permission_open' }
+ const t = setup({ screen: () => hold })
+ t.wait(30 * 60_000)
+ await t.resumer.tick([row()])
+ expect(t.steps).toEqual(['ask work.resume', 'check tab w1 h1'])
+ // The task is the agent's again, so its row no longer asks; the host still owes the typing.
+ hold = { ok: false, error: 'Could not read the terminal.' }
+ t.wait(15_000)
+ await t.resumer.tick([row({ resume: null })])
+ hold = { ok: true, text: '❯ ', hold: null }
+ await t.resumer.tick([row({ resume: null })])
+ expect(t.steps).toEqual(['ask work.resume', 'check tab w1 h1', 'check tab w1 h1'])
+ t.wait(15_000)
+ await t.resumer.tick([row({ resume: null })])
+ expect(t.steps).toEqual(['ask work.resume', 'check tab w1 h1', 'check tab w1 h1', 'check tab w1 h1', `type ${CONTINUE}`])
+ })
+
+ it('reads the screen when it types: a prompt that opens while the backend answers gets no continue (#1757 review, 3)', async () => {
+ let screen: SuperTabScreen = { ok: true, text: '❯ ', hold: null }
+ const t = setup({ screen: () => screen, reply: () => {
+ screen = { ok: true, text: 'Allow edit? 1. Yes 2. No', hold: 'permission_open' }
+ return { status: 200, body: { success: true, data: { result: {} } } }
+ } })
+ t.wait(30 * 60_000)
+ await t.resumer.tick([row()])
+ expect(t.steps).toEqual(['ask work.resume', 'check tab w1 h1'])
+ expect(t.core.superTabs!.input).not.toHaveBeenCalled()
+ })
+
+ it('drops typing it still owes once the task is no longer this session\'s', async () => {
+ let owns = true
+ const t = setup({ screen: () => ({ ok: true, text: 'Allow edit? 1. Yes 2. No', hold: 'permission_open' }), owns: () => owns })
+ t.wait(30 * 60_000)
+ await t.resumer.tick([row()])
+ owns = false
+ t.wait(15_000)
+ await t.resumer.tick([])
+ t.wait(15_000)
+ await t.resumer.tick([])
+ expect(t.steps).toEqual(['ask work.resume', 'check tab w1 h1', 'check tab w1 h1'])
+ })
+
+ // Nothing redraws when a limit resets: the screen its host reads then is the limit screen the engine left (Lead,
+ // 2026-10-27: prove continue goes into each engine). Codex marks its composer in bold only, so a plain read of it says
+ // the prompt is hidden; that is no prompt or menu Enter would answer.
+ it.each([['claude-session-limit', claudeScreen], ['claude-weekly-limit', claudeScreen], ['claude-opus-limit', claudeScreen],
+ ['claude-fable-limit', claudeScreen], ['codex-usage-limit', codexScreen], ['codex-model-limit', codexScreen]] as const)(
+ 'types continue into the %s screen as its engine reads it after the reset', async (name, engine) => {
+ const text = fixture(name)
+ const t = setup({ screen: () => ({ ok: true, text, hold: engine.inspect(text).messageHold }) })
+ t.wait(30 * 60_000)
+ await t.resumer.tick([row()])
+ expect(t.steps).toEqual(['ask work.resume', 'check tab w1 h1', `type ${CONTINUE}`])
+ })
+})
diff --git a/cli/src/superTabs/limitResume.ts b/cli/src/superTabs/limitResume.ts
new file mode 100644
index 000000000..7152447cc
--- /dev/null
+++ b/cli/src/superTabs/limitResume.ts
@@ -0,0 +1,99 @@
+/**
+ * Night shift (v2 B): a worker that hits a usage limit loses its task at once (backend superTabs/liveness.ts), and nothing
+ * took it back: lampOS lost about four times its throughput overnight to agents waiting out limits. When the limit screen
+ * said when it resets, the roster row says when the task resumes, until the Lead hands it on. Then this host types a short
+ * continue into that same session. It asks the backend first and types only once the backend has given the task back, so
+ * a task handed on before the reset never resumes in the old session.
+ */
+import type { CoreApi } from '../core/api.js'
+import { backend } from './host.js'
+import { WAITING } from './terminal.js'
+import { identifier, object, SuperTabHostError } from './wire.js'
+
+/** The agent was told its task moved when it was lost (liveness.ts), so the line says the task is its own again. */
+export const CONTINUE = 'continue: your usage limit has reset and this task is yours again'
+/** A resume that could not happen yet (a prompt open, the backend out of reach or its clock behind) waits this long. */
+const RETRY_MS = 15_000
+
+/** A loss due to resume: its agent here, and which loss of which task. */
+interface Due { tabId: string; agentId: string; harnessId: string; conversationId: string; assignmentId: string; lostAt: number; key: string }
+/** Whether this machine's assignment rows list the task as running in this session now (host.ts reads its feed). */
+type Owns = (tabId: string, assignmentId: string, harnessId: string) => Promise<boolean>
+
+export class LimitResume {
+ /** Losses resumed or refused here, by assignment and loss (one task can be lost, resumed and lost again): neither is
+ * asked about again, though a roster read from before still lists it. */
+ private readonly settled = new Set<string>()
+ private readonly retryAt = new Map<string, number>()
+ /** Losses the backend gave back whose continue is not typed yet: the row stops listing them once the task is resumed. */
+ private readonly typing = new Map<string, Due>()
+ private running: Promise<void> | null = null
+ private readonly now: () => number
+ private readonly log: (message: string) => void
+ private readonly owns: Owns
+
+ constructor(private readonly core: CoreApi, private readonly machineId: string, options: { owns: Owns; now?: () => number; log?: (message: string) => void }) {
+ this.owns = options.owns
+ this.now = options.now ?? Date.now
+ this.log = options.log ?? (message => console.warn(`[super-tabs] ${message}`))
+ }
+
+ /** Each host roster read; one pass at a time. */
+ tick(rows: unknown[]): Promise<void> {
+ return this.running ??= this.resumeDue(rows).catch(error => this.log(error instanceof Error ? error.message : String(error)))
+ .finally(() => { this.running = null })
+ }
+
+ private async resumeDue(rows: unknown[]): Promise<void> {
+ const now = this.now()
+ for (const row of rows.map(object)) {
+ const agent = object(row.agent), resume = object(row.resume)
+ if (!identifier(row.tabId) || !identifier(agent.id) || !identifier(agent.harnessId) || agent.machineId !== this.machineId) continue
+ if (!identifier(resume.conversationId) || !identifier(resume.assignmentId) || !Number.isSafeInteger(resume.lostAt) || !(Date.parse(String(resume.at)) <= now)) continue
+ const key = `${resume.assignmentId}-${resume.lostAt}`
+ if (row.stopRequested === true || !this.core.agents.byAgent(agent.harnessId) || this.settled.has(key) || (this.retryAt.get(key) ?? 0) > now) continue
+ await this.resume({ tabId: row.tabId, agentId: agent.id, harnessId: agent.harnessId, conversationId: resume.conversationId,
+ assignmentId: resume.assignmentId, lostAt: resume.lostAt as number, key }, now)
+ }
+ for (const due of [...this.typing.values()]) if ((this.retryAt.get(due.key) ?? 0) <= now) await this.type(due, now)
+ }
+
+ /** Asks the backend for the task back; once it says yes, the continue is owed (`typing`). */
+ private async resume(due: Due, now: number): Promise<void> {
+ try {
+ // The same operation each time: an answer lost on the way is replayed, not applied twice.
+ await backend(this.core, 'POST', `/api/super-tabs/${due.tabId}/commands`, { operationId: `limit-resume-${due.key}`, asAgentId: due.agentId,
+ command: { type: 'work.resume', conversationId: due.conversationId, assignmentId: due.assignmentId, lostAt: due.lostAt } })
+ } catch (error) {
+ const refused = error instanceof SuperTabHostError && error.status >= 400 && error.status < 500 && error.code !== 'LIMIT_NOT_RESET'
+ this.log(`limit resume of ${due.assignmentId}: ${error instanceof Error ? error.message : String(error)}`)
+ if (refused) this.settled.add(due.key)
+ else this.retryAt.set(due.key, now + RETRY_MS)
+ return
+ }
+ this.settled.add(due.key)
+ this.retryAt.delete(due.key)
+ this.typing.set(due.key, due)
+ }
+
+ /** Types the owed continue, checking each time first that the task is still this session's and nothing on screen would
+ * take the Enter. The screen is read here, after the backend answered, not before asking (#1757 review, 3): a prompt
+ * that opened meanwhile would have taken it. The read and the typing are still two steps; the terminal module checks
+ * holds at input once it lives outside the core (the follow-up to Avery's move). */
+ private async type(due: Due, now: number): Promise<void> {
+ // A replayed yes is the first answer, not who holds the task now: after a lost reply and a takeover it still says yes
+ // (#1757 review, 2). The assignment rows read now say whether this session runs it.
+ if (!await this.owns(due.tabId, due.assignmentId, due.harnessId)) {
+ this.typing.delete(due.key)
+ return this.log(`limit resume of ${due.assignmentId}: the task is no longer this session's`)
+ }
+ // Enter on a permission prompt, a question or a menu would answer it. An unreadable screen says nothing either way.
+ const read = await this.core.superTabs!.screen(due.harnessId, 0).catch(() => null)
+ if (!read?.ok || (read.hold !== null && WAITING.has(read.hold))) return void this.retryAt.set(due.key, now + RETRY_MS)
+ this.typing.delete(due.key)
+ this.retryAt.delete(due.key)
+ // The task is the agent's again either way; one it never continues is lost again when its lease runs out.
+ const typed = await this.core.superTabs!.input(due.harnessId, CONTINUE, ['Enter'])
+ if (!typed.ok) this.log(`limit resume of ${due.assignmentId}: ${typed.error}`)
+ }
+}
diff --git a/cli/src/superTabs/planCommand.spec.ts b/cli/src/superTabs/planCommand.spec.ts
new file mode 100644
index 000000000..dcde91c64
--- /dev/null
+++ b/cli/src/superTabs/planCommand.spec.ts
@@ -0,0 +1,162 @@
+import { execFile, spawnSync } from 'node:child_process'
+import { promisify } from 'node:util'
+import { mkdirSync, mkdtempSync, readdirSync, rmSync, statSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { afterEach, describe, expect, it, vi } from 'vitest'
+import { planWork, runSolver, schedulerFiles, type SolverRun } from './planCommand.js'
+import { group, machine, NOW, policy, state, type Json } from './fixtures/planState.js'
+
+const context = (s: Json) => ({ ok: true, value: { tab: { state: s, githubApp: false }, policy: { policy, warnings: [] }, agentId: 'lead1', machines: [] } })
+const scoped = (s: Json) => vi.fn(async (payload: Json) => payload.action === 'routeContext' ? context(s) : { error: 'UNEXPECTED' })
+const at = (minutes: number) => new Date(NOW + minutes * 60_000).toISOString()
+
+/** What `python -m scheduler plan` prints for g1 and g2 (tools/scheduler/scheduler/plan.py). */
+const answer = (plan: Json[]): Awaited<ReturnType<SolverRun>> => ({ ok: true, value: { status: 'OPTIMAL', reason: '', makespan: 180, cost: 540, gap: 0, seconds: 0.1, plan,
+ route: { status: 'EVALUATED', makespan: 240, cost: 600, plan: [] } } })
+
+describe('planWork', () => {
+ const rules = [{ projectId: 'p1', rule: { kind: 'minEffort', effort: 'high' }, text: 'At least high.' }]
+ const served = { localModels: [{ grid: 'swarm-g', model: 'deepseek/flash', name: 'DeepSeek', kind: 'api' }] }
+
+ it('gives each open group its machine, engine, model and effort, start order and expected finish, against the route', async () => {
+ const run = vi.fn<SolverRun>(async () => answer([
+ { task: 'g1', machine: 'm1', model: 'codex-default-default', start: 0, end: 60, order: 1 },
+ { task: 'g2', machine: 'm2', model: 'grid:deepseek/flash', start: 60, end: 180, order: 2 }]))
+ const s = state({ rules, machines: [machine('m1', {}, served), machine('m2')] })
+ const out = await planWork({ request: { groups: { g1: { difficulty: 'high', risk: 'low', size: 'medium' } } } }, scoped(s), { run, now: () => NOW, dataDir: '/unused' })
+ expect((run.mock.calls[0]![0].tasks as Json[]).map(t => t.id)).toEqual(['g1', 'g2'])
+ expect(out).toEqual({
+ ok: true, status: 'OPTIMAL', makespanMinutes: 180, cost: 540, route: { makespanMinutes: 240, cost: 600 },
+ plan: [
+ // Codex default leaves the effort to the engine, so it starts at the project's minimum, as the route lifts it.
+ { order: 1, groupId: 'g1', group: 'Group g1', machineId: 'm1', machine: 'm1.local', engine: 'codex', model: 'default', effort: 'high',
+ startsInMinutes: 0, finishesInMinutes: 60, finishAt: at(60) },
+ { order: 2, groupId: 'g2', group: 'Group g2', machineId: 'm2', machine: 'm2.local', engine: 'claude', gridModel: 'deepseek/flash', gridName: 'swarm-g',
+ startsInMinutes: 60, finishesInMinutes: 180, finishAt: at(180) },
+ ],
+ estimates: ['Group g2'], leftOut: [], ignored: [],
+ next: expect.stringContaining('overrideReason "scheduler plan"'),
+ })
+ })
+
+ it('says why machines were left out', async () => {
+ const run = vi.fn<SolverRun>(async () => answer([{ task: 'g1', machine: 'm1', model: 'claude-opus-high', start: 0, end: 60, order: 1 },
+ { task: 'g2', machine: 'm1', model: 'claude-opus-high', start: 60, end: 120, order: 2 }]))
+ const out = await planWork({ request: undefined }, scoped(state({ machines: [machine('m1'), machine('m2', { paused: true })] })), { run, now: () => NOW, dataDir: '/unused' })
+ expect(out.leftOut).toEqual([{ machine: 'm2.local', reason: 'New work is paused on this machine.' }])
+ })
+
+ it('without OR-Tools, says how to install it and that the route works as before', async () => {
+ const run = vi.fn<SolverRun>(async () => ({ error: 'ORTOOLS_MISSING', detail: 'OR-Tools is not installed for python3. Install it with: python3 -m pip install ortools==9.15.6755' }))
+ const out = await planWork({ request: undefined }, scoped(state()), { run, now: () => NOW, dataDir: '/unused' })
+ expect(out).toEqual({ error: 'ORTOOLS_MISSING', detail: 'OR-Tools is not installed for python3. Install it with: python3 -m pip install ortools==9.15.6755 Route each group as usual meanwhile.' })
+ })
+
+ it('reports a plan the scheduler cannot make, and why', async () => {
+ const run = vi.fn<SolverRun>(async () => ({ ok: true, value: { status: 'INFEASIBLE', reason: 'no machine and model meet the floor of: g1', plan: [], route: {} } }))
+ const out = await planWork({ request: undefined }, scoped(state()), { run, now: () => NOW, dataDir: '/unused' })
+ expect(out).toEqual({ error: 'NO_PLAN', detail: 'The scheduler found no plan: no machine and model meet the floor of: g1. Route each group as usual.' })
+ })
+
+ it('plans nothing, without running the solver, when no group is open', async () => {
+ const run = vi.fn<SolverRun>()
+ const out = await planWork({ request: undefined }, scoped(state({ conversations: [group('g1', { archived: true })] })), { run, now: () => NOW, dataDir: '/unused' })
+ expect(out).toEqual({ ok: true, plan: [], note: 'No open groups to plan.' })
+ expect(run).not.toHaveBeenCalled()
+ })
+
+ it('runs the solver on this machine by default, and says when it cannot', async () => {
+ const dataDir = mkdtempSync(join(tmpdir(), 'plan-')), python = join(dataDir, 'no-python3')
+ try {
+ const out = await planWork({ request: undefined }, scoped(state()), { now: () => NOW, dataDir, python })
+ expect(out).toEqual({ error: 'PYTHON_MISSING', detail: expect.stringMatching(/^Python 3 is not installed on this machine.*Route each group as usual meanwhile\.$/) })
+ } finally { rmSync(dataDir, { recursive: true, force: true }) }
+ })
+
+ it('refuses a bad request and passes on a failed read', async () => {
+ const run = vi.fn<SolverRun>()
+ expect(await planWork({ request: { groups: { g1: { difficulty: 'hard' } } } }, scoped(state()), { run, now: () => NOW, dataDir: '/unused' }))
+ .toEqual({ error: 'INVALID_REQUEST', detail: 'Set difficulty of g1 to low, medium or high.' })
+ const failing = vi.fn(async () => ({ error: 'LEAD_REQUIRED', detail: 'Only a Lead plans.' }))
+ expect(await planWork({ request: undefined }, failing, { run, now: () => NOW, dataDir: '/unused' })).toEqual({ error: 'LEAD_REQUIRED', detail: 'Only a Lead plans.' })
+ })
+})
+
+describe('the solver files', () => {
+ it('are the scheduler package, without its tests', () => {
+ const files = schedulerFiles()
+ expect(Object.keys(files)).toEqual(expect.arrayContaining(['__init__.py', '__main__.py', 'plan.py', 'solver.py', 'greedy.py', 'instance.py']))
+ expect(Object.keys(files).every(f => f.endsWith('.py') && !f.startsWith('test'))).toBe(true)
+ })
+})
+
+const instance = { tasks: [{ id: 'g1', title: 'g1', minutes: 60, floor: 1 }], machines: [{ id: 'm1', name: 'm1', slots: 1, engines: ['claude'] }],
+ models: [{ id: 'opus', engine: 'claude', cost: 3, quality: { default: 3 } }], accounts: [] }
+const hasPython = (python: string, code = 'pass') => spawnSync(python, ['-c', code]).status === 0
+// The solve itself needs OR-Tools: SCHEDULER_PYTHON names a Python that has it (tools/scheduler/README.md).
+const solverPython = process.env.SCHEDULER_PYTHON ?? 'python3'
+
+describe('runSolver', () => {
+ const dirs: string[] = []
+ const temp = () => { const d = mkdtempSync(join(tmpdir(), 'plan-')); dirs.push(d); return d }
+ afterEach(() => { for (const d of dirs.splice(0)) rmSync(d, { recursive: true, force: true }) })
+
+ it('says when Python is not installed', async () => {
+ expect(await runSolver(instance, { dataDir: temp(), python: join(temp(), 'no-python3') }))
+ .toEqual({ error: 'PYTHON_MISSING', detail: expect.stringContaining('Python 3 is not installed') })
+ })
+
+ it.skipIf(!hasPython('python3'))('never touches a package another process published, and runs from a whole copy of its own', async () => {
+ const dataDir = temp(), fake = temp()
+ mkdirSync(join(fake, 'ortools'))
+ writeFileSync(join(fake, 'ortools', '__init__.py'), "raise ImportError('No module named ortools')\n")
+ await runSolver(instance, { dataDir, python: 'python3', pythonPath: [fake] })
+ const [version] = readdirSync(join(dataDir, 'scheduler')), root = join(dataDir, 'scheduler', version!), pkg = join(root, 'scheduler')
+ // Another CLI process stopped while writing: the package has its entry point but not the solver.
+ rmSync(join(pkg, 'solver.py'))
+ const before = statSync(root).ino, kept = readdirSync(pkg).sort()
+ // A solver still running from that folder imports one more module after the others have published.
+ const importer = promisify(execFile)('python3', ['-c', 'import time, scheduler; time.sleep(2); import scheduler.instance; print("imported")'], { cwd: root, timeout: 30_000 })
+ // Each publisher waits at the barrier, so all of them find the package half-written at once.
+ const barrier = join(temp(), 'go')
+ const script = `
+ import { existsSync } from 'node:fs';
+ import { runSolver } from './src/superTabs/planCommand.ts';
+ while (!existsSync(process.argv[1])) await new Promise(r => setTimeout(r, 5));
+ const instance = { tasks: [{ id: 'g1', minutes: 60 }], machines: [{ id: 'm1', slots: 1, engines: ['claude'] }], models: [{ id: 'opus', engine: 'claude', cost: 3, quality: { default: 3 } }] };
+ console.log(JSON.stringify(await runSolver(instance, { dataDir: process.argv[2], python: 'python3', pythonPath: [process.argv[3]] })));
+ `
+ const run = promisify(execFile)
+ const children = [1, 2, 3, 4, 5, 6].map(() => run(process.execPath, ['--import', 'tsx', '--input-type=module', '-e', script, barrier, dataDir, fake], { timeout: 30_000 }))
+ await new Promise(r => setTimeout(r, 1000))
+ writeFileSync(barrier, '')
+ const answers = (await Promise.all(children)).map(c => JSON.parse(c.stdout.trim()))
+ // Every publisher ran a whole package: each reached the missing OR-Tools, none failed partway through its imports.
+ expect(answers.map(a => a.error)).toEqual(Array(6).fill('ORTOOLS_MISSING'))
+ expect((await importer).stdout.trim()).toBe('imported')
+ // The folder the running solver uses is the same one, untouched, and no private copy is left behind.
+ expect(statSync(root).ino).toBe(before)
+ expect(readdirSync(pkg).sort()).toEqual(kept)
+ expect(readdirSync(join(dataDir, 'scheduler'))).toEqual([version])
+ }, 60_000)
+
+ it('says when the solver stops without a plan', async () => {
+ // A program that exits 1 and prints nothing stands in for a solver that crashed.
+ expect(await runSolver(instance, { dataDir: temp(), python: process.platform === 'win32' ? 'cmd' : 'false' }))
+ .toEqual({ error: 'SOLVER_FAILED', detail: expect.stringContaining('The scheduler stopped (exit 1)') })
+ })
+
+ it.skipIf(!hasPython('python3'))('says when OR-Tools is not installed', async () => {
+ const fake = temp()
+ mkdirSync(join(fake, 'ortools'))
+ writeFileSync(join(fake, 'ortools', '__init__.py'), "raise ImportError('No module named ortools')\n")
+ const out = await runSolver(instance, { dataDir: temp(), python: 'python3', pythonPath: [fake] })
+ expect(out).toEqual({ error: 'ORTOOLS_MISSING', detail: expect.stringContaining('pip install ortools') })
+ })
+
+ it.skipIf(!hasPython(solverPython, 'import ortools'))('solves with the files written to the data folder', async () => {
+ const out = await runSolver(instance, { dataDir: temp(), python: solverPython })
+ expect(out).toMatchObject({ ok: true, value: { status: 'OPTIMAL', makespan: 60, plan: [{ task: 'g1', machine: 'm1', model: 'opus', start: 0, end: 60, order: 1 }] } })
+ })
+})
diff --git a/cli/src/superTabs/planCommand.ts b/cli/src/superTabs/planCommand.ts
new file mode 100644
index 000000000..df1a0985f
--- /dev/null
+++ b/cli/src/superTabs/planCommand.ts
@@ -0,0 +1,114 @@
+/** `harness super-tab plan [JSON]`: the best plan for all of a Lead's open work, from the scheduler (tools/scheduler,
+ * docs/plans/2026-10-27-swarm-scheduler.md). Advisory only: it records nothing, and the route stays the source of every
+ * decision; the Lead routes each group and passes the plan's pick as the override. The solver is Python with OR-Tools on the
+ * Lead's machine; without either the command says how to install it, and the route works as before. */
+import { spawn } from 'node:child_process'
+import { createHash, randomUUID } from 'node:crypto'
+import { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs'
+import { delimiter, join } from 'node:path'
+import { fileURLToPath } from 'node:url'
+import { parsePlanRequest, planSetup } from './planInput.js'
+import type { Policy } from './route.js'
+import type { ScopedRequest } from './start.js'
+import { object } from './wire.js'
+
+type Json = Record<string, unknown>
+export type SolverRun = (instance: Json) => Promise<{ ok: true; value: Json } | { error: string; detail: string }>
+
+declare const __SCHEDULER_FILES__: Record<string, string> | undefined
+/** How long the solver may think: the brief's limit for 30 tasks on 8 machines with 6 models (it takes about a quarter second). */
+const TIME_LIMIT_SECONDS = 10
+const INSTALL = 'Install Python 3 (python.org, or brew install python), then: python3 -m pip install ortools==9.15.6755.'
+const list = (value: unknown) => Array.isArray(value) ? value.map(object) : []
+
+/** The scheduler package's files. The release bundle carries them inside cli.js (build-bundle.mjs `define`), as the installed
+ * CLI has nothing beside it to read; a dev checkout and the tests read tools/scheduler/scheduler itself (src/superTabs/ and
+ * dist/superTabs/ are both three levels below the repository). */
+export function schedulerFiles(): Record<string, string> {
+ if (typeof __SCHEDULER_FILES__ === 'object' && __SCHEDULER_FILES__) return __SCHEDULER_FILES__
+ const dir = fileURLToPath(new URL('../../../tools/scheduler/scheduler/', import.meta.url))
+ return Object.fromEntries(readdirSync(dir).filter(f => f.endsWith('.py')).sort().map(f => [f, readFileSync(join(dir, f), 'utf8')]))
+}
+
+const whole = (dir: string, files: Record<string, string>) => Object.keys(files).every(name => existsSync(join(dir, 'scheduler', name)))
+
+/** The folder to run the package from, and whether it is this process's own, to remove after the run. Two Leads' CLIs may plan
+ * at once, and another's solver may be importing from the published folder at any moment, so a published folder is never
+ * deleted or replaced (review of #1764): a whole copy is written to a folder of this process's own and renamed into place
+ * only where none is published yet. Should the published one be missing a file (a process that stopped while writing before
+ * publication was atomic, or a disk that lost it), this run uses its own whole copy instead. */
+function packageFolder(root: string, files: Record<string, string>): { dir: string; own: boolean } {
+ if (whole(root, files)) return { dir: root, own: false }
+ const draft = `${root}.${process.pid}.${randomUUID()}`
+ mkdirSync(join(draft, 'scheduler'), { recursive: true })
+ for (const [name, text] of Object.entries(files)) writeFileSync(join(draft, 'scheduler', name), text)
+ if (!existsSync(root)) {
+ try { renameSync(draft, root); return { dir: root, own: false } } catch { /* Another process published first. */ }
+ }
+ if (whole(root, files)) { rmSync(draft, { recursive: true, force: true }); return { dir: root, own: false } }
+ return { dir: draft, own: true }
+}
+
+/** Runs `python -m scheduler plan` on [instance], with the package written once per version under the data folder. */
+export async function runSolver(instance: Json, options: { dataDir: string; python?: string; pythonPath?: string[] }): ReturnType<SolverRun> {
+ const files = schedulerFiles()
+ const version = createHash('sha256').update(JSON.stringify(files)).digest('hex').slice(0, 16)
+ const { dir: root, own } = packageFolder(join(options.dataDir, 'scheduler', version), files)
+ const python = options.python ?? 'python3'
+ const answer = await new Promise<Awaited<ReturnType<SolverRun>>>(resolve => {
+ const child = spawn(python, ['-m', 'scheduler', 'plan', '--time-limit', String(TIME_LIMIT_SECONDS)], {
+ cwd: root, env: { ...process.env, PYTHONPATH: [...(options.pythonPath ?? []), root].join(delimiter) }, stdio: ['pipe', 'pipe', 'pipe'],
+ })
+ let out = '', err = ''
+ child.stdout.on('data', chunk => { out += chunk })
+ child.stderr.on('data', chunk => { err += chunk })
+ child.on('error', (error: NodeJS.ErrnoException) => resolve(error.code === 'ENOENT'
+ ? { error: 'PYTHON_MISSING', detail: `Python 3 is not installed on this machine (${python}). ${INSTALL}` }
+ : { error: 'SOLVER_FAILED', detail: error.message }))
+ child.on('close', code => {
+ let value: Json | null = null
+ try { value = object(JSON.parse(out)) } catch { /* Not JSON: said below with the solver's own words. */ }
+ if (value && typeof value.error === 'string') resolve({ error: value.error, detail: String(value.detail ?? '') })
+ else if (code === 0 && value) resolve({ ok: true, value })
+ else resolve({ error: 'SOLVER_FAILED', detail: `The scheduler stopped (exit ${code}): ${err.trim().split('\n').slice(-3).join(' ')}` })
+ })
+ child.stdin.end(JSON.stringify(instance))
+ })
+ if (own) rmSync(root, { recursive: true, force: true })
+ return answer
+}
+
+export async function planWork(input: { request: unknown }, scoped: ScopedRequest, deps: { run?: SolverRun; now?: () => number; dataDir: string; python?: string }): Promise<Json> {
+ const request = parsePlanRequest(input.request)
+ if (typeof request === 'string') return { error: 'INVALID_REQUEST', detail: request }
+ const context = await scoped({ action: 'routeContext' })
+ if (context.error || context.ok !== true) return context
+ const value = object(context.value), tab = object(value.tab)
+ const now = (deps.now ?? Date.now)()
+ const setup = planSetup({ state: object(tab.state), policy: object(value.policy).policy as Policy, leadId: String(value.agentId),
+ request, githubApp: tab.githubApp === true, now })
+ if (!setup.instance.tasks.length) return { ok: true, plan: [], note: 'No open groups to plan.' }
+ const solved = await (deps.run ?? (instance => runSolver(instance, { dataDir: deps.dataDir, python: deps.python })))(setup.instance)
+ if ('error' in solved) return { error: solved.error, detail: `${solved.detail} Route each group as usual meanwhile.` }
+ const answer = solved.value
+ if (answer.status !== 'OPTIMAL' && answer.status !== 'FEASIBLE') {
+ return { error: 'NO_PLAN', detail: `The scheduler found no plan: ${String(answer.reason || answer.status)}. Route each group as usual.` }
+ }
+ const route = object(answer.route)
+ const plan = list(answer.plan).map(row => {
+ const group = String(row.task), machineId = String(row.machine), modelId = String(row.model), pick = setup.rows[modelId]!
+ // A model on the grid is started by its gridModel and gridName, never a model or effort (route.ts).
+ const runs = pick.gridModel ? { engine: pick.engine, gridModel: pick.gridModel, gridName: pick.gridName }
+ : { engine: pick.engine, model: pick.model, effort: setup.effortFor(group, modelId) }
+ return { order: Number(row.order), groupId: group, group: setup.titles[group], machineId, machine: setup.machineNames[machineId], ...runs,
+ startsInMinutes: Number(row.start), finishesInMinutes: Number(row.end), finishAt: new Date(now + Number(row.end) * 60_000).toISOString() }
+ })
+ return {
+ ok: true, status: answer.status, makespanMinutes: answer.makespan, cost: answer.cost,
+ route: { makespanMinutes: route.makespan, cost: route.cost }, plan,
+ estimates: setup.estimates.map(id => setup.titles[id]), leftOut: setup.leftOut, ignored: setup.ignored,
+ next: 'Follow the plan in order. For each group: route it as usual, then start (or assign) the plan\'s pick with the route\'s routeDecisionId '
+ + 'and overrideReason "scheduler plan" when it differs from the route\'s. Groups marked as estimates were planned at medium; '
+ + 'pass {"groups":{"GROUP":{"difficulty":…,"risk":…,"size":…}}} to plan them as assessed.',
+ }
+}
diff --git a/cli/src/superTabs/planInput.spec.ts b/cli/src/superTabs/planInput.spec.ts
new file mode 100644
index 000000000..8ca4cf94a
--- /dev/null
+++ b/cli/src/superTabs/planInput.spec.ts
@@ -0,0 +1,139 @@
+import { describe, expect, it } from 'vitest'
+import { parsePlanRequest, planSetup } from './planInput.js'
+import { group, machine, NOW, policy, state, type Json } from './fixtures/planState.js'
+
+const setup = (s: Json, request = {}) => planSetup({ state: s, policy, leadId: 'lead1', request, githubApp: false, now: NOW })
+const taskOf = (s: ReturnType<typeof setup>, id: string) => (s.instance.tasks as Json[]).find(t => t.id === id)!
+
+describe('parsePlanRequest', () => {
+ it('takes no input as no assessments', () => expect(parsePlanRequest(undefined)).toEqual({}))
+ it('reads each group\'s assessment, kind and the groups it waits for', () => {
+ expect(parsePlanRequest({ groups: { g1: { difficulty: 'high', risk: 'low', size: 'large', kind: 'ui', after: ['g2'] } } }))
+ .toEqual({ g1: { difficulty: 'high', risk: 'low', size: 'large', kind: 'ui', after: ['g2'] } })
+ })
+ it('refuses a bad level, size, kind or group id', () => {
+ expect(parsePlanRequest({ groups: { g1: { difficulty: 'hard', risk: 'low', size: 'small' } } })).toMatch(/difficulty/)
+ expect(parsePlanRequest({ groups: { g1: { difficulty: 'low', risk: 'low', size: 'huge' } } })).toMatch(/size/)
+ expect(parsePlanRequest({ groups: { g1: { difficulty: 'low', risk: 'low', size: 'small', kind: 'Two Words' } } })).toMatch(/kind/)
+ expect(parsePlanRequest({ groups: { 'not an id': { difficulty: 'low', risk: 'low', size: 'small' } } })).toMatch(/group/)
+ expect(parsePlanRequest({ groups: { g1: { difficulty: 'low', risk: 'low', size: 'small', after: ['bad id'] } } })).toMatch(/after/)
+ expect(parsePlanRequest([])).toMatch(/groups/)
+ })
+})
+
+describe('planSetup', () => {
+ it('plans the Lead\'s open groups: defined and not archived, never assigned or with their agent lost', () => {
+ const work = (status: string) => ({ assignment: { id: status, agentId: 'x', status } })
+ const s = setup(state({ conversations: [{ id: 'lead', leadId: 'lead1', title: 'Lead' }, group('g1'),
+ group('g2', work('working')), group('g3', { archived: true }), group('g4', { task: null }), group('g5', { leadId: 'someone else' }),
+ group('g6', work('done')), group('g7', work('lost')), group('g8', work('cancelled')), group('g9', work('review'))] }))
+ expect((s.instance.tasks as Json[]).map(t => t.id)).toEqual(['g1', 'g7'])
+ })
+
+ it('takes the Lead\'s assessment, and marks a group without one as an estimate at medium', () => {
+ const s = setup(state(), { g1: { difficulty: 'high', risk: 'high', size: 'large', kind: 'backend' } })
+ expect(taskOf(s, 'g1')).toMatchObject({ minutes: 180, floor: 3, kind: 'backend', difficulty: 'high', spend: { '5-hour': 50, weekly: 8 } })
+ expect(taskOf(s, 'g2')).toMatchObject({ minutes: 60, floor: 2, kind: 'default', difficulty: 'medium' })
+ expect(s.estimates).toEqual(['g2'])
+ })
+
+ it('keeps each task to the machines the owner\'s machines rule leaves for its project', () => {
+ const rules = [{ projectId: 'p1', rule: { kind: 'machines', machineIds: ['m2'] }, text: 'Only m2.' },
+ { projectId: 'p2', rule: { kind: 'machines', machineIds: ['m1'] }, text: 'Other project.' }]
+ expect(taskOf(setup(state({ rules })), 'g1').machines).toEqual(['m2'])
+ })
+
+ // A Mac (m1, its owner's) and its Harness Team account (m1-team) are one machine (docs/plans/2026-10-24-swarm-team-account.md).
+ const mac = () => [machine('m1'), machine('m1-team', { hostMachineId: 'm1' }), machine('m2')]
+ const projects = [{ id: 'p1', ownerId: 'owner', repository: { machineId: 'm1', cwd: '/repo', repositoryUrl: 'https://github.com/o/r' } },
+ { id: 'p2', ownerId: 'mate', repository: { machineId: 'm2', cwd: '/repo', repositoryUrl: 'https://github.com/o/r2' } }]
+
+ it('lets a machines rule naming a Mac allow its Harness Team account too, as the route does', () => {
+ // A teammate's project runs in the team account, which the rule allows only through the Mac it names.
+ const rules = [{ projectId: 'p2', rule: { kind: 'machines', machineIds: ['m1'] }, text: 'Only m1.' }]
+ const s = setup(state({ rules, projects, machines: mac(), conversations: [group('t1', { projectId: 'p2' })] }))
+ expect(taskOf(s, 't1').machines).toEqual(['m1-team'])
+ })
+
+ it('offers a Mac\'s own projects on the Mac and a teammate\'s in its team account, never both', () => {
+ const s = setup(state({ projects, machines: mac(), conversations: [group('o1', { projectId: 'p1' }), group('t1', { projectId: 'p2' })] }))
+ expect(taskOf(s, 'o1').machines).toEqual(['m1', 'm2'])
+ expect(taskOf(s, 't1').machines).toEqual(['m1-team', 'm2'])
+ })
+
+ it('has a Mac and its team account share the Mac\'s slots', () => {
+ const s = setup(state({ projects, machines: mac() }))
+ expect((s.instance.machines as Json[]).find(m => m.id === 'm1-team')).toMatchObject({ pool: 'm1' })
+ expect((s.instance.machines as Json[]).find(m => m.id === 'm1')).not.toHaveProperty('pool')
+ })
+
+ it('leaves out a forbidden model and a row below the minimum effort, lifting a row that leaves the effort to the engine', () => {
+ const rules = [{ projectId: 'p1', rule: { kind: 'forbidModel', model: 'opus' }, text: 'No Opus.' },
+ { projectId: 'p1', rule: { kind: 'minEffort', effort: 'high' }, text: 'At least high.' }]
+ const s = setup(state({ rules }))
+ // Opus is forbidden and Sonnet medium is below high; Codex default is lifted to high and stays.
+ expect(taskOf(s, 'g1').models).toEqual(['codex-default-default'])
+ 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', () => {
+ 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'] })
+ })
+
+ it('adds the groups the Lead says a group waits for, and lists one that is not open', () => {
+ const s = setup(state(), { g2: { difficulty: 'low', risk: 'low', size: 'small', after: ['g1', 'gone'] } })
+ expect(taskOf(s, 'g2').deps).toEqual(['g1'])
+ expect(s.ignored).toEqual(['gone'])
+ })
+
+ it('leaves out machines that cannot take a new agent now, saying why', () => {
+ const s = setup(state({ machines: [machine('m1'), machine('old', {}, { receivedAt: NOW - 60_000 }), machine('paused', { paused: true }),
+ machine('full', { availableSlots: 0 }), machine('win', {}, { resources: { memoryTotalBytes: 68_719_476_736, memoryUsedBytes: 1, projectDiskFreeBytes: 132_155_797_504, os: 'Windows' } }),
+ machine('tight', {}, { resources: { memoryTotalBytes: 8_000_000_000, memoryUsedBytes: 7_500_000_000, projectDiskFreeBytes: 132_155_797_504, os: 'macOS' } })] }))
+ expect((s.instance.machines as Json[]).map(m => m.id)).toEqual(['m1'])
+ expect(Object.fromEntries(s.leftOut.map(l => [l.machine, l.reason]))).toEqual({
+ 'old.local': 'Machine is offline or unreachable.', 'paused.local': 'New work is paused on this machine.',
+ 'full.local': 'This machine has no available agent slots.', 'win.local': 'Swarm agents do not run on Windows yet.',
+ 'tight.local': 'Insufficient measured free memory.' })
+ })
+
+ it('gives each machine its free slots and only the engines that can start work', () => {
+ const s = setup(state({ machines: [machine('m1', { availableSlots: 3 }, {
+ readiness: { engines: [{ engine: 'codex', installed: true, signedIn: false }] } }), machine('m2', {}, {
+ quotas: [{ engine: 'claude', known: true, windows: [{ name: 'weekly', usedPercent: 100, resetsAt: '2026-11-01T19:00:00+00:00' }] }] })] }))
+ expect(s.instance.machines).toEqual([{ id: 'm1', name: 'm1.local', slots: 3, engines: ['claude'] }, { id: 'm2', name: 'm2.local', slots: 2, engines: ['codex'] }])
+ })
+
+ it('reads each account\'s windows with minutes to their reset, sharing an account two machines report', () => {
+ const shared = { engine: 'codex', known: true, account: 'acct-x', windows: [{ name: 'weekly', usedPercent: 40, resetsAt: 1793592000 }] }
+ const s = setup(state({ machines: [machine('m1', {}, { quotas: [shared] }), machine('m2', {}, { quotas: [shared,
+ { engine: 'claude', known: true, windows: [{ name: '5-hour', usedPercent: 20, resetsAt: '2026-10-27T00:30:00+00:00' }, { name: 'weekly', usedPercent: 30, resetsAt: '2026-11-01T19:00:00+00:00' }] }] })] }))
+ // 1793592000 s is 2026-11-02T04:00Z, 8820 minutes on; 2026-11-01T19:00Z is 8280. The claude 5-hour reset has passed, so it is full again.
+ expect(s.instance.accounts).toEqual([
+ { id: 'acct-x', members: [['m1', 'codex'], ['m2', 'codex']], reserve: 10, windows: [{ name: 'weekly', left: 60, resets_in: 8820 }] },
+ { id: 'm2:claude', members: [['m2', 'claude']], reserve: 10, windows: [{ name: '5-hour', left: 100, resets_in: null }, { name: 'weekly', left: 70, resets_in: 8280 }] },
+ ])
+ })
+
+ it('offers a model served on the grid with the Builders it still takes, but never for a review', () => {
+ const served = { localModels: [{ grid: 'swarm-g', model: 'deepseek/flash', name: 'DeepSeek · OpenRouter', kind: 'api' }] }
+ const s = setup(state({ machines: [machine('m1', {}, served), machine('m2')],
+ starts: [{ request: { gridModel: 'deepseek/flash', gridName: 'swarm-g' }, harnessId: null, error: null }],
+ conversations: [group('g1'), group('r1', { reviewOf: 'g1' })] }))
+ expect((s.instance.models as Json[]).find(m => m.id === 'grid:deepseek/flash')).toEqual({ id: 'grid:deepseek/flash', engine: 'claude', cost: 1,
+ quality: { default: 1 }, concurrency: 3, subscription: false, remote: true, family: 'deepseek/flash', label: 'Claude on DeepSeek · OpenRouter (API)' })
+ expect(taskOf(s, 'g1').models).toContain('grid:deepseek/flash')
+ expect(taskOf(s, 'r1').models).not.toContain('grid:deepseek/flash')
+ expect(s.rows['grid:deepseek/flash']).toEqual({ engine: 'claude', model: 'default', effort: 'default', gridModel: 'deepseek/flash', gridName: 'swarm-g' })
+ })
+
+ it('offers a model shared from another grid only on the machines it was shared with', () => {
+ const shared = { localModels: [{ grid: 'other-grid', model: 'qwen/coder', name: 'Qwen' }] }
+ const s = setup(state({ machines: [machine('m1', {}, shared), machine('m2')] }))
+ expect((s.instance.models as Json[]).find(m => m.id === 'grid:qwen/coder')).toMatchObject({ machines: ['m1'], concurrency: 1, remote: true, label: 'Claude on Qwen (shared)' })
+ })
+})
diff --git a/cli/src/superTabs/planInput.ts b/cli/src/superTabs/planInput.ts
new file mode 100644
index 000000000..44ebc1d6f
--- /dev/null
+++ b/cli/src/superTabs/planInput.ts
@@ -0,0 +1,213 @@
+/** `harness super-tab plan`: the scheduler's input from the live Swarm (tools/scheduler, docs/plans/2026-10-27-swarm-scheduler.md).
+ * Pure: the Lead's open groups become tasks, the machines that can take a new agent now become machines, the routing policy's
+ * rows and the models served on the grid become models, and each machine's quota readings become accounts. The owner's hard
+ * rules are applied per task, as each binds only its own project's groups, with the same checks the route makes
+ * (routeCommand.ts), so the plan never offers what the route would refuse. Only new agents are planned, not idle members. */
+import { requiredToolReason, startRequirements } from './capacity.js'
+import { API_BUILDERS, breaks, floorFor, KIND_WORD, liftEffort, quotaOf2, SIZES, type Assessment, type Level, type Policy, type Size, type SwarmRule } from './route.js'
+import { LOCAL_FRESH_MS, OFFLINE, servedModels, STALLED, stalled, takesBuilder, unreadyPool } from './routeCommand.js'
+import { identifier, object } from './wire.js'
+
+type Json = Record<string, unknown>
+export interface GroupAssessment { difficulty: Level; risk: Level; size: Size; kind?: string; after?: string[] }
+/** The Lead's assessments, by group id. */
+export type PlanRequest = Record<string, GroupAssessment>
+/** What starts a plan's pick: a policy row, or a model served on the grid (started with gridModel and gridName). */
+export interface ModelRow { engine: 'claude' | 'codex'; model: string; effort: string; gridModel?: string; gridName?: string }
+export interface PlanSetup {
+ instance: { tasks: Json[]; machines: Json[]; models: Json[]; accounts: Json[] }
+ rows: Record<string, ModelRow>
+ titles: Record<string, string>
+ machineNames: Record<string, string>
+ /** Groups planned at the default assessment, which the Lead did not give. */
+ estimates: string[]
+ /** Groups the Lead named that are not open. */
+ ignored: string[]
+ leftOut: Array<{ machine: string; reason: string }>
+ /** The effort the pick starts at for that group: the row's own, or its project's minimum when the row leaves it to the engine. */
+ effortFor: (group: string, row: string) => string
+}
+
+const LEVELS: Level[] = ['low', 'medium', 'high']
+const ENGINES = ['claude', 'codex'] as const
+const ENGINE_WORD = { claude: 'Claude', codex: 'Codex' } as const
+const WINDOWS = ['5-hour', 'weekly']
+/** A group the Lead did not assess is planned as the route takes a Lead's task with no size: medium. */
+const DEFAULT: GroupAssessment = { difficulty: 'medium', risk: 'medium', size: 'medium' }
+const list = (value: unknown) => Array.isArray(value) ? value.map(object) : []
+const finite = (value: unknown): value is number => typeof value === 'number' && Number.isFinite(value)
+
+/** What the route says of a machine that cannot hold a new agent (routeCommand.ts probeMachine), in its words. */
+function shortfalls(observed: Json, needs: ReturnType<typeof startRequirements>): string[] {
+ const resources = object(observed.resources), tools = object(observed.tools)
+ return [
+ ...(!finite(resources.projectDiskFreeBytes) || resources.projectDiskFreeBytes < needs.diskBytes ? ['The project has insufficient measured free disk.'] : []),
+ ...(!finite(resources.memoryTotalBytes) || !finite(resources.memoryUsedBytes) || resources.memoryTotalBytes - resources.memoryUsedBytes < needs.memoryBytes ? ['Insufficient measured free memory.'] : []),
+ ...needs.tools.map(t => requiredToolReason(t, tools[t], object(observed.toolProbeErrors)[t])).filter((reason): reason is string => reason !== null),
+ ]
+}
+
+export function parsePlanRequest(value: unknown): PlanRequest | string {
+ if (value === undefined || value === null) return {}
+ const groups = object(object(value).groups)
+ if (Array.isArray(value) || typeof value !== 'object') return 'Give {"groups":{"GROUP":{"difficulty":"…","risk":"…","size":"…"}}}.'
+ const out: PlanRequest = {}
+ for (const [id, raw] of Object.entries(groups)) {
+ const a = object(raw)
+ if (!identifier(id)) return `"${id}" is not a group id.`
+ if (!LEVELS.includes(a.difficulty as Level)) return `Set difficulty of ${id} to low, medium or high.`
+ if (!LEVELS.includes(a.risk as Level)) return `Set risk of ${id} to low, medium or high.`
+ if (!Object.hasOwn(SIZES, String(a.size))) return `Set size of ${id} to small, medium or large.`
+ if (a.kind !== undefined && (typeof a.kind !== 'string' || !/^[a-z][a-z0-9-]{0,39}$/.test(a.kind))) return `Set kind of ${id} to one lowercase word, such as ui or docs.`
+ if (a.after !== undefined && (!Array.isArray(a.after) || !a.after.every(identifier))) return `Set after of ${id} to a list of group ids.`
+ out[id] = { difficulty: a.difficulty as Level, risk: a.risk as Level, size: a.size as Size, ...(a.kind ? { kind: a.kind as string } : {}),
+ ...(a.after ? { after: a.after as 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)
+ // Open work: a defined group no one has been given yet, or whose agent was lost, which the Lead hands on. Finished, cancelled
+ // and stopped work is not planned again, nor work still running or in review.
+ const waiting = (assignment: unknown) => { const a = object(assignment); return !a.id || a.status === 'lost' }
+ const open = conversations.filter(c => c.leadId === leadId && c.id !== 'lead' && c.archived !== true && c.task && waiting(c.assignment))
+ const openIds = new Set(open.map(c => String(c.id)))
+ // Rules bind only their own project's groups; a Mac's Harness Team account is that Mac, so a machines rule naming the Mac
+ // allows it too (routeTask).
+ const macOf = new Map(list(state.machines).filter(m => typeof m.hostMachineId === 'string').map(m => [String(m.machineId), String(m.hostMachineId)]))
+ const rulesOf = (projectId: string) => (list(state.rules).filter(r => r.rule && typeof r.text === 'string' && (r.projectId === undefined || r.projectId === projectId)) as unknown as SwarmRule[])
+ .map(r => r.rule.kind !== 'machines' ? r : { ...r, rule: { ...r.rule,
+ machineIds: [...r.rule.machineIds, ...[...macOf].filter(([, mac]) => r.rule.kind === 'machines' && r.rule.machineIds.includes(mac)).map(([team]) => team)] } })
+ const projectOf = (c: Json) => String(c.projectId ?? 'lead')
+
+ // Machines: those that can take a new agent now, for any project, with the engines that can start one.
+ const leftOut: PlanSetup['leftOut'] = []
+ const machines: Json[] = [], machineNames: Record<string, string> = {}, pools = new Map<string, Json>()
+ const needs = startRequirements({ tools: [], devices: [] })
+ for (const pool of list(state.machines)) {
+ const id = String(pool.machineId), name = String(pool.name ?? id), observed = object(pool.observation)
+ const quotas = list(observed.quotas)
+ const unready = unreadyPool(pool, undefined, '', false, githubApp, null)
+ const reasons = [
+ ...(!finite(observed.receivedAt) || now - observed.receivedAt >= LOCAL_FRESH_MS ? [OFFLINE] : []),
+ ...(pool.paused ? ['New work is paused on this machine.'] : []),
+ ...(pool.availableSlots === 0 ? ['This machine has no available agent slots.'] : []),
+ ...unready.all,
+ ...shortfalls(observed, needs),
+ ...(stalled(list(state.starts), id) ? [STALLED] : []),
+ ]
+ // An engine that is not ready, or whose account has a window used up, starts nothing (the route refuses both).
+ const exhausted = (engine: string) => {
+ const q = quotas.find(q => q.engine === engine)
+ return !!q && quotaOf2({ known: q.known === true, windows: list(q.windows).filter(w => finite(w.usedPercent)).map(w => ({ usedPercent: w.usedPercent as number, resetsAt: w.resetsAt })) }).leftPercent === 0
+ }
+ const listed = Array.isArray(pool.engines) ? pool.engines : []
+ const engines = ENGINES.filter(e => listed.includes(e) && !unready.engines[e] && !exhausted(e))
+ if (!reasons.length && !engines.length) reasons.push('No engine on this machine can start a new agent.')
+ if (reasons.length) { leftOut.push({ machine: name, reason: reasons[0]! }); continue }
+ machines.push({ id, name, slots: finite(pool.availableSlots) ? pool.availableSlots : Number(pool.maxAgents), engines })
+ machineNames[id] = name
+ pools.set(id, pool)
+ }
+
+ // A Mac's Harness Team account runs on the Mac, so the two share the Mac's slots (backend machines.ts machineSlots).
+ for (const m of machines) if (macOf.has(String(m.id)) && pools.has(macOf.get(String(m.id))!)) m.pool = macOf.get(String(m.id))
+
+ // Models: the policy's enabled rows, and each model served on the grid that still takes a Builder (never for a review).
+ const rows: Record<string, ModelRow> = {}, models: Json[] = []
+ for (const m of policy.models) {
+ if (!m.enabled || !ENGINES.includes(m.engine)) continue
+ const id = `${m.engine}-${m.model}-${m.effort}`
+ rows[id] = { engine: m.engine, model: m.model, effort: m.effort }
+ models.push({ id, engine: m.engine, cost: m.cost, quality: { default: m.quality }, label: `${ENGINE_WORD[m.engine]} ${m.model} ${m.effort}` })
+ }
+ const addOn = object(state.localModels)
+ const served = addOn.enabled === true && typeof addOn.grid === 'string' && policy.localModels?.enabled !== false
+ ? [...servedModels(state, addOn.grid, now).values()].filter(takesBuilder) : []
+ const gridRows = new Set<string>()
+ for (const s of served) {
+ const id = `grid:${s.model}`
+ if (rows[id]) continue
+ gridRows.add(id)
+ rows[id] = { engine: 'claude', model: 'default', effort: 'default', gridModel: s.model, gridName: s.grid }
+ // A Claude Code Builder drives it through the grid relay; an API answers four at once, a local engine one.
+ models.push({ id, engine: 'claude', cost: 1, quality: { default: policy.localModels?.quality ?? 1 },
+ 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> = {}
+ const tasks = open.map(c => {
+ const id = String(c.id), given = request[id], a = given ?? DEFAULT, projectId = projectOf(c)
+ if (!given) estimates.push(id)
+ titles[id] = String(c.title ?? id)
+ const rules = rulesOf(projectId), project = list(state.projects).find(p => p.id === projectId)
+ const review = typeof c.reviewOf === 'string'
+ const build = review ? conversations.find(b => b.id === c.reviewOf) : undefined
+ const buildOpen = !!build && openIds.has(String(build.id))
+ // A group it waits for that has finished is already done; one that is not in the tab at all is listed back.
+ 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.
+ const folded = new Set([...macOf].flatMap(([team, mac]) => {
+ const teamPool = list(state.machines).find(m => m.machineId === team)
+ return teamPool && list(state.machines).some(m => m.machineId === mac) ? [projectOwner === teamPool.contributorId ? team : mac] : []
+ }))
+ const allowed = [...pools].filter(([machineId, pool]) => {
+ const repository = object(project?.repository)
+ const teamWork = object(pool.teamWork)
+ const unready = unreadyPool(pool, project, projectId, !review, githubApp, projectOwner)
+ return !folded.has(machineId) && !unready.all.length && !unready.push
+ && !(teamWork.allowed === false && teamWork.code !== 'MACHINE_OFFLINE' && pool.contributorId !== projectOwner)
+ && !(pool.scope !== 'swarm' && projectId !== 'lead')
+ && !(pool.scope === 'swarm' && repository.machineId !== machineId && typeof repository.repositoryUrl !== 'string')
+ && !breaks(rules.filter(r => r.rule.kind === 'machines'), { machineId, engine: '', model: '', effort: '' })
+ }).map(([machineId]) => machineId)
+ const modelRules = rules.filter(r => r.rule.kind !== 'machines')
+ const allowedModels = Object.entries(rows).filter(([rowId, row]) => !(review && gridRows.has(rowId))
+ && !breaks(modelRules, { machineId: '', engine: row.engine, model: row.model, effort: liftEffort(rules, row.engine, row.effort) })).map(([rowId]) => rowId)
+ 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 }
+ })
+
+ // Accounts: each machine's quota readings, shared where two machines report one account (route.ts accountOf).
+ const accounts = new Map<string, Json>()
+ for (const [machineId, pool] of pools) {
+ for (const q of list(object(pool.observation).quotas)) {
+ if (!ENGINES.includes(q.engine as 'claude') || q.known !== true) continue
+ const quota = quotaOf2({ known: true, account: typeof q.account === 'string' ? q.account : null,
+ windows: list(q.windows).filter(w => finite(w.usedPercent)).map(w => ({ usedPercent: w.usedPercent as number, resetsAt: w.resetsAt, name: typeof w.name === 'string' ? w.name : undefined })) })
+ if (quota.metered || !quota.windows) continue
+ const key = quota.account ?? `${machineId}:${String(q.engine)}`
+ // A window whose reset has passed since it was read has refilled.
+ const windows = quota.windows.filter(w => WINDOWS.includes(String(w.name))).map(w => w.resetsAt !== null && w.resetsAt <= now
+ ? { name: w.name, left: 100, resets_in: null } : { name: w.name, left: w.leftPercent, resets_in: w.resetsAt === null ? null : Math.round((w.resetsAt - now) / 60_000) })
+ const account = accounts.get(key) ?? { id: key, members: [] as string[][], reserve: policy.quotaReserve, windows }
+ ;(account.members as string[][]).push([machineId, String(q.engine)])
+ accounts.set(key, account)
+ }
+ }
+
+ const byGroup = new Map(open.map(c => [String(c.id), rulesOf(projectOf(c))]))
+ return {
+ instance: { tasks, machines, models, accounts: [...accounts.values()] }, rows, titles, machineNames, estimates, ignored, leftOut,
+ effortFor: (group, row) => liftEffort(byGroup.get(group) ?? [], rows[row]!.engine, rows[row]!.effort),
+ }
+}
diff --git a/cli/src/superTabs/route.ts b/cli/src/superTabs/route.ts
index 2e13fb36f..dcecca03e 100644
--- a/cli/src/superTabs/route.ts
+++ b/cli/src/superTabs/route.ts
@@ -61,12 +61,14 @@ export interface Fit { status: 'fits' | 'unknown' | 'short'; coverage: number |
export interface Commitment { account: string; spend: Partial<Record<Window, number>>; size: Size; createdAt: number }
export interface Shown extends Probe { id: string; title: string; label: string; fit: Fit }
/** `short` is set when no candidate is expected to cover the task, to tell the Lead. */
-export interface Choice { shown: Shown[]; excluded: Array<{ title: string; reason: string }>; floor: number; belowFloor: boolean; short?: string }
+export interface Choice { shown: Shown[]; excluded: Array<{ title: string; reason: string }>; floor: number; belowFloor: boolean; short?: string
+ /** Every candidate left runs on an account the route was asked to avoid (`choose` `avoid`). */
+ avoided?: string }
export interface Verdict { pick: Shown; via: 'order' | 'only'; p: null; why: string }
const LEVELS: Level[] = ['low', 'medium', 'high']
/** Run time and spend per window by task size, for a policy row of cost 2 (owner's table, 2026-10-21); not in the policy yet. */
-const SIZES: Record<Size, { minutes: number; spend: Record<Window, number> }> = {
+export const SIZES: Record<Size, { minutes: number; spend: Record<Window, number> }> = {
small: { minutes: 20, spend: { '5-hour': 10, weekly: 1 } },
medium: { minutes: 60, spend: { '5-hour': 30, weekly: 4 } },
large: { minutes: 180, spend: { '5-hour': 50, weekly: 8 } },
@@ -99,9 +101,15 @@ export function breaks(rules: SwarmRule[], p: { machineId: string; engine: strin
/** A new agent whose policy row leaves the effort to the engine starts at the owner's minimum instead (Lead, 2026-10-22), so
* a minimum does not rule out the Codex `default` row. */
function lifted(rules: SwarmRule[], p: Probe): Probe {
- if (p.kind !== 'new' || rank(p.effort) >= 0) return p
- const least = Math.max(-1, ...rules.flatMap(({ rule }) => rule.kind === 'minEffort' && applies(rule, p.engine) ? [rank(rule.effort)] : []))
- return least < 0 ? p : { ...p, effort: EFFORTS[least] }
+ // The same probe when nothing is lifted: `choose` tells a lifted row from its original by identity.
+ const effort = p.kind === 'new' ? liftEffort(rules, p.engine, p.effort) : p.effort
+ return effort === p.effort ? p : { ...p, effort }
+}
+/** The effort a new agent on this row starts at: the row's own, or the owner's minimum when the row leaves it to the engine. */
+export function liftEffort(rules: SwarmRule[], engine: string, effort: string): string {
+ if (rank(effort) >= 0) return effort
+ 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. */
@@ -197,7 +205,7 @@ export function rateFor(policy: Policy, engine: string, model: string | null, ef
return row ? { quality: row.quality, cost: row.cost } : { quality: 1, cost: 1 }
}
-const KIND_WORD = { local: 'local', api: 'API', shared: 'shared' } as const
+export const KIND_WORD = { local: 'local', api: 'API', shared: 'shared' } as const
const runs = (p: Probe) => p.gridModel ? `${ENGINE[p.engine]} on ${p.gridLabel ?? p.gridModel} (${KIND_WORD[p.gridKind ?? 'local']})` : `${ENGINE[p.engine]} ${p.model} ${p.effort}`
/** A name's words for matching: lowercase letters and digits, "4.1" read as "41". */
const words = (text: string) => text.toLowerCase().split(/[^a-z0-9.]+/).map(w => w.replace(/\./g, '')).filter(Boolean)
@@ -273,15 +281,23 @@ interface Sized { fit: Fit; tight: Measured | null; text: string }
const pct = (n: number) => `${Math.round(n)}%`
const round = (n: number) => Math.round(n * 100) / 100
+/** The account a probe's work spends: a local model's node, its quota reading's account, else its machine's engine. */
+export function accountOf(p: Probe): string {
+ return p.gridModel ? `local:${p.gridName ?? ''}:${p.gridModel}` : p.quota.account ?? `${p.machineId}:${p.engine}`
+}
+
+const AVOIDED = 'Its account lost this task before (a model that kept failing, a limit or a stall), and another account is free.'
+const AVOIDED_ONLY = 'Every candidate runs on the account that lost this task before; check it is answering before you assign.'
+
/** How the probe's account would carry a task of this size (phase 1 §2–3). */
function sizeUp(p: Probe, policy: Policy, a: Assessment, now: number, open: Commitment[]): Sized {
// A local model spends no subscription: it always fits, at its policy cost, and its node is its account.
if (p.gridModel) {
return { fit: { status: 'fits', coverage: null, effectiveCost: p.cost, expiring: 0, spend: { '5-hour': 0, weekly: 0 },
- account: `local:${p.gridName ?? ''}:${p.gridModel}` }, tight: null, text: 'fits: a local model on the Swarm\'s grid uses no subscription' }
+ account: accountOf(p) }, tight: null, text: 'fits: a local model on the Swarm\'s grid uses no subscription' }
}
const { minutes, spend: base } = SIZES[a.size], runMs = minutes * 60_000
- const account = p.quota.account ?? `${p.machineId}:${p.engine}`
+ const account = accountOf(p)
const spend = { '5-hour': base['5-hour'] * p.cost / 2, weekly: base.weekly * p.cost / 2 }
if (p.quota.metered) return { fit: { status: 'fits', coverage: null, effectiveCost: p.cost, expiring: 0, spend, account }, tight: null, text: 'fits: metered, no usage window to run out' }
// Picks still at work hold what they were expected to spend, less the part of their run time already over.
@@ -347,7 +363,9 @@ function withEveryMachine<T extends { machineId: string }>(ranked: T[]): T[] {
return ranked.filter(p => keep.has(p))
}
-export function choose(probes: Probe[], policy: Policy, a: Assessment, now: number = Date.now(), open: Commitment[] = [], rules: SwarmRule[] = [], held: HeldModel[] = []): Choice | { error: 'NO_CANDIDATE'; excluded: Array<{ title: string; reason: string }> } {
+/** `avoid`: accounts of agents that lost this task (a review's Reviewer whose model kept failing): any other account goes first. */
+export function choose(probes: Probe[], policy: Policy, a: Assessment, now: number = Date.now(), open: Commitment[] = [], rules: SwarmRule[] = [], held: HeldModel[] = [],
+ avoid: string[] = []): Choice | { error: 'NO_CANDIDATE'; excluded: Array<{ title: string; reason: string }> } {
// A lifted row can equal another row on the same machine (Codex `default` lifted to high beside Codex high); one is kept.
// A person asking for a local model considers local models alone, whatever their strength.
if (a.local) probes = probes.filter(p => p.gridModel)
@@ -374,7 +392,11 @@ export function choose(probes: Probe[], policy: Policy, a: Assessment, now: numb
const byFloor = meeting.length ? meeting : viable
// Strength beats fit (owner, 2026-10-21): a hard task never goes to a weaker model because the strong ones are short of quota.
const top = Math.max(...byFloor.map(p => p.quality))
- const sized = (a.difficulty === 'high' ? byFloor.filter(p => p.quality === top) : byFloor).map(p => ({ ...p, ...sizeUp(p, policy, a, now, open) }))
+ const strongest = (a.difficulty === 'high' ? byFloor.filter(p => p.quality === top) : byFloor).map(p => ({ ...p, ...sizeUp(p, policy, a, now, open) }))
+ // An account whose model kept failing this task waits while any other account is offered.
+ const fresh = strongest.filter(p => !avoid.includes(p.fit.account))
+ const sized = fresh.length ? fresh : strongest
+ if (fresh.length) excluded.push(...strongest.filter(p => !fresh.includes(p)).map(p => ({ title: titleOf(p), reason: AVOIDED })))
// Only the first group that has anyone is shown: those that fit, then those whose quota is not fully known, then the short.
const status = (['fits', 'unknown', 'short'] as const).find(s => sized.some(p => p.fit.status === s))!
excluded.push(...sized.filter(p => p.fit.status !== status).map(p => ({ title: titleOf(p), reason: p.fit.status === 'unknown' ? UNREAD : runsOut(p.tight!) })))
@@ -383,7 +405,7 @@ export function choose(probes: Probe[], policy: Policy, a: Assessment, now: numb
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!
- return { shown, excluded, floor, belowFloor: !meeting.length, ...(status === 'short'
+ return { shown, excluded, floor, belowFloor: !meeting.length, ...(avoid.length && !fresh.length && strongest.some(p => avoid.includes(p.fit.account)) ? { avoided: AVOIDED_ONLY } : {}), ...(status === 'short'
? { short: `No candidate is expected to cover this task; its ${first.name} quota is expected to run out partway${first.resetsIn === null ? '' : ` and resets in ${span(first.resetsIn)}`}.` } : {}) }
}
diff --git a/cli/src/superTabs/routeCommand.spec.ts b/cli/src/superTabs/routeCommand.spec.ts
index dbdecfcb9..bca9cb350 100644
--- a/cli/src/superTabs/routeCommand.spec.ts
+++ b/cli/src/superTabs/routeCommand.spec.ts
@@ -110,6 +110,44 @@ describe('routeTask', () => {
await routeTask(input, s, where as never, opener(id => daemon(id, { agents: ['h1'] })))
expect((recorded(s).command.decision.candidates as Array<{ title: string }>).some(c => c.title.startsWith('Multiply'))).toBe(false)
})
+ // v2: one Codex account answered 429 for 40 minutes and stalled reviews. A review whose Reviewer lost it to a failing model
+ // goes first to another account, never back to the one that failed.
+ describe('a review whose Reviewer lost it', () => {
+ const accountOn = (account: string) => ({ providers: [{ ...usage.providers[0]!, account }] })
+ /** `removed`: the Lead stopped the failed Reviewer and its host removed it, so only the group remembers where it failed. */
+ const route = async (failed: boolean, machines: string[] = ['m1', 'm2'], removed = false) => {
+ const state = tab()
+ const reviewer = { id: 'r1', name: 'Reviewer', role: 'reviewer', machineId: 'm1', harnessId: 'hr', configuration: { engine: 'claude', model: 'sonnet', effort: 'medium' },
+ ...(failed ? { lostTask: { conversationId: 'g1', assignmentId: 'x', reason: 'its model keeps failing', at: 1 } } : {}) }
+ Object.assign(state.state.conversations[1]!, { reviewOf: 'lead', ...(failed ? { assignment: { id: 'x', agentId: 'r1', status: 'lost', lost: { reason: 'its model keeps failing', at: 1 } },
+ lostAttempt: { id: 'x', agentId: 'r1', machineId: 'm1', engine: 'claude' } } : {}) })
+ state.state.agents = [...agents.filter(a => a.id !== 'a2' || machines.includes('m2')), ...removed ? [] : [reviewer]]
+ const s = scoped({ tab: state, context: { ok: true, value: { agentId: 'lead', tab: state, policy: { policy, warnings: [] },
+ machines: machines.map(id => ({ machineId: id, name: id === 'm1' ? 'remote-1' : 'mac' })) } } })
+ const result = await routeTask(input, s, where as never, opener(id => daemon(id, { agents: ['hr'], usage: accountOn(id === 'm1' ? 'acct-1' : 'acct-2') })), () => 'op')
+ return { result, s }
+ }
+ it('goes to another account than the one whose model failed', async () => {
+ // Without the failure the first machine's account is first.
+ expect((await route(false)).result).toMatchObject({ ok: true, pick: { machineId: 'm1' } })
+ const { result, s } = await route(true)
+ expect(result).toMatchObject({ ok: true, pick: { kind: 'new', machineId: 'm2' } })
+ expect(recorded(s).command.decision.excluded).toEqual(expect.arrayContaining([expect.objectContaining({ title: expect.stringContaining('remote-1'),
+ reason: expect.stringContaining('another account is free') })]))
+ })
+ it('still routes to that account when no other is offered, and says so', async () => {
+ const { result } = await route(true, ['m1'])
+ expect(result).toMatchObject({ ok: true, pick: { machineId: 'm1' } })
+ expect(result.warnings).toEqual(expect.arrayContaining([expect.stringContaining('the account that lost this task before')]))
+ })
+ it('remembers the failed account after the Lead stops and removes that Reviewer', async () => {
+ expect((await route(true, ['m1', 'm2'], true)).result).toMatchObject({ ok: true, pick: { kind: 'new', machineId: 'm2' } })
+ const { result } = await route(true, ['m1'], true)
+ expect(result).toMatchObject({ ok: true, pick: { machineId: 'm1' } })
+ expect(result.warnings).toEqual(expect.arrayContaining([expect.stringContaining('the account that lost this task before')]))
+ })
+ })
+
// Final review, Important 3: cancelling or reassigning lost work must not make its old worker routable again.
describe('a member whose last task was lost', () => {
const lostTask = { conversationId: 'g0', assignmentId: 'x', reason: 'no progress for 30 minutes', at: 1 }
diff --git a/cli/src/superTabs/routeCommand.ts b/cli/src/superTabs/routeCommand.ts
index 2c125bcb9..c29bd600a 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 { requiredToolReason, startRequirements } from './capacity.js'
import { inspectCapacity, type ScopedRequest } from './start.js'
import { ENDED_WORK, object, within } from './wire.js'
-import { API_BUILDERS, choose, decide, parseAssessment, quotaOf2, rateFor, recordOf, repoMatch, repositoryKey, type Assessment, type Commitment, type HeldModel, type MemberFrame, type Policy, type Probe, type SwarmRule, type TaskFolder } from './route.js'
+import { accountOf, API_BUILDERS, choose, decide, parseAssessment, quotaOf2, rateFor, recordOf, repoMatch, repositoryKey, type Assessment, type Commitment, 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'
@@ -19,31 +19,31 @@ const TRANSPORT = new Set(['AGENT_UNAVAILABLE', 'SUPER_TAB_UNAVAILABLE', 'BACKEN
const MACHINES_UNREADABLE = "The account's machine list could not be read; only known machines were considered."
const DISK_UNVERIFIED = 'Project disk space could not be verified.'
const NO_PROJECT_FOLDER = 'This machine does not have the project folder. Add it to the Swarm so it can clone the project.'
-const OFFLINE = 'Machine is offline or unreachable.'
+export const OFFLINE = 'Machine is offline or unreachable.'
const UNKNOWN_QUOTA: Probe['quota'] = { known: false, leftPercent: null, resetsAt: null }
const UNKNOWN_LOAD: NonNullable<Probe['load']> = { agents: null, freeMemoryBytes: null, hasFolder: null }
const EXHAUSTED_WINDOW = 'The subscription has an exhausted usage window. Wait for a fresh allowance reading or choose another account.'
/** Temporary (Scholes, 2026-10-26): grid's CLI does not run on Windows yet, so a Swarm agent started there never comes up
* (WIN-DELL took starts that silently never ran). Lifting it is emptying this list. Compared with the OS every reading
* has (lib/machineHardware.ts names it `Windows`), so a host from before readiness is left out too. */
-const NO_SWARM_AGENTS_ON: readonly string[] = ['Windows']
+export const NO_SWARM_AGENTS_ON: readonly string[] = ['Windows']
const ENGINE_NAME: Record<string, string> = { claude: 'Claude Code', codex: 'Codex' }
const NO_PUSH = "This machine's git login cannot push to the project repository. Its owner can sign in to GitHub there (gh auth login, then gh auth setup-git)."
-const STALLED = 'Its last 2 starts on this machine started no agent (they failed or were never picked up), so it is left out until a start there succeeds. Its owner can check the machine.'
+export const STALLED = 'Its last 2 starts on this machine started no agent (they failed or were never picked up), so it is left out until a start there succeeds. Its owner can check the machine.'
/** What a machine says it cannot do for this task (#229 v1 routing): `all` keeps out its new agents, `engines` those of an
* engine, `push` its new agents and members alike. Only a known failure is said; anything unknown says nothing. */
-interface Unready { all: string[]; engines: Record<string, string>; push: string | null }
+export interface Unready { all: string[]; engines: Record<string, string>; push: string | null }
const READY: Unready = { all: [], engines: {}, push: null }
/** Whether the Swarm's last 2 starts on [machineId] both started nothing: failed, or queued and never picked up. A start
* being created (dispatched, no agent yet) is not counted, nor is a machine with fewer than 2 starts. */
-function stalled(starts: Json[], machineId: string): boolean {
+export function stalled(starts: Json[], machineId: string): boolean {
const last = starts.filter(s => object(s.request).machineId === machineId).slice(-2)
return last.length === 2 && last.every(s => !s.harnessId && (!!s.error || s.dispatched !== true))
}
/** What a contributed machine's reading says it is not ready for, for work in [projectId] ([needsPush] unless a review).
* Its own login's push access counts only when it is the one that pushes: not for a teammate's project where the server
* has the Harness GitHub App, whose token the agent pushes with (start.ts). */
-function unreadyPool(pool: Json, project: Json | undefined, projectId: string, needsPush: boolean, githubApp: boolean, projectOwner: unknown): Unready {
+export function unreadyPool(pool: Json, project: Json | undefined, projectId: string, needsPush: boolean, githubApp: boolean, projectOwner: unknown): Unready {
const observed = object(pool.observation), readiness = object(observed.readiness), repository = object(project?.repository)
const engines: Record<string, string> = {}
for (const e of list(readiness.engines)) {
@@ -256,7 +256,14 @@ export async function routeTask(input: { tabId: string; conversationId: string;
// Picks started or assigned and still at work hold part of their account's quota; the log, and so this, is per Swarm.
const working = (decisions ?? []).filter(d => d.final && d.outcome === null && typeof d.account === 'string')
.map(d => ({ account: d.account, spend: object(d.spend), size: d.size, createdAt: Date.parse(String(d.createdAt)) }) as Commitment)
- const choice = choose(probes, policy, assessment, Date.now(), working, rules, heldLocalModels(state))
+ // Work this group last lost (a Reviewer whose model kept failing, v2) goes first to any other account (route.ts choose). The
+ // group keeps where that attempt ran (backend superTabs/liveness.ts loseTask), so this holds once its agent is stopped and
+ // removed too; an attempt lost before that kept it is read from its agent, while that is still here.
+ const lostAttempt = object(group.lostAttempt), lostBy = agents.find(a => a.id === lostAttempt.agentId)
+ const failedOn = text(lostAttempt.machineId) ?? text(lostBy?.machineId), failedEngine = text(lostAttempt.engine) ?? text(object(lostBy?.configuration).engine)
+ const avoid = failedOn && failedEngine ? [...new Set([`${failedOn}:${failedEngine}`,
+ ...probes.filter(p => p.machineId === failedOn && p.engine === failedEngine && !p.gridModel).map(accountOf)])] : []
+ const choice = choose(probes, policy, assessment, Date.now(), working, rules, heldLocalModels(state), avoid)
if ('error' in choice) return choice
const verdict = decide(choice)
const operationId = `route-${newId()}`
@@ -276,7 +283,7 @@ export async function routeTask(input: { tabId: string; conversationId: string;
alternatives: alternativesTo(verdict.pick, choice.shown).map(publicOf),
warnings: [...(Array.isArray(effective.warnings) ? effective.warnings : []), ...(value.machinesUnreadable === true ? [MACHINES_UNREADABLE] : []),
...(choice.shown.some(p => p.kind === 'member' && p.terminalUnverified) ? ["A member's terminal could not be verified from its machine's snapshot. Check it before assignment."] : []),
- ...(choice.short ? [choice.short] : [])],
+ ...(choice.short ? [choice.short] : []), ...(choice.avoided ? [choice.avoided] : [])],
next: verdict.pick.kind === 'member'
? `Assign with: command OPERATION_ID {"type":"work.assign","conversationId":"${input.conversationId}","agentId":"${verdict.pick.agentId}"${decision}}`
: `Start with: start OPERATION_ID ${JSON.stringify({ conversationId: input.conversationId, name: review ? 'Reviewer' : 'Builder', ...(review ? { role: 'reviewer' } : {}), cwd: text(machines.get(verdict.pick.machineId)?.pool?.cwd) ?? assessment.needs.cwd ?? '/absolute/repo/on/that/machine',
@@ -294,15 +301,15 @@ function alternativesTo<T extends { id: string; machineId: string }>(pick: T, sh
}
/** A reading this old says nothing is served (backend `MACHINE_FRESH_MS`). */
-const LOCAL_FRESH_MS = 45_000
+export const LOCAL_FRESH_MS = 45_000
/** Refusals about a subscription's allowance, which a local model does not spend. */
const SUBSCRIPTION = /subscription/i
-interface Served { grid: string; model: string; label: string; kind: 'local' | 'api' | 'shared'; machines: Set<string> | null; holders: string[] }
+export interface Served { grid: string; model: string; label: string; kind: 'local' | 'api' | 'shared'; machines: Set<string> | null; holders: string[] }
/** The models served for the Swarm while the owner has the add-on on and a fresh reading lists them, by grid and model, each
* with the Builders on it: one started on a model, or starting on it, holds it until it leaves the Swarm. */
-function servedModels(state: Json, swarm: string, now: number): Map<string, Served> {
+export function servedModels(state: Json, swarm: string, now: number): Map<string, Served> {
// By grid and model: its label, and the machines that may run it (null: any).
const served = new Map<string, Served>()
for (const machine of list(state.machines)) {
@@ -329,7 +336,7 @@ function servedModels(state: Json, swarm: string, now: number): Map<string, Serv
}
/** Whether [m] can take another Builder: a local engine or a model shared with a member takes one, an API model up to [API_BUILDERS]. */
-const takesBuilder = (m: Served) => m.holders.length < (m.kind === 'api' ? API_BUILDERS : 1)
+export const takesBuilder = (m: Served) => m.holders.length < (m.kind === 'api' ? API_BUILDERS : 1)
/** The Swarm's served models that take no more Builders, and who is on them, then those a fresh reading says Builders are
* never offered, and why (superTabs/machines.ts refusedOn): what the route says when it offers none. */
diff --git a/cli/src/superTabs/service.spec.ts b/cli/src/superTabs/service.spec.ts
index 65da53a30..a23509584 100644
--- a/cli/src/superTabs/service.spec.ts
+++ b/cli/src/superTabs/service.spec.ts
@@ -568,7 +568,7 @@ describe('post --attach steps', () => {
it('teaches agents to say when their work needs a person or is stuck', async () => {
const t = setup()
const help = (await t.ask({ action: 'help' }, owner)) as { help: { command: string; commands: Array<Record<string, unknown>> } }
- expect(help.help.commands.filter(c => c.type === 'work.status').map(c => c.status)).toEqual(['working', 'needs_human', 'blocked', 'done'])
+ expect(help.help.commands.filter(c => c.type === 'work.status').map(c => c.status)).toEqual(['working', 'needs_human', 'needs_human', 'blocked', 'done'])
expect(help.help.command).toContain('needs_human')
})
@@ -837,6 +837,28 @@ describe('mentions on a post', () => {
swarm(t, 'new-lead')
expect(String((await help(t, { tabId: 'tab', agentId: t.agentId })).post)).not.toContain('--mention')
})
+ it('offers plan in help to a project\'s Lead only', async () => {
+ const t = setup()
+ swarm(t, t.agentId)
+ expect(String((await help(t, { tabId: 'tab', agentId: t.agentId })).plan)).toContain('plan [JSON]: the best plan for all your open groups')
+ swarm(t, 'new-lead')
+ expect((await help(t, { tabId: 'tab', agentId: t.agentId })).plan).toBeUndefined()
+ })
+
+ it('tells every agent how to read its decisions and ask one through needs_human, and only a Lead how to ask a batch', async () => {
+ const t = setup()
+ swarm(t, t.agentId)
+ const lead = await help(t, { tabId: 'tab', agentId: t.agentId })
+ const plain = await help(t, {})
+ for (const each of [lead, plain]) {
+ expect(each.decisions).toContain('decisions [--answered]: the decisions you asked of people')
+ expect(each.decisions).toContain('A decision is not a private channel')
+ expect(each.commands).toContainEqual(expect.objectContaining({ type: 'work.status', status: 'needs_human',
+ ask: { personId: 'PERSON', options: ['Option A', 'Option B'], recommended: 0, unblocks: 'What the answer unblocks' } }))
+ }
+ expect(lead.commands).toContainEqual(expect.objectContaining({ type: 'decision.ask', conversationId: 'GROUP', personId: 'PERSON' }))
+ expect(plain.commands).not.toContainEqual(expect.objectContaining({ type: 'decision.ask' }))
+ })
it('answers help without --mention outside a tab, or when the caller cannot be read', async () => {
const t = setup()
diff --git a/cli/src/superTabs/service.ts b/cli/src/superTabs/service.ts
index 1ff274730..7239fffca 100644
--- a/cli/src/superTabs/service.ts
+++ b/cli/src/superTabs/service.ts
@@ -25,6 +25,7 @@ const HELP = {
leadOptions: 'Leads: run help with --tab ID for options only a Lead has.',
messages: 'messages GROUP: read recent messages in a conversation.',
message: 'message GROUP MESSAGE_ID: read one exact message, including an earlier question or result referenced by a reply.',
+ decisions: 'decisions [--answered]: the decisions you asked of people, still open, or with --answered those answered (each with its choice and note). A Lead also sees those asked in its project. When your work needs a person to decide, ask through work.status needs_human with ask: the question as its result, 2 to 5 options, the one you recommend and what the answer unblocks. Keep working on your recommendation, marked provisional, until a notice in that conversation says it was answered; then read the answer here with --answered. The notice carries none of the answer. A decision is not a private channel: anything private goes through Chat with PM.',
post: `post GROUP TEXT OPERATION_ID [--reply-to MESSAGE_ID] [--attach PATH]...: ${POST_HELP}`,
start: 'start OPERATION_ID JSON: create one agent in a conversation on a machine in this Swarm\'s Machines list; to use another machine, a person adds it to the Swarm first. Repeat exactly after an interruption; it follows the same native creation receipt. It does not assign work. With worktree true, the agent starts from the repository\'s default branch, fetched first, unless you set branchRef (refs/heads/BRANCH, or refs/remotes/origin/BRANCH to fetch it first) to start from another branch, such as the one this work builds on. Set role "reviewer" to start a Reviewer; leave role out for a Builder. The role is kept for the session. On Custom skills, add "roleId" to the start request to start the agent in that role of its kind (a builder or reviewer role from status); without it the agent takes the first role of its kind. A Reviewer runs on claude or codex and is assigned only review groups (conversation.create with reviewOf naming the group it reviews); a review group is assigned only to a Reviewer. Add the Reviewer to the reviewed group with conversation.agent so it is told when that work is ready for review and can pass its independent check. Start one with a routeDecisionId like any agent.',
release: 'When a Builder finishes, decide reuse, keep or stop; prefer stop unless more work is coming soon. Reuse assigns new work; agent.release records keep or requests stop. Wait for the execution host to confirm a stop. A person can withdraw a stuck stop; the session cannot receive new work in that Swarm. Its native capacity stays reserved until its host confirms stopping. Other Swarms wait up to two minutes for an in-flight close, then may reuse it.',
@@ -40,6 +41,8 @@ const HELP = {
{ 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' },
{ type: 'project.skills', projectId: 'PROJECT', mode: 'default|orchestration|custom', askedIn: { conversationId: 'GROUP', messageId: 'OWNER_MESSAGE' } },
+ // The morning digest, at a person's local time; time null turns it off.
+ { type: 'project.digest', projectId: 'PROJECT', time: '08:00', timeZone: 'Asia/Ho_Chi_Minh' },
{ type: 'message.send', conversationId: 'GROUP', text: 'A message addressed to an agent', replyTo: null, recipientIds: ['AGENT'] },
{ type: 'conversation.create', title: 'Outcome', task: { goal: 'An independently assignable result', changes: 'What changes', constraints: 'What must stay true', owns: ['Paths or code areas'] }, checks: [{ description: 'Observable acceptance evidence', independent: false }] },
{ type: 'conversation.create', title: 'Review: Outcome', reviewOf: 'GROUP', task: { goal: 'An independent verdict on the Builder\'s revision', changes: 'None: read only', constraints: 'The reviewed group\'s constraints', owns: ['The reviewed group\'s owned code, read only'] }, checks: [{ description: 'Verdict with the reviewed revision', independent: false }] },
@@ -57,6 +60,9 @@ const HELP = {
{ type: 'work.status', conversationId: 'GROUP', assignmentId: 'ATTEMPT', status: 'working', result: null },
// Both reach the Lead and alert the Harness Pro on the machine running the agent until the status moves on.
{ type: 'work.status', conversationId: 'GROUP', assignmentId: 'ATTEMPT', status: 'needs_human', result: 'The decision you need from a person, asked as one short question' },
+ // The same, opened as a decision for one person in the conversation (decisions in help).
+ { type: 'work.status', conversationId: 'GROUP', assignmentId: 'ATTEMPT', status: 'needs_human', result: 'The question, in one sentence',
+ ask: { personId: 'PERSON', options: ['Option A', 'Option B'], recommended: 0, unblocks: 'What the answer unblocks' } },
{ type: 'work.status', conversationId: 'GROUP', assignmentId: 'ATTEMPT', status: 'blocked', result: 'Why you are stuck and what would unblock you, in one or two sentences' },
{ type: 'work.check', conversationId: 'GROUP', assignmentId: 'ATTEMPT', checkId: 'CHECK', passed: true, evidence: 'Exact test command, revision and observed result' },
{ type: 'work.status', conversationId: 'GROUP', assignmentId: 'ATTEMPT', status: 'done', result: 'Exact revision, evidence and deliverable links' },
@@ -68,7 +74,12 @@ const list = (value: unknown) => Array.isArray(value) ? value.map(object) : []
const answerOf = (read: SwarmRead) => ({ lastChangedAt: read.lastChangedAt, state: read.state, ...(read.githubApp ? { githubApp: true } : {}) })
const OFF_ROSTER = 'This agent is not on this machine\'s Swarm roster right now. That can mean this machine has no access to it, or its billing does not allow it. Check how this machine is shared.'
/** Only a project's Lead may tag people (spec 2026-10-24-lead-mentions), so only a Lead's help offers it. */
-const LEAD_HELP = { ...HELP, post: `post GROUP TEXT OPERATION_ID [--reply-to MESSAGE_ID] [--attach PATH]... [--mention PERSON]...: ${POST_HELP} --mention tags a person, by the id or email shown in status (up to 5), when you need them to act or decide; it shows in their notifications.` }
+const LEAD_HELP = { ...HELP, post: `post GROUP TEXT OPERATION_ID [--reply-to MESSAGE_ID] [--attach PATH]... [--mention PERSON]...: ${POST_HELP} --mention tags a person, by the id or email shown in status (up to 5), when you need them to act or decide; it shows in their notifications.`,
+ // Advisory (docs/plans/2026-10-27-swarm-scheduler.md): a plan for every open group at once, which the route still decides.
+ plan: 'plan [JSON]: the best plan for all your open groups at once, from the scheduler on this machine (Python 3 and OR-Tools; without them it says how to install, and routing works as before). Per group: the machine, engine, model and effort, start order and expected finish, with the finish time and cost against routing one group at a time. JSON (optional): {"groups":{"GROUP":{"difficulty":"low|medium|high","risk":"low|medium|high","size":"small|medium|large","kind":"optional word","after":["GROUP"]}}}; a group you do not assess is planned at medium and listed as an estimate. It keeps the owner\'s hard rules and a review\'s other model family, and records nothing: follow it in order by routing each group and starting the plan\'s pick with overrideReason "scheduler plan".',
+ // Only a project's Lead asks a batch: up to 10 questions for one person, in one of its project's conversations.
+ commands: [...HELP.commands, { type: 'decision.ask', conversationId: 'GROUP', personId: 'PERSON', questions: [{ question: 'One question a person decides',
+ options: ['Option A', 'Option B'], recommended: 0, unblocks: 'What the answer unblocks' }] }] }
const OTHER_WORK_FIELDS = ['conversationId', 'projectName', 'title', 'owns', 'status', 'agentName', 'pr'] as const
/** How old a host form a one-off question about this machine's Swarms may take: the host reads one every second. */
const POOLS_FRESH_MS = 5_000
@@ -372,6 +383,9 @@ export function superTabService(core: CoreApi, options: SuperTabServiceOptions =
const attempts = Array.isArray(tried) ? tried.slice(0, 50).map(object).map(a => ({ id: a.id, agentId: a.agentId, status: a.status, result: typeof a.result === 'string' ? a.result.slice(0, 500) : null, createdAt: a.createdAt ?? null })) : null
return { ok: true, value: { ...(decisions ? { decisions } : { decisionsUnreadable: true }), ...(attempts ? { attempts } : { attemptsUnreadable: true }) } }
}
+ if (payload.action === 'decisions' && (payload.state === 'open' || payload.state === 'answered')) {
+ return { ok: true, value: await backend(core, 'GET', `${path}/decisions?state=${payload.state}&${identity}`) }
+ }
if (payload.action === 'messages' && identifier(payload.conversationId)) {
const page = await backend(core, 'GET', `${path}/conversations/${payload.conversationId}/messages?${identity}`)
return { ok: true, value: markAnswered(page, [], agentId) }
diff --git a/cli/src/superTabs/serviceReads.spec.ts b/cli/src/superTabs/serviceReads.spec.ts
index 95b4f64ba..93943a312 100644
--- a/cli/src/superTabs/serviceReads.spec.ts
+++ b/cli/src/superTabs/serviceReads.spec.ts
@@ -55,6 +55,7 @@ describe('what each action reads of the Swarm', () => {
['attachment', { conversationId: FIXTURE.workGroup, step: 'sent', operationId: 'op-1' }],
['command', { operationId: 'op-2', command: { type: 'message.send', conversationId: FIXTURE.workGroup, text: 'Hi', replyTo: null, recipientIds: [] } }],
['help', {}],
+ ['decisions', { state: 'open' }],
])('reads nothing of it for %s', async (action, payload) => {
const s = swarm()
const answer = await s.ask({ action, tabId: T, agentId: FIXTURE.builderId, ...payload }, owner)
@@ -152,3 +153,14 @@ describe('route history when the group cannot be read for another reason', () =>
.toEqual({ error: 'SWARM_BUSY', detail: 'Busy', status: 503 })
})
})
+
+describe('decisions', () => {
+ it('reads the decisions the caller asked, open or answered, as that agent', async () => {
+ const listed = { decisions: [{ id: 'd1', question: 'Ship how?', options: ['Behind a flag', 'To everyone'], recommended: 0, choice: null }] }
+ for (const state of ['open', 'answered']) {
+ const s = swarm((method, path) => path.startsWith(`/api/super-tabs/${T}/decisions?`) ? ok(listed) : undefined)
+ expect(await s.ask({ action: 'decisions', tabId: T, agentId: FIXTURE.leadId, state }, owner)).toEqual({ ok: true, value: listed })
+ expect(s.call).toHaveBeenCalledWith('GET', `/api/super-tabs/${T}/decisions?state=${state}&asAgentId=${FIXTURE.leadId}`, undefined)
+ }
+ })
+})
diff --git a/cli/src/superTabs/start.spec.ts b/cli/src/superTabs/start.spec.ts
index 18759553f..2d3975398 100644
--- a/cli/src/superTabs/start.spec.ts
+++ b/cli/src/superTabs/start.spec.ts
@@ -681,6 +681,37 @@ describe('a routed Claude start launches with the model instead of switching it
expect(commands.find(c => c.type === 'agent.started')).toMatchObject({ startId: 'start', harnessId: 'native', configuration: { engine: 'claude' } })
})
+ // Builders started with opus and effort high read as effort 'auto' (Dee, 2026-10-27): Claude Code does not report an
+ // effort it was launched with, so the frame says auto, and the start stored that.
+ const launchedAsAuto = (f: ReturnType<typeof fixture>) => {
+ const request = f.request.getMockImplementation()!
+ f.request.mockImplementation(async (type, payload, ms) => {
+ const answer = await request(type, payload, ms)
+ const agent = answer.agent as Record<string, unknown> | undefined
+ return agent ? { ...answer, agent: { ...agent, selectedModel: 'runtime-v1:native:claude:opus@auto' } } : answer
+ })
+ }
+ const started = (f: ReturnType<typeof fixture>) => f.scoped.mock.calls.map(c => c[0].command as Record<string, unknown>).find(c => c?.type === 'agent.started')
+
+ it('records the effort it launched with when the engine reads it as auto', async () => {
+ const f = fixture({ launchModel: ['claude'] }); launchedAsAuto(f)
+ await begin(f)
+ expect(started(f)).toMatchObject({ configuration: { engine: 'claude', model: 'opus', effort: 'high' } })
+ })
+
+ it('records the effort the machine accepted at launch when a resumed start reads it as auto', async () => {
+ const f = fixture({ launchModel: ['claude'], acceptedLaunchModel: { model: 'opus', effort: 'high' } }); launchedAsAuto(f)
+ Object.assign(f.start.request, routed)
+ await startAgent({ action: 'resume', tabId: 'tab', startId: 'start' }, f.scoped, where, f.open)
+ expect(started(f)).toMatchObject({ configuration: { model: 'opus', effort: 'high' } })
+ })
+
+ it('keeps auto when nothing was launched with an effort', async () => {
+ const f = fixture({ launchModel: ['claude'] }); launchedAsAuto(f)
+ await begin(f, { model: 'default', effort: 'default' })
+ expect(started(f)).toMatchObject({ configuration: { model: 'opus', effort: 'auto' } })
+ })
+
it('sends neither for default and default', async () => {
const f = fixture({ launchModel: ['claude'] })
await begin(f, { model: 'default', effort: 'default' })
diff --git a/cli/src/superTabs/start.ts b/cli/src/superTabs/start.ts
index c0dff330d..924c46df4 100644
--- a/cli/src/superTabs/start.ts
+++ b/cli/src/superTabs/start.ts
@@ -256,7 +256,12 @@ export async function startAgent(input: Json, scoped: ScopedRequest, where: Wher
// Reports what the engine launched with; the routed model, once launched or switched, is observed afterwards.
const profile = parseRuntimeProfile(frame.selectedModel)
const matched = profile && profile.sessionId === nativeId && profile.engine === frame.engine ? profile : null
- const configuration = { engine: text(frame.engine) ?? String(request.engine), model: matched?.model ?? null, effort: matched?.effort ?? null,
+ // Claude Code does not report an effort it was launched with, so its frame reads auto: the agent runs the effort this
+ // start launched it with (a resumed start: the one the machine accepted at launch). Builders started with opus high
+ // were stored as auto until 2026-10-27.
+ const launchedEffort = launched ? effort : launched === undefined ? text(object(native.launchModel).effort) : null
+ const configuration = { engine: text(frame.engine) ?? String(request.engine), model: matched?.model ?? null,
+ effort: matched?.effort === 'auto' && launchedEffort ? launchedEffort : matched?.effort ?? null,
contextWindow: number(frame.contextWindow), engineVersion: text(frame.engineVersion) }
const startedSession = typeof frame.sessionId === 'string' && frame.sessionId && typeof frame.createdAt === 'string' && Number.isFinite(Date.parse(frame.createdAt))
? { sessionId: frame.sessionId, createdAt: frame.createdAt } : undefined
diff --git a/cli/src/superTabs/terminal.spec.ts b/cli/src/superTabs/terminal.spec.ts
index b3d0458d0..f5957e7e1 100644
--- a/cli/src/superTabs/terminal.spec.ts
+++ b/cli/src/superTabs/terminal.spec.ts
@@ -198,6 +198,20 @@ describe('the stuck and usage-limit alerts', () => {
expect(t.alerts()[1]).toEqual({ type: 'agent.alert', agentId: 'a1', alert: 'model', active: false })
})
+ it('raises nothing for a burst of failures that recovers before ten minutes, so its task is never lost for it', async () => {
+ // Last night's reviewer failures came and went (429 bursts): nine minutes of retries, then answers for ten.
+ const failing = (): SuperTabScreen => ({ ok: true, text: '✻ Waiting for API response · will retry in 2m 38s · check your network\n❯ ', hold: null })
+ const t = setup({ screen: failing })
+ await t.host.tick([row()])
+ t.wait(539_000); await t.host.tick([row()])
+ t.showing(idle)
+ for (let second = 0; second < 600; second += 15) { t.wait(15_000); await t.host.tick([row()]) }
+ // A second burst starts its own ten minutes.
+ t.showing(failing); t.wait(15_000); await t.host.tick([row()])
+ t.wait(539_000); await t.host.tick([row()])
+ expect(t.alerts()).toEqual([])
+ })
+
it('counts retries with fresh attempts between them as one failing stretch', async () => {
// Claude Code shows its countdown, then a plain spinner for the minutes each new attempt takes.
const failing = (): SuperTabScreen => ({ ok: true, text: '✻ Waiting for API response · will retry in 1m 18s · check your network\n❯ ', hold: null })
diff --git a/cli/src/superTabs/terminal.ts b/cli/src/superTabs/terminal.ts
index 34e268c05..9bed02872 100644
--- a/cli/src/superTabs/terminal.ts
+++ b/cli/src/superTabs/terminal.ts
@@ -24,7 +24,7 @@ const PROMPT_WAIT_MS = 3 * 60_000
/** The spec's cap on what a screen read returns. */
const MAX_SCREEN_BYTES = 64 * 1024
/** What the screen reader says a prompt or a question is waiting on; a popup or a hidden prompt is not one. */
-const WAITING: ReadonlySet<MessageHold> = new Set(['permission_open', 'question_open', 'menu_open', 'trust_open', 'update_prompt_open', 'model_prompt_open', 'sign_in_open'])
+export const WAITING: ReadonlySet<MessageHold> = new Set(['permission_open', 'question_open', 'menu_open', 'trust_open', 'update_prompt_open', 'model_prompt_open', 'sign_in_open'])
/** The spec's named keys, in any case: the name the Lead's request carries, and the terminal's own (core/superTabTerminal.ts).
* Ctrl-D and the like are left out: one closes an engine. */
const KEYS: Record<string, [string, string]> = { enter: ['Enter', 'Enter'], esc: ['Esc', 'Escape'], escape: ['Esc', 'Escape'], tab: ['Tab', 'Tab'],
@@ -250,7 +250,9 @@ export class TerminalHost {
state.limit = await this.episode(agent, 'limit', state.limit, limit !== null, now, () => true, limit ?? {})
if (modelFailing(read.text)) state.retried = now
const retrying = state.retried !== undefined && now - state.retried < MODEL_CLEAR_MS
- state.model = await this.episode(agent, 'model', state.model, retrying, now, since => now - since >= MODEL_WAIT_MS, {})
+ // Ten minutes up to the last retry seen, not up to now: the quiet minutes that confirm answers came again are not
+ // failure, so a burst that recovers before ten minutes never alerts (and its task is never lost for it).
+ state.model = await this.episode(agent, 'model', state.model, retrying, now, since => state.retried! - since >= MODEL_WAIT_MS, {})
}
}
diff --git a/desktop/lib/shared/theme/app_icons.dart b/desktop/lib/shared/theme/app_icons.dart
index 1478eface..d737b4517 100644
--- a/desktop/lib/shared/theme/app_icons.dart
+++ b/desktop/lib/shared/theme/app_icons.dart
@@ -187,6 +187,7 @@ abstract final class AppIcons {
static const terminal = LucideIcons.terminal400;
static const trash2 = LucideIcons.trash2400;
static const triangleAlert = LucideIcons.triangleAlert400;
+ static const trophy = LucideIcons.trophy400;
static const type = LucideIcons.type400;
static const undo2 = LucideIcons.undo2400;
static const unlink = LucideIcons.unlink400;
diff --git a/desktop/lib/super_tabs/agent_details.dart b/desktop/lib/super_tabs/agent_details.dart
index e4e9b0bcc..f761c6e9e 100644
--- a/desktop/lib/super_tabs/agent_details.dart
+++ b/desktop/lib/super_tabs/agent_details.dart
@@ -141,6 +141,8 @@ class SuperTabAgentInfo {
'blocked' => 'Stuck on "${group.title}"',
'review' => 'Waiting for review on "${group.title}"',
'reconciling' => 'Checking "${group.title}"',
+ // Its machine died, it stalled or hit a limit, and the Lead hands it on (backend liveness.ts).
+ 'lost' => 'Lost "${group.title}"',
'working' when activity == HarnessActivity.working =>
'Working on "${group.title}"',
// An assignment can outlive a native turn or connection. Keep the
diff --git a/desktop/lib/super_tabs/decisions.dart b/desktop/lib/super_tabs/decisions.dart
new file mode 100644
index 000000000..739edd10a
--- /dev/null
+++ b/desktop/lib/super_tabs/decisions.dart
@@ -0,0 +1,158 @@
+import 'dart:async';
+
+import 'package:flutter/foundation.dart';
+
+import 'controller.dart';
+import 'model.dart';
+
+/// One question an agent asked the reader: options, the one it recommends and
+/// what an answer unblocks (backend superTabs/decisions.ts).
+class SuperTabDecision {
+ SuperTabDecision.fromJson(Map<String, dynamic> row)
+ : id = row['id'] as String,
+ batchId = row['batchId'] as String? ?? row['id'] as String,
+ projectId = row['projectId'] as String? ?? '',
+ projectName = row['projectName'] as String? ?? '',
+ conversationId = row['conversationId'] as String,
+ conversationTitle = row['conversationTitle'] as String? ?? '',
+ askerName = row['askerName'] as String? ?? 'Agent',
+ question = row['question'] as String? ?? '',
+ options = List.unmodifiable([
+ for (final option in row['options'] as List? ?? const []) '$option',
+ ]),
+ recommended = (row['recommended'] as num?)?.toInt() ?? 0,
+ unblocks = row['unblocks'] as String? ?? '',
+ choice = (row['choice'] as num?)?.toInt(),
+ note = row['note'] as String?,
+ createdAt = DateTime.tryParse(row['createdAt'] as String? ?? '');
+ final String id, batchId, projectId, projectName, conversationId;
+ final String conversationTitle, askerName, question, unblocks;
+ final List<String> options;
+ final int recommended;
+
+ /// The option the reader chose; null while it is open.
+ final int? choice;
+ final String? note;
+ final DateTime? createdAt;
+}
+
+/// The reader's decisions in one Swarm: open and answered, read from the
+/// backend whenever the open count moves or the Swarm changes while one is
+/// open. One per controller, as the reader's tags are (notifications.dart).
+class SuperTabDecisions extends ChangeNotifier {
+ SuperTabDecisions._(this.controller) {
+ controller.addListener(_changed);
+ _changed();
+ }
+
+ static final _all = Expando<SuperTabDecisions>();
+ static SuperTabDecisions of(SuperTabController controller) =>
+ _all[controller] ??= SuperTabDecisions._(controller);
+
+ final SuperTabController controller;
+ List<SuperTabDecision> open = const [], answered = const [];
+ String? error;
+
+ /// Decisions being answered: their buttons wait for the backend.
+ final Set<String> answering = {};
+ int? _count;
+ int _lastChangedAt = -1;
+ Future<void>? _loading;
+ bool _dirty = false;
+
+ String get _path =>
+ '/api/super-tabs/${Uri.encodeComponent(controller.tabId)}';
+
+ /// The open ones asked in [projectId]'s conversations, for its Chat with PM.
+ List<SuperTabDecision> openIn(String projectId) => [
+ for (final d in open)
+ if (d.projectId == projectId) d,
+ ];
+
+ void _changed() {
+ final snapshot = controller.snapshot;
+ if (snapshot == null) return;
+ final count = snapshot.decisionsWaiting;
+ final moved = count != _count;
+ if (!moved && controller.lastChangedAt == _lastChangedAt) return;
+ _lastChangedAt = controller.lastChangedAt;
+ _count = count;
+ // Nothing open and nothing just answered: an idle Swarm reads nothing.
+ if (count == 0 && !moved) return;
+ unawaited(load());
+ }
+
+ /// Joins a read under way, and has it read once more when asked again.
+ Future<void> load() {
+ if (_loading case final running?) {
+ _dirty = true;
+ return running;
+ }
+ return _loading = () async {
+ do {
+ _dirty = false;
+ await _read();
+ } while (_dirty);
+ }().whenComplete(() => _loading = null);
+ }
+
+ Future<List<SuperTabDecision>> _list(String state) async {
+ final Map<String, dynamic> answer;
+ try {
+ answer = await controller.request('GET', '$_path/decisions?state=$state');
+ } on SuperTabFailure catch (failure) {
+ // A backend from before decisions has no list: there is nothing to show.
+ if (failure.statusCode == 404) return const [];
+ rethrow;
+ }
+ return List.unmodifiable([
+ for (final row in answer['decisions'] as List)
+ SuperTabDecision.fromJson(superTabMap(row)),
+ ]);
+ }
+
+ Future<void> _read() async {
+ try {
+ final [nextOpen, nextAnswered] = await Future.wait([
+ _list('open'),
+ _list('answered'),
+ ]);
+ open = nextOpen;
+ answered = nextAnswered;
+ error = null;
+ } catch (_) {
+ error = 'Could not load decisions. Try again.';
+ }
+ notifyListeners();
+ }
+
+ /// The reader's one-tap answer. Any reader may answer what was asked of
+ /// them, so this does not wait behind the composer's pending send.
+ Future<bool> answer(SuperTabDecision decision, int choice) async {
+ answering.add(decision.id);
+ notifyListeners();
+ try {
+ await controller.request(
+ 'POST',
+ '$_path/commands',
+ body: {
+ 'operationId': superTabOperationId(),
+ 'command': {
+ 'type': 'decision.answer',
+ 'decisionId': decision.id,
+ 'choice': choice,
+ },
+ },
+ );
+ } catch (_) {
+ error = 'Could not send your answer. Try again.';
+ return false;
+ } finally {
+ answering.remove(decision.id);
+ notifyListeners();
+ }
+ await load();
+ unawaited(controller.refresh());
+ return true;
+ }
+}
diff --git a/desktop/lib/super_tabs/decisions_view.dart b/desktop/lib/super_tabs/decisions_view.dart
new file mode 100644
index 000000000..90b91c0e1
--- /dev/null
+++ b/desktop/lib/super_tabs/decisions_view.dart
@@ -0,0 +1,172 @@
+import 'dart:async';
+
+import 'package:flutter/material.dart';
+
+import '../shared/theme/app_theme.dart' as grid;
+import '../widgets/desktop_chrome.dart';
+import 'decisions.dart';
+import 'section_heading.dart';
+
+/// The reader's decisions in the Notifications pane: what is open first, one
+/// batch per ask, then the last few answered.
+class SuperTabDecisionList extends StatelessWidget {
+ const SuperTabDecisionList({super.key, required this.decisions});
+ final SuperTabDecisions decisions;
+
+ /// How many answered decisions stay in view.
+ static const answeredShown = 5;
+
+ @override
+ Widget build(BuildContext context) => ListenableBuilder(
+ listenable: decisions,
+ builder: (context, _) {
+ grid.AppTheme.watch(context);
+ final d = decisions;
+ return Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ const Padding(
+ padding: EdgeInsets.fromLTRB(12, 16, 12, 4),
+ child: SuperTabSectionHeading('Decisions', endInset: 0),
+ ),
+ if (d.error case final error?) _note(error),
+ if (d.open.isEmpty) _note('No decisions waiting for you.'),
+ ..._batches(d),
+ for (final answered in d.answered.take(answeredShown))
+ SuperTabDecisionCard(decisions: d, decision: answered),
+ ],
+ );
+ },
+ );
+
+ Iterable<Widget> _batches(SuperTabDecisions d) sync* {
+ String? batch;
+ for (final decision in d.open) {
+ if (decision.batchId != batch) {
+ batch = decision.batchId;
+ final count = d.open.where((o) => o.batchId == batch).length;
+ // The reader's own chat with the PM is named as the sidebar names it,
+ // not by the reader's own name (as notifications.dart does).
+ final place =
+ d.controller.pmChat(decision.projectId)?.id ==
+ decision.conversationId
+ ? 'Chat with PM'
+ : decision.conversationTitle;
+ yield _note(
+ '${decision.askerName} asked $count '
+ '${count == 1 ? 'question' : 'questions'} · '
+ '${decision.projectName} · $place',
+ );
+ }
+ yield SuperTabDecisionCard(decisions: d, decision: decision);
+ }
+ }
+
+ static Widget _note(String text) => Padding(
+ padding: const EdgeInsets.fromLTRB(16, 6, 16, 4),
+ child: Text(text, style: DesktopChrome.metadata()),
+ );
+}
+
+/// The open decisions asked in one project, above its Chat with PM.
+class SuperTabDecisionsPanel extends StatelessWidget {
+ const SuperTabDecisionsPanel({
+ super.key,
+ required this.decisions,
+ required this.projectId,
+ });
+ final SuperTabDecisions decisions;
+ final String projectId;
+
+ @override
+ Widget build(BuildContext context) => ListenableBuilder(
+ listenable: decisions,
+ builder: (context, _) {
+ grid.AppTheme.watch(context);
+ final open = decisions.openIn(projectId);
+ if (open.isEmpty) return const SizedBox.shrink();
+ return ConstrainedBox(
+ constraints: const BoxConstraints(maxHeight: 320),
+ child: ListView(
+ key: const ValueKey('super-pm-decisions'),
+ shrinkWrap: true,
+ padding: const EdgeInsets.only(bottom: 8),
+ children: [
+ const Padding(
+ padding: EdgeInsets.fromLTRB(12, 12, 12, 4),
+ child: SuperTabSectionHeading('Decisions for you', endInset: 0),
+ ),
+ for (final decision in open)
+ SuperTabDecisionCard(decisions: decisions, decision: decision),
+ ],
+ ),
+ );
+ },
+ );
+}
+
+/// One question: what it unblocks, and one button per option, the
+/// recommended one marked. Answered, it shows the choice instead.
+class SuperTabDecisionCard extends StatelessWidget {
+ const SuperTabDecisionCard({
+ super.key,
+ required this.decisions,
+ required this.decision,
+ });
+ final SuperTabDecisions decisions;
+ final SuperTabDecision decision;
+
+ @override
+ Widget build(BuildContext context) {
+ final choice = decision.choice;
+ return Container(
+ key: ValueKey('super-decision-${decision.id}'),
+ margin: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
+ padding: const EdgeInsets.fromLTRB(12, 10, 12, 10),
+ decoration: BoxDecoration(
+ color: DesktopChrome.surface,
+ border: Border.all(color: DesktopChrome.rim),
+ borderRadius: BorderRadius.circular(DesktopChrome.rowRadius),
+ ),
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Text(decision.question, style: DesktopChrome.control(medium: true)),
+ const SizedBox(height: 2),
+ Text(
+ 'Unblocks: ${decision.unblocks}',
+ style: DesktopChrome.metadata(),
+ ),
+ const SizedBox(height: 8),
+ if (choice != null)
+ Text(
+ 'You chose: ${decision.options.elementAtOrNull(choice) ?? ''}',
+ style: DesktopChrome.control(color: DesktopChrome.muted),
+ )
+ else
+ Wrap(
+ spacing: 8,
+ runSpacing: 6,
+ children: [
+ for (final (index, option) in decision.options.indexed)
+ _option(index, option),
+ ],
+ ),
+ ],
+ ),
+ );
+ }
+
+ Widget _option(int index, String option) {
+ final recommended = index == decision.recommended;
+ final busy = decisions.answering.contains(decision.id);
+ final onPressed = busy
+ ? null
+ : () => unawaited(decisions.answer(decision, index));
+ final label = Text(recommended ? '$option · Recommended' : option);
+ final key = ValueKey('super-decision-${decision.id}-$index');
+ return recommended
+ ? FilledButton.tonal(key: key, onPressed: onPressed, child: label)
+ : OutlinedButton(key: key, onPressed: onPressed, child: label);
+ }
+}
diff --git a/desktop/lib/super_tabs/leaderboard/column.dart b/desktop/lib/super_tabs/leaderboard/column.dart
new file mode 100644
index 000000000..bfab65b4c
--- /dev/null
+++ b/desktop/lib/super_tabs/leaderboard/column.dart
@@ -0,0 +1,183 @@
+import 'dart:async';
+
+import 'package:flutter/material.dart';
+
+import '../../shared/theme/app_theme.dart' as grid;
+import '../../shared/widgets/app_select_field.dart';
+import '../../shared/widgets/skeleton.dart';
+import '../../widgets/desktop_chrome.dart';
+import '../pane_layout.dart';
+import 'format.dart';
+import 'goal_bar.dart';
+import 'person_row.dart';
+import 'reader.dart';
+import 'waiting_line.dart';
+
+/// The Swarm's human leaderboard, a fixed-width column on the right: the team
+/// goal, everyone's three numbers this week with medals for the top three, and
+/// who agents wait on now. People compete for fun; the reward is shared.
+class SuperTabLeaderboardColumn extends StatefulWidget {
+ const SuperTabLeaderboardColumn({
+ super.key,
+ required this.reader,
+ required this.projectId,
+ required this.viewerId,
+ required this.nameOf,
+ required this.onAnswer,
+ this.now = DateTime.now,
+ });
+
+ static const width = SuperTabPaneLayout.boardWidth;
+
+ final SuperTabLeaderboardReader reader;
+ final String projectId, viewerId;
+ final String Function(String personId) nameOf;
+
+ /// Opens a conversation where an agent waits on a person.
+ final ValueChanged<String> onAnswer;
+ final DateTime Function() now;
+
+ @override
+ State<SuperTabLeaderboardColumn> createState() =>
+ _SuperTabLeaderboardColumnState();
+}
+
+class _SuperTabLeaderboardColumnState extends State<SuperTabLeaderboardColumn> {
+ String? _open;
+
+ @override
+ void initState() {
+ super.initState();
+ unawaited(widget.reader.show(widget.projectId));
+ }
+
+ @override
+ void didUpdateWidget(SuperTabLeaderboardColumn old) {
+ super.didUpdateWidget(old);
+ if (old.reader != widget.reader) old.reader.hide();
+ if (old.projectId != widget.projectId || old.reader != widget.reader) {
+ _open = null;
+ unawaited(widget.reader.show(widget.projectId));
+ }
+ }
+
+ @override
+ void dispose() {
+ widget.reader.hide();
+ super.dispose();
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ grid.AppTheme.watch(context);
+ return ListenableBuilder(
+ listenable: widget.reader,
+ builder: (context, _) {
+ final reader = widget.reader, board = reader.board;
+ final current = leaderboardWeekOf(widget.now());
+ final top = board?.people.firstOrNull?.points ?? 0;
+ return ColoredBox(
+ color: DesktopChrome.surface,
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ _Header(
+ week: reader.week,
+ current: current,
+ onWeek: (week) =>
+ reader.showWeek(week == current ? null : week),
+ ),
+ if (reader.error != null)
+ Padding(
+ padding: const EdgeInsets.fromLTRB(16, 0, 16, 8),
+ child: Text(reader.error!, style: DesktopChrome.metadata()),
+ ),
+ if (board == null)
+ const Expanded(
+ child: SkeletonList(
+ rows: 5,
+ padding: EdgeInsets.symmetric(horizontal: 16),
+ ),
+ )
+ else ...[
+ LeaderboardGoalBar(
+ goal: board.goal,
+ weekName: weekName(reader.week, current),
+ ),
+ Expanded(
+ child: ListView(
+ padding: const EdgeInsets.symmetric(horizontal: 8),
+ children: [
+ for (final person in board.people)
+ LeaderboardPersonRow(
+ score: person,
+ name: widget.nameOf(person.personId),
+ topPoints: top,
+ open: _open == person.personId,
+ onTap: () => setState(
+ () => _open = _open == person.personId
+ ? null
+ : person.personId,
+ ),
+ ),
+ ],
+ ),
+ ),
+ LeaderboardWaitingLine(
+ waiting: board.waiting,
+ viewerId: widget.viewerId,
+ nameOf: widget.nameOf,
+ onAnswer: widget.onAnswer,
+ ),
+ ],
+ ],
+ ),
+ );
+ },
+ );
+ }
+}
+
+class _Header extends StatelessWidget {
+ const _Header({
+ required this.week,
+ required this.current,
+ required this.onWeek,
+ });
+ final int? week;
+ final int current;
+ final ValueChanged<int> onWeek;
+
+ @override
+ Widget build(BuildContext context) => Padding(
+ padding: const EdgeInsets.fromLTRB(16, 12, 12, 8),
+ child: Row(
+ children: [
+ Expanded(
+ child: Text(
+ 'Humans · ${weekName(week, current)}',
+ // As the People pane's section headings, beside it.
+ style: DesktopChrome.metadata().copyWith(
+ fontWeight: FontWeight.w600,
+ ),
+ ),
+ ),
+ AppSelectField<int>(
+ key: const ValueKey('leaderboard-week'),
+ value: week ?? current,
+ width: 120,
+ height: DesktopChrome.compactControlHeight,
+ semanticLabel: 'Week',
+ options: [
+ for (var back = 0; back < 4; back++)
+ SelectOption(
+ value: current - back * weekMs,
+ label: capitalized(weekName(current - back * weekMs, current)),
+ ),
+ ],
+ onChanged: onWeek,
+ ),
+ ],
+ ),
+ );
+}
diff --git a/desktop/lib/super_tabs/leaderboard/format.dart b/desktop/lib/super_tabs/leaderboard/format.dart
new file mode 100644
index 000000000..9bbf8dbb1
--- /dev/null
+++ b/desktop/lib/super_tabs/leaderboard/format.dart
@@ -0,0 +1,43 @@
+/// How the leaderboard writes its numbers.
+library;
+
+const _minute = 60000, _hour = 3600000;
+const weekMs = 7 * 86400000;
+
+/// "6 min" under an hour, then hours with one decimal unless whole: "3 h", "3.1 h".
+String leaderboardDuration(int ms) {
+ if (ms < _hour) return '${(ms / _minute).round()} min';
+ final hours = ms / _hour;
+ final rounded = (hours * 10).round() / 10;
+ return rounded == rounded.roundToDouble()
+ ? '${rounded.round()} h'
+ : '${rounded.toStringAsFixed(1)} h';
+}
+
+/// Whole agent-hours, as the points count them.
+String leaderboardHours(int ms) => '${(ms / _hour).round()}';
+
+String plural(int count, String one, [String? many]) =>
+ '$count ${count == 1 ? one : many ?? '${one}s'}';
+
+/// "this week", "last week", "2 weeks ago", from the week's Monday and this one.
+String weekName(int? week, int currentWeek) {
+ final back = week == null ? 0 : ((currentWeek - week) / weekMs).round();
+ return switch (back) {
+ 0 => 'this week',
+ 1 => 'last week',
+ _ => '$back weeks ago',
+ };
+}
+
+/// The Monday 00:00 UTC of the week [now] is in.
+int leaderboardWeekOf(DateTime now) {
+ final utc = now.toUtc();
+ final day = DateTime.utc(utc.year, utc.month, utc.day);
+ return day
+ .subtract(Duration(days: day.weekday - DateTime.monday))
+ .millisecondsSinceEpoch;
+}
+
+String capitalized(String text) =>
+ text.isEmpty ? text : '${text[0].toUpperCase()}${text.substring(1)}';
diff --git a/desktop/lib/super_tabs/leaderboard/goal_bar.dart b/desktop/lib/super_tabs/leaderboard/goal_bar.dart
new file mode 100644
index 000000000..88d39b8f1
--- /dev/null
+++ b/desktop/lib/super_tabs/leaderboard/goal_bar.dart
@@ -0,0 +1,68 @@
+import 'package:flutter/material.dart';
+
+import '../../widgets/desktop_chrome.dart';
+import 'format.dart';
+import 'model.dart';
+import 'progress_bar.dart';
+
+/// The shared reward on top: the project's open requests and this week against
+/// the one before. Everyone's points count toward it.
+class LeaderboardGoalBar extends StatelessWidget {
+ const LeaderboardGoalBar({
+ super.key,
+ required this.goal,
+ required this.weekName,
+ });
+ final SuperTabTeamGoal goal;
+
+ /// "this week", "last week", …: the week the board shows.
+ final String weekName;
+
+ @override
+ Widget build(BuildContext context) {
+ final now = goal.thisWeek, before = goal.lastWeek;
+ final earlier = weekName == 'this week' ? 'last week' : 'the week before';
+ final median = _median(now.medianAskToShipMs, before.medianAskToShipMs);
+ return Container(
+ margin: const EdgeInsets.fromLTRB(12, 0, 12, 8),
+ padding: const EdgeInsets.all(12),
+ decoration: BoxDecoration(
+ color: DesktopChrome.field,
+ borderRadius: BorderRadius.circular(DesktopChrome.rowRadius),
+ border: Border.all(color: DesktopChrome.rim),
+ ),
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Text(
+ 'Team goal · ${plural(goal.openRequests, 'open request')}',
+ style: DesktopChrome.control(medium: true),
+ ),
+ const SizedBox(height: 6),
+ LeaderboardProgressBar(
+ fraction: now.points == 0
+ ? 0
+ : now.points /
+ (now.points > before.points ? now.points : before.points),
+ ),
+ const SizedBox(height: 6),
+ Text(
+ '${now.shipped} shipped $weekName (${before.shipped} $earlier) · ${plural(now.points, 'point')}',
+ style: DesktopChrome.metadata(),
+ ),
+ if (median != null) Text(median, style: DesktopChrome.metadata()),
+ ],
+ ),
+ );
+ }
+
+ static String? _median(int? now, int? before) {
+ if (now == null) return null;
+ final text = 'Median ask to ship ${leaderboardDuration(now)}';
+ if (before == null) return text;
+ if (leaderboardDuration(now) == leaderboardDuration(before)) {
+ return '$text, as before';
+ }
+ return '$text, ${now < before ? 'down' : 'up'} from ${leaderboardDuration(before)}';
+ }
+}
diff --git a/desktop/lib/super_tabs/leaderboard/model.dart b/desktop/lib/super_tabs/leaderboard/model.dart
new file mode 100644
index 000000000..f17925161
--- /dev/null
+++ b/desktop/lib/super_tabs/leaderboard/model.dart
@@ -0,0 +1,98 @@
+/// The leaderboard read's answer, mirrored by hand from the backend's
+/// `backend/src/superTabs/leaderboard/contract.ts`. People are member ids; the
+/// column names them from the members the Swarm already shows.
+library;
+
+enum SuperTabMedal { gold, silver, bronze }
+
+int _int(Object? value) => value is num ? value.round() : 0;
+int? _optional(Object? value) => value is num ? value.round() : null;
+Map<String, dynamic> _map(Object? value) =>
+ value is Map ? value.cast<String, dynamic>() : const {};
+List<Map<String, dynamic>> _list(Object? value) =>
+ value is List ? value.whereType<Map>().map(_map).toList() : const [];
+
+class SuperTabLeaderboard {
+ SuperTabLeaderboard.fromJson(Map<String, dynamic> json)
+ : projectId = json['projectId'] as String? ?? '',
+ week = _int(json['week']),
+ goal = SuperTabTeamGoal.fromJson(_map(json['goal'])),
+ people = _list(json['people']).map(SuperTabPersonScore.fromJson).toList(),
+ waiting = SuperTabWaiting.fromJson(_map(json['waiting']));
+
+ final String projectId;
+
+ /// The week's Monday 00:00 UTC, in epoch milliseconds.
+ final int week;
+ final SuperTabTeamGoal goal;
+
+ /// Most points first.
+ final List<SuperTabPersonScore> people;
+ final SuperTabWaiting waiting;
+}
+
+class SuperTabWeekGoal {
+ SuperTabWeekGoal.fromJson(Map<String, dynamic> json)
+ : shipped = _int(json['shipped']),
+ points = _int(json['points']),
+ medianAskToShipMs = _optional(json['medianAskToShipMs']);
+ final int shipped, points;
+ final int? medianAskToShipMs;
+}
+
+class SuperTabTeamGoal {
+ SuperTabTeamGoal.fromJson(Map<String, dynamic> json)
+ : openRequests = _int(json['openRequests']),
+ thisWeek = SuperTabWeekGoal.fromJson(_map(json['thisWeek'])),
+ lastWeek = SuperTabWeekGoal.fromJson(_map(json['lastWeek']));
+ final int openRequests;
+ final SuperTabWeekGoal thisWeek, lastWeek;
+}
+
+class SuperTabPersonScore {
+ SuperTabPersonScore.fromJson(Map<String, dynamic> json)
+ : personId = json['personId'] as String? ?? '',
+ points = _int(json['points']),
+ rank = _int(json['rank']),
+ medal = SuperTabMedal.values.asNameMap()[json['medal']],
+ shipped = _int(_map(json['shipped'])['count']),
+ medianAskToShipMs = _optional(_map(json['shipped'])['medianAskToShipMs']),
+ unblocked = _int(_map(json['unblocked'])['count']),
+ unblockedMs = _int(_map(json['unblocked'])['agentMs']),
+ medianAnswerMs = _optional(_map(json['unblocked'])['medianAnswerMs']),
+ lentMachines = _int(_map(json['lent'])['machines']),
+ lentMs = _int(_map(json['lent'])['agentMs']),
+ streakDays = _int(json['streakDays']);
+
+ final String personId;
+ final int points, rank;
+ final SuperTabMedal? medal;
+ final int shipped, unblocked, lentMachines, streakDays;
+
+ /// Agent time the person's answers freed, and agent time run on their machines.
+ final int unblockedMs, lentMs;
+ final int? medianAskToShipMs, medianAnswerMs;
+}
+
+class SuperTabWaitingPerson {
+ SuperTabWaitingPerson.fromJson(Map<String, dynamic> json)
+ : personId = json['personId'] as String? ?? '',
+ count = _int(json['count']),
+ conversationIds = (json['conversationIds'] as List? ?? const [])
+ .whereType<String>()
+ .toList();
+ final String personId;
+ final int count;
+ final List<String> conversationIds;
+}
+
+/// Who agents wait on now: counts in name order, never a ranking.
+class SuperTabWaiting {
+ SuperTabWaiting.fromJson(Map<String, dynamic> json)
+ : total = _int(json['total']),
+ people = _list(json['people'])
+ .map(SuperTabWaitingPerson.fromJson)
+ .toList();
+ final int total;
+ final List<SuperTabWaitingPerson> people;
+}
diff --git a/desktop/lib/super_tabs/leaderboard/person_row.dart b/desktop/lib/super_tabs/leaderboard/person_row.dart
new file mode 100644
index 000000000..80798b491
--- /dev/null
+++ b/desktop/lib/super_tabs/leaderboard/person_row.dart
@@ -0,0 +1,176 @@
+import 'package:flutter/material.dart';
+
+import '../../widgets/desktop_chrome.dart';
+import '../identity.dart';
+import 'format.dart';
+import 'model.dart';
+import 'progress_bar.dart';
+
+/// Where the name starts: after the medal (24) and the avatar (20) with its gap (6).
+const _nameInset = 50.0;
+
+const _medals = {
+ SuperTabMedal.gold: '🏆',
+ SuperTabMedal.silver: '🥈',
+ SuperTabMedal.bronze: '🥉',
+};
+
+/// One person: medal, name, points bar and their three numbers; tapped, their week.
+class LeaderboardPersonRow extends StatelessWidget {
+ const LeaderboardPersonRow({
+ super.key,
+ required this.score,
+ required this.name,
+ required this.topPoints,
+ required this.open,
+ required this.onTap,
+ });
+ final SuperTabPersonScore score;
+ final String name;
+ final int topPoints;
+ final bool open;
+ final VoidCallback onTap;
+
+ /// Today's Swarm avatar, sized for the shared avatar widget (v2 H) to drop in here.
+ Widget _avatar() => SuperTabAvatar(
+ identity: 'person:${score.personId}',
+ name: name,
+ size: 20,
+ );
+
+ @override
+ Widget build(BuildContext context) {
+ final lent = score.lentMachines == 0
+ ? '—'
+ : plural(score.lentMachines, 'machine');
+ return InkWell(
+ key: ValueKey('leaderboard-person-${score.personId}'),
+ borderRadius: BorderRadius.circular(DesktopChrome.rowRadius),
+ onTap: onTap,
+ child: Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 8),
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Row(
+ children: [
+ SizedBox(width: 24, child: Text(_medals[score.medal] ?? '')),
+ _avatar(),
+ const SizedBox(width: 6),
+ Flexible(
+ child: Text(
+ name,
+ overflow: TextOverflow.ellipsis,
+ style: DesktopChrome.control(medium: true),
+ ),
+ ),
+ if (score.streakDays > 1) ...[
+ const SizedBox(width: 6),
+ Text(
+ '🔥 ${score.streakDays}',
+ style: DesktopChrome.metadata(),
+ ),
+ ],
+ const SizedBox(width: 8),
+ Expanded(
+ child: LeaderboardProgressBar(
+ fraction: topPoints == 0 ? 0 : score.points / topPoints,
+ ),
+ ),
+ const SizedBox(width: 8),
+ Text('${score.points} pts', style: DesktopChrome.control()),
+ ],
+ ),
+ Padding(
+ padding: const EdgeInsets.only(left: _nameInset, top: 2),
+ child: Text(
+ '🚀 ${score.shipped} shipped 🔓 ${score.unblocked} ⚡ $lent',
+ style: DesktopChrome.metadata(),
+ ),
+ ),
+ AnimatedSize(
+ duration: const Duration(milliseconds: 200),
+ curve: Curves.easeOutCubic,
+ alignment: Alignment.topCenter,
+ child: open
+ ? _Detail(score: score)
+ : const SizedBox(width: double.infinity),
+ ),
+ ],
+ ),
+ ),
+ );
+ }
+}
+
+/// A person's week, as the mockup's "Tap a name" card.
+class _Detail extends StatelessWidget {
+ const _Detail({required this.score});
+ final SuperTabPersonScore score;
+
+ @override
+ Widget build(BuildContext context) {
+ String median(int? ms, String what) =>
+ ms == null ? '' : ' · median ${leaderboardDuration(ms)}$what';
+ final rows = [
+ (
+ '🚀 Shipped',
+ score.shipped == 0
+ ? 'Nothing landed yet'
+ : '${plural(score.shipped, 'ask')} landed${median(score.medianAskToShipMs, ' to ship')}',
+ ),
+ (
+ '🔓 Unblocked',
+ score.unblocked == 0
+ ? 'Nothing answered yet'
+ : '${score.unblocked} answered${median(score.medianAnswerMs, '')} · ${leaderboardDuration(score.unblockedMs)} of agent time freed',
+ ),
+ (
+ '⚡ Lent',
+ score.lentMachines == 0
+ ? 'Nothing lent yet'
+ : '${plural(score.lentMachines, 'machine')} · ${leaderboardHours(score.lentMs)} slot-hours',
+ ),
+ (
+ '🔥 Streak',
+ score.streakDays == 0
+ ? 'No streak yet'
+ : '${plural(score.streakDays, 'day')} shipping',
+ ),
+ ];
+ return Container(
+ width: double.infinity,
+ margin: const EdgeInsets.only(left: _nameInset, top: 8),
+ padding: const EdgeInsets.all(10),
+ decoration: BoxDecoration(
+ color: DesktopChrome.field,
+ borderRadius: BorderRadius.circular(DesktopChrome.rowRadius),
+ border: Border.all(color: DesktopChrome.rim),
+ ),
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ for (final (label, value) in rows)
+ Padding(
+ padding: const EdgeInsets.symmetric(vertical: 2),
+ child: Row(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ SizedBox(
+ width: 88,
+ child: Text(
+ label,
+ style: DesktopChrome.metadata(
+ color: DesktopChrome.foreground,
+ ),
+ ),
+ ),
+ Expanded(child: Text(value, style: DesktopChrome.metadata())),
+ ],
+ ),
+ ),
+ ],
+ ),
+ );
+ }
+}
diff --git a/desktop/lib/super_tabs/leaderboard/progress_bar.dart b/desktop/lib/super_tabs/leaderboard/progress_bar.dart
new file mode 100644
index 000000000..594379dd0
--- /dev/null
+++ b/desktop/lib/super_tabs/leaderboard/progress_bar.dart
@@ -0,0 +1,38 @@
+import 'package:flutter/material.dart';
+
+import '../../widgets/desktop_chrome.dart';
+
+/// A thin rounded bar that glides to its new length when the board refreshes.
+class LeaderboardProgressBar extends StatelessWidget {
+ const LeaderboardProgressBar({
+ super.key,
+ required this.fraction,
+ this.height = 6,
+ });
+ final double fraction;
+ final double height;
+
+ @override
+ Widget build(BuildContext context) => ClipRRect(
+ borderRadius: BorderRadius.circular(height),
+ child: SizedBox(
+ height: height,
+ child: ColoredBox(
+ color: DesktopChrome.rim,
+ child: Align(
+ alignment: Alignment.centerLeft,
+ child: TweenAnimationBuilder<double>(
+ tween: Tween(end: fraction.clamp(0, 1).toDouble()),
+ duration: const Duration(milliseconds: 450),
+ curve: Curves.easeOutCubic,
+ builder: (context, value, _) => FractionallySizedBox(
+ widthFactor: value,
+ heightFactor: 1,
+ child: ColoredBox(color: DesktopChrome.accent),
+ ),
+ ),
+ ),
+ ),
+ ),
+ );
+}
diff --git a/desktop/lib/super_tabs/leaderboard/reader.dart b/desktop/lib/super_tabs/leaderboard/reader.dart
new file mode 100644
index 000000000..20d92059d
--- /dev/null
+++ b/desktop/lib/super_tabs/leaderboard/reader.dart
@@ -0,0 +1,93 @@
+import 'dart:async';
+
+import 'package:flutter/foundation.dart';
+
+import '../controller.dart';
+import 'model.dart';
+
+/// Reads one project's leaderboard while the column is shown, and again every
+/// minute: the board sums a week, so it moves slowly. A failed refresh keeps the
+/// last board and says why.
+class SuperTabLeaderboardReader extends ChangeNotifier {
+ SuperTabLeaderboardReader({
+ required this.tabId,
+ required this.request,
+ this.every = const Duration(minutes: 1),
+ });
+
+ final String tabId;
+ final SuperTabRequest request;
+ final Duration every;
+
+ SuperTabLeaderboard? board;
+ String? error;
+ String? _projectId;
+ int? _week;
+ int _read = 0;
+ Timer? _timer;
+ bool _disposed = false;
+
+ /// The Monday 00:00 UTC of the week shown; null for this week.
+ int? get week => _week;
+
+ /// Shows another week, null for this one.
+ Future<void> showWeek(int? week) {
+ if (week == _week) return Future.value();
+ _week = week;
+ // Another week's numbers under this week's name would mislead until the read lands.
+ board = null;
+ _notify();
+ return refresh();
+ }
+
+ /// Shows [projectId]'s board, read now and then every [every].
+ Future<void> show(String projectId) {
+ if (projectId != _projectId) {
+ _projectId = projectId;
+ board = null;
+ error = null;
+ }
+ _timer ??= Timer.periodic(every, (_) => unawaited(refresh()));
+ return refresh();
+ }
+
+ /// Stops the minute refresh while the column is not shown; the board stays.
+ void hide() {
+ _timer?.cancel();
+ _timer = null;
+ }
+
+ Future<void> refresh() async {
+ final projectId = _projectId;
+ if (projectId == null || _disposed) return;
+ final read = ++_read, week = _week;
+ try {
+ final answer = await request(
+ 'GET',
+ '/api/super-tabs/${Uri.encodeComponent(tabId)}/leaderboard'
+ '?projectId=${Uri.encodeQueryComponent(projectId)}'
+ '${week == null ? '' : '&week=$week'}',
+ );
+ if (read != _read) return;
+ board = SuperTabLeaderboard.fromJson(answer);
+ error = null;
+ } catch (failure) {
+ if (read != _read) return;
+ error = failure is SuperTabFailure
+ ? failure.message
+ : "Couldn't read the leaderboard.";
+ }
+ _notify();
+ }
+
+ void _notify() {
+ if (!_disposed) notifyListeners();
+ }
+
+ @override
+ void dispose() {
+ _disposed = true;
+ _timer?.cancel();
+ super.dispose();
+ }
+}
diff --git a/desktop/lib/super_tabs/leaderboard/swarm_board.dart b/desktop/lib/super_tabs/leaderboard/swarm_board.dart
new file mode 100644
index 000000000..c1015287d
--- /dev/null
+++ b/desktop/lib/super_tabs/leaderboard/swarm_board.dart
@@ -0,0 +1,69 @@
+import 'dart:async';
+
+import 'package:flutter/material.dart';
+
+import '../../shared/widgets/app_dialog.dart';
+import '../../widgets/desktop_chrome.dart';
+import '../controller.dart';
+import '../identity.dart';
+import 'column.dart';
+import 'reader.dart';
+
+/// The leaderboard of the Swarm a [SuperTabController] shows: the project of
+/// the selected conversation, people named as the roster names them, Answer
+/// opening the waiting conversation.
+class SuperTabSwarmBoard {
+ SuperTabSwarmBoard(this.controller)
+ : reader = SuperTabLeaderboardReader(
+ tabId: controller.tabId,
+ request: controller.request,
+ );
+
+ final SuperTabController controller;
+ final SuperTabLeaderboardReader reader;
+
+ /// A window this wide, scaled, has room for the column beside People.
+ static const columnFrom = 1380.0;
+
+ String get _projectId =>
+ controller.snapshot?.projectFor(controller.selectedId)?.id ?? 'lead';
+
+ String _name(String personId) {
+ final person = controller.snapshot?.people
+ .where((p) => p.id == personId)
+ .firstOrNull;
+ return person == null ? 'Former member' : superTabPersonName(person.email);
+ }
+
+ Widget column({required ValueChanged<String> onAnswer}) =>
+ SuperTabLeaderboardColumn(
+ reader: reader,
+ projectId: _projectId,
+ viewerId: controller.accountId,
+ nameOf: _name,
+ onAnswer: onAnswer,
+ );
+
+ /// For a window without room for the column.
+ Future<void> openDialog(BuildContext context) => showAppDialog<void>(
+ context: context,
+ builder: (dialog) => Dialog(
+ shape: DesktopChrome.shape(),
+ child: SizedBox(
+ width: SuperTabLeaderboardColumn.width,
+ height: (MediaQuery.sizeOf(dialog).height - 120).clamp(320, 640),
+ child: ClipRRect(
+ borderRadius: BorderRadius.circular(DesktopChrome.dialogRadius),
+ child: column(
+ onAnswer: (id) {
+ Navigator.of(dialog).pop();
+ unawaited(controller.select(id));
+ },
+ ),
+ ),
+ ),
+ ),
+ );
+
+ void dispose() => reader.dispose();
+}
diff --git a/desktop/lib/super_tabs/leaderboard/waiting_line.dart b/desktop/lib/super_tabs/leaderboard/waiting_line.dart
new file mode 100644
index 000000000..0f51235d2
--- /dev/null
+++ b/desktop/lib/super_tabs/leaderboard/waiting_line.dart
@@ -0,0 +1,70 @@
+import 'package:flutter/material.dart';
+
+import '../../widgets/desktop_chrome.dart';
+import 'model.dart';
+
+/// "Agents waiting on a person now": who and how many, in name order, never a
+/// ranking or blame. Answer goes straight to the viewer's own waiting item, or
+/// to the first one when none waits on them.
+class LeaderboardWaitingLine extends StatelessWidget {
+ const LeaderboardWaitingLine({
+ super.key,
+ required this.waiting,
+ required this.viewerId,
+ required this.nameOf,
+ required this.onAnswer,
+ });
+ final SuperTabWaiting waiting;
+ final String viewerId;
+ final String Function(String personId) nameOf;
+ final ValueChanged<String> onAnswer;
+
+ String? get _target {
+ final own = waiting.people.where((p) => p.personId == viewerId).firstOrNull;
+ return (own ?? waiting.people.firstOrNull)?.conversationIds.firstOrNull;
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ final target = _target;
+ return Container(
+ key: const ValueKey('leaderboard-waiting'),
+ padding: const EdgeInsets.fromLTRB(16, 10, 12, 12),
+ decoration: BoxDecoration(
+ border: Border(top: BorderSide(color: DesktopChrome.rim)),
+ ),
+ child: waiting.total == 0
+ ? Text(
+ 'No agent is waiting on a person.',
+ style: DesktopChrome.metadata(),
+ )
+ : Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ // The whole width, so the count never wraps beside Answer.
+ Text(
+ '⏳ Agents waiting on a person now: ${waiting.total}',
+ style: DesktopChrome.control(),
+ ),
+ Row(
+ children: [
+ Expanded(
+ child: Text(
+ waiting.people
+ .map((p) => '${nameOf(p.personId)} ${p.count}')
+ .join(' · '),
+ style: DesktopChrome.metadata(),
+ ),
+ ),
+ if (target != null)
+ TextButton(
+ onPressed: () => onAnswer(target),
+ child: const Text('Answer'),
+ ),
+ ],
+ ),
+ ],
+ ),
+ );
+ }
+}
diff --git a/desktop/lib/super_tabs/machines.dart b/desktop/lib/super_tabs/machines.dart
index 8761b33df..86654bd72 100644
--- a/desktop/lib/super_tabs/machines.dart
+++ b/desktop/lib/super_tabs/machines.dart
@@ -931,8 +931,8 @@ class _SuperTabMachinesState extends State<SuperTabMachines> {
final person = snapshot.people
.where((p) => p.id == contributor)
.firstOrNull;
- final teammateView = team != null && contributor != c.accountId;
- final reading = teammateView ? team : shared;
+ final reading = snapshot.readingPoolOf(id, c.accountId);
+ final teammateView = team != null && identical(reading, team);
final readId = teammateView ? teamId! : id;
final state = app?.stateOf(readId);
final observation = superTabMap(
diff --git a/desktop/lib/super_tabs/model.dart b/desktop/lib/super_tabs/model.dart
index 3a8f49ff7..2bf399c03 100644
--- a/desktop/lib/super_tabs/model.dart
+++ b/desktop/lib/super_tabs/model.dart
@@ -51,6 +51,7 @@ class SuperTabAgent {
role = row['role'] as String?,
roleId = row['roleId'] as String?,
limitedUntil = DateTime.tryParse(row['limitedUntil'] as String? ?? ''),
+ downSince = DateTime.tryParse(row['downSince'] as String? ?? ''),
configuration = Map.unmodifiable(superTabMap(row['configuration']));
final String id, projectId, name, machineId, harnessId, contributorId;
@@ -58,6 +59,10 @@ class SuperTabAgent {
/// (spec/2026-10-23-lead-sees-agent-terminal.md). Null when none was seen.
final DateTime? limitedUntil;
+ /// Since when its machine has reported its session gone, or its host confirmed a stop (backend machines.ts). Null
+ /// while it runs.
+ final DateTime? downSince;
+
/// The account whose computer runs it; a contributor may run agents on a computer another account shared with them.
final String machineOwnerId;
// Keep the legacy default for callers while allowing group-based roster ownership.
@@ -214,8 +219,18 @@ class SuperTabSnapshot {
(row) => Map<String, dynamic>.unmodifiable(row),
),
leadsConversationId = row['leadsConversationId'] as String?,
+ startEfforts = Map.unmodifiable({
+ for (final start
+ in row['starts'] is List ? row['starts'] as List : const [])
+ if (start case {
+ 'harnessId': final String harness,
+ 'request': {'effort': final String effort},
+ })
+ harness: effort,
+ }),
localModels = SuperTabLocalModels.read(row['localModels']),
- mentionsWaiting = (row['mentionsWaiting'] as num?)?.toInt() ?? 0 {
+ mentionsWaiting = (row['mentionsWaiting'] as num?)?.toInt() ?? 0,
+ decisionsWaiting = (row['decisionsWaiting'] as num?)?.toInt() ?? 0 {
if (row['version'] != 1) {
throw const FormatException('Update Harness to open this Swarm.');
}
@@ -246,6 +261,10 @@ class SuperTabSnapshot {
late final List<SuperTabProject> projects;
final List<Map<String, dynamic>> invitations;
+ /// The effort each started agent's start asked for, by harness id. Empty where the starts are not read (a view
+ /// kept on this device leaves them out).
+ final Map<String, String> startEfforts;
+
/// Where the projects' Product Managers talk, Swarm-wide; null in a Swarm
/// from before it (spec 2026-10-23-leads-see-and-talk.md).
final String? leadsConversationId;
@@ -256,6 +275,10 @@ class SuperTabSnapshot {
/// The reader's tags still waiting for them, Swarm-wide; 0 from a backend
/// before tags (spec 2026-10-24-lead-mentions.md).
final int mentionsWaiting;
+
+ /// Decisions asked of the reader and not yet answered, Swarm-wide; 0 from a
+ /// backend before decisions (backend superTabs/decisions.ts).
+ final int decisionsWaiting;
SuperTabConversation? conversation(String id) =>
conversations.where((c) => c.id == id).firstOrNull;
SuperTabAgent? agent(String id) =>
@@ -348,6 +371,20 @@ class SuperTabSnapshot {
return best;
}
+ /// The pool whose reading [accountId] sees for the machine row [machineId]: the Mac's Harness Team account for
+ /// everyone but the Mac's own contributor, since it runs their agents, also while the owner is away from the Mac; the
+ /// machine's own pool otherwise. The Machines view and Team at a glance read a machine by this one rule.
+ Map<String, dynamic>? readingPoolOf(String machineId, String? accountId) {
+ final own = pool(machineId), team = teamPoolOf(machineId);
+ final contributor =
+ own?['contributorId'] as String? ??
+ agents
+ .where((a) => placeOf(a.machineId) == machineId)
+ .firstOrNull
+ ?.contributorId;
+ return team != null && contributor != accountId ? team : own;
+ }
+
/// The machine [machineId] is shown as in this Swarm, one row per computer: the Mac, for its Harness Team account
/// while that Mac is in the Swarm too; [machineId] itself otherwise.
String placeOf(String machineId) => _macOf(pool(machineId)) ?? machineId;
diff --git a/desktop/lib/super_tabs/notifications.dart b/desktop/lib/super_tabs/notifications.dart
index b3417d346..7009e5341 100644
--- a/desktop/lib/super_tabs/notifications.dart
+++ b/desktop/lib/super_tabs/notifications.dart
@@ -186,11 +186,15 @@ class SuperTabNotifications extends StatefulWidget {
required this.mentions,
required this.onOpen,
this.now = DateTime.now,
+ this.leading,
});
final SuperTabMentions mentions;
final ValueChanged<SuperTabMention> onOpen;
final DateTime Function() now;
+ /// Shown first in the same list: the reader's decisions (decisions_view.dart).
+ final Widget? leading;
+
@override
State<SuperTabNotifications> createState() => _SuperTabNotificationsState();
}
@@ -325,6 +329,7 @@ class _SuperTabNotificationsState extends State<SuperTabNotifications> {
],
),
),
+ ?widget.leading,
_heading('Waiting'),
if (m.waiting.isEmpty) _empty('Nothing waiting for you.'),
for (final mention in m.waiting) _row(mention, waiting: true),
diff --git a/desktop/lib/super_tabs/pane_layout.dart b/desktop/lib/super_tabs/pane_layout.dart
index 35fab0cf6..c58a1eebf 100644
--- a/desktop/lib/super_tabs/pane_layout.dart
+++ b/desktop/lib/super_tabs/pane_layout.dart
@@ -18,6 +18,7 @@ class SuperTabPaneLayout extends StatefulWidget {
required this.onLeave,
this.left,
this.right,
+ this.board,
this.storage,
});
@@ -33,6 +34,11 @@ class SuperTabPaneLayout extends StatefulWidget {
static double drawerWidth(double available) =>
(available * drawerMaxFraction).clamp(0, rightWidth).toDouble();
final Widget? left, right;
+
+ /// The leaderboard, a fixed column at the far right beside [right]; the
+ /// resizable panes share what is left.
+ final Widget? board;
+ static const boardWidth = 300.0;
final Widget center;
final VoidCallback onLeave;
final LocalKeyValueStore? storage;
@@ -91,7 +97,27 @@ class _SuperTabPaneLayoutState extends State<SuperTabPaneLayout> {
}
@override
- Widget build(BuildContext context) => LayoutBuilder(
+ Widget build(BuildContext context) {
+ final board = widget.board;
+ if (board == null) return _panes();
+ return Row(
+ children: [
+ Expanded(child: _panes()),
+ SizedBox(
+ width: 1,
+ height: double.infinity,
+ child: ColoredBox(color: DesktopChrome.rim),
+ ),
+ SizedBox(
+ key: const ValueKey('super-board-pane'),
+ width: SuperTabPaneLayout.boardWidth,
+ child: board,
+ ),
+ ],
+ );
+ }
+
+ Widget _panes() => LayoutBuilder(
builder: (context, constraints) {
final width = constraints.maxWidth;
final scale = MediaQuery.textScalerOf(context);
diff --git a/desktop/lib/super_tabs/parts.dart b/desktop/lib/super_tabs/parts.dart
index 76aa2308e..f788de9dd 100644
--- a/desktop/lib/super_tabs/parts.dart
+++ b/desktop/lib/super_tabs/parts.dart
@@ -259,6 +259,9 @@ class SuperTabParts {
if (_derived['mentionsWaiting'] case final num waiting) {
state['mentionsWaiting'] = waiting.toInt();
}
+ if (_derived['decisionsWaiting'] case final num waiting) {
+ state['decisionsWaiting'] = waiting.toInt();
+ }
return state;
}
diff --git a/desktop/lib/super_tabs/project_sidebar.dart b/desktop/lib/super_tabs/project_sidebar.dart
index bb88dfcdc..25f1249b1 100644
--- a/desktop/lib/super_tabs/project_sidebar.dart
+++ b/desktop/lib/super_tabs/project_sidebar.dart
@@ -508,7 +508,9 @@ class ProjectSidebar extends StatelessWidget {
icon: AppIcons.bell,
onTap: onNotifications,
selected: notificationsSelected,
- badge: snapshot?.mentionsWaiting ?? 0,
+ badge:
+ (snapshot?.mentionsWaiting ?? 0) +
+ (snapshot?.decisionsWaiting ?? 0),
),
if (onNewProject != null ||
onYourDevices != null ||
diff --git a/desktop/lib/super_tabs/roles_editor.dart b/desktop/lib/super_tabs/roles_editor.dart
index 03bc9d45b..56d47a028 100644
--- a/desktop/lib/super_tabs/roles_editor.dart
+++ b/desktop/lib/super_tabs/roles_editor.dart
@@ -47,6 +47,7 @@ Keep each Builder's list a few tasks deep; do the easy, self-contained parts fir
## 3. Route, start, assign
- Route each group; reuse an idle agent before starting one; start only on the Swarm's machines.
+- With 3 or more groups waiting, run plan first: it places them all at once on the best machines and models. Then route each group in the plan's order and start the plan's pick, with overrideReason "scheduler plan" when the route picks otherwise. If plan cannot run here, route as usual.
- Local models: the route may pick one for low-difficulty, well-specified work; set "local":true only when a person asks for one, set "model" to a model a person names, and start it with the route's gridModel and gridName.
- The brief is all a Builder gets; never rely on chat history.
- Before assigning, look at other projects' active work; if your task touches the same code, say so in the Leads conversation and agree an order first.
@@ -57,9 +58,12 @@ Keep each Builder's list a few tasks deep; do the easy, self-contained parts fir
- When a worker seems stuck, read its terminal; answer prompts within its task; ask the owner before approving anything risky.
- A Builder or Reviewer that has been down for 2 hours (its machine offline, its session gone, or stopped): cancel its task with the reason, route it, and assign it to another agent with what the first one left (branch, last revision, last report).
- When you are told a task is lost, hand it on at once: route it and assign it to another agent, avoiding what failed (another machine if its machine died, another account or engine if it hit a usage limit). The new brief tells the successor to continue from the lost attempt's pushed branch and last result, not to start over.
+- A task lost to a usage limit resumes by itself in the same session when the limit resets (its wake-up says when). Hand it on at once only to another account or engine with allowance now, with its pushed branch and last progress note.
+- Morning digest: when a person asks for one, set the project's digest to their local time and time zone ("project.digest" with time "08:00" and timeZone "Asia/Ho_Chi_Minh"). When it wakes you, check that each pull request under Shipped is merged, then post one message to the people in the project chat.
- Work with no progress for 6 hours goes back to you: reassign it or cut it smaller.
- Needs a person: get the decision now. Blocked: change something (context, model, size or plan); never resend the same thing.
- When you need a person to act or decide, tag them in the message.
+- Ask people for decisions in one place: decision.ask puts up to 10 questions to one person at once, each with 2 to 5 options, the one you recommend and what the answer unblocks. Keep working on your recommendation, marked provisional, until they answer: a notice in that conversation tells you, and harness super-tab decisions --answered shows the answer. A decision is not a private channel: anything private goes through Chat with PM.
- Settle ambiguities you can and record "Ruling: what — why — cost if wrong".
- When a worker finishes: reuse, keep or stop. Prefer stop.
@@ -77,6 +81,10 @@ When the project owner asks in chat to switch this project's skills (Default or
- Answer questions, blockers and completions at once.
- Every post carries a result, a decision asked for with your recommendation, a question, or a fault; never an acknowledgement alone.
- Write like a colleague: short, in their language, no commands or internal ids. Call the roles Product Manager, Engineer and Reviewer.
+
+## Requests and Done
+- When you open a group for a person's request, asked in the project chat or in their Chat with PM, name them as its requester: requesterId on conversation.create, or conversation.requester for a group already open. It records only that they asked, never what they wrote.
+- Mark a group Done only after its pull request has merged: the leaderboard counts a request as shipped once its group is Done with a linked PR.
''';
const _defaultEngineer = r'''---
@@ -111,6 +119,7 @@ You finish one group's work completely, inside its brief, as if nobody will come
## 3. Blocked
- A person's decision: mark needs-human with one short question.
+- When you know who decides, add ask to that needs-human (the person, 2 to 5 options, the one you recommend, what it unblocks) and keep working on your recommendation, marked provisional, until a notice says it was answered; read the answer with harness super-tab decisions --answered.
- Can't go on: mark blocked with why and what would unblock you, then do the independent parts.
- Stop and ask before anything irreversible, security-sensitive, outside your worktree, visible or audible on a real device, or moving hardware.
diff --git a/desktop/lib/super_tabs/roster.dart b/desktop/lib/super_tabs/roster.dart
index 795b6930b..0628c4d26 100644
--- a/desktop/lib/super_tabs/roster.dart
+++ b/desktop/lib/super_tabs/roster.dart
@@ -2,9 +2,11 @@ import 'dart:async';
import 'package:flutter/material.dart';
+import '../shared/theme/app_icons.dart';
import '../shared/theme/app_theme.dart' as grid;
import '../shared/theme/appearance_prefs_store.dart';
import '../shared/widgets/app_dialog.dart';
+import '../shared/widgets/app_icon_button.dart';
import '../state/app_state.dart';
import '../state/harness_activity.dart';
import '../terminal/terminal_theme.dart';
@@ -19,6 +21,8 @@ import 'dialog_scope.dart';
import 'identity.dart';
import 'model.dart';
import 'section_heading.dart';
+import 'team_glance.dart';
+import 'team_glance_panel.dart';
/// The current Swarm's authorized people, with agents from the selected project.
class SuperTabRoster extends StatefulWidget {
@@ -265,6 +269,8 @@ class _SuperTabRosterState extends State<SuperTabRoster> {
Widget _agent(SuperTabAgent agent) {
final name = c.snapshot!.agentName(agent.id), activity = _activity(agent);
final info = SuperTabAgentInfo(c, widget.app, agent, activity: activity);
+ // One line, readable in a second (Dee, 2026-10-27): state, machine, model and effort. The task is in the tooltip.
+ final glance = superTabAgentGlance(info);
final project = c.snapshot!.projects
.where((p) => p.id == _agentProjectId(agent))
.firstOrNull;
@@ -368,7 +374,8 @@ class _SuperTabRosterState extends State<SuperTabRoster> {
const SizedBox(width: 6),
Expanded(
child: Text(
- status,
+ glance.line,
+ key: ValueKey('super-member-line-${agent.id}'),
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: DesktopChrome.metadata(),
@@ -491,6 +498,14 @@ class _SuperTabRosterState extends State<SuperTabRoster> {
? () => widget.onAddAgent(c.selected!)
: null,
addTooltip: 'Add agent',
+ actions: [
+ AppIconButton(
+ icon: AppIcons.layoutGrid,
+ tooltip: 'Team at a glance',
+ onPressed: () =>
+ unawaited(showSuperTabTeamGlance(context, c, widget.app)),
+ ),
+ ],
),
for (final agent in [...leads, ...agents]) _agent(agent),
];
diff --git a/desktop/lib/super_tabs/team_glance.dart b/desktop/lib/super_tabs/team_glance.dart
new file mode 100644
index 000000000..1d6bedc8d
--- /dev/null
+++ b/desktop/lib/super_tabs/team_glance.dart
@@ -0,0 +1,276 @@
+import '../state/app_state.dart';
+import '../state/harness_activity.dart';
+import 'agent_details.dart';
+import 'controller.dart';
+import 'machine_status.dart';
+
+/// Team at a glance (Dee, 2026-10-27: "it's hard to monitor the team"): where every agent runs, on which model and
+/// effort, and whether the spread makes sense. Read from the Swarm the person already sees, so nobody sees an agent
+/// or a machine they could not see before.
+
+/// An agent's state in a word. [waiting]: on a person (a question, needs-human work, an input prompt). [assigned]:
+/// holding a task with no turn seen running: a task can outlive its turn or connection, so it never reads as working.
+enum SuperTabAgentState {
+ working,
+ assigned,
+ stuck,
+ review,
+ checking,
+ waiting,
+ idle,
+ down,
+ lost,
+ limited,
+ starting,
+ paused,
+}
+
+/// One agent in one line: "Working · Mac Studio · opus high".
+class SuperTabAgentGlance {
+ const SuperTabAgentGlance({
+ required this.state,
+ required this.label,
+ required this.machine,
+ required this.model,
+ required this.effort,
+ required this.busy,
+ this.recordedEffort,
+ this.requestedEffort,
+ });
+
+ final SuperTabAgentState state;
+
+ /// The state as shown: one word, or "Limited until 09:05".
+ final String label;
+ final String? machine, model;
+
+ /// The effort to show: the recorded one, else its start's, else "unknown".
+ final String effort;
+
+ /// Holding a task: what the Swarm counts as this agent's load.
+ final bool busy;
+
+ /// The effort the agent's configuration records, and the one its start asked for; null when not known.
+ final String? recordedEffort, requestedEffort;
+
+ /// "opus high"; null when the model is not known (an agent read before it reported one).
+ String? get modelEffort => model == null ? null : '$model $effort';
+
+ String get line => [label, ?machine, ?modelEffort].join(' · ');
+}
+
+/// An effort that says which one runs. 'auto' is what Claude Code reports for an effort it was launched with, and
+/// 'default' what a start asks when it leaves the engine's own: neither names one.
+String? _concrete(Object? effort) =>
+ effort is String &&
+ effort.isNotEmpty &&
+ effort != 'auto' &&
+ effort != 'default'
+ ? effort
+ : null;
+
+const _activeWork = {
+ 'planned',
+ 'working',
+ 'review',
+ 'reconciling',
+ 'needs_human',
+ 'blocked',
+};
+
+SuperTabAgentGlance superTabAgentGlance(
+ SuperTabAgentInfo info, {
+ DateTime? now,
+}) {
+ final at = now ?? DateTime.now();
+ final agent = info.agent;
+ final work = info.taskGroup?.assignment?['status'];
+ final activity = info.activity;
+ final until = agent.limitedUntil?.toLocal();
+ String two(int n) => n.toString().padLeft(2, '0');
+ final (state, label) = switch (null) {
+ _ when work == 'lost' => (SuperTabAgentState.lost, 'Lost'),
+ _
+ when agent.downSince != null ||
+ activity == HarnessActivity.offline ||
+ activity == HarnessActivity.failed =>
+ (SuperTabAgentState.down, 'Down'),
+ _ when until != null && until.isAfter(at) => (
+ SuperTabAgentState.limited,
+ 'Limited until ${two(until.hour)}:${two(until.minute)}',
+ ),
+ _ when activity == HarnessActivity.starting => (
+ SuperTabAgentState.starting,
+ 'Starting',
+ ),
+ _ when activity == HarnessActivity.paused => (
+ SuperTabAgentState.paused,
+ 'Stopped',
+ ),
+ // Before waiting: the sidebar marks blocked work as needing input too.
+ _ when work == 'blocked' => (SuperTabAgentState.stuck, 'Stuck'),
+ _
+ when info.hasQuestion ||
+ work == 'needs_human' ||
+ activity == HarnessActivity.needsInput =>
+ (SuperTabAgentState.waiting, 'Waiting'),
+ _ when work == 'review' => (SuperTabAgentState.review, 'In review'),
+ _ when work == 'reconciling' => (SuperTabAgentState.checking, 'Checking'),
+ _ when activity == HarnessActivity.working => (
+ SuperTabAgentState.working,
+ 'Working',
+ ),
+ _ when work == 'planned' || work == 'working' => (
+ SuperTabAgentState.assigned,
+ 'Assigned',
+ ),
+ _ when activity == HarnessActivity.done => (
+ SuperTabAgentState.idle,
+ 'Finished',
+ ),
+ _ => (SuperTabAgentState.idle, 'Idle'),
+ };
+ final recorded = _concrete(agent.configuration['effort']);
+ final requested = _concrete(
+ info.controller.snapshot?.startEfforts[agent.harnessId],
+ );
+ return SuperTabAgentGlance(
+ state: state,
+ label: label,
+ machine: info.machine,
+ model: info.model,
+ effort: recorded ?? requested ?? 'unknown',
+ busy: _activeWork.contains(work),
+ recordedEffort: recorded,
+ requestedEffort: requested,
+ );
+}
+
+/// A machine of the Swarm with the agents on it. [status] is null for a machine the Swarm has no reading of.
+class SuperTabGlanceMachine {
+ SuperTabGlanceMachine(
+ this.id,
+ this.name,
+ this.status,
+ this.total,
+ this.free, {
+ this.paused = false,
+ });
+ final String id, name;
+ final SuperTabMachineStatus? status;
+ final int? total, free;
+ final bool paused;
+ final agents = <(String, SuperTabAgentGlance)>[];
+ bool get online =>
+ status == SuperTabMachineStatus.live ||
+ status == SuperTabMachineStatus.late;
+ int get busy => agents.where((a) => a.$2.busy).length;
+}
+
+class SuperTabTeamGlance {
+ SuperTabTeamGlance._(this.machines, this.models, this.warnings);
+
+ final List<SuperTabGlanceMachine> machines;
+
+ /// "opus high" and how many agents run it, most first.
+ final List<(String, int)> models;
+ final List<String> warnings;
+
+ factory SuperTabTeamGlance.of(
+ SuperTabController c,
+ AppNotifier? app, {
+ DateTime? now,
+ }) {
+ final at = now ?? DateTime.now();
+ final snapshot = c.snapshot;
+ if (snapshot == null) {
+ return SuperTabTeamGlance._(const [], const [], const []);
+ }
+ final machines = <String, SuperTabGlanceMachine>{};
+ for (final pool in snapshot.machines) {
+ final id = pool['machineId'] as String? ?? '';
+ // A Mac's Harness Team account is that Mac (SuperTabSnapshot.placeOf).
+ if (id.isEmpty || snapshot.placeOf(id) != id) continue;
+ // As the Machines view reads it: a teammate reads a Mac by its Harness Team account (review of #1759).
+ final reading = snapshot.readingPoolOf(id, c.accountId) ?? pool;
+ final received = (reading['observation'] as Map?)?['receivedAt'];
+ final total = (reading['maxAgents'] as num?)?.toInt();
+ machines[id] = SuperTabGlanceMachine(
+ id,
+ pool['name'] as String? ?? 'Unnamed machine',
+ superTabMachineStatus(
+ age: received is num
+ ? at.difference(
+ DateTime.fromMillisecondsSinceEpoch(received.toInt()),
+ )
+ : null,
+ ),
+ total,
+ (reading['availableSlots'] as num?)?.toInt(),
+ // A paused machine, or a paused Swarm, takes no new work.
+ paused:
+ snapshot.paused ||
+ pool['paused'] == true ||
+ reading['paused'] == true,
+ );
+ }
+ final models = <String, int>{};
+ final warnings = <String>[];
+ for (final agent in snapshot.agents) {
+ final info = SuperTabAgentInfo(c, app, agent);
+ final glance = superTabAgentGlance(info, now: at);
+ final name = snapshot.agentName(agent.id);
+ final place = snapshot.placeOf(agent.machineId);
+ (machines[place] ??= SuperTabGlanceMachine(
+ place,
+ glance.machine ?? 'Unknown machine',
+ null,
+ null,
+ null,
+ )).agents.add((name, glance));
+ final model = glance.modelEffort ?? 'Model not reported';
+ models[model] = (models[model] ?? 0) + 1;
+ if (glance.recordedEffort case final recorded?
+ when glance.requestedEffort != null &&
+ recorded != glance.requestedEffort) {
+ warnings.add(
+ '$name runs effort $recorded; its start asked for ${glance.requestedEffort}.',
+ );
+ }
+ }
+ for (final machine in machines.values) {
+ if (machine.status != SuperTabMachineStatus.offline) continue;
+ for (final (name, _) in machine.agents.where((a) => a.$2.busy)) {
+ warnings.add('$name is busy on ${machine.name}, which is offline.');
+ }
+ }
+ if (_pileUp(machines.values.toList()) case final warning?) {
+ warnings.insert(0, warning);
+ }
+ return SuperTabTeamGlance._(
+ machines.values.toList(),
+ (models.entries.map((e) => (e.key, e.value)).toList()
+ ..sort((a, b) => b.$2.compareTo(a.$2))),
+ warnings,
+ );
+ }
+}
+
+/// More than half the busy agents on one machine while an online one, not paused, has free slots.
+String? _pileUp(List<SuperTabGlanceMachine> machines) {
+ final busy = machines.fold(0, (sum, m) => sum + m.busy);
+ if (busy < 2) return null;
+ final crowded = machines.reduce((a, b) => a.busy >= b.busy ? a : b);
+ if (crowded.busy * 2 <= busy) return null;
+ int free(SuperTabGlanceMachine m) =>
+ m.free ?? ((m.total ?? 0) - m.agents.length).clamp(0, 1 << 30);
+ final room =
+ machines
+ .where((m) => m != crowded && m.online && !m.paused && free(m) > 0)
+ .toList()
+ ..sort((a, b) => free(b).compareTo(free(a)));
+ if (room.isEmpty) return null;
+ final slots = free(room.first);
+ return '${crowded.busy} of $busy busy agents are on ${crowded.name}, while ${room.first.name} has $slots free '
+ 'slot${slots == 1 ? '' : 's'}.';
+}
diff --git a/desktop/lib/super_tabs/team_glance_panel.dart b/desktop/lib/super_tabs/team_glance_panel.dart
new file mode 100644
index 000000000..22e4d4915
--- /dev/null
+++ b/desktop/lib/super_tabs/team_glance_panel.dart
@@ -0,0 +1,151 @@
+import 'package:flutter/material.dart';
+
+import '../shared/theme/app_icons.dart';
+import '../shared/theme/app_theme.dart' as grid;
+import '../shared/widgets/app_dialog.dart';
+import '../state/app_state.dart';
+import '../widgets/desktop_chrome.dart';
+import 'controller.dart';
+import 'machine_status.dart';
+import 'team_glance.dart';
+
+/// Opens Team at a glance over the Swarm, live: it follows the Swarm as it changes.
+Future<void> showSuperTabTeamGlance(
+ BuildContext context,
+ SuperTabController c,
+ AppNotifier? app,
+) => showAppDialog<void>(
+ context: context,
+ builder: (context) => AlertDialog(
+ title: const Text('Team at a glance'),
+ content: ListenableBuilder(
+ listenable: Listenable.merge([c, ?app]),
+ builder: (context, _) =>
+ SuperTabTeamGlancePanel(glance: SuperTabTeamGlance.of(c, app)),
+ ),
+ actions: [
+ TextButton(
+ onPressed: () => Navigator.pop(context),
+ child: const Text('Close'),
+ ),
+ ],
+ ),
+);
+
+/// The glance as one column of at most [width], so another panel (a leaderboard) can sit beside it; narrower on a
+/// phone.
+class SuperTabTeamGlancePanel extends StatelessWidget {
+ const SuperTabTeamGlancePanel({super.key, required this.glance});
+ final SuperTabTeamGlance glance;
+ static const width = 420.0;
+
+ @override
+ Widget build(BuildContext context) {
+ grid.AppTheme.watch(context);
+ Widget heading(String text) => Padding(
+ padding: const EdgeInsets.only(top: 16, bottom: 6),
+ child: Text(
+ text,
+ style: DesktopChrome.metadata().copyWith(fontWeight: FontWeight.w600),
+ ),
+ );
+ return ConstrainedBox(
+ constraints: const BoxConstraints(maxWidth: width),
+ child: SingleChildScrollView(
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ if (glance.warnings.isEmpty)
+ Text('Nothing looks wrong.', style: DesktopChrome.metadata())
+ else
+ for (final warning in glance.warnings) _Warning(warning),
+ heading('Machines'),
+ for (final machine in glance.machines) _Machine(machine),
+ heading('Models'),
+ Column(
+ key: const ValueKey('glance-models'),
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ for (final (model, count) in glance.models)
+ Text('$model · $count', style: DesktopChrome.control()),
+ ],
+ ),
+ ],
+ ),
+ ),
+ );
+ }
+}
+
+class _Warning extends StatelessWidget {
+ const _Warning(this.text);
+ final String text;
+
+ @override
+ Widget build(BuildContext context) => Padding(
+ padding: const EdgeInsets.only(bottom: 6),
+ child: Row(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Icon(
+ AppIcons.triangleAlert,
+ size: 16,
+ color: grid.AppPalette.warn,
+ ),
+ const SizedBox(width: 6),
+ Expanded(child: Text(text, style: DesktopChrome.control())),
+ ],
+ ),
+ );
+}
+
+class _Machine extends StatelessWidget {
+ const _Machine(this.machine);
+ final SuperTabGlanceMachine machine;
+
+ String get _summary {
+ final state = switch (machine.status) {
+ null => 'Not reported',
+ SuperTabMachineStatus.offline => 'Offline',
+ SuperTabMachineStatus.late => 'Late',
+ _ => 'Online',
+ };
+ final total = machine.total;
+ if (total == null) return state;
+ final used = machine.free == null
+ ? machine.agents.length
+ : total - machine.free!;
+ return '$state · $used of $total slots used';
+ }
+
+ @override
+ Widget build(BuildContext context) => Padding(
+ key: ValueKey('glance-machine-${machine.id}'),
+ padding: const EdgeInsets.only(bottom: 10),
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Wrap(
+ spacing: 8,
+ crossAxisAlignment: WrapCrossAlignment.end,
+ children: [
+ Text(machine.name, style: DesktopChrome.control()),
+ Text(_summary, style: DesktopChrome.metadata()),
+ ],
+ ),
+ if (machine.agents.isEmpty)
+ Text('No agents', style: DesktopChrome.metadata())
+ else
+ for (final (name, agent) in machine.agents)
+ Padding(
+ padding: const EdgeInsets.only(left: 12),
+ child: Text(
+ '$name · ${agent.label}',
+ style: DesktopChrome.metadata(),
+ ),
+ ),
+ ],
+ ),
+ );
+}
diff --git a/desktop/lib/super_tabs/view.dart b/desktop/lib/super_tabs/view.dart
index 788ccba4f..a5ea121e6 100644
--- a/desktop/lib/super_tabs/view.dart
+++ b/desktop/lib/super_tabs/view.dart
@@ -25,12 +25,15 @@ import 'workgroup_name.dart';
import 'message_row.dart';
import 'message_receipt.dart';
import 'notifications.dart';
+import 'decisions.dart';
+import 'decisions_view.dart';
import 'route_row.dart';
import 'terminal_row.dart';
import 'work_details.dart';
import 'project_sidebar.dart';
import 'project_options.dart';
import 'pane_layout.dart';
+import 'leaderboard/swarm_board.dart';
import '../widgets/dial_list_scroll.dart';
typedef _ComposerChoice = ({String label, String? detail, VoidCallback choose});
@@ -85,6 +88,12 @@ class _SuperTabViewState extends State<SuperTabView>
bool _sidebarOpen = false;
bool _rosterOpen = false;
bool _showPullRequests = false;
+
+ /// The human leaderboard (v2 G), read only once it is first opened; a column
+ /// when the window has room for it ([_boardRoomy], set by build), else a dialog.
+ bool _boardOpen = false, _boardRoomy = false;
+ SuperTabSwarmBoard? _boardRead;
+ SuperTabSwarmBoard get _board => _boardRead ??= SuperTabSwarmBoard(c);
bool _showNotifications = false;
// The message a tag opened, scrolled to once it is laid out.
String? _target;
@@ -331,6 +340,7 @@ class _SuperTabViewState extends State<SuperTabView>
_composer.dispose();
_focus.dispose();
_pullRequestsFocus.dispose();
+ _boardRead?.dispose();
for (final scroll in _scroll.values) {
scroll.dispose();
}
@@ -943,6 +953,21 @@ class _SuperTabViewState extends State<SuperTabView>
);
}
+ Widget _boardButton() {
+ final shown = _boardRoomy && _boardOpen;
+ return AppIconButton(
+ key: const ValueKey('super-leaderboard'),
+ icon: AppIcons.trophy,
+ size: AppIcons.inlineSize,
+ tooltip: 'Leaderboard',
+ selected: shown,
+ color: shown ? DesktopChrome.foreground : DesktopChrome.muted,
+ onPressed: _boardRoomy
+ ? () => setState(() => _boardOpen = !_boardOpen)
+ : () => unawaited(_board.openDialog(context)),
+ );
+ }
+
/// On a phone the header's bar holds Chat and ⋮, each a finger's size, and
/// ⋮ names the rest (terminals, pull requests, people) instead of five bare
/// icons. Desktop, which sets no [WorkspaceChrome.compactBelow], never.
@@ -1132,6 +1157,7 @@ class _SuperTabViewState extends State<SuperTabView>
_options(group, views: _menuNamesViews),
),
],
+ fingerTarget(enabled: _phone, _boardButton()),
if (!showRoster)
fingerTarget(
enabled: _phone,
@@ -1476,6 +1502,12 @@ class _SuperTabViewState extends State<SuperTabView>
],
),
),
+ // The reader's own chat with the PM shows what the PM asked them.
+ if (group != null && _isPmChat(group))
+ SuperTabDecisionsPanel(
+ decisions: SuperTabDecisions.of(c),
+ projectId: group.projectId,
+ ),
Expanded(
child: c.loading
? const Center(child: CircularProgressIndicator())
@@ -1986,6 +2018,9 @@ class _SuperTabViewState extends State<SuperTabView>
_readVisibleTailAfterFrame();
}
_chatCovered = chatCovered;
+ _boardRoomy =
+ constraints.maxWidth >=
+ MediaQuery.textScalerOf(context).scale(SuperTabSwarmBoard.columnFrom);
final roster = SuperTabRoster(
controller: c,
app: widget.app,
@@ -2011,6 +2046,14 @@ class _SuperTabViewState extends State<SuperTabView>
onLeave: _leaveResize,
left: narrow ? null : _sidebar(),
right: showRoster ? roster : null,
+ board: _boardRoomy && _boardOpen
+ ? _board.column(
+ onAnswer: (id) {
+ setState(() => _showPullRequests = false);
+ unawaited(c.select(id));
+ },
+ )
+ : null,
center: Column(
children: [
_header(c.selected, narrow, showRoster),
@@ -2042,6 +2085,9 @@ class _SuperTabViewState extends State<SuperTabView>
mentions: SuperTabMentions.of(c),
onOpen: (mention) =>
unawaited(_openMention(mention)),
+ leading: SuperTabDecisionList(
+ decisions: SuperTabDecisions.of(c),
+ ),
)
: const SizedBox.shrink(),
],
diff --git a/desktop/test/super_tab_decisions_test.dart b/desktop/test/super_tab_decisions_test.dart
new file mode 100644
index 000000000..cc78622b4
--- /dev/null
+++ b/desktop/test/super_tab_decisions_test.dart
@@ -0,0 +1,228 @@
+import 'dart:io';
+import 'dart:ui' as ui;
+
+import 'package:flutter/material.dart';
+import 'package:flutter/rendering.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/shared/theme/app_theme.dart' as grid;
+import 'package:harness/super_tabs/decisions.dart';
+import 'package:harness/super_tabs/model.dart';
+import 'package:harness/super_tabs/view.dart';
+
+import 'box_render_preview_test.dart' show loadPreviewFonts;
+import 'support/super_tab_fixture.dart';
+
+/// Set to a folder to write the PR's screenshots there.
+final shots = Platform.environment['SUPER_TAB_DECISION_SHOTS'];
+final _picture = GlobalKey();
+
+Future<void> shot(WidgetTester tester, String name) async {
+ if (shots == null) return;
+ await tester.runAsync(() async {
+ final boundary =
+ _picture.currentContext!.findRenderObject()! as RenderRepaintBoundary;
+ final image = await boundary.toImage();
+ final bytes = await image.toByteData(format: ui.ImageByteFormat.png);
+ await Directory(shots!).create(recursive: true);
+ await File('$shots/$name.png').writeAsBytes(bytes!.buffer.asUint8List());
+ image.dispose();
+ });
+}
+
+/// A Swarm whose reader is the peer, with the Lead and the peer's own Chat
+/// with PM in the first project.
+ConversationServer swarm() {
+ final server = ConversationServer();
+ server.state['projects'] = [projectFixture('lead', 'web-project', 'lead')];
+ server.state['people'] = [
+ {'id': 'owner', 'email': '[email protected]', 'role': 'owner'},
+ {'id': 'peer', 'email': '[email protected]', 'role': 'collaborator'},
+ ];
+ server.state['conversations'] = [
+ conversationFixture('lead', 'Lead'),
+ {
+ ...conversationFixture('pm-chat', 'ken.tran'),
+ 'projectId': 'lead',
+ 'audience': {
+ 'people': [
+ {'id': 'peer', 'generation': 'g1'},
+ ],
+ },
+ },
+ ];
+ return server;
+}
+
+Future<void> showView(WidgetTester tester, ConversationServer server) async {
+ await tester.binding.setSurfaceSize(const Size(1200, 900));
+ addTearDown(() => tester.binding.setSurfaceSize(null));
+ final c = server.controller(account: 'peer');
+ addTearDown(c.dispose);
+ await c.refresh();
+ await tester.pumpWidget(
+ MaterialApp(
+ theme: grid.buildAppTheme(brightness: Brightness.dark),
+ builder: (context, child) => RepaintBoundary(key: _picture, child: child),
+ home: Scaffold(
+ body: SuperTabView(
+ controller: c,
+ onInvite: () {},
+ onAddAgent: (_) {},
+ onOpenTerminal: (_) {},
+ machineName: (_) => 'Team Mac',
+ ),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ // The project's rows, Chat with PM among them, show once it is expanded.
+ if (!c.expandedProjects.contains('lead')) c.toggleProject('lead');
+ await tester.pumpAndSettle();
+}
+
+Finder notificationsEntry() =>
+ find.byKey(const ValueKey('super-notifications'));
+Finder option(String id, int index) =>
+ find.byKey(ValueKey('super-decision-$id-$index'));
+
+void main() {
+ setUpAll(() async {
+ if (shots != null) await loadPreviewFonts();
+ });
+
+ group('the reader\'s decisions', () {
+ test('the tab state counts the decisions waiting for the reader', () {
+ final server = swarm()..ask(['Ship how?', 'Name it?']);
+ expect(SuperTabSnapshot.fromJson(server.state).decisionsWaiting, 2);
+ });
+
+ test(
+ 'loads when the count moves, and one tap answers with that option',
+ () async {
+ final server = swarm()..ask(['Ship how?']);
+ final controller = server.controller(account: 'peer');
+ addTearDown(controller.dispose);
+ final decisions = SuperTabDecisions.of(controller);
+ await controller.refresh();
+ await decisions.load();
+ expect(decisions.open.single.question, 'Ship how?');
+ expect(decisions.open.single.recommended, 0);
+
+ expect(await decisions.answer(decisions.open.single, 1), isTrue);
+
+ expect(server.posts.last['command'], {
+ 'type': 'decision.answer',
+ 'decisionId': 'decision-1',
+ 'choice': 1,
+ });
+ expect(decisions.open, isEmpty);
+ expect(decisions.answered.single.choice, 1);
+ },
+ );
+ });
+
+ group('the Decisions list', () {
+ testWidgets(
+ 'lists one batch per ask, marks the recommendation, and answers with one tap',
+ (tester) async {
+ final server = swarm()..ask(['Ship how?', 'Name it?']);
+ await showView(tester, server);
+ expect(
+ find.descendant(of: notificationsEntry(), matching: find.text('2')),
+ findsOneWidget,
+ );
+ await tester.tap(notificationsEntry());
+ await tester.pumpAndSettle();
+ expect(find.text('Decisions'), findsOneWidget);
+ expect(
+ find.text('Wren asked 2 questions · web-project · Lead'),
+ findsOneWidget,
+ );
+ expect(find.text('Behind a flag · Recommended'), findsNWidgets(2));
+ expect(find.text('Unblocks: The release'), findsNWidgets(2));
+
+ await tester.tap(option('decision-2', 1));
+ await tester.pumpAndSettle();
+
+ expect(server.posts.last['command'], {
+ 'type': 'decision.answer',
+ 'decisionId': 'decision-2',
+ 'choice': 1,
+ });
+ expect(find.text('You chose: To everyone'), findsOneWidget);
+ expect(
+ find.text('Wren asked 1 question · web-project · Lead'),
+ findsOneWidget,
+ );
+ },
+ );
+
+ testWidgets('says when nothing waits', (tester) async {
+ await showView(tester, swarm());
+ await tester.tap(notificationsEntry());
+ await tester.pumpAndSettle();
+ expect(find.text('No decisions waiting for you.'), findsOneWidget);
+ });
+ });
+
+ group('Chat with PM', () {
+ testWidgets(
+ 'shows the reader\'s open decisions of that project above its messages',
+ (tester) async {
+ final server = swarm()
+ ..ask(['Ship how?'], conversationId: 'pm-chat')
+ ..ask(['Elsewhere?'], projectId: 'other');
+ await showView(tester, server);
+ await tester.tap(find.byKey(const ValueKey('super-pm-chat-lead')));
+ await tester.pumpAndSettle();
+ final panel = find.byKey(const ValueKey('super-pm-decisions'));
+ expect(panel, findsOneWidget);
+ expect(
+ find.descendant(of: panel, matching: find.text('Ship how?')),
+ findsOneWidget,
+ );
+ expect(
+ find.descendant(of: panel, matching: find.text('Elsewhere?')),
+ findsNothing,
+ );
+ // The list names the reader's own chat as the sidebar does.
+ await tester.tap(notificationsEntry());
+ await tester.pumpAndSettle();
+ expect(
+ find.text('Wren asked 1 question · web-project · Chat with PM'),
+ findsOneWidget,
+ );
+ await tester.tap(find.byKey(const ValueKey('super-pm-chat-lead')));
+ await tester.pumpAndSettle();
+
+ await tester.tap(option('decision-1', 0));
+ await tester.pumpAndSettle();
+ expect(panel, findsNothing);
+ },
+ );
+ });
+
+ testWidgets('screenshots for review', (tester) async {
+ final server = swarm()
+ ..ask([
+ 'Ship offline editing to everyone, or behind a flag first?',
+ 'Keep the old sync screen for a week?',
+ ])
+ ..ask(['Which name for the setting?'], recommended: 1);
+ server.decisions.last['options'] = ['Offline mode', 'Work offline'];
+ server.decisions.last['unblocks'] = 'The settings copy';
+ server.decisions[1]['options'] = ['Keep it a week', 'Remove it now'];
+ server.decisions[1]['unblocks'] = 'Deleting the old screen';
+ server.decisions.first['unblocks'] = 'Turning the feature on';
+ await showView(tester, server);
+ await tester.tap(notificationsEntry());
+ await tester.pumpAndSettle();
+ await shot(tester, 'decisions-list');
+ await tester.tap(option('decision-1', 0));
+ await tester.pumpAndSettle();
+ await shot(tester, 'decisions-answered');
+ await tester.tap(find.byKey(const ValueKey('super-pm-chat-lead')));
+ await tester.pumpAndSettle();
+ await shot(tester, 'chat-with-pm');
+ }, skip: shots == null);
+}
diff --git a/desktop/test/super_tab_leaderboard_mount_test.dart b/desktop/test/super_tab_leaderboard_mount_test.dart
new file mode 100644
index 000000000..e08d1bb6c
--- /dev/null
+++ b/desktop/test/super_tab_leaderboard_mount_test.dart
@@ -0,0 +1,143 @@
+import 'package:flutter/material.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/shared/theme/app_theme.dart' as grid;
+import 'package:harness/super_tabs/controller.dart';
+import 'package:harness/super_tabs/leaderboard/column.dart';
+import 'package:harness/super_tabs/view.dart';
+
+import 'support/super_tab_fixture.dart';
+
+/// Where the leaderboard opens in a Swarm (v2 G): a trophy in the conversation
+/// header shows it as a column at the far right, beside People, on a wide
+/// window, and as a dialog on a narrower one. Answer opens the waiting group.
+void main() {
+ final trophy = find.byKey(const ValueKey('super-leaderboard'));
+ final boardPane = find.byKey(const ValueKey('super-board-pane'));
+
+ ConversationServer swarm() => ConversationServer()
+ ..leaderboard = {
+ 'projectId': 'lead',
+ 'week': DateTime.utc(2026, 10, 26).millisecondsSinceEpoch,
+ 'goal': {
+ 'openRequests': 2,
+ 'thisWeek': {'shipped': 1, 'points': 3, 'medianAskToShipMs': 7200000},
+ 'lastWeek': {'shipped': 0, 'points': 0, 'medianAskToShipMs': null},
+ },
+ 'people': [
+ {
+ 'personId': 'owner',
+ 'points': 3,
+ 'rank': 1,
+ 'medal': 'gold',
+ 'shipped': {'count': 1, 'medianAskToShipMs': 7200000},
+ 'unblocked': {'count': 0, 'agentMs': 0, 'medianAnswerMs': null},
+ 'lent': {'machines': 0, 'agentMs': 0},
+ 'streakDays': 1,
+ },
+ ],
+ 'waiting': {
+ 'total': 1,
+ 'people': [
+ {
+ 'personId': 'owner',
+ 'count': 1,
+ 'conversationIds': ['offline'],
+ },
+ ],
+ },
+ };
+
+ Future<SuperTabController> show(
+ WidgetTester tester,
+ ConversationServer server,
+ Size size,
+ ) async {
+ await tester.binding.setSurfaceSize(size);
+ addTearDown(() => tester.binding.setSurfaceSize(null));
+ final controller = server.controller(
+ account: 'owner',
+ initial: {'tabId': 'tab', 'accountId': 'owner', 'selectedId': 'lead'},
+ );
+ await controller.refresh();
+ await tester.pumpWidget(
+ MaterialApp(
+ theme: grid.buildAppTheme(brightness: Brightness.dark),
+ home: Scaffold(
+ body: SuperTabView(
+ controller: controller,
+ onInvite: () {},
+ onAddAgent: (_) {},
+ onOpenTerminal: (_) {},
+ machineName: (_) => 'Studio',
+ ),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ return controller;
+ }
+
+ Future<void> close(WidgetTester tester, SuperTabController controller) async {
+ await tester.pumpWidget(const SizedBox());
+ await controller.flush();
+ controller.dispose();
+ }
+
+ testWidgets(
+ 'opens the board as a column at the far right of a wide window, and closes it again',
+ (tester) async {
+ final server = swarm();
+ final controller = await show(tester, server, const Size(1500, 800));
+ expect(boardPane, findsNothing);
+ expect(server.leaderboardReads, isEmpty);
+ await tester.tap(trophy);
+ await tester.pumpAndSettle();
+ expect(boardPane, findsOneWidget);
+ expect(tester.getSize(boardPane).width, SuperTabLeaderboardColumn.width);
+ expect(tester.getTopRight(boardPane).dx, 1500);
+ expect(find.text('Owner'), findsNothing);
+ expect(find.text('owner'), findsWidgets);
+ expect(server.leaderboardReads, [
+ '/api/super-tabs/tab/leaderboard?projectId=lead',
+ ]);
+ await tester.tap(trophy);
+ await tester.pumpAndSettle();
+ expect(boardPane, findsNothing);
+ await close(tester, controller);
+ },
+ );
+
+ testWidgets('opens the waiting group from Answer', (tester) async {
+ final server = swarm();
+ final controller = await show(tester, server, const Size(1500, 800));
+ await tester.tap(trophy);
+ await tester.pumpAndSettle();
+ await tester.tap(find.text('Answer'));
+ await tester.pumpAndSettle();
+ expect(controller.selectedId, 'offline');
+ await close(tester, controller);
+ });
+
+ testWidgets(
+ 'shows the board in a dialog when the window has no room for the column',
+ (tester) async {
+ final server = swarm();
+ final controller = await show(tester, server, const Size(1100, 800));
+ await tester.tap(trophy);
+ await tester.pumpAndSettle();
+ expect(boardPane, findsNothing);
+ expect(
+ find.descendant(
+ of: find.byType(Dialog),
+ matching: find.byType(SuperTabLeaderboardColumn),
+ ),
+ findsOneWidget,
+ );
+ await tester.tap(find.text('Answer'));
+ await tester.pumpAndSettle();
+ expect(find.byType(Dialog), findsNothing);
+ expect(controller.selectedId, 'offline');
+ await close(tester, controller);
+ },
+ );
+}
diff --git a/desktop/test/super_tab_leaderboard_test.dart b/desktop/test/super_tab_leaderboard_test.dart
new file mode 100644
index 000000000..f57ecb09f
--- /dev/null
+++ b/desktop/test/super_tab_leaderboard_test.dart
@@ -0,0 +1,410 @@
+import 'dart:async';
+
+import 'package:fake_async/fake_async.dart';
+import 'package:flutter/material.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/shared/theme/app_theme.dart' as grid;
+import 'package:harness/super_tabs/controller.dart';
+import 'package:harness/super_tabs/identity.dart';
+import 'package:harness/super_tabs/leaderboard/column.dart';
+import 'package:harness/super_tabs/leaderboard/model.dart';
+import 'package:harness/super_tabs/leaderboard/reader.dart';
+
+// Monday 2026-10-26 00:00 UTC.
+final week = DateTime.utc(2026, 10, 26).millisecondsSinceEpoch;
+const hour = 3600000;
+
+Map<String, dynamic> score(
+ String id, {
+ required int points,
+ required int rank,
+ String? medal,
+ int shipped = 0,
+ int unblocked = 0,
+ int machines = 0,
+ int lentMs = 0,
+ int streak = 0,
+}) => {
+ 'personId': id,
+ 'points': points,
+ 'rank': rank,
+ 'medal': medal,
+ 'shipped': {
+ 'count': shipped,
+ 'medianAskToShipMs': shipped > 0 ? 3.1 * hour : null,
+ },
+ 'unblocked': {
+ 'count': unblocked,
+ 'agentMs': unblocked * 2 * hour,
+ 'medianAnswerMs': unblocked > 0 ? 6 * 60000 : null,
+ },
+ 'lent': {'machines': machines, 'agentMs': lentMs},
+ 'streakDays': streak,
+};
+
+/// The read's answer for the layout mockup (numbers made up).
+Map<String, dynamic> answer({Map<String, dynamic>? waiting}) => {
+ 'projectId': 'lead',
+ 'week': week,
+ 'goal': {
+ 'openRequests': 7,
+ 'thisWeek': {'shipped': 19, 'points': 108, 'medianAskToShipMs': 3 * hour},
+ 'lastWeek': {'shipped': 12, 'points': 80, 'medianAskToShipMs': 5 * hour},
+ },
+ 'people': [
+ score(
+ 'ken',
+ points: 42,
+ rank: 1,
+ medal: 'gold',
+ shipped: 9,
+ unblocked: 14,
+ machines: 2,
+ lentMs: 31 * hour,
+ streak: 5,
+ ),
+ score(
+ 'dee',
+ points: 28,
+ rank: 2,
+ medal: 'silver',
+ shipped: 6,
+ unblocked: 5,
+ ),
+ score(
+ 'scholes',
+ points: 19,
+ rank: 3,
+ medal: 'bronze',
+ shipped: 2,
+ unblocked: 3,
+ machines: 1,
+ ),
+ score('tony', points: 0, rank: 4),
+ ],
+ 'waiting':
+ waiting ??
+ {
+ 'total': 3,
+ 'people': [
+ {
+ 'personId': 'ken',
+ 'count': 2,
+ 'conversationIds': ['g1', 'g2'],
+ },
+ {
+ 'personId': 'tony',
+ 'count': 1,
+ 'conversationIds': ['g3'],
+ },
+ ],
+ },
+};
+
+String name(String id) => '${id[0].toUpperCase()}${id.substring(1)}';
+
+class FakeRequests {
+ final paths = <String>[];
+ Object? Function(String path) respond = (_) => answer();
+ Future<Map<String, dynamic>> call(
+ String method,
+ String path, {
+ Map<String, dynamic>? body,
+ }) async {
+ paths.add('$method $path');
+ final result = respond(path);
+ if (result is Exception) throw result;
+ return result as Map<String, dynamic>;
+ }
+}
+
+void main() {
+ group('the leaderboard read', () {
+ test('parses every number the column shows', () {
+ final board = SuperTabLeaderboard.fromJson(answer());
+ expect(board.week, week);
+ expect(board.goal.openRequests, 7);
+ expect(board.goal.thisWeek.medianAskToShipMs, 3 * hour);
+ expect(board.goal.lastWeek.shipped, 12);
+ final ken = board.people.first;
+ expect(
+ [ken.personId, ken.points, ken.rank, ken.medal],
+ ['ken', 42, 1, SuperTabMedal.gold],
+ );
+ expect(
+ [
+ ken.shipped,
+ ken.unblocked,
+ ken.lentMachines,
+ ken.lentMs,
+ ken.streakDays,
+ ],
+ [9, 14, 2, 31 * hour, 5],
+ );
+ expect(ken.medianAskToShipMs, (3.1 * hour).round());
+ expect(board.people.last.medal, isNull);
+ expect(board.waiting.total, 3);
+ expect(board.waiting.people.map((w) => (w.personId, w.count)), [
+ ('ken', 2),
+ ('tony', 1),
+ ]);
+ });
+
+ test('asks for the project and, once chosen, the week', () async {
+ final requests = FakeRequests();
+ final reader = SuperTabLeaderboardReader(
+ tabId: 'tab 1',
+ request: requests.call,
+ );
+ addTearDown(reader.dispose);
+ await reader.show('lead');
+ await reader.showWeek(week - 7 * 86400000);
+ expect(requests.paths, [
+ 'GET /api/super-tabs/tab%201/leaderboard?projectId=lead',
+ 'GET /api/super-tabs/tab%201/leaderboard?projectId=lead&week=${week - 7 * 86400000}',
+ ]);
+ expect(reader.board?.week, week);
+ });
+
+ test('shows no numbers while another week is read, so one week never wears another\'s name', () async {
+ final requests = FakeRequests();
+ final pending = Completer<Map<String, dynamic>>();
+ final reader = SuperTabLeaderboardReader(
+ tabId: 'tab',
+ request: (method, path, {body}) => path.contains('&week=')
+ ? pending.future
+ : requests.call(method, path),
+ );
+ addTearDown(reader.dispose);
+ await reader.show('lead');
+ final earlier = reader.showWeek(week - 7 * 86400000);
+ expect(reader.board, isNull);
+ pending.complete({...answer(), 'week': week - 7 * 86400000});
+ await earlier;
+ expect(reader.board?.week, week - 7 * 86400000);
+ });
+
+ test('keeps the last board when a refresh fails, and says it could not refresh', () async {
+ final requests = FakeRequests();
+ final reader = SuperTabLeaderboardReader(
+ tabId: 'tab',
+ request: requests.call,
+ );
+ addTearDown(reader.dispose);
+ await reader.show('lead');
+ requests.respond = (_) =>
+ const SuperTabFailure('OFFLINE', 'No connection.');
+ await reader.refresh();
+ expect(reader.board, isNotNull);
+ expect(reader.error, 'No connection.');
+ });
+
+ test(
+ 'drops a board read for another project once the project changes',
+ () async {
+ final requests = FakeRequests(),
+ late = Completer<Map<String, dynamic>>();
+ final reader = SuperTabLeaderboardReader(
+ tabId: 'tab',
+ request: (method, path, {body}) => path.contains('projectId=old')
+ ? late.future
+ : requests.call(method, path),
+ );
+ addTearDown(reader.dispose);
+ final first = reader.show('old');
+ await reader.show('new');
+ late.complete({...answer(), 'projectId': 'old'});
+ await first;
+ expect(reader.board?.projectId, 'lead');
+ },
+ );
+
+ test(
+ 'refreshes on its own every minute while shown, and stops once hidden',
+ () {
+ fakeAsync((async) {
+ final requests = FakeRequests();
+ final reader = SuperTabLeaderboardReader(
+ tabId: 'tab',
+ request: requests.call,
+ );
+ reader.show('lead');
+ async.elapse(const Duration(minutes: 2, seconds: 1));
+ expect(requests.paths, hasLength(3));
+ reader.hide();
+ async.elapse(const Duration(minutes: 5));
+ expect(requests.paths, hasLength(3));
+ reader.dispose();
+ });
+ },
+ );
+ });
+
+ group('the leaderboard column', () {
+ Future<(SuperTabLeaderboardReader, List<String>)> mount(
+ WidgetTester tester, {
+ Map<String, dynamic>? waiting,
+ String viewer = 'tony',
+ }) async {
+ final requests = FakeRequests()
+ ..respond = (_) => answer(waiting: waiting);
+ final reader = SuperTabLeaderboardReader(
+ tabId: 'tab',
+ request: requests.call,
+ );
+ addTearDown(reader.dispose);
+ final answered = <String>[];
+ await tester.binding.setSurfaceSize(const Size(400, 1000));
+ addTearDown(() => tester.binding.setSurfaceSize(null));
+ await tester.pumpWidget(
+ MaterialApp(
+ theme: grid.buildAppTheme(brightness: Brightness.dark),
+ home: Scaffold(
+ body: SuperTabLeaderboardColumn(
+ reader: reader,
+ projectId: 'lead',
+ viewerId: viewer,
+ nameOf: name,
+ onAnswer: answered.add,
+ now: () => DateTime.fromMillisecondsSinceEpoch(
+ week + 3 * 86400000,
+ isUtc: true,
+ ),
+ ),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ return (reader, answered);
+ }
+
+ testWidgets(
+ 'gives the top three their medals and everyone their three numbers',
+ (tester) async {
+ await mount(tester);
+ expect(find.text('Humans · this week'), findsOneWidget);
+ expect(find.text('🏆'), findsOneWidget);
+ expect(find.text('🥈'), findsOneWidget);
+ expect(find.text('🥉'), findsOneWidget);
+ expect(find.text('42 pts'), findsOneWidget);
+ expect(
+ find.text('🚀 9 shipped 🔓 14 ⚡ 2 machines'),
+ findsOneWidget,
+ );
+ expect(find.text('🚀 6 shipped 🔓 5 ⚡ —'), findsOneWidget);
+ expect(find.text('🚀 2 shipped 🔓 3 ⚡ 1 machine'), findsOneWidget);
+ expect(find.text('Tony'), findsWidgets);
+ expect(find.text('0 pts'), findsOneWidget);
+ },
+ );
+
+ testWidgets(
+ 'shows each person\'s avatar beside their name, at the size the shared avatar takes',
+ (tester) async {
+ await mount(tester);
+ final avatars = tester
+ .widgetList<SuperTabAvatar>(find.byType(SuperTabAvatar))
+ .toList();
+ expect(avatars.map((a) => (a.identity, a.name, a.size)), [
+ ('person:ken', 'Ken', 20.0),
+ ('person:dee', 'Dee', 20.0),
+ ('person:scholes', 'Scholes', 20.0),
+ ('person:tony', 'Tony', 20.0),
+ ]);
+ },
+ );
+
+ testWidgets('shows the team goal against last week', (tester) async {
+ await mount(tester);
+ expect(find.text('Team goal · 7 open requests'), findsOneWidget);
+ expect(
+ find.text('19 shipped this week (12 last week) · 108 points'),
+ findsOneWidget,
+ );
+ expect(
+ find.text('Median ask to ship 3 h, down from 5 h'),
+ findsOneWidget,
+ );
+ });
+
+ testWidgets(
+ 'opens a person\'s week when their name is tapped, and closes it again',
+ (tester) async {
+ await mount(tester);
+ await tester.tap(find.byKey(const ValueKey('leaderboard-person-ken')));
+ await tester.pumpAndSettle();
+ expect(
+ find.text('9 asks landed · median 3.1 h to ship'),
+ findsOneWidget,
+ );
+ expect(
+ find.text('14 answered · median 6 min · 28 h of agent time freed'),
+ findsOneWidget,
+ );
+ expect(find.text('2 machines · 31 slot-hours'), findsOneWidget);
+ expect(find.text('5 days shipping'), findsOneWidget);
+ await tester.tap(find.byKey(const ValueKey('leaderboard-person-ken')));
+ await tester.pumpAndSettle();
+ expect(find.text('5 days shipping'), findsNothing);
+ },
+ );
+
+ testWidgets(
+ 'names who agents wait on with counts only, never ranks or medals',
+ (tester) async {
+ await mount(tester);
+ final line = find.byKey(const ValueKey('leaderboard-waiting'));
+ expect(
+ find.descendant(
+ of: line,
+ matching: find.text('⏳ Agents waiting on a person now: 3'),
+ ),
+ findsOneWidget,
+ );
+ expect(
+ find.descendant(of: line, matching: find.text('Ken 2 · Tony 1')),
+ findsOneWidget,
+ );
+ for (final medal in ['🏆', '🥈', '🥉', 'pts']) {
+ expect(
+ find.descendant(of: line, matching: find.textContaining(medal)),
+ findsNothing,
+ );
+ }
+ },
+ );
+
+ testWidgets('takes the viewer straight to what waits on them', (
+ tester,
+ ) async {
+ final (_, answered) = await mount(tester, viewer: 'tony');
+ await tester.tap(find.text('Answer'));
+ expect(answered, ['g3']);
+ });
+
+ testWidgets('takes anyone else to the first item waiting', (tester) async {
+ final (_, answered) = await mount(tester, viewer: 'dee');
+ await tester.tap(find.text('Answer'));
+ expect(answered, ['g1']);
+ });
+
+ testWidgets(
+ 'says nobody is waiting, without an answer button, when none is',
+ (tester) async {
+ await mount(tester, waiting: {'total': 0, 'people': []});
+ expect(find.text('No agent is waiting on a person.'), findsOneWidget);
+ expect(find.text('Answer'), findsNothing);
+ },
+ );
+
+ testWidgets('reads an earlier week when one is picked', (tester) async {
+ final (reader, _) = await mount(tester);
+ await tester.tap(find.byKey(const ValueKey('leaderboard-week')));
+ await tester.pumpAndSettle();
+ await tester.tap(find.text('Last week').last);
+ await tester.pumpAndSettle();
+ expect(reader.week, week - 7 * 86400000);
+ expect(find.text('Humans · last week'), findsOneWidget);
+ });
+ });
+}
diff --git a/desktop/test/super_tab_phone_header_test.dart b/desktop/test/super_tab_phone_header_test.dart
index d3212069c..09b20a595 100644
--- a/desktop/test/super_tab_phone_header_test.dart
+++ b/desktop/test/super_tab_phone_header_test.dart
@@ -28,6 +28,7 @@ void main() {
for (final control in [
find.byTooltip('Conversations'),
find.byKey(const ValueKey('super-chat')),
+ find.byKey(const ValueKey('super-leaderboard')),
_people,
_options,
]) {
diff --git a/desktop/test/super_tab_roster_test.dart b/desktop/test/super_tab_roster_test.dart
index 181f7b35a..2596b8e04 100644
--- a/desktop/test/super_tab_roster_test.dart
+++ b/desktop/test/super_tab_roster_test.dart
@@ -105,6 +105,11 @@ class RosterFixture {
Finder row(int i) => find.byKey(ValueKey('super-member-agent-$i'));
Finder inRow(int i, Finder child) =>
find.descendant(of: row(i), matching: child);
+
+ /// The row's one line: state, machine, model and effort (team glance, 2026-10-27).
+ Finder line(int i) => find.byKey(ValueKey('super-member-line-agent-$i'));
+ String lineText(WidgetTester tester, int i) =>
+ tester.widget<Text>(line(i)).data!;
HarnessActivity activity(WidgetTester tester, int i) =>
tester.widget<ActivityMark>(inRow(i, find.byType(ActivityMark))).activity;
@@ -187,7 +192,7 @@ void main() {
).toUtc().toIso8601String();
await f.controller.refresh();
await f.show(tester);
- expect(f.inRow(1, find.text('Limited until 09:05')), findsOneWidget);
+ expect(f.lineText(tester, 1), 'Limited until 09:05 · Test host');
expect(rowTooltip(tester, f, 1), contains('Limited until 09:05'));
await captureBoundary(
tester,
@@ -205,9 +210,10 @@ void main() {
await f.controller.refresh();
await tester.pumpAndSettle();
expect(find.textContaining('Limited until'), findsNothing);
+ expect(f.lineText(tester, 1), 'Assigned · Test host');
expect(
- f.inRow(1, find.text('Assigned to "Offline editing"')),
- findsOneWidget,
+ rowTooltip(tester, f, 1),
+ contains('Assigned to "Offline editing"'),
);
}
await f.close(tester);
@@ -248,10 +254,7 @@ void main() {
rowTooltip(tester, f, 1),
contains('Sage · Engineer · openharness'),
);
- expect(
- f.inRow(1, find.text('Working on "Offline editing"')),
- findsOneWidget,
- );
+ expect(f.lineText(tester, 1), 'Working · Test host · opus unknown');
final mouse = await tester.createGesture(kind: PointerDeviceKind.mouse);
await mouse.addPointer(location: Offset.zero);
await mouse.moveTo(tester.getCenter(f.row(1)));
@@ -272,7 +275,9 @@ void main() {
contains('Atlas · Product Manager · openharness'),
);
expect(rowTooltip(tester, f, 0), contains('Codex'));
- expect(f.inRow(0, find.text('Status unavailable')), findsOneWidget);
+ // No native state and no task: idle as far as the Swarm's work goes; the tooltip says what is not known.
+ expect(f.lineText(tester, 0), 'Idle');
+ expect(rowTooltip(tester, f, 0), contains('Status unavailable'));
expect(rowTooltip(tester, f, 0), isNot(contains('Last active')));
await tester.tap(f.row(0));
await tester.pumpAndSettle();
@@ -311,7 +316,7 @@ void main() {
await f.controller.refresh();
await f.show(tester);
expect(f.activity(tester, 1), HarnessActivity.needsInput);
- expect(f.inRow(1, find.text('Needs input')), findsOneWidget);
+ expect(f.lineText(tester, 1), 'Waiting · Test host');
expect(rowTooltip(tester, f, 1), contains('Needs input'));
expect(rowTooltip(tester, f, 1), isNot(contains('Working on')));
await f.close(tester);
@@ -331,9 +336,8 @@ void main() {
await f.show(tester);
final tooltip = rowTooltip(tester, f, 1);
expect(tooltip, contains(title));
- final activity = f.inRow(1, find.text('Working on "$title"'));
- expect(activity, findsOneWidget);
- expect(tester.getSize(activity).height, lessThan(30));
+ expect(f.lineText(tester, 1), 'Working · Test host');
+ expect(tester.getSize(f.line(1)).height, lessThan(30));
final mouse = await tester.createGesture(kind: PointerDeviceKind.mouse);
await mouse.addPointer(location: Offset.zero);
await mouse.moveTo(tester.getCenter(f.row(1)));
@@ -1026,7 +1030,7 @@ void main() {
final nameX = tester.getTopLeft(f.inRow(0, find.text('Atlas'))).dx;
final engine = tester.getRect(f.inRow(0, find.byType(EngineMark)));
final name = tester.getRect(f.inRow(0, find.text('Atlas')));
- final status = tester.getRect(f.inRow(0, find.text('Idle')));
+ final status = tester.getRect(f.line(0));
final mark = tester.getRect(f.inRow(0, find.byType(ActivityMark)));
expect(engine.left, greaterThan(name.right));
expect(engine.center.dy, closeTo(name.center.dy, 2));
@@ -1158,11 +1162,12 @@ void main() {
..['assignment'] = {'agentId': 'agent-1', 'status': 'planned'};
await f.controller.refresh();
await f.show(tester, nativeState: false);
+ expect(f.lineText(tester, 1), 'Assigned');
expect(
- f.inRow(1, find.text('Assigned to "Polish navigation"')),
- findsOneWidget,
+ rowTooltip(tester, f, 1),
+ contains('Assigned to "Polish navigation"'),
);
- expect(f.inRow(0, find.text('Status unavailable')), findsOneWidget);
+ expect(f.lineText(tester, 0), 'Idle');
expect(f.activity(tester, 1), HarnessActivity.unknown);
final copy = tester
.widgetList<Text>(
@@ -1211,7 +1216,12 @@ void main() {
? 'Working on "Polish navigation"'
: 'Assigned to "Polish navigation"';
expect(f.activity(tester, 1), activity);
- expect(f.inRow(1, find.text(status)), findsOneWidget);
+ expect(
+ f.lineText(tester, 1),
+ activity == HarnessActivity.working
+ ? 'Working · Test host'
+ : 'Assigned · Test host',
+ );
expect(rowTooltip(tester, f, 1), contains(status));
if (activity != HarnessActivity.working) {
expect(rowTooltip(tester, f, 1), isNot(contains('Working on')));
@@ -1219,10 +1229,7 @@ void main() {
}
await f.show(tester, nativeState: false);
expect(f.activity(tester, 1), HarnessActivity.unknown);
- expect(
- f.inRow(1, find.text('Assigned to "Polish navigation"')),
- findsOneWidget,
- );
+ expect(f.lineText(tester, 1), 'Assigned');
await f.close(tester);
},
);
@@ -1241,16 +1248,17 @@ void main() {
(f.server.state['conversations'] as List).add(currentTask);
await f.controller.refresh();
await f.show(tester, nativeState: false);
+ expect(f.lineText(tester, 1), 'Assigned');
expect(
- f.inRow(1, find.text('Assigned to "Polish navigation"')),
- findsOneWidget,
+ rowTooltip(tester, f, 1),
+ contains('Assigned to "Polish navigation"'),
);
expect(rowTooltip(tester, f, 1), isNot(contains('Cancelled task')));
(currentTask['assignment'] as Map)['status'] = 'cancelled';
await f.controller.refresh();
await tester.pumpAndSettle();
- expect(f.inRow(1, find.text('Status unavailable')), findsOneWidget);
+ expect(f.lineText(tester, 1), 'Idle');
expect(rowTooltip(tester, f, 1), isNot(contains('Polish navigation')));
expect(rowTooltip(tester, f, 1), isNot(contains('Working on')));
await f.close(tester);
@@ -1260,14 +1268,25 @@ void main() {
tester,
) async {
final f = await fixture(tester);
- for (final (status, activity, label) in [
- ('blocked', HarnessActivity.needsInput, 'Needs input'),
+ for (final (status, activity, label, line) in [
+ (
+ 'blocked',
+ HarnessActivity.needsInput,
+ 'Needs input',
+ 'Stuck · Test host',
+ ),
(
'review',
HarnessActivity.idle,
'Waiting for review on "Polish navigation"',
+ 'In review · Test host',
+ ),
+ (
+ 'reconciling',
+ HarnessActivity.idle,
+ 'Checking "Polish navigation"',
+ 'Checking · Test host',
),
- ('reconciling', HarnessActivity.idle, 'Checking "Polish navigation"'),
]) {
(f.server.state['conversations'] as List)[1]
..['title'] = 'Polish navigation'
@@ -1275,7 +1294,8 @@ void main() {
await f.controller.refresh();
await f.show(tester);
expect(f.activity(tester, 1), activity);
- expect(f.inRow(1, find.text(label)), findsOneWidget);
+ expect(f.lineText(tester, 1), line);
+ expect(rowTooltip(tester, f, 1), contains(label));
expect(rowTooltip(tester, f, 1), isNot(contains('Working on')));
}
await f.close(tester);
@@ -1314,14 +1334,20 @@ void main() {
};
await f.controller.refresh();
final machine = f.app.stateOf('m')!;
- for (final (activity, status, data) in [
- (HarnessActivity.offline, 'Offline', <String, dynamic>{}),
- (HarnessActivity.paused, 'Stopped', {'status': 'stopped'}),
- (HarnessActivity.starting, 'Starting', {'launchState': 'starting'}),
- (HarnessActivity.failed, 'Failed', {'launchState': 'failed'}),
+ for (final (activity, status, line, data) in [
+ (HarnessActivity.offline, 'Offline', 'Down', <String, dynamic>{}),
+ (HarnessActivity.paused, 'Stopped', 'Stopped', {'status': 'stopped'}),
+ (
+ HarnessActivity.starting,
+ 'Starting',
+ 'Starting',
+ {'launchState': 'starting'},
+ ),
+ (HarnessActivity.failed, 'Failed', 'Down', {'launchState': 'failed'}),
(
HarnessActivity.needsInput,
'Needs input',
+ 'Waiting',
{'launchState': 'failed', 'launchError': 'RESUME_UNCONFIRMED'},
),
]) {
@@ -1341,8 +1367,9 @@ void main() {
];
await f.show(tester);
expect(f.activity(tester, 1), activity);
- expect(f.inRow(1, find.text(status)), findsOneWidget);
- expect(f.inRow(1, find.textContaining('Working on')), findsNothing);
+ expect(f.lineText(tester, 1), '$line · Test host');
+ expect(rowTooltip(tester, f, 1), contains(status));
+ expect(f.inRow(1, find.textContaining('Working')), findsNothing);
expect(rowTooltip(tester, f, 1), isNot(contains('Working on')));
}
await f.close(tester);
@@ -1366,9 +1393,7 @@ void main() {
final name = tester.getRect(f.inRow(0, find.text(longName)));
final badgeFinder = f.inRow(0, find.text('PM'));
final badge = tester.getRect(badgeFinder);
- final status = tester.getRect(
- f.inRow(0, find.text('Status unavailable')),
- );
+ final status = tester.getRect(f.line(0));
final mark = tester.getRect(f.inRow(0, find.byType(ActivityMark)));
expect(name.left, tester.getTopLeft(find.text('owner')).dx);
expect(mark.left, name.left);
diff --git a/desktop/test/super_tab_team_glance_test.dart b/desktop/test/super_tab_team_glance_test.dart
new file mode 100644
index 000000000..27a50158e
--- /dev/null
+++ b/desktop/test/super_tab_team_glance_test.dart
@@ -0,0 +1,490 @@
+// Team at a glance (Dee, 2026-10-27): "it's hard to monitor the team". Each agent row says, in one line, its state, the
+// machine it runs on and its model and effort; one click from the Agents heading shows every machine with its agents
+// and slots, the model and effort counts, and what looks wrong: work piled on one machine while others have room, busy
+// agents on an offline machine, and agents running another effort than their start asked for.
+import 'package:flutter/material.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/shared/theme/app_theme.dart' as grid;
+import 'package:harness/state/harness_activity.dart';
+import 'package:harness/super_tabs/agent_details.dart';
+import 'package:harness/super_tabs/roster.dart';
+import 'package:harness/super_tabs/team_glance.dart';
+
+import 'support/super_tab_fixture.dart';
+
+const _offline = 10 * 60 * 1000;
+
+Map<String, dynamic> _machine(
+ String id,
+ String name, {
+ int max = 4,
+ int? free,
+ int age = 0,
+ bool paused = false,
+ String? host,
+}) => {
+ 'machineId': id,
+ 'name': name,
+ 'contributorId': 'owner',
+ 'hostMachineId': ?host,
+ 'scope': 'swarm',
+ 'cwd': '/swarm',
+ 'engines': ['claude', 'codex'],
+ 'maxAgents': max,
+ 'paused': paused,
+ 'availableSlots': ?free,
+ 'observation': {'receivedAt': DateTime.now().millisecondsSinceEpoch - age},
+};
+
+Map<String, dynamic> _agent(
+ String id,
+ String machineId, {
+ String model = 'opus',
+ String? effort = 'high',
+ String engine = 'claude',
+ Map<String, dynamic> extra = const {},
+}) => {
+ 'id': id,
+ 'projectId': 'lead',
+ 'name': id,
+ 'displayName': id,
+ 'machineId': machineId,
+ 'harnessId': 'h-$id',
+ 'contributorId': 'owner',
+ 'configuration': {'engine': engine, 'model': model, 'effort': ?effort},
+ ...extra,
+};
+
+Map<String, dynamic> _task(String agentId, String status) => {
+ ...conversationFixture('task-$agentId', 'Task of $agentId'),
+ 'leadId': 'Lead',
+ 'agentIds': ['Lead', agentId],
+ 'assignment': {'id': 'as-$agentId', 'agentId': agentId, 'status': status},
+};
+
+Map<String, dynamic> _start(String agentId, String effort) => {
+ 'id': 'start-$agentId',
+ 'harnessId': 'h-$agentId',
+ 'request': {
+ 'machineId': 'm1',
+ 'engine': 'claude',
+ 'model': 'opus',
+ 'effort': effort,
+ 'name': agentId,
+ },
+};
+
+/// A Swarm whose Lead runs on Mac Studio, with [agents], [machines], [tasks] and [starts] besides.
+Future<ConversationServer> _swarm(
+ WidgetTester tester, {
+ List<Map<String, dynamic>> agents = const [],
+ List<Map<String, dynamic>>? machines,
+ List<Map<String, dynamic>> tasks = const [],
+ List<Map<String, dynamic>> starts = const [],
+ String account = 'owner',
+}) async {
+ final server = ConversationServer();
+ if (account != 'owner') {
+ (server.state['people'] as List).add({
+ 'id': account,
+ 'email': '[email protected]',
+ 'role': 'collaborator',
+ });
+ }
+ server.state['machines'] =
+ machines ?? [_machine('m1', 'Mac Studio'), _machine('m2', 'MacBook Pro')];
+ server.state['agents'] = [_agent('Lead', 'm1'), ...agents];
+ (server.state['conversations'] as List)[0]['leadId'] = 'Lead';
+ (server.state['conversations'] as List).addAll(tasks);
+ server.state['starts'] = starts;
+ final c = server.controller(account: account);
+ await c.refresh();
+ addTearDown(c.dispose);
+ await tester.binding.setSurfaceSize(const Size(320, 1600));
+ addTearDown(() => tester.binding.setSurfaceSize(null));
+ await tester.pumpWidget(
+ MaterialApp(
+ theme: grid.buildAppTheme(brightness: Brightness.dark),
+ home: Scaffold(
+ body: SuperTabRoster(
+ controller: c,
+ onInvite: () {},
+ onOpenAgent: (_) {},
+ onAddAgent: (_) {},
+ ),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ return server;
+}
+
+Finder _row(String id) => find.byKey(ValueKey('super-member-$id'));
+Finder _line(String id, String text) =>
+ find.descendant(of: _row(id), matching: find.text(text));
+
+Future<void> _openGlance(WidgetTester tester) async {
+ await tester.tap(find.byTooltip('Team at a glance'));
+ await tester.pumpAndSettle();
+}
+
+void main() {
+ group('an agent row', () {
+ testWidgets(
+ 'says in one line its state, its machine, and its model and effort',
+ (tester) async {
+ await _swarm(
+ tester,
+ agents: [
+ _agent('Atlas', 'm1'),
+ _agent('Sage', 'm2', model: 'sonnet', effort: 'medium'),
+ ],
+ tasks: [_task('Atlas', 'working')],
+ );
+ // Holding a task with no turn seen running: assigned, never claimed as working.
+ expect(
+ _line('Atlas', 'Assigned · Mac Studio · opus high'),
+ findsOneWidget,
+ );
+ expect(
+ _line('Sage', 'Idle · MacBook Pro · sonnet medium'),
+ findsOneWidget,
+ );
+ },
+ );
+
+ test('reads working only while its turn runs, and keeps the task as assigned otherwise', () async {
+ final server = ConversationServer();
+ server.state['machines'] = [_machine('m1', 'Mac Studio')];
+ server.state['agents'] = [_agent('Atlas', 'm1')];
+ (server.state['conversations'] as List).add(_task('Atlas', 'working'));
+ final c = server.controller();
+ addTearDown(c.dispose);
+ await c.refresh();
+ final atlas = c.snapshot!.agent('Atlas')!;
+ String line(HarnessActivity? activity) => superTabAgentGlance(
+ SuperTabAgentInfo(c, null, atlas, activity: activity),
+ ).line;
+ expect(line(HarnessActivity.working), 'Working · Mac Studio · opus high');
+ expect(line(HarnessActivity.idle), 'Assigned · Mac Studio · opus high');
+ expect(line(null), 'Assigned · Mac Studio · opus high');
+ });
+
+ testWidgets(
+ 'names each state in a word: waiting, lost, down, limited, stuck, in review',
+ (tester) async {
+ final until = DateTime.now().add(const Duration(hours: 2)).toLocal();
+ String two(int n) => n.toString().padLeft(2, '0');
+ await _swarm(
+ tester,
+ agents: [
+ _agent('Wren', 'm1'),
+ _agent('Lark', 'm1'),
+ _agent(
+ 'Kite',
+ 'm2',
+ extra: {'downSince': DateTime.now().toUtc().toIso8601String()},
+ ),
+ _agent(
+ 'Rook',
+ 'm2',
+ extra: {'limitedUntil': until.toUtc().toIso8601String()},
+ ),
+ _agent('Moss', 'm1'),
+ _agent('Teal', 'm1'),
+ ],
+ tasks: [
+ _task('Wren', 'needs_human'),
+ _task('Lark', 'lost'),
+ _task('Moss', 'blocked'),
+ _task('Teal', 'review'),
+ ],
+ );
+ expect(_line('Moss', 'Stuck · Mac Studio · opus high'), findsOneWidget);
+ expect(
+ _line('Teal', 'In review · Mac Studio · opus high'),
+ findsOneWidget,
+ );
+ expect(
+ _line('Wren', 'Waiting · Mac Studio · opus high'),
+ findsOneWidget,
+ );
+ expect(_line('Lark', 'Lost · Mac Studio · opus high'), findsOneWidget);
+ final tip = tester
+ .widgetList<Tooltip>(
+ find.ancestor(of: _row('Lark'), matching: find.byType(Tooltip)),
+ )
+ .single
+ .message!;
+ expect(tip, contains('Lost "Task of Lark"'));
+ expect(_line('Kite', 'Down · MacBook Pro · opus high'), findsOneWidget);
+ expect(
+ _line(
+ 'Rook',
+ 'Limited until ${two(until.hour)}:${two(until.minute)} · MacBook Pro · opus high',
+ ),
+ findsOneWidget,
+ );
+ },
+ );
+
+ // Builders started with opus high were stored as auto (fixed in the CLI, 2026-10-27); one stored before the fix
+ // shows what its start asked for while the start still says, and otherwise that the effort is not known.
+ testWidgets(
+ 'shows the requested effort for an auto reading its start still names, else unknown',
+ (tester) async {
+ await _swarm(
+ tester,
+ agents: [
+ _agent('Nico', 'm1', effort: 'auto'),
+ _agent('Quinn', 'm1', effort: 'auto'),
+ _agent('Avery', 'm1', effort: null),
+ ],
+ starts: [_start('Nico', 'high')],
+ );
+ expect(_line('Nico', 'Idle · Mac Studio · opus high'), findsOneWidget);
+ expect(
+ _line('Quinn', 'Idle · Mac Studio · opus unknown'),
+ findsOneWidget,
+ );
+ expect(
+ _line('Avery', 'Idle · Mac Studio · opus unknown'),
+ findsOneWidget,
+ );
+ },
+ );
+
+ testWidgets('a start that asked for effort high is shown as high', (
+ tester,
+ ) async {
+ await _swarm(
+ tester,
+ agents: [_agent('Echo', 'm1')],
+ starts: [_start('Echo', 'high')],
+ );
+ expect(_line('Echo', 'Idle · Mac Studio · opus high'), findsOneWidget);
+ });
+ });
+
+ group('Team at a glance', () {
+ testWidgets(
+ 'opens with one click and lists each machine with its slots, state and agents',
+ (tester) async {
+ await _swarm(
+ tester,
+ machines: [
+ _machine('m1', 'Mac Studio', free: 2),
+ _machine('m2', 'MacBook Pro', max: 2, free: 2, age: _offline),
+ ],
+ agents: [_agent('Atlas', 'm1')],
+ );
+ await _openGlance(tester);
+ final studio = find.byKey(const ValueKey('glance-machine-m1'));
+ expect(
+ find.descendant(of: studio, matching: find.text('Mac Studio')),
+ findsOneWidget,
+ );
+ expect(
+ find.descendant(
+ of: studio,
+ matching: find.text('Online · 2 of 4 slots used'),
+ ),
+ findsOneWidget,
+ );
+ expect(
+ find.descendant(of: studio, matching: find.text('Lead · Idle')),
+ findsOneWidget,
+ );
+ expect(
+ find.descendant(of: studio, matching: find.text('Atlas · Idle')),
+ findsOneWidget,
+ );
+ final laptop = find.byKey(const ValueKey('glance-machine-m2'));
+ expect(
+ find.descendant(
+ of: laptop,
+ matching: find.text('Offline · 0 of 2 slots used'),
+ ),
+ findsOneWidget,
+ );
+ expect(
+ find.descendant(of: laptop, matching: find.text('No agents')),
+ findsOneWidget,
+ );
+ },
+ );
+
+ testWidgets('counts agents per model and effort, most first', (
+ tester,
+ ) async {
+ await _swarm(
+ tester,
+ agents: [
+ _agent('Atlas', 'm1'),
+ _agent('Sage', 'm2', model: 'sonnet', effort: 'medium'),
+ _agent('Finn', 'm2'),
+ ],
+ );
+ await _openGlance(tester);
+ final counts = find.byKey(const ValueKey('glance-models'));
+ expect(
+ find.descendant(of: counts, matching: find.text('opus high · 3')),
+ findsOneWidget,
+ );
+ expect(
+ find.descendant(of: counts, matching: find.text('sonnet medium · 1')),
+ findsOneWidget,
+ );
+ expect(
+ tester.getTopLeft(find.text('opus high · 3')).dy,
+ lessThan(tester.getTopLeft(find.text('sonnet medium · 1')).dy),
+ );
+ });
+
+ testWidgets(
+ 'warns when most busy agents sit on one machine while another has free slots',
+ (tester) async {
+ await _swarm(
+ tester,
+ machines: [
+ _machine('m1', 'Mac Studio', free: 0),
+ _machine('m2', 'MacBook Pro', free: 3),
+ ],
+ agents: [
+ _agent('Atlas', 'm1'),
+ _agent('Sage', 'm1'),
+ _agent('Finn', 'm2'),
+ ],
+ tasks: [
+ _task('Atlas', 'working'),
+ _task('Sage', 'working'),
+ _task('Finn', 'working'),
+ ],
+ );
+ await _openGlance(tester);
+ expect(
+ find.text(
+ '2 of 3 busy agents are on Mac Studio, while MacBook Pro has 3 free slots.',
+ ),
+ findsOneWidget,
+ );
+ },
+ );
+
+ testWidgets(
+ 'does not warn about piling up when the other machines have no room or are offline',
+ (tester) async {
+ await _swarm(
+ tester,
+ machines: [
+ _machine('m1', 'Mac Studio', free: 0),
+ _machine('m2', 'MacBook Pro', free: 3, age: _offline),
+ ],
+ agents: [_agent('Atlas', 'm1'), _agent('Sage', 'm1')],
+ tasks: [_task('Atlas', 'working'), _task('Sage', 'working')],
+ );
+ await _openGlance(tester);
+ expect(find.textContaining('busy agents are on'), findsNothing);
+ expect(find.text('Nothing looks wrong.'), findsOneWidget);
+ },
+ );
+
+ // Review of #1759: a paused machine takes no new work, so its free slots are no room.
+ testWidgets('does not count a paused machine as room', (tester) async {
+ await _swarm(
+ tester,
+ machines: [
+ _machine('m1', 'Mac Studio', free: 0),
+ _machine('m2', 'MacBook Pro', free: 3, paused: true),
+ ],
+ agents: [_agent('Atlas', 'm1'), _agent('Sage', 'm1')],
+ tasks: [_task('Atlas', 'working'), _task('Sage', 'working')],
+ );
+ await _openGlance(tester);
+ expect(find.textContaining('busy agents are on'), findsNothing);
+ expect(find.text('Nothing looks wrong.'), findsOneWidget);
+ });
+
+ // Review of #1759: a teammate reads a Mac by its Harness Team account, as the Machines view does; a stale reading
+ // of the Mac's own pool beside a live Team account is not an offline machine.
+ testWidgets(
+ 'reads a Mac by its Team account for a teammate, as the Machines view does',
+ (tester) async {
+ await _swarm(
+ tester,
+ account: 'peer',
+ machines: [
+ _machine('m1', 'Mac Studio', age: _offline),
+ _machine('m1-team', 'Mac Studio (team)', free: 3, host: 'm1'),
+ _machine('m2', 'MacBook Pro'),
+ ],
+ agents: [_agent('Finn', 'm1-team')],
+ tasks: [_task('Finn', 'working')],
+ );
+ await _openGlance(tester);
+ final studio = find.byKey(const ValueKey('glance-machine-m1'));
+ expect(
+ find.descendant(
+ of: studio,
+ matching: find.text('Online · 1 of 4 slots used'),
+ ),
+ findsOneWidget,
+ );
+ expect(
+ find.descendant(of: studio, matching: find.text('Finn · Assigned')),
+ findsOneWidget,
+ );
+ expect(find.textContaining('which is offline'), findsNothing);
+ expect(
+ find.byKey(const ValueKey('glance-machine-m1-team')),
+ findsNothing,
+ );
+ },
+ );
+
+ testWidgets('warns about a busy agent on an offline machine', (
+ tester,
+ ) async {
+ await _swarm(
+ tester,
+ machines: [
+ _machine('m1', 'Mac Studio'),
+ _machine('m2', 'MacBook Pro', age: _offline),
+ ],
+ agents: [_agent('Finn', 'm2')],
+ tasks: [_task('Finn', 'working')],
+ );
+ await _openGlance(tester);
+ expect(
+ find.text('Finn is busy on MacBook Pro, which is offline.'),
+ findsOneWidget,
+ );
+ });
+
+ testWidgets(
+ 'warns about an agent running another effort than its start asked for, not an unknown one',
+ (tester) async {
+ await _swarm(
+ tester,
+ agents: [
+ _agent('Hugo', 'm1', effort: 'xhigh'),
+ _agent('Nico', 'm1', effort: 'auto'),
+ _agent('Echo', 'm1'),
+ ],
+ starts: [
+ _start('Hugo', 'high'),
+ _start('Nico', 'high'),
+ _start('Echo', 'high'),
+ ],
+ );
+ await _openGlance(tester);
+ expect(
+ find.text('Hugo runs effort xhigh; its start asked for high.'),
+ findsOneWidget,
+ );
+ expect(find.textContaining('Nico runs'), findsNothing);
+ expect(find.textContaining('Echo runs'), findsNothing);
+ },
+ );
+ });
+}
diff --git a/desktop/test/support/super_tab_fixture.dart b/desktop/test/support/super_tab_fixture.dart
index 62f9f8ac4..94c86e306 100644
--- a/desktop/test/support/super_tab_fixture.dart
+++ b/desktop/test/support/super_tab_fixture.dart
@@ -69,6 +69,7 @@ class SwarmPartsBackend {
'machines',
'starts',
'mentionsWaiting',
+ 'decisionsWaiting',
'otherProjectsWork',
'githubApp',
}.contains(entry.key))
@@ -138,6 +139,8 @@ class SwarmPartsBackend {
'machines': <String, dynamic>{},
if (state['mentionsWaiting'] != null)
'mentionsWaiting': state['mentionsWaiting'],
+ if (state['decisionsWaiting'] != null)
+ 'decisionsWaiting': state['decisionsWaiting'],
if (state['otherProjectsWork'] != null)
'otherProjectsWork': state['otherProjectsWork'],
};
@@ -382,8 +385,14 @@ class ConversationServer {
final messages = <Map<String, dynamic>>[];
// Route decisions by id, answered by GET .../route-decisions/:id.
final routeDecisions = <String, Map<String, dynamic>>{};
+
+ /// The leaderboard read's answer; reads of it are listed in [leaderboardReads].
+ Map<String, dynamic>? leaderboard;
+ final leaderboardReads = <String>[];
// The reader's tags, newest last, answered by GET .../mentions?state=.
final mentions = <Map<String, dynamic>>[];
+ // Decisions asked of the reader, newest last, answered by GET .../decisions?state=.
+ final decisions = <Map<String, dynamic>>[];
// How many times the mentions list was read.
int mentionReads = 0;
// A backend from before tags: it has no list route.
@@ -521,6 +530,12 @@ class ConversationServer {
);
messages.last['replyTo'] = command['replyTo'];
output['messageId'] = 'message-$revision';
+ } else if (command['type'] == 'decision.answer') {
+ decisions.firstWhere((d) => d['id'] == command['decisionId'])
+ ..['choice'] = command['choice']
+ ..['answeredAt'] = '2026-10-27T06:00:00Z';
+ state['decisionsWaiting'] = (state['decisionsWaiting'] as int) - 1;
+ revision++;
} else if (command['type'] == 'mention.done') {
mentions.firstWhere((m) => m['id'] == command['mentionId'])
..['resolvedAt'] = '2026-10-24T06:00:00Z'
@@ -664,6 +679,24 @@ class ConversationServer {
}),
) as Map<String, dynamic>;
}
+ if (uri.pathSegments.last == 'leaderboard') {
+ leaderboardReads.add(path);
+ final board = leaderboard;
+ if (board == null) {
+ throw const SuperTabFailure('NOT_FOUND', 'Not found.', statusCode: 404);
+ }
+ return jsonDecode(jsonEncode(board)) as Map<String, dynamic>;
+ }
+ if (uri.pathSegments.last == 'decisions') {
+ final open = uri.queryParameters['state'] == 'open';
+ return jsonDecode(
+ jsonEncode({
+ 'decisions': decisions.reversed
+ .where((d) => (d['answeredAt'] == null) == open)
+ .toList(),
+ }),
+ ) as Map<String, dynamic>;
+ }
if (uri.pathSegments.last == 'routing-policy') {
final policy = routingPolicy;
if (policy == null) {
@@ -777,6 +810,38 @@ class ConversationServer {
group?['lastMessageSequence'] = revision;
}
+ /// The Lead asks the reader [questions] in one batch, as the backend records it.
+ void ask(
+ List<String> questions, {
+ String conversationId = 'lead',
+ String projectId = 'lead',
+ int recommended = 0,
+ }) {
+ final batch = 'batch-${decisions.length + 1}';
+ for (final question in questions) {
+ decisions.add({
+ 'id': 'decision-${decisions.length + 1}',
+ 'batchId': batch,
+ 'projectId': projectId,
+ 'projectName': 'web-project',
+ 'conversationId': conversationId,
+ 'conversationTitle': 'Lead',
+ 'askerName': 'Wren',
+ 'question': question,
+ 'options': ['Behind a flag', 'To everyone'],
+ 'recommended': recommended,
+ 'unblocks': 'The release',
+ 'createdAt': '2026-10-27T05:00:00Z',
+ 'answeredAt': null,
+ 'choice': null,
+ 'note': null,
+ });
+ }
+ state['decisionsWaiting'] =
+ ((state['decisionsWaiting'] as int?) ?? 0) + questions.length;
+ revision++;
+ }
+
/// Who asks, for the reads a [controller] makes: a private conversation is
/// read by its audience alone. A zone value, so that subclasses overriding
/// [request] keep it.
diff --git a/desktop/tool/super_tab_local_review.dart b/desktop/tool/super_tab_local_review.dart
index d570c883b..0d0581026 100644
--- a/desktop/tool/super_tab_local_review.dart
+++ b/desktop/tool/super_tab_local_review.dart
@@ -4,7 +4,7 @@
/// loopback origin that passes `/api/` to the local backend of the local
/// backend recipe (fake SSO tokens, local MongoDB and Redis). Open it with
/// `?tab=<id>&as=owner|peer` and optionally `&open=pm` (that person's Chat
-/// with PM, created on first use) or `&group=<id>`. It refuses any origin but
+/// with PM, created on first use) or `&group=<id>`, and `&glance=1` to open Team at a glance. It refuses any origin but
/// 127.0.0.1 and knows only the recipe's two fake test tokens: it never
/// reaches a real account or production data.
library;
@@ -17,6 +17,7 @@ import 'package:harness/shared/theme/app_theme.dart' as grid;
import 'package:harness/shared/theme/color_palette.dart';
import 'package:harness/super_tabs/controller.dart';
import 'package:harness/super_tabs/model.dart';
+import 'package:harness/super_tabs/team_glance_panel.dart';
import 'package:harness/super_tabs/view.dart';
import 'package:web/web.dart' as web;
@@ -112,8 +113,10 @@ Future<void> _review() async {
debugPrint('review: opened ${controller.selectedId}');
await controller.loadMessages(controller.selectedId);
debugPrint('review: messages loaded');
+ final navigator = GlobalKey<NavigatorState>();
runApp(
MaterialApp(
+ navigatorKey: navigator,
debugShowCheckedModeBanner: false,
theme: grid.buildAppTheme(brightness: palette.brightness),
home: Scaffold(
@@ -127,4 +130,10 @@ Future<void> _review() async {
),
),
);
+ if (query['glance'] == '1') {
+ WidgetsBinding.instance.addPostFrameCallback(
+ (_) =>
+ showSuperTabTeamGlance(navigator.currentContext!, controller, null),
+ );
+ }
}
diff --git a/docs/design/2026-10-27-swarm-decisions.md b/docs/design/2026-10-27-swarm-decisions.md
new file mode 100644
index 000000000..3f2fb971d
--- /dev/null
+++ b/docs/design/2026-10-27-swarm-decisions.md
@@ -0,0 +1,76 @@
+# Swarm decisions: questions to a person, in one place
+
+Status: built on `feat/swarm-v2` (PR #1753). Brief: Lead, 2026-10-27, conversation "Decisions".
+
+People were asked for decisions in scattered pings: a needs-human line in a work group, a tag in a Lead message, a
+question in chat. A decision now has one shape and one place:
+
+- **What a decision holds:**
+ - one question;
+ - 2 to 5 options;
+ - the option the asker recommends;
+ - what an answer unblocks;
+ - the person asked;
+ - the asking agent;
+ - the conversation it came from, and the task, when it came from a worker's needs-human.
+- **Who asks:**
+ - The project's Lead, with `decision.ask`: up to 10 questions to one person at once, in one of its project's
+ conversations.
+ - A worker, on its own task, with `work.status` `needs_human` plus `ask`. The question is its result. Without
+ `ask`, needs-human reaches the Lead as before, and the Lead asks.
+- **Batching:** one ask is one batch. The person gets one list and one badge, not a ping per question, and sees the
+ batch together ("Wren asked 2 questions · project · conversation").
+- **Answering:**
+ - The person asked taps one option (`decision.answer`), once. A viewer may answer what was asked of them.
+ - The asking agent and the project's Lead get a notice in the conversation the question came from. Only they read
+ it, and it carries none of the answer; it points them to `harness super-tab decisions --answered`, which checks who
+ reads it. Other readers of the conversation see nothing: no message, no unread mark, no link (review of #1753).
+ - The person must still be in the Swarm and still read that conversation, when answering and when an answer is
+ retried. An answer in a quiet or archived conversation works like any other.
+ - An exact repeat of an open ask is the same decision, not a second one: the same asker, task, question, options,
+ recommendation and what it unblocks. Another asker, another task or other options with the same text is a decision of
+ its own.
+- **Provisional work:** the asker keeps working on its recommendation, marked provisional, until the answer arrives.
+ The Lead and Builder skills say so.
+- **Who reads a decision:**
+ - The person asked: Desktop/web lists it in Notifications, and in their Chat with PM for that project.
+ - The asking agent: `harness super-tab decisions [--answered]`.
+ - The project's Lead.
+ - Nobody else, the Swarm's owner included.
+
+## A decision is not a private channel
+
+A decision is about the work, and it is seen where the work is seen:
+- The question a worker writes is in its own terminal.
+- A needs-human question still shows in its work group.
+- The answer is read through `harness super-tab decisions --answered`, in the asking agent's terminal.
+
+Anything private goes through the person's Chat with PM. A decision asked there stays inside that private
+conversation.
+
+## Where it lives
+
+- **Storage:** decisions are rows in `SuperTabDecision` (`backend/src/superTabs/decisions.ts`), outside the tab
+ state, as mentions are. No state part changes, and an older backend ignores them.
+- **Reads:**
+ - `GET /api/super-tabs/:tabId/decisions?state=open|answered[&asAgentId=]`.
+ - First load and changes carry the person's open count as `derived.decisionsWaiting`.
+ - A light change read also loads the conversations the person's open decisions are in, so the count holds.
+- **Team machines:** the read is on the team-session allowlist for agents (`backend/src/lib/teamSession.ts`).
+
+## Seen on an isolated stack
+
+Taken 2026-10-27 after the review fixes (the answer notice only the asker and the Lead read). Everything ran on 127.0.0.1:
+- loopback MongoDB and Redis containers;
+- the fake sign-in of the local backend recipe;
+- this branch's backend;
+- the web build of `desktop/tool/super_tab_local_review.dart` as the second person.
+
+The Lead asked through the real `decision.ask`.
+- The person's Chat with PM, with that project's open decisions above its messages:
+ ![Chat with PM](2026-10-27-swarm-decisions/1-chat-with-pm.png)
+- The Decisions list in Notifications, one batch per ask, with the recommendation marked:
+ ![Decisions](2026-10-27-swarm-decisions/2-decisions-list.png)
+- After one tap. The choice shows and the count drops. The person's Chat with PM gets no message and no unread mark.
+ The Lead's notice there carries none of the answer, and the Lead's decisions read has it:
+ ![Answered](2026-10-27-swarm-decisions/3-answered.png)
diff --git a/docs/design/2026-10-27-swarm-decisions/1-chat-with-pm.png b/docs/design/2026-10-27-swarm-decisions/1-chat-with-pm.png
new file mode 100644
index 000000000..0f6976494
Binary files /dev/null and b/docs/design/2026-10-27-swarm-decisions/1-chat-with-pm.png differ
diff --git a/docs/design/2026-10-27-swarm-decisions/2-decisions-list.png b/docs/design/2026-10-27-swarm-decisions/2-decisions-list.png
new file mode 100644
index 000000000..cf4371550
Binary files /dev/null and b/docs/design/2026-10-27-swarm-decisions/2-decisions-list.png differ
diff --git a/docs/design/2026-10-27-swarm-decisions/3-answered.png b/docs/design/2026-10-27-swarm-decisions/3-answered.png
new file mode 100644
index 000000000..78150bc2e
Binary files /dev/null and b/docs/design/2026-10-27-swarm-decisions/3-answered.png differ
diff --git a/docs/plans/2026-10-27-swarm-scheduler.md b/docs/plans/2026-10-27-swarm-scheduler.md
new file mode 100644
index 000000000..241890d91
--- /dev/null
+++ b/docs/plans/2026-10-27-swarm-scheduler.md
@@ -0,0 +1,186 @@
+# Swarm scheduler prototype: one plan for every task at once
+
+Status: prototype, not wired into routing (v2 E). Code: [`tools/scheduler/`](../../tools/scheduler/README.md).
+
+## Why
+
+Today's route places one task at a time. It takes the first candidate in a fixed order (cheaper in effect, stronger,
+more quota room; [`route.ts`](../../cli/src/superTabs/route.ts) `choose`) and never looks at what else is queued. Dee's
+goal is the global optimum for M tasks on N machines and their models, in this order:
+
+1. **Quality**: every task gets a model at or above its floor (a hard limit).
+2. **Finish time**: the time the last task ends (makespan), given dependencies, machine slots and model limits.
+3. **Cost**: the policy cost of the work, among the plans with the least finish time.
+
+The prototype solves that exactly with OR-Tools CP-SAT. It also gives the full set of plans where finish time can only
+be bought with cost (the Pareto set). It compares its plan with today's route and with what the Swarm actually picked
+on the night of 2026-10-26.
+
+## Formulation
+
+Inputs, in whole minutes:
+
+- **Task** *t*: estimate *e_t*, floor *f_t*, kind, dependencies *D_t*, tasks it must differ from *I_t* (a review and
+ its build), and weekly spend *s_t* at policy cost 2.
+- **Machine** *m*: slots *S_m* and engines.
+- **Model** *k*: engine, family, policy cost *c_k*, quality *q_k(kind)*, speed *v_k*, an optional limit *L_k* on tasks at
+ once (a local model serves 1 Builder, a shared API 4), and whether it spends the machine's subscription.
+- **Account** *a*: the machines and engines that share it, and the weekly quota *B_a* left after the reserve.
+
+An option *(t, m, k)* exists when *k*'s engine is on *m* and *q_k(kind_t) ≥ f_t*, so the quality floor is enforced
+by construction. Its duration is *d = ⌈e_t / v_k⌉*.
+
+Variables: a boolean *x_tmk* per option, and integer *start_t* and *end_t*.
+
+- Exactly one option per task: *Σ_mk x_tmk = 1*.
+- An optional interval of length *d_tmk* at *start_t*, present when *x_tmk* is set; *end_t = start_t + d_tmk* when it is.
+- Dependencies: *start_t ≥ end_p* for every *p ∈ D_t*.
+- Slots: a cumulative constraint per machine, capacity *S_m*.
+- Model limits: a cumulative constraint per model with a limit, capacity *L_k*.
+- Review independence: for each *u ∈ I_t* and family *F*, at most one of *t* and *u* uses a model of *F*.
+- Quota: for each account, *Σ x_tmk · s_t · c_k / 2 ≤ B_a* over the options that spend it (the route's
+ `sizeUp` scaling). This is the weekly window only; the exact plan has no 5-hour constraint.
+
+Objectives, lexicographic: first minimise *M = max_t end_t*. Then fix *M ≤ M\** and minimise
+*Σ x_tmk · c_k · e_t*. Both phases share one time limit (10 s by default), and each reports its bound. A
+result is `OPTIMAL` only when both phases prove optimality. Otherwise it is `FEASIBLE` with the gap.
+
+Pareto set: start with the lexicographic optimum *(M₁, C₁)*. Then repeat with *cost ≤ C_i − 1* until it is
+infeasible. Each step gives the fastest plan that is cheaper than the last one, at its least cost, so every proven step
+is on the front and the walk is exact.
+
+## Baseline: today's route
+
+`greedy.py` is a port of route.ts `sizeUp`, `choose` and `compare`. Each task is routed when it becomes ready, meaning
+its dependencies are done. Its candidates are the options at its floor or, if there are none, the best below it, and
+only the strongest for a hard task. Candidates whose quota fits come before unknown ones, and unknown before short.
+They are ordered by **effective cost**, then strength, then a machine's own engine before a shared API, then room on
+the tightest window, then the candidate's title. Effective cost is the route's:
+
+- If a 5-hour window resets before the task is over (plus an hour), the part the task would use is free, because it
+ would otherwise be lost. Near an Opus reset, Opus can beat cheaper Codex.
+- A task that is not hard pays extra for taking more than a day's share of the weekly window.
+
+The quota is read at the moment the task is routed. Work run since the start has used it, open picks hold the rest of
+their expected spend (decaying over their run time, as in the route), and a 5-hour window refills to 100% at each
+reset, every 5 hours. The exact plan does not model 5-hour windows at all: it budgets the weekly quota only. A review leaves out the family its build was given,
+as the Lead asks the route for. Then the task starts as early as its machine's slots and model limit allow.
+
+Left out: members (every pick is a new agent) and soft rules (this Swarm has none). The owner's hard machine rule
+applies to every plan (see below). The route does not look at slots, and the backend refuses a start on a full machine
+(`MACHINE_FULL`). The baseline queues the task there instead, which flatters the route.
+
+## Tonight's data
+
+Sources: the Lead's route log (75 requests with difficulty, risk, size and kind) and a Swarm status snapshot read
+at 2026-10-26 23:12 UTC (groups, assignments, 7 machines with slots and quotas, the owner's rules). Both are committed
+redacted, next to the converter: [`data/2026-10-26-status.redacted.json`](../../tools/scheduler/data/2026-10-26-status.redacted.json)
+and [`data/2026-10-26-route-log.redacted.json`](../../tools/scheduler/data/2026-10-26-route-log.redacted.json).
+`python -m scheduler redact` keeps only the fields the converter reads, so emails, briefs and home folders are dropped,
+and it replaces people's names (taken from their emails) in machine names, titles, rule texts and route reasons.
+`python -m scheduler convert` turns them, with the hand-checked
+[`data/2026-10-26-night.config.json`](../../tools/scheduler/data/2026-10-26-night.config.json), into
+[`data/2026-10-26-night.json`](../../tools/scheduler/data/2026-10-26-night.json): 42 tasks, 6 machines, 5 models (Opus,
+Codex, Sonnet, Haiku and the shared DeepSeek API) and 7 accounts. A test checks that converting the redacted inputs
+gives the same instance as the originals, apart from the replaced names.
+
+The owner's hard rule leaves six machines (it excludes WIN-DELL until it is fixed). The route refuses any other, so
+every plan here keeps to the six. None of tonight's picks ran on WIN-DELL.
+
+Read from the data: the machines, their slots and engines, the quota windows and their reset times, each group's
+assignment (machine, engine, model) and, for 12 groups, their own route request.
+
+**Estimates**, which the comparison depends on:
+
+| Input | Estimate |
+| --- | --- |
+| Task length and spend | The route's size table: small 20 min, medium 60, large 180; 5-hour 10, 30 and 50, weekly 1, 4 and 8 at cost 2 |
+| 20 groups' assessments | 14 are named by a variable in the log and matched by time and title. 6 have no request of their own and reuse a neighbouring one (G5 takes G3's, fixes C2 and I3 take C1's) |
+| 10 groups' assessments | No route request (research, G6, v1 liveness A and B, v2 A–E started directly): set by hand |
+| Dependencies | Read from the titles: a review after its build, and the 1726 chain (G1 → review → G2/G3 → G4/G5/G3b → G6 → merge → final review → fixes → their reviews) |
+| Policy | The default routing policy. The tab's effective policy is not in the snapshot |
+| Speed | 1.0 for every model: there is no data |
+| Accounts | Machines that report the same weekly reading are taken to share one account. The snapshot has no account keys |
+| Starting weekly quota | The snapshot is taken after the night. Every plan gets the weekly quota left plus what the actual picks are expected to have spent, at most 100% |
+| 5-hour windows | As read at the snapshot; a window whose reset has passed since its machine was observed is taken as full |
+
+Left out: 6 smoke tests and checks that a person pinned to one machine and model. The scheduler has nothing to
+choose for them.
+
+One limit applies to the whole comparison: it schedules the night's 42 tasks as one batch, known from the start. The
+real night learned of them over ten hours, so the result shows what a plan made with hindsight could gain, not what
+the route lost on any single decision.
+
+## Results
+
+Command: `python -m scheduler compare data/2026-10-26-night.json [--max-slots N]`, on an M-series Mac with 8 workers.
+Cost is the policy cost × estimated minutes.
+
+| Slots | Plan | Finish (min) | Cost | Solve |
+| --- | --- | --- | --- | --- |
+| as contributed (1–16) | exact | **800** (proven) | **7,440** (proven) | 0.14 s |
+| | today's route | 1,100 | 7,600 | – |
+| | tonight's picks | 800 | 10,100 | – |
+| at most 2 per machine | exact | **800** | **7,440** | 0.16 s |
+| | today's route | 1,460 | 7,800 | – |
+| | tonight's picks | 1,000 | 10,100 | – |
+| at most 1 per machine | exact | **800** | **7,440** | 0.20 s |
+| | today's route | 2,160 | 7,620 | – |
+| | tonight's picks | 1,840 | 10,100 | – |
+
+No plan breaks a floor or a review's family rule. 800 minutes is the critical path of the 1726 chain, so no plan can
+finish sooner. By the size table, tonight's picks would have spent 126% of MacBookPro2021's weekly Claude window
+(14 Opus tasks, 7 large and 7 medium), so the comparison lists them as over its quota. The account shows only 30% used
+now, so the table overestimates Opus spend by more than double. That is why the starting quota is capped at 100%, and
+why the quota inputs are estimates.
+
+- **Against tonight's picks, the exact plan costs 26% less at the same finish time.** Tonight ran 25 tasks on Opus
+ and 17 on Codex. The exact plan runs 22 on Codex, 14 on Opus and 6 on Sonnet. In the policy, Codex is as strong as
+ Opus (quality 3) and cheaper (2 against 3). Opus is kept for the reviews of Codex work, and Sonnet for 6 of the 7
+ tasks with floor 2. The saving relies on the policy's ratings. If Opus is in fact stronger for this work, the policy
+ should say so, and the solver will follow it.
+- **Against today's route, the exact plan finishes 27% sooner and costs 2% less; with 2 slots per machine 45% sooner,
+ with 1 slot 63% sooner.** The route ranks by effective cost and quota room, and never by queue. It sent 9 tasks
+ (900 minutes of work) to the one-slot MacBooks-MacBook-Pro-19, whose Codex account had the most room, and they wait
+ there in turn. The exact plan also uses that machine, but with short work that fits beside the critical path.
+- **Tonight's picks are fragile under load.** They piled 21 tasks on Mac Studio and 14 on MacBookPro2021, which is
+ fine with 16 and 8 slots, but at one slot per machine they finish at 1,840 minutes against 800.
+- **The Pareto set has one point** on this night: the cheapest plan also reaches the critical path, so there is no
+ trade-off to choose from. Generated busy nights have several (below).
+
+### Solve time
+
+Generated instances (`scheduler/bench.py`) are shaped like a busy night: builds with reviews (40%), chains, 1–4 slots
+per machine, binding quotas, and six models that differ in strength, cost and speed (one is a local model serving one
+Builder at a time). Three seeds each:
+
+| Tasks × machines × models | Solve (s) | Result |
+| --- | --- | --- |
+| 30 × 8 × 6 (the brief's limit: 10 s) | 0.25, 0.27, 0.23 | all proven optimal |
+| 60 × 12 × 6 | 1.12, 1.47, 1.42 | all proven optimal |
+| 100 × 16 × 6 | 4.91, 3.93, 3.87 | all proven optimal |
+| 150 × 20 × 6 | 8.64, 10.01, 9.73 | 1 proven; 2 found the least finish time but ran out of time on cost |
+
+The Pareto set on 30 × 8 × 6 is exact and complete in 1.4–2.3 s. For seed 1, its 7 points run from 468 minutes at cost
+3,860 to 509 minutes at 3,500: 41 more minutes saves 9%.
+
+## What this suggests
+
+- An exact global plan is cheap at the Swarm's size. Tonight solves in a fifth of a second, and 100 tasks in about 5 s.
+ No performance work was needed.
+- The largest gain on real data is not ordering but the choice of model under the policy, and the policy's ratings
+ decide it. Rating Opus above Codex, or giving quality per task kind (the format already takes it), changes the plan.
+- The route's blind spot is the queue: it ranks by effective cost and quota room, and ignores slots.
+
+Next steps, if this goes ahead: offer the exact plan to the Lead as advice beside the route's pick, and re-solve
+whenever a task arrives or finishes, with running tasks fixed. Learn task lengths and model speed from the attempts'
+times instead of the size table. Read the tab's effective policy and account keys rather than estimating them.
+
+Not modelled: 5-hour windows (they refill during a night, so a fixed budget would be wrong; modelling them needs
+time-indexed use), owner rules, reusing an idle member, memory and disk.
+
+## Validation
+
+`cd tools/scheduler && python -m unittest discover -s tests -t .` (Python 3.9, `ortools==9.15.6755`): 76 tests.
+Each constraint's test fails when that constraint is removed from the model and passes when it is restored. PR CI runs
+process checks only for `tools/` and `docs/`.
diff --git a/docs/swarms.md b/docs/swarms.md
index c81e0ae12..a99f8f162 100644
--- a/docs/swarms.md
+++ b/docs/swarms.md
@@ -183,6 +183,49 @@ chat only: no work is assigned in it, and only the product manager joins it
among agents. As with any session, the owner of the machine running the
product manager can see what its terminal shows.
+## Leaderboard
+
+The leaderboard shows how each person helped the team ship this week. People
+compete for fun, but the reward is shared: the team's goal is on top, and
+everyone's points count toward it. In Desktop and the web app, the trophy in the
+conversation header opens it. On a wide window it opens as a column at the far
+right, beside People. On a narrower one it opens as a dialog. It shows the project
+of the open conversation to the people who can read that project.
+
+Each person has three numbers:
+
+- **Shipped**: requests the person asked for whose work is Done with a linked
+ pull request. A group records its requester when it is opened. A person's own
+ new group names them, and a product manager names the person who asked in the
+ project chat or in their Chat with PM. Product managers mark a group Done only
+ after its pull request has merged. 3 points each.
+- **Unblocked**: items needing a person that the person answered. An answer counts
+ when it comes from the person the item waits on, or when it replies to the
+ question itself. That person is the group's requester, or the project's owner
+ when the group has none. 1 point each, plus 1 point for every 2 hours the agents
+ waited for those answers.
+- **Lent**: hours Swarm agents ran on the person's contributed machines, added up
+ from each machine's readings. A product manager's session doesn't count: it
+ coordinates in confidence and doesn't build. 1 point for every 10 hours.
+
+The top three get medals, and people with the same points share a place. A
+streak counts the days in a row, up to today, with a shipped request. Tapping a
+name shows that person's week: the median time from asking to shipping, the
+median time to answer, and the hours freed and lent. The team goal compares the
+project's open requests, what shipped and the median time from asking to
+shipping with the week before. Weeks run from Monday 00:00 UTC, and the week
+picker reaches back three weeks.
+
+**Agents waiting on a person now** lists who agents are waiting on and how many
+items each, in name order. An item leaves the list as soon as it is answered. It is never ranked and never earns points. **Answer**
+opens the reader's own waiting item, or the first one when none waits on them.
+
+Only facts count, never text. The leaderboard records when work was asked for and
+shipped, who answered and how long agents waited. It never records what anyone
+wrote. Private conversations, Chat with PM among them, never count and never
+appear in it. Decisions asked of a person will count toward Unblocked once
+decisions ship.
+
## Lead updates
The default update cadence is five minutes; the project menu also offers one,
diff --git a/tools/scheduler/.gitignore b/tools/scheduler/.gitignore
new file mode 100644
index 000000000..21d0b898f
--- /dev/null
+++ b/tools/scheduler/.gitignore
@@ -0,0 +1 @@
+.venv/
diff --git a/tools/scheduler/README.md b/tools/scheduler/README.md
new file mode 100644
index 000000000..cf232cfac
--- /dev/null
+++ b/tools/scheduler/README.md
@@ -0,0 +1,43 @@
+# Swarm scheduler (prototype)
+
+Places every task on a machine and a model at once. Quality floors are a hard limit; it minimises finish time, then
+cost, and proves the result optimal with OR-Tools CP-SAT. It does not route anything yet. Formulation and results:
+[docs/plans/2026-10-27-swarm-scheduler.md](../../docs/plans/2026-10-27-swarm-scheduler.md).
+
+```sh
+cd tools/scheduler
+python3 -m venv .venv && .venv/bin/pip install -r requirements.txt
+.venv/bin/python -m unittest discover -s tests -t .
+
+# The exact plan, or the Pareto set of finish time against cost, as JSON
+.venv/bin/python -m scheduler solve data/2026-10-26-night.json [--pareto] [--time-limit 10]
+# Exact plan, today's route and the picks the Swarm made, side by side
+.venv/bin/python -m scheduler compare data/2026-10-26-night.json [--max-slots 1]
+# A Swarm status snapshot and the Lead's route log, cut to what convert reads, without emails or people's names
+.venv/bin/python -m scheduler redact STATUS.json ROUTE_LOG.json STATUS_OUT.json ROUTE_LOG_OUT.json
+# Those inputs to a night file (this reproduces data/2026-10-26-night.json)
+.venv/bin/python -m scheduler convert data/2026-10-26-status.redacted.json data/2026-10-26-route-log.redacted.json \
+ data/2026-10-26-night.config.json OUT.json
+```
+
+## In the Swarm: `harness super-tab plan`
+
+A Lead runs `harness super-tab plan [JSON]` to get the best plan for all of its open groups at once: per group the machine,
+engine, model and effort, start order and expected finish, with the finish time and cost against routing one group at a
+time. It is advice only: the route still decides, and the Lead starts the plan's pick with `overrideReason "scheduler plan"`.
+The CLI builds the input from the live Swarm (`cli/src/superTabs/planInput.ts`), with the route's hard rules and readiness
+checks, and runs this package with the Lead's `python3` (`cli/src/superTabs/planCommand.ts`). The release carries the
+package's files inside `cli.js` (`cli/build-bundle.mjs`). Without Python or OR-Tools the command says how to install them:
+`python3 -m pip install ortools==9.15.6755`.
+
+| File | What it does |
+| --- | --- |
+| `scheduler/instance.py` | Instance format, checks, and the options that meet each task's floor |
+| `scheduler/solver.py` | CP-SAT model, the lexicographic solve and the Pareto set |
+| `scheduler/greedy.py` | Today's route (route.ts `sizeUp`, `choose`, `compare`) as a baseline, and the earliest start of a fixed assignment |
+| `scheduler/plan.py` | The plan for open work, as `harness super-tab plan` reads it |
+| `scheduler/compare.py` | The three plans side by side, and what a fixed plan breaks |
+| `scheduler/swarm.py` | Swarm status and route log to an instance |
+| `scheduler/redact.py` | The inputs cut to what `swarm.py` reads, with people's names replaced |
+| `scheduler/bench.py` | Generated busy nights for the solve-time check |
+| `data/` | The 2026-10-26 night: redacted status and route log, hand-checked inputs (`*.config.json`) and the converted instance |
diff --git a/tools/scheduler/data/2026-10-26-night.config.json b/tools/scheduler/data/2026-10-26-night.config.json
new file mode 100644
index 000000000..fc62204b0
--- /dev/null
+++ b/tools/scheduler/data/2026-10-26-night.config.json
@@ -0,0 +1,316 @@
+{
+ "about": "Inputs for the 2026-10-26 night that the Swarm status does not hold. Policy: the default routing policy (backend/src/superTabs/routingPolicy.ts), as the tab's effective policy is not in the snapshot. Dependencies: read from the group titles (a review after its build, the 1726 chain), an estimate.",
+ "policy": {
+ "models": [
+ {
+ "engine": "claude",
+ "model": "opus",
+ "effort": "high",
+ "quality": 3,
+ "cost": 3,
+ "enabled": true
+ },
+ {
+ "engine": "codex",
+ "model": "default",
+ "effort": "default",
+ "quality": 3,
+ "cost": 2,
+ "enabled": true
+ },
+ {
+ "engine": "claude",
+ "model": "sonnet",
+ "effort": "medium",
+ "quality": 2,
+ "cost": 2,
+ "enabled": true
+ },
+ {
+ "engine": "claude",
+ "model": "haiku",
+ "effort": "auto",
+ "quality": 1,
+ "cost": 1,
+ "enabled": true
+ }
+ ],
+ "floor": {
+ "low": 1,
+ "medium": 2,
+ "high": 3
+ },
+ "quotaReserve": 10,
+ "localModels": {
+ "quality": 1,
+ "enabled": true
+ }
+ },
+ "assessments": {
+ "2b8a76771f8d6e8380101ad0": {
+ "route": 20,
+ "note": "request named by a variable in the log, matched by time and title"
+ },
+ "5c48779c71d5111602eab51f": {
+ "route": 28,
+ "note": "request named by a variable in the log, matched by time and title"
+ },
+ "c2e38ce017f6f8e65ef8bdce": {
+ "route": 30,
+ "note": "request named by a variable in the log, matched by time and title"
+ },
+ "0a84ea687a435833d1649933": {
+ "route": 30,
+ "note": "no request of its own; takes G3's read-path request (same rewrite, CLI side)"
+ },
+ "2e2d726a3ff6196c26d44f8f": {
+ "route": 32,
+ "note": "request named by a variable in the log, matched by time and title"
+ },
+ "5f0d3516fb850999cb824c90": {
+ "route": 44,
+ "note": "request named by a variable in the log, matched by time and title"
+ },
+ "7a23487b3220d1564f9c7522": {
+ "route": 54,
+ "note": "no request of its own; takes the log's standard independent review request"
+ },
+ "e141b9c91ab56d8509789a49": {
+ "route": 54,
+ "note": "request named by a variable in the log, matched by time and title"
+ },
+ "1e43f418b6c92f435689581d": {
+ "route": 55,
+ "note": "request named by a variable in the log, matched by time and title"
+ },
+ "d71cdb0a2ab3181904d5eb3d": {
+ "route": 56,
+ "note": "request named by a variable in the log, matched by time and title"
+ },
+ "32777a379c1fd8cccfde3e85": {
+ "route": 57,
+ "note": "request named by a variable in the log, matched by time and title"
+ },
+ "400c47daa5f4e2be6ab1c2e3": {
+ "route": 67,
+ "note": "request named by a variable in the log, matched by time and title"
+ },
+ "4bc913c9bf52f96cadbcd419": {
+ "route": 68,
+ "note": "request named by a variable in the log, matched by time and title"
+ },
+ "42f34fffe4223cab2ff79e69": {
+ "route": 69,
+ "note": "request named by a variable in the log, matched by time and title"
+ },
+ "977d937c468e7720151c780e": {
+ "route": 73,
+ "note": "request named by a variable in the log, matched by time and title"
+ },
+ "b365e73faae5aa84b1b4d544": {
+ "route": 73,
+ "note": "no request of its own; takes fix C1's request"
+ },
+ "3f97d137a02c078abfdc7d74": {
+ "route": 73,
+ "note": "no request of its own; takes fix C1's request"
+ },
+ "42095c031091b32d2d5e163b": {
+ "route": 74,
+ "note": "no request of its own; takes the focused re-check request"
+ },
+ "a8c17a1e4fb9b75f771b67a7": {
+ "route": 74,
+ "note": "no request of its own; takes the focused re-check request"
+ },
+ "5c6b795d846d44bfb7591837": {
+ "route": 74,
+ "note": "request named by a variable in the log, matched by time and title"
+ },
+ "e6115d403f62dd42d5cf3ab3": {
+ "estimate": {
+ "difficulty": "medium",
+ "risk": "low",
+ "size": "medium",
+ "kind": "research"
+ },
+ "note": "no route request; estimate"
+ },
+ "acdc5546b9fcc601abb8b22c": {
+ "estimate": {
+ "difficulty": "medium",
+ "risk": "low",
+ "size": "medium",
+ "kind": "research"
+ },
+ "note": "no route request; estimate"
+ },
+ "8f099aef658fa637127c3482": {
+ "estimate": {
+ "difficulty": "high",
+ "risk": "high",
+ "size": "medium",
+ "kind": "backend"
+ },
+ "note": "no route request; estimate"
+ },
+ "4c650945b01ab59703017bfb": {
+ "estimate": {
+ "difficulty": "high",
+ "risk": "high",
+ "size": "large",
+ "kind": "backend"
+ },
+ "note": "no route request; estimate like v1 DM"
+ },
+ "b27e3b7574be0b1bf4a76986": {
+ "estimate": {
+ "difficulty": "high",
+ "risk": "high",
+ "size": "large",
+ "kind": "cli"
+ },
+ "note": "no route request; estimate like v1 DM"
+ },
+ "fa552b26cc36df06a9145405": {
+ "estimate": {
+ "difficulty": "high",
+ "risk": "medium",
+ "size": "large",
+ "kind": "cli"
+ },
+ "note": "no route request (started directly); estimate"
+ },
+ "88a2196381c696b3b458543f": {
+ "estimate": {
+ "difficulty": "high",
+ "risk": "medium",
+ "size": "large",
+ "kind": "cli"
+ },
+ "note": "no route request (started directly); estimate"
+ },
+ "04f4dd68dc6273061f4e6194": {
+ "estimate": {
+ "difficulty": "high",
+ "risk": "medium",
+ "size": "large",
+ "kind": "cli"
+ },
+ "note": "no route request (started directly); estimate"
+ },
+ "9109dbd1ee0f97b1f12ce4f5": {
+ "estimate": {
+ "difficulty": "high",
+ "risk": "medium",
+ "size": "large",
+ "kind": "cli"
+ },
+ "note": "no route request (started directly); estimate"
+ },
+ "1dace4d8419a80177f226de1": {
+ "estimate": {
+ "difficulty": "high",
+ "risk": "medium",
+ "size": "large",
+ "kind": "research"
+ },
+ "note": "no route request (started directly); estimate"
+ }
+ },
+ "deps": {
+ "5c48779c71d5111602eab51f": [
+ "aeef05a35995ca9f7cca7060"
+ ],
+ "df0940f037c9f6eef1b92b67": [
+ "5c48779c71d5111602eab51f"
+ ],
+ "c2e38ce017f6f8e65ef8bdce": [
+ "5c48779c71d5111602eab51f"
+ ],
+ "0a84ea687a435833d1649933": [
+ "c2e38ce017f6f8e65ef8bdce"
+ ],
+ "2e2d726a3ff6196c26d44f8f": [
+ "c2e38ce017f6f8e65ef8bdce"
+ ],
+ "6bc636fa6713886102b9cbfa": [
+ "659a6cc93b944bd24cae2884"
+ ],
+ "5f0d3516fb850999cb824c90": [
+ "0a84ea687a435833d1649933"
+ ],
+ "7a23487b3220d1564f9c7522": [
+ "c2e38ce017f6f8e65ef8bdce"
+ ],
+ "e141b9c91ab56d8509789a49": [
+ "2e2d726a3ff6196c26d44f8f"
+ ],
+ "0da3404ca7a4a33f57d4c871": [
+ "df0940f037c9f6eef1b92b67"
+ ],
+ "8f099aef658fa637127c3482": [
+ "0da3404ca7a4a33f57d4c871",
+ "7a23487b3220d1564f9c7522",
+ "5f0d3516fb850999cb824c90",
+ "e141b9c91ab56d8509789a49"
+ ],
+ "45e5e3322e966e128a7d0f3d": [
+ "c2e38ce017f6f8e65ef8bdce"
+ ],
+ "b483494ef289e282021b1e2a": [
+ "45e5e3322e966e128a7d0f3d"
+ ],
+ "400c47daa5f4e2be6ab1c2e3": [
+ "8f099aef658fa637127c3482"
+ ],
+ "4bc913c9bf52f96cadbcd419": [
+ "8f099aef658fa637127c3482",
+ "b483494ef289e282021b1e2a"
+ ],
+ "8718795de795e643c928d3cc": [
+ "4bc913c9bf52f96cadbcd419"
+ ],
+ "42f34fffe4223cab2ff79e69": [
+ "4bc913c9bf52f96cadbcd419"
+ ],
+ "977d937c468e7720151c780e": [
+ "42f34fffe4223cab2ff79e69"
+ ],
+ "b365e73faae5aa84b1b4d544": [
+ "42f34fffe4223cab2ff79e69"
+ ],
+ "3f97d137a02c078abfdc7d74": [
+ "42f34fffe4223cab2ff79e69"
+ ],
+ "5c6b795d846d44bfb7591837": [
+ "977d937c468e7720151c780e"
+ ],
+ "42095c031091b32d2d5e163b": [
+ "b365e73faae5aa84b1b4d544"
+ ],
+ "a8c17a1e4fb9b75f771b67a7": [
+ "3f97d137a02c078abfdc7d74"
+ ],
+ "4f49c22420c3c3fc57dda058": [
+ "b0b28597aa6be5ef38defa6e"
+ ],
+ "1e43f418b6c92f435689581d": [
+ "b27e3b7574be0b1bf4a76986"
+ ],
+ "d71cdb0a2ab3181904d5eb3d": [
+ "4c650945b01ab59703017bfb"
+ ],
+ "32777a379c1fd8cccfde3e85": [
+ "f3a620e144116d08c3a68338"
+ ]
+ },
+ "exclude": {
+ "274baf5b89089a604ebbff4b": "a person pinned it to one machine and the shared DeepSeek model",
+ "aa409e467756f366f8ec67d4": "a person pinned it to one machine and the shared DeepSeek model",
+ "feb85d3aef2375b81b4275eb": "a person pinned it to one machine and the shared DeepSeek model",
+ "d80142e540abade0e9ac21de": "a person pinned it to one machine and the shared DeepSeek model",
+ "8c0d038efe1b63d3b6628552": "a person pinned it to one machine and the shared DeepSeek model",
+ "e37ffff373d0afd7fc763726": "a person pinned it to one machine (a version and log check)"
+ }
+}
diff --git a/tools/scheduler/data/2026-10-26-night.json b/tools/scheduler/data/2026-10-26-night.json
new file mode 100644
index 000000000..c41f879d3
--- /dev/null
+++ b/tools/scheduler/data/2026-10-26-night.json
@@ -0,0 +1,1313 @@
+{
+ "instance": {
+ "tasks": [
+ {
+ "id": "9e7e516b4e7e1f90d7c9ca43",
+ "title": "Regression: API models in the Swarm",
+ "minutes": 180,
+ "floor": 2,
+ "kind": "testing",
+ "difficulty": "medium",
+ "spend": {
+ "5-hour": 50,
+ "weekly": 8
+ },
+ "deps": [],
+ "independent_of": []
+ },
+ {
+ "id": "2b8a76771f8d6e8380101ad0",
+ "title": "Measure: Super Tab load and message time on the web",
+ "minutes": 60,
+ "floor": 2,
+ "kind": "performance",
+ "difficulty": "medium",
+ "spend": {
+ "5-hour": 30,
+ "weekly": 4
+ },
+ "deps": [],
+ "independent_of": []
+ },
+ {
+ "id": "659a6cc93b944bd24cae2884",
+ "title": "1726 G0: Swarm load benchmark (baseline)",
+ "minutes": 60,
+ "floor": 2,
+ "kind": "backend",
+ "difficulty": "medium",
+ "spend": {
+ "5-hour": 30,
+ "weekly": 4
+ },
+ "deps": [],
+ "independent_of": []
+ },
+ {
+ "id": "aeef05a35995ca9f7cca7060",
+ "title": "1726 G1: design doc for Swarm state by parts",
+ "minutes": 60,
+ "floor": 3,
+ "kind": "design",
+ "difficulty": "high",
+ "spend": {
+ "5-hour": 30,
+ "weekly": 4
+ },
+ "deps": [],
+ "independent_of": []
+ },
+ {
+ "id": "5c48779c71d5111602eab51f",
+ "title": "Review: 1726 G1 design doc",
+ "minutes": 60,
+ "floor": 3,
+ "kind": "review",
+ "difficulty": "high",
+ "spend": {
+ "5-hour": 30,
+ "weekly": 4
+ },
+ "deps": [
+ "aeef05a35995ca9f7cca7060"
+ ],
+ "independent_of": [
+ "aeef05a35995ca9f7cca7060"
+ ]
+ },
+ {
+ "id": "df0940f037c9f6eef1b92b67",
+ "title": "1726 G2: backend storage and commands by parts",
+ "minutes": 180,
+ "floor": 3,
+ "kind": "backend",
+ "difficulty": "high",
+ "spend": {
+ "5-hour": 50,
+ "weekly": 8
+ },
+ "deps": [
+ "5c48779c71d5111602eab51f"
+ ],
+ "independent_of": []
+ },
+ {
+ "id": "c2e38ce017f6f8e65ef8bdce",
+ "title": "1726 G3: backend read API and migration",
+ "minutes": 180,
+ "floor": 3,
+ "kind": "backend",
+ "difficulty": "high",
+ "spend": {
+ "5-hour": 50,
+ "weekly": 8
+ },
+ "deps": [
+ "5c48779c71d5111602eab51f"
+ ],
+ "independent_of": []
+ },
+ {
+ "id": "0a84ea687a435833d1649933",
+ "title": "1726 G5: CLI on the new read API",
+ "minutes": 180,
+ "floor": 3,
+ "kind": "backend",
+ "difficulty": "high",
+ "spend": {
+ "5-hour": 50,
+ "weekly": 8
+ },
+ "deps": [
+ "c2e38ce017f6f8e65ef8bdce"
+ ],
+ "independent_of": []
+ },
+ {
+ "id": "2e2d726a3ff6196c26d44f8f",
+ "title": "1726 G4: Desktop and web on the new read API",
+ "minutes": 180,
+ "floor": 3,
+ "kind": "ui",
+ "difficulty": "high",
+ "spend": {
+ "5-hour": 50,
+ "weekly": 8
+ },
+ "deps": [
+ "c2e38ce017f6f8e65ef8bdce"
+ ],
+ "independent_of": []
+ },
+ {
+ "id": "6bc636fa6713886102b9cbfa",
+ "title": "Review: 1726 G0 benchmark",
+ "minutes": 20,
+ "floor": 2,
+ "kind": "review",
+ "difficulty": "medium",
+ "spend": {
+ "5-hour": 10,
+ "weekly": 1
+ },
+ "deps": [
+ "659a6cc93b944bd24cae2884"
+ ],
+ "independent_of": [
+ "659a6cc93b944bd24cae2884"
+ ]
+ },
+ {
+ "id": "5f0d3516fb850999cb824c90",
+ "title": "Review: 1726 G5 CLI",
+ "minutes": 60,
+ "floor": 3,
+ "kind": "review",
+ "difficulty": "high",
+ "spend": {
+ "5-hour": 30,
+ "weekly": 4
+ },
+ "deps": [
+ "0a84ea687a435833d1649933"
+ ],
+ "independent_of": [
+ "0a84ea687a435833d1649933"
+ ]
+ },
+ {
+ "id": "7a23487b3220d1564f9c7522",
+ "title": "Review: 1726 G3 read API and migration",
+ "minutes": 20,
+ "floor": 3,
+ "kind": "review",
+ "difficulty": "high",
+ "spend": {
+ "5-hour": 10,
+ "weekly": 1
+ },
+ "deps": [
+ "c2e38ce017f6f8e65ef8bdce"
+ ],
+ "independent_of": [
+ "c2e38ce017f6f8e65ef8bdce"
+ ]
+ },
+ {
+ "id": "e6115d403f62dd42d5cf3ab3",
+ "title": "Swarm plan R1: how the lampOS team works",
+ "minutes": 60,
+ "floor": 2,
+ "kind": "research",
+ "difficulty": "medium",
+ "spend": {
+ "5-hour": 30,
+ "weekly": 4
+ },
+ "deps": [],
+ "independent_of": []
+ },
+ {
+ "id": "acdc5546b9fcc601abb8b22c",
+ "title": "Swarm plan R2: pain points of fast agent teams",
+ "minutes": 60,
+ "floor": 2,
+ "kind": "research",
+ "difficulty": "medium",
+ "spend": {
+ "5-hour": 30,
+ "weekly": 4
+ },
+ "deps": [],
+ "independent_of": []
+ },
+ {
+ "id": "e141b9c91ab56d8509789a49",
+ "title": "Review: 1726 G4 Desktop and web",
+ "minutes": 20,
+ "floor": 3,
+ "kind": "review",
+ "difficulty": "high",
+ "spend": {
+ "5-hour": 10,
+ "weekly": 1
+ },
+ "deps": [
+ "2e2d726a3ff6196c26d44f8f"
+ ],
+ "independent_of": [
+ "2e2d726a3ff6196c26d44f8f"
+ ]
+ },
+ {
+ "id": "0da3404ca7a4a33f57d4c871",
+ "title": "Review: 1726 G2 backend storage and commands",
+ "minutes": 20,
+ "floor": 3,
+ "kind": "review",
+ "difficulty": "high",
+ "spend": {
+ "5-hour": 10,
+ "weekly": 1
+ },
+ "deps": [
+ "df0940f037c9f6eef1b92b67"
+ ],
+ "independent_of": [
+ "df0940f037c9f6eef1b92b67"
+ ]
+ },
+ {
+ "id": "8f099aef658fa637127c3482",
+ "title": "1726 G6: integrate, measure, migration dry run",
+ "minutes": 60,
+ "floor": 3,
+ "kind": "backend",
+ "difficulty": "high",
+ "spend": {
+ "5-hour": 30,
+ "weekly": 4
+ },
+ "deps": [
+ "0da3404ca7a4a33f57d4c871",
+ "7a23487b3220d1564f9c7522",
+ "5f0d3516fb850999cb824c90",
+ "e141b9c91ab56d8509789a49"
+ ],
+ "independent_of": []
+ },
+ {
+ "id": "45e5e3322e966e128a7d0f3d",
+ "title": "1726 G3b: reads load only the parts that changed",
+ "minutes": 60,
+ "floor": 3,
+ "kind": "backend",
+ "difficulty": "high",
+ "spend": {
+ "5-hour": 30,
+ "weekly": 4
+ },
+ "deps": [
+ "c2e38ce017f6f8e65ef8bdce"
+ ],
+ "independent_of": []
+ },
+ {
+ "id": "4c650945b01ab59703017bfb",
+ "title": "v1 liveness A: lost work and takeover (backend)",
+ "minutes": 180,
+ "floor": 3,
+ "kind": "backend",
+ "difficulty": "high",
+ "spend": {
+ "5-hour": 50,
+ "weekly": 8
+ },
+ "deps": [],
+ "independent_of": []
+ },
+ {
+ "id": "b27e3b7574be0b1bf4a76986",
+ "title": "v1 liveness B: host progress and Lead takeover (CLI)",
+ "minutes": 180,
+ "floor": 3,
+ "kind": "cli",
+ "difficulty": "high",
+ "spend": {
+ "5-hour": 50,
+ "weekly": 8
+ },
+ "deps": [],
+ "independent_of": []
+ },
+ {
+ "id": "b0b28597aa6be5ef38defa6e",
+ "title": "v1 routing: only machines that can do the work",
+ "minutes": 60,
+ "floor": 3,
+ "kind": "cli",
+ "difficulty": "high",
+ "spend": {
+ "5-hour": 30,
+ "weekly": 4
+ },
+ "deps": [],
+ "independent_of": []
+ },
+ {
+ "id": "f3a620e144116d08c3a68338",
+ "title": "v1 DM: a private chat with the PM for each person (Desktop and web)",
+ "minutes": 180,
+ "floor": 3,
+ "kind": "ui",
+ "difficulty": "high",
+ "spend": {
+ "5-hour": 50,
+ "weekly": 8
+ },
+ "deps": [],
+ "independent_of": []
+ },
+ {
+ "id": "4f49c22420c3c3fc57dda058",
+ "title": "Review: v1 routing: only machines that can do the work",
+ "minutes": 20,
+ "floor": 3,
+ "kind": "review",
+ "difficulty": "high",
+ "spend": {
+ "5-hour": 10,
+ "weekly": 1
+ },
+ "deps": [
+ "b0b28597aa6be5ef38defa6e"
+ ],
+ "independent_of": [
+ "b0b28597aa6be5ef38defa6e"
+ ]
+ },
+ {
+ "id": "1e43f418b6c92f435689581d",
+ "title": "Review: v1 liveness B: host progress and Lead takeover (CLI)",
+ "minutes": 20,
+ "floor": 3,
+ "kind": "review",
+ "difficulty": "high",
+ "spend": {
+ "5-hour": 10,
+ "weekly": 1
+ },
+ "deps": [
+ "b27e3b7574be0b1bf4a76986"
+ ],
+ "independent_of": [
+ "b27e3b7574be0b1bf4a76986"
+ ]
+ },
+ {
+ "id": "d71cdb0a2ab3181904d5eb3d",
+ "title": "Review: v1 liveness A: lost work and takeover (backend)",
+ "minutes": 20,
+ "floor": 3,
+ "kind": "review",
+ "difficulty": "high",
+ "spend": {
+ "5-hour": 10,
+ "weekly": 1
+ },
+ "deps": [
+ "4c650945b01ab59703017bfb"
+ ],
+ "independent_of": [
+ "4c650945b01ab59703017bfb"
+ ]
+ },
+ {
+ "id": "b483494ef289e282021b1e2a",
+ "title": "Review: 1726 G3b: reads load only the parts that changed",
+ "minutes": 20,
+ "floor": 3,
+ "kind": "review",
+ "difficulty": "high",
+ "spend": {
+ "5-hour": 10,
+ "weekly": 1
+ },
+ "deps": [
+ "45e5e3322e966e128a7d0f3d"
+ ],
+ "independent_of": [
+ "45e5e3322e966e128a7d0f3d"
+ ]
+ },
+ {
+ "id": "32777a379c1fd8cccfde3e85",
+ "title": "Review: v1 DM: Chat with PM (Desktop and web)",
+ "minutes": 20,
+ "floor": 3,
+ "kind": "review",
+ "difficulty": "high",
+ "spend": {
+ "5-hour": 10,
+ "weekly": 1
+ },
+ "deps": [
+ "f3a620e144116d08c3a68338"
+ ],
+ "independent_of": [
+ "f3a620e144116d08c3a68338"
+ ]
+ },
+ {
+ "id": "400c47daa5f4e2be6ab1c2e3",
+ "title": "Review: 1726 G6 results doc",
+ "minutes": 20,
+ "floor": 2,
+ "kind": "review",
+ "difficulty": "medium",
+ "spend": {
+ "5-hour": 10,
+ "weekly": 1
+ },
+ "deps": [
+ "8f099aef658fa637127c3482"
+ ],
+ "independent_of": [
+ "8f099aef658fa637127c3482"
+ ]
+ },
+ {
+ "id": "4bc913c9bf52f96cadbcd419",
+ "title": "1726 final: merge main into the feature branch",
+ "minutes": 60,
+ "floor": 3,
+ "kind": "merge",
+ "difficulty": "medium",
+ "spend": {
+ "5-hour": 30,
+ "weekly": 4
+ },
+ "deps": [
+ "8f099aef658fa637127c3482",
+ "b483494ef289e282021b1e2a"
+ ],
+ "independent_of": []
+ },
+ {
+ "id": "42f34fffe4223cab2ff79e69",
+ "title": "Review: 1726 final whole-branch review before main",
+ "minutes": 60,
+ "floor": 3,
+ "kind": "review",
+ "difficulty": "high",
+ "spend": {
+ "5-hour": 30,
+ "weekly": 4
+ },
+ "deps": [
+ "4bc913c9bf52f96cadbcd419"
+ ],
+ "independent_of": [
+ "4bc913c9bf52f96cadbcd419"
+ ]
+ },
+ {
+ "id": "8718795de795e643c928d3cc",
+ "title": "Review: 1726 final merge of main",
+ "minutes": 20,
+ "floor": 3,
+ "kind": "review",
+ "difficulty": "medium",
+ "spend": {
+ "5-hour": 10,
+ "weekly": 1
+ },
+ "deps": [
+ "4bc913c9bf52f96cadbcd419"
+ ],
+ "independent_of": [
+ "4bc913c9bf52f96cadbcd419"
+ ]
+ },
+ {
+ "id": "977d937c468e7720151c780e",
+ "title": "1726 final fix C1: private PM chat must not reach terminal observers",
+ "minutes": 60,
+ "floor": 3,
+ "kind": "fix",
+ "difficulty": "high",
+ "spend": {
+ "5-hour": 30,
+ "weekly": 4
+ },
+ "deps": [
+ "42f34fffe4223cab2ff79e69"
+ ],
+ "independent_of": []
+ },
+ {
+ "id": "b365e73faae5aa84b1b4d544",
+ "title": "1726 final fix C2: rollback must not expose private chats or lost work",
+ "minutes": 60,
+ "floor": 3,
+ "kind": "fix",
+ "difficulty": "high",
+ "spend": {
+ "5-hour": 30,
+ "weekly": 4
+ },
+ "deps": [
+ "42f34fffe4223cab2ff79e69"
+ ],
+ "independent_of": []
+ },
+ {
+ "id": "3f97d137a02c078abfdc7d74",
+ "title": "1726 final fix I3: a lost worker stays out of routing after cancel or reassign",
+ "minutes": 60,
+ "floor": 3,
+ "kind": "fix",
+ "difficulty": "high",
+ "spend": {
+ "5-hour": 30,
+ "weekly": 4
+ },
+ "deps": [
+ "42f34fffe4223cab2ff79e69"
+ ],
+ "independent_of": []
+ },
+ {
+ "id": "42095c031091b32d2d5e163b",
+ "title": "Review: 1726 final fix C2 rollback",
+ "minutes": 20,
+ "floor": 3,
+ "kind": "review",
+ "difficulty": "high",
+ "spend": {
+ "5-hour": 10,
+ "weekly": 1
+ },
+ "deps": [
+ "b365e73faae5aa84b1b4d544"
+ ],
+ "independent_of": [
+ "b365e73faae5aa84b1b4d544"
+ ]
+ },
+ {
+ "id": "a8c17a1e4fb9b75f771b67a7",
+ "title": "Review: 1726 final fix I3 lost worker routing",
+ "minutes": 20,
+ "floor": 3,
+ "kind": "review",
+ "difficulty": "high",
+ "spend": {
+ "5-hour": 10,
+ "weekly": 1
+ },
+ "deps": [
+ "3f97d137a02c078abfdc7d74"
+ ],
+ "independent_of": [
+ "3f97d137a02c078abfdc7d74"
+ ]
+ },
+ {
+ "id": "5c6b795d846d44bfb7591837",
+ "title": "Review: 1726 final fix C1 PM terminal observers",
+ "minutes": 20,
+ "floor": 3,
+ "kind": "review",
+ "difficulty": "high",
+ "spend": {
+ "5-hour": 10,
+ "weekly": 1
+ },
+ "deps": [
+ "977d937c468e7720151c780e"
+ ],
+ "independent_of": [
+ "977d937c468e7720151c780e"
+ ]
+ },
+ {
+ "id": "fa552b26cc36df06a9145405",
+ "title": "v2 A: Swarm as a switchable subsystem (out of the daemon core)",
+ "minutes": 180,
+ "floor": 3,
+ "kind": "cli",
+ "difficulty": "high",
+ "spend": {
+ "5-hour": 50,
+ "weekly": 8
+ },
+ "deps": [],
+ "independent_of": []
+ },
+ {
+ "id": "88a2196381c696b3b458543f",
+ "title": "v2 B: night shift (usage limits never stop the Swarm)",
+ "minutes": 180,
+ "floor": 3,
+ "kind": "cli",
+ "difficulty": "high",
+ "spend": {
+ "5-hour": 50,
+ "weekly": 8
+ },
+ "deps": [],
+ "independent_of": []
+ },
+ {
+ "id": "04f4dd68dc6273061f4e6194",
+ "title": "v2 C: decision packets (batched questions to people)",
+ "minutes": 180,
+ "floor": 3,
+ "kind": "cli",
+ "difficulty": "high",
+ "spend": {
+ "5-hour": 50,
+ "weekly": 8
+ },
+ "deps": [],
+ "independent_of": []
+ },
+ {
+ "id": "9109dbd1ee0f97b1f12ce4f5",
+ "title": "v2 D: review never waits on one reviewer (and no reviewer deadlocks)",
+ "minutes": 180,
+ "floor": 3,
+ "kind": "cli",
+ "difficulty": "high",
+ "spend": {
+ "5-hour": 50,
+ "weekly": 8
+ },
+ "deps": [],
+ "independent_of": []
+ },
+ {
+ "id": "1dace4d8419a80177f226de1",
+ "title": "v2 E: scheduler prototype (global assignment of tasks to machines and models)",
+ "minutes": 180,
+ "floor": 3,
+ "kind": "research",
+ "difficulty": "high",
+ "spend": {
+ "5-hour": 50,
+ "weekly": 8
+ },
+ "deps": [],
+ "independent_of": []
+ }
+ ],
+ "machines": [
+ {
+ "id": "383ce46764d8cbf68d598ec77827a6a2",
+ "name": "MacbookPro.local",
+ "slots": 16,
+ "engines": [
+ "claude",
+ "codex"
+ ]
+ },
+ {
+ "id": "001bcba1e7e9deb6f8756c053a951ce2",
+ "name": "[person]'s Mac",
+ "slots": 8,
+ "engines": [
+ "claude",
+ "codex"
+ ]
+ },
+ {
+ "id": "78351f130fd7a6e04a93c47790767040",
+ "name": "MacBookPro2021.local",
+ "slots": 8,
+ "engines": [
+ "claude",
+ "codex"
+ ]
+ },
+ {
+ "id": "e5c123a616155ce517f24c414cf57180",
+ "name": "MACs-Mac-Studio.local",
+ "slots": 16,
+ "engines": [
+ "claude",
+ "codex"
+ ]
+ },
+ {
+ "id": "ebedf81ba6a1ab03c324f4e8f58b094a",
+ "name": "MacBooks-MacBook-Pro-19.local",
+ "slots": 1,
+ "engines": [
+ "claude",
+ "codex"
+ ]
+ },
+ {
+ "id": "0caa2f6c73e8123baf0705c76b35420d",
+ "name": "MacBooks-MacBook-Pro-10.local",
+ "slots": 4,
+ "engines": [
+ "claude",
+ "codex"
+ ]
+ }
+ ],
+ "models": [
+ {
+ "id": "claude-opus",
+ "engine": "claude",
+ "cost": 3,
+ "quality": {
+ "default": 3
+ },
+ "label": "Claude opus high"
+ },
+ {
+ "id": "codex-default",
+ "engine": "codex",
+ "cost": 2,
+ "quality": {
+ "default": 3
+ },
+ "label": "Codex default default"
+ },
+ {
+ "id": "claude-sonnet",
+ "engine": "claude",
+ "cost": 2,
+ "quality": {
+ "default": 2
+ },
+ "label": "Claude sonnet medium"
+ },
+ {
+ "id": "claude-haiku",
+ "engine": "claude",
+ "cost": 1,
+ "quality": {
+ "default": 1
+ },
+ "label": "Claude haiku auto"
+ },
+ {
+ "id": "grid-deepseek/deepseek-v4.1-flash-1017",
+ "engine": "claude",
+ "cost": 1,
+ "quality": {
+ "default": 1
+ },
+ "concurrency": 4,
+ "subscription": false,
+ "family": "deepseek/deepseek-v4.1-flash-1017",
+ "remote": true,
+ "label": "Claude on deepseek/deepseek-v4.1-flash-1017 \u00b7 OpenRouter (API)"
+ }
+ ],
+ "accounts": [
+ {
+ "id": "codex-1",
+ "members": [
+ [
+ "383ce46764d8cbf68d598ec77827a6a2",
+ "codex"
+ ],
+ [
+ "e5c123a616155ce517f24c414cf57180",
+ "codex"
+ ]
+ ],
+ "reserve": 10.0,
+ "windows": [
+ {
+ "name": "weekly",
+ "left": 59.0,
+ "resets_in": 9055
+ }
+ ],
+ "budget": {
+ "weekly": 49.0
+ }
+ },
+ {
+ "id": "claude-2",
+ "members": [
+ [
+ "001bcba1e7e9deb6f8756c053a951ce2",
+ "claude"
+ ]
+ ],
+ "reserve": 10.0,
+ "windows": [
+ {
+ "name": "5-hour",
+ "left": 100.0,
+ "resets_in": null
+ },
+ {
+ "name": "weekly",
+ "left": 52.0,
+ "resets_in": 5267
+ }
+ ],
+ "budget": {
+ "weekly": 42.0
+ }
+ },
+ {
+ "id": "codex-3",
+ "members": [
+ [
+ "001bcba1e7e9deb6f8756c053a951ce2",
+ "codex"
+ ]
+ ],
+ "reserve": 10.0,
+ "windows": [
+ {
+ "name": "weekly",
+ "left": 0.0,
+ "resets_in": 32099
+ }
+ ],
+ "budget": {
+ "weekly": -10.0
+ }
+ },
+ {
+ "id": "claude-4",
+ "members": [
+ [
+ "78351f130fd7a6e04a93c47790767040",
+ "claude"
+ ]
+ ],
+ "reserve": 10.0,
+ "windows": [
+ {
+ "name": "5-hour",
+ "left": 98.0,
+ "resets_in": 257
+ },
+ {
+ "name": "weekly",
+ "left": 100.0,
+ "resets_in": 8387
+ }
+ ],
+ "budget": {
+ "weekly": 90.0
+ }
+ },
+ {
+ "id": "codex-5",
+ "members": [
+ [
+ "ebedf81ba6a1ab03c324f4e8f58b094a",
+ "codex"
+ ]
+ ],
+ "reserve": 10.0,
+ "windows": [
+ {
+ "name": "5-hour",
+ "left": 100.0,
+ "resets_in": 300
+ },
+ {
+ "name": "weekly",
+ "left": 95.0,
+ "resets_in": 9097
+ }
+ ],
+ "budget": {
+ "weekly": 85.0
+ }
+ },
+ {
+ "id": "claude-6",
+ "members": [
+ [
+ "0caa2f6c73e8123baf0705c76b35420d",
+ "claude"
+ ]
+ ],
+ "reserve": 10.0,
+ "windows": [
+ {
+ "name": "5-hour",
+ "left": 100.0,
+ "resets_in": null
+ },
+ {
+ "name": "weekly",
+ "left": 81.0,
+ "resets_in": 7487
+ }
+ ],
+ "budget": {
+ "weekly": 71.0
+ }
+ },
+ {
+ "id": "codex-7",
+ "members": [
+ [
+ "0caa2f6c73e8123baf0705c76b35420d",
+ "codex"
+ ]
+ ],
+ "reserve": 10.0,
+ "windows": [
+ {
+ "name": "weekly",
+ "left": 97.0,
+ "resets_in": 35126
+ }
+ ],
+ "budget": {
+ "weekly": 87.0
+ }
+ }
+ ]
+ },
+ "actual": {
+ "9e7e516b4e7e1f90d7c9ca43": [
+ "ebedf81ba6a1ab03c324f4e8f58b094a",
+ "claude-opus"
+ ],
+ "2b8a76771f8d6e8380101ad0": [
+ "ebedf81ba6a1ab03c324f4e8f58b094a",
+ "claude-opus"
+ ],
+ "659a6cc93b944bd24cae2884": [
+ "78351f130fd7a6e04a93c47790767040",
+ "claude-opus"
+ ],
+ "aeef05a35995ca9f7cca7060": [
+ "78351f130fd7a6e04a93c47790767040",
+ "claude-opus"
+ ],
+ "5c48779c71d5111602eab51f": [
+ "383ce46764d8cbf68d598ec77827a6a2",
+ "codex-default"
+ ],
+ "df0940f037c9f6eef1b92b67": [
+ "78351f130fd7a6e04a93c47790767040",
+ "claude-opus"
+ ],
+ "c2e38ce017f6f8e65ef8bdce": [
+ "78351f130fd7a6e04a93c47790767040",
+ "claude-opus"
+ ],
+ "0a84ea687a435833d1649933": [
+ "78351f130fd7a6e04a93c47790767040",
+ "claude-opus"
+ ],
+ "2e2d726a3ff6196c26d44f8f": [
+ "001bcba1e7e9deb6f8756c053a951ce2",
+ "claude-opus"
+ ],
+ "6bc636fa6713886102b9cbfa": [
+ "e5c123a616155ce517f24c414cf57180",
+ "codex-default"
+ ],
+ "5f0d3516fb850999cb824c90": [
+ "e5c123a616155ce517f24c414cf57180",
+ "codex-default"
+ ],
+ "7a23487b3220d1564f9c7522": [
+ "e5c123a616155ce517f24c414cf57180",
+ "codex-default"
+ ],
+ "e6115d403f62dd42d5cf3ab3": [
+ "e5c123a616155ce517f24c414cf57180",
+ "claude-opus"
+ ],
+ "acdc5546b9fcc601abb8b22c": [
+ "e5c123a616155ce517f24c414cf57180",
+ "claude-opus"
+ ],
+ "e141b9c91ab56d8509789a49": [
+ "e5c123a616155ce517f24c414cf57180",
+ "codex-default"
+ ],
+ "0da3404ca7a4a33f57d4c871": [
+ "e5c123a616155ce517f24c414cf57180",
+ "codex-default"
+ ],
+ "8f099aef658fa637127c3482": [
+ "78351f130fd7a6e04a93c47790767040",
+ "claude-opus"
+ ],
+ "45e5e3322e966e128a7d0f3d": [
+ "78351f130fd7a6e04a93c47790767040",
+ "claude-opus"
+ ],
+ "4c650945b01ab59703017bfb": [
+ "78351f130fd7a6e04a93c47790767040",
+ "claude-opus"
+ ],
+ "b27e3b7574be0b1bf4a76986": [
+ "78351f130fd7a6e04a93c47790767040",
+ "claude-opus"
+ ],
+ "b0b28597aa6be5ef38defa6e": [
+ "e5c123a616155ce517f24c414cf57180",
+ "claude-opus"
+ ],
+ "f3a620e144116d08c3a68338": [
+ "001bcba1e7e9deb6f8756c053a951ce2",
+ "claude-opus"
+ ],
+ "4f49c22420c3c3fc57dda058": [
+ "e5c123a616155ce517f24c414cf57180",
+ "codex-default"
+ ],
+ "1e43f418b6c92f435689581d": [
+ "e5c123a616155ce517f24c414cf57180",
+ "codex-default"
+ ],
+ "d71cdb0a2ab3181904d5eb3d": [
+ "e5c123a616155ce517f24c414cf57180",
+ "codex-default"
+ ],
+ "b483494ef289e282021b1e2a": [
+ "383ce46764d8cbf68d598ec77827a6a2",
+ "codex-default"
+ ],
+ "32777a379c1fd8cccfde3e85": [
+ "e5c123a616155ce517f24c414cf57180",
+ "codex-default"
+ ],
+ "400c47daa5f4e2be6ab1c2e3": [
+ "383ce46764d8cbf68d598ec77827a6a2",
+ "codex-default"
+ ],
+ "4bc913c9bf52f96cadbcd419": [
+ "78351f130fd7a6e04a93c47790767040",
+ "claude-opus"
+ ],
+ "42f34fffe4223cab2ff79e69": [
+ "e5c123a616155ce517f24c414cf57180",
+ "codex-default"
+ ],
+ "8718795de795e643c928d3cc": [
+ "e5c123a616155ce517f24c414cf57180",
+ "codex-default"
+ ],
+ "977d937c468e7720151c780e": [
+ "78351f130fd7a6e04a93c47790767040",
+ "claude-opus"
+ ],
+ "b365e73faae5aa84b1b4d544": [
+ "78351f130fd7a6e04a93c47790767040",
+ "claude-opus"
+ ],
+ "3f97d137a02c078abfdc7d74": [
+ "e5c123a616155ce517f24c414cf57180",
+ "claude-opus"
+ ],
+ "42095c031091b32d2d5e163b": [
+ "e5c123a616155ce517f24c414cf57180",
+ "codex-default"
+ ],
+ "a8c17a1e4fb9b75f771b67a7": [
+ "e5c123a616155ce517f24c414cf57180",
+ "codex-default"
+ ],
+ "5c6b795d846d44bfb7591837": [
+ "e5c123a616155ce517f24c414cf57180",
+ "codex-default"
+ ],
+ "fa552b26cc36df06a9145405": [
+ "e5c123a616155ce517f24c414cf57180",
+ "claude-opus"
+ ],
+ "88a2196381c696b3b458543f": [
+ "e5c123a616155ce517f24c414cf57180",
+ "claude-opus"
+ ],
+ "04f4dd68dc6273061f4e6194": [
+ "78351f130fd7a6e04a93c47790767040",
+ "claude-opus"
+ ],
+ "9109dbd1ee0f97b1f12ce4f5": [
+ "78351f130fd7a6e04a93c47790767040",
+ "claude-opus"
+ ],
+ "1dace4d8419a80177f226de1": [
+ "e5c123a616155ce517f24c414cf57180",
+ "claude-opus"
+ ]
+ },
+ "estimates": [
+ {
+ "group": "2b8a76771f8d6e8380101ad0",
+ "title": "Measure: Super Tab load and message time on the web",
+ "note": "request named by a variable in the log, matched by time and title"
+ },
+ {
+ "group": "5c48779c71d5111602eab51f",
+ "title": "Review: 1726 G1 design doc",
+ "note": "request named by a variable in the log, matched by time and title"
+ },
+ {
+ "group": "c2e38ce017f6f8e65ef8bdce",
+ "title": "1726 G3: backend read API and migration",
+ "note": "request named by a variable in the log, matched by time and title"
+ },
+ {
+ "group": "0a84ea687a435833d1649933",
+ "title": "1726 G5: CLI on the new read API",
+ "note": "no request of its own; takes G3's read-path request (same rewrite, CLI side)"
+ },
+ {
+ "group": "2e2d726a3ff6196c26d44f8f",
+ "title": "1726 G4: Desktop and web on the new read API",
+ "note": "request named by a variable in the log, matched by time and title"
+ },
+ {
+ "group": "5f0d3516fb850999cb824c90",
+ "title": "Review: 1726 G5 CLI",
+ "note": "request named by a variable in the log, matched by time and title"
+ },
+ {
+ "group": "7a23487b3220d1564f9c7522",
+ "title": "Review: 1726 G3 read API and migration",
+ "note": "no request of its own; takes the log's standard independent review request"
+ },
+ {
+ "group": "e6115d403f62dd42d5cf3ab3",
+ "title": "Swarm plan R1: how the lampOS team works",
+ "note": "no route request; estimate"
+ },
+ {
+ "group": "acdc5546b9fcc601abb8b22c",
+ "title": "Swarm plan R2: pain points of fast agent teams",
+ "note": "no route request; estimate"
+ },
+ {
+ "group": "e141b9c91ab56d8509789a49",
+ "title": "Review: 1726 G4 Desktop and web",
+ "note": "request named by a variable in the log, matched by time and title"
+ },
+ {
+ "group": "8f099aef658fa637127c3482",
+ "title": "1726 G6: integrate, measure, migration dry run",
+ "note": "no route request; estimate"
+ },
+ {
+ "group": "4c650945b01ab59703017bfb",
+ "title": "v1 liveness A: lost work and takeover (backend)",
+ "note": "no route request; estimate like v1 DM"
+ },
+ {
+ "group": "b27e3b7574be0b1bf4a76986",
+ "title": "v1 liveness B: host progress and Lead takeover (CLI)",
+ "note": "no route request; estimate like v1 DM"
+ },
+ {
+ "group": "1e43f418b6c92f435689581d",
+ "title": "Review: v1 liveness B: host progress and Lead takeover (CLI)",
+ "note": "request named by a variable in the log, matched by time and title"
+ },
+ {
+ "group": "d71cdb0a2ab3181904d5eb3d",
+ "title": "Review: v1 liveness A: lost work and takeover (backend)",
+ "note": "request named by a variable in the log, matched by time and title"
+ },
+ {
+ "group": "32777a379c1fd8cccfde3e85",
+ "title": "Review: v1 DM: Chat with PM (Desktop and web)",
+ "note": "request named by a variable in the log, matched by time and title"
+ },
+ {
+ "group": "400c47daa5f4e2be6ab1c2e3",
+ "title": "Review: 1726 G6 results doc",
+ "note": "request named by a variable in the log, matched by time and title"
+ },
+ {
+ "group": "4bc913c9bf52f96cadbcd419",
+ "title": "1726 final: merge main into the feature branch",
+ "note": "request named by a variable in the log, matched by time and title"
+ },
+ {
+ "group": "42f34fffe4223cab2ff79e69",
+ "title": "Review: 1726 final whole-branch review before main",
+ "note": "request named by a variable in the log, matched by time and title"
+ },
+ {
+ "group": "977d937c468e7720151c780e",
+ "title": "1726 final fix C1: private PM chat must not reach terminal observers",
+ "note": "request named by a variable in the log, matched by time and title"
+ },
+ {
+ "group": "b365e73faae5aa84b1b4d544",
+ "title": "1726 final fix C2: rollback must not expose private chats or lost work",
+ "note": "no request of its own; takes fix C1's request"
+ },
+ {
+ "group": "3f97d137a02c078abfdc7d74",
+ "title": "1726 final fix I3: a lost worker stays out of routing after cancel or reassign",
+ "note": "no request of its own; takes fix C1's request"
+ },
+ {
+ "group": "42095c031091b32d2d5e163b",
+ "title": "Review: 1726 final fix C2 rollback",
+ "note": "no request of its own; takes the focused re-check request"
+ },
+ {
+ "group": "a8c17a1e4fb9b75f771b67a7",
+ "title": "Review: 1726 final fix I3 lost worker routing",
+ "note": "no request of its own; takes the focused re-check request"
+ },
+ {
+ "group": "5c6b795d846d44bfb7591837",
+ "title": "Review: 1726 final fix C1 PM terminal observers",
+ "note": "request named by a variable in the log, matched by time and title"
+ },
+ {
+ "group": "fa552b26cc36df06a9145405",
+ "title": "v2 A: Swarm as a switchable subsystem (out of the daemon core)",
+ "note": "no route request (started directly); estimate"
+ },
+ {
+ "group": "88a2196381c696b3b458543f",
+ "title": "v2 B: night shift (usage limits never stop the Swarm)",
+ "note": "no route request (started directly); estimate"
+ },
+ {
+ "group": "04f4dd68dc6273061f4e6194",
+ "title": "v2 C: decision packets (batched questions to people)",
+ "note": "no route request (started directly); estimate"
+ },
+ {
+ "group": "9109dbd1ee0f97b1f12ce4f5",
+ "title": "v2 D: review never waits on one reviewer (and no reviewer deadlocks)",
+ "note": "no route request (started directly); estimate"
+ },
+ {
+ "group": "1dace4d8419a80177f226de1",
+ "title": "v2 E: scheduler prototype (global assignment of tasks to machines and models)",
+ "note": "no route request (started directly); estimate"
+ }
+ ],
+ "excluded": [
+ {
+ "group": "274baf5b89089a604ebbff4b",
+ "title": "Smoke: DeepSeek API on MacbookPro.local",
+ "reason": "a person pinned it to one machine and the shared DeepSeek model"
+ },
+ {
+ "group": "aa409e467756f366f8ec67d4",
+ "title": "Smoke: DeepSeek API on MacBooks-MacBook-Pro-19.local",
+ "reason": "a person pinned it to one machine and the shared DeepSeek model"
+ },
+ {
+ "group": "feb85d3aef2375b81b4275eb",
+ "title": "Smoke: DeepSeek API on MACs-Mac-Studio.local",
+ "reason": "a person pinned it to one machine and the shared DeepSeek model"
+ },
+ {
+ "group": "d80142e540abade0e9ac21de",
+ "title": "Smoke: DeepSeek API on [person]'s Mac",
+ "reason": "a person pinned it to one machine and the shared DeepSeek model"
+ },
+ {
+ "group": "8c0d038efe1b63d3b6628552",
+ "title": "Smoke: DeepSeek API after CLI 0.4.73 (Mac Studio)",
+ "reason": "a person pinned it to one machine and the shared DeepSeek model"
+ },
+ {
+ "group": "e37ffff373d0afd7fc763726",
+ "title": "Check: CLI version and grid log on MacbookPro.local",
+ "reason": "a person pinned it to one machine (a version and log check)"
+ }
+ ]
+}
diff --git a/tools/scheduler/data/2026-10-26-route-log.redacted.json b/tools/scheduler/data/2026-10-26-route-log.redacted.json
new file mode 100644
index 000000000..24d84dfca
--- /dev/null
+++ b/tools/scheduler/data/2026-10-26-route-log.redacted.json
@@ -0,0 +1,1104 @@
+[
+ {
+ "group": "9e7e516b4e7e1f90d7c9ca43",
+ "at": "2026-10-26T09:12:38.357Z",
+ "request": {
+ "difficulty": "medium",
+ "risk": "medium",
+ "size": "large",
+ "why": "Release-gating regression of Swarm API-model flows across several machines; needs judgment to diagnose a live grid fault and run tests, no product code changes.",
+ "kind": "testing",
+ "needs": {
+ "tools": [
+ "git",
+ "gh"
+ ],
+ "devices": []
+ }
+ }
+ },
+ {
+ "group": "9e7e516b4e7e1f90d7c9ca43",
+ "at": null,
+ "request": {
+ "difficulty": "medium",
+ "risk": "medium",
+ "size": "large",
+ "why": "Release-gating regression of Swarm API-model flows across several machines; needs judgment to diagnose a live grid fault and run tests, no product code changes.",
+ "kind": "testing",
+ "needs": {
+ "tools": [
+ "git",
+ "gh"
+ ],
+ "devices": []
+ }
+ }
+ },
+ {
+ "group": "9e7e516b4e7e1f90d7c9ca43",
+ "at": "2026-10-26T09:21:26.294Z",
+ "request": {
+ "difficulty": "low",
+ "risk": "low",
+ "size": "small",
+ "why": "Regression flow 3a: route naming the shared API model",
+ "model": "deepseek 4.1 flash"
+ }
+ },
+ {
+ "group": "9e7e516b4e7e1f90d7c9ca43",
+ "at": "2026-10-26T09:21:26.294Z",
+ "request": {
+ "difficulty": "low",
+ "risk": "low",
+ "size": "small",
+ "why": "Regression flow 3b: route without a model name"
+ }
+ },
+ {
+ "group": "9e7e516b4e7e1f90d7c9ca43",
+ "at": null,
+ "request": {
+ "difficulty": "low",
+ "risk": "low",
+ "size": "small",
+ "why": "Regression flow 3a: route naming the shared API model",
+ "model": "deepseek 4.1 flash"
+ }
+ },
+ {
+ "group": "9e7e516b4e7e1f90d7c9ca43",
+ "at": null,
+ "request": {
+ "difficulty": "low",
+ "risk": "low",
+ "size": "small",
+ "why": "Regression flow 3b: route without a model name"
+ }
+ },
+ {
+ "group": "9e7e516b4e7e1f90d7c9ca43",
+ "at": "2026-10-26T09:22:47.722Z",
+ "request": {
+ "difficulty": "low",
+ "risk": "low",
+ "size": "small",
+ "why": "Regression flow 3a (record)",
+ "model": "deepseek 4.1 flash"
+ }
+ },
+ {
+ "group": "9e7e516b4e7e1f90d7c9ca43",
+ "at": "2026-10-26T09:22:47.722Z",
+ "request": {
+ "difficulty": "low",
+ "risk": "low",
+ "size": "small",
+ "why": "Regression flow 3b (record)"
+ }
+ },
+ {
+ "group": "9e7e516b4e7e1f90d7c9ca43",
+ "at": null,
+ "request": {
+ "difficulty": "low",
+ "risk": "low",
+ "size": "small",
+ "why": "Regression flow 3a (record)",
+ "model": "deepseek 4.1 flash"
+ }
+ },
+ {
+ "group": "9e7e516b4e7e1f90d7c9ca43",
+ "at": null,
+ "request": {
+ "difficulty": "low",
+ "risk": "low",
+ "size": "small",
+ "why": "Regression flow 3b (record)"
+ }
+ },
+ {
+ "group": "274baf5b89089a604ebbff4b",
+ "at": "2026-10-26T09:29:39.499Z",
+ "request": {
+ "difficulty": "low",
+ "risk": "low",
+ "size": "small",
+ "why": "Retry smoke test on the sharing machine after a clone timeout",
+ "model": "deepseek 4.1 flash"
+ }
+ },
+ {
+ "group": "274baf5b89089a604ebbff4b",
+ "at": null,
+ "request": {
+ "difficulty": "low",
+ "risk": "low",
+ "size": "small",
+ "why": "Retry smoke test on the sharing machine after a clone timeout",
+ "model": "deepseek 4.1 flash"
+ }
+ },
+ {
+ "group": "$gid",
+ "at": "2026-10-26T09:32:34.201Z",
+ "request": {
+ "difficulty": "low",
+ "risk": "low",
+ "size": "small",
+ "why": "Smoke test of the shared DeepSeek API model on WIN-DELL",
+ "model": "deepseek 4.1 flash"
+ }
+ },
+ {
+ "group": "$gid",
+ "at": null,
+ "request": {
+ "difficulty": "low",
+ "risk": "low",
+ "size": "small",
+ "why": "Smoke test of the shared DeepSeek API model on WIN-DELL",
+ "model": "deepseek 4.1 flash"
+ }
+ },
+ {
+ "group": "837f400f3252d7491843ecff",
+ "at": "2026-10-26T09:32:41.697Z",
+ "request": {
+ "difficulty": "low",
+ "risk": "low",
+ "size": "small",
+ "why": "Smoke test of the shared DeepSeek API model on WIN-DELL",
+ "model": "deepseek 4.1 flash"
+ }
+ },
+ {
+ "group": "837f400f3252d7491843ecff",
+ "at": null,
+ "request": {
+ "difficulty": "low",
+ "risk": "low",
+ "size": "small",
+ "why": "Smoke test of the shared DeepSeek API model on WIN-DELL",
+ "model": "deepseek 4.1 flash"
+ }
+ },
+ {
+ "group": "9e7e516b4e7e1f90d7c9ca43",
+ "at": "2026-10-26T09:33:47.127Z",
+ "request": {
+ "difficulty": "low",
+ "risk": "low",
+ "size": "small",
+ "why": "Regression: route during the sharing machine clone",
+ "model": "deepseek 4.1 flash"
+ }
+ },
+ {
+ "group": "9e7e516b4e7e1f90d7c9ca43",
+ "at": null,
+ "request": {
+ "difficulty": "low",
+ "risk": "low",
+ "size": "small",
+ "why": "Regression: route during the sharing machine clone",
+ "model": "deepseek 4.1 flash"
+ }
+ },
+ {
+ "group": "837f400f3252d7491843ecff",
+ "at": "2026-10-26T09:35:13.722Z",
+ "request": {
+ "difficulty": "low",
+ "risk": "low",
+ "size": "small",
+ "why": "Smoke test of the shared DeepSeek API model on WIN-DELL",
+ "model": "deepseek 4.1 flash"
+ }
+ },
+ {
+ "group": "837f400f3252d7491843ecff",
+ "at": null,
+ "request": {
+ "difficulty": "low",
+ "risk": "low",
+ "size": "small",
+ "why": "Smoke test of the shared DeepSeek API model on WIN-DELL",
+ "model": "deepseek 4.1 flash"
+ }
+ },
+ {
+ "group": "$gid",
+ "at": "2026-10-26T09:41:14.651Z",
+ "request": {
+ "difficulty": "medium",
+ "risk": "low",
+ "size": "medium",
+ "why": "Browser performance measurement of the Flutter web Super Tab with a local fixture and DevTools throttling; judgment needed to rebuild the fixture and explain the waterfall.",
+ "kind": "performance",
+ "needs": {
+ "tools": [
+ "git",
+ "node"
+ ],
+ "devices": []
+ }
+ }
+ },
+ {
+ "group": "$gid",
+ "at": null,
+ "request": {
+ "difficulty": "medium",
+ "risk": "low",
+ "size": "medium",
+ "why": "Browser performance measurement of the Flutter web Super Tab with a local fixture and DevTools throttling; judgment needed to rebuild the fixture and explain the waterfall.",
+ "kind": "performance",
+ "needs": {
+ "tools": [
+ "git",
+ "node"
+ ],
+ "devices": []
+ }
+ }
+ },
+ {
+ "group": "659a6cc93b944bd24cae2884",
+ "at": "2026-10-26T10:16:48.078Z",
+ "request": {
+ "difficulty": "medium",
+ "risk": "low",
+ "size": "medium",
+ "why": "Integration benchmark against the real store on MongoMemoryReplSet; test-only code, needs care to be deterministic and pluggable.",
+ "kind": "backend",
+ "needs": {
+ "tools": [
+ "git",
+ "node"
+ ]
+ }
+ }
+ },
+ {
+ "group": "aeef05a35995ca9f7cca7060",
+ "at": "2026-10-26T10:16:48.078Z",
+ "request": {
+ "difficulty": "high",
+ "risk": "high",
+ "size": "medium",
+ "why": "Concurrency and migration design for the core Swarm store; mistakes are costly and subtle, needs the strongest model.",
+ "kind": "design",
+ "needs": {
+ "tools": [
+ "git",
+ "node"
+ ]
+ }
+ }
+ },
+ {
+ "group": "659a6cc93b944bd24cae2884",
+ "at": null,
+ "request": {
+ "difficulty": "medium",
+ "risk": "low",
+ "size": "medium",
+ "why": "Integration benchmark against the real store on MongoMemoryReplSet; test-only code, needs care to be deterministic and pluggable.",
+ "kind": "backend",
+ "needs": {
+ "tools": [
+ "git",
+ "node"
+ ]
+ }
+ }
+ },
+ {
+ "group": "aeef05a35995ca9f7cca7060",
+ "at": null,
+ "request": {
+ "difficulty": "high",
+ "risk": "high",
+ "size": "medium",
+ "why": "Concurrency and migration design for the core Swarm store; mistakes are costly and subtle, needs the strongest model.",
+ "kind": "design",
+ "needs": {
+ "tools": [
+ "git",
+ "node"
+ ]
+ }
+ }
+ },
+ {
+ "group": "aeef05a35995ca9f7cca7060",
+ "at": "2026-10-26T10:16:56.173Z",
+ "request": {
+ "difficulty": "high",
+ "risk": "high",
+ "size": "medium",
+ "why": "Concurrency and migration design for the core Swarm store; mistakes are costly and subtle, needs the strongest model.",
+ "kind": "design",
+ "needs": {
+ "tools": [
+ "git",
+ "node"
+ ]
+ }
+ }
+ },
+ {
+ "group": "aeef05a35995ca9f7cca7060",
+ "at": null,
+ "request": {
+ "difficulty": "high",
+ "risk": "high",
+ "size": "medium",
+ "why": "Concurrency and migration design for the core Swarm store; mistakes are costly and subtle, needs the strongest model.",
+ "kind": "design",
+ "needs": {
+ "tools": [
+ "git",
+ "node"
+ ]
+ }
+ }
+ },
+ {
+ "group": "$gid",
+ "at": "2026-10-26T10:45:11.476Z",
+ "request": {
+ "difficulty": "high",
+ "risk": "high",
+ "size": "medium",
+ "why": "Independent review of a concurrency/migration design for the core Swarm store; must be at least as strong as the Opus author, different engine preferred.",
+ "kind": "review",
+ "needs": {
+ "tools": [
+ "git"
+ ]
+ }
+ }
+ },
+ {
+ "group": "$gid",
+ "at": null,
+ "request": {
+ "difficulty": "high",
+ "risk": "high",
+ "size": "medium",
+ "why": "Independent review of a concurrency/migration design for the core Swarm store; must be at least as strong as the Opus author, different engine preferred.",
+ "kind": "review",
+ "needs": {
+ "tools": [
+ "git"
+ ]
+ }
+ }
+ },
+ {
+ "group": "$g",
+ "at": "2026-10-26T10:56:13.249Z",
+ "request": {
+ "difficulty": "high",
+ "risk": "high",
+ "size": "large",
+ "why": "Core Swarm read path / client rewrite against a reviewed design; correctness of cursors, visibility and migration matters a lot.",
+ "kind": "backend",
+ "needs": {
+ "tools": [
+ "git",
+ "node"
+ ]
+ }
+ }
+ },
+ {
+ "group": "$g",
+ "at": null,
+ "request": {
+ "difficulty": "high",
+ "risk": "high",
+ "size": "large",
+ "why": "Core Swarm read path / client rewrite against a reviewed design; correctness of cursors, visibility and migration matters a lot.",
+ "kind": "backend",
+ "needs": {
+ "tools": [
+ "git",
+ "node"
+ ]
+ }
+ }
+ },
+ {
+ "group": "$gid",
+ "at": "2026-10-26T10:57:29.841Z",
+ "request": {
+ "difficulty": "high",
+ "risk": "medium",
+ "size": "large",
+ "why": "Flutter client rewrite of Swarm reads against a reviewed contract, Desktop and web.",
+ "kind": "ui",
+ "needs": {
+ "tools": [
+ "git",
+ "flutter"
+ ]
+ }
+ }
+ },
+ {
+ "group": "$gid",
+ "at": null,
+ "request": {
+ "difficulty": "high",
+ "risk": "medium",
+ "size": "large",
+ "why": "Flutter client rewrite of Swarm reads against a reviewed contract, Desktop and web.",
+ "kind": "ui",
+ "needs": {
+ "tools": [
+ "git",
+ "flutter"
+ ]
+ }
+ }
+ },
+ {
+ "group": "df0940f037c9f6eef1b92b67",
+ "at": "2026-10-26T11:00:51.800Z",
+ "request": {
+ "difficulty": "high",
+ "risk": "high",
+ "size": "large",
+ "why": "Core Swarm store rewrite with concurrency invariants; reuse the design author who knows it best.",
+ "kind": "backend",
+ "needs": {
+ "tools": [
+ "git",
+ "node"
+ ]
+ }
+ }
+ },
+ {
+ "group": "df0940f037c9f6eef1b92b67",
+ "at": null,
+ "request": {
+ "difficulty": "high",
+ "risk": "high",
+ "size": "large",
+ "why": "Core Swarm store rewrite with concurrency invariants; reuse the design author who knows it best.",
+ "kind": "backend",
+ "needs": {
+ "tools": [
+ "git",
+ "node"
+ ]
+ }
+ }
+ },
+ {
+ "group": "df0940f037c9f6eef1b92b67",
+ "at": "2026-10-26T11:00:58.840Z",
+ "request": {
+ "difficulty": "high",
+ "risk": "high",
+ "size": "large",
+ "why": "Core Swarm store rewrite with concurrency invariants; reuse the design author who knows it best.",
+ "kind": "backend",
+ "needs": {
+ "tools": [
+ "git",
+ "node"
+ ]
+ }
+ }
+ },
+ {
+ "group": "df0940f037c9f6eef1b92b67",
+ "at": null,
+ "request": {
+ "difficulty": "high",
+ "risk": "high",
+ "size": "large",
+ "why": "Core Swarm store rewrite with concurrency invariants; reuse the design author who knows it best.",
+ "kind": "backend",
+ "needs": {
+ "tools": [
+ "git",
+ "node"
+ ]
+ }
+ }
+ },
+ {
+ "group": "df0940f037c9f6eef1b92b67",
+ "at": "2026-10-26T11:01:11.235Z",
+ "request": {
+ "difficulty": "high",
+ "risk": "high",
+ "size": "large",
+ "why": "Core Swarm store rewrite with concurrency invariants; reuse the design author who knows it best.",
+ "kind": "backend",
+ "needs": {
+ "tools": [
+ "git",
+ "node"
+ ]
+ }
+ }
+ },
+ {
+ "group": "df0940f037c9f6eef1b92b67",
+ "at": null,
+ "request": {
+ "difficulty": "high",
+ "risk": "high",
+ "size": "large",
+ "why": "Core Swarm store rewrite with concurrency invariants; reuse the design author who knows it best.",
+ "kind": "backend",
+ "needs": {
+ "tools": [
+ "git",
+ "node"
+ ]
+ }
+ }
+ },
+ {
+ "group": "$gid",
+ "at": "2026-10-26T11:06:31.615Z",
+ "request": {
+ "difficulty": "medium",
+ "risk": "low",
+ "size": "small",
+ "why": "Review of a test-only benchmark PR; reuse the idle Codex reviewer.",
+ "kind": "review"
+ }
+ },
+ {
+ "group": "$gid",
+ "at": null,
+ "request": {
+ "difficulty": "medium",
+ "risk": "low",
+ "size": "small",
+ "why": "Review of a test-only benchmark PR; reuse the idle Codex reviewer.",
+ "kind": "review"
+ }
+ },
+ {
+ "group": "6bc636fa6713886102b9cbfa",
+ "at": "2026-10-26T11:42:28.030Z",
+ "request": {
+ "difficulty": "medium",
+ "risk": "low",
+ "size": "small",
+ "why": "Re-review of three fixes on the test-only benchmark PR; same Reviewer.",
+ "kind": "review"
+ }
+ },
+ {
+ "group": "6bc636fa6713886102b9cbfa",
+ "at": null,
+ "request": {
+ "difficulty": "medium",
+ "risk": "low",
+ "size": "small",
+ "why": "Re-review of three fixes on the test-only benchmark PR; same Reviewer.",
+ "kind": "review"
+ }
+ },
+ {
+ "group": "$gid",
+ "at": "2026-10-26T11:47:56.476Z",
+ "request": {
+ "difficulty": "high",
+ "risk": "medium",
+ "size": "medium",
+ "why": "Independent review of the CLI read-path rewrite; at least as strong as the Opus author, different engine preferred.",
+ "kind": "review",
+ "needs": {
+ "tools": [
+ "git",
+ "node"
+ ]
+ }
+ }
+ },
+ {
+ "group": "$gid",
+ "at": null,
+ "request": {
+ "difficulty": "high",
+ "risk": "medium",
+ "size": "medium",
+ "why": "Independent review of the CLI read-path rewrite; at least as strong as the Opus author, different engine preferred.",
+ "kind": "review",
+ "needs": {
+ "tools": [
+ "git",
+ "node"
+ ]
+ }
+ }
+ },
+ {
+ "group": "0da3404ca7a4a33f57d4c871",
+ "at": null,
+ "request": {
+ "difficulty": "high",
+ "risk": "high",
+ "size": "small",
+ "why": "Round-3 re-review of the legacy default-project revocation fix.",
+ "kind": "review"
+ }
+ },
+ {
+ "group": "0da3404ca7a4a33f57d4c871",
+ "at": "2026-10-26T13:29:12.135Z",
+ "request": {
+ "difficulty": "high",
+ "risk": "high",
+ "size": "small",
+ "why": "Round-3 re-review of the legacy default-project revocation fix.",
+ "kind": "review"
+ }
+ },
+ {
+ "group": "$g",
+ "at": "2026-10-26T14:21:03.691Z",
+ "request": {
+ "difficulty": "high",
+ "risk": "high",
+ "size": "medium",
+ "why": "Rework the read API so it loads only changed parts; the read API owner knows this code best.",
+ "kind": "backend",
+ "needs": {
+ "tools": [
+ "git"
+ ]
+ }
+ }
+ },
+ {
+ "group": "45e5e3322e966e128a7d0f3d",
+ "at": "2026-10-26T14:21:14.836Z",
+ "request": {
+ "difficulty": "high",
+ "risk": "high",
+ "size": "medium",
+ "why": "Rework the read API so it loads only changed parts; the read API owner knows this code best.",
+ "kind": "backend",
+ "needs": {
+ "tools": [
+ "git"
+ ]
+ }
+ }
+ },
+ {
+ "group": "f3a620e144116d08c3a68338",
+ "at": "2026-10-26T14:50:13.055Z",
+ "request": {
+ "difficulty": "high",
+ "risk": "high",
+ "size": "large",
+ "why": "Desktop/web private PM channel; Reed built the Desktop client.",
+ "kind": "ui",
+ "needs": {
+ "tools": [
+ "git"
+ ]
+ }
+ }
+ },
+ {
+ "group": "f3a620e144116d08c3a68338",
+ "at": "2026-10-26T14:50:21.398Z",
+ "request": {
+ "difficulty": "high",
+ "risk": "high",
+ "size": "large",
+ "why": "Desktop/web private PM channel; Reed built the Desktop client.",
+ "kind": "ui",
+ "needs": {
+ "tools": [
+ "git"
+ ]
+ }
+ }
+ },
+ {
+ "group": "f3a620e144116d08c3a68338",
+ "at": "2026-10-26T14:50:31.668Z",
+ "request": {
+ "difficulty": "high",
+ "risk": "high",
+ "size": "large",
+ "why": "Desktop/web private PM channel; Reed built the Desktop client.",
+ "kind": "ui",
+ "needs": {
+ "tools": [
+ "git"
+ ]
+ }
+ }
+ },
+ {
+ "group": "b0b28597aa6be5ef38defa6e",
+ "at": "2026-10-26T14:51:05.634Z",
+ "request": {
+ "difficulty": "high",
+ "risk": "high",
+ "size": "medium",
+ "why": "Routing readiness; assign to Nico, started for it.",
+ "kind": "cli",
+ "needs": {
+ "tools": [
+ "git"
+ ]
+ }
+ }
+ },
+ {
+ "group": "$rg",
+ "at": "2026-10-26T15:12:17.992Z",
+ "request": {
+ "difficulty": "high",
+ "risk": "high",
+ "size": "small",
+ "why": "Independent review by a different model family.",
+ "kind": "review",
+ "needs": {
+ "tools": [
+ "git"
+ ]
+ }
+ }
+ },
+ {
+ "group": "$rg",
+ "at": "2026-10-26T15:16:01.265Z",
+ "request": {
+ "difficulty": "high",
+ "risk": "high",
+ "size": "small",
+ "why": "Independent review by a different model family.",
+ "kind": "review",
+ "needs": {
+ "tools": [
+ "git"
+ ]
+ }
+ }
+ },
+ {
+ "group": "$rg",
+ "at": "2026-10-26T15:18:15.220Z",
+ "request": {
+ "difficulty": "high",
+ "risk": "high",
+ "size": "small",
+ "why": "Independent review by a different model family.",
+ "kind": "review",
+ "needs": {
+ "tools": [
+ "git"
+ ]
+ }
+ }
+ },
+ {
+ "group": "$rg",
+ "at": "2026-10-26T15:19:55.427Z",
+ "request": {
+ "difficulty": "high",
+ "risk": "high",
+ "size": "small",
+ "why": "Independent review by a different model family.",
+ "kind": "review",
+ "needs": {
+ "tools": [
+ "git"
+ ]
+ }
+ }
+ },
+ {
+ "group": "b483494ef289e282021b1e2a",
+ "at": "2026-10-26T15:33:18.163Z",
+ "request": {
+ "difficulty": "high",
+ "risk": "high",
+ "size": "small",
+ "why": "Independent review; Mac Studio Codex account is rate limited.",
+ "kind": "review",
+ "needs": {
+ "tools": [
+ "git"
+ ]
+ }
+ }
+ },
+ {
+ "group": "$g",
+ "at": "2026-10-26T15:35:45.014Z",
+ "request": {
+ "difficulty": "high",
+ "risk": "high",
+ "size": "small",
+ "why": "Independent review by a different model family.",
+ "kind": "review",
+ "needs": {
+ "tools": [
+ "git"
+ ]
+ }
+ }
+ },
+ {
+ "group": "f3a620e144116d08c3a68338",
+ "at": "2026-10-26T15:37:30.000Z",
+ "request": {
+ "difficulty": "high",
+ "risk": "high",
+ "size": "medium",
+ "why": "Continue the private PM chat after the builder session stopped; its unpushed work is on [person]s Mac.",
+ "kind": "ui",
+ "needs": {
+ "tools": [
+ "git"
+ ]
+ }
+ }
+ },
+ {
+ "group": "f3a620e144116d08c3a68338",
+ "at": "2026-10-26T15:38:58.006Z",
+ "request": {
+ "difficulty": "high",
+ "risk": "high",
+ "size": "medium",
+ "why": "Continue the private PM chat on [person]s Mac.",
+ "kind": "ui",
+ "needs": {
+ "tools": [
+ "git"
+ ]
+ }
+ }
+ },
+ {
+ "group": "4f49c22420c3c3fc57dda058",
+ "at": "2026-10-26T15:41:39.037Z",
+ "request": {
+ "difficulty": "high",
+ "risk": "high",
+ "size": "small",
+ "why": "Re-check by the same reviewer.",
+ "kind": "review",
+ "needs": {
+ "tools": [
+ "git"
+ ]
+ }
+ }
+ },
+ {
+ "group": "4f49c22420c3c3fc57dda058",
+ "at": "2026-10-26T15:45:38.876Z",
+ "request": {
+ "difficulty": "high",
+ "risk": "high",
+ "size": "small",
+ "why": "Re-check by the same reviewer.",
+ "kind": "review",
+ "needs": {
+ "tools": [
+ "git"
+ ]
+ }
+ }
+ },
+ {
+ "group": "4f49c22420c3c3fc57dda058",
+ "at": "2026-10-26T15:45:53.937Z",
+ "request": {
+ "difficulty": "high",
+ "risk": "high",
+ "size": "small",
+ "why": "Re-check by the same reviewer.",
+ "kind": "review",
+ "needs": {
+ "tools": [
+ "git"
+ ]
+ }
+ }
+ },
+ {
+ "group": "4f49c22420c3c3fc57dda058",
+ "at": "2026-10-26T15:46:14.682Z",
+ "request": {
+ "difficulty": "high",
+ "risk": "high",
+ "size": "small",
+ "why": "Re-check by the same reviewer.",
+ "kind": "review",
+ "needs": {
+ "tools": [
+ "git"
+ ]
+ }
+ }
+ },
+ {
+ "group": "$g",
+ "at": "2026-10-26T16:11:46.748Z",
+ "request": {
+ "difficulty": "high",
+ "risk": "high",
+ "size": "small",
+ "why": "Independent review by a different model family.",
+ "kind": "review",
+ "needs": {
+ "tools": [
+ "git"
+ ]
+ }
+ }
+ },
+ {
+ "group": "$rg",
+ "at": "2026-10-26T17:06:13.468Z",
+ "request": {
+ "difficulty": "medium",
+ "risk": "medium",
+ "size": "small",
+ "why": "Independent review of a results doc.",
+ "kind": "review",
+ "needs": {
+ "tools": [
+ "git"
+ ]
+ }
+ }
+ },
+ {
+ "group": "$g",
+ "at": "2026-10-26T17:31:41.223Z",
+ "request": {
+ "difficulty": "medium",
+ "risk": "high",
+ "size": "medium",
+ "why": "Merge main into the feature branch; Theo knows the CLI side and his machine has Flutter.",
+ "kind": "merge",
+ "needs": {
+ "tools": [
+ "git"
+ ]
+ }
+ }
+ },
+ {
+ "group": "$g",
+ "at": "2026-10-26T17:33:15.525Z",
+ "request": {
+ "difficulty": "high",
+ "risk": "high",
+ "size": "medium",
+ "why": "Whole-branch release review by a different model family than the builders.",
+ "kind": "review",
+ "needs": {
+ "tools": [
+ "git"
+ ]
+ }
+ }
+ },
+ {
+ "group": "$g",
+ "at": "2026-10-26T17:34:27.675Z",
+ "request": {
+ "difficulty": "high",
+ "risk": "high",
+ "size": "medium",
+ "why": "Whole-branch release review by a different model family than the builders.",
+ "kind": "review",
+ "needs": {
+ "tools": [
+ "git"
+ ]
+ }
+ }
+ },
+ {
+ "group": "$rg",
+ "at": "2026-10-26T17:49:46.000Z",
+ "request": {
+ "difficulty": "medium",
+ "risk": "high",
+ "size": "small",
+ "why": "Independent review of the main merge.",
+ "kind": "review",
+ "needs": {
+ "tools": [
+ "git"
+ ]
+ }
+ }
+ },
+ {
+ "group": "8718795de795e643c928d3cc",
+ "at": "2026-10-26T17:50:18.606Z",
+ "request": {
+ "difficulty": "medium",
+ "risk": "high",
+ "size": "small",
+ "why": "Independent review of the main merge.",
+ "kind": "review",
+ "needs": {
+ "tools": [
+ "git"
+ ]
+ }
+ }
+ },
+ {
+ "group": "$g",
+ "at": "2026-10-26T18:29:05.891Z",
+ "request": {
+ "difficulty": "high",
+ "risk": "high",
+ "size": "medium",
+ "why": "Release-blocking fix from the final review.",
+ "kind": "fix",
+ "needs": {
+ "tools": [
+ "git"
+ ]
+ }
+ }
+ },
+ {
+ "group": "$rg",
+ "at": "2026-10-26T18:38:49.686Z",
+ "request": {
+ "difficulty": "high",
+ "risk": "high",
+ "size": "small",
+ "why": "Focused re-check by the reviewer who found the issue.",
+ "kind": "review",
+ "needs": {
+ "tools": [
+ "git"
+ ]
+ }
+ }
+ }
+]
diff --git a/tools/scheduler/data/2026-10-26-status.redacted.json b/tools/scheduler/data/2026-10-26-status.redacted.json
new file mode 100644
index 000000000..aa0702879
--- /dev/null
+++ b/tools/scheduler/data/2026-10-26-status.redacted.json
@@ -0,0 +1,1411 @@
+{
+ "value": {
+ "state": {
+ "people": [
+ {
+ "id": "6a86d24c2ea251076eb4eebe",
+ "role": "owner"
+ },
+ {
+ "id": "6a87d2540fc799caad5cf805",
+ "role": "collaborator"
+ },
+ {
+ "id": "6a9115f9d79b582a980a37a6",
+ "role": "collaborator"
+ },
+ {
+ "id": "6a9115a7b60eaba7239195e8",
+ "role": "collaborator"
+ },
+ {
+ "id": "6a8fe4fcf1a6b5972eed0103",
+ "role": "collaborator"
+ },
+ {
+ "id": "6aabb7bb349df514229c0a12",
+ "role": "collaborator"
+ }
+ ],
+ "agents": [
+ {
+ "id": "0fcbb3107d5336e0f5f8abdc",
+ "machineId": "e5c123a616155ce517f24c414cf57180",
+ "projectId": "5701099db2a04f605ac0d4d4",
+ "name": "Lead",
+ "configuration": {
+ "engine": "claude",
+ "model": "opus",
+ "effort": "auto"
+ }
+ },
+ {
+ "id": "fa8fc7a462989d9335bb1367",
+ "machineId": "ebedf81ba6a1ab03c324f4e8f58b094a",
+ "projectId": "5701099db2a04f605ac0d4d4",
+ "name": "Builder",
+ "configuration": {
+ "engine": "claude",
+ "model": "opus",
+ "effort": "auto"
+ }
+ },
+ {
+ "id": "60d89b4d55170d5a5f2819d7",
+ "machineId": "ebedf81ba6a1ab03c324f4e8f58b094a",
+ "projectId": "5701099db2a04f605ac0d4d4",
+ "name": "Builder",
+ "configuration": {
+ "engine": "claude",
+ "model": "opus",
+ "effort": "auto"
+ }
+ },
+ {
+ "id": "0540dbb44cdd4c2e2be7b512",
+ "machineId": "78351f130fd7a6e04a93c47790767040",
+ "projectId": "5701099db2a04f605ac0d4d4",
+ "name": "Builder",
+ "configuration": {
+ "engine": "claude",
+ "model": "opus",
+ "effort": "xhigh"
+ }
+ },
+ {
+ "id": "71331283f7e086e201e08684",
+ "machineId": "78351f130fd7a6e04a93c47790767040",
+ "projectId": "5701099db2a04f605ac0d4d4",
+ "name": "Builder",
+ "configuration": {
+ "engine": "claude",
+ "model": "opus",
+ "effort": "xhigh"
+ }
+ },
+ {
+ "id": "930adcb914795fa8be059096",
+ "machineId": "78351f130fd7a6e04a93c47790767040",
+ "projectId": "5701099db2a04f605ac0d4d4",
+ "name": "Builder",
+ "configuration": {
+ "engine": "claude",
+ "model": "opus",
+ "effort": "xhigh"
+ }
+ },
+ {
+ "id": "37afea9df555a4cd3467e36c",
+ "machineId": "e5c123a616155ce517f24c414cf57180",
+ "projectId": "5701099db2a04f605ac0d4d4",
+ "name": "Builder",
+ "configuration": {
+ "engine": "claude",
+ "model": "sonnet",
+ "effort": "auto"
+ }
+ },
+ {
+ "id": "dda0b17957d93620adad7b53",
+ "machineId": "e5c123a616155ce517f24c414cf57180",
+ "projectId": "5701099db2a04f605ac0d4d4",
+ "name": "Builder",
+ "configuration": {
+ "engine": "claude",
+ "model": "sonnet",
+ "effort": "medium"
+ }
+ },
+ {
+ "id": "96b2fe87fbc4df4ad29e57b4",
+ "machineId": "e5c123a616155ce517f24c414cf57180",
+ "projectId": "5701099db2a04f605ac0d4d4",
+ "name": "Reviewer",
+ "configuration": {
+ "engine": "codex",
+ "model": "gpt-6.1-sol",
+ "effort": "auto"
+ }
+ },
+ {
+ "id": "d236d1b58cc13dc360595eda",
+ "machineId": "e5c123a616155ce517f24c414cf57180",
+ "projectId": "5701099db2a04f605ac0d4d4",
+ "name": "Reviewer",
+ "configuration": {
+ "engine": "codex",
+ "model": "gpt-6.1-sol",
+ "effort": "auto"
+ }
+ },
+ {
+ "id": "937f9dbfee4a7f66a1bdb13b",
+ "machineId": "e5c123a616155ce517f24c414cf57180",
+ "projectId": "5701099db2a04f605ac0d4d4",
+ "name": "Reviewer",
+ "configuration": {
+ "engine": "codex",
+ "model": "gpt-6.1-sol",
+ "effort": "auto"
+ }
+ },
+ {
+ "id": "656329a6635d3b25bb81eac5",
+ "machineId": "e5c123a616155ce517f24c414cf57180",
+ "projectId": "5701099db2a04f605ac0d4d4",
+ "name": "Builder",
+ "configuration": {
+ "engine": "claude",
+ "model": "opus",
+ "effort": "auto"
+ }
+ },
+ {
+ "id": "d02c33080defd819f206b24e",
+ "machineId": "383ce46764d8cbf68d598ec77827a6a2",
+ "projectId": "5701099db2a04f605ac0d4d4",
+ "name": "Reviewer",
+ "configuration": {
+ "engine": "codex",
+ "model": "gpt-6-sol",
+ "effort": "high"
+ }
+ },
+ {
+ "id": "93bbf6fffaa8f7a7f0c757f1",
+ "machineId": "e5c123a616155ce517f24c414cf57180",
+ "projectId": "5701099db2a04f605ac0d4d4",
+ "name": "Builder",
+ "configuration": {
+ "engine": "claude",
+ "model": "opus",
+ "effort": "auto"
+ }
+ },
+ {
+ "id": "cda6a1e03d3ac133a46c3fc0",
+ "machineId": "e5c123a616155ce517f24c414cf57180",
+ "projectId": "5701099db2a04f605ac0d4d4",
+ "name": "Builder",
+ "configuration": {
+ "engine": "claude",
+ "model": "opus",
+ "effort": "auto"
+ }
+ }
+ ],
+ "machines": [
+ {
+ "machineId": "383ce46764d8cbf68d598ec77827a6a2",
+ "maxAgents": 16,
+ "engines": [
+ "claude",
+ "codex",
+ "cursor",
+ "opencode",
+ "pi",
+ "hermes",
+ "commandcode",
+ "devin",
+ "muse",
+ "amp",
+ "kilo",
+ "grok",
+ "agy",
+ "copilot"
+ ],
+ "name": "MacbookPro.local",
+ "observation": {
+ "receivedAt": 1793056351373,
+ "quotas": [
+ {
+ "engine": "claude",
+ "known": false,
+ "windows": []
+ },
+ {
+ "engine": "codex",
+ "known": true,
+ "windows": [
+ {
+ "name": "weekly",
+ "usedPercent": 67,
+ "resetsAt": 1793599668
+ }
+ ]
+ }
+ ],
+ "localModels": [
+ {
+ "grid": "swarm-626d5615ecf5",
+ "model": "deepseek/deepseek-v4.1-flash-1017",
+ "kind": "api",
+ "name": "deepseek/deepseek-v4.1-flash-1017 · OpenRouter"
+ }
+ ]
+ }
+ },
+ {
+ "machineId": "001bcba1e7e9deb6f8756c053a951ce2",
+ "maxAgents": 8,
+ "engines": [
+ "claude",
+ "codex",
+ "cursor",
+ "opencode",
+ "hermes",
+ "devin",
+ "muse",
+ "kilo",
+ "grok",
+ "agy"
+ ],
+ "name": "[person]'s Mac",
+ "observation": {
+ "receivedAt": 1793040578701,
+ "quotas": [
+ {
+ "engine": "claude",
+ "known": true,
+ "windows": [
+ {
+ "name": "5-hour",
+ "usedPercent": 3,
+ "resetsAt": "2026-10-26T21:59:59.739398+00:00"
+ },
+ {
+ "name": "weekly",
+ "usedPercent": 72,
+ "resetsAt": "2026-10-30T14:59:59.739417+00:00"
+ }
+ ]
+ },
+ {
+ "engine": "codex",
+ "known": true,
+ "windows": [
+ {
+ "name": "weekly",
+ "usedPercent": 100,
+ "resetsAt": 1794982274
+ }
+ ]
+ }
+ ],
+ "localModels": []
+ }
+ },
+ {
+ "machineId": "78351f130fd7a6e04a93c47790767040",
+ "maxAgents": 8,
+ "engines": [
+ "claude",
+ "codex",
+ "cursor",
+ "opencode",
+ "hermes"
+ ],
+ "name": "MacBookPro2021.local",
+ "observation": {
+ "receivedAt": 1793056351192,
+ "quotas": [
+ {
+ "engine": "claude",
+ "known": true,
+ "windows": [
+ {
+ "name": "5-hour",
+ "usedPercent": 2,
+ "resetsAt": "2026-10-27T03:29:59.883314+00:00"
+ },
+ {
+ "name": "weekly",
+ "usedPercent": 30,
+ "resetsAt": "2026-11-01T18:59:59.883335+00:00"
+ }
+ ]
+ },
+ {
+ "engine": "codex",
+ "known": true,
+ "windows": [
+ {
+ "name": "5-hour",
+ "usedPercent": 0,
+ "resetsAt": 1795648349
+ }
+ ]
+ }
+ ],
+ "localModels": []
+ }
+ },
+ {
+ "machineId": "d4a1916eb08cc2ececc17e4f90dae498",
+ "maxAgents": 8,
+ "engines": [
+ "claude",
+ "codex"
+ ],
+ "name": "WIN-DELL",
+ "observation": {
+ "receivedAt": 1793012659392,
+ "quotas": [
+ {
+ "engine": "claude",
+ "known": true,
+ "windows": [
+ {
+ "name": "5-hour",
+ "usedPercent": 25,
+ "resetsAt": "2026-10-26T11:50:00.464054+00:00"
+ },
+ {
+ "name": "weekly",
+ "usedPercent": 64,
+ "resetsAt": "2026-10-30T15:00:00.464076+00:00"
+ }
+ ]
+ },
+ {
+ "engine": "codex",
+ "known": true,
+ "windows": [
+ {
+ "name": "weekly",
+ "usedPercent": 33,
+ "resetsAt": 1793599668
+ }
+ ]
+ }
+ ],
+ "localModels": []
+ }
+ },
+ {
+ "machineId": "e5c123a616155ce517f24c414cf57180",
+ "maxAgents": 16,
+ "engines": [
+ "claude",
+ "codex"
+ ],
+ "name": "MACs-Mac-Studio.local",
+ "observation": {
+ "receivedAt": 1793056345878,
+ "quotas": [
+ {
+ "engine": "claude",
+ "known": false,
+ "windows": []
+ },
+ {
+ "engine": "codex",
+ "known": true,
+ "windows": [
+ {
+ "name": "weekly",
+ "usedPercent": 67,
+ "resetsAt": 1793599668
+ }
+ ]
+ }
+ ],
+ "localModels": []
+ }
+ },
+ {
+ "machineId": "ebedf81ba6a1ab03c324f4e8f58b094a",
+ "maxAgents": 1,
+ "engines": [
+ "claude",
+ "codex"
+ ],
+ "name": "MacBooks-MacBook-Pro-19.local",
+ "observation": {
+ "receivedAt": 1793056347164,
+ "quotas": [
+ {
+ "engine": "claude",
+ "known": false,
+ "windows": []
+ },
+ {
+ "engine": "codex",
+ "known": true,
+ "windows": [
+ {
+ "name": "5-hour",
+ "usedPercent": 0,
+ "resetsAt": 1793074344
+ },
+ {
+ "name": "weekly",
+ "usedPercent": 5,
+ "resetsAt": 1793602151
+ }
+ ]
+ }
+ ],
+ "localModels": []
+ }
+ },
+ {
+ "machineId": "0caa2f6c73e8123baf0705c76b35420d",
+ "maxAgents": 4,
+ "engines": [
+ "claude",
+ "codex"
+ ],
+ "name": "MacBooks-MacBook-Pro-10.local",
+ "observation": {
+ "receivedAt": 1793016835604,
+ "quotas": [
+ {
+ "engine": "claude",
+ "known": true,
+ "windows": [
+ {
+ "name": "5-hour",
+ "usedPercent": 16,
+ "resetsAt": "2026-10-26T14:59:59.648298+00:00"
+ },
+ {
+ "name": "weekly",
+ "usedPercent": 19,
+ "resetsAt": "2026-11-01T03:59:59.648321+00:00"
+ }
+ ]
+ },
+ {
+ "engine": "codex",
+ "known": true,
+ "windows": [
+ {
+ "name": "weekly",
+ "usedPercent": 3,
+ "resetsAt": 1795163925
+ }
+ ]
+ }
+ ],
+ "localModels": []
+ }
+ }
+ ],
+ "conversations": [
+ {
+ "id": "project-5701099db2a04f605ac0d4d4",
+ "projectId": "5701099db2a04f605ac0d4d4",
+ "title": "Lead",
+ "assignment": null
+ },
+ {
+ "id": "9e7e516b4e7e1f90d7c9ca43",
+ "projectId": "5701099db2a04f605ac0d4d4",
+ "title": "Regression: API models in the Swarm",
+ "assignment": {
+ "id": "1f0964cfb3e5c7d38b7806a2",
+ "agentId": "fa8fc7a462989d9335bb1367",
+ "status": "working",
+ "configuration": {
+ "engine": "claude",
+ "model": "opus",
+ "effort": "auto"
+ },
+ "execution": {
+ "machineId": "ebedf81ba6a1ab03c324f4e8f58b094a"
+ }
+ }
+ },
+ {
+ "id": "274baf5b89089a604ebbff4b",
+ "projectId": "5701099db2a04f605ac0d4d4",
+ "title": "Smoke: DeepSeek API on MacbookPro.local",
+ "assignment": {
+ "id": "fb5dcd8981e91928ca52fee2",
+ "agentId": "b9bd74aa495ad91bfb5e6481",
+ "status": "done",
+ "configuration": {
+ "engine": "claude",
+ "model": "deepseek/deepseek-v4.1-flash-1017",
+ "effort": "high"
+ },
+ "execution": {
+ "machineId": "383ce46764d8cbf68d598ec77827a6a2"
+ }
+ }
+ },
+ {
+ "id": "aa409e467756f366f8ec67d4",
+ "projectId": "5701099db2a04f605ac0d4d4",
+ "title": "Smoke: DeepSeek API on MacBooks-MacBook-Pro-19.local",
+ "assignment": {
+ "id": "fd17f229181721cac69beaab",
+ "agentId": "4253d47271da4bc84eef9edb",
+ "status": "done",
+ "configuration": {
+ "engine": "claude",
+ "model": "deepseek/deepseek-v4.1-flash-1017",
+ "effort": "auto"
+ },
+ "execution": {
+ "machineId": "ebedf81ba6a1ab03c324f4e8f58b094a"
+ }
+ }
+ },
+ {
+ "id": "feb85d3aef2375b81b4275eb",
+ "projectId": "5701099db2a04f605ac0d4d4",
+ "title": "Smoke: DeepSeek API on MACs-Mac-Studio.local",
+ "assignment": {
+ "id": "10b24f331a33a2b014e3ecd5",
+ "agentId": "090e9ec08116ca53444ca7b1",
+ "status": "done",
+ "configuration": {
+ "engine": "claude",
+ "model": "deepseek/deepseek-v4.1-flash-1017",
+ "effort": "auto"
+ },
+ "execution": {
+ "machineId": "e5c123a616155ce517f24c414cf57180"
+ }
+ }
+ },
+ {
+ "id": "d80142e540abade0e9ac21de",
+ "projectId": "5701099db2a04f605ac0d4d4",
+ "title": "Smoke: DeepSeek API on [person]'s Mac",
+ "assignment": {
+ "id": "62ec6337a87ba8f6c82b97f9",
+ "agentId": "51addee11e2be5413fa35cb8",
+ "status": "done",
+ "configuration": {
+ "engine": "claude",
+ "model": "deepseek/deepseek-v4.1-flash-1017",
+ "effort": "xhigh"
+ },
+ "execution": {
+ "machineId": "001bcba1e7e9deb6f8756c053a951ce2"
+ }
+ }
+ },
+ {
+ "id": "837f400f3252d7491843ecff",
+ "projectId": "5701099db2a04f605ac0d4d4",
+ "title": "Smoke: DeepSeek API on WIN-DELL",
+ "assignment": null
+ },
+ {
+ "id": "2b8a76771f8d6e8380101ad0",
+ "projectId": "5701099db2a04f605ac0d4d4",
+ "title": "Measure: Super Tab load and message time on the web",
+ "assignment": {
+ "id": "7d801f4ade75bbbcff9dd016",
+ "agentId": "60d89b4d55170d5a5f2819d7",
+ "status": "working",
+ "configuration": {
+ "engine": "claude",
+ "model": "opus",
+ "effort": "auto"
+ },
+ "execution": {
+ "machineId": "ebedf81ba6a1ab03c324f4e8f58b094a"
+ }
+ }
+ },
+ {
+ "id": "659a6cc93b944bd24cae2884",
+ "projectId": "5701099db2a04f605ac0d4d4",
+ "title": "1726 G0: Swarm load benchmark (baseline)",
+ "assignment": {
+ "id": "2cfd6ca673a31100abc117eb",
+ "agentId": "91b91e3786d8278afc40a96e",
+ "status": "done",
+ "configuration": {
+ "engine": "claude",
+ "model": "opus",
+ "effort": "high"
+ },
+ "execution": {
+ "machineId": "78351f130fd7a6e04a93c47790767040"
+ }
+ }
+ },
+ {
+ "id": "aeef05a35995ca9f7cca7060",
+ "projectId": "5701099db2a04f605ac0d4d4",
+ "title": "1726 G1: design doc for Swarm state by parts",
+ "assignment": {
+ "id": "09d0977df3acafae56af6178",
+ "agentId": "0540dbb44cdd4c2e2be7b512",
+ "status": "done",
+ "configuration": {
+ "engine": "claude",
+ "model": "opus",
+ "effort": "high"
+ },
+ "execution": {
+ "machineId": "78351f130fd7a6e04a93c47790767040"
+ }
+ }
+ },
+ {
+ "id": "8c0d038efe1b63d3b6628552",
+ "projectId": "5701099db2a04f605ac0d4d4",
+ "title": "Smoke: DeepSeek API after CLI 0.4.73 (Mac Studio)",
+ "assignment": {
+ "id": "6a6287f70a5d2ba89403a66d",
+ "agentId": "5d67c7f4f62ad5c54b7d5123",
+ "status": "done",
+ "configuration": {
+ "engine": "claude",
+ "model": "deepseek/deepseek-v4.1-flash-1017",
+ "effort": "auto"
+ },
+ "execution": {
+ "machineId": "e5c123a616155ce517f24c414cf57180"
+ }
+ }
+ },
+ {
+ "id": "424ee80b74789dcde33b6ade",
+ "projectId": "5701099db2a04f605ac0d4d4",
+ "title": "Check: CLI version and grid log on WIN-DELL",
+ "assignment": null
+ },
+ {
+ "id": "e37ffff373d0afd7fc763726",
+ "projectId": "5701099db2a04f605ac0d4d4",
+ "title": "Check: CLI version and grid log on MacbookPro.local",
+ "assignment": {
+ "id": "c9e64b2deb153a552d673c2d",
+ "agentId": "5dae1e8475f7813d88b5ce46",
+ "status": "done",
+ "configuration": {
+ "engine": "claude",
+ "model": "sonnet",
+ "effort": "medium"
+ },
+ "execution": {
+ "machineId": "383ce46764d8cbf68d598ec77827a6a2"
+ }
+ }
+ },
+ {
+ "id": "5c48779c71d5111602eab51f",
+ "projectId": "5701099db2a04f605ac0d4d4",
+ "title": "Review: 1726 G1 design doc",
+ "assignment": {
+ "id": "15cf42e5c2ee5348dfd5ac41",
+ "agentId": "7f5c2be98dc9c51b35af5de1",
+ "status": "done",
+ "configuration": {
+ "engine": "codex",
+ "model": "gpt-6-sol",
+ "effort": "high"
+ },
+ "execution": {
+ "machineId": "383ce46764d8cbf68d598ec77827a6a2"
+ }
+ }
+ },
+ {
+ "id": "df0940f037c9f6eef1b92b67",
+ "projectId": "5701099db2a04f605ac0d4d4",
+ "title": "1726 G2: backend storage and commands by parts",
+ "assignment": {
+ "id": "730c4929c97838e2f82d794c",
+ "agentId": "0540dbb44cdd4c2e2be7b512",
+ "status": "done",
+ "configuration": {
+ "engine": "claude",
+ "model": "opus",
+ "effort": "xhigh"
+ },
+ "execution": {
+ "machineId": "78351f130fd7a6e04a93c47790767040"
+ }
+ }
+ },
+ {
+ "id": "c2e38ce017f6f8e65ef8bdce",
+ "projectId": "5701099db2a04f605ac0d4d4",
+ "title": "1726 G3: backend read API and migration",
+ "assignment": {
+ "id": "390110f40abeb1f249ce092e",
+ "agentId": "71331283f7e086e201e08684",
+ "status": "done",
+ "configuration": {
+ "engine": "claude",
+ "model": "opus",
+ "effort": "xhigh"
+ },
+ "execution": {
+ "machineId": "78351f130fd7a6e04a93c47790767040"
+ }
+ }
+ },
+ {
+ "id": "0a84ea687a435833d1649933",
+ "projectId": "5701099db2a04f605ac0d4d4",
+ "title": "1726 G5: CLI on the new read API",
+ "assignment": {
+ "id": "f86275af026cfb5950ce0b4b",
+ "agentId": "930adcb914795fa8be059096",
+ "status": "done",
+ "configuration": {
+ "engine": "claude",
+ "model": "opus",
+ "effort": "xhigh"
+ },
+ "execution": {
+ "machineId": "78351f130fd7a6e04a93c47790767040"
+ }
+ }
+ },
+ {
+ "id": "2e2d726a3ff6196c26d44f8f",
+ "projectId": "5701099db2a04f605ac0d4d4",
+ "title": "1726 G4: Desktop and web on the new read API",
+ "assignment": {
+ "id": "be2d0c47157ea5746f5944cc",
+ "agentId": "7fc7f10cd2dc8496cf371522",
+ "status": "cancelled",
+ "configuration": {
+ "engine": "claude",
+ "model": "opus",
+ "effort": "high"
+ },
+ "execution": {
+ "machineId": "001bcba1e7e9deb6f8756c053a951ce2"
+ }
+ }
+ },
+ {
+ "id": "6bc636fa6713886102b9cbfa",
+ "projectId": "5701099db2a04f605ac0d4d4",
+ "title": "Review: 1726 G0 benchmark",
+ "assignment": {
+ "id": "8794d7b972c87d5edf506511",
+ "agentId": "d6d32b222b48616ae05c3231",
+ "status": "done",
+ "configuration": {
+ "engine": "codex",
+ "model": "gpt-6.1-sol",
+ "effort": "auto"
+ },
+ "execution": {
+ "machineId": "e5c123a616155ce517f24c414cf57180"
+ }
+ }
+ },
+ {
+ "id": "5f0d3516fb850999cb824c90",
+ "projectId": "5701099db2a04f605ac0d4d4",
+ "title": "Review: 1726 G5 CLI",
+ "assignment": {
+ "id": "660481291dd501f3b1a1a19e",
+ "agentId": "96b2fe87fbc4df4ad29e57b4",
+ "status": "done",
+ "configuration": {
+ "engine": "codex",
+ "model": "gpt-6.1-sol",
+ "effort": "auto"
+ },
+ "execution": {
+ "machineId": "e5c123a616155ce517f24c414cf57180"
+ }
+ }
+ },
+ {
+ "id": "7a23487b3220d1564f9c7522",
+ "projectId": "5701099db2a04f605ac0d4d4",
+ "title": "Review: 1726 G3 read API and migration",
+ "assignment": {
+ "id": "667f6d47cc52db17fbcdc3c7",
+ "agentId": "d236d1b58cc13dc360595eda",
+ "status": "done",
+ "configuration": {
+ "engine": "codex",
+ "model": "gpt-6.1-sol",
+ "effort": "auto"
+ },
+ "execution": {
+ "machineId": "e5c123a616155ce517f24c414cf57180"
+ }
+ }
+ },
+ {
+ "id": "e6115d403f62dd42d5cf3ab3",
+ "projectId": "5701099db2a04f605ac0d4d4",
+ "title": "Swarm plan R1: how the lampOS team works",
+ "assignment": {
+ "id": "9ab6da931320eefbe45b745f",
+ "agentId": "eb9d56c53b3590475cde4b69",
+ "status": "done",
+ "configuration": {
+ "engine": "claude",
+ "model": "opus",
+ "effort": "auto"
+ },
+ "execution": {
+ "machineId": "e5c123a616155ce517f24c414cf57180"
+ }
+ }
+ },
+ {
+ "id": "acdc5546b9fcc601abb8b22c",
+ "projectId": "5701099db2a04f605ac0d4d4",
+ "title": "Swarm plan R2: pain points of fast agent teams",
+ "assignment": {
+ "id": "301bb40071b2f3df218c110f",
+ "agentId": "dae0591e7300285ce9489f2d",
+ "status": "done",
+ "configuration": {
+ "engine": "claude",
+ "model": "opus",
+ "effort": "auto"
+ },
+ "execution": {
+ "machineId": "e5c123a616155ce517f24c414cf57180"
+ }
+ }
+ },
+ {
+ "id": "e141b9c91ab56d8509789a49",
+ "projectId": "5701099db2a04f605ac0d4d4",
+ "title": "Review: 1726 G4 Desktop and web",
+ "assignment": {
+ "id": "cdc7b7ae3a73da133dbb0d56",
+ "agentId": "937f9dbfee4a7f66a1bdb13b",
+ "status": "done",
+ "configuration": {
+ "engine": "codex",
+ "model": "gpt-6.1-sol",
+ "effort": "auto"
+ },
+ "execution": {
+ "machineId": "e5c123a616155ce517f24c414cf57180"
+ }
+ }
+ },
+ {
+ "id": "0da3404ca7a4a33f57d4c871",
+ "projectId": "5701099db2a04f605ac0d4d4",
+ "title": "Review: 1726 G2 backend storage and commands",
+ "assignment": {
+ "id": "4f39d45dc4228a882a7d39fb",
+ "agentId": "d6d32b222b48616ae05c3231",
+ "status": "done",
+ "configuration": {
+ "engine": "codex",
+ "model": "gpt-6.1-sol",
+ "effort": "auto"
+ },
+ "execution": {
+ "machineId": "e5c123a616155ce517f24c414cf57180"
+ }
+ }
+ },
+ {
+ "id": "8f099aef658fa637127c3482",
+ "projectId": "5701099db2a04f605ac0d4d4",
+ "title": "1726 G6: integrate, measure, migration dry run",
+ "assignment": {
+ "id": "13f2b2141a18213b77706cec",
+ "agentId": "91b91e3786d8278afc40a96e",
+ "status": "done",
+ "configuration": {
+ "engine": "claude",
+ "model": "opus",
+ "effort": "xhigh"
+ },
+ "execution": {
+ "machineId": "78351f130fd7a6e04a93c47790767040"
+ }
+ }
+ },
+ {
+ "id": "45e5e3322e966e128a7d0f3d",
+ "projectId": "5701099db2a04f605ac0d4d4",
+ "title": "1726 G3b: reads load only the parts that changed",
+ "assignment": {
+ "id": "064685631159620099640a44",
+ "agentId": "71331283f7e086e201e08684",
+ "status": "done",
+ "configuration": {
+ "engine": "claude",
+ "model": "opus",
+ "effort": "xhigh"
+ },
+ "execution": {
+ "machineId": "78351f130fd7a6e04a93c47790767040"
+ }
+ }
+ },
+ {
+ "id": "4c650945b01ab59703017bfb",
+ "projectId": "5701099db2a04f605ac0d4d4",
+ "title": "v1 liveness A: lost work and takeover (backend)",
+ "assignment": {
+ "id": "3add6df9ddc2585193bd9de5",
+ "agentId": "0540dbb44cdd4c2e2be7b512",
+ "status": "done",
+ "configuration": {
+ "engine": "claude",
+ "model": "opus",
+ "effort": "xhigh"
+ },
+ "execution": {
+ "machineId": "78351f130fd7a6e04a93c47790767040"
+ }
+ }
+ },
+ {
+ "id": "b27e3b7574be0b1bf4a76986",
+ "projectId": "5701099db2a04f605ac0d4d4",
+ "title": "v1 liveness B: host progress and Lead takeover (CLI)",
+ "assignment": {
+ "id": "0b55a76d3300dc52e1ac1e93",
+ "agentId": "930adcb914795fa8be059096",
+ "status": "done",
+ "configuration": {
+ "engine": "claude",
+ "model": "opus",
+ "effort": "xhigh"
+ },
+ "execution": {
+ "machineId": "78351f130fd7a6e04a93c47790767040"
+ }
+ }
+ },
+ {
+ "id": "b0b28597aa6be5ef38defa6e",
+ "projectId": "5701099db2a04f605ac0d4d4",
+ "title": "v1 routing: only machines that can do the work",
+ "assignment": {
+ "id": "7c3b8bc188554881c2f347c6",
+ "agentId": "656329a6635d3b25bb81eac5",
+ "status": "done",
+ "configuration": {
+ "engine": "claude",
+ "model": "opus",
+ "effort": "high"
+ },
+ "execution": {
+ "machineId": "e5c123a616155ce517f24c414cf57180"
+ }
+ }
+ },
+ {
+ "id": "f3a620e144116d08c3a68338",
+ "projectId": "5701099db2a04f605ac0d4d4",
+ "title": "v1 DM: a private chat with the PM for each person (Desktop and web)",
+ "assignment": {
+ "id": "da35660a3cb92945634d4733",
+ "agentId": "0a4f57d20d8002c862db5493",
+ "status": "done",
+ "configuration": {
+ "engine": "claude",
+ "model": "opus",
+ "effort": "high"
+ },
+ "execution": {
+ "machineId": "001bcba1e7e9deb6f8756c053a951ce2"
+ }
+ }
+ },
+ {
+ "id": "4f49c22420c3c3fc57dda058",
+ "projectId": "5701099db2a04f605ac0d4d4",
+ "title": "Review: v1 routing: only machines that can do the work",
+ "assignment": {
+ "id": "a0079d1d37cb9fe0bf8199b8",
+ "agentId": "d236d1b58cc13dc360595eda",
+ "status": "done",
+ "configuration": {
+ "engine": "codex",
+ "model": "gpt-6.1-sol",
+ "effort": "auto"
+ },
+ "execution": {
+ "machineId": "e5c123a616155ce517f24c414cf57180"
+ }
+ }
+ },
+ {
+ "id": "1e43f418b6c92f435689581d",
+ "projectId": "5701099db2a04f605ac0d4d4",
+ "title": "Review: v1 liveness B: host progress and Lead takeover (CLI)",
+ "assignment": {
+ "id": "d9d53c7460d1368639a7e079",
+ "agentId": "937f9dbfee4a7f66a1bdb13b",
+ "status": "done",
+ "configuration": {
+ "engine": "codex",
+ "model": "gpt-6.1-sol",
+ "effort": "auto"
+ },
+ "execution": {
+ "machineId": "e5c123a616155ce517f24c414cf57180"
+ }
+ }
+ },
+ {
+ "id": "d71cdb0a2ab3181904d5eb3d",
+ "projectId": "5701099db2a04f605ac0d4d4",
+ "title": "Review: v1 liveness A: lost work and takeover (backend)",
+ "assignment": {
+ "id": "12f71646335e00691c0cd47c",
+ "agentId": "96b2fe87fbc4df4ad29e57b4",
+ "status": "done",
+ "configuration": {
+ "engine": "codex",
+ "model": "gpt-6.1-sol",
+ "effort": "auto"
+ },
+ "execution": {
+ "machineId": "e5c123a616155ce517f24c414cf57180"
+ }
+ }
+ },
+ {
+ "id": "b483494ef289e282021b1e2a",
+ "projectId": "5701099db2a04f605ac0d4d4",
+ "title": "Review: 1726 G3b: reads load only the parts that changed",
+ "assignment": {
+ "id": "c9a56d7db0615ff05124f36e",
+ "agentId": "d02c33080defd819f206b24e",
+ "status": "done",
+ "configuration": {
+ "engine": "codex",
+ "model": "gpt-6-sol",
+ "effort": "high"
+ },
+ "execution": {
+ "machineId": "383ce46764d8cbf68d598ec77827a6a2"
+ }
+ }
+ },
+ {
+ "id": "32777a379c1fd8cccfde3e85",
+ "projectId": "5701099db2a04f605ac0d4d4",
+ "title": "Review: v1 DM: Chat with PM (Desktop and web)",
+ "assignment": {
+ "id": "b701a992577f1bc09e7abfcd",
+ "agentId": "937f9dbfee4a7f66a1bdb13b",
+ "status": "done",
+ "configuration": {
+ "engine": "codex",
+ "model": "gpt-6.1-sol",
+ "effort": "auto"
+ },
+ "execution": {
+ "machineId": "e5c123a616155ce517f24c414cf57180"
+ }
+ }
+ },
+ {
+ "id": "400c47daa5f4e2be6ab1c2e3",
+ "projectId": "5701099db2a04f605ac0d4d4",
+ "title": "Review: 1726 G6 results doc",
+ "assignment": {
+ "id": "d53957ff36c9c72fc6988049",
+ "agentId": "d02c33080defd819f206b24e",
+ "status": "done",
+ "configuration": {
+ "engine": "codex",
+ "model": "gpt-6-sol",
+ "effort": "high"
+ },
+ "execution": {
+ "machineId": "383ce46764d8cbf68d598ec77827a6a2"
+ }
+ }
+ },
+ {
+ "id": "4bc913c9bf52f96cadbcd419",
+ "projectId": "5701099db2a04f605ac0d4d4",
+ "title": "1726 final: merge main into the feature branch",
+ "assignment": {
+ "id": "9a6fd6fc993820e88eef0724",
+ "agentId": "930adcb914795fa8be059096",
+ "status": "review",
+ "configuration": {
+ "engine": "claude",
+ "model": "opus",
+ "effort": "xhigh"
+ },
+ "execution": {
+ "machineId": "78351f130fd7a6e04a93c47790767040"
+ }
+ }
+ },
+ {
+ "id": "04c39494afc5fb4c5a867455",
+ "projectId": "5701099db2a04f605ac0d4d4",
+ "title": "1726 final: whole-branch review before main",
+ "assignment": null
+ },
+ {
+ "id": "42f34fffe4223cab2ff79e69",
+ "projectId": "5701099db2a04f605ac0d4d4",
+ "title": "Review: 1726 final whole-branch review before main",
+ "assignment": {
+ "id": "25fc5065489973fc8761ffd0",
+ "agentId": "d236d1b58cc13dc360595eda",
+ "status": "done",
+ "configuration": {
+ "engine": "codex",
+ "model": "gpt-6.1-sol",
+ "effort": "auto"
+ },
+ "execution": {
+ "machineId": "e5c123a616155ce517f24c414cf57180"
+ }
+ }
+ },
+ {
+ "id": "8718795de795e643c928d3cc",
+ "projectId": "5701099db2a04f605ac0d4d4",
+ "title": "Review: 1726 final merge of main",
+ "assignment": {
+ "id": "4cd52095135d1cbc2d04afe3",
+ "agentId": "96b2fe87fbc4df4ad29e57b4",
+ "status": "done",
+ "configuration": {
+ "engine": "codex",
+ "model": "gpt-6.1-sol",
+ "effort": "auto"
+ },
+ "execution": {
+ "machineId": "e5c123a616155ce517f24c414cf57180"
+ }
+ }
+ },
+ {
+ "id": "977d937c468e7720151c780e",
+ "projectId": "5701099db2a04f605ac0d4d4",
+ "title": "1726 final fix C1: private PM chat must not reach terminal observers",
+ "assignment": {
+ "id": "b35233a8367efb08c180c09b",
+ "agentId": "0540dbb44cdd4c2e2be7b512",
+ "status": "done",
+ "configuration": {
+ "engine": "claude",
+ "model": "opus",
+ "effort": "xhigh"
+ },
+ "execution": {
+ "machineId": "78351f130fd7a6e04a93c47790767040"
+ }
+ }
+ },
+ {
+ "id": "b365e73faae5aa84b1b4d544",
+ "projectId": "5701099db2a04f605ac0d4d4",
+ "title": "1726 final fix C2: rollback must not expose private chats or lost work",
+ "assignment": {
+ "id": "e071da9fdc831304b37a4f27",
+ "agentId": "71331283f7e086e201e08684",
+ "status": "done",
+ "configuration": {
+ "engine": "claude",
+ "model": "opus",
+ "effort": "xhigh"
+ },
+ "execution": {
+ "machineId": "78351f130fd7a6e04a93c47790767040"
+ }
+ }
+ },
+ {
+ "id": "3f97d137a02c078abfdc7d74",
+ "projectId": "5701099db2a04f605ac0d4d4",
+ "title": "1726 final fix I3: a lost worker stays out of routing after cancel or reassign",
+ "assignment": {
+ "id": "bd546c8f6f4df12b9cab38d6",
+ "agentId": "656329a6635d3b25bb81eac5",
+ "status": "done",
+ "configuration": {
+ "engine": "claude",
+ "model": "opus",
+ "effort": "auto"
+ },
+ "execution": {
+ "machineId": "e5c123a616155ce517f24c414cf57180"
+ }
+ }
+ },
+ {
+ "id": "42095c031091b32d2d5e163b",
+ "projectId": "5701099db2a04f605ac0d4d4",
+ "title": "Review: 1726 final fix C2 rollback",
+ "assignment": {
+ "id": "da09821d0cb7183cc98b57da",
+ "agentId": "d236d1b58cc13dc360595eda",
+ "status": "done",
+ "configuration": {
+ "engine": "codex",
+ "model": "gpt-6.1-sol",
+ "effort": "auto"
+ },
+ "execution": {
+ "machineId": "e5c123a616155ce517f24c414cf57180"
+ }
+ }
+ },
+ {
+ "id": "a8c17a1e4fb9b75f771b67a7",
+ "projectId": "5701099db2a04f605ac0d4d4",
+ "title": "Review: 1726 final fix I3 lost worker routing",
+ "assignment": {
+ "id": "4e43fcdb8990a1d8600bac36",
+ "agentId": "d236d1b58cc13dc360595eda",
+ "status": "done",
+ "configuration": {
+ "engine": "codex",
+ "model": "gpt-6.1-sol",
+ "effort": "auto"
+ },
+ "execution": {
+ "machineId": "e5c123a616155ce517f24c414cf57180"
+ }
+ }
+ },
+ {
+ "id": "5c6b795d846d44bfb7591837",
+ "projectId": "5701099db2a04f605ac0d4d4",
+ "title": "Review: 1726 final fix C1 PM terminal observers",
+ "assignment": {
+ "id": "4a92a6812ce76d9b9fbdf150",
+ "agentId": "937f9dbfee4a7f66a1bdb13b",
+ "status": "done",
+ "configuration": {
+ "engine": "codex",
+ "model": "gpt-6.1-sol",
+ "effort": "auto"
+ },
+ "execution": {
+ "machineId": "e5c123a616155ce517f24c414cf57180"
+ }
+ }
+ },
+ {
+ "id": "fa552b26cc36df06a9145405",
+ "projectId": "5701099db2a04f605ac0d4d4",
+ "title": "v2 A: Swarm as a switchable subsystem (out of the daemon core)",
+ "assignment": {
+ "id": "e8724477c81fb0db1326db62",
+ "agentId": "93bbf6fffaa8f7a7f0c757f1",
+ "status": "working",
+ "configuration": {
+ "engine": "claude",
+ "model": "opus",
+ "effort": "auto"
+ },
+ "execution": {
+ "machineId": "e5c123a616155ce517f24c414cf57180"
+ }
+ }
+ },
+ {
+ "id": "88a2196381c696b3b458543f",
+ "projectId": "5701099db2a04f605ac0d4d4",
+ "title": "v2 B: night shift (usage limits never stop the Swarm)",
+ "assignment": {
+ "id": "1fc590d9b4c8d5ac5a5fc1c4",
+ "agentId": "656329a6635d3b25bb81eac5",
+ "status": "working",
+ "configuration": {
+ "engine": "claude",
+ "model": "opus",
+ "effort": "auto"
+ },
+ "execution": {
+ "machineId": "e5c123a616155ce517f24c414cf57180"
+ }
+ }
+ },
+ {
+ "id": "04f4dd68dc6273061f4e6194",
+ "projectId": "5701099db2a04f605ac0d4d4",
+ "title": "v2 C: decision packets (batched questions to people)",
+ "assignment": {
+ "id": "4960383ef28bb41d77bb62ab",
+ "agentId": "71331283f7e086e201e08684",
+ "status": "working",
+ "configuration": {
+ "engine": "claude",
+ "model": "opus",
+ "effort": "xhigh"
+ },
+ "execution": {
+ "machineId": "78351f130fd7a6e04a93c47790767040"
+ }
+ }
+ },
+ {
+ "id": "9109dbd1ee0f97b1f12ce4f5",
+ "projectId": "5701099db2a04f605ac0d4d4",
+ "title": "v2 D: review never waits on one reviewer (and no reviewer deadlocks)",
+ "assignment": {
+ "id": "e62849b8e36015b11ca858d0",
+ "agentId": "0540dbb44cdd4c2e2be7b512",
+ "status": "working",
+ "configuration": {
+ "engine": "claude",
+ "model": "opus",
+ "effort": "xhigh"
+ },
+ "execution": {
+ "machineId": "78351f130fd7a6e04a93c47790767040"
+ }
+ }
+ },
+ {
+ "id": "1dace4d8419a80177f226de1",
+ "projectId": "5701099db2a04f605ac0d4d4",
+ "title": "v2 E: scheduler prototype (global assignment of tasks to machines and models)",
+ "assignment": {
+ "id": "d6510a3429a3da95dc3913ab",
+ "agentId": "cda6a1e03d3ac133a46c3fc0",
+ "status": "working",
+ "configuration": {
+ "engine": "claude",
+ "model": "opus",
+ "effort": "auto"
+ },
+ "execution": {
+ "machineId": "e5c123a616155ce517f24c414cf57180"
+ }
+ }
+ },
+ {
+ "id": "27ecc522fbe3759f8e2d70cf",
+ "title": "Leads",
+ "assignment": null
+ }
+ ],
+ "rules": [
+ {
+ "id": "ac7486d7cb068ba952f5a9bf",
+ "projectId": "5701099db2a04f605ac0d4d4",
+ "rule": {
+ "kind": "machines",
+ "machineIds": [
+ "001bcba1e7e9deb6f8756c053a951ce2",
+ "78351f130fd7a6e04a93c47790767040",
+ "ebedf81ba6a1ab03c324f4e8f58b094a",
+ "e5c123a616155ce517f24c414cf57180",
+ "0caa2f6c73e8123baf0705c76b35420d",
+ "383ce46764d8cbf68d598ec77827a6a2"
+ ]
+ },
+ "createdAt": "2026-10-26T14:07:07.215Z",
+ "text": "Owner: no WIN-DELL until it is fixed. MacbookPro.local takes work again from 21:00 Vietnam time (\"Mac [person] tạm ko nhận việc đến 21H VN nha\")."
+ }
+ ]
+ }
+ }
+}
diff --git a/tools/scheduler/requirements.txt b/tools/scheduler/requirements.txt
new file mode 100644
index 000000000..c21d85799
--- /dev/null
+++ b/tools/scheduler/requirements.txt
@@ -0,0 +1 @@
+ortools==9.15.6755
diff --git a/tools/scheduler/scheduler/__init__.py b/tools/scheduler/scheduler/__init__.py
new file mode 100644
index 000000000..e69de29bb
diff --git a/tools/scheduler/scheduler/__main__.py b/tools/scheduler/scheduler/__main__.py
new file mode 100644
index 000000000..8e9667ad4
--- /dev/null
+++ b/tools/scheduler/scheduler/__main__.py
@@ -0,0 +1,68 @@
+"""python -m scheduler solve INSTANCE [--pareto] [--time-limit S]
+python -m scheduler plan [--time-limit S] < INSTANCE (the input and output of `harness super-tab plan`)
+python -m scheduler compare NIGHT [--time-limit S] [--max-slots N]
+python -m scheduler convert STATUS ROUTE_LOG CONFIG OUT
+python -m scheduler redact STATUS ROUTE_LOG STATUS_OUT ROUTE_LOG_OUT"""
+import argparse
+import dataclasses
+import json
+import sys
+
+# Exit code and answer when OR-Tools is not installed, which `harness super-tab plan` tells the Lead.
+ORTOOLS_MISSING = 3
+INSTALL = 'Install it with: python3 -m pip install ortools==9.15.6755'
+
+
+def main(argv=None) -> int:
+ parser = argparse.ArgumentParser(prog='scheduler')
+ sub = parser.add_subparsers(dest='command', required=True)
+ p_solve = sub.add_parser('solve', help='the exact plan for an instance, as JSON')
+ p_solve.add_argument('instance')
+ p_solve.add_argument('--pareto', action='store_true', help='print the finish time against cost set instead')
+ p_solve.add_argument('--time-limit', type=float, default=10.0)
+ p_plan = sub.add_parser('plan', help='the plan for open work: instance on stdin, plan as JSON')
+ p_plan.add_argument('--time-limit', type=float, default=10.0)
+ p_compare = sub.add_parser('compare', help='exact plan, greedy route and actual picks on a converted night')
+ p_compare.add_argument('night')
+ p_compare.add_argument('--time-limit', type=float, default=10.0)
+ p_compare.add_argument('--max-slots', type=int, help='cap every machine at this many agents')
+ p_convert = sub.add_parser('convert', help='a Swarm status snapshot and route log to a night file')
+ p_convert.add_argument('paths', nargs=4, metavar=('STATUS', 'ROUTE_LOG', 'CONFIG', 'OUT'))
+ p_redact = sub.add_parser('redact', help='keep only what convert reads, without emails or people\'s names')
+ p_redact.add_argument('paths', nargs=4, metavar=('STATUS', 'ROUTE_LOG', 'STATUS_OUT', 'ROUTE_LOG_OUT'))
+ args = parser.parse_args(argv)
+
+ from . import redact, swarm
+ if args.command == 'convert':
+ return swarm.main(args.paths)
+ if args.command == 'redact':
+ return redact.main(args.paths)
+ try:
+ from .compare import compare, table
+ from .instance import load
+ from .plan import plan
+ from .solver import pareto, solve
+ except ImportError as error:
+ if 'ortools' not in str(error):
+ raise
+ print(json.dumps({'error': 'ORTOOLS_MISSING', 'detail': f'OR-Tools is not installed for {sys.executable}. {INSTALL}'}))
+ return ORTOOLS_MISSING
+ if args.command == 'plan':
+ print(json.dumps(plan(json.load(sys.stdin), time_limit=args.time_limit)))
+ return 0
+ with open(getattr(args, 'instance', None) or args.night) as f:
+ data = json.load(f)
+ if args.command == 'compare':
+ print(table(compare(data, time_limit=args.time_limit, max_slots=args.max_slots)))
+ return 0
+ instance = load(data.get('instance', data))
+ if args.pareto:
+ front = pareto(instance, time_limit=args.time_limit)
+ print(json.dumps({'complete': front.complete, 'seconds': front.seconds, 'points': [dataclasses.asdict(p) for p in front.points]}, indent=1))
+ else:
+ print(json.dumps(dataclasses.asdict(solve(instance, time_limit=args.time_limit)), indent=1))
+ return 0
+
+
+if __name__ == '__main__':
+ sys.exit(main())
diff --git a/tools/scheduler/scheduler/bench.py b/tools/scheduler/scheduler/bench.py
new file mode 100644
index 000000000..13c0e673c
--- /dev/null
+++ b/tools/scheduler/scheduler/bench.py
@@ -0,0 +1,39 @@
+"""A generated instance shaped like a busy night, for the solve-time check: build tasks with reviews after them, chains
+of work, few slots per machine, quotas that bind and models that differ in strength, cost and speed."""
+import random
+
+# The routing policy's rows, a cheaper Codex and a slow local model on the grid.
+MODELS = [
+ {'id': 'claude-opus', 'engine': 'claude', 'cost': 3, 'quality': {'default': 3}, 'speed': 1.0},
+ {'id': 'codex-default', 'engine': 'codex', 'cost': 2, 'quality': {'default': 3}, 'speed': 0.9},
+ {'id': 'claude-sonnet', 'engine': 'claude', 'cost': 2, 'quality': {'default': 2, 'review': 3}, 'speed': 1.2},
+ {'id': 'codex-mini', 'engine': 'codex', 'cost': 1, 'quality': {'default': 2}, 'speed': 1.3},
+ {'id': 'claude-haiku', 'engine': 'claude', 'cost': 1, 'quality': {'default': 1}, 'speed': 1.5},
+ {'id': 'grid-local', 'engine': 'claude', 'cost': 1, 'quality': {'default': 1}, 'speed': 0.5, 'concurrency': 1,
+ 'subscription': False, 'family': 'local'},
+]
+SIZES = [(20, 1), (60, 4), (180, 8)]
+
+
+def generate(seed: int, tasks: int = 30, machines: int = 8, models: int = 6) -> dict:
+ rng = random.Random(seed)
+ out_tasks = []
+ while len(out_tasks) < tasks:
+ i = len(out_tasks)
+ minutes, weekly = rng.choice(SIZES)
+ earlier = [t['id'] for t in out_tasks if t['kind'] != 'review']
+ deps = rng.sample(earlier, k=min(len(earlier), rng.choice([0, 0, 1, 1, 2])))
+ build = {'id': f't{i}', 'title': f'task {i}', 'minutes': minutes, 'floor': rng.choice([1, 2, 2, 3, 3]), 'kind': 'build',
+ 'difficulty': rng.choice(['low', 'medium', 'high']), 'spend': {'weekly': weekly}, 'deps': deps}
+ out_tasks.append(build)
+ if len(out_tasks) < tasks and rng.random() < 0.4:
+ out_tasks.append({'id': f't{i + 1}', 'title': f'review of task {i}', 'minutes': 20, 'floor': 3, 'kind': 'review',
+ 'difficulty': 'high', 'spend': {'weekly': 1}, 'deps': [build['id']], 'independent_of': [build['id']]})
+ out_machines, accounts = [], []
+ for j in range(machines):
+ engines = rng.choice([['claude', 'codex'], ['claude', 'codex'], ['claude'], ['codex']])
+ out_machines.append({'id': f'm{j}', 'name': f'machine {j}', 'slots': rng.choice([1, 2, 2, 3, 4]), 'engines': engines})
+ for engine in engines:
+ if rng.random() < 0.7:
+ accounts.append({'id': f'm{j}-{engine}', 'members': [[f'm{j}', engine]], 'budget': {'weekly': rng.choice([10, 20, 40, 60])}})
+ return {'tasks': out_tasks, 'machines': out_machines, 'models': MODELS[:models], 'accounts': accounts}
diff --git a/tools/scheduler/scheduler/compare.py b/tools/scheduler/scheduler/compare.py
new file mode 100644
index 000000000..c2bb973b9
--- /dev/null
+++ b/tools/scheduler/scheduler/compare.py
@@ -0,0 +1,58 @@
+"""The exact plan against today's route and against the picks the Swarm actually made, on one instance."""
+from typing import Dict, List, Optional, Tuple
+
+from .greedy import Assignment, evaluate, greedy
+from .instance import Instance, Option, duration, load
+from .solver import QUOTA_SCALE, Result, pareto, quota_use, solve
+
+
+def broken(instance: Instance, assignment: Assignment) -> List[str]:
+ """Where a fixed assignment breaks the floors, a review's other family or an account's budget."""
+ out = []
+ for t in instance.tasks:
+ model = instance.model(assignment[t.id][1])
+ if model.quality_for(t.kind) < t.floor:
+ out.append(f'{t.id}: quality {model.quality_for(t.kind)} below its floor {t.floor}')
+ for other in t.independent_of:
+ if instance.model(assignment[other][1]).family == model.family:
+ out.append(f'{t.id}: reviewed by the same family ({model.family}) as {other}')
+ for account in instance.accounts:
+ for window, left in account.budget.items():
+ used = sum(quota_use(instance, Option(t.id, m, k, duration(t, instance.model(k))), window)
+ for t in instance.tasks for m, k in [assignment[t.id]] if instance.account_of(m, instance.model(k)) == account)
+ if used > 0 and used > left * QUOTA_SCALE:
+ out.append(f'account {account.id}: {window} {used / QUOTA_SCALE:.1f}% used of {left:.1f}% left')
+ return out
+
+
+def _row(name: str, instance: Instance, result: Result) -> dict:
+ assignment = {p.task: (p.machine, p.model) for p in result.plan}
+ return {'plan': name, 'status': result.status, 'makespan': result.makespan, 'cost': result.cost,
+ 'seconds': round(result.seconds, 3), 'broken': broken(instance, assignment) if len(assignment) == len(instance.tasks) else []}
+
+
+def compare(night: dict, time_limit: float = 10.0, max_slots: Optional[int] = None) -> dict:
+ """`max_slots` caps every machine's slots, to see the same night on a busier Swarm."""
+ data = night['instance']
+ if max_slots is not None:
+ data = {**data, 'machines': [{**m, 'slots': min(m['slots'], max_slots)} for m in data['machines']]}
+ instance = load(data)
+ rows = [_row('optimal', instance, solve(instance, time_limit=time_limit)), _row('greedy', instance, greedy(instance))]
+ actual = night.get('actual') or {}
+ if all(t.id in actual for t in instance.tasks):
+ rows.append(_row('actual', instance, evaluate(instance, {k: tuple(v) for k, v in actual.items()})))
+ front = pareto(instance, time_limit=time_limit)
+ return {'rows': rows, 'pareto': {'complete': front.complete, 'seconds': round(front.seconds, 3),
+ 'points': [{'makespan': p.makespan, 'cost': p.cost} for p in front.points]}}
+
+
+def table(report: dict) -> str:
+ lines = ['| plan | status | finish (min) | cost | solve (s) | broken |', '| --- | --- | --- | --- | --- | --- |']
+ for r in report['rows']:
+ lines.append(f"| {r['plan']} | {r['status']} | {r['makespan']} | {r['cost']} | {r['seconds']} | {len(r['broken'])} |")
+ front = report['pareto']
+ lines += ['', f"Pareto set ({'complete' if front['complete'] else 'incomplete'}, {front['seconds']} s): "
+ + ', '.join(f"{p['makespan']} min at cost {p['cost']}" for p in front['points'])]
+ for r in report['rows']:
+ lines += [f"{r['plan']} breaks: {b}" for b in r['broken']]
+ return '\n'.join(lines)
diff --git a/tools/scheduler/scheduler/greedy.py b/tools/scheduler/scheduler/greedy.py
new file mode 100644
index 000000000..1c6b8c0e4
--- /dev/null
+++ b/tools/scheduler/scheduler/greedy.py
@@ -0,0 +1,224 @@
+"""Today's route as a baseline. Each task is routed when it becomes ready (its dependencies are done) and takes the
+first candidate of cli/src/superTabs/route.ts `choose`: candidates at the floor (or, with none, the best below it),
+only the strongest for a hard task, those whose quota fits before the unknown and the short, then `compare`'s order:
+effective cost, strength, a machine's own engine before a shared API, room on the tightest window, and title.
+Effective cost is `sizeUp`'s: a 5-hour window that resets before the task is over makes its unused part free, and a
+task that is not hard pays for taking more than a day's share of the weekly window. The quota is read at that moment:
+work that has run since the plan began has used it, open picks hold the rest of theirs, and a 5-hour window refills at
+its reset. Then the task starts as early as its machine's slots and its model's limit allow, which is how the Swarm
+starts work it has routed; the route itself does not look at slots.
+
+Left out from the route: owner rules and members (the converter applies the owner's machine rule to every plan, and
+every pick here is a new agent). A review leaves out the family its build was given, as the Lead asks the route for.
+"""
+import heapq
+import math
+from dataclasses import dataclass
+from typing import Dict, List, Optional, Tuple
+
+from .instance import Account, Instance, Option, Task, Window, duration, options
+from .solver import Placement, Result, task_cost
+
+Assignment = Dict[str, Tuple[str, str]]
+# Minutes between refills; the route's windows (route.ts WINDOWS).
+PERIOD = {'5-hour': 300, 'weekly': 7 * 1440}
+STATUSES = ('fits', 'unknown', 'short')
+
+
+def _ordered(instance: Instance) -> List[Task]:
+ """Instance order, with each task after the tasks it depends on."""
+ done, out = set(), []
+
+ def visit(t: Task) -> None:
+ if t.id in done:
+ return
+ done.add(t.id)
+ for dep in t.deps:
+ visit(instance.task(dep))
+ out.append(t)
+
+ for t in instance.tasks:
+ visit(t)
+ return out
+
+
+def _place(instance: Instance, plan: Dict[str, Placement], t: Task, machine_id: str, model_id: str, ready: int) -> Placement:
+ """The earliest start at or after `ready` with a free slot on the machine and room on the model."""
+ model = instance.model(model_id)
+ length = duration(t, model)
+ pool = instance.slot_pool(machine_id)
+ same_machine = [p for p in plan.values() if instance.slot_pool(p.machine) == pool]
+ same_model = [p for p in plan.values() if p.model == model_id]
+
+ def free(start: int) -> bool:
+ end = start + length
+ # Usage only rises at a start, so checking each start inside the window (and the window's own) is enough.
+ for group, limit in ((same_machine, instance.pool_slots(pool)), (same_model, model.concurrency)):
+ if limit is None:
+ continue
+ for s in [start] + [p.start for p in group if start < p.start < end]:
+ if sum(1 for p in group if p.start <= s < p.end) >= limit:
+ return False
+ return True
+
+ candidates = sorted({ready} | {p.end for p in plan.values() if p.end > ready})
+ start = next(s for s in candidates if free(s))
+ return Placement(task=t.id, machine=machine_id, model=model_id, start=start, end=start + length)
+
+
+def _result(instance: Instance, plan: Dict[str, Placement]) -> Result:
+ placements = sorted(plan.values(), key=lambda p: (p.start, p.task))
+ cost = sum(task_cost(instance, Option(p.task, p.machine, p.model, p.end - p.start)) for p in placements)
+ return Result(status='EVALUATED', makespan=max((p.end for p in placements), default=0), cost=cost, plan=placements)
+
+
+def evaluate(instance: Instance, assignment: Assignment) -> Result:
+ """Start each task of a fixed assignment as early as possible, in instance order."""
+ plan: Dict[str, Placement] = {}
+ for t in _ordered(instance):
+ ready = max((plan[d].end for d in t.deps), default=0)
+ plan[t.id] = _place(instance, plan, t, *assignment[t.id], ready)
+ return _result(instance, plan)
+
+
+@dataclass(frozen=True)
+class Decision:
+ """A routed task: when it was routed, and when it runs."""
+ task: Task
+ machine: str
+ model: str
+ at: int
+ start: int
+ end: int
+
+
+@dataclass(frozen=True)
+class Measured:
+ name: str
+ usable: float
+ needed: float
+ resets_in: Optional[int]
+
+ @property
+ def ratio(self) -> float:
+ return self.usable / self.needed if self.needed else math.inf
+
+
+@dataclass(frozen=True)
+class Sized:
+ status: str
+ coverage: Optional[float]
+ effective_cost: float
+ tight: Optional[float]
+
+
+def _spend(instance: Instance, task: Task, model_id: str, window: str) -> float:
+ """route.ts: the size table's spend is for policy cost 2 and grows with the model's cost."""
+ return task.spend.get(window, 0.0) * instance.model(model_id).cost / 2
+
+
+def _reading(instance: Instance, window: Window, mine: List[Decision], now: int) -> Tuple[float, Optional[int]]:
+ """What the window would read at `now`: its reading at the start, or full again after a reset, less what work on the
+ account has used since; and the minutes to its next reset."""
+ left, since, reset = window.left, 0, window.resets_in
+ period = PERIOD.get(window.name)
+ if reset is not None and period and now >= reset:
+ passed = (now - reset) // period + 1
+ since, reset, left = reset + (passed - 1) * period, reset + passed * period, 100.0
+ used = 0.0
+ for d in mine:
+ overlap = max(0, min(d.end, now) - max(d.start, since))
+ if overlap:
+ used += _spend(instance, d.task, d.model, window.name) * overlap / (d.end - d.start)
+ return left - used, None if reset is None else max(1, reset - now)
+
+
+def size_up(instance: Instance, task: Task, option: Option, now: int, decisions: List[Decision]) -> Sized:
+ """route.ts `sizeUp`: how the candidate's account would carry the task, and its effective cost."""
+ model = instance.model(option.model)
+ if not model.subscription:
+ return Sized('fits', None, float(model.cost), None)
+ account: Optional[Account] = instance.account_of(option.machine, model)
+ if account is None:
+ return Sized('unknown', None, float(model.cost), None)
+ mine = [d for d in decisions if instance.account_of(d.machine, instance.model(d.model)) == account]
+ run = task.minutes
+ measured = []
+ for name in PERIOD:
+ window = next((w for w in account.windows if w.name == name), None)
+ if window is None:
+ continue
+ left, resets_in = _reading(instance, window, mine, now)
+ # Picks still at work hold what they were expected to spend, less the part of their run time already over.
+ committed = sum(_spend(instance, d.task, d.model, name) * max(0.0, 1 - (now - d.at) / d.task.minutes) for d in mine)
+ spend = _spend(instance, task, option.model, name)
+ # A window that refills mid-task carries only the part of the task before its reset.
+ needed = spend * resets_in / run if resets_in is not None and resets_in < run else spend
+ measured.append(Measured(name, left - account.reserve - committed, needed, resets_in))
+ complete = len(measured) == len(PERIOD) or (model.engine == 'codex' and [m.name for m in measured] == ['weekly'])
+ status = 'short' if any(m.usable < m.needed for m in measured) else 'fits' if complete else 'unknown'
+ tight = min(measured, key=lambda m: m.ratio) if measured else None
+ five = next((m for m in measured if m.name == '5-hour'), None)
+ week = next((m for m in measured if m.name == 'weekly'), None)
+ expiring = 0.0
+ if five and five.resets_in is not None and five.resets_in <= run + 60 and five.needed:
+ expiring = min(1.0, max(0.0, five.usable) / five.needed)
+ effective = model.cost * (1 - expiring)
+ if week:
+ day_budget = week.usable / max(1.0, (week.resets_in or 0) / 1440)
+ if task.difficulty != 'high' and day_budget > 0 and week.needed > day_budget:
+ effective += model.cost * week.needed / day_budget
+ coverage = None if tight is None else round(tight.ratio, 2)
+ return Sized(status, coverage, round(effective, 2), None if tight is None else tight.usable)
+
+
+def route_pick(instance: Instance, task: Task, now: int, decisions: List[Decision], assignment: Assignment) -> Optional[Option]:
+ """route.ts `choose` and `decide` for one task routed at `now`."""
+ taken = {instance.model(assignment[other][1]).family for other in task.independent_of if other in assignment}
+ viable = [o for o in options(instance, task, floor=False) if instance.model(o.model).family not in taken]
+ meeting = [o for o in viable if instance.model(o.model).quality_for(task.kind) >= task.floor]
+ opts = meeting or viable
+ if not opts:
+ return None
+ if task.difficulty == 'high':
+ top = max(instance.model(o.model).quality_for(task.kind) for o in opts)
+ opts = [o for o in opts if instance.model(o.model).quality_for(task.kind) == top]
+ sized = {o: size_up(instance, task, o, now, decisions) for o in opts}
+ status = next(s for s in STATUSES if any(z.status == s for z in sized.values()))
+ shown = [o for o in opts if sized[o].status == status]
+
+ def order(o: Option):
+ model, z = instance.model(o.model), sized[o]
+ first = (-(z.coverage or 0.0),) if status == 'short' else ()
+ return first + (z.effective_cost, -model.quality_for(task.kind), 1 if model.remote else 0,
+ -(z.tight if z.tight is not None else -math.inf), f'{model.label} · {instance.machine(o.machine).name}')
+
+ return min(shown, key=order)
+
+
+def greedy(instance: Instance) -> Result:
+ waiting = {t.id: len(t.deps) for t in instance.tasks}
+ index = {t.id: i for i, t in enumerate(instance.tasks)}
+ dependents: Dict[str, List[str]] = {t.id: [] for t in instance.tasks}
+ for t in instance.tasks:
+ for dep in t.deps:
+ dependents[dep].append(t.id)
+ ready = [(0, index[t.id], t.id) for t in instance.tasks if not t.deps]
+ heapq.heapify(ready)
+ plan: Dict[str, Placement] = {}
+ decisions: List[Decision] = []
+ assignment: Assignment = {}
+ while ready:
+ now, _, tid = heapq.heappop(ready)
+ t = instance.task(tid)
+ pick = route_pick(instance, t, now, decisions, assignment)
+ if pick is None:
+ return Result(status='INFEASIBLE', reason=f'no machine and model can run: {t.id}')
+ placed = _place(instance, plan, t, pick.machine, pick.model, now)
+ plan[tid], assignment[tid] = placed, (pick.machine, pick.model)
+ decisions.append(Decision(t, pick.machine, pick.model, now, placed.start, placed.end))
+ for nxt in dependents[tid]:
+ waiting[nxt] -= 1
+ if not waiting[nxt]:
+ heapq.heappush(ready, (max(plan[d].end for d in instance.task(nxt).deps), index[nxt], nxt))
+ return _result(instance, plan)
diff --git a/tools/scheduler/scheduler/instance.py b/tools/scheduler/scheduler/instance.py
new file mode 100644
index 000000000..a918fd7e6
--- /dev/null
+++ b/tools/scheduler/scheduler/instance.py
@@ -0,0 +1,245 @@
+"""A scheduling instance: the tasks to place, the machines that run them and the models they may use.
+
+Times are whole minutes. A model's quality is given per task kind, with a `default` for every other kind; a task may use a
+model only when that quality meets the task's floor. `spend` is what a task takes from each usage window of its account
+at policy cost 2 (the routing policy's table), scaled by the model's cost like `sizeUp` in cli/src/superTabs/route.ts.
+"""
+import math
+from dataclasses import dataclass, field
+from typing import Dict, List, Optional, Tuple
+
+
+class InstanceError(ValueError):
+ pass
+
+
+@dataclass(frozen=True)
+class Task:
+ id: str
+ title: str
+ minutes: int
+ floor: int = 1
+ kind: str = 'default'
+ deps: Tuple[str, ...] = ()
+ spend: Dict[str, float] = field(default_factory=dict)
+ difficulty: str = 'medium'
+ # Tasks whose model family this one must not share: a review is done by another family than the work it reviews.
+ independent_of: Tuple[str, ...] = ()
+ # Families the task may not use at all: a review whose build has already run is done by another family.
+ avoid_families: Tuple[str, ...] = ()
+ # The machines and models the owner's rules leave for the task's project; None is every one.
+ machines: Optional[Tuple[str, ...]] = None
+ models: Optional[Tuple[str, ...]] = None
+
+
+@dataclass(frozen=True)
+class Machine:
+ id: str
+ name: str
+ slots: int
+ engines: Tuple[str, ...]
+ # The machine whose slots this one shares: a Mac's Harness Team account runs on the Mac (One machine). None is its own.
+ pool: Optional[str] = None
+
+
+@dataclass(frozen=True)
+class Model:
+ id: str
+ engine: str
+ cost: int
+ quality: Dict[str, int]
+ speed: float = 1.0
+ # How many tasks may use the model at once across the Swarm: a local model serves one Builder, a shared API four.
+ concurrency: Optional[int] = None
+ # Machines that can reach it; None is every machine with its engine.
+ machines: Optional[Tuple[str, ...]] = None
+ # Whether it spends the machine's engine subscription (an API key or a model on the grid does not).
+ subscription: bool = True
+ # Models of one family think alike (Opus, Sonnet and Haiku are all Claude); None takes the engine's name.
+ family: Optional[str] = None
+ # A model reached through a member's API or another owner's grid; the route ranks it after a machine's own engine.
+ remote: bool = False
+ # The words the route's candidate title gives it (`Claude opus high`), its last tie-break; None takes the id.
+ label: Optional[str] = None
+
+ def __post_init__(self):
+ if self.family is None:
+ object.__setattr__(self, 'family', self.engine)
+ if self.label is None:
+ object.__setattr__(self, 'label', self.id)
+
+ def quality_for(self, kind: str) -> int:
+ return self.quality.get(kind, self.quality['default'])
+
+
+@dataclass(frozen=True)
+class Window:
+ """A usage window as read when the plan starts: percent left, and minutes until it refills (None: not known)."""
+ name: str
+ left: float
+ resets_in: Optional[int] = None
+
+
+@dataclass(frozen=True)
+class Account:
+ """One subscription. `budget` is what the exact plan may spend of each window, in percent; `windows` and `reserve`
+ are the readings the route ranks candidates by (greedy.py)."""
+ id: str
+ members: Tuple[Tuple[str, str], ...]
+ budget: Dict[str, float]
+ windows: Tuple[Window, ...] = ()
+ reserve: float = 0.0
+
+
+@dataclass(frozen=True)
+class Instance:
+ tasks: List[Task]
+ machines: List[Machine]
+ models: List[Model]
+ accounts: List[Account] = field(default_factory=list)
+
+ def task(self, id: str) -> Task:
+ return next(t for t in self.tasks if t.id == id)
+
+ def machine(self, id: str) -> Machine:
+ return next(m for m in self.machines if m.id == id)
+
+ def slot_pool(self, id: str) -> str:
+ return self.machine(id).pool or id
+
+ def pool_slots(self, pool: str) -> int:
+ """Free slots of a machine and the accounts on it: each reports the slots left on the one machine, so the fewest hold."""
+ return min(m.slots for m in self.machines if (m.pool or m.id) == pool)
+
+ def model(self, id: str) -> Model:
+ return next(m for m in self.models if m.id == id)
+
+ def account_of(self, machine: str, model: Model) -> Optional[Account]:
+ if not model.subscription:
+ return None
+ return next((a for a in self.accounts if (machine, model.engine) in a.members), None)
+
+
+@dataclass(frozen=True)
+class Option:
+ """One way to run a task: on this machine, with this model, taking this long."""
+ task: str
+ machine: str
+ model: str
+ minutes: int
+
+
+def _unique(kind: str, items) -> None:
+ seen = set()
+ for item in items:
+ if item.id in seen:
+ raise InstanceError(f'duplicate {kind} {item.id}')
+ seen.add(item.id)
+
+
+def _check_acyclic(tasks: List[Task]) -> None:
+ deps = {t.id: t.deps for t in tasks}
+ state: Dict[str, int] = {}
+
+ def visit(id: str, path: List[str]) -> None:
+ if state.get(id) == 2:
+ return
+ if state.get(id) == 1:
+ raise InstanceError(f'dependency cycle: {" -> ".join(path + [id])}')
+ state[id] = 1
+ for dep in deps[id]:
+ visit(dep, path + [id])
+ state[id] = 2
+
+ for t in tasks:
+ visit(t.id, [])
+
+
+def _account(a: dict) -> Account:
+ """Windows default to the budget, never refilling; the budget defaults to the weekly window less the reserve, as only
+ the weekly window holds over a night (a 5-hour window refills)."""
+ reserve = float(a.get('reserve', 0))
+ windows = tuple(Window(name=str(w['name']), left=float(w['left']), resets_in=None if w.get('resets_in') is None else int(w['resets_in']))
+ for w in a.get('windows', ()))
+ if 'budget' in a:
+ budget = {str(k): float(v) for k, v in a['budget'].items()}
+ else:
+ budget = {w.name: w.left - reserve for w in windows if w.name == 'weekly'}
+ if not windows:
+ windows = tuple(Window(name=k, left=v) for k, v in budget.items())
+ return Account(id=str(a['id']), members=tuple((str(x[0]), str(x[1])) for x in a['members']), budget=budget, windows=windows, reserve=reserve)
+
+
+def load(data: dict) -> Instance:
+ tasks = [Task(id=str(t['id']), title=str(t.get('title', t['id'])), minutes=int(t['minutes']), floor=int(t.get('floor', 1)),
+ kind=str(t.get('kind') or 'default'), deps=tuple(str(d) for d in t.get('deps', ())),
+ spend={str(k): float(v) for k, v in t.get('spend', {}).items()}, difficulty=str(t.get('difficulty', 'medium')),
+ independent_of=tuple(str(d) for d in t.get('independent_of', ())),
+ avoid_families=tuple(str(f) for f in t.get('avoid_families', ())),
+ machines=None if t.get('machines') is None else tuple(str(m) for m in t['machines']),
+ models=None if t.get('models') is None else tuple(str(m) for m in t['models']))
+ for t in data['tasks']]
+ machines = [Machine(id=str(m['id']), name=str(m.get('name', m['id'])), slots=int(m['slots']), engines=tuple(m['engines']),
+ pool=None if m.get('pool') is None else str(m['pool']))
+ for m in data['machines']]
+ models = [Model(id=str(m['id']), engine=str(m['engine']), cost=int(m['cost']), quality={str(k): int(v) for k, v in m['quality'].items()},
+ speed=float(m.get('speed', 1.0)), concurrency=m.get('concurrency'),
+ machines=tuple(m['machines']) if m.get('machines') is not None else None, subscription=bool(m.get('subscription', True)),
+ family=m.get('family'), label=m.get('label'),
+ remote=bool(m.get('remote', False)))
+ for m in data['models']]
+ accounts = [_account(a) for a in data.get('accounts', ())]
+ _unique('task', tasks)
+ _unique('machine', machines)
+ _unique('model', models)
+ _unique('account', accounts)
+ ids = {t.id for t in tasks}
+ for t in tasks:
+ if t.minutes <= 0:
+ raise InstanceError(f'{t.id} needs a positive estimate')
+ for dep in t.deps:
+ if dep not in ids:
+ raise InstanceError(f'{t.id} depends on unknown task {dep}')
+ for other in t.independent_of:
+ if other not in ids:
+ raise InstanceError(f'{t.id} must differ from unknown task {other}')
+ _check_acyclic(tasks)
+ machine_ids = {m.id for m in machines}
+ model_ids = {m.id for m in models}
+ for m in machines:
+ if m.pool is not None and m.pool not in machine_ids:
+ raise InstanceError(f'{m.id} shares slots with unknown machine {m.pool}')
+ for t in tasks:
+ for mid in t.machines or ():
+ if mid not in machine_ids:
+ raise InstanceError(f'{t.id} names unknown machine {mid}')
+ for kid in t.models or ():
+ if kid not in model_ids:
+ raise InstanceError(f'{t.id} names unknown model {kid}')
+ for m in models:
+ if 'default' not in m.quality:
+ raise InstanceError(f'{m.id} has no default quality')
+ if m.speed <= 0:
+ raise InstanceError(f'{m.id} needs a positive speed')
+ for mid in m.machines or ():
+ if mid not in machine_ids:
+ raise InstanceError(f'model {m.id} names unknown machine {mid}')
+ for a in accounts:
+ for mid, _ in a.members:
+ if mid not in machine_ids:
+ raise InstanceError(f'account {a.id} names unknown machine {mid}')
+ return Instance(tasks=tasks, machines=machines, models=models, accounts=accounts)
+
+
+def duration(task: Task, model: Model) -> int:
+ return math.ceil(task.minutes / model.speed)
+
+
+def options(instance: Instance, task: Task, floor: bool = True) -> List[Option]:
+ """Every machine and model that may run the task: the engine is on the machine and, unless `floor` is false, the
+ quality meets the floor."""
+ return [Option(task=task.id, machine=m.id, model=k.id, minutes=duration(task, k))
+ for m in instance.machines for k in instance.models
+ if k.engine in m.engines and (k.machines is None or m.id in k.machines) and k.family not in task.avoid_families
+ and (task.machines is None or m.id in task.machines) and (task.models is None or k.id in task.models)
+ and (not floor or k.quality_for(task.kind) >= task.floor)]
diff --git a/tools/scheduler/scheduler/plan.py b/tools/scheduler/scheduler/plan.py
new file mode 100644
index 000000000..218a5f535
--- /dev/null
+++ b/tools/scheduler/scheduler/plan.py
@@ -0,0 +1,17 @@
+"""The plan for open work, as `harness super-tab plan` reads it: each task's machine, model, start order and expected
+finish, with finish time and cost, and what today's route would do with the same work (cli/src/superTabs/planCommand.ts)."""
+from .greedy import greedy
+from .instance import load
+from .solver import solve
+
+
+def plan(data: dict, time_limit: float = 10.0) -> dict:
+ instance = load(data)
+ exact = solve(instance, time_limit=time_limit)
+ rows = [{'task': p.task, 'machine': p.machine, 'model': p.model, 'start': p.start, 'end': p.end, 'order': i + 1}
+ for i, p in enumerate(exact.plan)]
+ route = greedy(instance)
+ return {'status': exact.status, 'reason': exact.reason, 'makespan': exact.makespan, 'cost': exact.cost, 'gap': exact.gap,
+ 'seconds': round(exact.seconds, 3), 'plan': rows,
+ 'route': {'status': route.status, 'makespan': route.makespan, 'cost': route.cost,
+ 'plan': [{'task': p.task, 'machine': p.machine, 'model': p.model} for p in route.plan]}}
diff --git a/tools/scheduler/scheduler/redact.py b/tools/scheduler/scheduler/redact.py
new file mode 100644
index 000000000..d5b051ddc
--- /dev/null
+++ b/tools/scheduler/scheduler/redact.py
@@ -0,0 +1,75 @@
+"""Makes a Swarm status snapshot and a route log safe to commit beside the converter.
+
+Only the fields the converter reads are kept (ids, machines, quotas, models, assignments, rules, the route requests), so
+emails, briefs, home folders and anything else in the snapshot are dropped by default. People's names, taken from their
+emails, are replaced wherever text is kept: machine names, titles, rule texts and route reasons.
+"""
+import json
+import re
+from typing import Iterable, List, Optional, Tuple
+
+PERSON = '[person]'
+EMAIL = re.compile(r'[\w.+-]+@[\w-]+\.[\w.-]+')
+CREDENTIAL_URL = re.compile(r'\w+://[^/\s"@]+@')
+
+
+def _pick(value: Optional[dict], keys: Iterable[str]) -> dict:
+ return {k: value[k] for k in keys if value and k in value}
+
+
+def _names(people: List[dict]) -> List[str]:
+ """First names from people's emails: `ken15@…` gives `ken`, `phamngochuy.1989@…` gives `phamngochuy`."""
+ out = set()
+ for p in people:
+ local = str(p.get('email', '')).split('@')[0]
+ out.update(w for w in re.split(r'[^a-zA-Z]+', local) if len(w) >= 3)
+ return sorted(out, key=len, reverse=True)
+
+
+def _scrub(text: Optional[str], names: List[str]) -> Optional[str]:
+ if text is None:
+ return None
+ for name in names:
+ # Whole words only, with a possessive kept: "Diego's Mac" -> "[person]'s Mac"; "Deepseek" stays.
+ text = re.sub(rf"\b{re.escape(name)}(?=(?:'s|s)?\b)", PERSON, text, flags=re.IGNORECASE)
+ return text
+
+
+def redact(status: dict, route_log: List[dict]) -> Tuple[dict, List[dict]]:
+ state = status['value']['state']
+ names = _names(state.get('people') or [])
+ machines = [{**_pick(m, ('machineId', 'maxAgents', 'engines')), 'name': _scrub(m.get('name'), names),
+ 'observation': {
+ **_pick(m.get('observation'), ('receivedAt',)),
+ 'quotas': [{**_pick(q, ('engine', 'known')), 'windows': [_pick(w, ('name', 'usedPercent', 'resetsAt')) for w in q.get('windows', [])]}
+ for q in (m.get('observation') or {}).get('quotas', [])],
+ 'localModels': [{**_pick(x, ('grid', 'model', 'kind')), 'name': _scrub(x.get('name'), names)}
+ for x in (m.get('observation') or {}).get('localModels', [])]}}
+ for m in state.get('machines', [])]
+ conversations = [{**_pick(c, ('id', 'projectId')), 'title': _scrub(c.get('title'), names),
+ 'assignment': None if not c.get('assignment') else {
+ **_pick(c['assignment'], ('id', 'agentId', 'status')),
+ 'configuration': _pick(c['assignment'].get('configuration'), ('engine', 'model', 'effort')),
+ 'execution': _pick(c['assignment'].get('execution'), ('machineId',))}}
+ for c in state.get('conversations', [])]
+ agents = [{**_pick(a, ('id', 'machineId', 'projectId', 'name')), 'configuration': _pick(a.get('configuration'), ('engine', 'model', 'effort'))}
+ for a in state.get('agents', [])]
+ rules = [{**_pick(r, ('id', 'projectId', 'rule', 'createdAt')), 'text': _scrub(r.get('text'), names)} for r in state.get('rules', [])]
+ people = [_pick(p, ('id', 'role')) for p in state.get('people', [])]
+ out_status = {'value': {'state': {'people': people, 'agents': agents, 'machines': machines, 'conversations': conversations, 'rules': rules}}}
+ out_log = [{**_pick(r, ('group', 'at')), 'request': {**r['request'], 'why': _scrub(r['request'].get('why'), names)}} for r in route_log]
+ text = json.dumps([out_status, out_log])
+ if EMAIL.search(text) or CREDENTIAL_URL.search(text):
+ raise ValueError('an email or a URL with credentials is left after redaction')
+ return out_status, out_log
+
+
+def main(argv: List[str]) -> int:
+ status_in, log_in, status_out, log_out = argv
+ with open(status_in) as s, open(log_in) as l:
+ status, log = redact(json.load(s), json.load(l))
+ for path, value in ((status_out, status), (log_out, log)):
+ with open(path, 'w') as f:
+ json.dump(value, f, indent=1, ensure_ascii=False)
+ f.write('\n')
+ return 0
diff --git a/tools/scheduler/scheduler/solver.py b/tools/scheduler/scheduler/solver.py
new file mode 100644
index 000000000..10c4b7b24
--- /dev/null
+++ b/tools/scheduler/scheduler/solver.py
@@ -0,0 +1,208 @@
+"""The exact plan: CP-SAT places every task on one machine and model, then minimises finish time and, at that finish time,
+cost. docs/plans/2026-10-27-swarm-scheduler.md has the formulation.
+
+Cost is the model's policy cost times the task's estimate in minutes, so a large task on Opus costs 3 x 180.
+"""
+import time
+from dataclasses import dataclass, field
+from typing import Dict, List, Optional, Tuple
+
+from ortools.sat.python import cp_model
+
+from .instance import Instance, Option, options
+
+STATUS = {cp_model.OPTIMAL: 'OPTIMAL', cp_model.FEASIBLE: 'FEASIBLE', cp_model.INFEASIBLE: 'INFEASIBLE',
+ cp_model.MODEL_INVALID: 'MODEL_INVALID', cp_model.UNKNOWN: 'UNKNOWN'}
+# Quota is in percent with two decimals, so constraints stay integral.
+QUOTA_SCALE = 100
+
+
+@dataclass(frozen=True)
+class Placement:
+ task: str
+ machine: str
+ model: str
+ start: int
+ end: int
+
+
+@dataclass
+class Result:
+ status: str
+ reason: str = ''
+ makespan: Optional[int] = None
+ cost: Optional[int] = None
+ makespan_bound: Optional[int] = None
+ cost_bound: Optional[int] = None
+ gap: Optional[float] = None
+ seconds: float = 0.0
+ plan: List[Placement] = field(default_factory=list)
+
+
+def task_cost(instance: Instance, option: Option) -> int:
+ return instance.model(option.model).cost * instance.task(option.task).minutes
+
+
+def quota_use(instance: Instance, option: Option, window: str) -> int:
+ """What the option takes from its account's window, scaled: spend is given at cost 2 and grows with the model's cost."""
+ spend = instance.task(option.task).spend.get(window, 0.0)
+ return round(spend * instance.model(option.model).cost / 2 * QUOTA_SCALE)
+
+
+class Formulation:
+ """The constraints every plan obeys; objectives and caps are added by the caller."""
+
+ def __init__(self, instance: Instance):
+ self.instance = instance
+ self.model = cp_model.CpModel()
+ self.options: Dict[str, List[Option]] = {t.id: options(instance, t) for t in instance.tasks}
+ self.missing = [t for t, opts in self.options.items() if not opts]
+ if self.missing:
+ return
+ m = self.model
+ horizon = sum(max(o.minutes for o in opts) for opts in self.options.values())
+ self.start = {t.id: m.NewIntVar(0, horizon, f'start[{t.id}]') for t in instance.tasks}
+ self.end = {t.id: m.NewIntVar(0, horizon, f'end[{t.id}]') for t in instance.tasks}
+ self.pick: Dict[Option, cp_model.IntVar] = {}
+ by_machine: Dict[str, list] = {}
+ by_model: Dict[str, list] = {}
+ for t in instance.tasks:
+ picks = []
+ for o in self.options[t.id]:
+ x = m.NewBoolVar(f'x[{t.id},{o.machine},{o.model}]')
+ interval = m.NewOptionalFixedSizeIntervalVar(self.start[t.id], o.minutes, x, f'run[{t.id},{o.machine},{o.model}]')
+ m.Add(self.end[t.id] == self.start[t.id] + o.minutes).OnlyEnforceIf(x)
+ self.pick[o] = x
+ picks.append(x)
+ by_machine.setdefault(instance.slot_pool(o.machine), []).append(interval)
+ by_model.setdefault(o.model, []).append(interval)
+ m.AddExactlyOne(picks)
+ for dep in t.deps:
+ m.Add(self.start[t.id] >= self.end[dep])
+ for t in instance.tasks:
+ for other in t.independent_of:
+ for family in {k.family for k in instance.models}:
+ same = [x for o, x in self.pick.items() if o.task in (t.id, other) and instance.model(o.model).family == family]
+ if same:
+ m.Add(sum(same) <= 1)
+ for pool, intervals in by_machine.items():
+ slots = instance.pool_slots(pool)
+ if slots < len(intervals):
+ m.AddCumulative(intervals, [1] * len(intervals), slots)
+ for kid, intervals in by_model.items():
+ limit = instance.model(kid).concurrency
+ if limit is not None and limit < len(intervals):
+ m.AddCumulative(intervals, [1] * len(intervals), limit)
+ for account in instance.accounts:
+ for window, left in account.budget.items():
+ terms = [(quota_use(instance, o, window), x) for o, x in self.pick.items()
+ if instance.account_of(o.machine, instance.model(o.model)) == account]
+ terms = [(c, x) for c, x in terms if c > 0]
+ if terms:
+ m.Add(sum(c * x for c, x in terms) <= max(0, int(left * QUOTA_SCALE)))
+ self.makespan = m.NewIntVar(0, horizon, 'makespan')
+ m.AddMaxEquality(self.makespan, list(self.end.values()))
+ self.cost = sum(task_cost(instance, o) * x for o, x in self.pick.items())
+
+ def plan(self, solver: cp_model.CpSolver) -> List[Placement]:
+ out = []
+ for o, x in self.pick.items():
+ if solver.Value(x):
+ out.append(Placement(task=o.task, machine=o.machine, model=o.model, start=solver.Value(self.start[o.task]),
+ end=solver.Value(self.end[o.task])))
+ return sorted(out, key=lambda p: (p.start, p.task))
+
+ def hint(self, plan: List[Placement]) -> None:
+ chosen = {(p.task, p.machine, p.model): p for p in plan}
+ self.model.ClearHints()
+ for o, x in self.pick.items():
+ self.model.AddHint(x, (o.task, o.machine, o.model) in chosen)
+ for p in plan:
+ self.model.AddHint(self.start[p.task], p.start)
+
+
+def _solver(seconds: float, workers: int) -> cp_model.CpSolver:
+ solver = cp_model.CpSolver()
+ solver.parameters.max_time_in_seconds = max(0.05, seconds)
+ solver.parameters.num_search_workers = workers
+ solver.parameters.random_seed = 1
+ return solver
+
+
+def _gap(value: int, bound: int) -> float:
+ return 0.0 if value == bound else (value - bound) / max(1, abs(value))
+
+
+def solve(instance: Instance, time_limit: float = 10.0, workers: int = 8, makespan_cap: Optional[int] = None,
+ cost_cap: Optional[int] = None) -> Result:
+ """Least finish time, then least cost at that finish time. Both phases share `time_limit`. `makespan_cap` and
+ `cost_cap` bound the plan (for the Pareto set)."""
+ began = time.monotonic()
+ f = Formulation(instance)
+ if f.missing:
+ return Result(status='INFEASIBLE', reason=f'no machine and model meet the floor of: {", ".join(f.missing)}')
+ if makespan_cap is not None:
+ f.model.Add(f.makespan <= makespan_cap)
+ if cost_cap is not None:
+ f.model.Add(f.cost <= cost_cap)
+
+ f.model.Minimize(f.makespan)
+ first = _solver(time_limit, workers)
+ status = first.Solve(f.model)
+ if status not in (cp_model.OPTIMAL, cp_model.FEASIBLE):
+ reason = 'no plan meets the quota, slot and dependency limits' if status == cp_model.INFEASIBLE else 'no plan found within the time limit'
+ return Result(status=STATUS[status], reason=reason, seconds=time.monotonic() - began)
+ makespan = int(first.ObjectiveValue())
+ makespan_bound = int(first.BestObjectiveBound())
+ plan = f.plan(first)
+
+ # Second phase: hold the finish time found, minimise cost.
+ f.model.Add(f.makespan <= makespan)
+ f.hint(plan)
+ f.model.Minimize(f.cost)
+ second = _solver(time_limit - (time.monotonic() - began), workers)
+ status2 = second.Solve(f.model)
+ if status2 in (cp_model.OPTIMAL, cp_model.FEASIBLE):
+ plan = f.plan(second)
+ cost = int(second.ObjectiveValue())
+ cost_bound = int(second.BestObjectiveBound())
+ else:
+ # Out of time before the second phase found anything: the first phase's plan stands, with no cost bound.
+ cost = sum(task_cost(instance, Option(p.task, p.machine, p.model, p.end - p.start)) for p in plan)
+ cost_bound = 0
+ proven = status == cp_model.OPTIMAL and status2 == cp_model.OPTIMAL
+ return Result(status='OPTIMAL' if proven else 'FEASIBLE', makespan=makespan, cost=cost, makespan_bound=makespan_bound,
+ cost_bound=cost_bound, gap=max(_gap(makespan, makespan_bound), _gap(cost, cost_bound)),
+ seconds=time.monotonic() - began, plan=plan)
+
+
+@dataclass
+class Front:
+ points: List[Result]
+ complete: bool
+ seconds: float
+
+
+def pareto(instance: Instance, time_limit: float = 10.0, workers: int = 8) -> Front:
+ """Finish time against cost, fastest first. Each point is the fastest plan cheaper than the one before, at its least
+ cost, so every point found optimal is on the front; the walk ends when no cheaper plan exists. `complete` is false when
+ time ran out or a point was not proven optimal."""
+ began = time.monotonic()
+ points: List[Result] = []
+ cap: Optional[int] = None
+ complete = True
+ while True:
+ left = time_limit - (time.monotonic() - began)
+ if left <= 0:
+ complete = False
+ break
+ result = solve(instance, time_limit=left, workers=workers, cost_cap=cap)
+ if result.status == 'INFEASIBLE':
+ break
+ if result.status not in ('OPTIMAL', 'FEASIBLE'):
+ complete = False
+ break
+ complete = complete and result.status == 'OPTIMAL'
+ points.append(result)
+ cap = result.cost - 1
+ return Front(points=points, complete=complete, seconds=time.monotonic() - began)
diff --git a/tools/scheduler/scheduler/swarm.py b/tools/scheduler/scheduler/swarm.py
new file mode 100644
index 000000000..388562771
--- /dev/null
+++ b/tools/scheduler/scheduler/swarm.py
@@ -0,0 +1,224 @@
+"""Turns a Swarm status snapshot and the Lead's route log into an instance, plus the picks the Swarm actually made.
+
+What the snapshot does not hold comes from a config file kept beside the data (data/2026-10-26-night.json): the routing
+policy, which route request belongs to a group the log names only by a variable, estimates for groups with no request,
+dependencies, and groups a person pinned to one machine and model. Everything not read straight from the snapshot or
+the log is listed in `estimates`.
+"""
+import json
+from datetime import datetime
+from typing import Dict, List, Optional, Tuple
+
+# The owner's table in cli/src/superTabs/route.ts SIZES: run time, and spend per window at policy cost 2.
+SIZES = {'small': (20, {'5-hour': 10, 'weekly': 1}), 'medium': (60, {'5-hour': 30, 'weekly': 4}),
+ 'large': (180, {'5-hour': 50, 'weekly': 8})}
+ENGINES = ('claude', 'codex')
+ENGINE_WORD = {'claude': 'Claude', 'codex': 'Codex'}
+KIND_WORD = {'local': 'local', 'api': 'API', 'shared': 'shared'}
+# A model a member shares as an API answers four requests at once; a local engine one (route.ts API_BUILDERS).
+GRID_CONCURRENCY = {'api': 4, 'local': 1, 'shared': 1}
+
+
+class ConvertError(ValueError):
+ pass
+
+
+def model_id(engine: str, model: str) -> str:
+ return f'{engine}-{model}'
+
+
+def _models(policy: dict, machines: List[dict]) -> Tuple[List[dict], Dict[str, str]]:
+ """The policy's enabled rows, one per engine and model, and each model the grid serves. Returns the rows and a map
+ from a grid model's name to its row id."""
+ rows, seen = [], set()
+ for m in policy['models']:
+ key = model_id(m['engine'], m['model'])
+ if m['enabled'] and m['engine'] in ENGINES and key not in seen:
+ seen.add(key)
+ rows.append({'id': key, 'engine': m['engine'], 'cost': m['cost'], 'quality': {'default': m['quality']},
+ 'label': f"{ENGINE_WORD[m['engine']]} {m['model']} {m['effort']}"})
+ grid: Dict[str, str] = {}
+ local = policy.get('localModels') or {'quality': 1, 'enabled': True}
+ if local['enabled']:
+ for machine in machines:
+ for served in (machine.get('observation') or {}).get('localModels', []):
+ key = f"grid-{served['model']}"
+ if served['model'] not in grid:
+ grid[served['model']] = key
+ # A grid model is driven by a Claude Code Builder on any machine, through the grid relay.
+ kind = served.get('kind', 'local')
+ rows.append({'id': key, 'engine': 'claude', 'cost': 1, 'quality': {'default': local['quality']},
+ 'concurrency': GRID_CONCURRENCY.get(kind, 1), 'subscription': False, 'family': served['model'],
+ 'remote': kind in ('api', 'shared'),
+ 'label': f"Claude on {served.get('name') or served['model']} ({KIND_WORD.get(kind, 'local')})"})
+ return rows, grid
+
+
+def reset_ms(value) -> Optional[int]:
+ """route.ts `resetMs`: Claude sends ISO strings, Codex epoch seconds; anything above 1e10 is already milliseconds."""
+ if isinstance(value, (int, float)):
+ return int(value if value > 1e10 else value * 1000)
+ if isinstance(value, str):
+ try:
+ return int(datetime.fromisoformat(value.replace('Z', '+00:00')).timestamp() * 1000)
+ except ValueError:
+ return None
+ return None
+
+
+def snapshot_ms(machines: List[dict]) -> int:
+ """When the snapshot was read: its latest machine observation."""
+ return max(int((m.get('observation') or {}).get('receivedAt') or 0) for m in machines)
+
+
+def _windows(quota: dict, now: int) -> List[dict]:
+ """The 5-hour and weekly windows as read at `now`, with minutes to their reset; one whose reset has passed has refilled."""
+ out = []
+ for name in ('5-hour', 'weekly'):
+ w = next((w for w in quota['windows'] if w.get('name') == name), None)
+ if w is None:
+ continue
+ reset = reset_ms(w.get('resetsAt'))
+ if reset is not None and reset <= now:
+ out.append({'name': name, 'left': 100.0, 'resets_in': None})
+ else:
+ out.append({'name': name, 'left': float(100 - w['usedPercent']), 'resets_in': None if reset is None else round((reset - now) / 60000)})
+ return out
+
+
+def _accounts(machines: List[dict], reserve: int, now: int) -> List[dict]:
+ """One account per weekly reading; machines reporting the same reading (used and reset time) are taken to share it.
+ The exact plan's budget is the weekly window alone: a 5-hour window refills during a night's work. The route's
+ baseline reads both windows."""
+ by_reading: Dict[Tuple, dict] = {}
+ for machine in machines:
+ for quota in (machine.get('observation') or {}).get('quotas', []):
+ if quota['engine'] not in ENGINES or not quota.get('known'):
+ continue
+ weekly = next((w for w in quota['windows'] if w.get('name') == 'weekly'), None)
+ if weekly is None:
+ continue
+ reading = (quota['engine'], weekly['usedPercent'], str(weekly['resetsAt']))
+ if reading not in by_reading:
+ windows = _windows(quota, now)
+ left = next(w['left'] for w in windows if w['name'] == 'weekly')
+ by_reading[reading] = {'id': f"{quota['engine']}-{len(by_reading) + 1}", 'members': [], 'reserve': float(reserve),
+ 'windows': windows, 'budget': {'weekly': left - reserve}}
+ by_reading[reading]['members'].append([machine['machineId'], quota['engine']])
+ return list(by_reading.values())
+
+
+def _allowed(state: dict) -> Optional[set]:
+ """The machines the owner's hard `machines` rules leave; None when there is no such rule."""
+ allowed = None
+ for r in state.get('rules') or []:
+ rule = r.get('rule') or {}
+ if rule.get('kind') == 'machines':
+ ids = set(rule.get('machineIds') or [])
+ allowed = ids if allowed is None else allowed & ids
+ return allowed
+
+
+def _add_back(accounts: List[dict], tasks: List[dict], actual: Dict[str, list], models: List[dict]) -> None:
+ """The snapshot is taken after the night's work spent its quota. Adding back what the actual picks are expected to have
+ spent gives every plan the same budget the night started with (an estimate: the spend comes from the size table)."""
+ rows = {m['id']: m for m in models}
+ for t in tasks:
+ if t['id'] not in actual:
+ continue
+ machine_id, picked = actual[t['id']]
+ model = rows[picked]
+ if not model.get('subscription', True):
+ continue
+ account = next((a for a in accounts if [machine_id, model['engine']] in a['members']), None)
+ if account is not None:
+ # The weekly window only: the night's 5-hour windows have refilled since. A window holds at most 100%: the
+ # size table can estimate more spend than the window shows.
+ for w in account['windows']:
+ if w['name'] == 'weekly':
+ w['left'] = min(100.0, w['left'] + t['spend'].get('weekly', 0.0) * model['cost'] / 2)
+ account['budget']['weekly'] = w['left'] - account['reserve']
+
+
+def _actual_model(configuration: dict, grid: Dict[str, str], model_ids: set) -> Optional[str]:
+ engine, model = configuration.get('engine'), str(configuration.get('model') or '')
+ if model in grid:
+ return grid[model]
+ if engine == 'codex':
+ return model_id('codex', 'default')
+ if engine == 'claude':
+ family = next((f for f in ('opus', 'sonnet', 'haiku') if f in model), None)
+ if family and model_id('claude', family) in model_ids:
+ return model_id('claude', family)
+ return None
+
+
+def convert(status: dict, route_log: List[dict], config: dict) -> dict:
+ state = status['value']['state']
+ policy = config['policy']
+ # A model on the grid is reachable from every machine; work runs only on the machines the owner's rules leave.
+ models, grid = _models(policy, state['machines'])
+ now = snapshot_ms(state['machines'])
+ allowed = _allowed(state)
+ machines = [m for m in state['machines'] if allowed is None or m['machineId'] in allowed]
+ kept = {m['machineId'] for m in machines}
+ ids = {m['id'] for m in models}
+ exclude = config.get('exclude', {})
+ groups = [c for c in state['conversations'] if (c.get('assignment') or {}).get('configuration')]
+ tasks, actual, estimates, excluded = [], {}, [], []
+ for g in groups:
+ if g['id'] in exclude:
+ excluded.append({'group': g['id'], 'title': g['title'], 'reason': exclude[g['id']]})
+ continue
+ given = config.get('assessments', {}).get(g['id'])
+ direct = next((r for r in route_log if r['group'] == g['id']), None)
+ if given and 'route' in given:
+ request = route_log[given['route']]['request']
+ elif given and 'estimate' in given:
+ request = given['estimate']
+ elif direct:
+ request = direct['request']
+ else:
+ raise ConvertError(f'no assessment for {g["id"]} ({g["title"]})')
+ if given:
+ estimates.append({'group': g['id'], 'title': g['title'], 'note': given.get('note', '')})
+ minutes, spend = SIZES[request.get('size', 'medium')]
+ floor = min(3, policy['floor'][request['difficulty']] + (1 if request['risk'] == 'high' else 0))
+ deps = config.get('deps', {}).get(g['id'], [])
+ # A review is done by another model family than the work it reviews (the Lead asks for it on every review).
+ review = g['title'].startswith('Review:')
+ tasks.append({'id': g['id'], 'title': g['title'], 'minutes': minutes, 'floor': floor, 'kind': request.get('kind') or 'default',
+ 'difficulty': request['difficulty'], 'spend': dict(spend), 'deps': deps,
+ 'independent_of': deps if review else []})
+ assignment = g['assignment']
+ picked = _actual_model(assignment['configuration'], grid, ids)
+ if picked is not None:
+ if assignment['execution']['machineId'] not in kept:
+ raise ConvertError(f'{g["id"]} ran on a machine the owner\'s rules leave out')
+ actual[g['id']] = [assignment['execution']['machineId'], picked]
+ accounts = _accounts(machines, policy['quotaReserve'], now)
+ if config.get('budget', 'start') == 'start':
+ _add_back(accounts, tasks, actual, models)
+ task_ids = {t['id'] for t in tasks}
+ for t in tasks:
+ for dep in t['deps']:
+ if dep not in task_ids:
+ raise ConvertError(f'{t["id"]} depends on {dep}, which is not a task')
+ instance = {
+ 'tasks': tasks,
+ 'machines': [{'id': m['machineId'], 'name': m['name'], 'slots': m['maxAgents'],
+ 'engines': [e for e in m['engines'] if e in ENGINES]} for m in machines],
+ 'models': models,
+ 'accounts': accounts,
+ }
+ return {'instance': instance, 'actual': actual, 'estimates': estimates, 'excluded': excluded}
+
+
+def main(argv: List[str]) -> int:
+ status_path, log_path, config_path, out_path = argv
+ with open(status_path) as s, open(log_path) as l, open(config_path) as c:
+ out = convert(json.load(s), json.load(l), json.load(c))
+ with open(out_path, 'w') as f:
+ json.dump(out, f, indent=1)
+ f.write('\n')
+ return 0
diff --git a/tools/scheduler/tests/__init__.py b/tools/scheduler/tests/__init__.py
new file mode 100644
index 000000000..e69de29bb
diff --git a/tools/scheduler/tests/helpers.py b/tools/scheduler/tests/helpers.py
new file mode 100644
index 000000000..205dbede1
--- /dev/null
+++ b/tools/scheduler/tests/helpers.py
@@ -0,0 +1,18 @@
+"""Small hand-built instances for the tests: every expected value in the tests is worked out by hand from these."""
+
+
+def model(id, engine='claude', cost=1, quality=3, speed=1.0, **extra):
+ q = quality if isinstance(quality, dict) else {'default': quality}
+ return {'id': id, 'engine': engine, 'cost': cost, 'quality': q, 'speed': speed, **extra}
+
+
+def machine(id, slots=1, engines=('claude',)):
+ return {'id': id, 'name': id, 'slots': slots, 'engines': list(engines)}
+
+
+def task(id, minutes=60, floor=1, deps=(), **extra):
+ return {'id': id, 'title': id, 'minutes': minutes, 'floor': floor, 'deps': list(deps), **extra}
+
+
+def instance(tasks, machines, models, accounts=()):
+ return {'tasks': list(tasks), 'machines': list(machines), 'models': list(models), 'accounts': list(accounts)}
diff --git a/tools/scheduler/tests/test_bench.py b/tools/scheduler/tests/test_bench.py
new file mode 100644
index 000000000..cadf64ad4
--- /dev/null
+++ b/tools/scheduler/tests/test_bench.py
@@ -0,0 +1,31 @@
+import time
+import unittest
+
+from scheduler.bench import generate
+from scheduler.instance import load
+from scheduler.solver import solve
+
+
+class BenchTest(unittest.TestCase):
+ def test_the_generated_instance_has_the_asked_size_and_loads(self):
+ inst = load(generate(seed=1, tasks=30, machines=8, models=6))
+ self.assertEqual((len(inst.tasks), len(inst.machines), len(inst.models)), (30, 8, 6))
+ self.assertTrue(any(t.deps for t in inst.tasks))
+ self.assertTrue(any(t.independent_of for t in inst.tasks))
+ self.assertTrue(inst.accounts)
+
+ def test_the_same_seed_gives_the_same_instance(self):
+ self.assertEqual(generate(seed=7), generate(seed=7))
+
+ def test_30_tasks_8_machines_6_models_solve_to_proven_optimal_within_10_seconds(self):
+ for seed in (1, 2, 3):
+ with self.subTest(seed=seed):
+ inst = load(generate(seed=seed, tasks=30, machines=8, models=6))
+ began = time.monotonic()
+ result = solve(inst, time_limit=10.0)
+ self.assertLess(time.monotonic() - began, 10.0)
+ self.assertEqual(result.status, 'OPTIMAL')
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tools/scheduler/tests/test_cli.py b/tools/scheduler/tests/test_cli.py
new file mode 100644
index 000000000..f89fa1440
--- /dev/null
+++ b/tools/scheduler/tests/test_cli.py
@@ -0,0 +1,89 @@
+import json
+import os
+import subprocess
+import sys
+import tempfile
+import unittest
+
+from scheduler.compare import broken, compare
+from scheduler.instance import load
+from tests.helpers import instance, machine, model, task
+
+ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
+
+
+def two_tasks():
+ return instance([task('build', floor=3), task('review', minutes=20, floor=3, deps=['build'], independent_of=['build'])],
+ [machine('cheap', engines=['claude', 'codex']), machine('dear', engines=['claude', 'codex'])],
+ [model('gpt', engine='codex', cost=2), model('opus', cost=3), model('haiku', cost=1, quality=1)])
+
+
+class BrokenTest(unittest.TestCase):
+ def test_lists_a_pick_below_the_floor_and_a_review_by_the_same_family(self):
+ inst = load(two_tasks())
+ got = broken(inst, {'build': ('cheap', 'gpt'), 'review': ('dear', 'gpt')})
+ self.assertEqual(got, ['review: reviewed by the same family (codex) as build'])
+ got = broken(inst, {'build': ('cheap', 'gpt'), 'review': ('dear', 'haiku')})
+ self.assertEqual(got, ['review: quality 1 below its floor 3'])
+
+ def test_lists_an_account_spent_past_its_budget(self):
+ inst = load(instance([task('a', spend={'weekly': 8})], [machine('m')], [model('opus', cost=3)],
+ [{'id': 'acct', 'members': [['m', 'claude']], 'budget': {'weekly': 5}}]))
+ self.assertEqual(broken(inst, {'a': ('m', 'opus')}), ['account acct: weekly 12.0% used of 5.0% left'])
+
+ def test_an_account_already_past_its_reserve_is_not_listed_when_nothing_uses_it(self):
+ inst = load(instance([task('a', spend={'weekly': 8})], [machine('m'), machine('n')], [model('opus', cost=3)],
+ [{'id': 'acct', 'members': [['n', 'claude']], 'budget': {'weekly': -10}}]))
+ self.assertEqual(broken(inst, {'a': ('m', 'opus')}), [])
+
+
+class CompareTest(unittest.TestCase):
+ def test_reports_the_optimal_greedy_and_actual_plans(self):
+ night = {'instance': two_tasks(), 'actual': {'build': ['cheap', 'opus'], 'review': ['dear', 'gpt']}}
+ report = compare(night, time_limit=5.0)
+ rows = {r['plan']: r for r in report['rows']}
+ self.assertEqual((rows['optimal']['makespan'], rows['optimal']['cost']), (80, 2 * 60 + 3 * 20))
+ self.assertEqual(rows['optimal']['status'], 'OPTIMAL')
+ self.assertEqual((rows['actual']['makespan'], rows['actual']['cost']), (80, 3 * 60 + 2 * 20))
+ self.assertEqual(rows['actual']['broken'], [])
+ self.assertIn('greedy', rows)
+ self.assertEqual([(p['makespan'], p['cost']) for p in report['pareto']['points']], [(80, 180)])
+
+
+class SlotCapTest(unittest.TestCase):
+ def test_capping_slots_shows_the_night_on_fewer_agents_per_machine(self):
+ night = {'instance': instance([task('a'), task('b')], [machine('m', slots=4)], [model('opus')]), 'actual': {}}
+ rows = {r['plan']: r for r in compare(night, time_limit=5.0, max_slots=1)['rows']}
+ self.assertEqual(rows['optimal']['makespan'], 120)
+
+
+class CommandLineTest(unittest.TestCase):
+ def run_cli(self, *args):
+ done = subprocess.run([sys.executable, '-m', 'scheduler', *args], cwd=ROOT, capture_output=True, text=True, timeout=60)
+ self.assertEqual(done.returncode, 0, done.stderr)
+ return done.stdout
+
+ def test_solve_prints_the_plan_as_json(self):
+ with tempfile.NamedTemporaryFile('w', suffix='.json', delete=False) as f:
+ json.dump(two_tasks(), f)
+ try:
+ out = json.loads(self.run_cli('solve', f.name))
+ finally:
+ os.unlink(f.name)
+ self.assertEqual((out['status'], out['makespan'], out['cost']), ('OPTIMAL', 80, 180))
+ self.assertEqual(sorted(p['task'] for p in out['plan']), ['build', 'review'])
+
+ def test_compare_prints_a_table(self):
+ night = {'instance': two_tasks(), 'actual': {'build': ['cheap', 'opus'], 'review': ['dear', 'gpt']}}
+ with tempfile.NamedTemporaryFile('w', suffix='.json', delete=False) as f:
+ json.dump(night, f)
+ try:
+ out = self.run_cli('compare', f.name)
+ finally:
+ os.unlink(f.name)
+ self.assertIn('| optimal | OPTIMAL | 80 | 180 |', out)
+ self.assertIn('| actual |', out)
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tools/scheduler/tests/test_greedy.py b/tools/scheduler/tests/test_greedy.py
new file mode 100644
index 000000000..c07063413
--- /dev/null
+++ b/tools/scheduler/tests/test_greedy.py
@@ -0,0 +1,147 @@
+import unittest
+
+from scheduler.greedy import Decision, Sized, evaluate, greedy, size_up
+from scheduler.instance import Option, load
+from scheduler.solver import solve
+from tests.helpers import instance, machine, model, task
+
+
+def picks(result):
+ return {p.task: (p.machine, p.model) for p in result.plan}
+
+
+class EvaluateTest(unittest.TestCase):
+ def test_a_fixed_assignment_starts_each_task_as_early_as_slots_and_dependencies_allow(self):
+ inst = load(instance([task('a', minutes=60), task('b', minutes=30), task('c', minutes=20, deps=['a'])],
+ [machine('m', slots=1), machine('n', slots=1)], [model('opus', cost=3)]))
+ result = evaluate(inst, {'a': ('m', 'opus'), 'b': ('m', 'opus'), 'c': ('n', 'opus')})
+ got = {p.task: (p.start, p.end) for p in result.plan}
+ self.assertEqual(got, {'a': (0, 60), 'b': (60, 90), 'c': (60, 80)})
+ self.assertEqual(result.makespan, 90)
+ self.assertEqual(result.cost, 3 * (60 + 30 + 20))
+
+ def test_two_accounts_of_one_machine_queue_on_its_slots(self):
+ inst = load(instance([task('a'), task('b')], [machine('mac', slots=1), {**machine('team', slots=1), 'pool': 'mac'}], [model('opus')]))
+ self.assertEqual(evaluate(inst, {'a': ('mac', 'opus'), 'b': ('team', 'opus')}).makespan, 120)
+
+ def test_a_model_limited_to_one_task_queues_the_second(self):
+ inst = load(instance([task('a'), task('b')], [machine('m', slots=2), machine('n', slots=2)], [model('local', concurrency=1)]))
+ result = evaluate(inst, {'a': ('m', 'local'), 'b': ('n', 'local')})
+ self.assertEqual(result.makespan, 120)
+
+
+class RouteOrderTest(unittest.TestCase):
+ def test_picks_the_cheapest_model_that_meets_the_floor(self):
+ inst = load(instance([task('a', floor=2)], [machine('m')],
+ [model('haiku', cost=1, quality=1), model('sonnet', cost=2, quality=2), model('opus', cost=3, quality=3)]))
+ self.assertEqual(picks(greedy(inst)), {'a': ('m', 'sonnet')})
+
+ def test_a_hard_task_takes_only_the_strongest(self):
+ inst = load(instance([task('a', floor=2, difficulty='high')], [machine('m')],
+ [model('sonnet', cost=2, quality=2), model('opus', cost=3, quality=3)]))
+ self.assertEqual(picks(greedy(inst)), {'a': ('m', 'opus')})
+
+ def test_at_equal_cost_the_stronger_model_then_the_account_with_more_room(self):
+ accounts = [{'id': 'x', 'members': [['x', 'claude']], 'budget': {'weekly': 20}},
+ {'id': 'y', 'members': [['y', 'claude']], 'budget': {'weekly': 50}}]
+ inst = load(instance([task('a')], [machine('x'), machine('y')],
+ [model('sonnet', cost=2, quality=2), model('opus', cost=2, quality=3)], accounts))
+ self.assertEqual(picks(greedy(inst)), {'a': ('y', 'opus')})
+
+ def test_a_known_account_that_fits_comes_before_one_whose_quota_is_unknown(self):
+ accounts = [{'id': 'b', 'members': [['b', 'claude']], 'budget': {'weekly': 50}}]
+ inst = load(instance([task('t', spend={'weekly': 4})], [machine('a'), machine('b')], [model('opus')], accounts))
+ self.assertEqual(picks(greedy(inst)), {'t': ('b', 'opus')})
+
+ def test_skips_an_account_the_earlier_picks_have_used_up(self):
+ accounts = [{'id': 'x', 'members': [['x', 'claude']], 'budget': {'5-hour': 40}},
+ {'id': 'y', 'members': [['y', 'claude']], 'budget': {'5-hour': 35}}]
+ inst = load(instance([task('a', spend={'5-hour': 30}), task('b', spend={'5-hour': 30})],
+ [machine('x', slots=4), machine('y', slots=4)], [model('opus', cost=2)], accounts))
+ self.assertEqual(picks(greedy(inst)), {'a': ('x', 'opus'), 'b': ('y', 'opus')})
+
+ def test_a_review_skips_the_family_its_build_was_given(self):
+ inst = load(instance([task('build'), task('review', deps=['build'], independent_of=['build'])],
+ [machine('m', slots=2, engines=['claude', 'codex'])],
+ [model('gpt', engine='codex', cost=2), model('opus', cost=3)]))
+ self.assertEqual(picks(greedy(inst)), {'build': ('m', 'gpt'), 'review': ('m', 'opus')})
+
+ def test_ignores_the_queue_so_it_finishes_later_than_the_exact_plan(self):
+ # The route always takes the cheap one-slot machine; the exact plan spends more to run both at once.
+ inst = load(instance([task('a'), task('b')], [machine('cheap'), machine('dear', engines=['codex'])],
+ [model('haiku', cost=1), model('gpt', engine='codex', cost=3)]))
+ self.assertEqual(greedy(inst).makespan, 120)
+ self.assertEqual(solve(inst).makespan, 60)
+
+
+def account(id, machine, engine='claude', reserve=10, **windows):
+ """windows: name -> (left, resets_in); `five` is the 5-hour window."""
+ named = {'five': '5-hour', 'weekly': 'weekly'}
+ return {'id': id, 'members': [[machine, engine]], 'reserve': reserve,
+ 'windows': [{'name': named[k], 'left': v[0], 'resets_in': v[1]} for k, v in windows.items()]}
+
+
+LARGE = {'5-hour': 50, 'weekly': 8}
+MEDIUM = {'5-hour': 30, 'weekly': 4}
+
+
+class RouteQuotaTest(unittest.TestCase):
+ """route.ts sizeUp and compare: effective cost before cost, on the quota readings at the time each task is routed."""
+
+ def reset_case(self, resets_in):
+ return load(instance([task('t', minutes=180, floor=3, difficulty='high', spend=LARGE)],
+ [machine('a'), machine('b', engines=['codex'])],
+ [model('opus', cost=3), model('gpt', engine='codex', cost=2)],
+ [account('ca', 'a', five=(50, resets_in), weekly=(80, 7200)), account('cb', 'b', 'codex', weekly=(80, 7200))]))
+
+ def test_near_a_5_hour_reset_the_unused_window_makes_opus_free_so_it_beats_cheaper_codex(self):
+ # Resets in 30 minutes: the task needs 50 x 3/2 x 30/180 = 12.5 of the window and 40 is usable, otherwise lost.
+ self.assertEqual(picks(greedy(self.reset_case(30))), {'t': ('a', 'opus')})
+
+ def test_far_from_the_reset_cheaper_codex_wins(self):
+ self.assertEqual(picks(greedy(self.reset_case(600))), {'t': ('b', 'gpt')})
+
+ def test_a_task_that_is_not_hard_pays_for_more_than_a_days_share_of_the_weekly_window(self):
+ # Codex: 10 usable over 7 days is 1.43 a day against 4 needed, so its cost 2 becomes 2 + 2 x 4/1.43 = 7.6 > Opus's 3.
+ inst = load(instance([task('t', floor=2, difficulty='medium', spend=MEDIUM)],
+ [machine('x', engines=['codex']), machine('y')],
+ [model('gpt', engine='codex', cost=2), model('opus', cost=3)],
+ [account('cx', 'x', 'codex', weekly=(20, 10080)), account('cy', 'y', five=(100, None), weekly=(90, 1440))]))
+ self.assertEqual(picks(greedy(inst)), {'t': ('y', 'opus')})
+
+ def refill_case(self):
+ return load(instance([task('a', spend=MEDIUM), task('b', deps=['a'], spend=MEDIUM)],
+ [machine('x', slots=2), machine('y', slots=2)], [model('opus', cost=2)],
+ [account('ax', 'x', five=(15, 30), weekly=(90, 10000)), account('ay', 'y', five=(100, None), weekly=(90, 10000))]))
+
+ def test_a_5_hour_window_refills_at_its_reset(self):
+ # x's window has 15 left and resets at minute 30. Read at minute 60 it is full again: 100 - 10 reserve = 90
+ # usable against the 30 a medium task needs, and its next reset is 270 minutes away, so nothing is free.
+ inst = self.refill_case()
+ got = size_up(inst, inst.task('b'), Option('b', 'x', 'opus', 60), 60, [])
+ self.assertEqual(got, Sized('fits', 3.0, 2.0, 90.0))
+
+ def test_work_that_has_run_uses_the_window_and_a_finished_pick_holds_nothing(self):
+ # a ran on y from 0 to 60, using its 30: read at 60, y has 100 - 30 - 10 = 60 usable and a holds no more.
+ inst = self.refill_case()
+ ran = [Decision(inst.task('a'), 'y', 'opus', at=0, start=0, end=60)]
+ got = size_up(inst, inst.task('b'), Option('b', 'y', 'opus', 60), 60, ran)
+ self.assertEqual(got, Sized('fits', 2.0, 2.0, 60.0))
+
+ def test_an_open_pick_holds_the_rest_of_its_spend(self):
+ # a, routed at 0 and still running at 30, has used 15 and holds the other 15: 100 - 15 - 15 - 10 = 60.
+ inst = self.refill_case()
+ running = [Decision(inst.task('a'), 'y', 'opus', at=0, start=0, end=60)]
+ self.assertEqual(size_up(inst, inst.task('b'), Option('b', 'y', 'opus', 60), 30, running).tight, 60.0)
+
+ def test_a_task_routed_after_the_reset_goes_to_the_refilled_account(self):
+ # a, at 0: x has 5 usable, short of the 15 it needs before the reset, so a goes to y. b, at 60: x has 90, y 60.
+ self.assertEqual(picks(greedy(self.refill_case())), {'a': ('y', 'opus'), 'b': ('x', 'opus')})
+
+ def test_with_nothing_at_its_floor_the_route_takes_the_best_below_it(self):
+ inst = load(instance([task('t', floor=3)], [machine('m')], [model('haiku', cost=1, quality=1)]))
+ self.assertEqual(picks(greedy(inst)), {'t': ('m', 'haiku')})
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tools/scheduler/tests/test_instance.py b/tools/scheduler/tests/test_instance.py
new file mode 100644
index 000000000..884a2dd23
--- /dev/null
+++ b/tools/scheduler/tests/test_instance.py
@@ -0,0 +1,102 @@
+import unittest
+
+from scheduler.instance import InstanceError, load, options
+from tests.helpers import instance, machine, model, task
+
+
+class LoadTest(unittest.TestCase):
+ def test_reads_a_valid_instance(self):
+ inst = load(instance([task('a', minutes=30, floor=2, kind='review')], [machine('m', slots=2)], [model('opus', cost=3)]))
+ self.assertEqual(inst.tasks[0].minutes, 30)
+ self.assertEqual(inst.tasks[0].kind, 'review')
+ self.assertEqual(inst.machines[0].slots, 2)
+ self.assertEqual(inst.models[0].cost, 3)
+
+ def test_refuses_a_dependency_on_an_unknown_task(self):
+ with self.assertRaisesRegex(InstanceError, 'a depends on unknown task b'):
+ load(instance([task('a', deps=['b'])], [machine('m')], [model('opus')]))
+
+ def test_refuses_a_dependency_cycle(self):
+ with self.assertRaisesRegex(InstanceError, 'cycle'):
+ load(instance([task('a', deps=['b']), task('b', deps=['a'])], [machine('m')], [model('opus')]))
+
+ def test_refuses_duplicate_task_ids(self):
+ with self.assertRaisesRegex(InstanceError, 'duplicate task a'):
+ load(instance([task('a'), task('a')], [machine('m')], [model('opus')]))
+
+ def test_refuses_a_model_without_default_quality(self):
+ with self.assertRaisesRegex(InstanceError, 'opus has no default quality'):
+ load(instance([task('a')], [machine('m')], [model('opus', quality={'review': 3})]))
+
+ def test_refuses_independence_from_an_unknown_task(self):
+ with self.assertRaisesRegex(InstanceError, 'a must differ from unknown task b'):
+ load(instance([task('a', independent_of=['b'])], [machine('m')], [model('opus')]))
+
+ def test_refuses_a_machine_sharing_slots_with_an_unknown_one(self):
+ with self.assertRaisesRegex(InstanceError, 'team shares slots with unknown machine z'):
+ load(instance([task('a')], [{**machine('team'), 'pool': 'z'}], [model('opus')]))
+
+ def test_refuses_an_account_on_an_unknown_machine(self):
+ with self.assertRaisesRegex(InstanceError, 'account x names unknown machine z'):
+ load(instance([task('a')], [machine('m')], [model('opus')],
+ [{'id': 'x', 'members': [['z', 'claude']], 'budget': {'weekly': 10}}]))
+
+
+class AccountTest(unittest.TestCase):
+ def test_windows_default_to_the_budget_with_no_reset_and_no_reserve(self):
+ inst = load(instance([task('a')], [machine('m')], [model('opus')],
+ [{'id': 'x', 'members': [['m', 'claude']], 'budget': {'weekly': 40}}]))
+ w = inst.accounts[0].windows
+ self.assertEqual([(x.name, x.left, x.resets_in) for x in w], [('weekly', 40.0, None)])
+ self.assertEqual(inst.accounts[0].reserve, 0.0)
+
+ def test_the_budget_defaults_to_the_weekly_window_less_the_reserve(self):
+ inst = load(instance([task('a')], [machine('m')], [model('opus')],
+ [{'id': 'x', 'members': [['m', 'claude']], 'reserve': 10,
+ 'windows': [{'name': '5-hour', 'left': 90, 'resets_in': 30}, {'name': 'weekly', 'left': 50, 'resets_in': 5000}]}]))
+ self.assertEqual(inst.accounts[0].budget, {'weekly': 40.0})
+
+
+class OptionsTest(unittest.TestCase):
+ def test_only_models_meeting_the_floor_on_machines_with_their_engine(self):
+ inst = load(instance(
+ [task('a', floor=2)],
+ [machine('m1', engines=['claude']), machine('m2', engines=['codex'])],
+ [model('haiku', quality=1), model('opus', quality=3), model('gpt', engine='codex', quality=2)]))
+ got = sorted((o.machine, o.model) for o in options(inst, inst.tasks[0]))
+ self.assertEqual(got, [('m1', 'opus'), ('m2', 'gpt')])
+
+ def test_quality_for_the_task_kind_overrides_the_default(self):
+ inst = load(instance([task('r', floor=3, kind='review')], [machine('m')],
+ [model('sonnet', quality={'default': 2, 'review': 3})]))
+ self.assertEqual([o.model for o in options(inst, inst.tasks[0])], ['sonnet'])
+
+ def test_a_slower_model_takes_longer(self):
+ inst = load(instance([task('a', minutes=60)], [machine('m')], [model('local', speed=0.5)]))
+ self.assertEqual(options(inst, inst.tasks[0])[0].minutes, 120)
+
+ def test_a_family_the_task_must_avoid_is_never_offered(self):
+ # A review whose build already ran on Codex: Codex is off the table even though it meets the floor.
+ inst = load(instance([task('r', avoid_families=['codex'])], [machine('m', engines=['claude', 'codex'])],
+ [model('opus'), model('gpt', engine='codex')]))
+ self.assertEqual([o.model for o in options(inst, inst.tasks[0])], ['opus'])
+
+ def test_a_task_limited_to_some_machines_and_models_is_offered_only_those(self):
+ # The owner's rules for the task's project: only machine m2, and no Sonnet.
+ inst = load(instance([task('a', machines=['m2'], models=['opus'])], [machine('m1'), machine('m2')],
+ [model('opus'), model('sonnet')]))
+ self.assertEqual([(o.machine, o.model) for o in options(inst, inst.tasks[0])], [('m2', 'opus')])
+
+ def test_refuses_a_task_limited_to_an_unknown_machine_or_model(self):
+ with self.assertRaisesRegex(InstanceError, 'a names unknown machine z'):
+ load(instance([task('a', machines=['z'])], [machine('m')], [model('opus')]))
+ with self.assertRaisesRegex(InstanceError, 'a names unknown model z'):
+ load(instance([task('a', models=['z'])], [machine('m')], [model('opus')]))
+
+ def test_a_model_limited_to_some_machines_is_offered_only_there(self):
+ inst = load(instance([task('a')], [machine('m1'), machine('m2')], [model('local', machines=['m2'])]))
+ self.assertEqual([o.machine for o in options(inst, inst.tasks[0])], ['m2'])
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tools/scheduler/tests/test_pareto.py b/tools/scheduler/tests/test_pareto.py
new file mode 100644
index 000000000..da9d264ee
--- /dev/null
+++ b/tools/scheduler/tests/test_pareto.py
@@ -0,0 +1,32 @@
+import unittest
+
+from scheduler.instance import load
+from scheduler.solver import pareto
+from tests.helpers import instance, machine, model, task
+
+
+class ParetoTest(unittest.TestCase):
+ def test_two_tasks_on_a_cheap_and_a_dear_machine(self):
+ # Both on the cheap machine: 120 minutes, cost 120. Split: 60 minutes, cost 60 + 180. Both on the dear one: 120
+ # minutes, cost 360, dominated by the first.
+ inst = load(instance([task('a'), task('b')], [machine('cheap'), machine('dear', engines=['codex'])],
+ [model('haiku', cost=1), model('gpt', engine='codex', cost=3)]))
+ front = pareto(inst)
+ self.assertTrue(front.complete)
+ self.assertEqual([(p.makespan, p.cost) for p in front.points], [(60, 240), (120, 120)])
+
+ def test_three_points_when_a_middle_plan_trades_time_for_cost(self):
+ # Three 60-minute tasks; cheap has one slot at cost 1, dear one slot at cost 3.
+ # All cheap: 180 / 180. Two cheap, one dear: 120 / 120 + 180 = 300. Splitting further cannot beat 120 minutes.
+ inst = load(instance([task('a'), task('b'), task('c')], [machine('cheap'), machine('dear', engines=['codex'])],
+ [model('haiku', cost=1), model('gpt', engine='codex', cost=3)]))
+ front = pareto(inst)
+ self.assertEqual([(p.makespan, p.cost) for p in front.points], [(120, 300), (180, 180)])
+
+ def test_a_single_plan_is_a_single_point(self):
+ inst = load(instance([task('a')], [machine('m')], [model('opus', cost=3)]))
+ self.assertEqual([(p.makespan, p.cost) for p in pareto(inst).points], [(60, 180)])
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tools/scheduler/tests/test_plan.py b/tools/scheduler/tests/test_plan.py
new file mode 100644
index 000000000..8ad86aaf7
--- /dev/null
+++ b/tools/scheduler/tests/test_plan.py
@@ -0,0 +1,67 @@
+import json
+import os
+import subprocess
+import sys
+import tempfile
+import unittest
+
+from scheduler.plan import plan
+from tests.helpers import instance, machine, model, task
+
+ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
+
+
+def two_builds_and_a_review():
+ return instance([task('a'), task('b', minutes=20), task('r', minutes=20, floor=3, deps=['a'], independent_of=['a'])],
+ [machine('m', slots=1, engines=['claude', 'codex']), machine('n', slots=1, engines=['claude', 'codex'])],
+ [model('gpt', engine='codex', cost=2), model('opus', cost=3)])
+
+
+class PlanTest(unittest.TestCase):
+ def test_gives_each_task_its_machine_model_start_order_and_finish(self):
+ out = plan(two_builds_and_a_review(), time_limit=5.0)
+ self.assertEqual(out['status'], 'OPTIMAL')
+ # a (60) and b (20) start at once on the two machines; the review follows a on another family.
+ rows = {r['task']: r for r in out['plan']}
+ self.assertEqual(set(rows), {'a', 'b', 'r'})
+ self.assertEqual((rows['a']['start'], rows['a']['end']), (0, 60))
+ self.assertEqual((rows['r']['start'], rows['r']['end']), (60, 80))
+ self.assertNotEqual(rows['r']['model'], rows['a']['model'])
+ self.assertEqual([r['order'] for r in out['plan']], [1, 2, 3])
+ self.assertEqual(out['plan'][-1]['task'], 'r')
+ self.assertEqual((out['makespan'], out['cost']), (80, 2 * 60 + 2 * 20 + 3 * 20))
+
+ def test_says_what_the_route_would_do_for_the_same_work(self):
+ route = plan(two_builds_and_a_review(), time_limit=5.0)['route']
+ self.assertEqual(route['status'], 'EVALUATED')
+ self.assertEqual(sorted(r['task'] for r in route['plan']), ['a', 'b', 'r'])
+ self.assertEqual(set(route), {'status', 'makespan', 'cost', 'plan'})
+
+ def test_an_impossible_plan_says_why(self):
+ out = plan(instance([task('a', floor=3)], [machine('m')], [model('haiku', quality=1)]), time_limit=5.0)
+ self.assertEqual((out['status'], out['plan']), ('INFEASIBLE', []))
+ self.assertIn('a', out['reason'])
+
+
+class PlanCommandTest(unittest.TestCase):
+ def run_plan(self, env=None):
+ return subprocess.run([sys.executable, '-m', 'scheduler', 'plan', '--time-limit', '5'], cwd=ROOT, input=json.dumps(two_builds_and_a_review()),
+ capture_output=True, text=True, timeout=60, env={**os.environ, **(env or {})})
+
+ def test_reads_the_instance_on_stdin_and_prints_the_plan(self):
+ done = self.run_plan()
+ self.assertEqual(done.returncode, 0, done.stderr)
+ self.assertEqual(json.loads(done.stdout)['makespan'], 80)
+
+ def test_without_or_tools_it_says_so_with_exit_3(self):
+ with tempfile.TemporaryDirectory() as fake:
+ os.makedirs(os.path.join(fake, 'ortools'))
+ with open(os.path.join(fake, 'ortools', '__init__.py'), 'w') as f:
+ f.write("raise ImportError('No module named ortools')\n")
+ done = self.run_plan({'PYTHONPATH': fake})
+ self.assertEqual(done.returncode, 3)
+ self.assertEqual(json.loads(done.stdout)['error'], 'ORTOOLS_MISSING')
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tools/scheduler/tests/test_redact.py b/tools/scheduler/tests/test_redact.py
new file mode 100644
index 000000000..329bd95f7
--- /dev/null
+++ b/tools/scheduler/tests/test_redact.py
@@ -0,0 +1,65 @@
+import copy
+import json
+import unittest
+
+from scheduler.redact import redact
+from scheduler.swarm import convert
+from tests.test_swarm import CONFIG, ROUTE_LOG, STATUS
+
+
+def sample():
+ status = copy.deepcopy(STATUS)
+ state = status['value']['state']
+ state['people'] = [{'id': 'p1', 'email': '[email protected]', 'role': 'owner'},
+ {'id': 'p2', 'email': '[email protected]', 'role': 'collaborator'}]
+ state['machines'][1]['name'] = "Diego's Mac"
+ state['machines'][1]['cwd'] = '/Users/diego/.harness/cli/data/swarm-projects/x'
+ state['conversations'][1]['brief'] = 'Ask [email protected]; push with https://bot:[email protected]/o/r.git'
+ state['projects'] = [{'id': 'p', 'name': 'proj', 'repository': {'repositoryUrl': 'https://bot:[email protected]/o/r'}}]
+ state['rules'][0]['text'] = "Owner: Ken's Mac takes no work until 21:00"
+ log = copy.deepcopy(ROUTE_LOG) + [{'group': 'g9', 'request': {'difficulty': 'low', 'risk': 'low', 'size': 'small',
+ 'why': 'Continue on Diegos Mac; Ken knows it'}, 'at': None}]
+ return status, log
+
+
+class RedactTest(unittest.TestCase):
+ def setUp(self):
+ self.status, self.log = redact(*sample())
+ self.text = json.dumps([self.status, self.log])
+
+ def test_no_email_remains(self):
+ self.assertNotIn('@example.com', self.text)
+ self.assertNotIn('email', self.text)
+
+ def test_no_url_with_credentials_or_token_remains(self):
+ self.assertNotIn('ghp_secret', self.text)
+ self.assertNotIn('bot:', self.text)
+
+ def test_peoples_names_are_replaced_in_machine_names_rules_and_route_reasons(self):
+ for name in ('Diego', 'Ken', 'diego'):
+ self.assertNotIn(name, self.text)
+ state = self.status['value']['state']
+ self.assertEqual(state['machines'][1]['name'], "[person]'s Mac")
+ self.assertEqual(state['rules'][0]['text'], "Owner: [person]'s Mac takes no work until 21:00")
+ self.assertEqual(self.log[-1]['request']['why'], 'Continue on [person]s Mac; [person] knows it')
+
+ def test_home_folders_and_briefs_are_left_out(self):
+ self.assertNotIn('/Users/', self.text)
+ self.assertNotIn('brief', self.text)
+
+ def test_words_that_only_contain_a_name_are_kept(self):
+ status, log = sample()
+ log[-1]['request']['why'] = 'Deepseek token check'
+ status['value']['state']['people'].append({'id': 'p3', 'email': '[email protected]'})
+ self.assertEqual(redact(status, log)[1][-1]['request']['why'], 'Deepseek token check')
+
+ def test_converting_the_redacted_inputs_gives_the_same_instance_apart_from_names(self):
+ original = convert(*sample()[:1], ROUTE_LOG, CONFIG)
+ redacted = convert(self.status, self.log[:len(ROUTE_LOG)], CONFIG)
+ for m in original['instance']['machines']:
+ m['name'] = m['name'].replace('Diego', '[person]')
+ self.assertEqual(redacted, original)
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tools/scheduler/tests/test_solver.py b/tools/scheduler/tests/test_solver.py
new file mode 100644
index 000000000..574d0afe6
--- /dev/null
+++ b/tools/scheduler/tests/test_solver.py
@@ -0,0 +1,121 @@
+import unittest
+
+from scheduler.instance import load
+from scheduler.solver import solve
+from tests.helpers import instance, machine, model, task
+
+
+def placed(result):
+ return {p.task: p for p in result.plan}
+
+
+class FloorTest(unittest.TestCase):
+ def test_a_cheaper_model_below_the_floor_is_never_used(self):
+ inst = load(instance([task('a', floor=3)], [machine('m')], [model('haiku', cost=1, quality=1), model('opus', cost=3, quality=3)]))
+ result = solve(inst)
+ self.assertEqual(result.status, 'OPTIMAL')
+ self.assertEqual(placed(result)['a'].model, 'opus')
+
+ def test_no_model_meeting_the_floor_is_infeasible_and_names_the_task(self):
+ inst = load(instance([task('a', floor=3)], [machine('m')], [model('haiku', quality=1)]))
+ result = solve(inst)
+ self.assertEqual(result.status, 'INFEASIBLE')
+ self.assertIn('a', result.reason)
+
+
+class DependencyTest(unittest.TestCase):
+ def test_a_task_starts_after_the_task_it_depends_on_ends(self):
+ inst = load(instance([task('build', minutes=60), task('review', minutes=20, deps=['build'])],
+ [machine('m1'), machine('m2')], [model('opus')]))
+ result = solve(inst)
+ p = placed(result)
+ self.assertGreaterEqual(p['review'].start, p['build'].end)
+ self.assertEqual(result.makespan, 80)
+
+
+class SlotTest(unittest.TestCase):
+ def test_one_slot_runs_tasks_one_after_another(self):
+ inst = load(instance([task('a'), task('b'), task('c')], [machine('m', slots=1)], [model('opus')]))
+ self.assertEqual(solve(inst).makespan, 180)
+
+ def test_two_slots_run_two_at_a_time(self):
+ inst = load(instance([task('a'), task('b'), task('c')], [machine('m', slots=2)], [model('opus')]))
+ result = solve(inst)
+ self.assertEqual(result.makespan, 120)
+ for t in range(0, 120):
+ running = sum(1 for p in result.plan if p.start <= t < p.end)
+ self.assertLessEqual(running, 2)
+
+ def test_two_accounts_of_one_machine_share_its_slots(self):
+ # A Mac and its Harness Team account are one machine: one free slot between them runs one task at a time.
+ inst = load(instance([task('a', machines=['mac']), task('b', machines=['team'])],
+ [machine('mac', slots=1), {**machine('team', slots=1), 'pool': 'mac'}], [model('opus')]))
+ self.assertEqual(solve(inst).makespan, 120)
+
+ def test_a_local_model_serves_one_task_at_a_time_whatever_the_slots(self):
+ inst = load(instance([task('a'), task('b')], [machine('m', slots=4)], [model('local', concurrency=1)]))
+ self.assertEqual(solve(inst).makespan, 120)
+
+
+class QuotaTest(unittest.TestCase):
+ def test_an_account_short_of_quota_takes_only_what_fits(self):
+ # Each task spends 30% of the 5-hour window at cost 2; the cheap account has 40% left, so it carries one task.
+ tasks = [task('a', spend={'5-hour': 30}), task('b', spend={'5-hour': 30})]
+ inst = load(instance(tasks, [machine('cheap', slots=2), machine('dear', slots=2, engines=['codex'])],
+ [model('opus', cost=2), model('gpt', engine='codex', cost=3)],
+ [{'id': 'acct', 'members': [['cheap', 'claude']], 'budget': {'5-hour': 40}}]))
+ result = solve(inst)
+ self.assertEqual(sorted(p.machine for p in result.plan), ['cheap', 'dear'])
+
+ def test_a_model_outside_the_subscription_spends_no_quota(self):
+ tasks = [task('a', spend={'5-hour': 30}), task('b', spend={'5-hour': 30})]
+ inst = load(instance(tasks, [machine('m', slots=2)], [model('api', cost=1, subscription=False)],
+ [{'id': 'acct', 'members': [['m', 'claude']], 'budget': {'5-hour': 0}}]))
+ result = solve(inst)
+ self.assertEqual(result.status, 'OPTIMAL')
+ self.assertEqual(len(result.plan), 2)
+
+
+class IndependenceTest(unittest.TestCase):
+ def test_a_review_uses_another_model_family_than_the_work_it_reviews(self):
+ # Codex is cheaper for both, but the review must not be Codex if the build is.
+ inst = load(instance([task('build'), task('review', minutes=20, deps=['build'], independent_of=['build'])],
+ [machine('m', slots=2, engines=['claude', 'codex'])],
+ [model('gpt', engine='codex', cost=2), model('opus', cost=3)]))
+ result = solve(inst)
+ p = placed(result)
+ self.assertNotEqual(inst.model(p['build'].model).family, inst.model(p['review'].model).family)
+ self.assertEqual(result.cost, 60 * 2 + 20 * 3)
+
+ def test_models_of_one_engine_share_a_family_unless_given_one(self):
+ inst = load(instance([task('a')], [machine('m')], [model('opus'), model('grid', family='deepseek')]))
+ self.assertEqual((inst.model('opus').family, inst.model('grid').family), ('claude', 'deepseek'))
+
+
+class ObjectiveTest(unittest.TestCase):
+ def test_finish_time_comes_before_cost(self):
+ # One slot each: both on the cheap machine take 120 minutes; splitting finishes at 60 and costs more.
+ inst = load(instance([task('a'), task('b')], [machine('cheap'), machine('dear', engines=['codex'])],
+ [model('haiku', cost=1), model('gpt', engine='codex', cost=3)]))
+ result = solve(inst)
+ self.assertEqual(result.makespan, 60)
+ self.assertEqual(result.cost, 60 * 1 + 60 * 3)
+
+ def test_among_the_fastest_plans_the_cheapest_wins(self):
+ inst = load(instance([task('a'), task('b')], [machine('m', slots=2)], [model('opus', cost=3), model('sonnet', cost=2)]))
+ result = solve(inst)
+ self.assertEqual(result.makespan, 60)
+ self.assertEqual(result.cost, 240)
+ self.assertEqual({p.model for p in result.plan}, {'sonnet'})
+
+ def test_reports_proven_optimal_with_zero_gap(self):
+ inst = load(instance([task('a')], [machine('m')], [model('opus')]))
+ result = solve(inst)
+ self.assertEqual(result.status, 'OPTIMAL')
+ self.assertEqual(result.makespan_bound, result.makespan)
+ self.assertEqual(result.cost_bound, result.cost)
+ self.assertEqual(result.gap, 0.0)
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tools/scheduler/tests/test_swarm.py b/tools/scheduler/tests/test_swarm.py
new file mode 100644
index 000000000..18be48a26
--- /dev/null
+++ b/tools/scheduler/tests/test_swarm.py
@@ -0,0 +1,153 @@
+import copy
+import unittest
+
+from scheduler.instance import load
+from scheduler.swarm import ConvertError, convert
+
+POLICY = {
+ 'models': [
+ {'engine': 'claude', 'model': 'opus', 'effort': 'high', 'quality': 3, 'cost': 3, 'enabled': True},
+ {'engine': 'codex', 'model': 'default', 'effort': 'default', 'quality': 3, 'cost': 2, 'enabled': True},
+ {'engine': 'claude', 'model': 'sonnet', 'effort': 'medium', 'quality': 2, 'cost': 2, 'enabled': True},
+ {'engine': 'claude', 'model': 'haiku', 'effort': 'auto', 'quality': 1, 'cost': 1, 'enabled': False},
+ ],
+ 'floor': {'low': 1, 'medium': 2, 'high': 3},
+ 'quotaReserve': 10,
+ 'localModels': {'quality': 1, 'enabled': True},
+}
+
+
+def machine(id, name, slots, quotas, local=(), received=1793044800000):
+ return {'machineId': id, 'name': name, 'maxAgents': slots, 'engines': ['claude', 'codex', 'cursor'],
+ 'observation': {'quotas': quotas, 'localModels': list(local), 'receivedAt': received}}
+
+
+def group(id, title, engine=None, model=None, machine_id=None):
+ out = {'id': id, 'title': title, 'brief': '', 'assignment': None}
+ if engine:
+ out['assignment'] = {'status': 'done', 'configuration': {'engine': engine, 'model': model, 'effort': 'auto'},
+ 'execution': {'machineId': machine_id}}
+ return out
+
+
+# The snapshot is read at the latest observation: 2026-10-26T21:00Z (m2); m1 was observed at 20:00Z.
+# Codex reports resets in epoch seconds (1793480400 is 2026-10-31T21:00Z, 7200 minutes on), Claude as ISO strings.
+WEEKLY_67 = {'engine': 'codex', 'known': True, 'windows': [{'name': '5-hour', 'usedPercent': 20, 'resetsAt': '2026-10-26T22:00:00+00:00'},
+ {'name': 'weekly', 'usedPercent': 67, 'resetsAt': 1793480400}]}
+STATUS = {'value': {'state': {
+ 'machines': [
+ machine('m1', 'Studio', 16, [{'engine': 'claude', 'known': False, 'windows': []}, WEEKLY_67],
+ [{'grid': 'g', 'model': 'deepseek/flash', 'name': 'DeepSeek', 'kind': 'api'}]),
+ machine('m2', 'Laptop', 1, [{'engine': 'claude', 'known': True, 'windows': [
+ {'name': '5-hour', 'usedPercent': 3, 'resetsAt': '2026-10-26T20:30:00+00:00'},
+ {'name': 'weekly', 'usedPercent': 72, 'resetsAt': '2026-10-30T14:59:59+00:00'}]}, WEEKLY_67], received=1793048400000),
+ machine('m3', 'Banned', 8, [{'engine': 'claude', 'known': True, 'windows': [{'name': 'weekly', 'usedPercent': 10, 'resetsAt': 1793480400}]}]),
+ ],
+ 'rules': [{'projectId': 'p', 'rule': {'kind': 'machines', 'machineIds': ['m1', 'm2']}, 'text': 'Owner: no Banned for now'}],
+ 'conversations': [
+ group('lead', 'Lead'),
+ group('g1', 'Build', 'claude', 'opus', 'm2'),
+ group('g2', 'Review: Build', 'codex', 'gpt-6.1-sol', 'm1'),
+ group('g3', 'Smoke: DeepSeek on Laptop', 'claude', 'deepseek/flash', 'm2'),
+ group('g4', 'Docs', 'claude', 'sonnet', 'm1'),
+ ],
+}}}
+ROUTE_LOG = [
+ {'group': 'g1', 'request': {'difficulty': 'high', 'risk': 'high', 'size': 'large', 'kind': 'backend', 'why': 'b'}, 'at': '2026-10-26T10:00:00Z'},
+ {'group': '$rg', 'request': {'difficulty': 'medium', 'risk': 'low', 'size': 'small', 'kind': 'review', 'why': 'r'}, 'at': '2026-10-26T11:00:00Z'},
+]
+CONFIG = {
+ 'policy': POLICY,
+ 'assessments': {
+ 'g2': {'route': 1, 'note': 'matched by time and title'},
+ 'g4': {'estimate': {'difficulty': 'low', 'risk': 'low', 'size': 'medium', 'kind': 'docs'}, 'note': 'no route request'},
+ },
+ 'deps': {'g2': ['g1']},
+ 'exclude': {'g3': 'pinned by a person to one machine and model'},
+}
+
+
+class ConvertTest(unittest.TestCase):
+ def setUp(self):
+ self.out = convert(STATUS, ROUTE_LOG, CONFIG)
+ self.inst = load(self.out['instance'])
+
+ def test_machines_keep_their_slots_and_only_the_policy_engines(self):
+ self.assertEqual([(m.id, m.name, m.slots, m.engines) for m in self.inst.machines],
+ [('m1', 'Studio', 16, ('claude', 'codex')), ('m2', 'Laptop', 1, ('claude', 'codex'))])
+
+ def test_enabled_policy_rows_and_the_shared_api_model_become_models(self):
+ got = {m.id: (m.engine, m.cost, m.quality['default'], m.concurrency, m.subscription) for m in self.inst.models}
+ self.assertEqual(got, {'claude-opus': ('claude', 3, 3, None, True), 'codex-default': ('codex', 2, 3, None, True),
+ 'claude-sonnet': ('claude', 2, 2, None, True), 'grid-deepseek/flash': ('claude', 1, 1, 4, False)})
+
+ def test_weekly_quota_less_the_reserve_is_the_budget_and_identical_readings_share_an_account(self):
+ out = convert(STATUS, ROUTE_LOG, {**CONFIG, 'budget': 'now'})
+ got = sorted((tuple(map(tuple, a['members'])), a['budget']) for a in out['instance']['accounts'])
+ self.assertEqual(got, [((('m1', 'codex'), ('m2', 'codex')), {'weekly': 23.0}), ((('m2', 'claude'),), {'weekly': 18.0})])
+
+ def test_by_default_the_budget_is_the_start_of_the_night_with_the_actual_picks_spend_added_back(self):
+ # g1: large on Opus takes 8 x 3 / 2 = 12 from m2's Claude account; g2: small on Codex takes 1 from the shared one.
+ got = sorted((a.members, a.budget) for a in self.inst.accounts)
+ self.assertEqual(got, [((('m1', 'codex'), ('m2', 'codex')), {'weekly': 24.0}), ((('m2', 'claude'),), {'weekly': 30.0})])
+
+ def test_quota_windows_are_read_at_the_snapshot_with_resets_in_minutes_and_a_past_reset_refilled(self):
+ got = sorted((a.members, [(w.name, w.left, w.resets_in) for w in a.windows], a.reserve) for a in self.inst.accounts)
+ # Weekly left includes what the actual picks spent (start of the night); the 5-hour readings are as read.
+ self.assertEqual(got, [
+ ((('m1', 'codex'), ('m2', 'codex')), [('5-hour', 80.0, 60), ('weekly', 34.0, 7200)], 10.0),
+ ((('m2', 'claude'),), [('5-hour', 100.0, None), ('weekly', 40.0, 5400)], 10.0)])
+
+ def test_added_back_spend_never_takes_a_window_past_full(self):
+ # m2's Claude weekly: 5% used, so 95 left; adding back g1's 12 would give 107, more than a window holds.
+ status = copy.deepcopy(STATUS)
+ status['value']['state']['machines'][1]['observation']['quotas'][0]['windows'][1]['usedPercent'] = 5
+ claude = next(a for a in load(convert(status, ROUTE_LOG, CONFIG)['instance']).accounts if a.members == (('m2', 'claude'),))
+ self.assertEqual((claude.windows[1].left, claude.budget), (100.0, {'weekly': 90.0}))
+
+ def test_an_owner_rule_naming_machines_leaves_the_others_out(self):
+ self.assertNotIn('m3', [m.id for m in self.inst.machines])
+ self.assertFalse([a for a in self.inst.accounts if any(m == 'm3' for m, _ in a.members)])
+
+ def test_models_carry_the_words_of_the_routes_candidate_title(self):
+ got = {m.id: m.label for m in self.inst.models}
+ self.assertEqual(got, {'claude-opus': 'Claude opus high', 'codex-default': 'Codex default default',
+ 'claude-sonnet': 'Claude sonnet medium', 'grid-deepseek/flash': 'Claude on DeepSeek (API)'})
+
+ def test_a_task_takes_its_assessment_from_the_route_log(self):
+ t = self.inst.task('g1')
+ self.assertEqual((t.minutes, t.floor, t.kind, t.difficulty, t.spend), (180, 3, 'backend', 'high', {'5-hour': 50, 'weekly': 8}))
+
+ def test_a_hand_matched_request_and_an_estimate_are_used_and_listed_as_estimates(self):
+ self.assertEqual((self.inst.task('g2').minutes, self.inst.task('g2').floor), (20, 2))
+ self.assertEqual((self.inst.task('g4').minutes, self.inst.task('g4').floor), (60, 1))
+ self.assertEqual(sorted(e['group'] for e in self.out['estimates']), ['g2', 'g4'])
+
+ def test_dependencies_come_from_the_config(self):
+ self.assertEqual(self.inst.task('g2').deps, ('g1',))
+
+ def test_a_review_must_differ_from_the_work_it_depends_on(self):
+ self.assertEqual(self.inst.task('g2').independent_of, ('g1',))
+ self.assertEqual(self.inst.task('g1').independent_of, ())
+
+ def test_a_grid_model_is_its_own_family(self):
+ self.assertEqual(self.inst.model('grid-deepseek/flash').family, 'deepseek/flash')
+
+ def test_groups_without_work_and_excluded_groups_are_left_out(self):
+ self.assertEqual([t.id for t in self.inst.tasks], ['g1', 'g2', 'g4'])
+ self.assertEqual(self.out['excluded'], [{'group': 'g3', 'title': 'Smoke: DeepSeek on Laptop', 'reason': 'pinned by a person to one machine and model'}])
+
+ def test_actual_picks_map_each_assignment_to_its_model_row(self):
+ self.assertEqual(self.out['actual'], {'g1': ['m2', 'claude-opus'], 'g2': ['m1', 'codex-default'], 'g4': ['m1', 'claude-sonnet']})
+
+ def test_a_dependency_on_an_unknown_group_is_refused(self):
+ with self.assertRaisesRegex(ConvertError, 'g2 depends on g9'):
+ convert(STATUS, ROUTE_LOG, {**CONFIG, 'deps': {'g2': ['g9']}})
+
+ def test_a_group_with_no_assessment_is_refused(self):
+ with self.assertRaisesRegex(ConvertError, 'no assessment for g4'):
+ convert(STATUS, ROUTE_LOG, {**CONFIG, 'assessments': {'g2': CONFIG['assessments']['g2']}})
+
+
+if __name__ == '__main__':
+ unittest.main()