Skip to content

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

Super Tab routing: give Jev the full context for each decision (#1431)

0xken153a36b799db61
diff --git a/backend/integration/superTabs.test.ts b/backend/integration/superTabs.test.ts
index 55e9e13d7..114f02d98 100644
--- a/backend/integration/superTabs.test.ts
+++ b/backend/integration/superTabs.test.ts
@@ -393,6 +393,50 @@ describe('Super Tabs on a real Mongo replica set', () => {
expect((await db.superTabAttempt.findUnique({ where: { id: assignmentId } }))!.snapshot).toMatchObject({ assignment: { status: 'stopped', configuration: config } })
})
+ it('lists the attempts of one group, newest first, after a stop and a new definition', async () => {
+ const { tab, lead } = await fixture()
+ const worker = (await run(tab, { type: 'agent.add', conversationId: 'lead', machineId: 'test-host', harnessId: randomUUID(),
+ name: 'Builder', configuration: config, lead: false })).result.agentId as string
+ const define = (brief: string): Command => ({ type: 'work.define', conversationId: 'lead', brief, checks: [{ description: 'Test passes.', independent: false }] })
+ const attempt = async (brief: string) => {
+ await run(tab, define(brief))
+ const id = (await run(tab, { type: 'work.assign', conversationId: 'lead', agentId: worker })).result.assignmentId as string
+ await store.stopped(host, tab, id, 'native-stop-receipt')
+ return id
+ }
+ const first = await attempt('Build it.')
+ const second = await attempt('Build it again.')
+ await run(tab, define('Build it a third time.'))
+ // A host-confirmed stop sets its own result, so a long one is seeded: the server cuts it.
+ const long = randomUUID()
+ await db.superTabAttempt.create({ data: { id: long, tabId: tab, conversationId: 'lead', createdAt: new Date(0), snapshot: { assignment: {
+ id: long, agentId: worker, status: 'done', result: 'x'.repeat(900), execution: { machineId: 'test-host', harnessId: 'secret-harness', machineOwnerId: host.sub } } } } })
+ const url = `/api/super-tabs/${tab}/conversations/lead/attempts`
+ const read = (user: AuthUser, query = '') => app.inject({ url: `${url}${query}`, headers: { authorization: `Bearer ${user.sub}` } })
+ const listed = (await read(owner)).json().data
+ expect(listed.map((a: { id: string }) => a.id)).toEqual([second, first, long])
+ expect(listed[1]).toMatchObject({ id: first, agentId: worker, status: 'stopped', createdAt: expect.any(String) })
+ expect(listed[2]).toMatchObject({ id: long, status: 'done', result: 'x'.repeat(500) })
+ // Only what a reader of the group needs: no host grant, configuration or brief.
+ expect(Object.keys(listed[2]).sort()).toEqual(['agentId', 'createdAt', 'id', 'result', 'status'])
+ expect((await read(host, `?asAgentId=${lead}`)).json().data).toHaveLength(3)
+ await invite(tab, 'viewer')
+ expect((await read(peer)).statusCode).toBe(200)
+ expect((await app.inject({ url, headers: { authorization: `Bearer ${randomUUID()}` } })).statusCode).toBe(401)
+ })
+
+ it('refuses the attempts of a group to a non-member and never crosses tabs', async () => {
+ const one = await fixture()
+ const two = await fixture()
+ const group = (await run(two.tab, { type: 'conversation.create', title: 'Other work', brief: '', checks: [] })).result.conversationId as string
+ const read = (tab: string, conversation: string, user: AuthUser, query = '') =>
+ app.inject({ url: `/api/super-tabs/${tab}/conversations/${conversation}/attempts${query}`, headers: { authorization: `Bearer ${user.sub}` } })
+ expect((await read(one.tab, 'lead', peer)).statusCode).toBe(403)
+ expect((await read(one.tab, group, owner)).statusCode).toBe(404)
+ expect((await read(two.tab, group, owner)).statusCode).toBe(200)
+ expect((await read(one.tab, 'lead', host, `?asAgentId=${two.lead}`)).statusCode).not.toBe(200)
+ })
+
it('tells the lead once when the host confirms its worker stopped', async () => {
const { tab, lead } = await fixture()
const worker = (await run(tab, { type: 'agent.add', conversationId: 'lead', machineId: 'test-host', harnessId: randomUUID(),
diff --git a/backend/src/routes/superTabs.ts b/backend/src/routes/superTabs.ts
index 4bfea0688..546dfdde3 100644
--- a/backend/src/routes/superTabs.ts
+++ b/backend/src/routes/superTabs.ts
@@ -79,6 +79,9 @@ export async function superTabRoutes(app: FastifyInstance, options: { store?: Su
app.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 messageParams>; Querystring: z.infer<typeof agentQuery> }>('/api/super-tabs/:tabId/conversations/:conversationId/attempts',
+ { preHandler: [validateParams(messageParams), validateQuery(agentQuery)] },
+ (req, reply) => respond(reply, () => store.attempts(req.user!, req.params.tabId, req.params.conversationId, 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)))
diff --git a/backend/src/superTabs/commands.test.ts b/backend/src/superTabs/commands.test.ts
index 265943612..a3d5c4550 100644
--- a/backend/src/superTabs/commands.test.ts
+++ b/backend/src/superTabs/commands.test.ts
@@ -267,6 +267,17 @@ describe('route.record and route.override', () => {
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('keeps the context Jev was given with the record, bounded, and still takes a record without it', () => {
+ const f = routed()
+ const run = (decision: unknown) => f.run({ type: 'route.record', conversationId: 'lead', decision } as Command, f.leadActor, { recentRoutes: 0 })
+ expect(run(record({ context: { chars: 9000, missing: ['messages', 'activity'] } })).routeDecisions[0]).toMatchObject({ record: { context: { chars: 9000, missing: ['messages', 'activity'] } } })
+ expect(run(record()).routeDecisions[0]).toMatchObject({ record: { pick: 'c0' } })
+ for (const context of [{ chars: -1, missing: [] }, { chars: 1.5, missing: [] }, { chars: 40_000, missing: [] }, { chars: 10 },
+ { chars: 10, missing: Array.from({ length: 11 }, (_, i) => `s${i}`) }, { chars: 10, missing: ['x'.repeat(41)] }, { chars: 10, missing: [''] },
+ { chars: 10, missing: [], extra: 1 }]) {
+ expect(() => run(record({ context }))).toThrow()
+ }
+ })
it('refuses a pick outside the candidates, a non-lead agent and a busy hour', () => {
const f = routed()
const route = (decision: unknown, actor: Actor, context: Partial<CommandContext>) =>
diff --git a/backend/src/superTabs/routeRecord.ts b/backend/src/superTabs/routeRecord.ts
index ff02968a1..ed2d02d7a 100644
--- a/backend/src/superTabs/routeRecord.ts
+++ b/backend/src/superTabs/routeRecord.ts
@@ -33,6 +33,8 @@ export const routeRecordSchema = z.object({
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),
+ /** How much context Jev was given and which sources could not be read, so pick quality can later be compared with completeness. */
+ context: z.object({ chars: z.number().int().min(0).max(30_000), missing: z.array(z.string().min(1).max(40)).max(10) }).strict().optional(),
}).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.')
diff --git a/backend/src/superTabs/store.ts b/backend/src/superTabs/store.ts
index f233e53f9..99f45d4f4 100644
--- a/backend/src/superTabs/store.ts
+++ b/backend/src/superTabs/store.ts
@@ -8,7 +8,7 @@ import { applyCommand, operationSchema, type Command, type CommandContext } from
import { revokeNativeContexts, SuperTabNativeStore } from './native.js'
import {
activeWork, actorKey, agent, author, conversation, createSuperTab, fail, person, stableId, visibleState,
- SuperTabError, type Actor, type Agent, type Author, type MessageDraft, type SuperTabState,
+ SuperTabError, type Actor, type Agent, type Assignment, 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'
@@ -352,6 +352,24 @@ export class SuperTabStore {
})
}
+ /**
+ * Every earlier attempt of one group. `work.define` takes a stopped assignment out of the state, so this is the
+ * only place a reader (the Lead choosing an agent for a retry) can still see who tried and how it ended
+ * (manual run 2026-10-19). The snapshot also holds the host grant and configuration; none of it leaves here.
+ */
+ async attempts(user: AuthUser, tabId: string, conversationId: 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))
+ conversation(state, conversationId)
+ const rows = await tx.superTabAttempt.findMany({ where: { tabId, conversationId }, orderBy: { createdAt: 'desc' }, take: 50 })
+ return rows.map(row => {
+ const assignment = (row.snapshot as unknown as { assignment: Assignment }).assignment
+ return { id: row.id, agentId: assignment.agentId, status: assignment.status, result: assignment.result?.slice(0, 500) ?? null, createdAt: row.createdAt }
+ })
+ })
+ }
+
async routeDecisions(user: AuthUser, tabId: string, asAgentId?: string) {
return transaction(this.db, async tx => {
const state = stateOf(await this.row(tx, user, tabId))
diff --git a/cli/src/superTabs/capacity.spec.ts b/cli/src/superTabs/capacity.spec.ts
index b8baa14cf..3bb9f4418 100644
--- a/cli/src/superTabs/capacity.spec.ts
+++ b/cli/src/superTabs/capacity.spec.ts
@@ -19,7 +19,7 @@ it('keeps unknown quota distinct from unused quota and honors all limiting windo
const input = { providers: [{ provider: 'codex', account: 'opaque', email: '[email protected]', outcome: 'answered', httpStatus: 200,
body: { rate_limit: { primary_window: { used_percent: 10, reset_at: 1000 }, secondary_window: { used_percent: 100, reset_at: 2000 } } } }] }
const quota = quotaOf(input, 'codex', false)
- expect(quota).toEqual({ known: true, account: 'opaque', windows: [{ usedPercent: 10, resetsAt: 1000 }, { usedPercent: 100, resetsAt: 2000 }] })
+ expect(quota).toEqual({ known: true, account: 'opaque', windows: [{ usedPercent: 10, resetsAt: 1000, name: '5-hour' }, { usedPercent: 100, resetsAt: 2000, name: 'weekly' }] })
expect(quotaOf(input, 'codex', true)).toMatchObject({ known: false, account: null })
const capacity = { resources: { cpuPercent: 95, memoryTotalBytes: 1000, memoryUsedBytes: 950, projectDiskFreeBytes: 10 }, tools: {}, devices: {} }
const result = admission(capacity, { installed: true }, quota, requirements)
diff --git a/cli/src/superTabs/capacity.ts b/cli/src/superTabs/capacity.ts
index 3f678ebcd..320ac6ac2 100644
--- a/cli/src/superTabs/capacity.ts
+++ b/cli/src/superTabs/capacity.ts
@@ -58,15 +58,16 @@ const finite = (v: unknown): v is number => typeof v === 'number' && Number.isFi
* invented token counts; an unreported/custom-profile allowance is unknown. */
export function quotaOf(reply: Json, engine: string, customAccount: boolean) {
const reading = !customAccount && Array.isArray(reply.providers) ? reply.providers.map(object).find(r => r.provider === engine) : null
- const windows: Array<{ usedPercent: number; resetsAt: unknown }> = []
+ const windows: Array<{ usedPercent: number; resetsAt: unknown; name: string }> = []
if (reading?.outcome === 'answered' && reading.httpStatus === 200) {
const body = object(reading.body)
const raw = engine === 'claude' ? [body.five_hour, body.seven_day]
: engine === 'codex' ? [object(body.rate_limit).primary_window, object(body.rate_limit).secondary_window] : []
- for (const value of raw) {
+ // Both engines report the short window first and the weekly one second; the name is by that position, kept even when one is missing.
+ raw.forEach((value, index) => {
const w = object(value), used = w.utilization ?? w.used_percentage ?? w.used_percent
- if (finite(used) && used >= 0 && used <= 100) windows.push({ usedPercent: used, resetsAt: w.resets_at ?? w.reset_at ?? null })
- }
+ if (finite(used) && used >= 0 && used <= 100) windows.push({ usedPercent: used, resetsAt: w.resets_at ?? w.reset_at ?? null, name: index === 0 ? '5-hour' : 'weekly' })
+ })
}
return { known: windows.length > 0, account: typeof reading?.account === 'string' ? reading.account : null, windows }
}
diff --git a/cli/src/superTabs/route.spec.ts b/cli/src/superTabs/route.spec.ts
index 5415bfe84..31034f3a2 100644
--- a/cli/src/superTabs/route.spec.ts
+++ b/cli/src/superTabs/route.spec.ts
@@ -1,6 +1,7 @@
// cli/src/superTabs/route.spec.ts
+import { createHash } from 'node:crypto'
import { describe, expect, it } from 'vitest'
-import { choose, decide, floorFor, jevQuestion, parseAssessment, quotaOf2, rateFor, recordOf, type Assessment, type Policy, type Probe } from './route.js'
+import { choose, contextSize, decide, floorFor, jevQuestion, parseAssessment, quotaOf2, rateFor, recordOf, repoMatch, scrub, type Assessment, type MemberFrame, type Policy, type Probe, type TaskFolder } from './route.js'
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 },
@@ -31,7 +32,7 @@ describe('assessment and floor', () => {
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') })
+ .toMatchObject({ 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()
@@ -88,14 +89,21 @@ describe('choose', () => {
})
})
+const base = { title: 'T', brief: '', checks: [] as string[], messages: [] as Array<{ from: string; text: string }> | null, folder: null as TaskFolder | null,
+ attempts: [] as Array<{ agent: string; outcome: string; result?: string }>, recent: [] as Array<{ title: string; via: string; outcome: string | null }> | null }
+const ok = (r: ReturnType<typeof choose>) => { if ('error' in r) throw new Error('x'); return r }
+const frame = (patch: Partial<MemberFrame> = {}): MemberFrame => ({ title: 'Fix auth', project: 'api', cwd: '/w/api', root: '/w/api', remote: 'github.com/acme/api', branch: 'feat/auth', updatedAt: 1_000_000 - 2 * 3_600_000, ...patch })
+const folder = (patch: Partial<TaskFolder> = {}): TaskFolder => ({ cwd: '/w/api', kind: 'git', name: 'api', root: '/w/api', remote: 'github.com/acme/api', ...patch })
+
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())
+ const q = jevQuestion({ ...base, title: 'Build', brief: 'b'.repeat(5000), checks: ['Tests pass', 'Docs updated'], attempts: [{ agent: 'Builder', outcome: '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.history).toContain('Builder: stopped')
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)
@@ -141,7 +149,7 @@ describe('edges', () => {
})
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 })
+ .toMatchObject({ 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)
})
@@ -196,11 +204,19 @@ describe('edges', () => {
})
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)
+ const q = jevQuestion({ ...base, title: 'T' }, 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.')
+ expect(q.state.history).toContain('No earlier attempts in this group.')
+ })
+ it('ends the Lead\'s reason with exactly one period, whatever the Lead ended it with', () => {
+ const r = ok(choose([probe({ quality: 3 })], policy, a()))
+ const lead = (why: string) => jevQuestion({ ...base, title: 'T' }, a({ why }), policy, r).state.lead
+ for (const why of ['Add one function', 'Add one function.', 'Add one function...']) expect(lead(why)).toContain('Why: Add one function. Task folder')
+ // A question or an exclamation is already a full stop.
+ expect(lead('Is it safe?')).toContain('Why: Is it safe? Task folder')
+ expect(lead('Do it now!')).toContain('Why: Do it now! Task folder')
})
it('keeps a floor-meeting candidate even when it is low on quota or unknown', () => {
const low = { known: true, leftPercent: 5, resetsAt: null }
@@ -224,3 +240,240 @@ describe('edges', () => {
expect(rec.p).toBeNull()
})
})
+
+// Every fake secret is built here from pieces, so that no source line holds a whole key shape (GitHub push protection
+// refuses those, even in a test).
+const fake = (...parts: string[]) => parts.join('')
+const AWS_ID = fake('AKIA', 'IOSFODNN7', 'EXAMPLE')
+const AWS_SECRET = fake('wJalrXUtnFEMI/', 'K7MDENG/', 'bPxRfiCYEXAMPLEKEY')
+// Random-looking 40-character base64 keys that keep a `/` inside (a leading one is not a key shape): the same twelve every run.
+const slashedKeys = Array.from({ length: 400 }, (_, i) => createHash('sha256').update(String(i)).digest('base64').slice(0, 40))
+ .filter(key => key.slice(1, -1).includes('/')).slice(0, 12)
+
+describe('scrub', () => {
+ it('replaces emails and each token shape, and leaves ordinary text alone', () => {
+ const text = [
+ 'mail [email protected] now', fake('key sk-', 'proj-', 'abcdefghijklmnop1234'), fake('gh ghp', '_abcdefghijklmnopqrstuvwx'), fake('slack xox', 'b-1234567890-abcdef'),
+ fake('aws AKIA', 'ABCDEFGHIJKLMNOP'), fake('auth Bear', 'er eyJ', 'hbGciOi.abc-def_ghi'), `hex ${'a1'.repeat(16)}`, `b64 ${'Zm9vYmFy0'.repeat(5)}==`, 'plain words and /usr/bin/node stay',
+ ].join('\n')
+ const out = scrub(text)
+ expect(out).not.toMatch(/@|sk-|ghp_|xoxb|AKIA|Bearer|a1a1a1|Zm9v/)
+ expect(out.match(/\[email\]/g)).toHaveLength(1)
+ expect(out.match(/\[secret\]/g)!.length).toBeGreaterThanOrEqual(7)
+ expect(out).toContain('plain words and /usr/bin/node stay')
+ expect(scrub('commit abc1234 at v1.2.3')).toBe('commit abc1234 at v1.2.3')
+ })
+ it('keeps paths, URLs, branch names, UUIDs and file names, and still catches real keys', () => {
+ for (const keep of [
+ 'docs/superpowers/specs/2026-10-19-super-tab-routing-v1-design.md', 'https://github.com/autonomous-ai/openharness/pull/1424',
+ '0xken15/feat/super-tab-jev-context-v2', '/Users/nqhieu84/harnesses/worktrees/openharness/routing-v1', '3f2b8c1e-9a4d-4e57-8b1a-6c0d2e9f7a31',
+ 'feature/Add-OAuth2-Flow-For-Mobile-Clients-2026-10',
+ ]) expect(scrub(`see ${keep} now`)).toBe(`see ${keep} now`)
+ // A key is judged on its own, even inside a path or after an equals sign.
+ for (const key of [
+ fake('sk-', 'proj-', 'AbCdEf0123456789abcdefGH'), fake('ghp', '_AbCdEf0123456789abcdefghijklmn'), AWS_ID, fake('xox', 'b-123456789012-abcdefABCDEF'),
+ fake('eyJ', 'hbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.', 'eyJ', 'zdWIiOiIxMjM0NTY3ODkwIn0.', 'dBjftJeZ4CVPmB92K27', 'uhbUJU1p1rwW1gFWFOEjXk'),
+ fake('wJalrXUtnFEMIK7MDENG', 'bPxRfiCYEXAMPLEKEY12='),
+ fake('Zm9vYmFyQmF6UXV4', 'MTIzNDU2Nzg5MEFiQ2RF', 'ZkdoSWpLbE1u'), fake('Ab3_dEf-9GhI1jKl_', 'MnO5pQr-StU7vWx_YzA2bCd4'), fake('e3b0c44298fc1c14', '9afbf4c8996fb924', '27ae41e4'),
+ ]) {
+ expect(scrub(`k ${key} z`)).toBe('k [secret] z')
+ expect(scrub(`path/${key}/end`)).toContain('[secret]')
+ }
+ // Standard base64 keys keep their `/`: AWS's documented example secret key, and a fixed sample of random 40-character keys.
+ expect(scrub(`secret ${AWS_SECRET} here`)).toBe('secret [secret] here')
+ expect(scrub(`AWS_SECRET_ACCESS_KEY=${AWS_SECRET}`)).toBe('AWS_SECRET_ACCESS_KEY=[secret]')
+ expect(slashedKeys).toHaveLength(12)
+ for (const key of slashedKeys) {
+ expect(scrub(`k ${key} z`)).toBe('k [secret] z')
+ expect(scrub(`"${key}"`)).toBe('"[secret]"')
+ }
+ // A relative path of plain words is not a key, even with a digit and a capital in it.
+ expect(scrub('see src/superTabs/RouteCommand/specHelpers/Util2/fixtures now')).toBe('see src/superTabs/RouteCommand/specHelpers/Util2/fixtures now')
+ // Bearer needs a token-like value, and its spelling.
+ expect(scrub('Bearer is a word, and bearer token too')).toBe('Bearer is a word, and bearer token too')
+ expect(scrub(fake('Authorization: Bear', 'er abcdefghij', '0123456789klmn'))).toBe('Authorization: [secret]')
+ })
+})
+
+describe('the context Jev is given', () => {
+ const now = 1_000_000
+ const members = (patch: Partial<Probe> = {}) => ok(choose([
+ probe({ kind: 'member', agentId: 'a1', name: 'Multiply', activity: 'idle', frame: frame(), repo: 'same', earlier: [{ group: 'API', outcome: 'done' }], ...patch }),
+ probe({ machineName: 'mac', load: { agents: 3, freeMemoryBytes: 6.5e9, hasFolder: true } }),
+ ], policy, a(), now))
+ const ask = (patch: Record<string, unknown> = {}, choice = members()) => jevQuestion({ ...base, ...patch }, a({ needs: { tools: [], devices: [], cwd: '/w/api' } }), policy, choice)
+
+ it('tells what a member is doing, where, and whether it is the task\'s repository', () => {
+ const label = members().shown.find(s => s.kind === 'member')!.label
+ expect(label).toContain('same repo')
+ expect(label).toContain('on "Fix auth"')
+ expect(label).toContain('api, branch feat/auth')
+ expect(label).toContain('last active 2h ago')
+ expect(label).toContain('earlier here: API done')
+ expect(members({ repo: 'different' }).shown.find(s => s.kind === 'member')!.label).toContain('different repo')
+ expect(members({ repo: 'unknown' }).shown.find(s => s.kind === 'member')!.label).toContain('repo unknown')
+ expect(members({ repo: undefined }).shown.find(s => s.kind === 'member')!.label).not.toMatch(/repo/)
+ })
+ it('says unknown for a member whose activity could not be read, and shows what is missing from a frame', () => {
+ const none = members({ frame: null, repo: 'unknown', earlier: [] }).shown.find(s => s.kind === 'member')!.label
+ expect(none).toContain('activity unknown')
+ expect(none).not.toContain('earlier here')
+ const bare = members({ frame: frame({ title: null, project: null, branch: null, updatedAt: null }) }).shown.find(s => s.kind === 'member')!.label
+ expect(bare).toContain('last active unknown')
+ expect(bare).not.toMatch(/on "|branch/)
+ const noBranch = members({ frame: frame({ branch: null }) }).shown.find(s => s.kind === 'member')!.label
+ expect(noBranch).toContain('in api')
+ expect(noBranch).not.toContain('branch')
+ expect(members({ frame: frame({ project: null, branch: 'main' }) }).shown.find(s => s.kind === 'member')!.label).toContain('branch main')
+ expect(members({ frame: frame({ updatedAt: 1_000_000 + 5_000 }) }).shown.find(s => s.kind === 'member')!.label).toContain('last active 1m ago')
+ })
+ it('tells what a new agent starts on: the task folder, the agents running and the memory free', () => {
+ const label = members().shown.find(s => s.kind === 'new')!.label
+ expect(label).toContain('has the task folder')
+ expect(label).toContain('3 agents running')
+ expect(label).toContain('6.5 GB memory free')
+ const one = ok(choose([probe({ load: { agents: 1, freeMemoryBytes: 2.5e8, hasFolder: false } })], policy, a(), now)).shown[0].label
+ expect(one).toContain('no task folder')
+ expect(one).toContain('1 agent running')
+ expect(one).toContain('250 MB memory free')
+ const unknown = ok(choose([probe({ load: { agents: null, freeMemoryBytes: null, hasFolder: null } })], policy, a(), now)).shown[0].label
+ expect(unknown).toContain('agents running unknown · free memory unknown')
+ expect(unknown).not.toMatch(/folder/)
+ expect(ok(choose([probe({ load: { agents: 2, freeMemoryBytes: null, hasFolder: null } })], policy, a(), now)).shown[0].label).toContain('2 agents running · free memory unknown')
+ expect(ok(choose([probe()], policy, a(), now)).shown[0].label).not.toMatch(/running|memory|folder/)
+ })
+ it('puts earlier work before the quota, so a length cut removes the quota first', () => {
+ const label = members().shown.find(s => s.kind === 'member')!.label
+ expect(label.indexOf('earlier here')).toBeLessThan(label.indexOf('quota'))
+ })
+ it('lists every quota window with what is left and when it resets', () => {
+ const quota = { known: true, leftPercent: 40, resetsAt: now + 2 * 3_600_000, windows: [
+ { name: '5-hour', leftPercent: 40, resetsAt: now + 2 * 3_600_000 }, { name: 'weekly', leftPercent: 90, resetsAt: now + 5 * 86_400_000 }, { name: null, leftPercent: 75, resetsAt: null }] }
+ const label = ok(choose([probe({ quota })], policy, a(), now)).shown[0].label
+ expect(label).toContain('quota 5-hour 40% left (resets in 2h), weekly 90% left (resets in 5 days), window 75% left')
+ })
+ it('names the task folder and its repository in the Lead\'s assessment', () => {
+ expect(ask({ folder: folder() }).state.lead).toContain('Task folder: api (git repository api)')
+ expect(ask({ folder: folder({ cwd: '/w/notes', kind: 'none', name: null, root: null }) }).state.lead).toContain('Task folder: notes (not a git repository)')
+ expect(ask({ folder: folder({ kind: 'unknown', name: null }) }).state.lead).toContain('Task folder: api (repository unknown)')
+ expect(ask({ folder: folder({ cwd: '/', name: null }) }).state.lead).toContain('Task folder: / (git repository )')
+ expect(ask({ folder: folder({ kind: 'missing', name: null, root: null, remote: null }) }).state.lead).toContain('Task folder: api (not on the Lead\'s machine)')
+ expect(ask({ folder: null }).state.lead).toContain('Task folder: not stated')
+ expect(ask({ folder: folder() }).state.lead).not.toContain('/w/')
+ })
+ it('gives the last messages as a role-tagged transcript, newest last, and marks missing or empty ones', () => {
+ const messages = Array.from({ length: 4 }, (_, i) => ({ from: i % 2 ? 'Lead' : 'person', text: `m${i}` }))
+ expect(ask({ messages }).state.task).toContain('Recent messages:\nperson: m0\nLead: m1\nperson: m2\nLead: m3')
+ expect(ask({ messages: [] }).state.task).toContain('Recent messages: none')
+ expect(ask({ messages: null }).state.task).toContain('Recent messages: unknown')
+ expect(ask({ messages: [], noneInLatest: true }).state.task).toContain('Recent messages: none in the latest 100 messages')
+ expect(ask({ messages: [{ from: 'Multiply', text: 'x' }] }).state.task).toContain('Multiply: x')
+ })
+ it('tells the policy: the cost scale and why the floor is what it is', () => {
+ const policyText = (assessment: Assessment, p = policy) => { const c = ok(choose([probe({ quality: 3 })], p, assessment, now)); return jevQuestion(base, assessment, p, c).state.policy }
+ expect(policyText(a({ difficulty: 'high', risk: 'low' }))).toContain('Quality floor: 3 (difficulty high needs quality 3).')
+ expect(policyText(a({ difficulty: 'medium', risk: 'high' }))).toContain('Quality floor: 3 (difficulty medium needs quality 2, plus 1 for high risk).')
+ expect(policyText(a({ difficulty: 'high', risk: 'high' }))).toContain('Quality floor: 3 (difficulty high needs quality 3, plus 1 for high risk, at most 3).')
+ expect(policyText(a())).toContain('Cost is relative: cost 3 is about 3 times cost 1.')
+ })
+ it('lists all attempts in the group with their outcome and a cut result, and the last routing decisions', () => {
+ const q = ask({ attempts: [{ agent: 'Multiply', outcome: 'stopped', result: 'r'.repeat(300) }, { agent: 'New agent (claude opus)', outcome: 'done' }],
+ recent: [{ title: 'Multiply · Claude sonnet medium · remote-1', via: 'jev', outcome: 'stopped' }, { title: 'New agent · Codex', via: 'order', outcome: null }] })
+ expect(q.state.history).toContain(`- Multiply: stopped — ${'r'.repeat(199)}…`)
+ expect(q.state.history).toContain('- New agent (claude opus): done')
+ expect(q.state.history).toContain('- Multiply · Claude sonnet medium · remote-1 (jev): stopped')
+ expect(q.state.history).toContain('- New agent · Codex (order): open')
+ expect(ask({ recent: [{ title: 'Pick', outcome: 'done' }] }).state.history).toContain('- Pick: done')
+ expect(ask({ recent: null }).state.history).toContain('Recent routing in this Super Tab: unknown')
+ expect(ask({ recent: [] }).state.history).toContain('Recent routing in this Super Tab: none')
+ })
+ it('keeps the newest of too many messages and attempts, with a mark for what was dropped', () => {
+ const words = (i: number) => `msg${i} ${'lorem ipsum '.repeat(40)}`.slice(0, 500).padEnd(500, '.')
+ const messages = Array.from({ length: 10 }, (_, i) => ({ from: 'person', text: words(i) }))
+ const task = ask({ messages }).state.task
+ const part = task.slice(task.indexOf('Recent messages:'))
+ expect(part.length).toBeLessThanOrEqual('Recent messages:\n'.length + 3500)
+ expect(part).toContain('…\n')
+ expect(part.endsWith(words(9))).toBe(true)
+ expect(part).not.toContain('msg0')
+ const attempts = Array.from({ length: 60 }, (_, i) => ({ agent: `Agent${i}`, outcome: 'stopped', result: 'x'.repeat(200) }))
+ const history = ask({ attempts }).state.history
+ expect(history).toContain('Agent59')
+ expect(history).not.toContain('Agent0:')
+ expect(history).toMatch(/…/)
+ })
+ it('scrubs emails and secrets everywhere, so no @ or token reaches Jev', () => {
+ const dirty = fake('ping [email protected] with sk-', 'abcdefghijklmnopqrstu and Bear', 'er abcdef.ghijklmnop.qrstuvwxyz and ghp', '_abcdefghijklmnopqrstuvw')
+ const choice = ok(choose([probe({ kind: 'member', agentId: 'a1', name: 'Multiply', frame: frame({ title: dirty, branch: '[email protected]' }), repo: 'same', earlier: [{ group: dirty, outcome: 'done' }] }),
+ probe({ machineName: 'mac' })], policy, a(), now))
+ const q = jevQuestion({ ...base, title: dirty, brief: dirty, checks: [dirty], messages: [{ from: 'person', text: dirty }],
+ attempts: [{ agent: 'Multiply', outcome: 'stopped', result: dirty }], recent: [{ title: dirty, via: 'jev', outcome: null }] },
+ a({ why: dirty, needs: { tools: [], devices: [], cwd: '/w/[email protected]' } }), { ...policy, notes: dirty }, choice)
+ const all = JSON.stringify(q)
+ expect(all).not.toMatch(/@|sk-abc|ghp_|Bearer/)
+ expect(all).toContain('[email]')
+ expect(all).toContain('[secret]')
+ })
+ it('stays within every hosted limit and its own budget at the worst case', () => {
+ const long = (c: string, n: number) => c.repeat(n)
+ const probes = Array.from({ length: 12 }, (_, i) => probe({ kind: 'member', agentId: `a${i}`, name: long('N', 80), machineName: long('M', 80), model: long('o', 200), activity: 'idle',
+ frame: frame({ title: long('T', 300), project: long('P', 300), branch: long('Q', 300) }), repo: 'same',
+ earlier: Array.from({ length: 9 }, () => ({ group: long('G', 90), outcome: 'stopped' })),
+ quota: { known: true, leftPercent: 50, resetsAt: now + 1e9, windows: [{ name: '5-hour', leftPercent: 50, resetsAt: now + 3_600_000 }, { name: 'weekly', leftPercent: 70, resetsAt: now + 5 * 86_400_000 }] } }))
+ const choice = ok(choose(probes, { ...policy, notes: long('n', 3000) }, a(), now))
+ const q = jevQuestion({ title: long('t', 500), brief: long('k', 9000), checks: Array.from({ length: 30 }, () => long('q', 200)),
+ messages: Array.from({ length: 10 }, () => ({ from: long('X', 90), text: long('m', 2000) })), folder: folder({ cwd: `/${long('z', 300)}`, name: long('r', 300) }),
+ attempts: Array.from({ length: 40 }, () => ({ agent: long('Y', 90), outcome: 'stopped', result: long('x', 900) })),
+ recent: Array.from({ length: 5 }, () => ({ title: long('R', 200), via: 'jev', outcome: 'stopped' })) },
+ a({ why: long('w', 300), needs: { tools: Array.from({ length: 20 }, () => long('t', 80)), devices: Array.from({ length: 20 }, () => long('/z', 40)), cwd: `/${long('z', 300)}` } }),
+ { ...policy, notes: long('n', 3000) }, choice)
+ expect(Object.keys(q.state)).toEqual(['task', 'lead', 'policy', 'history'])
+ const limit = { task: 7000, lead: 1000, policy: 1000, history: 6000 } as const
+ for (const key of Object.keys(limit) as Array<keyof typeof limit>) {
+ expect(q.state[key].length).toBeLessThanOrEqual(limit[key])
+ // Whole messages and attempts are kept or dropped, so a part may end up to one line short of its budget.
+ expect(q.state[key].length).toBeGreaterThan(limit[key] - 700)
+ }
+ expect(Object.values(q.state).reduce((sum, v) => sum + v.length, 0)).toBeLessThanOrEqual(15_000)
+ const labels = Object.values(q.questions.who.criteria)
+ expect(labels).toHaveLength(12)
+ expect(labels.every(l => l.length <= 640)).toBe(true)
+ expect(labels.some(l => l.endsWith('…'))).toBe(true)
+ expect(q.questions.who.instructions.length).toBeLessThanOrEqual(1500)
+ expect(contextSize(q)).toBe(Object.values(q.state).reduce((sum, v) => sum + v.length, 0) + labels.reduce((sum, l) => sum + l.length, 0) + q.questions.who.instructions.length)
+ // The parts that matter stay: the end of the messages and the task's own budgets.
+ expect(q.state.task).toContain('Brief: ' + long('k', 100))
+ expect(q.state.task).toContain('Recent messages:')
+ })
+ it('records the size of the context and what was missing, only when given', () => {
+ const c = members(), v = decide(c, undefined, 'BUSY')
+ expect(recordOf(c, v, a(), policy, { chars: 5000, missing: ['messages'] })).toMatchObject({ context: { chars: 5000, missing: ['messages'] } })
+ expect(recordOf(c, v, a(), policy)).not.toHaveProperty('context')
+ })
+})
+
+describe('repoMatch', () => {
+ it('marks a member as in the task\'s repository by remote, then root, then folder', () => {
+ expect(repoMatch(null, frame(), true)).toBeUndefined()
+ expect(repoMatch(folder(), null, true)).toBe('unknown')
+ expect(repoMatch(folder({ kind: 'unknown' }), frame(), true)).toBe('unknown')
+ // The same remote is the same repository wherever the checkout is.
+ expect(repoMatch(folder(), frame({ cwd: '/other/api', root: '/other/api' }), false)).toBe('same')
+ expect(repoMatch(folder(), frame({ remote: 'github.com/acme/web' }), true)).toBe('different')
+ expect(repoMatch(folder({ remote: null }), frame({ remote: null }), true)).toBe('same')
+ expect(repoMatch(folder({ remote: null }), frame({ remote: null, root: '/w/web', cwd: '/w/web' }), true)).toBe('different')
+ // Paths on two machines say nothing without a remote.
+ expect(repoMatch(folder({ remote: null }), frame({ remote: null, root: '/w/web', cwd: '/w/web' }), false)).toBe('unknown')
+ expect(repoMatch(folder({ kind: 'none', root: null, remote: null }), frame({ root: null, remote: null }), true)).toBe('same')
+ expect(repoMatch(folder({ kind: 'none', root: null, remote: null }), frame({ root: null, remote: null, cwd: '/w/else' }), true)).toBe('different')
+ expect(repoMatch(folder({ kind: 'none', root: null, remote: null }), frame({ root: null, remote: null, cwd: null }), true)).toBe('unknown')
+ // A task folder inside a repository is judged by the repository's root.
+ expect(repoMatch(folder({ cwd: '/w/api/sub', remote: null }), frame({ remote: null }), true)).toBe('same')
+ // The Lead's machine may not have the folder at all: a member standing in it is in it, on any machine.
+ const missing = folder({ kind: 'missing', root: null, remote: null, name: null })
+ expect(repoMatch(missing, frame({ remote: null, root: '/w/api', cwd: '/w/api' }), false)).toBe('same')
+ expect(repoMatch(missing, frame({ remote: null, root: '/w/api-wt', cwd: '/w/api' }), false)).toBe('same')
+ expect(repoMatch(missing, frame({ remote: null, root: '/w/web', cwd: '/w/web' }), false)).toBe('unknown')
+ expect(repoMatch(missing, frame({ remote: null, root: '/w/web', cwd: '/w/web' }), true)).toBe('different')
+ })
+})
diff --git a/cli/src/superTabs/route.ts b/cli/src/superTabs/route.ts
index bee396fda..5d4838279 100644
--- a/cli/src/superTabs/route.ts
+++ b/cli/src/superTabs/route.ts
@@ -2,7 +2,7 @@
* 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 { basename, 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'
@@ -11,12 +11,28 @@ 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 }
+/** One usage window, named by the reader (`5-hour`, `weekly`); `leftPercent` is what remains of it. */
+export interface QuotaWindow { name: string | null; leftPercent: number; resetsAt: number | null }
+/** `leftPercent` and `resetsAt` are the tightest window's, which ranks candidates; `windows` is every window, for Jev. */
+export interface Quota { known: boolean; leftPercent: number | null; resetsAt: number | null; windows?: QuotaWindow[] }
+/** The task's folder as the Lead's machine sees it. `unknown` means it could not be read, `none` that it is not a repository,
+ * `missing` that the Lead's machine has no such folder (a member elsewhere may). */
+export interface TaskFolder { cwd: string; kind: 'git' | 'none' | 'missing' | 'unknown'; name: string | null; root: string | null; remote: string | null }
+/** What a member's `agents_list` frame says it is working on; every field is null when the frame does not say. */
+export interface MemberFrame { title: string | null; project: string | null; cwd: string | null; root: string | null; remote: string | null; branch: string | null; updatedAt: number | null }
+/** What a machine offers a new agent. Each field is null when it could not be read. */
+export interface MachineLoad { agents: number | null; freeMemoryBytes: number | null; hasFolder: boolean | 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[]
+ /** Members: the frame (null when it could not be read), whether the member is in the task's repository, and its earlier work in this Super Tab. */
+ frame?: MemberFrame | null; repo?: 'same' | 'different' | 'unknown'; earlier?: Array<{ group: string; outcome: string }>
+ /** New agents: what the machine has. */
+ load?: MachineLoad
}
+export interface Attempt { agent: string; outcome: string; result?: string }
+export interface RecentRoute { title: string; via?: string; outcome: string | null }
export interface Shown extends Probe { id: string; title: string; label: string }
export interface Choice { shown: Shown[]; excluded: Array<{ title: string; reason: string }>; floor: number; belowFloor: boolean }
export interface Verdict { pick: Shown; via: 'jev' | 'order' | 'only'; p: number | null; why: string; fallback?: 'unsure' | 'unavailable' }
@@ -26,6 +42,39 @@ 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)}…`
+/** Jev is a hosted model, so nothing that identifies a person or opens an account goes to it. Emails and the common
+ * key shapes are replaced before any text is cut, so a cut never leaves half a key behind. A long hex run is taken
+ * for a key even when it is a commit id: a lost id costs less than a leaked key. */
+const SECRETS = [
+ /\b(?:sk|pk|rk)-[A-Za-z0-9_-]{16,}/g, /\bgh[pousr]_[A-Za-z0-9]{20,}/g, /\bxox[a-z]-[A-Za-z0-9-]{10,}/g, /\bAKIA[0-9A-Z]{16}\b/g,
+ /\bBearer\s+[A-Za-z0-9._~+/=-]{20,}/g, /\beyJ[A-Za-z0-9_-]{5,}\.[A-Za-z0-9_-]{5,}\.[A-Za-z0-9_-]*/g, /\b[0-9a-fA-F]{32,}\b/g,
+]
+/** A base64 or base64url key, as opposed to a path, a URL or a branch name that is just as long: it has all three of
+ * upper case, lower case and digits, and no words joined by hyphens. `/` and `.` end a run, so a long path is judged by
+ * its segments and a JWT by its parts. */
+const keyLike = (run: string) => /[A-Z]/.test(run) && /[a-z]/.test(run) && /\d/.test(run) && !/[A-Z]?[a-z]{3,}-[A-Z]?[a-z]{3,}/.test(run)
+/** Standard base64 uses `/`, which also separates path pieces. A whole token (not a path from the root, no dot) is a key
+ * when it looks like one and none of its pieces is a plain word, which a relative path would have. */
+const plainWord = (piece: string) => /^[A-Z]?[a-z]{5,}$/.test(piece)
+const slashedKey = (token: string) => /^[A-Za-z0-9+/]{32,}={0,2}$/.test(token) && token.includes('/') && keyLike(token) && !token.split('/').some(plainWord)
+export function scrub(text: string): string {
+ const plain = SECRETS.reduce((t, pattern) => t.replace(pattern, '[secret]'), text.replace(/[^\s@<>()"',;]+@[^\s@<>()"',;]+/g, '[email]'))
+ return plain.replace(/[^\s"'=:,;()<>]+/g, token => slashedKey(token) ? '[secret]' : token)
+ .replace(/[A-Za-z0-9+_=-]{32,}/g, run => keyLike(run) ? '[secret]' : run)
+}
+const fit = (text: string, max: number) => cut(scrub(text), max)
+/** The newest lines that fit, for logs where the end matters most; a leading mark says older ones were dropped. */
+function newest(lines: string[], max: number): string {
+ if (lines.join('\n').length <= max) return lines.join('\n')
+ let kept = ''
+ for (let i = lines.length - 1; i >= 0; i--) {
+ const next = kept ? `${lines[i]}\n${kept}` : lines[i]
+ if (next.length > max - 2) break
+ kept = next
+ }
+ return `…\n${kept}`
+}
+
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.'
@@ -47,10 +96,27 @@ function resetMs(value: unknown): number | null {
if (typeof value === 'string') { const ms = Date.parse(value); return Number.isFinite(ms) ? ms : null }
return null
}
-export function quotaOf2(q: { known: boolean; windows: Array<{ usedPercent: number; resetsAt: unknown }> }): Quota {
+export function quotaOf2(q: { known: boolean; windows: Array<{ usedPercent: number; resetsAt: unknown; name?: string }> }): Quota {
if (!q.known || !q.windows.length) return { known: false, leftPercent: null, resetsAt: null }
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) }
+ return { known: true, leftPercent: Math.max(0, 100 - tightest.usedPercent), resetsAt: resetMs(tightest.resetsAt),
+ windows: q.windows.map(w => ({ name: w.name ?? null, leftPercent: Math.max(0, 100 - w.usedPercent), resetsAt: resetMs(w.resetsAt) })) }
+}
+
+/** Whether a member's checkout is the task's repository: the same remote wherever it lives, else the same root on one
+ * machine. Paths on two machines say nothing without a remote. Undefined when the Lead named no folder. */
+export function repoMatch(folder: TaskFolder | null, frame: MemberFrame | null, sameMachine: boolean): Probe['repo'] | undefined {
+ if (!folder) return undefined
+ if (!frame || folder.kind === 'unknown') return 'unknown'
+ if (folder.remote && frame.remote) return folder.remote === frame.remote ? 'same' : 'different'
+ const theirs = frame.root ?? frame.cwd
+ // A frame that names no checkout says nothing. The folder the Lead named is a path on the machine that will run the
+ // task, so a member standing in exactly it is in it, wherever the Lead is.
+ if (!theirs) return 'unknown'
+ if (theirs === folder.cwd || frame.cwd === folder.cwd) return 'same'
+ // Other paths on two machines say nothing without a remote.
+ if (!sameMachine) return 'unknown'
+ return (folder.root ?? folder.cwd) === theirs ? 'same' : 'different'
}
/** A member's model is what its engine reported after work: Claude's full id (`claude-opus-4-7`, `claude-sonnet-4-5[1m]`),
@@ -65,19 +131,42 @@ export function rateFor(policy: Policy, engine: string, model: string | null, ef
}
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)
+/** Jev does not know the time, so a reset or a last activity is told as how far away it is. */
+function span(ms: number): string {
if (ms < 3_600_000) return `${Math.max(1, Math.round(ms / 60_000))}m`
if (ms < 48 * 3_600_000) return `${Math.round(ms / 3_600_000)}h`
return `${Math.round(ms / 86_400_000)} days`
}
+const resetsIn = (resetsAt: number, now: number) => span(Math.max(0, resetsAt - now))
function quotaText(q: Quota, now: number): string {
if (!q.known || q.leftPercent === null) return 'quota unknown'
+ if (q.windows?.length) {
+ return `quota ${q.windows.map(w => `${w.name ?? 'window'} ${Math.round(w.leftPercent)}% left${w.resetsAt === null ? '' : ` (resets in ${resetsIn(w.resetsAt, now)})`}`).join(', ')}`
+ }
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)
+const bytes = (n: number) => n >= 1e9 ? `${(n / 1e9).toFixed(1)} GB` : `${Math.round(n / 1e6)} MB`
+/** What a member is doing and has done, or one phrase saying it is not known. */
+function memberText(p: Probe, now: number): string[] {
+ const f = p.frame
+ const repo = p.repo ? [p.repo === 'unknown' ? 'repo unknown' : `${p.repo} repo`] : []
+ if (!f) return [...repo, 'activity unknown']
+ const where = [f.project && fit(f.project, 40), f.branch && `branch ${fit(f.branch, 40)}`].filter(Boolean).join(', ')
+ return [...repo, ...(f.title ? [`on "${fit(f.title, 80)}"`] : []), ...(where ? [f.project ? `in ${where}` : where] : []),
+ f.updatedAt === null ? 'last active unknown' : `last active ${span(Math.max(0, now - f.updatedAt))} ago`]
+}
+function machineText(load: MachineLoad): string[] {
+ return [...(load.hasFolder === null ? [] : [load.hasFolder ? 'has the task folder' : 'no task folder']),
+ load.agents === null ? 'agents running unknown' : `${load.agents} ${load.agents === 1 ? 'agent' : 'agents'} running`,
+ load.freeMemoryBytes === null ? 'free memory unknown' : `${bytes(load.freeMemoryBytes)} memory free`]
+}
+/** The most telling parts come first and the least last, because the hosted limit cuts the end. */
+const labelOf = (p: Probe, now: number) => fit([
+ p.kind === 'member' ? `Member ${fit(p.name ?? '', 40)}`.trim() : 'New agent', `${ENGINE[p.engine]} ${p.model} ${p.effort}`, `quality ${p.quality}, cost ${p.cost}`,
+ fit(p.machineName, 40), p.activity, ...(p.kind === 'member' ? memberText(p, now) : p.load ? machineText(p.load) : []),
+ ...(p.earlier?.length ? [`earlier here: ${p.earlier.slice(0, 3).map(e => `${fit(e.group, 40)} ${e.outcome}`).join('; ')}`] : []), quotaText(p.quota, now),
+].join(' · '), 640)
/** The fixed policy order (D): cheaper, then more quota left, then an earlier reset, then a member, then by title. */
function compare(x: Probe, y: Probe): number {
@@ -110,15 +199,44 @@ 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.',
+ 'A member marked "same repo" already has the task\'s code open, which saves a start; prefer it over an equal candidate.',
+ 'A candidate that already failed or stopped on this task is a worse choice. A member that is idle in the Super Tab saves a start.',
+ 'Unknown means the information could not be read; it is not a bad sign.',
].join(' '), 1500)
-export function jevQuestion(input: { title: string; brief: string; checks: string[]; history: string[] }, a: Assessment, policy: Policy, choice: Choice) {
+const folderText = (f: TaskFolder | null) => !f ? 'not stated'
+ : `${fit(basename(f.cwd) || f.cwd, 80)} (${f.kind === 'git' ? `git repository ${fit(f.name ?? '', 80)}` : f.kind === 'none' ? 'not a git repository'
+ : f.kind === 'missing' ? 'not on the Lead\'s machine' : 'repository unknown'})`
+
+export interface JevInput {
+ title: string; brief: string; checks: string[]
+ /** The last messages as `person`, `Lead` or an agent's name; null when they could not be read. */
+ messages: Array<{ from: string; text: string }> | null
+ /** True when the latest page of the group held only log rows (routing notes, transcripts), so "none" would mislead. */
+ noneInLatest?: boolean
+ folder: TaskFolder | null; attempts: Attempt[]
+ /** The Super Tab's latest routing decisions; null when they could not be read. */
+ recent: RecentRoute[] | null
+}
+
+/** The hosted route allows 4 keys and 17,000 characters of state. Each key has its own budget so that one long
+ * brief cannot push out the messages or the history. */
+export function jevQuestion(input: JevInput, a: Assessment, policy: Policy, choice: Choice) {
+ const messages = input.messages === null ? 'Recent messages: unknown' : input.messages.length
+ ? `Recent messages:\n${newest(input.messages.map(m => `${fit(m.from, 40)}: ${fit(m.text, 600)}`), 3500)}` : `Recent messages: none${input.noneInLatest ? ' in the latest 100 messages' : ''}`
+ const base = policy.floor[a.difficulty]
+ const risk = a.risk === 'high' ? `, plus 1 for high risk${base + 1 > 3 ? ', at most 3' : ''}` : ''
+ const floor = `Quality floor: ${choice.floor} (difficulty ${a.difficulty} needs quality ${base}${risk})${choice.belowFloor ? '; no candidate meets it, so all are shown' : ''}. `
+ + 'Cost is relative: cost 3 is about 3 times cost 1. Notes: '
+ const attempts = input.attempts.length
+ ? `Attempts in this group:\n${newest(input.attempts.map(t => `- ${fit(t.agent, 60)}: ${fit(t.outcome, 20)}${t.result ? ` — ${fit(t.result, 200)}` : ''}`), 4700)}` : 'No earlier attempts in this group.'
+ const recent = input.recent === null ? 'Recent routing in this Super Tab: unknown' : input.recent.length
+ ? `Recent routing in this Super Tab:\n${input.recent.map(r => `- ${fit(r.title, 200)}${r.via ? ` (${fit(r.via, 20)})` : ''}: ${r.outcome ? fit(r.outcome, 20) : 'open'}`).join('\n')}` : 'Recent routing in this Super Tab: none'
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),
+ task: fit(`Group: ${fit(input.title, 160)}\nBrief: ${fit(input.brief, 2000)}\nChecks:\n${fit(input.checks.map(c => `- ${c}`).join('\n'), 1000)}\n${messages}`, 7000),
+ lead: fit(`Difficulty: ${a.difficulty}. Risk: ${a.risk}. Why: ${/[!?]$/.test(a.why) ? a.why : `${a.why.replace(/\.+$/, '')}.`} Task folder: ${folderText(input.folder)}. Needs tools: ${a.needs.tools.join(', ') || 'none'}; devices: ${a.needs.devices.join(', ') || 'none'}.`, 1000),
+ policy: fit(`${floor}${policy.notes || 'none'}`, 1000),
+ history: fit(`${attempts}\n\n${recent}`, 6000),
}
const questions: Record<string, JevChoice> = {
who: { type: 'choice', instructions: INSTRUCTIONS, criteria: Object.fromEntries(choice.shown.map(s => [s.id, s.label])) },
@@ -126,6 +244,10 @@ export function jevQuestion(input: { title: string; brief: string; checks: strin
return { state, questions }
}
+/** How many characters Jev was given in all, for the decision log. */
+export const contextSize = (q: ReturnType<typeof jevQuestion>): number =>
+ Object.values(q.state).reduce((sum, v) => sum + v.length, 0) + Object.values(q.questions.who.criteria).reduce((sum, v) => sum + v.length, 0) + q.questions.who.instructions.length
+
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.' }
@@ -138,7 +260,7 @@ export function decide(choice: Choice, answer: JevChoiceAnswer | undefined, unav
return { pick: first, via: 'order', p: null, why: `${reason}; first in the policy order.`, fallback: unavailable ? 'unavailable' : 'unsure' }
}
-export function recordOf(choice: Choice, verdict: Verdict, a: Assessment, policy: Policy): Record<string, unknown> {
+export function recordOf(choice: Choice, verdict: Verdict, a: Assessment, policy: Policy, context?: { chars: number; missing: string[] }): 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,
@@ -146,5 +268,6 @@ export function recordOf(choice: Choice, verdict: Verdict, a: Assessment, policy
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),
+ ...(context ? { context } : {}),
}
}
diff --git a/cli/src/superTabs/routeCommand.spec.ts b/cli/src/superTabs/routeCommand.spec.ts
index 315c116bd..15a744415 100644
--- a/cli/src/superTabs/routeCommand.spec.ts
+++ b/cli/src/superTabs/routeCommand.spec.ts
@@ -1,6 +1,10 @@
import { describe, expect, it, vi, type Mock } from 'vitest'
import type { openDaemon } from '../agentClient/daemon.js'
+import { mkdtemp, rm, writeFile } from 'node:fs/promises'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
import { routeTask } from './routeCommand.js'
+import type { describeScmProject } from '../scm/scmProjects.js'
import { admission, quotaOf } from './capacity.js'
const policy = { version: 1, floor: { low: 1, medium: 2, high: 3 }, quotaReserve: 10, notes: '', models: [
@@ -18,15 +22,15 @@ const conversations = (assignment: unknown = null) => [
]
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 } = {}) {
+function daemon(machineId: string, options: { agents?: string[]; frames?: Record<string, Record<string, unknown>>; capacity?: Record<string, unknown>; terminalAvailable?: boolean; tools?: Record<string, boolean>; devices?: Record<string, boolean>; usage?: unknown; listFails?: boolean; engines?: unknown } = {}) {
return {
machineId, close: vi.fn(),
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 } })) }
+ return { agents: (options.agents ?? []).map(id => ({ id, terminal: { available: options.terminalAvailable ?? true }, ...options.frames?.[id] })) }
}
- if (type === 'super_tabs') return { resources: { memoryTotalBytes: 8e9, memoryUsedBytes: 1e9, cpuPercent: 10, projectDiskFreeBytes: 1e11 }, tools: options.tools ?? { git: true }, devices: options.devices ?? {} }
+ if (type === 'super_tabs') return options.capacity ?? { 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 {}
@@ -34,9 +38,10 @@ function daemon(machineId: string, options: { agents?: string[]; terminalAvailab
}
}
type Answer = Record<string, unknown>
-function scoped(answers: { jev?: Answer; record?: Answer; tab?: unknown; context?: Answer; jevThrows?: boolean; recordThrows?: boolean } = {}) {
+function scoped(answers: { jev?: Answer; record?: Answer; tab?: unknown; context?: Answer; history?: Answer; historyHangs?: boolean; 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 === 'routeHistory') return answers.historyHangs ? new Promise(() => {}) : answers.history ?? { ok: true, value: { messages: [], decisions: [], attempts: [] } }
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.
@@ -271,11 +276,11 @@ describe('routeTask', () => {
] as const) {
const s = scoped({ tab: tab(assignment) })
await routeTask(input, s, where as never, opener())
- expect(jevCall(s).state.history).toContain(line)
+ 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.')
+ expect(jevCall(s).state.history).toContain('No earlier attempts in this group.')
})
it('keeps a group without brief or checks routable', async () => {
const odd = tab(); const group = odd.state.conversations[1] as Record<string, unknown>
@@ -316,3 +321,257 @@ describe('routeTask', () => {
expect(unknown).toMatchObject({ allowed: true, reasons: [] })
})
})
+
+describe('the context routeTask gives Jev', () => {
+ const git = (patch: Record<string, unknown> = {}) => ({ kind: 'git', name: 'api', cwd: '/w/api', root: '/w/api', remote: 'github.com/acme/api', branch: 'main', ...patch })
+ /** The Lead's machine, as the folder reader sees it: the folder is there (unless said otherwise) and the SCM describes it. */
+ const describeGit = (found: unknown = git(), isDirectory = true) => ({ describe: vi.fn(async () => found) as unknown as typeof describeScmProject & Mock, isDirectory: vi.fn(async () => isDirectory) })
+ const hoursAgo = (h: number) => new Date(Date.now() - h * 3_600_000).toISOString()
+ const frame = (patch: Record<string, unknown> = {}) => ({ title: 'Fix auth', updatedAt: hoursAgo(2), project: git({ cwd: '/w/api-wt', root: '/w/api-wt', branch: 'feat/auth' }),
+ gitContext: { current: { branch: 'feat/auth' } }, ...patch })
+ const withCwd = { ...input, assessment: { ...input.assessment, needs: { cwd: '/w/api' } } }
+ /** The context read and the history read of one tab; `extra` sets the tab, the messages and the decisions. */
+ const world = (extra: Record<string, unknown> = {}, assignment: unknown = null) => {
+ const { tab: given, ...past } = extra
+ return { context: { ok: true, value: { agentId: 'lead', tab: given ?? tab(assignment), policy: { policy, warnings: [] }, machines: [{ machineId: 'm1', name: 'remote-1' }, { machineId: 'm2', name: 'mac' }] } },
+ history: { ok: true, value: { messages: [{ from: 'person', text: 'Please add the endpoint.' }, { from: 'Lead', text: 'On it.' }], decisions: [], attempts: [], ...past } } }
+ }
+ const labels = (s: ReturnType<typeof scoped>) => Object.values(jevCall(s).questions.who.criteria as Record<string, string>)
+ const memberLabel = (s: ReturnType<typeof scoped>) => labels(s).find(l => l.startsWith('Member Multiply'))!
+ const newLabel = (s: ReturnType<typeof scoped>) => labels(s).find(l => l.startsWith('New agent'))!
+
+ it('reads the messages, the task folder, the member frames and the machines, and gives Jev what each says', async () => {
+ const s = scoped(world())
+ const make = (id: string) => daemon(id, { agents: id === 'm1' ? ['h1', 'x', 'y'] : ['z'], frames: { h1: frame() } })
+ const describeRepo = describeGit()
+ await routeTask(withCwd, s, where as never, opener(make), () => 'op', describeRepo)
+ expect(describeRepo.describe).toHaveBeenCalledWith('/w/api')
+ expect(describeRepo.isDirectory).toHaveBeenCalledWith('/w/api')
+ expect(jevCall(s).state.task).toContain('Recent messages:\nperson: Please add the endpoint.\nLead: On it.')
+ expect(jevCall(s).state.lead).toContain('Task folder: api (git repository api)')
+ expect(memberLabel(s)).toContain('same repo · on "Fix auth" · in api, branch feat/auth · last active 2h ago')
+ expect(labels(s).some(l => /^New agent.*remote-1.*has the task folder · 3 agents running · 7\.0 GB memory free/.test(l))).toBe(true)
+ expect(recorded(s).command.decision.context).toEqual({ chars: expect.any(Number), missing: [] })
+ expect(recorded(s).command.decision.context.chars).toBeGreaterThan(1000)
+ expect(recorded(s).command.decision.context.chars).toBeLessThan(17_000 + 31 * 640)
+ })
+ it('marks a member in another repository, and one it cannot compare', async () => {
+ const other = frame({ project: git({ name: 'web', remote: 'github.com/acme/web', root: '/w/web', cwd: '/w/web' }) })
+ const s = scoped(world())
+ await routeTask(withCwd, s, where as never, opener(id => daemon(id, { agents: id === 'm1' ? ['h1'] : [], frames: { h1: other } })), () => 'op', describeGit())
+ expect(memberLabel(s)).toContain('different repo')
+ const t = scoped(world())
+ await routeTask(withCwd, t, where as never, opener(id => daemon(id, { agents: id === 'm1' ? ['h1'] : [] })), () => 'op', describeGit())
+ expect(memberLabel(t)).toContain('repo unknown · last active unknown')
+ const u = scoped(world())
+ await routeTask(input, u, where as never, opener(id => daemon(id, { agents: id === 'm1' ? ['h1'] : [], frames: { h1: frame() } })), () => 'op')
+ expect(memberLabel(u)).not.toMatch(/repo/)
+ expect(u.mock.calls.find(c => c[0].action === 'command')![0].command.decision.context.missing).toEqual([])
+ })
+ it('compares a member on another machine by remote only, and uses the branch the frame\'s project reports', async () => {
+ const two = tab(); two.state.agents = [{ ...agents[0], machineId: 'm2' }, agents[1]] as never
+ const elsewhere = frame({ gitContext: undefined, project: git({ remote: null, root: '/other/api', cwd: '/other/api', branch: 'from-project' }) })
+ const s = scoped(world({ tab: two }))
+ await routeTask(withCwd, s, where as never, opener(id => daemon(id, { agents: id === 'm2' ? ['h1'] : [], frames: { h1: elsewhere } })), () => 'op', describeGit({ ...git(), remote: null }))
+ expect(memberLabel(s)).toContain('repo unknown')
+ expect(memberLabel(s)).toContain('branch from-project')
+ })
+ it('keeps a frame without a project, a title or a time as what the member does not say', async () => {
+ const s = scoped(world())
+ await routeTask(withCwd, s, where as never, opener(id => daemon(id, { agents: id === 'm1' ? ['h1'] : [], frames: { h1: { title: 5, updatedAt: 'later', project: null } } })), () => 'op', describeGit({ kind: 'none', cwd: '/w/api', root: null, remote: null, name: 'api', branch: null }))
+ expect(memberLabel(s)).toMatch(/repo unknown · last active unknown/)
+ expect(memberLabel(s)).not.toMatch(/on "|branch/)
+ expect(jevCall(s).state.lead).toContain('Task folder: api (not a git repository)')
+ })
+ it('tells Jev what the group and the Super Tab have tried: ended attempts from the state and the log, and the last five decisions', async () => {
+ const decision = (id: string, conversationId: string, patch: Record<string, unknown> = {}) => ({ id, conversationId, title: `Pick ${id}`, via: 'jev', outcome: 'stopped', assignmentId: `as-${id}`,
+ createdAt: '2026-10-19T10:00:00Z', final: { kind: 'new', engine: 'claude', model: 'opus' }, ...patch })
+ const decisions = [{ ...decision('d7', 'g1', { outcome: null, assignmentId: null, final: null }), via: undefined }, decision('d6', 'g1', { outcome: 'done', assignmentId: 'x', final: { kind: 'member', agentId: 'a1' } }), decision('d5', 'g1'),
+ decision('d4', 'other', { final: { kind: 'member', agentId: 'a1' }, outcome: 'done' }), decision('d3', 'g1', { final: null }), decision('d2', 'lead'), decision('d1', 'g1', { outcome: 'superseded' }), decision('d0', 'g1', { final: { kind: 'member', agentId: 'gone' } })]
+ const s = scoped(world({ decisions }, { id: 'x', agentId: 'a1', status: 'done', result: 'Shipped.' }))
+ await routeTask(input, s, where as never, opener())
+ const history = jevCall(s).state.history as string
+ // Oldest first: the log's attempt by an agent the tab no longer has, its stopped new-agent attempt, then the member's finished one with the result its assignment holds.
+ expect(history).toMatch(/Attempts in this group:\n- An agent: stopped\n- New agent \(claude opus\): stopped\n- Multiply: done — Shipped\./)
+ expect(history).toContain('Recent routing in this Super Tab:\n- Pick d7: open\n- Pick d6 (jev): done\n- Pick d5 (jev): stopped\n- Pick d4 (jev): done\n- Pick d3 (jev): stopped')
+ expect(history).not.toContain('Pick d2')
+ // Multiply's earlier work in this Super Tab: the finished assignment (also in the log), and the log's one in a group this tab no longer has.
+ expect(memberLabel(s)).toContain('earlier here: API done; another group done')
+ })
+ it('labels a member with the effort it was launched with when it reports none, and keeps an effort it reports', async () => {
+ const label = async (effort: string | undefined, start: unknown) => {
+ const t = tab(); t.state.agents = [{ ...agents[0], configuration: { engine: 'claude', model: 'sonnet', effort } }, agents[1]] as never
+ ;(t.state as Record<string, unknown>).starts = start === undefined ? undefined : [{ harnessId: 'other', request: { effort: 'low' } }, { harnessId: 'h1', request: start }]
+ const s = scoped(world({ tab: t }))
+ await routeTask(input, s, where as never, opener())
+ return memberLabel(s)
+ }
+ expect(await label('auto', { effort: 'medium' })).toContain('Claude sonnet medium')
+ expect(await label(undefined, { effort: 'medium' })).toContain('Claude sonnet medium')
+ expect(await label('high', { effort: 'medium' })).toContain('Claude sonnet high')
+ expect(await label('auto', undefined)).toContain('Claude sonnet auto')
+ expect(await label('auto', { effort: 'default' })).toContain('Claude sonnet auto')
+ expect(await label('auto', {})).toContain('Claude sonnet auto')
+ // The rating follows the launch effort too: opus rows exist only at high.
+ const t = tab(); t.state.agents = [{ ...agents[0], configuration: { engine: 'claude', model: 'opus', effort: 'auto' } }, agents[1]] as never
+ ;(t.state as Record<string, unknown>).starts = [{ harnessId: 'h1', request: { effort: 'high' } }]
+ const s = scoped(world({ tab: t }))
+ await routeTask(input, s, where as never, opener())
+ expect(memberLabel(s)).toContain('Claude opus high')
+ })
+ it('keeps a stopped attempt in the history and in the member\'s earlier work after the group was defined again', async () => {
+ // `work.define` took the stopped assignment out of the state and no decision of the log names it (a person assigned it).
+ // A row without an id names no assignment and is left out.
+ const attempts = [{ agentId: 'a1', status: 'done' }, { id: 'as-2', agentId: 'a1', status: 'done', result: 'Shipped.' }, { id: 'as-1', agentId: 'a1', status: 'stopped', result: 'Tests failed.' }]
+ const s = scoped(world({ attempts }))
+ await routeTask(input, s, where as never, opener())
+ expect(jevCall(s).state.history).toContain('Attempts in this group:\n- Multiply: stopped — Tests failed.\n- Multiply: done — Shipped.')
+ expect(memberLabel(s)).toContain('earlier here: API done; API stopped')
+ })
+ it('orders the group\'s attempts oldest first, a person\'s assignment before a routed one, and keeps the newest for the member', async () => {
+ // as-1 was assigned by a person (no decision); as-2 was routed. The log alone would list as-2 first.
+ const decision = { id: 'd2', conversationId: 'g1', title: 'Pick', via: 'jev', outcome: 'done', assignmentId: 'as-2', createdAt: '2026-10-19T11:00:00Z', final: { kind: 'member', agentId: 'a1' } }
+ const attempts = [{ id: 'as-2', agentId: 'a1', status: 'done', result: 'Second.', createdAt: '2026-10-19T11:00:00Z' }, { id: 'as-1', agentId: 'a1', status: 'stopped', result: 'First.', createdAt: '2026-10-19T10:00:00Z' }]
+ const s = scoped(world({ decisions: [decision], attempts }, { id: 'as-3', agentId: 'a1', status: 'stopped', result: 'Third.' }))
+ await routeTask(input, s, where as never, opener())
+ expect(jevCall(s).state.history).toContain('Attempts in this group:\n- Multiply: stopped — First.\n- Multiply: done — Second.\n- Multiply: stopped — Third.')
+ expect(memberLabel(s)).toContain('earlier here: API stopped; API done; API stopped')
+ // Without the attempts read the log's order stays.
+ const old = scoped(world({ decisions: [decision], attempts: undefined, attemptsUnreadable: true }, { id: 'as-3', agentId: 'a1', status: 'stopped', result: 'Third.' }))
+ await routeTask(input, old, where as never, opener())
+ expect(jevCall(old).state.history).toContain('Attempts in this group:\n- Multiply: done\n- Multiply: stopped — Third.')
+ })
+ it('lists an attempt once when the log and the attempts both know it', async () => {
+ const decision = { id: 'd5', conversationId: 'g1', title: 'Pick', via: 'jev', outcome: 'stopped', assignmentId: 'as-1', createdAt: '2026-10-19T10:00:00Z', final: { kind: 'new', engine: 'claude', model: 'opus' } }
+ const s = scoped(world({ decisions: [decision], attempts: [{ id: 'as-1', agentId: 'gone', status: 'stopped', result: 'Out of memory.' }] }, { id: 'as-2', agentId: 'a1', status: 'done', result: 'Shipped.' }))
+ await routeTask(input, s, where as never, opener())
+ const history = jevCall(s).state.history as string
+ // The log names the started agent; the attempt gives the result.
+ expect(history).toContain('Attempts in this group:\n- New agent (claude opus): stopped — Out of memory.\n- Multiply: done — Shipped.')
+ expect(history.match(/Out of memory/g)).toHaveLength(1)
+ expect(memberLabel(s)).toContain('earlier here: API done')
+ })
+ it('cuts an attempt\'s result to 200 characters and scrubs it', async () => {
+ const result = `Key sk-${'a1'.repeat(20)} sent to [email protected]. ${'x'.repeat(400)}`
+ const s = scoped(world({ attempts: [{ id: 'as-1', agentId: 'a1', status: 'stopped', result }] }))
+ await routeTask(input, s, where as never, opener())
+ const line = (jevCall(s).state.history as string).split('\n').find(l => l.startsWith('- Multiply: stopped'))!
+ expect(line).toContain('[secret] sent to [email]')
+ expect(line).not.toMatch(/@|sk-/)
+ expect(line.length).toBeLessThanOrEqual('- Multiply: stopped — '.length + 200)
+ })
+ it('keeps the log\'s name for a started agent whose assignment names an agent the tab no longer has', async () => {
+ const decision = { id: 'd5', conversationId: 'g1', title: 'Pick', via: 'jev', outcome: 'stopped', assignmentId: 'as-5', createdAt: '2026-10-19T10:00:00Z', final: { kind: 'new', engine: 'claude', model: 'opus' } }
+ const s = scoped(world({ decisions: [decision] }, { id: 'as-5', agentId: 'gone', status: 'stopped', result: 'Out of memory.' }))
+ await routeTask(input, s, where as never, opener())
+ expect(jevCall(s).state.history).toContain('- New agent (claude opus): stopped — Out of memory.')
+ // A machine that reports no capacity measured nothing, so nothing there can be admitted; the route says so.
+ expect(await routeTask(withCwd, scoped(world()), where as never, opener(id => daemon(id, { agents: id === 'm1' ? ['h1'] : [], capacity: {} })), () => 'op', describeGit())).toMatchObject({ error: 'NO_CANDIDATE' })
+ })
+ it('lists a member\'s earlier work newest first, three at most', async () => {
+ const many = tab(); many.state.conversations = [conversations()[0],
+ ...[1, 2, 3, 4].map(i => ({ id: `e${i}`, title: `Group ${i}`, leadId: 'lead', agentIds: [], archived: false, brief: '', checks: [], assignment: { id: `x${i}`, agentId: 'a1', status: 'stopped', result: null } })),
+ conversations()[1]] as never
+ const s = scoped(world({ tab: many }))
+ await routeTask(input, s, where as never, opener(id => daemon(id, { agents: id === 'm1' ? ['h1'] : [] })))
+ expect(memberLabel(s)).toContain('earlier here: Group 4 stopped; Group 3 stopped; Group 2 stopped')
+ expect(memberLabel(s)).not.toContain('Group 1')
+ })
+ it('still routes when a source cannot be read, and lists each one in the decision', async () => {
+ const run = async (extra: Record<string, unknown>, options: Record<string, unknown> = {}, describeRepo: ReturnType<typeof describeGit> = describeGit()) => {
+ const s = scoped(world(extra))
+ const answer = await routeTask(withCwd, s, where as never, opener(id => daemon(id, { agents: id === 'm1' ? ['h1'] : [], frames: { h1: frame() }, ...options })), () => 'op', describeRepo)
+ expect(answer).toMatchObject({ ok: true })
+ return { s, missing: recorded(s).command.decision.context.missing as string[] }
+ }
+ expect((await run({})).missing).toEqual([])
+ const noMessages = await run({ messages: undefined, messagesUnreadable: true })
+ expect(jevCall(noMessages.s).state.task).toContain('Recent messages: unknown')
+ expect(noMessages.missing).toEqual(['messages'])
+ // An older backend (404) and a failed read both leave the attempts out: today's history, and a note in the decision.
+ const noAttempts = await run({ attempts: undefined, attemptsUnreadable: true })
+ expect(jevCall(noAttempts.s).state.history).toContain('No earlier attempts in this group.')
+ expect(noAttempts.missing).toEqual(['attempts'])
+ const noLog = await run({ decisions: undefined, decisionsUnreadable: true })
+ expect(jevCall(noLog.s).state.history).toContain('Recent routing in this Super Tab: unknown')
+ expect(noLog.missing).toEqual(['route log'])
+ for (const failing of [vi.fn(async () => { throw new Error('git') }), vi.fn(async () => null)]) {
+ const noFolder = await run({}, {}, { ...describeGit(), describe: failing as never })
+ expect(jevCall(noFolder.s).state.lead).toContain('Task folder: api (repository unknown)')
+ expect(memberLabel(noFolder.s)).toContain('repo unknown')
+ expect(noFolder.missing).toEqual(['task folder'])
+ }
+ // A folder read that never answers does not hold the route: it is given up after three seconds.
+ vi.useFakeTimers()
+ try {
+ const pending = run({}, {}, { ...describeGit(), describe: vi.fn(() => new Promise(() => {})) as never })
+ await vi.advanceTimersByTimeAsync(3000)
+ expect((await pending).missing).toEqual(['task folder'])
+ } finally { vi.useRealTimers() }
+ // Without the agent list there is no machine load; the members there cannot run, so only new agents are shown.
+ const noList = await run({}, { listFails: true })
+ expect(noList.missing).toEqual(['machine load'])
+ expect(newLabel(noList.s)).toContain('agents running unknown')
+ })
+ it('finds a member in the task\'s folder when the Lead\'s machine does not have it', async () => {
+ const two = tab(); two.state.agents = [{ ...agents[0], machineId: 'm2' }, agents[1]] as never
+ const s = scoped(world({ tab: two }))
+ const there = frame({ project: git({ remote: null, root: '/w/api', cwd: '/w/api' }) })
+ const reader = describeGit(git(), false)
+ await routeTask(withCwd, s, where as never, opener(id => daemon(id, { agents: id === 'm2' ? ['h1'] : [], frames: { h1: there } })), () => 'op', reader)
+ expect(memberLabel(s)).toContain('same repo')
+ expect(jevCall(s).state.lead).toContain('Task folder: api (not on the Lead\'s machine)')
+ expect(reader.describe).not.toHaveBeenCalled()
+ expect(recorded(s).command.decision.context.missing).toEqual(['task folder'])
+ })
+ it('says a folder is unknown, not missing, when it cannot be told apart from a refusal', async () => {
+ for (const code of ['EACCES', 'ENOTDIR']) {
+ const s = scoped(world())
+ await routeTask(withCwd, s, where as never, opener(), () => 'op', { describe: vi.fn() as never, isDirectory: async () => { throw Object.assign(new Error(code), { code }) } })
+ expect(jevCall(s).state.lead).toContain('Task folder: api (repository unknown)')
+ expect(recorded(s).command.decision.context.missing).toEqual(['task folder'])
+ }
+ })
+ it('reads the task folder on this machine when no reader is given', async () => {
+ const dir = await mkdtemp(join(tmpdir(), 'route-folder-'))
+ try {
+ await writeFile(join(dir, 'file'), 'x')
+ for (const [cwd, folder] of [[dir, 'not a git repository'], [join(dir, 'absent'), 'not on the Lead\'s machine'], [join(dir, 'file', 'inside'), 'repository unknown']] as const) {
+ const s = scoped(world())
+ await routeTask({ ...input, assessment: { ...input.assessment, needs: { cwd } } }, s, where as never, opener(), () => 'op')
+ expect(jevCall(s).state.lead).toContain(folder)
+ }
+ } finally { await rm(dir, { recursive: true, force: true }) }
+ })
+ it('starts the probes before the context reads settle, and gives up on a read that hangs', async () => {
+ const s = scoped({ ...world(), historyHangs: true })
+ const open = opener()
+ vi.useFakeTimers()
+ try {
+ const pending = routeTask(withCwd, s, where as never, open, () => 'op', { describe: vi.fn(() => new Promise(() => {})) as never, isDirectory: async () => true })
+ await vi.advanceTimersByTimeAsync(0)
+ // Both context reads are still waiting, and the machines have already been opened.
+ expect(s.mock.calls.some(c => c[0].action === 'routeHistory')).toBe(true)
+ expect(open).toHaveBeenCalled()
+ expect(s.mock.calls.some(c => c[0].action === 'routeJev')).toBe(false)
+ await vi.advanceTimersByTimeAsync(3000)
+ expect(await pending).toMatchObject({ ok: true })
+ } finally { vi.useRealTimers() }
+ expect(recorded(s).command.decision.context.missing).toEqual(expect.arrayContaining(['messages', 'route log', 'attempts', 'task folder']))
+ })
+ it('lists a member whose machine cannot be opened as one whose activity is unknown', 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(world({ tab: two }))
+ const open = vi.fn(async (_w: unknown, id: string) => id === 'theirs' ? Promise.reject(new Error('not yours')) : daemon(id, { agents: id === 'm1' ? ['h1'] : [], frames: { h1: frame() }, usage: { providers: [] } })) as never
+ await routeTask(input, s, where as never, open)
+ expect(labels(s).find(l => l.startsWith('Member Collab'))).toContain('activity unknown')
+ expect(recorded(s).command.decision.context.missing).toEqual(['member activity'])
+ })
+ it('records no context when Jev was not asked', async () => {
+ const s = scoped(world())
+ 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({ via: 'only' })
+ expect(recorded(s).command.decision).not.toHaveProperty('context')
+ })
+})
diff --git a/cli/src/superTabs/routeCommand.ts b/cli/src/superTabs/routeCommand.ts
index c515c930d..3e91198e7 100644
--- a/cli/src/superTabs/routeCommand.ts
+++ b/cli/src/superTabs/routeCommand.ts
@@ -5,8 +5,10 @@ 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 { object, within } from './wire.js'
+import { choose, contextSize, decide, jevQuestion, parseAssessment, quotaOf2, rateFor, recordOf, repoMatch, type Assessment, type Attempt, type MemberFrame, type Policy, type Probe, type TaskFolder } from './route.js'
+import { stat } from 'node:fs/promises'
+import { describeScmProject } from '../scm/scmProjects.js'
import type { JevChoiceAnswer } from '../lib/jev/jevClient.js'
type Json = Record<string, unknown>
@@ -17,11 +19,81 @@ const TRANSPORT = new Set(['AGENT_UNAVAILABLE', 'SUPER_TAB_UNAVAILABLE', 'BACKEN
const MACHINES_UNREADABLE = "The account's machine list could not be read; only known machines were considered."
const OFFLINE = 'Machine is offline or unreachable.'
const UNKNOWN_QUOTA: Probe['quota'] = { known: false, leftPercent: null, resetsAt: null }
+const UNKNOWN_LOAD: NonNullable<Probe['load']> = { agents: null, freeMemoryBytes: null, hasFolder: null }
const 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) : []
+/** The Lead's machine, for the task's folder; replaced in tests. */
+interface FolderReader { describe: typeof describeScmProject; isDirectory: (path: string) => Promise<boolean> }
+const FOLDER_READER: FolderReader = { describe: describeScmProject, isDirectory: path => stat(path).then(s => s.isDirectory(), (error: NodeJS.ErrnoException) => {
+ // Only an absent folder is "not on this machine"; a refusal or a broken path says nothing, so the read fails and the folder is unknown.
+ if (error.code === 'ENOENT') return false
+ throw error
+ }) }
+async function readFolder(cwd: string, reader: FolderReader): Promise<TaskFolder> {
+ const folder = { cwd, name: null, root: null, remote: null }
+ // The SCM description only checks the path's form, so a folder this machine lacks must be found out first.
+ if (!await reader.isDirectory(cwd)) return { ...folder, kind: 'missing' }
+ const described = await reader.describe(cwd)
+ if (!described) return { ...folder, kind: 'unknown' }
+ return { cwd, kind: described.kind, name: described.kind === 'git' ? described.name : null, root: described.root, remote: described.remote }
+}
+const text = (value: unknown) => typeof value === 'string' ? value : null
+/** A member started by `start` was launched with `--effort`, which Claude never reports back, so its configuration says
+ * `auto` (manual run 2026-10-19). The tab's start record still holds what it was launched with; an effort the member
+ * does report is kept. */
+function withLaunchEffort(member: Json, starts: Json[]): Json {
+ const configuration = object(member.configuration)
+ if (configuration.effort && configuration.effort !== 'auto') return member
+ const launched = object(starts.find(s => s.harnessId === member.harnessId)?.request).effort
+ return typeof launched === 'string' && launched !== 'default' ? { ...member, configuration: { ...configuration, effort: launched } } : member
+}
+const finite = (value: unknown): value is number => typeof value === 'number' && Number.isFinite(value)
+
+/** Work that ended in this Super Tab, oldest first: the log's decisions, the group's attempts and each group's last
+ * assignment, joined by assignment id. The log knows which agent a decision started; the attempts are every earlier
+ * assignment of this group, also those `work.define` took out of the state (a person's assignment has no decision);
+ * the state knows the agent and the result of each group's last one. */
+interface Ended { assignmentId: string; groupId: string; group: string; agentId: string | null; agent: string; outcome: string; result?: string }
+function endedWork(conversations: Json[], agents: Json[], decisions: Json[] | null, attempts: Json[] | null, attemptsGroup: string): Ended[] {
+ const titleOf = (id: unknown) => String(conversations.find(c => c.id === id)?.title ?? 'another group')
+ const nameOf = (id: unknown) => text(agents.find(a => a.id === id)?.name)
+ const ended: Ended[] = [...(decisions ?? [])].reverse().flatMap(d => {
+ const final = object(d.final)
+ return typeof d.assignmentId === 'string' && ['done', 'stopped'].includes(String(d.outcome)) && final.kind
+ ? [{ assignmentId: d.assignmentId, groupId: String(d.conversationId), group: titleOf(d.conversationId), outcome: String(d.outcome),
+ agentId: final.kind === 'member' ? String(final.agentId) : null,
+ agent: final.kind === 'member' ? nameOf(final.agentId) ?? 'An agent' : `New agent (${String(final.engine)} ${String(final.model)})` }]
+ : []
+ })
+ // The assignment's own record wins on agent and outcome; a started agent the tab no longer has keeps the log's name.
+ const join = (assignment: Json, groupId: string) => {
+ const result = text(assignment.result) ?? undefined, known = ended.find(e => e.assignmentId === assignment.id)
+ if (known) return Object.assign(known, { agentId: String(assignment.agentId), agent: nameOf(assignment.agentId) ?? known.agent, result })
+ const added: Ended = { assignmentId: String(assignment.id), groupId, group: titleOf(groupId), agentId: String(assignment.agentId), agent: nameOf(assignment.agentId) ?? 'An agent', outcome: String(assignment.status), result }
+ ended.push(added)
+ return added
+ }
+ // With the attempts read the group's own work is ordered by it: oldest first, then the current assignment. The log's
+ // order alone puts a routed attempt before an earlier one a person assigned (it has no decision). Without the read
+ // the log's order stays.
+ const last = (e: Ended) => { if (attempts) ended.push(...ended.splice(ended.indexOf(e), 1)) }
+ const time = (a: Json) => Date.parse(String(a.createdAt)) || 0
+ for (const attempt of [...(attempts ?? [])].reverse().sort((x, y) => time(x) - time(y))) if (attempt.id) last(join(attempt, attemptsGroup))
+ for (const c of conversations) {
+ const current = object(c.assignment)
+ if (current.id && !active(current)) last(join(current, String(c.id)))
+ }
+ return ended
+}
+/** The fields of a frame that say what the agent works on; an absent or malformed one says nothing. */
+function frameOf(frame: Json): MemberFrame {
+ const project = object(frame.project), updatedAt = Date.parse(String(frame.updatedAt))
+ return { title: text(frame.title), project: text(project.name), cwd: text(project.cwd), root: text(project.root), remote: text(project.remote),
+ branch: text(object(object(frame.gitContext).current).branch) ?? text(project.branch), updatedAt: Number.isFinite(updatedAt) ? updatedAt : null }
+}
export async function routeTask(input: { tabId: string; conversationId: string; assessment: unknown }, request: ScopedRequest, where: Where,
- open: typeof openDaemon = openDaemon, newId: () => string = randomUUID): Promise<Json> {
+ open: typeof openDaemon = openDaemon, newId: () => string = randomUUID, reader: FolderReader = FOLDER_READER): 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) {
@@ -30,6 +102,7 @@ export async function routeTask(input: { tabId: string; conversationId: string;
}
const assessment = parseAssessment(input.assessment)
if (typeof assessment === 'string') return { error: 'INVALID_REQUEST', detail: assessment }
+ const cwd = assessment.needs.cwd
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)
@@ -41,7 +114,7 @@ export async function routeTask(input: { tabId: string; conversationId: string;
// 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)))
+ const members = agents.filter(a => !busy.has(String(a.id)) && ENGINES.includes(String(object(a.configuration).engine))).map(a => withLaunchEffort(a, list(state.starts)))
// 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 }>()
@@ -51,20 +124,37 @@ export async function routeTask(input: { tabId: string; conversationId: string;
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()
+ // The probes do not wait for the context reads: the machines, the task's folder and the group's talk and log are read
+ // together, and each read that is only context gives up after three seconds. What needs several of them (whether a
+ // member is in the task's repository, what it did before) is joined afterwards.
+ const [probed, read, history] = await Promise.all([
+ Promise.all([...machines].map(([machineId, machine]) =>
+ probeMachine(machineId, machine, members.filter(m => m.machineId === machineId), enabled, policy, assessment, where, open))),
+ cwd ? within(readFolder(cwd, reader)) : null,
+ within(scoped({ action: 'routeHistory', conversationId: input.conversationId })),
+ ])
+ const folder: TaskFolder | null = !cwd ? null : read ?? { cwd, kind: 'unknown', name: null, root: null, remote: null }
+ const past = object(history?.ok === true ? history.value : {})
+ const decisions = Array.isArray(past.decisions) ? list(past.decisions) : null
+ const messages = Array.isArray(past.messages) ? list(past.messages).map(m => ({ from: String(m.from), text: String(m.text) })) : null
+ const attempts = Array.isArray(past.attempts) ? list(past.attempts) : null
+ const ended = endedWork(conversations, agents, decisions, attempts, input.conversationId)
+ const probes = probed.flat().map(p => p.kind === 'member' ? { ...p, repo: repoMatch(folder, p.frame ?? null, p.machineId === where.machineId),
+ earlier: ended.filter(e => e.agentId === p.agentId).reverse().slice(0, 3).map(e => ({ group: e.group, outcome: e.outcome })) } : p)
const choice = choose(probes, policy, assessment, Date.now())
if ('error' in choice) return choice
+ // What Jev could not be told, for the decision log: pick quality can later be compared with how complete this was.
+ const missing = [...(messages ? [] : ['messages']), ...(decisions ? [] : ['route log']), ...(attempts ? [] : ['attempts']), ...(folder && ['unknown', 'missing'].includes(folder.kind) ? ['task folder'] : []),
+ ...(choice.shown.some(s => s.kind === 'member' && !s.frame) ? ['member activity'] : []),
+ ...(choice.shown.some(s => s.kind === 'new' && (s.load!.agents === null || s.load!.freeMemoryBytes === null)) ? ['machine load'] : [])]
- let answer: JevChoiceAnswer | undefined, unavailable: string | null = null
+ let answer: JevChoiceAnswer | undefined, unavailable: string | null = null, question: ReturnType<typeof jevQuestion> | undefined
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)
+ // Every attempt in this group that ended: a worker that stopped on this task is a worse choice.
+ const attempts: Attempt[] = ended.filter(e => e.groupId === input.conversationId).map(e => ({ agent: e.agent, outcome: e.outcome, ...(e.result ? { result: e.result } : {}) }))
+ const recent = decisions?.slice(0, 5).map(d => ({ title: String(d.title), ...(typeof d.via === 'string' ? { via: d.via } : {}), outcome: text(d.outcome) })) ?? null
+ question = jevQuestion({ title: String(group.title ?? ''), brief: String(group.brief ?? ''), checks, messages, noneInLatest: past.noneInLatest === true, folder, attempts, recent }, 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)
@@ -73,7 +163,7 @@ export async function routeTask(input: { tabId: string; conversationId: string;
}
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) } })
+ command: { type: 'route.record', conversationId: input.conversationId, decision: recordOf(choice, verdict, assessment, policy, question && { chars: contextSize(question), missing }) } })
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}"` : ''
@@ -96,16 +186,16 @@ async function probeMachine(machineId: string, { name: machineName, status, acco
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 memberProbe = (m: Json, refusals: string[] = [], quota = UNKNOWN_QUOTA, frame: MemberFrame | null = null): 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 }
+ quota, activity: 'idle', known: quota.known, refusals, frame }
}
- const newProbe = (m: Policy['models'][number], refusals: string[], quota: Probe['quota'], known: boolean): Probe => ({
+ const newProbe = (m: Policy['models'][number], refusals: string[], quota: Probe['quota'], known: boolean, load: Probe['load'] = UNKNOWN_LOAD): 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 })
+ quota, activity: 'new agent', known, refusals, load })
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()]
@@ -116,7 +206,8 @@ async function probeMachine(machineId: string, { name: machineName, status, acco
}
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)))
+ const frames = list(listed.agents)
+ const live = new Set(frames.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>>>()
@@ -132,11 +223,17 @@ async function probeMachine(machineId: string, { name: machineName, status, acco
// 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)))
+ const frame = frames.find(f => f.id === m.harnessId)
+ probes.push(memberProbe(m, refusals, quotaOf2(inspected.quota), frame ? frameOf(frame) : null))
}
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))
+ const resources = object(inspected.capacity.resources)
+ // The capacity probe already measured the task's folder (its disk), so the answer is reused, not asked again.
+ const load = { agents: Array.isArray(listed.agents) ? frames.length : null,
+ freeMemoryBytes: finite(resources.memoryTotalBytes) && finite(resources.memoryUsedBytes) ? resources.memoryTotalBytes - resources.memoryUsedBytes : null,
+ hasFolder: a.needs.cwd ? finite(resources.projectDiskFreeBytes) : null }
+ probes.push(newProbe(m, inspected.allowed ? [] : inspected.reasons, quotaOf2(inspected.quota), inspected.unknown.length === 0 && inspected.quota.known, load))
}
return probes
} finally { target.close() }
diff --git a/cli/src/superTabs/service.spec.ts b/cli/src/superTabs/service.spec.ts
index 113a4b242..f1fb7486f 100644
--- a/cli/src/superTabs/service.spec.ts
+++ b/cli/src/superTabs/service.spec.ts
@@ -1,5 +1,5 @@
import { createHash } from 'node:crypto'
-import { expect, it, vi } from 'vitest'
+import { describe, expect, it, vi } from 'vitest'
import { fakeCore } from '../testing/fakeCore.js'
import { superTabService } from './service.js'
import type { SuperTabHost } from './host.js'
@@ -113,6 +113,111 @@ it('returns the routing context to a verified contribution', async () => {
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)
})
+describe('routeHistory for Jev', () => {
+ const contextOf = (t: ReturnType<typeof setup>, read: (path: string) => Promise<unknown>, lead?: string) => {
+ const state = { agents: [{ ...t.agent, name: 'Boss' }, { id: 'a2', name: 'Multiply' }, { id: 'a3', name: 'Reader' }], conversations: [{ id: 'g1', leadId: lead ?? t.agentId }] }
+ vi.mocked(t.core.account.backend).mockImplementation(async (_method, path) => {
+ if (path.includes('/messages') || path.includes('/route-decisions') || path.includes('/attempts')) return await read(path) as never
+ return { status: 200, body: { success: true, data: path.includes('/routing-policy') ? { policy: { version: 1 }, warnings: [] } : { state } } }
+ })
+ t.core.account.machines = vi.fn(async () => ({ status: 200, body: { data: { machines: [] } } }))
+ return t.ask({ action: 'routeHistory', tabId: 'tab', harnessId: 'native', conversationId: 'g1' }, owner) as Promise<{ value: Record<string, unknown> }>
+ }
+ const ok = (data: unknown) => ({ status: 200, body: { success: true, data } })
+ it('gives the last ten group messages with a role instead of an author, and never an agent transcript or a routing note', async () => {
+ const t = setup()
+ const person = (text: string) => ({ author: { kind: 'person', id: 'u1', name: '[email protected]' }, text })
+ const rows = [
+ ...Array.from({ length: 8 }, (_, i) => person(`early ${i}`)),
+ { author: { kind: 'agent', id: t.agentId, name: 'Boss' }, text: 'Lead says' },
+ { author: { kind: 'agent', id: 'a2', name: 'Multiply' }, text: 'Worker says', source: null },
+ { author: { kind: 'agent', id: 'a2', name: 'Multiply' }, text: 'TRANSCRIPT', source: { kind: 'native', phase: 'answer' } },
+ { author: { kind: 'agent', id: t.agentId, name: 'Boss' }, text: 'Routed to X', source: { kind: 'route', decisionId: 'd' } },
+ { author: { kind: 'agent', id: 'gone', name: 'Gone' }, text: 'x'.repeat(1500) },
+ { author: { kind: 'agent', id: 'a3', name: 'Reader' }, text: 'last' },
+ ]
+ const { value } = await contextOf(t, async path => path.includes('/messages') ? ok({ messages: rows }) : ok([]))
+ const messages = value.messages as Array<{ from: string; text: string }>
+ expect(messages.map(m => m.from)).toEqual([...Array(6).fill('person'), 'Lead', 'Multiply', 'agent', 'Reader'])
+ expect(messages[0].text).toBe('early 2')
+ expect(messages[8].text).toBe('x'.repeat(1000))
+ expect(JSON.stringify(value.messages)).not.toMatch(/@|TRANSCRIPT|Routed to/)
+ expect(value).not.toHaveProperty('messagesUnreadable')
+ expect(vi.mocked(t.core.account.backend)).toHaveBeenCalledWith('GET', `/api/super-tabs/tab/conversations/g1/messages?asAgentId=${t.agentId}`, undefined)
+ })
+ it('says the latest page held only log rows, instead of saying nothing was said', async () => {
+ const only = [{ author: { kind: 'agent', id: 'a2', name: 'Multiply' }, text: 'T', source: { kind: 'native' } }]
+ const { value } = await contextOf(setup(), async path => path.includes('/messages') ? ok({ messages: only }) : ok([]))
+ expect(value).toMatchObject({ messages: [], noneInLatest: true })
+ const empty = await contextOf(setup(), async path => path.includes('/messages') ? ok({ messages: [] }) : ok([]))
+ expect(empty.value).toEqual({ messages: [], decisions: [], attempts: [] })
+ })
+ it('is for the Lead of the group only, like the route', async () => {
+ const t = setup()
+ expect(await contextOf(t, async () => ok([]), 'someone-else')).toMatchObject({ error: 'LEAD_REQUIRED', status: 403 })
+ expect(vi.mocked(t.core.account.backend)).not.toHaveBeenCalledWith('GET', expect.stringContaining('/messages'), undefined)
+ })
+ it('gives the latest routing decisions in brief, newest first, without their records', async () => {
+ const t = setup()
+ const decision = (i: number) => ({ id: `d${i}`, conversationId: 'g1', record: { pick: 'c1', via: i === 2 ? undefined : 'jev', candidates: [{ id: 'c0', title: 'Other' }, { id: 'c1', title: `Pick ${i}`, label: 'big'.repeat(100) }] },
+ final: i % 2 ? { kind: 'member', agentId: 'a2', machineId: 'm1' } : { kind: 'new', startId: 's', machineId: 'm1', engine: 'claude', model: 'opus', effort: 'high' },
+ outcome: i % 3 ? 'done' : null, assignmentId: `as${i}`, createdAt: '2026-10-19T10:00:00Z', outcomeAt: null })
+ const unfinished = { id: 'dx', conversationId: 'g1', record: { pick: 'c9', via: 'order', candidates: [] }, final: null, outcome: 'superseded', assignmentId: null, createdAt: '2026-10-19T09:00:00Z' }
+ const { value } = await contextOf(t, async path => path.includes('/messages') ? ok({ messages: [] }) : ok([...Array.from({ length: 60 }, (_, i) => decision(i)), unfinished]))
+ const decisions = value.decisions as Array<Record<string, unknown>>
+ expect(decisions).toHaveLength(50)
+ expect(decisions[0]).toEqual({ id: 'd0', conversationId: 'g1', title: 'Pick 0', via: 'jev', outcome: null, assignmentId: 'as0', createdAt: '2026-10-19T10:00:00Z',
+ final: { kind: 'new', engine: 'claude', model: 'opus' } })
+ expect(decisions[1]).toMatchObject({ final: { kind: 'member', agentId: 'a2' }, outcome: 'done' })
+ expect(decisions[2]).not.toHaveProperty('via')
+ expect(JSON.stringify(decisions)).not.toContain('bigbig')
+ const last = await contextOf(setup(), async path => path.includes('/messages') ? ok({ messages: [] }) : ok([unfinished]))
+ expect(last.value.decisions).toEqual([{ id: 'dx', conversationId: 'g1', title: 'unknown pick', via: 'order', outcome: 'superseded', assignmentId: null, createdAt: '2026-10-19T09:00:00Z', final: null }])
+ })
+ it('gives every attempt of the group, newest first, with only what Jev needs and no more than fifty', async () => {
+ const t = setup()
+ const row = (i: number) => ({ id: `as${i}`, agentId: i % 2 ? 'a2' : 'gone', status: 'stopped', result: i === 0 ? 'Tests failed.' : i === 2 ? 'y'.repeat(900) : null, createdAt: '2026-10-19T10:00:00Z',
+ conversationId: 'g1', execution: { harnessId: 'secret' } })
+ const { value } = await contextOf(t, async path => path.includes('/attempts') ? ok(Array.from({ length: 60 }, (_, i) => row(i))) : ok(path.includes('/messages') ? { messages: [] } : []))
+ const attempts = value.attempts as Array<Record<string, unknown>>
+ expect(attempts).toHaveLength(50)
+ expect(attempts[0]).toEqual({ id: 'as0', agentId: 'gone', status: 'stopped', result: 'Tests failed.', createdAt: '2026-10-19T10:00:00Z' })
+ expect(attempts[1]).toEqual({ id: 'as1', agentId: 'a2', status: 'stopped', result: null, createdAt: '2026-10-19T10:00:00Z' })
+ expect(attempts[2].result).toBe('y'.repeat(500))
+ expect(JSON.stringify(attempts)).not.toContain('secret')
+ expect(value).not.toHaveProperty('attemptsUnreadable')
+ expect(vi.mocked(t.core.account.backend)).toHaveBeenCalledWith('GET', `/api/super-tabs/tab/conversations/g1/attempts?asAgentId=${t.agentId}`, undefined)
+ })
+ it('marks the attempts unreadable when an older backend answers 404 or the read fails or hangs', async () => {
+ const without = (path: string) => path.includes('/messages') ? ok({ messages: [] }) : ok([])
+ const old = await contextOf(setup(), async path => path.includes('/attempts') ? { status: 404, body: { success: false, error: { code: 'NOT_FOUND' } } } : without(path))
+ expect(old.value).toMatchObject({ messages: [], decisions: [], attemptsUnreadable: true })
+ expect(old.value).not.toHaveProperty('attempts')
+ const failed = await contextOf(setup(), async path => path.includes('/attempts') ? Promise.reject(new Error('down')) : without(path))
+ expect(failed.value).toMatchObject({ attemptsUnreadable: true, messages: [] })
+ const odd = await contextOf(setup(), async path => path.includes('/attempts') ? ok({ attempts: 'no' }) : without(path))
+ expect(odd.value).toMatchObject({ attemptsUnreadable: true })
+ vi.useFakeTimers()
+ try {
+ const slow = contextOf(setup(), async path => path.includes('/attempts') ? new Promise(() => {}) : without(path))
+ await vi.advanceTimersByTimeAsync(3000)
+ expect((await slow).value).toMatchObject({ messages: [], decisions: [], attemptsUnreadable: true })
+ } finally { vi.useRealTimers() }
+ })
+ it('marks each source it could not read on its own, and never waits longer than three seconds for one', async () => {
+ const failed = await contextOf(setup(), async path => path.includes('/messages') ? Promise.reject(new Error('down')) : ok([]))
+ expect(failed.value).toMatchObject({ messagesUnreadable: true, decisions: [] })
+ expect(failed.value).not.toHaveProperty('decisionsUnreadable')
+ const odd = await contextOf(setup(), async path => path.includes('/messages') ? ok({ messages: 'no' }) : { status: 503, body: { error: 'SERVICE_UNAVAILABLE' } })
+ expect(odd.value).toMatchObject({ messagesUnreadable: true, decisionsUnreadable: true })
+ vi.useFakeTimers()
+ try {
+ const slow = contextOf(setup(), async path => path.includes('/messages') ? ok({ messages: [] }) : new Promise(() => {}))
+ await vi.advanceTimersByTimeAsync(3000)
+ expect((await slow).value).toMatchObject({ messages: [], decisionsUnreadable: true })
+ } finally { vi.useRealTimers() }
+ })
+})
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')
diff --git a/cli/src/superTabs/service.ts b/cli/src/superTabs/service.ts
index b769e74c9..efbd3884d 100644
--- a/cli/src/superTabs/service.ts
+++ b/cli/src/superTabs/service.ts
@@ -3,6 +3,7 @@ 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 { within } from './wire.js'
import { createJevDecide, type JevDecide } from '../lib/jev/jevClient.js'
import { machineChoices } from '../lib/newCommand.js'
import { START_REQUIREMENTS } from './capacity.js'
@@ -32,6 +33,8 @@ const HELP = {
],
}
+const list = (value: unknown) => Array.isArray(value) ? value.map(object) : []
+
export interface SuperTabServiceOptions {
capacity?: typeof readCapabilities
host?: (core: CoreApi, machineId: string) => SuperTabHost
@@ -118,6 +121,37 @@ export function superTabService(core: CoreApi, options: SuperTabServiceOptions =
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 }) } }
}
+ // What Jev reads besides the candidates. Apart from `routeContext` so the Lead reads it while it probes the
+ // machines; the group's Lead only, like the route itself.
+ if (payload.action === 'routeHistory') {
+ const group = list(state.conversations).find(c => c.id === payload.conversationId)
+ if (!group || group.leadId !== agentId) return { error: 'LEAD_REQUIRED', detail: 'The coordinating Lead of this group owns routing.', status: 403 }
+ const [written, logged, tried] = await Promise.all([
+ within(backend(core, 'GET', `${path}/conversations/${payload.conversationId}/messages?${identity}`)),
+ within(backend(core, 'GET', `${path}/route-decisions?${identity}`)),
+ // An older backend has no such route: its 404 is unreadable like any other failure.
+ within(backend(core, 'GET', `${path}/conversations/${payload.conversationId}/attempts?${identity}`)),
+ ])
+ // Jev reads the group's talk as roles: an email is a person's name here, so it never leaves this step.
+ // Native rows are an agent's own transcript and route rows are the log's, so only the talk is kept.
+ const rows = Array.isArray(object(written).messages) ? list(object(written).messages) : null
+ const messages = rows?.filter(m => !m.source).slice(-10).map(m => {
+ const by = object(m.author)
+ return { from: by.kind === 'person' ? 'person' : by.id === group.leadId ? 'Lead' : String(list(state.agents).find(a => a.id === by.id)?.name ?? 'agent'),
+ text: String(m.text ?? '').slice(0, 1000) }
+ })
+ // The log's records carry every candidate's line; Jev needs only who was picked and how it went.
+ const decisions = Array.isArray(logged) ? logged.slice(0, 50).map(object).map(d => {
+ const record = object(d.record), final = object(d.final)
+ return { id: d.id, conversationId: d.conversationId, title: String(list(record.candidates).find(c => c.id === record.pick)?.title ?? 'unknown pick'),
+ ...(typeof record.via === 'string' ? { via: record.via } : {}), outcome: d.outcome ?? null, assignmentId: d.assignmentId ?? null, createdAt: d.createdAt,
+ final: final.kind === 'member' ? { kind: 'member', agentId: final.agentId } : final.kind === 'new' ? { kind: 'new', engine: final.engine, model: final.model } : null }
+ }) : null
+ // Every attempt the group had, also the ones `work.define` took out of the state; the server already cut the results.
+ const attempts = Array.isArray(tried) ? tried.slice(0, 50).map(object).map(a => ({ id: a.id, agentId: a.agentId, status: a.status, result: typeof a.result === 'string' ? a.result.slice(0, 500) : null, createdAt: a.createdAt ?? null })) : null
+ return { ok: true, value: { ...(messages ? { messages, ...(rows!.length && !messages.length ? { noneInLatest: true } : {}) } : { messagesUnreadable: true }),
+ ...(decisions ? { decisions } : { decisionsUnreadable: true }), ...(attempts ? { attempts } : { attemptsUnreadable: 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
diff --git a/cli/src/superTabs/wire.ts b/cli/src/superTabs/wire.ts
index 2d1e00877..80f7421f3 100644
--- a/cli/src/superTabs/wire.ts
+++ b/cli/src/superTabs/wire.ts
@@ -1,3 +1,8 @@
type Json = Record<string, unknown>
export const object = (v: unknown): Json => v && typeof v === 'object' && !Array.isArray(v) ? v as Json : {}
export const identifier = (v: unknown): v is string => typeof v === 'string' && /^[A-Za-z0-9_-]{1,160}$/.test(v)
+/** A read that only adds context to a decision: it answers within `ms` or not at all, and never fails the request. */
+export async function within<T>(read: Promise<T>, ms = 3000): Promise<T | null> {
+ let timer: NodeJS.Timeout | undefined
+ try { return await Promise.race([read, new Promise<null>(resolve => { timer = setTimeout(resolve, ms, null) })]) } catch { return null } finally { clearTimeout(timer) }
+}
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.md
index 6997c3b8f..ad6857a59 100644
--- 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.md
@@ -135,23 +135,84 @@ The policy order (D) is fixed in code and is not configurable:
### What Jev is given
-One choice question, "Which candidate should do this task?", with one criterion line per candidate.
+Jev decides, so it is given enough to decide on: what the task is, what each candidate is doing now and
+has done, what the machines have, every quota window, and what was tried before. One choice question,
+"Which candidate should do this task?", with one criterion line per candidate.
+
+The hosted route allows 4 string keys and 17,000 characters of `state`, criteria of at most 640
+characters, instructions of at most 1,500 and 48 criteria. The state keeps four keys, each with its own
+budget, so that a long brief cannot push out the messages or the history. A part is cut at its own budget
+and the cut is marked with "…". For the two logs (messages and attempts) the **newest** lines are kept and
+a leading "…" says older ones were dropped.
```
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"
+ task (7,000): group title (160); brief (2,000); checks (1,000);
+ the last 10 messages of the group, newest last (3,500), tagged "person", "Lead"
+ or the agent's name: "person: Please add the endpoint." / "Lead: On it."
+ lead (1,000): difficulty, risk, why (300); the task folder as a basename and, when it is a git
+ repository on the Lead's machine, the repository name; needs (tools, devices)
+ policy (1,000): why the floor is what it is (the difficulty's quality, plus one for high risk, at
+ most 3); the cost scale ("cost is relative: cost 3 is about 3 times cost 1"); notes
+ history (6,000): every ended attempt in this group (agent, outcome, result cut at 200 characters);
+ the Super Tab's last 5 routing decisions (pick, via, outcome)
+criteria (640 each, most telling parts first, the end is what a cut removes):
+ c0: "Member Multiply · Claude opus high · quality 3, cost 3 · remote-1 · idle · same repo ·
+ on "Fix auth" · in api, branch feat/auth · last active 2h ago ·
+ quota 5-hour 60% left (resets in 2h), weekly 90% left (resets in 5 days) ·
+ earlier here: API done; Docs stopped"
+ c1: "New agent · Codex gpt-5 medium · quality 2, cost 1 · Mac · new agent · has the task folder ·
+ 3 agents running · 6.5 GB memory free · quota 5-hour 90% left (resets in 4h), weekly 70% 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.
+A member's effort in the label is the one its configuration reports. When that is missing or `auto` (Claude never
+reports the effort it was launched with), it comes from the tab's start record (`request.effort` of the `starts`
+entry with the member's `harnessId`), unless that is `default`. The value feeds both the label and the quality/cost
+rating.
+
+Where each piece comes from, all read by the Lead's `route` (the attempts read, below, is the one backend endpoint this adds):
+
+| Piece | Source |
+|---|---|
+| Messages | `GET /api/super-tabs/:tab/conversations/:group/messages` as the Lead, in the service action `routeHistory` (the group's Lead only, like `routeJev`), read alongside the machine probes. Only plain group talk is kept: rows with a `source` (a native agent transcript, a route note) are dropped. Authors become roles in the service; a person's name is their email and never leaves it. |
+| Task folder | `needs.cwd`. The Lead's machine first checks that the folder exists; if not, Jev is told "not on the Lead's machine" and `task folder` is logged as missing. Otherwise the SCM description gives the repository's name, remote and root. |
+| Member activity | The member's `agents_list` frame on its machine: session `title`, `project` (name, remote, root, cwd), the git branch and `updatedAt`, shown as "last active 2h ago". |
+| Same repo | The strongest member signal. The same remote is the same repository wherever the checkout is; a member standing exactly in `needs.cwd` (its root or cwd) is in it on any machine, since the path is the one that will run the task; otherwise the same root counts only on the Lead's own machine. A member whose frame names no checkout, or whose machine cannot be compared, is "repo unknown", not "different repo". Shown only when the Lead named a folder. |
+| Earlier work | The member's ended assignments in this Super Tab (group and outcome, newest first, three at most), from the group's attempts read, the decision log and the tab state. The group's own entries are ordered oldest first by the attempts read, the current assignment last; without that read the log's order stays. |
+| New agents | The capacity probe's answer for the task folder (`has the task folder`), the number of agents in the machine's `agents_list`, and free memory from the capacity resources. |
+| Quota | Every window the reader reports, by name (`5-hour`, `weekly`), each with the percentage left and a relative reset. The tightest window still orders the candidates. |
+| Attempts | Every earlier attempt of the group, from `GET /api/super-tabs/:tab/conversations/:group/attempts?asAgentId=`, read by `routeHistory` in parallel with the messages and the log. `work.define` takes a stopped assignment out of the tab state, so without this read a retried group looked untried (manual run 2026-10-19). The log's ended decisions and the group's current assignment are joined to it by assignment id, so an attempt shows once; the log still names the agent that a decision started. Each shows the agent, the outcome and the result, scrubbed and cut at 200 characters. The same attempts feed the member's "earlier here". |
+| Recent decisions | The first 5 of the same log, newest first. A decision without a recorded `via` shows without it. |
+
+A source that cannot be read (an offline machine, a failed read, a missing frame) is left out and
+replaced by one phrase: "Recent messages: unknown", "activity unknown", "repo unknown", "agents running
+unknown", "free memory unknown", "repository unknown", "Recent routing in this Super Tab: unknown". An older backend that answers 404 to the attempts read is a failed read: the history falls back to the log and the current assignment, and `attempts` is logged as missing. Routing
+never waits on or fails because of context: once `routeContext` has named the machines and members, the probes,
+the task folder read and `routeHistory` (messages, decisions and attempts) start together, and each context read gives up
+after three seconds. What needs several of them (whether a member is in the task's repository, its earlier
+work) is joined afterwards. When the latest 100 messages hold only log rows, Jev is told "none in the latest 100
+messages".
+
+**What Jev never receives:** emails, tokens, credentials, or an agent's transcript. Session titles are short
+summaries and are allowed. Group messages carry the same exposure as the brief, which is the same exposure as
+the voice router: the task text goes to OpenRouter, or through the backend with the hosted key.
+
+**Scrubbing.** Every piece of free text (messages, results, titles, branches, notes, names) is scrubbed
+before it is cut, so a cut cannot leave half a key behind. Email-like strings become "[email]". Token-like
+strings become "[secret]": `sk-…`, `ghp_…` and the other GitHub prefixes, `xox…-`, AWS `AKIA…`,
+`Bearer <20+ characters>`, a JWT, and runs of 32 or more hex characters. A base64 or base64url key of 32 or
+more characters is recognised by having upper case, lower case and digits and no words joined by hyphens;
+`/` and `.` end a run, so paths, URLs, branch names, UUIDs and file names are kept. A commit id is replaced:
+a lost id costs less than a leaked key.
+
+**Decision log.** The record carries `context: { chars, missing }`: how many characters Jev was given in all
+(state, criteria and instructions) and which sources could not be read (`messages`, `route log`,
+`attempts`, `task folder`, `member activity`, `machine load`). It is optional, absent when Jev was not asked, and lets
+pick quality be compared with how complete the context was.
+
+Instructions tell Jev to prefer a member marked "same repo" over an equal candidate, to treat a candidate that
+already failed or stopped on this task as worse, and not to read "unknown" as a bad sign.
### Reading the answer
@@ -186,6 +247,7 @@ small. Each record holds:
- 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`;
+- `context`: the size of what Jev was given and the sources it lacked (see "What Jev is given");
- `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;
@@ -267,6 +329,11 @@ Writes and links:
- 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.
+- The attempts of one group are read through `GET /api/super-tabs/:tabId/conversations/:conversationId/attempts`,
+ authorized like the messages read (a member of the tab, or an agent through `asAgentId` with the same checks;
+ never across tabs). It returns at most 50, newest first, each with `id`, `agentId`, `status`, `result` (cut at
+ 500 characters) and `createdAt` (when the assignment was replaced). Execution grants, receipts and the
+ configuration stay on the server.
v1 has no analysis screen.
### Timing: the Lead is never blocked
@@ -313,6 +380,7 @@ Limits:
- at most 12 candidates shown to Jev;
- `why` at most 300 characters, the brief cut at 2000, `notes` at most 500;
+- the state parts within their budgets (7,000, 1,000, 1,000 and 6,000 characters), each criterion within 640;
- one open decision per group;
- at most 30 `route` calls per tab per hour, so a looping Lead cannot spend the Jev budget.
@@ -324,13 +392,18 @@ Limits:
- `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.
+ - the context respects every limit, at the worst case, and contains no email or token (each token shape is scrubbed);
+ - every new label, the same-repo marking, both quota windows, and a phrase for each missing source;
+ - each context source failing on its own still routes, and is listed in the record's `context.missing`.
+ - a stopped attempt stays in the history after a new definition, shows once when the log also knows it, and has its result scrubbed;
+ - the Lead's reason ends in exactly one period.
- **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.
+ - the attempts read lists a stopped attempt after a new `work.define`, lets a viewer read, refuses a non-member and never crosses tabs.
- **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;