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.

⌘B: route by the same work on the same subject — hill-climbed on a real desk (#1156)

Dee93d49e9c873d
diff --git a/cli/scripts/route-eval/README.md b/cli/scripts/route-eval/README.md
new file mode 100644
index 000000000..91c1fbde7
--- /dev/null
+++ b/cli/scripts/route-eval/README.md
@@ -0,0 +1,18 @@
+# ⌘B's router, measured on a real desk
+
+How ⌘B's routing was hill-climbed (docs/design/2026-10-09-auto-router.md), and how to do it again.
+Nothing here sends anything: the router only decides. Each decision costs about $0.0002 of the
+OpenRouter key the router uses.
+
+1. Snapshot the desk, from `cli/`: `node scripts/route-eval/collect.mjs ~/route-eval/desk.json`.
+ It holds your sessions' names, last prompts and summaries: keep it out of the repository.
+2. Write cases against it, in English, as a person really types:
+ `[{"text": "...", "want": [index, ...] or ["new"], "last": index (optional), "why": "..."}]`.
+ `want` is the desk index (or indexes, when two are equally right) the message belongs to, or `"new"`.
+ `last` is where the previous ⌘B message went, for a follow-up. Have someone who did not write the
+ router write some of them blind, keep a set held out until the end, and have a red team write
+ messages to break it: sets written while reading the sessions are too easy.
+3. Run them through the router as the desktop calls it:
+ `npx tsx scripts/route-eval/eval.mts ~/route-eval/desk.json ~/route-eval/cases.json 3`.
+ A WRONG send (a message typed into the wrong conversation) is the failure that matters; a miss
+ (new work where a session should have taken it) costs a harness.
diff --git a/cli/scripts/route-eval/collect.mjs b/cli/scripts/route-eval/collect.mjs
new file mode 100644
index 000000000..8e6514343
--- /dev/null
+++ b/cli/scripts/route-eval/collect.mjs
@@ -0,0 +1,49 @@
+// Snapshot the desk as ⌘B sends it (desktop/lib/state/task_route.dart taskRouteChoices + warmTaskRoute):
+// every connected machine; live sessions and stopped ones active in the last 7 days that can resume
+// (claude/codex with a sessionId); never terminals. Each with its last 2 asks and its last 3 turn recaps
+// (recap || text, each ≤140, joined " / "), as agent_recent n:3, its machine and its conversation.
+// Reads this computer's daemon (127.0.0.1:18473) and the machines it reaches; changes nothing.
+// usage: node scripts/route-eval/collect.mjs <desk.json>
+import { writeFileSync } from 'node:fs'
+const AUTO = /^(?:(?:harness|agent)-[1-9]\d*|.+ harness \d{1,2}-\d{1,2} \d{1,2}:\d{2}(?::\d{2})?)$/
+const machines = JSON.parse(await (await fetch('http://127.0.0.1:18473/api/machines')).text())
+const rows = (machines.data ?? machines).machines ?? machines.data ?? machines
+const live = rows.filter((m) => (m.online ?? m.status) === 'running' || m.online === true)
+const out = []
+for (const m of live) {
+ const machineId = m.machineId ?? m.id
+ const ws = new WebSocket('ws://127.0.0.1:18473/api/local-ws')
+ const pending = new Map(); let n = 0
+ const opened = await Promise.race([new Promise((r) => { ws.onopen = () => r(true) }), new Promise((r) => setTimeout(() => r(false), 5000))])
+ if (!opened) { console.log('no connection to', m.name); continue }
+ ws.onmessage = (e) => { if (typeof e.data !== 'string') return; const msg = JSON.parse(e.data); const r = pending.get(msg.payload?.requestId); if (r) { pending.delete(msg.payload.requestId); r(msg.payload) } }
+ const ask = (type, payload = {}, ms = 8000) => new Promise((resolve) => { const requestId = `p${++n}`; pending.set(requestId, resolve); ws.send(JSON.stringify({ type, payload: { ...payload, requestId } })); setTimeout(() => resolve({}), ms) })
+ ws.send(JSON.stringify({ type: 'machine_select', payload: { machineId, localProtocolVersion: 1 } }))
+ await new Promise((r) => setTimeout(r, 1000))
+ const agents = (await ask('agents_list', { includeStopped: true })).agents ?? []
+ const week = Date.now() - 7 * 86400000
+ const picked = []
+ for (const a of agents) {
+ if (!a.engine || a.engine === 'terminal') continue
+ const at = Date.parse(a.updatedAt ?? '') || 0
+ const stopped = a.status === 'stopped'
+ if (stopped && !((a.engine === 'claude' || a.engine === 'codex') && a.sessionId && at > week)) continue
+ picked.push({ a, at, stopped })
+ }
+ await Promise.all(picked.map(async ({ a, at, stopped }) => {
+ const recent = await ask('agent_recent', { agentId: a.id, n: 3 }, 4000)
+ const turns = (recent.events ?? []).map((e) => (e.recap ?? e.text ?? '')).filter((t) => typeof t === 'string').map((t) => t.replace(/\s+/g, ' ').trim()).filter(Boolean).slice(0, 3)
+ const name = AUTO.test(a.name ?? '') ? (a.title?.trim() || 'Untitled Pane') : a.name
+ out.push({ id: `${machineId}\n${a.id}`, name, machine: m.name, engine: a.engine, at,
+ asks: (recent.asks ?? []).filter((s) => typeof s === 'string' && s).slice(0, 2),
+ ...(turns.length ? { about: turns.map((t) => t.length <= 140 ? t : t.slice(0, 140)).join(' / ') } : {}),
+ ...(stopped ? { stoppedAgoMs: Math.max(0, Date.now() - at) } : {}),
+ folder: a.project?.cwd ?? '', ...(a.sessionId ? { conversation: a.sessionId } : {}) })
+ }))
+ console.log(m.name, picked.length)
+ ws.close()
+}
+out.sort((a, b) => (b.at || 0) - (a.at || 0))
+writeFileSync(process.argv[2], JSON.stringify(out, null, 1))
+console.log('total', out.length, '→ offered', Math.min(40, out.length))
+process.exit(0)
diff --git a/cli/scripts/route-eval/eval.mts b/cli/scripts/route-eval/eval.mts
new file mode 100644
index 000000000..d8662e6a7
--- /dev/null
+++ b/cli/scripts/route-eval/eval.mts
@@ -0,0 +1,28 @@
+// ⌘B's router on a snapshot of a real desk: deciding only, nothing is ever sent (README.md).
+// usage (from cli/): npx tsx scripts/route-eval/eval.mts <desk.json> <cases.json[,more.json]> [runs]
+import { readFileSync } from 'node:fs'
+import { createJevDecide } from '../../src/lib/jev/jevClient.ts'
+import { decideRoute, type RouteSession } from '../../src/lib/routeDecide.ts'
+type D = { id: string; name: string; machine: string; at: number; asks: string[]; about?: string; stoppedAgoMs?: number }
+type Case = { text: string; want: (number | 'new')[]; last?: number }
+const desk: D[] = JSON.parse(readFileSync(process.argv[2], 'utf8'))
+const sids: (string | null)[] = desk.map((s) => (s as { conversation?: string }).conversation ?? null)
+const cases: Case[] = process.argv[3].split(',').flatMap((f) => JSON.parse(readFileSync(f, 'utf8')))
+const RUNS = Number(process.argv[4] ?? 2)
+// The desktop's order: live newest first, then stopped newest first, 80 at most.
+const order = desk.map((_, i) => i).sort((a, b) => ((desk[a].stoppedAgoMs === undefined ? 0 : 1) - (desk[b].stoppedAgoMs === undefined ? 0 : 1)) || (desk[b].at || 0) - (desk[a].at || 0)).slice(0, 80)
+const sessions: RouteSession[] = order.map((i) => ({ id: String(i), name: desk[i].name, asks: desk[i].asks, ...(desk[i].about ? { about: desk[i].about } : {}), ...(desk[i].stoppedAgoMs !== undefined ? { stoppedAgoMs: desk[i].stoppedAgoMs } : {}), machine: desk[i].machine, ...(sids[i] ? { conversation: sids[i]! } : {}) }))
+const jev = createJevDecide()
+let right = 0, wrong = 0, missed = 0, i = 0
+const wrongs = new Map<string, number>()
+const jobs = cases.flatMap((c) => Array.from({ length: RUNS }, () => c))
+await Promise.all(Array.from({ length: 8 }, async () => {
+ while (i < jobs.length) {
+ const c = jobs[i++]
+ const v = await decideRoute({ text: c.text, sessions, projects: [], agents: [], ...(c.last !== undefined ? { last: { id: String(c.last), agoMs: 60_000 } } : {}) }, { jev })
+ const got: number | 'new' = v.kind === 'session' ? Number(v.id) : 'new'
+ if (c.want.includes(got)) right++; else if (got !== 'new') { wrong++; const k = `${c.text.slice(0, 70)} → ${desk[got as number].name}`; wrongs.set(k, (wrongs.get(k) ?? 0) + 1) } else missed++
+ }
+}))
+console.log(`real router: right ${right}/${jobs.length} (${(100 * right / jobs.length).toFixed(1)}%), WRONG SENDS ${wrong}, missed ${missed}`)
+for (const [k, n] of wrongs) console.log(` WRONG×${n} ${k}`)
diff --git a/cli/src/lib/routeDecide.spec.ts b/cli/src/lib/routeDecide.spec.ts
index bffe55c1c..4ba5d591b 100644
--- a/cli/src/lib/routeDecide.spec.ts
+++ b/cli/src/lib/routeDecide.spec.ts
@@ -5,7 +5,7 @@ import { describe, expect, it, vi } from 'vitest'
import type { JevChoice, JevChoiceAnswer } from './jev/jevClient.js'
import { JevUnavailable } from './jev/jevClient.js'
-import { decideRoute, JEV_LEAD_OPTIONS, JEV_LEAD_P, JEV_LEAD_RATIO, JEV_SURE_P, jevPick, type RouteDeps, type RouteInput, type RouteOption, type RouteSession } from './routeDecide.js'
+import { decideRoute, JEV_LEAD_OPTIONS, JEV_LEAD_P, JEV_LEAD_RATIO, JEV_LIVE_RATIO, JEV_OVER_STOPPED, JEV_SURE_P, jevPick, offered, type RouteDeps, type RouteInput, type RouteOption, type RouteSession } from './routeDecide.js'
/** A choice of [choice] at [p] over [options], the rest shared evenly among the others. */
function said(choice: string, p: number, options: string[]): JevChoiceAnswer {
@@ -31,6 +31,23 @@ const AGENTS: RouteOption[] = [{ id: 'claude', name: 'Claude Code' }, { id: 'cod
const input = (over: Partial<RouteInput> = {}): RouteInput => ({ text: 'the prometheus alert fired again', sessions: DESK, projects: [], agents: [], ...over })
const steps = (trace: string) => trace.split(' · ')
+const TARGET_QUESTION = 'A person typed this message into a box that either sends it to one of their ongoing sessions or starts a new one. ' +
+ "Choose a session only when the message is clearly about that session's own work: it continues that work, or it is the same " +
+ 'kind of work on the same subject. Sharing a few words with a session is not enough. If the message names nothing to go on ' +
+ '(like "merge it" or "continue"), asks for a new session, or is about another subject, choose none. Prefer a session that is ' +
+ 'still running over a stopped one, unless the message clearly continues the stopped one.'
+const FOLLOW_UP = ' Their previous message went to the session given as previous_message_went_to: a follow-up that names nothing new goes there too; a message about something else does not.'
+const TOPIC_QUESTION = {
+ type: 'choice',
+ instructions: 'Does this message name anything of its own to work on or ask about? A single word is enough: "retention", "the daemon", "the round unit", "the tui".',
+ criteria: {
+ yes: 'Yes: it names a subject or task, even briefly and even when it starts with "also" or "and"',
+ no: 'No: it is only words like "merge it", "do it", "ok merge", "what does that do", "post it as is", "continue", "take care of them all"',
+ },
+}
+/** Jev says the message names nothing of its own, at [p]. */
+const topicless = (p = 0.8): JevChoiceAnswer => ({ choice: 'no', probabilities: { yes: 1 - p, no: p } })
+
describe('Jev\'s pick', () => {
it('is its choice when it gives it 0.6 or more over exactly the options asked', () => {
expect(JEV_SURE_P).toBe(0.6)
@@ -89,13 +106,14 @@ describe('where a task goes', () => {
expect(questions).toEqual({
target: {
type: 'choice',
- instructions: 'A person typed this message to continue their work. Which of their ongoing sessions is it for?',
+ instructions: TARGET_QUESTION,
criteria: {
s0: 'billing retries — asked: why was the card charged twice',
s1: 'Prometheus alerts — lately: raised the alert threshold to 90%',
- new: 'None of them: it starts new, unrelated work',
+ new: 'None of them: no session does this kind of work',
},
},
+ topic: TOPIC_QUESTION,
project: {
type: 'choice',
instructions: 'If this becomes new work, which project folder does it belong in?',
@@ -111,7 +129,7 @@ describe('where a task goes', () => {
it('describes a session to Jev by its name, its last ask and its last turns, in one line cut short', async () => {
const remote = jev()
- const long = session('a1', ` ${'n'.repeat(250)}\n`, [`${'y'.repeat(200)}`, 'older'], 'z'.repeat(500))
+ const long = session('a1', ` ${'n'.repeat(250)}\n`, [`deploy the ${'y'.repeat(200)}`, 'older'], 'z'.repeat(500))
const tidy = session('a2', 'auth\n\n api', ['rotate the\ttokens'])
await decideRoute(input({
sessions: [long, tidy, session('a3', 'bare'), session('a4', 'quiet', [], 'only turns')],
@@ -121,7 +139,7 @@ describe('where a task goes', () => {
const [, questions] = remote.mock.calls[0]!
const criteria = questions.target!.criteria
// The name, then the first 120 of its last ask and the first 420 of its last turns: cut at 600 with an ellipsis.
- expect(criteria.s0).toBe(`${`${'n'.repeat(250)} — asked: ${'y'.repeat(120)} — lately: ${'z'.repeat(420)}`.slice(0, 599)}…`)
+ expect(criteria.s0).toBe(`${`${'n'.repeat(250)} — asked: deploy the ${'y'.repeat(109)} — lately: ${'z'.repeat(420)}`.slice(0, 599)}…`)
expect(criteria.s0).toHaveLength(600)
expect(criteria.s1).toBe('auth api — asked: rotate the tokens')
expect(criteria.s2).toBe('bare')
@@ -134,18 +152,18 @@ describe('where a task goes', () => {
it('asks no project or agent question when there is one or none to choose from', async () => {
const remote = jev()
await decideRoute(input({ projects: [PROJECTS[0]!], agents: [AGENTS[0]!] }), { jev: remote })
- expect(Object.keys(remote.mock.calls[0]![1])).toEqual(['target'])
+ expect(Object.keys(remote.mock.calls[0]![1])).toEqual(['target', 'topic'])
await decideRoute(input(), { jev: remote })
- expect(Object.keys(remote.mock.calls[1]![1])).toEqual(['target'])
+ expect(Object.keys(remote.mock.calls[1]![1])).toEqual(['target', 'topic'])
// Two projects and one agent: the project is asked, the agent is not.
await decideRoute(input({ projects: PROJECTS, agents: [AGENTS[0]!] }), { jev: remote })
- expect(Object.keys(remote.mock.calls[2]![1])).toEqual(['target', 'project'])
+ expect(Object.keys(remote.mock.calls[2]![1])).toEqual(['target', 'topic', 'project'])
})
it('asks Jev about the sessions with "new" alone when the desk is empty', async () => {
const remote = jev({ target: said('new', 1, ['new']) })
const verdict = await decideRoute(input({ sessions: [] }), { jev: remote })
- expect(remote.mock.calls[0]![1].target!.criteria).toEqual({ new: 'None of them: it starts new, unrelated work' })
+ expect(remote.mock.calls[0]![1].target!.criteria).toEqual({ new: 'None of them: no session does this kind of work' })
expect(verdict).toEqual({ kind: 'new', via: 'jev', why: 'Jev: new work', trace: '0 sessions · jev: "new" 1.00' })
})
@@ -233,12 +251,12 @@ describe('where a task goes', () => {
it('tells Jev which sessions are stopped, and how long ago they were last active', async () => {
const remote = jev({ target: said('new', 0.9, ['s0', 's1', 's2', 'new']) })
- const stopped = (id: string, name: string, stoppedAgoMs: number): RouteSession => ({ ...session(id, name), stoppedAgoMs })
+ const stopped = (id: string, name: string, stoppedAgoMs: number): RouteSession => ({ ...session(id, name, [], 'built the rig'), stoppedAgoMs })
await decideRoute(input({ sessions: [stopped('a1', 'lamp v1', 3 * 86_400_000), stopped('a2', 'lamp v2', 5 * 3_600_000), stopped('a3', 'notes', 60_000)] }), { jev: remote })
expect(remote.mock.calls[0][1].target.criteria).toMatchObject({
- s0: 'lamp v1 — stopped, last active 3 days ago',
- s1: 'lamp v2 — stopped, last active 5 hours ago',
- s2: 'notes — stopped, last active 1 minute ago',
+ s0: 'lamp v1 — stopped, last active 3 days ago — lately: built the rig',
+ s1: 'lamp v2 — stopped, last active 5 hours ago — lately: built the rig',
+ s2: 'notes — stopped, last active 1 minute ago — lately: built the rig',
})
})
@@ -287,3 +305,153 @@ describe('where a task goes', () => {
// The deps a router hands decideRoute are the same shape: a check that this file's fakes stay assignable.
const _deps: RouteDeps = { jev: jev(), log: () => {} }
void _deps
+
+describe('the sessions Jev is shown', () => {
+ const live = (id: string, name: string, over: Partial<RouteSession> = {}): RouteSession => ({ ...session(id, name, ['look at the alerts']), ...over })
+ const stopped = (id: string, name: string, over: Partial<RouteSession> = {}): RouteSession => ({ ...live(id, name), stoppedAgoMs: 3_600_000, ...over })
+
+ it('are the live ones first, then stopped ones, each in the order the client sent them', () => {
+ const shown = offered([stopped('s1', 'old work'), live('l1', 'alerts'), stopped('s2', 'older work'), live('l2', 'billing')])
+ expect(shown.map((s) => s.id)).toEqual(['l1', 'l2', 's1', 's2'])
+ })
+
+ it('show a conversation listed twice once, the live one before a stopped one', () => {
+ const shown = offered([stopped('s1', 'User activation', { conversation: 'c1' }), live('l1', 'renamed', { conversation: 'c1' }), stopped('s2', 'shell path', { conversation: 'c1' })])
+ expect(shown.map((s) => s.id)).toEqual(['l1'])
+ })
+
+ it('drop a stopped session a live one has the name of, a stopped twin by name, and one with nothing to read', () => {
+ const shown = offered([
+ live('l1', 'X Posts'),
+ stopped('s1', 'x posts'),
+ stopped('s2', 'lamp GTM'),
+ stopped('s3', 'Lamp GTM'),
+ stopped('s4', 'hi', { asks: ['ok', 'continue'], about: ' ' }),
+ stopped('s5', 'agent note', { asks: ['Another Claude session sent a message: <agent-message from="x">'] }),
+ ])
+ expect(shown.map((s) => s.id)).toEqual(['l1', 's2'])
+ })
+
+ it('are forty at most', () => {
+ expect(offered(Array.from({ length: 50 }, (_, i) => live(`l${i}`, `s${i}`)))).toHaveLength(40)
+ })
+
+ it('are described with their machine, and the last prompt of the person\'s own that names something', async () => {
+ const remote = jev()
+ await decideRoute(input({ sessions: [
+ { ...session('a1', 'X Posts', ['ok merge it', 'Another Claude session sent a message: hi', '<pasted_content id="1">Spending my Saturday with the kids</pasted_content>']), machine: 'M2' },
+ { ...session('a2', 'hub', ['cont', 'allow']), machine: 'office' },
+ ] }), { jev: remote })
+ expect(remote.mock.calls[0]![1].target!.criteria).toMatchObject({
+ s0: 'X Posts — on M2 — asked: Spending my Saturday with the kids',
+ s1: 'hub — on office',
+ })
+ })
+})
+
+describe('a message that names nothing of its own', () => {
+ it('goes where the last task went, minutes ago, whatever the sessions\' words', async () => {
+ const remote = jev({ target: said('s0', 0.5, TARGETS), topic: topicless() })
+ const verdict = await decideRoute(input({ text: 'merge it', last: { id: 'a2', agoMs: 60_000 } }), { jev: remote })
+ expect(verdict).toMatchObject({ kind: 'session', id: 'a2', p: 0.8 })
+ expect(steps(verdict.trace)).toContain('names nothing: to "Prometheus alerts", where the last went')
+ // The previous session is told to Jev, and how to read it.
+ expect(remote.mock.calls[0]![0]).toEqual({ message: 'merge it', previous_message_went_to: 'Prometheus alerts' })
+ expect(remote.mock.calls[0]![1].target!.instructions).toBe(TARGET_QUESTION + FOLLOW_UP)
+ })
+
+ it('is new work when nothing went anywhere just now, even with a session Jev is sure of', async () => {
+ const verdict = await decideRoute(input({ text: 'merge it' }), { jev: jev({ target: said('s0', 0.95, TARGETS), topic: topicless() }) })
+ expect(verdict).toMatchObject({ kind: 'new', via: 'jev', why: 'names nothing, and no task went anywhere just now' })
+ expect(steps(verdict.trace)).toContain('names nothing: nowhere to go')
+ })
+
+ it('is new work when Jev is sure of another session than the last: the two disagree', async () => {
+ const verdict = await decideRoute(input({ text: 'merge it', last: { id: 'a2', agoMs: 60_000 } }), { jev: jev({ target: said('s0', 0.9, TARGETS), topic: topicless() }) })
+ expect(verdict).toMatchObject({ kind: 'new', why: 'names nothing, and Jev pointed elsewhere' })
+ // Sure of the last itself: it goes there.
+ const agreed = await decideRoute(input({ text: 'merge it', last: { id: 'a2', agoMs: 60_000 } }), { jev: jev({ target: said('s1', 0.9, TARGETS), topic: topicless() }) })
+ expect(agreed).toMatchObject({ kind: 'session', id: 'a2' })
+ })
+
+ it('finds the last session by its conversation when it is shown as its live self', async () => {
+ const sessions: RouteSession[] = [
+ { ...session('a1', 'billing retries', ['why was the card charged twice']), conversation: 'c1' },
+ { ...session('old', 'billing (before the rename)', ['refund the order']), conversation: 'c1', stoppedAgoMs: 60_000 },
+ ]
+ const verdict = await decideRoute(input({ text: 'merge it', sessions, last: { id: 'old', agoMs: 60_000 } }), { jev: jev({ target: said('new', 0.5, ['s0', 'new']), topic: topicless() }) })
+ expect(verdict).toMatchObject({ kind: 'session', id: 'a1' })
+ // A last that is not there at all is nowhere to go.
+ const gone = await decideRoute(input({ text: 'merge it', last: { id: 'nowhere', agoMs: 60_000 } }), { jev: jev({ target: said('new', 0.5, TARGETS), topic: topicless() }) })
+ expect(gone).toMatchObject({ kind: 'new', why: 'names nothing, and no task went anywhere just now' })
+ })
+
+ it('is decided by the sessions when Jev is not sure it names nothing', async () => {
+ for (const topic of [topicless(0.55), topicless(0.5), { choice: 'no', probabilities: { yes: 0.2 } }, { choice: 'no', probabilities: { yes: 0.1, no: Number.NaN } }]) {
+ const verdict = await decideRoute(input({ text: 'also check retention' }), { jev: jev({ target: said('s0', 0.9, TARGETS), topic }) })
+ expect(verdict, JSON.stringify(topic)).toMatchObject({ kind: 'session', id: 'a1' })
+ }
+ })
+})
+
+describe('a message that asks for a new session', () => {
+ it('is new work, whatever Jev picks', async () => {
+ for (const text of ['start a new session and write an x post about lamp', 'in a fresh session, look at the usage data', 'Open a new harness for the parser', 'spin up another session to check retention']) {
+ const verdict = await decideRoute(input({ text }), { jev: jev({ target: said('s0', 0.95, TARGETS) }) })
+ expect(verdict, text).toMatchObject({ kind: 'new', why: 'asked for a new session' })
+ }
+ })
+
+ it('is not one that only talks about a new pane, a thread or a session', async () => {
+ for (const text of ['the new pane is broken', 'race on a different thread', 'rewrite the parser from scratch', 'new session restore drops the cwd']) {
+ const verdict = await decideRoute(input({ text }), { jev: jev({ target: said('s0', 0.95, TARGETS) }) })
+ expect(verdict, text).toMatchObject({ kind: 'session', id: 'a1' })
+ }
+ })
+})
+
+describe('a running session\'s lead', () => {
+ const desk: RouteSession[] = [
+ session('live', 'X Posts', ['write a post about the lamp']),
+ { ...session('copy', 'write an x post about the', ['write an x post about the device']), stoppedAgoMs: 3_600_000 },
+ session('twin', 'X Posts', ['draft another post']),
+ session('other', 'usage data', ['retention today']),
+ session('more', 'firmware', ['flash the round unit']),
+ ]
+ // Jev's answer over the desk as it is shown: live ones first, so the stopped copy is s4.
+ const answer = (p: Record<string, number>, choice = 's0') => ({ target: { choice, probabilities: p } })
+
+ it('is not held back by a stopped copy of its work, by 1.25 times it or more', async () => {
+ expect([JEV_LIVE_RATIO, JEV_OVER_STOPPED]).toEqual([1.75, 1.25])
+ const verdict = await decideRoute(input({ text: 'post this on x', sessions: desk }), { jev: jev(answer({ s0: 0.44, s1: 0.1, s2: 0.06, s3: 0.04, s4: 0.32, new: 0.04 })) })
+ expect(verdict).toMatchObject({ kind: 'session', id: 'live' })
+ })
+
+ it('is held back by another running session, a twin of its name too, or new work within 1.75 times it, or a stopped one within 1.25', async () => {
+ for (const p of [
+ { s0: 0.44, s1: 0.05, s2: 0.3, s3: 0.08, s4: 0.05, new: 0.08 },
+ { s0: 0.44, s1: 0.05, s2: 0.08, s3: 0.08, s4: 0.05, new: 0.3 },
+ // Two "X Posts" running: a coin flip, not a lead.
+ { s0: 0.42, s1: 0.4, s2: 0.05, s3: 0.05, s4: 0.04, new: 0.04 },
+ { s0: 0.41, s1: 0.05, s2: 0.05, s3: 0.05, s4: 0.4, new: 0.04 },
+ ]) {
+ const verdict = await decideRoute(input({ text: 'post this on x', sessions: desk }), { jev: jev(answer(p)) })
+ expect(verdict.kind, JSON.stringify(p)).toBe('new')
+ }
+ })
+
+ it('is no lead for a stopped pick, a pick below 0.4, one that is not the likeliest, a broken answer, or fewer than six options', async () => {
+ const cases: [string, Record<string, JevChoiceAnswer>, RouteSession[]][] = [
+ ['stopped', answer({ s0: 0.3, s1: 0.05, s2: 0.05, s3: 0.05, s4: 0.45, new: 0.1 }, 's4'), desk],
+ ['low', answer({ s0: 0.39, s1: 0.1, s2: 0.1, s3: 0.06, s4: 0.3, new: 0.05 }), desk],
+ ['not top', answer({ s0: 0.42, s1: 0.03, s2: 0.03, s3: 0.03, s4: 0.45, new: 0.04 }), desk],
+ ['broken', answer({ s0: 0.45, s4: 0.3 }), desk],
+ // Would lead (0.5 against 0.2) over six; over five there is no spread to excuse it.
+ ['five', answer({ s0: 0.5, s1: 0.05, s2: 0.2, s3: 0.2, new: 0.05 }), desk.filter((s) => s.id !== 'copy')],
+ ]
+ for (const [name, answers, sessions] of cases) {
+ const verdict = await decideRoute(input({ text: 'post this on x', sessions }), { jev: jev(answers) })
+ expect(verdict.kind, name).toBe('new')
+ }
+ })
+})
diff --git a/cli/src/lib/routeDecide.ts b/cli/src/lib/routeDecide.ts
index 319966783..0653e424f 100644
--- a/cli/src/lib/routeDecide.ts
+++ b/cli/src/lib/routeDecide.ts
@@ -2,9 +2,19 @@
* Where a typed task goes, decided without asking the person (docs/design/2026-10-09-auto-router.md).
*
* Jev 1.13, through OpenRouter (~0.6 s), is asked once: which session the task is for (or none — new
- * work), and, for new work, which project and which agent. Its pick is taken at JEV_SURE_P or more, or when
- * it still leads clearly (`jevPick`); otherwise Jev is unsure and the task is new work. A project or agent
- * Jev is unsure of is left to the caller, which uses the pane the person is in.
+ * work), whether the message names anything of its own, and, for new work, which project and which agent.
+ * Its pick is taken at JEV_SURE_P or more, or when it still leads clearly (`jevPick`, `leadsLive`);
+ * otherwise Jev is unsure and the task is new work. A message that names nothing ("merge it") goes where
+ * the last one went, or nowhere; one that asks for a new session is new work. A project or agent Jev is
+ * unsure of is left to the caller, which uses the pane the person is in.
+ *
+ * Hill-climbed on the owner's real desk (2026-10-10, 80 sessions on three machines, 390 labelled
+ * messages, a red team's 116 written to break it, and 50 held out): from 63% right with 25 wrong sends in
+ * 123 to 90% right with none in 202, 51% to 72% right with 66 to 6 in a red team's 232, and 83% with 4 in
+ * 100 held out. What moved it, in order:
+ * the sessions Jev is shown (live ones first, no stopped twins or empty leftovers, no pasted-text noise),
+ * a question that asks for the same work on the same subject rather than shared words, and the check for
+ * a message that names nothing. docs/design/2026-10-09-auto-router.md has the runs.
*
* Jev alone, owner's call 2026-10-10. It started as a ladder with julia-1, a local model, deciding first:
* every task sent to a wrong session — on the benchmark and on the owner's desk ("how is lamp v2 going"
@@ -28,6 +38,10 @@ export interface RouteSession {
about?: string
/** How long ago a stopped session was last active; absent for a live one. Sending to it resumes it. */
stoppedAgoMs?: number
+ /** The machine it runs on, as the person names it: "the lamp session on tropic". */
+ machine?: string
+ /** Its conversation: one conversation listed twice (a resume, a rename) is one session to Jev. */
+ conversation?: string
}
/** A project a new harness could start in; [id] is the caller's, handed back untouched. */
export interface RouteOption { id: string; name: string }
@@ -56,7 +70,9 @@ export interface RouteDeps {
log?: (line: string) => void
}
-/** The sessions, projects and agents Jev weighs, at most: a client sends its most recently active first. */
+/** The sessions, projects and agents Jev weighs, at most: a client sends its live sessions first, then its
+ * stopped ones, each most recently active first. More stopped sessions than this let in let old leftovers
+ * ("daemon refactoring", 53 hours stopped) take tasks that were new work: 7 wrong sends at 50, none at 40. */
const JEV_OPTIONS = 40
const LABEL_CHARS = 600
/** A follow-up names nothing; who the person was just talking to is what Jev gets to go on. */
@@ -77,6 +93,11 @@ export const JEV_SURE_P = 0.6
export const JEV_LEAD_P = 0.4
export const JEV_LEAD_RATIO = 2
export const JEV_LEAD_OPTIONS = 6
+/** A running session's lead over every other running session and new work. A stopped copy of the same work
+ * ("X Posts" 0.44 against the stopped "write an x post about the" 0.32) holds it back only within
+ * JEV_OVER_STOPPED: the person prefers what is running, but not on a coin flip. */
+export const JEV_LIVE_RATIO = 1.75
+export const JEV_OVER_STOPPED = 1.25
/** The likeliest of [options] other than [choice], for the log: how far ahead the pick was. */
function runnerUp(p: Record<string, number>, choice: string, options: string[]): string | undefined {
@@ -92,8 +113,8 @@ export function jevPick(answer: JevChoiceAnswer | undefined, options: string[],
const top = p[answer.choice]
if (top >= JEV_SURE_P) return answer.choice
if (!lead || options.length < JEV_LEAD_OPTIONS) return undefined
- const next = runnerUp(p, answer.choice, options)
- return top >= JEV_LEAD_P && top >= JEV_LEAD_RATIO * (next === undefined ? 0 : p[next]) ? answer.choice : undefined
+ // Six options or more: there is always one next.
+ return top >= JEV_LEAD_P && top >= JEV_LEAD_RATIO * p[runnerUp(p, answer.choice, options)!] ? answer.choice : undefined
}
/** An error and what caused it: fetch's own message ("fetch failed") says nothing by itself. */
@@ -113,36 +134,126 @@ function ago(ms: number): string {
return `${n} ${unit}${n === 1 ? '' : 's'}`
}
-/** A session as Jev reads it: its name, whether it is stopped, the person's last prompt and what its last
- * turns were about. */
+/** A prompt that is not the person's words: another agent's message, a question's reply, a bare image. */
+const NOT_SAID = /^(another claude session sent a message|<agent-message|<send_user_message|<task-notification|\[image #\d+\]\s*$)/i
+const tidy = (text: string): string => text.replace(/<\/?pasted_content[^>]*>/g, ' ').replace(/\s+/g, ' ').trim()
+/** Words that name nothing: a prompt made only of these ("ok merge it", "cont", "allow") was bait — a
+ * message that echoed it ("merge it") went to that session, whatever it was about. */
+const FILLER = new Set(("ok okay yes yeah yep no nope sure please pls thanks thank you ty cool great nice good looks look lgtm lfg " +
+ "let lets let's go do it that this the a an and or but so to of on in for with is are was be can could would should will we " +
+ "i you me my our continue cont keep going again now then just also all them merge merged ship push approve allow run retry " +
+ "try fix go ahead done next proceed").split(' '))
+const namesSomething = (text: string): boolean =>
+ text.toLowerCase().replace(/[^\p{L}\p{N}#' ]+/gu, ' ').split(/\s+/).filter((word) => word.length > 1 && !FILLER.has(word)).length >= 2
+/** The person's last prompt worth showing Jev: their own words, naming something. */
+const lastAsk = (session: RouteSession): string | undefined =>
+ session.asks.map(tidy).find((ask) => ask && !NOT_SAID.test(ask) && namesSomething(ask))
+
+/** A session as Jev reads it: its name, its machine, whether it is stopped, the person's last prompt that
+ * names something and what its last turns were about. */
function describe(session: RouteSession): string {
+ const ask = lastAsk(session)
+ const about = tidy(session.about ?? '')
return label([
session.name,
+ session.machine ? `on ${session.machine}` : '',
session.stoppedAgoMs === undefined ? '' : `stopped, last active ${ago(session.stoppedAgoMs)} ago`,
- session.asks[0] ? `asked: ${session.asks[0].slice(0, 120)}` : '',
- session.about ? `lately: ${session.about.slice(0, 420)}` : '',
+ ask ? `asked: ${ask.slice(0, 120)}` : '',
+ about ? `lately: ${about.slice(0, 420)}` : '',
].filter(Boolean).join(' — '))
}
+/** The sessions Jev is shown, at most JEV_OPTIONS: live ones first, then stopped ones, each in the client's
+ * order. A conversation listed twice is shown once, live before stopped. A stopped session goes when a
+ * live one has its name (its older self) or a stopped one already does, or when it has nothing to read.
+ * On the owner's desk the live "X Posts" shared Jev's vote with three stopped copies of itself, and
+ * empty stopped leftovers took the places of live sessions: "Harness TUI" was not among the forty. */
+export function offered(all: RouteSession[]): RouteSession[] {
+ const live = all.filter((session) => session.stoppedAgoMs === undefined)
+ const stopped = all.filter((session) => session.stoppedAgoMs !== undefined)
+ const liveNames = new Set(live.map((session) => session.name.toLowerCase()))
+ const conversations = new Set<string>()
+ const stoppedNames = new Set<string>()
+ const out: RouteSession[] = []
+ for (const session of [...live, ...stopped]) {
+ if (session.conversation) {
+ if (conversations.has(session.conversation)) continue
+ conversations.add(session.conversation)
+ }
+ if (session.stoppedAgoMs !== undefined) {
+ const name = session.name.toLowerCase()
+ if (liveNames.has(name) || stoppedNames.has(name)) continue
+ if (!lastAsk(session) && !tidy(session.about ?? '')) continue
+ stoppedNames.add(name)
+ }
+ out.push(session)
+ }
+ return out.slice(0, JEV_OPTIONS)
+}
+
+/** "start a new session and…", "open a fresh harness for…", "in a fresh session, …": what the person asked
+ * for, decided. A verb or "in" before it: "the new pane is broken" and "new session restore drops the cwd"
+ * are about a new pane and a new session, not asking for one. */
+const ASKS_FOR_NEW = /\b(?:(?:start|open|spin up|make|create|launch|begin|use)\s+(?:an?\s+)?(?:new|fresh|separate|another|different)\s+(?:session|harness|chat|pane|conversation)|in\s+an?\s+(?:new|fresh|separate)\s+(?:session|harness|chat|conversation))\b/i
+
+/** A running pick that leads every other running session, and new work, by JEV_LIVE_RATIO, and a stopped one
+ * by JEV_OVER_STOPPED. A running twin of its own name is a rival like any other: two "Untitled Pane"s at
+ * 0.42 and 0.40 are a coin flip, not a lead. */
+function leadsLive(answer: JevChoiceAnswer | undefined, sessions: RouteSession[], targets: string[]): string | undefined {
+ const p = answer?.probabilities
+ if (!answer || !p || answer.choice === 'new' || !targets.includes(answer.choice) || targets.length < JEV_LEAD_OPTIONS) return undefined
+ // A missing or broken number compares false below: no lead.
+ const top = sessions[Number(answer.choice.slice(1))]
+ const pTop = p[answer.choice]
+ if (top.stoppedAgoMs !== undefined || pTop < JEV_LEAD_P || targets.some((id) => p[id] > pTop)) return undefined
+ const others = targets.filter((id) => id !== answer.choice)
+ const stopped = (id: string) => id !== 'new' && sessions[Number(id.slice(1))].stoppedAgoMs !== undefined
+ const most = (ids: string[]) => Math.max(0, ...ids.map((id) => p[id]))
+ return pTop >= JEV_LIVE_RATIO * most(others.filter((id) => !stopped(id))) && pTop >= JEV_OVER_STOPPED * most(others.filter(stopped))
+ ? answer.choice
+ : undefined
+}
+
/** [signal] stops the question when whoever asked has gone: Jev's answer would act on nothing. */
export async function decideRoute(input: RouteInput, deps: RouteDeps, signal?: AbortSignal): Promise<RouteVerdict> {
const { text } = input
- const sessions = input.sessions.slice(0, JEV_OPTIONS)
+ const sessions = offered(input.sessions)
const projects = input.projects.slice(0, JEV_OPTIONS)
const agents = input.agents.slice(0, JEV_OPTIONS)
const trace: string[] = [`${sessions.length} sessions`]
if (!deps.jev) return { kind: 'unavailable', why: 'Jev is not set up', trace: [...trace, 'jev: not set up'].join(' · ') }
+ // Where the last task went, minutes ago: found by its conversation when the session shown for it is its
+ // live self or the one listed first (`offered` shows a conversation once).
+ const sent = input.last && input.last.agoMs <= CONTINUITY_MS ? input.sessions.find((session) => session.id === input.last!.id) : undefined
+ const last = sent && (sessions.includes(sent) ? sent : sent.conversation ? sessions.find((session) => session.conversation === sent.conversation) : undefined)
const questions: Record<string, JevChoice> = {
target: {
type: 'choice',
- // Worded as measured (docs/design/2026-10-09-auto-router.md): this framing — the person continuing
- // their own work — got 95% right against 85% for "which session should this message go to?", with
- // the same one wrong send.
- instructions: 'A person typed this message to continue their work. Which of their ongoing sessions is it for?',
+ // Worded as measured. "Continue their work" let a message go wherever its words were last typed
+ // ("merge it" to the session whose last prompt was "ok merge it"); "whose job is this kind of work"
+ // sent the lamp's retention to Harness's usage session. Asking for the same work on the same subject,
+ // and not for shared words, took a red team's 116 messages from 66 wrong sends in 232 to 16.
+ instructions: 'A person typed this message into a box that either sends it to one of their ongoing sessions or starts a new one. ' +
+ "Choose a session only when the message is clearly about that session's own work: it continues that work, or it is the same " +
+ 'kind of work on the same subject. Sharing a few words with a session is not enough. If the message names nothing to go on ' +
+ '(like "merge it" or "continue"), asks for a new session, or is about another subject, choose none. Prefer a session that is ' +
+ 'still running over a stopped one, unless the message clearly continues the stopped one.' +
+ (last ? ' Their previous message went to the session given as previous_message_went_to: a follow-up that names nothing new goes there too; a message about something else does not.' : ''),
criteria: {
...Object.fromEntries(sessions.map((session, i) => [`s${i}`, describe(session)])),
- new: 'None of them: it starts new, unrelated work',
+ new: 'None of them: no session does this kind of work',
+ },
+ },
+ // A message that names nothing of its own is decided here and not by the sessions' words: it goes where
+ // the last one went, or it is new work. "A single word is enough" is what keeps "also check retention"
+ // and "and the daemon?" from being taken for one ("say what it is about on its own" took them).
+ topic: {
+ type: 'choice',
+ instructions: 'Does this message name anything of its own to work on or ask about? A single word is enough: "retention", "the daemon", "the round unit", "the tui".',
+ criteria: {
+ yes: 'Yes: it names a subject or task, even briefly and even when it starts with "also" or "and"',
+ no: 'No: it is only words like "merge it", "do it", "ok merge", "what does that do", "post it as is", "continue", "take care of them all"',
},
},
}
@@ -160,7 +271,6 @@ export async function decideRoute(input: RouteInput, deps: RouteDeps, signal?: A
criteria: Object.fromEntries(agents.map((agent, i) => [`a${i}`, label(agent.name)])),
}
}
- const last = input.last && input.last.agoMs <= CONTINUITY_MS ? sessions.find((session) => session.id === input.last!.id) : undefined
const state = last ? { message: text, previous_message_went_to: last.name } : { message: text }
let answers: Awaited<ReturnType<JevDecide>>
@@ -178,10 +288,22 @@ export async function decideRoute(input: RouteInput, deps: RouteDeps, signal?: A
// The runner-up too: whether a pick led clearly is what the next change to the bar is measured from.
trace.push(`jev: ${said ? `"${name(said.choice) ?? said.choice}" ${odds(said.choice)}${next ? `, then "${name(next)}" ${odds(next)}` : ''}` : 'no answer'}`)
- const target = jevPick(said, targets, true)
+ // Names nothing, on Jev's sure word: a yes or no at 0.5 is a coin flip, and a coin flip must not override
+ // where the words point.
+ const topic = answers.topic
+ const noOdds = topic?.probabilities.no
+ const topicless = topic?.choice === 'no' && typeof noOdds === 'number' && Number.isFinite(noOdds) && noOdds >= JEV_SURE_P
+ const askedForNew = ASKS_FOR_NEW.test(text)
+ const picked = jevPick(said, targets, true) ?? leadsLive(said, sessions, targets)
+ const lastId = last ? `s${sessions.indexOf(last)}` : undefined
+ // Names nothing, yet Jev is sure of another session than the last: the two disagree, and new work is safe.
+ const torn = topicless && lastId !== undefined && picked !== undefined && picked !== 'new' && picked !== lastId
+ if (topicless) trace.push(`names nothing: ${torn ? 'but Jev is sure of another session than the last' : last ? `to "${last.name}", where the last went` : 'nowhere to go'}`)
+ if (askedForNew) trace.push('asked for a new session')
+ const target = askedForNew ? 'new' : topicless ? (torn || !lastId ? 'new' : lastId) : picked
if (target && target !== 'new') {
const session = sessions[Number(target.slice(1))]
- return { kind: 'session', id: session.id, p: said!.probabilities[target], trace: trace.join(' · ') }
+ return { kind: 'session', id: session.id, p: topicless ? noOdds! : said!.probabilities[target], trace: trace.join(' · ') }
}
const pick = (key: 'project' | 'agent', prefix: string, options: RouteOption[]): string | undefined => {
@@ -195,7 +317,7 @@ export async function decideRoute(input: RouteInput, deps: RouteDeps, signal?: A
...(project ? { project } : {}),
...(agent ? { agent } : {}),
via: target ? 'jev' : 'unsure',
- why: target ? 'Jev: new work' : 'Jev was not sure',
+ why: askedForNew ? 'asked for a new session' : torn ? 'names nothing, and Jev pointed elsewhere' : topicless ? 'names nothing, and no task went anywhere just now' : target ? 'Jev: new work' : 'Jev was not sure',
trace: trace.join(' · '),
}
}
diff --git a/cli/src/services/router.spec.ts b/cli/src/services/router.spec.ts
index eacbba2c3..fc784c77b 100644
--- a/cli/src/services/router.spec.ts
+++ b/cli/src/services/router.spec.ts
@@ -113,6 +113,14 @@ describe('what a client sends', () => {
for (const odd of [undefined, -1, Number.NaN, Number.POSITIVE_INFINITY, '3600000']) expect(sent(odd), String(odd)).toEqual({ id: 'a1', name: 'lamp v1', asks: [] })
})
+ it('says where a session runs and which conversation it is, when those are short strings', () => {
+ const sent = (machine: unknown, conversation: unknown) => routeInput({ text: 'go', sessions: [{ id: 'a1', name: 'X Posts', machine, conversation }] })?.sessions[0]
+ expect(sent('M2', 'c-1')).toEqual({ id: 'a1', name: 'X Posts', asks: [], machine: 'M2', conversation: 'c-1' })
+ for (const [machine, conversation] of [[undefined, undefined], [' ', ''], ['m'.repeat(101), 'c'.repeat(201)], [4, ['c']]]) {
+ expect(sent(machine, conversation), String(machine)).toEqual({ id: 'a1', name: 'X Posts', asks: [] })
+ }
+ })
+
it('says where the last task went only with a session id and a finite time', () => {
const last = (value: unknown) => routeInput({ text: 'go', last: value })!
expect(last({ id: 'a1', agoMs: 0 }).last).toEqual({ id: 'a1', agoMs: 0 })
diff --git a/cli/src/services/router.ts b/cli/src/services/router.ts
index 33fb443e2..8defce8ed 100644
--- a/cli/src/services/router.ts
+++ b/cli/src/services/router.ts
@@ -35,11 +35,17 @@ function options(raw: unknown): RouteOption[] {
function sessions(raw: unknown): RouteSession[] {
if (!Array.isArray(raw)) return []
return raw.slice(0, MAX_SESSIONS).flatMap((row) => {
- const { id, name, asks, about, stoppedAgoMs } = (row ?? {}) as { id?: unknown; name?: unknown; asks?: unknown; about?: unknown; stoppedAgoMs?: unknown }
+ const { id, name, asks, about, stoppedAgoMs, machine, conversation } = (row ?? {}) as { id?: unknown; name?: unknown; asks?: unknown; about?: unknown; stoppedAgoMs?: unknown; machine?: unknown; conversation?: unknown }
if (typeof id !== 'string' || typeof name !== 'string' || id.length > 4200 || name.length > 300) return []
const said = Array.isArray(asks) ? asks.filter((ask): ask is string => typeof ask === 'string').slice(0, 3).map((ask) => ask.slice(0, 500)) : []
const stopped = typeof stoppedAgoMs === 'number' && Number.isFinite(stoppedAgoMs) && stoppedAgoMs >= 0 ? { stoppedAgoMs } : {}
- return [{ id, name, asks: said, ...(typeof about === 'string' && about.trim() ? { about: about.slice(0, 500) } : {}), ...stopped }]
+ return [{
+ id, name, asks: said,
+ ...(typeof about === 'string' && about.trim() ? { about: about.slice(0, 500) } : {}),
+ ...stopped,
+ ...(typeof machine === 'string' && machine.trim() && machine.length <= 100 ? { machine } : {}),
+ ...(typeof conversation === 'string' && conversation && conversation.length <= 200 ? { conversation } : {}),
+ }]
})
}
diff --git a/desktop/lib/state/task_route.dart b/desktop/lib/state/task_route.dart
index 6cf9b5f4d..fce07dc36 100644
--- a/desktop/lib/state/task_route.dart
+++ b/desktop/lib/state/task_route.dart
@@ -36,6 +36,10 @@ class TaskRouteChoices {
if (value.about != null) 'about': value.about,
if (value.stoppedFor case final stopped?)
'stoppedAgoMs': stopped.inMilliseconds,
+ 'machine': value.machine,
+ if (value.conversation case final conversation?
+ when conversation.isNotEmpty)
+ 'conversation': conversation,
},
],
'projects': [
@@ -64,7 +68,10 @@ bool _usable(String folder) =>
!folder.contains('/.harness/') &&
folder.length <= 4096;
-const _sessionCap = 40;
+/// The candidates sent, at most: the router shows Jev forty, after it drops twins and empty leftovers, so
+/// it is sent more to choose from — live sessions first, then stopped ones (cli/src/lib/routeDecide.ts
+/// `offered`).
+const _sessionCap = 80;
/// How long a stopped session stays one a task can be for. The rail keeps every stopped session it ever
/// ran; a week is what a person picks back up ("the lamp work from Tuesday"), and past it the list only
@@ -125,9 +132,9 @@ TaskRouteChoices taskRouteChoices(AppNotifier app, {DateTime? now}) {
),
};
// Live sessions, and stopped ones active in the last [stoppedSessionsWithin] that can resume their own
- // conversation — a follow-up typed into a fresh one would land with none of what it follows. The most
- // recently active first, and at most [_sessionCap]: the first try sent all two hundred the rail keeps,
- // and the one the task was for was not among the forty Jev was shown.
+ // conversation — a follow-up typed into a fresh one would land with none of what it follows. Live ones
+ // first, then stopped ones, each the most recently active first, and at most [_sessionCap]: sorted by
+ // activity alone, stopped leftovers took the places of live sessions on the owner's desk.
final live =
[
for (final machine in machines)
@@ -139,6 +146,9 @@ TaskRouteChoices taskRouteChoices(AppNotifier app, {DateTime? now}) {
agent.lastActivityAt?.isAfter(since) == true)))
(machine: machine, agent: agent),
]..sort((a, b) {
+ final stopped =
+ (a.agent.isStopped ? 1 : 0) - (b.agent.isStopped ? 1 : 0);
+ if (stopped != 0) return stopped;
final at = a.agent.lastActivityAt, bt = b.agent.lastActivityAt;
return bt == null
? (at == null ? 0 : -1)
@@ -166,6 +176,7 @@ TaskRouteChoices taskRouteChoices(AppNotifier app, {DateTime? now}) {
about:
_recent[app]?['${machine.machine.machineId}\n${agent.id}']?.about ??
_about(_preview(app, machine.machine.machineId, agent)),
+ conversation: agent.sessionId,
// Never less than nothing: a machine whose clock runs ahead would otherwise read as live.
stoppedFor: agent.isStopped
? _atLeastZero(
@@ -284,6 +295,9 @@ typedef TaskRouteSession = ({
/// How long ago a stopped session was last active; null for a live one. Jev is told, so a live "lamp
/// v2" is not mistaken for the stopped "lamp v1" of last week.
Duration? stoppedFor,
+
+ /// Its conversation: the same one listed twice (resumed, renamed) is one session to the router.
+ String? conversation,
});
SessionPreview? _preview(AppNotifier app, String machineId, Agent agent) =>
diff --git a/desktop/test/route_card_test.dart b/desktop/test/route_card_test.dart
index e3f75d5f6..d1c806986 100644
--- a/desktop/test/route_card_test.dart
+++ b/desktop/test/route_card_test.dart
@@ -229,11 +229,13 @@ Agent _agent(
);
void main() {
- test('the router is offered live sessions on reachable machines, newest first, forty at most', () {
+ test('the router is offered sessions on reachable machines: live ones first, newest first, eighty at most', () {
final app = _App();
addTearDown(app.dispose);
app.machineStates['m']!.agents = [
- for (var i = 0; i < 50; i++) _agent('a$i', minutesAgo: i),
+ // A stopped session more recent than every live one still comes after them.
+ _agent('recent', status: 'stopped', sessionId: 'c-r', minutesAgo: 0),
+ for (var i = 0; i < 90; i++) _agent('a$i', minutesAgo: i + 1),
_agent('stopped', status: 'stopped'),
const Agent(
id: 'sh',
@@ -255,7 +257,15 @@ void main() {
app,
now: _now,
).sessions.values.map((s) => s.agentId).toList();
- expect(ids, [for (var i = 0; i < 40; i++) 'a$i']);
+ expect(ids, [for (var i = 0; i < 80; i++) 'a$i']);
+ app.machineStates['m']!.agents = [
+ _agent('recent', status: 'stopped', sessionId: 'c-r', minutesAgo: 0),
+ for (var i = 0; i < 3; i++) _agent('a$i', minutesAgo: i + 1),
+ ];
+ expect(
+ taskRouteChoices(app, now: _now).sessions.values.map((s) => s.agentId),
+ ['a0', 'a1', 'a2', 'recent'],
+ );
});
test('a stopped session is offered for a week, when it can resume its own conversation', () {
@@ -297,16 +307,22 @@ void main() {
app,
now: _now,
).sessions.values.map((s) => s.agentId).toList();
- expect(ids, ['tuesday', 'live']);
- // Jev is told it is stopped, and since when; a live one says nothing of the kind.
+ // Live first, whatever is more recent.
+ expect(ids, ['live', 'tuesday']);
+ // Jev is told it is stopped, and since when; a live one says nothing of the kind. Each says where it
+ // runs, and which conversation it is.
final sent = {
for (final row
in taskRouteChoices(app, now: _now).toPayload()['sessions'] as List)
- (row as Map)['id']: row['stoppedAgoMs'],
+ (row as Map)['id']: (
+ row['stoppedAgoMs'],
+ row['machine'],
+ row['conversation'],
+ ),
};
expect(sent, {
- 'm\ntuesday': const Duration(days: 4).inMilliseconds,
- 'm\nlive': null,
+ 'm\ntuesday': (const Duration(days: 4).inMilliseconds, 'Office', 'c-1'),
+ 'm\nlive': (null, 'Office', null),
});
// A machine whose clock runs ahead still reads as stopped, never as live.
final ahead = taskRouteChoices(
diff --git a/docs/design/2026-10-09-auto-router.md b/docs/design/2026-10-09-auto-router.md
index d5e9b2ef5..02aaf3651 100644
--- a/docs/design/2026-10-09-auto-router.md
+++ b/docs/design/2026-10-09-auto-router.md
@@ -94,6 +94,53 @@ every answer.
reported it; about 6,000 decisions per dollar.
- **Time**: about 0.6 s per decision.
+## Hill-climbed on the owner's desk (2026-10-10)
+
+The first version was hit and miss on the owner's real desk, so it was measured there and climbed:
+- **The desk:** 80 sessions on three machines, half of them stopped, with duplicates, QA panes and
+ sessions left over from earlier wrong routes.
+- **390 labelled English messages:**
+ - 41 by hand, including every message the owner reported misrouted;
+ - 60 written blind;
+ - 116 from a red team whose job was to break it (typos, "merge it", pasted logs, "the one on tropic",
+ same-kind traps);
+ - 50 held out until the end.
+- **Runs:** each message 2 or 3 times; deciding only, nothing sent (`cli/scripts/route-eval/`).
+
+| Set | Before | After |
+|---|---|---|
+| By hand + blind (101) | 63% right, 25 wrong sends in 123 (by hand alone) | 90% right, 0 wrong sends in 202 |
+| Red team (116) | 51% right, 66 wrong sends in 232 | 72% right, 6 in 232 |
+| Held out (50) | 81% right, 7 wrong sends in 150 | 83% right, 4 in 100 |
+
+What moved it, in order:
+1. **What Jev is shown** (`offered`). Live sessions come first, then stopped ones:
+ - A conversation listed twice is shown once.
+ - A stopped session is dropped when a live one has its name, or when it has nothing to read.
+ - Pasted-text tags, other agents' messages, and prompts that name nothing ("ok merge it", "cont") are
+ left out of descriptions. Each session says its machine.
+
+ On the owner's desk, the live "X Posts" shared Jev's vote with three stopped copies of itself, and
+ stopped leftovers took live sessions' places among the forty.
+2. **The question** asks for "the same kind of work on the same subject", not continuity or shared
+ words. "Continue their work" let "merge it" follow the words "ok merge it"; "whose job is this kind of
+ work" sent the lamp's retention to Harness's usage session.
+3. **A message that names nothing of its own** ("merge it", "post it as is"; Jev is asked in the same
+ call) goes where the last task went, or is new work. "A single word is enough" keeps "also check
+ retention" from counting as one.
+4. **Smaller rules:**
+ - A message asking for a new session is new work.
+ - A running pick is not held back by a stopped copy or a same-named twin (1.75× the rest).
+ - No more stopped sessions than forty in all: at fifty, old leftovers took new work.
+
+Every wrong send left in these runs is a judgement call a person could make either way:
+- a job post about the lamp firmware went to the lamp firmware session;
+- "rotate the leaked OpenRouter key" went to the session that checked it;
+- "why is the dial showing the wrong pane" went to the ⌘B session.
+
+Most misses split two right answers (two sessions that both flashed the round unit) or are stopped
+sessions beyond the forty. They become new work, which costs a harness.
+
## Not done
- The other clients: the phone, the web, the TUI and the dial still use their own