The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
Merge batch 11-05 i2210: #3186 #3174 #3190 #3169 (#3194)
0xken1553a67a0c9d72
diff --git a/cli/src/gateway/start.ts b/cli/src/gateway/start.tsindex cc6ae2bd8..91c208854 100644--- a/cli/src/gateway/start.ts+++ b/cli/src/gateway/start.ts@@ -291,7 +291,10 @@ export function startGateway(host: GatewayHost): StartedGateway {switchAccount: (from, to) => {// Run once, whatever it throws: the log goes on to the new account either way, and its devices// come back from that log. Run again, a half-done switch would put away what it already restored.- try { switchAccountTrust(from, to) } catch (err) {+ try {+ const epoch = account.signIn?.epoch ?? ''+ switchAccountTrust(from, to, undefined, { forgetPrevious: epoch.startsWith('team:') || epoch.startsWith('adopted:team:') })+ } catch (err) {console.log(`[devlog] could not swap the trust stores to the new account: ${err instanceof Error ? err.message : String(err)}`)}gateway.e2ee.reloadPaired()diff --git a/cli/src/lib/e2ee/accountTrust.spec.ts b/cli/src/lib/e2ee/accountTrust.spec.tsindex 6f4e7a99e..15edb03db 100644--- a/cli/src/lib/e2ee/accountTrust.spec.ts+++ b/cli/src/lib/e2ee/accountTrust.spec.ts@@ -43,6 +43,26 @@ describe('trust stores kept per account', () => {expect(read(dir, 'identity.json')).toEqual({ pub: 'me' })})+ it('discards the departing Team owner stash and never restores it on a later switch', () => {+ const dir = e2e()+ write(dir, 'paired.json', [web('a-web'), device])+ write(dir, 'group.json', { members: ['a'], removed: [] })+ write(dir, 'group-blocked.json', ['a-blocked'])+ write(dir, 'machinePeers.json', [{ machineId: 'ma', pub: 'a-box' }])+ // A previous switch left a stash too: it must not remain accessible to the next owner's agents.+ mkdirSync(join(dir, 'accounts', A), { recursive: true })+ write(join(dir, 'accounts', A), 'old.json', { label: 'previous owner' })+ switchAccountTrust(A, B, dir, { forgetPrevious: true })+ expect(existsSync(join(dir, 'accounts', A))).toBe(false)+ expect(read(dir, 'paired.json')).toEqual([device])+ for (const name of ['group.json', 'group-blocked.json', 'machinePeers.json']) expect(read(dir, name)).toBeUndefined()+ write(dir, 'paired.json', [device, web('b-web')])+ switchAccountTrust(B, A, dir, { forgetPrevious: true })+ expect(read(dir, 'paired.json')).toEqual([device])+ expect(existsSync(join(dir, 'accounts', B))).toBe(false)+ expect(read(dir, 'identity.json')).toEqual({ pub: 'me' })+ })+it('a stash cut short after its copy keeps the keys in both places, and a second run finishes it', () => {const dir = e2e()// The copy was written, the live file not yet cut.diff --git a/cli/src/lib/e2ee/accountTrust.ts b/cli/src/lib/e2ee/accountTrust.tsindex e9bb92ee8..8fdccf51a 100644--- a/cli/src/lib/e2ee/accountTrust.ts+++ b/cli/src/lib/e2ee/accountTrust.ts@@ -75,8 +75,10 @@ export function unstashTrust(acct: string, dir = defaultDir()): void {}/** Leave `from`'s trust for `to`'s. Both ids are checked before anything moves. */-export function switchAccountTrust(from: string, to: string, dir = defaultDir()): void {+export function switchAccountTrust(from: string, to: string, dir = defaultDir(), { forgetPrevious = false }: { forgetPrevious?: boolean } = {}): void {accountDir(dir, to)stashTrust(from, dir)+ // The Team account now runs another owner's agents: none of the departing owner's stash may remain readable.+ if (forgetPrevious) rmSync(accountDir(dir, from), { recursive: true, force: true })unstashTrust(to, dir)}diff --git a/cli/src/lib/e2ee/deviceLogStore.ts b/cli/src/lib/e2ee/deviceLogStore.tsindex 9aa497e7e..9cb0c6f25 100644--- a/cli/src/lib/e2ee/deviceLogStore.ts+++ b/cli/src/lib/e2ee/deviceLogStore.ts@@ -202,12 +202,12 @@ export class DeviceLogStore {return next}- /** Keep `file` — the log of an account this machine is leaving — to restore if it comes back. */- archive(file: DevLogFile): void {+ /** Keep the departing log for an ordinary sign-in; Team switches discard it, including an older archived copy. */+ archive(file: DevLogFile, { forget = false }: { forget?: boolean } = {}): void {if (!file.state) returnconst all = this.archived()delete all[file.state.acct]- all[file.state.acct] = trimmed(file)+ if (!forget) all[file.state.acct] = trimmed(file)const accts = Object.keys(all)for (const acct of accts.slice(0, Math.max(0, accts.length - DEVLOG_ARCHIVED))) delete all[acct]this.writeJson(this.archiveFile, all)diff --git a/cli/src/lib/e2ee/deviceLogSyncer.spec.ts b/cli/src/lib/e2ee/deviceLogSyncer.spec.tsindex 11b78fc3c..054a822cc 100644--- a/cli/src/lib/e2ee/deviceLogSyncer.spec.ts+++ b/cli/src/lib/e2ee/deviceLogSyncer.spec.ts@@ -1670,6 +1670,40 @@ describe('DeviceLogSyncer — departed keys, sign-ins and kept accounts', () =>expect(t.store.read().state?.acct).toBe(ACCT)})+ for (const review of [false, true]) {+ for (const team of [false, true]) {+ it(`${team ? 'Team' : 'ordinary'} switch ${review ? 'by confirmed review' : 'by refresh'} ${team ? 'forgets' : 'archives'} the departing device log`, async () => {+ const who = { epoch: 'u1', acct: ACCT }+ const s = setup({ signIn: () => who.epoch, signInAcct: () => who.acct })+ s.backend.add(box2, 'machine', MID2, 'previous owner private device')+ await s.syncer.register()+ const old = { ...s.store.read(), suspended: [phone.pub], preLog: [box2.pub] }+ s.store.write(old)+ // A copy from an older build must not survive beside the departing live log.+ s.store.archive(old)+ who.epoch = team ? 'team:new-owner' : 'u2'+ who.acct = review ? 'unmatched' : 'acct-2'+ const other = FakeBackend.of('acct-2')+ other.add(phone, 'viewer', '', 'new owner phone')+ s.backend.fetch.mockImplementation(other.fetch)+ await s.syncer.refresh()+ if (review) {+ expect(s.store.read().frozen?.reason).toBe('invalid')+ await s.syncer.rebaseline(true)+ }+ expect(s.store.read().state?.acct).toBe('acct-2')+ if (team) {+ expect(s.store.archivedFile(ACCT)).toBeNull()+ expect(s.store.archivedSuspended()).not.toContain(phone.pub)+ expect(s.store.read().suspended ?? []).not.toContain(phone.pub)+ } else {+ expect(s.store.archivedFile(ACCT)?.state?.active[box2.pub]?.label).toBe('previous owner private device')+ expect(s.store.archivedSuspended()).toContain(phone.pub)+ }+ })+ }+ }+it('a review of another account\'s list swaps them too', async () => {const switchAccount = vi.fn()const s = await signedInAgain(null, { switchAccount })diff --git a/cli/src/lib/e2ee/deviceLogSyncer.ts b/cli/src/lib/e2ee/deviceLogSyncer.tsindex 31702559b..69a3f3178 100644--- a/cli/src/lib/e2ee/deviceLogSyncer.ts+++ b/cli/src/lib/e2ee/deviceLogSyncer.ts@@ -383,6 +383,12 @@ export class DeviceLogSyncer {return local === null || file.owner === local.epoch}+ private archiveDeparting(file: DevLogFile): void {+ const epoch = this.deps.signIn()?.epoch ?? ''+ // Team agents must not inherit the departing owner's device names, keys or trust decisions.+ this.deps.store.archive(file, { forget: epoch.startsWith('team:') || epoch.startsWith('adopted:team:') })+ }+/** `file`, with every key a fork suspended in another account's kept log, and active in this one,* suspended (and new) here as well: it is not trusted either way, so the list says so — and "It's* mine" lifts it, everywhere (a review of this list does not: it never showed that suspension). */@@ -566,9 +572,9 @@ export class DeviceLogSyncer {}if (reset) {if (now) {- // What the account left behind trusted goes with its log, and comes back with it.+ // Ordinary sign-ins keep the departing trust and log; Team sign-ins discard them.this.deps.switchAccount?.(now.acct, got.acct)- this.deps.store.archive(latest)+ this.archiveDeparting(latest)}// Back to an account this machine was signed in to before: its log as verified then, and every// mark on it (frozen, suspended, pending), go on from where they were.@@ -1024,12 +1030,12 @@ export class DeviceLogSyncer {// The joined point never moves up past the reviewed head: a shorter list (rolled back, or// another account's) must leave every key added to it from here on news.const joinedSeq = Math.min(base.joinedSeq ?? base.notifiedUpTo, next.head.seq)- // The reviewed list is another account's: the one this machine leaves is kept, as on a sign-in+ // The reviewed list is another account's: the departing log follows the same policy as a sign-in// (and what a fork suspended in it stays suspended here) — and a kept one of the reviewed account// goes on from where it was.if (file.state && !same) {this.deps.switchAccount?.(file.state.acct, next.acct)- this.deps.store.archive(file)+ this.archiveDeparting(file)}const { joining: _j, ...rest } = baseconst reviewed: DevLogFile = this.carrySuspensions({diff --git a/cli/src/lib/swarmTools.ts b/cli/src/lib/swarmTools.tsindex 32aa74fed..97cd35ec2 100644--- a/cli/src/lib/swarmTools.ts+++ b/cli/src/lib/swarmTools.ts@@ -88,12 +88,13 @@ Swarm and machine settings (each refused unless you may change that setting; a p- Remove a note: \`{"type":"note.remove","projectId":"PROJECT","noteId":"NOTE"}\` (each note's id is in the \`instructions\` output): the coordinator, or a person who reads the project. An expired note is already gone.## Route and start-- \`route GROUP JSON\` lists who could do a group's work, before you start an agent or assign it. Work you do yourself is not routed. JSON: \`{"difficulty":"low|medium|high","risk":"low|medium|high","size":"small|medium|large","why":"one sentence","kind":"${ROUTE_KIND_HELP}","local":true,"model":"optional","needs":{"tools":[],"devices":[],"cwd":"/absolute/repo"}}\`.+- \`route GROUP JSON [--full-instructions] [--instructions-read REVISION]\` lists who could do a group's work, before you start an agent or assign it. Work you do yourself is not routed. JSON: \`{"difficulty":"low|medium|high","risk":"low|medium|high","size":"small|medium|large","why":"one sentence","kind":"${ROUTE_KIND_HELP}","local":true,"model":"optional","needs":{"tools":[],"devices":[],"cwd":"/absolute/repo"}}\`.- size is how long the work runs: small about 20 minutes, medium about an hour, large about three hours.- \`local\` only when a person asked for a local model. When a person names a model, set \`model\` to their words ("deepseek 4.1 flash"): the route then offers that model alone, unrated when the catalog does not list it.- It leaves out what cannot run (a machine offline, paused or full, an engine signed out or suspended, tools or devices the work needs, a machine that cannot take a teammate's project), and says why.- ${CHEAP_FIRST_HELP}- - It ranks nothing and names no pick: the rest come by machine name, then engine, each with its facts (model, effort, the catalog's strength and price, quota fit with weekly % left and reset time, the agents on its machine, idle or new). What else it knows is a note on the candidate: a used-up quota, a lost task, a machine whose last starts failed, a task requirement naming another machine, a model not offered by default, an account a project's PM runs on (which PM), a plug-in's finding. The first row is first by its machine's name, not by merit: choose by your project's Routing instructions.+ - Its answer is short: the instructions' Routing section and revision; the whole text with \`--full-instructions\`; only the revision with \`--instructions-read REVISION\` (the revision you read) while that is still current, so pass it on every route after you read them.+ - It ranks nothing and names no pick: the rest come by machine name, then engine. \`candidates\` is keyed by each machine's line (its name, \`machineId\`, agents, and \`cwd\` where it differs from the answer's \`cwd\`), each holding one line per candidate: its id, new or the member (agent id, idle or working), engine model effort, quota fit as "fits 62% · resets 5d", and its notes, each cut to a short clause. What else it knows is a note on the candidate: a used-up quota, a lost task, a machine whose last starts failed, a task requirement naming another machine, a model not offered by default, an account a project's PM runs on (which PM), a plug-in's finding. The first row is first by its machine's name, not by merit: choose by your project's Routing instructions.- A candidate on a model served on the Swarm's grid starts with the \`gridModel\` and \`gridName\` its row gives, in place of model and effort.- Start or assign the candidate you chose with the decision's \`routeDecisionId\` and \`overrideReason\`: the Routing rule that chose it, in one sentence. The decision records the candidate the start or assignment matches.- \`plan [JSON]\` places all open groups at once on machines and models (needs Python 3 and OR-Tools; without them it says how to install). JSON optional: \`{"groups":{"GROUP":{"difficulty":"...","risk":"...","size":"...","kind":"optional","after":["GROUP"]}}}\`. It records nothing: route each group, then start the plan's pick with the route's \`routeDecisionId\`.diff --git a/cli/src/superTabs/command.spec.ts b/cli/src/superTabs/command.spec.tsindex ab83306a7..e90d71778 100644--- a/cli/src/superTabs/command.spec.ts+++ b/cli/src/superTabs/command.spec.ts@@ -156,6 +156,44 @@ it('parses route GROUP JSON', () => {expect(parseSuperTabArgs([...prefix, 'route', 'g1', '{"difficulty":"low","risk":"low","why":"x"}'], where).payload).toMatchObject({ action: 'route', conversationId: 'g1', assessment: { difficulty: 'low' } })})+// Task #3294: the whole instructions only on request, and none of it again for a revision the caller read.+it('parses route\'s --full-instructions and --instructions-read N, and refuses anything else after the JSON', () => {+ const json = '{"difficulty":"low","risk":"low","why":"x"}'+ expect(parseSuperTabArgs([...prefix, 'route', 'g1', json], where).payload).not.toHaveProperty('fullInstructions')+ expect(parseSuperTabArgs([...prefix, 'route', 'g1', json, '--full-instructions'], where).payload).toMatchObject({ action: 'route', fullInstructions: true })+ expect(parseSuperTabArgs([...prefix, 'route', 'g1', json, '--instructions-read', '74'], where).payload).toMatchObject({ instructionsRead: 74 })+ expect(parseSuperTabArgs([...prefix, 'route', 'g1', json, '--instructions-read', '74', '--full-instructions'], where).payload)+ .toMatchObject({ instructionsRead: 74, fullInstructions: true })+ for (const tail of [['--instructions-read'], ['--instructions-read', 'x'], ['--instructions-read', '-1'], ['--full'], ['--full-instructions', '--full-instructions']]) {+ expect(() => parseSuperTabArgs([...prefix, 'route', 'g1', json, ...tail], where)).toThrow('harness super-tab')+ }+})+it('prints the compact route answer: the Routing section, not the whole instructions', async () => {+ const print = vi.fn(), close = vi.fn()+ const text = '# P\n\n## Roles\nWHOLE\n\n## Routing\nBy quota.\n'+ const request = vi.fn(async (type: string, payload: Record<string, unknown> = {}) => {+ if (type === 'agents_list') return { agents: [{ id: 'native', engine: 'claude', tmuxPane: '%42', status: 'active' }] }+ if (payload.action === 'routeContext') return { ok: true, value: { agentId: 'lead', tab: { revision: 1, state: {+ agents: [{ id: 'a1', name: 'Multiply', machineId: 'machine', harnessId: 'native', configuration: { engine: 'claude', model: 'opus', effort: 'high' } }],+ conversations: [{ id: 'g1', title: 'API', leadId: 'a1', agentIds: ['a1'], archived: false, brief: '', checks: [], assignment: null }] } },+ policy: { policy: { version: 1, models: [{ engine: 'claude', model: 'opus', effort: 'high', quality: 3, cost: 3, enabled: true }] } }, machines: [{ machineId: 'machine', name: 'mac' }] } }+ if (payload.action === 'command') return { ok: true, value: { result: { routeDecisionId: 'd1' } } }+ if (payload.action === 'instructions') return { ok: true, value: { revision: 7, text, notes: [] } }+ if (payload.action === 'routeHistory') return { ok: true, value: { decisions: [], attempts: [] } }+ if (type === 'engines_probe') return { engines: [{ engine: 'claude', installed: true, signedIn: true }] }+ if (type === 'usage_read') return { providers: [] }+ return { resources: { memoryTotalBytes: 8e9, memoryUsedBytes: 1e9, cpuPercent: 10, projectDiskFreeBytes: 1e11 }, tools: { git: true }, devices: {} }+ })+ const deps = { where: () => where, pane: '%42', open: async () => ({ request, close, machineId: 'machine' }), print }+ await superTabCommand(['--tab', 'tab', 'route', 'g1', '{"difficulty":"low","risk":"low","why":"x"}'], deps)+ const printed = JSON.parse(print.mock.calls.at(-1)![0] as string)+ expect(printed).toMatchObject({ ok: true, instructions: { revision: 7, routing: '## Routing\nBy quota.' }, candidates: { 'mac · machineId machine · 1 agents': [expect.stringMatching(/^c0 Multiply/), expect.stringMatching(/^c1 new/)] } })+ expect(JSON.stringify(printed)).not.toContain('WHOLE')+ await superTabCommand(['--tab', 'tab', 'route', 'g1', '{"difficulty":"low","risk":"low","why":"x"}', '--full-instructions'], deps)+ expect(JSON.parse(print.mock.calls.at(-1)![0] as string)).toMatchObject({ instructions: { revision: 7, text } })+ await superTabCommand(['--tab', 'tab', 'route', 'g1', '{"difficulty":"low","risk":"low","why":"x"}', '--instructions-read', '7'], deps)+ expect(JSON.parse(print.mock.calls.at(-1)![0] as string).instructions).toEqual({ revision: 7, unchanged: expect.any(String), notes: [] })+})it('routes through the caller and prints the decision, or the parse failure as an error', async () => {const print = vi.fn(), close = vi.fn()const request = vi.fn(async (type: string, payload: Record<string, unknown> = {}) => {diff --git a/cli/src/superTabs/command.ts b/cli/src/superTabs/command.tsindex 900e1a1bc..ea8b306d5 100644--- a/cli/src/superTabs/command.ts+++ b/cli/src/superTabs/command.ts@@ -1,6 +1,6 @@import { inspectCapacity, startAgent } from './start.js'import { object } from './host.js'-import { routeTask } from './routeCommand.js'+import { routeAnswer, routeTask } from './routeCommand.js'import { planWork } from './planCommand.js'import { openDaemon, whereFor, type Daemon, type Where } from '../agentClient/daemon.js'import { callerOf, outsideCaller, type Frame } from '../agentClient/model.js'@@ -29,7 +29,7 @@ function harnessIn(frames: PaneFrame[], pane: string, machineId: string): booleaconst ELSEWHERE = 'From a harness, Swarm commands go to this computer\'s own Harness only: leave out --machine and --port, or give this computer\'s own.'-const USAGE = 'harness super-tab --tab ID [--agent ID] [--port N --machine ID] status [--project NAME] [--archived [PAGE]] | messages GROUP [--thread ROOT] [--before SEQUENCE MESSAGE_ID] | message GROUP MESSAGE_ID | mine | task GROUP | decisions [--answered] | costs [--days N] | post GROUP TEXT|- OPERATION_ID [--to AGENT]... [--answers MESSAGE_ID | --reply-to MESSAGE_ID] [--attach PATH]... [--mention PERSON]... | react GROUP MESSAGE_ID EMOJI OPERATION_ID [--off] | command OPERATION_ID JSON | propose OPERATION_ID JSON [--attach PATH]... | start OPERATION_ID JSON | resume START_ID | capacity MACHINE_ID JSON | route GROUP JSON | plan [JSON] | remove-machine MACHINE_ID [--yes] | set-agents MACHINE_ID COUNT | instructions [PROJECT] | screen AGENT [--scrollback N] | type AGENT [TEXT] [--key K]... | help'+const USAGE = 'harness super-tab --tab ID [--agent ID] [--port N --machine ID] status [--project NAME] [--archived [PAGE]] | messages GROUP [--thread ROOT] [--before SEQUENCE MESSAGE_ID] | message GROUP MESSAGE_ID | mine | task GROUP | decisions [--answered] | costs [--days N] | post GROUP TEXT|- OPERATION_ID [--to AGENT]... [--answers MESSAGE_ID | --reply-to MESSAGE_ID] [--attach PATH]... [--mention PERSON]... | react GROUP MESSAGE_ID EMOJI OPERATION_ID [--off] | command OPERATION_ID JSON | propose OPERATION_ID JSON [--attach PATH]... | start OPERATION_ID JSON | resume START_ID | capacity MACHINE_ID JSON | route GROUP JSON [--full-instructions] [--instructions-read REVISION] | plan [JSON] | remove-machine MACHINE_ID [--yes] | set-agents MACHINE_ID COUNT | instructions [PROJECT] | screen AGENT [--scrollback N] | type AGENT [TEXT] [--key K]... | help'/** A Buddy's guard refuses a post or a proposal read from stdin (#2358): there its words would skip the secret check. A Buddy* that followed the stdin form here was refused and tried again (#2360 took it out of a Buddy's help), so a Buddy's usage* line and JSON hints never offer it. */@@ -144,6 +144,17 @@ async function buddyHere(open: typeof openDaemon, local: Where, pane: string | u/** The files one proposal may carry (backend buddies.ts MAX_PROPOSAL_ATTACHMENTS). */const MAX_PROPOSAL_FILES = 5+/** route's flags after its JSON: `--full-instructions` and `--instructions-read N`, each at most once; null for anything else. */+function routeFlags(tail: string[]): { fullInstructions?: true; instructionsRead?: number } | null {+ const flags: { fullInstructions?: true; instructionsRead?: number } = {}+ for (let i = 0; i < tail.length; i++) {+ if (tail[i] === '--full-instructions' && !flags.fullInstructions) flags.fullInstructions = true+ else if (tail[i] === '--instructions-read' && flags.instructionsRead === undefined && /^\d{1,9}$/.test(tail[i + 1] ?? '')) flags.instructionsRead = Number(tail[++i])+ else return null+ }+ return flags+}+/** [stdin] is asked for what `-` stands for: `post`'s message, or the JSON of the action it names. */export function parseSuperTabArgs(argv: readonly string[], where: Where, stdin: (what: string) => string = () => readFileSync(0, 'utf8'),terminal: () => boolean = () => isatty(0)) {@@ -259,8 +270,11 @@ export function parseSuperTabArgs(argv: readonly string[], where: Where, stdin:} else if (action === 'set-agents' && identifier(first) && /^[1-9][0-9]{0,3}$/.test(second ?? '') && positional.length === 3) {// The machine's owner, as the person: how many Swarm agents may run on it at once (contribution.ts setMachineAgents).Object.assign(payload, { action: 'setMachineAgents', machineId: first, maxAgents: Number(second) })- } else if (action === 'route' && identifier(first) && second && positional.length === 3) {- Object.assign(payload, { conversationId: first, assessment: jsonArgument(action, second) })+ } else if (action === 'route' && identifier(first) && second && positional[3]?.startsWith('--') && !routeFlags(positional.slice(3))) {+ throw usageError()+ } else if (action === 'route' && identifier(first) && second && routeFlags(positional.slice(3))) {+ // The whole instructions only on request, and none of them for a revision the caller read (task #3294).+ Object.assign(payload, { conversationId: first, assessment: jsonArgument(action, second), ...routeFlags(positional.slice(3)) })} else if (action === 'plan' && positional.length <= 2) {if (first !== undefined) payload.request = JSON.parse(first)} else if (action === 'screen' && identifier(first) && (positional.length === 2@@ -413,8 +427,9 @@ export async function superTabCommand(argv: readonly string[], deps: {print(JSON.stringify(answer))return 1} else if (request.payload.action === 'route') {- result = await routeTask({ tabId: String(request.payload.tabId), conversationId: String(request.payload.conversationId),- assessment: request.payload.assessment }, scoped, request.where, deps.open)+ result = routeAnswer(await routeTask({ tabId: String(request.payload.tabId), conversationId: String(request.payload.conversationId),+ assessment: request.payload.assessment }, scoped, request.where, deps.open),+ { fullInstructions: request.payload.fullInstructions === true, ...(typeof request.payload.instructionsRead === 'number' ? { instructionsRead: request.payload.instructionsRead } : {}) })} else if (request.payload.action === 'plan') {// Advisory: the plan records nothing, and the solver runs here, on the Lead's machine.result = await planWork({ request: request.payload.request }, scoped, { dataDir: request.where.dataDir })diff --git a/cli/src/superTabs/route.ts b/cli/src/superTabs/route.tsindex b3c7ff254..8304a3cb4 100644--- a/cli/src/superTabs/route.ts+++ b/cli/src/superTabs/route.ts@@ -607,6 +607,15 @@ export function quotaBrief(p: Pick<Probe, 'quota' | 'gridModel'> & { fit: Pick<Freturn `${p.fit.status}: weekly ${Math.round(left)}% left${resetsAt === null ? '' : `, resets in ${weeklyResetsIn(resetsAt, now)}`}`}+/** [quotaBrief] in a candidate's one line (task #3294): "fits 62% · resets 5d", the weekly window the project's order compares. */+export function quotaLine(p: Pick<Probe, 'quota' | 'gridModel'> & { fit: Pick<Fit, 'status'> }, now: number): string {+ if (p.gridModel) return 'free (grid)'+ if (p.quota.metered) return 'metered'+ const { left, resetsAt } = weekly(p.quota)+ if (left === null) return `${p.fit.status === 'unknown' ? '' : `${p.fit.status}, `}weekly unknown${p.quota.why ? ` (${cut(p.quota.why, 40)})` : ''}`+ return `${p.fit.status} ${Math.round(left)}%${resetsAt === null ? '' : ` · resets ${weeklyResetsIn(resetsAt, now)}`}`+}+/** One unrated new agent per machine of the named model's engine, on that machine's first row of the engine, which carries* its facts and its quota ([CLAUDE_NAMES]). The person's words are the model's id, in lowercase with no spaces. */function unratedProbes(probes: Probe[], named: string): Probe[] {diff --git a/cli/src/superTabs/routeCommand.spec.ts b/cli/src/superTabs/routeCommand.spec.tsindex e2c25c128..2a944ab6c 100644--- a/cli/src/superTabs/routeCommand.spec.ts+++ b/cli/src/superTabs/routeCommand.spec.ts@@ -4,7 +4,7 @@ import { mkdtemp, rm, writeFile } from 'node:fs/promises'import { tmpdir } from 'node:os'import { join } from 'node:path'import { PM_ACCOUNT_NOTE } from './pmAccounts.js'-import { ELSEWHERE, heldByStarts, heldLocalModels, leftOut, localProbes, NO_SWARM_AGENTS_ON, offlineModels, routeTask, servedModels, STALL_RETRY_MS, stalled } from './routeCommand.js'+import { ELSEWHERE, heldByStarts, heldLocalModels, leftOut, localProbes, NO_SWARM_AGENTS_ON, noteClause, offlineModels, routeAnswer, routeTask, routingSection, servedModels, STALL_RETRY_MS, stalled } from './routeCommand.js'import type { describeScmProject } from '../scm/scmProjects.js'import { admission, quotaOf, RELAYED_QUOTA, USED_UP_WINDOW } from './capacity.js'import { NONE_COVERS, OTHER_REPOSITORY, type Catalog, type Probe, type RoutePlugin } from './route.js'@@ -2368,3 +2368,133 @@ describe('needs.access', () => {for (const r of requirements) expect(r).not.toContain('access')})})++// Ken, 2026-11-05 (task #3294): each route answer was ~45k characters (the whole instructions, every candidate as an object,+// long left-out reasons), 467 a day in one project's PM context. The answer printed is a few thousand.+describe('the route answer an agent reads (task #3294)', () => {+ const names = ['Ken\'s MacBook Pro', 'Mac Studio', 'Tony\'s Mac mini', 'Diego\'s review machine', 'Huy\'s MacBook Air', 'Scholes\'s iMac',+ 'Dee\'s Mac mini', 'Amon\'s MacBook Pro', 'Build box', 'Kelvin\'s Mac Studio']+ const machineIds = names.map((_, i) => `${String(i).padStart(2, '0')}f3923b927e36499865b0bd2b6223a4`)+ const gone = ['Old Linux box', 'Windows laptop', 'Lab Raspberry Pi', 'Office NUC', 'Spare Mac mini'].map((name, i) => ({ machineId: `gone${i}9865b0bd2b6223a457f3923b927`, name }))+ const fleetPolicy = { ...policy, models: [...policy.models.filter(m => m.model !== 'sonnet'), { engine: 'codex', model: 'gpt-6-astra', effort: 'xhigh', quality: 3, cost: 3, enabled: true }] }+ const week = (provider: string, used: number) => ({ provider, outcome: 'answered', httpStatus: 200, account: `${provider}-acct`, body: {+ five_hour: { utilization: 20, resets_at: new Date(Date.now() + 3 * 3_600_000).toISOString() },+ seven_day: { utilization: used, resets_at: new Date(Date.now() + 5 * 86_400_000).toISOString() } } })+ // Every machine runs an idle Claude and an idle Codex member, and offers a new agent of each: 40 candidates.+ const crew = machineIds.flatMap((machineId, i) => [+ { id: `${machineId.slice(0, 20)}cl${i}`, name: `Aspen${i}`, machineId, harnessId: `hc${i}`, configuration: { engine: 'claude', model: 'opus', effort: 'high' } },+ { id: `${machineId.slice(0, 20)}cx${i}`, name: `Birch${i}`, machineId, harnessId: `hx${i}`, configuration: { engine: 'codex', model: 'gpt-6-astra', effort: 'xhigh' } }])+ const fleet = () => {+ const state = tab().state+ state.agents = [agents[1]!, ...crew]+ state.conversations[0]!.agentIds = ['lead', ...crew.map(a => a.id)]+ return { revision: 3, state }+ }+ const routing = ['## Routing', '', '### Models', '', ...Array.from({ length: 12 }, (_, i) => `- Rule ${i}: ${'route by quota and machine. '.repeat(12).trim()}`)].join('\n')+ const document = ['# Project instructions', '', '## Roles', '', 'x'.repeat(20_000), '', routing, '', '## Rules for every agent', '', 'y'.repeat(6_000)].join('\n')+ const fleetScoped = (revision = 74) => scoped({ policy: fleetPolicy as typeof policy,+ context: { ok: true, value: { agentId: 'lead', tab: fleet(), policy: { policy: fleetPolicy, warnings: [] },+ machines: [...machineIds.map((machineId, i) => ({ machineId, name: names[i] })), ...gone] } },+ instructions: { ok: true, value: { projectId: 'p1', revision, text: document, notes: [{ id: 'n1', text: 'Release Amon\'s hotfix first.', askedBy: 'Ken' }] } } })+ const fleetOpener = () => opener(id => {+ const i = machineIds.indexOf(id)+ if (i < 0) return { ...daemon(id), request: vi.fn(async () => { throw new Error('offline') }) }+ return daemon(id, { agents: [`hc${i}`, `hx${i}`], usage: { providers: [week('claude', 38), week('codex', 55)] },+ engines: [{ engine: 'claude', installed: true, signedIn: true }, { engine: 'codex', installed: true, signedIn: true }] })+ })+ const fit: PluginMaker = { name: 'Machine fit', make: async () => ({ name: 'Machine fit',+ adjust: c => c.kind === 'new' ? { strength: 0, reason: 'its 3 agents use 61% of the CPU; a build here waits on the others, and its disk has 40 GB free, enough for this task.' } : null }) }+ const fleetRoute = () => routeTask(input, fleetScoped(), where as never, fleetOpener(), () => 'op', undefined, [fit])++ it('is under 8,000 characters for 40 candidates, and every row still says what a start or an assignment needs', async () => {+ const answer = await fleetRoute()+ expect((answer.candidates as unknown[]).length).toBe(40)+ const printed = routeAnswer(answer, { instructionsRead: 74 })+ expect(JSON.stringify(printed).length).toBeLessThan(8_000)+ // The first route of a revision adds only its Routing section.+ expect(JSON.stringify(routeAnswer(answer)).length).toBeLessThan(8_000 + routing.length)+ // Each machine once, with what a start there takes; every candidate a line under it, with what a start or an assignment takes.+ const machines = Object.entries(printed.candidates as Record<string, string[]>)+ expect(machines).toHaveLength(10)+ const lines = machines.flatMap(([machine, rows]) => rows.map(line => ({ machine, line })))+ expect(lines).toHaveLength(40)+ for (const [i, row] of (answer.candidates as Array<{ id: string; kind: string; agentId?: string; machineId: string; engine: string; model: string; effort: string; cwd?: string }>).entries()) {+ const { machine, line } = lines[i]!+ expect(line).toMatch(new RegExp(`^${row.id} ${row.kind === 'new' ? 'new' : `\\S+ \\(agent ${row.agentId}, idle\\)`} · ${row.engine} ${row.model} ${row.effort} · `))+ expect(machine).toMatch(new RegExp(`· machineId ${row.machineId} · 2 agents$`))+ }+ // The why of an unranked route is the next's first sentence; the record keeps it whole.+ expect(printed).not.toHaveProperty('why')+ expect(printed.next).toMatch(/^Not ranked: listed by machine name\. Choose one by the project's Routing instructions \(Order and quota\)/)+ expect(routeAnswer({ ok: true, via: 'only', why: 'Only candidate that can run this task.' })).toMatchObject({ why: 'Only candidate that can run this task.' })+ // The folder a start takes is said once when every machine shares it (a live route: 23 machines, one folder of 85 characters).+ expect(printed.cwd).toBe('/absolute/repo/on/that/machine')+ expect(lines[0]!.line).toMatch(/· fits 62% · resets 5d$/)+ // A note is its first clause, long enough to keep the name or the cause it carries (review of #3169).+ expect(noteClause(PM_ACCOUNT_NOTE(['lamp (Faye)', 'computer (Sage)']))).toBe('This account runs the PM of lamp (Faye) and computer (Sage)')+ expect(noteClause('Its last start failed while preparing the project folder. The start has the details; this does not suspend the engine.'))+ .toBe('Its last start failed while preparing the project folder')+ expect(noteClause('x'.repeat(100))).toBe(`${'x'.repeat(71)}…`)+ // A note is its first clause; the record for Details keeps it whole.+ expect(lines[1]!.line).toMatch(/· Machine fit: its 3 agents use 61% of the CPU$/)+ })+ it('gives the instructions as their Routing section and revision, the whole text on request, and none of it again for a revision read', async () => {+ const answer = await fleetRoute()+ const plain = routeAnswer(answer).instructions as Record<string, unknown>+ expect(plain).toEqual({ revision: 74, routing, notes: ['Release Amon\'s hotfix first.'], more: expect.stringContaining('--full-instructions') })+ expect(JSON.stringify(routeAnswer(answer))).not.toContain('x'.repeat(100))+ expect(routeAnswer(answer, { fullInstructions: true }).instructions).toMatchObject({ revision: 74, text: document, notes: ['Release Amon\'s hotfix first.'] })+ // A revision already read is not sent again; an older one is.+ const read = routeAnswer(answer, { instructionsRead: 74 }).instructions as Record<string, unknown>+ // Its notes still come: adding one does not change the revision (review of #3169).+ expect(read).toEqual({ revision: 74, unchanged: expect.stringContaining('revision 74'), notes: ['Release Amon\'s hotfix first.'] })+ expect(routeAnswer(answer, { instructionsRead: 73 }).instructions).toMatchObject({ revision: 74, routing })+ // The whole text wins over a revision read.+ expect(routeAnswer(answer, { fullInstructions: true, instructionsRead: 74 }).instructions).toMatchObject({ text: document })+ // Instructions with no Routing section are sent whole, never as nothing; unreadable ones say so.+ const bare = { ...answer, instructions: { revision: 2, text: '# Rules\n\nWork by this.', notes: [] } }+ expect(routeAnswer(bare).instructions).toMatchObject({ revision: 2, text: '# Rules\n\nWork by this.' })+ expect(routeAnswer({ ...answer, instructions: undefined, instructionsUnreadable: true })).toMatchObject({ instructionsUnreadable: true })+ })+ it('says a machine\'s own folder only where it differs from the one most share, and no room, which the record keeps', () => {+ const row = (id: string, machineName: string, cwd: string) => ({ id, kind: 'new', machineId: `id-${machineName}`, machineName, cwd, agents: 1, machine: '6 slots free · 14 GB memory free', line: `${id} new` })+ const printed = routeAnswer({ ok: true, candidates: [row('c0', 'a', '/Users/t/repo'), row('c1', 'b', '/home/t/repo'), row('c2', 'c', '/Users/t/repo')] })+ expect(printed).toEqual({ ok: true, cwd: '/Users/t/repo', candidates: { 'a · machineId id-a · 1 agents': ['c0 new'],+ 'b · machineId id-b · 1 agents · cwd /home/t/repo': ['c1 new'], 'c · machineId id-c · 1 agents': ['c2 new'] } })+ expect(JSON.stringify(printed)).not.toContain('slots')+ // Members only: no folder to say.+ expect(routeAnswer({ ok: true, candidates: [{ id: 'c0', kind: 'member', machineId: 'm', machineName: 'a', line: 'c0 M' }] })).not.toHaveProperty('cwd')+ })+ it('says each machine left out in one line, and what is left out of no machine when nothing can run', () => {+ const long = 'z'.repeat(400)+ const printed = routeAnswer({ error: 'NO_CANDIDATE', excluded: [{ title: 'Named model', reason: long }, { title: 't', reason: 'x', machine: 'mac' }],+ leftOut: [{ machine: 'mac', reasons: ['Machine is offline or unreachable.', 'b', 'c'] }, { machine: 'pi', reasons: [long] },+ { machine: 'nuc', reasons: ['Machine is offline or unreachable.'] }], warnings: [long] })+ expect(printed).toEqual({ error: 'NO_CANDIDATE', excluded: [`Named model: ${'z'.repeat(119)}…`],+ // Machines left out for the same first reason share its line (a live route: five machines offline).+ leftOut: ['mac (+2 more reasons), nuc: Machine is offline or unreachable.', `pi: ${'z'.repeat(119)}…`], warnings: [`${'z'.repeat(239)}…`] })+ })+ it('tells two machines of one name apart by id', async () => {+ const twin = fleetScoped(), base = twin.getMockImplementation()!+ twin.mockImplementation(async payload => {+ const answer = await base(payload)+ if (payload.action !== 'routeContext') return answer+ const value = answer.value as { machines: Array<{ machineId: string; name: string }> }+ return { ...answer, value: { ...value, machines: value.machines.map(m => m.machineId === machineIds[1] ? { ...m, name: names[0]! } : m) } }+ })+ const answer = await routeTask(input, twin, where as never, fleetOpener(), () => 'op', undefined, [fit])+ const machines = Object.keys(routeAnswer(answer).candidates as Record<string, string[]>)+ expect(machines.filter(m => m.startsWith(names[0]!))).toEqual(expect.arrayContaining([+ `Ken's MacBook Pro · machineId ${machineIds[0]} · 2 agents`, `Ken's MacBook Pro · machineId ${machineIds[1]} · 2 agents`]))+ })+ it('finds the Routing section up to the next heading of its level or higher, its own subsections kept', () => {+ expect(routingSection('# P\n\n## Roles\nr\n\n## Routing\n\n### Models\nm\n\n## Rules\nx')).toBe('## Routing\n\n### Models\nm')+ expect(routingSection('## Routing\nonly')).toBe('## Routing\nonly')+ expect(routingSection('# Routing\nTop\n# Next')).toBe('# Routing\nTop')+ expect(routingSection('## Roles\nRouting is mentioned, not a heading.\n### Routing notes\nn')).toBeNull()+ // A shell comment in a fenced block is not a heading (review of #3169), nor a Routing heading inside one.+ expect(routingSection('## Routing\n```sh\n# start it\nharness start\n```\nafter\n## Rules\nx')).toBe('## Routing\n```sh\n# start it\nharness start\n```\nafter')+ expect(routingSection('```\n## Routing\n```\n## Roles\nr')).toBeNull()+ })+})+diff --git a/cli/src/superTabs/routeCommand.ts b/cli/src/superTabs/routeCommand.tsindex cd9114ad7..c56a77206 100644--- a/cli/src/superTabs/routeCommand.ts+++ b/cli/src/superTabs/routeCommand.ts@@ -10,7 +10,7 @@ import { START_DEADLINE_MS, START_WINDOW_MS } from './reservations.js'import { inspectCapacity, type ScopedRequest } from './start.js'import { ENDED_WORK, object, within } from './wire.js'import { withPmAccounts } from './pmAccounts.js'-import { accountOf, API_BUILDERS, bytes, machineBrief, catalogFrom, catalogRow, choose, decide, gridStrength, parseAssessment, OLD_RECORD_MAX, quotaBrief, quotaOf2, recentStartNotes, recordOf, repoMatch, repositoryKey, type Assessment, type Catalog, type CatalogModel, type RecordShape, type Commitment, type Excluded, type Shown, type HeldModel, type MemberFrame, type Probe, type TaskFolder } from './route.js'+import { accountOf, API_BUILDERS, bytes, machineBrief, catalogFrom, catalogRow, choose, decide, gridStrength, parseAssessment, OLD_RECORD_MAX, quotaBrief, quotaLine, quotaOf2, recentStartNotes, UNRATED, recordOf, repoMatch, repositoryKey, type Assessment, type Catalog, type CatalogModel, type RecordShape, type Commitment, type Excluded, type Shown, type HeldModel, type MemberFrame, type Probe, type TaskFolder } from './route.js'import { makePlugins, ROUTE_PLUGIN_MAKERS, type PluginMaker } from './routePlugins.js'import { CI_HOLD_OPENING, CI_RETRY_MINUTES, heavyOfStart, MACHINE_FIT_MAKER } from './machineFit.js'import { stat } from 'node:fs/promises'@@ -549,7 +549,15 @@ export async function routeTask(input: { tabId: string; conversationId: string;const publicOf = (s: Shown) => ({ id: s.id, kind: s.kind, ...(s.agentId ? { agentId: s.agentId } : {}), machineId: s.machineId,engine: s.engine, model: s.model, effort: s.effort, title: s.title, ...(s.gridModel ? { gridModel: s.gridModel, gridName: s.gridName } : {}),...(s.unrated ? { unrated: true } : {}), quota: quotaBrief(s, now), ...(s.kind === 'new' ? { cwd: cwdOn(s.machineId) } : {}),- ...(s.kind === 'new' && s.load?.room ? { machine: machineBrief(s.load.room) } : {}), ...(s.notes.length ? { notes: s.notes } : {}) })+ ...(s.kind === 'new' && s.load?.room ? { machine: machineBrief(s.load.room) } : {}), ...(s.notes.length ? { notes: s.notes } : {}),+ machineName: s.machineName, ...(agentsOn.has(s.machineId) ? { agents: agentsOn.get(s.machineId) } : {}), line: lineOf(s) })+ // The agents on each machine, as any of its rows read them: a member's row may carry no reading of its machine.+ const agentsOn = new Map(offered.filter(s => typeof s.load?.agents === 'number').map(s => [s.machineId, s.load!.agents!]))+ // A candidate in one line for the agent choosing (task #3294), under its machine, which says its id, agents, folder and room+ // once (routeAnswer).+ const lineOf = (s: Shown) => [`${s.id} ${s.kind === 'new' ? 'new' : `${s.name ?? 'Member'} (agent ${s.agentId}, ${s.activity})`}`,+ s.gridModel ? `${s.engine} on the grid: gridModel ${s.gridModel}, gridName ${s.gridName}` : `${s.engine} ${s.model} ${s.effort}${s.unrated ? ' (unrated)' : ''}`,+ quotaLine(s, now), ...s.notes.filter(n => n !== UNRATED).map(noteClause)].join(' · ')// Every recorded row: the coordinator may reuse a particular member (the same Reviewer for its next round, Routing rule 3),// so none is hidden behind another on its account.const shownRows = offered@@ -571,17 +579,18 @@ export async function routeTask(input: { tabId: string; conversationId: string;* agent started, each with the chosen row's own fields; RULE is the Routing rule that chose it, which the backend asks for* with a decision that has no pick, and the start or assignment records the candidate it matches. */function nextOf(rows: Shown[], conversationId: string, routeDecisionId: string | undefined, instructions: boolean, needs: Assessment['needs']): string {- const choose = 'Choose one candidate by the project\'s Routing instructions (Order and quota); the list is by machine name, not by merit.'+ // Said once and short (task #3294): it rode on every route, 467 a day in one PM's context.+ const choose = 'Not ranked: listed by machine name. Choose one by the project\'s Routing instructions (Order and quota), and give the rule that chose it as overrideReason.'const decided = routeDecisionId ? { routeDecisionId, overrideReason: 'RULE' } : {}- const assign = `Assign a member with: command OPERATION_ID ${JSON.stringify({ type: 'work.assign', conversationId, agentId: 'AGENT', ...decided })}`+ const assign = `Assign a member: command OPERATION_ID ${JSON.stringify({ type: 'work.assign', conversationId, agentId: 'AGENT', ...decided })}`// No fixed role name: NAME and ROLE are the agent's to fill from the project's instructions. A backend without instructions// takes no roleName (it came with them, phase 2).- const start = `Start a new agent with: start OPERATION_ID ${JSON.stringify({ conversationId, name: 'NAME', ...(instructions ? { roleName: 'ROLE' } : {}),+ const start = `Start a new agent: start OPERATION_ID ${JSON.stringify({ conversationId, name: 'NAME', ...(instructions ? { roleName: 'ROLE' } : {}),cwd: 'CWD', worktree: true, requirements: startRequirements(needs), ...(needs.heavy ? { heavy: needs.heavy } : {}),- machineId: 'MACHINE', engine: 'ENGINE', model: 'MODEL', effort: 'EFFORT', ...decided })}, then assign the started agent${routeDecisionId ? ' with the same routeDecisionId' : ''}. `- + 'Put the chosen row\'s machineId, engine, model, effort and cwd for MACHINE, ENGINE, MODEL, EFFORT and CWD; a row on a model served on the Swarm\'s grid takes its gridModel and gridName in place of model and effort. '- + `Put the agent's name for NAME${instructions ? ' and its role in the project\'s instructions for ROLE' : ''}. It starts from the repository's default branch, fetched first; add "branchRef":"refs/remotes/origin/BRANCH" to start from another branch.`- const rule = routeDecisionId ? ' Put the Routing rule that chose it for RULE (urgency, context or a machine the work needs where it departs from the order).' : ''+ machineId: 'MACHINE', engine: 'ENGINE', model: 'MODEL', effort: 'EFFORT', ...decided })}, then assign it${routeDecisionId ? ' with the same routeDecisionId' : ''}. `+ + 'MACHINE is its machine\'s machineId, CWD the cwd its machine names or else the answer\'s; ENGINE, MODEL and EFFORT its line\'s; a grid line takes its gridModel and gridName in place of model and effort. '+ + `NAME is the agent's name${instructions ? ', ROLE its role in the instructions' : ''}. It starts from the default branch, fetched first; add "branchRef":"refs/remotes/origin/BRANCH" for another.`+ const rule = routeDecisionId ? ' RULE: the Routing rule that chose it.' : ''return [choose, ...(rows.some(r => r.kind === 'member') ? [assign] : []), ...(rows.some(r => r.kind === 'new') ? [start] : [])].join(' ') + rule}@@ -827,3 +836,91 @@ async function probeMachine(machineId: string, { name: machineName, status, accoreturn probes} finally { target.close() }}++/** A note in a candidate's line: its first sentence, cut short. The record for Details keeps it whole. Long enough for the+ * name or the cause a note carries (which PM an account runs, what a failed start was preparing; review of #3169). */+export function noteClause(note: string): string {+ const first = /^(.*?[^.])(?:\.\s|;\s|\.$|$)/.exec(note.trim())?.[1] ?? note+ return first.length <= NOTE_MAX ? first : `${first.slice(0, NOTE_MAX - 1)}…`+}+const NOTE_MAX = 72, LEFT_OUT_REASON_MAX = 120, WARNING_MAX = 240++/** The section of the instructions headed "Routing" (any level), up to the next heading of its level or higher, with its+ * own subsections (Models, Machines, Order and quota); null when the instructions have none. */+export function routingSection(text: string): string | null {+ // Line by line, so a shell comment in a fenced block is not taken for a heading (review of #3169).+ const lines = text.split('\n')+ let fenced = false, start = -1, level = 0+ for (const [i, line] of lines.entries()) {+ if (/^\s*(```|~~~)/.test(line)) { fenced = !fenced; continue }+ const head = fenced ? null : /^(#{1,6})[ \t]+(.*?)[ \t]*$/.exec(line)+ if (!head) continue+ if (start >= 0 && head[1]!.length <= level) return lines.slice(start, i).join('\n').trimEnd()+ if (start < 0 && head[2] === 'Routing') { start = i; level = head[1]!.length }+ }+ return start < 0 ? null : lines.slice(start).join('\n').trimEnd()+}++/** What `harness super-tab route` prints of [answer] (task #3294, Ken 2026-11-05): each answer was ~45k characters, the+ * whole instructions (~30k) and every candidate as an object (~15k), 467 a day in one PM's context. It prints the+ * instructions' Routing section and revision (the whole text with [fullInstructions]; only the revision when the caller+ * already read it, [instructionsRead]), each candidate in one line, each machine's id, start folder and room once, and one+ * line per machine left out. The decision recorded for Details is the whole one ([routeTask]). */+export function routeAnswer(answer: Json, options: { fullInstructions?: boolean; instructionsRead?: number } = {}): Json {+ const { instructions, candidates, leftOut: out, excluded, warnings, p, why, ...rest } = answer+ // An unranked route's why is its next's first sentence; the record keeps it whole.+ const printed: Json = { ...rest, ...(p === null || p === undefined ? {} : { p }), ...(why === undefined || answer.via === 'instructions' ? {} : { why }) }+ const written = instructions && typeof instructions === 'object' ? object(instructions) : null+ if (written) {+ const notes = Array.isArray(written.notes) ? written.notes.map(n => String(object(n).text ?? n)) : []+ const text = String(written.text ?? ''), routing = routingSection(text)+ printed.instructions = options.fullInstructions || routing === null ? { revision: written.revision, text, notes }+ : options.instructionsRead === written.revision+ // Its notes still come: adding one does not change the revision (backend note.add), and they hold the short-lived+ // routing facts (a machine away today; review of #3169).+ ? { revision: written.revision, unchanged: `You read revision ${written.revision}; it is current. Route with --full-instructions to have it again.`, notes }+ : { revision: written.revision, routing, notes, more: 'The Routing section only: the whole text with the instructions command, or route with --full-instructions. '+ + `Route with --instructions-read ${written.revision} once you have read this revision.` }+ }+ if (Array.isArray(candidates)) {+ // By machine, in the list's order: the machine's id and agents once, then its candidates' lines. The folder a start takes+ // is said once, the one most machines share (a live route: 23 machines, one folder of 85 characters), and on a machine+ // only where it differs. Free slots, memory and disk stay in the record: the route already leaves out what cannot run.+ const rows = candidates.map(object)+ const folders = new Map<string, number>()+ for (const row of rows) if (row.kind === 'new' && typeof row.cwd === 'string') folders.set(row.cwd, (folders.get(row.cwd) ?? 0) + 1)+ const cwd = [...folders].sort((x, y) => y[1] - x[1])[0]?.[0]+ if (cwd) printed.cwd = cwd+ const machines = new Map<string, { machine: string; candidates: string[] }>()+ // By id: two machines of one name are told apart by the machineId their lines say.+ for (const row of rows) {+ const id = String(row.machineId), name = String(row.machineName ?? row.machineId)+ const at = machines.get(id) ?? machines.set(id, { machine: '', candidates: [] }).get(id)!+ if (!at.machine || row.kind === 'new' && row.cwd !== cwd && !at.machine.includes(' · cwd ')) {+ at.machine = [name, `machineId ${row.machineId}`, ...(typeof row.agents === 'number' ? [`${row.agents} agents`] : []),+ ...(row.kind === 'new' && row.cwd && row.cwd !== cwd ? [`cwd ${row.cwd}`] : [])].join(' · ')+ }+ at.candidates.push(String(row.line))+ }+ // Keyed by the machine's line: an object per machine cost 30 characters each (a live route: 21 machines).+ printed.candidates = Object.fromEntries([...machines.values()].map(m => [m.machine, m.candidates]))+ }+ if (Array.isArray(excluded)) {+ // Without a candidate: what is left out of no machine (a named model, the catalog) is said; each machine's is in leftOut.+ const general = excluded.map(object).filter(e => !e.machine).map(e => `${e.title}: ${cut(String(e.reason), LEFT_OUT_REASON_MAX)}`)+ if (general.length) printed.excluded = general+ }+ if (Array.isArray(out)) {+ // Machines left out for the same first reason share its line (a live route: five machines offline, five lines).+ const byReason = new Map<string, string[]>()+ for (const m of out.map(object)) {+ const reasons = Array.isArray(m.reasons) ? m.reasons.map(String) : []+ const reason = cut(reasons[0] ?? 'left out', LEFT_OUT_REASON_MAX)+ byReason.set(reason, [...byReason.get(reason) ?? [], `${m.machine}${reasons.length > 1 ? ` (+${reasons.length - 1} more reasons)` : ''}`])+ }+ printed.leftOut = [...byReason].map(([reason, machines]) => `${machines.join(', ')}: ${reason}`)+ }+ if (Array.isArray(warnings) && warnings.length) printed.warnings = warnings.map(w => cut(String(w), WARNING_MAX))+ return printed+}+const cut = (text: string, max: number) => text.length <= max ? text : `${text.slice(0, max - 1)}…`diff --git a/cli/src/superTabs/service.spec.ts b/cli/src/superTabs/service.spec.tsindex a7abc49d7..c72a0bea6 100644--- a/cli/src/superTabs/service.spec.ts+++ b/cli/src/superTabs/service.spec.ts@@ -1258,6 +1258,19 @@ describe('the Harness Team account, offered by Desktop on this Mac', () => {// Amon, 11-05 (#3215): his Mac's entry was moved into the Swarm by the server (backend computerMoves.ts), so this daemon kept// no host record and never started its host: the Team account it should add sat "joining" for good, and nothing was sent.+ it('allows Team restart only from its local owner and only for a manual setup request', async () => {+ const offer = vi.fn(async () => ({ state: 'started' as const }))+ const service = superTabService(fakeCore(), { teamSetup: vi.fn(async () => ({ offer, decline: vi.fn() })) })+ await service.requests.super_tabs({ action: 'teamSetup', reason: 'manual', restart: true }, owner)+ expect(offer).toHaveBeenLastCalledWith('manual', expect.any(Function), false, { signInAgain: false, restart: true })+ for (const asker of [{ local: false, owner: true }, { local: true, owner: false }]) {+ expect(await service.requests.super_tabs({ action: 'teamSetup', reason: 'manual', restart: true }, asker as never)).toEqual({ error: 'OWNER_REQUIRED' })+ }+ expect(offer).toHaveBeenCalledTimes(1)+ await service.requests.super_tabs({ action: 'teamSetup', reason: 'join', restart: true }, owner)+ expect(offer).toHaveBeenLastCalledWith('join', expect.any(Function), false, { signInAgain: false })+ })+it("starts its Swarm host when the server says one of its Swarms changed, though it keeps no host record", async () => {const heard = new Set<(notice: never) => void>()const start = vi.fn()diff --git a/cli/src/superTabs/service.ts b/cli/src/superTabs/service.tsindex 49103cd36..34d5271fd 100644--- a/cli/src/superTabs/service.ts+++ b/cli/src/superTabs/service.ts@@ -89,7 +89,7 @@ const HELP = {// A person's own command, for the machines they added; an agent's terminal is refused (command.ts), so no agent raises its// own machine's room (Lead, 2026-10-28).setAgents: 'set-agents MACHINE_ID COUNT: for a machine\'s owner, from their own terminal, not an agent\'s: how many Swarm agents may run on that machine at once. Each agent still needs free memory when it starts. A machine may offer one agent for every 2 GB of its memory, and at least 4; a larger number is refused.',- route: `route GROUP JSON: list who could do a group's work, before you start an agent or assign it to another. Work you do yourself is not routed. JSON: {"difficulty":"low|medium|high","risk":"low|medium|high","size":"small|medium|large","why":"one sentence","kind":"${ROUTE_KIND_HELP}","local":"optional true, only when a person asked for a local model","model":"optional: the model a person named, in their words; only it is offered","needs":{"tools":[],"devices":[],"cwd":"/absolute/repo"}}. size is how long the work runs: small about 20 minutes, medium about an hour, large about three hours. The route leaves out what cannot run, and says why: a machine offline, paused or full, an engine not installed, signed out or suspended, tools or devices the work needs that a machine lacks, and machines that cannot take a teammate's project (it runs only on Team machines: a Mac's Harness Team account whose privacy check passed, or a machine used only for agents). It ranks nothing and names no pick: the rest come by machine name, then engine, each with its facts (model, effort, the catalog's strength and price, quota fit with weekly % left and reset time, the agents on its machine, idle or new), and it notes what else it knows on each candidate: a used-up quota, a lost task, a machine whose last starts failed, a task requirement naming another machine, a model the catalog does not offer by default or does not rate, a plug-in's finding. ${CHEAP_FIRST_HELP} The first row is first by its machine's name, not by merit: choose by your project's Routing instructions. A named model the catalog does not list is offered unrated. A candidate on a model served on the Swarm's grid starts with gridModel and gridName in place of model and effort. Start or assign the candidate you chose with the routeDecisionId and overrideReason, the Routing rule that chose it, so the decision records what ran and why.`,+ route: `route GROUP JSON [--full-instructions] [--instructions-read REVISION]: list who could do a group's work, before you start an agent or assign it to another. Work you do yourself is not routed. It answers with the instructions' Routing section and revision (the whole text with --full-instructions; only the revision with --instructions-read REVISION, the one you read, while it is current), candidates keyed by each machine's line (its machineId, agents, and cwd where it differs from the answer's cwd) with one line per candidate under it, and the machines left out, one line per reason. JSON: {"difficulty":"low|medium|high","risk":"low|medium|high","size":"small|medium|large","why":"one sentence","kind":"${ROUTE_KIND_HELP}","local":"optional true, only when a person asked for a local model","model":"optional: the model a person named, in their words; only it is offered","needs":{"tools":[],"devices":[],"cwd":"/absolute/repo"}}. size is how long the work runs: small about 20 minutes, medium about an hour, large about three hours. The route leaves out what cannot run, and says why: a machine offline, paused or full, an engine not installed, signed out or suspended, tools or devices the work needs that a machine lacks, and machines that cannot take a teammate's project (it runs only on Team machines: a Mac's Harness Team account whose privacy check passed, or a machine used only for agents). It ranks nothing and names no pick: the rest come by machine name, then engine, each with its facts (model, effort, the catalog's strength and price, quota fit with weekly % left and reset time, the agents on its machine, idle or new), and it notes what else it knows on each candidate: a used-up quota, a lost task, a machine whose last starts failed, a task requirement naming another machine, a model the catalog does not offer by default or does not rate, a plug-in's finding. ${CHEAP_FIRST_HELP} The first row is first by its machine's name, not by merit: choose by your project's Routing instructions. A named model the catalog does not list is offered unrated. A candidate on a model served on the Swarm's grid starts with gridModel and gridName in place of model and effort. Start or assign the candidate you chose with the routeDecisionId and overrideReason, the Routing rule that chose it, so the decision records what ran and why.`,screen: 'screen AGENT [--scrollback N]: read another agent\'s terminal in your project as plain text, with up to 200 lines of scrollback. Use it when an agent seems stuck.',type: 'type AGENT [TEXT] [--key K]...: type text, then keys (Enter, Esc, Tab, Up, Down, Left, Right, Ctrl-C, 0-9), into another agent\'s terminal in your project. Answer prompts within its task; ask the owner before approving anything risky.',capacity: 'capacity MACHINE_ID JSON: inspect machine, engine and quota headroom. JSON uses the start request fields below. Unknown allowances are not reported as free tokens.',@@ -493,8 +493,9 @@ export function superTabService(core: CoreApi, options: SuperTabServiceOptions =// `signInAgain`: Set up on a row the Swarm says has no Team account while this Mac has one, so it serves another account// (#3122). Only the person's own Set up: a check or an automatic moment signs nothing in again.const signInAgain = payload.action === 'teamSetup' && payload.reason === 'manual' && payload.signInAgain === true+ const restart = payload.action === 'teamSetup' && payload.reason === 'manual' && payload.restart === truereturn { ok: true, ...await (await setup()).offer(payload.reason as AutoSetupReason, () => sharedSwarm(sources()),- payload.action === 'teamSetupCheck', { signInAgain }) }+ payload.action === 'teamSetupCheck', { signInAgain, ...restart ? { restart: true } : {} }) }}if (payload.action === 'swarmRole') {const grant = await port.swarmRole(String(payload.harnessId ?? ''))diff --git a/cli/src/team/autoSetup.spec.ts b/cli/src/team/autoSetup.spec.tsindex 4580a2f60..9ec582aa1 100644--- a/cli/src/team/autoSetup.spec.ts+++ b/cli/src/team/autoSetup.spec.ts@@ -322,6 +322,16 @@ describe('a half-finished setup is repaired, not taken for done (#2765, Darren-Mexpect(quiet.deps.setup).not.toHaveBeenCalled()})+ it('restarts an existing account only on an explicit manual restart and preserves its sign-in', async () => {+ const f = fake({ accountExists: vi.fn(async () => true) })+ expect(await f.auto.offer('join', undefined, false, { restart: true })).toEqual({ state: 'exists' })+ expect(await f.auto.offer('manual', undefined, true, { restart: true })).toEqual({ state: 'wanted' })+ expect(f.deps.setup).not.toHaveBeenCalled()+ expect(await f.auto.offer('manual', undefined, false, { restart: true })).toEqual({ state: 'started' })+ await f.auto.settled()+ expect(f.deps.setup).toHaveBeenCalledWith(expect.any(Function))+ })+it('with every part in place it is done: exists, and nothing runs', async () => {const f = fake({ accountExists: vi.fn(async () => true), missing: async () => [] } as Partial<AutoSetupDeps>)expect(await f.auto.offer('manual')).toEqual({ state: 'exists' })diff --git a/cli/src/team/autoSetup.ts b/cli/src/team/autoSetup.tsindex ce3078504..39465bd8e 100644--- a/cli/src/team/autoSetup.ts+++ b/cli/src/team/autoSetup.ts@@ -118,15 +118,15 @@ export class TeamAutoSetup {* found it serving another account of this computer (#3122), which no part of it shows.*/async offer(reason: AutoSetupReason, sharedSwarm: () => Promise<boolean> = async () => false, check = false,- { signInAgain = false }: { signInAgain?: boolean } = {}): Promise<{ state: AutoSetupState }> {- const state = await this.decide(reason, sharedSwarm, check, signInAgain)+ { signInAgain = false, restart = false }: { signInAgain?: boolean; restart?: boolean } = {}): Promise<{ state: AutoSetupState }> {+ const state = await this.decide(reason, sharedSwarm, check, signInAgain, restart)// Every answer is said, not only a setup that starts: Macs in a Swarm went without the prompt and nothing on them said// why (2026-10-27). A check that finds it wanted starts nothing: that is Desktop's question, not an answer.if (state !== 'started' && state !== 'wanted') this.deps.log(`the Harness Team account was not offered (${reason}): ${state}`)return { state }}- private async decide(reason: AutoSetupReason, sharedSwarm: () => Promise<boolean>, check: boolean, signInAgain: boolean): Promise<AutoSetupState> {+ private async decide(reason: AutoSetupReason, sharedSwarm: () => Promise<boolean>, check: boolean, signInAgain: boolean, restart: boolean): Promise<AutoSetupState> {const { deps } = this// A Mac, a Linux and a Windows computer (docs/superpowers/plans/2026-10-28-harness-team-account-windows.md).if (!teamLayout(deps.platform)) return 'unsupported'@@ -137,7 +137,7 @@ export class TeamAutoSetup {if (deps.readConfig() || await deps.accountExists(TEAM_USER)) {// Done only when every part is there (#2765: an account with no daemon answered "already set up", and nothing// repaired it). A part missing is repaired only when the person asks (Set up): no password is asked for on its own.- const again = reason === 'manual' && signInAgain+ const again = reason === 'manual' && (signInAgain || restart)if (!(await this.missing()).length && !again) return 'exists'if (reason !== 'manual') return 'incomplete'} else if (reason !== 'manual') {diff --git a/cli/src/team/command.spec.ts b/cli/src/team/command.spec.tsindex ef83256ef..3cc96af67 100644--- a/cli/src/team/command.spec.ts+++ b/cli/src/team/command.spec.ts@@ -658,6 +658,41 @@ describe('internal verbs', () => {expect(broken.out.join('\n')).toContain('could not check the engines: no home')})+ it('__start replaces a historical sign-in success when no Team session remains', async () => {+ const f = inTeam()+ f.status.set(STATUS, { version: 1, signIn: { state: 'signed-in', at: 1 } })+ await teamCommand(['__start'], f.deps)+ expect(f.status.get(STATUS)?.signIn).toMatchObject({ state: 'signed-out', at: 1_000_000 })+ })++ it('__start pins the handed sign-in to its redeemed account', async () => {+ const f = inTeam()+ await teamCommand(['__start', '/Users/harnessteam/.harness/team-handoff'], f.deps)+ expect(f.session()?.signInAcct).toBe('user-placeholder-1')+ expect(f.deps.get).toHaveBeenCalledWith('/api/auth/me', {+ authorization: 'Bearer hna_team', 'x-autonomous-env': 'prod',+ })+ })++ it('__start does not pin a replacement sign-in when the account lookup returns late', async () => {+ const f = inTeam()+ f.deps.get = vi.fn(async () => {+ f.setSession({ ...computer, signInEpoch: 'replacement@1000001' })+ return { user: { id: 'previous-owner' } }+ }) as never+ await teamCommand(['__start', '/Users/harnessteam/.harness/team-handoff'], f.deps)+ expect(f.session()?.signInEpoch).toBe('replacement@1000001')+ expect(f.session()?.signInAcct).toBeUndefined()+ })++ it('__start keeps a redeemed sign-in and reports an account lookup failure', async () => {+ const f = inTeam({ get: vi.fn(async () => { throw new Error('offline') }) as never })+ await teamCommand(['__start', '/Users/harnessteam/.harness/team-handoff'], f.deps)+ expect(f.session()).toMatchObject({ kind: 'team', refreshToken: 'hnr_team' })+ expect(f.out.join('\n')).toContain('could not record the signed-in account')+ expect(f.status.get(STATUS)?.signIn?.state).toBe('signed-in')+ })+// Task #3262 (Amon, 11-05): Repair handed his Harness Team account to him, but the sign-in it made was adopted, so its device// key log stayed kelvin's and froze, and it refused his daemon. A sign-in from the handoff file is the owner's own setup run,// behind the macOS password: made by hand, at this run, so the log may start over for the account it was handed to.diff --git a/cli/src/team/command.ts b/cli/src/team/command.tsindex 81b8fb23a..c3a489b91 100644--- a/cli/src/team/command.ts+++ b/cli/src/team/command.ts@@ -796,6 +796,9 @@ async function jobStart(deps: TeamCommandDeps, file: string | undefined): Promistry { deps.writeStatus(statusFile, update) } catch (error) { log(`could not write ${statusFile}: ${(error as Error).message}`) }}const label = `${deps.hostname().slice(0, 60)} · Team`+ if (mine && deps.session()?.kind !== 'team') {+ report({ signIn: { state: 'signed-out', at: deps.now(), detail: 'The Team sign-in is no longer available. Run harness team setup --sign-in-again.' } })+ }if (file) {let code: string | null = nulltry {@@ -813,7 +816,20 @@ async function jobStart(deps: TeamCommandDeps, file: string | undefined): Promisconst computerId = deps.computerId()const tokens = await redeemTeamHandoff(code, label, computerId, { post: deps.post, sleep: deps.sleep, now: deps.now })// The owner's setup run handed it over: a sign-in by hand, so the device key log may start over for its account (#3262).- deps.writeSession(teamSession(tokens, computerId, deps.autonomousEnv, deps.now(), { signInEpoch: handedTeamSignInEpoch(deps.now()) }))+ const handed = teamSession(tokens, computerId, deps.autonomousEnv, deps.now(), { signInEpoch: handedTeamSignInEpoch(deps.now()) })+ deps.writeSession(handed)+ // Pin the account while this is still the handed sign-in. The first device-log read may happen much later.+ try {+ const me = await deps.get<{ user?: { id?: unknown } }>('/api/auth/me', {+ authorization: `Bearer ${handed.accessToken}`, 'x-autonomous-env': handed.autonomousEnv,+ })+ const acct = me?.user?.id+ if (typeof acct !== 'string' || !acct) throw new Error('no account')+ await deps.updateSession((latest) => latest.signInEpoch === handed.signInEpoch+ ? { ...latest, signInAcct: acct } : null)+ } catch {+ log('could not record the signed-in account; trust recovery requires a connection within ten minutes')+ }if (previous) await revokeHarnessRefresh(deps.post, previous.refreshToken)log(previous ? 'signed in for team work again; the previous sign-in was ended' : 'signed in for team work')report({ signIn: { state: 'signed-in', at: deps.now() } })diff --git a/cli/src/team/privacy.spec.ts b/cli/src/team/privacy.spec.tsindex a13a43c48..68842097f 100644--- a/cli/src/team/privacy.spec.ts+++ b/cli/src/team/privacy.spec.ts@@ -242,6 +242,22 @@ describe('privacy observer', () => {return { o, check, writeStatus, step: (ms: number) => { now += ms } }}+ it('reports when the Team daemon loses its sign-in instead of retaining historical success', () => {+ let signedIn = true+ const writeStatus = vi.fn()+ const o = new TeamPrivacyObserver({ config: () => teamConfig, user: () => 'harnessteam',+ teamSession: () => signedIn, check: () => ({ passed: true, checkedAt: 7 }), writeStatus, now: () => 7 })+ o.observe()+ signedIn = false+ o.observe()+ expect(writeStatus).toHaveBeenCalledWith(teamConfig.statusFile, {+ signIn: { state: 'signed-out', at: 7, detail: 'The Team sign-in is no longer available. Run harness team setup --sign-in-again.' },+ })+ const calls = writeStatus.mock.calls.length+ o.observe()+ expect(writeStatus).toHaveBeenCalledTimes(calls)+ })+it('checks in the team account, at most every five minutes, and reports it for the owner', () => {const f = observer()expect(f.o.observe()).toEqual({ mode: 'account', passed: true, checkedAt: 1_000 })@@ -280,7 +296,8 @@ describe('privacy observer', () => {const o = new TeamPrivacyObserver({ config: () => ({ ...teamConfig, statusFile: file }), user: () => 'harnessteam', teamSession: () => false,check: () => ({ passed: true, checkedAt: 7 }), writeStatus: writeTeamStatus, now: () => 7 })o.observe()- expect(JSON.parse(readFileSync(file, 'utf8'))).toEqual({ version: 1, privacy: { passed: true, checkedAt: 7 } })+ expect(JSON.parse(readFileSync(file, 'utf8'))).toEqual({ version: 1, privacy: { passed: true, checkedAt: 7 },+ signIn: { state: 'signed-out', at: 7, detail: 'The Team sign-in is no longer available. Run harness team setup --sign-in-again.' } })})})diff --git a/cli/src/team/privacy.ts b/cli/src/team/privacy.tsindex 2426f9653..9e98b0504 100644--- a/cli/src/team/privacy.ts+++ b/cli/src/team/privacy.ts@@ -327,6 +327,7 @@ export interface PrivacyObserverDeps {export class TeamPrivacyObserver {private last: PrivacyResult | null = null+ private signedIn: boolean | null = nullconstructor(private readonly deps: PrivacyObserverDeps) {}/** This daemon runs in the Harness Team account that setup made. */@@ -339,6 +340,16 @@ export class TeamPrivacyObserver {const config = this.inTeamAccount()if (config) {const now = this.deps.now()+ const signedIn = this.deps.teamSession()+ if (signedIn !== this.signedIn) {+ if (!signedIn) {+ try {+ this.deps.writeStatus(config.statusFile, { signIn: { state: 'signed-out', at: now,+ detail: 'The Team sign-in is no longer available. Run harness team setup --sign-in-again.' } })+ this.signedIn = signedIn+ } catch { /* Try the status write again at the next observation; privacy is checked independently. */ }+ } else this.signedIn = signedIn+ }if (!this.last || now - this.last.checkedAt >= PRIVACY_RECHECK_MS || now < this.last.checkedAt) {try {this.last = this.deps.check(config)diff --git a/cli/src/team/refresh.spec.ts b/cli/src/team/refresh.spec.tsindex d781b143b..fbd83063f 100644--- a/cli/src/team/refresh.spec.ts+++ b/cli/src/team/refresh.spec.ts@@ -1,12 +1,14 @@-import { mkdtempSync, rmSync } from 'node:fs'+import { spawn } from 'node:child_process'+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'import { tmpdir } from 'node:os'import { join } from 'node:path'import { afterEach, describe, expect, it, vi } from 'vitest'+import { ownProcessGroup } from '../lib/windows/noWindow.js'import { validCreationId } from '../lib/agentCreationReceipt.js'import type { TeamConfig } from './config.js'import type { TeamStatus } from './privacy.js'import {- readLastTry, refreshCreationId, refreshTeamAccount, TEAM_REFRESH_RETRY_MS, teamBuildStale, writeLastTry, type TeamRefreshDeps,+ readLastTry, refreshCreationId, refreshTeamAccount, TEAM_REFRESH_RETRY_MS, teamBuildStale, teamUpdateArgv, writeLastTry, type TeamRefreshDeps,} from './refresh.js'const config = { node: '/Users/harnessteam/.harness/runtime/node/bin/node', cli: '/Users/harnessteam/.harness/cli/cli.js',@@ -19,7 +21,7 @@ afterEach(() => { for (const dir of cleanup.splice(0)) rmSync(dir, { recursive:function deps(over: Partial<TeamRefreshDeps> = {}) {let last: number | null = nullconst d: TeamRefreshDeps = {- config: () => config, status: () => signedOut(2_000), publishedAt: () => 1_000,+ platform: 'darwin', config: () => config, status: () => signedOut(2_000), publishedAt: () => 1_000,machines: async () => [{ machineId: 'mac', sessionKind: 'computer' }, { machineId: 'team', sessionKind: 'team', hostMachineId: 'mac' },{ machineId: 'other-team', sessionKind: 'team', hostMachineId: 'other' }],machineId: () => 'mac', run: vi.fn(async () => ({ ok: true })), lastTry: () => last, remember: vi.fn((at: number) => { last = at }),@@ -46,7 +48,7 @@ describe('a Harness Team account on a build too old for its owner\'s subscriptioit('is updated by its owner\'s daemon, as itself, over the link to its own machine; once a day', async () => {const d = deps()await refreshTeamAccount(d)- expect(d.run).toHaveBeenCalledWith('team', [config.node, config.cli, 'update', '--force'], '/Users/harnessteam')+ expect(d.run).toHaveBeenCalledWith('team', teamUpdateArgv(config, 'darwin'), '/Users/harnessteam')expect(d.remember).toHaveBeenCalledWith(5_000)expect(d.log).toHaveBeenCalledWith(expect.stringContaining('updating it'))await refreshTeamAccount(d)@@ -110,3 +112,31 @@ it('waits for a status read that happens off the main thread (audit W4)', asyncawait refreshTeamAccount(deps({ status: async () => { await new Promise((r) => setTimeout(r, 5)); return signedOut(2_000) }, lastTry: look }))expect(look).toHaveBeenCalled()})++// A shell hosted by the Team daemon is ended when update stops that daemon. The updater must finish outside that group.+it.skipIf(process.platform === 'win32')('finishes a simulated update after its hosting daemon process group closes', async () => {+ const dir = mkdtempSync(join(tmpdir(), 'team-update-survival-'))+ cleanup.push(dir)+ mkdirSync(join(dir, '.harness', 'cli', 'data'), { recursive: true })+ const cli = join(dir, 'fake-cli.cjs')+ writeFileSync(cli, `const fs = require('node:fs');+const root = process.env.TEAM_TEST_ROOT;+const finish = () => { if (!fs.existsSync(root + '/release')) return; fs.writeFileSync(root + '/daemon-running', 'new version'); watch.close(); };+const watch = fs.watch(root, finish);+fs.writeFileSync(root + '/ready', String(process.pid));+finish();`)+ const argv = teamUpdateArgv({ node: process.execPath, cli, home: dir }, 'darwin')+ const host = spawn(argv[0]!, argv.slice(1), { ...ownProcessGroup(), stdio: 'ignore', env: { ...process.env, TEAM_TEST_ROOT: dir } })+ let updater: number | null = null+ try {+ await vi.waitFor(() => expect(existsSync(join(dir, 'ready'))).toBe(true), { timeout: 5000 })+ updater = Number(readFileSync(join(dir, 'ready'), 'utf8'))+ try { process.kill(-host.pid!, 'SIGTERM') } catch (error) { if ((error as NodeJS.ErrnoException).code !== 'ESRCH') throw error }+ writeFileSync(join(dir, 'release'), '')+ await vi.waitFor(() => expect(existsSync(join(dir, 'daemon-running'))).toBe(true), { timeout: 2000 })+ expect(readFileSync(join(dir, 'daemon-running'), 'utf8')).toBe('new version')+ } finally {+ host.kill('SIGKILL')+ if (updater !== null) { try { process.kill(updater, 'SIGKILL') } catch { /* already finished */ } }+ }+})diff --git a/cli/src/team/refresh.ts b/cli/src/team/refresh.tsindex d645c9c5b..845448547 100644--- a/cli/src/team/refresh.ts+++ b/cli/src/team/refresh.ts@@ -20,7 +20,8 @@ import { dirname, join } from 'node:path'import type { TeamConfig } from './config.js'import type { TeamStatus } from './privacy.js'import { TEAM_ENGINES } from './engines.js'-import { checkWindowsPath } from './layout.js'+import { checkWindowsPath, teamPaths } from './layout.js'+import { ownProcessGroup } from '../lib/windows/noWindow.js'import { windowsTeamPaths } from './windowsLayout.js'/** How long after one try the owner's daemon may try again. */@@ -61,6 +62,18 @@ export function teamBuildStale(status: TeamStatus | null, publishedAt: number |* into the very line cmd.exe parses (it quotes only a word that needs it).*/export function teamUpdateArgv(config: Pick<TeamConfig, 'node' | 'cli' | 'home'>, platform: NodeJS.Platform): string[] {+ if (platform === 'darwin') {+ // The shell belongs to the daemon update stops. Start outside its process group before acknowledging the request.+ // Inline Node also works on the old Team builds this refresh exists to repair: they have no new internal command.+ const script = `const fs = require('node:fs');+const fd = fs.openSync(process.argv[3], 'a', 0o600);+const child = require('node:child_process').spawn(process.argv[1], [process.argv[2], 'update', '--force'], {+ ...${JSON.stringify(ownProcessGroup('darwin'))}, stdio: ['ignore', fd, fd], env: process.env+});+child.once('spawn', () => { fs.closeSync(fd); child.unref(); });+child.once('error', () => { fs.closeSync(fd); console.error('The Team updater could not start; see harness team logs.'); process.exitCode = 1; });`+ return [config.node, '-e', script, config.node, config.cli, teamPaths(config.home).log]+ }if (platform !== 'win32') return [config.node, config.cli, 'update', '--force']const cli = windowsTeamPaths(checkWindowsPath(config.home, 'team home')).cliconst node = checkWindowsPath(config.node, 'team Node')diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dartindex 578687465..77e57577f 100644--- a/desktop/lib/state/app_state.dart+++ b/desktop/lib/state/app_state.dart@@ -2638,7 +2638,10 @@ class AppNotifier extends ChangeNotifier {/// to set it up from here. With [signInAgain], an account already here is/// signed in again for this account: the Swarm found it serving another/// account of this computer (#3122).- Future<String> setUpTeamAccount({bool signInAgain = false}) async {+ Future<String> setUpTeamAccount({+ bool signInAgain = false,+ bool restart = false,+ }) async {final here = _teamAccountHere();if (here == null) return 'unsupported';try {@@ -2646,6 +2649,7 @@ class AppNotifier extends ChangeNotifier {'action': 'teamSetup','reason': 'manual',if (signInAgain) 'signInAgain': true,+ if (restart) 'restart': true,});return answer['state']?.toString() ?? 'started';} on SuperTabFailure catch (failure) {diff --git a/desktop/lib/super_tabs/machines.dart b/desktop/lib/super_tabs/machines.dartindex f5bab0f61..c32a2064b 100644--- a/desktop/lib/super_tabs/machines.dart+++ b/desktop/lib/super_tabs/machines.dart@@ -1574,6 +1574,15 @@ class _SuperTabMachinesState extends State<SuperTabMachines> {}}final line = _teammatesLine(shared, team, contributor);+ final restartTeam =+ team != null &&+ (team['teamWork'] as Map?)?['code'] == 'MACHINE_OFFLINE' &&+ contributor == c.accountId &&+ app != null &&+ app.canSetUpTeamAccount &&+ app.stateOf(id)?.isLocalMachine == true &&+ (status == SuperTabMachineStatus.live ||+ status == SuperTabMachineStatus.late);final setUpTeam =line != null &&team == null &&@@ -1598,7 +1607,7 @@ class _SuperTabMachinesState extends State<SuperTabMachines> {// While setup runs, its step and the time left, and that the person may// go on working (#3169); otherwise its own person reads why: they// cancelled, or setup failed and why.- final progress = setUpTeam ? _setupWatch?.line : null;+ final progress = (setUpTeam || restartTeam) ? _setupWatch?.line : null;final problem = progress != null? '$progress\nKeep working. We\'ll tell you when it\'s ready.': setUpTeam@@ -1612,10 +1621,13 @@ class _SuperTabMachinesState extends State<SuperTabMachines> {problem: problem,history: superTabMachineHistory(shared, snapshot.people),// Set up would ask for the password again while one setup runs.- setUpTeam: (setUpTeam && progress == null) || joinLine != null,+ setUpTeam:+ ((setUpTeam || restartTeam) && progress == null) || joinLine != null,retryJoin: joinLine != null,setUpTeamLabel: joinLine != null? 'Retry'+ : restartTeam+ ? 'Restart': superTabTeamSetupAction(_teamSetup),owner: person,contributor: contributor,@@ -2276,10 +2288,15 @@ class _SuperTabMachinesState extends State<SuperTabMachines> {await showTeamAccountSetup(context,widget.app!,- missing: _teamSetup?.state == 'incomplete'+ restart: view.setUpTeamLabel == 'Restart',+ missing: view.setUpTeamLabel == 'Restart'+ ? 'Harness Team account offline'+ : _teamSetup?.state == 'incomplete'? _teamSetup?.detail ?? '': null,- signInAgain: _teamSetup?.state == 'exists',+ signInAgain:+ view.setUpTeamLabel != 'Restart' &&+ _teamSetup?.state == 'exists',);await _readTeamSetup();}diff --git a/desktop/lib/super_tabs/project_sidebar.dart b/desktop/lib/super_tabs/project_sidebar.dartindex 54cec3aff..3e9889157 100644--- a/desktop/lib/super_tabs/project_sidebar.dart+++ b/desktop/lib/super_tabs/project_sidebar.dart@@ -654,7 +654,7 @@ class ProjectSidebar extends StatelessWidget {) {final hidden = superTabHiddenProjects(controller, app: app);return [- for (final project in snapshot?.projects ?? const <SuperTabProject>[])+ for (final project in ([...?snapshot?.projects]..sort(_compareProjects)))if (reading.of(project) case final readwhen read.lead != null &&(!controller.unreadOnly || _hasUnread(read)) &&@@ -667,7 +667,7 @@ class ProjectSidebar extends StatelessWidget {children: [_row(read.lead!, reading: read)],),),- ]..sort((a, b) => a.$1.toLowerCase().compareTo(b.$1.toLowerCase()));+ ];}// The sidebar's ink scope (#3006): a theme's own sidebar ink reaches the@@ -946,6 +946,14 @@ class _ProjectReading {};}+String _projectSortName(String name) =>+ (name.startsWith('#') ? name.substring(1).trimLeft() : name).toLowerCase();++int _compareProjects(SuperTabProject a, SuperTabProject b) {+ final byName = _projectSortName(a.name).compareTo(_projectSortName(b.name));+ return byName != 0 ? byName : a.id.compareTo(b.id);+}+/// The chats in the order the sidebar lists them, for Option+Shift+Down and/// Up (Slack's next unread): the reader's one Buddy chat (`# buddy`, first/// under Projects), each project's chat from A to Z, then the reader's@@ -959,8 +967,7 @@ List<String> superTabSidebarOrder(}) {final snapshot = controller.snapshot;if (snapshot == null) return const [];- final projects = [...snapshot.projects]- ..sort((a, b) => a.name.toLowerCase().compareTo(b.name.toLowerCase()));+ final projects = [...snapshot.projects]..sort(_compareProjects);final hidden = superTabHiddenProjects(controller, app: app);return [if (controller.oneBuddy)diff --git a/desktop/lib/super_tabs/team_account_setup.dart b/desktop/lib/super_tabs/team_account_setup.dartindex 7a79677e5..5fa916e7a 100644--- a/desktop/lib/super_tabs/team_account_setup.dart+++ b/desktop/lib/super_tabs/team_account_setup.dart@@ -23,6 +23,7 @@ Future<void> showTeamAccountSetup(String? operatingSystem,String? missing,bool signInAgain = false,+ bool restart = false,}) => showAppDialog<void>(context: context,barrierDismissible: false,@@ -31,6 +32,7 @@ Future<void> showTeamAccountSetup(asked: asked,missing: signInAgain ? 'it is signed in for another account' : missing,signInAgain: signInAgain,+ restart: restart,words: _Words.of(operatingSystem ?? RuntimePlatform.operatingSystem),),);@@ -240,6 +242,7 @@ class _TeamAccountSetup extends StatefulWidget {required this.words,this.missing,this.signInAgain = false,+ this.restart = false,});final AppNotifier app;@@ -248,6 +251,7 @@ class _TeamAccountSetup extends StatefulWidget {/// The account is there, signed in for another account of this computer (#3122): Repair signs it in for this one.final bool signInAgain;+ final bool restart;/// The account is there and these parts are not (cli/src/team/autoSetup.ts `missingDetail`, #2765): the dialog/// repairs instead of setting up. Empty for a part it could not name.@@ -270,6 +274,7 @@ class _TeamAccountSetupState extends State<_TeamAccountSetup> {try {final state = await widget.app.setUpTeamAccount(signInAgain: widget.signInAgain,+ restart: widget.restart,);// The row and the notice follow it from here (#3169): the dialog's OK// leaves the person free while it runs.diff --git a/desktop/test/super_tab_sidebar_test.dart b/desktop/test/super_tab_sidebar_test.dartindex b37457583..bef1c1d8e 100644--- a/desktop/test/super_tab_sidebar_test.dart+++ b/desktop/test/super_tab_sidebar_test.dart@@ -345,6 +345,44 @@ void main() {);}+ testWidgets('project A to Z ignores # and stays fixed after new activity', (+ tester,+ ) async {+ addTearDown(() => tester.binding.setSurfaceSize(null));+ final app = createApp(connected: true);+ addTearDown(app.dispose);+ final server = ConversationServer();+ final controller = await projectSidebar(server);+ server.state['projects'] = [+ projectFixture('lead', '# Zebra', 'lead'),+ projectFixture('empty', 'alpha', 'empty-lead'),+ ];+ await controller.refresh();+ await pumpSidebar(tester, controller, app);+ for (final updated in [false, true]) {+ if (updated) {+ final lead = (server.state['conversations'] as List)+ .cast<Map<String, dynamic>>()+ .firstWhere((c) => c['id'] == 'lead');+ lead['lastMessageSequence'] = 99;+ lead['changedAt'] = DateTime.utc(2030).millisecondsSinceEpoch;+ await controller.refresh();+ await tester.pumpAndSettle();+ }+ expect(+ tester.getTopLeft(find.byKey(const ValueKey('super-project-empty'))).dy,+ lessThan(+ tester+ .getTopLeft(find.byKey(const ValueKey('super-project-lead')))+ .dy,+ ),+ );+ expect(superTabSidebarOrder(controller).take(2), ['empty-lead', 'lead']);+ }+ expect(tester.takeException(), isNull);+ await disposeSidebar(tester, controller);+ });+testWidgets('reads like a chat app: Activity, Projects A to Z, Buddies, ''then Manage; no # product-managers, no tasks', (tester) async {addTearDown(() => tester.binding.setSurfaceSize(null));diff --git a/desktop/test/super_tab_team_machine_test.dart b/desktop/test/super_tab_team_machine_test.dartindex c55012712..0d2d4e8a6 100644--- a/desktop/test/super_tab_team_machine_test.dart+++ b/desktop/test/super_tab_team_machine_test.dart@@ -2,11 +2,15 @@// second contribution, its pool naming the Mac as `hostMachineId`, and the Swarm shows the Mac alone. Its agents read as// on the Mac; teammates read the account's availability, which runs while the owner is away from the Mac; the only new// words are one line when teammates' agents cannot run there.+import 'dart:io';+import 'package:flutter/material.dart';import 'package:flutter_test/flutter_test.dart';import 'package:harness/super_tabs/agent_details.dart';+import 'package:harness/shared/theme/app_theme.dart' as grid;import 'package:harness/super_tabs/machines.dart';+import 'support/capture.dart';import 'support/rename_connection.dart';import 'support/super_tab_fixture.dart';import 'swarm_state_test.dart' show createApp;@@ -25,6 +29,10 @@ class _TeamDaemon extends RenameConnection {Map<String, dynamic> payload = const {},Duration timeout = const Duration(seconds: 20),}) {+ if (type == 'super_tabs' && payload['action'] == 'teamSetup') {+ asked.add(Map.of(payload));+ return Future.value({'ok': true, 'state': 'exists'});+ }if (type == 'super_tabs' && payload['action'] == 'teamSetupStatus') {asked.add(Map.of(payload));return Future.value(status);@@ -114,6 +122,7 @@ String? _problemText(WidgetTester tester, String id) =>tester.widget<Text>(_problem(id)).data;void main() {+ setUpAll(() => loadCaptureFonts(Platform.environment['TEAM_RESTART_SHOTS']));testWidgets('a Mac and its Harness Team account are one row, with every agent of both under it',(tester) async {@@ -323,6 +332,90 @@ void main() {},);+ testWidgets(+ 'an offline Team account offers its local owner Restart through the standard setup flow',+ (tester) async {+ final shots = Platform.environment['TEAM_RESTART_SHOTS'];+ final previousBrightness = grid.AppTheme.brightness.value;+ addTearDown(() => grid.AppTheme.brightness.value = previousBrightness);+ final daemon = _TeamDaemon()..status = {'ok': true, 'state': 'exists'};+ final app = createApp(connectionForTest: (_) => daemon, connected: true)+ ..teamAccountHereForTest = true;+ app.machineStates['m']!.localOnly = true;+ Future<void> mount({+ String account = 'owner',+ String id = 'm',+ bool hostOffline = false,+ Brightness brightness = Brightness.light,+ }) async {+ grid.AppTheme.brightness.value = brightness;+ final server = _swarm();+ server.state['machines'] = [+ _pool(id, contributor: 'owner', age: hostOffline ? _offlineAge : 0),+ _pool(+ '$id-team',+ contributor: 'owner',+ host: id,+ age: _offlineAge,+ teamWork: _refused('MACHINE_OFFLINE'),+ ),+ ];+ final c = server.controller(account: account);+ await c.refresh();+ await tester.pumpWidget(+ MaterialApp(+ debugShowCheckedModeBanner: false,+ theme: grid.buildAppTheme(brightness: brightness),+ home: Scaffold(+ body: SuperTabMachines(+ controller: c,+ app: app,+ onAddAgent: (_) {},+ ),+ ),+ ),+ );+ await tester.pumpAndSettle();+ final button = find.byKey(ValueKey('super-machine-team-setup-$id'));+ if (account == 'owner' && id == 'm' && !hostOffline) {+ expect(+ _problemText(tester, id),+ "Teammates' agents paused: Harness Team account offline",+ );+ expect(+ find.descendant(of: button, matching: find.text('Restart')),+ findsOneWidget,+ );+ expect(tester.widget(button), isA<OutlinedButton>());+ await captureWindow(tester, shots, 'team-offline-${brightness.name}');+ await tester.tap(button);+ await tester.pumpAndSettle();+ await tester.tap(+ find.byKey(const Key('team-account-setup-continue')),+ );+ await tester.pumpAndSettle();+ expect(daemon.asked.where((a) => a['action'] == 'teamSetup').last, {+ 'action': 'teamSetup',+ 'reason': 'manual',+ 'restart': true,+ });+ await tester.tap(find.byKey(const Key('team-account-setup-done')));+ await tester.pumpAndSettle();+ } else {+ expect(button, findsNothing);+ }+ await _unmount(tester, c);+ }++ await mount();+ await mount(brightness: Brightness.dark);+ await mount(account: 'peer');+ await mount(id: 'remote');+ await mount(hostOffline: true);+ app.dispose();+ },+ );+// Scholes, 2026-10-29: a Mac whose person cancelled the password prompt, or whose setup failed, said only "not set up".testWidgets('this Mac\'s row says why it has no Harness Team account, for its person alone, with Set up to try again',diff --git a/desktop/test/team_account_offer_test.dart b/desktop/test/team_account_offer_test.dartindex a67c23247..7079ef4e3 100644--- a/desktop/test/team_account_offer_test.dart+++ b/desktop/test/team_account_offer_test.dart@@ -204,6 +204,14 @@ void main() {},);+ test('restarts Team through manual setup without replacing its sign-in', () async {+ daemon.answer = {'ok': true, 'state': 'started'};+ expect(await app.setUpTeamAccount(restart: true), 'started');+ expect(daemon.asked, [+ {'action': 'teamSetup', 'reason': 'manual', 'restart': true},+ ]);+ });+test('sets it up when the person asks, and remembers "Not now"', () async {daemon.answer = {'ok': true, 'state': 'started'};expect(await app.setUpTeamAccount(), 'started');diff --git a/docs/design/2026-11-03-swarm-slack-redesign.md b/docs/design/2026-11-03-swarm-slack-redesign.mdindex e336d9888..64c7cd4f6 100644--- a/docs/design/2026-11-03-swarm-slack-redesign.md+++ b/docs/design/2026-11-03-swarm-slack-redesign.md@@ -20,7 +20,7 @@ Slack reports that people open its mobile apps 15–20 times a day, for 20–30| Five tabs cut to three, still labelled (label-less tabs hurt accessibility and comprehension) | Four labelled tabs: Home · Buddy · Activity · You | Three labelled tabs: Home · Buddy · Activity. You moves to an avatar || A bar of tiles for unreads and secondary surfaces | Two large cards: While you were away, Threads | One tile bar: While you were away · Threads · Agents || Filters in each tab, as a bottom sheet on Android, not an overflow menu | Home has a Sort and filter sheet | The same sheet, now also holding Mark all read and Refresh |-| Pull down to open search, swipe sideways to change kind | No search in Swarm. Find lives only in the terminal | A Search button on Home's top bar plus a pull down at its top. Chips or a sideways swipe change the kind |+| Pull down to open search, swipe sideways to change kind | No search in Swarm. Find lives only in the terminal | A Search button on Home's top bar. Chips or a sideways swipe change the kind. Pulling down on Home refreshes it (D5, updated 2026-11-05) || One feed for threads, mentions, alerts, invitations | What needs you is in 6 places. Invitations sit on Home | Activity opens on All. Invitations head All and Needs you and count on the tab's badge || The header shrinks as you scroll | Fixed header | Built, then dropped with the Search field (D10) || Less-used surfaces move to familiar places | Harness is reachable only through 4 "Open terminal" menu items | An Agents tile, and Agents in Search |@@ -45,7 +45,7 @@ Paths are relative to `mobile/lib/`.| Idea | Arrange Swarm as Slack does: tiles, one-line rows, Search, one Activity feed | Merge Home and Activity into one urgency-sorted inbox | Keep the structure, fix density only || Tabs | Home · Buddy · Activity, You on the avatar | Inbox · Projects · Buddy | Home · Buddy · Activity · You || Strongest point | Fixes all five problems with little to learn | Approve is one tap from opening the app | Lowest risk |-| Cost | You is one tap further. Two earlier decisions are reversed. Home loses pull-to-refresh | Far from Slack. The list reorders under your finger. The most work | Four tabs stay, Harness stays hidden |+| Cost | You is one tap further. Two earlier decisions are reversed | Far from Slack. The list reorders under your finger. The most work | Four tabs stay, Harness stays hidden |**Why not B.** Slack keeps places (Home) apart from work (Activity). Merging them gives a list that grows with every task and keeps reordering itself.@@ -92,20 +92,21 @@ Each decision lists what was chosen, the alternatives, the reasoning, the cost,- **No state dot** (Tony, 2026-11-03): an idle team's grey dot sat on nearly every row and said nothing, so the dot went first for idle teams and then altogether. A tag or decision waiting on the person still makes the name bold and adds `@N`; who works, waits or is down is on the project's page, in Activity and on the Agents tile. Home no longer counts a team per row, and its loading rows draw the name's bar alone.- **Phase 2:** the unread rule. Agents post constantly, so almost every row ends up bold. The proposal is that only people's messages, tags of the person and items that need them make a row bold. That has to change together with desktop `_hasUnread`.-### D5. Search from the top bar, plus a pull down to open it+### D5. Search from the top bar; pull down to refresh Home- **Alternatives:** a Search tab (old Slack); a magnifier only; the pull only (new Slack); the terminal's Find.-- **Why:** Slack removed the overlap between "Jump to" and a Search tab. Swarm had no search at all. A visible field is easy to find, and the pull is a shortcut for those who know it. The field folds on scroll, so it costs nothing while browsing.-- **Cost:** Home loses pull-to-refresh. Swarm already polls, so Refresh moves into the filter sheet (D9).-- **Changed after review** (Tony, 2026-11-03): the field under the top bar is gone. Search is a magnifier on the top bar, before the avatar, where Sort and filter was; it opens the same Search page. The pull stays.-- **Built** (`swarm/swarm_home_search.dart`, `swarm/swarm_search_page.dart`):+- **Why:** Slack removed the overlap between "Jump to" and a Search tab. Swarm had no search at all. A visible Search button makes it easy to find without taking space from Home's list. People expect a pull down on Home to refresh it.+- **Cost:** Search takes a tap on the top bar; it has no pull shortcut. Refresh is available both by pulling and in Sort and filter (D9).+- **Changed after review** (Tony, 2026-11-03): the field under the top bar is gone. Search is a magnifier on the top bar, before the avatar, where Sort and filter was; it opens the same Search page.+- **Updated** (Tony, 2026-11-05, [#3176](https://github.com/autonomous-ai/openharness/pull/3176)): pulling down refreshes Home again. The earlier pull-to-search behavior looked like a broken refresh, so it was removed.+- **Built** (`swarm/swarm_page.dart`, `swarm/swarm_search_page.dart`):- Chips: **Recent · Projects · Chats · Agents**. People are left out: a person has no page of their own in Swarm yet. Agents shows only when the app's computers can list them.- Recent lists what moved last, at most 12. While something is typed, the Recent chip reads All and lists every kind.- Matching ignores case and accents, as New message's To: does (`swarmSearchFold`). Ranking: the title starts with the text (a leading # is optional), then a word in it does, then the title holds it, then its Swarm or computer does. The prototype said to reuse Find's ranking, but Find ranks machines and agents for the terminal, and the To: field is the matching people already know in Swarm.- Projects are those the person reads; a private project someone else owns stays out unless they are on it. Chats are the person's own Buddy chats, never another person's or an archived one.- A row opens its project, chat or agent over Search, and back returns to Search as it was left.- While the Swarms are read it shows a skeleton, never "nothing". A Swarm that could not be read is said above what the others have.- - The pull counts only a drag that began with the list at its top and went past 72pt, on Android (clamping) and iOS (bouncing) alike. A hint says "Pull to search", then "Release to search", with a haptic at the threshold.+ - Pulling down at the top of Home shows the refresh indicator and reads the Swarms again, on Android and iOS. With no computer answering, it rechecks the computers first; a failed recheck is logged and the Swarms are still read. This uses the same refresh path as Sort and filter, including when Home is pushed over another page, and opens no Search page.- The chips scroll sideways on a narrow phone, as Activity's pills do. A chip opened by a swipe of the pages scrolls into sight.- A drag on the results puts the keyboard away, a short list included.- **Phase 2:** searching message content needs a backend API.@@ -149,7 +150,7 @@ Each decision lists what was chosen, the alternatives, the reasoning, the cost,- **Why:** the app already has the sheet (`swarm/swarm_home_view_sheet.dart`), and the header drops to two controls, which suits Dee's preference for a minimal UI.- **Where:** at the right of the projects' first caption (Projects, or Pinned when a project is pinned), not on the top bar (Tony, 2026-11-03): it sorts and filters the projects, so it sits over them, and the top bar keeps Search and the avatar. A Home pushed over another page has none, as before.- **Cost:** Mark all read is one tap further. Its Undo toast stays.-- **Built:** both close the sheet, then act. Mark all read is greyed when nothing is unread. Refresh does what the pull did (recheck the computers when there are none, then read every Swarm) and says "Refreshing…".+- **Built:** both close the sheet, then act. Mark all read is greyed when nothing is unread. Refresh does what the pull does (recheck the computers when none answers, then read every Swarm) and says "Refreshing…".### D10. The header folds on scroll@@ -174,7 +175,7 @@ The New message button (2026-10-30), the composer (approved 2026-11-01), labelle1. Direction A.2. Drop the You tab and the Threads row on Home: yes.-3. Pull down to search in place of pull to refresh, with Refresh in the filter sheet: yes.+3. The initial pull-to-search choice was superseded on 2026-11-05: a pull refreshes Home, Search stays on the top bar, and Refresh stays in the filter sheet (D5).4. "@" becomes "Mentions" on the phone only. Desktop does not change.5. Built in a worktree from `feat/mobile-ios-android`, with this spec and the prototype in the same commit.@@ -182,9 +183,10 @@ The New message button (2026-10-30), the composer (approved 2026-11-01), labelleAll under `mobile/lib/swarm/`.-- **New:** `swarm_agents.dart`, `swarm_home_tiles.dart`, `swarm_home_search.dart`, `swarm_search_page.dart`, `swarm_project_details.dart`.+- **New:** `swarm_agents.dart`, `swarm_home_tiles.dart`, `swarm_search_page.dart`, `swarm_project_details.dart`.- **Changed:** `swarm_tabs.dart`, `swarm_you_page.dart`, `swarm_page.dart`, `swarm_home_rows.dart`, `swarm_home_top.dart`, `swarm_home_view_sheet.dart`, `swarm_activity.dart`, `swarm_activity_page.dart`, `swarm_computers.dart`, `swarm_project_page.dart`, `swarm_conversation_page.dart`, `swarm_style.dart`, `swarm_threads_page.dart`.- **Removed:** `SwarmAwayCard` and `SwarmThreadsRow`, replaced by tiles, and the You tab.+- **Removed on 2026-11-05:** `swarm_home_search.dart` and its pull-to-search widget; Home uses `RefreshIndicator` instead.## 9. Tests@@ -193,7 +195,8 @@ Widget and unit tests under `mobile/test/swarm/`. Run with `cd mobile && flutter- **Tabs** (`swarm_tabs_test.dart`, `phone/phone_shell_swarm_home_test.dart`): three labelled tabs, the avatar opening You with back, You going with the tabs when Swarm is turned off, While you were away opening Activity on Needs you, a repeated ask applied again.- **Tiles** (`swarm_home_tiles_test.dart`): figures, skeletons and what a screen reader hears; the row's order, sizes and sideways scroll.- **Project rows** (`swarm_home_project_row_test.dart`, `swarm_home_test.dart`): one line, bold when new, the Swarm's name with several, no people line.-- **Search** (`swarm_search_page_test.dart`, `swarm_home_search_test.dart`): the ways in; each kind and what it leaves out; ranking, case and accents; chips, swipes and the chip following; opening a row and coming back; agents; reading and failure; the keyboard inset (the page ends at the keyboard, once) and a drag putting the keyboard away. The pull is tested on clamping and bouncing lists, and a drag begun mid-list opens nothing. Home has no field; the top bar's Search opens the page. The page's field takes none of the app's field outline or fill, focused or not, in light and dark.+- **Search** (`swarm_search_page_test.dart`): the ways in; each kind and what it leaves out; ranking, case and accents; chips, swipes and the chip following; opening a row and coming back; agents; reading and failure; the keyboard inset (the page ends at the keyboard, once) and a drag putting the keyboard away. Home has no field; the top bar's Search opens the page, while a pull refreshes Home without opening Search. The page's field takes none of the app's field outline or fill, focused or not, in light and dark.+- **Pull to refresh** (`swarm_home_instant_test.dart`): Android and iOS pulls recheck computers before reading the Swarms when none answers; failed rechecks are logged and the Swarms still read; with computers answering, the pull only reads the Swarms.- **Activity** (`swarm_activity_test.dart`, `swarm_activity_page_test.dart`, `swarm_activity_feed_page_test.dart`, `swarm_invitations_in_swarm_test.dart`): All's order, Mentions, Invitations in All and Needs you with their counts, the tab badge counting them and dropping one put off.- **Filter sheet** (`swarm_home_view_test.dart`, `swarm_mark_all_test.dart`, `swarm_home_instant_test.dart`): Mark all read and Refresh in the sheet.- **Project details** (`swarm_project_details_test.dart`): the header button, every item and its order, Invite for the owner alone, Open terminal and its greyed states, each row's sheet, and the sheet closing with access, sign-out or the project.diff --git a/docs/plans/2026-11-05-compact-route-answer-plan.md b/docs/plans/2026-11-05-compact-route-answer-plan.mdnew file mode 100644index 000000000..670cf43f1--- /dev/null+++ b/docs/plans/2026-11-05-compact-route-answer-plan.md@@ -0,0 +1,65 @@+# Compact route answer Implementation Plan++> Way of working: this project's Engineer role (project instructions, Engineer): the plan is the pull request's first+> commit, then each task's failing test is committed before the code that passes it. No Execution Handoff.++**Goal:** A route answer the coordinator reads is a few thousand characters, not ~45,000 (task #3294, Ken 2026-11-05):+the Routing section and the revision instead of the whole instructions, one compact line per candidate, a short+left-out list. A 40-candidate answer is under 8,000 characters.++**Architecture:** `routeTask` (cli/src/superTabs/routeCommand.ts) keeps building the structured answer it builds today,+and the decision it records for Details is unchanged. A new pure function, `routeAnswer(answer, options)`, renders that+structured answer into what `harness super-tab route` prints: the instructions' Routing section and revision (the whole+text with `--full-instructions`, none with `--instructions-read N` while N is still current), one line per candidate,+a machines map (id, start folder, room) said once per machine instead of on every row, one line per left-out machine.+`command.ts` parses the two flags and prints `routeAnswer(...)` instead of the structured object.++**Tech Stack:** TypeScript, vitest (cli).++**Spec:** task #3294 brief. Every engine on every machine stays listed (Ken, 2026-11-03).++## Global Constraints++- CLI only: the answer is built in the CLI; the backend record (`route.record`) is unchanged.+- Swarm code stays out of cli/src/core.+- Every candidate the record holds is still in the answer, with what a start or an assignment needs: its id, agentId,+ machine id, engine, model, effort, grid model and name, start folder.+- The skill text that names the route answer's fields (cli/src/lib/swarmTools.ts) says the new shape and flags.++## Review Focus++- Nothing the coordinator needs to start or assign is lost from a row (machine id and cwd through the machines map).+- The Routing section is found in real instructions (`## Routing` up to the next `## ` heading); instructions without one+ fall back to the whole text, never to nothing.+- `--instructions-read N` leaves the text out only when N is the current revision.++## Tasks++### Task 1: the size test and the compact renderer++**Files:** cli/src/superTabs/routeCommand.ts, cli/src/superTabs/routeCommand.spec.ts, cli/src/superTabs/route.ts++**Interfaces:** `routeAnswer(answer: Json, options?: { fullInstructions?: boolean; instructionsRead?: number }): Json`;+`routingSection(text: string): string | null`; `quotaLine(...)` in route.ts.++- [ ] Failing test: a 40-candidate route answer (10 machines, both engines, new and idle rows, PM-account notes,+ long plug-in notes, 20 left-out machines) rendered by `routeAnswer` with the instructions read is under 8,000+ characters, and every row still says its id, machine, engine, model, effort and agentId.+- [ ] Failing test: instructions come back as the Routing section and revision only; the whole text with+ `fullInstructions`; only the revision when `instructionsRead` is the current revision; the Routing section again+ when it is not.+- [ ] Implement `routingSection`, the compact quota line, the candidate line, the machines map and the left-out lines.++### Task 2: the flags and the printed answer++**Files:** cli/src/superTabs/command.ts, cli/src/superTabs/command.spec.ts++- [ ] Failing test: `route GROUP JSON --full-instructions` and `--instructions-read 74` parse; anything else is refused;+ the printed route answer is the compact one.+- [ ] Implement the parse and print `routeAnswer`.++### Task 3: the skill text++**Files:** cli/src/lib/swarmTools.ts, cli/src/lib/swarmSkills.ts (if it names a changed field)++- [ ] Say the answer's shape and the two flags in the `route` lines; the coordinator passes the revision it read.diff --git a/docs/plans/2026-11-05-project-order-plan.md b/docs/plans/2026-11-05-project-order-plan.mdnew file mode 100644index 000000000..1fb5daa87--- /dev/null+++ b/docs/plans/2026-11-05-project-order-plan.md@@ -0,0 +1,48 @@+# Fixed project order implementation plan++> Implement natively, task by task with test-driven development and one independent pull request review.++**Goal:** Keep phone Home and Desktop/web projects alphabetically ordered despite new activity.+**Architecture:** Sort existing phone sections by case-insensitive project name, ignoring a leading #. Preserve explicit existing newest/unread opt-ins and section membership. Apply the same name comparison to Desktop rows and keyboard navigation, without changing their appearance.+**Tech Stack:** Dart, Flutter, flutter_test.+**Spec:** Swarm task #3353, conversation 045fdf04dee8ca86c98e72fd.++## Global Constraints++- Requested by dee through Harness.+- Preserve the current layout, bold names and unread dots; no backend or CLI changes.+- Use memory stores and fake sign-in; never sign the Mac out.+- Run affected phone and Desktop tests and check-ui-style before Ready; CI supplies full component suites.+- Record failing and passing test evidence in a PR comment. One independent review and UI test step.++## Review Focus++- New activity and unread changes must not reorder the default project list.+- Leading # and mixed case must not distort A–Z order.+- Equal normalized names must have a deterministic order independent of input order.+- Pinned and quiet sections retain existing membership and explicit newest mode retains its behavior.+- Desktop keyboard navigation follows the displayed order.++## Task 1: Phone Home ordering++**Files:** Modify `mobile/lib/swarm/swarm_home_list.dart`; test `mobile/test/swarm/swarm_home_list_test.dart` and `mobile/test/swarm/swarm_home_view_test.dart`.+**Interfaces:** Consume `swarmHomeLists`; preserve its signature and return sections.++- [x] Add regressions for A–Z mixed-case/hash names, activity/unread updates, equal names and pinned/quiet sections; update old default-order expectations.+- [x] Run the named phone tests, observe ordering failures and commit tests.+- [x] Replace default activity comparison with normalized name ordering and deterministic key tie-break; preserve explicit newest/unread choices.+- [x] Run affected phone tests; commit and push.++## Task 2: Desktop/web sidebar ordering++**Files:** Modify `desktop/lib/super_tabs/project_sidebar.dart`; test `desktop/test/super_tab_sidebar_test.dart`.+**Interfaces:** Preserve `ProjectSidebar` and `superTabSidebarOrder` APIs.++- [x] Add widget regression for hash/mixed-case project names and unchanged positions after new activity; verify navigation order too.+- [x] Run that test, observe the ordering failure and commit tests.+- [x] Normalize names and use deterministic ties in row/navigation sorting.+- [x] Run affected Desktop tests and `python3 scripts/check-ui-style.py`; commit and push.++## Validation scope++Dart-only list comparisons; no schema, persistence, process, platform or dependency changes. Run the affected home list/view/row/widget tests and sidebar/navigation tests with two workers and 60-second per-test limits on macOS. Full component suites run in PR CI. Independent Tester verifies light/dark UI and activity update behavior with fake state. No release is authorized for the Engineer.diff --git a/docs/plans/2026-11-05-team-update-recovery-plan.md b/docs/plans/2026-11-05-team-update-recovery-plan.mdnew file mode 100644index 000000000..21d823646--- /dev/null+++ b/docs/plans/2026-11-05-team-update-recovery-plan.md@@ -0,0 +1,88 @@+# Team account update recovery implementation plan++> Implement task by task in this Engineer session, test first, with independent security reviews and user-flow testing of the completed pull request.++**Goal:** Keep the macOS Team account available through CLI updates, offer Restart when it is offline, and finish the handed-sign-in trust fixes.++**Architecture:** Keep Team lifecycle policy in `cli/src/team`. Reuse existing setup for the password-protected Restart action. Pin a redeemed handed sign-in to its account through the guarded session update, and discard the departing owner's trust on Team account switches.++**Tech Stack:** TypeScript, Node, Vitest, launchd; Flutter/Dart widget tests.++**Spec:** Swarm task #3307, conversation `faf4f30958d4f61cdf6a8119`; prerequisite PR https://github.com/autonomous-ai/openharness/pull/3159.++## Global Constraints++- Two independent security reviews; no real sign-in/out or account creation in tests.+- macOS recovery and Desktop action; preserve Linux and Windows lifecycle behavior.+- Swarm code stays out of cli/src/core. Keep the owner's session separate from Team work.+- Show Amon the ASCII row mockup and obtain his yes before implementing the row.+- Use targeted local tests; component suites come from PR CI. Run relevant checks CI omits.+- First PR-body line: Requested by kelvin1295 through Harness.++## Review Focus++- An update interrupted after stopping its own daemon must recover without a second daemon.+- An intentional stop or sign-out must not be undone by recovery.+- Delayed account lookup must never annotate a replacement sign-in.+- Failed redemption must preserve the old sign-in and trust.+- A remote viewer or another member must never get an administrator action on this Mac.++## Design++- Growth: one existing session account field; no new history. Departing Team trust is deleted rather than retained per owner.+- Concurrency: session writes use updateAuthSession and match the exact epoch; daemon starts retain the existing spawn lock.+- Read cost: one bounded auth/me lookup after redemption; existing machine observations drive the row.+- Scale: constant local work per handoff/update; repeated failures are surfaced in existing logs/status.+- Compatibility: existing optional signInAcct field; old clients ignore it. No backend protocol changes.+- Migration + rollback: no database migration; old binaries ignore the account pin. Deleted old-owner trust is intentionally not restored; another setup can recreate trust from the signed device log.+- Audience: only the local machine's own signed-in contributor sees Restart; existing setup validates and prompts for administrator authority.+- Identity: redeemed Team token authenticates account lookup; never the machine owner's login.+- Failure: failed lookup preserves existing fallback and reports a bounded diagnostic; restart failures use existing setup status.+- Platforms: recovery is macOS-specific; shared handoff fixes retain Windows/Linux tests.++## Task 1: Reproduce and fix the update lifecycle++**Files:** `cli/src/team/script.ts`, `cli/src/team/script.spec.ts`, `cli/src/team/refresh.ts`, `cli/src/team/refresh.spec.ts`; update command integration only if the traced cause requires it.+**Interfaces:** existing `teamLaunchdPlist`, `TEAM_JOB_WRAPPER`, `teamUpdateArgv`; no new public command.++- [x] Trace stop, stage, relaunch and launchd exit handling. The owner refresh runs update in a shell hosted by the Team daemon that update stops; closing that process group reproduces the interrupted update. Keep the updater independent before acknowledging its launch; preserve intentional-stop semantics and failure-only launchd policy.+- [x] Commit a regression simulating that update through isolated fake processes and temporary files; prove daemon availability afterward and intentional-stop behavior. Watch it fail.+- [x] Commit the smallest lifecycle correction; run affected Team lifecycle tests and typecheck.++## Task 2: Finish handed sign-in isolation++**Files:** `cli/src/team/command.ts`, `cli/src/team/command.spec.ts`, `cli/src/team/handoff.ts`; `cli/src/lib/e2ee/accountTrust.ts` and its spec, `cli/src/gateway/start.ts` for the departing-stash policy.+**Interfaces:** existing `TeamCommandDeps.get/updateSession`, `teamSession`, `switchAccountTrust`; integrate prerequisite #3159 before changing its handed epoch.++- [x] Commit failing cases for account pin after redemption, failed lookup, and epoch replacement during lookup; observe failures.+- [x] Pin auth/me's account using the redeemed token and exact sign-in epoch; preserve sign-in on lookup failure. Commit green code.+- [x] Commit failing temporary-store cases for Team owner switch deleting the departing stash and preserving ordinary account stash/identity/device pairings; observe failures.+- [x] Implement the Team-specific discard policy outside core; commit green code and run affected trust and handoff specs.++## Task 3: Offline row Restart++**Files:** `desktop/lib/super_tabs/machines.dart`, `desktop/test/super_tab_team_machine_test.dart`, relevant existing setup widget fixtures.+**Interfaces:** add an optional local-owner-only `restart` flag through `AppNotifier.setUpTeamAccount`, the existing setup dialog, `superTabs/service.ts`, and `TeamAutoSetup.offer`; Restart invokes the same password-protected setup without replacing a valid sign-in.++- [x] Post the ASCII mockup to Amon and notify his Buddy; Amon replied "ok" on 2026-11-05 before Desktop implementation.+- [x] Commit failing widget cases for local-owner offline reason + Restart, no action for remote/other-owner/offline-host cases, and standard button invoking setup; observe failures.+- [x] Implement approved copy/action with existing standard button; commit green code.+- [x] Run affected macOS Flutter tests and capture light/dark fixtures using memory state and fake sign-in.++## Added scope from the PM++River requested that status reflect a Team sign-in that no longer works. Regressions cover a missing session at daemon startup and loss during observation, replacing historical success with signed-out.++## Completion++- [ ] Post red/green evidence in a PR comment; mark ready at a stable head.+- [ ] Hand the Integrator the PR for two security reviews and independent Team-account testing.+- [ ] Resolve findings test first, record all task acceptance checks, then report the exact head and evidence through work status.++## Security review correction: departing device-log archive++SecLarch found that deleting the departing trust stash still left the same owner's device names, keys and suspensions in the device-log archive. The refresh and confirmed-review switch paths must both discard the departing log (including a pre-existing archived copy) for Team sign-ins. Ordinary sign-ins continue archiving. Historical stashes for unrelated owners and status recovery are recorded minor findings, outside this correction.++- [x] Commit four regression cases before implementation: Team and ordinary switches, through refresh and confirmed review. Both Team cases fail without the fix.+- [x] Apply the same Team epoch policy as trust-stash cleanup when archiving the departing log.+- [ ] Validate device-log/store/trust tests and importer tests, publish red/green evidence, and request delta reviews at the new head.diff --git a/mobile/lib/swarm/swarm_home_list.dart b/mobile/lib/swarm/swarm_home_list.dartindex abd7e5bdf..38e15c15d 100644--- a/mobile/lib/swarm/swarm_home_list.dart+++ b/mobile/lib/swarm/swarm_home_list.dart@@ -37,8 +37,8 @@ class SwarmHomeProject {String get key => swarmHomeProjectKey(swarmId, project.id);}-/// Home's projects in their groups, each newest first: those the person-/// pinned ([pinned]); then the others ([recent]), save those quiet for more+/// Home's projects alphabetically in their groups: those the person pinned+/// ([pinned]); then the others ([recent]), save those quiet for more/// than [swarmQuietAfter], which fold under "Other projects" ([quiet]).typedef SwarmHomeLists = ({List<SwarmHomeProject> pinned,@@ -48,11 +48,11 @@ typedef SwarmHomeLists = ({/// [projects], in the order read, as Home groups them (Tony, 2026-10-29):/// pinned ones by their [pins] key at the top, quiet or not; the others by-/// latest activity, those quiet for a day folded. A project whose time is not-/// known comes after those whose is, in the order read, and is never folded,-/// nor is one with something new in it. Nothing is folded when nothing else-/// would be listed. [sort] newest folds nothing; [unreadsFirst] brings those-/// with something new to the top of each list, in the same order among them.+/// name, ignoring a leading # and case, with quiet projects folded for a day.+/// A project with unknown activity or something new is never folded. Nothing+/// is folded when nothing else would be listed. [sort] newest orders by+/// activity and folds nothing; [unreadsFirst] brings those with something new+/// to the top of each list, in the same order among them.SwarmHomeLists swarmHomeLists(Iterable<SwarmHomeProject> projects, {required Set<String> pins,@@ -76,8 +76,27 @@ SwarmHomeLists swarmHomeLists(recent.add(project);}}- // Stable: what is not known keeps the order read, after the rest.- List<SwarmHomeProject> newest(List<SwarmHomeProject> list) {+ List<SwarmHomeProject> ordered(List<SwarmHomeProject> list) {+ if (sort == SwarmHomeSort.sections) {+ final named =+ [+ for (final p in list)+ (+ p,+ (p.project.name.startsWith('#')+ ? p.project.name.substring(1).trimLeft()+ : p.project.name)+ .toLowerCase(),+ ),+ ]..sort((a, b) {+ if (unreadsFirst && _hasNews(a.$1) != _hasNews(b.$1)) {+ return _hasNews(a.$1) ? -1 : 1;+ }+ final byName = a.$2.compareTo(b.$2);+ return byName != 0 ? byName : a.$1.key.compareTo(b.$1.key);+ });+ return [for (final entry in named) entry.$1];+ }final order = {for (final (i, p) in list.indexed) p: i};return list..sort((a, b) {if (unreadsFirst && _hasNews(a) != _hasNews(b)) {@@ -91,9 +110,13 @@ SwarmHomeLists swarmHomeLists(}if (pinned.isEmpty && recent.isEmpty) {- return (pinned: const [], recent: newest(quiet), quiet: const []);+ return (pinned: const [], recent: ordered(quiet), quiet: const []);}- return (pinned: newest(pinned), recent: newest(recent), quiet: newest(quiet));+ return (+ pinned: ordered(pinned),+ recent: ordered(recent),+ quiet: ordered(quiet),+ );}bool _hasNews(SwarmHomeProject p) =>diff --git a/mobile/test/swarm/swarm_home_list_test.dart b/mobile/test/swarm/swarm_home_list_test.dartindex b07da3ac9..4f334377d 100644--- a/mobile/test/swarm/swarm_home_list_test.dart+++ b/mobile/test/swarm/swarm_home_list_test.dart@@ -209,8 +209,47 @@ void main() {for (final p in projects) p.project.id,];- test('newest first; one with no time known after them, in the order '- 'read, and never folded', () {+ test('default A to Z ignores # and case, not activity or unread', () {+ SwarmHomeProject named(+ String id,+ String name,+ int minutes, {+ SwarmProjectNews news = swarmNoProjectNews,+ }) => SwarmHomeProject(+ swarmId: tab,+ project: SuperTabProject.fromJson({+ 'id': id,+ 'name': name,+ 'ownerId': me,+ 'leadConversationId': 'lead-$id',+ }),+ active: at(ago(minutes)),+ news: news,+ );+ for (final updated in [false, true]) {+ final lists = swarmHomeLists(+ [+ named(+ 'z',+ '# Zebra',+ updated ? 0 : 10,+ news: updated+ ? (bold: true, tags: 1, hasWaitingTag: true)+ : swarmNoProjectNews,+ ),+ named('b', 'beta', 1),+ named('a2', '# ALPHA', 3),+ named('a1', 'alpha', 5),+ ],+ pins: const {},+ now: now,+ );+ expect(ids(lists.recent), ['a1', 'a2', 'b', 'z']);+ expect(lists.recent.last.news.bold, updated);+ }+ });++ test('default alphabetical order includes projects with no activity', () {final lists = swarmHomeLists([project('a', minutes: 40),@@ -224,11 +263,11 @@ void main() {);expect(ids(lists.pinned), isEmpty);- expect(ids(lists.recent), ['c', 'e', 'a', 'b', 'd']);+ expect(ids(lists.recent), ['a', 'b', 'c', 'd', 'e']);expect(lists.quiet, isEmpty);});- test('quiet for more than a day: folded under Other projects, newest '+ test('quiet for more than a day: folded under Other projects, alphabetical ''first', () {final lists = swarmHomeLists([@@ -242,10 +281,10 @@ void main() {);expect(ids(lists.recent), ['b']);- expect(ids(lists.quiet), ['a', 'd', 'c']);+ expect(ids(lists.quiet), ['a', 'c', 'd']);});- test('pinned: at the top in a group of their own, newest first, quiet '+ test('pinned: at the top in a group of their own, alphabetical, quiet ''or not, and out of Projects', () {final lists = swarmHomeLists([@@ -259,8 +298,8 @@ void main() {now: now,);- expect(ids(lists.pinned), ['d', 'b']);- expect(ids(lists.recent), ['c', 'a']);+ expect(ids(lists.pinned), ['b', 'd']);+ expect(ids(lists.recent), ['a', 'c']);expect(ids(lists.quiet), ['e']);});diff --git a/mobile/test/swarm/swarm_home_test.dart b/mobile/test/swarm/swarm_home_test.dartindex 39db24a25..72aeff1d5 100644--- a/mobile/test/swarm/swarm_home_test.dart+++ b/mobile/test/swarm/swarm_home_test.dart@@ -970,24 +970,48 @@ void main() {},);- testWidgets('projects newest first, the time off the row', (tester) async {- final now = DateTime.utc(2026, 10, 29, 10);- int ago(int minutes) =>- now.subtract(Duration(minutes: minutes)).millisecondsSinceEpoch;- final fake = backend();- timed(fake, {for (final id in mobileChats) id: ago(9), webLead: ago(2)});- await pump(tester, fake, now: () => now);-- expect(- y(tester, 'swarm-project-$tab-$web'),- lessThan(y(tester, 'swarm-project-$tab-$project')),- );- expect(inside('swarm-project-$tab-$web', find.text('2m')), findsNothing);- expect(- inside('swarm-project-$tab-$project', find.text('9m')),- findsNothing,- );- });+ testWidgets(+ 'projects stay alphabetical after new activity, the time off the row',+ (tester) async {+ final now = DateTime.utc(2026, 10, 29, 10);+ int ago(int minutes) =>+ now.subtract(Duration(minutes: minutes)).millisecondsSinceEpoch;+ final fake = backend();+ timed(fake, {+ for (final id in mobileChats) id: ago(9),+ webLead: ago(2),+ });+ final host = await pump(tester, fake, now: () => now);+ void alphabetical() => expect(+ y(tester, 'swarm-project-$tab-$project'),+ lessThan(y(tester, 'swarm-project-$tab-$web')),+ );+ alphabetical();+ moveOn(fake, {+ webLead: {+ ...groupData(webLead, title: 'Web', lastMessageSequence: 99),+ 'projectId': web,+ 'lastPersonSequence': 99,+ 'changedAt': now.millisecondsSinceEpoch,+ },+ });+ await host.session!.inbox.refresh();+ await tester.pumpAndSettle();+ alphabetical();+ expect(+ inside('swarm-project-$tab-$web', key('swarm-project-unread')),+ findsOneWidget,+ );+ expect(+ inside('swarm-project-$tab-$web', find.text('2m')),+ findsNothing,+ );+ expect(+ inside('swarm-project-$tab-$project', find.text('9m')),+ findsNothing,+ );+ },+ );testWidgets('a project quiet for a day folds under Other projects, which ''a tap opens and closes', (tester) async {@@ -1043,8 +1067,10 @@ void main() {testWidgets('a long press pins a project at the top, with no Pinned ''heading (anh Dee, 2026-11-04); Unpin puts it back', (tester) async {final host = await pump(tester, backend());+ host.session!.home.setSort(SwarmHomeSort.newest);+ await tester.pumpAndSettle();double top(String id) => y(tester, 'swarm-project-$tab-$id');- expect(top(web), lessThan(top(project)), reason: 'newer first');+ expect(top(web), lessThan(top(project)), reason: 'explicit newest first');await tester.longPress(key('swarm-project-$tab-$project'));await tester.pumpAndSettle();@@ -1549,8 +1575,8 @@ void main() {);final order = ['swarm-heading-$tab',- webRow,mobileRow,+ webRow,'swarm-heading-$second',backendRow,];diff --git a/mobile/test/swarm/swarm_home_view_test.dart b/mobile/test/swarm/swarm_home_view_test.dartindex abcfa390b..f44153801 100644--- a/mobile/test/swarm/swarm_home_view_test.dart+++ b/mobile/test/swarm/swarm_home_view_test.dart@@ -84,7 +84,7 @@ void main() {test('Sections folds the quiet ones, as Home always has', () {final lists = swarmHomeLists(projects, pins: pins, now: now);expect(ids(lists.pinned), ['pinned-read']);- expect(ids(lists.recent), ['new-read', 'tagged', 'older-unread']);+ expect(ids(lists.recent), ['new-read', 'older-unread', 'tagged']);expect(ids(lists.quiet), ['old-read']);});@@ -117,7 +117,7 @@ void main() {unreadsFirst: true,);expect(ids(lists.pinned), ['pinned-tagged', 'pinned-read']);- expect(ids(lists.recent), ['tagged', 'older-unread', 'new-read']);+ expect(ids(lists.recent), ['older-unread', 'tagged', 'new-read']);});test('All leaves them; Unread keeps anything new, pinned too; Mentions '@@ -136,7 +136,7 @@ void main() {);final unread = swarmHomeFiltered(lists, SwarmHomeFilter.unread);expect(ids(unread.pinned), ['pinned-unread']);- expect(ids(unread.recent), ['tagged', 'older-unread']);+ expect(ids(unread.recent), ['older-unread', 'tagged']);expect(unread.quiet, isEmpty);final mentions = swarmHomeFiltered(lists, SwarmHomeFilter.mentions);expect(mentions.pinned, isEmpty);@@ -565,7 +565,9 @@ void main() {testWidgets('Move to the top brings the unread project over a newer read ''one, and the row says so', (tester) async {- await pump(tester, backend());+ final host = await pump(tester, backend());+ host.session!.home.setSort(SwarmHomeSort.newest);+ await tester.pumpAndSettle();double top(String id) => tester.getTopLeft(project_(id)).dy;expect(top(web), lessThan(top(project)));@@ -575,7 +577,7 @@ void main() {expect(text(tester, 'swarm-view-sort-current'),- 'Sections. Unreads on top.',+ 'Newest to oldest. Unreads on top.',);expect(top(project), lessThan(top(web)));});