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.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
Super Tab routing v1: route each delegation, log it, and let a person change it (#1424)
0xken156fc7e28c3c1f
diff --git a/backend/integration/superTabs.test.ts b/backend/integration/superTabs.test.tsindex d99c1d595..55e9e13d7 100644--- a/backend/integration/superTabs.test.ts+++ b/backend/integration/superTabs.test.ts@@ -13,6 +13,7 @@ import { superTabRoutes } from '../src/routes/superTabs.js'import { errorHandler } from '../src/middlewares/errorHandler.js'import type { Command } from '../src/superTabs/commands.js'import { nextMachineShareGrants } from '../src/lib/machineSharePolicy.js'+import { DEFAULT_ROUTING_POLICY } from '../src/superTabs/routingPolicy.js'// A fresh loopback replica set, created here. This suite never reads DATABASE_URL or an existing database.let replica: MongoMemoryReplSet@@ -535,4 +536,146 @@ describe('Super Tabs on a real Mongo replica set', () => {await db.user.update({ where: { id: owner.sub }, data: { email: owner.email } })}})++ it('stores the account routing policy with revisions and merges the owner policy into each tab', async () => {+ const initial = await store.accountPolicy(owner)+ expect(initial).toEqual({ policy: DEFAULT_ROUTING_POLICY, revision: 0, isDefault: true })+ const saved = await store.saveAccountPolicy(owner, 0, { ...DEFAULT_ROUTING_POLICY, quotaReserve: 30 })+ expect(saved.revision).toBe(1)+ await expect(store.saveAccountPolicy(owner, 0, DEFAULT_ROUTING_POLICY)).rejects.toMatchObject({ code: 'REVISION_CHANGED' })+ const { tab, lead } = await fixture()+ await run(tab, { type: 'tab.routingPolicy', policy: { notes: 'Prefer remote-1.' } })+ await invite(tab, 'viewer')+ // A member reads the owner's policy, never their own account's.+ await store.saveAccountPolicy(peer, 0, { ...DEFAULT_ROUTING_POLICY, quotaReserve: 5 })+ for (const [user, asAgent] of [[owner, undefined], [peer, undefined], [host, lead]] as const) {+ const effective = await store.tabPolicy(user, tab, asAgent)+ expect(effective.policy.quotaReserve).toBe(30)+ expect(effective.policy.notes).toBe('Prefer remote-1.')+ expect(effective.overridden).toEqual(['notes'])+ // The owner's account value, so a field reset to the account default can show it.+ expect(effective.account).toEqual({ ...DEFAULT_ROUTING_POLICY, quotaReserve: 30 })+ }+ const response = await app.inject({ url: `/api/super-tabs/${tab}/routing-policy`, headers: { authorization: `Bearer ${peer.sub}` } })+ expect(response.statusCode).toBe(200)+ expect((await app.inject({ url: '/api/super-tabs/routing-policy', headers: { authorization: `Bearer ${owner.sub}` } })).statusCode).toBe(200)+ })++ it('lets exactly one of two concurrent saves win the same revision', async () => {+ const results = await Promise.allSettled([host, host].map((user, i) =>+ store.saveAccountPolicy(user, 0, { ...DEFAULT_ROUTING_POLICY, quotaReserve: 10 + i })))+ expect(results.filter(r => r.status === 'fulfilled')).toHaveLength(1)+ expect((await store.accountPolicy(host)).revision).toBe(1)+ })++ it('records, supersedes and lets a person change a route decision; a closed one refuses', async () => {+ const { tab, lead } = await fixture()+ const decision = { assessment: { difficulty: 'medium', risk: 'low', why: 'A small API change.' },+ candidates: [+ { id: 'c0', kind: 'member', agentId: lead, machineId: 'test-host', engine: 'claude', model: 'sonnet', effort: 'medium', quality: 2, cost: 2, title: 'Lead · Claude sonnet medium · test-host', label: 'Member Lead' },+ { id: 'c1', kind: 'new', machineId: 'test-host', engine: 'claude', model: 'opus', effort: 'high', quality: 3, cost: 3, title: 'New agent · Claude opus high · test-host', label: 'New agent' },+ ], excluded: [{ title: 'New agent · Codex · test-host', reason: 'The selected agent engine is not installed on this machine.' }],+ floor: 2, notes: false, pick: 'c0', via: 'order', fallback: 'unsure', p: null, belowFloor: false, why: 'Jev unsure; first in the policy order.' }+ const first = (await run(tab, { type: 'route.record', conversationId: 'lead', decision } as Command, host, lead)).result.routeDecisionId as string+ const second = (await run(tab, { type: 'route.record', conversationId: 'lead', decision } as Command, host, lead)).result.routeDecisionId as string+ expect((await store.routeDecision(owner, tab, first)).outcome).toBe('superseded')+ const rows = (await store.messages(owner, tab, 'lead', {})).messages+ expect(rows.at(-1)).toMatchObject({ text: expect.stringContaining('"A small API change."'),+ source: { kind: 'route', decisionId: second, via: 'order', fallback: 'unsure', why: 'A small API change.' } })+ await expect(run(tab, { type: 'route.override', decisionId: first, candidateId: 'c1', reason: 'Needs Opus.' } as Command))+ .rejects.toMatchObject({ code: 'ROUTE_CLOSED' })+ await run(tab, { type: 'route.override', decisionId: second, candidateId: 'c1', reason: 'Needs Opus.' } as Command)+ expect((await store.routeDecision(owner, tab, second)).override).toMatchObject({ by: 'person', candidateId: 'c1' })+ expect((await store.deliveries(host, tab, lead)).length).toBeGreaterThan(0)+ await invite(tab, 'viewer')+ await expect(run(tab, { type: 'route.override', decisionId: second, candidateId: 'c0', reason: 'No.' } as Command, peer))+ .rejects.toMatchObject({ status: 403 })+ expect((await store.routeDecisions(owner, tab)).map(d => d.id)).toEqual([second, first])+ const response = await app.inject({ url: `/api/super-tabs/${tab}/route-decisions/${second}`, headers: { authorization: `Bearer ${peer.sub}` } })+ expect(response.statusCode).toBe(200)+ })++ it('corrects the log to the model that ran when the routed switch failed, and reads the times of one decision', async () => {+ const { tab, lead } = await fixture()+ const decision = { assessment: { difficulty: 'low', risk: 'low', why: 'Docs.' },+ candidates: [{ id: 'c0', kind: 'new', machineId: 'test-host', engine: 'claude', model: 'haiku', effort: 'auto', quality: 1, cost: 1, title: 'New agent', label: 'New agent' }],+ excluded: [], floor: 1, notes: false, pick: 'c0', via: 'only', p: null, belowFloor: false, why: 'Only candidate.' }+ const routeDecisionId = (await run(tab, { type: 'route.record', conversationId: 'lead', decision } as Command, host, lead)).result.routeDecisionId as string+ const request = { conversationId: 'lead', machineId: 'test-host', engine: 'claude', model: 'haiku', effort: 'auto', name: 'Builder', cwd: '/fixture/repo', worktree: false,+ requirements: { memoryBytes: 0, diskBytes: 0, maxCpuPercent: 100, tools: [], devices: [], quotaRequired: false } }+ const startId = (await run(tab, { type: 'agent.start', request, routeDecisionId } as Command, host, lead)).result.startId as string+ await expect(run(tab, { type: 'route.modelResult', decisionId: routeDecisionId, startId: 'other', model: 'sonnet', effort: 'auto' } as Command, host, lead))+ .rejects.toMatchObject({ code: 'ROUTE_MISMATCH' })+ const before = (await store.messages(owner, tab, 'lead', {})).messages.length+ await run(tab, { type: 'route.modelResult', decisionId: routeDecisionId, startId, model: 'sonnet', effort: 'auto' } as Command, host, lead)+ expect((await store.messages(owner, tab, 'lead', {})).messages).toHaveLength(before)+ const read = async () => (await app.inject({ url: `/api/super-tabs/${tab}/route-decisions/${routeDecisionId}`, headers: { authorization: `Bearer ${owner.sub}` } })).json().data+ expect(await read()).toMatchObject({ outcome: null, outcomeAt: null, createdAt: expect.any(String),+ final: { kind: 'new', startId, model: 'sonnet', effort: 'auto', requested: { model: 'haiku', effort: 'auto' } } })+ })++ it('names the failing field when a command is invalid', async () => {+ const { tab } = await fixture()+ const command = { type: 'agent.start', request: { conversationId: 'lead', machineId: 'test-host', engine: 'claude', name: 'Builder', cwd: '/fixture/repo', worktree: false } }+ const response = await app.inject({ method: 'POST', url: `/api/super-tabs/${tab}/commands`, headers: { authorization: `Bearer ${owner.sub}` },+ payload: { operationId: randomUUID(), command } })+ expect(response.statusCode).toBe(400)+ expect(response.json().error.message).toContain('command.request.requirements')+ })++ it('closes a linked decision with the assignment outcome', async () => {+ const { tab, lead } = await fixture()+ const group = (await run(tab, { type: 'conversation.create', title: 'Build', brief: 'Build it.', checks: [{ description: 'Tests pass', independent: false }] })).result.conversationId as string+ const worker = (await run(tab, { type: 'agent.add', conversationId: group, machineId: 'test-host', harnessId: randomUUID(),+ name: 'Builder', configuration: config, lead: false })).result.agentId as string+ const decision = { assessment: { difficulty: 'low', risk: 'low', why: 'Small.' },+ candidates: [{ id: 'c0', kind: 'member', agentId: worker, machineId: 'test-host', engine: 'claude', model: 'sonnet', effort: 'medium', quality: 2, cost: 2, title: 'Builder', label: 'Member Builder' }],+ excluded: [], floor: 1, notes: false, pick: 'c0', via: 'only', p: null, belowFloor: false, why: 'Only candidate.' }+ const routeDecisionId = (await run(tab, { type: 'route.record', conversationId: group, decision } as Command, host, lead)).result.routeDecisionId as string+ const assignmentId = (await run(tab, { type: 'work.assign', conversationId: group, agentId: worker, routeDecisionId } as Command, host, lead)).result.assignmentId as string+ expect(await store.routeDecision(owner, tab, routeDecisionId)).toMatchObject({ assignmentId, final: { kind: 'member', agentId: worker } })+ await store.stopped(host, tab, assignmentId, 'native-stop-receipt')+ expect((await store.routeDecision(owner, tab, routeDecisionId)).outcome).toBe('stopped')+ })++ it('keeps a decision open when the Lead stops its work to hand over to the candidate a person chose', async () => {+ const { tab, lead } = await fixture()+ const group = (await run(tab, { type: 'conversation.create', title: 'Build', brief: 'Build it.', checks: [{ description: 'Tests pass', independent: false }] })).result.conversationId as string+ const add = async (name: string) => (await run(tab, { type: 'agent.add', conversationId: group, machineId: 'test-host', harnessId: randomUUID(),+ name, configuration: config, lead: false })).result.agentId as string+ const picked = await add('Picked'), chosen = await add('Chosen')+ const candidate = (id: string, agentId: string, title: string) => ({ id, kind: 'member', agentId, machineId: 'test-host', engine: 'codex',+ model: 'fixture-model', effort: 'high', quality: 2, cost: 2, title, label: `Member ${title}` })+ const decision = { assessment: { difficulty: 'low', risk: 'low', why: 'Small.' },+ candidates: [candidate('c0', picked, 'Picked'), candidate('c1', chosen, 'Chosen')],+ excluded: [], floor: 1, notes: false, pick: 'c0', via: 'jev', p: 0.9, belowFloor: false, why: 'Jev chose Picked.' }+ const id = (await run(tab, { type: 'route.record', conversationId: group, decision } as Command, host, lead)).result.routeDecisionId as string+ const first = (await run(tab, { type: 'work.assign', conversationId: group, agentId: picked, routeDecisionId: id } as Command, host, lead)).result.assignmentId as string+ await run(tab, { type: 'route.override', decisionId: id, candidateId: 'c1', reason: 'Chosen knows this code.' } as Command)+ // The person's Change reaches the Lead as a message to act on.+ const rows = (await store.messages(owner, tab, group, {})).messages+ const change = rows.at(-1)!+ expect(change).toMatchObject({ source: { kind: 'route-override', by: 'person' }, text: expect.stringContaining('chose Chosen instead of Picked') })+ expect((await store.deliveries(host, tab, lead)).map(d => d.messageId)).toContain(change.id)+ // The first attempt is still running: no second link may overwrite its final.+ await expect(run(tab, { type: 'work.assign', conversationId: group, agentId: chosen, routeDecisionId: id } as Command, host, lead))+ .rejects.toMatchObject({ code: 'WORK_ACTIVE' })+ await store.stopped(host, tab, first, 'handover-stop-receipt')+ expect(await store.routeDecision(owner, tab, id)).toMatchObject({ outcome: null, assignmentId: null, final: null })+ const second = (await run(tab, { type: 'work.assign', conversationId: group, agentId: chosen, routeDecisionId: id } as Command, host, lead)).result.assignmentId as string+ expect(await store.routeDecision(owner, tab, id)).toMatchObject({ outcome: null, assignmentId: second, final: { kind: 'member', agentId: chosen } })+ const check = (await store.read(owner, tab)).state.conversations.find(c => c.id === group)!.checks[0]!.id+ await run(tab, { type: 'work.check', conversationId: group, assignmentId: second, checkId: check, passed: true, evidence: 'ok' } as Command, host, chosen)+ await run(tab, { type: 'work.status', conversationId: group, assignmentId: second, status: 'done', result: 'Built.' } as Command, host, chosen)+ expect(await store.routeDecision(owner, tab, id)).toMatchObject({ outcome: 'done', assignmentId: second })+ })++ it('limits route records to 30 per tab per hour', async () => {+ const { tab, lead } = await fixture()+ const decision = { assessment: { difficulty: 'low', risk: 'low', why: 'Docs.' },+ candidates: [{ id: 'c0', kind: 'new', machineId: 'test-host', engine: 'claude', model: 'haiku', effort: 'auto', quality: 1, cost: 1, title: 'New agent', label: 'New agent' }],+ excluded: [], floor: 1, notes: false, pick: 'c0', via: 'only', p: null, belowFloor: false, why: 'Only candidate.' }+ for (let i = 0; i < 30; i++) await run(tab, { type: 'route.record', conversationId: 'lead', decision } as Command, host, lead)+ await expect(run(tab, { type: 'route.record', conversationId: 'lead', decision } as Command, host, lead)).rejects.toMatchObject({ code: 'RATE_LIMITED', status: 429 })+ })})diff --git a/backend/prisma/schema.prisma b/backend/prisma/schema.prismaindex c3aa69ccb..0d45ba980 100644--- a/backend/prisma/schema.prisma+++ b/backend/prisma/schema.prisma@@ -1077,6 +1077,18 @@ model SuperTabRun {createdAt DateTime @default(now())}+// One routing policy document per account and environment (superTabs/routingPolicy.ts).+model RoutingPolicy {+ id String @id @map("_id")+ userId String+ autonomousEnv String+ revision Int @default(0)+ policy Json+ updatedAt DateTime @updatedAt++ @@unique([userId, autonomousEnv])+}+model SuperTabAttempt {id String @id @map("_id")tabId String@@ -1087,6 +1099,24 @@ model SuperTabAttempt {@@index([tabId, conversationId, createdAt])}+/// One `harness super-tab route` decision (superTabs/routeRecord.ts). Pruned after 90 days on write.+model SuperTabRouteDecision {+ id String @id @map("_id")+ tabId String+ conversationId String+ record Json+ final Json?+ override Json?+ assignmentId String?+ outcome String?+ outcomeAt DateTime?+ createdAt DateTime @default(now())++ @@index([tabId, createdAt])+ @@index([tabId, conversationId, outcome])+ @@index([tabId, assignmentId])+}+model SuperTabStopReceipt {id String @id @map("_id")tabId Stringdiff --git a/backend/src/middlewares/validation.ts b/backend/src/middlewares/validation.tsindex 212bc931d..494cc2495 100644--- a/backend/src/middlewares/validation.ts+++ b/backend/src/middlewares/validation.ts@@ -2,11 +2,14 @@ import type { FastifyReply, FastifyRequest } from 'fastify'import { z } from 'zod'import { ValidationError } from '../errors/index.js'-export function validateBody<T extends z.ZodTypeAny>(schema: T) {+/** `named` puts the failing field's path before zod's message, which alone ("expected number, received undefined") does not say which one. */+export function validateBody<T extends z.ZodTypeAny>(schema: T, options: { named?: boolean } = {}) {return async (request: FastifyRequest<{ Body: z.infer<T> }>, _reply: FastifyReply): Promise<void> => {const result = schema.safeParse(request.body)if (!result.success) {- throw new ValidationError(result.error.issues[0]?.message || 'Invalid request body')+ const issue = result.error.issues[0]+ const field = options.named && issue?.path.length ? `${issue.path.join('.')}: ` : ''+ throw new ValidationError(issue?.message ? `${field}${issue.message}` : 'Invalid request body')}request.body = result.data as z.infer<T>}diff --git a/backend/src/routes/superTabs.ts b/backend/src/routes/superTabs.tsindex 46e4e4b1c..4bfea0688 100644--- a/backend/src/routes/superTabs.ts+++ b/backend/src/routes/superTabs.ts@@ -6,6 +6,7 @@ import { sendError, sendSuccess } from '../utils/response.js'import { operationSchema } from '../superTabs/commands.js'import { SuperTabError } from '../superTabs/model.js'import { SuperTabStore } from '../superTabs/store.js'+import { routingPolicySchema } from '../superTabs/routingPolicy.js'import { nativeEventSchema, openNativeSchema } from '../superTabs/native.js'const id = z.string().min(1).max(160).regex(/^[A-Za-z0-9_-]+$/)@@ -20,6 +21,7 @@ const messageParams = tabParams.extend({ conversationId: id })const messageQuery = agentQuery.extend({ after: z.coerce.number().int().nonnegative().safe().optional(),before: z.coerce.number().int().nonnegative().safe().optional(), messageId: id.optional() }).refine(q => [q.after, q.before, q.messageId].filter(value => value !== undefined).length <= 1, 'Choose one message cursor or exact message.')+const decisionParams = tabParams.extend({ decisionId: id })const hostParams = z.object({ machineId: id })const deliveryParams = tabParams.extend({ agentId: id })const deliveryActionParams = deliveryParams.extend({ deliveryId: id })@@ -27,6 +29,7 @@ const deliveryAction = z.discriminatedUnion('type', [z.object({ type: z.literal('claim'), claimId: id }).strict(),z.object({ type: z.literal('ack'), claimId: id, receipt: z.string().min(1).max(2000), uncertain: z.boolean() }).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()async function respond(reply: FastifyReply, action: () => Promise<unknown>) {@@ -48,6 +51,12 @@ export async function superTabRoutes(app: FastifyInstance, options: { store?: Suapp.post<{ Params: z.infer<typeof nativeParams>; Body: z.infer<typeof nativeEventSchema> }>('/api/super-tabs/:tabId/native/:contextId',{ preHandler: [validateParams(nativeParams), validateBody(nativeEventSchema)] },(req, reply) => respond(reply, () => store.native.append(req.user!, req.params.tabId, req.params.contextId, req.body)))+ app.get('/api/super-tabs/routing-policy', (req, reply) => respond(reply, () => store.accountPolicy(req.user!)))+ app.post<{ Body: z.infer<typeof savePolicy> }>('/api/super-tabs/routing-policy', { preHandler: validateBody(savePolicy) },+ (req, reply) => respond(reply, () => store.saveAccountPolicy(req.user!, req.body.revision, req.body.policy)))+ app.get<{ Params: z.infer<typeof tabParams>; Querystring: z.infer<typeof agentQuery> }>('/api/super-tabs/:tabId/routing-policy',+ { preHandler: [validateParams(tabParams), validateQuery(agentQuery)] },+ (req, reply) => respond(reply, () => store.tabPolicy(req.user!, req.params.tabId, req.query.asAgentId)))app.get<{ Querystring: z.infer<typeof listQuery> }>('/api/super-tabs', { preHandler: validateQuery(listQuery) },(req, reply) => respond(reply, () => store.list(req.user!, req.query.after)))app.post<{ Body: z.infer<typeof create> }>('/api/super-tabs', { preHandler: validateBody(create) },@@ -61,7 +70,7 @@ export async function superTabRoutes(app: FastifyInstance, options: { store?: Su{ preHandler: [validateParams(tabParams), validateQuery(agentQuery)] },(req, reply) => respond(reply, () => store.read(req.user!, req.params.tabId, req.query.asAgentId)))app.post<{ Params: z.infer<typeof tabParams>; Body: z.infer<typeof operation> }>('/api/super-tabs/:tabId/commands',- { preHandler: [validateParams(tabParams), validateBody(operation)] },+ { preHandler: [validateParams(tabParams), validateBody(operation, { named: true })] },(req, reply) => respond(reply, () => store.execute(req.user!, req.params.tabId,{ operationId: req.body.operationId, command: req.body.command }, req.body.asAgentId)))app.get<{ Params: z.infer<typeof startParams>; Querystring: z.infer<typeof agentQuery> }>('/api/super-tabs/:tabId/starts/:startId',@@ -70,6 +79,12 @@ export async function superTabRoutes(app: FastifyInstance, options: { store?: Suapp.get<{ Params: z.infer<typeof messageParams>; Querystring: z.infer<typeof messageQuery> }>('/api/super-tabs/:tabId/conversations/:conversationId/messages',{ preHandler: [validateParams(messageParams), validateQuery(messageQuery)] },(req, reply) => respond(reply, () => store.messages(req.user!, req.params.tabId, req.params.conversationId, req.query, req.query.asAgentId)))+ app.get<{ Params: z.infer<typeof tabParams>; Querystring: z.infer<typeof agentQuery> }>('/api/super-tabs/:tabId/route-decisions',+ { preHandler: [validateParams(tabParams), validateQuery(agentQuery)] },+ (req, reply) => respond(reply, () => store.routeDecisions(req.user!, req.params.tabId, req.query.asAgentId)))+ app.get<{ Params: z.infer<typeof decisionParams>; Querystring: z.infer<typeof agentQuery> }>('/api/super-tabs/:tabId/route-decisions/:decisionId',+ { preHandler: [validateParams(decisionParams), validateQuery(agentQuery)] },+ (req, reply) => respond(reply, () => store.routeDecision(req.user!, req.params.tabId, req.params.decisionId, req.query.asAgentId)))app.get<{ Params: z.infer<typeof deliveryParams> }>('/api/super-tabs/:tabId/agents/:agentId/deliveries',{ preHandler: validateParams(deliveryParams) },(req, reply) => respond(reply, () => store.deliveries(req.user!, req.params.tabId, req.params.agentId)))diff --git a/backend/src/superTabs/commands.test.ts b/backend/src/superTabs/commands.test.tsindex c21f19b7d..265943612 100644--- a/backend/src/superTabs/commands.test.ts+++ b/backend/src/superTabs/commands.test.ts@@ -1,6 +1,7 @@import { describe, expect, it } from 'vitest'import { applyCommand, commandSchema, type Command, type CommandContext } from './commands.js'import { createSuperTab, visibleState, type Actor, type AgentConfiguration } from './model.js'+import type { RouteDecision } from './routeRecord.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]' }@@ -216,3 +217,220 @@ it('starts only in the chosen conversation, captures authority, and never assignf.run({ type: 'tab.pause', paused: true })expect(() => f.run({ type: 'agent.start', request }, actor, { contribution })).toThrow('paused')})++describe('tab.routingPolicy', () => {+ it('lets only the owner set or clear the tab override', () => {+ const f = fixture()+ f.run({ type: 'tab.routingPolicy', policy: { quotaReserve: 25 } })+ expect(f.state.routingPolicy).toEqual({ quotaReserve: 25 })+ f.invite('collaborator')+ expect(() => f.run({ type: 'tab.routingPolicy', policy: { notes: 'x' } }, peer)).toThrow('Only the Super Tab owner')+ f.run({ type: 'tab.routingPolicy', policy: null })+ expect(f.state.routingPolicy).toBeUndefined()+ })+ it('refuses an invalid override', () => {+ const f = fixture()+ expect(() => commandSchema.parse({ type: 'tab.routingPolicy', policy: { quotaReserve: 99 } })).toThrow()+ expect(() => f.run({ type: 'tab.routingPolicy', policy: { quotaReserve: 99 } } as never)).toThrow()+ })+})++const candidate = (id: string, patch: Record<string, unknown> = {}) => ({ id, kind: 'new', machineId: 'machine', engine: 'claude',+ model: 'opus', effort: 'high', quality: 3, cost: 3, title: `Title ${id}`, label: `Label ${id}`, ...patch })+const record = (patch: Record<string, unknown> = {}) => ({ assessment: { difficulty: 'high', risk: 'low', why: 'Schema change.' },+ candidates: [candidate('c0'), candidate('c1', { model: 'sonnet', quality: 2, cost: 2 })], excluded: [], floor: 3, notes: false,+ pick: 'c0', via: 'jev', p: 0.82, belowFloor: false, why: 'Highest quality within quota.', ...patch })+/** The base fixture plus a coordinating Lead and a worker, both on one host. */+function routed() {+ const f = fixture()+ const lead = f.add('lead', 'owner', 'lead', true), worker = f.add('worker')+ const agentActor = (agentId: string): Actor => ({ kind: 'agent', agentId, machineOwnerId: 'host-owner' })+ const define = (group: string) => f.run({ type: 'work.define', conversationId: group, brief: 'Build it.', checks: [{ description: 'Tests pass.', independent: false }] })+ /** Records a completed native start for an agent, as the decision's `new` final refers to it. */+ const startedFor = (agentId: string) => {+ const member = f.state.agents.find(a => a.id === agentId)!+ f.state.starts ??= []+ f.state.starts.push({ id: `start-${agentId}`, harnessId: member.harnessId, request: { machineId: member.machineId } } as never)+ return `start-${agentId}`+ }+ return { ...f, get state() { return f.state }, lead, worker, define, startedFor, contribution: { machineOwnerId: 'host-owner', contributorId: 'owner' },+ leadActor: agentActor(lead), workerActor: agentActor(worker) }+}++describe('route.record and route.override', () => {+ it('records a lead decision as a route message with its id', () => {+ const f = routed()+ const effects = f.run({ type: 'route.record', conversationId: 'lead', decision: record() } as Command, f.leadActor, { recentRoutes: 0 })+ expect(effects.result.routeDecisionId).toBeTruthy()+ expect(effects.routeDecisions).toEqual([{ op: 'create', id: effects.result.routeDecisionId, conversationId: 'lead', record: expect.objectContaining({ pick: 'c0' }) }])+ expect(effects.messages[0]).toMatchObject({ text: 'Routed to Title c0 — Jev 82% · "Schema change."',+ source: { kind: 'route', decisionId: effects.result.routeDecisionId, via: 'jev', p: 0.82, belowFloor: false,+ pick: { id: 'c0', title: 'Title c0' }, alternatives: [{ id: 'c1', title: 'Title c1' }] } })+ })+ it('refuses a pick outside the candidates, a non-lead agent and a busy hour', () => {+ const f = routed()+ const route = (decision: unknown, actor: Actor, context: Partial<CommandContext>) =>+ f.run({ type: 'route.record', conversationId: 'lead', decision } as Command, actor, context)+ expect(() => route(record({ pick: 'c5' }), f.leadActor, { recentRoutes: 0 })).toThrow()+ expect(() => route(record(), f.workerActor, { recentRoutes: 0 })).toThrow('coordinating lead')+ expect(() => route(record(), f.leadActor, { recentRoutes: 30 })).toThrow('30 tasks')+ })+ it('lets a writer change an open decision with a reason and tells the lead', () => {+ const f = routed()+ const decision = { id: 'd1', conversationId: 'lead', record: record(), final: null, override: null, assignmentId: null, outcome: null } as unknown as RouteDecision+ const effects = f.run({ type: 'route.override', decisionId: 'd1', candidateId: 'c1', reason: 'Opus quota is needed elsewhere.' }, undefined, { routeDecision: decision })+ expect(effects.routeDecisions).toEqual([{ op: 'override', id: 'd1', override: expect.objectContaining({ by: 'person', candidateId: 'c1', reason: 'Opus quota is needed elsewhere.' }) }])+ expect(effects.messages[0]!.recipients).toEqual([f.lead])+ expect(effects.messages[0]!.text).toContain('chose Title c1 instead of Title c0. Hand this task over to it. Reason: Opus quota is needed elsewhere.')+ expect(effects.messages[0]!.source).toEqual({ kind: 'route-override', decisionId: 'd1', by: 'person' })+ })+ it('refuses an override by an agent, of a closed decision, or of the current choice', () => {+ const f = routed()+ const open = { id: 'd1', conversationId: 'lead', record: record(), final: null, override: null, assignmentId: null, outcome: null } as unknown as RouteDecision+ const command = { type: 'route.override', decisionId: 'd1', candidateId: 'c1', reason: 'Because.' } as const+ expect(() => f.run(command, f.leadActor, { routeDecision: open })).toThrow('A person')+ expect(() => f.run(command, undefined, { routeDecision: { ...open, outcome: 'superseded' } })).toThrow('no longer open')+ expect(() => f.run({ ...command, candidateId: 'c0' }, undefined, { routeDecision: open })).toThrow('already')+ })+})++describe('route.modelResult', () => {+ const started = (patch: Record<string, unknown> = {}) => ({ id: 'd1', conversationId: 'lead', record: record(),+ final: { kind: 'new', startId: 'start-1', machineId: 'machine', engine: 'claude', model: 'opus', effort: 'high' },+ override: null, assignmentId: null, outcome: null, ...patch }) as unknown as RouteDecision+ const result = { type: 'route.modelResult', decisionId: 'd1', startId: 'start-1', model: 'sonnet', effort: 'auto' } as const++ it('records what the agent actually runs and keeps the routed model as requested, without a message', () => {+ const f = routed()+ const effects = f.run(result, f.leadActor, { routeDecision: started() })+ expect(effects.routeDecisions).toEqual([{ op: 'final', id: 'd1', final: { kind: 'new', startId: 'start-1', machineId: 'machine', engine: 'claude',+ model: 'sonnet', effort: 'auto', requested: { model: 'opus', effort: 'high' } } }])+ expect(effects.messages).toEqual([])+ })+ it('keeps the first requested values when it is corrected again', () => {+ const f = routed()+ const final = { kind: 'new', startId: 'start-1', machineId: 'machine', engine: 'claude', model: 'sonnet', effort: 'auto', requested: { model: 'opus', effort: 'high' } }+ const effects = f.run({ ...result, model: 'haiku' }, f.leadActor, { routeDecision: started({ final }) })+ expect(effects.routeDecisions[0]).toMatchObject({ final: { model: 'haiku', requested: { model: 'opus', effort: 'high' } } })+ })+ it('is for the coordinating Lead only', () => {+ const f = routed()+ expect(() => f.run(result, f.workerActor, { routeDecision: started() })).toThrow('coordinating lead')+ })+ it('refuses a closed decision, a member final, no final and another start', () => {+ const f = routed()+ const run = (decision: RouteDecision) => () => f.run(result, f.leadActor, { routeDecision: decision })+ expect(run(started({ outcome: 'done' }))).toThrow('no longer open')+ expect(run(started({ final: { kind: 'member', agentId: f.worker, machineId: 'machine' } }))).toThrow(expect.objectContaining({ code: 'ROUTE_MISMATCH' }))+ expect(run(started({ final: null }))).toThrow(expect.objectContaining({ code: 'ROUTE_MISMATCH' }))+ expect(run(started({ final: { kind: 'new', startId: 'start-2', machineId: 'machine', engine: 'claude', model: 'opus', effort: 'high' } })))+ .toThrow(expect.objectContaining({ code: 'ROUTE_MISMATCH' }))+ })+ it('bounds the model and effort', () => {+ expect(() => commandSchema.parse({ ...result, model: 'm'.repeat(201) })).toThrow()+ expect(() => commandSchema.parse({ ...result, effort: 'e'.repeat(81) })).toThrow()+ })+ it('lets the assignment still match the routed pick after the switch failed', () => {+ const f = routed()+ f.define('lead')+ const final = { kind: 'new', startId: f.startedFor(f.worker), machineId: 'machine', engine: 'claude', model: 'sonnet', effort: 'auto', requested: { model: 'opus', effort: 'high' } }+ const effects = f.run({ type: 'work.assign', conversationId: 'lead', agentId: f.worker, routeDecisionId: 'd1' }, f.leadActor, { routeDecision: started({ final }) })+ expect(effects.routeDecisions).toEqual([{ op: 'final', id: 'd1', final, assignmentId: effects.result.assignmentId }])+ })+})++describe('decisions linked to work', () => {+ const open = (patch: Record<string, unknown> = {}) => ({ id: 'd1', conversationId: 'lead', record: record(), final: null, override: null, assignmentId: null, outcome: null, ...patch }) as unknown as RouteDecision++ it('links an assignment of the picked member, and needs a reason otherwise', () => {+ const f = routed()+ const member = record({ candidates: [candidate('c0', { kind: 'member', agentId: f.worker }), candidate('c1')], pick: 'c0' })+ f.define('lead')+ const linked = f.run({ type: 'work.assign', conversationId: 'lead', agentId: f.worker, routeDecisionId: 'd1' }, f.leadActor, { routeDecision: open({ record: member }) })+ expect(linked.routeDecisions).toEqual([{ op: 'final', id: 'd1', final: { kind: 'member', agentId: f.worker, machineId: expect.any(String) }, assignmentId: linked.result.assignmentId }])+ })++ it('gives the policy-order row the Lead’s reason and why the order decided', () => {+ const f = routed()+ const order = (patch: Record<string, unknown>) => f.run({ type: 'route.record', conversationId: 'lead', decision: record({ via: 'order', p: null, ...patch }) } as Command,+ f.leadActor, { recentRoutes: 0 }).messages[0]!+ expect(order({ fallback: 'unavailable', why: 'Jev unavailable (BUSY); first in the policy order.' })).toMatchObject({+ text: 'Routed to Title c0 — by policy order · "Schema change."', source: { why: 'Schema change.', fallback: 'unavailable' } })+ expect(order({ fallback: 'unsure' }).source).toMatchObject({ fallback: 'unsure' })+ expect(order({}).source).not.toHaveProperty('fallback')+ expect(() => order({ fallback: 'sleepy' })).toThrow()+ })++ it('refuses a second link while the first assignment of the decision is still running', () => {+ const f = routed()+ f.define('lead')+ const running = f.run({ type: 'work.assign', conversationId: 'lead', agentId: f.worker }, f.leadActor)+ const assignmentId = running.result.assignmentId as string+ const request = { conversationId: 'lead', machineId: 'machine', engine: 'claude', model: 'opus', effort: 'high', name: 'Builder', cwd: '/repo', worktree: false,+ requirements: { memoryBytes: 0, diskBytes: 0, maxCpuPercent: 100, tools: [], devices: [], quotaRequired: false } }+ expect(() => f.run({ type: 'agent.start', request, routeDecisionId: 'd1' }, f.leadActor, { routeDecision: open({ assignmentId }), contribution: f.contribution }))+ .toThrow('already has running work')+ // Once that work ended, the decision may be linked again.+ f.state.conversations.find(c => c.id === 'lead')!.assignment!.status = 'stopped'+ expect(f.run({ type: 'agent.start', request, routeDecisionId: 'd1' }, f.leadActor, { routeDecision: open({ assignmentId }), contribution: f.contribution }).routeDecisions).toHaveLength(1)+ })++ it('needs a reason when a start differs from the pick, and tells the group about it', () => {+ const f = routed()+ const request = { conversationId: 'lead', machineId: 'machine', engine: 'claude', model: 'sonnet', effort: 'high', name: 'Builder', cwd: '/repo', worktree: false,+ requirements: { memoryBytes: 0, diskBytes: 0, maxCpuPercent: 100, tools: [], devices: [], quotaRequired: false } }+ const start = (extra: Record<string, unknown> = {}) => f.run({ type: 'agent.start', request, routeDecisionId: 'd1', ...extra } as Command, f.leadActor, { routeDecision: open(), contribution: f.contribution })+ expect(() => start()).toThrow(expect.objectContaining({ code: 'OVERRIDE_REASON_REQUIRED' }))+ const effects = start({ overrideReason: 'Sonnet is enough here.' })+ expect(effects.routeDecisions[0]).toMatchObject({ op: 'final', override: { by: 'lead', reason: 'Sonnet is enough here.' } })+ expect(effects.messages[0]).toMatchObject({ text: 'Lead started Builder instead of Title c0. Reason: Sonnet is enough here.',+ source: { kind: 'route-override', decisionId: 'd1', by: 'lead' } })+ })++ it('refuses a mismatch without a reason and records the lead override with one', () => {+ const f = routed()+ f.define('lead')+ expect(() => f.run({ type: 'work.assign', conversationId: 'lead', agentId: f.worker, routeDecisionId: 'd1' }, f.leadActor, { routeDecision: open() }))+ .toThrow('reason')+ const effects = f.run({ type: 'work.assign', conversationId: 'lead', agentId: f.worker, routeDecisionId: 'd1', overrideReason: 'This worker already has the context.' }, f.leadActor, { routeDecision: open() })+ expect(effects.routeDecisions[0]).toMatchObject({ op: 'final', override: { by: 'lead', reason: 'This worker already has the context.' } })+ expect(effects.messages.some(m => m.source?.kind === 'route-override')).toBe(true)+ expect(effects.result.messageId).toBe(effects.messages[0]!.id)+ })++ it('refuses a decision from another group', () => {+ const f = routed()+ f.define('lead')+ expect(() => f.run({ type: 'work.assign', conversationId: 'lead', agentId: f.worker, routeDecisionId: 'd1', overrideReason: 'x' }, f.leadActor,+ { routeDecision: open({ conversationId: 'other' }) })).toThrow('another group')+ })++ it('links a start that matches the picked new agent, model and effort', () => {+ const f = routed()+ const request = { conversationId: 'lead', machineId: 'machine', engine: 'claude', model: 'opus', effort: 'high', name: 'Builder', cwd: '/repo', worktree: false,+ requirements: { memoryBytes: 0, diskBytes: 0, maxCpuPercent: 100, tools: [], devices: [], quotaRequired: false } }+ const effects = f.run({ type: 'agent.start', request, routeDecisionId: 'd1' }, f.leadActor, { routeDecision: open(), contribution: f.contribution })+ expect(effects.routeDecisions).toEqual([{ op: 'final', id: 'd1', final: { kind: 'new', startId: effects.result.startId, machineId: 'machine', engine: 'claude', model: 'opus', effort: 'high' } }])+ expect(f.state.starts![0]!.request).toMatchObject({ model: 'opus', effort: 'high' })+ })++ it('links the assignment of an agent started from the decision and keeps the started model and effort', () => {+ const f = routed()+ f.define('lead')+ const final = { kind: 'new', startId: f.startedFor(f.worker), machineId: 'machine', engine: 'claude', model: 'opus', effort: 'high' }+ const effects = f.run({ type: 'work.assign', conversationId: 'lead', agentId: f.worker, routeDecisionId: 'd1' }, f.leadActor, { routeDecision: open({ final }) })+ expect(effects.routeDecisions).toEqual([{ op: 'final', id: 'd1', final, assignmentId: effects.result.assignmentId }])+ expect(effects.routeDecisions[0]).not.toHaveProperty('override')+ })++ it('needs a Lead reason when a person overrode the pick after the start', () => {+ const f = routed()+ f.define('lead')+ const final = { kind: 'new', startId: f.startedFor(f.worker), machineId: 'machine', engine: 'claude', model: 'opus', effort: 'high' }+ const overridden = open({ final, override: { by: 'person', actorKey: 'person:owner', candidateId: 'c1', reason: 'Use Sonnet.' } })+ const assign = { type: 'work.assign', conversationId: 'lead', agentId: f.worker, routeDecisionId: 'd1' } as const+ expect(() => f.run(assign, f.leadActor, { routeDecision: overridden })).toThrow('reason')+ const effects = f.run({ ...assign, overrideReason: 'The opus agent is already warm.' }, f.leadActor, { routeDecision: overridden })+ expect(effects.routeDecisions[0]).toMatchObject({ op: 'final', final, override: { by: 'lead', reason: 'The opus agent is already warm.' } })+ })+})diff --git a/backend/src/superTabs/commands.ts b/backend/src/superTabs/commands.tsindex 18f53876b..7bf8ef0c0 100644--- a/backend/src/superTabs/commands.ts+++ b/backend/src/superTabs/commands.ts@@ -3,9 +3,12 @@ import {activeWork, actorKey, agent, author, conversation, fail, person, stableId,type Actor, type Agent, type Author, type CommandEffects, type SuperTabState,} from './model.js'+import { routeRecordSchema, routeTitle, startedAs, type RouteCandidate, type RouteDecision, type RouteFinal, type RouteOverride } from './routeRecord.js'+import { routingOverrideSchema } from './routingPolicy.js'const id = z.string().min(1).max(160).regex(/^[A-Za-z0-9_-]+$/)const title = z.string().trim().min(1).max(160)+const reason = z.string().trim().min(1).max(300)const text = z.string().trim().min(1).max(32_000)const configuration = z.object({engine: z.string().min(1).max(80), model: z.string().max(200).nullable(),@@ -16,6 +19,7 @@ const path = z.string().min(1).max(4096).regex(/^\//).refine(value => !/[\x00-\xexport const startRequestSchema = z.object({conversationId: id, machineId: id, engine: z.string().min(1).max(80), name: title, cwd: path,worktree: z.boolean(), branchRef: z.string().max(1024).regex(/^refs\/(heads|remotes)\/[^\s\x00-\x1f\x7f]+$/).optional(),+ model: z.string().trim().min(1).max(200).optional(), effort: z.string().trim().min(1).max(80).optional(),permissionMode: z.string().min(1).max(80).optional(), codexHome: path.optional(),gridModel: z.string().min(1).max(2048).optional(), gridName: z.string().min(1).max(2048).optional(),requirements: z.object({ memoryBytes: z.number().int().nonnegative().safe(), diskBytes: z.number().int().nonnegative().safe(),@@ -27,11 +31,12 @@ const check = z.object({ description: z.string().trim().min(1).max(1000), indepeexport const commandSchema = z.discriminatedUnion('type', [z.object({ type: z.literal('tab.rename'), name: title }).strict(),z.object({ type: z.literal('tab.pause'), paused: z.boolean() }).strict(),+ z.object({ type: z.literal('tab.routingPolicy'), policy: routingOverrideSchema.nullable() }).strict(),z.object({ type: z.literal('conversation.create'), title, brief: z.string().trim().max(8000), checks: z.array(check).max(40) }).strict(),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('agent.add'), conversationId: id, machineId: id, harnessId: id, name: title, configuration, lead: z.boolean(), initialMessage: text.optional() }).strict(),- z.object({ type: z.literal('agent.start'), request: startRequestSchema }).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(),z.object({ type: z.literal('agent.started'), startId: id, harnessId: id, configuration }).strict(),z.object({ type: z.literal('agent.startFailed'), startId: id, error: text }).strict(),@@ -45,9 +50,12 @@ export const commandSchema = z.discriminatedUnion('type', [z.object({ type: z.literal('message.send'), conversationId: id, text, replyTo: id.nullable(), recipientIds: z.array(id).max(16) }).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, checks: z.array(check).min(1).max(40) }).strict(),- z.object({ type: z.literal('work.assign'), conversationId: id, agentId: id }).strict(),+ z.object({ type: z.literal('work.assign'), conversationId: id, agentId: id, routeDecisionId: id.optional(), overrideReason: reason.optional() }).strict(),z.object({ type: z.literal('work.status'), conversationId: id, assignmentId: id,status: z.enum(['working', 'needs_human', 'review', 'done', 'stopped']), result: text.nullable() }).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(),z.object({ type: z.literal('work.check'), conversationId: id, assignmentId: id, checkId: id, passed: z.boolean(), evidence: text }).strict(),])export type Command = z.infer<typeof commandSchema>@@ -64,6 +72,10 @@ export interface CommandContext {confirmedStopped?: boolean/** An uncertain receipt and its original message, read transactionally. */delivery?: { id: string; conversationId: string; agentId: string; messageId: string; text: string }+ /** Route decisions this tab recorded in the last hour, counted by the store. */+ recentRoutes?: number+ /** The decision a command names, read from SuperTabRouteDecision by the store. */+ routeDecision?: RouteDecision}function controls(state: SuperTabState, actor: Actor, conversationId = 'lead'): void {@@ -85,7 +97,7 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Commaconst command = commandSchema.parse(input)const state = structuredClone(original)const result: Record<string, unknown> = {}- const effects: CommandEffects = { state, messages: [], cancelledAgents: [], previousAttempts: [], result }+ const effects: CommandEffects = { state, messages: [], cancelledAgents: [], previousAttempts: [], routeDecisions: [], result }const operationId = stableId(state.id, actorKey(actor), context.operationId)// Acceptance is the only operation a non-member can perform; the verified account email owns the invite.@@ -108,10 +120,31 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Commaif (group.assignment) effects.previousAttempts.push(structuredClone({ conversationId: group.id,brief: group.brief, checks: group.checks, assignment: group.assignment }))}- const message = (conversationId: string, body: string, recipients: string[] = [], replyTo: string | null = null) => {- effects.messages.push({ id: operationId, conversationId, author: sender, text: body, replyTo, recipients })+ const message = (conversationId: string, body: string, recipients: string[] = [], replyTo: string | null = null, source?: Record<string, unknown>) => {+ effects.messages.push({ id: operationId, conversationId, author: sender, text: body, replyTo, recipients, ...(source ? { source } : {}) })result.messageId = operationId}+ const openDecision = (): RouteDecision => {+ const decision = context.routeDecision ?? fail('NOT_FOUND', 'This routing decision is unavailable.', 404)+ if (decision.outcome) fail('ROUTE_CLOSED', 'This routing decision is no longer open. Route the task again.')+ return decision+ }+ /** The candidate a start or assignment should match, and whether it does. A mismatch needs the lead's reason. */+ const linkDecision = (conversationId: string, matches: (c: RouteCandidate, d: RouteDecision) => boolean,+ finalOf: (d: RouteDecision) => RouteFinal, reasonText: string | undefined, assignmentId?: string) => {+ const decision = openDecision()+ if (decision.conversationId !== conversationId) fail('ROUTE_MISMATCH', 'This routing decision belongs to another group.')+ // A second start or assignment must not overwrite the final while the first attempt is still running.+ if (decision.assignmentId && state.conversations.some(c => c.assignment?.id === decision.assignmentId && activeWork(c))) {+ fail('ROUTE_LINKED', 'This routing decision already has running work. Stop it before handing the task over.')+ }+ const expected = decision.record.candidates.find(c => c.id === (decision.override?.candidateId ?? decision.record.pick))!+ const matched = matches(expected, decision)+ if (!matched && !reasonText) fail('OVERRIDE_REASON_REQUIRED', `Routing chose ${expected.title}. Pass an override reason to choose otherwise.`, 400)+ const override: RouteOverride | undefined = matched ? undefined : { by: 'lead', actorKey: actorKey(actor), reason: reasonText! }+ effects.routeDecisions.push({ op: 'final', id: decision.id, final: finalOf(decision), ...(override ? { override } : {}), ...(assignmentId ? { assignmentId } : {}) })+ return { decision, expected, override }+ }const removeAgent = (target: Agent) => {state.agents = state.agents.filter(a => a.id !== target.id)effects.cancelledAgents.push(target.id)@@ -131,6 +164,11 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Commacontrols(state, actor)state.paused = command.pausedbreak+ case 'tab.routingPolicy':+ if (actor.kind !== 'person' || actor.userId !== state.ownerId) fail('OWNER_REQUIRED', 'Only the Super Tab owner can change its routing policy.', 403)+ if (command.policy && Object.keys(command.policy).length) state.routingPolicy = command.policy+ else delete state.routingPolicy+ breakcase 'conversation.create': {controls(state, actor)if (state.paused) fail('PAUSED', 'New work is paused in this Super Tab.')@@ -206,6 +244,15 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: CommacontributorId: contributor.id, membershipGeneration: contributor.generation, machineOwnerId: grant.machineOwnerId,hostGrant: grant.hostGrant ?? null, request: command.request, harnessId: null, dispatched: false, error: null })result.startId = operationId+ if (command.routeDecisionId) {+ const r = command.request+ const model = r.model ?? 'default', effort = r.effort ?? 'default'+ const { decision, expected, override } = linkDecision(r.conversationId,+ c => c.kind === 'new' && c.machineId === r.machineId && c.engine === r.engine && c.model === model && c.effort === effort,+ () => ({ kind: 'new', startId: operationId, machineId: r.machineId, engine: r.engine, model, effort }), command.overrideReason)+ if (override) message(r.conversationId, `Lead started ${r.name} instead of ${expected.title}. Reason: ${override.reason}`, [], null,+ { kind: 'route-override', decisionId: decision.id, by: 'lead' })+ }break}case 'agent.startDispatch':@@ -351,6 +398,52 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Commaresult.resolution = command.resolutionbreak}+ case 'route.record': {+ controls(state, actor, command.conversationId)+ open(state, command.conversationId)+ if ((context.recentRoutes ?? 0) >= 30) fail('RATE_LIMITED', 'This Super Tab routed 30 tasks in the last hour. Wait before routing again.', 429)+ const decision = command.decision+ const pick = decision.candidates.find(c => c.id === decision.pick)!+ const via = decision.via === 'jev' ? `Jev ${Math.round((decision.p ?? 0) * 100)}%`+ : decision.via === 'only' ? 'only candidate' : 'by policy order'+ effects.routeDecisions.push({ op: 'create', id: operationId, conversationId: command.conversationId, record: decision })+ result.routeDecisionId = operationId+ // The row quotes the Lead's reason for the task; the verdict's own text stays in the decision record.+ const reason = decision.assessment.why+ message(command.conversationId, `Routed to ${pick.title} — ${via} · "${reason}"`, [], null, {+ kind: 'route', decisionId: operationId, via: decision.via, p: decision.p, belowFloor: decision.belowFloor, why: reason,+ ...(decision.via === 'order' && decision.fallback ? { fallback: decision.fallback } : {}),+ pick: { id: pick.id, title: pick.title },+ alternatives: decision.candidates.filter(c => c.id !== pick.id).map(c => ({ id: c.id, title: c.title })),+ })+ break+ }+ case 'route.modelResult': {+ const decision = openDecision()+ controls(state, actor, decision.conversationId)+ const final = decision.final+ if (final?.kind !== 'new' || final.startId !== command.startId) fail('ROUTE_MISMATCH', 'This routing decision did not start that agent.')+ // The final says who was actually started. When the routed switch failed, the request moves to `requested`.+ effects.routeDecisions.push({ op: 'final', id: decision.id,+ final: { ...final, model: command.model, effort: command.effort, requested: final.requested ?? { model: final.model, effort: final.effort } } })+ break+ }+ case 'route.override': {+ if (actor.kind !== 'person') fail('HUMAN_REQUIRED', 'A person changes a routing decision; the lead overrides when it starts or assigns.', 403)+ const decision = openDecision()+ controls(state, actor, decision.conversationId)+ open(state, decision.conversationId)+ const current = decision.override?.candidateId ?? decision.record.pick+ const chosen = decision.record.candidates.find(c => c.id === command.candidateId) ?? fail('NOT_FOUND', 'Choose one of this decision’s candidates.', 404)+ if (chosen.id === current) fail('ALREADY_CHOSEN', 'That candidate is already the choice.')+ if (chosen.kind === 'member' && !state.agents.some(a => a.id === chosen.agentId)) fail('CANDIDATE_UNAVAILABLE', 'That agent left this Super Tab. Choose another.')+ effects.routeDecisions.push({ op: 'override', id: decision.id, override: { by: 'person', actorKey: actorKey(actor), candidateId: chosen.id, reason: command.reason } })+ const lead = conversation(state, decision.conversationId).leadId+ message(decision.conversationId,+ `${sender.name} chose ${chosen.title} instead of ${routeTitle(decision, current)}. Hand this task over to it. Reason: ${command.reason}`,+ lead ? [lead] : [], null, { kind: 'route-override', decisionId: decision.id, by: 'person' })+ break+ }case 'work.define': {controls(state, actor, command.conversationId)const group = open(state, command.conversationId)@@ -376,7 +469,20 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Commaexecution: { machineId: worker.machineId, harnessId: worker.harnessId, machineOwnerId: worker.machineOwnerId }, result: null }group.checks.forEach(c => { c.evidence = null; c.passedBy = null })result.assignmentId = operationId+ let routeNote: { decisionId: string; text: string } | null = null+ if (command.routeDecisionId) {+ const started = (d: RouteDecision) => d.final?.kind === 'new' &&+ !!state.starts?.some(s => s.id === (d.final as { startId: string }).startId && s.harnessId === worker.harnessId && s.request.machineId === worker.machineId)+ // An agent started from this decision keeps the final that records its model and effort; only the assignment is added.+ const { decision, expected, override } = linkDecision(group.id,+ (c, d) => (c.kind === 'member' && c.agentId === worker.id) || (c.kind === 'new' && started(d) && d.final?.kind === 'new' &&+ startedAs(c, d.final)),+ d => started(d) ? d.final! : { kind: 'member', agentId: worker.id, machineId: worker.machineId }, command.overrideReason, operationId)+ if (override) routeNote = { decisionId: decision.id, text: `Lead assigned ${worker.name} instead of ${expected.title}. Reason: ${override.reason}` }+ }message(group.id, `${group.brief}\n\nAcceptance checks:\n${group.checks.map(c => `- ${c.description}`).join('\n')}`, [worker.id])+ if (routeNote) effects.messages.push({ id: stableId(operationId, 'route-override'), conversationId: group.id, author: sender,+ text: routeNote.text, replyTo: null, recipients: [], source: { kind: 'route-override', decisionId: routeNote.decisionId, by: 'lead' } })break}case 'work.status': {diff --git a/backend/src/superTabs/model.ts b/backend/src/superTabs/model.tsindex 569a3cffa..c993cfc03 100644--- a/backend/src/superTabs/model.ts+++ b/backend/src/superTabs/model.ts@@ -1,4 +1,5 @@import { createHash } from 'node:crypto'+import type { RouteDecisionEffect } from './routeRecord.js'export type Role = 'owner' | 'collaborator' | 'viewer'export interface Person { id: string; email: string; role: Role; generation: string }@@ -26,6 +27,8 @@ export interface AgentStartRequest {conversationId: stringmachineId: stringengine: string+ model?: string+ effort?: stringname: stringcwd: stringworktree: boolean@@ -89,6 +92,8 @@ export interface SuperTabState {name: stringownerId: stringenvironment: string+ /** Fields this tab overrides from its owner's account routing policy (routingPolicy.ts). */+ routingPolicy?: import('./routingPolicy.js').RoutingOverridepaused: booleanpeople: Person[]agents: Agent[]@@ -107,12 +112,15 @@ export interface MessageDraft {text: stringreplyTo: string | nullrecipients: string[]+ /** Structured row kind for clients; `native` is written by native.ts, `route`/`route-override` by commands. */+ source?: Record<string, unknown>}export interface CommandEffects {state: SuperTabStatemessages: MessageDraft[]cancelledAgents: string[]previousAttempts: Array<{ conversationId: string; brief: string; checks: Check[]; assignment: Assignment }>+ routeDecisions: RouteDecisionEffect[]result: Record<string, unknown>}export class SuperTabError extends Error {diff --git a/backend/src/superTabs/routeDecisions.ts b/backend/src/superTabs/routeDecisions.tsnew file mode 100644index 000000000..bec4ecc17--- /dev/null+++ b/backend/src/superTabs/routeDecisions.ts@@ -0,0 +1,64 @@+/** Persistence for route decisions. Called inside SuperTabStore's transactions. */+import type { Prisma, SuperTabRouteDecision } from '@prisma/client'+import { finalMatches, type RouteDecision, type RouteDecisionEffect, type RouteFinal, type RouteOverride, type RouteRecord } from './routeRecord.js'++type Tx = Prisma.TransactionClient+const json = (value: unknown): Prisma.InputJsonValue => JSON.parse(JSON.stringify(value)) as Prisma.InputJsonValue+/** Mongo omits unset fields, so `outcome: null` alone would miss every open decision. */+const open: Prisma.SuperTabRouteDecisionWhereInput = { OR: [{ outcome: null }, { outcome: { isSet: false } }] }+export const RETENTION_MS = 90 * 24 * 60 * 60_000++export const decisionOf = (row: SuperTabRouteDecision): RouteDecision => ({+ id: row.id, conversationId: row.conversationId, record: row.record as unknown as RouteRecord,+ final: (row.final ?? null) as unknown as RouteFinal | null, override: (row.override ?? null) as unknown as RouteOverride | null,+ assignmentId: row.assignmentId, outcome: row.outcome,+})++/** The decision with the times the log shows: when it was recorded and when its outcome was. */+export const timedDecisionOf = (row: SuperTabRouteDecision) => ({ ...decisionOf(row), createdAt: row.createdAt, outcomeAt: row.outcomeAt })++export async function recentRoutes(tx: Tx, tabId: string, now: number): Promise<number> {+ return tx.superTabRouteDecision.count({ where: { tabId, createdAt: { gte: new Date(now - 60 * 60_000) } } })+}++export async function readDecision(tx: Tx, tabId: string, id: string): Promise<RouteDecision | undefined> {+ const row = await tx.superTabRouteDecision.findFirst({ where: { id, tabId } })+ return row ? decisionOf(row) : undefined+}++export async function writeRouteEffects(tx: Tx, tabId: string, effects: RouteDecisionEffect[], now: number): Promise<void> {+ for (const effect of effects) {+ if (effect.op === 'create') {+ // One open decision per group: a newer route supersedes the open one.+ await tx.superTabRouteDecision.updateMany({ where: { tabId, conversationId: effect.conversationId, ...open },+ data: { outcome: 'superseded', outcomeAt: new Date(now) } })+ await tx.superTabRouteDecision.create({ data: { id: effect.id, tabId, conversationId: effect.conversationId,+ record: json(effect.record), createdAt: new Date(now) } })+ await tx.superTabRouteDecision.deleteMany({ where: { tabId, createdAt: { lt: new Date(now - RETENTION_MS) } } })+ } else if (effect.op === 'override') {+ await tx.superTabRouteDecision.update({ where: { id: effect.id }, data: { override: json(effect.override) } })+ } else {+ await tx.superTabRouteDecision.update({ where: { id: effect.id }, data: {+ final: json(effect.final), ...(effect.override ? { override: json(effect.override) } : {}),+ ...(effect.assignmentId ? { assignmentId: effect.assignmentId } : {}),+ } })+ }+ }+}++export async function closeAssignment(tx: Tx, tabId: string, assignmentId: string, outcome: 'done' | 'stopped', now: number): Promise<void> {+ // The Lead must stop an assignment before handing the task to the candidate a person chose. That stop is+ // the handover, not the end of the decision: keep it open so the next start or assignment links to it.+ if (outcome === 'stopped') {+ const rows = await tx.superTabRouteDecision.findMany({ where: { tabId, assignmentId, ...open } })+ for (const row of rows) {+ const decision = decisionOf(row)+ const chosen = decision.override?.by === 'person' ? decision.record.candidates.find(c => c.id === decision.override!.candidateId) : undefined+ if (chosen && !finalMatches(chosen, decision.final)) {+ await tx.superTabRouteDecision.update({ where: { id: row.id }, data: { assignmentId: null, final: null } })+ return+ }+ }+ }+ await tx.superTabRouteDecision.updateMany({ where: { tabId, assignmentId, ...open }, data: { outcome, outcomeAt: new Date(now) } })+}diff --git a/backend/src/superTabs/routeRecord.ts b/backend/src/superTabs/routeRecord.tsnew file mode 100644index 000000000..ff02968a1--- /dev/null+++ b/backend/src/superTabs/routeRecord.ts@@ -0,0 +1,68 @@+/** What `harness super-tab route` records (docs/superpowers/specs/2026-10-19-super-tab-routing-v1-design.md). */+import { z } from 'zod'++const level = z.enum(['low', 'medium', 'high'])+const candidateId = z.string().regex(/^c\d{1,2}$/)+const machine = z.string().min(1).max(160).regex(/^[A-Za-z0-9_-]+$/)+export const routeCandidateSchema = z.object({+ id: candidateId,+ kind: z.enum(['member', 'new']),+ agentId: machine.optional(),+ machineId: machine,+ engine: z.enum(['claude', 'codex']),+ model: z.string().min(1).max(200),+ effort: z.string().min(1).max(80),+ quality: z.number().int().min(1).max(3),+ cost: z.number().int().min(1).max(100),+ /** Short, for the conversation row: "Multiply · Claude opus high · remote-1". */+ title: z.string().trim().min(1).max(160),+ /** The criterion line Jev was shown. */+ label: z.string().trim().min(1).max(640),+}).strict().refine(c => (c.kind === 'member') === !!c.agentId, 'Members name their agent; new agents do not.')+export const routeRecordSchema = z.object({+ assessment: z.object({ difficulty: level, risk: level, why: z.string().trim().min(1).max(300) }).strict(),+ candidates: z.array(routeCandidateSchema).min(1).max(12),+ excluded: z.array(z.object({ title: z.string().trim().min(1).max(160), reason: z.string().trim().min(1).max(500) }).strict()).max(200),+ floor: z.number().int().min(1).max(3),+ notes: z.boolean(),+ pick: candidateId,+ via: z.enum(['jev', 'order', 'only']),+ /** Why the policy order decided, when it did: Jev answered without enough confidence, or could not be asked. */+ fallback: z.enum(['unsure', 'unavailable']).optional(),+ p: z.number().min(0).max(1).nullable(),+ belowFloor: z.boolean(),+ /** The verdict's own explanation, kept for analysis; the row quotes the Lead's assessment instead. */+ why: z.string().trim().min(1).max(300),+}).strict().refine(d => d.candidates.some(c => c.id === d.pick), 'The pick must be one of the candidates.')+ .refine(d => new Set(d.candidates.map(c => c.id)).size === d.candidates.length, 'Candidate ids must be unique.')++/**+ * Whether a started agent is the candidate's: the same machine, engine, and the model and effort that were+ * requested. After a failed switch `final` holds what ran, so the request is the one that names the candidate.+ */+export const startedAs = (candidate: RouteCandidate, final: Extract<RouteFinal, { kind: 'new' }>): boolean =>+ final.machineId === candidate.machineId && final.engine === candidate.engine &&+ (final.requested?.model ?? final.model) === candidate.model && (final.requested?.effort ?? final.effort) === candidate.effort++/** Whether a decision's final names this candidate: the same agent, or the same start. */+export const finalMatches = (candidate: RouteCandidate, final: RouteFinal | null): boolean => !!final && (candidate.kind === 'member'+ ? final.kind === 'member' && final.agentId === candidate.agentId+ : final.kind === 'new' && startedAs(candidate, final))++export type RouteCandidate = z.infer<typeof routeCandidateSchema>+export type RouteRecord = z.infer<typeof routeRecordSchema>+export type RouteFinal =+ | { kind: 'member'; agentId: string; machineId: string }+ /** After a failed model switch, `model` and `effort` are what ran and `requested` is what routing asked for. */+ | { kind: 'new'; startId: string; machineId: string; engine: string; model: string; effort: string; requested?: { model: string; effort: string } }+export interface RouteOverride { by: 'lead' | 'person'; actorKey: string; candidateId?: string; reason: string }+export interface RouteDecision {+ id: string; conversationId: string; record: RouteRecord+ final: RouteFinal | null; override: RouteOverride | null; assignmentId: string | null; outcome: string | null+}+export type RouteDecisionEffect =+ | { op: 'create'; id: string; conversationId: string; record: RouteRecord }+ | { op: 'override'; id: string; override: RouteOverride }+ | { op: 'final'; id: string; final: RouteFinal; override?: RouteOverride; assignmentId?: string }+export const routeTitle = (decision: RouteDecision, candidateId: string): string =>+ decision.record.candidates.find(c => c.id === candidateId)?.title ?? 'another candidate'diff --git a/backend/src/superTabs/routingPolicy.test.ts b/backend/src/superTabs/routingPolicy.test.tsnew file mode 100644index 000000000..13f01987e--- /dev/null+++ b/backend/src/superTabs/routingPolicy.test.ts@@ -0,0 +1,42 @@+import { describe, expect, it } from 'vitest'+import { DEFAULT_ROUTING_POLICY, effectivePolicy, routingOverrideSchema, routingPolicySchema } from './routingPolicy.js'++describe('routing policy', () => {+ it('ships a valid default that needs no setup', () => {+ expect(routingPolicySchema.parse(DEFAULT_ROUTING_POLICY)).toEqual(DEFAULT_ROUTING_POLICY)+ expect(DEFAULT_ROUTING_POLICY.floor).toEqual({ low: 1, medium: 2, high: 3 })+ expect(DEFAULT_ROUTING_POLICY.quotaReserve).toBe(10)+ expect(DEFAULT_ROUTING_POLICY.notes).toBe('')+ expect(new Set(DEFAULT_ROUTING_POLICY.models.map(m => m.engine))).toEqual(new Set(['claude', 'codex']))+ })++ it('uses the default when the account has none, and merges a tab override field by field', () => {+ expect(effectivePolicy(null, null)).toEqual({ policy: DEFAULT_ROUTING_POLICY, warnings: [], overridden: [] })+ const account = { ...DEFAULT_ROUTING_POLICY, quotaReserve: 20, notes: 'Frontend prefers Claude.' }+ const result = effectivePolicy(account, { notes: 'Long jobs on remote-1.' })+ expect(result.policy.quotaReserve).toBe(20)+ expect(result.policy.notes).toBe('Long jobs on remote-1.')+ expect(result.overridden).toEqual(['notes'])+ expect(result.warnings).toEqual([])+ })++ it('falls back to the default with a warning for a corrupt account policy or override', () => {+ const corrupt = effectivePolicy({ version: 9 }, { floor: { low: 7 } })+ expect(corrupt.policy).toEqual(DEFAULT_ROUTING_POLICY)+ expect(corrupt.warnings).toEqual([+ 'The account routing policy is unreadable; the built-in default applies.',+ 'This Super Tab routing override is unreadable and was ignored.',+ ])+ })++ it('rejects out-of-range values and unknown engines', () => {+ const bad = (patch: Record<string, unknown>) => routingPolicySchema.safeParse({ ...DEFAULT_ROUTING_POLICY, ...patch }).success+ expect(bad({ quotaReserve: 91 })).toBe(false)+ expect(bad({ notes: 'x'.repeat(501) })).toBe(false)+ expect(bad({ floor: { low: 0, medium: 2, high: 3 } })).toBe(false)+ expect(bad({ models: [{ ...DEFAULT_ROUTING_POLICY.models[0], engine: 'cursor' }] })).toBe(false)+ expect(bad({ models: [{ ...DEFAULT_ROUTING_POLICY.models[0], cost: 0 }] })).toBe(false)+ expect(bad({ models: [] })).toBe(false)+ expect(routingOverrideSchema.safeParse({ version: 1 }).success).toBe(false)+ })+})diff --git a/backend/src/superTabs/routingPolicy.ts b/backend/src/superTabs/routingPolicy.tsnew file mode 100644index 000000000..fd8c2bba8--- /dev/null+++ b/backend/src/superTabs/routingPolicy.ts@@ -0,0 +1,59 @@+/** Super Tab routing policy (docs/superpowers/specs/2026-10-19-super-tab-routing-v1-design.md).+ * The account default applies to every tab its owner creates; a tab owner may override single fields.+ * Every field has a built-in default so routing works before anyone opens the form. */+import { z } from 'zod'++const quality = z.number().int().min(1).max(3)+const modelRow = z.object({+ engine: z.enum(['claude', 'codex']),+ // `default` keeps the engine's own configured model or effort; no runtime switch is made.+ model: z.string().trim().min(1).max(200),+ effort: z.string().trim().min(1).max(80),+ quality,+ cost: z.number().int().min(1).max(100),+ enabled: z.boolean(),+}).strict()+const fields = {+ models: z.array(modelRow).min(1).max(40),+ floor: z.object({ low: quality, medium: quality, high: quality }).strict(),+ quotaReserve: z.number().int().min(0).max(90),+ notes: z.string().trim().max(500),+}+export const routingPolicySchema = z.object({ version: z.literal(1), ...fields }).strict()+export const routingOverrideSchema = z.object(fields).partial().strict()+export type RoutingPolicy = z.infer<typeof routingPolicySchema>+export type RoutingOverride = z.infer<typeof routingOverrideSchema>+export type RoutingModel = RoutingPolicy['models'][number]++export const DEFAULT_ROUTING_POLICY: RoutingPolicy = {+ version: 1,+ 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,+ notes: '',+}++export function effectivePolicy(account: unknown, override: unknown) {+ const warnings: string[] = []+ let policy = DEFAULT_ROUTING_POLICY+ if (account !== null && account !== undefined) {+ const parsed = routingPolicySchema.safeParse(account)+ if (parsed.success) policy = parsed.data+ else warnings.push('The account routing policy is unreadable; the built-in default applies.')+ }+ const overridden: Array<keyof RoutingOverride> = []+ if (override !== null && override !== undefined) {+ const parsed = routingOverrideSchema.safeParse(override)+ if (!parsed.success) warnings.push('This Super Tab routing override is unreadable and was ignored.')+ else {+ policy = { ...policy, ...parsed.data }+ overridden.push(...(Object.keys(parsed.data) as Array<keyof RoutingOverride>))+ }+ }+ return { policy, warnings, overridden }+}diff --git a/backend/src/superTabs/store.ts b/backend/src/superTabs/store.tsindex 38ba07984..f233e53f9 100644--- a/backend/src/superTabs/store.ts+++ b/backend/src/superTabs/store.ts@@ -10,6 +10,8 @@ import {activeWork, actorKey, agent, author, conversation, createSuperTab, fail, person, stableId, visibleState,SuperTabError, type Actor, type Agent, type Author, type MessageDraft, type SuperTabState,} from './model.js'+import { closeAssignment, readDecision, recentRoutes, timedDecisionOf, writeRouteEffects } from './routeDecisions.js'+import { DEFAULT_ROUTING_POLICY, effectivePolicy, routingPolicySchema, type RoutingPolicy } from './routingPolicy.js'type Transaction = Prisma.TransactionClientconst json = (value: unknown): Prisma.InputJsonValue => JSON.parse(JSON.stringify(value)) as Prisma.InputJsonValue@@ -47,6 +49,41 @@ export class SuperTabStore {})}+ private policyId(user: AuthUser) { return stableId('routing-policy', user.sub, user.autonomousEnv) }++ async accountPolicy(user: AuthUser) {+ const row = await this.db.routingPolicy.findUnique({ where: { id: this.policyId(user) } })+ if (!row) return { policy: DEFAULT_ROUTING_POLICY, revision: 0, isDefault: true }+ const { policy } = effectivePolicy(row.policy, null)+ return { policy, revision: row.revision, isDefault: false }+ }++ async saveAccountPolicy(user: AuthUser, revision: number, input: RoutingPolicy) {+ const policy = routingPolicySchema.parse(input)+ return transaction(this.db, async tx => {+ const id = this.policyId(user)+ const row = await tx.routingPolicy.findUnique({ where: { id } })+ if ((row?.revision ?? 0) !== revision) fail('REVISION_CHANGED', 'The routing policy changed elsewhere. Reload it and try again.')+ const next = revision + 1+ if (row) await tx.routingPolicy.update({ where: { id, revision }, data: { revision: next, policy: json(policy) } })+ else await tx.routingPolicy.create({ data: { id, userId: user.sub, autonomousEnv: user.autonomousEnv, revision: next, policy: json(policy) } })+ return { policy, revision: next, isDefault: false as const }+ })+ }++ /** Viewers and agents read the same effective policy; it always comes from the tab owner's account. */+ async tabPolicy(user: AuthUser, tabId: string, asAgentId?: string) {+ return transaction(this.db, async tx => {+ const row = await this.row(tx, user, tabId)+ const state = stateOf(row)+ author(state, await this.actor(tx, user, state, asAgentId))+ const account = await tx.routingPolicy.findUnique({ where: { id: stableId('routing-policy', state.ownerId, state.environment) } })+ // The owner's account policy alone, so a field reset to "use account default" can show its value.+ return { ...effectivePolicy(account?.policy ?? null, state.routingPolicy ?? null), override: state.routingPolicy ?? null,+ account: effectivePolicy(account?.policy ?? null, null).policy }+ })+ }+private async row(tx: Transaction, user: AuthUser, tabId: string) {return await tx.superTab.findFirst({ where: { id: tabId, autonomousEnv: user.autonomousEnv } }) ??fail('NOT_FOUND', 'This Super Tab is unavailable.', 404)@@ -213,6 +250,10 @@ export class SuperTabStore {context.confirmedStopped = !!proof && !!execution && proof.machineId === execution.machineId &&proof.harnessId === execution.harnessId && proof.machineOwnerId === execution.machineOwnerId}+ if (command.type === 'route.record') context.recentRoutes = await recentRoutes(tx, tabId, context.now)+ const decisionId = command.type === 'route.override' || command.type === 'route.modelResult' ? command.decisionId+ : command.type === 'work.assign' || command.type === 'agent.start' ? command.routeDecisionId : undefined+ if (decisionId) context.routeDecision = await readDecision(tx, tabId, decisionId) ?? fail('NOT_FOUND', 'This routing decision is unavailable.', 404)const effects = applyCommand(original, actor, command, context)await revokeNativeContexts(tx, original, effects.state)const revision = row.revision + 1@@ -247,6 +288,10 @@ export class SuperTabStore {await tx.superTab.update({ where: { id: tabId, revision: row.revision }, data: {revision, state: json(effects.state), ...indexes(effects.state),} })+ await writeRouteEffects(tx, tabId, effects.routeDecisions, context.now)+ if (command.type === 'work.status' && (command.status === 'done' || command.status === 'stopped')) {+ await closeAssignment(tx, tabId, command.assignmentId, command.status, context.now)+ }await this.writeMessages(tx, tabId, effects.state, effects.messages, revision)const revoked = [...original.people.filter(p => !effects.state.people.some(n => n.id === p.id && n.generation === p.generation))@@ -272,7 +317,8 @@ export class SuperTabStore {private async writeMessages(tx: Transaction, tabId: string, state: SuperTabState, messages: MessageDraft[], revision: number) {for (const message of messages) {await tx.superTabMessage.create({ data: { id: message.id, tabId, conversationId: message.conversationId,- sequence: revision, author: json(message.author), text: message.text, replyTo: message.replyTo, recipientIds: message.recipients } })+ sequence: revision, author: json(message.author), ...(message.source ? { source: json(message.source) } : {}),+ text: message.text, replyTo: message.replyTo, recipientIds: message.recipients } })for (const recipient of message.recipients) {const target = agent(state, recipient)const group = conversation(state, message.conversationId)@@ -306,6 +352,24 @@ export class SuperTabStore {})}+ async routeDecisions(user: AuthUser, tabId: string, asAgentId?: string) {+ return transaction(this.db, async tx => {+ const state = stateOf(await this.row(tx, user, tabId))+ author(state, await this.actor(tx, user, state, asAgentId))+ const rows = await tx.superTabRouteDecision.findMany({ where: { tabId }, orderBy: { createdAt: 'desc' }, take: 100 })+ return rows.map(timedDecisionOf)+ })+ }++ async routeDecision(user: AuthUser, tabId: string, decisionId: string, asAgentId?: string) {+ return transaction(this.db, async tx => {+ const state = stateOf(await this.row(tx, user, tabId))+ author(state, await this.actor(tx, user, state, asAgentId))+ const row = await tx.superTabRouteDecision.findFirst({ where: { id: decisionId, tabId } })+ return row ? timedDecisionOf(row) : fail('NOT_FOUND', 'This routing decision is unavailable.', 404)+ })+ }+/** Host polling discovers only registered sessions on its own machine, never unrelated tab transcripts. */async hostTabs(user: AuthUser, machineId: string) {return transaction(this.db, async tx => {@@ -457,6 +521,7 @@ export class SuperTabStore {await tx.superTabRun.deleteMany({ where: { tabId, assignmentId } })await tx.superTabDelivery.updateMany({ where: { tabId, assignmentId,status: { in: ['queued', 'claimed', 'uncertain'] } }, data: { status: 'cancelled' } })+ await closeAssignment(tx, tabId, assignmentId, 'stopped', this.now())// No agent command closes this attempt, so nobody was told: in the two-account E2E of 2026-10-19// the Lead learned of a stopped worker only by re-reading status. Say it in the group, as the// worker's own Stopped update would, and deliver it to the Lead. A removed worker was removeddiff --git a/backend/src/types/productUsage.ts b/backend/src/types/productUsage.tsindex 8b6c51120..5bb5247a2 100644--- a/backend/src/types/productUsage.ts+++ b/backend/src/types/productUsage.ts@@ -85,6 +85,7 @@ export const LAUNCH_ERROR_CODES = [// What a new harness asked for, refused before anything starts (core/agents/launches.ts, lib/engineLaunch.ts).'invalid_codex_home', 'invalid_prompt', 'prompt_too_long', 'prompt_unsupported', 'invalid_agent', 'invalid_session','invalid_started_by', 'agent_unsupported', 'invalid_runtime_profile', 'grid_engine_unsupported', 'codex_cli_too_old',+ 'invalid_launch_model', 'launch_model_unsupported',// A new project's folder (lib/projectFolder.ts) and the launch's durable receipt (lib/agentCreationReceipt.ts).'project_exists', 'invalid_repository', 'clone_failed', 'clone_timeout', 'git_unavailable', 'project_preparation_failed','creation_conflict', 'creation_storage_failed', 'launch_authority_changed', 'internal',diff --git a/cli/e2e/harness/fakeBackend.ts b/cli/e2e/harness/fakeBackend.tsindex 50b3b6a4c..3897ecf6a 100644--- a/cli/e2e/harness/fakeBackend.ts+++ b/cli/e2e/harness/fakeBackend.ts@@ -110,6 +110,8 @@ export class FakeBackend {}>) | null = null/** Opt-in fixture: older scenarios keep the endpoint absent, as on an older backend. */productUsage: { enabled: boolean; revision: number; reports: Record<string, unknown>[]; stallReports?: boolean } | null = null+ /** `POST /api/route/jev`, Harness's hosted Jev. Unset answers 503 JEV_BUSY, which callers treat as unavailable. */+ jev: ((body: Record<string, any>) => Record<string, unknown>) | null = nullreadonly seen: string[] = []/** What `GET /api/agent-messages` answers: the account's tabs and who is in each; null, a 404. */agentMessages: Record<string, unknown> | null = null@@ -218,6 +220,15 @@ export class FakeBackend {})return}+ if (req.url?.split('?')[0] === '/api/route/jev' && req.method === 'POST') {+ let raw = ''+ req.on('data', (chunk) => { raw += chunk })+ req.on('end', () => {+ if (!backend.jev) { res.statusCode = 503; res.end(json({ success: false, error: { code: 'JEV_BUSY', message: 'Fixture Jev is off.' } })); return }+ res.end(json({ success: true, data: { answers: backend.jev(JSON.parse(raw || '{}')) } }))+ })+ return+ }if (req.url?.split('?')[0] === '/api/experimental-settings' && (req.method === 'GET' || req.method === 'PATCH')) {if (req.method === 'GET') { res.end(json({ success: true, data: backend.experimentalSettings() })); return }let raw = ''diff --git a/cli/e2e/harness/fakeEngine.mjs b/cli/e2e/harness/fakeEngine.mjsindex 7f73dcdac..019dede1e 100644--- a/cli/e2e/harness/fakeEngine.mjs+++ b/cli/e2e/harness/fakeEngine.mjs@@ -171,7 +171,7 @@ export async function run(engine, config = {}, { native = false } = {}) {]: ['Usage: claude [options] [command] [prompt]', '', 'Arguments:', ' prompt Your prompt', '',- ' --model <model>', ' --permission-mode <mode> (choices: "acceptEdits", "auto", "bypassPermissions", "default", "plan")',+ ' --model <model>', ' --effort <level>', ' --permission-mode <mode> (choices: "acceptEdits", "auto", "bypassPermissions", "default", "plan")',' --dangerously-skip-permissions', ' -r, --resume [value]', ' --fork-session', ' --session-id <uuid>', '',]).filter((line) => !line.split(/[^A-Za-z0-9-]+/).some((word) => without.has(word))).join('\n'))return@@ -185,6 +185,8 @@ export async function run(engine, config = {}, { native = false } = {}) {: `error: unexpected argument '${refused}' found\n\nUsage: codex [OPTIONS] [PROMPT]\n\nFor more information, try '--help'.\n`)process.exit(engine === 'claude' ? 1 : 2)}+ // Every launch's argv, for a test to read what an agent was started with.+ if (config.root) appendFileSync(join(config.root, 'launch-argv'), `${JSON.stringify({ engine, args })}\n`)// The process table shows it as it shows the real CLI: named `claude` or `codex`, with the command line// it was started with, both of which discovery reads (tmux.ts: a resume typed into a pane names its// conversation on that command line). The title used to be the name alone, so no argument was ever ondiff --git a/cli/e2e/superTabRoute.e2e.ts b/cli/e2e/superTabRoute.e2e.tsnew file mode 100644index 000000000..94fabbac4--- /dev/null+++ b/cli/e2e/superTabRoute.e2e.ts@@ -0,0 +1,168 @@+/** `harness super-tab route` on the real native protocol: a private daemon, tmux and data dir, fake Claude+ * engines and the fake backend (its hosted Jev included). Database authorization is covered by the backend's tests. */+import { createHash } from 'node:crypto'+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { afterEach, expect, it, onTestFailed } from 'vitest'+import { superTabCommand } from '../src/superTabs/command.js'+import { LocalClient } from './harness/client.js'+import { IsolatedDaemon } from './harness/daemon.js'+import { FakeBackend, type FakeMachine } from './harness/fakeBackend.js'++const ME: FakeMachine = { machineId: 'c9'.repeat(16), computerId: 'e2e-super-tab-route-computer', name: 'Fixture', token: 'e2e-super-tab-route-token' }+const TAB = 'route-tab'+const POLICY = { version: 1, floor: { low: 1, medium: 2, high: 3 }, quotaReserve: 10, notes: '', models: [+ { engine: 'claude', model: 'sonnet', effort: 'medium', quality: 2, cost: 2, enabled: true },+ { engine: 'claude', model: 'opus', effort: 'high', quality: 3, cost: 3, enabled: true },+ { engine: 'codex', model: 'default', effort: 'default', quality: 3, cost: 2, enabled: false },+] }+let daemon: IsolatedDaemon | undefined, backend: FakeBackend | undefined, nowhere: string | undefined+const clients: LocalClient[] = []+afterEach(async () => {+ clients.splice(0).forEach(client => client.close())+ await daemon?.close(); daemon = undefined+ await backend?.close(); backend = undefined+ if (nowhere) rmSync(nowhere, { recursive: true, force: true }); nowhere = undefined+})++async function setup(hostedJev: FakeBackend['jev'], options: { workerBusy?: boolean } = {}) {+ const relay = await FakeBackend.start(); backend = relay; relay.addMachine(ME); relay.jev = hostedJev+ // The daemon asks Jev on an OpenRouter key when it finds one (jevClient resolveJevKey): the environment's+ // variable, ORI_CREDENTIALS_PATH or TYPESAFE_CREDENTIALS. This run must reach the fake backend and never+ // OpenRouter, so the variable is emptied and both files point at a folder that holds nothing. The+ // default locations are under the isolated HOME.+ nowhere = mkdtempSync(join(tmpdir(), 'route-e2e-no-key-'))+ const d = await IsolatedDaemon.create({ submissionGate: true, env: {+ BACKEND_WS_URL: relay.wsUrl, WEB_URL: relay.httpUrl, ADAPTER_COMPUTER_ID: ME.computerId,+ ANTHROPIC_API_KEY: 'fixture-not-a-credential',+ OPENROUTER_API_KEY: '', ORI_CREDENTIALS_PATH: join(nowhere, 'credentials.json'), TYPESAFE_CREDENTIALS: join(nowhere, 'typesafe'),+ } }); daemon = d+ writeFileSync(join(d.root, 'auth', 'session.json'), JSON.stringify({ version: 1, accessToken: ME.token,+ autonomousEnv: 'prod', computerId: ME.computerId, machineId: ME.machineId,+ expiresAt: Date.now() + 30 * 24 * 3600_000, updatedAt: Date.now(), signInEpoch: 'e2e',+ }), { mode: 0o600 })+ onTestFailed(() => console.log(d.log().split('\n').slice(-160).join('\n')))+ await d.start()+ const client = await LocalClient.connect(d, { machineId: ME.machineId }); clients.push(client)+ const cwd = join(d.projectsDir, 'project'); mkdirSync(cwd, { recursive: true })+ const create = async () => {+ const made = await client.request('agent_create', { engine: 'claude', cwd, bypassPermission: true }, 90_000)+ expect(made.error, JSON.stringify(made)).toBeUndefined()+ return made.agent.id as string+ }+ const idFor = (harnessId: string) => createHash('sha256').update(JSON.stringify([ME.machineId, harnessId])).digest('hex').slice(0, 24)+ const leadHarness = await create(), workerHarness = await create()+ const leadId = idFor(leadHarness), workerId = idFor(workerHarness)+ const agents = [+ { id: leadId, name: 'Lead', machineId: ME.machineId, harnessId: leadHarness, configuration: { engine: 'claude', model: 'opus', effort: 'high' } },+ { id: workerId, name: 'Multiply', machineId: ME.machineId, harnessId: workerHarness, configuration: { engine: 'claude', model: 'sonnet', effort: 'medium' } },+ ]+ const conversations = [+ { id: 'lead', title: 'Lead', leadId, agentIds: [leadId, workerId], archived: false, brief: '', checks: [],+ assignment: options.workerBusy ? { id: 'busy', agentId: workerId, status: 'working' } : null },+ { id: 'g1', title: 'API', leadId, agentIds: [leadId], archived: false, brief: 'Add the endpoint.', checks: [{ description: 'Tests pass' }], assignment: null },+ ]+ const records: Array<Record<string, any>> = []+ const commands: Array<Record<string, any>> = []+ const starts = new Map<string, Record<string, any>>()+ relay.superTabs = async (method, raw, body) => {+ const url = new URL(raw, relay.httpUrl), path = url.pathname+ if (path === `/api/super-tabs/${TAB}` && method === 'GET') return { data: { revision: records.length, state: { id: TAB, agents, conversations } } }+ if (path === `/api/super-tabs/${TAB}/routing-policy`) return { data: { policy: POLICY, warnings: [], overridden: [] } }+ if (path === `/api/super-tabs/${TAB}/route-decisions`) return { data: [] }+ if (path === `/api/super-tabs/${TAB}/commands` && body.command?.type === 'route.record') {+ records.push(body)+ return { data: { revision: records.length, result: { routeDecisionId: `d-${records.length}` } } }+ }+ if (path === `/api/super-tabs/hosts/${ME.machineId}` || path === `/api/super-tabs/hosts/${ME.machineId}/assignments`) return { data: [] }+ if (path.startsWith(`/api/super-tabs/${TAB}/starts/`)) return { data: starts.get(path.split('/').at(-1)!) }+ if (path === `/api/super-tabs/${TAB}/commands`) {+ const command = body.command+ commands.push(body)+ if (command.type === 'agent.start') {+ const startId = `start-${body.operationId}`+ starts.set(startId, { id: startId, creationId: `super-${startId}`, request: command.request, dispatched: false, harnessId: null })+ return { data: { result: { startId } } }+ }+ const start = starts.get(String(command.startId))!+ if (command.type === 'agent.startDispatch') start.dispatched = true+ if (command.type === 'agent.started') { start.harnessId = command.harnessId; return { data: { result: { agentId: idFor(command.harnessId) } } } }+ return { data: { result: {} } }+ }+ throw new Error(`Unexpected request ${method} ${raw}`)+ }+ const where = { port: d.port, dataDir: d.dataDir, machineId: ME.machineId, harnessPane: true }+ async function route(group = 'g1') {+ let answer: Record<string, any> = {}+ const code = await superTabCommand(['--tab', TAB, '--agent', leadId, 'route', group,+ JSON.stringify({ difficulty: 'medium', risk: 'low', why: 'Endpoint.' })], { where: () => where, print: text => { answer = JSON.parse(text) } })+ return { code, answer }+ }+ async function start(operationId: string, request: Record<string, unknown>) {+ let answer: Record<string, any> = {}+ const code = await superTabCommand(['--tab', TAB, '--agent', leadId, 'start', operationId, JSON.stringify(request)],+ { where: () => where, print: text => { answer = JSON.parse(text) } })+ return { code, answer }+ }+ return { route, start, records, commands, relay, client, cwd }+}++it('routes to Jev’s pick and records the decision', async () => {+ const asked: Array<Record<string, any>> = []+ const { route, records } = await setup(body => {+ asked.push(body)+ const ids = Object.keys(body.questions.who.criteria)+ return { who: { choice: 'c1', probabilities: Object.fromEntries(ids.map(id => [id, id === 'c1' ? 0.9 : 0.1 / (ids.length - 1)])) } }+ })+ const { code, answer } = await route()+ expect(code, JSON.stringify(answer)).toBe(0)+ expect(answer).toMatchObject({ ok: true, routeDecisionId: 'd-1', via: 'jev', pick: { id: 'c1' } })+ expect(asked).toHaveLength(1)+ expect(records).toHaveLength(1)+ expect(records[0].command.decision).toMatchObject({ via: 'jev', pick: 'c1' })+ // The idle worker is a candidate; the Lead never is.+ const titles = (records[0].command.decision.candidates as Array<{ title: string }>).map(c => c.title)+ expect(titles.some(t => t.startsWith('Multiply ·'))).toBe(true)+ expect(titles.some(t => t.startsWith('Lead ·'))).toBe(false)+ // The service runs in its own process, which reads the account's machines through the core: titles carry the+ // machine's name, not its id (the 2026-10-19 manual run).+ expect(titles.every(t => t.endsWith(` · ${ME.name}`))).toBe(true)+}, 180_000)++it('falls back to the policy order when Jev is unavailable', async () => {+ const { route, records, relay } = await setup(null)+ const { code, answer } = await route()+ expect(code, JSON.stringify(answer)).toBe(0)+ expect(relay.seen.some(line => line.startsWith('POST /api/route/jev'))).toBe(true)+ expect(answer).toMatchObject({ ok: true, routeDecisionId: 'd-1', via: 'order', pick: { id: 'c0' } })+ expect(records[0].command.decision).toMatchObject({ via: 'order', pick: 'c0' })+}, 180_000)++it('starts the routed pick as a new agent with its decision, model and effort', async () => {+ const { route, start, commands, client, cwd } = await setup(null, { workerBusy: true })+ const routed = await route()+ expect(routed.code, JSON.stringify(routed.answer)).toBe(0)+ const pick = routed.answer.pick+ expect(pick).toMatchObject({ kind: 'new', engine: 'claude', model: 'sonnet', effort: 'medium' })+ const request = { conversationId: 'g1', machineId: pick.machineId, engine: pick.engine, model: pick.model, effort: pick.effort, name: 'Builder',+ cwd, worktree: false, permissionMode: 'auto', requirements: { memoryBytes: 0, diskBytes: 1, maxCpuPercent: 100, tools: [], devices: [], quotaRequired: false },+ routeDecisionId: routed.answer.routeDecisionId }+ const started = await start('route-start', request)+ expect(started.code, JSON.stringify(started.answer)).toBe(0)+ expect(started.answer.harnessId).toBeTruthy()+ const command = commands.find(c => c.command.type === 'agent.start')!.command+ // The decision rides on the command, never inside the machine-side request.+ expect(command.routeDecisionId).toBe('d-1')+ expect(command.request).toMatchObject({ model: 'sonnet', effort: 'medium', engine: 'claude' })+ expect(command.request).not.toHaveProperty('routeDecisionId')+ const listed = await client.request('agents_list', {}, 30_000)+ expect((listed.agents as Array<{ id: string }>).some(a => a.id === started.answer.harnessId)).toBe(true)+ // The routed model is a flag of that session alone: it is on the new agent's command line, and nothing typed+ // /model into its pane, which Claude Code would save as the person's default.+ const launches = readFileSync(join(daemon!.engineConfig.root, 'launch-argv'), 'utf8').trim().split('\n').map(line => JSON.parse(line) as { engine: string; args: string[] })+ const routedLaunch = launches.filter(l => l.engine === 'claude' && l.args.includes('--model'))+ expect(routedLaunch).toHaveLength(1)+ expect(routedLaunch[0]!.args.slice(routedLaunch[0]!.args.indexOf('--model'))).toEqual(expect.arrayContaining(['--model', 'sonnet', '--effort', 'medium']))+ expect(existsSync(join(daemon!.engineConfig.root, 'model-control-commands'))).toBe(false)+}, 240_000)diff --git a/cli/package.json b/cli/package.jsonindex 27882d11b..549fed906 100644--- a/cli/package.json+++ b/cli/package.json@@ -20,6 +20,7 @@"test:harnessd": "vitest run --config vitest.harnessd.config.ts","test:core": "vitest run --config vitest.core.config.ts","test:shared-tabs": "vitest run --config vitest.shared-tabs.config.ts",+ "test:super-tabs": "vitest run --config vitest.super-tabs.config.ts","test:e2e": "vitest run --config vitest.e2e.config.ts","test:sharing-e2e": "tsx scripts/share-harness-e2e.ts","test:remote-viewers": "vitest run --config vitest.viewer.config.ts",diff --git a/cli/src/backendSocket.ts b/cli/src/backendSocket.tsindex ad4d31d1d..7998eea8d 100644--- a/cli/src/backendSocket.ts+++ b/cli/src/backendSocket.ts@@ -29,6 +29,7 @@ import { ENGINES, type AgentEngine } from './engines/types.js'import { gridCliPresence } from './lib/gridBinary.js'import { GRID_FLEET_PROTOCOL, GRID_FLEET_MAX_TIMEOUT_MS } from './lib/gridFleetProtocol.js'import { isApiLaunch, parseGridLaunchOverride, type GridLaunchOverride } from './lib/gridLaunchWire.js'+import type { LaunchModel } from './lib/launchModel.js'import type { ScmLaunchRecord } from './scm/types.js'import type { StartedBy } from './lib/agentAttribution.js'import { probeEngines } from './lib/engineProbe.js'@@ -156,6 +157,9 @@ export class BackendSocket {/** A mode from `PERMISSION_MODES` for this engine; null when the client sent only* `bypassPermission`, which then decides. Validated here (`INVALID_PERMISSION_MODE`). */permissionMode: string | null+ /** The model and effort to launch the engine with, for that session only (lib/launchModel.ts); absent when the+ * engine should open on its own. Validated here, and only for an engine that declares the flags. */+ launchModel?: LaunchModel | null/** A conversation Harness did not start, to open this harness ON: the engine resumes it, in its own* folder (lib/sessionSearch/external.ts). Null for a new conversation. Shape-checked here; cli.ts* checks it is one it found, not open elsewhere, and not already a harness. */diff --git a/cli/src/core/agents/create.spec.ts b/cli/src/core/agents/create.spec.tsindex 52fbcc25e..f9ba3bac7 100644--- a/cli/src/core/agents/create.spec.ts+++ b/cli/src/core/agents/create.spec.ts@@ -627,6 +627,16 @@ describe('creating an agent', () => {expect(t.deps.gridLaunchMachine).toHaveBeenCalledWith('claude', undefined)})+ it('launches with the model and effort it was given, as a launch option the registry row never keeps', async () => {+ const { create } = setup()+ await create(request({ launchModel: { model: 'opus', effort: 'high' } }))+ const options = vi.mocked(buildEngineLaunchArgv).mock.calls[0][1] as Record<string, unknown>+ expect(options).toMatchObject({ launchModel: { model: 'opus', effort: 'high' } })+ expect(vi.mocked(createAndRegisterPane).mock.calls[0][0]).not.toHaveProperty('launchModel')+ await create(request())+ expect(vi.mocked(buildEngineLaunchArgv).mock.calls[1][1]).not.toHaveProperty('launchModel')+ })+it('opens as a named agent, with a first prompt, and does not install an engine with a path override', async () => {vi.mocked(enginePathOverride).mockReturnValueOnce('/opt/claude' as never)const { deps, create } = setup()diff --git a/cli/src/core/agents/create.ts b/cli/src/core/agents/create.tsindex fea5c9891..b893c4727 100644--- a/cli/src/core/agents/create.ts+++ b/cli/src/core/agents/create.ts@@ -99,7 +99,7 @@ export function createAgentCreator({if (input.resumeSessionId) return { ok: true, dispatch: () => externalResume(input) }const stale = () => ({ ok: false as const, error: 'LAUNCH_AUTHORITY_CHANGED', unavailable: 'launch', detail: 'Waiting for the original launch request’s authority.' })if (!authority.current()) return stale()- let { engine, cwd, bypassPermission, permissionMode, grid, codexHome, dsh, prompt, name, agent, scmLaunchRecord, startedBy, parentAgentId } = input+ let { engine, cwd, bypassPermission, permissionMode, grid, codexHome, dsh, prompt, name, agent, scmLaunchRecord, startedBy, parentAgentId, launchModel } = inputif (!tmuxBackend) return { ok: false, error: 'TMUX_UNAVAILABLE' }if (blocksFolder(cwd)) return { ok: false, error: 'WORKTREE_BUSY' }const workspaceIdentity = () => { const info = statSync(cwd); return `${info.dev}:${info.ino}:${realpathSync(cwd)}` }@@ -333,7 +333,7 @@ export function createAgentCreator({// The first prompt is a launch option only — never part of `extraArgs`, which the registry row// carries into a relaunch (engineLaunch.ts, `firstPrompt`).const firstPrompt = prompt- const launchOptions = { ...(native ? { native } : {}), bypassPermission, ...(permissionMode ? { permissionMode } : {}), extraArgs: extraArgs.length ? extraArgs : undefined, installIfMissing, clearEnv, cwd, harnessNode: dsh ? true : undefined, ...(firstPrompt ? { firstPrompt } : {}), terminalHint: { machineName: terminalHintMachineName() } }+ const launchOptions = { ...(native ? { native } : {}), bypassPermission, ...(permissionMode ? { permissionMode } : {}), extraArgs: extraArgs.length ? extraArgs : undefined, installIfMissing, clearEnv, cwd, harnessNode: dsh ? true : undefined, ...(firstPrompt ? { firstPrompt } : {}), ...(launchModel ? { launchModel } : {}), terminalHint: { machineName: terminalHintMachineName() } }const command = buildEngineCommandArgv(engine, launchOptions)const argv = buildEngineLaunchArgv(engine, launchOptions)// A tmux route is enough to stream its screen. Register it before looking for a process so bothdiff --git a/cli/src/core/agents/launches.spec.ts b/cli/src/core/agents/launches.spec.tsindex bab498eae..7b97d7b1f 100644--- a/cli/src/core/agents/launches.spec.ts+++ b/cli/src/core/agents/launches.spec.ts@@ -10,7 +10,7 @@ import type { NativeLaunchResult } from '../../engines/nativeLaunch.js'import { createNativeLaunchPreparer } from '../../engines/prepareNativeLaunch.js'import { AgentCreationReceiptError, AgentCreationReceipts, creationFingerprint, type AgentCreationOutcome } from '../../lib/agentCreationReceipt.js'import type { AgentFrame } from '../../lib/agentFrame.js'-import { MAX_FIRST_PROMPT_CHARS, permissionModeApproves, permissionModeFlags, supportsFirstPrompt, supportsNamedAgent } from '../../lib/engineLaunch.js'+import { MAX_FIRST_PROMPT_CHARS, permissionModeApproves, permissionModeFlags, supportsFirstPrompt, supportsNamedAgent, unsupportedLaunchModelFlag } from '../../lib/engineLaunch.js'import { parseGridLaunchOverride } from '../../lib/gridLaunchWire.js'import { parseNewAgentModel } from '../../lib/newAgentModel.js'import { parseProjectFolder, prepareProjectFolder, ProjectFolderError } from '../../lib/projectFolder.js'@@ -50,6 +50,8 @@ vi.mock('../../lib/engineLaunch.js', async (real) => ({...await real<object>(),supportsFirstPrompt: vi.fn(() => true), supportsNamedAgent: vi.fn(() => true),permissionModeFlags: vi.fn(() => ['--flag']), permissionModeApproves: vi.fn(() => false),+ // The engine's own --help is never run by a spec.+ unsupportedLaunchModelFlag: vi.fn(async () => null),}))vi.mock('../../lib/projectFolder.js', async (real) => {const actual = await real<typeof import('../../lib/projectFolder.js')>()@@ -351,6 +353,46 @@ describe('agent_create, launched', () => {expect(Object.keys(byPerson!)).not.toContain('startedBy')})+ it('hands a Claude launch its model and effort, and nothing for default, so older receipts\' fingerprints stay as they were', async () => {+ const { ask, create } = setup()+ await ask({ engine: 'claude', cwd: '/w', model: 'opus', effort: 'high' })+ await ask({ engine: 'claude', cwd: '/w', model: 'default', effort: 'default' })+ await ask({ engine: 'claude', cwd: '/w' })+ const [routed, byDefault, plain] = vi.mocked(create!).mock.calls.map(([input]) => input)+ expect(routed).toMatchObject({ engine: 'claude', launchModel: { model: 'opus', effort: 'high' } })+ expect(Object.keys(byDefault!)).not.toContain('launchModel')+ expect(Object.keys(plain!)).not.toContain('launchModel')+ })++ it('refuses a launch model before any receipt when the installed engine lacks a flag, and proceeds when it has them', async () => {+ const { ask, create, deps } = setup()+ vi.mocked(unsupportedLaunchModelFlag).mockResolvedValueOnce('--effort')+ expect(await ask({ engine: 'claude', cwd: '/w', creationId: CREATION, model: 'opus', effort: 'high' }))+ .toMatchObject({ error: 'LAUNCH_MODEL_UNSUPPORTED', detail: expect.stringContaining('--effort') })+ expect(unsupportedLaunchModelFlag).toHaveBeenCalledWith('claude', { model: 'opus', effort: 'high' })+ expect(create).not.toHaveBeenCalled()+ expect(deps.receipts.has(CREATION, 'any')).toBe(false)+ expect(deps.receipts.pendingIntent(CREATION)).toBeFalsy()+ // The same creation id is then free to start the agent without them.+ vi.mocked(unsupportedLaunchModelFlag).mockResolvedValueOnce(null)+ await ask({ engine: 'claude', cwd: '/w', creationId: CREATION, model: 'opus', effort: 'high' })+ await vi.waitFor(() => expect(create).toHaveBeenCalledOnce())+ expect(vi.mocked(create!).mock.calls[0][0]).toMatchObject({ launchModel: { model: 'opus', effort: 'high' } })+ })++ it('refuses a launch model its engine cannot take, a malformed one, and one beside a grid or a resumed conversation', async () => {+ const { ask, create } = setup()+ expect(await ask({ engine: 'codex', cwd: '/w', model: 'gpt-5', effort: 'high' })).toMatchObject({ error: 'LAUNCH_MODEL_UNSUPPORTED', detail: expect.stringContaining('codex') })+ expect(await ask({ engine: 'claude', cwd: '/w', model: 'opus; ls' })).toMatchObject({ error: 'INVALID_LAUNCH_MODEL' })+ expect(await ask({ engine: 'claude', cwd: '/w', effort: 'enormous' })).toMatchObject({ error: 'INVALID_LAUNCH_MODEL' })+ vi.mocked(parseGridLaunchOverride).mockReturnValueOnce({ state: 'ok', override: { networkName: 'g' } } as never)+ expect(await ask({ engine: 'claude', cwd: '/w', model: 'opus' })).toMatchObject({ error: 'INVALID_LAUNCH_MODEL', detail: expect.stringContaining('grid') })+ vi.mocked(parseNewAgentModel).mockReturnValueOnce({ state: 'ok', selection: { model: 'm', grid: 'g' } })+ expect(await ask({ engine: 'claude', cwd: '/w', model: 'opus' })).toMatchObject({ error: 'INVALID_LAUNCH_MODEL' })+ expect(await ask({ engine: 'claude', cwd: '/w', resumeSessionId: 'abc12345', model: 'opus' })).toMatchObject({ error: 'INVALID_SESSION' })+ expect(create).not.toHaveBeenCalled()+ })+it('hands on which harness here started it, and leaves out one this machine does not know', async () => {const { ask, create } = setup()await ask({ engine: 'claude', cwd: '/w', startedBy: 'agent', parentAgentId: 'a1' })diff --git a/cli/src/core/agents/launches.ts b/cli/src/core/agents/launches.tsindex c14630330..f6e83f900 100644--- a/cli/src/core/agents/launches.ts+++ b/cli/src/core/agents/launches.ts@@ -23,9 +23,10 @@ import type { AgentFrame } from '../../lib/agentFrame.js'import { engineLabel } from '../../lib/agentNames.js'import {AGENT_NAME_RE, FirstPromptUnsupportedError, MAX_FIRST_PROMPT_CHARS, NamedAgentUnsupportedError, permissionModeApproves,- permissionModeFlags, supportsFirstPrompt, supportsNamedAgent,+ permissionModeFlags, supportsFirstPrompt, supportsNamedAgent, unsupportedLaunchModelFlag,} from '../../lib/engineLaunch.js'import { parseGridLaunchOverride, type GridLaunchOverride } from '../../lib/gridLaunchWire.js'+import { parseLaunchModel } from '../../lib/launchModel.js'import { parseNewAgentModel, type NewAgentModel } from '../../lib/newAgentModel.js'import { parseProjectFolder, prepareProjectFolder, projectsRoot, ProjectFolderError, type ProjectFolder } from '../../lib/projectFolder.js'import type { ScmLaunchRecord } from '../../scm/types.js'@@ -323,6 +324,21 @@ export function createLaunchRequests({ receipts, createAgent, prepareCreate, preconst grid = parseGridLaunchOverride(payload.grid)if (grid.state === 'invalid') { reply({ error: 'INVALID_GRID', detail: grid.reason }); return }if (terminal && grid.state === 'ok') { reply({ error: 'INVALID_GRID', detail: 'a terminal has no engine to point at a grid' }); return }+ // A model and effort for this session alone, as flags (lib/launchModel.ts). Refused, never ignored: a daemon that+ // dropped them would start the agent on the engine's own model and look like it worked, so a caller that gets+ // LAUNCH_MODEL_UNSUPPORTED switches the model after the start instead. A grid picks its own model.+ const launchModel = parseLaunchModel(engine, payload)+ if (launchModel.state === 'invalid') { reply({ error: 'INVALID_LAUNCH_MODEL', detail: launchModel.detail }); return }+ if (launchModel.state === 'unsupported') { reply({ error: 'LAUNCH_MODEL_UNSUPPORTED', detail: launchModel.detail }); return }+ if (launchModel.state === 'ok' && (grid.state === 'ok' || model.state === 'ok')) {+ reply({ error: 'INVALID_LAUNCH_MODEL', detail: 'a grid chooses its own model' }); return+ }+ // A Claude Code too old for the flags would print its help in the new pane. Refused here, before any receipt, so the+ // caller creates the agent without them and switches the model afterwards, as it did before the flags.+ if (launchModel.state === 'ok') {+ const missing = await unsupportedLaunchModelFlag(engine, launchModel.launchModel)+ if (missing) { reply({ error: 'LAUNCH_MODEL_UNSUPPORTED', detail: `The ${engine} on this machine does not support ${missing}; update ${engine} to launch it with a model.` }); return }+ }// Same validation the desktop app already applies client-side (`Agent._safeCodexHome`) —// repeated here because a client's own check is not a guarantee about what actually// arrives on the wire.@@ -396,7 +412,7 @@ export function createLaunchRequests({ receipts, createAgent, prepareCreate, preif (typeof payload.resumeSessionId !== 'string' || !/^[A-Za-z0-9][A-Za-z0-9._-]{1,127}$/.test(payload.resumeSessionId)) {reply({ error: 'INVALID_SESSION', detail: 'resumeSessionId must be a session id' }); return}- if (terminal || projectFolder || grid.state === 'ok' || model.state === 'ok' || dsh || prompt || agent) {+ if (terminal || projectFolder || grid.state === 'ok' || model.state === 'ok' || launchModel.state === 'ok' || dsh || prompt || agent) {reply({ error: 'INVALID_SESSION', detail: 'a resumed conversation takes no new folder, grid, harness, prompt or agent' }); return}resumeSessionId = payload.resumeSessionId@@ -438,6 +454,7 @@ export function createLaunchRequests({ receipts, createAgent, prepareCreate, pretakeOver,// Only when set: a person's create keeps the fingerprint its receipt was recorded with before the field....(payload.startedBy === 'agent' ? { startedBy: 'agent' as const } : {}),+ ...(launchModel.state === 'ok' ? { launchModel: launchModel.launchModel } : {}),...(parentAgentId ? { parentAgentId } : {}),}const fingerprintInput = model.state === 'ok' ? { ...input, modelSelection: model.selection } : inputdiff --git a/cli/src/engines/claude/launch.ts b/cli/src/engines/claude/launch.tsindex df2f4e9a9..73167e104 100644--- a/cli/src/engines/claude/launch.ts+++ b/cli/src/engines/claude/launch.ts@@ -14,6 +14,9 @@ const permissionModes = {export const launch: EngineLaunch = {permissionModes, bypassPermission: permissionModes.auto,firstPromptArgs: [], resumeArgs: ['--resume'], forkArgs: { lead: ['--resume'], after: ['--fork-session'] },+ // `claude --help` (2.1.303): `--model` and `--effort` are "for the current session". `/model` and `/effort` typed into the+ // pane are saved as the person's default instead, which a routed start must not do.+ modelArgs: { model: ['--model', '{value}'], effort: ['--effort', '{value}'], efforts: ['low', 'medium', 'high', 'xhigh', 'max'] },instructionFiles: ['CLAUDE.md'],contextArgs: { args: ['--append-system-prompt', 'Read the harness context at {file} before working.'], quote: 'json' },// Claude Code reads CLAUDE.md, and AGENTS.md only through an import line in it.diff --git a/cli/src/engines/claude/runtimeProfile.ts b/cli/src/engines/claude/runtimeProfile.tsindex 6581ba923..afd149540 100644--- a/cli/src/engines/claude/runtimeProfile.ts+++ b/cli/src/engines/claude/runtimeProfile.ts@@ -33,7 +33,7 @@ function normalizeClaudeDisplay(value: string): string | null {return null}-function claudeAliasForModel(model: string): string | null {+export function claudeAliasForModel(model: string): string | null {const normalized = model.toLowerCase()if ((CLAUDE_ALIASES as readonly string[]).includes(normalized)) return normalizedreturn /^claude-(opus|fable|sonnet|haiku)(?:-|$)/.exec(normalized)?.[1] ?? nulldiff --git a/cli/src/engines/facets/launch.ts b/cli/src/engines/facets/launch.tsindex 12af35772..7218b305d 100644--- a/cli/src/engines/facets/launch.ts+++ b/cli/src/engines/facets/launch.ts@@ -230,12 +230,26 @@ export interface InstructionAttribution {args: readonly string[]}+/**+ * The flags that give ONE session its model and effort, so that nothing is written to the person's own engine+ * settings (Claude Code's `/model` and `/effort` commands are saved there as the new default). `{value}` in an+ * argument is the model or the effort. `efforts` are the levels the effort flag takes; any other is refused.+ * Applied by lib/launchModel.ts.+ */+export interface ModelArgsContract {+ model: readonly string[]+ effort: readonly string[]+ efforts: readonly string[]+}+/** Literal argv contracts copied from the existing launch paths. No engine version behavior changes. */export interface EngineLaunch {permissionModes: Readonly<Record<string, readonly string[]>>bypassPermission: string[]firstPromptArgs: readonly string[]resumeArgs: string[]+ /** How a new session is launched with a model and effort of its own, for this session only. */+ modelArgs?: ModelArgsContractforkArgs: { lead: string[]; after?: string[] }instructionFiles: readonly string[]contextArgs?: ContextArgsTemplatediff --git a/cli/src/lib/engineLaunch.spec.ts b/cli/src/lib/engineLaunch.spec.tsindex be5964063..c333054d8 100644--- a/cli/src/lib/engineLaunch.spec.ts+++ b/cli/src/lib/engineLaunch.spec.ts@@ -28,6 +28,7 @@ import {permissionFlagToVerify,permissionModeFlags,refusePermissionFlagIfUnsupported,+ unsupportedLaunchModelFlag,resetCommandFlagSupportCache,engineFallbackPrelude,ENGINE_INPUT_DRAIN_SH,@@ -816,6 +817,23 @@ describe('a login shell that is not POSIX', () => {})})+describe('a model and effort on launch', () => {+ it('gives Claude Code its model and effort as flags of that session, ahead of the first prompt', () => {+ expect(buildEngineCommandArgv('claude', { launchModel: { model: 'opus', effort: 'high' }, extraArgs: ['--x'], firstPrompt: 'go' }))+ .toEqual([engineBin('claude'), '--x', '--model', 'opus', '--effort', 'high', 'go'])+ expect(buildEngineCommandArgv('claude', { launchModel: { model: 'default', effort: 'default' } })).toEqual([engineBin('claude')])+ })++ it('keeps a model with shell characters one argv item, never part of a shell string', () => {+ const argv = buildEngineCommandArgv('claude', { launchModel: { model: 'a$(id)', effort: null } })+ expect(argv).toEqual([engineBin('claude'), '--model', 'a$(id)'])+ })++ it('leaves an engine without the flags as it was', () => {+ expect(buildEngineCommandArgv('codex', { launchModel: { model: 'gpt-5', effort: 'high' } })).toEqual(buildEngineCommandArgv('codex'))+ })+})+describe('a first prompt on launch', () => {const PROMPT = 'Start a local model on this machine'@@ -1079,6 +1097,34 @@ describe('the permission gates', () => {})})+describe('the launch model gate', () => {+ function withFakeClaude(help: string): string {+ const binDir = mkdtempSync(join(tmpdir(), 'harness-engine-gate-'))+ dirs.push(binDir)+ process.env.HARNESS_ENGINE_TEST_PATH = binDir+ fakeEngine(binDir, 'claude', help)+ return bashProbeShell()+ }++ it('names the first flag a build of the engine lacks', async () => {+ const shell = withFakeClaude('--model <model>')+ await expect(unsupportedLaunchModelFlag('claude', { model: 'opus', effort: 'high' }, shell)).resolves.toBe('--effort')+ await expect(unsupportedLaunchModelFlag('claude', { model: 'opus', effort: null }, shell)).resolves.toBeNull()+ })++ it('does not read a longer flag as the one it needs', async () => {+ const shell = withFakeClaude('--model <model>\n--effort-hint')+ await expect(unsupportedLaunchModelFlag('claude', { model: null, effort: 'high' }, shell)).resolves.toBe('--effort')+ })++ it('lets a build that has both flags through, and asks nothing for default or an engine without flags', async () => {+ const shell = withFakeClaude('--model <model>\n--effort <level>')+ await expect(unsupportedLaunchModelFlag('claude', { model: 'opus', effort: 'high' }, shell)).resolves.toBeNull()+ await expect(unsupportedLaunchModelFlag('claude', { model: 'default', effort: 'default' }, shell)).resolves.toBeNull()+ await expect(unsupportedLaunchModelFlag('codex', { model: 'x', effort: 'high' }, shell)).resolves.toBeNull()+ })+})+describe('permissionFlagToVerify', () => {it('names the single token a mode adds', () => {expect(permissionFlagToVerify('opencode', { permissionMode: 'auto' })).toBe('--auto')diff --git a/cli/src/lib/engineLaunch.ts b/cli/src/lib/engineLaunch.tsindex d941dfd44..dd7c93d6b 100644--- a/cli/src/lib/engineLaunch.ts+++ b/cli/src/lib/engineLaunch.ts@@ -16,6 +16,7 @@ import { isTerminalEngine, type AgentEngine } from '../engines/types.js'import { isOpencodeV2 } from '../engines/opencode/contract.js'import { binaryOnPath, resolveBinaryOnPath } from './binaryOnPath.js'import { engineBin } from './engineBin.js'+import { launchModelArgs, type LaunchModel } from './launchModel.js'import { engineInstallPaths, npmEnginePrefix, type EngineInstallRecipe } from './engineInstall.js'import { engineLabel } from './agentNames.js'import { GRID_NO_UPDATE_CHECK_VAR, gridBinaryPath } from './gridBinary.js'@@ -220,6 +221,11 @@ export interface LaunchCommandOptions {* what the user typed.*/firstPrompt?: string+ /**+ * The model and effort this session runs on, as flags of that session alone (lib/launchModel.ts). A launch option+ * like `firstPrompt`: never written to the registry row, so a relaunch is the engine's own again.+ */+ launchModel?: LaunchModel/*** Terminal only: print the tile's banner before the first prompt — the wordmark, where this pane* is, that an agent typed here becomes the tile, and `harness remote`. Every NEW terminal tile@@ -378,6 +384,7 @@ export function buildEngineCommandArgv(engine: AgentEngine, opts: LaunchCommandO// Ahead of the extra arguments, so a grid's or a harness's own value for the same key is the one that holds.argv.push(...screenArgs(launchContract(engine)))if (opts.extraArgs?.length) argv.push(...opts.extraArgs)+ if (opts.launchModel) argv.push(...launchModelArgs(engine, opts.launchModel))if (opts.firstPrompt) argv.push(...firstPromptArgs(engine, opts.firstPrompt))return argv}@@ -1465,6 +1472,18 @@ async function unsupportedPermissionFlag(return support === 'unsupported' ? flag : null}+/**+ * The first flag of a launch model (lib/launchModel.ts) that the engine on disk does not list in its `--help`, or null.+ * It reads the help the way the permission gate does, through the same probe and cache, so a Claude Code too old for+ * `--model` or `--effort` is refused before a pane exists instead of printing its help in one. `unknown` never refuses.+ */+export async function unsupportedLaunchModelFlag(engine: AgentEngine, launchModel: LaunchModel, shell: string | undefined = undefined): Promise<string | null> {+ for (const flag of launchModelArgs(engine, launchModel).filter((arg) => arg.startsWith('--'))) {+ if (await commandSupportsFlagInInteractiveShell(engineBin(engine), flag, shell) === 'unsupported') return flag+ }+ return null+}+/*** For a launch somebody is waiting on — create, fork. Refusing is kinder than opening a pane that* the engine will fill with its own help text and leave: the person is here, and Ask works today.diff --git a/cli/src/lib/launchModel.spec.ts b/cli/src/lib/launchModel.spec.tsnew file mode 100644index 000000000..1ae9f28d1--- /dev/null+++ b/cli/src/lib/launchModel.spec.ts@@ -0,0 +1,67 @@+import { describe, expect, it } from 'vitest'+import { launchModelArgs, launchModelEngines, parseLaunchModel } from './launchModel.js'++describe('parseLaunchModel', () => {+ it('is absent when neither field is sent, or both are null', () => {+ expect(parseLaunchModel('claude', {})).toStrictEqual({ state: 'absent' })+ expect(parseLaunchModel('claude', { model: null, effort: null })).toStrictEqual({ state: 'absent' })+ })++ it('accepts a Claude model and effort', () => {+ expect(parseLaunchModel('claude', { model: 'opus', effort: 'high' })).toStrictEqual({ state: 'ok', launchModel: { model: 'opus', effort: 'high' } })+ expect(parseLaunchModel('claude', { model: ' claude-opus-5[1m] ' })).toStrictEqual({ state: 'ok', launchModel: { model: 'claude-opus-5[1m]', effort: null } })+ expect(parseLaunchModel('claude', { effort: 'max' })).toStrictEqual({ state: 'ok', launchModel: { model: null, effort: 'max' } })+ })++ it('treats default (and an automatic effort) as nothing to launch with', () => {+ expect(parseLaunchModel('claude', { model: 'default', effort: 'default' })).toStrictEqual({ state: 'absent' })+ expect(parseLaunchModel('claude', { model: 'opus', effort: 'auto' })).toStrictEqual({ state: 'ok', launchModel: { model: 'opus', effort: null } })+ expect(parseLaunchModel('claude', { model: 'default', effort: 'low' })).toStrictEqual({ state: 'ok', launchModel: { model: null, effort: 'low' } })+ // The same answer for an engine without support: nothing is asked of it.+ expect(parseLaunchModel('codex', { model: 'default', effort: 'default' })).toStrictEqual({ state: 'absent' })+ })++ it.each([+ { model: 7 }, { model: '' }, { model: ' ' }, { model: 'opus; rm -rf ~' }, { model: '--settings' }, { model: '$(id)' },+ { model: 'a b' }, { model: 'x'.repeat(65) }, { model: 'opus\nsonnet' },+ { effort: 3 }, { effort: 'enormous' }, { effort: 'high; ls' }, { effort: '--model' }, { effort: '' },+ ])('refuses %j as invalid', (payload) => {+ expect(parseLaunchModel('claude', payload)).toMatchObject({ state: 'invalid', detail: expect.any(String) })+ })++ it('refuses an engine that cannot take a launch model', () => {+ expect(parseLaunchModel('codex', { model: 'gpt-5', effort: 'high' })).toMatchObject({ state: 'unsupported', detail: expect.stringContaining('codex') })+ expect(parseLaunchModel('terminal', { model: 'opus' })).toMatchObject({ state: 'unsupported' })+ })++ it('checks the shape before the engine, so a malformed value is never called unsupported', () => {+ expect(parseLaunchModel('codex', { model: 'a b' })).toMatchObject({ state: 'invalid' })+ })+})++describe('launchModelArgs', () => {+ it('is the model alone', () => {+ expect(launchModelArgs('claude', { model: 'opus', effort: null })).toStrictEqual(['--model', 'opus'])+ })++ it('is the model and the effort, each its own argv item', () => {+ expect(launchModelArgs('claude', { model: 'claude-opus-5[1m]', effort: 'xhigh' })).toStrictEqual(['--model', 'claude-opus-5[1m]', '--effort', 'xhigh'])+ })++ it('is the effort alone', () => {+ expect(launchModelArgs('claude', { model: null, effort: 'low' })).toStrictEqual(['--effort', 'low'])+ })++ it('skips default and keeps a value with a replacement pattern as written', () => {+ expect(launchModelArgs('claude', { model: 'default', effort: 'default' })).toStrictEqual([])+ expect(launchModelArgs('claude', { model: 'a$&b', effort: null })).toStrictEqual(['--model', 'a$&b'])+ })++ it('names nothing for an engine without support', () => {+ expect(launchModelArgs('codex', { model: 'gpt-5', effort: 'high' })).toStrictEqual([])+ })+})++it('names the engines that take a launch model', () => {+ expect(launchModelEngines()).toStrictEqual(['claude'])+})diff --git a/cli/src/lib/launchModel.ts b/cli/src/lib/launchModel.tsnew file mode 100644index 000000000..4edddee56--- /dev/null+++ b/cli/src/lib/launchModel.ts@@ -0,0 +1,60 @@+/**+ * The model and effort a new agent is launched with, for that session only (`EngineLaunch.modelArgs`). A routed+ * Super Tab start used to type `/model` into the new pane, which Claude Code saves as the person's default model+ * in their own settings.json (manual run 2, 2026-10-19). A flag on the command line is not saved anywhere.+ */+import { fill } from '../engines/kit/launchArgs.js'+import { engineLaunches, launchContract } from '../engines/launches.js'++export interface LaunchModel { model: string | null; effort: string | null }++export type ParsedLaunchModel =+ | { state: 'absent' }+ | { state: 'ok'; launchModel: LaunchModel }+ | { state: 'invalid'; detail: string }+ | { state: 'unsupported'; detail: string }++// One word, as the engines name models: an alias, a full name, `claude-opus-5[1m]`. A flag, a space or a shell+// character never fits, and it travels as its own argv item besides, so it is never read by a shell.+const MODEL = /^[A-Za-z0-9][A-Za-z0-9._:\-[\]]{0,63}$/+const EFFORT = /^[a-z]{1,16}$/+const SHAPE = 'model and effort must each be a short word'++/** `default` keeps what the engine would launch with, and `auto` is no level of its own: neither is a flag. */+const named = (value: string, none: readonly string[]) => none.includes(value) ? null : value++/** Reads `model` and `effort` of an `agent_create` payload. Absent when nothing remains to launch with. */+export function parseLaunchModel(engine: string, payload: Record<string, unknown>): ParsedLaunchModel {+ const fields: Array<['model' | 'effort', unknown]> = [['model', payload.model], ['effort', payload.effort]]+ const read: LaunchModel = { model: null, effort: null }+ for (const [field, raw] of fields) {+ if (raw === undefined || raw === null) continue+ const value = typeof raw === 'string' ? raw.trim() : null+ if (value === null || !(field === 'model' ? MODEL : EFFORT).test(value)) return { state: 'invalid', detail: SHAPE }+ read[field] = named(value, field === 'model' ? ['default'] : ['default', 'auto'])+ }+ if (!read.model && !read.effort) return { state: 'absent' }+ const contract = launchContract(engine)?.modelArgs+ if (!contract) return { state: 'unsupported', detail: `${engine} cannot be launched with a model; it takes one after it starts.` }+ if (read.effort && !contract.efforts.includes(read.effort)) {+ return { state: 'invalid', detail: `${engine} takes an effort of ${contract.efforts.join(', ')}` }+ }+ return { state: 'ok', launchModel: read }+}++/** The argv for `launchModel`, nothing for `default` or for an engine that declares no flags. */+export function launchModelArgs(engine: string, launchModel: LaunchModel): string[] {+ const contract = launchContract(engine)?.modelArgs+ if (!contract) return []+ const model = launchModel.model && named(launchModel.model, ['default'])+ const effort = launchModel.effort && named(launchModel.effort, ['default', 'auto'])+ return [+ ...(model ? contract.model.map((arg) => fill(arg, 'value', model)) : []),+ ...(effort ? contract.effort.map((arg) => fill(arg, 'value', effort)) : []),+ ]+}++/** The engines that take a launch model: what `super_tabs capacity` tells a Lead's machine. */+export function launchModelEngines(): string[] {+ return Object.entries(engineLaunches).filter(([, launch]) => launch.modelArgs).map(([name]) => name)+}diff --git a/cli/src/lib/productUsageContract.ts b/cli/src/lib/productUsageContract.tsindex 8b6c51120..5bb5247a2 100644--- a/cli/src/lib/productUsageContract.ts+++ b/cli/src/lib/productUsageContract.ts@@ -85,6 +85,7 @@ export const LAUNCH_ERROR_CODES = [// What a new harness asked for, refused before anything starts (core/agents/launches.ts, lib/engineLaunch.ts).'invalid_codex_home', 'invalid_prompt', 'prompt_too_long', 'prompt_unsupported', 'invalid_agent', 'invalid_session','invalid_started_by', 'agent_unsupported', 'invalid_runtime_profile', 'grid_engine_unsupported', 'codex_cli_too_old',+ 'invalid_launch_model', 'launch_model_unsupported',// A new project's folder (lib/projectFolder.ts) and the launch's durable receipt (lib/agentCreationReceipt.ts).'project_exists', 'invalid_repository', 'clone_failed', 'clone_timeout', 'git_unavailable', 'project_preparation_failed','creation_conflict', 'creation_storage_failed', 'launch_authority_changed', 'internal',diff --git a/cli/src/services/processCoreApi.spec.ts b/cli/src/services/processCoreApi.spec.tsindex fa5cb2583..b0364227c 100644--- a/cli/src/services/processCoreApi.spec.ts+++ b/cli/src/services/processCoreApi.spec.ts@@ -145,7 +145,9 @@ describe('the core API a light service runs on in its own process', () => {await expect(withSummaries.agents.summaries(['a1'])).resolves.toEqual({})expect(api.account.signedIn()).toBe(false)expect(api.account.environment()).toBe('')- await expect(api.account.machines()).resolves.toEqual({ status: 503, body: {} })+ await expect(api.account.machines()).resolves.toEqual({ status: 503, body: { error: 'SERVICE_UNAVAILABLE' } })+ // What the devices' process starts from before it asks the core for the list.+ await expect(UNASKED.account.machines()).resolves.toEqual({ status: 503, body: {} })api.clients.sendLocal({ type: 'dial_focus', payload: {} })expect(api.clients.sendToWindow('w1', { type: 'dial_form', payload: {} })).toBe(false)expect(api.clients.hasWindow()).toBe(false)@@ -189,6 +191,17 @@ describe('the core API a light service runs on in its own process', () => {expect(listeners).toHaveLength(1)})+ it('lists the account\'s machines the way it reads the backend, and no more than that read may ask', async () => {+ const ask = vi.fn(async (_query: string, _payload: Record<string, unknown>): Promise<Record<string, unknown>> => ({ status: 200, body: { data: { machines: [{ machineId: 'm1', name: 'remote-1' }] } } }))+ const api = processCoreApi('/data', 'superTabs', { ask })+ expect(await api.account.machines()).toEqual({ status: 200, body: { data: { machines: [{ machineId: 'm1', name: 'remote-1' }] } } })+ expect(ask).toHaveBeenCalledOnce()+ expect(ask).toHaveBeenCalledWith('backend', { method: 'GET', path: '/api/machines' })+ // A service the core does not answer for (it is not an experiment) gets the core's refusal, not a list.+ ask.mockResolvedValueOnce({ error: 'NOT_AN_EXPERIMENT' })+ expect(await processCoreApi('/data', 'store', { ask }).account.machines()).toEqual({ status: 502, body: { error: 'NOT_AN_EXPERIMENT' } })+ })+it('gives the cloud agents their doors only with a core to ask, and never waits on or throws from them', async () => {expect(processCoreApi('/data', 'cloud').cloud).toBeUndefined()const ask = vi.fn(async (_query: string): Promise<Record<string, unknown>> => { throw new Error('gone') })diff --git a/cli/src/services/processCoreApi.ts b/cli/src/services/processCoreApi.tsindex 1b56a4ed0..22930b67b 100644--- a/cli/src/services/processCoreApi.ts+++ b/cli/src/services/processCoreApi.ts@@ -96,6 +96,13 @@ export function processCoreApi(dataDir: string, service: string, view: AgentsVieconst live = (): ShownAgent[] => view.live?.() ?? []const ask = view.askconst daemon = (): DaemonAddress => view.daemon?.() ?? DAEMON_UNKNOWN+ const backend: CoreApi['account']['backend'] = async (method, path, body) => {+ const answer = await (ask?.('backend', { method, path, ...(body === undefined ? {} : { body }) }) ?? Promise.reject(new Error('no core to ask')))+ .catch((): Payload => ({ status: 503, body: { error: 'SERVICE_UNAVAILABLE' } }))+ return typeof answer.status === 'number' && answer.body && typeof answer.body === 'object'+ ? { status: answer.status, body: answer.body as Payload }+ : { status: 502, body: { error: typeof answer.error === 'string' ? answer.error : 'BACKEND_UNREACHABLE' } }+ }return {dataDir,usage: async target => {@@ -183,13 +190,7 @@ export function processCoreApi(dataDir: string, service: string, view: AgentsVieconnectorVault: CONNECTOR_VAULT_OFF,privateGridName: async () => null,machineName: () => null,- backend: async (method, path, body) => {- const answer = await (ask?.('backend', { method, path, ...(body === undefined ? {} : { body }) }) ?? Promise.reject(new Error('no core to ask')))- .catch((): Payload => ({ status: 503, body: { error: 'SERVICE_UNAVAILABLE' } }))- return typeof answer.status === 'number' && answer.body && typeof answer.body === 'object'- ? { status: answer.status, body: answer.body as Payload }- : { status: 502, body: { error: typeof answer.error === 'string' ? answer.error : 'BACKEND_UNREACHABLE' } }- },+ backend,// The account signed in here, asked of the core: Share derives its tabs' observers for it (core/experimentQueries.ts// `account`), and Agent Messages asks its own link (services/messagesProcess.ts). A core that cannot say: none.identity: async () => {@@ -199,6 +200,10 @@ export function processCoreApi(dataDir: string, service: string, view: AgentsVie},onNotice: (listener) => view.onNotice?.(listener) ?? (() => {}),...UNASKED.account,+ // The account's machine list is the one read of `/api/machines` the core's `backend` answer gives an experiment+ // already, so a service that is not asked for it gets the same refusal for it as for any other path. The Super+ // Tab service's route context needs it: in its own process it saw none (the 2026-10-19 manual run).+ machines: () => backend('GET', '/api/machines'),},clients: {viewerChanged: () => {}, viewerFrame: () => false, gridNamed: () => {}, gridModelsChanged: () => {}, dshInstallStatus: () => {},diff --git a/cli/src/superTabs/capacity.spec.ts b/cli/src/superTabs/capacity.spec.tsindex ece9cc618..b8baa14cf 100644--- a/cli/src/superTabs/capacity.spec.ts+++ b/cli/src/superTabs/capacity.spec.ts@@ -6,6 +6,8 @@ it('uses the destination filesystem and reports missing tools/devices without exdisk: vi.fn(async () => ({ freeBytes: 500, volume: 'volume', path: '/fixture/repo' })), tool: vi.fn(async () => true), device: vi.fn(async () => true) }const capacity = await readCapabilities({ cwd: '/fixture/repo', tools: ['git'], devices: ['/dev/test'] }, deps)expect(deps.disk).toHaveBeenCalledWith('/fixture/repo', false)+ // Which engines this daemon launches with a model: a daemon without the field gets the switch after the start.+ expect(capacity).toMatchObject({ ok: true, launchModel: ['claude'] })expect(admission(capacity, { installed: true }, quotaOf({}, 'codex', false), requirements)).toMatchObject({ allowed: true, unknown: ['Subscription allowance is unknown for this account.'] })deps.disk.mockRejectedValueOnce(new Error('not mounted'))const missing = await readCapabilities({ cwd: '/fixture/repo', tools: [], devices: [] }, deps)diff --git a/cli/src/superTabs/capacity.ts b/cli/src/superTabs/capacity.tsindex 861bde789..3f678ebcd 100644--- a/cli/src/superTabs/capacity.ts+++ b/cli/src/superTabs/capacity.ts@@ -3,6 +3,7 @@ import { constants } from 'node:fs'import { isAbsolute } from 'node:path'import { readMachineResources } from '../lib/machineResources.js'import { commandAvailableInInteractiveShell } from '../lib/engineLaunch.js'+import { launchModelEngines } from '../lib/launchModel.js'import { object } from './wire.js'import { readCapacityDisk } from './disk.js'@@ -11,6 +12,13 @@ export interface Requirements {memoryBytes: number; diskBytes: number; maxCpuPercent: numbertools: string[]; devices: string[]; quotaRequired: boolean}+/** What `start` asks of a machine when the Lead has no reason to ask for more: the help's template. */+export const START_REQUIREMENTS: Requirements = { memoryBytes: 2147483648, diskBytes: 10737418240, maxCpuPercent: 85, tools: ['git'], devices: [], quotaRequired: false }+/** The same plus what the task needs. The route admits a pick on exactly this, so the start it suggests is admitted too. */+export const startRequirements = (needs: { tools: string[]; devices: string[] }): Requirements =>+ // CPU use is only a momentary reading: a busy machine would refuse every candidate (seen in the route e2e at 98.7%), so the route does not cap it.+ ({ ...START_REQUIREMENTS, maxCpuPercent: 100, tools: [...new Set([...START_REQUIREMENTS.tools, ...needs.tools])], devices: needs.devices })+export async function readCapabilities(input: Json, deps = {resources: readMachineResources,disk: readCapacityDisk,@@ -40,7 +48,9 @@ export async function readCapabilities(input: Json, deps = {])return { ok: true, sampledAt: Date.now(), resources: { ...resources, projectDiskFreeBytes: disk?.freeBytes ?? null,projectDiskVolume: disk?.volume ?? null, projectDiskPath: disk?.path ?? null },- tools: Object.fromEntries(toolValues), devices: Object.fromEntries(deviceValues) }+ tools: Object.fromEntries(toolValues), devices: Object.fromEntries(deviceValues),+ // A daemon from before the launch flags leaves this out, and a start then switches the model after it.+ launchModel: launchModelEngines() }}const finite = (v: unknown): v is number => typeof v === 'number' && Number.isFinite(v)diff --git a/cli/src/superTabs/command.spec.ts b/cli/src/superTabs/command.spec.tsindex a6a12c1e7..502425750 100644--- a/cli/src/superTabs/command.spec.ts+++ b/cli/src/superTabs/command.spec.ts@@ -13,7 +13,7 @@ it('keeps an explicit stable receipt for agent messages and arbitrary work commaexpect(parseSuperTabArgs(['--tab', 'tab', 'status'], where).payload.agentId).toBe('')for (const argv of [[], ['status'], [...prefix, 'post', 'lead', 'Ready'], [...prefix, 'messages', '../other'],[...prefix, 'message', 'lead'], [...prefix, 'message', 'lead', '../other'], [...prefix, 'message', 'lead', 'id', 'extra'],- ['--port', 'no', 'help'], ['--machine', '', 'help'], [...prefix, 'status', 'extra']]) {+ ['--port', 'no', 'help'], ['--machine', '', 'help'], [...prefix, 'status', 'extra'], [...prefix, 'route', 'g1'], [...prefix, 'route', '../x', '{}']]) {expect(() => parseSuperTabArgs(argv, where)).toThrow('harness super-tab')}})@@ -40,3 +40,21 @@ it('uses the existing daemon transport and retains a receipt in an uncertain ansexpect(JSON.parse(print.mock.calls.at(-1)![0])).toEqual({ error: 'Connection lost', operationId: 'op' })expect(close).toHaveBeenCalledTimes(2)})+it('parses route GROUP JSON', () => {+ expect(parseSuperTabArgs([...prefix, 'route', 'g1', '{"difficulty":"low","risk":"low","why":"x"}'], where).payload)+ .toMatchObject({ action: 'route', conversationId: 'g1', assessment: { difficulty: 'low' } })+})+it('routes through the caller and prints the decision, or the parse failure as an error', 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: 'AGENT_UNAVAILABLE', detail: 'x' }+ return { ok: true }+ })+ const deps = { where: () => where, pane: '%42', open: async () => ({ request, close, machineId: 'machine' }), print }+ expect(await superTabCommand(['--tab', 'tab', 'route', 'g1', '{"difficulty":"low","risk":"low","why":"x"}'], 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: 'AGENT_UNAVAILABLE' })+ expect(await superTabCommand(['--tab', 'tab', 'route', 'g1', '{nope'], deps)).toBe(1)+ expect(JSON.parse(print.mock.calls.at(-1)![0]).error).toMatch(/JSON/)+})diff --git a/cli/src/superTabs/command.ts b/cli/src/superTabs/command.tsindex 74b4d56ea..556b6f41f 100644--- a/cli/src/superTabs/command.ts+++ b/cli/src/superTabs/command.ts@@ -1,10 +1,11 @@import { inspectCapacity, startAgent } from './start.js'import { object } from './host.js'+import { routeTask } from './routeCommand.js'import { openDaemon, whereFor, type Daemon, type Where } from '../agentClient/daemon.js'import { callerOf, type Frame } from '../agentClient/model.js'import { identifier } from './host.js'-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 | command OPERATION_ID JSON | start OPERATION_ID JSON | resume START_ID | capacity MACHINE_ID JSON | help'+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 | command OPERATION_ID JSON | start OPERATION_ID JSON | resume START_ID | capacity MACHINE_ID JSON | route GROUP JSON | help'export function parseSuperTabArgs(argv: readonly string[], where: Where) {const positional: string[] = []let tabId = '', agentId = ''@@ -35,6 +36,8 @@ export function parseSuperTabArgs(argv: readonly string[], where: Where) {} else if (action === 'resume' && identifier(first) && positional.length === 2) payload.startId = firstelse if (action === 'capacity' && identifier(first) && second && positional.length === 3) {Object.assign(payload, { targetMachineId: first, request: JSON.parse(second) })+ } else if (action === 'route' && identifier(first) && second && positional.length === 3) {+ Object.assign(payload, { conversationId: first, assessment: JSON.parse(second) })} else if (!['status', 'help'].includes(action) || positional.length !== 1) throw new Error(USAGE)return { where: target, payload }}@@ -73,6 +76,9 @@ export async function superTabCommand(argv: readonly string[], deps: {try { result = { ok: true, ...await inspectCapacity(target, object(request.payload.request)) } }finally { target.close() }}+ } 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 result = await daemon.request('super_tabs', request.payload, 30_000)print(JSON.stringify({ ...result, ...(operationId ? { operationId } : {}) }))return result.error ? 1 : 0diff --git a/cli/src/superTabs/host.ts b/cli/src/superTabs/host.tsindex 37df4fc63..e3b57ef5b 100644--- a/cli/src/superTabs/host.ts+++ b/cli/src/superTabs/host.ts@@ -342,7 +342,7 @@ export class SuperTabHost {return `You are participating in a shared Super Tab conversation (${group}). Other humans and agents see messages posted there.\n`+ `Read its state: ${command} status\nRead this conversation: ${command} messages ${shellQuote(group)}\n`+ `Reply there: ${command} post ${shellQuote(group)} 'your message' UNIQUE_OPERATION_ID\n`- + `Manage agreed work and delegation: ${command} help. Use independently verifiable outcomes; local helper subagents need no separate group.\n`+ + `Manage agreed work and delegation: ${command} help. Leads: route before starting or assigning: ${command} route GROUP JSON. Use independently verifiable outcomes; local helper subagents need no separate group.\n`+ `Ask questions and post results in this conversation. Include the exact revision, evidence and usable output links. Replies to these delivered instructions must be posted here explicitly.\n\n`+ native + reply + `Message ${String(message.id)} from ${String(object(message.author).name ?? 'a collaborator')}:\n${message.text}`}diff --git a/cli/src/superTabs/route.spec.ts b/cli/src/superTabs/route.spec.tsnew file mode 100644index 000000000..5415bfe84--- /dev/null+++ b/cli/src/superTabs/route.spec.ts@@ -0,0 +1,226 @@+// cli/src/superTabs/route.spec.ts+import { describe, expect, it } from 'vitest'+import { choose, decide, floorFor, jevQuestion, parseAssessment, quotaOf2, rateFor, recordOf, type Assessment, type Policy, type Probe } from './route.js'++const policy: Policy = { version: 1, floor: { low: 1, medium: 2, high: 3 }, quotaReserve: 10, notes: 'Frontend prefers Claude.', models: [+ { engine: 'claude', model: 'opus', effort: 'high', quality: 3, cost: 3, enabled: true },+ { 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 },+] }+const a = (patch: Partial<Assessment> = {}): Assessment => ({ difficulty: 'medium', risk: 'low', why: 'API change.', needs: { tools: [], devices: [] }, ...patch })+const probe = (patch: Partial<Probe> = {}): Probe => ({ kind: 'new', machineId: 'm1', machineName: 'remote-1', engine: 'claude', model: 'sonnet',+ effort: 'medium', quality: 2, cost: 2, quota: { known: true, leftPercent: 50, resetsAt: 1_000 }, activity: 'new', known: true, refusals: [], ...patch })++describe('assessment and floor', () => {+ it('parses a Lead assessment and explains what is wrong', () => {+ expect(parseAssessment({ difficulty: 'high', risk: 'low', why: ' Schema. ', needs: { tools: ['git'] } }))+ .toEqual({ difficulty: 'high', risk: 'low', why: 'Schema.', needs: { tools: ['git'], devices: [] } })+ expect(parseAssessment({ difficulty: 'hard', risk: 'low', why: 'x' })).toContain('difficulty')+ expect(parseAssessment({ difficulty: 'low', risk: 'low', why: 'x'.repeat(301) })).toContain('300')+ expect(parseAssessment({ difficulty: 'low', risk: 'low', why: 'x', needs: { cwd: 'relative' } })).toContain('absolute')+ expect(parseAssessment(null)).toContain('difficulty')+ })+ it('raises the floor by one for high risk, to at most 3', () => {+ expect(floorFor(policy, a())).toBe(2)+ expect(floorFor(policy, a({ risk: 'high' }))).toBe(3)+ expect(floorFor(policy, a({ difficulty: 'high', risk: 'high' }))).toBe(3)+ })+})++describe('quota and rates', () => {+ it('normalizes reset times from epoch seconds, milliseconds and ISO strings and uses the tightest window', () => {+ expect(quotaOf2({ known: true, windows: [{ usedPercent: 20, resetsAt: 1_800_000_000 }, { usedPercent: 70, resetsAt: '2026-10-19T12:00:00Z' }] }))+ .toEqual({ known: true, leftPercent: 30, resetsAt: Date.parse('2026-10-19T12:00:00Z') })+ expect(quotaOf2({ known: true, windows: [{ usedPercent: 10, resetsAt: 1_800_000_000 }] }).resetsAt).toBe(1_800_000_000_000)+ expect(quotaOf2({ known: true, windows: [{ usedPercent: 10, resetsAt: 1_800_000_000_000 }] }).resetsAt).toBe(1_800_000_000_000)+ expect(quotaOf2({ known: true, windows: [{ usedPercent: 10, resetsAt: 'soon' }] }).resetsAt).toBeNull()+ expect(quotaOf2({ known: false, windows: [] })).toEqual({ known: false, leftPercent: null, resetsAt: null })+ })+ it('rates a member by its policy row, then by model, else conservatively', () => {+ expect(rateFor(policy, 'claude', 'opus', 'high')).toEqual({ quality: 3, cost: 3 })+ expect(rateFor(policy, 'claude', 'opus', 'max')).toEqual({ quality: 3, cost: 3 })+ expect(rateFor(policy, 'claude', null, null)).toEqual({ quality: 1, cost: 1 })+ })+})++describe('choose', () => {+ it('returns NO_CANDIDATE with reasons when nothing can run', () => {+ expect(choose([probe({ refusals: ['Machine is offline.'] })], policy, a())).toEqual({ error: 'NO_CANDIDATE',+ excluded: [{ title: 'New agent · Claude sonnet medium · remote-1', reason: 'Machine is offline.' }] })+ })+ it('shows only floor-meeting candidates, ordered by cost, quota, reset and member first', () => {+ const r = choose([+ probe({ model: 'opus', effort: 'high', quality: 3, cost: 3 }),+ probe({ machineId: 'm2', machineName: 'mac', quota: { known: true, leftPercent: 80, resetsAt: 5_000 } }),+ probe({ quota: { known: true, leftPercent: 80, resetsAt: 2_000 } }),+ probe({ kind: 'member', agentId: 'a1', name: 'Multiply', quota: { known: true, leftPercent: 80, resetsAt: 2_000 }, activity: 'idle' }),+ probe({ model: 'haiku', effort: 'auto', quality: 1, cost: 1 }),+ probe(),+ ], policy, a())+ if ('error' in r) throw new Error('unexpected')+ expect(r.belowFloor).toBe(false)+ expect(r.shown.map(s => s.title)).toEqual([+ 'Multiply · Claude sonnet medium · remote-1',+ 'New agent · Claude sonnet medium · remote-1',+ 'New agent · Claude sonnet medium · mac',+ 'New agent · Claude sonnet medium · remote-1',+ 'New agent · Claude opus high · remote-1',+ ])+ expect(r.shown.map(s => s.id)).toEqual(['c0', 'c1', 'c2', 'c3', 'c4'])+ })+ it('marks belowFloor when nobody meets it, keeps the quota reserve, and prefers known candidates', () => {+ const r = choose([probe({ quality: 1 }), probe({ quality: 1, quota: { known: true, leftPercent: 5, resetsAt: null } })], policy, a({ difficulty: 'high' }))+ if ('error' in r) throw new Error('unexpected')+ expect(r.belowFloor).toBe(true)+ expect(r.shown).toHaveLength(1)+ const onlyReserve = choose([probe({ quota: { known: true, leftPercent: 5, resetsAt: null } })], policy, a())+ if ('error' in onlyReserve) throw new Error('unexpected')+ expect(onlyReserve.shown).toHaveLength(1)+ const unknown = choose([probe({ known: false, quota: { known: false, leftPercent: null, resetsAt: null } }), probe()], policy, a())+ if ('error' in unknown) throw new Error('unexpected')+ expect(unknown.shown.map(s => s.known)).toEqual([true])+ })+ it('shows at most 12 candidates', () => {+ const r = choose(Array.from({ length: 20 }, (_, i) => probe({ machineId: `m${i}`, machineName: `box-${String(i).padStart(2, '0')}` })), policy, a())+ if ('error' in r) throw new Error('unexpected')+ expect(r.shown).toHaveLength(12)+ })+})++describe('Jev context and verdict', () => {+ const choice = () => { const r = choose([probe({ kind: 'member', agentId: 'a1', name: 'Multiply', activity: 'idle' }), probe({ machineName: 'mac' })], policy, a()); if ('error' in r) throw new Error('x'); return r }+ it('builds at most four string keys within the hosted limits, with no email', () => {+ const q = jevQuestion({ title: 'Build', brief: 'b'.repeat(5000), checks: ['Tests pass', 'Docs updated'], history: ['Builder: stopped'] }, a(), policy, choice())+ expect(Object.keys(q.state)).toEqual(['task', 'lead', 'policy', 'history'])+ expect(Object.values(q.state).every(v => typeof v === 'string')).toBe(true)+ expect(Object.values(q.state).join('').length).toBeLessThanOrEqual(17_000)+ expect(q.state.task.length).toBeLessThan(5000)+ expect(q.state.policy).toContain('Frontend prefers Claude.')+ expect(Object.keys(q.questions.who.criteria)).toEqual(['c0', 'c1'])+ expect(Object.values(q.questions.who.criteria).every(v => v.length <= 640)).toBe(true)+ expect(q.questions.who.instructions.length).toBeLessThanOrEqual(1500)+ expect(JSON.stringify(q)).not.toMatch(/@/)+ })+ it('takes a sure Jev pick, falls back to order when unsure or unavailable, and skips Jev for one candidate', () => {+ const c = choice()+ expect(decide(c, { choice: 'c1', probabilities: { c0: 0.2, c1: 0.8 } }, null)).toMatchObject({ via: 'jev', p: 0.8, pick: { id: 'c1' } })+ expect(decide(c, { choice: 'c1', probabilities: { c0: 0.45, c1: 0.55 } }, null)).toMatchObject({ via: 'order', fallback: 'unsure', pick: { id: 'c0' }, why: expect.stringContaining('Jev unsure') })+ expect(decide(c, undefined, 'BUSY')).toMatchObject({ via: 'order', fallback: 'unavailable', pick: { id: 'c0' }, why: expect.stringContaining('Jev unavailable') })+ const one = choose([probe()], policy, a()); if ('error' in one) throw new Error('x')+ expect(decide(one, undefined, null)).toMatchObject({ via: 'only', p: null })+ })+ it('broken Jev answers fall back to order', () => {+ const c = choice()+ expect(decide(c, { choice: 'c9', probabilities: { c0: 0.1, c9: 0.9 } }, null).via).toBe('order')+ expect(decide(c, { choice: 'c1', probabilities: { c1: 0.9 } }, null).via).toBe('order')+ })+ it('produces a record the backend schema accepts', () => {+ const c = choice(), v = decide(c, { choice: 'c1', probabilities: { c0: 0.2, c1: 0.8 } }, null)+ expect(recordOf(c, v, a(), policy)).toEqual({ assessment: { difficulty: 'medium', risk: 'low', why: 'API change.' },+ candidates: c.shown.map(s => ({ id: s.id, kind: s.kind, ...(s.agentId ? { agentId: s.agentId } : {}), machineId: s.machineId,+ engine: s.engine, model: s.model, effort: s.effort, quality: s.quality, cost: s.cost, title: s.title, label: s.label })),+ excluded: [], floor: 2, notes: true, pick: 'c1', via: 'jev', p: 0.8, belowFloor: false, why: v.why })+ // The policy order says which fallback decided; the other routes carry none.+ const order = decide(c, undefined, 'BUSY')+ expect(recordOf(c, order, a(), policy)).toMatchObject({ via: 'order', fallback: 'unavailable', why: order.why })+ })+})++describe('edges', () => {+ const unknownQuota = { known: false, leftPercent: null, resetsAt: null }+ const ok = (r: ReturnType<typeof choose>) => { if ('error' in r) throw new Error('x'); return r }+ it('rejects a bad risk or a missing why and ignores malformed needs', () => {+ expect(parseAssessment({ difficulty: 'low', risk: 'urgent', why: 'x' })).toContain('risk')+ expect(parseAssessment({ difficulty: 'low', risk: 'low', why: 7 })).toContain('why')+ expect(parseAssessment({ difficulty: 'low', risk: 'low', why: 'x', needs: null }))+ .toEqual({ difficulty: 'low', risk: 'low', why: 'x', needs: { tools: [], devices: [] } })+ expect(parseAssessment({ difficulty: 'low', risk: 'low', why: 'x', needs: { tools: 'git', devices: [1], cwd: 5 } })).toContain('absolute')+ expect(parseAssessment({ difficulty: 'low', risk: 'low', why: 'x', needs: { devices: ['cam'], cwd: '/work' } }))+ .toEqual({ difficulty: 'low', risk: 'low', why: 'x', needs: { tools: [], devices: ['cam'], cwd: '/work' } })+ })+ it('keeps the tightest window whatever its order and drops an unusable reset', () => {+ expect(quotaOf2({ known: true, windows: [{ usedPercent: 70, resetsAt: 1_800_000_000 }, { usedPercent: 20, resetsAt: null }] }))+ .toEqual({ known: true, leftPercent: 30, resetsAt: 1_800_000_000_000 })+ expect(quotaOf2({ known: true, windows: [{ usedPercent: 20, resetsAt: null }] }).resetsAt).toBeNull()+ expect(quotaOf2({ known: true, windows: [{ usedPercent: 130, resetsAt: null }] }).leftPercent).toBe(0)+ })+ it('rates default models, unknown models and unknown engines', () => {+ expect(rateFor(policy, 'codex', null, null)).toEqual({ quality: 3, cost: 2 })+ expect(rateFor(policy, 'claude', 'sonnet', null)).toEqual({ quality: 2, cost: 2 })+ expect(rateFor(policy, 'codex', 'gpt-x', 'high')).toEqual({ quality: 3, cost: 2 })+ expect(rateFor(policy, 'other', 'gpt-x', 'high')).toEqual({ quality: 1, cost: 1 })+ })+ it('rates a working member by the model its engine reported, not only by the catalog alias', () => {+ expect(rateFor(policy, 'claude', 'claude-opus-4-7', 'high')).toEqual({ quality: 3, cost: 3 })+ expect(rateFor(policy, 'claude', 'claude-opus-4-7', 'xhigh')).toEqual({ quality: 3, cost: 3 })+ expect(rateFor(policy, 'claude', 'claude-sonnet-4-5[1m]', 'medium')).toEqual({ quality: 2, cost: 2 })+ expect(rateFor(policy, 'claude', 'sonnet[1m]', null)).toEqual({ quality: 2, cost: 2 })+ expect(rateFor(policy, 'claude', 'claude-haiku-4-5', 'auto')).toEqual({ quality: 1, cost: 1 })+ // Codex reports a real slug; its catalog row is `default`.+ expect(rateFor(policy, 'codex', 'gpt-5.5', 'high')).toEqual({ quality: 3, cost: 2 })+ // A model that matches nothing and an engine without a default row stay at the floor.+ expect(rateFor(policy, 'claude', 'claude-mystery-1', 'high')).toEqual({ quality: 1, cost: 1 })+ })+ it('titles and labels nameless members, unknown quota and quota without a reset', () => {+ const r = ok(choose([+ probe({ kind: 'member', agentId: 'a1', quota: { known: true, leftPercent: null, resetsAt: null } }),+ probe({ machineName: 'mac', quota: { known: true, leftPercent: 40, resetsAt: null } }),+ ], policy, a()))+ expect(r.shown.map(s => s.title)).toEqual(['New agent · Claude sonnet medium · mac', 'Member · Claude sonnet medium · remote-1'])+ expect(r.shown[1].label).toContain('Member ·')+ expect(r.shown[1].label).toContain('quota unknown')+ expect(r.shown[0].label).toContain('quota 40% left')+ expect(ok(choose([probe({ known: false, quota: unknownQuota })], policy, a())).shown[0].label).toContain('quota unknown')+ expect(ok(choose([probe({ quota: { known: true, leftPercent: 50, resetsAt: 0 } })], policy, a())).shown[0].label).toContain('resets in 1m')+ })+ it('tells Jev how far away a reset is, because Jev does not know the time', () => {+ const label = (resetsAt: number) => ok(choose([probe({ quota: { known: true, leftPercent: 50, resetsAt } })], policy, a(), 1_000_000)).shown[0].label+ expect(label(1_000_000 + 30 * 60_000)).toContain('quota 50% left, resets in 30m')+ expect(label(1_000_000 + 2 * 3_600_000)).toContain('resets in 2h')+ expect(label(1_000_000 + 5 * 86_400_000)).toContain('resets in 5 days')+ expect(label(1_000_000 - 5_000)).toContain('resets in 1m')+ // Without a clock argument it reads the real one.+ const soon = { known: true, leftPercent: 50, resetsAt: Date.now() + 3 * 3_600_000 }+ expect(ok(choose([probe({ quota: soon })], policy, a())).shown[0].label).toContain('resets in 3h')+ })+ it('falls back to unknown probes, to underfunded ones, and breaks every tie deterministically', () => {+ expect(ok(choose([probe({ known: false, quota: unknownQuota })], policy, a())).shown).toHaveLength(1)+ const tie = ok(choose([+ probe({ machineName: 'b', quota: unknownQuota }), probe({ machineName: 'a', quota: unknownQuota }),+ probe({ kind: 'member', agentId: 'a1', name: 'M', machineName: 'z', quota: unknownQuota }),+ ], policy, a()))+ expect(tie.shown.map(s => s.title.split(' · ')[2])).toEqual(['z', 'a', 'b'])+ expect(ok(choose([probe({ machineName: 'b' }), probe({ kind: 'member', agentId: 'a1', name: 'M' })], policy, a())).shown[0].kind).toBe('member')+ expect(ok(choose([probe({ kind: 'member', agentId: 'a1', name: 'M' }), probe({ machineName: 'b' })], policy, a())).shown[0].kind).toBe('member')+ })+ it('tells Jev about tools, devices, an empty history, a missed floor and absent notes', () => {+ const r = ok(choose([probe({ quality: 1 })], policy, a({ difficulty: 'high' })))+ const q = jevQuestion({ title: 'T', brief: '', checks: [], history: [] }, a({ needs: { tools: ['git', 'node'], devices: ['cam'] } }), { ...policy, notes: '' }, r)+ expect(q.state.lead).toContain('tools: git, node; devices: cam')+ expect(q.state.policy).toContain('no candidate meets it')+ expect(q.state.policy).toContain('Notes: none')+ expect(q.state.history).toBe('No earlier attempts.')+ })+ it('keeps a floor-meeting candidate even when it is low on quota or unknown', () => {+ const low = { known: true, leftPercent: 5, resetsAt: null }+ const r = ok(choose([probe({ quality: 1 }), probe({ quality: 3, machineName: 'mac', quota: low })], policy, a({ difficulty: 'high' })))+ expect(r.belowFloor).toBe(false)+ expect(r.shown.map(s => s.title)).toEqual(['New agent · Claude sonnet medium · mac'])+ const u = ok(choose([probe({ quality: 1 }), probe({ quality: 3, machineName: 'mac', known: false, quota: unknownQuota })], policy, a({ difficulty: 'high' })))+ expect(u.belowFloor).toBe(false)+ expect(u.shown.map(s => s.title)).toEqual(['New agent · Claude sonnet medium · mac'])+ })+ it('trims what the record carries to the backend limits', () => {+ const long = 'x'.repeat(900)+ const r = ok(choose([probe({ kind: 'member', agentId: 'a_1-B', name: long, machineId: 'm-1_X' }), probe({ machineName: long })], policy, a()))+ const rec = recordOf({ ...r, excluded: Array.from({ length: 250 }, () => ({ title: long.slice(0, 160), reason: long })) },+ decide(r, undefined, long), a(), { ...policy, notes: '' }) as { candidates: Array<Record<string, string>>; excluded: Array<{ reason: string }>; why: string; notes: boolean; p: number | null }+ expect(rec.candidates.every(c => /^c\d{1,2}$/.test(c.id) && c.title.length <= 160 && c.label.length <= 640 && /^[A-Za-z0-9_-]+$/.test(c.machineId))).toBe(true)+ expect(rec.excluded).toHaveLength(200)+ expect(rec.excluded.every(e => e.reason.length <= 500)).toBe(true)+ expect(rec.why.length).toBeLessThanOrEqual(300)+ expect(rec.notes).toBe(false)+ expect(rec.p).toBeNull()+ })+})diff --git a/cli/src/superTabs/route.ts b/cli/src/superTabs/route.tsnew file mode 100644index 000000000..bee396fda--- /dev/null+++ b/cli/src/superTabs/route.ts@@ -0,0 +1,150 @@+/** Super Tab routing v1, the pure half (docs/superpowers/specs/2026-10-19-super-tab-routing-v1-design.md).+ * The system removes what cannot run the task, Jev chooses among the rest with the full context, and a+ * fixed policy order decides when Jev is unsure or unavailable. Jev's acceptance rule is the voice+ * router's (`jevPick`), tuned on the owner's desk on 2026-10-10. */+import { isAbsolute } from 'node:path'+import type { JevChoice, JevChoiceAnswer } from '../lib/jev/jevClient.js'+import { claudeAliasForModel } from '../engines/claude/runtimeProfile.js'+import { jevPick } from '../lib/routeDecide.js'++export type Level = 'low' | 'medium' | 'high'+export interface Assessment { difficulty: Level; risk: Level; why: string; needs: { tools: string[]; devices: string[]; cwd?: string } }+export interface PolicyModel { engine: 'claude' | 'codex'; model: string; effort: string; quality: number; cost: number; enabled: boolean }+export interface Policy { version: 1; models: PolicyModel[]; floor: Record<Level, number>; quotaReserve: number; notes: string }+export interface Quota { known: boolean; leftPercent: number | null; resetsAt: number | null }+export interface Probe {+ kind: 'member' | 'new'; agentId?: string; name?: string; machineId: string; machineName: string+ engine: 'claude' | 'codex'; model: string; effort: string; quality: number; cost: number+ quota: Quota; activity: string; known: boolean; refusals: string[]+}+export interface Shown extends Probe { id: string; title: string; label: string }+export interface Choice { shown: Shown[]; excluded: Array<{ title: string; reason: string }>; floor: number; belowFloor: boolean }+export interface Verdict { pick: Shown; via: 'jev' | 'order' | 'only'; p: number | null; why: string; fallback?: 'unsure' | 'unavailable' }++const LEVELS: Level[] = ['low', 'medium', 'high']+const MAX_SHOWN = 12+const ENGINE = { claude: 'Claude', codex: 'Codex' } as const+const cut = (text: string, max: number) => text.length <= max ? text : `${text.slice(0, max - 1)}…`++export function parseAssessment(value: unknown): Assessment | string {+ const v = (value && typeof value === 'object' ? value : {}) as Record<string, unknown>+ if (!LEVELS.includes(v.difficulty as Level)) return 'Set difficulty to low, medium or high.'+ if (!LEVELS.includes(v.risk as Level)) return 'Set risk to low, medium or high.'+ const why = typeof v.why === 'string' ? v.why.trim() : ''+ if (!why || why.length > 300) return 'Give why in 1 to 300 characters.'+ const needs = (v.needs && typeof v.needs === 'object' ? v.needs : {}) as Record<string, unknown>+ const list = (x: unknown) => Array.isArray(x) && x.every(i => typeof i === 'string') ? x as string[] : []+ const cwd = needs.cwd+ if (cwd !== undefined && (typeof cwd !== 'string' || !isAbsolute(cwd))) return 'needs.cwd must be an absolute path.'+ return { difficulty: v.difficulty as Level, risk: v.risk as Level, why, needs: { tools: list(needs.tools), devices: list(needs.devices), ...(cwd ? { cwd } : {}) } }+}++export const floorFor = (policy: Policy, a: Assessment): number => Math.min(3, policy.floor[a.difficulty] + (a.risk === 'high' ? 1 : 0))++/** Claude sends ISO strings, Codex epoch seconds; anything above 1e10 is already milliseconds. */+function resetMs(value: unknown): number | null {+ if (typeof value === 'number' && Number.isFinite(value)) return value > 1e10 ? value : value * 1000+ if (typeof value === 'string') { const ms = Date.parse(value); return Number.isFinite(ms) ? ms : null }+ return null+}+export function quotaOf2(q: { known: boolean; windows: Array<{ usedPercent: number; resetsAt: unknown }> }): Quota {+ if (!q.known || !q.windows.length) return { known: false, leftPercent: null, resetsAt: null }+ const tightest = q.windows.reduce((x, y) => y.usedPercent > x.usedPercent ? y : x)+ return { known: true, leftPercent: Math.max(0, 100 - tightest.usedPercent), resetsAt: resetMs(tightest.resetsAt) }+}++/** A member's model is what its engine reported after work: Claude's full id (`claude-opus-4-7`, `claude-sonnet-4-5[1m]`),+ * Codex's slug (`gpt-5.5`). The policy names Claude families and a Codex `default`, so the id is reduced to its family+ * first, and an id with no row of its own takes the engine's `default` row before the floor. */+export function rateFor(policy: Policy, engine: string, model: string | null, effort: string | null): { quality: number; cost: number } {+ const name = engine === 'claude' && model ? claudeAliasForModel(model.replace(/\[1m\]$/i, '')) ?? model : model ?? 'default'+ const row = policy.models.find(m => m.engine === engine && m.model === name && m.effort === (effort ?? 'default'))+ ?? policy.models.find(m => m.engine === engine && m.model === name)+ ?? policy.models.find(m => m.engine === engine && m.model === 'default')+ return row ? { quality: row.quality, cost: row.cost } : { quality: 1, cost: 1 }+}++const titleOf = (p: Probe) => cut(`${p.kind === 'member' ? p.name ?? 'Member' : 'New agent'} · ${ENGINE[p.engine]} ${p.model} ${p.effort} · ${p.machineName}`, 160)+/** Jev does not know the time, so a reset is told as how far away it is. */+function resetsIn(resetsAt: number, now: number): string {+ const ms = Math.max(0, resetsAt - now)+ if (ms < 3_600_000) return `${Math.max(1, Math.round(ms / 60_000))}m`+ if (ms < 48 * 3_600_000) return `${Math.round(ms / 3_600_000)}h`+ return `${Math.round(ms / 86_400_000)} days`+}+function quotaText(q: Quota, now: number): string {+ if (!q.known || q.leftPercent === null) return 'quota unknown'+ if (q.resetsAt === null) return `quota ${Math.round(q.leftPercent)}% left`+ return `quota ${Math.round(q.leftPercent)}% left, resets in ${resetsIn(q.resetsAt, now)}`+}+const labelOf = (p: Probe, now: number) => cut(`${p.kind === 'member' ? `Member ${p.name ?? ''}`.trim() : 'New agent'} · ${ENGINE[p.engine]} ${p.model} ${p.effort} · quality ${p.quality}, cost ${p.cost} · ${p.machineName} · ${p.activity} · ${quotaText(p.quota, now)}`, 640)++/** The fixed policy order (D): cheaper, then more quota left, then an earlier reset, then a member, then by title. */+function compare(x: Probe, y: Probe): number {+ return x.cost - y.cost+ || (y.quota.leftPercent ?? -1) - (x.quota.leftPercent ?? -1)+ || (x.quota.resetsAt ?? Infinity) - (y.quota.resetsAt ?? Infinity)+ || (x.kind === y.kind ? 0 : x.kind === 'member' ? -1 : 1)+ || titleOf(x).localeCompare(titleOf(y))+}++export function choose(probes: Probe[], policy: Policy, a: Assessment, now: number = Date.now()): Choice | { error: 'NO_CANDIDATE'; excluded: Array<{ title: string; reason: string }> } {+ const excluded = probes.filter(p => p.refusals.length).map(p => ({ title: titleOf(p), reason: p.refusals.join(' ') }))+ const viable = probes.filter(p => !p.refusals.length)+ if (!viable.length) return { error: 'NO_CANDIDATE', excluded }+ const floor = floorFor(policy, a)+ // Each step narrows only when something is left, so a floor-meeting candidate is never dropped for being+ // unknown or low on quota; those are fallbacks, not filters.+ const meeting = viable.filter(p => p.quality >= floor)+ const byFloor = meeting.length ? meeting : viable+ const known = byFloor.filter(p => p.known)+ const byKnown = known.length ? known : byFloor+ const funded = byKnown.filter(p => p.quota.leftPercent === null || p.quota.leftPercent >= policy.quotaReserve)+ const set = funded.length ? funded : byKnown+ const shown = [...set].sort(compare).slice(0, MAX_SHOWN)+ .map((p, i) => ({ ...p, id: `c${i}`, title: titleOf(p), label: labelOf(p, now) }))+ return { shown, excluded, floor, belowFloor: !meeting.length }+}++const INSTRUCTIONS = cut([+ 'Choose the candidate that should do this task.',+ 'The Lead assessed its difficulty and risk; every candidate shown meets the quality floor unless the policy says none does.',+ 'Prefer lower cost, then more quota left and an earlier reset, unless the task, its history or the policy notes give a clear reason otherwise.',+ 'A candidate that already failed or stopped on this task is a worse choice. An idle member already in the Super Tab saves a start.',+].join(' '), 1500)++export function jevQuestion(input: { title: string; brief: string; checks: string[]; history: string[] }, a: Assessment, policy: Policy, choice: Choice) {+ const state = {+ task: cut(`Group: ${cut(input.title, 160)}\nBrief: ${cut(input.brief, 2000)}\nChecks:\n${cut(input.checks.map(c => `- ${c}`).join('\n'), 2000)}`, 4400),+ lead: cut(`Difficulty: ${a.difficulty}. Risk: ${a.risk}. Why: ${a.why}. Needs tools: ${a.needs.tools.join(', ') || 'none'}; devices: ${a.needs.devices.join(', ') || 'none'}.`, 800),+ policy: cut(`Quality floor: ${choice.floor}${choice.belowFloor ? ' (no candidate meets it; all are shown)' : ''}. Notes: ${policy.notes || 'none'}`, 700),+ history: cut(input.history.length ? input.history.join('\n') : 'No earlier attempts.', 2000),+ }+ const questions: Record<string, JevChoice> = {+ who: { type: 'choice', instructions: INSTRUCTIONS, criteria: Object.fromEntries(choice.shown.map(s => [s.id, s.label])) },+ }+ return { state, questions }+}++export function decide(choice: Choice, answer: JevChoiceAnswer | undefined, unavailable: string | null): Verdict {+ const first = choice.shown[0]+ if (choice.shown.length === 1) return { pick: first, via: 'only', p: null, why: 'Only candidate that can run this task.' }+ const picked = unavailable ? undefined : jevPick(answer, choice.shown.map(s => s.id), true)+ if (picked) {+ const pick = choice.shown.find(s => s.id === picked)!+ return { pick, via: 'jev', p: answer!.probabilities[picked], why: `Jev chose ${pick.title}.` }+ }+ const reason = unavailable ? `Jev unavailable (${unavailable})` : 'Jev unsure'+ return { pick: first, via: 'order', p: null, why: `${reason}; first in the policy order.`, fallback: unavailable ? 'unavailable' : 'unsure' }+}++export function recordOf(choice: Choice, verdict: Verdict, a: Assessment, policy: Policy): Record<string, unknown> {+ return {+ assessment: { difficulty: a.difficulty, risk: a.risk, why: a.why },+ candidates: choice.shown.map(s => ({ id: s.id, kind: s.kind, ...(s.agentId ? { agentId: s.agentId } : {}), machineId: s.machineId,+ engine: s.engine, model: s.model, effort: s.effort, quality: s.quality, cost: s.cost, title: s.title, label: s.label })),+ excluded: choice.excluded.slice(0, 200).map(e => ({ title: e.title, reason: cut(e.reason, 500) })),+ floor: choice.floor, notes: policy.notes.length > 0,+ pick: verdict.pick.id, via: verdict.via, ...(verdict.fallback ? { fallback: verdict.fallback } : {}), p: verdict.p, belowFloor: choice.belowFloor, why: cut(verdict.why, 300),+ }+}diff --git a/cli/src/superTabs/routeCommand.spec.ts b/cli/src/superTabs/routeCommand.spec.tsnew file mode 100644index 000000000..315c116bd--- /dev/null+++ b/cli/src/superTabs/routeCommand.spec.ts@@ -0,0 +1,318 @@+import { describe, expect, it, vi, type Mock } from 'vitest'+import type { openDaemon } from '../agentClient/daemon.js'+import { routeTask } from './routeCommand.js'+import { admission, quotaOf } from './capacity.js'++const policy = { version: 1, floor: { low: 1, medium: 2, high: 3 }, quotaReserve: 10, notes: '', models: [+ { engine: 'claude', model: 'opus', effort: 'high', quality: 3, cost: 3, enabled: true },+ { engine: 'claude', model: 'sonnet', effort: 'medium', quality: 2, cost: 2, enabled: true },+ { engine: 'codex', model: 'default', effort: 'default', quality: 3, cost: 2, enabled: false },+] }+const agents = [+ { id: 'a1', name: 'Multiply', machineId: 'm1', harnessId: 'h1', configuration: { engine: 'claude', model: 'sonnet', effort: 'medium' } },+ { id: 'lead', name: 'Lead', machineId: 'm1', harnessId: 'hl', configuration: { engine: 'claude', model: 'opus', effort: 'high' } },+]+const conversations = (assignment: unknown = null) => [+ { id: 'lead', title: 'Lead', leadId: 'lead', agentIds: ['lead', 'a1'], archived: false, brief: '', checks: [], assignment: null },+ { id: 'g1', title: 'API', leadId: 'lead', agentIds: ['lead'], archived: false, brief: 'Add the endpoint.', checks: [{ description: 'Tests pass' }], assignment },+]+const tab = (assignment: unknown = null) => ({ revision: 3, state: { id: 'tab', agents, conversations: conversations(assignment) } })+const usage = { providers: [{ provider: 'claude', outcome: 'answered', httpStatus: 200, account: 'acct', body: { five_hour: { utilization: 40, resets_at: '2026-10-19T12:00:00Z' }, seven_day: { utilization: 10 } } }] }+function daemon(machineId: string, options: { agents?: string[]; terminalAvailable?: boolean; tools?: Record<string, boolean>; devices?: Record<string, boolean>; usage?: unknown; listFails?: boolean; engines?: unknown } = {}) {+ return {+ machineId, close: vi.fn(),+ request: vi.fn(async (type: string, _payload?: unknown, _timeout?: number) => {+ if (type === 'agents_list') {+ if (options.listFails) throw new Error('timeout')+ return { agents: (options.agents ?? []).map(id => ({ id, terminal: { available: options.terminalAvailable ?? true } })) }+ }+ if (type === 'super_tabs') return { resources: { memoryTotalBytes: 8e9, memoryUsedBytes: 1e9, cpuPercent: 10, projectDiskFreeBytes: 1e11 }, tools: options.tools ?? { git: true }, devices: options.devices ?? {} }+ if (type === 'engines_probe') return { engines: options.engines ?? [{ engine: 'claude', installed: true, signedIn: true }] }+ if (type === 'usage_read') return options.usage ?? usage+ return {}+ }),+ }+}+type Answer = Record<string, unknown>+function scoped(answers: { jev?: Answer; record?: Answer; tab?: unknown; context?: Answer; jevThrows?: boolean; recordThrows?: boolean } = {}) {+ return vi.fn(async (payload: Record<string, any>): Promise<Record<string, unknown>> => {+ if (payload.action === 'routeContext') return answers.context ?? { ok: true, value: { agentId: 'lead', tab: answers.tab ?? tab(), policy: { policy, warnings: ['w'] }, machines: [{ machineId: 'm1', name: 'remote-1' }, { machineId: 'm2', name: 'mac' }] } }+ if (payload.action === 'routeJev') {+ if (answers.jevThrows) throw new Error('socket closed')+ // Jev answers over every candidate it was shown, as the real client's answers do.+ const ids = Object.keys(payload.questions.who.criteria)+ return answers.jev ?? { ok: true, value: { answers: { who: { choice: 'c1', probabilities: Object.fromEntries(ids.map(id => [id, id === 'c1' ? 0.9 : 0.1 / (ids.length - 1)])) } } } }+ }+ if (payload.action === 'command') {+ if (answers.recordThrows) throw new Error('socket closed')+ return answers.record ?? { ok: true, value: { result: { routeDecisionId: 'd1' } } }+ }+ return { error: 'UNEXPECTED' }+ })+}+const where = { port: 1, dataDir: '/nonexistent', machineId: 'm1' }+const input = { tabId: 'tab', conversationId: 'g1', assessment: { difficulty: 'medium', risk: 'low', why: 'Endpoint.' } }+const opener = (make: (id: string) => ReturnType<typeof daemon> = id => daemon(id, { agents: id === 'm1' ? ['h1'] : [] })) => vi.fn(async (_w: unknown, id = '') => make(id)) as unknown as typeof openDaemon & Mock+const recorded = (s: ReturnType<typeof scoped>) => s.mock.calls.find(c => c[0].action === 'command')![0]+const jevCall = (s: ReturnType<typeof scoped>) => s.mock.calls.find(c => c[0].action === 'routeJev')![0]++describe('routeTask', () => {+ it('collects members and new agents, asks Jev, records and returns the pick', async () => {+ const s = scoped()+ const result = await routeTask(input, s, where as never, opener(), () => 'op')+ expect(result).toMatchObject({ ok: true, routeDecisionId: 'd1', via: 'jev', pick: { id: 'c1' }, warnings: ['w'] })+ const record = recorded(s)+ expect(record).toMatchObject({ operationId: 'route-op', command: { type: 'route.record', conversationId: 'g1' } })+ // The idle Lead is not a candidate (neither the group's nor the tab's); the idle member Multiply is.+ const titles = (record.command.decision.candidates as Array<{ title: string }>).map(c => c.title)+ expect(titles).toContain('Multiply · Claude sonnet medium · remote-1')+ expect(titles.some(t => t.startsWith('Lead'))).toBe(false)+ expect((result.alternatives as unknown[]).length).toBeLessThanOrEqual(2)+ expect(titles.some(t => /^Lead|\bLead\b/.test(t.split(' · ')[0]))).toBe(false)+ // The Lead's id is never offered either, even where the group's Lead and the tab Lead differ.+ const other = tab(); (other.state.conversations[1] as Record<string, unknown>).leadId = 'a1'+ const t = scoped({ tab: other, context: { ok: true, value: { agentId: 'a1', tab: other, policy: { policy }, machines: [{ machineId: 'm1', name: 'remote-1' }] } } })+ await routeTask(input, t, where as never, opener(), () => 'op')+ const offered = (recorded(t).command.decision.candidates as Array<{ title: string }>).map(c => c.title)+ expect(offered.length).toBeGreaterThan(0)+ expect(offered.some(c => /^(Lead|Multiply) ·/.test(c))).toBe(false)+ })+ it('tells the Lead how to assign a member or start a new agent with the decision', async () => {+ const member = await routeTask(input, scoped({ jev: { ok: true, value: { unavailable: 'BUSY' } } }), where as never, opener(), () => 'op')+ // Cheapest first: the member on sonnet.+ expect(member).toMatchObject({ pick: { kind: 'member', agentId: 'a1' } })+ expect(member.next).toContain('"type":"work.assign","conversationId":"g1","agentId":"a1","routeDecisionId":"d1"')+ const fresh = await routeTask({ ...input, assessment: { ...input.assessment, difficulty: 'high' } }, scoped({ jev: { ok: true, value: { unavailable: 'BUSY' } } }), where as never, opener(), () => 'op')+ expect(fresh).toMatchObject({ pick: { kind: 'new', engine: 'claude', model: 'opus', effort: 'high' } })+ expect(fresh.next).toContain('"engine":"claude","model":"opus","effort":"high","routeDecisionId":"d1"')+ // A complete start: every field its schema requires, with the defaults the help gives.+ const hint = JSON.parse(/start OPERATION_ID (\{.*\}), then/.exec(fresh.next as string)![1]!)+ expect(hint).toEqual({ conversationId: 'g1', name: 'Builder', cwd: '/absolute/repo/on/that/machine', worktree: true,+ requirements: { memoryBytes: 2147483648, diskBytes: 10737418240, maxCpuPercent: 100, tools: ['git'], devices: [], quotaRequired: false },+ machineId: 'm2', engine: 'claude', model: 'opus', effort: 'high', routeDecisionId: 'd1' })+ // The task's own repository, when the assessment named one, and no decision when none was recorded.+ const placed = await routeTask({ ...input, assessment: { ...input.assessment, difficulty: 'high', needs: { cwd: '/repo/api' } } },+ scoped({ record: { error: 'BACKEND_UNAVAILABLE' } }), where as never, opener(), () => 'op')+ expect(JSON.parse(/start OPERATION_ID (\{.*\}), then/.exec(placed.next as string)![1]!)).toMatchObject({ cwd: '/repo/api' })+ expect(placed.next).not.toContain('routeDecisionId')+ })+ it('admits the pick on the requirements its start hint asks for, with the task\'s tools and devices', async () => {+ const needs = { tools: ['git', 'docker'], devices: ['/dev/ttyUSB0'] }+ const hard = { ...input, assessment: { ...input.assessment, difficulty: 'high', needs } }+ const daemons: ReturnType<typeof daemon>[] = []+ const make = opener((id) => { const d = daemon(id, { tools: { git: true, docker: true }, devices: { '/dev/ttyUSB0': true } }); daemons.push(d); return d })+ const result = await routeTask(hard, scoped(), where as never, make, () => 'op')+ const hint = JSON.parse(/start OPERATION_ID (\{.*\}), then/.exec(result.next as string)![1]!)+ expect(hint.requirements).toEqual({ memoryBytes: 2147483648, diskBytes: 10737418240, maxCpuPercent: 100, tools: ['git', 'docker'], devices: ['/dev/ttyUSB0'], quotaRequired: false })+ // The probe asked each machine about the same tools and devices, so what it admitted starts.+ const capacity = daemons.flatMap(d => d.request.mock.calls).filter(c => c[0] === 'super_tabs').map(c => c[1] as Record<string, unknown>)+ expect(capacity.length).toBeGreaterThan(0)+ for (const asked of capacity) expect(asked).toMatchObject({ tools: ['git', 'docker'], devices: ['/dev/ttyUSB0'] })+ })+ it('keeps a machine in the route when its CPU reads busy, because CPU use is only a momentary reading', async () => {+ const make = opener(id => {+ const d = daemon(id, { agents: id === 'm1' ? ['h1'] : [] }), request = d.request.getMockImplementation()!+ d.request.mockImplementation(async (type, payload, ms) => type === 'super_tabs' && (payload as Record<string, unknown>)?.action === 'capacity'+ ? { resources: { memoryTotalBytes: 8e9, memoryUsedBytes: 1e9, cpuPercent: 98, projectDiskFreeBytes: 1e11 }, tools: { git: true }, devices: {} }+ : request(type, payload, ms))+ return d+ })+ const result = await routeTask({ ...input, assessment: { ...input.assessment, difficulty: 'high' } }, scoped(), where as never, make, () => 'op')+ expect(result).toMatchObject({ ok: true, pick: { kind: 'new' } })+ })+ it('warns when the account\'s machines could not be read, and still offers the Lead\'s own machine', async () => {+ const context = { ok: true, value: { agentId: 'lead', tab: tab(), policy: { policy, warnings: ['w'] }, machines: [], machinesUnreadable: true } }+ const result = await routeTask(input, scoped({ context }), where as never, opener(), () => 'op')+ expect(result).toMatchObject({ ok: true, warnings: ['w', "The account's machine list could not be read; only known machines were considered."] })+ const fine = await routeTask(input, scoped(), where as never, opener(), () => 'op')+ expect(fine.warnings).toEqual(['w'])+ })+ it('names a member that has no name, model or effort of its own, and leaves the decision blank when it is unrecorded', async () => {+ const plain = tab(); plain.state.agents = [{ id: 'a1', machineId: 'm1', harnessId: 'h1', configuration: { engine: 'claude' } }, agents[1]] as never+ const options = { tab: plain, record: { error: 'BACKEND_UNAVAILABLE' }, jev: { ok: true, value: { unavailable: 'BUSY' } } }+ const easy = await routeTask({ ...input, assessment: { ...input.assessment, difficulty: 'low' } }, scoped(options), where as never, opener())+ expect(easy).toMatchObject({ unrecorded: true, pick: { kind: 'member', title: 'Member · Claude default default · remote-1' } })+ expect(easy.next).not.toContain('routeDecisionId')+ const hard = await routeTask({ ...input, assessment: { ...input.assessment, difficulty: 'high' } }, scoped(options), where as never, opener())+ expect(hard).toMatchObject({ unrecorded: true, pick: { kind: 'new' } })+ expect(hard.next).not.toMatch(/routeDecisionId"|same routeDecisionId/)+ })+ it('refuses a caller who is not the Lead of the group before probing anything', async () => {+ const open = vi.fn()+ const s = scoped({ context: { ok: true, value: { agentId: 'a1', tab: tab(), policy: { policy }, machines: [] } } })+ expect(await routeTask(input, s, where as never, open as never)).toMatchObject({ error: 'LEAD_REQUIRED' })+ expect(open).not.toHaveBeenCalled()+ })+ it('returns a Jev-stage refusal as the result instead of falling back to the policy order', async () => {+ for (const error of ['RATE_LIMITED', 'LEAD_REQUIRED']) {+ const s = scoped({ jev: { error, detail: 'no', status: 429 } })+ expect(await routeTask(input, s, where as never, opener())).toMatchObject({ error })+ expect(s.mock.calls.some(c => c[0].action === 'command')).toBe(false)+ }+ })+ it('returns a record refusal as an error, and only a transport failure as unrecorded', async () => {+ expect(await routeTask(input, scoped({ record: { error: 'RATE_LIMITED', detail: 'slow down', status: 429 } }), where as never, opener()))+ .toMatchObject({ error: 'RATE_LIMITED' })+ for (const error of ['BACKEND_UNAVAILABLE', 'BACKEND_TIMEOUT', 'BACKEND_UNREACHABLE', 'AGENT_UNAVAILABLE', 'SUPER_TAB_UNAVAILABLE']) {+ expect(await routeTask(input, scoped({ record: { error } }), where as never, opener())).toMatchObject({ ok: true, unrecorded: true })+ }+ })+ it('returns NO_CANDIDATE with reasons when every account machine is offline, without opening any', async () => {+ const open = vi.fn()+ const offline = { ok: true, value: { agentId: 'lead', tab: tab(), policy: { policy }, machines: [{ machineId: 'm1', name: 'remote-1', status: 'offline' }, { machineId: 'm2', name: 'mac', status: 'offline' }] } }+ const result = await routeTask(input, scoped({ context: offline }), where as never, open as never)+ expect(result).toMatchObject({ error: 'NO_CANDIDATE' })+ expect((result.excluded as Array<{ reason: string }>).every(e => /offline or unreachable/.test(e.reason))).toBe(true)+ expect((result.excluded as unknown[]).length).toBeGreaterThan(2)+ expect(open).not.toHaveBeenCalled()+ })+ it('keeps a member on a machine this account cannot open as unknown, not offline, and routes to it when nothing known is left', async () => {+ const s = scoped()+ const open = vi.fn(async () => { throw Object.assign(new Error('gone'), { code: 'MACHINE_UNAVAILABLE' }) })+ const result = await routeTask(input, s, where as never, open as never)+ expect(result).toMatchObject({ ok: true, pick: { kind: 'member', agentId: 'a1' } })+ const decision = recorded(s).command.decision+ expect(decision.candidates).toHaveLength(1)+ // New agents there stay excluded: nothing can start on a machine nobody can open.+ expect(decision.excluded).toEqual(expect.arrayContaining([expect.objectContaining({ reason: 'Machine is offline or unreachable.' })]))+ expect(decision.excluded.some((e: { title: string }) => e.title.startsWith('Multiply'))).toBe(false)+ })+ it('prefers a member whose capacity is known over one on a machine that cannot be read', async () => {+ const two = tab(); two.state.agents = [...agents, { id: 'a2', name: 'Collab', machineId: 'theirs', harnessId: 'h2', configuration: { engine: 'claude', model: 'sonnet', effort: 'medium' } }] as never+ const s = scoped({ tab: two, jev: { ok: true, value: { unavailable: 'BUSY' } } })+ const open = vi.fn(async (_w: unknown, id: string) => id === 'theirs' ? Promise.reject(new Error('not yours')) : daemon(id, { agents: id === 'm1' ? ['h1'] : [] })) as never+ // theirs is not in the account's list, m1 is; the unknown collaborator member is shown only as a fallback.+ const result = await routeTask(input, s, where as never, open)+ expect(result).toMatchObject({ ok: true })+ const titles = (recorded(s).command.decision.candidates as Array<{ title: string }>).map(c => c.title)+ expect(titles.some(t => t.startsWith('Multiply'))).toBe(true)+ expect(titles.some(t => t.startsWith('Collab'))).toBe(false)+ expect(recorded(s).command.decision.excluded.some((e: { title: string }) => e.title.startsWith('Collab'))).toBe(false)+ })+ it('opens a machine only members know and probes its members, but starts nothing new there', async () => {+ const two = tab(); two.state.agents = [{ ...agents[0], machineId: 'theirs' }, agents[1]] as never+ const s = scoped({ tab: two })+ const open = opener(id => daemon(id, { agents: id === 'theirs' ? ['h1'] : [] }))+ await routeTask(input, s, where as never, open)+ const titles = (recorded(s).command.decision.candidates as Array<{ title: string }>).map(c => c.title)+ expect(titles).toContain('Multiply · Claude sonnet medium · theirs')+ expect(titles.filter(t => t.endsWith('· theirs'))).toHaveLength(1)+ })+ it('rates members by the model their engine reported after work', async () => {+ const working = tab()+ working.state.agents = [+ { id: 'a1', name: 'Opus hand', machineId: 'm1', harnessId: 'h1', configuration: { engine: 'claude', model: 'claude-opus-4-7', effort: 'high' } },+ { id: 'a3', name: 'Sonnet hand', machineId: 'm1', harnessId: 'h3', configuration: { engine: 'claude', model: 'claude-sonnet-4-5[1m]', effort: 'medium' } },+ { id: 'a4', name: 'Codex hand', machineId: 'm1', harnessId: 'h4', configuration: { engine: 'codex', model: 'gpt-5.5', effort: 'high' } },+ agents[1]] as never+ const s = scoped({ tab: working, jev: { ok: true, value: { unavailable: 'BUSY' } } })+ const open = opener(id => daemon(id, { agents: id === 'm1' ? ['h1', 'h3', 'h4'] : [], usage: { providers: [] }, engines: [{ engine: 'claude', installed: true, signedIn: true }, { engine: 'codex', installed: true, signedIn: true }] }))+ await routeTask(input, s, where as never, open)+ const rated = Object.fromEntries((recorded(s).command.decision.candidates as Array<{ title: string; quality: number; cost: number }>)+ .filter(c => /hand/.test(c.title)).map(c => [c.title.split(' · ')[0], [c.quality, c.cost]]))+ expect(rated).toEqual({ 'Opus hand': [3, 3], 'Sonnet hand': [2, 2], 'Codex hand': [3, 2] })+ })+ it('falls back to the policy order when Jev is unavailable, and still routes when recording fails', async () => {+ const result = await routeTask(input, scoped({ jev: { ok: true, value: { unavailable: 'BUSY' } }, record: { error: 'BACKEND_UNAVAILABLE' } }), where as never, opener())+ expect(result).toMatchObject({ ok: true, via: 'order', unrecorded: true })+ expect(result).not.toHaveProperty('routeDecisionId')+ })+ it('treats a failed Jev answer or a lost connection as Jev unavailable and still routes', async () => {+ const failed = await routeTask(input, scoped({ jev: { error: 'AGENT_UNAVAILABLE' } }), where as never, opener())+ expect(failed).toMatchObject({ ok: true, via: 'order' })+ expect(failed.why).toContain('UNAVAILABLE')+ const lost = await routeTask(input, scoped({ jevThrows: true, recordThrows: true }), where as never, opener())+ expect(lost).toMatchObject({ ok: true, via: 'order', unrecorded: true })+ const noAnswer = await routeTask(input, scoped({ jev: { ok: true, value: { answers: {} } } }), where as never, opener())+ expect(noAnswer).toMatchObject({ ok: true, via: 'order' })+ const s = scoped(); await routeTask(input, s, where as never, opener())+ expect(jevCall(s).conversationId).toBe('g1')+ })+ it('does not ask Jev when only one candidate can run the task', async () => {+ const s = scoped()+ // Only the member's machine answers, and its engine is not installed for a new agent.+ const open = vi.fn(async (_w: unknown, id: string) => id === 'm1'+ ? daemon(id, { agents: ['h1'], engines: [{ engine: 'claude', installed: false }] }) as never : Promise.reject(new Error('gone')))+ expect(await routeTask(input, s, where as never, open as never)).toMatchObject({ ok: true, via: 'only', pick: { agentId: 'a1' } })+ expect(s.mock.calls.filter(c => c[0].action === 'routeJev')).toHaveLength(0)+ })+ it('refuses an invalid assessment, an unknown group and a failed context read', async () => {+ const open = vi.fn()+ expect(await routeTask({ ...input, assessment: { difficulty: 'x' } }, scoped(), where as never, open as never)).toMatchObject({ error: 'INVALID_REQUEST' })+ expect(await routeTask({ ...input, conversationId: 'nope' }, scoped(), where as never, open as never)).toMatchObject({ error: 'NOT_FOUND' })+ const failing = vi.fn(async () => ({ error: 'AGENT_UNAVAILABLE', detail: 'x' }))+ expect(await routeTask(input, failing, where as never, open as never)).toMatchObject({ error: 'AGENT_UNAVAILABLE' })+ const refused = vi.fn(async () => { throw new Error('socket closed') })+ expect(await routeTask(input, refused, where as never, open as never)).toEqual({ error: 'AGENT_UNAVAILABLE', detail: 'socket closed' })+ expect(await routeTask(input, vi.fn(async () => { throw 'odd' }), where as never, open as never)).toMatchObject({ error: 'AGENT_UNAVAILABLE' })+ expect(await routeTask(input, scoped({ context: { ok: false } }), where as never, open as never)).toMatchObject({ ok: false })+ expect(open).not.toHaveBeenCalled()+ })+ it('tolerates a tab without agents, conversations or machines, and names a machine only the members know', async () => {+ const bare = { ok: true, value: { tab: { state: {} }, policy: { policy } } }+ expect(await routeTask(input, scoped({ context: bare }), where as never, vi.fn() as never)).toMatchObject({ error: 'NOT_FOUND' })+ const s = scoped({ context: { ok: true, value: { agentId: 'lead', tab: tab(), policy: { policy } } } })+ const result = await routeTask(input, s, where as never, opener())+ expect(result).toMatchObject({ ok: true, warnings: [] })+ expect((recorded(s).command.decision.candidates as Array<{ title: string }>).some(c => c.title.endsWith('· m1'))).toBe(true)+ })+ it('excludes a member whose terminal is gone or not running, and survives a failed agent list', async () => {+ const s = scoped()+ await routeTask(input, s, where as never, opener(id => daemon(id, { agents: ['h1'], terminalAvailable: false })))+ expect(recorded(s).command.decision.excluded).toEqual(expect.arrayContaining([{ title: 'Multiply · Claude sonnet medium · remote-1', reason: 'Its terminal is not running.' }]))+ const t = scoped()+ await routeTask(input, t, where as never, opener(id => daemon(id, { listFails: true })))+ expect(recorded(t).command.decision.excluded).toEqual(expect.arrayContaining([expect.objectContaining({ reason: 'Its terminal is not running.' })]))+ })+ it('gives the history of a group whose last attempt ended', async () => {+ for (const [assignment, line] of [+ [{ id: 'x', agentId: 'a1', status: 'stopped', result: 'Tests failed.' }, 'Multiply: stopped — Tests failed.'],+ [{ id: 'x', agentId: 'gone', status: 'done' }, 'An agent: done'],+ ] as const) {+ const s = scoped({ tab: tab(assignment) })+ await routeTask(input, s, where as never, opener())+ expect(jevCall(s).state.history).toContain(line)+ }+ const s = scoped({ tab: tab({ id: 'x', agentId: 'a1', status: 'working' }) })+ await routeTask(input, s, where as never, opener(id => daemon(id, { agents: ['h1'] })))+ expect(jevCall(s).state.history).toBe('No earlier attempts.')+ })+ it('keeps a group without brief or checks routable', async () => {+ const odd = tab(); const group = odd.state.conversations[1] as Record<string, unknown>+ delete group.brief; group.title = undefined; group.checks = [{}]+ const s = scoped({ tab: odd })+ expect(await routeTask(input, s, where as never, opener())).toMatchObject({ ok: true })+ delete group.checks+ expect(await routeTask(input, s, where as never, opener())).toMatchObject({ ok: true })+ })+ it('turns the task needs and the real admission refusals into member and new-agent exclusions', async () => {+ const needs = { tools: ['git'], devices: ['/dev/ttyUSB0'], cwd: '/repo' }+ const s = scoped()+ const open = opener(id => daemon(id, { agents: id === 'm1' ? ['h1'] : [], tools: { git: false }, devices: {} }))+ const result = await routeTask({ ...input, assessment: { ...input.assessment, needs } }, s, where as never, open)+ expect(result).toMatchObject({ error: 'NO_CANDIDATE' })+ const reasons = (result.excluded as Array<{ reason: string }>).map(e => e.reason)+ expect(reasons).toContain('Required tool unavailable: git. Required device unavailable: /dev/ttyUSB0.')+ const d = open.mock.results[0] && await open.mock.results[0].value as ReturnType<typeof daemon>+ expect(d.request).toHaveBeenCalledWith('super_tabs', expect.objectContaining({ action: 'capacity', cwd: '/repo', tools: ['git'], devices: ['/dev/ttyUSB0'] }), 20_000)+ })+ it('excludes a member on an exhausted usage window but not one whose quota is merely unknown', async () => {+ const exhausted = { providers: [{ provider: 'claude', outcome: 'answered', httpStatus: 200, body: { five_hour: { utilization: 100 } } }] }+ const s = scoped()+ await routeTask(input, s, where as never, opener(id => daemon(id, { agents: id === 'm1' ? ['h1'] : [], usage: id === 'm1' ? exhausted : usage })))+ expect(recorded(s).command.decision.excluded).toEqual(expect.arrayContaining([expect.objectContaining({ title: expect.stringContaining('Multiply'), reason: expect.stringContaining('exhausted usage window') })]))+ const t = scoped()+ await routeTask(input, t, where as never, opener(id => daemon(id, { agents: id === 'm1' ? ['h1'] : [], usage: { providers: [] } })))+ expect((recorded(t).command.decision.candidates as Array<{ title: string }>).some(c => c.title.startsWith('Multiply'))).toBe(true)+ })+ it('uses the real admission texts the member refusal filter keys on', () => {+ const quota = quotaOf({ providers: [{ provider: 'claude', outcome: 'answered', httpStatus: 200, body: { five_hour: { utilization: 100 } } }] }, 'claude', false)+ const requirements = { memoryBytes: 0, diskBytes: 0, maxCpuPercent: 100, tools: ['git'], devices: ['/dev/x'], quotaRequired: false }+ const { reasons } = admission({ resources: {}, tools: {}, devices: {} }, { installed: true, signedIn: true }, quota, requirements)+ expect(reasons).toEqual([+ 'Required tool unavailable: git.', 'Required device unavailable: /dev/x.',+ 'The subscription has an exhausted usage window. Wait for a fresh allowance reading or choose another account.'])+ const unknown = admission({ resources: {}, tools: {}, devices: {} }, { installed: true, signedIn: true }, quotaOf({}, 'claude', false), { ...requirements, tools: [], devices: [] })+ expect(unknown).toMatchObject({ allowed: true, reasons: [] })+ })+})diff --git a/cli/src/superTabs/routeCommand.ts b/cli/src/superTabs/routeCommand.tsnew file mode 100644index 000000000..c515c930d--- /dev/null+++ b/cli/src/superTabs/routeCommand.ts@@ -0,0 +1,143 @@+/** `harness super-tab route GROUP JSON`: the Lead's routing step (docs/superpowers/specs/2026-10-19-super-tab-routing-v1-design.md).+ * Reads the tab, the effective policy and the account's machines; probes each machine once per engine with+ * the same admission `start` uses; then orders, asks Jev, and records the decision in the tab. */+import { randomUUID } from 'node:crypto'+import { openDaemon, type Daemon, type Where } from '../agentClient/daemon.js'+import { startRequirements } from './capacity.js'+import { inspectCapacity, type ScopedRequest } from './start.js'+import { object } from './wire.js'+import { choose, decide, jevQuestion, parseAssessment, quotaOf2, rateFor, recordOf, type Assessment, type Policy, type Probe } from './route.js'+import type { JevChoiceAnswer } from '../lib/jev/jevClient.js'++type Json = Record<string, unknown>+const ENGINES = ['claude', 'codex']+// Only these say the request never reached a decision; any other refusal (RATE_LIMITED, LEAD_REQUIRED,+// validation) is the answer and must reach the Lead.+const TRANSPORT = new Set(['AGENT_UNAVAILABLE', 'SUPER_TAB_UNAVAILABLE', 'BACKEND_UNAVAILABLE', 'BACKEND_TIMEOUT', 'BACKEND_UNREACHABLE'])+const MACHINES_UNREADABLE = "The account's machine list could not be read; only known machines were considered."+const OFFLINE = 'Machine is offline or unreachable.'+const UNKNOWN_QUOTA: Probe['quota'] = { known: false, leftPercent: null, resetsAt: null }+const active = (assignment: unknown) => { const a = object(assignment); return !!a.id && !['done', 'stopped'].includes(String(a.status)) }+const list = (value: unknown) => Array.isArray(value) ? value.map(object) : []++export async function routeTask(input: { tabId: string; conversationId: string; assessment: unknown }, request: ScopedRequest, where: Where,+ open: typeof openDaemon = openDaemon, newId: () => string = randomUUID): Promise<Json> {+ // A lost connection is an answer here, never a throw: the Lead must still get a decision or a reason.+ const scoped: ScopedRequest = async payload => {+ try { return await request(payload) } catch (error) {+ return { error: 'AGENT_UNAVAILABLE', detail: error instanceof Error ? error.message : 'The request to the machine failed.' }+ }+ }+ const assessment = parseAssessment(input.assessment)+ if (typeof assessment === 'string') return { error: 'INVALID_REQUEST', detail: assessment }+ const context = await scoped({ action: 'routeContext' })+ if (context.error || context.ok !== true) return context+ const value = object(context.value), state = object(object(value.tab).state), effective = object(value.policy)+ const policy = effective.policy as unknown as Policy+ const conversations = list(state.conversations), agents = list(state.agents)+ const group = conversations.find(c => c.id === input.conversationId)+ if (!group) return { error: 'NOT_FOUND', detail: 'No such group in this Super Tab.' }+ if (group.leadId !== value.agentId) return { error: 'LEAD_REQUIRED', detail: 'Only the Lead of this group routes its work.' }+ // The group's Lead and the tab Lead coordinate; neither is a worker candidate even when idle.+ const busy = new Set([String(group.leadId), String(conversations.find(c => c.id === 'lead')?.leadId),+ ...conversations.filter(c => active(c.assignment)).map(c => String(object(c.assignment).agentId))])+ const members = agents.filter(a => !busy.has(String(a.id)) && ENGINES.includes(String(object(a.configuration).engine)))+ // The account's machines can start a new agent. A member may run on a machine only its collaborator can+ // open; the Lead tries that machine too, but a member there is unknown, never offline.+ const machines = new Map<string, { name: string; status: string; account: boolean }>()+ for (const m of list(value.machines)) machines.set(String(m.machineId), { name: String(m.name), status: String(m.status ?? 'unknown'), account: true })+ // The Lead's own machine is the account's even when the list could not be read.+ if (!machines.has(where.machineId)) machines.set(where.machineId, { name: where.machineId, status: 'unknown', account: true })+ for (const m of members) if (!machines.has(String(m.machineId))) machines.set(String(m.machineId), { name: String(m.machineId), status: 'unknown', account: false })+ const enabled = policy.models.filter(m => m.enabled)++ const probes = (await Promise.all([...machines].map(([machineId, machine]) =>+ probeMachine(machineId, machine, members.filter(m => m.machineId === machineId), enabled, policy, assessment, where, open)))).flat()+ const choice = choose(probes, policy, assessment, Date.now())+ if ('error' in choice) return choice++ let answer: JevChoiceAnswer | undefined, unavailable: string | null = null+ if (choice.shown.length > 1) {+ const checks = list(group.checks).map(c => String(c.description ?? ''))+ // The group's last attempt, when it ended: a worker that stopped on this task is a worse choice.+ const last = object(group.assignment)+ const history = last.id && !active(last)+ ? [`${String(agents.find(a => a.id === last.agentId)?.name ?? 'An agent')}: ${String(last.status)}${typeof last.result === 'string' ? ` — ${last.result.slice(0, 300)}` : ''}`]+ : []+ const question = jevQuestion({ title: String(group.title ?? ''), brief: String(group.brief ?? ''), checks, history }, assessment, policy, choice)+ const reply = await scoped({ action: 'routeJev', conversationId: input.conversationId, ...question })+ if (typeof reply.error === 'string' && !TRANSPORT.has(reply.error)) return reply+ const jev = object(reply.value)+ if (reply.ok !== true || typeof jev.unavailable === 'string') unavailable = typeof jev.unavailable === 'string' ? jev.unavailable : 'UNAVAILABLE'+ else answer = object(jev.answers).who as JevChoiceAnswer | undefined+ }+ const verdict = decide(choice, answer, unavailable)+ const recorded = await scoped({ action: 'command', operationId: `route-${newId()}`,+ command: { type: 'route.record', conversationId: input.conversationId, decision: recordOf(choice, verdict, assessment, policy) } })+ if (typeof recorded.error === 'string' && !TRANSPORT.has(recorded.error)) return recorded+ const routeDecisionId = recorded.ok === true ? object(object(recorded.value).result).routeDecisionId : undefined+ const decision = typeof routeDecisionId === 'string' ? `,"routeDecisionId":"${routeDecisionId}"` : ''+ const publicOf = (s: typeof verdict.pick) => ({ id: s.id, kind: s.kind, ...(s.agentId ? { agentId: s.agentId } : {}), machineId: s.machineId,+ engine: s.engine, model: s.model, effort: s.effort, title: s.title })+ return {+ ok: true, ...(typeof routeDecisionId === 'string' ? { routeDecisionId } : { unrecorded: true }),+ pick: publicOf(verdict.pick), via: verdict.via, p: verdict.p, belowFloor: choice.belowFloor, why: verdict.why,+ alternatives: choice.shown.filter(s => s.id !== verdict.pick.id).slice(0, 2).map(publicOf),+ warnings: [...(Array.isArray(effective.warnings) ? effective.warnings : []), ...(value.machinesUnreadable === true ? [MACHINES_UNREADABLE] : [])],+ next: verdict.pick.kind === 'member'+ ? `Assign with: command OPERATION_ID {"type":"work.assign","conversationId":"${input.conversationId}","agentId":"${verdict.pick.agentId}"${decision}}`+ : `Start with: start OPERATION_ID ${JSON.stringify({ conversationId: input.conversationId, name: 'Builder', cwd: assessment.needs.cwd ?? '/absolute/repo/on/that/machine',+ worktree: true, requirements: startRequirements(assessment.needs), machineId: verdict.pick.machineId, engine: verdict.pick.engine, model: verdict.pick.model,+ effort: verdict.pick.effort, ...(typeof routeDecisionId === 'string' ? { routeDecisionId } : {}) })}, then assign the started agent${decision ? ' with the same routeDecisionId' : ''}.`,+ }+}++async function probeMachine(machineId: string, { name: machineName, status, account }: { name: string; status: string; account: boolean },+ members: Json[], allModels: Policy['models'], policy: Policy, a: Assessment, where: Where, open: typeof openDaemon): Promise<Probe[]> {+ const models = account ? allModels : []+ const engines = [...new Set([...models.map(m => m.engine), ...members.map(m => String(object(m.configuration).engine) as 'claude' | 'codex')])]+ const memberProbe = (m: Json, refusals: string[] = [], quota = UNKNOWN_QUOTA): Probe => {+ const c = object(m.configuration), engine = String(c.engine) as 'claude' | 'codex'+ const model = typeof c.model === 'string' ? c.model : null, effort = typeof c.effort === 'string' ? c.effort : null+ return { kind: 'member', agentId: String(m.id), name: String(m.name ?? 'Member'), machineId, machineName, engine,+ model: model ?? 'default', effort: effort ?? 'default', ...rateFor(policy, engine, model, effort),+ quota, activity: 'idle', known: quota.known, refusals }+ }+ const newProbe = (m: Policy['models'][number], refusals: string[], quota: Probe['quota'], known: boolean): Probe => ({+ kind: 'new', machineId, machineName, engine: m.engine, model: m.model, effort: m.effort, quality: m.quality, cost: m.cost,+ quota, activity: 'new agent', known, refusals })+ const offline = () => models.map(m => newProbe(m, [OFFLINE], UNKNOWN_QUOTA, false))+ // The account says this machine is off, so nothing there can run or be asked.+ if (account && status === 'offline') return [...members.map(m => memberProbe(m, [OFFLINE])), ...offline()]+ let target: Daemon+ try { target = await open(where, machineId) } catch {+ // Not being able to open a machine says nothing about the agents already on it; only a new start needs it.+ return [...members.map(m => memberProbe(m)), ...offline()]+ }+ try {+ const listed = object(await target.request('agents_list', {}, 10_000).catch(() => ({})))+ const live = new Set(list(listed.agents).filter(f => object(f.terminal).available !== false).map(f => String(f.id)))+ // Quota is not required to route: an unknown allowance only ranks a candidate lower. The start's own+ // requirements are (the hint suggests exactly these), and so is an exhausted usage window.+ const byEngine = new Map<string, Awaited<ReturnType<typeof inspectCapacity>>>()+ for (const engine of engines) {+ byEngine.set(engine, await inspectCapacity(target, { engine, cwd: a.needs.cwd ?? '/', worktree: false,+ requirements: startRequirements(a.needs) }))+ }+ const probes: Probe[] = []+ for (const m of members) {+ const inspected = byEngine.get(String(object(m.configuration).engine))!+ const refusals = [+ ...(live.has(String(m.harnessId)) ? [] : ['Its terminal is not running.']),+ // A running member already has its engine, memory and sign-in; only these three can still rule it out.+ ...inspected.reasons.filter(r => /usage window|Required tool|Required device/.test(r)),+ ]+ probes.push(memberProbe(m, refusals, quotaOf2(inspected.quota)))+ }+ for (const m of models) {+ const inspected = byEngine.get(m.engine)!+ probes.push(newProbe(m, inspected.allowed ? [] : inspected.reasons, quotaOf2(inspected.quota), inspected.unknown.length === 0 && inspected.quota.known))+ }+ return probes+ } finally { target.close() }+}diff --git a/cli/src/superTabs/service.spec.ts b/cli/src/superTabs/service.spec.tsindex ae70bc9d8..113a4b242 100644--- a/cli/src/superTabs/service.spec.ts+++ b/cli/src/superTabs/service.spec.ts@@ -3,15 +3,20 @@ import { expect, it, vi } from 'vitest'import { fakeCore } from '../testing/fakeCore.js'import { superTabService } from './service.js'import type { SuperTabHost } from './host.js'+import { createJevDecide, type JevDecide } from '../lib/jev/jevClient.js'++// The real client would read the developer's OpenRouter key; the account backend is the only part under test.+vi.mock('../lib/jev/jevClient.js', async importOriginal => ({ ...await importOriginal<typeof import('../lib/jev/jevClient.js')>(), createJevDecide: vi.fn() }))+const createJev = vi.mocked(createJevDecide)const owner = { local: true, owner: true }, visitor = { local: false, owner: false }-function setup() {+function setup(options: { jev?: () => JevDecide } = {}) {const agentId = createHash('sha256').update(JSON.stringify(['machine-1', 'native'])).digest('hex').slice(0, 24)const agent = { id: agentId, machineId: 'machine-1', harnessId: 'native' }const call = vi.fn(async () => ({ status: 200, body: { success: true, data: { state: { agents: [agent] } } } }))const core = fakeCore({ account: { backend: call }, agents: { byAgent: vi.fn(() => ({ agentId: 'native' }) as never) } })const start = vi.fn(), stop = vi.fn()- const service = superTabService(core, { host: () => ({ machineId: 'machine-1', start, stop }) as unknown as SuperTabHost })+ const service = superTabService(core, { host: () => ({ machineId: 'machine-1', start, stop }) as unknown as SuperTabHost, ...options })return { ...service, call, core, agent, agentId, start, stop, ask: service.requests.super_tabs }}it('keeps a shared machine controller out of the host account while accepting its own paired apps', async () => {@@ -94,3 +99,83 @@ it('lets a machine client prepare only a backend-verified terminal context', asyexpect(prepareNative).toHaveBeenLastCalledWith('tab', 'context_1234567890', true, undefined)expect(core.account.backend).not.toHaveBeenCalled()})++it('returns the routing context to a verified contribution', async () => {+ const t = setup()+ vi.mocked(t.core.account.backend).mockImplementation(async (_method, path) => path.includes('/routing-policy')+ ? { status: 200, body: { success: true, data: { policy: { version: 1 }, warnings: [], overridden: [] } } }+ : { status: 200, body: { success: true, data: { state: { agents: [t.agent] } } } })+ t.core.account.machines = vi.fn(async () => ({ status: 200, body: { success: true, data: {+ machines: [{ machineId: 'm1', name: 'remote-1', status: 'online' }],+ sharedMachines: [{ machineId: 'm2', name: 'shared', status: 'online', share: { added: true } }, { machineId: 'm3', name: 'not added', status: 'online' }] } } }))+ expect(await t.ask({ action: 'routeContext', tabId: 'tab', harnessId: 'native' }, owner)).toEqual({ ok: true, value: {+ agentId: t.agentId, tab: { state: { agents: [t.agent] } }, policy: { policy: { version: 1 }, warnings: [], overridden: [] },+ machines: [{ machineId: 'm1', name: 'remote-1', status: 'online' }, { machineId: 'm2', name: 'shared', status: 'online' }] } })+ expect(t.call).toHaveBeenCalledWith('GET', `/api/super-tabs/tab/routing-policy?asAgentId=${t.agentId}`, undefined)+})+it('says the machine list could not be read, instead of offering none', async () => {+ const t = setup()+ vi.mocked(t.core.account.backend).mockImplementation(async (_method, path) => path.includes('/routing-policy')+ ? { status: 200, body: { success: true, data: { policy: { version: 1 }, warnings: [], overridden: [] } } }+ : { status: 200, body: { success: true, data: { state: { agents: [t.agent] } } } })+ for (const answer of [async () => ({ status: 503, body: { error: 'SERVICE_UNAVAILABLE' } }), async () => { throw new Error('link lost') }]) {+ t.core.account.machines = vi.fn(answer)+ expect(await t.ask({ action: 'routeContext', tabId: 'tab', harnessId: 'native' }, owner)).toMatchObject({ ok: true, value: { machines: [], machinesUnreadable: true } })+ }+ t.core.account.machines = vi.fn(async () => ({ status: 200, body: { data: { machines: [{ machineId: 'm1', name: 'remote-1', status: 'online' }] } } }))+ expect((await t.ask({ action: 'routeContext', tabId: 'tab', harnessId: 'native' }, owner) as { value: object }).value).not.toHaveProperty('machinesUnreadable')+})+const routing = (t: ReturnType<typeof setup>, decisions: unknown[] = [], leadId?: string) => vi.mocked(t.core.account.backend).mockImplementation(async (_method, path) => path.includes('/route-decisions')+ ? { status: 200, body: { success: true, data: decisions } }+ : { status: 200, body: { success: true, data: { state: { agents: [t.agent], conversations: [{ id: 'g1', leadId: leadId ?? t.agentId }] } } } })+it('asks Jev with a three-second limit and reports unavailability instead of failing', async () => {+ const answer = { who: { choice: 'c1', probabilities: { c0: 0.2, c1: 0.8 } } }+ const decide = vi.fn<JevDecide>(async () => answer)+ const t = setup({ jev: () => decide }); routing(t)+ expect(await t.ask({ action: 'routeJev', tabId: 'tab', harnessId: 'native', conversationId: 'g1', state: { task: 't' }, questions: { who: {} } }, owner))+ .toEqual({ ok: true, value: { answers: answer } })+ expect(decide.mock.calls[0][2]).toBeInstanceOf(AbortSignal)+ const ask = (extra: object = {}) => t.ask({ action: 'routeJev', tabId: 'tab', harnessId: 'native', conversationId: 'g1', state: {}, questions: {}, ...extra }, owner)+ decide.mockRejectedValueOnce(Object.assign(new Error('busy'), { code: 'BUSY' }))+ expect(await ask()).toEqual({ ok: true, value: { unavailable: 'BUSY' } })+ decide.mockRejectedValueOnce(new DOMException('The operation timed out.', 'TimeoutError'))+ expect(await ask()).toEqual({ ok: true, value: { unavailable: 'TIMEOUT' } })+ decide.mockRejectedValueOnce(new DOMException('Aborted', 'AbortError'))+ expect(await ask()).toEqual({ ok: true, value: { unavailable: 'TIMEOUT' } })+ decide.mockRejectedValueOnce(new Error('boom'))+ expect(await ask()).toEqual({ ok: true, value: { unavailable: 'UNAVAILABLE' } })+ decide.mockRejectedValueOnce('odd')+ expect(await ask()).toEqual({ ok: true, value: { unavailable: 'UNAVAILABLE' } })+})+it('builds Jev from the account backend when no override is given', async () => {+ const t = setup()+ const hosted = { who: { choice: 'c0', probabilities: { c0: 1 } } }+ vi.mocked(t.core.account.backend).mockImplementation(async (_method, path) => path === '/api/route/jev'+ ? { status: 200, body: { data: { answers: hosted } } }+ : path.includes('/route-decisions') ? { status: 200, body: { success: true, data: [] } }+ : { status: 200, body: { success: true, data: { state: { agents: [t.agent], conversations: [{ id: 'g1', leadId: t.agentId }] } } } })+ createJev.mockImplementationOnce(options => (async () => {+ const reply = await options!.backend!('POST', '/api/route/jev', {})+ return (reply.body.data as { answers: Record<string, never> }).answers+ }) as JevDecide)+ const service = superTabService(t.core, { host: () => ({ machineId: 'machine-1', start: vi.fn(), stop: vi.fn() }) as unknown as SuperTabHost })+ expect(await service.requests.super_tabs({ action: 'routeJev', tabId: 'tab', harnessId: 'native', conversationId: 'g1', state: {}, questions: {} }, owner))+ .toEqual({ ok: true, value: { answers: hosted } })+})+it('refuses routing to anyone but the group Lead, and past 30 decisions in the rolling hour, before asking Jev', async () => {+ const decide = vi.fn<JevDecide>(async () => ({}))+ const t = setup({ jev: () => decide })+ const ask = (conversationId: string) => t.ask({ action: 'routeJev', tabId: 'tab', harnessId: 'native', conversationId, state: {}, questions: {} }, owner)+ routing(t, [], 'someone-else')+ expect(await ask('g1')).toMatchObject({ error: 'LEAD_REQUIRED', status: 403 })+ routing(t)+ expect(await ask('missing')).toMatchObject({ error: 'LEAD_REQUIRED' })+ const recent = (n: number, age = 1000) => Array.from({ length: n }, () => ({ createdAt: new Date(Date.now() - age).toISOString() }))+ routing(t, recent(30))+ expect(await ask('g1')).toMatchObject({ error: 'RATE_LIMITED', status: 429 })+ routing(t, [...recent(29), ...recent(50, 61 * 60_000)])+ expect(await ask('g1')).toMatchObject({ ok: true })+ routing(t, { not: 'a list' } as never)+ expect(await ask('g1')).toMatchObject({ ok: true })+ expect(decide).toHaveBeenCalledTimes(2)+})diff --git a/cli/src/superTabs/service.ts b/cli/src/superTabs/service.tsindex fbec15e9b..b769e74c9 100644--- a/cli/src/superTabs/service.ts+++ b/cli/src/superTabs/service.ts@@ -3,6 +3,9 @@ import { existsSync } from 'node:fs'import { createHash } from 'node:crypto'import type { CoreApi, ServiceRequests, SuperTabsPort } from '../core/api.js'import { backend, hostJournalFile, identifier, object, SuperTabHost, SuperTabHostError } from './host.js'+import { createJevDecide, type JevDecide } from '../lib/jev/jevClient.js'+import { machineChoices } from '../lib/newCommand.js'+import { START_REQUIREMENTS } from './capacity.js'import { CapacityReservations, type ReservationBook } from './reservations.js'const HELP = {@@ -12,15 +15,17 @@ const HELP = {post: 'post GROUP TEXT OPERATION_ID: reply in that conversation. Use a unique ID per message and reuse it after an interrupted request.',start: 'start OPERATION_ID JSON: create one agent in a conversation on a machine you can access. Repeat exactly after an interruption; it follows the same native creation receipt. It does not assign work.',resume: 'resume START_ID: finish a pending start without creating another agent.',+ route: 'route GROUP JSON: before starting or assigning work, choose who does it. JSON: {"difficulty":"low|medium|high","risk":"low|medium|high","why":"one sentence","needs":{"tools":[],"devices":[],"cwd":"/absolute/repo"}}. Start or assign the pick with its routeDecisionId; to choose otherwise, pass overrideReason.',capacity: 'capacity MACHINE_ID JSON: inspect machine, engine and quota headroom. JSON uses the start request fields below. Unknown allowances are not reported as free tokens.',- startRequest: { conversationId: 'GROUP', machineId: 'MACHINE', engine: 'codex', name: 'Builder', cwd: '/absolute/repo/on/that/machine', worktree: true, requirements: { memoryBytes: 2147483648, diskBytes: 10737418240, maxCpuPercent: 85, tools: ['git'], devices: [], quotaRequired: false } },+ startRequest: { conversationId: 'GROUP', machineId: 'MACHINE', engine: 'codex', name: 'Builder', cwd: '/absolute/repo/on/that/machine', worktree: true, requirements: START_REQUIREMENTS,+ model: 'opus', effort: 'high', routeDecisionId: 'DECISION' },command: 'command OPERATION_ID JSON: send one of the commands below. Reuse exactly the same ID and JSON after an interrupted request.',commands: [{ type: 'message.send', conversationId: 'GROUP', text: 'A message addressed to an agent', replyTo: null, recipientIds: ['AGENT'] },{ type: 'conversation.create', title: 'Outcome', brief: 'An independently assignable result', checks: [{ description: 'Observable acceptance evidence', independent: false }] },{ type: 'conversation.agent', conversationId: 'GROUP', agentId: 'AGENT', present: true, lead: false },{ type: 'work.define', conversationId: 'GROUP', brief: 'What to deliver', checks: [{ description: 'Observable acceptance evidence', independent: false }] },- { type: 'work.assign', conversationId: 'GROUP', agentId: 'AGENT' },+ { type: 'work.assign', conversationId: 'GROUP', agentId: 'AGENT', routeDecisionId: 'DECISION' },{ type: 'work.status', conversationId: 'GROUP', assignmentId: 'ATTEMPT', status: 'working', result: null },{ 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' },@@ -31,6 +36,8 @@ export interface SuperTabServiceOptions {capacity?: typeof readCapabilitieshost?: (core: CoreApi, machineId: string) => SuperTabHostreservations?: (core: CoreApi, machineId: string) => ReservationBook+ /** Jev for `route`; Harness's hosted key through the backend when the person has no key of their own. */+ jev?: (core: CoreApi) => JevDecide}export function superTabService(core: CoreApi, options: SuperTabServiceOptions = {}): { requests: ServiceRequests; port: SuperTabsPort } {let host: SuperTabHost | null = null@@ -99,6 +106,38 @@ export function superTabService(core: CoreApi, options: SuperTabServiceOptions =return { ok: true, value: await backend(core, 'GET', `${path}/starts/${payload.startId}?${identity}`) }}if (payload.action === 'status') return { ok: true, value: answer }+ if (payload.action === 'routeContext') {+ const [policy, machines] = await Promise.all([+ backend(core, 'GET', `${path}/routing-policy?${identity}`),+ core.account.machines().catch(() => null),+ ])+ // A list that could not be read is not an empty one: the Lead's route says so.+ const readable = machines?.status === 200+ // Machines shared with the account but not yet added refuse it, so they are not offered.+ return { ok: true, value: { tab: answer, policy, agentId,+ machines: readable ? machineChoices(object(object(machines.body).data), null).filter(m => !m.toAdd).map(m => ({ machineId: m.machineId, name: m.label, status: m.status })) : [],+ ...(readable ? {} : { machinesUnreadable: true }) } }+ }+ if (payload.action === 'routeJev') {+ // Jev costs money and the decision is the Lead's, so both rules are checked before it is asked.+ const group = Array.isArray(state.conversations) ? state.conversations.map(object).find(c => c.id === payload.conversationId) : undefined+ if (!group || group.leadId !== agentId) return { error: 'LEAD_REQUIRED', detail: 'The coordinating Lead of this group owns routing.', status: 403 }+ const decisions = await backend(core, 'GET', `${path}/route-decisions?${identity}`)+ const hourAgo = Date.now() - 60 * 60_000+ if ((Array.isArray(decisions) ? decisions : []).filter(d => Date.parse(String(object(d).createdAt)) >= hourAgo).length >= 30) {+ return { error: 'RATE_LIMITED', detail: 'This Super Tab routed 30 tasks in the last hour. Wait before routing again.', status: 429 }+ }+ const decide = (options.jev ?? (api => createJevDecide({ backend: (m, p, b) => api.account.backend(m, p, b) })))(core)+ try {+ // Routing never waits on Jev beyond three seconds; the policy order decides instead.+ return { ok: true, value: { answers: await decide(payload.state, object(payload.questions) as never, AbortSignal.timeout(3000)) } }+ } catch (error) {+ // A timeout is a DOMException whose `code` is a number; Jev's own refusals carry a string code.+ const name = error instanceof Error ? error.name : ''+ const code = error && typeof error === 'object' && 'code' in error && typeof error.code === 'string' ? error.code : null+ return { ok: true, value: { unavailable: name === 'TimeoutError' || name === 'AbortError' ? 'TIMEOUT' : code ?? 'UNAVAILABLE' } }+ }+ }if (payload.action === 'messages' && identifier(payload.conversationId)) {return { ok: true, value: await backend(core, 'GET', `${path}/conversations/${payload.conversationId}/messages?${identity}`) }}diff --git a/cli/src/superTabs/start.spec.ts b/cli/src/superTabs/start.spec.tsindex 817f5c6a2..a043199e3 100644--- a/cli/src/superTabs/start.spec.ts+++ b/cli/src/superTabs/start.spec.ts@@ -1,7 +1,7 @@-import { expect, it, vi } from 'vitest'+import { describe, expect, it, vi } from 'vitest'import { startAgent } from './start.js'const where = { port: 14001, machineId: 'lead-machine', dataDir: '/fixture' }-function fixture(options: { refuse?: string; loseCancel?: boolean; loseFailure?: boolean } = {}) {+function fixture(options: { refuse?: string; loseCancel?: boolean; loseFailure?: boolean; launchModel?: string[]; refuseModel?: string; frame?: string } = {}) {const start = { creationId: 'super-native-receipt', error: null as string | null, request: { machineId: 'target', conversationId: 'group', engine: 'claude', name: 'Builder', cwd: '/repo', worktree: true,requirements: { memoryBytes: 100, diskBytes: 200, maxCpuPercent: 80, tools: ['git'], devices: [], quotaRequired: false } }, dispatched: false }let nativeState = 'missing', lostJoin = false@@ -16,16 +16,19 @@ function fixture(options: { refuse?: string; loseCancel?: boolean; loseFailure?:if (cmd.type === 'agent.started' && lostJoin) { lostJoin = false; throw new Error('Join interrupted') }return { ok: true, value: { result: cmd.type === 'agent.start' ? { startId: 'start' } : { agentId: 'worker' } } }})- const request = vi.fn(async (type: string, payload: Record<string, unknown> = {}): Promise<Record<string, unknown>> => {+ const request = vi.fn(async (type: string, payload: Record<string, unknown> = {}, _ms?: number): Promise<Record<string, unknown>> => {if (type === 'agent_create_status') return { creationId: start.creationId, state: nativeState, ...(nativeState === 'created' ? { agent: { id: 'native', engine: 'claude', selectedModel: 'runtime-v1:native:claude:fixture-model@high' } } : {}) }- if (type === 'engines_probe') return { engines: [{ engine: 'claude', installed: true }] }+ if (type === 'agents_list' && options.frame) return { agents: [{ id: 'native', engine: 'claude', selectedModel: options.frame }] }+ if (type === 'engines_probe') return { engines: [{ engine: (payload.engines as string[])[0], installed: true }] }if (type === 'usage_read') return { providers: [] }if (type === 'super_tabs') {if (payload.action === 'reserveCapacity') return { ok: true, reservationId: start.creationId }if (payload.action === 'observeCapacity') return { ok: true, reservationId: start.creationId, harnessId: 'native', released: nativeState === 'cancelled' }- return { ok: true, resources: { cpuPercent: 20, memoryTotalBytes: 1000, memoryUsedBytes: 100, projectDiskFreeBytes: 1000 }, tools: { git: true }, devices: {} }+ return { ok: true, resources: { cpuPercent: 20, memoryTotalBytes: 1000, memoryUsedBytes: 100, projectDiskFreeBytes: 1000 }, tools: { git: true }, devices: {},+ ...(options.launchModel ? { launchModel: options.launchModel } : {}) }}if (type === 'agent_create') {+ if (options.refuseModel && payload.model !== undefined) return { error: options.refuseModel, detail: 'This daemon cannot launch with a model.' }if (options.refuse) return { error: options.refuse, detail: 'This agent does not support that permission mode.' }nativeState = 'created'; return { creationId: start.creationId, state: 'created', agent: { id: 'native', engine: 'claude', selectedModel: 'runtime-v1:native:claude:fixture-model@high' } }}@@ -39,6 +42,14 @@ function fixture(options: { refuse?: string; loseCancel?: boolean; loseFailure?:const close = vi.fn(), open = vi.fn(async () => ({ machineId: 'target', request, close }))return { scoped, start, request, open, close, loseJoin: () => { lostJoin = true }, forget: () => { nativeState = 'missing' } }}+const switchCall = (f: { request: { mock: { calls: unknown[][] } } }) => f.request.mock.calls.find(c => c[0] === 'agent_update')+const expectSwitchTo = (f: Parameters<typeof switchCall>[0], selectedModel: string) => {+ const call = switchCall(f)!+ expect(call[1]).toEqual({ agentId: 'native', selectedModel })+ // What is left of the 60 s budget, which a millisecond of delay takes from.+ expect(call[2]).toBeGreaterThan(50_000)+ expect(call[2]).toBeLessThanOrEqual(60_000)+}it('uses one native creation receipt and joins its captured group after a lost join reply', async () => {const f = fixture(); f.loseJoin()const input = { action: 'start', tabId: 'tab', operationId: 'user-intent', request: f.start.request }@@ -179,3 +190,345 @@ it.each([true, false])('reconciles a previously created but unavailable harnessexpect(f.start.error === null).toBe(!released)expect(f.request.mock.calls.some(c => c[0] === 'agent_create')).toBe(false)})++it('sends the routing decision at the command level, not inside the machine request', async () => {+ const f = fixture()+ await startAgent({ action: 'start', tabId: 'tab', operationId: 'op', request: { ...f.start.request, routeDecisionId: 'd1', overrideReason: 'Needs the Mac.' } }, f.scoped, where, f.open)+ const sent = f.scoped.mock.calls.map(c => c[0].command as Record<string, any>).find(c => c?.type === 'agent.start')!+ expect(sent).toMatchObject({ routeDecisionId: 'd1', overrideReason: 'Needs the Mac.' })+ expect(sent.request).not.toHaveProperty('routeDecisionId')+ expect(sent.request).not.toHaveProperty('overrideReason')+ const plain = fixture()+ await startAgent({ action: 'start', tabId: 'tab', operationId: 'op', request: plain.start.request }, plain.scoped, where, plain.open)+ const bare = plain.scoped.mock.calls.map(c => c[0].command as Record<string, any>).find(c => c?.type === 'agent.start')!+ expect(bare).not.toHaveProperty('routeDecisionId')+ expect(bare).not.toHaveProperty('overrideReason')+})++it('applies a routed model and effort to the created agent through the ordinary runtime switch', async () => {+ const f = fixture(), request = f.request.getMockImplementation()!+ f.request.mockImplementation(async (type, payload) => type === 'agent_update'+ ? { agent: { id: 'native', engine: 'claude', selectedModel: 'runtime-v1:native:claude:opus@high' } }+ : request(type, payload))+ // The backend keeps the model and effort in the stored request, which the machine side reads back.+ Object.assign(f.start.request, { model: 'opus', effort: 'high' })+ const input = { action: 'start', tabId: 'tab', operationId: 'op', request: f.start.request }+ expect(await startAgent(input, f.scoped, where, f.open)).toMatchObject({ ok: true, harnessId: 'native' })+ expectSwitchTo(f, 'runtime-v1:native:claude:opus@high')+})++it('joins the roster before the model switch, so the join prompt can finish', async () => {+ const f = fixture(), order: string[] = [], request = f.request.getMockImplementation()!, scoped = f.scoped.getMockImplementation()!+ f.scoped.mockImplementation(async payload => {+ const type = (payload.command as Record<string, unknown> | undefined)?.type+ if (type === 'agent.started') order.push('agent.started')+ return scoped(payload)+ })+ f.request.mockImplementation(async (type, payload) => {+ if (type !== 'agent_update') return request(type, payload)+ order.push('agent_update')+ return { agent: { id: 'native', engine: 'claude', selectedModel: 'runtime-v1:native:claude:opus@high' } }+ })+ Object.assign(f.start.request, { model: 'opus', effort: 'high' })+ expect(await startAgent({ action: 'start', tabId: 'tab', operationId: 'op', request: f.start.request }, f.scoped, where, f.open)).toMatchObject({ ok: true })+ expect(order).toEqual(['agent.started', 'agent_update'])+})++it('makes no model switch when the agent could not join the roster', async () => {+ const f = fixture(); f.loseJoin()+ Object.assign(f.start.request, { model: 'opus', effort: 'high' })+ await expect(startAgent({ action: 'start', tabId: 'tab', operationId: 'op', request: f.start.request }, f.scoped, where, f.open)).rejects.toThrow('Join interrupted')+ expect(f.request.mock.calls.some(c => c[0] === 'agent_update')).toBe(false)+})++it('leaves the engine on its own model for default, or when no model is routed', async () => {+ for (const extra of [{ model: 'default', effort: 'default' }, { model: 'opus' }, {}]) {+ const f = fixture(); Object.assign(f.start.request, extra)+ expect(await startAgent({ action: 'start', tabId: 'tab', operationId: 'op', request: f.start.request }, f.scoped, where, f.open)).toMatchObject({ ok: true })+ expect(f.request.mock.calls.some(c => c[0] === 'agent_update')).toBe(false)+ }+})++it.each([{ error: 'INVALID_RUNTIME_PROFILE' }, 'lost'])('still starts the agent and warns when the model switch fails: %j', async failure => {+ const f = fixture(), request = f.request.getMockImplementation()!+ f.request.mockImplementation(async (type, payload) => {+ if (type !== 'agent_update') return request(type, payload)+ if (typeof failure === 'string') throw new Error(failure)+ return failure+ })+ Object.assign(f.start.request, { model: 'opus', effort: 'high' })+ const result = await startAgent({ action: 'start', tabId: 'tab', operationId: 'op', request: f.start.request }, f.scoped, where, f.open)+ expect(result).toMatchObject({ ok: true, harnessId: 'native' })+ expect(result.modelWarning).toMatch(/Started with the engine's own model; switching to opus high failed/)+})++// agent_create submits the first prompt, so the pane is still working when the switch is first tried.+async function busySwitch(busyFor: number) {+ vi.useFakeTimers()+ try {+ const f = fixture(), request = f.request.getMockImplementation()!+ let tries = 0+ f.request.mockImplementation(async (type, payload) => {+ if (type !== 'agent_update') return request(type, payload)+ return ++tries <= busyFor ? { error: 'BUSY' } : { agent: { id: 'native', engine: 'claude', selectedModel: 'runtime-v1:native:claude:opus@high' } }+ })+ Object.assign(f.start.request, { model: 'opus', effort: 'high' })+ const run = startAgent({ action: 'start', tabId: 'tab', operationId: 'op', request: f.start.request }, f.scoped, where, f.open)+ await vi.advanceTimersByTimeAsync(70_000)+ return { result: await run, tries: () => tries, f }+ } finally { vi.useRealTimers() }+}+it('retries the model switch while the new agent is still busy with its first prompt', async () => {+ const { result, tries } = await busySwitch(3)+ expect(result).toMatchObject({ ok: true, harnessId: 'native' })+ expect(result.modelWarning).toBeUndefined()+ expect(tries()).toBe(4)+})+it('stops at the first error that is not BUSY', async () => {+ const f = fixture(), request = f.request.getMockImplementation()!+ f.request.mockImplementation(async (type, payload) => type === 'agent_update' ? { error: 'INVALID_RUNTIME_PROFILE' } : request(type, payload))+ Object.assign(f.start.request, { model: 'opus', effort: 'high' })+ const result = await startAgent({ action: 'start', tabId: 'tab', operationId: 'op', request: f.start.request }, f.scoped, where, f.open)+ expect(f.request.mock.calls.filter(c => c[0] === 'agent_update')).toHaveLength(1)+ expect(result.modelWarning).toMatch(/failed \(INVALID_RUNTIME_PROFILE\)/)+})+it('gives up on the model switch after at most 60 seconds of BUSY and warns', async () => {+ const { result, tries } = await busySwitch(Infinity)+ expect(result).toMatchObject({ ok: true, harnessId: 'native' })+ expect(result.modelWarning).toMatch(/switching to opus high failed \(BUSY\)/)+ expect(tries()).toBeGreaterThan(30)+ expect(tries()).toBeLessThanOrEqual(61)+})+it('bounds the whole model switch by the budget when the daemon hangs on agent_update', async () => {+ vi.useFakeTimers()+ try {+ const f = fixture(), request = f.request.getMockImplementation()!+ const timeouts: number[] = []+ f.request.mockImplementation(async (type, payload, ms) => {+ if (type !== 'agent_update') return request(type, payload)+ timeouts.push(ms as number)+ // The first try is slow and BUSY; the second hangs until its own timeout.+ if (timeouts.length === 1) { await new Promise(resolve => setTimeout(resolve, 30_000)); return { error: 'BUSY' } }+ return new Promise((_, reject) => setTimeout(() => reject(new Error('timeout')), ms as number))+ })+ Object.assign(f.start.request, { model: 'opus', effort: 'high' })+ const begun = Date.now()+ let elapsed = -1+ const run = startAgent({ action: 'start', tabId: 'tab', operationId: 'op', request: f.start.request }, f.scoped, where, f.open)+ .then(result => { elapsed = Date.now() - begun; return result })+ await vi.advanceTimersByTimeAsync(130_000)+ const result = await run+ expect(result.modelWarning).toMatch(/switching to opus high failed \(MODEL_UNAVAILABLE\)/)+ expect(timeouts).toEqual([60_000, 29_000])+ expect(elapsed).toBeLessThanOrEqual(60_000)+ } finally { vi.useRealTimers() }+})++it('retries UNSUPPORTED_CLI_VERSION like BUSY: a fresh Claude learns its version only from its first transcript records', async () => {+ vi.useFakeTimers()+ try {+ const f = fixture(), request = f.request.getMockImplementation()!+ let tries = 0+ f.request.mockImplementation(async (type, payload) => {+ if (type !== 'agent_update') return request(type, payload)+ return ++tries <= 2 ? { error: 'UNSUPPORTED_CLI_VERSION' } : { agent: { id: 'native', engine: 'claude', selectedModel: 'runtime-v1:native:claude:opus@high' } }+ })+ Object.assign(f.start.request, { model: 'opus', effort: 'high' })+ const run = startAgent({ action: 'start', tabId: 'tab', operationId: 'op', request: f.start.request }, f.scoped, where, f.open)+ await vi.advanceTimersByTimeAsync(10_000)+ const result = await run+ expect(result).toMatchObject({ ok: true, harnessId: 'native' })+ expect(result.modelWarning).toBeUndefined()+ expect(tries).toBe(3)+ } finally { vi.useRealTimers() }+})++// The routed switch never succeeds; the agent's frame (agents_list) says what it runs instead.+async function failedSwitch(options: { routeDecisionId?: string; ran?: string | null; send?: 'fails'; listFails?: boolean; error?: string; engine?: string } = {}) {+ vi.useFakeTimers()+ try {+ const f = fixture(), request = f.request.getMockImplementation()!, scoped = f.scoped.getMockImplementation()!+ f.request.mockImplementation(async (type, payload) => {+ if (type === 'agent_update') return { error: options.error ?? 'INVALID_RUNTIME_PROFILE' }+ if (type === 'agents_list') {+ if (options.listFails) throw new Error('timeout')+ return { agents: [{ id: 'other', selectedModel: 'runtime-v1:other:claude:opus@high' },+ { id: 'native', engine: 'claude', selectedModel: options.ran === null ? null : `runtime-v1:native:claude:${options.ran ?? 'sonnet@auto'}` }] }+ }+ return request(type, payload)+ })+ f.scoped.mockImplementation(async payload => {+ if ((payload.command as Record<string, unknown> | undefined)?.type === 'route.modelResult' && options.send === 'fails') throw new Error('backend down')+ return scoped(payload)+ })+ Object.assign(f.start.request, { model: 'haiku', effort: 'auto' })+ if (options.engine) f.start.request.engine = options.engine+ const run = startAgent({ action: 'start', tabId: 'tab', operationId: 'op',+ request: { ...f.start.request, ...(options.routeDecisionId ? { routeDecisionId: options.routeDecisionId } : {}) } }, f.scoped, where, f.open)+ await vi.advanceTimersByTimeAsync(70_000)+ const sent = f.scoped.mock.calls.map(c => c[0]).filter(c => (c.command as Record<string, unknown> | undefined)?.type === 'route.modelResult')+ const updates = f.request.mock.calls.filter(c => c[0] === 'agent_update').length+ return { result: await run, sent, updates }+ } finally { vi.useRealTimers() }+}+it('corrects the decision log to the model the agent runs when the routed switch failed', async () => {+ const { result, sent } = await failedSwitch({ routeDecisionId: 'd1' })+ expect(result).toMatchObject({ ok: true, harnessId: 'native' })+ expect(result.modelWarning).toBe("Started with the engine's own model; switching to haiku auto failed (INVALID_RUNTIME_PROFILE).")+ expect(sent).toEqual([expect.objectContaining({ action: 'command', operationId: 'model-result-start',+ command: { type: 'route.modelResult', decisionId: 'd1', startId: 'start', model: 'sonnet', effort: 'auto' } })])+})+it('sends no correction when the switch worked, or when the start was not routed', async () => {+ const worked = fixture(), request = worked.request.getMockImplementation()!+ worked.request.mockImplementation(async (type, payload) => type === 'agent_update'+ ? { agent: { id: 'native', engine: 'claude', selectedModel: 'runtime-v1:native:claude:haiku@auto' } } : request(type, payload))+ Object.assign(worked.start.request, { model: 'haiku', effort: 'auto' })+ await startAgent({ action: 'start', tabId: 'tab', operationId: 'op', request: { ...worked.start.request, routeDecisionId: 'd1' } }, worked.scoped, where, worked.open)+ expect(worked.scoped.mock.calls.some(c => (c[0].command as Record<string, unknown> | undefined)?.type === 'route.modelResult')).toBe(false)+ expect((await failedSwitch()).sent).toEqual([])+})+it('keeps the start ok and says so when the log could not be corrected', async () => {+ for (const options of [{ send: 'fails' as const }, { listFails: true }, { ran: null }]) {+ const { result, sent } = await failedSwitch({ routeDecisionId: 'd1', ...options })+ expect(result).toMatchObject({ ok: true, harnessId: 'native' })+ expect(result.modelWarning).toBe("Started with the engine's own model; switching to haiku auto failed (INVALID_RUNTIME_PROFILE). The routing decision log could not be corrected to the model that ran.")+ expect(sent).toHaveLength(options.send ? 1 : 0)+ }+})+it('also corrects the log when the switch ran out of its budget on a version the daemon never learned', async () => {+ const { result, sent } = await failedSwitch({ routeDecisionId: 'd1', error: 'UNSUPPORTED_CLI_VERSION' })+ expect(result.modelWarning).toMatch(/failed \(UNSUPPORTED_CLI_VERSION\)\.$/)+ expect(sent).toHaveLength(1)+})+it('stops at the first UNSUPPORTED_CLI_VERSION of an engine other than Claude: waiting does not load its driver', async () => {+ const { result, updates } = await failedSwitch({ error: 'UNSUPPORTED_CLI_VERSION', engine: 'codex' })+ expect(updates).toBe(1)+ expect(result.modelWarning).toMatch(/failed \(UNSUPPORTED_CLI_VERSION\)/)+})+it('drops the warning and the correction when the frame shows the routed model after a failed reply', async () => {+ const { result, sent, updates } = await failedSwitch({ routeDecisionId: 'd1', ran: 'haiku@auto', error: 'MODEL_UNAVAILABLE' })+ expect(updates).toBe(1)+ expect(result).toMatchObject({ ok: true, harnessId: 'native' })+ expect(result).not.toHaveProperty('modelWarning')+ expect(sent).toEqual([])+})++describe('a routed Claude start launches with the model instead of switching it after the start', () => {+ const routed = { model: 'opus', effort: 'high' }+ const begin = (f: ReturnType<typeof fixture>, extra: Record<string, unknown> = routed) => {+ Object.assign(f.start.request, extra)+ return startAgent({ action: 'start', tabId: 'tab', operationId: 'op', request: f.start.request }, f.scoped, where, f.open)+ }+ const created = (f: ReturnType<typeof fixture>) => f.request.mock.calls.filter(c => c[0] === 'agent_create').map(c => c[1] as Record<string, unknown>)+ const switched = (f: ReturnType<typeof fixture>) => f.request.mock.calls.some(c => c[0] === 'agent_update')++ it('sends the model and effort in agent_create and types nothing into the pane afterwards', async () => {+ const f = fixture({ launchModel: ['claude'] })+ expect(await begin(f)).toMatchObject({ ok: true, harnessId: 'native' })+ expect(created(f)).toHaveLength(1)+ expect(created(f)[0]).toMatchObject({ engine: 'claude', creationId: 'super-native-receipt', model: 'opus', effort: 'high' })+ expect(switched(f)).toBe(false)+ })++ it('still reports the engine configuration and the join', async () => {+ const f = fixture({ launchModel: ['claude'] })+ await begin(f)+ const commands = f.scoped.mock.calls.map(c => c[0].command as Record<string, unknown>).filter(Boolean)+ expect(commands.find(c => c.type === 'agent.started')).toMatchObject({ startId: 'start', harnessId: 'native', configuration: { engine: 'claude' } })+ })++ it('sends neither for default and default', async () => {+ const f = fixture({ launchModel: ['claude'] })+ await begin(f, { model: 'default', effort: 'default' })+ expect(created(f)[0]).not.toHaveProperty('model')+ expect(created(f)[0]).not.toHaveProperty('effort')+ expect(switched(f)).toBe(false)+ })++ it.each([{ model: 'opus' }, {}])('sends neither when no complete model is routed: %j', async (extra) => {+ const f = fixture({ launchModel: ['claude'] })+ await begin(f, extra)+ expect(created(f)[0]).not.toHaveProperty('model')+ expect(switched(f)).toBe(false)+ })++ it('keeps the switch for a daemon that does not say it launches with a model', async () => {+ const f = fixture()+ await begin(f)+ expect(created(f)[0]).not.toHaveProperty('model')+ expect(created(f)[0]).not.toHaveProperty('effort')+ expectSwitchTo(f, 'runtime-v1:native:claude:opus@high')+ })++ it('keeps the switch for an engine the daemon does not launch with a model', async () => {+ const f = fixture({ launchModel: ['claude'] })+ await begin(f, { ...routed, engine: 'codex' })+ expect(created(f)[0]).not.toHaveProperty('model')+ expect(switched(f)).toBe(true)+ })++ it('keeps the switch for an agent on a grid model, which chooses its own', async () => {+ const f = fixture({ launchModel: ['claude'] })+ await begin(f, { ...routed, gridModel: 'm', gridName: 'g' })+ expect(created(f)[0]).not.toHaveProperty('model')+ expect(switched(f)).toBe(true)+ })++ it.each(['LAUNCH_MODEL_UNSUPPORTED', 'INVALID_LAUNCH_MODEL'])('creates again without them under the same receipt when the daemon answers %s, then switches', async (refuseModel) => {+ // A daemon older than the launch flags, or one that cannot take this value, refuses before it makes a receipt.+ const f = fixture({ launchModel: ['claude'], refuseModel })+ expect(await begin(f)).toMatchObject({ ok: true, harnessId: 'native' })+ const sent = created(f)+ expect(sent).toHaveLength(2)+ expect(sent[1]).toMatchObject({ creationId: 'super-native-receipt' })+ expect(sent[1]).not.toHaveProperty('model')+ expect(sent[1]).not.toHaveProperty('effort')+ expect(f.request.mock.calls.some(c => c[0] === 'agent_create_cancel')).toBe(false)+ expectSwitchTo(f, 'runtime-v1:native:claude:opus@high')+ })++ describe('a start resumed after the create was sent decides from what the agent runs', () => {+ const resume = async (f: ReturnType<typeof fixture>) => {+ f.loseJoin()+ await expect(begin(f)).rejects.toThrow('Join interrupted')+ return startAgent({ action: 'resume', tabId: 'tab', startId: 'start' }, f.scoped, where, f.open)+ }++ it('does nothing when the frame shows the routed pair', async () => {+ const f = fixture({ launchModel: ['claude'], frame: 'runtime-v1:native:claude:opus@high' })+ const result = await resume(f)+ expect(result).toMatchObject({ ok: true })+ expect(result).not.toHaveProperty('modelWarning')+ expect(created(f)).toHaveLength(1)+ expect(switched(f)).toBe(false)+ })++ it('does not count default or an automatic effort as a difference', async () => {+ const f = fixture({ launchModel: ['claude'], frame: 'runtime-v1:native:claude:opus@high' })+ const result = await resume(f)+ expect(result).not.toHaveProperty('modelWarning')+ for (const wanted of [{ model: 'default', effort: 'high' }, { model: 'opus', effort: 'auto' }]) {+ const g = fixture({ launchModel: ['claude'], frame: 'runtime-v1:native:claude:opus@high' }); Object.assign(g.start.request, wanted); g.loseJoin()+ await expect(startAgent({ action: 'start', tabId: 'tab', operationId: 'op', request: g.start.request }, g.scoped, where, g.open)).rejects.toThrow('Join interrupted')+ expect(await startAgent({ action: 'resume', tabId: 'tab', startId: 'start' }, g.scoped, where, g.open)).toMatchObject({ ok: true })+ expect(switched(g)).toBe(false)+ }+ })++ it('switches when the frame shows something else, even for a machine that launches with a model', async () => {+ // The create fell back after INVALID_LAUNCH_MODEL (an effort the flag does not take), then the join reply was lost.+ const f = fixture({ launchModel: ['claude'], refuseModel: 'INVALID_LAUNCH_MODEL', frame: 'runtime-v1:native:claude:sonnet@medium' })+ expect(await resume(f)).toMatchObject({ ok: true })+ expect(created(f)).toHaveLength(2)+ expectSwitchTo(f, 'runtime-v1:native:claude:opus@high')+ })++ it('does not type /model when the frame cannot be read, and warns', async () => {+ for (const f of [fixture({ launchModel: ['claude'] }), fixture()]) {+ const result = await resume(f)+ expect(result).toMatchObject({ ok: true, modelWarning: expect.stringContaining('opus high') })+ expect(switched(f)).toBe(false)+ }+ })+ })+})diff --git a/cli/src/superTabs/start.ts b/cli/src/superTabs/start.tsindex 49a371b0d..5d6b0a5f6 100644--- a/cli/src/superTabs/start.ts+++ b/cli/src/superTabs/start.ts@@ -1,3 +1,4 @@+import { encodeRuntimeProfile } from '../engines/kit/runtime.js'import { parseRuntimeProfile } from '../lib/runtimeProfileWire.js'import { randomUUID } from 'node:crypto'import { openDaemon, type Daemon, type Where } from '../agentClient/daemon.js'@@ -16,6 +17,12 @@ const PRE_DISPATCH_REFUSALS = new Set(['PROMPT_TOO_LONG', 'PROMPT_UNSUPPORTED', 'INVALID_AGENT', 'AGENT_UNSUPPORTED','INVALID_PERMISSION_MODE', 'INVALID_SESSION', 'INVALID_STARTED_BY', 'UNSUPPORTED_ON_REMOTE',])+// A daemon that cannot take the launch model answers these before it makes a receipt, so the same creation id can be+// sent again without it. Any other refusal still ends the start.+const LAUNCH_MODEL_REFUSALS = new Set(['LAUNCH_MODEL_UNSUPPORTED', 'INVALID_LAUNCH_MODEL'])+// The join turn must finish before the pane accepts a model switch, and it ends only once the roster shows the agent.+const MODEL_SWITCH_WAIT_MS = 60_000+const MODEL_SWITCH_RETRY_MS = 1_000const CANCELLED_START = 'The machine cancelled this request before starting an agent. Review its settings and create a new start request.'function requireSuccess(reply: Json): Json {if (reply.error || reply.ok !== true) throw new Error(String(reply.detail ?? reply.error ?? 'This Super Tab request did not succeed.'))@@ -41,14 +48,22 @@ export async function inspectCapacity(target: Daemon, request: Json) {return { capacity, engine, quota, ...admission(capacity, engine, quota, requirements, !!request.codexHome || !!request.gridModel) }}+/** Whether the machine launches `engine` with a model of its own for that session (lib/launchModel.ts). A daemon from+ * before the flags does not name the field, and agent_create would silently drop a model it does not know. */+const launchesWithModel = (capacity: Json, engine: unknown) => Array.isArray(capacity.launchModel) && capacity.launchModel.includes(engine)+/** Starts through the ordinary native launch protocol, with its durable receipt.* This CLI owns no machine credential and does not change legacy spawn settings.* Every invocation resumes the backend intent before it may open a native pane. */export async function startAgent(input: Json, scoped: ScopedRequest, where: Where, open: typeof openDaemon = openDaemon): Promise<Json> {let startId = input.startId+ let routed: unknownif (input.action === 'start') {+ // The routing decision belongs to the command, not to the machine-side request.+ const { routeDecisionId, overrideReason, ...request } = object(input.request)+ routed = routeDecisionIdconst result = requireSuccess(await scoped({ action: 'command', operationId: input.operationId,- command: { type: 'agent.start', request: input.request } }))+ command: { type: 'agent.start', request, ...(routeDecisionId ? { routeDecisionId } : {}), ...(overrideReason ? { overrideReason } : {}) } }))startId = object(result.result).startId}if (!identifier(startId)) throw new Error('The start has no durable receipt. Do not create an agent without it.')@@ -58,6 +73,21 @@ export async function startAgent(input: Json, scoped: ScopedRequest, where: Wherif (start.error) return { error: 'START_FAILED', startId, detail: start.error }if (start.harnessId) return { ok: true, startId, machineId: request.machineId, harnessId: start.harnessId }const target = await open(where, request.machineId)+ /** What the agent runs now, as its frame says; null when the frame cannot say. */+ const ranNow = async (agentId: string, engine: string) => {+ const listed = await target.request('agents_list', {}, 10_000).catch((): Json => ({}))+ const frame = (Array.isArray(listed.agents) ? listed.agents.map(object) : []).find(f => f.id === agentId)+ const ran = parseRuntimeProfile(frame?.selectedModel)+ return ran && ran.sessionId === agentId && ran.engine === engine ? ran : null+ }+ /** The model and effort routed for this start; `default` keeps what the engine launches with. */+ const model = text(request.model), effort = text(request.effort)+ const routedModel = !!model && !!effort && !(model === 'default' && effort === 'default')+ /** Whether this start may launch the agent with them: a grid model chooses its own. */+ const canLaunch = routedModel && request.gridModel === undefined && request.gridName === undefined+ /** Whether the agent was launched with them, so that nothing is left to switch. Unknown (undefined) when this+ * invocation sent no create: a resumed start, which then reads what the agent runs. */+ let launched: boolean | undefinedtry {let refusal: string | null = nulllet native = await target.request('agent_create_status', { creationId }, 10_000)@@ -85,7 +115,18 @@ export async function startAgent(input: Json, scoped: ScopedRequest, where: Wher...(request.worktree ? { projectSource: 'worktree', gitSource: request.cwd, branchName: `super-tab/${startId}`, ...(request.branchRef ? { branchRef: request.branchRef } : {}) } : { cwd: request.cwd }),}for (const key of ['permissionMode', 'codexHome', 'gridModel', 'gridName']) if (request[key] !== undefined) payload[key] = request[key]+ // The routed model goes on the command line of this session alone. Typing /model into the pane afterwards saves+ // it as the person's default in their own Claude settings (manual run 2, 2026-10-19).+ launched = canLaunch && launchesWithModel(resources.capacity, request.engine)+ if (launched) { payload.model = model; payload.effort = effort }native = await target.request('agent_create', payload, 25_000)+ if (launched && LAUNCH_MODEL_REFUSALS.has(String(native.error))) {+ // A machine that refuses them (this value, or this Claude Code build) made no receipt: the same creation id+ // starts the agent as it always did, and the switch below sets the model after the start.+ delete payload.model; delete payload.effort+ launched = false+ native = await target.request('agent_create', payload, 25_000)+ }if (PRE_DISPATCH_REFUSALS.has(String(native.error))) {refusal = String(native.detail ?? native.error)// A durable cancellation also fences a delayed copy of this create.@@ -128,6 +169,7 @@ export async function startAgent(input: Json, scoped: ScopedRequest, where: Wher}if (native.state !== 'created') return { error: 'START_UNCERTAIN', startId, creationId,detail: 'The created agent is unavailable, but its stop is not confirmed. Inspect the execution machine before starting another agent.' }+ // 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 : nullconst configuration = { engine: text(frame.engine) ?? String(request.engine), model: matched?.model ?? null, effort: matched?.effort ?? null,@@ -136,6 +178,54 @@ export async function startAgent(input: Json, scoped: ScopedRequest, where: Whercommand: { type: 'agent.started', startId, harnessId: nativeId, configuration } }))await target.request('super_tabs', { action: 'wake' }).catch(() => {})await target.request('harness_share_rosters', {}).catch(() => {})- return { ok: true, startId, machineId: request.machineId, harnessId: nativeId, ...object(joined.result) }+ // A launched agent already runs the routed model. Any other (Codex, a grid model, a machine that does not list the+ // engine or refused the model) is switched once it has joined: agent_create submits the join prompt, which tells the+ // agent to poll the roster. The agent enters the roster first, so that turn can finish; the ordinary runtime switch+ // answers BUSY until the turn ends, and is retried for a bounded time. A fresh Claude has no CLI version until its+ // first transcript records, and the switch answers UNSUPPORTED_CLI_VERSION until then (the 2026-10-19 manual run):+ // the daemon does not put that version on the agent's frame, so an old version cannot be told from an unknown one+ // and both retry within the bound. `default` keeps what the engine launched with. The start returns only after the+ // switch settles, so the Lead assigns work only once the routed model is in place.+ let modelWarning: string | undefined+ let switching = routedModel && launched === false+ if (routedModel && launched === undefined) {+ // This invocation did not send the create, and the one that did may have launched with the model, fallen back to+ // the switch, or been cut off before either. Only the agent's frame says which; /model is never typed blind, as+ // Claude Code would save it as the person's default.+ const ran = await ranNow(nativeId, String(request.engine))+ const same = (wanted: string, actual: string) => wanted === 'default' || wanted === 'auto' || wanted === actual+ if (!ran) modelWarning = `Could not confirm that the agent runs ${model} ${effort}; its configuration could not be read, so it was left as it is.`+ else switching = !same(String(model), ran.model) || !same(String(effort), ran.effort)+ }+ if (switching) {+ const selectedModel = encodeRuntimeProfile({ sessionId: nativeId, engine: String(request.engine) as never, model: String(model), effort: effort as never })+ const giveUp = Date.now() + MODEL_SWITCH_WAIT_MS+ let reply: Json+ // BUSY ends with the agent's first turn. Claude alone learns its version late; for any other engine the same+ // answer means its driver cannot load, which waiting does not change.+ const retryable = (error: string) => error === 'BUSY' || (error === 'UNSUPPORTED_CLI_VERSION' && request.engine === 'claude')+ // Each try gets only what is left of the budget, and none starts with under a retry interval left, so a+ // hanging daemon cannot stretch the whole switch past the Lead's own shell timeout.+ for (;;) {+ reply = await target.request('agent_update', { agentId: nativeId, selectedModel }, Math.min(60_000, giveUp - Date.now())).catch(() => ({ error: 'MODEL_UNAVAILABLE' }))+ if (!retryable(String(reply.error)) || giveUp - Date.now() < 2 * MODEL_SWITCH_RETRY_MS) break+ await new Promise(resolve => setTimeout(resolve, MODEL_SWITCH_RETRY_MS))+ }+ if (reply.error) {+ // A client timeout can follow a switch the daemon did apply: then the agent runs the routed model.+ const ran = await ranNow(nativeId, String(request.engine))+ if (ran?.model !== model || ran.effort !== effort) {+ modelWarning = `Started with the engine's own model; switching to ${model} ${effort} failed (${String(reply.error)}).`+ // The decision log says who was actually started, so it must not keep the model that was asked for.+ if (identifier(routed)) {+ const corrected = ran && await scoped({ action: 'command', operationId: `model-result-${startId}`,+ command: { type: 'route.modelResult', decisionId: routed, startId, model: ran.model, effort: ran.effort } })+ .then(requireSuccess).then(() => true, () => false)+ if (!corrected) modelWarning += ' The routing decision log could not be corrected to the model that ran.'+ }+ }+ }+ }+ return { ok: true, startId, machineId: request.machineId, harnessId: nativeId, ...object(joined.result), ...(modelWarning ? { modelWarning } : {}) }} finally { target.close() }}diff --git a/cli/vitest.super-tabs.config.ts b/cli/vitest.super-tabs.config.tsnew file mode 100644index 000000000..9160cfbdb--- /dev/null+++ b/cli/vitest.super-tabs.config.ts@@ -0,0 +1,14 @@+// cli/vitest.super-tabs.config.ts+import { defineConfig } from 'vitest/config'+import base from './vitest.config.js'++/** Super Tab routing v1 (docs/superpowers/specs/2026-10-19-super-tab-routing-v1-design.md): new files outside+ * the core and services, which no other gate covers, held to 100% in every file. */+const FILES = ['src/superTabs/route.ts', 'src/superTabs/routeCommand.ts']+export default defineConfig({+ test: {+ ...base.test,+ include: FILES.map(f => f.replace(/\.ts$/, '.spec.ts')),+ coverage: { enabled: true, provider: 'v8', include: FILES, thresholds: { perFile: true, lines: 100, statements: 100, branches: 100, functions: 100 } },+ },+})diff --git a/desktop/design/terminal-workspace.md b/desktop/design/terminal-workspace.mdindex 2d36aeeb6..870bd5876 100644--- a/desktop/design/terminal-workspace.md+++ b/desktop/design/terminal-workspace.md@@ -37,6 +37,11 @@ confirmed roster (for example after sign-out). If the agent is already stopped,only **Open terminal** (in Participants or on a message) resumes its saved conversation; a restoredor revisited terminal selection closes instead, so an explicit stop stays stopped.+A Lead routes each delegation with `harness super-tab route`. The decision appears in the+conversation as one row (who, how — Jev's confidence or the policy order — and why); owners and+collaborators can **Change** it with a reason, which tells the Lead to hand the task over.+Settings ▸ Routing holds the account's policy; a Super Tab's **Routing** overrides single fields.+## Keep the workspace structureTabs remain compact and content-sized, adding one at a time until the row fills.diff --git a/desktop/lib/settings/sections/routing_section.dart b/desktop/lib/settings/sections/routing_section.dartnew file mode 100644index 000000000..e1c4bd370--- /dev/null+++ b/desktop/lib/settings/sections/routing_section.dart@@ -0,0 +1,130 @@+import 'dart:async';++import 'package:flutter/material.dart';++import '../../shared/widgets/section_scaffold.dart';+import '../../state/app_state.dart';+import '../../super_tabs/routing_policy.dart';+import '../../super_tabs/routing_policy_form.dart';++/// Settings ▸ Routing: the account's routing default for every Super Tab it+/// owns. A Super Tab can override single fields from its own Routing dialog.+class RoutingSection extends StatefulWidget {+ const RoutingSection({super.key, required this.notifier});+ final AppNotifier notifier;++ @override+ State<RoutingSection> createState() => _RoutingSectionState();+}++class _RoutingSectionState extends State<RoutingSection> {+ RoutingPolicy? _policy;+ int _revision = 0;+ String? _error;+ bool _saving = false, _valid = true, _saved = false;++ @override+ void initState() {+ super.initState();+ unawaited(_load());+ }++ Future<void> _load() async {+ try {+ final answer = await widget.notifier.superTabs.map(+ 'GET',+ '/api/super-tabs/routing-policy',+ );+ if (!mounted) return;+ setState(() {+ _policy = RoutingPolicy.fromJson(+ Map<String, dynamic>.from(answer['policy'] as Map),+ );+ _revision = (answer['revision'] as num).toInt();+ _error = null;+ });+ } catch (failure) {+ if (mounted) {+ setState(() => _error = 'Could not load the routing policy. $failure');+ }+ }+ }++ Future<void> _save() async {+ final policy = _policy;+ if (policy == null || _saving) return;+ setState(() {+ _saving = true;+ _saved = false;+ });+ try {+ final answer = await widget.notifier.superTabs.map(+ 'POST',+ '/api/super-tabs/routing-policy',+ body: {'revision': _revision, 'policy': policy.toJson()},+ );+ if (mounted) {+ setState(() {+ _revision = (answer['revision'] as num).toInt();+ _error = null;+ _saved = true;+ });+ }+ } catch (failure) {+ if (mounted) setState(() => _error = 'Could not save. $failure');+ } finally {+ if (mounted) setState(() => _saving = false);+ }+ }++ @override+ Widget build(BuildContext context) {+ final policy = _policy;+ final theme = Theme.of(context);+ return SectionScaffold(+ title: 'Routing',+ subtitle: 'How a Super Tab Lead chooses who does each task. Each Super Tab you own can override these.',+ child: SingleChildScrollView(+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ if (_error != null)+ Padding(+ padding: const EdgeInsets.only(bottom: 12),+ child: Text(+ _error!,+ style: TextStyle(color: theme.colorScheme.error),+ ),+ ),+ if (policy == null && _error == null)+ const LinearProgressIndicator(),+ if (policy != null) ...[+ RoutingPolicyForm(+ value: policy,+ onChanged: (v) => setState(() {+ _policy = v;+ _saved = false;+ }),+ onValidChanged: (ok) => setState(() => _valid = ok),+ ),+ Row(+ children: [+ FilledButton(+ onPressed: _saving || !_valid+ ? null+ : () => unawaited(_save()),+ child: const Text('Save'),+ ),+ if (_saved) ...[+ const SizedBox(width: 12),+ Text('Saved.', style: theme.textTheme.bodySmall),+ ],+ ],+ ),+ ],+ ],+ ),+ ),+ );+ }+}diff --git a/desktop/lib/settings/settings_body.dart b/desktop/lib/settings/settings_body.dartindex 1c516651a..db2f3feed 100644--- a/desktop/lib/settings/settings_body.dart+++ b/desktop/lib/settings/settings_body.dart@@ -10,6 +10,7 @@ import 'sections/debug_section.dart';import 'sections/experimental_section.dart';import 'sections/notifications_section.dart';import 'sections/privacy_section.dart';+import 'sections/routing_section.dart';import 'sections/shortcuts_section.dart';import 'sections/tab_invites_section.dart';import 'sections/usage_section.dart';@@ -47,6 +48,7 @@ class SettingsBody extends StatelessWidget {notifier: notifier,store: experimentalFeatures ?? notifier.experimentalFeatures,),+ SettingsSection.routing => RoutingSection(notifier: notifier),SettingsSection.tabInvites => TabInvitesSection(notifier: notifier),SettingsSection.shortcuts => const ShortcutsSection(),SettingsSection.debug => const DebugSection(),diff --git a/desktop/lib/settings/settings_section.dart b/desktop/lib/settings/settings_section.dartindex fe06678e0..a4272a0cc 100644--- a/desktop/lib/settings/settings_section.dart+++ b/desktop/lib/settings/settings_section.dart@@ -38,6 +38,11 @@ enum SettingsSection {shortcuts(AppIcons.keyboard, 'Keyboard shortcuts'),connectors(AppIcons.plug, 'Connectors'),usage(AppIcons.chartNoAxesColumn, 'Usage'),+ routing(+ AppIcons.slidersHorizontal,+ 'Routing',+ keywords: ['models', 'quota', 'jev', 'super tab', 'lead'],+ ),tabInvites(AppIcons.users,'Tab invites',@@ -139,8 +144,13 @@ const _kSettingsGroups = [// What the agents on this machine have spent. It carries the switches that decide which logs// are read at all — the pane is off until somebody sets it.SettingsSection.usage,+ // Which models a Super Tab's Lead may pick, and how it weighs them: the account's default.+ SettingsSection.routing,+ ]),+ SettingsGroup('Labs', [+ SettingsSection.tabInvites,+ SettingsSection.experimental,]),- SettingsGroup('Labs', [SettingsSection.tabInvites, SettingsSection.experimental]),// Debug, in builds that have it, beside the version a report has to name.SettingsGroup('Help', [SettingsSection.about, SettingsSection.debug]),];diff --git a/desktop/lib/super_tabs/launch.dart b/desktop/lib/super_tabs/launch.dartindex 309e25464..ab182ea40 100644--- a/desktop/lib/super_tabs/launch.dart+++ b/desktop/lib/super_tabs/launch.dart@@ -128,6 +128,7 @@ class SuperTabLaunch {'Reuse that operation ID and exact message after a lost reply. Your native terminal is not the shared conversation.\n''If sandbox restrictions block this local Harness command, request permission to run it outside the sandbox. ''For work groups, assignments, acceptance evidence and messages to other agents, use `$command help`. '+ '${saved['lead'] == true ? 'Before starting or assigning work, run `$command route GROUP JSON` with your difficulty and risk assessment, then start or assign its pick with the routeDecisionId it returns. To choose otherwise, pass overrideReason. If it answers NO_CANDIDATE, tell the person in the group why, using its reasons; do not guess another machine. ' : ''}''Use a group for an independently assignable outcome with acceptance checks. Reuse existing groups and agents. ''Engine-native helper subagents do not need a group. Questions stay in the conversation where the work happens. ''Report exact revisions, evidence and links appropriate to the project.\n\n'diff --git a/desktop/lib/super_tabs/model.dart b/desktop/lib/super_tabs/model.dartindex 00c18486a..133dfd935 100644--- a/desktop/lib/super_tabs/model.dart+++ b/desktop/lib/super_tabs/model.dart@@ -101,6 +101,63 @@ class SuperTabSnapshot {: message.authorName;}+class SuperTabRouteChoice {+ const SuperTabRouteChoice(this.id, this.title);+ final String id, title;+}++/// The routing decision a Lead message reports: who got the task and why.+class SuperTabRoute {+ SuperTabRoute._(+ this.decisionId,+ this.via,+ this.p,+ this.belowFloor,+ this.why,+ this.fallback,+ this.pick,+ this.alternatives,+ );+ static SuperTabRoute? fromSource(Map<String, dynamic> s) {+ final pick = s['pick'];+ final decisionId = s['decisionId'];+ if (s['kind'] != 'route' ||+ decisionId is! String ||+ pick is! Map ||+ pick['id'] is! String ||+ pick['title'] is! String) {+ return null;+ }+ final via = s['via'];+ final why = s['why'];+ final alternatives = s['alternatives'];+ return SuperTabRoute._(+ decisionId,+ via is String ? via : 'order',+ s['p'] is num ? (s['p'] as num).toDouble() : null,+ s['belowFloor'] == true,+ why is String ? why : '',+ s['fallback'] is String ? s['fallback'] as String : null,+ SuperTabRouteChoice(pick['id'] as String, pick['title'] as String),+ [+ if (alternatives is List)+ for (final a in alternatives)+ if (a is Map && a['id'] is String && a['title'] is String)+ SuperTabRouteChoice(a['id'] as String, a['title'] as String),+ ],+ );+ }++ /// The Lead's reason for the task. Why the policy order decided, when it did,+ /// is [fallback]: `unsure` or `unavailable`.+ final String decisionId, via, why;+ final String? fallback;+ final double? p;+ final bool belowFloor;+ final SuperTabRouteChoice pick;+ final List<SuperTabRouteChoice> alternatives;+}+class SuperTabMessage {SuperTabMessage.fromJson(Map<String, dynamic> row): id = _text(row, 'id'),@@ -126,6 +183,8 @@ class SuperTabMessage {String get authorId => author['id'] as String? ?? '';bool get fromAgent => author['kind'] == 'agent';bool get fromTerminal => source['kind'] == 'native';+ SuperTabRoute? get route => SuperTabRoute.fromSource(source);+ bool get routeOverride => source['kind'] == 'route-override';String? get terminalNote {if (!fromTerminal) return null;final phase = source['phase'];diff --git a/desktop/lib/super_tabs/route_row.dart b/desktop/lib/super_tabs/route_row.dartnew file mode 100644index 000000000..a9ec5cf89--- /dev/null+++ b/desktop/lib/super_tabs/route_row.dart@@ -0,0 +1,495 @@+import 'dart:async';++import 'package:flutter/material.dart';++import '../shared/theme/app_theme.dart' as grid;+import '../shared/widgets/app_dialog.dart';+import '../widgets/desktop_chrome.dart';+import 'controller.dart';+import 'dialog_scope.dart';+import 'model.dart';+import 'routing_policy.dart';+import 'routing_policy_form.dart';++/// One routing decision in the conversation: who was chosen, how, and why.+/// Writers can change it afterwards; the Lead is told to hand the task over.+class SuperTabRouteRow extends StatefulWidget {+ const SuperTabRouteRow({+ super.key,+ required this.message,+ required this.route,+ required this.controller,+ });+ final SuperTabMessage message;+ final SuperTabRoute route;+ final SuperTabController controller;+ @override+ State<SuperTabRouteRow> createState() => _SuperTabRouteRowState();+}++class _SuperTabRouteRowState extends State<SuperTabRouteRow> {+ Map<String, dynamic>? _details;+ bool _expanded = false;+ // Kept in the row, not a snackbar: a refusal must stay readable until the+ // person tries again.+ String? _problem;++ String get _how => switch (widget.route.via) {+ 'jev' => 'Jev ${((widget.route.p ?? 0) * 100).round()}%',+ 'only' => 'only candidate',+ _ => switch (widget.route.fallback) {+ 'unavailable' => 'by policy order (Jev unavailable)',+ 'unsure' => 'by policy order (Jev unsure)',+ _ => 'by policy order',+ },+ };++ /// The recorded decision, loaded once; null when it cannot be read.+ Future<Map<String, dynamic>?> _load() async {+ if (_details != null) return _details;+ try {+ final answer = await widget.controller.request(+ 'GET',+ '/api/super-tabs/${widget.controller.tabId}/route-decisions/${widget.route.decisionId}',+ );+ if (mounted) _details = answer;+ return answer;+ } catch (_) {+ return null;+ }+ }++ Future<void> _toggle() async {+ setState(() => _expanded = !_expanded);+ if (!_expanded || _details != null) return;+ final answer = await _load();+ if (mounted) setState(() => _details = answer ?? const {'error': true});+ }++ Future<void> _change() async {+ final c = widget.controller;+ final choice = await showAppDialog<(String, String)>(+ context: context,+ builder: (_) => SuperTabDialogScope(+ controller: c,+ child: _ChangeDialog(route: widget.route, load: _load),+ ),+ );+ if (choice == null || !mounted) return;+ setState(() => _problem = null);+ // command() answers null without trying when the controller is busy, so+ // that case must not be reported as a refusal.+ if (c.saving || c.hasPendingAction) {+ setState(() => _problem = 'Finish the pending action first.');+ return;+ }+ final result = await c.command({+ 'type': 'route.override',+ 'decisionId': widget.route.decisionId,+ 'candidateId': choice.$1,+ 'reason': choice.$2,+ });+ // An attempted command resets operationError first, so a value here is+ // this attempt's refusal.+ if (result == null && mounted) {+ setState(+ () => _problem = c.operationError ?? 'Could not change the route.',+ );+ return;+ }+ // The decision now names the new choice; a kept copy would offer it as an+ // alternative on the next Change.+ _details = null;+ if (_expanded && mounted) {+ final answer = await _load();+ if (mounted) setState(() => _details = answer ?? const {'error': true});+ }+ }++ @override+ Widget build(BuildContext context) {+ final r = widget.route;+ return Padding(+ padding: const EdgeInsets.symmetric(vertical: 4),+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ Wrap(+ spacing: 8,+ crossAxisAlignment: WrapCrossAlignment.center,+ children: [+ InkWell(+ onTap: _toggle,+ child: Text(+ 'Routed to ${r.pick.title} — $_how · "${r.why}"',+ style: DesktopChrome.metadata(),+ ),+ ),+ if (r.belowFloor)+ Container(+ padding: const EdgeInsets.symmetric(+ horizontal: 6,+ vertical: 2,+ ),+ decoration: BoxDecoration(+ color: grid.AppPalette.warn.withValues(alpha: 0.12),+ borderRadius: BorderRadius.circular(4),+ ),+ child: Text(+ 'Below quality floor',+ style: DesktopChrome.metadata(color: grid.AppPalette.warn),+ ),+ ),+ if (widget.controller.canWrite && r.alternatives.isNotEmpty)+ TextButton(+ onPressed: () => unawaited(_change()),+ child: const Text('Change'),+ ),+ ],+ ),+ if (_problem != null)+ Text(_problem!, style: DesktopChrome.metadata()),+ if (_expanded) _detailsView(),+ ],+ ),+ );+ }++ Widget _detailsView() {+ final d = _details;+ if (d == null) {+ return const Padding(+ padding: EdgeInsets.all(8),+ child: LinearProgressIndicator(),+ );+ }+ if (d['error'] == true) {+ return Text(+ 'Could not load this decision.',+ style: DesktopChrome.metadata(),+ );+ }+ final record = superTabMap(d['record'] ?? const {});+ final candidates = (record['candidates'] as List? ?? const []).map(+ superTabMap,+ );+ final excluded = (record['excluded'] as List? ?? const []).map(superTabMap);+ return Padding(+ padding: const EdgeInsets.only(left: 12, top: 4),+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ Text(+ 'Quality floor ${record['floor']}${record['notes'] == true ? ' · policy notes applied' : ''}',+ style: DesktopChrome.metadata(),+ ),+ for (final c in candidates)+ Text('${c['id']}: ${c['label']}', style: DesktopChrome.metadata()),+ for (final e in excluded)+ Text(+ 'Not possible: ${e['title']} — ${e['reason']}',+ style: DesktopChrome.metadata(),+ ),+ ],+ ),+ );+ }+}++class _Option {+ const _Option(this.id, this.title, this.label);+ final String id, title;+ final String? label;+}++class _ChangeDialog extends StatefulWidget {+ const _ChangeDialog({required this.route, required this.load});+ final SuperTabRoute route;+ final Future<Map<String, dynamic>?> Function() load;+ @override+ State<_ChangeDialog> createState() => _ChangeDialogState();+}++class _ChangeDialogState extends State<_ChangeDialog> {+ String? _choice;+ List<_Option>? _options;+ bool _failed = false;+ final _reason = TextEditingController();++ @override+ void initState() {+ super.initState();+ unawaited(_open());+ }++ @override+ void dispose() {+ _reason.dispose();+ super.dispose();+ }++ Future<void> _open() async {+ final d = await widget.load();+ if (!mounted) return;+ if (d == null) {+ setState(() => _failed = true);+ return;+ }+ final record = superTabMap(d['record'] ?? const {});+ final candidates = [+ for (final c in record['candidates'] as List? ?? const [])+ if (c is Map && c['id'] is String) superTabMap(c),+ ];+ final pick = record['pick'];+ final current =+ superTabMap(d['override'] ?? const {})['candidateId'] ??+ (pick is Map ? pick['id'] : pick);+ String? labelOf(String id) => candidates+ .where((c) => c['id'] == id)+ .map((c) => c['label'])+ .whereType<String>()+ .firstOrNull;+ final options = <_Option>[+ for (final a in widget.route.alternatives)+ if (a.id != current) _Option(a.id, a.title, labelOf(a.id)),+ ];+ for (final c in candidates) {+ final id = c['id'] as String;+ if (id == current || options.any((o) => o.id == id)) continue;+ options.add(+ _Option(+ id,+ c['title'] as String? ?? id,+ c['label'] is String ? c['label'] as String : null,+ ),+ );+ }+ setState(() => _options = options);+ }++ @override+ Widget build(BuildContext context) {+ final reason = _reason.text.trim();+ final ready = _choice != null && reason.isNotEmpty && reason.length <= 300;+ final options = _options;+ return AlertDialog(+ title: const Text('Change who does this task'),+ content: SizedBox(+ width: 480,+ child: Column(+ mainAxisSize: MainAxisSize.min,+ children: [+ if (_failed)+ Text(+ 'Could not load this decision. Close and try again.',+ style: DesktopChrome.control(),+ )+ else if (options == null)+ const LinearProgressIndicator()+ else+ RadioGroup<String>(+ groupValue: _choice,+ onChanged: (v) => setState(() => _choice = v),+ child: Column(+ children: [+ for (final o in options)+ RadioListTile<String>(+ value: o.id,+ title: Text(o.title),+ subtitle: o.label == null ? null : Text(o.label!),+ ),+ ],+ ),+ ),+ TextField(+ controller: _reason,+ maxLength: 300,+ decoration: const InputDecoration(labelText: 'Reason'),+ onChanged: (_) => setState(() {}),+ ),+ ],+ ),+ ),+ actions: [+ TextButton(+ onPressed: () => Navigator.of(context).pop(),+ child: const Text('Cancel'),+ ),+ FilledButton(+ onPressed: ready+ ? () => Navigator.of(context).pop((_choice!, reason))+ : null,+ child: const Text('Change'),+ ),+ ],+ );+ }+}++/// Opens this Super Tab's routing policy: the effective policy, with the+/// fields it overrides marked. Only the owner can change it.+Future<void> showSuperTabRouting(BuildContext context, SuperTabController c) =>+ showAppDialog<void>(+ context: context,+ builder: (_) => SuperTabDialogScope(+ controller: c,+ requireWrite: false,+ child: _RoutingDialog(controller: c),+ ),+ );++class _RoutingDialog extends StatefulWidget {+ const _RoutingDialog({required this.controller});+ final SuperTabController controller;+ @override+ State<_RoutingDialog> createState() => _RoutingDialogState();+}++class _RoutingDialogState extends State<_RoutingDialog> {+ RoutingPolicy? _policy;+ // The owner's account policy: what a field shows after Use account default.+ RoutingPolicy? _account;+ // The fields this Super Tab overrides; the rest follow the account default.+ final _overridden = <String>{};+ List<String> _warnings = const [];+ String? _problem;+ bool _valid = true;++ SuperTabController get _c => widget.controller;++ @override+ void initState() {+ super.initState();+ unawaited(_load());+ }++ Future<void> _load() async {+ try {+ final answer = await _c.request(+ 'GET',+ '/api/super-tabs/${_c.tabId}/routing-policy',+ );+ if (!mounted) return;+ setState(() {+ _policy = RoutingPolicy.fromJson(superTabMap(answer['policy']));+ if (answer['account'] is Map) {+ _account = RoutingPolicy.fromJson(superTabMap(answer['account']));+ }+ _overridden.addAll((answer['overridden'] as List? ?? const []).cast());+ _warnings = (answer['warnings'] as List? ?? const [])+ .whereType<String>()+ .toList();+ });+ } catch (failure) {+ if (mounted) {+ setState(+ () => _problem = 'Could not load the routing policy. $failure',+ );+ }+ }+ }++ Future<void> _save() async {+ final policy = _policy;+ if (policy == null) return;+ setState(() => _problem = null);+ // command() answers null without trying when the controller is busy, so+ // that case must not be reported as a refusal.+ if (_c.saving || _c.hasPendingAction) {+ setState(() => _problem = 'Finish the pending action first.');+ return;+ }+ final result = await _c.command({+ 'type': 'tab.routingPolicy',+ 'policy': _overridden.isEmpty ? null : policy.fields(_overridden),+ });+ if (!mounted) return;+ if (result == null) {+ setState(+ () => _problem = _c.operationError ?? 'Could not save the routing.',+ );+ return;+ }+ Navigator.of(context).pop();+ }++ /// The fields [next] differs in, so editing one marks it as overridden.+ Set<String> _changed(RoutingPolicy a, RoutingPolicy b) {+ final x = a.toJson(), y = b.toJson();+ return {+ for (final k in const ['models', 'floor', 'quotaReserve', 'notes'])+ if (x[k].toString() != y[k].toString()) k,+ };+ }++ @override+ Widget build(BuildContext context) {+ final policy = _policy;+ final owner = _c.isOwner;+ return ListenableBuilder(+ listenable: _c,+ builder: (context, _) => AlertDialog(+ title: const Text('Routing for this Super Tab'),+ content: SizedBox(+ width: 560,+ child: SingleChildScrollView(+ child: Column(+ mainAxisSize: MainAxisSize.min,+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ if (policy == null && _problem == null)+ const LinearProgressIndicator(),+ for (final warning in _warnings)+ Padding(+ padding: const EdgeInsets.only(bottom: 8),+ child: Text(warning, style: DesktopChrome.metadata()),+ ),+ if (policy != null)+ RoutingPolicyForm(+ value: policy,+ readOnly: !owner,+ overridden: _overridden,+ onValidChanged: (ok) => setState(() => _valid = ok),+ onChanged: (next) => setState(() {+ _overridden.addAll(_changed(policy, next));+ _policy = next;+ }),+ onUseDefault: (field) => setState(() {+ _overridden.remove(field);+ final account = _account;+ if (account != null) {+ _policy = policy.takeField(field, account);+ }+ }),+ ),+ if (_problem != null)+ Padding(+ padding: const EdgeInsets.only(top: 8),+ child: Text(+ _problem!,+ style: DesktopChrome.control(+ color: Theme.of(context).colorScheme.error,+ ),+ ),+ ),+ ],+ ),+ ),+ ),+ actions: [+ TextButton(+ onPressed: () => Navigator.of(context).pop(),+ child: Text(owner ? 'Cancel' : 'Close'),+ ),+ if (owner)+ FilledButton(+ onPressed: policy == null || !_valid || _c.saving+ ? null+ : () => unawaited(_save()),+ child: const Text('Save'),+ ),+ ],+ ),+ );+ }+}diff --git a/desktop/lib/super_tabs/routing_policy.dart b/desktop/lib/super_tabs/routing_policy.dartnew file mode 100644index 000000000..39bac23f3--- /dev/null+++ b/desktop/lib/super_tabs/routing_policy.dart@@ -0,0 +1,116 @@+/// One model the Lead may route to, as the backend stores it+/// (backend/src/superTabs/routingPolicy.ts).+class RoutingModel {+ const RoutingModel({+ required this.engine,+ required this.model,+ required this.effort,+ required this.quality,+ required this.cost,+ required this.enabled,+ });++ factory RoutingModel.fromJson(Map<String, dynamic> j) => RoutingModel(+ engine: j['engine'] as String,+ model: j['model'] as String,+ effort: j['effort'] as String,+ quality: (j['quality'] as num).toInt(),+ cost: (j['cost'] as num).toInt(),+ enabled: j['enabled'] == true,+ );++ final String engine, model, effort;+ final int quality, cost;+ final bool enabled;++ RoutingModel copyWith({int? quality, int? cost, bool? enabled}) =>+ RoutingModel(+ engine: engine,+ model: model,+ effort: effort,+ quality: quality ?? this.quality,+ cost: cost ?? this.cost,+ enabled: enabled ?? this.enabled,+ );++ Map<String, dynamic> toJson() => {+ 'engine': engine,+ 'model': model,+ 'effort': effort,+ 'quality': quality,+ 'cost': cost,+ 'enabled': enabled,+ };++ String get label =>+ '${engine == 'claude' ? 'Claude' : 'Codex'} '+ '${model == 'default' ? 'default model' : model}'+ '${effort == 'default' ? '' : ' $effort'}';+}++/// The Super Tab routing policy: which models may be chosen, the quality each+/// difficulty needs, and how much quota to keep back.+class RoutingPolicy {+ const RoutingPolicy({+ required this.models,+ required this.floor,+ required this.quotaReserve,+ required this.notes,+ });++ factory RoutingPolicy.fromJson(Map<String, dynamic> j) {+ final floor = Map<String, dynamic>.from(j['floor'] as Map);+ return RoutingPolicy(+ models: [+ for (final m in j['models'] as List)+ RoutingModel.fromJson(Map<String, dynamic>.from(m as Map)),+ ],+ floor: {+ for (final k in const ['low', 'medium', 'high'])+ k: (floor[k] as num).toInt(),+ },+ quotaReserve: (j['quotaReserve'] as num).toInt(),+ notes: j['notes'] as String? ?? '',+ );+ }++ final List<RoutingModel> models;+ final Map<String, int> floor;+ final int quotaReserve;+ final String notes;++ RoutingPolicy copyWith({+ List<RoutingModel>? models,+ Map<String, int>? floor,+ int? quotaReserve,+ String? notes,+ }) => RoutingPolicy(+ models: models ?? this.models,+ floor: floor ?? this.floor,+ quotaReserve: quotaReserve ?? this.quotaReserve,+ notes: notes ?? this.notes,+ );++ Map<String, dynamic> toJson() => {+ 'version': 1,+ 'floor': floor,+ 'quotaReserve': quotaReserve,+ 'notes': notes,+ 'models': [for (final m in models) m.toJson()],+ };++ /// This policy with one field taken from [other], for a field that goes back+ /// to the account default.+ RoutingPolicy takeField(String field, RoutingPolicy other) => switch (field) {+ 'models' => copyWith(models: other.models),+ 'floor' => copyWith(floor: other.floor),+ 'quotaReserve' => copyWith(quotaReserve: other.quotaReserve),+ _ => copyWith(notes: other.notes),+ };++ /// Only the named fields, for a Super Tab override.+ Map<String, dynamic> fields(Set<String> names) => {+ for (final e in toJson().entries)+ if (names.contains(e.key)) e.key: e.value,+ };+}diff --git a/desktop/lib/super_tabs/routing_policy_form.dart b/desktop/lib/super_tabs/routing_policy_form.dartnew file mode 100644index 000000000..7dcbb5517--- /dev/null+++ b/desktop/lib/super_tabs/routing_policy_form.dart@@ -0,0 +1,269 @@+import 'package:flutter/material.dart';+import 'package:flutter/services.dart';++import '../shared/widgets/setting_row.dart';+import 'routing_policy.dart';++/// The routing policy editor, used by Settings ▸ Routing (the account default)+/// and by a Super Tab's Routing dialog (override mode, with Use account+/// default).+///+/// A number outside what the backend accepts is flagged under its field and is+/// never passed to [onChanged]; [onValidChanged] says whether every field is+/// acceptable, so the host can hold Save back.+class RoutingPolicyForm extends StatefulWidget {+ const RoutingPolicyForm({+ super.key,+ required this.value,+ required this.onChanged,+ this.onValidChanged,+ this.overridden,+ this.onUseDefault,+ this.readOnly = false,+ });+ final RoutingPolicy value;+ final ValueChanged<RoutingPolicy> onChanged;+ final ValueChanged<bool>? onValidChanged;+ final Set<String>? overridden;+ final ValueChanged<String>? onUseDefault;+ final bool readOnly;++ @override+ State<RoutingPolicyForm> createState() => _RoutingPolicyFormState();+}++class _RoutingPolicyFormState extends State<RoutingPolicyForm> {+ final _invalid = <Key>{};+ // Bumped when a field goes back to the account default, so its inputs start+ // again from the value now shown instead of what was typed.+ final _restarts = <String, int>{};+ static const _keyPrefix = {+ 'models': 'routing-model-',+ 'floor': 'routing-floor-',+ 'quotaReserve': 'routing-reserve',+ };++ RoutingPolicy get _value => widget.value;++ void _number(Key key, String text, int min, int max, ValueChanged<int> set) {+ final n = int.tryParse(text);+ final ok = n != null && n >= min && n <= max;+ final wasValid = _invalid.isEmpty;+ setState(() => ok ? _invalid.remove(key) : _invalid.add(key));+ if (wasValid != _invalid.isEmpty) {+ widget.onValidChanged?.call(_invalid.isEmpty);+ }+ if (ok) set(n);+ }++ void _useDefault(String field) {+ final wasValid = _invalid.isEmpty;+ final prefix = _keyPrefix[field];+ setState(() {+ _restarts[field] = (_restarts[field] ?? 0) + 1;+ if (prefix != null) {+ _invalid.removeWhere(+ (k) => (k as ValueKey<String>).value.startsWith(prefix),+ );+ }+ });+ if (wasValid != _invalid.isEmpty) {+ widget.onValidChanged?.call(_invalid.isEmpty);+ }+ widget.onUseDefault!(field);+ }++ Widget _field(+ Key key,+ String label,+ int current,+ int min,+ int max,+ ValueChanged<int> set,+ ) => SizedBox(+ width: 104,+ child: TextFormField(+ key: key,+ initialValue: '$current',+ enabled: !widget.readOnly,+ keyboardType: TextInputType.number,+ inputFormatters: [FilteringTextInputFormatter.digitsOnly],+ decoration: InputDecoration(+ labelText: label,+ isDense: true,+ errorText: _invalid.contains(key) ? 'Use $min–$max' : null,+ ),+ onChanged: (text) => _number(key, text, min, max, set),+ ),+ );++ /// The setting block: its title and detail, the per-field reset when this+ /// field is overridden, and its editor underneath.+ Widget _block(String field, String title, String detail, Widget editor) =>+ Padding(+ padding: const EdgeInsets.only(bottom: 10),+ child: SettingRow(+ title: title,+ detail: detail,+ control:+ widget.overridden?.contains(field) == true &&+ widget.onUseDefault != null &&+ !widget.readOnly+ ? TextButton(+ onPressed: () => _useDefault(field),+ child: const Text('Use account default'),+ )+ : const SizedBox.shrink(),+ footer: KeyedSubtree(+ key: ValueKey('$field-${_restarts[field] ?? 0}'),+ child: editor,+ ),+ ),+ );++ @override+ Widget build(BuildContext context) {+ final small = Theme.of(context).textTheme.bodySmall;+ List<RoutingModel> withModel(int i, RoutingModel m) =>+ [..._value.models]..[i] = m;+ const reserveKey = ValueKey('routing-reserve');+ final rangeError = Theme.of(context).colorScheme.error;+ return Column(+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ _block(+ 'models',+ 'Models',+ 'Quality 1–3 and relative cost 1–100 decide who is chosen. Turn a model off to never use it.',+ Column(+ children: [+ for (final (i, m) in _value.models.indexed)+ Padding(+ padding: const EdgeInsets.symmetric(vertical: 4),+ child: Wrap(+ spacing: 12,+ runSpacing: 8,+ crossAxisAlignment: WrapCrossAlignment.center,+ children: [+ Switch(+ key: ValueKey('routing-model-enabled-$i'),+ value: m.enabled,+ onChanged: widget.readOnly+ ? null+ : (on) => widget.onChanged(+ _value.copyWith(+ models: withModel(i, m.copyWith(enabled: on)),+ ),+ ),+ ),+ SizedBox(width: 180, child: Text(m.label)),+ _field(+ ValueKey('routing-model-quality-$i'),+ 'Quality',+ m.quality,+ 1,+ 3,+ (q) => widget.onChanged(+ _value.copyWith(+ models: withModel(i, m.copyWith(quality: q)),+ ),+ ),+ ),+ _field(+ ValueKey('routing-model-cost-$i'),+ 'Cost',+ m.cost,+ 1,+ 100,+ (c) => widget.onChanged(+ _value.copyWith(+ models: withModel(i, m.copyWith(cost: c)),+ ),+ ),+ ),+ ],+ ),+ ),+ ],+ ),+ ),+ _block(+ 'floor',+ 'Quality floor by difficulty',+ 'The lowest quality (1–3) a model needs for a task of that difficulty. High risk raises the floor by one.',+ Wrap(+ spacing: 12,+ runSpacing: 8,+ children: [+ for (final level in const ['low', 'medium', 'high'])+ _field(+ ValueKey('routing-floor-$level'),+ '${level[0].toUpperCase()}${level.substring(1)}',+ _value.floor[level]!,+ 1,+ 3,+ (n) => widget.onChanged(+ _value.copyWith(floor: {..._value.floor, level: n}),+ ),+ ),+ ],+ ),+ ),+ _block(+ 'quotaReserve',+ 'Quota reserve',+ 'Percent of an account’s quota to keep back. Below this, the account is used only when nothing else can run the task.',+ Row(+ children: [+ SizedBox(+ width: 120,+ child: TextFormField(+ key: reserveKey,+ initialValue: '${_value.quotaReserve}',+ enabled: !widget.readOnly,+ keyboardType: TextInputType.number,+ inputFormatters: [FilteringTextInputFormatter.digitsOnly],+ decoration: const InputDecoration(+ isDense: true,+ suffixText: '%',+ ),+ onChanged: (text) => _number(+ reserveKey,+ text,+ 0,+ 90,+ (n) => widget.onChanged(_value.copyWith(quotaReserve: n)),+ ),+ ),+ ),+ if (_invalid.contains(reserveKey))+ Padding(+ padding: const EdgeInsets.only(left: 12),+ child: Text(+ 'Enter a number from 0 to 90.',+ style: small?.copyWith(color: rangeError),+ ),+ ),+ ],+ ),+ ),+ _block(+ 'notes',+ 'Notes for Jev',+ 'Anything the Lead should weigh when choosing, in plain words.',+ TextFormField(+ key: const ValueKey('routing-notes'),+ initialValue: _value.notes,+ enabled: !widget.readOnly,+ maxLength: 500,+ maxLines: 3,+ decoration: const InputDecoration(+ hintText: 'For example: frontend prefers Claude; long jobs on remote-1.',+ ),+ onChanged: (text) => widget.onChanged(_value.copyWith(notes: text)),+ ),+ ),+ ],+ );+ }+}diff --git a/desktop/lib/super_tabs/view.dart b/desktop/lib/super_tabs/view.dartindex 6b16b8104..dd2edeb93 100644--- a/desktop/lib/super_tabs/view.dart+++ b/desktop/lib/super_tabs/view.dart@@ -13,6 +13,7 @@ import 'controller.dart';import 'dialog_scope.dart';import 'model.dart';import 'message_row.dart';+import 'route_row.dart';import 'work_details.dart';/// The contents of one app tab. Its title stays in the app's existing tab bar.@@ -790,6 +791,15 @@ class _SuperTabViewState extends State<SuperTabView> {: null,child: Text(c.isOwner ? 'Invite' : 'People'),),+ TextButton(+ onPressed: c.snapshot != null+ ? () {+ _closeSidebar();+ unawaited(showSuperTabRouting(context, c));+ }+ : null,+ child: const Text('Routing'),+ ),],),),@@ -1018,6 +1028,15 @@ class _SuperTabViewState extends State<SuperTabView> {bool grouped,Map<String, SuperTabMessage> byId,) {+ final route = message.route;+ if (route != null) {+ return SuperTabRouteRow(+ key: ValueKey('super-message-${message.id}'),+ message: message,+ route: route,+ controller: c,+ );+ }final agent = message.fromAgent? c.snapshot?.agent(message.authorId): null;diff --git a/desktop/test/routing_policy_test.dart b/desktop/test/routing_policy_test.dartnew file mode 100644index 000000000..059c65bf4--- /dev/null+++ b/desktop/test/routing_policy_test.dart@@ -0,0 +1,286 @@+import 'package:flutter/material.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness/super_tabs/routing_policy.dart';+import 'package:harness/super_tabs/routing_policy_form.dart';+import 'package:harness/super_tabs/route_row.dart';++import 'super_tab_launch_test.dart' show SuperTabLaunchFixture, tabId;++final json = {+ 'version': 1,+ 'floor': {'low': 1, 'medium': 2, 'high': 3},+ 'quotaReserve': 10,+ 'notes': '',+ '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,+ },+ ],+};++Widget formOf(Widget form) => MaterialApp(+ home: Scaffold(body: SingleChildScrollView(child: form)),+);++void main() {+ test('round-trips the backend policy', () {+ expect(RoutingPolicy.fromJson(json).toJson(), json);+ });++ testWidgets('edits a model, the floor, the reserve and the notes', (+ tester,+ ) async {+ RoutingPolicy? changed;+ await tester.pumpWidget(+ formOf(+ RoutingPolicyForm(+ value: RoutingPolicy.fromJson(json),+ onChanged: (v) => changed = v,+ ),+ ),+ );+ await tester.tap(find.byKey(const ValueKey('routing-model-enabled-1')));+ await tester.pump();+ expect(changed!.models[1].enabled, isFalse);+ await tester.enterText(find.byKey(const ValueKey('routing-reserve')), '25');+ await tester.pump();+ expect(changed!.quotaReserve, 25);+ await tester.enterText(+ find.byKey(const ValueKey('routing-notes')),+ 'Frontend prefers Claude.',+ );+ await tester.pump();+ expect(changed!.notes, 'Frontend prefers Claude.');+ });++ testWidgets('a value the backend would reject is flagged, not accepted', (+ tester,+ ) async {+ RoutingPolicy? changed;+ final valid = <bool>[];+ await tester.pumpWidget(+ formOf(+ RoutingPolicyForm(+ value: RoutingPolicy.fromJson(json),+ onChanged: (v) => changed = v,+ onValidChanged: valid.add,+ ),+ ),+ );+ await tester.enterText(find.byKey(const ValueKey('routing-reserve')), '95');+ await tester.pump();+ expect(changed, isNull);+ expect(valid, [false]);+ expect(find.text('Enter a number from 0 to 90.'), findsOneWidget);+ await tester.enterText(find.byKey(const ValueKey('routing-reserve')), '90');+ await tester.pump();+ expect(changed!.quotaReserve, 90);+ expect(valid, [false, true]);+ expect(find.text('Enter a number from 0 to 90.'), findsNothing);+ });++ testWidgets(+ 'override mode offers Use account default per field and read-only hides edits',+ (tester) async {+ final used = <String>[];+ await tester.pumpWidget(+ formOf(+ RoutingPolicyForm(+ value: RoutingPolicy.fromJson(json),+ onChanged: (_) {},+ overridden: const {'notes'},+ onUseDefault: used.add,+ ),+ ),+ );+ expect(find.text('Use account default'), findsOneWidget);+ await tester.tap(find.text('Use account default'));+ expect(used, ['notes']);+ await tester.pumpWidget(+ formOf(+ RoutingPolicyForm(+ value: RoutingPolicy.fromJson(json),+ onChanged: (_) {},+ readOnly: true,+ ),+ ),+ );+ expect(+ tester+ .widget<Switch>(+ find.byKey(const ValueKey('routing-model-enabled-0')),+ )+ .onChanged,+ isNull,+ );+ },+ );++ Map<String, dynamic> policyAnswer() => {+ 'policy': json,+ 'warnings': <dynamic>[],+ 'overridden': <String>[],+ 'override': null,+ };++ Widget opener(controller) => MaterialApp(+ home: Scaffold(+ body: Builder(+ builder: (context) => TextButton(+ onPressed: () => showSuperTabRouting(context, controller),+ child: const Text('Open routing'),+ ),+ ),+ ),+ );++ testWidgets('the owner saves an override with only the changed field', (+ tester,+ ) async {+ final f = SuperTabLaunchFixture();+ f.connection.server.routingPolicy = policyAnswer();+ final controller = await f.app.superTabs.open(tabId);+ await controller.refresh();+ await tester.pumpWidget(opener(controller));+ await tester.tap(find.text('Open routing'));+ await tester.pumpAndSettle();+ await tester.enterText(+ find.byKey(const ValueKey('routing-notes')),+ 'Frontend prefers Claude.',+ );+ await tester.pump();+ await tester.tap(find.widgetWithText(FilledButton, 'Save'));+ await tester.pumpAndSettle();+ expect(f.connection.server.posts.last['command'], {+ 'type': 'tab.routingPolicy',+ 'policy': {'notes': 'Frontend prefers Claude.'},+ });+ expect(find.text('Routing for this Super Tab'), findsNothing);+ f.app.superTabs.dispose();+ });++ testWidgets(+ 'Use account default shows the account value, clears the field, and saves no override',+ (tester) async {+ final f = SuperTabLaunchFixture();+ final account = {...json, 'notes': 'Account notes.'};+ f.connection.server.routingPolicy = {+ ...policyAnswer(),+ 'policy': {...json, 'notes': 'Tab notes.'},+ 'account': account,+ 'overridden': ['notes'],+ };+ final controller = await f.app.superTabs.open(tabId);+ await controller.refresh();+ await tester.pumpWidget(opener(controller));+ await tester.tap(find.text('Open routing'));+ await tester.pumpAndSettle();+ expect(find.text('Tab notes.'), findsOneWidget);+ await tester.ensureVisible(find.text('Use account default'));+ await tester.tap(find.text('Use account default'));+ await tester.pumpAndSettle();+ expect(find.text('Tab notes.'), findsNothing);+ expect(find.text('Account notes.'), findsOneWidget);+ expect(find.text('Use account default'), findsNothing);+ await tester.tap(find.widgetWithText(FilledButton, 'Save'));+ await tester.pumpAndSettle();+ expect(f.connection.server.posts.last['command'], {+ 'type': 'tab.routingPolicy',+ 'policy': null,+ });+ f.app.superTabs.dispose();+ },+ );++ testWidgets(+ 'Use account default on a field with a bad number restores Save',+ (tester) async {+ final f = SuperTabLaunchFixture();+ f.connection.server.routingPolicy = {+ ...policyAnswer(),+ 'policy': {...json, 'quotaReserve': 25},+ 'account': {...json, 'quotaReserve': 10},+ 'overridden': ['quotaReserve'],+ };+ final controller = await f.app.superTabs.open(tabId);+ await controller.refresh();+ await tester.pumpWidget(opener(controller));+ await tester.tap(find.text('Open routing'));+ await tester.pumpAndSettle();+ await tester.enterText(+ find.byKey(const ValueKey('routing-reserve')),+ '95',+ );+ await tester.pump();+ expect(find.text('Enter a number from 0 to 90.'), findsOneWidget);+ expect(+ tester+ .widget<FilledButton>(find.widgetWithText(FilledButton, 'Save'))+ .onPressed,+ isNull,+ );+ await tester.ensureVisible(find.text('Use account default'));+ await tester.tap(find.text('Use account default'));+ await tester.pumpAndSettle();+ expect(find.text('Enter a number from 0 to 90.'), findsNothing);+ expect(find.text('10'), findsOneWidget);+ expect(+ tester+ .widget<FilledButton>(find.widgetWithText(FilledButton, 'Save'))+ .onPressed,+ isNotNull,+ );+ f.app.superTabs.dispose();+ },+ );++ testWidgets('a refused save stays open and says why', (tester) async {+ final f = SuperTabLaunchFixture();+ f.connection.server.routingPolicy = policyAnswer();+ f.connection.server.refuse = {+ 'code': 'OWNER_REQUIRED',+ 'message': 'Only the owner can change routing.',+ };+ final controller = await f.app.superTabs.open(tabId);+ await controller.refresh();+ await tester.pumpWidget(opener(controller));+ await tester.tap(find.text('Open routing'));+ await tester.pumpAndSettle();+ await tester.enterText(find.byKey(const ValueKey('routing-notes')), 'x');+ await tester.pump();+ await tester.tap(find.widgetWithText(FilledButton, 'Save'));+ await tester.pumpAndSettle();+ expect(find.text('Routing for this Super Tab'), findsOneWidget);+ expect(find.textContaining('Only the owner'), findsOneWidget);+ f.app.superTabs.dispose();+ });++ testWidgets('a viewer sees the effective policy and no Save', (tester) async {+ final f = SuperTabLaunchFixture();+ f.connection.server.routingPolicy = policyAnswer();+ f.connection.server.state['ownerId'] = 'someone-else';+ (f.connection.server.state['people'] as List)[0]['role'] = 'viewer';+ final controller = await f.app.superTabs.open(tabId);+ await controller.refresh();+ await tester.pumpWidget(opener(controller));+ await tester.tap(find.text('Open routing'));+ await tester.pumpAndSettle();+ expect(find.text('Claude opus high'), findsOneWidget);+ expect(find.widgetWithText(FilledButton, 'Save'), findsNothing);+ expect(find.text('Close'), findsOneWidget);+ f.app.superTabs.dispose();+ });+}diff --git a/desktop/test/settings_screen_test.dart b/desktop/test/settings_screen_test.dartindex 66de0d845..3c96f6011 100644--- a/desktop/test/settings_screen_test.dart+++ b/desktop/test/settings_screen_test.dart@@ -101,6 +101,8 @@ void main() {'Keyboard shortcuts','Connectors','Usage',+ 'Routing',+ 'Tab invites','Experimental','About','Debug',diff --git a/desktop/test/settings_section_test.dart b/desktop/test/settings_section_test.dartindex d7f373858..d55f2cb35 100644--- a/desktop/test/settings_section_test.dart+++ b/desktop/test/settings_section_test.dart@@ -38,6 +38,7 @@ void main() {// files, and it reads nothing at all until a provider is switched on, so// there is nothing here for a shipped build to hide.SettingsSection.usage,+ SettingsSection.routing,SettingsSection.tabInvites,SettingsSection.experimental,SettingsSection.about,@@ -61,7 +62,11 @@ void main() {if (kIsWeb) SettingsSection.privacy,SettingsSection.shortcuts,],- [if (!kIsWeb) SettingsSection.connectors, SettingsSection.usage],+ [+ if (!kIsWeb) SettingsSection.connectors,+ SettingsSection.usage,+ SettingsSection.routing,+ ],[SettingsSection.tabInvites, SettingsSection.experimental],[SettingsSection.about, SettingsSection.debug],]);diff --git a/desktop/test/super_tab_launch_test.dart b/desktop/test/super_tab_launch_test.dartindex dc3ee93a4..4a41e57a0 100644--- a/desktop/test/super_tab_launch_test.dart+++ b/desktop/test/super_tab_launch_test.dart@@ -492,6 +492,21 @@ void main() {);}+ test('the lead prompt routes before starting or assigning work', () async {+ final f = SuperTabLaunchFixture()..connection.nativeName = 'hi';+ final box = await f.box(engine: 'claude');+ expect(await box.create(), NewHarnessOutcome.created, reason: box.error);+ final prompt =+ f.connection.calls+ .firstWhere((c) => c.$1 == 'agent_create')+ .$2['prompt']+ as String;+ expect(prompt, contains('route GROUP'));+ expect(prompt, contains('routeDecisionId'));+ expect(prompt, contains('overrideReason'));+ expect(prompt, contains('NO_CANDIDATE'));+ });+test('lost join acknowledgement retries the same contribution without a second native launch', () async {final f = SuperTabLaunchFixture()..connection.loseJoin = true;final box = await f.box();diff --git a/desktop/test/super_tab_route_test.dart b/desktop/test/super_tab_route_test.dartnew file mode 100644index 000000000..925db9ee6--- /dev/null+++ b/desktop/test/super_tab_route_test.dart@@ -0,0 +1,385 @@+import 'package:flutter/material.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness/super_tabs/model.dart';+import 'package:harness/super_tabs/route_row.dart';++import 'super_tab_launch_test.dart' show SuperTabLaunchFixture, tabId;++Map<String, dynamic> routeRow({+ String via = 'jev',+ double? p = 0.82,+ bool belowFloor = false,+ String? fallback,+}) => {+ 'id': 'm1',+ 'conversationId': 'offline',+ 'text': 'Routed to Multiply',+ 'replyTo': null,+ 'sequence': 4,+ 'author': {'kind': 'agent', 'id': 'lead', 'name': 'Lead'},+ 'deliveries': const [],+ 'source': {+ 'kind': 'route',+ 'decisionId': 'd1',+ 'via': via,+ 'p': p,+ 'belowFloor': belowFloor,+ 'why': 'schema change, high risk',+ 'fallback': ?fallback,+ 'pick': {'id': 'c0', 'title': 'Multiply · Claude opus high · remote-1'},+ 'alternatives': [+ {'id': 'c1', 'title': 'New agent · Claude sonnet medium · mac'},+ ],+ },+};++Map<String, dynamic> decision({String? overrideTo}) => {+ 'id': 'd1',+ 'conversationId': 'offline',+ 'record': {+ 'candidates': [+ {+ 'id': 'c0',+ 'label': 'Opus, deepest review',+ 'title': 'Multiply · Claude opus high · remote-1',+ },+ {+ 'id': 'c1',+ 'label': 'Sonnet, fastest turnaround',+ 'title': 'New agent · Claude sonnet medium · mac',+ },+ {+ 'id': 'c2',+ 'label': 'Codex, cheapest',+ 'title': 'New agent · Codex low · mac',+ },+ ],+ 'excluded': const [],+ 'floor': 3,+ 'notes': false,+ 'pick': 'c0',+ },+ 'override': overrideTo == null ? null : {'candidateId': overrideTo},+};++Widget rowOf(SuperTabMessage message, controller) => MaterialApp(+ home: Scaffold(+ body: SuperTabRouteRow(+ message: message,+ route: message.route!,+ controller: controller,+ ),+ ),+);++void main() {+ test('parses route sources', () {+ final message = SuperTabMessage.fromJson(routeRow());+ expect(message.route!.decisionId, 'd1');+ expect(message.route!.alternatives.single.title, startsWith('New agent'));+ expect(+ SuperTabMessage.fromJson({+ ...routeRow(),+ 'source': {'kind': 'route-override', 'decisionId': 'd1', 'by': 'lead'},+ }).routeOverride,+ isTrue,+ );+ expect(+ SuperTabMessage.fromJson({+ ...routeRow(),+ 'source': {'kind': 'route', 'decisionId': 'd1'},+ }).route,+ isNull,+ );+ });++ test('wrong-typed route sources never throw', () {+ Map<String, dynamic> source(Map<String, dynamic> extra) => {+ ...routeRow()['source'] as Map<String, dynamic>,+ ...extra,+ };+ SuperTabRoute? parse(Map<String, dynamic> extra) =>+ SuperTabRoute.fromSource(source(extra));+ final odd = parse({'via': 7, 'why': 3, 'p': 'high', 'alternatives': 'x'})!;+ expect(odd.via, 'order');+ expect(odd.why, '');+ expect(odd.p, isNull);+ expect(odd.alternatives, isEmpty);+ expect(parse({'pick': 'c0'}), isNull);+ expect(+ parse({+ 'pick': {'id': 1, 'title': 'x'},+ }),+ isNull,+ );+ expect(parse({'decisionId': 4}), isNull);+ });++ for (final c in [+ (via: 'jev', p: 0.82, below: false, fallback: null, text: 'Jev 82%'),+ (+ via: 'order',+ p: null,+ below: false,+ fallback: null,+ text: 'by policy order ·',+ ),+ (+ via: 'order',+ p: null,+ below: false,+ fallback: 'unsure',+ text: 'by policy order (Jev unsure)',+ ),+ (+ via: 'order',+ p: null,+ below: false,+ fallback: 'unavailable',+ text: 'by policy order (Jev unavailable)',+ ),+ (+ via: 'only',+ p: null,+ below: true,+ fallback: null,+ text: 'Below quality floor',+ ),+ ]) {+ testWidgets('renders ${c.via} ${c.fallback ?? ''}', (tester) async {+ final f = SuperTabLaunchFixture();+ final controller = await f.app.superTabs.open(tabId);+ final message = SuperTabMessage.fromJson(+ routeRow(via: c.via, p: c.p, belowFloor: c.below, fallback: c.fallback),+ );+ await tester.pumpWidget(rowOf(message, controller));+ expect(+ find.textContaining('Routed to Multiply · Claude opus high · remote-1'),+ findsOneWidget,+ );+ expect(find.textContaining(c.text), findsOneWidget);+ // The row quotes the Lead's reason, never the verdict's own text.+ expect(find.textContaining('"schema change, high risk"'), findsOneWidget);+ f.app.superTabs.dispose();+ });+ }++ testWidgets('a second Change does not offer the choice just made', (+ tester,+ ) async {+ final f = SuperTabLaunchFixture();+ f.connection.server.routeDecisions['d1'] = decision();+ final controller = await f.app.superTabs.open(tabId);+ await controller.refresh();+ final message = SuperTabMessage.fromJson(routeRow());+ await tester.pumpWidget(rowOf(message, controller));+ await tester.tap(find.text('Change'));+ await tester.pumpAndSettle();+ expect(find.text('Sonnet, fastest turnaround'), findsOneWidget);+ await tester.tap(find.textContaining('New agent · Claude sonnet medium'));+ await tester.pumpAndSettle();+ await tester.enterText(find.byType(TextField), 'Because.');+ await tester.pump();+ // The backend now names the choice as the decision's override.+ f.connection.server.routeDecisions['d1'] = decision(overrideTo: 'c1');+ await tester.tap(find.widgetWithText(FilledButton, 'Change'));+ await tester.pumpAndSettle();+ await tester.tap(find.text('Change'));+ await tester.pumpAndSettle();+ expect(find.text('Sonnet, fastest turnaround'), findsNothing);+ expect(find.text('Codex, cheapest'), findsOneWidget);+ f.app.superTabs.dispose();+ });++ testWidgets('an open details view is read again after a Change', (+ tester,+ ) async {+ final f = SuperTabLaunchFixture();+ f.connection.server.routeDecisions['d1'] = decision();+ final controller = await f.app.superTabs.open(tabId);+ await controller.refresh();+ final message = SuperTabMessage.fromJson(routeRow());+ await tester.pumpWidget(rowOf(message, controller));+ await tester.tap(find.textContaining('Routed to'));+ await tester.pumpAndSettle();+ expect(find.textContaining('Quality floor 3'), findsOneWidget);+ f.connection.server.routeDecisions['d1'] = {+ ...decision(overrideTo: 'c1'),+ 'record': {...(decision()['record'] as Map), 'floor': 2},+ };+ await tester.tap(find.text('Change'));+ await tester.pumpAndSettle();+ await tester.tap(find.textContaining('New agent · Claude sonnet medium'));+ await tester.pumpAndSettle();+ await tester.enterText(find.byType(TextField), 'Because.');+ await tester.pump();+ await tester.tap(find.widgetWithText(FilledButton, 'Change'));+ await tester.pumpAndSettle();+ expect(find.textContaining('Quality floor 2'), findsOneWidget);+ f.app.superTabs.dispose();+ });++ testWidgets(+ 'Change needs write access and a reason, then sends route.override',+ (tester) async {+ final f = SuperTabLaunchFixture();+ f.connection.server.routeDecisions['d1'] = decision();+ final controller = await f.app.superTabs.open(tabId);+ await controller.refresh();+ final message = SuperTabMessage.fromJson(routeRow());+ await tester.pumpWidget(rowOf(message, controller));+ await tester.tap(find.text('Change'));+ await tester.pumpAndSettle();+ await tester.tap(+ find.textContaining('New agent · Claude sonnet medium · mac'),+ );+ await tester.pumpAndSettle();+ final confirm = find.widgetWithText(FilledButton, 'Change');+ expect(tester.widget<FilledButton>(confirm).onPressed, isNull);+ await tester.enterText(+ find.byType(TextField),+ 'Opus quota is needed elsewhere.',+ );+ await tester.pump();+ await tester.tap(confirm);+ await tester.pumpAndSettle();+ final sent =+ f.connection.calls+ .where(+ (call) =>+ (call.$2['path'] as String?)?.endsWith('/commands') ==+ true,+ )+ .last+ .$2['body']+ as Map;+ expect(sent['command'], {+ 'type': 'route.override',+ 'decisionId': 'd1',+ 'candidateId': 'c1',+ 'reason': 'Opus quota is needed elsewhere.',+ });+ f.app.superTabs.dispose();+ },+ );++ testWidgets('a viewer sees no Change', (tester) async {+ final f = SuperTabLaunchFixture();+ (f.connection.server.state['people'] as List)[0]['role'] = 'viewer';+ final controller = await f.app.superTabs.open(tabId);+ await controller.refresh();+ final message = SuperTabMessage.fromJson(routeRow());+ await tester.pumpWidget(rowOf(message, controller));+ expect(find.text('Change'), findsNothing);+ f.app.superTabs.dispose();+ });++ testWidgets('Change shows the refusal', (tester) async {+ final f = SuperTabLaunchFixture();+ f.connection.server.routeDecisions['d1'] = decision();+ f.connection.server.refuse = {+ 'code': 'ROUTE_CLOSED',+ 'message':+ 'This routing decision is no longer open. Route the task again.',+ };+ final controller = await f.app.superTabs.open(tabId);+ await controller.refresh();+ final message = SuperTabMessage.fromJson(routeRow());+ await tester.pumpWidget(rowOf(message, controller));+ await tester.tap(find.text('Change'));+ await tester.pumpAndSettle();+ await tester.tap(find.textContaining('New agent · Claude sonnet'));+ await tester.pumpAndSettle();+ await tester.enterText(find.byType(TextField), 'Because.');+ await tester.pump();+ await tester.tap(find.widgetWithText(FilledButton, 'Change'));+ await tester.pumpAndSettle();+ expect(find.textContaining('no longer open'), findsOneWidget);+ f.app.superTabs.dispose();+ });++ testWidgets(+ 'Change lists alternatives with criterion lines, minus the current choice',+ (tester) async {+ final f = SuperTabLaunchFixture();+ f.connection.server.routeDecisions['d1'] = decision();+ final controller = await f.app.superTabs.open(tabId);+ await controller.refresh();+ final message = SuperTabMessage.fromJson(routeRow());+ await tester.pumpWidget(rowOf(message, controller));+ await tester.tap(find.text('Change'));+ await tester.pumpAndSettle();+ expect(find.text('Sonnet, fastest turnaround'), findsOneWidget);+ expect(find.text('Codex, cheapest'), findsOneWidget);+ expect(find.text('Opus, deepest review'), findsNothing);+ final order = [+ tester.getTopLeft(find.text('Sonnet, fastest turnaround')).dy,+ tester.getTopLeft(find.text('Codex, cheapest')).dy,+ ];+ expect(order[0], lessThan(order[1]));+ f.app.superTabs.dispose();+ },+ );++ testWidgets('Change excludes an earlier override target', (tester) async {+ final f = SuperTabLaunchFixture();+ f.connection.server.routeDecisions['d1'] = decision(overrideTo: 'c1');+ final controller = await f.app.superTabs.open(tabId);+ await controller.refresh();+ final message = SuperTabMessage.fromJson(routeRow());+ await tester.pumpWidget(rowOf(message, controller));+ await tester.tap(find.text('Change'));+ await tester.pumpAndSettle();+ expect(find.text('Sonnet, fastest turnaround'), findsNothing);+ expect(find.text('Codex, cheapest'), findsOneWidget);+ f.app.superTabs.dispose();+ });++ testWidgets('Change says so when the decision cannot be loaded', (+ tester,+ ) async {+ final f = SuperTabLaunchFixture();+ final controller = await f.app.superTabs.open(tabId);+ await controller.refresh();+ final message = SuperTabMessage.fromJson(routeRow());+ await tester.pumpWidget(rowOf(message, controller));+ await tester.tap(find.text('Change'));+ await tester.pumpAndSettle();+ expect(find.textContaining('Could not load this decision'), findsOneWidget);+ expect(find.byType(RadioListTile<String>), findsNothing);+ f.app.superTabs.dispose();+ });++ testWidgets(+ 'Change while another action is pending is not reported as a refusal',+ (tester) async {+ final f = SuperTabLaunchFixture();+ f.connection.server.routeDecisions['d1'] = decision();+ final controller = await f.app.superTabs.open(tabId);+ await controller.refresh();+ f.connection.server.loseReply = true;+ await controller.command({+ 'type': 'conversation.create',+ 'title': 'Other',+ 'brief': '',+ 'checks': <dynamic>[],+ });+ expect(controller.hasPendingAction, isTrue);+ final before = f.connection.server.posts.length;+ final message = SuperTabMessage.fromJson(routeRow());+ await tester.pumpWidget(rowOf(message, controller));+ await tester.tap(find.text('Change'));+ await tester.pumpAndSettle();+ await tester.tap(find.textContaining('New agent · Claude sonnet'));+ await tester.pumpAndSettle();+ await tester.enterText(find.byType(TextField), 'Because.');+ await tester.pump();+ await tester.tap(find.widgetWithText(FilledButton, 'Change'));+ await tester.pumpAndSettle();+ expect(find.text('Finish the pending action first.'), findsOneWidget);+ expect(find.textContaining('not confirmed'), findsNothing);+ expect(f.connection.server.posts.length, before);+ f.app.superTabs.dispose();+ },+ );+}diff --git a/desktop/test/support/super_tab_fixture.dart b/desktop/test/support/super_tab_fixture.dartindex 87cd674ee..cd3cc2911 100644--- a/desktop/test/support/super_tab_fixture.dart+++ b/desktop/test/support/super_tab_fixture.dart@@ -18,9 +18,15 @@ class ConversationServer {int revision = 0;bool loseReply = false, reject = false, failSave = false, failReads = false;Map<String, dynamic>? saved;+ // Makes every command answer with this refusal: {code, message}.+ Map<String, String>? refuse;final posts = <Map<String, dynamic>>[];final receipts = <String, Map<String, dynamic>>{};final messages = <Map<String, dynamic>>[];+ // Route decisions by id, answered by GET .../route-decisions/:id.+ final routeDecisions = <String, Map<String, dynamic>>{};+ // The effective routing policy answered by GET .../routing-policy.+ Map<String, dynamic>? routingPolicy;final state = <String, dynamic>{'version': 1,'id': 'tab',@@ -72,6 +78,13 @@ class ConversationServer {statusCode: 400,);}+ if (refuse case final refusal?) {+ throw SuperTabFailure(+ refusal['code']!,+ refusal['message']!,+ statusCode: 409,+ );+ }final operationId = body['operationId'] as String;if (receipts[operationId] case final receipt?) return receipt;final command = body['command'] as Map;@@ -101,6 +114,21 @@ class ConversationServer {}if (failReads) throw StateError('Offline');final uri = Uri.parse(path);+ if (uri.pathSegments.last == 'routing-policy') {+ final policy = routingPolicy;+ if (policy == null) {+ throw const SuperTabFailure('NOT_FOUND', 'No routing policy.');+ }+ return jsonDecode(jsonEncode(policy)) as Map<String, dynamic>;+ }+ if (uri.pathSegments.length > 2 &&+ uri.pathSegments[uri.pathSegments.length - 2] == 'route-decisions') {+ final decision = routeDecisions[uri.pathSegments.last];+ if (decision == null) {+ throw const SuperTabFailure('NOT_FOUND', 'No such decision.');+ }+ return jsonDecode(jsonEncode(decision)) as Map<String, dynamic>;+ }if (uri.pathSegments.last == 'messages') {final conversationId = uri.pathSegments[4];final after = int.tryParse(uri.queryParameters['after'] ?? '');diff --git a/docs/plans/2026-10-19-super-tab-routing-v1.md b/docs/plans/2026-10-19-super-tab-routing-v1.mdnew file mode 100644index 000000000..cf7d6556e--- /dev/null+++ b/docs/plans/2026-10-19-super-tab-routing-v1.md@@ -0,0 +1,2506 @@+# Super Tab Routing v1 Implementation Plan++> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.++**Goal:** Before a Super Tab Lead starts or assigns work, `harness super-tab route` filters what cannot run the task, lets Jev choose among the rest with full context, falls back to a fixed policy order, records the decision, and shows it in the conversation where a person can change it.++**Architecture:** The backend owns the routing policy (account default plus a per-tab override), the decision log (`SuperTabRouteDecision`) and the commands that link decisions to starts and assignments. The CLI owns candidate collection, the hard filter, the policy order and the Jev call, as a pure core (`cli/src/superTabs/route.ts`) driven by a thin orchestrator (`routeCommand.ts`) and two new Super Tab service actions. The Desktop renders route messages, the Change override and the policy forms.++**Tech Stack:** TypeScript (Fastify, Prisma on MongoDB, zod, vitest) in `backend/` and `cli/`; Flutter/Dart in `desktop/`.++**Spec:** `docs/superpowers/specs/2026-10-19-super-tab-routing-v1-design.md`++## Global Constraints++- Engines routed in v1: `claude` and `codex` only (the only engines with quota readings and model control).+- Quality is an integer 1–3; cost is an integer 1–100; `quotaReserve` is 0–90 (percent); `notes` at most 500 characters.+- Default `floor`: `{low: 1, medium: 2, high: 3}`; a `high` risk raises the floor by one, to at most 3.+- Default `quotaReserve`: `10`.+- Policy order (fixed, not configurable): meets floor → lowest cost → most quota left (tightest window) → earliest reset → member before new agent → stable by title.+- At most 12 candidates shown to Jev; exactly one candidate → no Jev call (`via: 'only'`).+- Jev pick accepted with `jevPick(answer, ids, true)` from `cli/src/lib/routeDecide.ts` (p ≥ 0.6, or a clear lead with ≥ 6 options); otherwise the policy order (`via: 'order'`).+- Jev timeout: 3 seconds (`AbortSignal.timeout(3000)`), no retry.+- Hosted Jev limits (`backend/src/routes/jevRoute.ts`): `state` is at most 4 string keys and 17,000 characters in total; each criterion at most 640 characters; instructions at most 1,500 characters.+- Text limits: Lead `why` ≤ 300, brief cut at 2000, `notes` ≤ 500, override `reason` ≤ 300.+- At most 30 `route.record` per tab per rolling hour (`RATE_LIMITED`, 429). One open decision per group (a newer one supersedes it). Decision records are pruned after 90 days.+- Jev never receives emails, tokens, credentials or transcripts.+- Visible copy in English, following `docs/naming-system.md` (**Super Tab**, **Lead**).+- Tests never call the real Jev or OpenRouter; tests never touch the developer's daemon (port 18473), `~/.harness`, `~/.claude`, `~/.codex` or the real tmux server.+- Ship as one change: backend → CLI → Desktop. No part merges on its own.+- Do not commit until the owner asks; each task's "Commit" step is a local commit only when the owner has authorized commits for this branch.++## Rulings made while planning (deviations from the spec text, to be folded back into the spec)++1. **Model selection for new agents.** `agent_create` accepts no model or effort. A start request gains optional `model` and `effort`; after the agent is created, `start.ts` applies them with `agent_update {agentId, selectedModel: encodeRuntimeProfile(...)}`. A policy row whose `model` and `effort` are both `default` launches the engine as configured and skips `agent_update`. The default catalog uses `default` for Codex because Codex model slugs come from each machine's `models_cache.json`.+2. **Outcomes.** `done`, `stopped` and `superseded` only. The spec's `reassigned` is dropped: an override is recorded in its own `override` field, and a re-route supersedes.+3. **Lead overrides post a message** (`source.kind: 'route-override'`), because route rows are immutable messages.+4. **Expanding a route row** reads `GET /api/super-tabs/:tabId/route-decisions/:decisionId`, besides the list endpoint the spec names.+5. **Account policy endpoint** is `/api/super-tabs/routing-policy` (GET and POST), not `/api/routing-policy`, so the Desktop and CLI reach it through the existing Super Tab backend passthrough (`cli/src/superTabs/service.ts` path regex) without a new daemon route.+6. **Candidates' quality for members** comes from the policy row matching engine + model + effort, then engine + model; a member matching no row is quality 1, cost 1 (conservative: it rarely meets a floor).++## Review Focus++1. A tab where every machine is offline or every engine is exhausted → `route` returns `NO_CANDIDATE` with one exclusion reason per candidate, never an empty success. (Task 6, test "returns NO_CANDIDATE with reasons".)+2. Jev answers with a probability map missing one option, or picks an id it was not shown → treated as unsure, policy order wins. (Task 5, test "broken Jev answers fall back to order".)+3. A person presses Change on an old decision after a newer route superseded it → refused with `ROUTE_CLOSED`, and the Desktop shows the error instead of silently doing nothing. (Task 3 test "override of a closed decision"; Task 8 test "Change shows the refusal".)+4. Codex `resetsAt` arrives as epoch seconds and Claude's as an ISO string → both order correctly by earliest reset. (Task 5, test "normalizes reset times".)+5. A Lead passes a `routeDecisionId` from another group to `work.assign` → refused, not silently linked. (Task 4, test "decision from another group".)++---++## File Structure++**Backend**+- Create `backend/src/superTabs/routingPolicy.ts` — policy zod schemas, built-in default, field-by-field merge with warnings.+- Create `backend/src/superTabs/routingPolicy.test.ts`.+- Create `backend/src/superTabs/routeRecord.ts` — route decision zod schemas and types shared by commands and store.+- Create `backend/src/superTabs/routeDecisions.ts` — transactional writes of decision effects, supersede, prune, outcomes, reads.+- Modify `backend/src/superTabs/model.ts` — `SuperTabState.routingPolicy?`, `MessageDraft.source?`, `CommandEffects.routeDecisions`, route types.+- Modify `backend/src/superTabs/commands.ts` — `tab.routingPolicy`, `route.record`, `route.override`; `routeDecisionId`/`overrideReason` on `work.assign` and `agent.start`; `model`/`effort` on start requests.+- Modify `backend/src/superTabs/commands.test.ts`.+- Modify `backend/src/superTabs/store.ts` — load decision context, write effects, message `source`, outcomes, account policy and effective policy reads.+- Modify `backend/src/routes/superTabs.ts` — four routes.+- Modify `backend/prisma/schema.prisma` — `RoutingPolicy`, `SuperTabRouteDecision`.+- Modify `backend/integration/superTabs.test.ts`.++**CLI**+- Create `cli/src/superTabs/route.ts` — pure routing core.+- Create `cli/src/superTabs/route.spec.ts`.+- Create `cli/src/superTabs/routeCommand.ts` — orchestrates context, probes, Jev, record.+- Create `cli/src/superTabs/routeCommand.spec.ts`.+- Create `cli/vitest.super-tabs.config.ts` and script `test:super-tabs` — 100% per file for the new files.+- Modify `cli/src/superTabs/service.ts` (+ spec) — actions `routeContext`, `routeJev`; HELP.+- Modify `cli/src/superTabs/command.ts` (+ spec) — `route GROUP JSON`.+- Modify `cli/src/superTabs/start.ts` (+ spec) — `routeDecisionId`/`overrideReason` passthrough; apply `model`/`effort`.+- Modify `cli/src/superTabs/host.ts` — delivery prompt names `route`.+- Create `cli/e2e/superTabRoute.e2e.ts`; modify `cli/e2e/harness/fakeBackend.ts` (`/api/route/jev`).++**Desktop**+- Create `desktop/lib/super_tabs/routing_policy.dart` — Dart policy model.+- Create `desktop/lib/super_tabs/routing_policy_form.dart` — shared form.+- Create `desktop/lib/super_tabs/route_row.dart` — route and override rows, Change dialog, expand.+- Create `desktop/lib/settings/sections/routing_section.dart`.+- Modify `desktop/lib/super_tabs/model.dart`, `view.dart`, `launch.dart`, `desktop/lib/settings/settings_section.dart`, `desktop/lib/settings/settings_body.dart`.+- Tests: `desktop/test/super_tab_route_test.dart`, `desktop/test/routing_policy_test.dart`, update `desktop/test/settings_section_test.dart`.++---++## Phase A — Backend++### Task 1: Routing policy core++**Files:**+- Create: `backend/src/superTabs/routingPolicy.ts`+- Test: `backend/src/superTabs/routingPolicy.test.ts`++**Interfaces:**+- Produces:+ - `routingPolicySchema` (zod), `routingOverrideSchema` (zod, partial, no `version`)+ - `type RoutingPolicy`, `type RoutingOverride`, `type RoutingModel`+ - `DEFAULT_ROUTING_POLICY: RoutingPolicy`+ - `effectivePolicy(account: unknown, override: unknown): { policy: RoutingPolicy; warnings: string[]; overridden: Array<keyof RoutingOverride> }`++- [ ] **Step 1: Write the failing test**++```ts+// backend/src/superTabs/routingPolicy.test.ts+import { describe, expect, it } from 'vitest'+import { DEFAULT_ROUTING_POLICY, effectivePolicy, routingOverrideSchema, routingPolicySchema } from './routingPolicy.js'++describe('routing policy', () => {+ it('ships a valid default that needs no setup', () => {+ expect(routingPolicySchema.parse(DEFAULT_ROUTING_POLICY)).toEqual(DEFAULT_ROUTING_POLICY)+ expect(DEFAULT_ROUTING_POLICY.floor).toEqual({ low: 1, medium: 2, high: 3 })+ expect(DEFAULT_ROUTING_POLICY.quotaReserve).toBe(10)+ expect(DEFAULT_ROUTING_POLICY.notes).toBe('')+ expect(new Set(DEFAULT_ROUTING_POLICY.models.map(m => m.engine))).toEqual(new Set(['claude', 'codex']))+ })++ it('uses the default when the account has none, and merges a tab override field by field', () => {+ expect(effectivePolicy(null, null)).toEqual({ policy: DEFAULT_ROUTING_POLICY, warnings: [], overridden: [] })+ const account = { ...DEFAULT_ROUTING_POLICY, quotaReserve: 20, notes: 'Frontend prefers Claude.' }+ const result = effectivePolicy(account, { notes: 'Long jobs on remote-1.' })+ expect(result.policy.quotaReserve).toBe(20)+ expect(result.policy.notes).toBe('Long jobs on remote-1.')+ expect(result.overridden).toEqual(['notes'])+ expect(result.warnings).toEqual([])+ })++ it('falls back to the default with a warning for a corrupt account policy or override', () => {+ const corrupt = effectivePolicy({ version: 9 }, { floor: { low: 7 } })+ expect(corrupt.policy).toEqual(DEFAULT_ROUTING_POLICY)+ expect(corrupt.warnings).toEqual([+ 'The account routing policy is unreadable; the built-in default applies.',+ 'This Super Tab routing override is unreadable and was ignored.',+ ])+ })++ it('rejects out-of-range values and unknown engines', () => {+ const bad = (patch: Record<string, unknown>) => routingPolicySchema.safeParse({ ...DEFAULT_ROUTING_POLICY, ...patch }).success+ expect(bad({ quotaReserve: 91 })).toBe(false)+ expect(bad({ notes: 'x'.repeat(501) })).toBe(false)+ expect(bad({ floor: { low: 0, medium: 2, high: 3 } })).toBe(false)+ expect(bad({ models: [{ ...DEFAULT_ROUTING_POLICY.models[0], engine: 'cursor' }] })).toBe(false)+ expect(bad({ models: [{ ...DEFAULT_ROUTING_POLICY.models[0], cost: 0 }] })).toBe(false)+ expect(bad({ models: [] })).toBe(false)+ expect(routingOverrideSchema.safeParse({ version: 1 }).success).toBe(false)+ })+})+```++- [ ] **Step 2: Run test to verify it fails**++Run: `cd backend && npx vitest run src/superTabs/routingPolicy.test.ts`+Expected: FAIL with "Failed to load url ./routingPolicy.js" (module missing).++- [ ] **Step 3: Write minimal implementation**++```ts+// backend/src/superTabs/routingPolicy.ts+/** Super Tab routing policy (docs/superpowers/specs/2026-10-19-super-tab-routing-v1-design.md).+ * The account default applies to every tab its owner creates; a tab owner may override single fields.+ * Every field has a built-in default so routing works before anyone opens the form. */+import { z } from 'zod'++const quality = z.number().int().min(1).max(3)+const modelRow = z.object({+ engine: z.enum(['claude', 'codex']),+ // `default` keeps the engine's own configured model or effort; no runtime switch is made.+ model: z.string().trim().min(1).max(200),+ effort: z.string().trim().min(1).max(80),+ quality,+ cost: z.number().int().min(1).max(100),+ enabled: z.boolean(),+}).strict()+const fields = {+ models: z.array(modelRow).min(1).max(40),+ floor: z.object({ low: quality, medium: quality, high: quality }).strict(),+ quotaReserve: z.number().int().min(0).max(90),+ notes: z.string().trim().max(500),+}+export const routingPolicySchema = z.object({ version: z.literal(1), ...fields }).strict()+export const routingOverrideSchema = z.object(fields).partial().strict()+export type RoutingPolicy = z.infer<typeof routingPolicySchema>+export type RoutingOverride = z.infer<typeof routingOverrideSchema>+export type RoutingModel = RoutingPolicy['models'][number]++export const DEFAULT_ROUTING_POLICY: RoutingPolicy = {+ version: 1,+ 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,+ notes: '',+}++export function effectivePolicy(account: unknown, override: unknown) {+ const warnings: string[] = []+ let policy = DEFAULT_ROUTING_POLICY+ if (account !== null && account !== undefined) {+ const parsed = routingPolicySchema.safeParse(account)+ if (parsed.success) policy = parsed.data+ else warnings.push('The account routing policy is unreadable; the built-in default applies.')+ }+ const overridden: Array<keyof RoutingOverride> = []+ if (override !== null && override !== undefined) {+ const parsed = routingOverrideSchema.safeParse(override)+ if (!parsed.success) warnings.push('This Super Tab routing override is unreadable and was ignored.')+ else {+ policy = { ...policy, ...parsed.data }+ overridden.push(...(Object.keys(parsed.data) as Array<keyof RoutingOverride>))+ }+ }+ return { policy, warnings, overridden }+}+```++- [ ] **Step 4: Run test to verify it passes**++Run: `cd backend && npx vitest run src/superTabs/routingPolicy.test.ts`+Expected: PASS (4 tests).++- [ ] **Step 5: Commit**++```bash+git add backend/src/superTabs/routingPolicy.ts backend/src/superTabs/routingPolicy.test.ts+git commit -m "Super Tab routing: policy schema, default and merge"+```++---++### Task 2: Account policy storage, tab override and effective-policy routes++**Files:**+- Modify: `backend/prisma/schema.prisma` (after `model SuperTabRun`)+- Modify: `backend/src/superTabs/model.ts` (`SuperTabState`)+- Modify: `backend/src/superTabs/commands.ts` (schema + switch)+- Modify: `backend/src/superTabs/store.ts` (new methods)+- Modify: `backend/src/routes/superTabs.ts`+- Test: `backend/src/superTabs/commands.test.ts`, `backend/integration/superTabs.test.ts`++**Interfaces:**+- Consumes: `routingPolicySchema`, `routingOverrideSchema`, `effectivePolicy`, `DEFAULT_ROUTING_POLICY` (Task 1).+- Produces:+ - Command `{ type: 'tab.routingPolicy', policy: RoutingOverride | null }` (owner only).+ - `SuperTabStore.accountPolicy(user): Promise<{ policy: RoutingPolicy; revision: number; isDefault: boolean }>`+ - `SuperTabStore.saveAccountPolicy(user, revision: number, policy: RoutingPolicy): Promise<{ policy; revision; isDefault: false }>`+ - `SuperTabStore.tabPolicy(user, tabId, asAgentId?): Promise<{ policy: RoutingPolicy; warnings: string[]; overridden: string[]; override: RoutingOverride | null }>`+ - Routes: `GET /api/super-tabs/routing-policy`, `POST /api/super-tabs/routing-policy` body `{ revision, policy }`, `GET /api/super-tabs/:tabId/routing-policy?asAgentId=`.++- [ ] **Step 1: Write the failing unit test** (append to `backend/src/superTabs/commands.test.ts`, using its existing `fixture()` helper and its `run(command, actor, context)`)++```ts+describe('tab.routingPolicy', () => {+ it('lets only the owner set or clear the tab override', () => {+ const f = fixture()+ f.run({ type: 'tab.routingPolicy', policy: { quotaReserve: 25 } })+ expect(f.state.routingPolicy).toEqual({ quotaReserve: 25 })+ f.invite('collaborator')+ expect(() => f.run({ type: 'tab.routingPolicy', policy: { notes: 'x' } }, f.collaborator)).toThrow('Only the Super Tab owner')+ f.run({ type: 'tab.routingPolicy', policy: null })+ expect(f.state.routingPolicy).toBeUndefined()+ })+ it('refuses an invalid override', () => {+ const f = fixture()+ expect(() => f.run({ type: 'tab.routingPolicy', policy: { quotaReserve: 99 } } as never)).toThrow()+ })+})+```++If `fixture()` in `commands.test.ts` names its state, owner or collaborator differently, use its names; the assertions stay the same.++- [ ] **Step 2: Run test to verify it fails**++Run: `cd backend && npx vitest run src/superTabs/commands.test.ts -t "tab.routingPolicy"`+Expected: FAIL (zod: invalid discriminator `tab.routingPolicy`).++- [ ] **Step 3: Implement the command**++In `backend/src/superTabs/model.ts`, add to `SuperTabState`:++```ts+ /** Fields this tab overrides from its owner's account routing policy (routingPolicy.ts). */+ routingPolicy?: import('./routingPolicy.js').RoutingOverride+```++In `backend/src/superTabs/commands.ts`, import and add to `commandSchema`:++```ts+import { routingOverrideSchema } from './routingPolicy.js'+// ...+ z.object({ type: z.literal('tab.routingPolicy'), policy: routingOverrideSchema.nullable() }).strict(),+```++and to the `switch` in `applyCommand`:++```ts+ case 'tab.routingPolicy':+ if (actor.kind !== 'person' || actor.userId !== state.ownerId) fail('OWNER_REQUIRED', 'Only the Super Tab owner can change its routing policy.', 403)+ if (command.policy && Object.keys(command.policy).length) state.routingPolicy = command.policy+ else delete state.routingPolicy+ break+```++- [ ] **Step 4: Run the unit test**++Run: `cd backend && npx vitest run src/superTabs/commands.test.ts -t "tab.routingPolicy"`+Expected: PASS.++- [ ] **Step 5: Add the Prisma model**++```prisma+// One routing policy document per account and environment (superTabs/routingPolicy.ts).+model RoutingPolicy {+ id String @id @map("_id")+ userId String+ autonomousEnv String+ revision Int @default(0)+ policy Json+ updatedAt DateTime @updatedAt++ @@unique([userId, autonomousEnv])+}+```++Run: `cd backend && npx prisma generate`+Expected: "Generated Prisma Client".++- [ ] **Step 6: Write the failing integration test** (append inside the existing `describe` of `backend/integration/superTabs.test.ts`)++```ts+ it('stores the account routing policy with revisions and merges the owner policy into each tab', async () => {+ const initial = await store.accountPolicy(owner)+ expect(initial).toEqual({ policy: DEFAULT_ROUTING_POLICY, revision: 0, isDefault: true })+ const saved = await store.saveAccountPolicy(owner, 0, { ...DEFAULT_ROUTING_POLICY, quotaReserve: 30 })+ expect(saved.revision).toBe(1)+ await expect(store.saveAccountPolicy(owner, 0, DEFAULT_ROUTING_POLICY)).rejects.toMatchObject({ code: 'REVISION_CHANGED' })+ const { tab, lead } = await fixture()+ await run(tab, { type: 'tab.routingPolicy', policy: { notes: 'Prefer remote-1.' } })+ await invite(tab, 'viewer')+ // A member reads the owner's policy, never their own account's.+ await store.saveAccountPolicy(peer, 0, { ...DEFAULT_ROUTING_POLICY, quotaReserve: 5 })+ for (const [user, asAgent] of [[owner, undefined], [peer, undefined], [host, lead]] as const) {+ const effective = await store.tabPolicy(user, tab, asAgent)+ expect(effective.policy.quotaReserve).toBe(30)+ expect(effective.policy.notes).toBe('Prefer remote-1.')+ expect(effective.overridden).toEqual(['notes'])+ }+ })+```++Add `import { DEFAULT_ROUTING_POLICY } from '../src/superTabs/routingPolicy.js'` at the top.++- [ ] **Step 7: Run it to verify it fails**++Run: `cd backend && npm run test:super-tabs -- -t "account routing policy"`+Expected: FAIL (`store.accountPolicy is not a function`).++- [ ] **Step 8: Implement the store methods** (in `SuperTabStore`, `backend/src/superTabs/store.ts`)++```ts+import { DEFAULT_ROUTING_POLICY, effectivePolicy, routingPolicySchema, type RoutingPolicy } from './routingPolicy.js'+// ...+ private policyId(user: AuthUser) { return stableId('routing-policy', user.sub, user.autonomousEnv) }++ async accountPolicy(user: AuthUser) {+ const row = await this.db.routingPolicy.findUnique({ where: { id: this.policyId(user) } })+ if (!row) return { policy: DEFAULT_ROUTING_POLICY, revision: 0, isDefault: true }+ const { policy } = effectivePolicy(row.policy, null)+ return { policy, revision: row.revision, isDefault: false }+ }++ async saveAccountPolicy(user: AuthUser, revision: number, input: RoutingPolicy) {+ const policy = routingPolicySchema.parse(input)+ return transaction(this.db, async tx => {+ const id = this.policyId(user)+ const row = await tx.routingPolicy.findUnique({ where: { id } })+ if ((row?.revision ?? 0) !== revision) fail('REVISION_CHANGED', 'The routing policy changed elsewhere. Reload it and try again.')+ const next = revision + 1+ if (row) await tx.routingPolicy.update({ where: { id, revision }, data: { revision: next, policy: json(policy) } })+ else await tx.routingPolicy.create({ data: { id, userId: user.sub, autonomousEnv: user.autonomousEnv, revision: next, policy: json(policy) } })+ return { policy, revision: next, isDefault: false as const }+ })+ }++ async tabPolicy(user: AuthUser, tabId: string, asAgentId?: string) {+ return transaction(this.db, async tx => {+ const row = await this.row(tx, user, tabId)+ const state = stateOf(row)+ author(state, await this.actor(tx, user, state, asAgentId))+ const account = await tx.routingPolicy.findUnique({ where: { id: stableId('routing-policy', state.ownerId, state.environment) } })+ return { ...effectivePolicy(account?.policy ?? null, state.routingPolicy ?? null), override: state.routingPolicy ?? null }+ })+ }+```++`author`, `stableId` and `fail` are already imported in `store.ts` from `./model.js`; add any that are not.++- [ ] **Step 9: Add the routes** (in `superTabRoutes`, `backend/src/routes/superTabs.ts`, before the `'/api/super-tabs/:tabId'` GET)++```ts+import { routingPolicySchema } from '../superTabs/routingPolicy.js'+// ...+const savePolicy = z.object({ revision: z.number().int().nonnegative().safe(), policy: routingPolicySchema }).strict()+// ...+ app.get('/api/super-tabs/routing-policy', (req, reply) => respond(reply, () => store.accountPolicy(req.user!)))+ app.post<{ Body: z.infer<typeof savePolicy> }>('/api/super-tabs/routing-policy', { preHandler: validateBody(savePolicy) },+ (req, reply) => respond(reply, () => store.saveAccountPolicy(req.user!, req.body.revision, req.body.policy)))+ app.get<{ Params: z.infer<typeof tabParams>; Querystring: z.infer<typeof agentQuery> }>('/api/super-tabs/:tabId/routing-policy',+ { preHandler: [validateParams(tabParams), validateQuery(agentQuery)] },+ (req, reply) => respond(reply, () => store.tabPolicy(req.user!, req.params.tabId, req.query.asAgentId)))+```++- [ ] **Step 10: Run the backend checks**++Run: `cd backend && npx tsc --noEmit -p . && npx vitest run src/superTabs && npm run test:super-tabs`+Expected: all PASS (the existing 21 integration tests plus the new one).++- [ ] **Step 11: Commit**++```bash+git add backend/prisma/schema.prisma backend/src/superTabs backend/src/routes/superTabs.ts backend/integration/superTabs.test.ts+git commit -m "Super Tab routing: account policy, tab override and effective policy"+```++---++### Task 3: Decision log, route messages and person override++**Files:**+- Create: `backend/src/superTabs/routeRecord.ts`+- Create: `backend/src/superTabs/routeDecisions.ts`+- Modify: `backend/prisma/schema.prisma`, `backend/src/superTabs/model.ts`, `backend/src/superTabs/commands.ts`, `backend/src/superTabs/store.ts`, `backend/src/routes/superTabs.ts`+- Test: `backend/src/superTabs/commands.test.ts`, `backend/integration/superTabs.test.ts`++**Interfaces:**+- Produces:+ - `routeRecordSchema` (zod) and types `RouteCandidate`, `RouteRecord`, `RouteFinal`, `RouteOverride`, `RouteDecision`, `RouteDecisionEffect` (in `routeRecord.ts`).+ - Commands `{ type: 'route.record', conversationId, decision: RouteRecord }` → `result.routeDecisionId`; `{ type: 'route.override', decisionId, candidateId, reason }`.+ - `MessageDraft.source?: Record<string, unknown>`; route messages carry `source.kind === 'route'` or `'route-override'`.+ - `CommandContext.recentRoutes?: number`, `CommandContext.routeDecision?: RouteDecision`.+ - `CommandEffects.routeDecisions: RouteDecisionEffect[]`.+ - Store: `routeDecisions(user, tabId)` (newest 100) and `routeDecision(user, tabId, decisionId)`; routes `GET /api/super-tabs/:tabId/route-decisions` and `GET /api/super-tabs/:tabId/route-decisions/:decisionId`.++- [ ] **Step 1: Write `routeRecord.ts`** (types and schema only; exercised by the tests in the next steps)++```ts+// backend/src/superTabs/routeRecord.ts+/** What `harness super-tab route` records (docs/superpowers/specs/2026-10-19-super-tab-routing-v1-design.md). */+import { z } from 'zod'++const level = z.enum(['low', 'medium', 'high'])+const candidateId = z.string().regex(/^c\d{1,2}$/)+const machine = z.string().min(1).max(160).regex(/^[A-Za-z0-9_-]+$/)+export const routeCandidateSchema = z.object({+ id: candidateId,+ kind: z.enum(['member', 'new']),+ agentId: machine.optional(),+ machineId: machine,+ engine: z.enum(['claude', 'codex']),+ model: z.string().min(1).max(200),+ effort: z.string().min(1).max(80),+ quality: z.number().int().min(1).max(3),+ cost: z.number().int().min(1).max(100),+ /** Short, for the conversation row: "Multiply · Claude opus high · remote-1". */+ title: z.string().trim().min(1).max(160),+ /** The criterion line Jev was shown. */+ label: z.string().trim().min(1).max(640),+}).strict().refine(c => (c.kind === 'member') === !!c.agentId, 'Members name their agent; new agents do not.')+export const routeRecordSchema = z.object({+ assessment: z.object({ difficulty: level, risk: level, why: z.string().trim().min(1).max(300) }).strict(),+ candidates: z.array(routeCandidateSchema).min(1).max(12),+ excluded: z.array(z.object({ title: z.string().trim().min(1).max(160), reason: z.string().trim().min(1).max(500) }).strict()).max(200),+ floor: z.number().int().min(1).max(3),+ notes: z.boolean(),+ pick: candidateId,+ via: z.enum(['jev', 'order', 'only']),+ p: z.number().min(0).max(1).nullable(),+ belowFloor: z.boolean(),+ why: z.string().trim().min(1).max(300),+}).strict().refine(d => d.candidates.some(c => c.id === d.pick), 'The pick must be one of the candidates.')+ .refine(d => new Set(d.candidates.map(c => c.id)).size === d.candidates.length, 'Candidate ids must be unique.')++export type RouteCandidate = z.infer<typeof routeCandidateSchema>+export type RouteRecord = z.infer<typeof routeRecordSchema>+export type RouteFinal =+ | { kind: 'member'; agentId: string; machineId: string }+ | { kind: 'new'; startId: string; machineId: string; engine: string; model: string; effort: string }+export interface RouteOverride { by: 'lead' | 'person'; actorKey: string; candidateId?: string; reason: string }+export interface RouteDecision {+ id: string; conversationId: string; record: RouteRecord+ final: RouteFinal | null; override: RouteOverride | null; assignmentId: string | null; outcome: string | null+}+export type RouteDecisionEffect =+ | { op: 'create'; id: string; conversationId: string; record: RouteRecord }+ | { op: 'override'; id: string; override: RouteOverride }+ | { op: 'final'; id: string; final: RouteFinal; override?: RouteOverride; assignmentId?: string }+export const routeTitle = (decision: RouteDecision, candidateId: string): string =>+ decision.record.candidates.find(c => c.id === candidateId)?.title ?? 'another candidate'+```++- [ ] **Step 2: Write the failing unit tests** (append to `backend/src/superTabs/commands.test.ts`; `lead` is the lead agent from the fixture and `leadActor` its `{kind:'agent', agentId, machineOwnerId:'host-owner'}` actor — use the fixture's real names)++```ts+const candidate = (id: string, patch: Record<string, unknown> = {}) => ({ id, kind: 'new', machineId: 'machine', engine: 'claude',+ model: 'opus', effort: 'high', quality: 3, cost: 3, title: `Title ${id}`, label: `Label ${id}`, ...patch })+const record = (patch: Record<string, unknown> = {}) => ({ assessment: { difficulty: 'high', risk: 'low', why: 'Schema change.' },+ candidates: [candidate('c0'), candidate('c1', { model: 'sonnet', quality: 2, cost: 2 })], excluded: [], floor: 3, notes: false,+ pick: 'c0', via: 'jev', p: 0.82, belowFloor: false, why: 'Highest quality within quota.', ...patch })++describe('route.record and route.override', () => {+ it('records a lead decision as a route message with its id', () => {+ const f = fixture()+ const effects = f.run({ type: 'route.record', conversationId: 'lead', decision: record() }, f.leadActor, { recentRoutes: 0 })+ expect(effects.result.routeDecisionId).toBeTruthy()+ expect(effects.routeDecisions).toEqual([{ op: 'create', id: effects.result.routeDecisionId, conversationId: 'lead', record: expect.objectContaining({ pick: 'c0' }) }])+ expect(effects.messages[0]).toMatchObject({ text: 'Routed to Title c0 — Jev 82% · "Highest quality within quota."',+ source: { kind: 'route', decisionId: effects.result.routeDecisionId, via: 'jev', p: 0.82, belowFloor: false,+ pick: { id: 'c0', title: 'Title c0' }, alternatives: [{ id: 'c1', title: 'Title c1' }] } })+ })+ it('refuses a pick outside the candidates, a non-lead agent and a busy hour', () => {+ const f = fixture()+ expect(() => f.run({ type: 'route.record', conversationId: 'lead', decision: record({ pick: 'c5' }) }, f.leadActor, { recentRoutes: 0 })).toThrow()+ expect(() => f.run({ type: 'route.record', conversationId: 'lead', decision: record() }, f.workerActor, { recentRoutes: 0 })).toThrow('coordinating lead')+ expect(() => f.run({ type: 'route.record', conversationId: 'lead', decision: record() }, f.leadActor, { recentRoutes: 30 })).toThrow('30 tasks')+ })+ it('lets a writer change an open decision with a reason and tells the lead', () => {+ const f = fixture()+ const decision = { id: 'd1', conversationId: 'lead', record: record(), final: null, override: null, assignmentId: null, outcome: null }+ const effects = f.run({ type: 'route.override', decisionId: 'd1', candidateId: 'c1', reason: 'Opus quota is needed elsewhere.' }, undefined, { routeDecision: decision })+ expect(effects.routeDecisions).toEqual([{ op: 'override', id: 'd1', override: expect.objectContaining({ by: 'person', candidateId: 'c1', reason: 'Opus quota is needed elsewhere.' }) }])+ expect(effects.messages[0].recipients).toEqual([f.lead])+ expect(effects.messages[0].text).toContain('chose Title c1 instead of Title c0. Hand this task over to it. Reason: Opus quota is needed elsewhere.')+ expect(effects.messages[0].source).toEqual({ kind: 'route-override', decisionId: 'd1', by: 'person' })+ })+ it('refuses an override by an agent, of a closed decision, or of the current choice', () => {+ const f = fixture()+ const open = { id: 'd1', conversationId: 'lead', record: record(), final: null, override: null, assignmentId: null, outcome: null }+ const command = { type: 'route.override', decisionId: 'd1', candidateId: 'c1', reason: 'Because.' } as const+ expect(() => f.run(command, f.leadActor, { routeDecision: open })).toThrow('A person')+ expect(() => f.run(command, undefined, { routeDecision: { ...open, outcome: 'superseded' } })).toThrow('no longer open')+ expect(() => f.run({ ...command, candidateId: 'c0' }, undefined, { routeDecision: open })).toThrow('already')+ })+})+```++`f.run(command, actor = owner, context = {})` must return the `CommandEffects`; if the fixture's `run` returns only the state, extend it to return the effects (keep existing callers working). If the fixture has no worker agent, add one with its existing `add(...)` helper as `f.workerActor`.++- [ ] **Step 3: Run tests to verify they fail**++Run: `cd backend && npx vitest run src/superTabs/commands.test.ts -t "route.record"`+Expected: FAIL (unknown command type).++- [ ] **Step 4: Implement model and command changes**++`backend/src/superTabs/model.ts`:++```ts+import type { RouteDecision, RouteDecisionEffect } from './routeRecord.js'+// MessageDraft gains:+ /** Structured row kind for clients; `native` is written by native.ts, `route`/`route-override` by commands. */+ source?: Record<string, unknown>+// CommandEffects gains:+ routeDecisions: RouteDecisionEffect[]+```++`backend/src/superTabs/commands.ts`:++```ts+import { routeRecordSchema, routeTitle, type RouteDecision } from './routeRecord.js'+const reason = z.string().trim().min(1).max(300)+// commandSchema additions:+ 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(),+// CommandContext additions:+ /** Route decisions this tab recorded in the last hour, counted by the store. */+ recentRoutes?: number+ /** The decision a command names, read from SuperTabRouteDecision by the store. */+ routeDecision?: RouteDecision+```++In `applyCommand`, initialise `routeDecisions: []` in `effects`, extend `message()` with an optional `source`:++```ts+ const message = (conversationId: string, body: string, recipients: string[] = [], replyTo: string | null = null, source?: Record<string, unknown>) => {+ effects.messages.push({ id: operationId, conversationId, author: sender, text: body, replyTo, recipients, ...(source ? { source } : {}) })+ result.messageId = operationId+ }+ const openDecision = (): RouteDecision => {+ const decision = context.routeDecision ?? fail('NOT_FOUND', 'This routing decision is unavailable.', 404)+ if (decision.outcome) fail('ROUTE_CLOSED', 'This routing decision is no longer open. Route the task again.')+ return decision+ }+```++and the cases:++```ts+ case 'route.record': {+ controls(state, actor, command.conversationId)+ open(state, command.conversationId)+ if ((context.recentRoutes ?? 0) >= 30) fail('RATE_LIMITED', 'This Super Tab routed 30 tasks in the last hour. Wait before routing again.', 429)+ const decision = command.decision+ const pick = decision.candidates.find(c => c.id === decision.pick)!+ const via = decision.via === 'jev' ? `Jev ${Math.round((decision.p ?? 0) * 100)}%`+ : decision.via === 'only' ? 'only candidate' : 'by policy order'+ effects.routeDecisions.push({ op: 'create', id: operationId, conversationId: command.conversationId, record: decision })+ result.routeDecisionId = operationId+ message(command.conversationId, `Routed to ${pick.title} — ${via} · "${decision.why}"`, [], null, {+ kind: 'route', decisionId: operationId, via: decision.via, p: decision.p, belowFloor: decision.belowFloor, why: decision.why,+ pick: { id: pick.id, title: pick.title },+ alternatives: decision.candidates.filter(c => c.id !== pick.id).map(c => ({ id: c.id, title: c.title })),+ })+ break+ }+ case 'route.override': {+ if (actor.kind !== 'person') fail('HUMAN_REQUIRED', 'A person changes a routing decision; the lead overrides when it starts or assigns.', 403)+ const decision = openDecision()+ controls(state, actor, decision.conversationId)+ open(state, decision.conversationId)+ const current = decision.override?.candidateId ?? decision.record.pick+ const chosen = decision.record.candidates.find(c => c.id === command.candidateId) ?? fail('NOT_FOUND', 'Choose one of this decision’s candidates.', 404)+ if (chosen.id === current) fail('ALREADY_CHOSEN', 'That candidate is already the choice.')+ if (chosen.kind === 'member' && !state.agents.some(a => a.id === chosen.agentId)) fail('CANDIDATE_UNAVAILABLE', 'That agent left this Super Tab. Choose another.')+ effects.routeDecisions.push({ op: 'override', id: decision.id, override: { by: 'person', actorKey: actorKey(actor), candidateId: chosen.id, reason: command.reason } })+ const lead = conversation(state, decision.conversationId).leadId+ message(decision.conversationId,+ `${sender.name} chose ${chosen.title} instead of ${routeTitle(decision, current)}. Hand this task over to it. Reason: ${command.reason}`,+ lead ? [lead] : [], null, { kind: 'route-override', decisionId: decision.id, by: 'person' })+ break+ }+```++`sender` is the existing `author(state, actor, ...)` result; for a person it carries `name`. If `Author` has no `name` for people, use `actor.email`.++- [ ] **Step 5: Run unit tests**++Run: `cd backend && npx vitest run src/superTabs/commands.test.ts`+Expected: PASS (all, including existing tests).++- [ ] **Step 6: Add the Prisma model and the transactional effects**++```prisma+// One `harness super-tab route` decision (superTabs/routeRecord.ts). Pruned after 90 days on write.+model SuperTabRouteDecision {+ id String @id @map("_id")+ tabId String+ conversationId String+ record Json+ final Json?+ override Json?+ assignmentId String?+ outcome String?+ outcomeAt DateTime?+ createdAt DateTime @default(now())++ @@index([tabId, createdAt])+ @@index([tabId, conversationId, outcome])+ @@index([tabId, assignmentId])+}+```++Run: `cd backend && npx prisma generate`.++```ts+// backend/src/superTabs/routeDecisions.ts+/** Persistence for route decisions. Called inside SuperTabStore's transactions. */+import type { Prisma, SuperTabRouteDecision } from '@prisma/client'+import type { RouteDecision, RouteDecisionEffect, RouteFinal, RouteOverride, RouteRecord } from './routeRecord.js'++type Tx = Prisma.TransactionClient+const json = (value: unknown): Prisma.InputJsonValue => JSON.parse(JSON.stringify(value)) as Prisma.InputJsonValue+export const RETENTION_MS = 90 * 24 * 60 * 60_000++export const decisionOf = (row: SuperTabRouteDecision): RouteDecision => ({+ id: row.id, conversationId: row.conversationId, record: row.record as unknown as RouteRecord,+ final: (row.final ?? null) as unknown as RouteFinal | null, override: (row.override ?? null) as unknown as RouteOverride | null,+ assignmentId: row.assignmentId, outcome: row.outcome,+})++export async function recentRoutes(tx: Tx, tabId: string, now: number): Promise<number> {+ return tx.superTabRouteDecision.count({ where: { tabId, createdAt: { gte: new Date(now - 60 * 60_000) } } })+}++export async function readDecision(tx: Tx, tabId: string, id: string): Promise<RouteDecision | undefined> {+ const row = await tx.superTabRouteDecision.findFirst({ where: { id, tabId } })+ return row ? decisionOf(row) : undefined+}++export async function writeRouteEffects(tx: Tx, tabId: string, effects: RouteDecisionEffect[], now: number): Promise<void> {+ for (const effect of effects) {+ if (effect.op === 'create') {+ // One open decision per group: a newer route supersedes the open one.+ await tx.superTabRouteDecision.updateMany({ where: { tabId, conversationId: effect.conversationId, outcome: null },+ data: { outcome: 'superseded', outcomeAt: new Date(now) } })+ await tx.superTabRouteDecision.create({ data: { id: effect.id, tabId, conversationId: effect.conversationId,+ record: json(effect.record), createdAt: new Date(now) } })+ await tx.superTabRouteDecision.deleteMany({ where: { tabId, createdAt: { lt: new Date(now - RETENTION_MS) } } })+ } else if (effect.op === 'override') {+ await tx.superTabRouteDecision.update({ where: { id: effect.id }, data: { override: json(effect.override) } })+ } else {+ await tx.superTabRouteDecision.update({ where: { id: effect.id }, data: {+ final: json(effect.final), ...(effect.override ? { override: json(effect.override) } : {}),+ ...(effect.assignmentId ? { assignmentId: effect.assignmentId } : {}),+ } })+ }+ }+}++export async function closeAssignment(tx: Tx, tabId: string, assignmentId: string, outcome: 'done' | 'stopped', now: number): Promise<void> {+ await tx.superTabRouteDecision.updateMany({ where: { tabId, assignmentId, outcome: null }, data: { outcome, outcomeAt: new Date(now) } })+}+```++In `store.execute` (`backend/src/superTabs/store.ts`), before `applyCommand`:++```ts+ if (command.type === 'route.record') context.recentRoutes = await recentRoutes(tx, tabId, context.now)+ const decisionId = command.type === 'route.override' ? command.decisionId+ : command.type === 'work.assign' || command.type === 'agent.start' ? command.routeDecisionId : undefined+ if (decisionId) context.routeDecision = await readDecision(tx, tabId, decisionId) ?? fail('NOT_FOUND', 'This routing decision is unavailable.', 404)+```++(`command.routeDecisionId` on `work.assign`/`agent.start` is added in Task 4; until then guard it with `'routeDecisionId' in command ? command.routeDecisionId : undefined` and simplify in Task 4.)++After the `superTab.update(...)` call:++```ts+ await writeRouteEffects(tx, tabId, effects.routeDecisions, context.now)+ if (command.type === 'work.status' && (command.status === 'done' || command.status === 'stopped')) {+ await closeAssignment(tx, tabId, command.assignmentId, command.status, context.now)+ }+```++and write `source` with each message:++```ts+ await tx.superTabMessage.create({ data: { id: message.id, tabId, conversationId: message.conversationId,+ sequence: revision, author: json(message.author), ...(message.source ? { source: json(message.source) } : {}),+ text: message.text, replyTo: message.replyTo, recipientIds: message.recipients } })+```++Add the reads:++```ts+ async routeDecisions(user: AuthUser, tabId: string) {+ return transaction(this.db, async tx => {+ const state = stateOf(await this.row(tx, user, tabId))+ author(state, await this.actor(tx, user, state))+ const rows = await tx.superTabRouteDecision.findMany({ where: { tabId }, orderBy: { createdAt: 'desc' }, take: 100 })+ return rows.map(row => ({ ...decisionOf(row), createdAt: row.createdAt, outcomeAt: row.outcomeAt }))+ })+ }+ async routeDecision(user: AuthUser, tabId: string, decisionId: string) {+ return transaction(this.db, async tx => {+ const state = stateOf(await this.row(tx, user, tabId))+ author(state, await this.actor(tx, user, state))+ return await readDecision(tx, tabId, decisionId) ?? fail('NOT_FOUND', 'This routing decision is unavailable.', 404)+ })+ }+```++Routes (`backend/src/routes/superTabs.ts`):++```ts+const decisionParams = tabParams.extend({ decisionId: id })+ app.get<{ Params: z.infer<typeof tabParams> }>('/api/super-tabs/:tabId/route-decisions', { preHandler: validateParams(tabParams) },+ (req, reply) => respond(reply, () => store.routeDecisions(req.user!, req.params.tabId)))+ app.get<{ Params: z.infer<typeof decisionParams> }>('/api/super-tabs/:tabId/route-decisions/:decisionId', { preHandler: validateParams(decisionParams) },+ (req, reply) => respond(reply, () => store.routeDecision(req.user!, req.params.tabId, req.params.decisionId)))+```++- [ ] **Step 7: Write the failing integration test**++```ts+ it('records, supersedes and lets a person change a route decision; a closed one refuses', async () => {+ const { tab, lead } = await fixture()+ const decision = { assessment: { difficulty: 'medium', risk: 'low', why: 'A small API change.' },+ candidates: [+ { id: 'c0', kind: 'member', agentId: lead, machineId: 'test-host', engine: 'claude', model: 'sonnet', effort: 'medium', quality: 2, cost: 2, title: 'Lead · Claude sonnet medium · test-host', label: 'Member Lead' },+ { id: 'c1', kind: 'new', machineId: 'test-host', engine: 'claude', model: 'opus', effort: 'high', quality: 3, cost: 3, title: 'New agent · Claude opus high · test-host', label: 'New agent' },+ ], excluded: [{ title: 'New agent · Codex · test-host', reason: 'The selected agent engine is not installed on this machine.' }],+ floor: 2, notes: false, pick: 'c0', via: 'order', p: null, belowFloor: false, why: 'Cheapest candidate that meets the floor.' }+ const first = (await run(tab, { type: 'route.record', conversationId: 'lead', decision } as Command, host, lead)).result.routeDecisionId as string+ const second = (await run(tab, { type: 'route.record', conversationId: 'lead', decision } as Command, host, lead)).result.routeDecisionId as string+ expect((await store.routeDecision(owner, tab, first)).outcome).toBe('superseded')+ const rows = (await store.messages(owner, tab, 'lead', {})).messages+ expect(rows.at(-1)).toMatchObject({ source: { kind: 'route', decisionId: second, via: 'order' } })+ await expect(run(tab, { type: 'route.override', decisionId: first, candidateId: 'c1', reason: 'Needs Opus.' } as Command))+ .rejects.toMatchObject({ code: 'ROUTE_CLOSED' })+ await run(tab, { type: 'route.override', decisionId: second, candidateId: 'c1', reason: 'Needs Opus.' } as Command)+ expect((await store.routeDecision(owner, tab, second)).override).toMatchObject({ by: 'person', candidateId: 'c1' })+ expect((await store.deliveries(host, tab, lead)).length).toBeGreaterThan(0)+ await invite(tab, 'viewer')+ await expect(run(tab, { type: 'route.override', decisionId: second, candidateId: 'c0', reason: 'No.' } as Command, peer))+ .rejects.toMatchObject({ status: 403 })+ expect((await store.routeDecisions(owner, tab)).map(d => d.id)).toEqual([second, first])+ })++ it('limits route records to 30 per tab per hour', async () => {+ const { tab, lead } = await fixture()+ const decision = { assessment: { difficulty: 'low', risk: 'low', why: 'Docs.' },+ candidates: [{ id: 'c0', kind: 'new', machineId: 'test-host', engine: 'claude', model: 'haiku', effort: 'auto', quality: 1, cost: 1, title: 'New agent', label: 'New agent' }],+ excluded: [], floor: 1, notes: false, pick: 'c0', via: 'only', p: null, belowFloor: false, why: 'Only candidate.' }+ for (let i = 0; i < 30; i++) await run(tab, { type: 'route.record', conversationId: 'lead', decision } as Command, host, lead)+ await expect(run(tab, { type: 'route.record', conversationId: 'lead', decision } as Command, host, lead)).rejects.toMatchObject({ code: 'RATE_LIMITED', status: 429 })+ })+```++- [ ] **Step 8: Run backend checks**++Run: `cd backend && npx tsc --noEmit -p . && npx vitest run src/superTabs && npm run test:super-tabs`+Expected: all PASS.++- [ ] **Step 9: Commit**++```bash+git add backend+git commit -m "Super Tab routing: decision log, route messages and person override"+```++---++### Task 4: Link decisions to starts and assignments; model and effort on starts++**Files:**+- Modify: `backend/src/superTabs/commands.ts`, `backend/src/superTabs/model.ts` (`AgentStartRequest`), `backend/src/superTabs/store.ts` (simplify the Task 3 guard)+- Test: `backend/src/superTabs/commands.test.ts`, `backend/integration/superTabs.test.ts`++**Interfaces:**+- Consumes: `RouteDecision`, `RouteFinal`, `RouteOverride`, `routeTitle` (Task 3).+- Produces:+ - `work.assign` and `agent.start` accept optional `routeDecisionId` and `overrideReason` (≤ 300).+ - `startRequestSchema` accepts optional `model` (≤ 200) and `effort` (≤ 80); `AgentStartRequest` gains `model?: string; effort?: string`.+ - A mismatch with the expected candidate without `overrideReason` → `OVERRIDE_REASON_REQUIRED` (400). A decision from another group → `ROUTE_MISMATCH` (409).+ - With a reason, a Lead override posts `source: {kind: 'route-override', decisionId, by: 'lead'}`.++- [ ] **Step 1: Write the failing unit tests** (append to `commands.test.ts`; reuse `record()`/`candidate()` from Task 3)++```ts+describe('decisions linked to work', () => {+ const open = (patch: Record<string, unknown> = {}) => ({ id: 'd1', conversationId: 'lead', record: record(), final: null, override: null, assignmentId: null, outcome: null, ...patch })++ it('links an assignment of the picked member, and needs a reason otherwise', () => {+ const f = fixture()+ const member = record({ candidates: [candidate('c0', { kind: 'member', agentId: f.worker }), candidate('c1')], pick: 'c0' })+ f.define('lead')+ const linked = f.run({ type: 'work.assign', conversationId: 'lead', agentId: f.worker, routeDecisionId: 'd1' }, f.leadActor, { routeDecision: open({ record: member }) })+ expect(linked.routeDecisions).toEqual([{ op: 'final', id: 'd1', final: { kind: 'member', agentId: f.worker, machineId: expect.any(String) }, assignmentId: linked.result.assignmentId }])+ })++ it('refuses a mismatch without a reason and records the lead override with one', () => {+ const f = fixture()+ f.define('lead')+ expect(() => f.run({ type: 'work.assign', conversationId: 'lead', agentId: f.worker, routeDecisionId: 'd1' }, f.leadActor, { routeDecision: open() }))+ .toThrow('reason')+ const effects = f.run({ type: 'work.assign', conversationId: 'lead', agentId: f.worker, routeDecisionId: 'd1', overrideReason: 'This worker already has the context.' }, f.leadActor, { routeDecision: open() })+ expect(effects.routeDecisions[0]).toMatchObject({ op: 'final', override: { by: 'lead', reason: 'This worker already has the context.' } })+ expect(effects.messages.some(m => m.source?.kind === 'route-override')).toBe(true)+ })++ it('refuses a decision from another group', () => {+ const f = fixture()+ f.define('lead')+ expect(() => f.run({ type: 'work.assign', conversationId: 'lead', agentId: f.worker, routeDecisionId: 'd1', overrideReason: 'x' }, f.leadActor,+ { routeDecision: open({ conversationId: 'other' }) })).toThrow('another group')+ })++ it('links a start that matches the picked new agent, model and effort', () => {+ const f = fixture()+ const request = { conversationId: 'lead', machineId: 'machine', engine: 'claude', model: 'opus', effort: 'high', name: 'Builder', cwd: '/repo', worktree: false,+ requirements: { memoryBytes: 0, diskBytes: 0, maxCpuPercent: 100, tools: [], devices: [], quotaRequired: false } }+ const effects = f.run({ type: 'agent.start', request, routeDecisionId: 'd1' }, f.leadActor, { routeDecision: open(), contribution: f.contribution })+ expect(effects.routeDecisions).toEqual([{ op: 'final', id: 'd1', final: { kind: 'new', startId: effects.result.startId, machineId: 'machine', engine: 'claude', model: 'opus', effort: 'high' } }])+ })++ it('links the assignment of an agent started from the decision', () => {+ const f = fixture()+ f.define('lead')+ const started = open({ final: { kind: 'new', startId: f.startedFor(f.worker), machineId: 'machine', engine: 'claude', model: 'opus', effort: 'high' } })+ const effects = f.run({ type: 'work.assign', conversationId: 'lead', agentId: f.worker, routeDecisionId: 'd1' }, f.leadActor, { routeDecision: started })+ expect(effects.routeDecisions[0]).toMatchObject({ op: 'final', assignmentId: effects.result.assignmentId })+ expect(effects.routeDecisions[0]).not.toHaveProperty('override')+ })+})+```++Fixture helpers needed (add to the test's `fixture()` if missing): `f.worker` (a non-lead agent id in conversation `lead` on machine `machine`), `f.define(group)` (runs `work.define` with one check), `f.contribution` (the `context.contribution` the fixture already passes for `agent.add`), and `f.startedFor(agentId)` which pushes a completed start into `state.starts` with that agent's `harnessId`/`machineId` and returns its id.++- [ ] **Step 2: Run tests to verify they fail**++Run: `cd backend && npx vitest run src/superTabs/commands.test.ts -t "decisions linked"`+Expected: FAIL (`routeDecisionId` rejected by the strict schema).++- [ ] **Step 3: Implement**++Schema changes in `commands.ts`:++```ts+// startRequestSchema gains:+ model: z.string().trim().min(1).max(200).optional(), effort: z.string().trim().min(1).max(80).optional(),+// commandSchema:+ z.object({ type: z.literal('agent.start'), request: startRequestSchema, routeDecisionId: id.optional(), overrideReason: reason.optional() }).strict(),+ z.object({ type: z.literal('work.assign'), conversationId: id, agentId: id, routeDecisionId: id.optional(), overrideReason: reason.optional() }).strict(),+```++`model.ts` `AgentStartRequest` gains `model?: string` and `effort?: string`.++Helpers in `applyCommand` (after `openDecision`):++```ts+ /** The candidate a start or assignment should match, and whether it does. A mismatch needs the lead's reason. */+ const linkDecision = (conversationId: string, matches: (c: RouteCandidate, d: RouteDecision) => boolean,+ final: RouteFinal, reasonText: string | undefined, assignmentId?: string) => {+ const decision = openDecision()+ if (decision.conversationId !== conversationId) fail('ROUTE_MISMATCH', 'This routing decision belongs to another group.')+ const expected = decision.record.candidates.find(c => c.id === (decision.override?.candidateId ?? decision.record.pick))!+ const matched = matches(expected, decision)+ if (!matched && !reasonText) fail('OVERRIDE_REASON_REQUIRED', `Routing chose ${expected.title}. Pass overrideReason to choose otherwise.`, 400)+ const override: RouteOverride | undefined = matched ? undefined : { by: 'lead', actorKey: actorKey(actor), reason: reasonText! }+ effects.routeDecisions.push({ op: 'final', id: decision.id, final, ...(override ? { override } : {}), ...(assignmentId ? { assignmentId } : {}) })+ return { decision, expected, override }+ }+```++Import `RouteCandidate`, `RouteFinal`, `RouteOverride` types from `./routeRecord.js`.++In `case 'agent.start'`, after `result.startId = operationId`:++```ts+ if (command.routeDecisionId) {+ const r = command.request+ const model = r.model ?? 'default', effort = r.effort ?? 'default'+ const { decision, expected, override } = linkDecision(r.conversationId,+ c => c.kind === 'new' && c.machineId === r.machineId && c.engine === r.engine && c.model === model && c.effort === effort,+ { kind: 'new', startId: operationId, machineId: r.machineId, engine: r.engine, model, effort }, command.overrideReason)+ if (override) message(r.conversationId, `Lead started ${r.name} instead of ${expected.title}. Reason: ${override.reason}`, [], null,+ { kind: 'route-override', decisionId: decision.id, by: 'lead' })+ }+```++`message()` sets `result.messageId`; that is harmless here.++In `case 'work.assign'`, after `result.assignmentId = operationId` and **before** the existing `message(...)` call to the worker (so the worker's brief remains the last message and `result.messageId` stays the brief's id), compute the link; post the override note after the brief:++```ts+ let routeNote: { decisionId: string; text: string } | null = null+ if (command.routeDecisionId) {+ const started = (d: RouteDecision) => d.final?.kind === 'new' &&+ state.starts?.some(s => s.id === (d.final as { startId: string }).startId && s.harnessId === worker.harnessId && s.request.machineId === worker.machineId)+ const { decision, expected, override } = linkDecision(group.id,+ (c, d) => (c.kind === 'member' && c.agentId === worker.id) || (c.kind === 'new' && !!started(d)),+ { kind: 'member', agentId: worker.id, machineId: worker.machineId }, command.overrideReason, operationId)+ if (override) routeNote = { decisionId: decision.id, text: `Lead assigned ${worker.name} instead of ${expected.title}. Reason: ${override.reason}` }+ }+ // existing: message(group.id, `${group.brief}...`, [worker.id])+ if (routeNote) effects.messages.push({ id: stableId(operationId, 'route-override'), conversationId: group.id, author: sender,+ text: routeNote.text, replyTo: null, recipients: [], source: { kind: 'route-override', decisionId: routeNote.decisionId, by: 'lead' } })+```++The second message needs its own id (`stableId(operationId, 'route-override')`) because message ids are unique.++In `store.ts`, replace the Task 3 guard with the typed field:++```ts+ const decisionId = command.type === 'route.override' ? command.decisionId+ : command.type === 'work.assign' || command.type === 'agent.start' ? command.routeDecisionId : undefined+```++- [ ] **Step 4: Run unit tests**++Run: `cd backend && npx vitest run src/superTabs/commands.test.ts`+Expected: PASS.++- [ ] **Step 5: Write the failing integration test**++```ts+ it('closes a linked decision with the assignment outcome', async () => {+ const { tab, lead } = await fixture()+ const group = (await run(tab, { type: 'conversation.create', title: 'Build', brief: 'Build it.', checks: [{ description: 'Tests pass', independent: false }] })).result.conversationId as string+ const worker = (await run(tab, { type: 'agent.add', conversationId: group, machineId: 'test-host', harnessId: randomUUID(),+ name: 'Builder', configuration: config, lead: false })).result.agentId as string+ const decision = { assessment: { difficulty: 'low', risk: 'low', why: 'Small.' },+ candidates: [{ id: 'c0', kind: 'member', agentId: worker, machineId: 'test-host', engine: 'claude', model: 'sonnet', effort: 'medium', quality: 2, cost: 2, title: 'Builder', label: 'Member Builder' }],+ excluded: [], floor: 1, notes: false, pick: 'c0', via: 'only', p: null, belowFloor: false, why: 'Only candidate.' }+ const routeDecisionId = (await run(tab, { type: 'route.record', conversationId: group, decision } as Command, host, lead)).result.routeDecisionId as string+ const assignmentId = (await run(tab, { type: 'work.assign', conversationId: group, agentId: worker, routeDecisionId } as Command, host, lead)).result.assignmentId as string+ expect(await store.routeDecision(owner, tab, routeDecisionId)).toMatchObject({ assignmentId, final: { kind: 'member', agentId: worker } })+ // Completing needs check evidence (existing rule); stopping needs a host receipt. Use the existing stop path:+ await store.stopped(host, tab, assignmentId, 'Stopped by fixture.')+ await run(tab, { type: 'work.status', conversationId: group, assignmentId, status: 'stopped', result: null } as Command, host, lead)+ expect((await store.routeDecision(owner, tab, routeDecisionId)).outcome).toBe('stopped')+ })+```++If `store.stopped(...)` needs a different argument shape, follow the existing integration test that stops an assignment.++- [ ] **Step 6: Run backend checks**++Run: `cd backend && npx tsc --noEmit -p . && npm test && npm run test:super-tabs`+Expected: all PASS.++- [ ] **Step 7: Commit**++```bash+git add backend+git commit -m "Super Tab routing: link decisions to starts and assignments"+```++---++## Phase B — CLI++### Task 5: Pure routing core++**Files:**+- Create: `cli/src/superTabs/route.ts`+- Test: `cli/src/superTabs/route.spec.ts`+- Create: `cli/vitest.super-tabs.config.ts`; modify `cli/package.json` (script `test:super-tabs`)++**Interfaces:**+- Consumes: `jevPick` from `cli/src/lib/routeDecide.ts`; `JevChoice`, `JevChoiceAnswer` from `cli/src/lib/jev/jevClient.ts`; `quotaOf` shape from `cli/src/superTabs/capacity.ts`.+- Produces (exact names used by Task 6):++```ts+export type Level = 'low' | 'medium' | 'high'+export interface Assessment { difficulty: Level; risk: Level; why: string; needs: { tools: string[]; devices: string[]; cwd?: string } }+export interface PolicyModel { engine: 'claude' | 'codex'; model: string; effort: string; quality: number; cost: number; enabled: boolean }+export interface Policy { version: 1; models: PolicyModel[]; floor: Record<Level, number>; quotaReserve: number; notes: string }+export interface Quota { known: boolean; leftPercent: number | null; resetsAt: number | null }+export interface Probe {+ kind: 'member' | 'new'; agentId?: string; name?: string; machineId: string; machineName: string+ engine: 'claude' | 'codex'; model: string; effort: string; quality: number; cost: number+ quota: Quota; activity: string; known: boolean; refusals: string[]+}+export interface Shown extends Probe { id: string; title: string; label: string }+export interface Choice { shown: Shown[]; excluded: Array<{ title: string; reason: string }>; floor: number; belowFloor: boolean }+export interface Verdict { pick: Shown; via: 'jev' | 'order' | 'only'; p: number | null; why: string }+export function parseAssessment(value: unknown): Assessment | string // string = error detail+export function floorFor(policy: Policy, a: Assessment): number+export function quotaOf2(q: { known: boolean; windows: Array<{ usedPercent: number; resetsAt: unknown }> }): Quota+export function rateFor(policy: Policy, engine: string, model: string | null, effort: string | null): { quality: number; cost: number }+export function choose(probes: Probe[], policy: Policy, a: Assessment): Choice | { error: 'NO_CANDIDATE'; excluded: Array<{ title: string; reason: string }> }+export function jevQuestion(input: { title: string; brief: string; checks: string[]; history: string[] }, a: Assessment, policy: Policy, choice: Choice):+ { state: Record<string, string>; questions: Record<string, JevChoice> }+export function decide(choice: Choice, answer: JevChoiceAnswer | undefined, unavailable: string | null): Verdict+export function recordOf(choice: Choice, verdict: Verdict, a: Assessment, policy: Policy): Record<string, unknown> // routeRecordSchema payload+```++- [ ] **Step 1: Write the failing tests**++```ts+// cli/src/superTabs/route.spec.ts+import { describe, expect, it } from 'vitest'+import { choose, decide, floorFor, jevQuestion, parseAssessment, quotaOf2, rateFor, recordOf, type Assessment, type Policy, type Probe } from './route.js'++const policy: Policy = { version: 1, floor: { low: 1, medium: 2, high: 3 }, quotaReserve: 10, notes: 'Frontend prefers Claude.', models: [+ { engine: 'claude', model: 'opus', effort: 'high', quality: 3, cost: 3, enabled: true },+ { 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 },+] }+const a = (patch: Partial<Assessment> = {}): Assessment => ({ difficulty: 'medium', risk: 'low', why: 'API change.', needs: { tools: [], devices: [] }, ...patch })+const probe = (patch: Partial<Probe> = {}): Probe => ({ kind: 'new', machineId: 'm1', machineName: 'remote-1', engine: 'claude', model: 'sonnet',+ effort: 'medium', quality: 2, cost: 2, quota: { known: true, leftPercent: 50, resetsAt: 1_000 }, activity: 'new', known: true, refusals: [], ...patch })++describe('assessment and floor', () => {+ it('parses a Lead assessment and explains what is wrong', () => {+ expect(parseAssessment({ difficulty: 'high', risk: 'low', why: ' Schema. ', needs: { tools: ['git'] } }))+ .toEqual({ difficulty: 'high', risk: 'low', why: 'Schema.', needs: { tools: ['git'], devices: [] } })+ expect(parseAssessment({ difficulty: 'hard', risk: 'low', why: 'x' })).toContain('difficulty')+ expect(parseAssessment({ difficulty: 'low', risk: 'low', why: 'x'.repeat(301) })).toContain('300')+ expect(parseAssessment({ difficulty: 'low', risk: 'low', why: 'x', needs: { cwd: 'relative' } })).toContain('absolute')+ expect(parseAssessment(null)).toContain('difficulty')+ })+ it('raises the floor by one for high risk, to at most 3', () => {+ expect(floorFor(policy, a())).toBe(2)+ expect(floorFor(policy, a({ risk: 'high' }))).toBe(3)+ expect(floorFor(policy, a({ difficulty: 'high', risk: 'high' }))).toBe(3)+ })+})++describe('quota and rates', () => {+ it('normalizes reset times from epoch seconds, milliseconds and ISO strings and uses the tightest window', () => {+ expect(quotaOf2({ known: true, windows: [{ usedPercent: 20, resetsAt: 1_800_000_000 }, { usedPercent: 70, resetsAt: '2026-10-19T12:00:00Z' }] }))+ .toEqual({ known: true, leftPercent: 30, resetsAt: Date.parse('2026-10-19T12:00:00Z') })+ expect(quotaOf2({ known: true, windows: [{ usedPercent: 10, resetsAt: 1_800_000_000 }] }).resetsAt).toBe(1_800_000_000_000)+ expect(quotaOf2({ known: true, windows: [{ usedPercent: 10, resetsAt: 1_800_000_000_000 }] }).resetsAt).toBe(1_800_000_000_000)+ expect(quotaOf2({ known: true, windows: [{ usedPercent: 10, resetsAt: 'soon' }] }).resetsAt).toBeNull()+ expect(quotaOf2({ known: false, windows: [] })).toEqual({ known: false, leftPercent: null, resetsAt: null })+ })+ it('rates a member by its policy row, then by model, else conservatively', () => {+ expect(rateFor(policy, 'claude', 'opus', 'high')).toEqual({ quality: 3, cost: 3 })+ expect(rateFor(policy, 'claude', 'opus', 'max')).toEqual({ quality: 3, cost: 3 })+ expect(rateFor(policy, 'claude', null, null)).toEqual({ quality: 1, cost: 1 })+ })+})++describe('choose', () => {+ it('returns NO_CANDIDATE with reasons when nothing can run', () => {+ expect(choose([probe({ refusals: ['Machine is offline.'] })], policy, a())).toEqual({ error: 'NO_CANDIDATE',+ excluded: [{ title: 'New agent · Claude sonnet medium · remote-1', reason: 'Machine is offline.' }] })+ })+ it('shows only floor-meeting candidates, ordered by cost, quota, reset and member first', () => {+ const r = choose([+ probe({ model: 'opus', effort: 'high', quality: 3, cost: 3 }),+ probe({ machineId: 'm2', machineName: 'mac', quota: { known: true, leftPercent: 80, resetsAt: 5_000 } }),+ probe({ quota: { known: true, leftPercent: 80, resetsAt: 2_000 } }),+ probe({ kind: 'member', agentId: 'a1', name: 'Multiply', quota: { known: true, leftPercent: 80, resetsAt: 2_000 }, activity: 'idle' }),+ probe({ model: 'haiku', effort: 'auto', quality: 1, cost: 1 }),+ ], policy, a())+ if ('error' in r) throw new Error('unexpected')+ expect(r.belowFloor).toBe(false)+ expect(r.shown.map(s => s.title)).toEqual([+ 'Multiply · Claude sonnet medium · remote-1',+ 'New agent · Claude sonnet medium · remote-1',+ 'New agent · Claude sonnet medium · mac',+ 'New agent · Claude sonnet medium · remote-1',+ 'New agent · Claude opus high · remote-1',+ ])+ expect(r.shown.map(s => s.id)).toEqual(['c0', 'c1', 'c2', 'c3', 'c4'])+ })+ it('marks belowFloor when nobody meets it, keeps the quota reserve, and prefers known candidates', () => {+ const r = choose([probe({ quality: 1 }), probe({ quality: 1, quota: { known: true, leftPercent: 5, resetsAt: null } })], policy, a({ difficulty: 'high' }))+ if ('error' in r) throw new Error('unexpected')+ expect(r.belowFloor).toBe(true)+ expect(r.shown).toHaveLength(1)+ const onlyReserve = choose([probe({ quota: { known: true, leftPercent: 5, resetsAt: null } })], policy, a())+ if ('error' in onlyReserve) throw new Error('unexpected')+ expect(onlyReserve.shown).toHaveLength(1)+ const unknown = choose([probe({ known: false, quota: { known: false, leftPercent: null, resetsAt: null } }), probe()], policy, a())+ if ('error' in unknown) throw new Error('unexpected')+ expect(unknown.shown.map(s => s.known)).toEqual([true])+ })+ it('shows at most 12 candidates', () => {+ const r = choose(Array.from({ length: 20 }, (_, i) => probe({ machineId: `m${i}`, machineName: `box-${String(i).padStart(2, '0')}` })), policy, a())+ if ('error' in r) throw new Error('unexpected')+ expect(r.shown).toHaveLength(12)+ })+})++describe('Jev context and verdict', () => {+ const choice = () => { const r = choose([probe({ kind: 'member', agentId: 'a1', name: 'Multiply', activity: 'idle' }), probe({ machineName: 'mac' })], policy, a()); if ('error' in r) throw new Error('x'); return r }+ it('builds at most four string keys within the hosted limits, with no email', () => {+ const q = jevQuestion({ title: 'Build', brief: 'b'.repeat(5000), checks: ['Tests pass', 'Docs updated'], history: ['Builder: stopped'] }, a(), policy, choice())+ expect(Object.keys(q.state)).toEqual(['task', 'lead', 'policy', 'history'])+ expect(Object.values(q.state).every(v => typeof v === 'string')).toBe(true)+ expect(Object.values(q.state).join('').length).toBeLessThanOrEqual(17_000)+ expect(q.state.task.length).toBeLessThan(5000)+ expect(q.state.policy).toContain('Frontend prefers Claude.')+ expect(Object.keys(q.questions.who.criteria)).toEqual(['c0', 'c1'])+ expect(Object.values(q.questions.who.criteria).every(v => v.length <= 640)).toBe(true)+ expect(q.questions.who.instructions.length).toBeLessThanOrEqual(1500)+ expect(JSON.stringify(q)).not.toMatch(/@/)+ })+ it('takes a sure Jev pick, falls back to order when unsure or unavailable, and skips Jev for one candidate', () => {+ const c = choice()+ expect(decide(c, { choice: 'c1', probabilities: { c0: 0.2, c1: 0.8 } }, null)).toMatchObject({ via: 'jev', p: 0.8, pick: { id: 'c1' } })+ expect(decide(c, { choice: 'c1', probabilities: { c0: 0.45, c1: 0.55 } }, null)).toMatchObject({ via: 'order', pick: { id: 'c0' }, why: expect.stringContaining('Jev unsure') })+ expect(decide(c, undefined, 'BUSY')).toMatchObject({ via: 'order', pick: { id: 'c0' }, why: expect.stringContaining('Jev unavailable') })+ const one = choose([probe()], policy, a()); if ('error' in one) throw new Error('x')+ expect(decide(one, undefined, null)).toMatchObject({ via: 'only', p: null })+ })+ it('broken Jev answers fall back to order', () => {+ const c = choice()+ expect(decide(c, { choice: 'c9', probabilities: { c0: 0.1, c9: 0.9 } }, null).via).toBe('order')+ expect(decide(c, { choice: 'c1', probabilities: { c1: 0.9 } }, null).via).toBe('order')+ })+ it('produces a record the backend schema accepts', () => {+ const c = choice(), v = decide(c, { choice: 'c1', probabilities: { c0: 0.2, c1: 0.8 } }, null)+ expect(recordOf(c, v, a(), policy)).toEqual({ assessment: { difficulty: 'medium', risk: 'low', why: 'API change.' },+ candidates: c.shown.map(s => ({ id: s.id, kind: s.kind, ...(s.agentId ? { agentId: s.agentId } : {}), machineId: s.machineId,+ engine: s.engine, model: s.model, effort: s.effort, quality: s.quality, cost: s.cost, title: s.title, label: s.label })),+ excluded: [], floor: 2, notes: true, pick: 'c1', via: 'jev', p: 0.8, belowFloor: false, why: v.why })+ })+})+```++- [ ] **Step 2: Run tests to verify they fail**++Run: `cd cli && npx vitest run src/superTabs/route.spec.ts`+Expected: FAIL (module missing).++- [ ] **Step 3: Implement `route.ts`**++```ts+// cli/src/superTabs/route.ts+/** Super Tab routing v1, the pure half (docs/superpowers/specs/2026-10-19-super-tab-routing-v1-design.md).+ * The system removes what cannot run the task, Jev chooses among the rest with the full context, and a+ * fixed policy order decides when Jev is unsure or unavailable. Jev's acceptance rule is the voice+ * router's (`jevPick`), tuned on the owner's desk on 2026-10-10. */+import { isAbsolute } from 'node:path'+import type { JevChoice, JevChoiceAnswer } from '../lib/jev/jevClient.js'+import { jevPick } from '../lib/routeDecide.js'++export type Level = 'low' | 'medium' | 'high'+export interface Assessment { difficulty: Level; risk: Level; why: string; needs: { tools: string[]; devices: string[]; cwd?: string } }+export interface PolicyModel { engine: 'claude' | 'codex'; model: string; effort: string; quality: number; cost: number; enabled: boolean }+export interface Policy { version: 1; models: PolicyModel[]; floor: Record<Level, number>; quotaReserve: number; notes: string }+export interface Quota { known: boolean; leftPercent: number | null; resetsAt: number | null }+export interface Probe {+ kind: 'member' | 'new'; agentId?: string; name?: string; machineId: string; machineName: string+ engine: 'claude' | 'codex'; model: string; effort: string; quality: number; cost: number+ quota: Quota; activity: string; known: boolean; refusals: string[]+}+export interface Shown extends Probe { id: string; title: string; label: string }+export interface Choice { shown: Shown[]; excluded: Array<{ title: string; reason: string }>; floor: number; belowFloor: boolean }+export interface Verdict { pick: Shown; via: 'jev' | 'order' | 'only'; p: number | null; why: string }++const LEVELS: Level[] = ['low', 'medium', 'high']+const MAX_SHOWN = 12+const ENGINE = { claude: 'Claude', codex: 'Codex' } as const+const cut = (text: string, max: number) => text.length <= max ? text : `${text.slice(0, max - 1)}…`++export function parseAssessment(value: unknown): Assessment | string {+ const v = (value && typeof value === 'object' ? value : {}) as Record<string, unknown>+ if (!LEVELS.includes(v.difficulty as Level)) return 'Set difficulty to low, medium or high.'+ if (!LEVELS.includes(v.risk as Level)) return 'Set risk to low, medium or high.'+ const why = typeof v.why === 'string' ? v.why.trim() : ''+ if (!why || why.length > 300) return 'Give why in 1 to 300 characters.'+ const needs = (v.needs && typeof v.needs === 'object' ? v.needs : {}) as Record<string, unknown>+ const list = (x: unknown) => Array.isArray(x) && x.every(i => typeof i === 'string') ? x as string[] : []+ const cwd = needs.cwd+ if (cwd !== undefined && (typeof cwd !== 'string' || !isAbsolute(cwd))) return 'needs.cwd must be an absolute path.'+ return { difficulty: v.difficulty as Level, risk: v.risk as Level, why, needs: { tools: list(needs.tools), devices: list(needs.devices), ...(cwd ? { cwd } : {}) } }+}++export const floorFor = (policy: Policy, a: Assessment): number => Math.min(3, policy.floor[a.difficulty] + (a.risk === 'high' ? 1 : 0))++/** Claude sends ISO strings, Codex epoch seconds; anything above 1e10 is already milliseconds. */+function resetMs(value: unknown): number | null {+ if (typeof value === 'number' && Number.isFinite(value)) return value > 1e10 ? value : value * 1000+ if (typeof value === 'string') { const ms = Date.parse(value); return Number.isFinite(ms) ? ms : null }+ return null+}+export function quotaOf2(q: { known: boolean; windows: Array<{ usedPercent: number; resetsAt: unknown }> }): Quota {+ if (!q.known || !q.windows.length) return { known: false, leftPercent: null, resetsAt: null }+ const tightest = q.windows.reduce((x, y) => y.usedPercent > x.usedPercent ? y : x)+ return { known: true, leftPercent: Math.max(0, 100 - tightest.usedPercent), resetsAt: resetMs(tightest.resetsAt) }+}++export function rateFor(policy: Policy, engine: string, model: string | null, effort: string | null): { quality: number; cost: number } {+ const row = policy.models.find(m => m.engine === engine && m.model === (model ?? 'default') && m.effort === (effort ?? 'default'))+ ?? policy.models.find(m => m.engine === engine && m.model === (model ?? 'default'))+ return row ? { quality: row.quality, cost: row.cost } : { quality: 1, cost: 1 }+}++const titleOf = (p: Probe) => cut(`${p.kind === 'member' ? p.name ?? 'Member' : 'New agent'} · ${ENGINE[p.engine]} ${p.model} ${p.effort} · ${p.machineName}`, 160)+function quotaText(q: Quota): string {+ if (!q.known || q.leftPercent === null) return 'quota unknown'+ if (q.resetsAt === null) return `quota ${Math.round(q.leftPercent)}% left`+ return `quota ${Math.round(q.leftPercent)}% left, resets ${new Date(q.resetsAt).toISOString()}`+}+const labelOf = (p: Probe) => cut(`${p.kind === 'member' ? `Member ${p.name ?? ''}`.trim() : 'New agent'} · ${ENGINE[p.engine]} ${p.model} ${p.effort} · quality ${p.quality}, cost ${p.cost} · ${p.machineName} · ${p.activity} · ${quotaText(p.quota)}`, 640)++/** The fixed policy order (D): cheaper, then more quota left, then an earlier reset, then a member, then by title. */+function compare(x: Probe, y: Probe): number {+ return x.cost - y.cost+ || (y.quota.leftPercent ?? -1) - (x.quota.leftPercent ?? -1)+ || (x.quota.resetsAt ?? Infinity) - (y.quota.resetsAt ?? Infinity)+ || (x.kind === y.kind ? 0 : x.kind === 'member' ? -1 : 1)+ || titleOf(x).localeCompare(titleOf(y))+}++export function choose(probes: Probe[], policy: Policy, a: Assessment): Choice | { error: 'NO_CANDIDATE'; excluded: Array<{ title: string; reason: string }> } {+ const excluded = probes.filter(p => p.refusals.length).map(p => ({ title: titleOf(p), reason: p.refusals.join(' ') }))+ const viable = probes.filter(p => !p.refusals.length)+ if (!viable.length) return { error: 'NO_CANDIDATE', excluded }+ const known = viable.filter(p => p.known)+ const pool = known.length ? known : viable+ const reserved = pool.filter(p => p.quota.leftPercent === null || p.quota.leftPercent >= policy.quotaReserve)+ const funded = reserved.length ? reserved : pool+ const floor = floorFor(policy, a)+ const meeting = funded.filter(p => p.quality >= floor)+ const set = meeting.length ? meeting : funded+ const shown = [...set].sort(compare).slice(0, MAX_SHOWN)+ .map((p, i) => ({ ...p, id: `c${i}`, title: titleOf(p), label: labelOf(p) }))+ return { shown, excluded, floor, belowFloor: !meeting.length }+}++const INSTRUCTIONS = cut([+ 'Choose the candidate that should do this task.',+ 'The Lead assessed its difficulty and risk; every candidate shown meets the quality floor unless the policy says none does.',+ 'Prefer lower cost, then more quota left and an earlier reset, unless the task, its history or the policy notes give a clear reason otherwise.',+ 'A candidate that already failed or stopped on this task is a worse choice. An idle member already in the Super Tab saves a start.',+].join(' '), 1500)++export function jevQuestion(input: { title: string; brief: string; checks: string[]; history: string[] }, a: Assessment, policy: Policy, choice: Choice) {+ const state = {+ task: cut(`Group: ${cut(input.title, 160)}\nBrief: ${cut(input.brief, 2000)}\nChecks:\n${cut(input.checks.map(c => `- ${c}`).join('\n'), 2000)}`, 4400),+ lead: cut(`Difficulty: ${a.difficulty}. Risk: ${a.risk}. Why: ${a.why}. Needs tools: ${a.needs.tools.join(', ') || 'none'}; devices: ${a.needs.devices.join(', ') || 'none'}.`, 800),+ policy: cut(`Quality floor: ${choice.floor}${choice.belowFloor ? ' (no candidate meets it; all are shown)' : ''}. Notes: ${policy.notes || 'none'}`, 700),+ history: cut(input.history.length ? input.history.join('\n') : 'No earlier attempts.', 2000),+ }+ const questions: Record<string, JevChoice> = {+ who: { type: 'choice', instructions: INSTRUCTIONS, criteria: Object.fromEntries(choice.shown.map(s => [s.id, s.label])) },+ }+ return { state, questions }+}++export function decide(choice: Choice, answer: JevChoiceAnswer | undefined, unavailable: string | null): Verdict {+ const first = choice.shown[0]+ if (choice.shown.length === 1) return { pick: first, via: 'only', p: null, why: 'Only candidate that can run this task.' }+ const picked = unavailable ? undefined : jevPick(answer, choice.shown.map(s => s.id), true)+ if (picked) {+ const pick = choice.shown.find(s => s.id === picked)!+ return { pick, via: 'jev', p: answer!.probabilities[picked], why: `Jev chose ${pick.title}.` }+ }+ const reason = unavailable ? `Jev unavailable (${unavailable})` : 'Jev unsure'+ return { pick: first, via: 'order', p: null, why: `${reason}; first in the policy order.` }+}++export function recordOf(choice: Choice, verdict: Verdict, a: Assessment, policy: Policy): Record<string, unknown> {+ return {+ assessment: { difficulty: a.difficulty, risk: a.risk, why: a.why },+ candidates: choice.shown.map(s => ({ id: s.id, kind: s.kind, ...(s.agentId ? { agentId: s.agentId } : {}), machineId: s.machineId,+ engine: s.engine, model: s.model, effort: s.effort, quality: s.quality, cost: s.cost, title: s.title, label: s.label })),+ excluded: choice.excluded.slice(0, 200).map(e => ({ title: e.title, reason: cut(e.reason, 500) })),+ floor: choice.floor, notes: policy.notes.length > 0,+ pick: verdict.pick.id, via: verdict.via, p: verdict.p, belowFloor: choice.belowFloor, why: cut(verdict.why, 300),+ }+}+```++- [ ] **Step 4: Add the coverage gate**++```ts+// cli/vitest.super-tabs.config.ts+import { defineConfig } from 'vitest/config'+import base from './vitest.config.js'++/** Super Tab routing v1 (docs/superpowers/specs/2026-10-19-super-tab-routing-v1-design.md): new files outside+ * the core and services, which no other gate covers, held to 100% in every file. */+const FILES = ['src/superTabs/route.ts', 'src/superTabs/routeCommand.ts']+export default defineConfig({+ test: {+ ...base.test,+ include: FILES.map(f => f.replace(/\.ts$/, '.spec.ts')),+ coverage: { enabled: true, provider: 'v8', include: FILES, thresholds: { perFile: true, lines: 100, statements: 100, branches: 100, functions: 100 } },+ },+})+```++Add to `cli/package.json` scripts: `"test:super-tabs": "vitest run --config vitest.super-tabs.config.ts"`. Until Task 6 creates `routeCommand.ts`, list only `route.ts` in `FILES`; Task 6 adds the second entry.++- [ ] **Step 5: Run tests**++Run: `cd cli && npx tsc --noEmit -p . && npm run test:super-tabs`+Expected: PASS, 100% for `route.ts`. If a branch is uncovered, add the missing case to `route.spec.ts` (do not lower the threshold).++- [ ] **Step 6: Commit**++```bash+git add cli/src/superTabs/route.ts cli/src/superTabs/route.spec.ts cli/vitest.super-tabs.config.ts cli/package.json+git commit -m "Super Tab routing: pure candidate order, Jev context and verdict"+```++---++### Task 6: `harness super-tab route`, service actions and start passthrough++**Files:**+- Create: `cli/src/superTabs/routeCommand.ts`, `cli/src/superTabs/routeCommand.spec.ts`+- Modify: `cli/src/superTabs/service.ts` (+ `service.spec.ts`), `cli/src/superTabs/command.ts` (+ `command.spec.ts`), `cli/src/superTabs/start.ts` (+ `start.spec.ts`), `cli/vitest.super-tabs.config.ts`++**Interfaces:**+- Consumes: everything Task 5 produces; `inspectCapacity(target, request)` and `quotaOf` (`start.ts`, `capacity.ts`); `openDaemon`, `Where` (`cli/src/agentClient/daemon.ts`); `machineChoices` (`cli/src/lib/newCommand.ts`); `createJevDecide` (`cli/src/lib/jev/jevClient.ts`); `encodeRuntimeProfile` (`cli/src/engines/kit/runtime.ts`).+- Produces:+ - Service actions (after the caller is verified as a running contribution): `routeContext` → `{ ok: true, value: { tab, policy, machines } }`; `routeJev` `{ state, questions }` → `{ ok: true, value: { answers } }` or `{ ok: true, value: { unavailable: code } }`.+ - `routeTask(input: { tabId: string; conversationId: string; assessment: unknown }, scoped: ScopedRequest, where: Where, open?: typeof openDaemon, newId?: () => string): Promise<Record<string, unknown>>`+ - CLI verb: `harness super-tab --tab ID route GROUP JSON`.+ - `start OPERATION_ID JSON` accepts `routeDecisionId`, `overrideReason`, `model`, `effort` inside JSON.++- [ ] **Step 1: Write failing service tests** (append to `cli/src/superTabs/service.spec.ts`, using its existing `fakeCore` setup that already answers `GET /api/super-tabs/:tab?asAgentId=` with a state whose agent is running on this machine)++```ts+ it('returns the routing context to a verified contribution', async () => {+ const t = setup() // the spec's existing helper; extend its backend mock with the two paths below+ t.answer('GET', `/api/super-tabs/tab/routing-policy?asAgentId=${t.agentId}`, { policy: { version: 1 }, warnings: [], overridden: [] })+ t.core.account.machines = vi.fn(async () => ({ status: 200, body: { success: true, data: { machines: [{ machineId: 'm1', name: 'remote-1', status: 'online' }], sharedMachines: [] } } }))+ const reply = await t.request({ action: 'routeContext', tabId: 'tab', harnessId: 'harness' })+ expect(reply).toEqual({ ok: true, value: { tab: expect.objectContaining({ state: expect.any(Object) }),+ policy: { policy: { version: 1 }, warnings: [], overridden: [] }, machines: [{ machineId: 'm1', name: 'remote-1' }] } })+ })+ it('asks Jev with a three-second limit and reports unavailability instead of failing', async () => {+ const decide = vi.fn(async () => ({ who: { choice: 'c1', probabilities: { c0: 0.2, c1: 0.8 } } }))+ const t = setup({ jev: () => decide })+ expect(await t.request({ action: 'routeJev', tabId: 'tab', harnessId: 'harness', state: { task: 't' }, questions: { who: {} } }))+ .toEqual({ ok: true, value: { answers: { who: { choice: 'c1', probabilities: { c0: 0.2, c1: 0.8 } } } } })+ expect(decide.mock.calls[0][2]).toBeInstanceOf(AbortSignal)+ decide.mockRejectedValueOnce(Object.assign(new Error('busy'), { code: 'BUSY' }))+ expect(await t.request({ action: 'routeJev', tabId: 'tab', harnessId: 'harness', state: {}, questions: {} }))+ .toEqual({ ok: true, value: { unavailable: 'BUSY' } })+ })+```++If `service.spec.ts` has no `setup()` with `answer()`/`request()` helpers, write them at the top of the new `describe`: build `fakeCore({ account: { backend: vi.fn(async (method, path) => ...) } })` and call `superTabService(core, options).requests.super_tabs(payload, { owner: true, local: true }, new AbortController().signal)` as the existing tests in that file do.++- [ ] **Step 2: Run them to verify they fail**++Run: `cd cli && npx vitest run src/superTabs/service.spec.ts -t "routing context|asks Jev"`+Expected: FAIL (`INVALID_REQUEST`).++- [ ] **Step 3: Implement the service actions** (`cli/src/superTabs/service.ts`)++```ts+import { createJevDecide, type JevDecide } from '../lib/jev/jevClient.js'+import { machineChoices } from '../lib/newCommand.js'+// SuperTabServiceOptions gains:+ /** Jev for `route`; Harness's hosted key through the backend when the person has no key of their own. */+ jev?: (core: CoreApi) => JevDecide+// after `if (payload.action === 'status') return { ok: true, value: answer }`:+ if (payload.action === 'routeContext') {+ const [policy, machines] = await Promise.all([+ backend(core, 'GET', `${path}/routing-policy?${identity}`),+ core.account.machines(),+ ])+ const data = object(object(machines.body).data)+ return { ok: true, value: { tab: answer, policy,+ machines: machineChoices(data, null).filter(m => !m.toAdd).map(m => ({ machineId: m.machineId, name: m.label })) } }+ }+ if (payload.action === 'routeJev') {+ const decide = (options.jev ?? (api => createJevDecide({ backend: (m, p, b) => api.account.backend(m, p, b) })))(core)+ try {+ // Routing never waits on Jev beyond three seconds; the policy order decides instead.+ return { ok: true, value: { answers: await decide(payload.state, object(payload.questions) as never, AbortSignal.timeout(3000)) } }+ } catch (error) {+ const code = error && typeof error === 'object' && 'code' in error && typeof error.code === 'string' ? error.code : 'UNAVAILABLE'+ return { ok: true, value: { unavailable: code } }+ }+ }+```++`machineChoices` lists the account's own machines and the shared ones it may use; `toAdd` machines refuse this account, so they are dropped.++Add to `HELP`:++```ts+ route: 'route GROUP JSON: before starting or assigning work, choose who does it. JSON: {"difficulty":"low|medium|high","risk":"low|medium|high","why":"one sentence","needs":{"tools":[],"devices":[],"cwd":"/absolute/repo"}}. Start or assign the pick with its routeDecisionId; to choose otherwise, pass overrideReason.',+```++and in `startRequest` add `model: 'opus', effort: 'high', routeDecisionId: 'DECISION'`; in the `work.assign` entry of `commands` add `routeDecisionId: 'DECISION'`.++- [ ] **Step 4: Run service tests**++Run: `cd cli && npx vitest run src/superTabs/service.spec.ts`+Expected: PASS.++- [ ] **Step 5: Write failing `routeTask` tests** (`cli/src/superTabs/routeCommand.spec.ts`)++```ts+import { describe, expect, it, vi } from 'vitest'+import { routeTask } from './routeCommand.js'++const policy = { version: 1, floor: { low: 1, medium: 2, high: 3 }, quotaReserve: 10, notes: '', models: [+ { engine: 'claude', model: 'opus', effort: 'high', quality: 3, cost: 3, enabled: true },+ { engine: 'claude', model: 'sonnet', effort: 'medium', quality: 2, cost: 2, enabled: true },+ { engine: 'codex', model: 'default', effort: 'default', quality: 3, cost: 2, enabled: false },+] }+const tab = { revision: 3, state: { id: 'tab', agents: [+ { id: 'a1', name: 'Multiply', machineId: 'm1', harnessId: 'h1', configuration: { engine: 'claude', model: 'sonnet', effort: 'medium' } },+ { id: 'lead', name: 'Lead', machineId: 'm1', harnessId: 'hl', configuration: { engine: 'claude', model: 'opus', effort: 'high' } },+], conversations: [+ { id: 'lead', title: 'Lead', leadId: 'lead', agentIds: ['lead', 'a1'], archived: false, brief: '', checks: [], assignment: { id: 'x', agentId: 'lead', status: 'working' } },+ { id: 'g1', title: 'API', leadId: 'lead', agentIds: ['lead'], archived: false, brief: 'Add the endpoint.', checks: [{ description: 'Tests pass' }], assignment: null },+] } }+const usage = { providers: [{ provider: 'claude', outcome: 'answered', httpStatus: 200, account: 'acct', body: { five_hour: { utilization: 40, resets_at: '2026-10-19T12:00:00Z' }, seven_day: { utilization: 10 } } }] }+function daemon(machineId: string, options: { offline?: boolean; agents?: string[] } = {}) {+ return {+ machineId, close: vi.fn(),+ request: vi.fn(async (type: string) => {+ if (type === 'agents_list') return { agents: (options.agents ?? []).map(id => ({ id, terminal: { available: true } })) }+ if (type === 'super_tabs') return { resources: { memoryTotalBytes: 8e9, memoryUsedBytes: 1e9, cpuPercent: 10, projectDiskFreeBytes: 1e11 }, tools: {}, devices: {} }+ if (type === 'engines_probe') return { engines: [{ engine: 'claude', installed: true, signedIn: true }] }+ if (type === 'usage_read') return usage+ return {}+ }),+ }+}+function scoped(answers: { jev?: unknown; record?: unknown } = {}) {+ return vi.fn(async (payload: Record<string, any>) => {+ if (payload.action === 'routeContext') return { ok: true, value: { tab, policy: { policy, warnings: [] }, machines: [{ machineId: 'm1', name: 'remote-1' }, { machineId: 'm2', name: 'mac' }] } }+ if (payload.action === 'routeJev') return answers.jev ?? { ok: true, value: { answers: { who: { choice: 'c1', probabilities: { c0: 0.1, c1: 0.9 } } } } }+ if (payload.action === 'command') return answers.record ?? { ok: true, value: { result: { routeDecisionId: 'd1' } } }+ return { error: 'UNEXPECTED' }+ })+}+const where = { port: 1, dataDir: '/nonexistent', machineId: 'm1' }+const input = { tabId: 'tab', conversationId: 'g1', assessment: { difficulty: 'medium', risk: 'low', why: 'Endpoint.' } }++describe('routeTask', () => {+ it('collects members and new agents, asks Jev, records and returns the pick', async () => {+ const s = scoped()+ const open = vi.fn(async (_w: unknown, id: string) => daemon(id, { agents: id === 'm1' ? ['h1'] : [] }) as never)+ const result = await routeTask(input, s, where as never, open, () => 'op')+ expect(result).toMatchObject({ ok: true, routeDecisionId: 'd1', via: 'jev', pick: { id: 'c1' } })+ const record = s.mock.calls.find(c => c[0].action === 'command')![0]+ expect(record).toMatchObject({ operationId: 'route-op', command: { type: 'route.record', conversationId: 'g1' } })+ // The busy Lead is not a candidate; the idle member Multiply is.+ const titles = (record.command.decision.candidates as Array<{ title: string }>).map(c => c.title)+ expect(titles).toContain('Multiply · Claude sonnet medium · remote-1')+ expect(titles.some(t => t.startsWith('Lead'))).toBe(false)+ })+ it('returns NO_CANDIDATE with reasons when every machine is unreachable', async () => {+ const open = vi.fn(async () => { throw Object.assign(new Error('gone'), { code: 'MACHINE_UNAVAILABLE' }) })+ const result = await routeTask(input, scoped(), where as never, open as never)+ expect(result).toMatchObject({ error: 'NO_CANDIDATE' })+ expect((result.excluded as Array<{ reason: string }>).every(e => /offline or unreachable/.test(e.reason))).toBe(true)+ })+ it('falls back to the policy order when Jev is unavailable, and still routes when recording fails', async () => {+ const open = vi.fn(async (_w: unknown, id: string) => daemon(id, { agents: id === 'm1' ? ['h1'] : [] }) as never)+ const result = await routeTask(input, scoped({ jev: { ok: true, value: { unavailable: 'BUSY' } }, record: { error: 'BACKEND_UNAVAILABLE' } }), where as never, open)+ expect(result).toMatchObject({ ok: true, via: 'order', unrecorded: true })+ expect(result).not.toHaveProperty('routeDecisionId')+ })+ it('refuses an invalid assessment, an unknown group and a failed context read', async () => {+ const open = vi.fn()+ expect(await routeTask({ ...input, assessment: { difficulty: 'x' } }, scoped(), where as never, open as never)).toMatchObject({ error: 'INVALID_REQUEST' })+ expect(await routeTask({ ...input, conversationId: 'nope' }, scoped(), where as never, open as never)).toMatchObject({ error: 'NOT_FOUND' })+ const failing = vi.fn(async () => ({ error: 'AGENT_UNAVAILABLE', detail: 'x' }))+ expect(await routeTask(input, failing, where as never, open as never)).toMatchObject({ error: 'AGENT_UNAVAILABLE' })+ })+})+```++- [ ] **Step 6: Run to verify failure**++Run: `cd cli && npx vitest run src/superTabs/routeCommand.spec.ts`+Expected: FAIL (module missing).++- [ ] **Step 7: Implement `routeCommand.ts`**++```ts+// cli/src/superTabs/routeCommand.ts+/** `harness super-tab route GROUP JSON`: the Lead's routing step (docs/superpowers/specs/2026-10-19-super-tab-routing-v1-design.md).+ * Reads the tab, the effective policy and the account's machines; probes each machine once per engine with+ * the same admission `start` uses; then orders, asks Jev, and records the decision in the tab. */+import { randomUUID } from 'node:crypto'+import { openDaemon, type Daemon, type Where } from '../agentClient/daemon.js'+import { inspectCapacity, type ScopedRequest } from './start.js'+import { object } from './wire.js'+import { choose, decide, jevQuestion, parseAssessment, quotaOf2, rateFor, recordOf, type Assessment, type Policy, type Probe } from './route.js'+import type { JevChoiceAnswer } from '../lib/jev/jevClient.js'++type Json = Record<string, unknown>+const ENGINES = ['claude', 'codex'] as const+const OFFLINE = 'Machine is offline or unreachable.'+const active = (assignment: unknown) => { const a = object(assignment); return !!a.id && !['done', 'stopped'].includes(String(a.status)) }++export async function routeTask(input: { tabId: string; conversationId: string; assessment: unknown }, scoped: ScopedRequest, where: Where,+ open: typeof openDaemon = openDaemon, newId: () => string = randomUUID): Promise<Json> {+ const assessment = parseAssessment(input.assessment)+ if (typeof assessment === 'string') return { error: 'INVALID_REQUEST', detail: assessment }+ const context = await scoped({ action: 'routeContext' })+ if (context.error || context.ok !== true) return context+ const value = object(context.value), state = object(object(value.tab).state), effective = object(value.policy)+ const policy = effective.policy as unknown as Policy+ const conversations = Array.isArray(state.conversations) ? state.conversations.map(object) : []+ const group = conversations.find(c => c.id === input.conversationId)+ if (!group) return { error: 'NOT_FOUND', detail: 'No such group in this Super Tab.' }+ const busy = new Set(conversations.filter(c => active(c.assignment)).map(c => String(object(c.assignment).agentId)))+ const members = (Array.isArray(state.agents) ? state.agents.map(object) : [])+ .filter(a => !busy.has(String(a.id)) && ENGINES.includes(String(object(a.configuration).engine) as never))+ const machines = new Map<string, string>()+ for (const m of Array.isArray(value.machines) ? value.machines.map(object) : []) machines.set(String(m.machineId), String(m.name))+ for (const m of members) if (!machines.has(String(m.machineId))) machines.set(String(m.machineId), String(m.machineId))+ const enabled = policy.models.filter(m => m.enabled)++ const probes = (await Promise.all([...machines].map(([machineId, machineName]) =>+ probeMachine(machineId, machineName, members.filter(m => m.machineId === machineId), enabled, policy, assessment, where, open)))).flat()+ const choice = choose(probes, policy, assessment)+ if ('error' in choice) return choice++ let answer: JevChoiceAnswer | undefined, unavailable: string | null = null+ if (choice.shown.length > 1) {+ const checks = Array.isArray(group.checks) ? group.checks.map(c => String(object(c).description ?? '')) : []+ // The group's last attempt, when it ended: a worker that stopped on this task is a worse choice.+ const last = object(group.assignment), agents = Array.isArray(state.agents) ? state.agents.map(object) : []+ const history = last.id && !active(last)+ ? [`${String(agents.find(a => a.id === last.agentId)?.name ?? 'An agent')}: ${String(last.status)}${typeof last.result === 'string' ? ` — ${last.result.slice(0, 300)}` : ''}`]+ : []+ const question = jevQuestion({ title: String(group.title ?? ''), brief: String(group.brief ?? ''), checks, history }, assessment, policy, choice)+ const reply = await scoped({ action: 'routeJev', ...question })+ const jev = object(reply.value)+ if (reply.ok !== true || typeof jev.unavailable === 'string') unavailable = typeof jev.unavailable === 'string' ? jev.unavailable : 'UNAVAILABLE'+ else answer = object(jev.answers).who as JevChoiceAnswer | undefined+ }+ const verdict = decide(choice, answer, unavailable)+ const recorded = await scoped({ action: 'command', operationId: `route-${newId()}`,+ command: { type: 'route.record', conversationId: input.conversationId, decision: recordOf(choice, verdict, assessment, policy) } })+ const routeDecisionId = recorded.ok === true ? object(object(recorded.value).result).routeDecisionId : undefined+ const publicOf = (s: typeof verdict.pick) => ({ id: s.id, kind: s.kind, ...(s.agentId ? { agentId: s.agentId } : {}), machineId: s.machineId,+ engine: s.engine, model: s.model, effort: s.effort, title: s.title })+ return {+ ok: true, ...(typeof routeDecisionId === 'string' ? { routeDecisionId } : { unrecorded: true }),+ pick: publicOf(verdict.pick), via: verdict.via, p: verdict.p, belowFloor: choice.belowFloor, why: verdict.why,+ alternatives: choice.shown.filter(s => s.id !== verdict.pick.id).slice(0, 2).map(publicOf),+ warnings: Array.isArray(effective.warnings) ? effective.warnings : [],+ next: verdict.pick.kind === 'member'+ ? `Assign with: command OPERATION_ID {"type":"work.assign","conversationId":"${input.conversationId}","agentId":"${verdict.pick.agentId}","routeDecisionId":"${routeDecisionId ?? ''}"}`+ : `Start with: start OPERATION_ID {..., "machineId":"${verdict.pick.machineId}","engine":"${verdict.pick.engine}","model":"${verdict.pick.model}","effort":"${verdict.pick.effort}","routeDecisionId":"${routeDecisionId ?? ''}"}, then assign the started agent with the same routeDecisionId.`,+ }+}++async function probeMachine(machineId: string, machineName: string, members: Json[], models: Policy['models'], policy: Policy,+ a: Assessment, where: Where, open: typeof openDaemon): Promise<Probe[]> {+ const engines = [...new Set([...models.map(m => m.engine), ...members.map(m => String(object(m.configuration).engine) as 'claude' | 'codex')])]+ const memberProbe = (m: Json, refusals: string[], quota = { known: false, leftPercent: null, resetsAt: null } as Probe['quota']): Probe => {+ const c = object(m.configuration), engine = String(c.engine) as 'claude' | 'codex'+ const model = typeof c.model === 'string' ? c.model : null, effort = typeof c.effort === 'string' ? c.effort : null+ return { kind: 'member', agentId: String(m.id), name: String(m.name ?? 'Member'), machineId, machineName, engine,+ model: model ?? 'default', effort: effort ?? 'default', ...rateFor(policy, engine, model, effort),+ quota, activity: 'idle', known: quota.known, refusals }+ }+ const newProbe = (m: Policy['models'][number], refusals: string[], quota: Probe['quota'], known: boolean): Probe => ({+ kind: 'new', machineId, machineName, engine: m.engine, model: m.model, effort: m.effort, quality: m.quality, cost: m.cost,+ quota, activity: 'new agent', known, refusals })+ let target: Daemon+ try { target = await open(where, machineId) } catch {+ return [...members.map(m => memberProbe(m, [OFFLINE])), ...models.map(m => newProbe(m, [OFFLINE], { known: false, leftPercent: null, resetsAt: null }, false))]+ }+ try {+ const listed = object(await target.request('agents_list', {}, 10_000).catch(() => ({})))+ const live = new Set((Array.isArray(listed.agents) ? listed.agents.map(object) : [])+ .filter(f => object(f.terminal).available !== false).map(f => String(f.id)))+ const byEngine = new Map<string, Awaited<ReturnType<typeof inspectCapacity>>>()+ for (const engine of engines) {+ byEngine.set(engine, await inspectCapacity(target, { engine, cwd: a.needs.cwd ?? '/', worktree: false,+ requirements: { memoryBytes: 0, diskBytes: 0, maxCpuPercent: 100, tools: a.needs.tools, devices: a.needs.devices, quotaRequired: false } }))+ }+ const probes: Probe[] = []+ for (const m of members) {+ const inspected = byEngine.get(String(object(m.configuration).engine))!+ const quota = quotaOf2(inspected.quota)+ const refusals = [+ ...(live.has(String(m.harnessId)) ? [] : ['Its terminal is not running.']),+ ...inspected.reasons.filter(r => /usage window|Required tool|Required device/.test(r)),+ ]+ probes.push(memberProbe(m, refusals, quota))+ }+ for (const m of models) {+ const inspected = byEngine.get(m.engine)!+ probes.push(newProbe(m, inspected.allowed ? [] : inspected.reasons, quotaOf2(inspected.quota), inspected.unknown.length === 0 && inspected.quota.known))+ }+ return probes+ } finally { target.close() }+}+```++Add `'src/superTabs/routeCommand.ts'` to `FILES` in `cli/vitest.super-tabs.config.ts`.++- [ ] **Step 8: Wire the verb** (`cli/src/superTabs/command.ts`)++Update `USAGE` to add `| route GROUP JSON`. In the parser, before the final `else if (!['status', 'help']...)`:++```ts+else if (action === 'route' && identifier(first) && second && positional.length === 3) {+ Object.assign(payload, { conversationId: first, assessment: JSON.parse(second) })+}+```++In `superTabCommand`, beside the `capacity` branch:++```ts+} 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)+```++Add `import { routeTask } from './routeCommand.js'`. In `command.spec.ts`, add `['route', 'g1']` and `['route', '../x', '{}']` to the invalid-argv list, and one valid parse test:++```ts+ it('parses route GROUP JSON', () => {+ expect(parseSuperTabArgs(['--tab', 'tab', 'route', 'g1', '{"difficulty":"low","risk":"low","why":"x"}']).payload)+ .toMatchObject({ action: 'route', conversationId: 'g1', assessment: { difficulty: 'low' } })+ })+```++(Use the parser's real exported name in `command.ts`; the spec file already imports it.)++- [ ] **Step 9: Start passthrough and model application** (`cli/src/superTabs/start.ts`)++In `startAgent`, replace the `agent.start` command build:++```ts+ if (input.action === 'start') {+ const { routeDecisionId, overrideReason, ...request } = object(input.request)+ const result = requireSuccess(await scoped({ action: 'command', operationId: input.operationId,+ command: { type: 'agent.start', request, ...(routeDecisionId ? { routeDecisionId } : {}), ...(overrideReason ? { overrideReason } : {}) } }))+ startId = object(result.result).startId+ }+```++After `if (native.state !== 'created') return {...}` and before reading `frame.selectedModel`:++```ts+ // agent_create takes no model or effort; a routed start applies them through the+ // ordinary runtime switch. `default` keeps what the engine launched with.+ let modelWarning: string | undefined+ const model = text(request.model), effort = text(request.effort)+ if (model && effort && !(model === 'default' && effort === 'default')) {+ const reply = await target.request('agent_update', { agentId: nativeId,+ selectedModel: encodeRuntimeProfile({ sessionId: String(nativeId), engine: String(request.engine) as never, model, effort: effort as never }) }, 60_000).catch(() => ({ error: 'MODEL_UNAVAILABLE' }))+ if (reply.error) modelWarning = `Started with the engine's own model; switching to ${model} ${effort} failed (${String(reply.error)}).`+ else Object.assign(frame, object(reply.agent))+ }+```++Add `...(modelWarning ? { modelWarning } : {})` to the final success return, and `import { encodeRuntimeProfile } from '../engines/kit/runtime.js'`.++Add tests to `start.spec.ts` with its existing fake daemon:+- a start with `routeDecisionId` and `overrideReason` sends them at the command's top level and not inside `request`;+- a start with `model: 'opus', effort: 'high'` calls `agent_update` with `selectedModel: 'runtime-v1:<harnessId>:claude:opus@high'`;+- `model: 'default', effort: 'default'` makes no `agent_update` call;+- an `agent_update` error returns `ok: true` with `modelWarning`.++- [ ] **Step 10: Run CLI checks**++Run: `cd cli && npx tsc --noEmit -p . && npm run test:super-tabs && npx vitest run src/superTabs && npm run test:core`+Expected: all PASS; `test:super-tabs` at 100% for both files.++- [ ] **Step 11: Commit**++```bash+git add cli+git commit -m "Super Tab routing: the route command, Jev and the routed start"+```++---++### Task 7: Lead instructions and the end-to-end route++**Files:**+- Modify: `desktop/lib/super_tabs/launch.dart` (Lead prompt, around lines 120–141)+- Modify: `cli/src/superTabs/host.ts` (`prompt()`, around line 318)+- Modify: `cli/e2e/harness/fakeBackend.ts` (add `/api/route/jev`)+- Create: `cli/e2e/superTabRoute.e2e.ts`+- Test: `desktop/test/super_tab_launch_test.dart` (prompt assertion)++**Interfaces:**+- Consumes: `harness super-tab route` (Task 6); backend shapes from Tasks 2–4.+- Produces: the Lead prompt line and the delivery prompt line naming `route`.++- [ ] **Step 1: Write the failing prompt test** (append to `desktop/test/super_tab_launch_test.dart`, next to the existing assertions on the Lead prompt text)++```dart+ test('the Lead prompt routes before starting or assigning work', () {+ final prompt = superTabLeadPromptForTest(tabId: 'tab'); // use the file's existing prompt builder or test seam+ expect(prompt, contains('route GROUP'));+ expect(prompt, contains('routeDecisionId'));+ expect(prompt, contains('overrideReason'));+ });+```++If `launch.dart` has no test seam for the prompt, assert on the prompt captured by the existing launch test's fake connection (`agent_create` payload `prompt`).++- [ ] **Step 2: Run to verify it fails**++Run: `cd desktop && flutter test test/super_tab_launch_test.dart`+Expected: FAIL (text missing).++- [ ] **Step 3: Add the instruction**++In `launch.dart`, after the sentence that begins `'For work groups, assignments, acceptance evidence and messages to other agents, use `$command help`. '`, add for the Lead variant:++```dart+'Before starting or assigning work, run `$command route GROUP JSON` with your difficulty and risk assessment, '+'then start or assign its pick with the routeDecisionId it returns. To choose otherwise, pass overrideReason. '+'If it answers NO_CANDIDATE, tell the person in the group why, using its reasons; do not guess another machine. '+```++Add one `routeCommand.spec.ts` case for the history line: a group whose `assignment` is `{id:'x', agentId:'a1', status:'stopped', result:'Tests failed.'}` makes the `routeJev` payload's `state.history` contain `Multiply: stopped — Tests failed.`.++In `host.ts` `prompt()`, change `Manage agreed work and delegation: ${command} help.` to `Manage agreed work and delegation: ${command} help. Route before starting or assigning: ${command} route GROUP JSON.`, and update the matching expectation in `host.spec.ts` if one asserts that sentence.++- [ ] **Step 4: Run the prompt tests**++Run: `cd desktop && flutter test test/super_tab_launch_test.dart && cd ../cli && npx vitest run src/superTabs/host.spec.ts`+Expected: PASS.++- [ ] **Step 5: Add the fake Jev route** (`cli/e2e/harness/fakeBackend.ts`)++Next to the `/api/experimental-settings` handler, add a public field and handler:++```ts+ /** `POST /api/route/jev`, Harness's hosted Jev. Unset answers 503 JEV_BUSY, which callers treat as unavailable. */+ jev: ((body: Record<string, any>) => Record<string, unknown>) | null = null+// in the request handler:+ if (req.url?.split('?')[0] === '/api/route/jev' && req.method === 'POST') {+ const body = await readJson(req) // use the file's existing body reader+ if (!backend.jev) return send(res, 503, { success: false, error: { code: 'JEV_BUSY', message: 'Fixture Jev is off.' } })+ return send(res, 200, { success: true, data: backend.jev(body) })+ }+```++Use the file's real helpers for reading JSON and sending replies (the `/api/experimental-settings` handler shows them).++- [ ] **Step 6: Write the e2e test** (`cli/e2e/superTabRoute.e2e.ts`)++Model the setup on the first test in `cli/e2e/superTabs.e2e.ts` (same `ME`, `FakeBackend.start()`, `IsolatedDaemon.create(...)`, session file, `relay.superTabs` handler). The `relay.superTabs` handler must answer:++- `GET /api/super-tabs/TAB?asAgentId=…` → `{ data: { revision, state } }` with one idle member (a fake Claude harness created in the daemon, as the existing test creates one) and a group `g1` with a brief and one check;+- `GET /api/super-tabs/TAB/routing-policy?asAgentId=…` → `{ data: { policy: <Claude-only policy: sonnet medium q2 c2, opus high q3 c3>, warnings: [], overridden: [] } }`;+- `POST /api/super-tabs/TAB/commands` with `command.type === 'route.record'` → push the body to `records` and return `{ data: { revision, result: { routeDecisionId: 'd-' + records.length } } }`.++Two cases:++```ts+it('routes to Jev’s pick and records the decision', async () => {+ // setup as above; relay.jev = body => ({ who: { choice: 'c1', probabilities: { c0: 0.1, c1: 0.9 } } })+ const code = await superTabCommand({ argv: ['--tab', TAB, '--agent', leadAgentId, 'route', 'g1', JSON.stringify({ difficulty: 'medium', risk: 'low', why: 'Endpoint.' })] }, deps)+ expect(code).toBe(0)+ expect(records).toHaveLength(1)+ expect(records[0].command.decision).toMatchObject({ via: 'jev', pick: 'c1' })+})+it('falls back to the policy order when Jev is unavailable', async () => {+ // relay.jev = null+ // same call; expect records[0].command.decision.via === 'order' and pick === 'c0'+})+```++Call `superTabCommand` the way `superTabs.e2e.ts` does (its `deps`/printing capture), and read the printed JSON to assert `ok: true` and `routeDecisionId`.++- [ ] **Step 7: Run the e2e test**++Run: `cd cli && npx vitest run -c vitest.e2e.config.ts e2e/superTabRoute.e2e.ts`+Expected: 2 PASS. (Uses a private tmux server and data dir; never the developer's daemon.)++- [ ] **Step 8: Commit**++```bash+git add desktop/lib/super_tabs/launch.dart desktop/test/super_tab_launch_test.dart cli/src/superTabs/host.ts cli/src/superTabs/host.spec.ts cli/e2e+git commit -m "Super Tab routing: Lead instructions and an end-to-end route"+```++---++## Phase C — Desktop++### Task 8: Route rows and Change++**Files:**+- Create: `desktop/lib/super_tabs/route_row.dart`+- Modify: `desktop/lib/super_tabs/model.dart` (route getters on `SuperTabMessage`)+- Modify: `desktop/lib/super_tabs/view.dart` (`_message`, around line 1009)+- Test: `desktop/test/super_tab_route_test.dart`++**Interfaces:**+- Consumes: message `source` shapes from Tasks 3–4; `SuperTabController.command(Map)` and `request(method, path)`; `c.canWrite`.+- Produces:+ - `SuperTabMessage.route` → `SuperTabRoute?` (`decisionId`, `via`, `p`, `belowFloor`, `why`, `pick`, `alternatives`), `SuperTabMessage.routeOverride` → `bool`.+ - `SuperTabRouteRow({required SuperTabMessage message, required SuperTabRoute route, required SuperTabController controller})`.++- [ ] **Step 1: Write the failing widget tests**++```dart+// desktop/test/super_tab_route_test.dart+import 'package:flutter/material.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness/super_tabs/model.dart';+import 'package:harness/super_tabs/route_row.dart';++import 'super_tab_launch_test.dart' show SuperTabLaunchFixture, tabId;++Map<String, dynamic> routeRow({String via = 'jev', double? p = 0.82, bool belowFloor = false}) => {+ 'id': 'm1', 'conversationId': 'offline', 'text': 'Routed to Multiply', 'replyTo': null, 'sequence': 4,+ 'author': {'kind': 'agent', 'id': 'lead', 'name': 'Lead'}, 'deliveries': const [],+ 'source': {'kind': 'route', 'decisionId': 'd1', 'via': via, 'p': p, 'belowFloor': belowFloor, 'why': 'schema change, high risk',+ 'pick': {'id': 'c0', 'title': 'Multiply · Claude opus high · remote-1'},+ 'alternatives': [{'id': 'c1', 'title': 'New agent · Claude sonnet medium · mac'}]},+};++void main() {+ test('parses route sources', () {+ final message = SuperTabMessage.fromJson(routeRow());+ expect(message.route!.decisionId, 'd1');+ expect(message.route!.alternatives.single.title, startsWith('New agent'));+ expect(SuperTabMessage.fromJson({...routeRow(), 'source': {'kind': 'route-override', 'decisionId': 'd1', 'by': 'lead'}}).routeOverride, isTrue);+ expect(SuperTabMessage.fromJson({...routeRow(), 'source': {'kind': 'route', 'decisionId': 'd1'}}).route, isNull);+ });++ for (final c in [+ (via: 'jev', p: 0.82, below: false, text: 'Jev 82%'),+ (via: 'order', p: null, below: false, text: 'by policy order'),+ (via: 'only', p: null, below: true, text: 'Below quality floor'),+ ]) {+ testWidgets('renders ${c.via}', (tester) async {+ final f = SuperTabLaunchFixture();+ final controller = await f.app.superTabs.open(tabId);+ final message = SuperTabMessage.fromJson(routeRow(via: c.via, p: c.p, belowFloor: c.below));+ await tester.pumpWidget(MaterialApp(home: Scaffold(body: SuperTabRouteRow(message: message, route: message.route!, controller: controller))));+ expect(find.textContaining('Routed to Multiply · Claude opus high · remote-1'), findsOneWidget);+ expect(find.textContaining(c.text), findsOneWidget);+ f.app.superTabs.dispose();+ });+ }++ testWidgets('Change needs write access and a reason, then sends route.override', (tester) async {+ final f = SuperTabLaunchFixture();+ final controller = await f.app.superTabs.open(tabId);+ await controller.refresh();+ final message = SuperTabMessage.fromJson(routeRow());+ await tester.pumpWidget(MaterialApp(home: Scaffold(body: SuperTabRouteRow(message: message, route: message.route!, controller: controller))));+ await tester.tap(find.text('Change'));+ await tester.pumpAndSettle();+ await tester.tap(find.textContaining('New agent · Claude sonnet medium · mac'));+ await tester.pumpAndSettle();+ final confirm = find.widgetWithText(FilledButton, 'Change');+ expect(tester.widget<FilledButton>(confirm).onPressed, isNull);+ await tester.enterText(find.byType(TextField), 'Opus quota is needed elsewhere.');+ await tester.pump();+ await tester.tap(confirm);+ await tester.pumpAndSettle();+ final sent = f.connection.calls.where((call) => (call.$2['path'] as String?)?.endsWith('/commands') == true).last.$2['body'] as Map;+ expect(sent['command'], {'type': 'route.override', 'decisionId': 'd1', 'candidateId': 'c1', 'reason': 'Opus quota is needed elsewhere.'});+ f.app.superTabs.dispose();+ });++ testWidgets('a viewer sees no Change', (tester) async {+ final f = SuperTabLaunchFixture();+ (f.connection.server.state['people'] as List)[0]['role'] = 'viewer';+ final controller = await f.app.superTabs.open(tabId);+ await controller.refresh();+ final message = SuperTabMessage.fromJson(routeRow());+ await tester.pumpWidget(MaterialApp(home: Scaffold(body: SuperTabRouteRow(message: message, route: message.route!, controller: controller))));+ expect(find.text('Change'), findsNothing);+ f.app.superTabs.dispose();+ });++ testWidgets('Change shows the refusal', (tester) async {+ final f = SuperTabLaunchFixture();+ f.connection.server.refuse = {'code': 'ROUTE_CLOSED', 'message': 'This routing decision is no longer open. Route the task again.'};+ final controller = await f.app.superTabs.open(tabId);+ await controller.refresh();+ final message = SuperTabMessage.fromJson(routeRow());+ await tester.pumpWidget(MaterialApp(home: Scaffold(body: SuperTabRouteRow(message: message, route: message.route!, controller: controller))));+ await tester.tap(find.text('Change'));+ await tester.pumpAndSettle();+ await tester.tap(find.textContaining('New agent'));+ await tester.pumpAndSettle();+ await tester.enterText(find.byType(TextField), 'Because.');+ await tester.pump();+ await tester.tap(find.widgetWithText(FilledButton, 'Change'));+ await tester.pumpAndSettle();+ expect(find.textContaining('no longer open'), findsOneWidget);+ f.app.superTabs.dispose();+ });+}+```++`SuperTabLaunchFixture`'s fake server (`super_tab_launch_test.dart`) may need a `refuse` field that makes the next `/commands` POST answer `{ok: false, error: code, detail: message}` the way the controller's other refusal tests expect; add it there if missing. Use how the controller surfaces command errors (`controller.error` or its snackbar) as the existing `super_tab_chat_test.dart` does.++- [ ] **Step 2: Run to verify failure**++Run: `cd desktop && flutter test test/super_tab_route_test.dart`+Expected: FAIL (missing file).++- [ ] **Step 3: Implement**++`model.dart` additions:++```dart+class SuperTabRouteChoice {+ const SuperTabRouteChoice(this.id, this.title);+ final String id, title;+}++class SuperTabRoute {+ SuperTabRoute._(this.decisionId, this.via, this.p, this.belowFloor, this.why, this.pick, this.alternatives);+ static SuperTabRoute? fromSource(Map<String, dynamic> s) {+ final pick = superTabMap(s['pick'] ?? const {});+ if (s['kind'] != 'route' || s['decisionId'] is! String || pick['id'] is! String || pick['title'] is! String) return null;+ return SuperTabRoute._(+ s['decisionId'] as String, s['via'] as String? ?? 'order', (s['p'] as num?)?.toDouble(), s['belowFloor'] == true,+ s['why'] as String? ?? '', SuperTabRouteChoice(pick['id'] as String, pick['title'] as String),+ [for (final a in (s['alternatives'] as List? ?? const []))+ if (a is Map && a['id'] is String && a['title'] is String) SuperTabRouteChoice(a['id'] as String, a['title'] as String)],+ );+ }+ final String decisionId, via, why;+ final double? p;+ final bool belowFloor;+ final SuperTabRouteChoice pick;+ final List<SuperTabRouteChoice> alternatives;+}+// in SuperTabMessage:+ SuperTabRoute? get route => SuperTabRoute.fromSource(source);+ bool get routeOverride => source['kind'] == 'route-override';+```++`route_row.dart`:++```dart+import 'dart:async';++import 'package:flutter/material.dart';++import '../widgets/desktop_chrome.dart';+import 'controller.dart';+import 'model.dart';++/// One routing decision in the conversation: who was chosen, how, and why.+/// Writers can change it afterwards; the Lead is told to hand the task over.+class SuperTabRouteRow extends StatefulWidget {+ const SuperTabRouteRow({super.key, required this.message, required this.route, required this.controller});+ final SuperTabMessage message;+ final SuperTabRoute route;+ final SuperTabController controller;+ @override+ State<SuperTabRouteRow> createState() => _SuperTabRouteRowState();+}++class _SuperTabRouteRowState extends State<SuperTabRouteRow> {+ Map<String, dynamic>? _details;+ bool _expanded = false;++ String get _how => switch (widget.route.via) {+ 'jev' => 'Jev ${((widget.route.p ?? 0) * 100).round()}%',+ 'only' => 'only candidate',+ _ => widget.route.why.startsWith('Jev unavailable') ? 'by policy order (Jev unavailable)' : 'by policy order (Jev unsure)',+ };++ Future<void> _toggle() async {+ setState(() => _expanded = !_expanded);+ if (!_expanded || _details != null) return;+ try {+ final answer = await widget.controller.request('GET', '/api/super-tabs/${widget.controller.tabId}/route-decisions/${widget.route.decisionId}');+ if (mounted) setState(() => _details = answer);+ } catch (_) {+ if (mounted) setState(() => _details = const {'error': true});+ }+ }++ Future<void> _change() async {+ final choice = await showDialog<(SuperTabRouteChoice, String)>(context: context, builder: (_) => _ChangeDialog(route: widget.route));+ if (choice == null || !mounted) return;+ final messenger = ScaffoldMessenger.maybeOf(context);+ try {+ await widget.controller.command({'type': 'route.override', 'decisionId': widget.route.decisionId, 'candidateId': choice.$1.id, 'reason': choice.$2});+ final error = widget.controller.error; // use the controller's real error field+ if (error != null) messenger?.showSnackBar(SnackBar(content: Text(error)));+ } catch (failure) {+ messenger?.showSnackBar(SnackBar(content: Text(failure.toString())));+ }+ }++ @override+ Widget build(BuildContext context) {+ final r = widget.route;+ return Padding(+ padding: const EdgeInsets.symmetric(vertical: 4),+ child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [+ Wrap(spacing: 8, crossAxisAlignment: WrapCrossAlignment.center, children: [+ InkWell(onTap: _toggle, child: Text('Routed to ${r.pick.title} — $_how · "${r.why}"', style: DesktopChrome.metadata())),+ if (r.belowFloor)+ Container(+ padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),+ decoration: BoxDecoration(color: Colors.amber.withValues(alpha: 0.2), borderRadius: BorderRadius.circular(4)),+ child: Text('Below quality floor', style: DesktopChrome.metadata()),+ ),+ if (widget.controller.canWrite && r.alternatives.isNotEmpty)+ TextButton(onPressed: () => unawaited(_change()), child: const Text('Change')),+ ]),+ if (_expanded) _detailsView(),+ ]),+ );+ }++ Widget _detailsView() {+ final d = _details;+ if (d == null) return const Padding(padding: EdgeInsets.all(8), child: LinearProgressIndicator());+ if (d['error'] == true) return Text('Could not load this decision.', style: DesktopChrome.metadata());+ final record = superTabMap(d['record'] ?? const {});+ final candidates = (record['candidates'] as List? ?? const []).map((c) => superTabMap(c));+ final excluded = (record['excluded'] as List? ?? const []).map((c) => superTabMap(c));+ return Padding(+ padding: const EdgeInsets.only(left: 12, top: 4),+ child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [+ Text('Quality floor ${record['floor']}${record['notes'] == true ? ' · policy notes applied' : ''}', style: DesktopChrome.metadata()),+ for (final c in candidates) Text('${c['id']}: ${c['label']}', style: DesktopChrome.metadata()),+ for (final e in excluded) Text('Not possible: ${e['title']} — ${e['reason']}', style: DesktopChrome.metadata()),+ ]),+ );+ }+}++class _ChangeDialog extends StatefulWidget {+ const _ChangeDialog({required this.route});+ final SuperTabRoute route;+ @override+ State<_ChangeDialog> createState() => _ChangeDialogState();+}++class _ChangeDialogState extends State<_ChangeDialog> {+ SuperTabRouteChoice? _choice;+ final _reason = TextEditingController();+ @override+ void dispose() { _reason.dispose(); super.dispose(); }+ @override+ Widget build(BuildContext context) {+ final ready = _choice != null && _reason.text.trim().isNotEmpty && _reason.text.trim().length <= 300;+ return AlertDialog(+ title: const Text('Change who does this task'),+ content: SizedBox(width: 480, child: Column(mainAxisSize: MainAxisSize.min, children: [+ for (final a in widget.route.alternatives)+ RadioListTile<SuperTabRouteChoice>(value: a, groupValue: _choice, title: Text(a.title), onChanged: (v) => setState(() => _choice = v)),+ TextField(controller: _reason, maxLength: 300, decoration: const InputDecoration(labelText: 'Reason'), onChanged: (_) => setState(() {})),+ ])),+ actions: [+ TextButton(onPressed: () => Navigator.of(context).pop(), child: const Text('Cancel')),+ FilledButton(onPressed: ready ? () => Navigator.of(context).pop((_choice!, _reason.text.trim())) : null, child: const Text('Change')),+ ],+ );+ }+}+```++`controller.tabId`, `controller.request`, `controller.command` and `canWrite` exist (`controller.dart`). Replace `widget.controller.error` with how `SuperTabController` exposes the last command failure (read `retry()` in `controller.dart`).++In `view.dart` `_message(...)`, return the route row first:++```dart+ final route = message.route;+ if (route != null) {+ return SuperTabRouteRow(key: ValueKey('super-message-${message.id}'), message: message, route: route, controller: c);+ }+```++Override messages (`routeOverride`) render as ordinary rows; their text already names who chose what and why.++- [ ] **Step 4: Run tests**++Run: `cd desktop && flutter analyze lib/super_tabs test/super_tab_route_test.dart && flutter test test/super_tab_route_test.dart test/super_tab_chat_test.dart test/super_tab_view_test.dart`+Expected: no analyzer issues; all PASS.++- [ ] **Step 5: Commit**++```bash+git add desktop/lib/super_tabs desktop/test/super_tab_route_test.dart desktop/test/super_tab_launch_test.dart+git commit -m "Super Tab routing: route rows, details and Change"+```++---++### Task 9: Routing policy forms (Settings ▸ Routing and the Super Tab override)++**Files:**+- Create: `desktop/lib/super_tabs/routing_policy.dart`, `desktop/lib/super_tabs/routing_policy_form.dart`, `desktop/lib/settings/sections/routing_section.dart`+- Modify: `desktop/lib/settings/settings_section.dart`, `desktop/lib/settings/settings_body.dart`, `desktop/lib/super_tabs/view.dart` (sidebar footer, lines ~762–788)+- Test: `desktop/test/routing_policy_test.dart`, `desktop/test/settings_section_test.dart`++**Interfaces:**+- Consumes: backend `GET/POST /api/super-tabs/routing-policy`, `GET /api/super-tabs/:tabId/routing-policy`, command `tab.routingPolicy` (Task 2); `app.superTabs.map(method, path, {body})` (`SuperTabClient`).+- Produces:+ - `RoutingPolicy` (Dart) with `fromJson`, `toJson`, `copyWith`; `RoutingModel`.+ - `RoutingPolicyForm({required RoutingPolicy value, required ValueChanged<RoutingPolicy> onChanged, Set<String>? overridden, ValueChanged<String>? onUseDefault, bool readOnly = false})`.+ - `SettingsSection.routing` in the Agents group.+ - `showSuperTabRouting(BuildContext, SuperTabController, SuperTabClient)`.++- [ ] **Step 1: Write the failing tests**++```dart+// desktop/test/routing_policy_test.dart+import 'package:flutter/material.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness/super_tabs/routing_policy.dart';+import 'package:harness/super_tabs/routing_policy_form.dart';++final json = {+ 'version': 1, 'floor': {'low': 1, 'medium': 2, 'high': 3}, 'quotaReserve': 10, 'notes': '',+ '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},+ ],+};++void main() {+ test('round-trips the backend policy', () {+ expect(RoutingPolicy.fromJson(json).toJson(), json);+ });++ testWidgets('edits a model, the floor, the reserve and the notes', (tester) async {+ RoutingPolicy? changed;+ await tester.pumpWidget(MaterialApp(home: Scaffold(body: SingleChildScrollView(+ child: RoutingPolicyForm(value: RoutingPolicy.fromJson(json), onChanged: (v) => changed = v)))));+ await tester.tap(find.byKey(const ValueKey('routing-model-enabled-1')));+ await tester.pump();+ expect(changed!.models[1].enabled, isFalse);+ await tester.enterText(find.byKey(const ValueKey('routing-reserve')), '25');+ await tester.pump();+ expect(changed!.quotaReserve, 25);+ await tester.enterText(find.byKey(const ValueKey('routing-notes')), 'Frontend prefers Claude.');+ await tester.pump();+ expect(changed!.notes, 'Frontend prefers Claude.');+ });++ testWidgets('override mode offers Use account default per field and read-only hides edits', (tester) async {+ final used = <String>[];+ await tester.pumpWidget(MaterialApp(home: Scaffold(body: SingleChildScrollView(child: RoutingPolicyForm(+ value: RoutingPolicy.fromJson(json), onChanged: (_) {}, overridden: const {'notes'}, onUseDefault: used.add)))));+ expect(find.text('Use account default'), findsOneWidget);+ await tester.tap(find.text('Use account default'));+ expect(used, ['notes']);+ await tester.pumpWidget(MaterialApp(home: Scaffold(body: SingleChildScrollView(child: RoutingPolicyForm(+ value: RoutingPolicy.fromJson(json), onChanged: (_) {}, readOnly: true)))));+ expect(tester.widget<Switch>(find.byKey(const ValueKey('routing-model-enabled-0'))).onChanged, isNull);+ });+}+```++In `desktop/test/settings_section_test.dart`, change the Agents group expectation to `[SettingsSection.connectors, SettingsSection.usage, SettingsSection.routing]`.++- [ ] **Step 2: Run to verify failure**++Run: `cd desktop && flutter test test/routing_policy_test.dart test/settings_section_test.dart`+Expected: FAIL.++- [ ] **Step 3: Implement the model**++```dart+// desktop/lib/super_tabs/routing_policy.dart+/// The Super Tab routing policy as the backend stores it (backend/src/superTabs/routingPolicy.ts).+class RoutingModel {+ const RoutingModel({required this.engine, required this.model, required this.effort, required this.quality, required this.cost, required this.enabled});+ factory RoutingModel.fromJson(Map<String, dynamic> j) => RoutingModel(engine: j['engine'] as String, model: j['model'] as String,+ effort: j['effort'] as String, quality: (j['quality'] as num).toInt(), cost: (j['cost'] as num).toInt(), enabled: j['enabled'] == true);+ final String engine, model, effort;+ final int quality, cost;+ final bool enabled;+ RoutingModel copyWith({int? quality, int? cost, bool? enabled}) => RoutingModel(engine: engine, model: model, effort: effort,+ quality: quality ?? this.quality, cost: cost ?? this.cost, enabled: enabled ?? this.enabled);+ Map<String, dynamic> toJson() => {'engine': engine, 'model': model, 'effort': effort, 'quality': quality, 'cost': cost, 'enabled': enabled};+ String get label => '${engine == 'claude' ? 'Claude' : 'Codex'} ${model == 'default' ? 'default model' : model}${effort == 'default' ? '' : ' $effort'}';+}++class RoutingPolicy {+ const RoutingPolicy({required this.models, required this.floor, required this.quotaReserve, required this.notes});+ factory RoutingPolicy.fromJson(Map<String, dynamic> j) {+ final floor = Map<String, dynamic>.from(j['floor'] as Map);+ return RoutingPolicy(+ models: [for (final m in j['models'] as List) RoutingModel.fromJson(Map<String, dynamic>.from(m as Map))],+ floor: {for (final k in const ['low', 'medium', 'high']) k: (floor[k] as num).toInt()},+ quotaReserve: (j['quotaReserve'] as num).toInt(), notes: j['notes'] as String? ?? '');+ }+ final List<RoutingModel> models;+ final Map<String, int> floor;+ final int quotaReserve;+ final String notes;+ RoutingPolicy copyWith({List<RoutingModel>? models, Map<String, int>? floor, int? quotaReserve, String? notes}) => RoutingPolicy(+ models: models ?? this.models, floor: floor ?? this.floor, quotaReserve: quotaReserve ?? this.quotaReserve, notes: notes ?? this.notes);+ Map<String, dynamic> toJson() => {'version': 1, 'floor': floor, 'quotaReserve': quotaReserve, 'notes': notes, 'models': [for (final m in models) m.toJson()]};+ /// Only the named fields, for a Super Tab override.+ Map<String, dynamic> fields(Set<String> names) => {for (final e in toJson().entries) if (names.contains(e.key)) e.key: e.value};+}+```++Make `toJson()` key order match the test's `json` map (Dart map equality ignores order, so `expect(..., json)` holds either way).++- [ ] **Step 4: Implement the form**++```dart+// desktop/lib/super_tabs/routing_policy_form.dart+import 'package:flutter/material.dart';+import 'package:flutter/services.dart';++import '../widgets/desktop_chrome.dart';+import 'routing_policy.dart';++/// The routing policy editor, used by Settings ▸ Routing (account default) and+/// by a Super Tab's Routing dialog (override mode, with Use account default).+class RoutingPolicyForm extends StatelessWidget {+ const RoutingPolicyForm({super.key, required this.value, required this.onChanged, this.overridden, this.onUseDefault, this.readOnly = false});+ final RoutingPolicy value;+ final ValueChanged<RoutingPolicy> onChanged;+ final Set<String>? overridden;+ final ValueChanged<String>? onUseDefault;+ final bool readOnly;++ Widget _heading(String title, String field) => Row(children: [+ Expanded(child: Text(title, style: DesktopChrome.control())),+ if (overridden?.contains(field) == true && onUseDefault != null && !readOnly)+ TextButton(onPressed: () => onUseDefault!(field), child: const Text('Use account default')),+ ]);++ Widget _number(Key key, int current, int min, int max, ValueChanged<int> set) => SizedBox(width: 72, child: TextFormField(+ key: key, initialValue: '$current', enabled: !readOnly, keyboardType: TextInputType.number,+ inputFormatters: [FilteringTextInputFormatter.digitsOnly],+ onChanged: (text) { final n = int.tryParse(text); if (n != null && n >= min && n <= max) set(n); }));++ @override+ Widget build(BuildContext context) {+ return Column(crossAxisAlignment: CrossAxisAlignment.start, children: [+ _heading('Models', 'models'),+ Text('Quality 1–3 and relative cost decide who is chosen. Turn a model off to never use it.', style: DesktopChrome.metadata()),+ for (final (i, m) in value.models.indexed)+ Row(children: [+ Switch(key: ValueKey('routing-model-enabled-$i'), value: m.enabled,+ onChanged: readOnly ? null : (on) => onChanged(value.copyWith(models: [...value.models]..[i] = m.copyWith(enabled: on)))),+ Expanded(child: Text(m.label)),+ Text('Quality ', style: DesktopChrome.metadata()),+ _number(ValueKey('routing-model-quality-$i'), m.quality, 1, 3, (q) => onChanged(value.copyWith(models: [...value.models]..[i] = m.copyWith(quality: q)))),+ Text(' Cost ', style: DesktopChrome.metadata()),+ _number(ValueKey('routing-model-cost-$i'), m.cost, 1, 100, (c) => onChanged(value.copyWith(models: [...value.models]..[i] = m.copyWith(cost: c)))),+ ]),+ const SizedBox(height: 12),+ _heading('Quality floor by difficulty', 'floor'),+ Row(children: [+ for (final level in const ['low', 'medium', 'high']) ...[+ Text('${level[0].toUpperCase()}${level.substring(1)} '),+ _number(ValueKey('routing-floor-$level'), value.floor[level]!, 1, 3, (n) => onChanged(value.copyWith(floor: {...value.floor, level: n}))),+ const SizedBox(width: 12),+ ],+ ]),+ Text('High risk raises the floor by one.', style: DesktopChrome.metadata()),+ const SizedBox(height: 12),+ _heading('Quota reserve', 'quotaReserve'),+ Row(children: [+ _number(const ValueKey('routing-reserve'), value.quotaReserve, 0, 90, (n) => onChanged(value.copyWith(quotaReserve: n))),+ const Text(' % — below this, an account is used only when nothing else can run the task.'),+ ]),+ const SizedBox(height: 12),+ _heading('Notes for Jev', 'notes'),+ TextFormField(key: const ValueKey('routing-notes'), initialValue: value.notes, enabled: !readOnly, maxLength: 500, maxLines: 3,+ decoration: const InputDecoration(hintText: 'For example: frontend prefers Claude; long jobs on remote-1.'),+ onChanged: (text) => onChanged(value.copyWith(notes: text))),+ ]);+ }+}+```++- [ ] **Step 5: Implement Settings ▸ Routing**++In `settings_section.dart`, add `routing(AppIcons.route, 'Routing', keywords: ['routing', 'models', 'quota', 'jev', 'super tab'])` (pick an existing `AppIcons` member if `route` does not exist, e.g. the one Connectors uses), and add it to the `'Agents'` group after `usage`. In `settings_body.dart`, add the `SettingsSection.routing => RoutingSection(app: ...)` case, passing what other sections receive.++```dart+// desktop/lib/settings/sections/routing_section.dart+import 'dart:async';++import 'package:flutter/material.dart';++import '../../shared/widgets/section_scaffold.dart';+import '../../state/app_state.dart';+import '../../super_tabs/routing_policy.dart';+import '../../super_tabs/routing_policy_form.dart';++/// The account's routing default for every Super Tab it owns.+class RoutingSection extends StatefulWidget {+ const RoutingSection({super.key, required this.app});+ final AppNotifier app;+ @override+ State<RoutingSection> createState() => _RoutingSectionState();+}++class _RoutingSectionState extends State<RoutingSection> {+ RoutingPolicy? _policy;+ int _revision = 0;+ String? _error;+ bool _saving = false;++ @override+ void initState() { super.initState(); unawaited(_load()); }++ Future<void> _load() async {+ try {+ final answer = await widget.app.superTabs.map('GET', '/api/super-tabs/routing-policy');+ if (!mounted) return;+ setState(() { _policy = RoutingPolicy.fromJson(Map<String, dynamic>.from(answer['policy'] as Map)); _revision = (answer['revision'] as num).toInt(); _error = null; });+ } catch (failure) {+ if (mounted) setState(() => _error = 'Could not load the routing policy. $failure');+ }+ }++ Future<void> _save() async {+ final policy = _policy;+ if (policy == null) return;+ setState(() => _saving = true);+ try {+ final answer = await widget.app.superTabs.map('POST', '/api/super-tabs/routing-policy', body: {'revision': _revision, 'policy': policy.toJson()});+ if (mounted) setState(() { _revision = (answer['revision'] as num).toInt(); _error = null; });+ } catch (failure) {+ if (mounted) setState(() => _error = 'Could not save. $failure');+ } finally {+ if (mounted) setState(() => _saving = false);+ }+ }++ @override+ Widget build(BuildContext context) {+ final policy = _policy;+ return SectionScaffold(+ title: 'Routing',+ subtitle: 'How a Super Tab Lead chooses who does each task. Each Super Tab you own can override these.',+ child: SingleChildScrollView(child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [+ if (_error != null) Padding(padding: const EdgeInsets.only(bottom: 8), child: Text(_error!)),+ if (policy == null && _error == null) const LinearProgressIndicator(),+ if (policy != null) ...[+ RoutingPolicyForm(value: policy, onChanged: (v) => setState(() => _policy = v)),+ const SizedBox(height: 12),+ FilledButton(onPressed: _saving ? null : () => unawaited(_save()), child: const Text('Save')),+ ],+ ])),+ );+ }+}+```++Use the real `SectionScaffold` import path and constructor (`shared/widgets/section_scaffold.dart`), and the real client field on `AppNotifier` (`superTabs`).++- [ ] **Step 6: Implement the Super Tab override**++In `view.dart`'s footer `Wrap`, after the Invite/People button, add:++```dart+TextButton(+ onPressed: c.snapshot != null ? () { _closeSidebar(); unawaited(showSuperTabRouting(context, c)); } : null,+ child: const Text('Routing'),+),+```++Add `showSuperTabRouting` to `route_row.dart` (it already imports the controller):++```dart+Future<void> showSuperTabRouting(BuildContext context, SuperTabController c) async {+ final answer = await c.request('GET', '/api/super-tabs/${c.tabId}/routing-policy');+ if (!context.mounted) return;+ var policy = RoutingPolicy.fromJson(superTabMap(answer['policy']));+ final overridden = {...(answer['overridden'] as List? ?? const []).cast<String>()};+ await showDialog<void>(context: context, builder: (dialogContext) => StatefulBuilder(builder: (context, update) => AlertDialog(+ title: const Text('Routing for this Super Tab'),+ content: SizedBox(width: 560, child: SingleChildScrollView(child: RoutingPolicyForm(+ value: policy, readOnly: !c.isOwner, overridden: overridden,+ onChanged: (v) => update(() { for (final f in _changedFields(policy, v)) overridden.add(f); policy = v; }),+ onUseDefault: (field) => update(() => overridden.remove(field)),+ ))),+ actions: [+ TextButton(onPressed: () => Navigator.of(dialogContext).pop(), child: Text(c.isOwner ? 'Cancel' : 'Close')),+ if (c.isOwner)+ FilledButton(onPressed: () async {+ await c.command({'type': 'tab.routingPolicy', 'policy': overridden.isEmpty ? null : policy.fields(overridden)});+ if (dialogContext.mounted) Navigator.of(dialogContext).pop();+ }, child: const Text('Save')),+ ],+ )));+}++Set<String> _changedFields(RoutingPolicy a, RoutingPolicy b) {+ final x = a.toJson(), y = b.toJson();+ return {for (final k in const ['models', 'floor', 'quotaReserve', 'notes']) if (x[k].toString() != y[k].toString()) k};+}+```++A field removed with **Use account default** keeps showing the merged value until the dialog reopens, which then reads the account value again; this is acceptable for v1.++Add a widget test to `routing_policy_test.dart` or `super_tab_route_test.dart`: open the dialog with the fixture (owner), change notes, Save → the last `/commands` body is `{'type': 'tab.routingPolicy', 'policy': {'notes': '...'}}`; as a viewer, no Save button.++- [ ] **Step 7: Run tests**++Run: `cd desktop && flutter analyze lib test && flutter test test/routing_policy_test.dart test/settings_section_test.dart test/settings_screen_test.dart test/settings_compact_test.dart test/super_tab_route_test.dart`+Expected: no analyzer issues; all PASS.++- [ ] **Step 8: Commit**++```bash+git add desktop+git commit -m "Super Tab routing: policy forms in Settings and each Super Tab"+```++---++## Phase D — Validation and delivery++### Task 10: Docs, full checks and the one manual Jev run++**Files:**+- Modify: `desktop/design/terminal-workspace.md` (one paragraph on route rows and Routing), `docs/superpowers/specs/2026-10-19-super-tab-routing-v1-design.md` (fold in the planning rulings above)++- [ ] **Step 1: Update docs**++In the spec, apply the six rulings from the top of this plan (start `model`/`effort` via `agent_update`; outcomes `done|stopped|superseded`; Lead override messages; the decision read endpoint; `/api/super-tabs/routing-policy`; member rating). In `terminal-workspace.md`, add after the Super Tab paragraph:++```+A Lead routes each delegation with `harness super-tab route`. The decision appears in the+conversation as one row (who, how — Jev's confidence or the policy order — and why); owners and+collaborators can **Change** it with a reason, which tells the Lead to hand the task over.+Settings ▸ Routing holds the account's policy; a Super Tab's **Routing** overrides single fields.+```++- [ ] **Step 2: Run the affected suites together**++Run (in parallel, within the machine's capacity):+- `cd backend && npx tsc --noEmit -p . && npm test && npm run test:super-tabs`+- `cd cli && npx tsc --noEmit -p . && npm run test:super-tabs && npm run test:core && npx vitest run src/superTabs && npx vitest run -c vitest.e2e.config.ts e2e/superTabs.e2e.ts e2e/superTabRoute.e2e.ts` (Node 24: `PATH=$(dirname $(npx -y node@24 -e 'console.log(process.execPath)')):$PATH`)+- `cd desktop && flutter analyze && flutter test test/super_tab_*_test.dart test/routing_policy_test.dart test/settings_*_test.dart test/session_close_test.dart`++Expected: all PASS. Record the counts in the PR.++- [ ] **Step 3: One manual run with the real Jev**++On a test Super Tab (not the person's working tabs), with an isolated CLI build pointed at production, ask the Lead to route a small task and confirm the conversation shows the route row with `Jev NN%`. Record the tab, the decision id and the screenshot in the PR. Do not type into the person's real harnesses.++- [ ] **Step 4: Open the PR** (only when the owner asks)++Push the branch, open the PR with the validation record, keep it draft until the owner asks to mark it ready; then follow `AGENTS.md` (CI `ci/required`, independent review, `make merge-pr`, release backend → CLI → Desktop).diff --git a/docs/superpowers/specs/2026-10-19-super-tab-routing-v1-design.md b/docs/superpowers/specs/2026-10-19-super-tab-routing-v1-design.mdnew file mode 100644index 000000000..6997c3b8f--- /dev/null+++ b/docs/superpowers/specs/2026-10-19-super-tab-routing-v1-design.md@@ -0,0 +1,354 @@+# Super Tab routing v1++Date: 2026-10-19. Status: design approved and implemented on branch `feat/super-tab-routing-v1`; not yet merged.++## Purpose++A Super Tab Lead delegates work by choosing a machine, an engine and a model itself, then calling+`harness super-tab start …` or `command {work.assign}`. Each Lead chooses differently, nothing+follows the account's cost and quality preferences, and nobody can see afterwards why a task went+where it did.++Routing v1 adds one step before a start or an assignment. The system filters out what cannot run+the task, **Jev** chooses among the rest with the full context, and a fixed policy order decides when+Jev is unsure or unavailable. The Lead still acts, and a person can change the choice later. Every+decision is logged, so routing can be measured and tuned, as the voice router was+(`cli/src/lib/routeDecide.ts`, `docs/design/2026-10-09-auto-router.md`).++### Decisions taken in discussion++- **Approach: hybrid.** Hard filter → Jev chooses with full context → fixed policy order as the+ fallback → the Lead or a person may override, with a reason. (Owner, 2026-10-19: "Jev quyết định OK,+ nhưng phải đưa nó đủ context.")+- **Policy scope (C):** an account-wide default, which each Super Tab may override.+- **Priority (D):** first the quality the difficulty needs, then the cheapest, then the most quota+ left, with reset timing breaking ties.+- **Who assesses difficulty and risk:** the Lead, who holds the task's context. Jev receives the+ Lead's assessment as input and does not guess difficulty itself.++### Success criteria++- Every Lead delegation in a Super Tab goes through `route`, and the decision is visible in the+ conversation with a one-line reason.+- Routing never blocks on Jev: with no key, no budget or a timeout, the policy order decides.+- A person can change a decision in two clicks plus a reason, and the Lead is told to hand over.+- The log holds enough to compare Jev's picks with the policy order and with task outcomes.++## Architecture and flow++```+Lead: harness super-tab route GROUP '{difficulty, risk, why, needs:{tools, devices, cwd?}}'+ 1. Collect candidates: idle members of the tab, plus "new agent" on each reachable machine for each+ model the effective policy allows.+ 2. Hard filter: offline, no permission, capacity admission refused, exhausted quota, engine missing.+ 3. Order the rest by the policy order (D). Apply the quality floor and the quota reserve (below).+ 4. Ask Jev once, with the context below, to choose among at most 12 candidates.+ 5. Read the answer; fall back to the policy order when Jev is unsure or unavailable.+ 6. Record the decision in the tab (route.record) and return it to the Lead.+Lead: start or assign the pick, passing routeDecisionId — or choose another, with a reason.+```++- `route` refuses a caller who is not the group's Lead (`LEAD_REQUIRED`). It checks the 30-per-hour+ limit before Jev is asked: the CLI counts the tab's decisions created in the last hour+ (`RATE_LIMITED`).+- The group's Lead and the tab Lead are never candidates; a Lead cannot route work to itself.+- `route` runs in the Lead's CLI, in the Super Tab service (`cli/src/superTabs/`), beside the+ existing `capacity` and `start` subcommands. It reuses the capacity reader and `admission()`+ (`cli/src/superTabs/capacity.ts`) for the hard filter, including quota windows and their reset+ times.+- Jev is asked through the existing `createJevDecide` (`cli/src/lib/jev/jevClient.ts`): the+ person's own OpenRouter key, or Harness's hosted key through `/api/route/jev`, which counts toward+ that route's existing daily budget. No new backend service.+- The Lead remains the executor. `route` only recommends; nothing starts or assigns automatically.+- The Lead's Super Tab instructions and the `harness super-tab` help gain one rule: before starting or+ assigning work, run `route`, pass its `routeDecisionId`, and give a reason when choosing otherwise.++## Policy++### Fields++Every field has a built-in default, so routing works with no setup.++| Field | Meaning | Default |+|---|---|---|+| `models` | Allowed model profiles. Each row: `engine`, `model`, `effort`, `quality` (1–3), `cost` (relative, positive integer), `enabled`. | A built-in catalog in Harness: e.g. Opus / GPT-5.x high = quality 3, Sonnet / GPT-5.x medium = 2, light models = 1. Rows can be disabled ("no Codex"). |+| `floor` | Minimum quality by the Lead's difficulty: `{low, medium, high}`. A `high` risk raises the floor by one, to at most 3. | `{low: 1, medium: 2, high: 3}` |+| `quotaReserve` | Percent of quota left below which an account is used only when nothing else remains. | `10` |+| `notes` | Free text for Jev, at most 500 characters ("frontend prefers Claude", "long jobs on remote-1"). | empty |++The policy order (D) is fixed in code and is not configurable:++1. meets the floor;+2. lowest `cost`;+3. most quota left (the account's tightest window);+4. earliest reset of that window;+5. an existing idle member before a new agent (no start cost);+6. stable by candidate id.++`notes` is how a person tells Jev what the fixed order cannot express.++### Storage and scope++- **Account default:** a new backend model `RoutingPolicy`, one document per user and environment,+ versioned JSON validated with zod on write. Read and written (GET and POST) through `/api/super-tabs/routing-policy`, so+ the Desktop and CLI reach it through the existing Super Tab backend passthrough without a new+ daemon route.+- **Tab override:** an optional `state.routingPolicy` in the Super Tab state holding only the+ overridden fields. Only the tab **owner** changes it, through a new command `tab.routingPolicy`.+- **Effective policy:** the tab owner's account default, with the tab's overridden fields replacing+ it field by field. A tab with several people follows its owner's policy, never the viewer's.+- A corrupt or unknown-version policy falls back to the built-in default, and `route` returns a+ warning with its result.++### UI++- Desktop: Settings ▸ Agents ▸ **Routing**, a short form: the model table (enabled, quality, cost),+ the three floor values, the quota reserve and the notes. It follows the desktop design system and+ `SettingRow`.+- Settings ▸ Routing holds Save back while a value is out of range.+- Super Tab: **Routing** in the sidebar footer, beside New group and Invite. It opens the same form in+ override mode; each field has **Use account default**, which shows the owner's account value for+ that field (`GET .../routing-policy` also returns `account`, the owner's account policy). Viewers and collaborators see the effective+ policy read-only.++## Jev context and reading the answer++### Before asking++- Candidates are ordered by the policy order after the hard filter.+- The list is narrowed in a fixed order: floor, then known, then reserve. Each step keeps its subset+ only if anything survives it.+- Floor: when any candidate meets the floor, **only those** are shown to Jev. When no viable+ candidate meets it, all are shown and the result is marked `belowFloor`.+- Known: a candidate whose capacity or quota could not be read is **unknown**. It is shown only when+ no known candidate remains, and never when `quotaRequired` is set (the existing admission rule).+ A member whose machine the Lead's account cannot open (a collaborator's machine, or one not in the+ account's list) is unknown, not offline. A machine the account lists as offline is not opened, and+ its members and new agents are excluded as offline. New agents are probed only on the account's+ machines, so an account machine that cannot be opened excludes them as unreachable. The account's+ machines are read through the core (the Super Tab service runs in its own process); when that list cannot+ be read, `route` adds a warning ("The account's machine list could not be read; only known machines were+ considered.") and considers the Lead's own machine and the members' machines.+- Reserve: an account below the quota reserve is shown only when no other candidate remains.+- At most **12** candidates, the first 12 in the policy order.+- With exactly **one** candidate, Jev is not asked (`via: 'only'`).++### What Jev is given++One choice question, "Which candidate should do this task?", with one criterion line per candidate.++```+state:+ task: group title, brief (cut at 2000 characters), check titles+ lead: difficulty, risk, why (at most 300 characters), needs (tools, devices)+ policy: the floor that applies, notes+ history: earlier assignments in this group (agent, outcome)+criteria:+ c0: "Member Multiply · Claude Opus high · quality 3, cost 3 · remote-1 · idle, last did+ 'API tests' · Claude quota 62% left, resets in 2h"+ c1: "New agent · Codex gpt-5 medium · quality 2, cost 1 · Mac · Codex quota 90% left,+ resets in 5 days"+```++Jev is never given people's emails, tokens, credentials or transcripts. This is the same exposure+as the voice router: the task text goes to OpenRouter, or through the backend with the hosted key.++### Reading the answer++- Jev's choice is taken at **p ≥ 0.6**, or when it **leads clearly**, by the same rule and constants+ as `jevPick` in `routeDecide.ts` → `via: 'jev'`.+- Otherwise the first candidate in the policy order is taken → `via: 'order'`, reason "Jev unsure".+- When Jev cannot be asked (no key, hosted budget spent, 3-second timeout) → the policy order, with+ reason "Jev unavailable". No retry. Routing never waits on Jev beyond the timeout. A timeout+ reports `TIMEOUT` as the reason; other failures report `UNAVAILABLE`.+- A choice outside the candidates, or broken probabilities, counts as unsure.+- Reset times in the criterion lines are given as how far away they are ("resets in 2h"), because+ Jev does not know the current time.+- The result: `routeDecisionId`, `pick`, `via`, `p`, `belowFloor`, `why` (one sentence),+ `alternatives` (the next two in the policy order), `warnings`.+- Cost: exactly one Jev call per `route` (about 0.6 s).+- `next` for a new agent is a complete start JSON: `conversationId`, a sample `name`, the task's `cwd` (else a+ placeholder path), `worktree`, `requirements` (the help's defaults, with the task's `needs.tools` added and+ `needs.devices` set), and the pick's machine,+ engine, model and effort, with `routeDecisionId` only when the decision was recorded. The capacity probe+ uses the same requirements (memory, disk, tools, devices; quota stays optional; CPU is not capped, because it is only a momentary reading and a busy machine would refuse every candidate), so a pick the+ route admitted is admitted again by the start it suggests.++## Log, override and the Desktop++### The decision log++A new backend collection `SuperTabRouteDecision`, kept apart from the tab state so the state stays+small. Each record holds:++- `tabId`, `conversationId`, `createdAt`;+- the Lead's assessment (difficulty, risk, why);+- the candidates shown to Jev (id and criterion line), and the filtered-out ones with their reasons;+- the effective policy's floor and whether `notes` were set;+- `pick`, `via`, `p`, `belowFloor`;+- `final`: who was actually started or assigned. For a started agent whose routed model switch failed, `model`+ and `effort` are what actually runs and `requested` keeps the routed pair;+- `override`: by whom (the Lead or a person) and the reason;+- `outcome`: `done`, `stopped` or `superseded`, with its time. A person's or Lead's change of+ choice is recorded in `override`, never as an outcome; a new route supersedes.++Writes and links:++- The Lead records a decision with a new command `route.record`, authorized like the other agent+ commands. Only transport failures make a result `unrecorded`; any other refusal of the record is+ returned to the Lead as an error.+- `work.assign` and `agent.start` accept an optional `routeDecisionId`. The backend fills `final`. A+ `final` that differs from `pick` without an `overrideReason` is refused with+ `OVERRIDE_REASON_REQUIRED`.+- A start request carries optional `model` and `effort`. A routed Claude start launches the agent with them as+ launch arguments that apply to that session only: `agent_create` accepts optional `model` and `effort`, and+ Claude Code is started with `--model <model> --effort <effort>` (`claude --help`: "for the current session").+ Nothing is typed into the pane and nothing is written to the person's Claude settings. This replaces typing+ `/model`, which Claude Code saves as the default model in its `settings.json`, and which also cost about 13 s+ of retries (manual run 2). `default` for the model, and `default` or `auto` for the effort, add no flag.+ - The daemon takes them only for an engine whose launch contract declares the flags (`modelArgs`; now Claude).+ Any other engine, and a Claude whose `--help` lacks `--model` or `--effort` (read through the permission-flag+ probe and its cache), is answered `LAUNCH_MODEL_UNSUPPORTED`; a malformed value, an effort the flag does not+ take, or any of them beside a grid model, `INVALID_LAUNCH_MODEL`. Both come before a creation receipt exists.+ The values travel as separate argv items, are never part of a shell string, and are not kept on the agent's+ row. On a relaunch, `--resume` restores the session's model (`cli/src/lib/subscriptionModel.ts`), but the+ effort comes from the person's settings again. An effort of `auto` adds no flag, so the person's own+ `effortLevel` applies.+ - An older daemon would ignore the unknown payload fields and start the agent on the engine's own model. The+ agent's frame cannot tell the two apart at creation (its `selectedModel` is not yet read from the pane), so+ the daemon names the engines it launches with a model in the `launchModel` field of its `super_tabs`+ `capacity` reply, and `start.ts` sends `model` and `effort` only to a machine that lists the engine, for an+ engine that is not on a grid model. For any other start (Codex, a grid model, a daemon without the field)+ the agent is created without them and uses the post-create switch below. When a machine that was sent them+ refuses with `LAUNCH_MODEL_UNSUPPORTED` or `INVALID_LAUNCH_MODEL` (a value or a Claude build it cannot use),+ the same creation id creates the agent without them and the switch follows. A start resumed after the create+ was sent cannot know which of these happened, so it reads the agent's frame (`agents_list`): the routed pair+ (`default`, and an `auto` effort, match anything) means nothing to do; another pair runs the switch; a+ frame that cannot be read leaves the agent as it is and reports a `modelWarning`. `/model` is never typed+ without knowing the current state.+ - The post-create switch: `start.ts` first sends `agent.started`, so the agent joins the roster and the+ join turn that `agent_create` submitted can finish, and only then applies them with+ `agent_update {agentId, selectedModel}`. Until that turn ends the switch answers `BUSY`, and a fresh+ Claude answers `UNSUPPORTED_CLI_VERSION` until its first transcript records tell the daemon its CLI+ version (seen in the 2026-10-19 manual run). The daemon does not put that version on the agent's frame,+ so a known old version cannot be told from an unknown one: `start.ts` retries both every second for at+ most 60 s (for Claude only; another engine's UNSUPPORTED_CLI_VERSION is final) and returns only after the switch settled, so the Lead assigns work once the routed model is+ in place. If it still fails and the agent's frame does not show the routed pair, `start.ts` leaves the agent on the engine's own model, reports+ `modelWarning`, and corrects the decision with `route.modelResult` (below). A launched agent has no switch+ to fail, so it has no `modelWarning` and no correction; its model is observed afterwards through the+ host's `agent.configuration`. A policy row whose `model` and `effort` are both `default` launches the+ engine as configured and skips both paths; the default catalog uses `default` for Codex because its model+ slugs come from each machine's `models_cache.json`.+- A command the backend refuses as invalid names the failing field before zod's message, for example+ `command.request.requirements: Invalid input: expected object, received undefined`.+- `route.modelResult {decisionId, startId, model, effort}` is sent by the Lead's CLI only when the routed+ switch failed, with the model and effort the agent's frame (`agents_list`) shows. It is authorized like+ `route.record` (the coordinating Lead of the decision's group), needs an open decision whose `final` is+ the `new` start named by `startId` (otherwise `ROUTE_MISMATCH`), sets `final.model` and `final.effort` to+ what runs, keeps the routed pair in `final.requested`, and posts no message. Matching a later assignment to+ a candidate uses `requested` when it is there. If the frame cannot say what runs or the command fails, the+ start still succeeds and `modelWarning` adds that the decision log could not be corrected. Only the first+ `start` invocation knows the decision id, so a start resumed after an interruption is not corrected.+- Assigning an agent that was started from the decision keeps the start's `final` (engine, model and+ effort) and only adds the assignment. A direct assignment of a member records `final` as a member.+- Quality and cost of a member come from the policy row matching engine, model and effort, then+ engine and model, then the engine's `default` row. A member's model is the one its engine reported+ after work, so a Claude id (`claude-opus-4-7`, `claude-sonnet-4-5[1m]`) is first reduced to its+ family (`opus`, `sonnet`) and a Codex slug (`gpt-5.5`) falls to the `default` row. A member+ matching no row is quality 1, cost 1, so it rarely meets a floor.+- `outcome` is filled automatically when the assignment becomes `done` or `stopped`. A+ host-confirmed stop of the agent closes the linked decision too, except where a person's Change+ named another candidate than the one that was running: that stop is the handover, so the decision+ stays open with its `final` and assignment cleared, and the Lead's start or assignment of the+ chosen candidate links to it and closes it later.+- A start or assignment that names a decision whose assignment is still running is refused with+ `ROUTE_LINKED`, so a second attempt cannot overwrite the first one's `final`.+- A newer `route` for the same group supersedes the open one.+- Records are kept 90 days and read through `GET /api/super-tabs/:id/route-decisions` for analysis. A single decision is read+ through `GET /api/super-tabs/:tabId/route-decisions/:decisionId`, which expanding a route row uses. Both return+ `createdAt` and `outcomeAt` beside the record.+ v1 has no analysis screen.++### Timing: the Lead is never blocked++- The Lead runs `route`, then starts or assigns **immediately**. No approval wait.+- A person overrides **afterwards**: **Change** on the route row, then another candidate and a reason.+ The backend records the override and posts the Lead a message in the group: "[person] chose X+ instead of Y. Hand this task over to X." The Lead uses the existing handover flow: it stops the active assignment, then starts or assigns+ the chosen candidate with the same `routeDecisionId`. A Lead's own+ override also posts a message (`source.kind: 'route-override'`), because route rows are immutable+ messages.++### Desktop++- Each decision is one compact row in the conversation, in time order:+ `Routed to Multiply · Claude Opus high · remote-1 — Jev 82% · "schema change, high risk"`.+ The quoted text is the Lead's own reason (`assessment.why`), also carried as `source.why`; the+ verdict's one-sentence `why` stays in the decision record only.+ - `via: 'order'` reads "by policy order (Jev unsure)" or "(Jev unavailable)", from+ `source.fallback` (`unsure` or `unavailable`, carried by the record when the policy order decided).+ - `belowFloor` adds an amber **Below quality floor** label.+ - A Lead override is shown as a message in the conversation with the Lead's reason, beside the+ unchanged route row.+- **Change** appears only for the owner and collaborators, never for viewers. It opens a dialog that loads+ the decision record: the alternatives first, then the remaining candidates, each with its+ criterion line, leaving out the current choice. A short reason is required before confirming.+- Expanding the row reads the single decision and shows every candidate, the filtered-out ones and why, and the policy applied.+- Visible copy follows the [Naming System](../../naming-system.md).++## Errors and limits++| Situation | Handling |+|---|---|+| No candidate survives the hard filter | `route` returns `NO_CANDIDATE` with each candidate's exclusion reason. The Lead tells the person in the group and does not guess. |+| A machine's capacity or quota cannot be read | The candidate is unknown (see above). |+| Jev errors, times out, has no key or no budget | The policy order, `via: 'order'`, with the reason. No retry. |+| Jev returns an unknown choice or broken probabilities | Treated as unsure; the policy order. |+| `route.record` fails (network) | `route` still returns its result, flagged `unrecorded`. The Lead starts or assigns without a `routeDecisionId`. |+| Corrupt or unknown-version policy | The built-in default, with a warning in the result. |+| The pick disappears between `route` and the start | Existing admission refuses. The Lead runs `route` again; the old record becomes `superseded`. |+| An override names a candidate that is no longer available | Refused with a clear error; the person chooses again. |++Limits:++- at most 12 candidates shown to Jev;+- `why` at most 300 characters, the brief cut at 2000, `notes` at most 500;+- one open decision per group;+- at most 30 `route` calls per tab per hour, so a looping Lead cannot spend the Jev budget.++## Testing++- **CLI unit tests, 100% coverage for the new files** (`npm run test:core` where they fall under+ it):+ - the policy order (floor, cost, quota, reset, member before new agent);+ - `belowFloor` and the quota reserve;+ - the hard filter, one test per exclusion reason;+ - reading Jev's answer: the p threshold, a clear lead, an unknown choice, a timeout, `only`;+ - the context respects every limit and contains no email or token.+- **Backend integration (in-memory Mongo, `test:super-tabs`):**+ - the account policy and the tab override, merged field by field, owner-only;+ - `route.record`, `final`, `route.modelResult`, and `OVERRIDE_REASON_REQUIRED`;+ - automatic outcomes on `done` and `stopped`, and `superseded`;+ - a person's override posts the Lead its handover message;+ - viewers are refused, and the rate limit holds.+- **CLI end to end** (isolated daemon, `FakeBackend`, a fake Jev):+ - the Lead routes, then starts the pick;+ - Jev failing falls back to the policy order;+ - a person's override reaches the Lead.+- **Desktop widget tests:** the route row for each `via` and for `belowFloor`; **Change** only with+ permission and with a required reason; the Settings ▸ Routing form and the tab override form with+ **Use account default**.+- Tests never call the real Jev or OpenRouter. One manual run with the real Jev on a test tab is+ recorded in the PR.++## Delivery++One change, shipped complete: backend (policy, log, commands) → CLI (`route`, Lead instructions)+→ Desktop (route row, Change, forms). No part is merged on its own.++## Out of scope for v1++- Policy per group, spending caps in money, machine restrictions (machine sharing already grants or+ withholds machines).+- An approval gate before delegation.+- A statistics dashboard, and learning the policy from outcomes.