Skip to content

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

Merge batch 11-06 j0710: #3256 #3230 #3068 #3250 (#3258)

0xken1504baa0aa1da9
diff --git a/backend/integration/crewDispatch.test.ts b/backend/integration/crewDispatch.test.ts
new file mode 100644
index 000000000..9588f8dbb
--- /dev/null
+++ b/backend/integration/crewDispatch.test.ts
@@ -0,0 +1,257 @@
+import { randomUUID } from 'node:crypto'
+import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'
+import type { MongoMemoryReplSet } from 'mongodb-memory-server-core'
+import type { Prisma, PrismaClient } from '@prisma/client'
+import type { AuthUser } from '../src/lib/ssoAuth.js'
+import { DISPATCH_RETRY_MS, SuperTabStore } from '../src/superTabs/store.js'
+import { noteChange, swarmTransaction } from '../src/superTabs/cache.js'
+import type { Command } from '../src/superTabs/commands.js'
+import type { Agent, Conversation } from '../src/superTabs/model.js'
+import { planDatabase } from './plans.test-support.js'
+
+// The Swarm hands the next task to a free crew member by itself (task #3400). A fresh loopback replica set; never DATABASE_URL.
+let replica: MongoMemoryReplSet
+let db: PrismaClient
+const NOW = Date.parse('2026-11-05T15:00:00Z')
+const owner: AuthUser = { sub: '410000000000000000000001', email: '[email protected]', autonomousEnv: 'prod', role: 'user' }
+const config = { engine: 'claude', model: 'fixture-model', effort: 'high', contextWindow: 200000, engineVersion: 'fixture' }
+
+beforeAll(async () => {
+ ({ replica, db } = await planDatabase('crew_dispatch_test'))
+ await db.user.create({ data: { id: owner.sub, externalId: `fixture-${owner.sub}`, email: owner.email, autonomousEnv: 'prod' } })
+ await db.machine.create({ data: { machineId: 'owner-mac', userId: owner.sub, apiKey: 'fixture-owner-mac', managerId: 'fixture', autonomousEnv: 'prod', authMode: 'remote' } })
+ await db.machine.create({ data: { machineId: 'team-mac', userId: owner.sub, apiKey: 'fixture-team-mac', managerId: 'fixture', autonomousEnv: 'prod', authMode: 'remote' } })
+})
+afterAll(async () => {
+ await db?.$disconnect()
+ await replica?.stop()
+})
+
+/** A Swarm with a PM and the crew [lanes] (name -> lane), and the tasks [owns] (title -> one owned path), in that order. */
+async function swarm(lanes: Record<string, string | null>, owns: Record<string, string>, dispatch = false, pmMachine = 'owner-mac') {
+ let clock = NOW
+ const store = new SuperTabStore(db, () => clock, null, { dispatch })
+ /** Moves this Swarm's server clock on. */
+ const advance = (ms: number) => { clock += ms }
+ const tab = (await store.create(owner, randomUUID(), 'Crew', 'public')).id
+ const execute = (command: Command, asAgentId?: string) => store.execute(owner, tab, { operationId: randomUUID(), command }, asAgentId)
+ const add = async (name: string, lead = false) => String((await execute({ type: 'agent.add', conversationId: 'lead', machineId: lead ? pmMachine : 'owner-mac',
+ harnessId: randomUUID(), name, configuration: config, lead })).result.agentId)
+ const pm = await add('PM', true)
+ const crew: Record<string, string> = {}
+ for (const [name, lane] of Object.entries(lanes)) {
+ crew[name] = await add(name)
+ // Marked as #3397's crew.add marks it, until that command lands.
+ await editAgent(tab, crew[name]!, agent => ({ ...agent, crew: { role: 'Engineer', ...lane ? { lane } : {}, at: NOW, by: owner.sub } }))
+ }
+ const tasks: Record<string, string> = {}
+ for (const [title, path] of Object.entries(owns)) {
+ tasks[title] = String((await execute({ type: 'conversation.create', title, checks: [],
+ task: { goal: `${title}.`, changes: 'The change.', constraints: 'None.', owns: [path] } })).result.conversationId)
+ }
+ /** Who holds each task now, by name, from what is stored. */
+ const holders = async () => {
+ const names = Object.fromEntries(Object.entries(crew).map(([name, id]) => [id, name]))
+ return Object.fromEntries(await Promise.all(Object.entries(tasks).map(async ([title, id]) => {
+ const group = await readGroup(tab, id)
+ const holder = group.assignment && !['lost', 'stopped', 'cancelled'].includes(group.assignment.status) ? names[group.assignment.agentId] ?? group.assignment.agentId : null
+ return [title, holder]
+ })))
+ }
+ return { store, tab, pm, crew, tasks, execute, holders, advance }
+}
+
+/** Writes a part outside the store as every writer does (cacheOn.test-support.ts): a new version, and the Swarm's stamp moved. */
+async function editAgent(tabId: string, agentId: string, edit: (agent: Agent) => Agent) {
+ await swarmTransaction(db, async tx => {
+ const row = await tx.swarmAgent.findUniqueOrThrow({ where: { tabId_key: { tabId, key: agentId } } })
+ await tx.swarmAgent.update({ where: { id: row.id }, data: { version: row.version + 1, changedAt: new Date(),
+ data: edit(row.data as unknown as Agent) as unknown as Prisma.InputJsonValue } })
+ noteChange(tx, tabId, 'main')
+ })
+}
+async function editGroup(tabId: string, groupId: string, edit: (group: Conversation) => Conversation) {
+ await swarmTransaction(db, async tx => {
+ const row = await tx.swarmGroup.findUniqueOrThrow({ where: { tabId_key: { tabId, key: groupId } } })
+ await tx.swarmGroup.update({ where: { id: row.id }, data: { version: row.version + 1, changedAt: new Date(),
+ data: edit(row.data as unknown as Conversation) as unknown as Prisma.InputJsonValue } })
+ noteChange(tx, tabId, 'main')
+ })
+}
+async function readGroup(tabId: string, groupId: string): Promise<Conversation> {
+ return (await db.swarmGroup.findUniqueOrThrow({ where: { tabId_key: { tabId, key: groupId } } })).data as unknown as Conversation
+}
+
+describe('the crew dispatch pass', () => {
+ it('hands a free member its pinned task first, then its lane\'s top task, as the PM, through work.assign', async () => {
+ const s = await swarm({ Ash: 'backend', Birch: 'desktop' }, { Api: 'backend/src/a.ts', Store: 'backend/src/b.ts', Board: 'desktop/lib/c.dart' })
+ await editGroup(s.tab, s.tasks.Store!, group => ({ ...group, pin: { agentId: s.crew.Ash!, why: 'ci', at: NOW } }))
+ expect(await s.store.dispatchCrew(s.tab)).toMatchObject({ assigned: 2 })
+ expect(await s.holders()).toEqual({ Api: null, Store: 'Ash', Board: 'Birch' })
+ // The assignment is an ordinary one, made by the project's PM, and it cleared the pin.
+ const store = await readGroup(s.tab, s.tasks.Store!)
+ expect(store.pin).toBeUndefined()
+ const notice = (await s.store.messages(owner, s.tab, s.tasks.Store!, {})).messages.find(m => m.author.id === s.pm)
+ expect(notice).toBeDefined()
+ // A second pass finds nobody free and changes nothing.
+ expect(await s.store.dispatchCrew(s.tab)).toMatchObject({ assigned: 0 })
+ expect(await s.holders()).toEqual({ Api: null, Store: 'Ash', Board: 'Birch' })
+ })
+
+ it('assigns once when two passes race, from two servers: one task to the member, never two, never one task twice', async () => {
+ const s = await swarm({ Ash: 'backend' }, { Api: 'backend/src/a.ts', Store: 'backend/src/b.ts' })
+ const other = new SuperTabStore(db, () => NOW)
+ await Promise.all([s.store.dispatchCrew(s.tab), other.dispatchCrew(s.tab), s.store.dispatchCrew(s.tab)])
+ expect(await s.holders()).toEqual({ Api: 'Ash', Store: null })
+
+ const t = await swarm({ Cedar: 'backend', Dune: 'backend' }, { Api: 'backend/src/a.ts' })
+ await Promise.all([t.store.dispatchCrew(t.tab), new SuperTabStore(db, () => NOW).dispatchCrew(t.tab)])
+ const held = Object.values(await t.holders())
+ expect(held).toHaveLength(1)
+ expect(['Cedar', 'Dune']).toContain(held[0])
+ })
+
+ it('leaves a project without crew to its PM', async () => {
+ const s = await swarm({}, { Api: 'backend/src/a.ts' })
+ await s.execute({ type: 'agent.add', conversationId: 'lead', machineId: 'owner-mac', harnessId: randomUUID(), name: 'Plain', configuration: config, lead: false })
+ expect(await s.store.dispatchCrew(s.tab)).toMatchObject({ assigned: 0 })
+ expect(await s.holders()).toEqual({ Api: null })
+ })
+
+ it('assigns as a PM that runs in a Harness Team account, with no one\'s sign-in', async () => {
+ const s = await swarm({ Ash: 'backend' }, { Api: 'backend/src/a.ts' })
+ // The PM's machine becomes a Team account's: an ordinary sign-in may no longer speak as its agents (store.ts notTeamMachine).
+ await db.machine.updateMany({ where: { machineId: 'owner-mac', userId: owner.sub }, data: { sessionKind: 'team' } })
+ try {
+ expect(await s.store.dispatchCrew(s.tab)).toMatchObject({ assigned: 1 })
+ expect(await s.holders()).toEqual({ Api: 'Ash' })
+ } finally {
+ await db.machine.updateMany({ where: { machineId: 'owner-mac', userId: owner.sub }, data: { sessionKind: null } })
+ }
+ })
+
+ it('runs by itself a second after a write that opens a task, only in a Swarm with a crew', async () => {
+ const s = await swarm({ Ash: 'backend' }, {}, true)
+ const id = String((await s.execute({ type: 'conversation.create', title: 'Api', checks: [],
+ task: { goal: 'Api.', changes: 'The change.', constraints: 'None.', owns: ['backend/src/a.ts'] } })).result.conversationId)
+ await vi.waitFor(async () => expect((await readGroup(s.tab, id)).assignment?.agentId).toBe(s.crew.Ash), { timeout: 5_000, interval: 200 })
+
+ // A progress note frees nobody: no pass is scheduled by it. Handing over for review schedules one.
+ await vi.waitFor(() => expect(s.store.dispatchScheduled(s.tab)).toBe(false), { timeout: 5_000, interval: 100 })
+ const assignmentId = (await readGroup(s.tab, id)).assignment!.id
+ await s.execute({ type: 'work.status', conversationId: id, assignmentId, status: 'working', result: 'Halfway.' }, s.crew.Ash)
+ expect(s.store.dispatchScheduled(s.tab)).toBe(false)
+ await s.execute({ type: 'work.status', conversationId: id, assignmentId, status: 'review', result: 'Ready at abc1234.' }, s.crew.Ash)
+ expect(s.store.dispatchScheduled(s.tab)).toBe(true)
+
+ // In a Swarm without a crew, no write schedules one.
+ const plain = await swarm({}, {}, true)
+ await plain.execute({ type: 'conversation.create', title: 'Api', checks: [],
+ task: { goal: 'Api.', changes: 'The change.', constraints: 'None.', owns: ['backend/src/a.ts'] } })
+ expect(plain.store.dispatchScheduled(plain.tab)).toBe(false)
+ })
+
+ it('does not assign a member taken out of the crew while the pass read GitHub', async () => {
+ const s = await swarm({ Ash: 'backend' }, { Api: 'backend/src/a.ts' })
+ const store = s.store as unknown as { pushOriginFor: (...args: unknown[]) => Promise<unknown> }
+ vi.spyOn(store, 'pushOriginFor').mockImplementationOnce(async () => {
+ await editAgent(s.tab, s.crew.Ash!, agent => { const { crew: _crew, ...rest } = agent; return rest as Agent })
+ return undefined
+ })
+ await s.store.dispatchCrew(s.tab)
+ expect(await s.holders()).toEqual({ Api: null })
+ })
+
+ it('assigns nothing as a PM whose grant no longer holds, waits a little, and assigns once its access is back', async () => {
+ const s = await swarm({ Ash: 'backend' }, { Api: 'backend/src/a.ts' })
+ // The PM's machine row is gone (removed, or billing ended): the agent path refuses it (store.ts grantHolds).
+ const row = await db.machine.findFirstOrThrow({ where: { machineId: 'owner-mac', userId: owner.sub } })
+ await db.machine.delete({ where: { id: row.id } })
+ try {
+ const first = await s.store.dispatchCrew(s.tab)
+ expect(first.assigned).toBe(0)
+ expect(Object.keys(first.skipped)).toEqual(['HOST_UNAVAILABLE'])
+ expect(await s.holders()).toEqual({ Api: null })
+ // Its PM is not tried again at once, by this pass or the sweep's check.
+ expect(await s.store.dispatchCrew(s.tab)).toEqual({ assigned: 0, skipped: {} })
+ } finally {
+ await db.machine.create({ data: { machineId: 'owner-mac', userId: owner.sub, apiKey: 'fixture-owner-mac', managerId: 'fixture', autonomousEnv: 'prod', authMode: 'remote' } })
+ }
+ // Its access is back, in the same round of the same task: the next try after the short wait assigns it.
+ s.advance(DISPATCH_RETRY_MS)
+ expect(await s.store.dispatchCrew(s.tab)).toMatchObject({ assigned: 1 })
+ expect(await s.holders()).toEqual({ Api: 'Ash' })
+ })
+
+ it('never has a Team-account PM assign a member outside a Team account', async () => {
+ const s = await swarm({ Ash: 'backend' }, { Api: 'backend/src/a.ts' }, false, 'team-mac')
+ // The PM runs in a Harness Team account on its own machine (its record says so); Ash runs in the main account.
+ await editAgent(s.tab, s.pm, agent => ({ ...agent, teamAccount: true }))
+ expect(await s.store.dispatchCrew(s.tab)).toMatchObject({ assigned: 0 })
+ expect(await s.holders()).toEqual({ Api: null })
+ })
+
+ it('assigns once the Swarm resumes, after a pause that came while the pass read GitHub', async () => {
+ const s = await swarm({ Ash: 'backend' }, { Api: 'backend/src/a.ts' })
+ const store = s.store as unknown as { pushOriginFor: (...args: unknown[]) => Promise<unknown> }
+ vi.spyOn(store, 'pushOriginFor').mockImplementationOnce(async () => {
+ await s.execute({ type: 'tab.pause', paused: true })
+ return undefined
+ })
+ expect(await s.store.dispatchCrew(s.tab)).toMatchObject({ assigned: 0 })
+ expect(await s.holders()).toEqual({ Api: null })
+ // Resumed in the same round, with no time passing: the pause left nothing behind.
+ await s.execute({ type: 'tab.pause', paused: false })
+ expect(await s.store.dispatchCrew(s.tab)).toMatchObject({ assigned: 1 })
+ expect(await s.holders()).toEqual({ Api: 'Ash' })
+ })
+
+ it('assigns within the short retry once the repository is approved, and not before it', async () => {
+ const s = await swarm({ Ash: 'backend' }, { Api: 'backend/src/a.ts' })
+ // Ash runs in a Team account, which reaches the repository only through the GitHub App (repositoryReach.ts).
+ await editAgent(s.tab, s.crew.Ash!, agent => ({ ...agent, teamAccount: true }))
+ const store = s.store as unknown as { repositoryReachFor: (...args: unknown[]) => Promise<unknown> }
+ vi.spyOn(store, 'repositoryReachFor').mockResolvedValueOnce({ state: 'not-approved', repository: 'owner/repo' })
+ const refused = await s.store.dispatchCrew(s.tab)
+ expect(refused).toMatchObject({ assigned: 0, skipped: { REPOSITORY_UNREACHABLE: 1 } })
+ // Approved now, in the same round. The pick waits its short retry, then goes.
+ expect(await s.store.dispatchCrew(s.tab)).toEqual({ assigned: 0, skipped: {} })
+ s.advance(DISPATCH_RETRY_MS)
+ expect(await s.store.dispatchCrew(s.tab)).toMatchObject({ assigned: 1 })
+ expect(await s.holders()).toEqual({ Api: 'Ash' })
+ })
+
+ it('does not assign a task postponed while the pass read GitHub', async () => {
+ const s = await swarm({ Ash: 'backend' }, { Api: 'backend/src/a.ts' })
+ // Between the pass's read and its write: a person moves the task to tomorrow.
+ const store = s.store as unknown as { pushOriginFor: (...args: unknown[]) => Promise<unknown> }
+ vi.spyOn(store, 'pushOriginFor').mockImplementationOnce(async () => {
+ await s.execute({ type: 'work.queue', conversationId: s.tasks.Api!, notBefore: '2026-11-07', hold: { kind: 'requester' } })
+ return undefined
+ })
+ await s.store.dispatchCrew(s.tab)
+ expect(await s.holders()).toEqual({ Api: null })
+ })
+
+ it('assigns a task again after it was redefined, not the first round\'s receipt', async () => {
+ const s = await swarm({ Ash: 'backend' }, { Api: 'backend/src/a.ts' })
+ expect(await s.store.dispatchCrew(s.tab)).toMatchObject({ assigned: 1 })
+ const first = (await readGroup(s.tab, s.tasks.Api!)).assignment!.id
+ await s.execute({ type: 'work.status', conversationId: s.tasks.Api!, assignmentId: first, status: 'done', result: 'Shipped at abc1234.' }, s.crew.Ash)
+ await s.execute({ type: 'work.define', conversationId: s.tasks.Api!, checks: [],
+ task: { goal: 'Api, second round.', changes: 'More.', constraints: 'None.', owns: ['backend/src/a.ts'] } })
+ expect(await s.store.dispatchCrew(s.tab)).toMatchObject({ assigned: 1 })
+ const second = (await readGroup(s.tab, s.tasks.Api!)).assignment!
+ expect(second.id).not.toBe(first)
+ expect(second.status).toBe('working')
+ })
+
+ it('skips a task the member may not take (Team-written code, main account) and gives it its next one', async () => {
+ const s = await swarm({ Ash: 'backend' }, { Api: 'backend/src/a.ts', Store: 'backend/src/b.ts' })
+ // Team-written code goes only to a Team account's agent: Ash runs in the main account.
+ await editGroup(s.tab, s.tasks.Api!, group => ({ ...group, teamWritten: true }))
+ const done = await s.store.dispatchCrew(s.tab)
+ expect(done.assigned).toBe(1)
+ expect(await s.holders()).toEqual({ Api: null, Store: 'Ash' })
+ })
+})
diff --git a/backend/src/routes/superTabs.ts b/backend/src/routes/superTabs.ts
index d13adcf82..81a8b4e6e 100644
--- a/backend/src/routes/superTabs.ts
+++ b/backend/src/routes/superTabs.ts
@@ -262,6 +262,9 @@ async function productionStore(github: GitHubTokens | null, approvals: Approvals
return new SuperTabStore(prisma, Date.now, attachmentsFromEnv(env),
// Older history pages and the costs report read the secondaries (lib/prisma.ts, task #2970).
{ replica: prismaSecondary,
+ // Free crew members get their next task from the 30-second sweep and right after the writes that free one (task #3400).
+ // Here, not in the worker: its work.assign reads the GitHub facts this store's hooks below give.
+ dispatch: true,
// Thread replies and tags reach the phones of whoever they tell, while the app is closed (push/send.ts, task #2905).
phoneNotices: notices => { void sendPhoneNotices(prisma, phones, notices) },
// A task that ends revokes the token it was given; a revoke that fails is logged inside and never blocks the write.
diff --git a/backend/src/superTabs/commands.ts b/backend/src/superTabs/commands.ts
index b343d8cc6..b5ab7c313 100644
--- a/backend/src/superTabs/commands.ts
+++ b/backend/src/superTabs/commands.ts
@@ -74,6 +74,7 @@ import { BUILT_IN_HEADING, tidySaved } from './pmSchedule.js'
import { contractRefusal, missingContract } from './taskContract.js'
import { DEFAULT_PRIORITY, PRIORITY_DEFAULTED, TASK_PRIORITIES, priorityLine, proposalPriority, titlePriority, type TaskPriority } from './taskPriority.js'
import { placeAfter, queueSiblings } from './taskQueue.js'
+import { DISPATCH_RULES, laneNamed, pinBuilder, spokenList, stampLane } from './dispatch.js'
const id = z.string().min(1).max(160).regex(/^[A-Za-z0-9_-]+$/)
/** A route override's reason when its agent gave none: following another candidate needs none (project instructions). */
@@ -289,6 +290,8 @@ export const commandSchema = z.discriminatedUnion('type', [
hold: heldReason.optional() }).strict()
.refine(c => c.after !== undefined || c.notBefore !== undefined, 'Give the task a place (after) or a not-before date.')
.refine(c => c.hold === undefined || typeof c.notBefore === 'string', 'A hold reason goes with a not-before date.'),
+ // The lane a task is handed out in (dispatch.ts): one of the lane table's, any case; null for the one its paths choose.
+ z.object({ type: z.literal('work.lane'), conversationId: id, lane: z.string().trim().min(1).max(80).nullable() }).strict(),
// The Lead's record that a request's pull request merged (leaderboard/record.ts recordMerged); `mergedAt` for a backfill.
// `fixes`: the merged PR this one fixes, for its model's fixes after merge (leaderboard/record.ts recordFix).
z.object({ type: z.literal('conversation.merged'), conversationId: id, pullRequestUrl: z.string().max(400).regex(PULL_REQUEST_URL),
@@ -1665,6 +1668,8 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,
const owning = isStep(group) ? state.conversations.find(c => c.id === group.reviewOf) : undefined
if (owning && !owning.agentIds.includes(worker.id) && joinsProject(state, owning, worker.id)) owning.agentIds.push(worker.id)
rememberAttempt(group)
+ // Whoever it was pinned to (dispatch.ts), it is in someone's hands now.
+ delete group.pin
group.assignment = { id: assignmentId, agentId: worker.id, status: 'working', configuration: structuredClone(worker.configuration),
execution: { machineId: worker.machineId, harnessId: worker.harnessId, machineOwnerId: worker.machineOwnerId }, result: null }
renewLease(group.assignment, context.now)
@@ -2513,6 +2518,7 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,
assignment: null, lastMessageSequence: 0,
checks: storedChecks(command.checks, operationId),
})
+ stampLane(state.conversations.at(-1)!)
recordAsked(state.conversations.at(-1)!, requesterId, context.now)
// The reason stands only where nobody is named, and is shown in the task's first row beside its goal.
const noRequester = !requesterId && actor.kind === 'agent' ? command.noRequesterReason : undefined
@@ -2589,6 +2595,19 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,
}
break
}
+ case 'work.lane': {
+ chatOnly(command.conversationId)
+ coordinatorOrPerson(state, actor, command.conversationId)
+ const task = open(state, command.conversationId)
+ if (task.id === groupProject(state, task).leadConversationId || task.kind || task.audience || task.reviewOf) {
+ fail('LANE_TASK_ONLY', 'Only a task has a lane: name a task, not a chat or a step.', 400)
+ }
+ if (command.lane === null) delete task.lane
+ else task.lane = laneNamed(DISPATCH_RULES.lanes, command.lane)
+ ?? fail('LANE_UNKNOWN', `Name a lane: ${spokenList(DISPATCH_RULES.lanes.map(l => l.name))}.`, 400)
+ stampLane(task)
+ break
+ }
case 'work.priority': {
chatOnly(command.conversationId)
coordinatorOrPerson(state, actor, command.conversationId)
@@ -3868,6 +3887,7 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,
group.brief = command.task ? renderWorkTask(command.task) : command.brief!
if (command.task) group.task = command.task
else delete group.task
+ stampLane(group)
group.checks = storedChecks(command.checks, operationId)
message(group.id, group.brief, [], null, SYSTEM_ROW)
bindTaskCard(group, effects.messages.at(-1)!)
@@ -4145,7 +4165,10 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,
if (!command.passed && byAssignee && actor.kind === 'agent' && group.reviewOf) {
const build = state.conversations.find(c => c.id === group.reviewOf)
if (build) changesRequested(state, build, actor.agentId, context.now)
+ // A handed build goes back to its Engineer (handed.ts, #3399); a build nobody holds waits for its builder to fix what the
+ // step found (dispatch.ts). The pin does nothing once the reopen made it active work.
if (build) reopen(build)
+ if (build) pinBuilder(build, 'findings', context.now)
}
if (actor.kind === 'agent') renewOwnTask(state, group, actor.agentId, context.now)
break
diff --git a/backend/src/superTabs/dispatch.test.ts b/backend/src/superTabs/dispatch.test.ts
new file mode 100644
index 000000000..fdddb4ae2
--- /dev/null
+++ b/backend/src/superTabs/dispatch.test.ts
@@ -0,0 +1,397 @@
+import { describe, expect, it } from 'vitest'
+import { applyCommand, commandSchema, type Command, type CommandContext } from './commands.js'
+import { createSuperTab, type Actor, type AgentConfiguration, type Conversation, type MessageDraft } from './model.js'
+import { capacityLine, DISPATCH_RULES, dispatchPlan, freeCrew, laneCapacity, laneOf, nudgeLine, pinBuilder, pullRequestPin, returnReason } from './dispatch.js'
+import type { PullRequestWatch } from './pullRequestEvents.js'
+import { sweepLiveness } from './liveness.js'
+import type { Agent } from './model.js'
+
+/** A lane a crew mark names (crew.ts, #3397). */
+type CrewLane = NonNullable<NonNullable<Agent['crew']>['lane']>
+import { groupView } from './read/views.js'
+
+const NOW = Date.parse('2026-11-05T15:00:00Z')
+
+// Task #3400 (anh Dee's Swarm redesign, 2026-11-05): the server hands a free crew member its next task.
+const owner: Extract<Actor, { kind: 'person' }> = { kind: 'person', userId: 'owner', email: '[email protected]' }
+const config: AgentConfiguration = { engine: 'claude', model: 'test-model', effort: 'high', contextWindow: 200000, engineVersion: 'fixture' }
+const contribution = { machineOwnerId: 'host-owner', contributorId: 'owner' }
+
+/** A Swarm with a PM and the agents [names], all on 'host'; `task` opens a task owning [owns]. */
+export function crewSwarm(names: string[] = []) {
+ let state = createSuperTab('tab', 'Pilot', { id: 'owner', email: owner.email }, 'prod')
+ let sequence = 0
+ const run = (command: Command, actor: Actor = owner, context: Partial<CommandContext> = {}) => {
+ const effects = applyCommand(state, actor, commandSchema.parse(command), { now: 1000, operationId: `op-${++sequence}`, ...context })
+ state = effects.state
+ return effects
+ }
+ const add = (name: string, lead = false) => run({ type: 'agent.add', conversationId: 'lead', machineId: 'host', harnessId: name,
+ name, configuration: config, lead }, owner, { contribution }).result.agentId as string
+ const pm = add('PM', true)
+ const ids = Object.fromEntries(names.map(name => [name, add(name)]))
+ const as = (agentId: string): Actor => ({ kind: 'agent', agentId, machineOwnerId: 'host-owner' })
+ const task = (title: string, owns: string[], extra: Record<string, unknown> = {}) => run({ type: 'conversation.create', title,
+ task: { goal: `${title}.`, changes: 'The change.', constraints: 'None.', owns }, checks: [], ...extra } as Command).result.conversationId as string
+ const group = (id: string): Conversation => state.conversations.find(c => c.id === id)!
+ return { run, add, pm, ids, as, task, group, get state() { return state } }
+}
+
+describe('a task\'s lane', () => {
+ const lanes = DISPATCH_RULES.lanes
+
+ it('is the lane that owns most of its paths, a tie going to the table\'s first', () => {
+ const s = crewSwarm()
+ expect(laneOf(s.group(s.task('Server', ['backend/src/superTabs/x.ts'])), lanes)).toBe('backend')
+ expect(laneOf(s.group(s.task('Board', ['desktop/lib/a.dart', 'backend/src/b.ts', 'desktop/test/c_test.dart'])), lanes)).toBe('Desktop')
+ expect(laneOf(s.group(s.task('Both', ['cli/src/a.ts', 'mobile/lib/b.dart'])), lanes)).toBe('CLI')
+ expect(laneOf(s.group(s.task('Docs', ['docs/plans/'])), lanes)).toBe('docs')
+ expect(laneOf(s.group(s.task('Elsewhere', ['firmware/main.c'])), lanes)).toBeNull()
+ // A path that only starts like a lane's is not in it.
+ expect(laneOf(s.group(s.task('Lookalike', ['backend-tools/run.sh'])), lanes)).toBeNull()
+ })
+
+ it('is the one the PM or a person set, over its paths, and null clears it', () => {
+ const s = crewSwarm()
+ const id = s.task('Server', ['backend/src/x.ts'])
+ s.run({ type: 'work.lane', conversationId: id, lane: 'desktop' }, s.as(s.pm))
+ expect(s.group(id).lane).toBe('Desktop')
+ expect(laneOf(s.group(id), lanes)).toBe('Desktop')
+ s.run({ type: 'work.lane', conversationId: id, lane: 'mobile' })
+ expect(laneOf(s.group(id), lanes)).toBe('mobile')
+ s.run({ type: 'work.lane', conversationId: id, lane: null }, s.as(s.pm))
+ expect(s.group(id)).not.toHaveProperty('lane')
+ expect(laneOf(s.group(id), lanes)).toBe('backend')
+ })
+
+ it('is set by no other agent, and only to a lane of the table, on a task', () => {
+ const s = crewSwarm(['Builder'])
+ const id = s.task('Server', ['backend/src/x.ts'])
+ const before = structuredClone(s.state)
+ expect(() => s.run({ type: 'work.lane', conversationId: id, lane: 'CLI' }, s.as(s.ids.Builder!)))
+ .toThrow(expect.objectContaining({ code: 'COORDINATOR_REQUIRED' }))
+ expect(() => s.run({ type: 'work.lane', conversationId: id, lane: 'firmware' }))
+ .toThrow(expect.objectContaining({ code: 'LANE_UNKNOWN', status: 400, message: 'Name a lane: backend, CLI, Desktop, mobile or docs.' }))
+ expect(() => s.run({ type: 'work.lane', conversationId: 'lead', lane: 'CLI' }))
+ .toThrow(expect.objectContaining({ code: 'LANE_TASK_ONLY', status: 400 }))
+ expect(s.state).toEqual(before)
+ })
+})
+
+describe('what a free crew member gets', () => {
+ /** A crew of [names] (Engineers with no lane unless [lanes] gives one), and four tasks: two backend, one Desktop, one CLI. */
+ function crew(names: string[], lanes: Record<string, CrewLane> = {}) {
+ const s = crewSwarm(names)
+ for (const name of names) {
+ const member = s.state.agents.find(a => a.id === s.ids[name])!
+ member.crew = { role: 'Engineer', ...lanes[name] ? { lane: lanes[name] } : {}, at: 1000, by: 'owner' }
+ }
+ const tasks = { api: s.task('Api', ['backend/src/a.ts']), store: s.task('Store', ['backend/src/b.ts']),
+ board: s.task('Board', ['desktop/lib/c.dart']), hosts: s.task('Hosts', ['cli/src/d.ts']) }
+ const picks = (now = NOW) => dispatchPlan(s.state, 'lead', DISPATCH_RULES, now).map(p => [nameOf(s, p.agentId), titleOf(s, p.conversationId), p.why])
+ return { ...s, tasks, picks, get state() { return s.state } }
+ }
+ const nameOf = (s: ReturnType<typeof crewSwarm>, id: string) => s.state.agents.find(a => a.id === id)!.name
+ const titleOf = (s: ReturnType<typeof crewSwarm>, id: string) => s.group(id).title
+ /** Gives [agentId] [conversationId] in [status], as work.assign and then work.status leave it (written directly, so a test
+ * sets any number of tasks in any status at once). */
+ const holding = (s: ReturnType<typeof crewSwarm>, agentId: string, conversationId: string, status: 'working' | 'review' | 'done' = 'working') => {
+ s.group(conversationId).assignment = { id: `held-${conversationId}`, agentId, status, configuration: config,
+ execution: { machineId: 'host', harnessId: agentId, machineOwnerId: 'host-owner' }, result: null }
+ }
+
+ it('is its lane\'s top task, the queue\'s order, each task to one member', () => {
+ const s = crew(['Ash', 'Birch', 'Cedar'], { Ash: 'backend', Birch: 'backend', Cedar: 'desktop' })
+ expect(s.picks()).toEqual([['Ash', 'Api', 'lane'], ['Birch', 'Store', 'lane'], ['Cedar', 'Board', 'lane']])
+ })
+
+ it('puts a P0 first, wherever the queue has it', () => {
+ const s = crew(['Ash'], { Ash: 'backend' })
+ s.run({ type: 'work.priority', conversationId: s.tasks.store, priority: 'P0' })
+ expect(s.picks()).toEqual([['Ash', 'Store', 'lane']])
+ })
+
+ it('gives a crew Engineer with no lane the project\'s top task, and any other role nothing', () => {
+ const s = crew(['Ash', 'Birch'])
+ s.state.agents.find(a => a.id === s.ids.Birch)!.crew!.role = 'Reviewer'
+ s.run({ type: 'work.queue', conversationId: s.tasks.hosts, after: null })
+ expect(s.picks()).toEqual([['Ash', 'Hosts', 'lane']])
+ })
+
+ it('gives a member its pinned task first, and a pin whose member left the crew goes to the lane', () => {
+ const s = crew(['Ash', 'Birch'], { Ash: 'backend', Birch: 'backend' })
+ s.group(s.tasks.store).pin = { agentId: s.ids.Birch!, why: 'ci', at: 2000 }
+ expect(s.picks()).toEqual([['Ash', 'Api', 'lane'], ['Birch', 'Store', 'pin']])
+ delete s.state.agents.find(a => a.id === s.ids.Birch)!.crew
+ expect(s.picks()).toEqual([['Ash', 'Api', 'lane']])
+ })
+
+ // Merge check of #3230 (ReviewPulse2): main's #3399 frees an Engineer whose task is handed (handed.ts); the dispatch read a
+ // stand-in that counted it busy, so a member with a handed task never got the next one though work.assign would take it.
+ it('counts a member busy while work.assign does: a task in its hands, not a handed one under the limit', () => {
+ const s = crew(['Ash'], { Ash: 'backend' })
+ expect(s.picks()).toEqual([['Ash', 'Api', 'lane']])
+ // One handed task, under the limit of three: Ash is free and gets the lane's next task, which work.assign takes.
+ holding(s, s.ids.Ash!, s.tasks.api, 'review')
+ expect(freeCrew(s.state, 'lead', DISPATCH_RULES, NOW).map(a => a.id)).toEqual([s.ids.Ash])
+ expect(s.picks()).toEqual([['Ash', 'Store', 'lane']])
+ expect(() => s.run({ type: 'work.assign', conversationId: s.tasks.store, agentId: s.ids.Ash! })).not.toThrow()
+ expect(s.group(s.tasks.store).assignment).toMatchObject({ agentId: s.ids.Ash, status: 'working' })
+ })
+
+ it('gives a member with as many handed tasks as the limit nothing new, and one with a task in its hands nothing', () => {
+ const s = crew(['Ash'], { Ash: 'backend' })
+ const more = [s.task('Cache', ['backend/src/e.ts']), s.task('Queue', ['backend/src/f.ts'])]
+ for (const id of [s.tasks.api, ...more].slice(0, DISPATCH_RULES.maxHanded)) holding(s, s.ids.Ash!, id, 'review')
+ expect(freeCrew(s.state, 'lead', DISPATCH_RULES, NOW)).toEqual([])
+ // A finished one counts no more; one in its hands keeps it busy.
+ holding(s, s.ids.Ash!, s.tasks.api, 'done')
+ expect(s.picks()).toEqual([['Ash', 'Store', 'lane']])
+ holding(s, s.ids.Ash!, s.tasks.api, 'working')
+ expect(s.picks()).toEqual([])
+ })
+
+ it('leaves out a pick its caller says to skip (one work.assign refused this round)', () => {
+ const s = crew(['Ash'], { Ash: 'backend' })
+ const skip = (groupId: string, agentId: string) => groupId === s.tasks.api && agentId === s.ids.Ash
+ expect(dispatchPlan(s.state, 'lead', DISPATCH_RULES, NOW, skip).map(p => titleOf(s, p.conversationId))).toEqual(['Store'])
+ })
+
+ it('reads not-before as a day in the project\'s time zone, Vietnam\'s without one', () => {
+ const s = crew(['Ash'], { Ash: 'backend' })
+ const late = Date.parse('2026-11-05T18:00:00Z') // 01:00 on 11-06 in Vietnam
+ s.run({ type: 'work.queue', conversationId: s.tasks.api, notBefore: '2026-11-06', hold: { kind: 'requester' } })
+ expect(dispatchPlan(s.state, 'lead', DISPATCH_RULES, late).map(p => titleOf(s, p.conversationId))).toEqual(['Api'])
+ expect(dispatchPlan(s.state, 'lead', DISPATCH_RULES, late - 2 * 3_600_000).map(p => titleOf(s, p.conversationId))).toEqual(['Store'])
+ })
+
+ it('leaves out the PM, a Buddy, a stopping member, a moving one and an agent not in the crew; an asleep one is free', () => {
+ const s = crew(['Ash', 'Birch', 'Cedar', 'Dune'], { Ash: 'backend', Birch: 'backend', Cedar: 'backend', Dune: 'backend' })
+ const pm = s.state.agents.find(a => a.id === s.pm)!
+ pm.crew = { role: 'PM', at: 1000, by: 'owner' }
+ const agent = (name: string) => s.state.agents.find(a => a.id === s.ids[name])!
+ agent('Ash').workDecision = 'stop'
+ Object.assign(agent('Birch'), { movedTo: { machineId: 'other', at: 2000 } })
+ Object.assign(agent('Cedar'), { asleep: { since: 2000 } })
+ s.add('Elm')
+ expect(freeCrew(s.state, 'lead', DISPATCH_RULES, NOW).map(a => a.name)).toEqual(['Cedar', 'Dune'])
+ })
+
+ it('never picks a step, an archived task, a chat, a finished task or one not to start before a later day', () => {
+ const s = crew(['Ash'], { Ash: 'backend' })
+ s.run({ type: 'conversation.create', title: 'Review', brief: 'Review it.', reviewOf: s.tasks.board, step: 'Review', checks: [] })
+ s.run({ type: 'conversation.archive', conversationId: s.tasks.api, archived: true })
+ s.run({ type: 'work.queue', conversationId: s.tasks.store, notBefore: '2026-11-06', hold: { kind: 'requester' } })
+ expect(s.picks()).toEqual([])
+ s.run({ type: 'work.queue', conversationId: s.tasks.store, notBefore: '2026-11-05', hold: { kind: 'requester' } })
+ expect(s.picks()).toEqual([['Ash', 'Store', 'lane']])
+ holding(s, s.ids.Ash!, s.tasks.store, 'done')
+ expect(s.picks()).toEqual([])
+ })
+
+ it('does not hand a member the task it lost for no progress at once; another member takes it', () => {
+ const s = crew(['Ash', 'Birch'], { Ash: 'backend', Birch: 'desktop' })
+ holding(s, s.ids.Ash!, s.tasks.api)
+ const assignment = s.group(s.tasks.api).assignment!
+ assignment.status = 'lost'
+ assignment.lost = { reason: returnReason('backend'), at: NOW }
+ s.group(s.tasks.api).lostAttempt = { id: assignment.id, agentId: s.ids.Ash!, machineId: 'host', engine: 'claude' }
+ expect(s.picks()).toEqual([['Ash', 'Store', 'lane'], ['Birch', 'Board', 'lane']])
+ s.group(s.tasks.store).lane = 'Desktop'
+ s.group(s.tasks.board).lane = 'backend'
+ expect(s.picks()).toEqual([['Ash', 'Board', 'lane'], ['Birch', 'Store', 'lane']])
+ })
+
+ it('ignores a pin to the member that lost the task for no progress: another member takes it', () => {
+ const s = crew(['Ash', 'Birch'], { Ash: 'backend', Birch: 'backend' })
+ holding(s, s.ids.Ash!, s.tasks.api)
+ const assignment = s.group(s.tasks.api).assignment!
+ assignment.status = 'lost'
+ assignment.lost = { reason: returnReason('backend'), at: NOW }
+ s.group(s.tasks.api).lostAttempt = { id: assignment.id, agentId: s.ids.Ash!, machineId: 'host', engine: 'claude' }
+ // Red CI arrives before the next pass and pins it to Ash, its builder.
+ s.group(s.tasks.api).pin = { agentId: s.ids.Ash!, why: 'ci', at: NOW }
+ expect(s.picks()).toEqual([['Ash', 'Store', 'lane'], ['Birch', 'Api', 'lane']])
+ })
+
+ it('leaves out a member its machine or engine cannot serve now: a usage limit, a model failing, offline, its session stopped', () => {
+ const s = crew(['Ash', 'Birch', 'Cedar', 'Dune', 'Elm'], { Ash: 'backend', Birch: 'backend', Cedar: 'backend', Dune: 'backend', Elm: 'backend' })
+ const agent = (name: string) => s.state.agents.find(a => a.id === s.ids[name])!
+ const report = (receivedAt: number, stopped: string[] = []) => [{ machineId: 'host', name: 'Mac', observation: { receivedAt,
+ runningHarnessIds: s.state.agents.map(a => a.harnessId).filter(h => !stopped.includes(h)), stoppedHarnessIds: stopped } }] as never
+ s.state.machines = report(NOW, ['Dune', 'Elm'])
+ Object.assign(agent('Ash'), { alerting: ['limit'], limitedUntil: new Date(NOW + 3_600_000).toISOString() })
+ Object.assign(agent('Birch'), { alerting: ['model'] })
+ // Dune's session stopped: it is out. Elm's stopped too, but it is asleep on purpose: assigning it wakes it.
+ Object.assign(agent('Elm'), { asleep: { since: NOW - 60_000 } })
+ expect(freeCrew(s.state, 'lead', DISPATCH_RULES, NOW).map(a => a.name)).toEqual(['Cedar', 'Elm'])
+ // A limit that has reset counts no more.
+ expect(freeCrew(s.state, 'lead', DISPATCH_RULES, NOW + 2 * 3_600_000).map(a => a.name)).toEqual([])
+ s.state.machines = report(NOW + 2 * 3_600_000)
+ expect(freeCrew(s.state, 'lead', DISPATCH_RULES, NOW + 2 * 3_600_000).map(a => a.name)).toEqual(['Ash', 'Cedar', 'Dune', 'Elm'])
+ })
+
+ it('hands out nothing while the Swarm is paused', () => {
+ const s = crew(['Ash'], { Ash: 'backend' })
+ s.state.paused = true
+ expect(s.picks()).toEqual([])
+ })
+})
+
+describe('the crew\'s clocks: 2 hours without progress tells the member, 3 hours puts the task back in its lane', () => {
+ const HOUR = 3_600_000, AT = 1000
+ /** Ash (crew, backend) working on Api since AT; Birch (crew, backend) free. */
+ function working() {
+ const s = crewSwarm(['Ash', 'Birch'])
+ for (const name of ['Ash', 'Birch']) s.state.agents.find(a => a.id === s.ids[name])!.crew = { role: 'Engineer', lane: 'backend', at: AT, by: 'owner' }
+ const api = s.task('Api', ['backend/src/a.ts'])
+ s.run({ type: 'work.assign', conversationId: api, agentId: s.ids.Ash! }, s.as(s.pm))
+ /** The liveness sweep at [now], with the machine reporting every session running and busy on screen till then. */
+ const sweep = (now: number) => {
+ s.state.machines = [{ machineId: 'host', name: 'Mac', observation: { runningHarnessIds: s.state.agents.map(a => a.harnessId),
+ stoppedHarnessIds: [], receivedAt: now, harnessProgress: Object.fromEntries(s.state.agents.map(a => [a.harnessId, now])) } }] as never
+ return sweepLiveness(s.state, now)
+ }
+ const lines = (rows: MessageDraft[]) => rows.filter(r => r.conversationId === api && r.recipients.includes(s.ids.Ash!)).map(r => r.text)
+ return { ...s, api, sweep, lines, get state() { return s.state } }
+ }
+
+ it('tells the member once at 2 hours, and again only after a new spell of quiet', () => {
+ const s = working()
+ expect(s.lines(s.sweep(AT + 2 * HOUR - 60_000))).toEqual([])
+ expect(s.lines(s.sweep(AT + 2 * HOUR))).toEqual([nudgeLine('backend')])
+ expect(nudgeLine('backend')).toBe('No progress on this task for 2 hours. Post where it stands, or set it blocked with why; at 3 hours it goes back to the backend lane.')
+ expect(s.lines(s.sweep(AT + 2 * HOUR + 30_000))).toEqual([])
+ expect(s.group(s.api).assignment!.status).toBe('working')
+ // Its own post at 2 h 10 restarts both clocks.
+ s.run({ type: 'message.send', conversationId: s.api, text: 'Halfway: the store is done.', replyTo: null, recipientIds: [] }, s.as(s.ids.Ash!), { now: AT + 2 * HOUR + 10 * 60_000 })
+ expect(s.lines(s.sweep(AT + 3 * HOUR))).toEqual([])
+ expect(s.group(s.api).assignment!.status).toBe('working')
+ expect(s.lines(s.sweep(AT + 4 * HOUR + 10 * 60_000))).toEqual([nudgeLine('backend')])
+ })
+
+ it('returns the task to its lane at 3 hours with the reason, for another member, not the same one', () => {
+ const s = working()
+ s.sweep(AT + 2 * HOUR)
+ s.sweep(AT + 3 * HOUR)
+ const group = s.group(s.api)
+ expect(group.assignment!.status).toBe('lost')
+ expect(group.assignment!.lost!.reason).toBe('no progress for 3 hours: back in the backend lane')
+ expect(dispatchPlan(s.state, 'lead', DISPATCH_RULES, AT + 3 * HOUR).map(p => [p.agentId, p.conversationId])).toEqual([[s.ids.Birch!, s.api]])
+ })
+
+ it('does not tell a member that waits on its own task\'s open step', () => {
+ const s = working()
+ const step = s.run({ type: 'conversation.create', title: 'Test', brief: 'Test it.', reviewOf: s.api, step: 'Test', checks: [] }).result.conversationId as string
+ s.run({ type: 'work.assign', conversationId: step, agentId: s.ids.Birch! }, s.as(s.pm))
+ expect(s.lines(s.sweep(AT + 2 * HOUR))).toEqual([])
+ })
+
+ it('never ticks while it waits on a person or a review, nor for a worker not in the crew', () => {
+ const s = working()
+ s.group(s.api).assignment!.status = 'needs_human'
+ s.sweep(AT + 4 * HOUR)
+ expect(s.group(s.api).assignment!.status).toBe('needs_human')
+ s.group(s.api).assignment!.status = 'review'
+ s.sweep(AT + 5 * HOUR)
+ expect(s.group(s.api).assignment!.status).toBe('review')
+ s.group(s.api).assignment!.status = 'working'
+ delete s.state.agents.find(a => a.id === s.ids.Ash)!.crew
+ expect(s.lines(s.sweep(AT + 6 * HOUR))).toEqual([])
+ expect(s.group(s.api).assignment!.status).toBe('working')
+ })
+})
+
+describe('the capacity line per lane', () => {
+ it('counts each lane\'s waiting and busy tasks and its oldest wait, for the pass\'s log line', () => {
+ const s = crewSwarm(['Ash'])
+ s.state.agents.find(a => a.id === s.ids.Ash)!.crew = { role: 'Engineer', lane: 'desktop', at: 1000, by: 'owner' }
+ const [a, b, c] = [s.task('A', ['desktop/lib/a.dart']), s.task('B', ['desktop/lib/b.dart']), s.task('C', ['desktop/lib/c.dart'])]
+ s.task('Server', ['backend/src/x.ts'])
+ s.run({ type: 'work.priority', conversationId: c, priority: 'P0' })
+ s.run({ type: 'work.assign', conversationId: a, agentId: s.ids.Ash! }, s.as(s.pm))
+ s.group(b).liveness = { state: 'orphaned', why: 'unstarted', since: NOW - 2.5 * 3_600_000 }
+ s.group(c).liveness = { state: 'orphaned', why: 'lost', since: NOW - 3_600_000 }
+ expect(laneCapacity(s.state, 'lead', DISPATCH_RULES)).toEqual([
+ { lane: 'backend', waiting: 1, busy: 0, oldestAt: null },
+ { lane: 'Desktop', waiting: 2, busy: 1, oldestAt: NOW - 2.5 * 3_600_000 },
+ ])
+ const desktop = laneCapacity(s.state, 'lead', DISPATCH_RULES)[1]!
+ expect(capacityLine(desktop, NOW)).toBe('Desktop: 2 waiting, 1 busy, oldest 2 h')
+ expect(capacityLine({ ...desktop, oldestAt: NOW - 25 * 60_000 }, NOW)).toBe('Desktop: 2 waiting, 1 busy, oldest 25 min')
+ expect(capacityLine({ ...desktop, oldestAt: null }, NOW)).toBe('Desktop: 2 waiting, 1 busy')
+ })
+
+ it('reaches readers on each task, as its hand-out lane, so a change read that sends only changed tasks keeps every lane whole', () => {
+ const s = crewSwarm(['Ash'])
+ const server = s.task('Server', ['backend/src/x.ts']), elsewhere = s.task('Elsewhere', ['firmware/main.c'])
+ expect(groupView(s.group(server), new Set())).toMatchObject({ handOutLane: 'backend' })
+ s.run({ type: 'work.lane', conversationId: server, lane: 'docs' })
+ expect(groupView(s.group(server), new Set())).toMatchObject({ handOutLane: 'docs' })
+ expect(groupView(s.group(elsewhere), new Set())).toMatchObject({ handOutLane: null })
+ // A chat or a step has none.
+ expect(groupView(s.group('lead'), new Set())).not.toHaveProperty('handOutLane')
+ const step = s.run({ type: 'conversation.create', title: 'Review', brief: 'Review it.', reviewOf: server, step: 'Review', checks: [] }).result.conversationId as string
+ expect(groupView(s.group(step), new Set())).not.toHaveProperty('handOutLane')
+ })
+})
+
+describe('pins: a task without active work waits for its builder after findings, red CI or a conflict', () => {
+ const watch = (patch: Partial<PullRequestWatch> = {}): PullRequestWatch => ({ url: 'https://github.com/o/r/pull/1', number: 1, state: 'open', draft: false,
+ head: 'abc1234', base: 'main', mergeable: true, checkRuns: [{ name: 'ci/required', status: 'completed', conclusion: 'success', completedAt: 1 }],
+ checkSuites: [], ...patch } as PullRequestWatch)
+
+ it('reads red CI and a conflict from the pull request, and nothing from a green one', () => {
+ expect(pullRequestPin(watch())).toBeNull()
+ expect(pullRequestPin(watch({ mergeable: null }))).toBeNull()
+ expect(pullRequestPin(watch({ checkRuns: [{ name: 'ci/required', status: 'completed', conclusion: 'failure', completedAt: 1 }] }))).toBe('ci')
+ expect(pullRequestPin(watch({ mergeable: false }))).toBe('conflict')
+ })
+
+ /** Ash built Api and lost it; Birch reviews it in a step. */
+ function lostBuild() {
+ const s = crewSwarm(['Ash', 'Birch'])
+ const api = s.task('Api', ['backend/src/a.ts'])
+ s.run({ type: 'work.assign', conversationId: api, agentId: s.ids.Ash! }, s.as(s.pm))
+ const step = s.run({ type: 'conversation.create', title: 'Review', brief: 'Review it.', reviewOf: api, step: 'Review',
+ checks: [{ description: 'It reads right.', independent: true }] }).result.conversationId as string
+ s.run({ type: 'work.assign', conversationId: step, agentId: s.ids.Birch! }, s.as(s.pm))
+ const build = s.group(api), assignment = build.assignment!
+ assignment.status = 'lost'
+ build.lostAttempt = { id: assignment.id, agentId: s.ids.Ash!, machineId: 'host', engine: 'claude' }
+ return { ...s, api, step, get state() { return s.state } }
+ }
+
+ it('pins its builder when a step\'s agent fails the step, and not while the build is in someone\'s hands', () => {
+ const s = lostBuild()
+ const check = s.group(s.step).checks[0]!.id
+ const assignmentId = s.group(s.step).assignment!.id
+ s.run({ type: 'work.check', conversationId: s.step, assignmentId, checkId: check, passed: false, evidence: 'The total is wrong.' }, s.as(s.ids.Birch!), { now: 5000 })
+ expect(s.group(s.api).pin).toEqual({ agentId: s.ids.Ash!, why: 'findings', at: 5000 })
+ // Its next assignment clears it.
+ s.run({ type: 'work.assign', conversationId: s.api, agentId: s.ids.Ash! }, s.as(s.pm))
+ expect(s.group(s.api)).not.toHaveProperty('pin')
+ s.run({ type: 'work.check', conversationId: s.step, assignmentId, checkId: check, passed: false, evidence: 'Still wrong.' }, s.as(s.ids.Birch!), { now: 6000 })
+ expect(s.group(s.api)).not.toHaveProperty('pin')
+ })
+
+ it('pins the agent of its last round, not an older one, when that round was stopped', () => {
+ const s = lostBuild()
+ const build = s.group(s.api)
+ build.assignment = { ...build.assignment!, agentId: s.ids.Birch!, status: 'stopped' }
+ pinBuilder(build, 'ci', 7000)
+ expect(build.pin).toEqual({ agentId: s.ids.Birch!, why: 'ci', at: 7000 })
+ })
+
+ it('pins as pinBuilder says: to the last attempt\'s agent, never over active work', () => {
+ const s = lostBuild()
+ pinBuilder(s.group(s.api), 'ci', 7000)
+ expect(s.group(s.api).pin).toEqual({ agentId: s.ids.Ash!, why: 'ci', at: 7000 })
+ // An older pin keeps its time: it has waited longer.
+ pinBuilder(s.group(s.api), 'conflict', 8000)
+ expect(s.group(s.api).pin).toEqual({ agentId: s.ids.Ash!, why: 'ci', at: 7000 })
+ const fresh = s.group(s.task('Fresh', ['backend/src/f.ts']))
+ pinBuilder(fresh, 'ci', 9000)
+ expect(fresh).not.toHaveProperty('pin')
+ })
+})
diff --git a/backend/src/superTabs/dispatch.ts b/backend/src/superTabs/dispatch.ts
new file mode 100644
index 000000000..dddaa23e1
--- /dev/null
+++ b/backend/src/superTabs/dispatch.ts
@@ -0,0 +1,239 @@
+/**
+ * The Swarm hands the next task to a free crew member by itself (task #3400, anh Dee's Swarm redesign, 2026-11-05: the
+ * server does the routine). What it decides is here, from the state alone: each task's lane, who of the crew is free, what
+ * each free member gets, the two clocks and the capacity line. The store's pass (store.ts dispatchCrew) sends each pick
+ * through work.assign, whose own write refuses a second assignment.
+ */
+import { isBuddy } from './buddies.js'
+import { sessionClosed } from './closedAgents.js'
+import { activeWork, handed, occupiesAgent, type Agent, type Assignment, type Conversation, type SuperTabState } from './model.js'
+import { agentProjectId, onTeamAccount, projectOf, projectsOf } from './projects.js'
+import { barredFromTeamWritten } from './teamWritten.js'
+import { digestOf, localNow } from './digest.js'
+import { DEFAULT_TIME_ZONE } from './costs/reflection.js'
+import { queueOrder, queueSiblings } from './taskQueue.js'
+import { unavailableReason } from './liveness.js'
+import { FAILED, type PullRequestWatch } from './pullRequestEvents.js'
+
+const HOUR_MS = 3_600_000
+
+/** A lane of work and the repository paths it owns: the project rules record's `lanes` entry (#3393), the same shape. */
+export interface Lane { name: string; owns: readonly string[] }
+
+/** The numbers of the dispatch, in one place until the project rules record (#3393) holds them. */
+export const DISPATCH_RULES = Object.freeze({
+ /** How often the worker's pass runs; commits that free a member or open a task run it at once too. */
+ everyMs: 30_000,
+ /** A member with this many handed tasks (ready for review, still its own) takes no new one. */
+ maxHanded: 3,
+ /** Without progress this long, the member is told once. */
+ nudgeAfterMs: 2 * HOUR_MS,
+ /** Without progress this long, the task goes back to its lane. */
+ returnAfterMs: 3 * HOUR_MS,
+ lanes: Object.freeze([
+ { name: 'backend', owns: ['backend/'] },
+ { name: 'CLI', owns: ['cli/'] },
+ { name: 'Desktop', owns: ['desktop/'] },
+ { name: 'mobile', owns: ['mobile/'] },
+ { name: 'docs', owns: ['docs/'] },
+ ] as readonly Lane[]),
+})
+export type DispatchRules = typeof DISPATCH_RULES
+
+/** The lane [name] means, matched in any case, as the table writes it; undefined when the table has none by that name. */
+export function laneNamed(lanes: readonly Lane[], name: string): string | undefined {
+ return lanes.find(lane => lane.name.toLowerCase() === name.trim().toLowerCase())?.name
+}
+
+/** Stores [group]'s hand-out lane, when it is a task (not a chat, a step or a private chat), after its paths or lane changed:
+ * readers copy it (read/views.ts groupView), no read computes it. */
+export function stampLane(group: Conversation): void {
+ if (group.task && !group.reviewOf && !group.kind && !group.audience) group.handOutLane = laneOf(group, DISPATCH_RULES.lanes)
+ else delete group.handOutLane
+}
+
+/** "a, b or c": the lane names as a refusal lists them. */
+export function spokenList(names: readonly string[]): string {
+ return names.length <= 1 ? names.join('') : `${names.slice(0, -1).join(', ')} or ${names.at(-1)}`
+}
+
+/** Whether [path] lies under [area]: an area ending in '/' is a folder, any other names one path and what is under it. */
+const under = (path: string, area: string): boolean => {
+ const folder = area.endsWith('/') ? area : `${area}/`
+ return path === area || path.startsWith(folder)
+}
+
+/** The lane [group]'s task is handed out in: the one its PM or a person set (work.lane), else the lane owning most of its
+ * owned paths, a tie going to the table's first; null when no lane owns any of them. */
+export function laneOf(group: Pick<Conversation, 'lane' | 'task'>, lanes: readonly Lane[]): string | null {
+ if (group.lane) return laneNamed(lanes, group.lane) ?? group.lane
+ let best: string | null = null, most = 0
+ for (const lane of lanes) {
+ const count = (group.task?.owns ?? []).filter(path => lane.owns.some(area => under(path.replace(/^\.?\//, ''), area))).length
+ if (count > most) { best = lane.name; most = count }
+ }
+ return best
+}
+
+/** The reason the 3-hour clock gives a task it puts back in its lane (liveness.ts); the dispatch reads it to keep that task
+ * from its last member for one pass. */
+export const returnReason = (lane: string | null): string => `no progress for 3 hours: back in the ${lane ?? 'project'} lane`
+const RETURN_PREFIX = 'no progress for 3 hours'
+
+/** What a crew member hears after 2 hours without progress on its task. */
+export const nudgeLine = (lane: string | null): string =>
+ `No progress on this task for 2 hours. Post where it stands, or set it blocked with why; at 3 hours it goes back to the ${lane ?? 'project'} lane.`
+
+/** The crew's clocks on [assignment] of [group], held by [worker] (liveness.ts): from its own last progress (its assignment,
+ * status, check or post: `progressAt`), only while a crew member is working on a task. `nudge` after `nudgeAfterMs`, once
+ * per spell of quiet; `return` after `returnAfterMs`. Waiting on a person, blocked or handed: no clock. */
+export function crewClock(group: Conversation, worker: Agent, assignment: Assignment, now: number, rules: DispatchRules): 'nudge' | 'return' | null {
+ const since = assignment.progressAt
+ if (!worker.crew || group.reviewOf || assignment.status !== 'working' || since === undefined) return null
+ if (now - since >= rules.returnAfterMs) return 'return'
+ return now - since >= rules.nudgeAfterMs && !(assignment.nudgedAt !== undefined && assignment.nudgedAt >= since) ? 'nudge' : null
+}
+
+/** Moving off a failing machine (task #3398, crewMove.ts): work.assign refuses it until the move lands. Read without a type
+ * until #3398 declares it, as #3397 does. */
+const moving = (agent: Agent): boolean => !!(agent as { movedTo?: unknown }).movedTo
+/** Asleep (task #3398, crewSleep.ts): its session closed on purpose; work.assign wakes it in the same write. */
+const asleep = (agent: Agent): boolean => !!(agent as { asleep?: unknown }).asleep
+
+/** The crew of [projectId] free for a task: crew members (not its PM, not a Buddy, not stopping or moving, a session not
+ * closed unless asleep, no launch still pending) with nothing in their hands and fewer than `maxHanded` handed tasks;
+ * fewest handed first, then as the roster lists them. */
+export function freeCrew(state: SuperTabState, projectId: string, rules: DispatchRules, now: number): Agent[] {
+ const leads = new Set(state.conversations.flatMap(c => c.leadId ? [c.leadId] : []))
+ const handedBy = new Map<string, number>(), busy = new Set<string>()
+ for (const group of state.conversations) {
+ const holder = group.assignment?.agentId
+ if (!holder) continue
+ if (occupiesAgent(group)) busy.add(holder)
+ else if (activeWork(group) && handed(group)) handedBy.set(holder, (handedBy.get(holder) ?? 0) + 1)
+ }
+ // A PM in a Harness Team account assigns only agents of its own machine or another Team account (store.ts teamCommand,
+ // security review 2 of #2089): the main account stays out of its reach.
+ const leadId = state.conversations.find(c => c.id === projectOf(state, projectId).leadConversationId)?.leadId
+ const lead = leadId ? state.agents.find(a => a.id === leadId) : undefined
+ const reachable = (agent: Agent) => !lead || !onTeamAccount(state, lead) || agent.machineId === lead.machineId || onTeamAccount(state, agent)
+ const launching = (agent: Agent) => !!state.starts?.some(s => !s.poolSettled && s.poolGeneration && s.request.machineId === agent.machineId && s.harnessId === agent.harnessId)
+ return state.agents
+ .filter(agent => !!agent.crew && agentProjectId(state, agent) === projectId && !leads.has(agent.id) && !isBuddy(agent)
+ && agent.workDecision !== 'stop' && !moving(agent) && (asleep(agent) || !sessionClosed(state, agent, now)) && !launching(agent)
+ && !busy.has(agent.id) && (handedBy.get(agent.id) ?? 0) < rules.maxHanded && reachable(agent)
+ // A member its machine or engine cannot serve now would lose the task at once (liveness.ts): until that clears.
+ && !unavailableReason(state, agent, now, asleep(agent)))
+ .map((agent, at) => ({ agent, at, handed: handedBy.get(agent.id) ?? 0 }))
+ .sort((a, b) => a.handed - b.handed || a.at - b.at)
+ .map(entry => entry.agent)
+}
+
+/** The open tasks of [projectId] a member may be handed, in the order they go out: a task (not its chat, a Buddy chat, a
+ * private chat or a step) with a brief, no active work, not finished, whose not-before day has come; P0 first, then the
+ * project's Next up. */
+export function openTasks(state: SuperTabState, projectId: string, now: number): Conversation[] {
+ const project = projectOf(state, projectId)
+ // The day people meant: the project's own (its digest's time zone), Vietnam's without one, as the PM schedule reads it.
+ const today = localNow(digestOf(project)?.timeZone ?? DEFAULT_TIME_ZONE, now).date
+ const open = queueSiblings(state, project).filter(group => (group.task || group.brief.trim())
+ && !activeWork(group) && !['done', 'cancelled'].includes(group.assignment?.status ?? '') && !(group.notBefore && group.notBefore > today))
+ const ordered = queueOrder(open)
+ return [...ordered.filter(g => g.priority === 'P0'), ...ordered.filter(g => g.priority !== 'P0')]
+}
+
+/** Whether [member] takes work in [lane]: its own lane, or any for a crew Engineer with none. */
+function takes(member: Agent, lane: string | null, rules: DispatchRules): boolean {
+ const own = member.crew?.lane
+ if (own) return lane !== null && laneNamed(rules.lanes, own) === lane
+ return /^engineer$/i.test(member.crew?.role.trim() ?? '')
+}
+
+/** The tasks [member] could be handed now, best first: those pinned to it (oldest pin first), then its lane's open tasks.
+ * A task it just lost to the 3-hour clock is not offered to it. */
+export function candidatesFor(state: SuperTabState, member: Agent, rules: DispatchRules, now: number, open = openTasks(state, agentProjectId(state, member)!, now),
+ skip: Skip = () => false) {
+ const lostByIt = (group: Conversation) => group.lostAttempt?.agentId === member.id && lostToClock(group)
+ const pinned = open.filter(g => pinOf(g)?.agentId === member.id).sort((a, b) => pinOf(a)!.at - pinOf(b)!.at)
+ const crewIds = new Set(state.agents.filter(a => a.crew).map(a => a.id))
+ const lane = open.filter(g => !pinned.includes(g) && !(pinOf(g) && crewIds.has(pinOf(g)!.agentId)) && !lostByIt(g)
+ && takes(member, laneOf(g, rules.lanes), rules))
+ // Team-written code goes to Team accounts only (teamWritten.ts); a pick refused this round is not sent again (store.ts).
+ const allowed = (group: Conversation) => !barredFromTeamWritten(state, group, member) && !skip(group.id, member.id)
+ return [...pinned.filter(allowed).map(group => ({ group, why: 'pin' as const })), ...lane.filter(allowed).map(group => ({ group, why: 'lane' as const }))]
+}
+
+/** Lost to the 3-hour clock: its last member gets it not again at once (review 1 of #3230's plan, Review Focus). */
+const lostToClock = (group: Conversation): boolean => group.assignment?.status === 'lost' && !!group.assignment.lost?.reason.startsWith(RETURN_PREFIX)
+/** [group]'s pin, unless it names the member that just lost it to the clock: then it goes to the lane (review 2 of #3230). */
+const pinOf = (group: Conversation): Conversation['pin'] =>
+ group.pin && !(lostToClock(group) && group.lostAttempt?.agentId === group.pin.agentId) ? group.pin : undefined
+
+/** A pick the caller leaves out: one whose work.assign was refused this round (store.ts dispatchCrew). */
+export type Skip = (conversationId: string, agentId: string) => boolean
+
+/** The round a task is in, for its dispatch's operation id and refusal memory: its last assignment's, kept across a
+ * redefinition (its run ledger), so a new round never replays the last one's receipt. */
+export const roundOf = (group: Conversation): string => group.ledger?.runs?.at(-1)?.assignmentId ?? group.assignment?.id ?? 'first'
+
+/** One assignment the dispatch makes. */
+export interface DispatchPick { conversationId: string; agentId: string; why: 'pin' | 'lane'; lane: string | null }
+
+/** What each free crew member of [projectId] gets in one pass: its first candidate no other member took first. Nothing while
+ * the Swarm is paused. */
+export function dispatchPlan(state: SuperTabState, projectId: string, rules: DispatchRules, now: number, skip: Skip = () => false): DispatchPick[] {
+ if (state.paused) return []
+ const open = openTasks(state, projectId, now), taken = new Set<string>(), picks: DispatchPick[] = []
+ for (const member of freeCrew(state, projectId, rules, now)) {
+ const next = candidatesFor(state, member, rules, now, open, skip).find(c => !taken.has(c.group.id))
+ if (!next) continue
+ taken.add(next.group.id)
+ picks.push({ conversationId: next.group.id, agentId: member.id, why: next.why, lane: laneOf(next.group, rules.lanes) })
+ }
+ return picks
+}
+
+/** One lane's line of the capacity read: its waiting tasks (open, nobody's, in hand-out order), how many of its tasks are in
+ * someone's hands, and since when the longest-waiting one has waited (null when no wait was recorded). */
+export interface LaneCapacity { lane: string; waiting: number; busy: number; oldestAt: number | null }
+
+/** When [group] began waiting with nobody holding it: as its liveness recorded, else when its last attempt was lost. */
+const waitingSince = (group: Conversation): number | undefined =>
+ group.liveness?.state === 'orphaned' ? group.liveness.since : group.assignment?.lost?.at
+
+/** [projectId]'s lanes as the dispatch sees them, in the table's order, each with work waiting or in hand. A time, not an age,
+ * so the read's summary does not move as the clock does (read/derivedEtag.ts). */
+export function laneCapacity(state: SuperTabState, projectId: string, rules: DispatchRules, now = Date.now()): LaneCapacity[] {
+ const open = openTasks(state, projectId, now)
+ const project = projectOf(state, projectId)
+ const busy = queueSiblings(state, project).filter(occupiesAgent)
+ return rules.lanes.flatMap(({ name }) => {
+ const waiting = open.filter(g => laneOf(g, rules.lanes) === name)
+ const inHand = busy.filter(g => laneOf(g, rules.lanes) === name).length
+ if (!waiting.length && !inHand) return []
+ const since = waiting.map(waitingSince).filter((t): t is number => t !== undefined)
+ return [{ lane: name, waiting: waiting.length, busy: inHand, oldestAt: since.length ? Math.min(...since) : null }]
+ })
+}
+
+/** "Desktop: 6 waiting, 2 busy, oldest 2 h" (under an hour in minutes; no oldest when none was recorded). */
+export function capacityLine(c: LaneCapacity, now: number): string {
+ const age = c.oldestAt === null ? null : Math.max(0, now - c.oldestAt)
+ const oldest = age === null ? '' : age >= HOUR_MS ? `, oldest ${Math.floor(age / HOUR_MS)} h` : `, oldest ${Math.floor(age / 60_000)} min`
+ return `${c.lane}: ${c.waiting} waiting, ${c.busy} busy${oldest}`
+}
+
+/** What [watch] says its task's builder should come back for: a merge conflict, or a failed check run at its head. */
+export function pullRequestPin(watch: Pick<PullRequestWatch, 'mergeable' | 'checkRuns'>): 'ci' | 'conflict' | null {
+ if (watch.mergeable === false) return 'conflict'
+ return watch.checkRuns.some(run => !!run.conclusion && FAILED.has(run.conclusion)) ? 'ci' : null
+}
+
+/** Pins [group], a task with no active work, to its last attempt's agent for [why]: the dispatch hands it to that member
+ * first, while it is in the crew (candidatesFor). A pin already there keeps its time; active work is never pinned. */
+export function pinBuilder(group: Conversation, why: NonNullable<Conversation['pin']>['why'], now: number): void {
+ // Its last round's agent: a stopped round's, not an older lost one's.
+ const builder = group.assignment?.agentId ?? group.lostAttempt?.agentId
+ if (!builder || activeWork(group) || group.pin) return
+ group.pin = { agentId: builder, why, at: now }
+}
diff --git a/backend/src/superTabs/dispatchRefusals.test.ts b/backend/src/superTabs/dispatchRefusals.test.ts
new file mode 100644
index 000000000..1c753b4b5
--- /dev/null
+++ b/backend/src/superTabs/dispatchRefusals.test.ts
@@ -0,0 +1,27 @@
+import { describe, expect, it } from 'vitest'
+import { RefusalMemory } from './dispatchRefusals.js'
+
+// The crew dispatch's memory of refused picks (store.ts dispatchCrew, review 2 of #3230): bounded, and expired entries go
+// whether or not their task is ever looked at again.
+describe('the dispatch\'s refusal memory', () => {
+ it('forgets an entry at its expiry, whether or not the same pick is asked about again', () => {
+ const memory = new RefusalMemory(100)
+ memory.remember('tab:task-a:round-1:ash', 1_000)
+ memory.remember('tab:task-b:round-1:ash', 5_000)
+ expect(memory.refused('tab:task-a:round-1:ash', 999)).toBe(true)
+ // The task moved to another round: its old key is never asked about again, and still goes.
+ memory.prune(1_000)
+ expect(memory.size).toBe(1)
+ expect(memory.refused('tab:task-a:round-1:ash', 999)).toBe(false)
+ expect(memory.refused('tab:task-b:round-1:ash', 4_999)).toBe(true)
+ expect(memory.refused('tab:task-b:round-1:ash', 5_000)).toBe(false)
+ })
+
+ it('holds at most its limit, forgetting the oldest first', () => {
+ const memory = new RefusalMemory(3)
+ for (const key of ['a', 'b', 'c', 'd']) memory.remember(key, 10_000)
+ expect(memory.size).toBe(3)
+ expect(memory.refused('a', 0)).toBe(false)
+ expect(['b', 'c', 'd'].every(key => memory.refused(key, 0))).toBe(true)
+ })
+})
diff --git a/backend/src/superTabs/dispatchRefusals.ts b/backend/src/superTabs/dispatchRefusals.ts
new file mode 100644
index 000000000..c59f0f7f6
--- /dev/null
+++ b/backend/src/superTabs/dispatchRefusals.ts
@@ -0,0 +1,30 @@
+/**
+ * Picks of the crew dispatch whose work.assign was refused for a reason their round will not change (store.ts dispatchCrew,
+ * task #3400): neither a pass nor the sweep's check sends one again until it expires (review 1 of #3230). Per process, in
+ * memory, never stored. Its lifecycle (review 2 of #3230): an entry goes at its expiry, on the next prune (every pass), whether
+ * or not its task is looked at again; at most `limit` are held, the oldest forgotten first.
+ */
+export class RefusalMemory {
+ private readonly until = new Map<string, number>()
+ constructor(private readonly limit: number) {}
+
+ get size(): number { return this.until.size }
+
+ /** Remembers [key] until [expiresAt]; at the limit, forgets the oldest entry first. */
+ remember(key: string, expiresAt: number): void {
+ this.until.delete(key)
+ while (this.until.size >= this.limit) this.until.delete(this.until.keys().next().value!)
+ this.until.set(key, expiresAt)
+ }
+
+ /** Whether [key] is remembered at [now]. */
+ refused(key: string, now: number): boolean {
+ const until = this.until.get(key)
+ return until !== undefined && until > now
+ }
+
+ /** Forgets every entry expired at [now]. */
+ prune(now: number): void {
+ for (const [key, until] of this.until) if (until <= now) this.until.delete(key)
+ }
+}
diff --git a/backend/src/superTabs/liveness.ts b/backend/src/superTabs/liveness.ts
index 2e63170d2..f3f359e47 100644
--- a/backend/src/superTabs/liveness.ts
+++ b/backend/src/superTabs/liveness.ts
@@ -16,6 +16,7 @@ import { coordinatorNameOf } from './instructions.js'
import { waitedOn } from './leaderboard/record.js'
import { isStep } from './steps.js'
import { endedReply } from './taskLine.js'
+import { crewClock, DISPATCH_RULES, laneOf, nudgeLine, returnReason } from './dispatch.js'
import { handed, pickUp, unclaimedAt, unclaimedReason } from './handed.js'
// Work never sits with a dead owner (design: "A Swarm that never stops", 2026-10-26). A worker's active assignment is held
@@ -316,23 +317,35 @@ const reopening = (worker: Agent, now: number): boolean => {
return isCrew(worker) && !away.asleep && !away.movedTo && !!worker.downSince && now - Date.parse(worker.downSince) < CREW_REOPEN_GRACE_MS
}
-/** Why a worker has lost its task now, or null while it still holds it. Only a machine that has reported can be offline. */
-function lostReason(state: SuperTabState, group: Conversation, worker: Agent, assignment: Assignment, now: number, steps: StepIndex): string | null {
- // A handed task waits on its Reviewers and CI, not on its Engineer, which may be down or at work elsewhere (task #3399).
- if (handed(group)) return null
+/** Why [worker] cannot work now: its session stopped (unless [closedOnPurpose]: asleep, task #3398; or, for a task it
+ * [holds], a crew member its host is reopening, crew.ts), its machine offline, a usage limit, or its model failing. A task
+ * its agent holds is lost for it (lostReason); the crew dispatch hands such a member nothing new (dispatch.ts freeCrew).
+ * Only a machine that has reported can be offline. */
+export function unavailableReason(state: SuperTabState, worker: Agent, now: number, closedOnPurpose = false, holds = false): string | null {
const pool = state.machines?.find(m => m.machineId === worker.machineId)
- // A crew member's host reopens its session in place (crew.ts): it keeps its task for the reopen's grace.
- if (pool?.observation?.stoppedHarnessIds.includes(worker.harnessId) && !reopening(worker, now)) return sessionStopped(pool.name)
+ if (!closedOnPurpose && pool?.observation?.stoppedHarnessIds.includes(worker.harnessId) && !(holds && reopening(worker, now))) return sessionStopped(pool.name)
if (pool?.observation && now - pool.observation.receivedAt > OFFLINE_LOST_MS) return machineOffline(pool.name)
const limited = limitReason(worker, now)
if (limited) return limited
// Its host alerts only after ten minutes of retries without an answer (cli superTabs/terminal.ts MODEL_WAIT_MS), so a
// short burst of failures that recovers never gets here.
if (worker.alerting?.includes('model')) return 'its model keeps failing'
+ return null
+}
+
+/** Why a worker has lost its task now, or null while it still holds it. */
+function lostReason(state: SuperTabState, group: Conversation, worker: Agent, assignment: Assignment, now: number, steps: StepIndex): string | null {
+ // A handed task waits on its Reviewers and CI, not on its Engineer, which may be down or at work elsewhere (task #3399).
+ if (handed(group)) return null
+ // A crew member its host is reopening keeps its task for the reopen's grace (crew.ts).
+ const gone = unavailableReason(state, worker, now, false, true)
+ if (gone) return gone
// Back with its Engineer and not picked up in time: anyone free in the lane takes it (handed.ts, #3399).
const unclaimed = unclaimedReason(assignment, now)
if (unclaimed) return unclaimed
if (waitingForReview(assignment) || waitingForRevision(state, group) || waitingOnSteps(state, group, steps) || waitingOnPerson(state, group, worker, assignment)) return null
+ // A crew member 3 hours without progress of its own puts its task back in its lane (task #3400), however busy its screen.
+ if (crewClock(group, worker, assignment, now, DISPATCH_RULES) === 'return') return returnReason(laneOf(group, DISPATCH_RULES.lanes))
const end = leaseEnd(group, assignment, reportRenewedAt(state, worker))
if (end !== undefined && now > end) {
const progress = lastProgress(state, worker, assignment)
@@ -370,6 +383,26 @@ function loseTask(state: SuperTabState, group: Conversation, worker: Agent, reas
...endedReply(state, group, stableId('task-line-lost', assignment.id, loss), sender)]
}
+/** The crew members 2 hours without progress on their task hear it once in the task, from its PM (dispatch.ts crewClock). */
+function crewNudges(state: SuperTabState, now: number): MessageDraft[] {
+ // Most Swarms have no crew: one pass over the agents, nothing else. Then one pass over the work, the step index only for a
+ // task whose line is due (a measured 25% on the sweep at 2,000 tasks when it walked every task twice).
+ const crew = new Map(state.agents.filter(a => a.crew).map(a => [a.id, a]))
+ if (!crew.size) return []
+ let steps: StepIndex | undefined
+ return state.conversations.flatMap(group => {
+ const assignment = group.assignment, worker = assignment && crew.get(assignment.agentId)
+ if (!worker || !activeWork(group) || crewClock(group, worker, assignment, now, DISPATCH_RULES) !== 'nudge') return []
+ if (state.conversations.some(c => c.leadId === worker.id)) return []
+ steps ??= stepIndex(state)
+ // Waiting on others is no lack of progress: the waits that stop a loss stop the line too (lostReason).
+ if (waitingForReview(assignment) || waitingForRevision(state, group) || waitingOnSteps(state, group, steps) || waitingOnPerson(state, group, worker, assignment)) return []
+ assignment.nudgedAt = now
+ return [reachable(state, { id: stableId('crew-nudge', assignment.id, String(now)), conversationId: group.id, author: writtenBy(state, leadOf(state, worker) ?? worker),
+ replyTo: null, recipients: [worker.id], text: nudgeLine(laneOf(group, DISPATCH_RULES.lanes)), source: { kind: 'crew-nudge', assignmentId: assignment.id } })]
+ })
+}
+
/** Loses at once the tasks of the workers `which` picks that have a reason now: an agent that just reported a usage limit,
* the agents of a machine that just reported. A task lost to that limit resumes at `resumeAt` when its screen said when the
* limit resets (the host types into the same session then, cli superTabs/limitResume.ts). */
@@ -418,7 +451,7 @@ function leadNotice(state: SuperTabState, start: AgentStart, text: string | null
/** The time checks, run on the Lead's poll and on any machine's report: every worker task with a reason is lost, and
* every start dispatched over 3 minutes ago that is not running fails, unless its machine is still preparing it. */
export function sweepLiveness(state: SuperTabState, now: number): MessageDraft[] {
- const drafts = [...loseTasks(state, now), ...failStalledStarts(state, now), ...unpurged(state, now), ...staleSwitches(state, now), ...staleModelRequests(state, now)]
+ const drafts = [...loseTasks(state, now), ...crewNudges(state, now), ...failStalledStarts(state, now), ...unpurged(state, now), ...staleSwitches(state, now), ...staleModelRequests(state, now)]
// A Buddy start that timed out may have been the last on its Buddy-only machine (security review 1 of #2234).
dropIdleBuddyMachines(state, now)
return drafts
diff --git a/backend/src/superTabs/mergeTrain/config.ts b/backend/src/superTabs/mergeTrain/config.ts
index 92b626ed9..1dba73a34 100644
--- a/backend/src/superTabs/mergeTrain/config.ts
+++ b/backend/src/superTabs/mergeTrain/config.ts
@@ -1,9 +1,7 @@
/**
- * The merge train's numbers (task #3402), in one place until the project rules record (task #3393) holds them: the train is
- * off until a project switches it on (River, 2026-11-05: merging someone's repository by itself would surprise them), and
- * runs every 10 minutes once on.
+ * The merge train's fixed numbers (task #3402). Its switch, interval and the reads a change needs are the project's rules
+ * record (superTabs/policy.ts, task #3475): edited by people without a release, shared with the review steps.
*/
-export const TRAIN_DEFAULTS = Object.freeze({ enabled: false, everyMinutes: 10 })
/** Branches the train builds batches on. Nothing else in a repository may use this prefix. */
export const TRAIN_BRANCH_PREFIX = 'harness-train/'
@@ -23,20 +21,3 @@ export const TRAIN_PROJECTS = 50
export const FAST_LANE: readonly RegExp[] = [/^docs\//, /\.md$/i]
/** Paths the train's token may not change (it has no `workflows` permission): GitHub would refuse the merge. */
export const NOT_MERGEABLE_BY_TOKEN = /^\.github\/workflows\//
-
-/**
- * Where each area of the review table lives in the repository, by the table's own area names (task #3393's seed). Until the
- * table maps its areas to paths, these patterns do; they err wide, as a pull request that needs one more read than it got
- * only waits, and one merged with too few cannot be taken back (River, 2026-11-05: fail closed on the review table).
- */
-export const REVIEW_AREAS: ReadonlyArray<{ area: string; paths: RegExp }> = [
- { area: 'Sign-in', paths: /(^|\/)(auth|login|sign_?in|signin|session)[^/]*$|^backend\/src\/middlewares\//i },
- { area: 'Tokens', paths: /token|^backend\/src\/github\//i },
- { area: 'Encryption', paths: /crypt|cipher|secret|credential|key(s|chain)?\b/i },
- { area: 'Access', paths: /access|permission|audience|membership/i },
- { area: 'Buddy guard', paths: /guard/i },
- { area: 'Device links', paths: /device|harness_?links|pairing|join_?link/i },
- { area: 'Deletion', paths: /purge|delet|cleanup|sweep|prune/i },
-]
-/** Reads an area above needs while the project has no review table. */
-export const SECURITY_READS = 2
diff --git a/backend/src/superTabs/mergeTrain/plan.test.ts b/backend/src/superTabs/mergeTrain/plan.test.ts
index b770a762e..231534792 100644
--- a/backend/src/superTabs/mergeTrain/plan.test.ts
+++ b/backend/src/superTabs/mergeTrain/plan.test.ts
@@ -1,7 +1,7 @@
import { describe, expect, it } from 'vitest'
import type { Check, Conversation } from '../model.js'
-import { componentOf, eligible, headReads, laneOf, requiredReads, splitRed, type TrainCandidate, type TrainTask } from './plan.js'
-import { TRAIN_DEFAULTS } from './config.js'
+import { componentOf, eligible, headReads, laneOf, splitRed, type TrainCandidate, type TrainTask } from './plan.js'
+import { requiredReads, SEED_RULES } from '../policy.js'
const URL = 'https://github.com/acme/app/pull/7'
const HEAD = 'a'.repeat(40), OLD = 'b'.repeat(40)
@@ -134,23 +134,20 @@ describe('lanes and components', () => {
})
})
-describe('requiredReads', () => {
+// The train's reads come from the project rules record (policy.ts, task #3475); its seed asks what the train's own table did.
+describe('requiredReads, from the rules record\'s seed', () => {
it('asks the default for ordinary paths and two for the security areas, failing closed', () => {
- expect(requiredReads(['backend/src/superTabs/cards.ts'])).toBe(1)
- expect(requiredReads(['backend/src/github/tokens.ts'])).toBe(2)
- expect(requiredReads(['backend/src/routes/auth.ts', 'docs/a.md'])).toBe(2)
- expect(requiredReads(['backend/src/superTabs/purge.ts'])).toBe(2)
- expect(requiredReads(['desktop/lib/super_tabs/buddy_guard.dart'])).toBe(2)
- })
- it('takes the reads from the rules record when it names the area, never fewer than the default', () => {
- const reviews = { defaultReads: 1, rows: [{ area: 'Tokens', reads: 3 }] }
- expect(requiredReads(['backend/src/github/tokens.ts'], reviews)).toBe(3)
- expect(requiredReads(['backend/src/superTabs/cards.ts'], { defaultReads: 2, rows: [] })).toBe(2)
+ expect(requiredReads(SEED_RULES, ['backend/src/superTabs/cards.ts'])).toBe(1)
+ expect(requiredReads(SEED_RULES, ['backend/src/github/tokens.ts'])).toBe(2)
+ expect(requiredReads(SEED_RULES, ['backend/src/routes/auth.ts', 'docs/a.md'])).toBe(2)
+ expect(requiredReads(SEED_RULES, ['backend/src/superTabs/purge.ts'])).toBe(2)
+ expect(requiredReads(SEED_RULES, ['desktop/lib/super_tabs/buddy_guard.dart'])).toBe(2)
+ expect(requiredReads(SEED_RULES, null)).toBe(2)
})
})
-describe('config', () => {
+describe('the rules record\'s seed for the train', () => {
it('is off until a project switches it on, every 10 minutes', () => {
- expect(TRAIN_DEFAULTS).toEqual({ enabled: false, everyMinutes: 10 })
+ expect(SEED_RULES.mergeTrain).toEqual({ enabled: false, everyMinutes: 10 })
})
})
diff --git a/backend/src/superTabs/mergeTrain/plan.ts b/backend/src/superTabs/mergeTrain/plan.ts
index ca985e03b..83f85eebe 100644
--- a/backend/src/superTabs/mergeTrain/plan.ts
+++ b/backend/src/superTabs/mergeTrain/plan.ts
@@ -4,7 +4,7 @@
* be taken back, and one that waits a pass costs ten minutes.
*/
import type { Check, CheckVerdict, Conversation } from '../model.js'
-import { FAST_LANE, REVIEW_AREAS, SECURITY_READS, TRAIN_HOLD_LABELS } from './config.js'
+import { FAST_LANE, TRAIN_HOLD_LABELS } from './config.js'
/** A pull request as the train reads it from GitHub this pass. */
export interface TrainCandidate {
@@ -83,21 +83,6 @@ export function headReads(task: TrainTask, url: string, head: string): number |
return reviewed ? readers.size : null
}
-/** The review table's part the train reads (task #3393 rules.reviews). */
-export interface ReviewTable { defaultReads: number; rows: Array<{ area: string; reads: number }> }
-
-/** The reads [files] need: the most any area they touch asks, never fewer than the default. Without a table, each security
- * area needs [SECURITY_READS]. */
-export function requiredReads(files: readonly string[], reviews?: ReviewTable): number {
- let reads = reviews?.defaultReads ?? 1
- for (const { area, paths } of REVIEW_AREAS) {
- if (!files.some(file => paths.test(file))) continue
- const row = reviews?.rows.find(r => r.area.toLowerCase() === area.toLowerCase())
- reads = Math.max(reads, reviews ? row?.reads ?? reviews.defaultReads : SECURITY_READS)
- }
- return reads
-}
-
export type Ineligible = 'closed' | 'draft' | 'base' | 'hold' | 'ci' | 'mergeable' | 'conflict' | 'verdict' | 'reads'
/** Whether [candidate] may join a batch, given its [reads] at its head (headReads) and the reads its files need. */
diff --git a/backend/src/superTabs/mergeTrain/rulesRecord.test.ts b/backend/src/superTabs/mergeTrain/rulesRecord.test.ts
new file mode 100644
index 000000000..8268e731e
--- /dev/null
+++ b/backend/src/superTabs/mergeTrain/rulesRecord.test.ts
@@ -0,0 +1,151 @@
+/**
+ * Task #3475 (anh Dee's Swarm redesign): the merge train reads the project rules record (policy.ts, task #3393) for the reads
+ * a change needs and for its switch and interval, so one rules edit changes both the review steps and what the train waits
+ * for. With no saved record the seed applies; a record that cannot be read holds the project.
+ */
+import { describe, expect, it } from 'vitest'
+import type { Check, Conversation } from '../model.js'
+import { requiredReads, SEED_RULES, type ProjectRules } from '../policy.js'
+import type { TrainProject } from '../store.js'
+import { fakeTrainGitHub, type FakePull } from './fakeTrainGitHub.js'
+import type { TrainTask } from './plan.js'
+import { recordTrainRules, runMergeTrain, type MergeTrainDeps } from './run.js'
+import { newTrainMemory, trainPass, type TrainSwarm, type TrainTaskPull } from './train.js'
+
+const MINUTE = 60_000
+
+/** A task whose review step passed at [head] of [url], once by each of [reviewers]. */
+function approvedTask(url: string, head: string, reviewers: string[]): TrainTask {
+ const check = (by: string): Check => ({ id: `c-${by}`, description: 'Review', independent: true, evidence: 'ok', passedBy: by,
+ verdicts: [{ by, passed: true, evidence: 'ok', at: 1, pullRequest: url, head, patch: `patch-${head}` }] as unknown as Check['verdicts'] })
+ return {
+ checks: [],
+ pullRequestHeads: { [url]: { head, patch: `patch-${head}`, at: 1 } },
+ steps: reviewers.map(by => ({ step: 'Review', title: 'Review', archived: false, checks: [check(by)], assignment: { status: 'done' } as Conversation['assignment'] })),
+ }
+}
+
+/** One pass over a pull request changing [files], approved by [reads] reviewers, with [rules]: whether the train batched it. */
+async function batched(rules: ProjectRules, files: string[], reads: number): Promise<{ batched: boolean; told: string[] }> {
+ const repo = fakeTrainGitHub(), memory = newTrainMemory()
+ const tasks = new Map<string, TrainTaskPull>(), told: string[] = []
+ const swarm: TrainSwarm = {
+ async pulls() { return [...tasks.values()] },
+ async merged() {},
+ async tell(_taskId, _url, _key, text) { told.push(text) },
+ }
+ const pull: FakePull = repo.addPull(7, files)
+ tasks.set('task-7', { taskId: 'task-7', url: pull.url, task: approvedTask(pull.url, pull.head, Array.from({ length: reads }, (_, i) => `agent:r${i}`)) })
+ await trainPass({ projectId: 'p1', github: repo.github, swarm, memory, now: Date.UTC(2026, 10, 6, 4), rules: { enabled: true, rules } })
+ return { batched: repo.batches().length === 1, told }
+}
+
+/** The seed with one more area: three reads on payments code. */
+const PAYMENTS: ProjectRules = { ...structuredClone(SEED_RULES), reviews: { ...structuredClone(SEED_RULES.reviews),
+ rows: [...structuredClone(SEED_RULES.reviews.rows), { area: 'Payments', reads: 3, paths: ['**/payments/**'] }] } }
+
+describe('the merge train reads the project rules record', () => {
+ it('waits for the reads a saved rules record asks: a new area changes what it takes', async () => {
+ const files = ['backend/src/payments/charge.ts']
+ // The seed has no payments area: one read is enough.
+ expect((await batched(SEED_RULES, files, 1)).batched).toBe(true)
+ // The saved record asks three: two are not enough, and the Engineer is told how many.
+ const short = await batched(PAYMENTS, files, 2)
+ expect(short.batched).toBe(false)
+ expect(short.told.join('\n')).toContain('needs 3 passed reviews')
+ expect((await batched(PAYMENTS, files, 3)).batched).toBe(true)
+ })
+
+ // River, 11-06: a saved record can raise a security area, never lower it below two reads (policy.ts floor).
+ it('never merges a security change on one read, whatever a saved record says', async () => {
+ const one = { ...structuredClone(SEED_RULES), reviews: { ...structuredClone(SEED_RULES.reviews),
+ rows: SEED_RULES.reviews.rows.map(row => ({ ...row, reads: 1 })) } }
+ for (const file of ['backend/src/github/tokens.ts', 'backend/src/lib/deviceRevoke.ts', 'backend/src/superTabs/ruleGuard.ts']) {
+ expect((await batched(one, [file], 1)).batched, file).toBe(false)
+ expect((await batched(one, [file], 2)).batched, file).toBe(true)
+ }
+ })
+
+ // The train batches a change exactly when it has the reads the record's requiredReads gives, for the seed and a saved record,
+ // over every kind of change. The review steps (task #3401, not on main yet) are to plan with the same requiredReads; this
+ // pins the train to that function, not to the review steps' own code (review of #3250).
+ it('requires the same reads as the review steps for the same files', async () => {
+ const changes = [
+ ['backend/src/superTabs/cards.ts'],
+ ['backend/src/github/tokens.ts'],
+ ['backend/src/lib/ssoAuth.ts', 'desktop/lib/a.dart'],
+ ['backend/src/superTabs/purge.ts'],
+ ['mobile/lib/e2ee/box.dart'],
+ ['backend/src/payments/charge.ts', 'backend/src/superTabs/cards.ts'],
+ ['desktop/test/a_test.dart'],
+ ['backend/src/superTabs/latests/x.ts'],
+ ]
+ for (const rules of [SEED_RULES, PAYMENTS]) {
+ for (const files of changes) {
+ const needed = requiredReads(rules, files)
+ expect((await batched(rules, files, needed - 1)).batched, `${files} with ${needed - 1}`).toBe(false)
+ expect((await batched(rules, files, needed)).batched, `${files} with ${needed}`).toBe(true)
+ }
+ }
+ })
+})
+
+describe('the merge train reads each project\'s record', () => {
+ const project: TrainProject = { tabId: 't1', projectId: 'p1', ownerId: 'o1', autonomousEnv: 'prod', repositoryUrl: 'https://github.com/acme/app', pulls: [] }
+ const row = (rules: ProjectRules) => ({ revision: 4, rules })
+ /** A database whose newest saved rules row is [answer] (null: none), or whose read fails. */
+ const db = (answer: ReturnType<typeof row> | null | Error) => ({
+ superTabProjectRules: { findFirst: async () => { if (answer instanceof Error) throw answer; return answer } },
+ }) as unknown as Parameters<typeof recordTrainRules>[0]
+ function deps(rules: MergeTrainDeps['rules']) {
+ const calls: string[] = []
+ const value: MergeTrainDeps = {
+ store: { trainProjects: async () => [project], trainMerged: async () => {}, trainTell: async () => true },
+ app: {
+ installation: async () => { calls.push('installation'); return 7 },
+ createToken: async () => { calls.push('token'); return { token: 'ghs_x', expiresAt: '2030-01-01T00:00:00Z' } },
+ installationCall: async (_token, method, path) => {
+ calls.push(`${method} ${path}`)
+ if (path.endsWith('/git/ref/heads/main')) return { status: 200, body: { ref: 'refs/heads/main', object: { type: 'commit', sha: 'c'.repeat(40) } } }
+ if (path.includes('/pulls?')) return { status: 200, body: [] }
+ return { status: 404, body: {} }
+ },
+ revoke: async () => { calls.push('revoke') },
+ },
+ approved: async () => true,
+ rules,
+ }
+ return { value, calls }
+ }
+
+ it('applies the seed with no saved record: the train is off and reads nothing', async () => {
+ const { value, calls } = deps(recordTrainRules(db(null)))
+ expect(await runMergeTrain(value, new Map(), 1_000_000)).toBe(0)
+ expect(calls).toEqual([])
+ })
+
+ it('runs on a saved record\'s switch, at its interval', async () => {
+ const on = { ...structuredClone(SEED_RULES), mergeTrain: { enabled: true, everyMinutes: 30 } }
+ const { value } = deps(recordTrainRules(db(row(on))))
+ const memories = new Map(), start = 100 * MINUTE
+ expect(await runMergeTrain(value, memories, start)).toBe(1)
+ expect(await runMergeTrain(value, memories, start + 20 * MINUTE)).toBe(0)
+ expect(await runMergeTrain(value, memories, start + 30 * MINUTE)).toBe(1)
+ })
+
+ // SecAlder's security review of #3250: a saved row with no read count read as one read, failing open.
+ it('holds a project whose saved record does not pass the schema: a broken row never reads as fewer reads', async () => {
+ const broken = { ...structuredClone(SEED_RULES), mergeTrain: { enabled: true, everyMinutes: 10 },
+ reviews: { ...structuredClone(SEED_RULES.reviews), rows: [{ area: 'Tokens', paths: ['**/*token*'] }] } } as unknown as ProjectRules
+ const { value, calls } = deps(recordTrainRules(db(row(broken))))
+ expect(await runMergeTrain(value, new Map(), 100 * MINUTE)).toBe(0)
+ expect(calls).toEqual([])
+ await expect(recordTrainRules(db(row(broken)))('t1', 'p1')).rejects.toThrow()
+ })
+
+ it('holds a project whose record cannot be read: nothing read from GitHub, never the seed\'s numbers instead', async () => {
+ const { value, calls } = deps(recordTrainRules(db(new Error('database unavailable'))))
+ expect(await runMergeTrain(value, new Map(), 1_000_000)).toBe(0)
+ expect(calls).toEqual([])
+ })
+})
diff --git a/backend/src/superTabs/mergeTrain/run.test.ts b/backend/src/superTabs/mergeTrain/run.test.ts
index 0d16e5249..5ddb77fbc 100644
--- a/backend/src/superTabs/mergeTrain/run.test.ts
+++ b/backend/src/superTabs/mergeTrain/run.test.ts
@@ -1,6 +1,10 @@
import { describe, expect, it } from 'vitest'
import type { TrainProject } from '../store.js'
import { runMergeTrain, type MergeTrainDeps, type TrainMemories } from './run.js'
+import { SEED_RULES } from '../policy.js'
+
+const OFF = async () => ({ enabled: false, everyMinutes: 10, rules: SEED_RULES })
+const ON = async () => ({ enabled: true, everyMinutes: 10, rules: SEED_RULES })
const project: TrainProject = { tabId: 't1', projectId: 'p1', ownerId: 'o1', autonomousEnv: 'prod', repositoryUrl: 'https://github.com/acme/app', pulls: [] }
@@ -20,6 +24,7 @@ function deps(over: Partial<MergeTrainDeps> = {}) {
revoke: async () => { calls.push('revoke') },
},
approved: async () => true,
+ rules: OFF,
...over,
}
return { value, calls }
@@ -33,7 +38,7 @@ describe('running the merge train', () => {
})
it('runs a switched-on project once per interval, with one token revoked after', async () => {
- const { value, calls } = deps({ rules: async () => ({ enabled: true, everyMinutes: 10 }) })
+ const { value, calls } = deps({ rules: ON })
const memories: TrainMemories = new Map()
expect(await runMergeTrain(value, memories, 1_000_000)).toBe(1)
expect(calls.filter(c => c === 'token' || c === 'revoke')).toEqual(['token', 'revoke'])
@@ -42,7 +47,7 @@ describe('running the merge train', () => {
})
it('skips a repository not approved for the project', async () => {
- const { value, calls } = deps({ rules: async () => ({ enabled: true, everyMinutes: 10 }), approved: async () => false })
+ const { value, calls } = deps({ rules: ON, approved: async () => false })
expect(await runMergeTrain(value, new Map(), 1_000_000)).toBe(0)
expect(calls).toEqual([])
})
diff --git a/backend/src/superTabs/mergeTrain/run.ts b/backend/src/superTabs/mergeTrain/run.ts
index 9c8eeb84f..a32dcc47d 100644
--- a/backend/src/superTabs/mergeTrain/run.ts
+++ b/backend/src/superTabs/mergeTrain/run.ts
@@ -1,7 +1,7 @@
/**
* Runs the merge train (train.ts) in the singleton worker: every minute it looks at the projects with tasks that link pull
- * requests, and runs a pass for each whose train is switched on and whose interval has passed. The switch and the interval
- * are the project's rules (task #3393); until that record lands they are [TRAIN_DEFAULTS], off.
+ * requests, and runs a pass for each whose train is switched on and whose interval has passed. The switch, the interval and
+ * the reads a change needs are the project's rules record (policy.ts, task #3475): the seed, off, until a project saves one.
*
* A project runs only where its repository may get the app's tokens at all: the app installed there, and approved for the
* project wherever approval is asked (github/approvals.ts), as an agent's token would be.
@@ -11,21 +11,26 @@ import { githubRepository } from '../../github/repository.js'
import { repositoryTrain } from '../../github/train.js'
import { logger } from '../../utils/logger.js'
import type { SuperTabStore, TrainProject } from '../store.js'
-import { TRAIN_DEFAULTS } from './config.js'
-import type { ReviewTable } from './plan.js'
+import type { ProjectRules } from '../policy.js'
+import { currentRules } from '../policyStore.js'
import { newTrainMemory, trainPass, type TrainMemory } from './train.js'
-export interface ProjectTrainRules { enabled: boolean; everyMinutes: number; reviews?: ReviewTable }
+export interface ProjectTrainRules { enabled: boolean; everyMinutes: number; rules: ProjectRules }
export type TrainRulesReader = (tabId: string, projectId: string) => Promise<ProjectTrainRules>
-/** Until the project rules record lands (task #3393): the defaults, off for every project. */
-export const defaultTrainRules: TrainRulesReader = async () => ({ ...TRAIN_DEFAULTS })
+/** Each project's rules record as it is now (policyStore.ts currentRules): the seed, off, when it saved none. A record that
+ * cannot be read throws, and the run skips that project: never the seed's numbers in place of a saved record. */
+export const recordTrainRules = (db: Parameters<typeof currentRules>[0]): TrainRulesReader => async (tabId, projectId) => {
+ const { rules } = await currentRules(db, tabId, projectId)
+ return { enabled: rules.mergeTrain.enabled, everyMinutes: rules.mergeTrain.everyMinutes, rules }
+}
export interface MergeTrainDeps {
store: Pick<SuperTabStore, 'trainProjects' | 'trainMerged' | 'trainTell'>
app: Pick<GitHubApp, 'installation' | 'createToken' | 'installationCall' | 'revoke'>
/** Whether [repository] may get the app's tokens for this project. */
approved: (project: TrainProject, repository: string) => Promise<boolean>
- rules?: TrainRulesReader
+ /** Each project's rules: its record (recordTrainRules). */
+ rules: TrainRulesReader
}
/** What a worker keeps per project between runs: its train's memory and when it last ran. */
@@ -33,7 +38,7 @@ export type TrainMemories = Map<string, { memory: TrainMemory; ranAt: number }>
/** One run over every project. The passes that ran. */
export async function runMergeTrain(deps: MergeTrainDeps, memories: TrainMemories, now: number): Promise<number> {
- const rules = deps.rules ?? defaultTrainRules
+ const rules = deps.rules
let ran = 0
for (const project of await deps.store.trainProjects(now)) {
const key = `${project.tabId}:${project.projectId}`
diff --git a/backend/src/superTabs/mergeTrain/train.test.ts b/backend/src/superTabs/mergeTrain/train.test.ts
index b430cc6c5..9ca70dde2 100644
--- a/backend/src/superTabs/mergeTrain/train.test.ts
+++ b/backend/src/superTabs/mergeTrain/train.test.ts
@@ -2,10 +2,11 @@ import { describe, expect, it } from 'vitest'
import type { Check, Conversation } from '../model.js'
import { fakeTrainGitHub, type FakePull } from './fakeTrainGitHub.js'
import type { TrainTask } from './plan.js'
-import { newTrainMemory, trainPass, type TrainSwarm, type TrainTaskPull } from './train.js'
+import { newTrainMemory, trainPass, type TrainRules, type TrainSwarm, type TrainTaskPull } from './train.js'
+import { SEED_RULES } from '../policy.js'
const MINUTE = 60_000
-const ON = { enabled: true }
+const ON: TrainRules = { enabled: true, rules: SEED_RULES }
/** A task whose one review step passed at [head] of [url]. */
function approvedTask(url: string, head: string, reviewers = ['agent:reviewer']): TrainTask {
@@ -37,7 +38,7 @@ function fakeSwarm() {
const setup = () => {
const repo = fakeTrainGitHub(), swarm = fakeSwarm(), memory = newTrainMemory()
let now = Date.UTC(2026, 10, 5, 15)
- const pass = (rules: { enabled: boolean } = ON) => trainPass({ projectId: 'p1', github: repo.github, swarm: swarm.swarm, memory, now: (now += 10 * MINUTE), rules })
+ const pass = (rules: TrainRules = ON) => trainPass({ projectId: 'p1', github: repo.github, swarm: swarm.swarm, memory, now: (now += 10 * MINUTE), rules })
return { repo, swarm, memory, pass }
}
@@ -377,7 +378,7 @@ describe('the merge train finishes batches', () => {
const batch = repo.batches()[0]!
repo.state.ci.set(batch.head, 'success')
const before = { reads: repo.state.reads.length, writes: repo.state.writes.length }
- expect(await pass({ enabled: false })).toEqual({ off: true })
+ expect(await pass({ enabled: false, rules: SEED_RULES })).toEqual({ off: true })
expect({ reads: repo.state.reads.length, writes: repo.state.writes.length }).toEqual(before)
expect(repo.batches()).toEqual([batch])
})
diff --git a/backend/src/superTabs/mergeTrain/train.ts b/backend/src/superTabs/mergeTrain/train.ts
index eb03832cf..ec5ec2e1a 100644
--- a/backend/src/superTabs/mergeTrain/train.ts
+++ b/backend/src/superTabs/mergeTrain/train.ts
@@ -14,7 +14,8 @@
*/
import { TrainReadError, type TrainGitHub, type TrainPull } from '../../github/train.js'
import { NOT_MERGEABLE_BY_TOKEN, TRAIN_BRANCH_PREFIX, TRAIN_CI_TIMEOUT_MS, TRAIN_MAX_BATCH } from './config.js'
-import { eligible, headReads, laneOf, requiredReads, splitRed, type Ineligible, type ReviewTable, type TrainTask } from './plan.js'
+import { eligible, headReads, laneOf, splitRed, type Ineligible, type TrainTask } from './plan.js'
+import { requiredReads, type ProjectRules } from '../policy.js'
/** A task's linked pull request, as the Swarm holds it: what headReads reads. */
export interface TrainTaskPull { taskId: string; url: string; task: TrainTask }
@@ -37,7 +38,8 @@ interface Batch { number: number; url: string; branch: string; tip: string; base
export interface TrainMemory { batches: Map<number, Batch>; failed: Set<string>; splits: string[][] }
export const newTrainMemory = (): TrainMemory => ({ batches: new Map(), failed: new Set(), splits: [] })
-export interface TrainRules { enabled: boolean; reviews?: ReviewTable }
+/** The project's rules record as this pass read it: its switch, and the review table its reads come from (policy.ts). */
+export interface TrainRules { enabled: boolean; rules: ProjectRules }
export type TrainPassLine = { off: true } | { candidates: number; unreadable: number; built: number; merged: number; split: number; closed: number; refused: number; unrecorded: number }
const short = (sha: string) => sha.slice(0, 12)
@@ -73,7 +75,7 @@ export async function trainPass(input: { projectId: string; github: TrainGitHub;
const pull = await github.pull(number)
if (pull.state !== 'open' || pull.url.toLowerCase() !== linked.url.toLowerCase() || pull.headRef.startsWith(TRAIN_BRANCH_PREFIX)) return null
const files = await github.files(number), ciRequired = await github.ciRequired(pull.head)
- const reads = headReads(linked.task, linked.url, pull.head), required = requiredReads(files, rules.reviews)
+ const reads = headReads(linked.task, linked.url, pull.head), required = requiredReads(rules.rules, files)
const verdict = eligible({ url: linked.url, number, head: pull.head, state: pull.state, draft: pull.draft, base: pull.base, mergeable: pull.mergeable,
labels: pull.labels, files, ciRequired }, reads, required)
return { member: { number, url: linked.url, head: pull.head, title: pull.title, files, taskId: linked.taskId }, verdict, reads, required, lane: laneOf(files) }
diff --git a/backend/src/superTabs/model.ts b/backend/src/superTabs/model.ts
index 46fcb61b4..f41f4919b 100644
--- a/backend/src/superTabs/model.ts
+++ b/backend/src/superTabs/model.ts
@@ -277,6 +277,8 @@ export interface Assignment {
leaseUntil?: number
/** Its agent's last progress the lease saw, for the Lead's wake-up when it is lost. */
progressAt?: number
+ /** When its crew member was told it had been 2 hours without progress (dispatch.ts crewClock): once per quiet spell. */
+ nudgedAt?: number
/** While it needs a human: the person its agent asked (work.status with ask), whom its wait names (liveness.ts). */
askedOf?: string
/** While it is blocked or needs a human: why it waits (heldReason.ts). Absent on a hold from before reasons. */
@@ -444,6 +446,15 @@ export interface Conversation {
/** How urgent its task is (taskPriority.ts), set by conversation.create and work.priority. Absent on a step, a chat and a task
* from before priorities, which reads as P2. */
priority?: import('./taskPriority.js').TaskPriority
+ /** The lane its PM or a person put it in (dispatch.ts laneOf), set by work.lane, as the lane table writes it. Absent: its
+ * owned paths choose. */
+ lane?: string
+ /** Its lane as the dispatch hands it out (dispatch.ts laneOf), stored when its paths or lane change (stampLane), so reads
+ * only copy it. Absent on a chat, a step, and a task from before; null when no lane owns its paths. */
+ handOutLane?: string | null
+ /** The member it waits for, without active work (dispatch.ts): its builder, after another agent's failed check, red CI or a
+ * merge conflict. The next assignment clears it. */
+ pin?: { agentId: string; why: 'findings' | 'ci' | 'conflict'; at: number }
/** What its project's PM owes here (pulse.ts): people's messages that reached it, not answered, reacted to or made a task
* yet, at most MAX_OWED. Bookkeeping: readers get it counted in the pulse, never this list. */
owed?: import('./pulse.js').OwedAsk[]
@@ -676,6 +687,8 @@ export const NOTICE_READERS = {
// The Lead's wakes and requests, and the worker's "moved" line (liveness.ts, tidy.ts, projectUpdates.ts, digest.ts); two
// projects changing the same code, to both their Leads in the Leads chat (commands.ts).
'work-stalled': 'recipients', 'work-lost': 'recipients', 'work-resumed': 'recipients', 'idle-stop': 'recipients',
+ // A crew member's 2 hours without progress on its task, to that member (dispatch.ts crewClock, liveness.ts).
+ 'crew-nudge': 'recipients',
// An agent with no open task for 15 minutes, and a grid attempt's failed first review, told to the coordinator (tidy.ts
// idleNotices, commands.ts work.check; project instructions, phase 4). `idle-stop` rows are from before.
idle: 'recipients', 'review-failed': 'recipients',
diff --git a/backend/src/superTabs/parts/light.test.ts b/backend/src/superTabs/parts/light.test.ts
index ccabbc7ae..76f068f24 100644
--- a/backend/src/superTabs/parts/light.test.ts
+++ b/backend/src/superTabs/parts/light.test.ts
@@ -8,7 +8,7 @@ import { FINISHED, GROUP_FIELDS } from './light.js'
* here, and the test below until light.ts either projects it or names it as unread by reads (review of #1745). */
const assignment: Required<Assignment> = {
id: 'w', agentId: 'a', status: 'working', configuration: { engine: 'codex', model: null, effort: null, contextWindow: null, engineVersion: null },
- execution: { machineId: 'm', harnessId: 'h', machineOwnerId: 'o' }, result: null, recordingProgress: { at: 1, revision: 1 }, leaseUntil: 1, progressAt: 1, askedOf: 'p', hold: { kind: 'requester' }, reviewFoundAt: 1, changesRequestedAt: 1, toldEngineerAt: 1,
+ execution: { machineId: 'm', harnessId: 'h', machineOwnerId: 'o' }, result: null, recordingProgress: { at: 1, revision: 1 }, leaseUntil: 1, progressAt: 1, nudgedAt: 1, askedOf: 'p', hold: { kind: 'requester' }, reviewFoundAt: 1, changesRequestedAt: 1, toldEngineerAt: 1,
reopened: { at: 1, why: 'r' }, handoffs: 1, verdicts: [{ by: 'agent:r', passed: true, handoff: 1, review: 'g' }], lost: { reason: 'r', at: 1 },
}
const conversation: Required<Conversation> = {
@@ -16,7 +16,7 @@ const conversation: Required<Conversation> = {
task: { goal: '', changes: '', constraints: '', owns: [] }, reviewOf: 'r', teamWritten: true, teamWrittenBy: { kind: 'assigned' }, step: 'Review', reviewStamp: { assignmentId: 'w', handoff: 1 }, checks: [], assignment, lastMessageSequence: 0, lastMainSequence: 0, lastPersonSequence: 0, heardAt: 0, pullRequestUrls: [], pullRequestEvents: {}, cards: {},
messageSeq: 0, reportSeq: 0, dormant: false, lastActivityAt: '', audience: { people: [] }, lostAttempt: { id: 'w', agentId: 'a' }, reactionSeq: 0,
requesterId: 'p', ledger: {}, proposals: [], buddyName: 'Sparky', buddySessions: [], buddyDownTold: true, liveness: { state: 'quiet', why: 'silent', since: 1 }, leadAction: { kind: 'post', at: 1 },
- stepUp: { attempt: 2, floor: 2, reason: 'r', at: 1, carry: '' }, queueRank: 1.5, notBefore: '2026-12-04', hold: { kind: 'requester' }, priority: 'P0', owed: [], pulse: {} as never,
+ stepUp: { attempt: 2, floor: 2, reason: 'r', at: 1, carry: '' }, queueRank: 1.5, notBefore: '2026-12-04', hold: { kind: 'requester' }, priority: 'P0', lane: 'Desktop', handOutLane: 'Desktop', pin: { agentId: 'a', why: 'ci', at: 1 }, owed: [], pulse: {} as never,
}
describe('the light conversation projection (parts/light.ts)', () => {
diff --git a/backend/src/superTabs/parts/light.ts b/backend/src/superTabs/parts/light.ts
index bcf865b0b..d551d918c 100644
--- a/backend/src/superTabs/parts/light.ts
+++ b/backend/src/superTabs/parts/light.ts
@@ -28,8 +28,8 @@ export const GROUP_FIELDS = {
always: ['id', 'kind', 'projectId', 'leadId', 'agentIds', 'archived', 'audience', 'dormant', 'assignment.id', 'assignment.agentId', 'assignment.status',
'assignment.lost', 'reviewOf', 'pulse'],
whenRunning: ['title', 'task.owns', 'assignment.execution', 'assignment.result'],
- unread: ['number', 'brief', 'teamWritten', 'teamWrittenBy', 'step', 'reviewStamp', 'checks', 'lastMessageSequence', 'lastMainSequence', 'lastPersonSequence', 'heardAt', 'pullRequestUrls', 'pullRequestEvents', 'cards', 'messageSeq', 'reportSeq', 'lastActivityAt', 'lostAttempt', 'requesterId', 'ledger', 'reactionSeq', 'proposals', 'buddyName', 'buddySessions', 'buddyDownTold', 'liveness', 'leadAction', 'stepUp', 'queueRank', 'notBefore', 'hold', 'priority', 'owed',
- 'assignment.configuration', 'assignment.recordingProgress', 'assignment.leaseUntil', 'assignment.progressAt', 'assignment.askedOf', 'assignment.hold', 'assignment.reviewFoundAt', 'assignment.changesRequestedAt', 'assignment.toldEngineerAt',
+ unread: ['number', 'brief', 'teamWritten', 'teamWrittenBy', 'step', 'reviewStamp', 'checks', 'lastMessageSequence', 'lastMainSequence', 'lastPersonSequence', 'heardAt', 'pullRequestUrls', 'pullRequestEvents', 'cards', 'messageSeq', 'reportSeq', 'lastActivityAt', 'lostAttempt', 'requesterId', 'ledger', 'reactionSeq', 'proposals', 'buddyName', 'buddySessions', 'buddyDownTold', 'liveness', 'leadAction', 'stepUp', 'queueRank', 'notBefore', 'hold', 'priority', 'owed', 'lane', 'handOutLane', 'pin',
+ 'assignment.configuration', 'assignment.recordingProgress', 'assignment.leaseUntil', 'assignment.progressAt', 'assignment.nudgedAt', 'assignment.askedOf', 'assignment.hold', 'assignment.reviewFoundAt', 'assignment.changesRequestedAt', 'assignment.toldEngineerAt',
'assignment.reopened', 'assignment.handoffs', 'assignment.verdicts'],
} as const
const LIGHT_GROUP = {
diff --git a/backend/src/superTabs/parts/touches.ts b/backend/src/superTabs/parts/touches.ts
index 2126d09ad..b9058be75 100644
--- a/backend/src/superTabs/parts/touches.ts
+++ b/backend/src/superTabs/parts/touches.ts
@@ -117,6 +117,7 @@ export function touchesFor(command: Command, actor: Actor, before: SuperTabState
break
// Whether an agent may change a priority is whether it is still its project's PM (commands.ts coordinatorOrPerson).
case 'work.priority':
+ case 'work.lane':
leadCheck(projectOfGroup(command.conversationId)?.id)
break
case 'conversation.requester':
diff --git a/backend/src/superTabs/policy.securityExclusions.json b/backend/src/superTabs/policy.securityExclusions.json
new file mode 100644
index 000000000..009f292a1
--- /dev/null
+++ b/backend/src/superTabs/policy.securityExclusions.json
@@ -0,0 +1,160 @@
+{
+ "description": "Files the merge train's old matcher held at two reads that the seed's security areas leave at one, on purpose (task #3475, River, SecAlder and ReviewLinnea, review of #3250). policy.test.ts fails on any other file the old matcher held that drops to one read. Whole classes dropped by rule are in the test itself: non-code (images, video, 3D models, Markdown, docs/, samples/, output/), firmware and hardware under devices/ that is not a link file, and accessibility.",
+ "dropped": [
+ {
+ "reason": "Agent, engine, terminal, editor and UI sessions: not sign-in. Sign-in sessions stay held by name (sessionScope, backend/src/**/session*, the web's community session, the session lock).",
+ "files": [
+ "cli/src/core/engines/sessionBinding.ts",
+ "cli/src/core/terminals/sessions.ts",
+ "cli/src/e2e/sessionName.ts",
+ "cli/src/e2e/sessionTools.ts",
+ "cli/src/engines/__fixtures__/session-store.golden.json",
+ "cli/src/engines/agy/session.ts",
+ "cli/src/engines/claude/sessionStore.ts",
+ "cli/src/engines/codex/sessionStore.ts",
+ "cli/src/engines/copilot/session.ts",
+ "cli/src/engines/facets/sessionStore.ts",
+ "cli/src/engines/grok/session.spec.ts",
+ "cli/src/engines/grok/session.ts",
+ "cli/src/engines/kit/sessionIdentity.spec.ts",
+ "cli/src/engines/kit/sessionIdentity.ts",
+ "cli/src/engines/kit/sessionLocation.spec.ts",
+ "cli/src/engines/kit/sessionLocation.ts",
+ "cli/src/engines/kit/sessionRecords.ts",
+ "cli/src/engines/opencode/sessionModel.spec.ts",
+ "cli/src/engines/opencode/sessionModel.ts",
+ "cli/src/engines/sessionFiles.ts",
+ "cli/src/engines/sessionStore.golden.spec.ts",
+ "cli/src/engines/sessionStoreContracts.ts",
+ "cli/src/engines/sessionStores.ts",
+ "cli/src/lib/fixtures/session-work-codex.jsonl",
+ "cli/src/lib/sessionCheckpoint.spec.ts",
+ "cli/src/lib/sessionCheckpoint.sqlite.spec.ts",
+ "cli/src/lib/sessionCheckpoint.ts",
+ "cli/src/lib/sessionGitContext.spec.ts",
+ "cli/src/lib/sessionGitContext.ts",
+ "cli/src/lib/sessionGitHistory.spec.ts",
+ "cli/src/lib/sessionGitHistory.ts",
+ "cli/src/lib/sessionGitPullRequest.spec.ts",
+ "cli/src/lib/sessionGitPullRequest.ts",
+ "cli/src/lib/sessionInput.spec.ts",
+ "cli/src/lib/sessionInput.ts",
+ "cli/src/lib/sessionRepair.bounds.spec.ts",
+ "cli/src/lib/sessionRepair.eager.spec.ts",
+ "cli/src/lib/sessionRepair.metadata.spec.ts",
+ "cli/src/lib/sessionRepair.spec.ts",
+ "cli/src/lib/sessionRepair.ts",
+ "cli/src/lib/sessionSearch/sessionTurns.spec.ts",
+ "cli/src/lib/sessionSearch/sessionTurns.ts",
+ "cli/src/lib/sessionSync.spec.ts",
+ "cli/src/lib/sessionSync.ts",
+ "cli/src/lib/sessionTitle.homes.spec.ts",
+ "cli/src/lib/sessionTitle.spec.ts",
+ "cli/src/lib/sessionTitle.ts",
+ "cli/src/lib/sessionWork.spec.ts",
+ "cli/src/lib/sessionWork.ts",
+ "cli/src/lib/sessionWorkCache.spec.ts",
+ "cli/src/lib/sessionWorkWire.ts",
+ "cli/src/lib/sessions.spec.ts",
+ "cli/src/lib/sessions.ts",
+ "desktop/integration_test/session_close_native_test.dart",
+ "desktop/lib/state/session_activity.dart",
+ "desktop/lib/state/session_content_search.dart",
+ "desktop/lib/state/session_preview.dart",
+ "desktop/lib/state/session_tail.dart",
+ "desktop/lib/widgets/session_activity_label.dart",
+ "desktop/lib/widgets/session_close_dialog.dart",
+ "desktop/lib/widgets/session_tail_view.dart",
+ "desktop/lib/widgets/session_work_dialog.dart",
+ "desktop/scripts/windows-e2e/session-run.ps1",
+ "desktop/test/session_activity_test.dart",
+ "desktop/test/session_close_dialog_test.dart",
+ "desktop/test/session_close_test.dart",
+ "desktop/test/session_content_search_test.dart",
+ "desktop/test/session_git_context_test.dart",
+ "desktop/test/session_preview_app_test.dart",
+ "desktop/test/session_preview_test.dart",
+ "desktop/test/session_search_daemon_e2e_test.dart",
+ "desktop/test/session_search_rendering_test.dart",
+ "desktop/test/session_tail_test.dart",
+ "desktop/test/session_work_dialog_test.dart",
+ "desktop/test/session_work_navigation_test.dart",
+ "desktop/test/session_work_state_test.dart",
+ "mobile/lib/phone/session_work_page.dart",
+ "mobile/lib/state/session_content_search.dart",
+ "mobile/lib/state/session_preview.dart",
+ "mobile/test/session_content_search_test.dart",
+ "mobile/test/session_git_context_test.dart",
+ "mobile/test/session_preview_test.dart",
+ "mobile/test/session_work_page_test.dart",
+ "mobile/test/session_work_state_test.dart",
+ "os/root/usr/lib/harness-os/session",
+ "os/root/usr/lib/harness-os/session-settings.py",
+ "os/tests/session_update_vm.py",
+ "os/tests/session_vm.py",
+ "provider/example-provider/src/sessions.ts",
+ "store/agents/memories/lib/sessions.mjs",
+ "store/agents/memories/test/sessions.test.mjs",
+ "store/agents/music-studio/examples/keepsake/session.json",
+ "store/agents/music-studio/examples/orbit-runner/session.json",
+ "store/agents/music-studio/template/piece/session.json",
+ "store/agents/music-studio/template/studio/session.mjs",
+ "store/agents/music-studio/test/session.test.mjs",
+ "tui/src/session_close.rs",
+ "tui/tests/session-picker.py"
+ ]
+ },
+ {
+ "reason": "Guards that are not the Buddy, rule, devices, PM or TLS guard, or one under backend/src/superTabs (Redis, turn, launch, menu, surface cache, JSON, companion guards).",
+ "files": [
+ "backend/src/lib/redisGuard.test.ts",
+ "backend/src/lib/redisGuard.ts",
+ "backend/src/lib/shortTurnGuard.test.ts",
+ "backend/src/lib/shortTurnGuard.ts",
+ "cli/src/core/turns/shortTurnGuard.spec.ts",
+ "cli/src/core/turns/shortTurnGuard.ts",
+ "cli/src/engines/kit/nativeLaunchGuard.spec.ts",
+ "cli/src/engines/kit/nativeLaunchGuard.ts",
+ "companions/src/shared/guard.boundary.spec.ts",
+ "companions/src/shared/guard.fuzz.spec.ts",
+ "companions/src/shared/guard.spec.ts",
+ "desktop/lib/widgets/browser_menu_guard.dart",
+ "desktop/macos/Runner/SurfaceCacheGuard.swift",
+ "desktop/test/browser_menu_guard_test.dart",
+ "desktop/test/native_picker_guard_test.dart",
+ "mobile/test/phone_edge/new_branch_guard_test.dart",
+ "mobile/test/test_home_guard_test.dart",
+ "store/agents/home-assistant/test/guard_probe.py",
+ "store/agents/phaser/viewer/guard.js"
+ ]
+ },
+ {
+ "reason": "Keyboard keys, cache and image keys, and a hash that keeps account ids out of logs, outside backend/src and cli/src (key and keys are held only there). Account storage forgotten at sign-out stays held as deletion (account_keys).",
+ "files": [
+ "desktop/lib/finder/widgets/finder_diff_keys.dart",
+ "desktop/lib/finder/widgets/finder_tree_keys.dart",
+ "desktop/lib/shortcuts/text_editing_keys.dart",
+ "desktop/lib/usage/usage_account_key.dart",
+ "desktop/third_party/xterm/lib/src/core/input/keys.dart",
+ "mobile/lib/phone/question_keys.dart",
+ "mobile/third_party/xterm/lib/src/core/input/keys.dart",
+ "os/platforms/orangepi-4pro/base-key.sh",
+ "term/src/keys.rs",
+ "tui/src/keys.rs",
+ "website/src/app/hub/components/useMenuKeys.ts"
+ ]
+ },
+ {
+ "reason": "Device UI and data that is not the device link (pet editor and settings, store agents, test fixtures): device file names stay held, and the device folders only in the CLI.",
+ "files": [
+ "desktop/lib/devices/loose_sheet.dart",
+ "desktop/lib/devices/pet_editor.dart",
+ "desktop/lib/devices/pet_settings.dart",
+ "desktop/lib/devices/pet_source.dart",
+ "store/agents/devices/LICENSE",
+ "store/agents/devices/harness.json",
+ "store/agents/devices/store.json"
+ ]
+ }
+ ]
+}
diff --git a/backend/src/superTabs/policy.test.ts b/backend/src/superTabs/policy.test.ts
index 184efa276..0d18d90a4 100644
--- a/backend/src/superTabs/policy.test.ts
+++ b/backend/src/superTabs/policy.test.ts
@@ -1,3 +1,5 @@
+import { execFileSync } from 'node:child_process'
+import { readFileSync } from 'node:fs'
import { describe, expect, it } from 'vitest'
import { applyCommand, type Command, type CommandContext } from './commands.js'
import { createSuperTab, type Actor, type AgentConfiguration } from './model.js'
@@ -120,6 +122,119 @@ const set = (baseRevision: number, rules: ProjectRules, extra: Partial<Extract<C
({ type: 'rules.set', projectId: 'lead', baseRevision, rules, summary: 'Releases start at 10', ...extra })
const code = (run: () => unknown): unknown => { try { run() } catch (error) { return (error as { code?: string }).code ?? 'INVALID' } return undefined }
+// Task #3475 (review of #3250): the merge train used these patterns before it read the record. They held a file at two reads
+// wherever they matched, and the seed must hold at least as much (River, 11-05: fail closed on the review table).
+const OLD_TRAIN_AREAS: ReadonlyArray<{ area: string; paths: RegExp }> = [
+ { area: 'Sign-in', paths: /(^|\/)(auth|login|sign_?in|signin|session)[^/]*$|^backend\/src\/middlewares\//i },
+ { area: 'Tokens', paths: /token|^backend\/src\/github\//i },
+ { area: 'Encryption', paths: /crypt|cipher|secret|credential|key(s|chain)?\b/i },
+ { area: 'Access', paths: /access|permission|audience|membership/i },
+ { area: 'Buddy guard', paths: /guard/i },
+ { area: 'Device links', paths: /device|harness_?links|pairing|join_?link/i },
+ { area: 'Deletion', paths: /purge|delet|cleanup|sweep|prune/i },
+]
+const oldTrainHeldAtTwo = (file: string) => OLD_TRAIN_AREAS.some(({ paths }) => paths.test(file))
+
+describe('the seed asks two reads wherever the merge train did', () => {
+ it('holds the files the review of #3250 named at two reads', () => {
+ for (const file of ['backend/src/lib/deviceRevoke.ts', 'backend/src/lib/deviceKeyLog.ts', 'backend/src/lib/deviceWs.ts',
+ 'backend/src/push/devices.ts', 'backend/src/superTabs/sessionScope.ts',
+ 'backend/src/push/keys.ts', 'backend/src/routes/deviceKeys.ts', 'cli/src/gateway/tabKey.ts', 'cli/src/lib/terminalKeys.ts',
+ 'backend/src/superTabs/ruleGuard.ts', 'backend/src/superTabs/sweeps.ts', 'backend/src/lib/attachmentSweep.ts',
+ 'backend/src/lib/chunkSweep.ts', 'backend/src/lib/harness_links.ts', 'mobile/lib/join_link.dart', 'backend/src/audience.ts',
+ 'backend/src/membership/rows.ts', 'tools/prune-caches.sh', 'backend/src/crypto/box.ts', 'backend/src/lib/keys/store.ts',
+ // SecAlder's security review of #3250.
+ 'backend/src/routes/harnessLinks.ts', 'backend/src/lib/deviceLogCore.ts', 'cli/src/core/devicesLink.ts',
+ 'cli/src/gateway/observerKey.ts', 'backend/src/lib/pendingUploadSweep.ts', 'cli/src/lib/worktreeSweep.ts',
+ // Kept when the false hits were narrowed (River, SecAlder, ReviewLinnea): the real sign-in sessions, guards, device code
+ // and the device link's own files in the firmware.
+ 'website/src/lib/community/session.ts', 'os/packaging/labwc/session-lock-presentation.patch', 'cli/src/lib/turnTlsGuard.ts',
+ 'cli/src/services/devicesGuard.ts', 'desktop/lib/super_tabs/lead_guard.dart', 'backend/src/superTabs/anyGuard.ts',
+ 'desktop/lib/devices/wifi_robots.dart', 'mobile/lib/phone/add_device/saved_wifi.dart', 'cli/src/devices/client.ts',
+ 'devices/harness-device/firmware/main/cable_client.c', 'devices/harness-pro/firmware/main/pair_ble.c',
+ // Aster's security review of #3250: the vLLM server's API-key check, the companions' secret-redaction guard, and the
+ // team handoff with its machine-key proof.
+ 'store/agents/vllm/guard.py', 'companions/src/shared/guard.ts', 'cli/src/team/handoff.ts']) {
+ expect(requiredReads(SEED_RULES, [file]), file).toBe(2)
+ }
+ })
+
+ // River, 11-06: fail closed, but a pattern that catches unrelated files is narrowed. These stay at one read.
+ it('leaves the old matcher\'s false hits at one read', () => {
+ for (const file of ['devices/harness-device/firmware/main/app_main.c', '.github/assets/readme/device.gif',
+ 'output/orchestrator-live/token/model.stl', 'docs/autonomous-device-integration.md', 'desktop/tool/accessibility_regression/main.dart',
+ 'backend/src/lib/redisGuard.ts', 'cli/src/engines/claude/sessionStore.ts', 'cli/src/core/terminals/sessions.ts',
+ 'desktop/lib/finder/widgets/finder_diff_keys.dart', 'docs/performance/2026-09-22-pane-data/pane-sweep-after-1.json']) {
+ expect(requiredReads(SEED_RULES, [file]), file).toBe(1)
+ }
+ })
+
+ // Every file the old matcher held stays at two reads, except what the reviews dropped on purpose: whole classes by rule
+ // here, and single files in policy.securityExclusions.json, each under its reason. A file dropping out of the security
+ // areas fails this until a review adds it there.
+ it('holds every file of this repository the old patterns held, at two reads, except the reviewed exclusions', () => {
+ const DROPPED_BY_RULE: ReadonlyArray<{ reason: string; test: (file: string) => boolean }> = [
+ { reason: 'Runs no code: images (not SVG, which can carry script), video, 3D models, Markdown, docs/, samples/, output/',
+ test: file => /\.(png|jpe?g|gif|webp|ico|icns|mp4|mov|webm|stl|step|stp|3mf|obj|glb|gltf|f3d|md)$|^(docs|samples|output)\//i.test(file) },
+ { reason: 'Firmware and hardware under devices/ that is not a link file (cable, pair, link and key files stay held)',
+ test: file => file.startsWith('devices/') },
+ { reason: 'Accessibility is not access control', test: file => /accessib/i.test(file) },
+ ]
+ const listed = new Set((JSON.parse(readFileSync(new URL('./policy.securityExclusions.json', import.meta.url), 'utf8')) as
+ { dropped: Array<{ reason: string; files: string[] }> }).dropped.flatMap(group => group.files))
+ const root = execFileSync('git', ['rev-parse', '--show-toplevel'], { encoding: 'utf8' }).trim()
+ const files = execFileSync('git', ['ls-files'], { cwd: root, encoding: 'utf8', maxBuffer: 64 * 1024 * 1024 }).split('\n').filter(Boolean)
+ expect(files.length).toBeGreaterThan(100)
+ const missed = files.filter(file => oldTrainHeldAtTwo(file) && requiredReads(SEED_RULES, [file]) < 2
+ && !listed.has(file) && !DROPPED_BY_RULE.some(rule => rule.test(file)))
+ expect(missed, `${missed.length} files the train held at two now need one, and no review dropped them`).toEqual([])
+ })
+})
+
+describe('a saved record can raise a security area, never lower it below two reads', () => {
+ // River, 11-06 (#3475): the floor is code, whatever a saved record says.
+ const lowered = (reads: number): ProjectRules => ({ ...copy(), reviews: { ...copy().reviews,
+ rows: SEED_RULES.reviews.rows.map(row => ({ ...row, reads })) } })
+ const removed = (): ProjectRules => ({ ...copy(), reviews: { ...copy().reviews, rows: [] } })
+
+ it('keeps two reads on a security file when a record lowers or removes its area', () => {
+ for (const rules of [lowered(1), removed()]) {
+ expect(requiredReads(rules, ['backend/src/github/tokens.ts'])).toBe(2)
+ expect(requiredReads(rules, ['backend/src/lib/deviceRevoke.ts'])).toBe(2)
+ expect(requiredReads(rules, null)).toBe(2)
+ expect(requiredReads(rules, ['backend/src/superTabs/cards.ts'])).toBe(1)
+ }
+ })
+
+ // SecAlder, re-review of #3250: the non-code and accessibility filter trims the built-in patterns only. A path a person puts
+ // in a security row of their record counts exactly as written.
+ it('counts a path a person added to a security row as written, non-code and accessibility too', () => {
+ const added = (area: string, glob: string): ProjectRules => ({ ...copy(), reviews: { ...copy().reviews,
+ rows: SEED_RULES.reviews.rows.map(row => row.area === area ? { ...row, paths: [...row.paths, glob] } : row) } })
+ expect(requiredReads(added('Sign-in', 'samples/**'), ['samples/x.ts'])).toBe(2)
+ expect(requiredReads(added('Sign-in', 'web/**/*.svg'), ['web/a/login-form.svg'])).toBe(2)
+ expect(requiredReads(added('Sign-in', 'web/**/*.svg'), ['web/a/icon.svg'])).toBe(2)
+ expect(requiredReads(added('Access', '**/accessibility/**'), ['desktop/accessibility/main.dart'])).toBe(2)
+ expect(requiredReads(added('Access', 'docs/**'), ['docs/plan.md'])).toBe(2)
+ // The seed's own patterns still leave those out.
+ expect(requiredReads(SEED_RULES, ['samples/x.ts', 'desktop/accessibility/main.dart', 'docs/token.md'])).toBe(1)
+ })
+
+ // ReviewLinnea, re-review of #3250: account_keys decides which stored Swarm data is forgotten at sign-out (deletion).
+ it('holds the account storage keys forgotten at sign-out at two reads', () => {
+ expect(requiredReads(SEED_RULES, ['desktop/lib/super_tabs/account_keys.dart'])).toBe(2)
+ })
+
+ it('holds an SVG named for a security area: an SVG can carry script', () => {
+ expect(requiredReads(SEED_RULES, ['website/public/auth-logo.svg'])).toBe(2)
+ })
+
+ it('takes a record that raises a security area', () => {
+ expect(requiredReads(lowered(3), ['backend/src/github/tokens.ts'])).toBe(3)
+ expect(requiredReads(lowered(3), null)).toBe(3)
+ })
+})
+
describe('reads and tests a change needs', () => {
it('matches globs as the review steps do: ** any folders, * and ? in one name, ignoring case', () => {
expect(globMatch('**/*auth*', 'backend/src/lib/ssoAuth.ts')).toBe(true)
diff --git a/backend/src/superTabs/policy.ts b/backend/src/superTabs/policy.ts
index 13c4f8925..5ed92d89f 100644
--- a/backend/src/superTabs/policy.ts
+++ b/backend/src/superTabs/policy.ts
@@ -78,6 +78,41 @@ function deepFreeze<T>(value: T): T {
return Object.freeze(value)
}
+/**
+ * The review table's security areas (project instructions, Ken 2026-10-29: two independent reviews for sign-in, tokens,
+ * access, encryption, the Buddy guard, the device link and anything that deletes data). Each old term matches as a name or as
+ * a folder, as the merge train's own matcher did before it read this record (task #3475, review of #3250: it erred wide, and
+ * so does this). The seed starts from these rows, and requiredReads never asks fewer than two reads where they match, whatever
+ * a saved record says (River, 2026-11-06): a record can raise an area, never lower it.
+ */
+export const SECURITY_ROWS: ReadonlyArray<{ area: string; reads: number; paths: string[] }> = deepFreeze([
+ { area: 'Sign-in', reads: 2, paths: ['**/*auth*', '**/*login*', '**/*logout*', '**/*signin*', '**/*sign_in*', '**/middlewares/**', '**/sessionScope*', 'backend/src/**/session*', '**/community/session*', '**/session-lock*', 'store/agents/**/guard.py'] },
+ { area: 'Tokens', reads: 2, paths: ['**/*token*', '**/*token*/**', '**/*credential*', '**/*credential*/**', '**/*secret*', '**/*secret*/**', '**/*keychain*', 'backend/src/github/**', 'cli/src/team/handoff*'] },
+ { area: 'Encryption', reads: 2, paths: ['**/*crypt*', '**/*crypt*/**', '**/*cipher*', '**/*cipher*/**', '**/*encrypt*', '**/e2ee/**', '**/*seal*', '**/*pake*', '**/*tlsguard*', 'backend/src/**/*key', 'backend/src/**/*key.*', 'backend/src/**/*key/**', 'backend/src/**/*key-*', 'backend/src/**/*keys', 'backend/src/**/*keys.*', 'backend/src/**/*keys/**', 'backend/src/**/*keys-*', 'cli/src/**/*key', 'cli/src/**/*key.*', 'cli/src/**/*key/**', 'cli/src/**/*key-*', 'cli/src/**/*keys', 'cli/src/**/*keys.*', 'cli/src/**/*keys/**', 'cli/src/**/*keys-*'] },
+ { area: 'Access', reads: 2, paths: ['**/*access*', '**/*access*/**', '**/*permission*', '**/*permission*/**', '**/*audience*', '**/*audience*/**', '**/*membership*', '**/*membership*/**', '**/*authority*', '**/*trust*', '**/teamWritten*'] },
+ { area: 'Buddy guard', reads: 2, paths: ['**/*buddy*guard*', '**/*ruleguard*', '**/*rule_guard*', '**/*devicesguard*', '**/*devices_guard*', '**/*leadguard*', '**/*lead_guard*', 'backend/src/superTabs/*guard*', 'companions/src/shared/guard.ts'] },
+ { area: 'Device links', reads: 2, paths: ['**/*device*', 'cli/src/device/**', 'cli/src/devices/**', 'cli/src/lib/*device*/**', '**/add_device/**', '**/*wifi_robot*', 'devices/**/*cable*', 'devices/**/*pair*', 'devices/**/*link*', 'devices/**/*key*', '**/*harnesslinks*', '**/*harnesslinks*/**', '**/*harness_links*', '**/*harness_links*/**', '**/*pairing*', '**/*pairing*/**', '**/*joinlink*', '**/*joinlink*/**', '**/*join_link*', '**/*join_link*/**', '**/*deviceauth*'] },
+ { area: 'Deletion', reads: 2, paths: ['**/*delet*', '**/*delet*/**', '**/*purge*', '**/*purge*/**', '**/*cleanup*', '**/*cleanup*/**', '**/*sweep*', '**/*sweep*/**', '**/*prune*', '**/*prune*/**', '**/*tombstone*', '**/*wipe*', '**/account_keys*'] },
+])
+/** The fewest reads a change to a security area gets, whatever a saved record says. */
+export const SECURITY_FLOOR_READS = 2
+/** What runs no code: images (not SVG, which can carry script), video, 3D models, Markdown, docs, samples and build output.
+ * The built-in security patterns never catch it (River, SecAlder and ReviewLinnea, review of #3250); a path a person writes
+ * into a security row of their record still does, as written. */
+const NOT_CODE = /\.(png|jpe?g|gif|webp|ico|icns|mp4|mov|webm|stl|step|stp|3mf|obj|glb|gltf|f3d|md)$|^(docs|samples|output)\//i
+/** Names a security term catches by accident, per area: accessibility is not access control. */
+const NOT_AREA: Readonly<Record<string, RegExp>> = { access: /accessib/i }
+/** The built-in patterns of each security area, by its name in lower case. */
+const BUILT_IN = new Map(SECURITY_ROWS.map(row => [row.area.toLowerCase(), new Set(row.paths)]))
+/** Whether [glob] of a security area's row catches [file]: a built-in pattern catches code only, not a known false name; a
+ * pattern a person added to the row in their record catches exactly what it says (SecAlder, re-review of #3250). */
+function securityGlob(area: string, glob: string, file: string): boolean {
+ if (!globMatch(glob, file)) return false
+ if (!BUILT_IN.get(area.toLowerCase())?.has(glob)) return true
+ return !NOT_CODE.test(file) && !NOT_AREA[area.toLowerCase()]?.test(file)
+}
+const inSecurityArea = (row: { area: string; paths: readonly string[] }, file: string) => row.paths.some(glob => securityGlob(row.area, glob, file))
+
/** Today's numbers (task #3393; project instructions, 2026-11-05): what a project reads until its first save. */
export const SEED_RULES: ProjectRules = deepFreeze({
releaseWindow: { start: '09:00', end: '18:00', timeZone: 'Asia/Ho_Chi_Minh' },
@@ -86,15 +121,7 @@ export const SEED_RULES: ProjectRules = deepFreeze({
// (project instructions, Ken 2026-10-29), a test where the change runs (Workflow 2).
reviews: {
defaultReads: 1,
- rows: [
- { area: 'Sign-in', reads: 2, paths: ['**/*auth*', '**/*login*', '**/*logout*', '**/*signin*', '**/*sign_in*', '**/middlewares/**'] },
- { area: 'Tokens', reads: 2, paths: ['**/*token*', '**/*credential*', '**/*secret*', '**/*keychain*', 'backend/src/github/**'] },
- { area: 'Encryption', reads: 2, paths: ['**/*crypto*', '**/*encrypt*', '**/e2ee/**', '**/*seal*', '**/*pake*'] },
- { area: 'Access', reads: 2, paths: ['**/*access*', '**/*permission*', '**/*authority*', '**/*trust*', '**/teamWritten*'] },
- { area: 'Buddy guard', reads: 2, paths: ['**/*buddyguard*', '**/*buddy_guard*'] },
- { area: 'Device links', reads: 2, paths: ['**/*devicelink*', '**/*device_link*', '**/*deviceauth*', '**/*pairing*'] },
- { area: 'Deletion', reads: 2, paths: ['**/*delet*', '**/*purge*', '**/*cleanup*', '**/*tombstone*', '**/*wipe*'] },
- ],
+ rows: SECURITY_ROWS.map(row => ({ ...row, paths: [...row.paths] })),
test: [
{ where: 'Desktop on a Mac', paths: ['desktop/**'] },
{ where: 'The CLI on a Mac and on a Linux machine', paths: ['cli/**', 'pty/**', 'term/**', 'tui/**', 'daemons/**'] },
@@ -232,7 +259,15 @@ export function touchedRows(rules: ProjectRules, files: readonly string[] | null
/** The independent reads a change to [files] needs: the most any touched row asks, at least the default. Files that could
* not be read (null) need the most any row asks (the merge train and the review steps fail closed, #3401, #3402). */
export function requiredReads(rules: ProjectRules, files: readonly string[] | null): number {
- return Math.max(rules.reviews.defaultReads, ...touchedRows(rules, files).map(row => row.reads))
+ // The floor (River, 2026-11-06): a security area's two reads hold whatever the record's own rows say, and unknown files
+ // touch every area.
+ const security = files === null || files.some(file => SECURITY_ROWS.some(row => inSecurityArea(row, file)))
+ // A security area's own row in the record reads files the same way, so a doc or an image named after a device asks no
+ // second read; any other row reads every file.
+ const areas = new Set(SECURITY_ROWS.map(row => row.area.toLowerCase()))
+ const rows = files === null ? touchedRows(rules, null) : rules.reviews.rows.filter(row => areas.has(row.area.toLowerCase())
+ ? files.some(file => inSecurityArea(row, file)) : files.some(file => row.paths.some(glob => globMatch(glob, file))))
+ return Math.max(rules.reviews.defaultReads, ...rows.map(row => row.reads), security ? SECURITY_FLOOR_READS : 0)
}
/** Where a change to [files] runs, for its test, in the table's order: none for tests, fixtures and docs alone, and none when
diff --git a/backend/src/superTabs/policyStore.ts b/backend/src/superTabs/policyStore.ts
index a2fbd57b1..6e00149ca 100644
--- a/backend/src/superTabs/policyStore.ts
+++ b/backend/src/superTabs/policyStore.ts
@@ -4,7 +4,7 @@
*/
import type { Prisma } from '@prisma/client'
import { stableId } from './model.js'
-import { MAX_RULES_REVISIONS, SEED_RULES, type ProjectRules, type RulesChange, type RulesWrite } from './policy.js'
+import { MAX_RULES_REVISIONS, projectRulesSchema, SEED_RULES, type ProjectRules, type RulesChange, type RulesWrite } from './policy.js'
type Transaction = Prisma.TransactionClient
@@ -31,7 +31,13 @@ export async function readRules(tx: Transaction, tabId: string, projectId: strin
/** The record a project runs on now, for a server worker (the merge train, the release schedule): its newest revision, or
* the seed at revision 0. Takes the client or a transaction. */
export async function currentRules(tx: Transaction, tabId: string, projectId: string): Promise<{ revision: number; rules: ProjectRules }> {
- return await readRules(tx, tabId, projectId) ?? { revision: 0, rules: SEED_RULES }
+ const saved = await readRules(tx, tabId, projectId)
+ if (!saved) return { revision: 0, rules: SEED_RULES }
+ // Checked again on the way out (SecAlder, review of #3250): a stored row the schema refuses (one with no read count, a
+ // pattern from a looser past schema) would read as fewer reads. It throws, and the caller holds: never a partial record.
+ const parsed = projectRulesSchema.safeParse(saved.rules)
+ if (!parsed.success) throw new Error(`project rules revision ${saved.revision} does not pass the schema; save the rules again`)
+ return { revision: saved.revision, rules: parsed.data }
}
/** Every kept revision, newest first: at most MAX_RULES_REVISIONS rows of the same index. */
diff --git a/backend/src/superTabs/promptWaits.test.ts b/backend/src/superTabs/promptWaits.test.ts
new file mode 100644
index 000000000..89dbb5839
--- /dev/null
+++ b/backend/src/superTabs/promptWaits.test.ts
@@ -0,0 +1,101 @@
+import { describe, expect, it } from 'vitest'
+import { applyCommand, type Command } from './commands.js'
+import * as store from './parts/index.js'
+import { readerView } from './read/views.js'
+import { NOW, outsider, owner, peer, richSwarm } from './read/fixture.test-support.js'
+import { promptWaits } from './promptWaits.js'
+import type { Actor } from './model.js'
+import { agentDisplayName } from './agentNames.js'
+
+/** A task's agent at a prompt: the alert its own host sends (terminal.ts terminalAlert), and its end. */
+const host = (agentId: string): Actor => ({ kind: 'agent', agentId, machineOwnerId: `${owner.userId}-machine` })
+const prompt = (agentId: string, active = true): Command => ({ type: 'agent.alert', agentId, alert: 'prompt', active })
+
+function scene() {
+ const s = richSwarm()
+ const alert = (agentId: string, active = true) => applyCommand(s.state, host(agentId), prompt(agentId, active), { now: NOW, operationId: `alert-${agentId}-${active}` })
+ const send = (agentId: string, active = true) => { const effects = alert(agentId, active); s.edit(state => Object.assign(state, effects.state)); return effects }
+ return Object.assign(s, { send })
+}
+
+describe('a task agent waiting at a prompt (task #3029)', () => {
+ it('reaches the task\'s requester under Decisions, still tells the PM, and clears when the agent moves on', () => {
+ const s = scene()
+ s.run({ type: 'conversation.requester', conversationId: s.web, personId: peer.userId })
+ expect(promptWaits(s.state, peer)).toEqual([])
+ const effects = s.send(s.worker)
+ // The PM's row is as before: in the task, delivered to the PM.
+ expect(effects.messages).toEqual([expect.objectContaining({ conversationId: s.web, recipients: [s.lead],
+ source: { kind: 'terminal-alert', agentId: s.worker, alert: 'prompt' } })])
+ expect(promptWaits(s.state, peer)).toEqual([{ agentId: s.worker, agentName: agentDisplayName(s.state.agents, s.worker), conversationId: s.web, conversationTitle: 'Web',
+ projectId: s.state.projects![0]!.id, projectName: s.state.projects![0]!.name }])
+ s.send(s.worker, false)
+ expect(promptWaits(s.state, peer)).toEqual([])
+ })
+
+ it('tells only the task\'s own people: not other members, not the machine\'s owner without a device, not a reader the task is closed to', () => {
+ const s = scene()
+ s.run({ type: 'conversation.requester', conversationId: s.web, personId: peer.userId })
+ s.send(s.worker)
+ expect(promptWaits(s.state, outsider)).toEqual([])
+ expect(promptWaits(s.state, owner)).toEqual([])
+ // A requester who no longer reads the task's project is told nothing of it.
+ s.edit(state => { const web = state.conversations.find(c => c.id === s.web)!; web.projectId = s.secret })
+ expect(promptWaits(s.state, peer)).toEqual([])
+ })
+
+ it('reaches the machine\'s owner when the task needs a device on that machine', () => {
+ const s = scene()
+ const bench = s.group('Flash the board')
+ const flasher = s.add('flasher', bench, false, peer, 'peer-mac', peer.userId)
+ s.run({ type: 'work.assign', conversationId: bench, agentId: flasher })
+ s.edit(state => {
+ const agent = state.agents.find(a => a.id === flasher)!
+ agent.alerting = ['prompt']
+ })
+ // No device: the machine's owner is not the task's person.
+ expect(promptWaits(s.state, peer)).toEqual([])
+ s.edit(state => { const task = state.conversations.find(c => c.id === bench)!; task.task = { ...task.task!, requires: { devices: ['/dev/cu.usbmodem1'] } } })
+ expect(promptWaits(s.state, peer).map(w => w.agentId)).toEqual([flasher])
+ // A device on another machine is not this machine's owner's to handle.
+ s.edit(state => { const task = state.conversations.find(c => c.id === bench)!; task.task = { ...task.task!, requires: { machines: ['host'], devices: ['/dev/cu.usbmodem1'] } } })
+ expect(promptWaits(s.state, peer)).toEqual([])
+ })
+
+ it('reaches the machine\'s owner when a step\'s task needs a device on that machine: a step carries no requirements of its own', () => {
+ const s = scene()
+ const bench = s.group('Flash the board')
+ s.edit(state => { const task = state.conversations.find(c => c.id === bench)!; task.task = { ...task.task!, requires: { devices: ['/dev/cu.usbmodem1'] } } })
+ const test = s.run({ type: 'conversation.create', title: 'Test Flash the board', brief: 'Test it on the board.', checks: [], reviewOf: bench }).conversationId as string
+ const tester = s.add('tester', test, false, peer, 'peer-mac', peer.userId)
+ s.run({ type: 'work.assign', conversationId: test, agentId: tester })
+ s.edit(state => { state.agents.find(a => a.id === tester)!.alerting = ['prompt'] })
+ expect(promptWaits(s.state, peer).map(w => [w.agentId, w.conversationId])).toEqual([[tester, test]])
+ // The task's device is on another machine: not this machine's owner's to handle.
+ s.edit(state => { const task = state.conversations.find(c => c.id === bench)!; task.task = { ...task.task!, requires: { machines: ['host'], devices: ['/dev/cu.usbmodem1'] } } })
+ expect(promptWaits(s.state, peer)).toEqual([])
+ })
+
+ it('reaches the requester of the task a step reviews, and nobody for an agent with no task', () => {
+ const s = scene()
+ s.run({ type: 'conversation.requester', conversationId: s.web, personId: peer.userId })
+ const review = s.run({ type: 'conversation.create', title: 'Review Web', brief: 'Review it.', checks: [], reviewOf: s.web }).conversationId as string
+ const reviewer = s.add('reviewer', review)
+ s.run({ type: 'work.assign', conversationId: review, agentId: reviewer })
+ s.send(reviewer)
+ expect(promptWaits(s.state, peer).map(w => [w.agentId, w.conversationId])).toEqual([[reviewer, review]])
+ // The Lead has no task: its prompt stays the PM's own business.
+ s.send(s.lead)
+ expect(promptWaits(s.state, peer).map(w => w.agentId)).toEqual([reviewer])
+ })
+
+ it('is in a person\'s read view, and in no agent\'s', () => {
+ const s = scene()
+ s.run({ type: 'conversation.requester', conversationId: s.web, personId: peer.userId })
+ s.send(s.worker)
+ const parts = store.split(s.state, { tabId: 'tab', version: 9_000, now: NOW })
+ expect(readerView(parts, peer, NOW, { teamMachines: [] }).derived.promptsWaiting).toEqual([expect.objectContaining({ agentId: s.worker, conversationId: s.web })])
+ expect(readerView(parts, outsider, NOW, { teamMachines: [] }).derived.promptsWaiting).toEqual([])
+ expect(readerView(parts, host(s.lead), NOW, { teamMachines: [] }).derived).not.toHaveProperty('promptsWaiting')
+ })
+})
diff --git a/backend/src/superTabs/promptWaits.ts b/backend/src/superTabs/promptWaits.ts
new file mode 100644
index 000000000..4efca5786
--- /dev/null
+++ b/backend/src/superTabs/promptWaits.ts
@@ -0,0 +1,38 @@
+/** A task's agent waiting at a prompt in its terminal, for the task's own people (task #3029). An agent that needs a person
+ * ("press Connect on the iPhone") often writes it only in its terminal; its host's prompt alert (terminal.ts terminalAlert)
+ * told the PM alone. Each person's read now lists the prompts that wait for them, under Decisions: the task's requester (a
+ * step's, the task it reviews), and its machine's owner when the task needs a device there. Derived from the live state on
+ * every read, never stored: a prompt's row goes when its alert ends, or its work does, and nothing is left to delete. */
+import { agentDisplayName } from './agentNames.js'
+import { isBuddy } from './buddies.js'
+import { activeWork, type Actor, type Agent, type Conversation, type SuperTabState } from './model.js'
+import { canReadGroup, groupProject } from './projects.js'
+
+/** One waiting prompt as a person reads it: no screen text (a screen can show secrets); the person's app reads the agent's
+ * last lines through the terminal read, which checks who may (terminal.ts mayDrive). */
+export interface PromptWait { agentId: string; agentName: string; conversationId: string; conversationTitle: string; projectId: string; projectName: string }
+
+/** Whether [personId] is the person [group]'s task needs, for [target] working on it. */
+function taskPerson(state: SuperTabState, group: Conversation, target: Agent, personId: string): boolean {
+ // A step's person is its task's: whoever opened the step only asked for its review.
+ const task = group.reviewOf ? state.conversations.find(c => c.id === group.reviewOf) ?? group : group
+ if (task.requesterId === personId) return true
+ // Someone's hands on a device plugged into this machine: its owner's, when the task names no other machine. A step is
+ // opened without its task's requirements, so a Tester's step on a device task reads its task's.
+ const requires = group.task?.requires?.devices?.length ? group.task.requires : task.task?.requires
+ return target.machineOwnerId === personId && !!requires?.devices?.length && (!requires.machines?.length || requires.machines.includes(target.machineId))
+}
+
+/** The prompts that wait for [actor], a person: each agent of theirs at a prompt in the task it works on, in a task they read. */
+export function promptWaits(state: SuperTabState, actor: Extract<Actor, { kind: 'person' }>): PromptWait[] {
+ if (!state.people.some(p => p.id === actor.userId)) return []
+ const waiting = state.agents.filter(a => a.alerting?.includes('prompt') && !isBuddy(a))
+ if (!waiting.length) return []
+ return waiting.flatMap(target => {
+ const group = state.conversations.find(c => activeWork(c) && c.assignment!.agentId === target.id)
+ if (!group || !taskPerson(state, group, target, actor.userId) || !canReadGroup(state, actor, group)) return []
+ const project = groupProject(state, group)
+ return [{ agentId: target.id, agentName: agentDisplayName(state.agents, target.id) ?? target.name, conversationId: group.id,
+ conversationTitle: group.title, projectId: project.id, projectName: project.name }]
+ })
+}
diff --git a/backend/src/superTabs/pullRequestEvents.ts b/backend/src/superTabs/pullRequestEvents.ts
index 437702c4c..31e63b000 100644
--- a/backend/src/superTabs/pullRequestEvents.ts
+++ b/backend/src/superTabs/pullRequestEvents.ts
@@ -32,7 +32,7 @@ export interface PullRequestWatch {
/** One message for the Engineer, and the key it is posted under once. */
export interface PullRequestEvent { key: string; text: string }
-const FAILED = new Set(['failure', 'timed_out', 'cancelled', 'action_required', 'startup_failure'])
+export const FAILED = new Set(['failure', 'timed_out', 'cancelled', 'action_required', 'startup_failure'])
const PASSED = new Set(['success', 'neutral', 'skipped'])
/** The keys a group keeps per pull request: its marks, and its newest heads' CI and conflict keys. */
export const SEEN_KEPT = 50
diff --git a/backend/src/superTabs/read/contract.ts b/backend/src/superTabs/read/contract.ts
index fabe78996..d1d8037ba 100644
--- a/backend/src/superTabs/read/contract.ts
+++ b/backend/src/superTabs/read/contract.ts
@@ -8,6 +8,7 @@
*/
import type { Agent, AgentStart, Conversation, Person, SuperTabState, WorkStatus } from '../model.js'
import type { ContributedMachine } from '../machines.js'
+import type { PromptWait } from '../promptWaits.js'
export const READ_FORMAT = 2
export type PartKind = 'head' | 'member' | 'agent' | 'group' | 'machine' | 'start' | 'progress'
@@ -37,6 +38,10 @@ export interface Audience { people: Array<{ id: string; generation: string }> }
/** A conversation with its own message counter (`lastMessageSequence` and message sequences compare within one group).
* `dormant` is set only on a dormant group fetched on demand; `audience` only on a private conversation. */
export type GroupView = Omit<Conversation, 'messageSeq' | 'reportSeq' | 'dormant' | 'lastActivityAt' | 'audience' | 'ledger' | 'proposals'> & {
+ /** A task's lane, as the crew dispatch hands it out (dispatch.ts laneOf: its PM's, else its owned paths'), null when no
+ * lane owns its paths; absent on a chat or a step. From the group alone, so a change read's changed tasks keep every lane's
+ * count whole on the reader's side (task #3400). Absent from an older backend. */
+ handOutLane?: string | null
/** When it shipped (ms): its first Done; absent until it has. Nothing else of its ledger is sent. */
shippedAt?: number
/** Why a held task is held, or `none` for a hold from before reasons; absent when it is not held (heldReason.ts heldView). */
@@ -94,6 +99,9 @@ export interface Derived {
decisionsWaiting?: number
/** A person only: a digest of which decisions are open, moving when they change though the count may not. */
decisionsDigest?: string
+ /** A person only: the task agents waiting at a prompt in their terminals for them (promptWaits.ts), shown under Decisions and
+ * counted with them. Absent from an older backend, and for an agent. */
+ promptsWaiting?: PromptWait[]
/** A person only: a digest of which of their Activity rows are unread (activity.ts), moving when one is written, read or
* removed. No count and no chat: the client reads its list again when it moves. Absent from an older backend. */
activityDigest?: string
diff --git a/backend/src/superTabs/read/views.ts b/backend/src/superTabs/read/views.ts
index 7e5a15b6f..120c34559 100644
--- a/backend/src/superTabs/read/views.ts
+++ b/backend/src/superTabs/read/views.ts
@@ -4,6 +4,7 @@
* in `derived`, so a part never changes without a new version (Lead's ruling).
*/
import { machineSuspensionReason, suspendedEngines } from '../engineHealth.js'
+import { DISPATCH_RULES, laneOf } from '../dispatch.js'
import { leadChoices } from '../leadStart.js'
import { heldView } from '../heldReason.js'
import { isBuddyChat, isBuddyReader } from '../buddies.js'
@@ -12,6 +13,7 @@ import { availableSlots, slotCounter, machineTeamWork, type ContributedMachine }
import * as store from '../parts/index.js'
import type { Part, SwarmParts } from '../parts/index.js'
import { canReadGroup } from '../projects.js'
+import { promptWaits } from '../promptWaits.js'
import { storedPulse, type Pulse } from '../pulse.js'
import { coordinatorNameOf, roleNameOf } from '../instructions.js'
import { withAvatarView } from '../profile.js'
@@ -73,8 +75,11 @@ export function groupView(group: Conversation, seenMachines: ReadonlySet<string>
const readers = isBuddyChat(group) ? { buddyOwnerId: audience!.people[0]!.id } : audience ? { audience } : {}
const shippedAt = ledger?.shippedAt
const held = heldView(group)
- return { ...rest, messageSeq: messageSeq ?? 0, ...(dormant ? { dormant: true as const } : {}), ...(shippedAt === undefined ? {} : { shippedAt }),
+ const view: GroupView = { ...rest, messageSeq: messageSeq ?? 0, ...(dormant ? { dormant: true as const } : {}), ...(shippedAt === undefined ? {} : { shippedAt }),
...(held ? { held } : {}), ...readers }
+ // A task's hand-out lane (dispatch.ts stampLane) is stored with it; only a task stored before that is worked out here.
+ if (group.handOutLane === undefined && group.task && !group.reviewOf && !group.kind && !audience) view.handOutLane = laneOf(group, DISPATCH_RULES.lanes)
+ return view
}
/** A conversation's whole data as the reader may see it: a task's requirement lists only the machines they see. */
@@ -199,6 +204,8 @@ function derive(state: SuperTabState, visible: SuperTabState, actor: Actor, now:
...(actor.kind === 'person' && extras.mentionsDigest !== undefined ? { mentionsDigest: extras.mentionsDigest } : {}),
...(actor.kind === 'person' && extras.decisionsWaiting !== undefined ? { decisionsWaiting: extras.decisionsWaiting } : {}),
...(actor.kind === 'person' && extras.decisionsDigest !== undefined ? { decisionsDigest: extras.decisionsDigest } : {}),
+ // Its agents waiting at a prompt in their tasks, under Decisions (promptWaits.ts): from the live state, every read.
+ ...(actor.kind === 'person' ? { promptsWaiting: promptWaits(state, actor) } : {}),
...(actor.kind === 'person' && extras.activityDigest !== undefined ? { activityDigest: extras.activityDigest } : {}),
...(actor.kind === 'person' && extras.remindersDigest !== undefined ? { remindersDigest: extras.remindersDigest } : {}),
threadSessions: true as const,
diff --git a/backend/src/superTabs/store.ts b/backend/src/superTabs/store.ts
index 1326bcf51..a79bd9328 100644
--- a/backend/src/superTabs/store.ts
+++ b/backend/src/superTabs/store.ts
@@ -65,6 +65,8 @@ import { digestDue, digestMessageId, digestOf, digestRequest, digestSince } from
import { moveChatMark } from './read/threadMarkSeeds.js'
import { closedAgents, nextRemovalAt, removeClosedAgents, reopened, restoreRefusal, restoreSessions } from './closedAgents.js'
import { sessionRows } from './memberRows.js'
+import { RefusalMemory } from './dispatchRefusals.js'
+import { candidatesFor, DISPATCH_RULES, dispatchPlan, freeCrew, laneCapacity, openTasks, pinBuilder, pullRequestPin, roundOf, type Skip } from './dispatch.js'
import { failRefusedStarts, judgedMachines, loseTasks, nextLossAt, recordTaskState, sweepForLead, sweepLiveness, SWEEP_EVERY_MS, unpurgedNotice } from './liveness.js'
import { endedReply, taskLineChats } from './taskLine.js'
import { archivable, archiveLine, archiveWaitsFor, idleNotices, reviewClosable, reviewCloseLine, reviewPullRequests, type SettledPullRequest } from './tidy.js'
@@ -157,6 +159,28 @@ const hash = (value: unknown): string => createHash('sha256').update(JSON.string
* for a busy Swarm) until the maintenance script removes it, and every command and read loads this row. */
/** The most Swarms a rename reaches at once, as many as a host reads (read/host.ts FULL_TABS); its readings do the rest. */
const MACHINE_RENAME_SWARMS = 500
+/** The writes after which the crew dispatch runs (store.ts dispatchSoon): those that may free a member or open a task. A
+ * status only when it hands the task over or ends it; a progress note, the Swarm's most frequent write, frees nobody. */
+const DISPATCH_TRIGGERS: ReadonlySet<string> = new Set(['work.cancel', 'conversation.create', 'work.define', 'work.priority',
+ 'work.queue', 'work.lane', 'agent.release', 'crew.add'])
+const FREEING_STATUSES: ReadonlySet<string> = new Set(['done', 'review', 'stopped'])
+const freesOrOpens = (command: Command): boolean =>
+ command.type === 'work.status' ? FREEING_STATUSES.has(command.status) : DISPATCH_TRIGGERS.has(command.type)
+/** How long a refused pick is not sent again in the same round. */
+/** How long a pick refused for a reason its round cannot change (LASTING_REFUSALS) is not sent again. */
+const DISPATCH_REFUSAL_MS = 60 * 60_000
+/** How long any other refusal waits before the dispatch tries again: a PM refused itself (its project waits), or a pick
+ * refused for what may recover without a new round (repository access, a session reopening...; review 2 of #3230). */
+export const DISPATCH_RETRY_MS = 2 * 60_000
+/** The refusals a task's round cannot change: Team-written code for a member outside a Team account, a Buddy. Named, so
+ * everything else is retried soon. */
+const LASTING_REFUSALS: ReadonlySet<string> = new Set(['TEAM_WRITTEN_WORK', 'BUDDY_NOT_ASSIGNABLE'])
+/** At most this many refused picks, and as many waiting PMs, are remembered per process; the oldest go first. */
+const DISPATCH_REFUSALS_HELD = 5_000
+/** How long the dispatch waits after a trigger, so a burst of writes runs one pass. */
+const DISPATCH_DEBOUNCE_MS = 1_000
+/** Picks one member tries in a pass before the next member's turn: each refused one is logged by code. */
+const DISPATCH_TRIES = 3
const SWARM_ROW = { id: true, ownerId: true, revision: true, format: true, deletedAt: true } satisfies Prisma.SuperTabSelect
export type SwarmRow = Prisma.SuperTabGetPayload<{ select: typeof SWARM_ROW }>
/** A Swarm whose state still waits for its split into parts (design section 6.1) is not served until it is split. */
@@ -391,6 +415,9 @@ export interface SuperTabStoreHooks {
/** No Harness GitHub App on this server: a Mac's Harness Team account joins no Swarm and takes no teammates' work, since
* it has no git login to fetch or push with (commands.ts `teamAccountsIdle`). */
teamAccountsIdle?: boolean
+ /** Hand free crew members their next task after the writes that may free one or open a task, and from the 30-second sweep
+ * (store.ts dispatchCrew, task #3400). Off unless a server turns it on. */
+ dispatch?: boolean
/** A terminal request was answered or refused, after the commit (lib/bus.ts tells every instance). It must not throw. */
terminalAnswered?: (requestId: string) => void
/** Calls `onChange` when that request is answered or refused on any instance; resolves to the call that stops listening. */
@@ -1609,11 +1636,13 @@ export class SuperTabStore {
/** [only]: what the store alone may give a command: `overdue` for decision.answer (leaveOverdueDecisions), `movedTo` for
* machine.moved (computerSignedIn). */
private async executeOnce(user: AuthUser, tabId: string, input: { operationId: string; command: Command }, asAgentId?: string, hostMachineId?: string,
- workspaceLeave = false, only: { overdue?: boolean; movedTo?: { machineId: string; ownerId: string } } = {}) {
+ workspaceLeave = false, only: { overdue?: boolean; movedTo?: { machineId: string; ownerId: string }; asProjectPm?: string } = {}) {
const { operationId, command } = operationSchema.parse(input)
const [pushOrigin, repositoryReach, pullRequestFiles] = await Promise.all([this.pushOriginFor(user, tabId, command), this.repositoryReachFor(user, tabId, command),
this.pullRequestFilesFor(user, tabId, command)])
let ended: WorkHold[] = [], started: WorkHold[] = []
+ // Whether the Swarm, as this write leaves it, has a crew: only then may the write start a dispatch pass (dispatchSoon).
+ let crewed = false
const done = await transaction(this.db, async tx => {
// A retried attempt starts again: only the attempt that commits says which tasks ended or started.
ended = []
@@ -1669,6 +1698,9 @@ export class SuperTabStore {
}
// A removed agent's or machine's host confirms its close or cleanup as the machine owner, who may have left the Swarm with it.
const actor: Actor = command.type === 'agent.sessionClosed' || command.type === 'machine.cleaned' ? { kind: 'person', userId: user.sub, email: user.email }
+ // The server's own crew dispatch (dispatchCrew), as the project's PM, with no sign-in of anyone's: only while that
+ // agent still leads a project in this write's state, and only for work.assign. No route reaches it.
+ : only.asProjectPm ? await this.projectPmActor(tx, original, only.asProjectPm, command, user)
: hostMachineId && 'startId' in command
? await this.poolHostActor(tx, user, original, hostMachineId, command.startId)
: await this.actor(tx, user, original, asAgentId, workspaceLeave && command.type === 'member.remove' && command.userId === user.sub && !asAgentId)
@@ -1923,6 +1955,7 @@ export class SuperTabStore {
: command.type === 'work.assign' || command.type === 'agent.start' ? command.routeDecisionId : undefined
if (decisionId) context.routeDecision = await readDecision(tx, tabId, decisionId) ?? fail('NOT_FOUND', 'This routing decision is unavailable.', 404)
const effects = applyCommand(original, actor, command, context)
+ crewed = effects.state.agents.some(a => !!a.crew)
// An agent-only notice changes nothing people see: no link, no unread mark, no project report.
const shown = effects.messages.filter(message => !agentOnly(message.source, message.recipients))
for (const group of effects.state.conversations) {
@@ -2237,9 +2270,153 @@ export class SuperTabStore {
})
this.endWork(tabId, ended)
this.startWork(tabId, started)
+ // A write that may free a crew member or open a task hands out work at once, not at the next 30-second sweep (dispatch.ts).
+ if (crewed && freesOrOpens(command)) this.dispatchSoon(tabId)
return done
}
+ /**
+ * The project PM the crew dispatch speaks as (dispatchCrew), checked inside the write as the agent path checks an agent:
+ * it still leads the task's own project and is not stopping, its grant holds (Workspace, machine, share: grantHolds), a
+ * PM in a Team account reaches only what its own session could (teamCommand), and the task is still one the dispatch would
+ * hand out now (its state may have moved since the pass read it: postponed, pinned, defined again). It only assigns.
+ */
+ private async projectPmActor(tx: Transaction, state: SuperTabState, agentId: string, command: Command, user: AuthUser): Promise<Actor> {
+ const pm = state.agents.find(a => a.id === agentId)
+ const task = command.type === 'work.assign' ? state.conversations.find(c => c.id === command.conversationId) : undefined
+ const project = task && groupProject(state, task)
+ // A refusal of the PM itself (gone, stopping, its grant or its Team boundary) is the PM's, not this pick's: marked so the
+ // pass waits a little on that PM instead of remembering the pick (dispatchCrew).
+ const pmRefused = (error: unknown): never => {
+ if (error instanceof SuperTabError) throw new SuperTabError(error.code, error.message, error.status, error.unreachable, { ...error.details, pmRefused: true })
+ throw error
+ }
+ if (!pm || !task || !project || pm.workDecision === 'stop' || ledProject(state, agentId)?.id !== project.id) {
+ return pmRefused(new SuperTabError('NOT_FOUND', 'This Super Tab is unavailable.', 404))
+ }
+ // The pick as this write's state has it: the member still free and in the crew, the task still its candidate (open, its
+ // day come, its lane or pin, not the one it just lost). What moved since the pass read is refused, and the next pass decides.
+ const assigned = command.type === 'work.assign' ? command.agentId : undefined
+ const now = this.now(), member = freeCrew(state, project.id, DISPATCH_RULES, now).find(a => a.id === assigned)
+ if (!member || !candidatesFor(state, member, DISPATCH_RULES, now).some(c => c.group.id === task.id)) {
+ fail('DISPATCH_STALE', 'This task is no longer one to hand out to this member.', 409)
+ }
+ try {
+ await this.agentGrant(tx, state, pm)
+ if (onTeamAccount(state, pm)) this.teamCommand(state, pm.machineId, user, command)
+ } catch (error) { return pmRefused(error) }
+ return { kind: 'agent', agentId, machineOwnerId: pm.machineOwnerId }
+ }
+
+ /** Picks whose work.assign was refused, by Swarm, task, round and member: for DISPATCH_REFUSAL_MS when their round cannot
+ * change the reason (LASTING_REFUSALS), else for DISPATCH_RETRY_MS; and PMs refused themselves, by Swarm and PM, for
+ * DISPATCH_RETRY_MS, so access that comes back is used within minutes (review 2 of #3230). Pruned every pass and bounded
+ * (dispatchRefusals.ts). Per process. */
+ private readonly refusedPicks = new RefusalMemory(DISPATCH_REFUSALS_HELD)
+ private readonly waitingPms = new RefusalMemory(DISPATCH_REFUSALS_HELD)
+ private refusedKey(tabId: string, group: Conversation, agentId: string): string { return `${tabId}:${group.id}:${roundOf(group)}:${agentId}` }
+ private refusedSkip(tabId: string, state: SuperTabState, now: number): Skip {
+ return (conversationId, agentId) => {
+ const group = state.conversations.find(c => c.id === conversationId)
+ return !!group && this.refusedPicks.refused(this.refusedKey(tabId, group, agentId), now)
+ }
+ }
+ /** Whether [project]'s PM was refused itself a moment ago: its project waits until DISPATCH_PM_RETRY_MS has passed. */
+ private pmWaiting(tabId: string, state: SuperTabState, project: SwarmProject, now: number): boolean {
+ const leadId = state.conversations.find(c => c.id === project.leadConversationId)?.leadId
+ return !!leadId && this.waitingPms.refused(`${tabId}:${leadId}`, now)
+ }
+
+ private readonly dispatchWaiting = new Map<string, ReturnType<typeof setTimeout>>()
+ /** Whether a write scheduled a dispatch pass for [tabId] that has not run yet (dispatchSoon). */
+ dispatchScheduled(tabId: string): boolean { return this.dispatchWaiting.has(tabId) }
+ /** Runs the crew dispatch for [tabId] a second from now, once however many writes asked: on servers whose hooks turn it on. */
+ private dispatchSoon(tabId: string): void {
+ if (!this.hooks.dispatch || this.dispatchWaiting.has(tabId)) return
+ const timer = setTimeout(() => {
+ this.dispatchWaiting.delete(tabId)
+ this.dispatchCrew(tabId).catch(error => logger.warn('[swarm-dispatch] pass failed', { tabId, error: error instanceof Error ? error.message : String(error) }))
+ }, DISPATCH_DEBOUNCE_MS)
+ timer.unref?.()
+ this.dispatchWaiting.set(tabId, timer)
+ }
+
+ /**
+ * Hands each free crew member of [tabId]'s projects its next task (dispatch.ts, task #3400): its pinned task, then its lane's
+ * top one. Reads the Swarm once, outside any write; each pick is the project's own work.assign, sent as its PM (the actor
+ * the PM itself would be), in that command's own transaction, so WORK_ACTIVE and AGENT_BUSY refuse a second assignment
+ * inside the write. The operation id names the task and its round (its last assignment), so passes racing from two servers
+ * replay one receipt or collide, and never assign twice. A refused pick is counted by code and the member's next task tried,
+ * up to DISPATCH_TRIES. A project with no PM, or no free crew, is left alone.
+ */
+ async dispatchCrew(tabId: string): Promise<{ assigned: number; skipped: Record<string, number> }> {
+ const out = { assigned: 0, skipped: {} as Record<string, number> }, started = performance.now()
+ const load: Record<string, { waiting: number; busy: number }> = {}
+ const skipCode = (code: string) => { out.skipped[code] = (out.skipped[code] ?? 0) + 1 }
+ const row = await this.db.superTab.findUnique({ where: { id: tabId }, select: { ...SWARM_ROW, autonomousEnv: true } })
+ if (!row || row.deletedAt || row.format !== 2) return out
+ const { state } = await loadRow(this.db, row)
+ const now = this.now(), rules = DISPATCH_RULES
+ if (state.paused) return out
+ this.refusedPicks.prune(now)
+ this.waitingPms.prune(now)
+ projects: for (const project of projectsOf(state)) {
+ if (this.pmWaiting(tabId, state, project, now)) continue
+ const free = freeCrew(state, project.id, rules, now)
+ if (!free.length) continue
+ for (const lane of laneCapacity(state, project.id, rules, now)) {
+ const total = load[lane.lane] ??= { waiting: 0, busy: 0 }
+ total.waiting += lane.waiting
+ total.busy += lane.busy
+ }
+ const leadId = state.conversations.find(c => c.id === project.leadConversationId)?.leadId
+ const lead = leadId ? state.agents.find(a => a.id === leadId) : undefined
+ if (!lead) { skipCode('NO_PM'); continue }
+ // No one's sign-in: the Swarm's environment for its reads, and the PM as the actor (executeOnce asProjectPm).
+ const user: AuthUser = { sub: lead.machineOwnerId, email: '', autonomousEnv: row.autonomousEnv as AuthUser['autonomousEnv'], role: 'user' }
+ const open = openTasks(state, project.id, now), taken = new Set<string>(), skip = this.refusedSkip(tabId, state, now)
+ for (const member of free) {
+ let tries = 0
+ for (const { group } of candidatesFor(state, member, rules, now, open, skip)) {
+ if (taken.has(group.id)) continue
+ if (++tries > DISPATCH_TRIES) break
+ try {
+ await this.executeOnce(user, tabId, { operationId: stableId('dispatch', group.id, roundOf(group)),
+ command: { type: 'work.assign', conversationId: group.id, agentId: member.id } }, undefined, undefined, false, { asProjectPm: lead.id })
+ taken.add(group.id)
+ out.assigned++
+ break
+ } catch (error) {
+ const code = error instanceof SuperTabError ? error.code : 'unknown'
+ skipCode(code)
+ // Another pass took this task, or this member: the next member, or the next task.
+ if (code === 'WORK_ACTIVE' || code === 'OPERATION_REUSED') { taken.add(group.id); continue }
+ if (code === 'unknown') throw error
+ // The PM itself was refused: nothing more for its project now; the sweep tries it again after a short wait.
+ if (error instanceof SuperTabError && error.details?.pmRefused) {
+ this.waitingPms.remember(`${tabId}:${lead.id}`, now + DISPATCH_RETRY_MS)
+ continue projects
+ }
+ // Paused meanwhile: nothing more this pass, and nothing remembered; a resume's next pass hands out work at once.
+ if (code === 'PAUSED') break projects
+ // What another write changed meanwhile (the member took work, its start is settling, the task moved): next pass.
+ if (code === 'AGENT_BUSY' || code === 'START_PENDING') break
+ if (code === 'DISPATCH_STALE') continue
+ // Not sent again for an hour if its round cannot change it, else for a short retry (DISPATCH_RETRY_MS).
+ this.refusedPicks.remember(this.refusedKey(tabId, group, member.id), now + (LASTING_REFUSALS.has(code) ? DISPATCH_REFUSAL_MS : DISPATCH_RETRY_MS))
+ if (code === 'AGENT_CLOSED' || code === 'STOP_REQUESTED') break
+ }
+ }
+ }
+ }
+ // One line a pass that did something (backend/AGENTS.md rule 4; ENGINEERING.md 8): counts, codes, lane loads and how long
+ // it took, never names or ids but the Swarm's.
+ if (out.assigned || Object.keys(out.skipped).length) {
+ logger.info('[swarm-dispatch] pass', { tabId, ...out, lanes: load, ms: Math.round(performance.now() - started) })
+ }
+ return out
+ }
+
private startWork(tabId: string, started: WorkHold[]): void {
if (!started.length || !this.hooks.workStarted) return
try { this.hooks.workStarted(tabId, started) } catch (error) {
@@ -3932,6 +4109,11 @@ export class SuperTabStore {
? crewNeedsMachine(state, now) ? await this.crewDeps(tx, state, now) : { admits: () => false } : null
const checked = [...failRefusedStarts(state, machineId, now), ...loseTasks(state, now, worker => worker.machineId === machineId),
...sweep ? sweepLiveness(state, now) : [], ...crew ? applyCrewKeep(state, now, crew) : []]
+ // The 30-second sweep also hands out work when the Swarm, as loaded here, has a free crew member and a task for it.
+ if (sweep && this.hooks.dispatch && projectsOf(state).some(p => !this.pmWaiting(tabId, state, p, now)
+ && dispatchPlan(state, p.id, DISPATCH_RULES, now, this.refusedSkip(tabId, state, now)).length)) {
+ afterCommit(tx, () => this.dispatchSoon(tabId))
+ }
// Then the agents it shows closed leave, those with no active work left: the Lead is told of their tasks above (closedAgents.ts).
const closedOut = removeClosedAgents(state, state.agents.filter(a => closed.includes(a.id)), now).map(a => a.id)
removedIds.push(...closedOut)
@@ -4780,6 +4962,10 @@ export class SuperTabStore {
// Back in its hands: the session's cross-Swarm fence covers it again if nothing does (endRuns).
await this.restoreRuns(tx, tabId, state, [group.assignment!.agentId])
}
+ // A task nobody holds whose pull request turned red or conflicts waits for its builder (dispatch.ts); a handed one the
+ // reopen above made active work is not pinned.
+ const pinned = pullRequestPin(watch)
+ if (pinned) pinBuilder(group, pinned, now)
const ownerId = ownerOf(state, group), owner = ownerId ? state.agents.find(a => a.id === ownerId) : undefined
// Written as its project's Lead, as the Swarm's own lines are (tidy.ts archiveLine); as the Engineer itself without one.
const leadId = state.conversations.find(c => c.id === groupProject(state, group).leadConversationId)?.leadId
diff --git a/backend/src/worker.ts b/backend/src/worker.ts
index 7165c6e53..0512a3259 100644
--- a/backend/src/worker.ts
+++ b/backend/src/worker.ts
@@ -26,7 +26,7 @@ import { startDeliveryCompaction } from './superTabs/deliveryCompaction.js'
import { startThreadBackfill } from './superTabs/threadBackfill.js'
import { appPullRequests, markFinishedGroups, startSwarmArchive, unknownPullRequests } from './superTabs/archive.js'
import { appPullRequestWatch, startPullRequestWatch } from './superTabs/pullRequestEvents.js'
-import { startMergeTrain } from './superTabs/mergeTrain/run.js'
+import { recordTrainRules, startMergeTrain } from './superTabs/mergeTrain/run.js'
import { teamAccountRequired } from './superTabs/machines.js'
import { PrismaApprovals } from './github/approvals.js'
import { SuperTabStore } from './superTabs/store.js'
@@ -162,11 +162,11 @@ async function start(): Promise<void> {
// GitHub events on an open task's pull request reach its Engineer within a minute (superTabs/pullRequestEvents.ts): only
// with the app, which reads them.
if (githubApp) stopPullRequestWatch = startPullRequestWatch(prisma, swarms, () => appPullRequestWatch(githubApp))
- // Every minute, each project whose merge train is switched on (its rules; off until then) merges what passed at its head, in
+ // Every minute, each project whose merge train is switched on (its rules record; off until saved on) merges what passed at its head, in
// batches through the app (superTabs/mergeTrain/, task #3402). Only where an agent's token could be had for the repository.
if (githubApp) {
const approvals = new PrismaApprovals(prisma)
- stopMergeTrain = startMergeTrain({ store: swarms, app: githubApp,
+ stopMergeTrain = startMergeTrain({ store: swarms, app: githubApp, rules: recordTrainRules(prisma),
approved: async (project, repository) => !teamAccountRequired() || approvals.approved(project.autonomousEnv, project.tabId, project.projectId, repository) })
}
// A delivery that can no longer move ends as Not sent, instead of waiting for good (superTabs/deliverySettle.ts).
diff --git a/backend/vitest.super-tabs.config.ts b/backend/vitest.super-tabs.config.ts
index dde6ed2c2..df766fe8f 100644
--- a/backend/vitest.super-tabs.config.ts
+++ b/backend/vitest.super-tabs.config.ts
@@ -8,5 +8,5 @@ export default defineConfig({ test: { include: ['integration/superTabs.test.ts',
'integration/superTabBuddyProbes.test.ts', 'integration/superTabBuddySessions.test.ts', 'integration/superTabSwarmBuddy.test.ts', 'integration/superTabPersonalLead.test.ts', 'integration/superTabCosts.test.ts', 'integration/harnessSharesList.test.ts', 'integration/harnessSharesIndexPlan.test.ts', 'integration/atlasSnapshot.test.ts', 'integration/queryStats.test.ts',
'integration/superTabEvidence.test.ts', 'integration/superTabAttemptModels.test.ts', 'integration/superTabNamedReads.test.ts', 'integration/swarmSweepPlans.test.ts', 'integration/overdueDecisions.test.ts', 'integration/workerIndexPlans.test.ts', 'integration/superTabReflection.test.ts', 'integration/superTabScorecard.test.ts',
'integration/superTabMessagePages.test.ts', 'integration/superTabDeliveryCompaction.test.ts', 'integration/superTabNoticeDigest.test.ts', 'integration/superTabPmSchedule.test.ts', 'integration/superTabDigestHour.test.ts', 'integration/superTabCommandLoads.test.ts', 'integration/superTabThreads.test.ts', 'integration/superTabMachineRemovals.test.ts',
- 'integration/superTabInstructions.test.ts', 'integration/superTabProjectRules.test.ts', 'integration/superTabWorkflow.test.ts', 'integration/superTabTaskLines.test.ts', 'integration/superTabDeletion.test.ts', 'integration/communityReports.test.ts', 'integration/superTabMachineNames.test.ts', 'integration/superTabComputerMoves.test.ts', 'integration/superTabTagsClear.test.ts', 'integration/swarmAgentTombstones.test.ts', 'integration/superTabPullRequestEvents.test.ts', 'integration/superTabReviewSteps.test.ts', 'integration/superTabMergeTrain.test.ts', 'integration/superTabProposals.test.ts', 'integration/superTabRequestReads.test.ts', 'integration/superTabVoiceMessages.test.ts', 'integration/superTabThumbnails.test.ts', 'integration/superTabProjectChatWorkers.test.ts', 'integration/prismaQueryTiming.test.ts', 'integration/secondaryReads.test.ts', 'integration/pushDevices.test.ts'], hookTimeout: 120000, testTimeout: 30000, setupFiles: ['integration/noDefaultDigest.test-support.ts', 'integration/cacheOn.test-support.ts', 'src/lib/noRedis.test-support.ts'],
+ 'integration/superTabInstructions.test.ts', 'integration/superTabProjectRules.test.ts', 'integration/superTabWorkflow.test.ts', 'integration/superTabTaskLines.test.ts', 'integration/superTabDeletion.test.ts', 'integration/communityReports.test.ts', 'integration/superTabMachineNames.test.ts', 'integration/superTabComputerMoves.test.ts', 'integration/superTabTagsClear.test.ts', 'integration/swarmAgentTombstones.test.ts', 'integration/superTabPullRequestEvents.test.ts', 'integration/superTabReviewSteps.test.ts', 'integration/superTabMergeTrain.test.ts', 'integration/superTabProposals.test.ts', 'integration/superTabRequestReads.test.ts', 'integration/superTabVoiceMessages.test.ts', 'integration/superTabThumbnails.test.ts', 'integration/superTabProjectChatWorkers.test.ts', 'integration/prismaQueryTiming.test.ts', 'integration/secondaryReads.test.ts', 'integration/pushDevices.test.ts', 'integration/crewDispatch.test.ts'], hookTimeout: 120000, testTimeout: 30000, setupFiles: ['integration/noDefaultDigest.test-support.ts', 'integration/cacheOn.test-support.ts', 'src/lib/noRedis.test-support.ts'],
fileParallelism: false, env: { NODE_ENV: 'test', HARNESS_CREDENTIAL_ENCRYPTION_KEY: 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=' } } })
diff --git a/cli/src/lib/projectFolder.spec.ts b/cli/src/lib/projectFolder.spec.ts
index 206f37668..4be5250cc 100644
--- a/cli/src/lib/projectFolder.spec.ts
+++ b/cli/src/lib/projectFolder.spec.ts
@@ -421,7 +421,8 @@ describe('the project clone of a large repository', () => {
gitIn(dest, 'fetch', '-q', 'origin', 'feature')
gitIn(dest, 'checkout', '-q', 'feature')
expect(await readFile(join(dest, 'feature.txt'), 'utf8')).toBe('feature work\n')
- })
+ // It runs a real git clone, which took over the default 5 s on a loaded CI runner.
+ }, 60_000)
/** A stand-in for git at [root]/fake-git: [body] runs for `clone`; `config` succeeds. Its pid is written to [root]/pid. */
async function fakeGit(body: string): Promise<string> {
diff --git a/cli/src/lib/swarmSkills.spec.ts b/cli/src/lib/swarmSkills.spec.ts
index 3963b9317..b55230896 100644
--- a/cli/src/lib/swarmSkills.spec.ts
+++ b/cli/src/lib/swarmSkills.spec.ts
@@ -247,7 +247,9 @@ describe('built-in Swarm skills', () => {
// Task #2963 (Ken, 2026-11-04): a post that names no one no longer reaches the Lead.
const reaches = '- A post reaches only the agents you name, with --to <agent id> or @Name in its text, any agent of this project; they join the group if they are not in it. A reply also reaches the agent whose message it answers. A post in a task or step that names no one reaches its assigned agent, and anywhere else no agent.\n'
const status = '- The Lead hears your work through your status (done, stuck, needs a human): never post it a result, a verdict, a Ready or an acknowledgement.\n'
- const whoReaches = (role: 'lead' | 'dev' | 'review') => `## Who a post reaches\n${reaches}${role === 'lead' ? '- Agents report to you through their status; their posts reach you only when they name you.\n'
+ // Task #3029 (Gray, 2026-11-05): an agent that needed a person ("press Connect on the iPhone") wrote it only in its terminal.
+ const askPerson = '- When you need a person to do something (press a button, plug in or unlock a device, sign in, decide), never ask only in your terminal: nobody reads it there. Post the ask in the task\'s conversation, tag the person by @username, and set needs_human on your task with that one question; with no task of your own, ask it as a decision.\n'
+ const whoReaches = (role: 'lead' | 'dev' | 'review') => `## Who a post reaches\n${reaches}${askPerson}${role === 'lead' ? '- Agents report to you through their status; their posts reach you only when they name you.\n'
: `${role === 'dev' ? '- Answer your Reviewer, and tell it a fix is pushed, with --to its agent id.\n' : '- Send your verdict and findings to the Builder with --to its agent id.\n'}${status}`}\n`
// The Builder's 👀 replaces its "say that you took it" line, in both modes.
const took = '- React 👀 to the message that assigned it and mark it working; your first post is your plan or a first result, never that you took it.\n'
@@ -268,6 +270,13 @@ describe('built-in Swarm skills', () => {
}
})
// Project instructions, phase 1: agents talk to each other by name; since #2963 an unnamed post never goes to the Lead.
+ it('tells every role to post an ask for a person in the task, tagged, never only in its terminal (task #3029)', () => {
+ for (const mode of ['orchestration', 'default'] as const) for (const role of ['lead', 'dev', 'review'] as const) {
+ const text = readFileSync(prepareSwarmSkill(fixture(), { role, key: 'session', mode }).file, 'utf8')
+ expect(text.split(askPerson), `${mode} ${role}`).toHaveLength(2)
+ expect(askPerson).toMatch(/never ask only in your terminal.*Post the ask in the task.*tag the person.*needs_human/)
+ }
+ })
it('tells every role who a post reaches, the Builder to answer its Reviewer and the Reviewer its Builder by name', () => {
for (const mode of ['orchestration', 'default'] as const) for (const role of ['lead', 'dev', 'review'] as const) {
const text = readFileSync(prepareSwarmSkill(fixture(), { role, key: 'session', mode }).file, 'utf8')
@@ -1072,7 +1081,8 @@ describe('a Buddy\'s folder', () => {
// built-in text it launched with, for a Swarm with no instructions, and a row an older CLI saved relaunches onto its own.
describe('role kinds keep their role files', () => {
/** The whole file a Reviewer's launch writes in each mode, byte for byte, as before role kinds (its post rules as of #3057). */
- const REVIEW = { orchestration: '9238d7fd7a516bee7b5d64d4145e2a1fa9cb4e96c5d9a4cdddb5751cd346db98', default: 'd8cab4c0afa83e57a2975caeda63341ed839ba94c4ab56b35c138275e3ad22c2' }
+ // Task #3029's ask-a-person line changed both; the byte-for-byte tests above show it is the only change.
+ const REVIEW = { orchestration: 'a308926d41b60cdbe3405d25b9c89a2c8924cfe3b65a1d6a0ab3106165279316', default: '9a010ed13a8b1c1019a8aee156baa94c0cfe9c657d2a614ff24fc746a454663e' }
const folder = (workspace: string, key: string, name: string) =>
join(realpathSync(workspace), '.harness', 'runtime', sha256(key), 'swarm', 'skills', name)
it('keeps each session\'s role file', () => {
diff --git a/cli/src/lib/swarmSkills.ts b/cli/src/lib/swarmSkills.ts
index f03392e1d..0389ed2ce 100644
--- a/cli/src/lib/swarmSkills.ts
+++ b/cli/src/lib/swarmSkills.ts
@@ -164,6 +164,7 @@ For large work, post the group plan and get the owner's ok before assigning; onc
## Who a post reaches
- A post reaches only the agents you name, with --to <agent id> or @Name in its text, any agent of this project; they join the group if they are not in it. A reply also reaches the agent whose message it answers. A post in a task or step that names no one reaches its assigned agent, and anywhere else no agent.
+- When you need a person to do something (press a button, plug in or unlock a device, sign in, decide), never ask only in your terminal: nobody reads it there. Post the ask in the task's conversation, tag the person by @username, and set needs_human on your task with that one question; with no task of your own, ask it as a decision.
- Agents report to you through their status; their posts reach you only when they name you.
## Reactions
@@ -315,6 +316,7 @@ Record each acceptance check with the exact command, revision and observed resul
## Who a post reaches
- A post reaches only the agents you name, with --to <agent id> or @Name in its text, any agent of this project; they join the group if they are not in it. A reply also reaches the agent whose message it answers. A post in a task or step that names no one reaches its assigned agent, and anywhere else no agent.
+- When you need a person to do something (press a button, plug in or unlock a device, sign in, decide), never ask only in your terminal: nobody reads it there. Post the ask in the task's conversation, tag the person by @username, and set needs_human on your task with that one question; with no task of your own, ask it as a decision.
- Answer your Reviewer, and tell it a fix is pushed, with --to its agent id.
- The Lead hears your work through your status (done, stuck, needs a human): never post it a result, a verdict, a Ready or an acknowledgement.
@@ -393,6 +395,7 @@ Mark your review assignment done with the verdict and revision. Print little.
## Who a post reaches
- A post reaches only the agents you name, with --to <agent id> or @Name in its text, any agent of this project; they join the group if they are not in it. A reply also reaches the agent whose message it answers. A post in a task or step that names no one reaches its assigned agent, and anywhere else no agent.
+- When you need a person to do something (press a button, plug in or unlock a device, sign in, decide), never ask only in your terminal: nobody reads it there. Post the ask in the task's conversation, tag the person by @username, and set needs_human on your task with that one question; with no task of your own, ask it as a decision.
- Send your verdict and findings to the Builder with --to its agent id.
- The Lead hears your work through your status (done, stuck, needs a human): never post it a result, a verdict, a Ready or an acknowledgement.
@@ -503,6 +506,7 @@ When the project owner asks in chat to switch this project's skills (Default or
## Who a post reaches
- A post reaches only the agents you name, with --to <agent id> or @Name in its text, any agent of this project; they join the group if they are not in it. A reply also reaches the agent whose message it answers. A post in a task or step that names no one reaches its assigned agent, and anywhere else no agent.
+- When you need a person to do something (press a button, plug in or unlock a device, sign in, decide), never ask only in your terminal: nobody reads it there. Post the ask in the task's conversation, tag the person by @username, and set needs_human on your task with that one question; with no task of your own, ask it as a decision.
- Agents report to you through their status; their posts reach you only when they name you.
## Reactions
@@ -584,6 +588,7 @@ You finish one group's work completely, inside its brief, as if nobody will come
## Who a post reaches
- A post reaches only the agents you name, with --to <agent id> or @Name in its text, any agent of this project; they join the group if they are not in it. A reply also reaches the agent whose message it answers. A post in a task or step that names no one reaches its assigned agent, and anywhere else no agent.
+- When you need a person to do something (press a button, plug in or unlock a device, sign in, decide), never ask only in your terminal: nobody reads it there. Post the ask in the task's conversation, tag the person by @username, and set needs_human on your task with that one question; with no task of your own, ask it as a decision.
- Answer your Reviewer, and tell it a fix is pushed, with --to its agent id.
- The Lead hears your work through your status (done, stuck, needs a human): never post it a result, a verdict, a Ready or an acknowledgement.
@@ -635,6 +640,7 @@ Mark your review done with the verdict and revision.
## Who a post reaches
- A post reaches only the agents you name, with --to <agent id> or @Name in its text, any agent of this project; they join the group if they are not in it. A reply also reaches the agent whose message it answers. A post in a task or step that names no one reaches its assigned agent, and anywhere else no agent.
+- When you need a person to do something (press a button, plug in or unlock a device, sign in, decide), never ask only in your terminal: nobody reads it there. Post the ask in the task's conversation, tag the person by @username, and set needs_human on your task with that one question; with no task of your own, ask it as a decision.
- Send your verdict and findings to the Builder with --to its agent id.
- The Lead hears your work through your status (done, stuck, needs a human): never post it a result, a verdict, a Ready or an acknowledgement.
diff --git a/desktop/lib/super_tabs/activity.dart b/desktop/lib/super_tabs/activity.dart
index 2b894e911..dcdce8565 100644
--- a/desktop/lib/super_tabs/activity.dart
+++ b/desktop/lib/super_tabs/activity.dart
@@ -11,8 +11,9 @@ import 'model.dart';
import 'notifications.dart';
import 'reminders.dart';
-/// What one row of Needs you is.
-enum SuperTabNeedKind { decision, agent }
+/// What one row of Needs you is: a decision, an agent that asked the reader,
+/// or an agent of their task waiting at a prompt in its terminal (#3029).
+enum SuperTabNeedKind { decision, agent, prompt }
/// One row of Needs you: a decision asked of the reader, or an agent waiting
/// on them.
@@ -29,7 +30,7 @@ class SuperTabNeed {
});
final SuperTabNeedKind kind;
- /// Stable across reads: `decision:<id>`, `agent:<group>`.
+ /// Stable across reads: `decision:<id>`, `agent:<group>`, `prompt:<agent>`.
final String id;
/// What the row says: the question, or `<agent> is waiting on you`.
@@ -178,6 +179,15 @@ class SuperTabActivity extends ChangeNotifier {
question: _askedBy(group),
agentId: group.assignment!['agentId'] as String,
),
+ for (final wait in snapshot.promptsWaiting)
+ SuperTabNeed(
+ kind: SuperTabNeedKind.prompt,
+ id: 'prompt:${wait.agentId}',
+ title: '${wait.agentName} is waiting at a prompt in its terminal',
+ conversationId: wait.conversationId,
+ question: wait.conversationTitle,
+ agentId: wait.agentId,
+ ),
];
}
@@ -296,6 +306,7 @@ class SuperTabActivity extends ChangeNotifier {
? decisions.open.length
: snapshot.decisionsWaiting) +
_asking(snapshot).length +
+ snapshot.promptsWaiting.length +
reminders.due.length;
}
diff --git a/desktop/lib/super_tabs/decisions_page.dart b/desktop/lib/super_tabs/decisions_page.dart
index 3101a157b..4891221a2 100644
--- a/desktop/lib/super_tabs/decisions_page.dart
+++ b/desktop/lib/super_tabs/decisions_page.dart
@@ -13,22 +13,36 @@ import 'decisions.dart';
import 'decisions_view.dart' show quietDecisionAction;
import 'model.dart';
import 'page_rows.dart';
+import 'prompt_lines.dart';
import 'reminders.dart';
/// Decisions, the sidebar's first page (anh Dee, 11-05, task #2996): what
/// waits on the reader's answer, as Needs you listed it. Due reminders lead,
-/// then the agents waiting on them, then the decisions by day. Each can be
-/// answered here: a decision by an option or in words, an agent in words.
+/// then the agents waiting on them (an agent of their task at a prompt in its
+/// terminal too, task #3029), then the decisions by day. Each can be answered
+/// here: a decision by an option or in words, an agent in words or at its
+/// prompt.
class SuperTabDecisionsPage extends StatefulWidget {
const SuperTabDecisionsPage({
super.key,
required this.activity,
required this.onOpenConversation,
this.onOpenReminder,
+ this.highlight,
+ this.highlightTurn = 0,
this.now = DateTime.now,
});
final SuperTabActivity activity;
+ /// The need a notice opened the page for (`decision:<id>`, as
+ /// [SuperTabNeed.id]): its row lights for a moment, so the reader sees which
+ /// one (task #3029). [highlightTurn] lights it again for the same need.
+ final String? highlight;
+ final int highlightTurn;
+
+ /// How long a [highlight] stays lit.
+ static const lit = Duration(milliseconds: 1800);
+
/// Opens the chat of an agent waiting on the reader, or of a decision.
final ValueChanged<String> onOpenConversation;
@@ -44,10 +58,15 @@ class _DecisionsPageState extends State<SuperTabDecisionsPage> {
late SuperTabActivity _activity = widget.activity;
bool _handledShown = false;
+ /// The row lit for a moment ([SuperTabDecisionsPage.highlight]).
+ String? _lit;
+ Timer? _unlight;
+
@override
void initState() {
super.initState();
_activity.opened();
+ _light(widget.highlight);
}
@override
@@ -57,14 +76,47 @@ class _DecisionsPageState extends State<SuperTabDecisionsPage> {
_activity.closed();
_activity = widget.activity..opened();
}
+ if (widget.highlight != old.highlight ||
+ widget.highlightTurn != old.highlightTurn) {
+ _light(widget.highlight);
+ }
+ }
+
+ void _light(String? id) {
+ _unlight?.cancel();
+ _lit = id;
+ if (id == null) return;
+ _unlight = Timer(SuperTabDecisionsPage.lit, () {
+ if (mounted) setState(() => _lit = null);
+ });
}
@override
void dispose() {
+ _unlight?.cancel();
_activity.closed();
super.dispose();
}
+ /// [row], washed in the accent while it is the one lit, and brought into
+ /// view. One shape lit or not, so the row keeps its state (a typed answer).
+ Widget _lighting(String id, Widget row) {
+ final lit = _lit == id;
+ return AnimatedContainer(
+ duration: const Duration(milliseconds: 240),
+ decoration: BoxDecoration(
+ color: lit ? grid.AppSurface.accentWashHover : Colors.transparent,
+ borderRadius: BorderRadius.circular(grid.AppDesktop.fieldRadius),
+ ),
+ child: Stack(
+ children: [
+ row,
+ if (lit) _BringIntoView(key: ValueKey('super-activity-lit:$id')),
+ ],
+ ),
+ );
+ }
+
String _when(DateTime at) => superTabPageWhen(context, at, widget.now());
SuperTabSnapshot? get _snapshot => _activity.controller.snapshot;
@@ -195,8 +247,13 @@ class _DecisionsPageState extends State<SuperTabDecisionsPage> {
// decisions, and is not left to the PM.
for (final reminder in due) _reminder(reminder),
// An agent waiting has no time of its own: it leads, above the days.
- for (final n in waiting) _need(n),
- ...superTabByDay<SuperTabNeed>(decided, (n) => n.at, _need, widget.now()),
+ for (final n in waiting) _lighting(n.id, _need(n)),
+ ...superTabByDay<SuperTabNeed>(
+ decided,
+ (n) => n.at,
+ (n) => _lighting(n.id, _need(n)),
+ widget.now(),
+ ),
];
}
@@ -227,6 +284,7 @@ class _DecisionsPageState extends State<SuperTabDecisionsPage> {
Widget _need(SuperTabNeed need) {
final decision = need.decision;
+ if (need.kind == SuperTabNeedKind.prompt) return _prompt(need);
if (decision == null) {
final project = _snapshot?.projectFor(need.conversationId);
return SuperTabPageRow(
@@ -296,6 +354,51 @@ class _DecisionsPageState extends State<SuperTabDecisionsPage> {
);
}
+ /// An agent of the reader's task at a prompt in its terminal (task #3029):
+ /// its last lines, and its terminal a click away, beside the task. It
+ /// leaves once the agent moves on (the read drops it).
+ Widget _prompt(SuperTabNeed need) {
+ final agentId = need.agentId!;
+ final project = _snapshot?.projectFor(need.conversationId);
+ void open() {
+ widget.onOpenConversation(need.conversationId);
+ _activity.controller.openAgentTerminal(
+ agentId,
+ conversationId: need.conversationId,
+ );
+ }
+
+ return SuperTabPageRow(
+ key: ValueKey('super-activity-row-${need.id}'),
+ avatarName: _snapshot?.agent(agentId)?.displayName ?? need.title,
+ who: need.title,
+ where: project?.name,
+ privateWhere: project?.isPrivate == true,
+ trailing: 'Open',
+ preview: need.question,
+ extra: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ SuperTabPromptLines(
+ key: ValueKey('super-prompt-read:$agentId'),
+ controller: _activity.controller,
+ agentId: agentId,
+ ),
+ Padding(
+ padding: const EdgeInsets.only(top: grid.AppDesktop.controlGap),
+ child: OutlinedButton(
+ key: ValueKey('super-prompt-open:$agentId'),
+ onPressed: open,
+ child: const Text('Open terminal'),
+ ),
+ ),
+ ],
+ ),
+ onTap: open,
+ );
+ }
+
Widget _reminder(SuperTabReminder reminder) {
final project = _snapshot?.projectFor(reminder.conversationId);
final name = reminder.authorName?.trim() ?? '';
@@ -507,3 +610,31 @@ class _AnswerInWordsState extends State<_AnswerInWords> {
);
}
}
+
+/// Brings the row it sits in into view once, as it lights.
+class _BringIntoView extends StatefulWidget {
+ const _BringIntoView({super.key});
+
+ @override
+ State<_BringIntoView> createState() => _BringIntoViewState();
+}
+
+class _BringIntoViewState extends State<_BringIntoView> {
+ @override
+ void initState() {
+ super.initState();
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ if (!mounted) return;
+ unawaited(
+ Scrollable.ensureVisible(
+ context,
+ alignment: 0.3,
+ duration: const Duration(milliseconds: 200),
+ ),
+ );
+ });
+ }
+
+ @override
+ Widget build(BuildContext context) => const SizedBox.shrink();
+}
diff --git a/desktop/lib/super_tabs/member_groups.dart b/desktop/lib/super_tabs/member_groups.dart
new file mode 100644
index 000000000..337388b99
--- /dev/null
+++ b/desktop/lib/super_tabs/member_groups.dart
@@ -0,0 +1,239 @@
+import 'backlog.dart';
+import 'model.dart';
+import 'task_groups.dart';
+import 'zone_time.dart';
+
+/// How many tasks a crew member may have handed over and still take the next
+/// (backend dispatch.ts `DISPATCH_RULES.maxHanded`).
+const superTabMaxHanded = 3;
+
+/// Where a crew member stands: a task in its hands, as many handed over as
+/// it may have, or free for the next one.
+enum SuperTabMemberState {
+ working('Working'),
+ full('Full'),
+ free('Free');
+
+ const SuperTabMemberState(this.label);
+ final String label;
+}
+
+/// One crew member's column in the Tasks view's Members layout (task #3400):
+/// the tasks in its hands, and those it handed over for review.
+class SuperTabMemberColumn {
+ const SuperTabMemberColumn({
+ required this.agent,
+ required this.inHand,
+ required this.handed,
+ });
+ final SuperTabAgent agent;
+ final List<SuperTabTaskEntry> inHand, handed;
+
+ /// Read from all its tasks: what a search or Mine hides still counts.
+ SuperTabMemberState get state => inHand.isNotEmpty
+ ? SuperTabMemberState.working
+ : handed.length >= superTabMaxHanded
+ ? SuperTabMemberState.full
+ : SuperTabMemberState.free;
+}
+
+/// A task nobody holds, with the lane the Swarm hands it out in (null when
+/// no lane owns it, or the server is one from before hand-out lanes).
+typedef SuperTabUnassignedEntry = ({SuperTabTaskEntry entry, String? lane});
+
+/// The heading of [agent]'s column: its name, then its lane when it has one.
+String superTabMemberHeading(SuperTabAgent agent) =>
+ [agent.displayName ?? agent.name, ?_laneName(agent.crewLane)].join(' · ');
+
+/// [lane] as the lane table names it (the crew mark keeps it in lower case).
+String? _laneName(String? lane) => lane == null
+ ? null
+ : _laneOrder.firstWhere(
+ (name) => name.toLowerCase() == lane.toLowerCase(),
+ orElse: () => lane,
+ );
+
+/// Work on [task] that is still on (backend model.ts `activeWork`).
+bool _active(SuperTabConversation task) => const {
+ 'working',
+ 'needs_human',
+ 'blocked',
+ 'review',
+ 'planned',
+ 'reconciling',
+}.contains(task.assignment?['status']);
+
+/// Handed over: its own status is review (backend handed.ts); a step's
+/// review is not a hand-over.
+bool _handed(SuperTabConversation task) =>
+ task.reviewOf == null && task.assignment?['status'] == 'review';
+
+/// Nobody holds it and it is not finished: no active work, and not done or
+/// cancelled.
+bool _unheld(SuperTabConversation task) =>
+ !_active(task) &&
+ !const {'done', 'cancelled'}.contains(task.assignment?['status']);
+
+/// The Members layout of a project: a column for each crew member of
+/// [projectId] among [agents], in roster order, and the open tasks of
+/// [entries] (the board's cards, unfiltered) that nobody holds.
+///
+/// A member's column has what is in its hands (active work it has not
+/// handed over), then what it handed over. Unassigned goes in the Swarm's
+/// hand-out order (backend dispatch.ts `openTasks`): P0 first, then the
+/// project's shared queue; each with its hand-out lane.
+({List<SuperTabMemberColumn> members, List<SuperTabUnassignedEntry> unassigned})
+superTabMemberGroups({
+ required Iterable<SuperTabAgent> agents,
+ required String projectId,
+ required Iterable<SuperTabTaskEntry> entries,
+}) {
+ final open = {
+ for (final entry in entries)
+ if (entry.task case final task? when !superTabTaskShipped(task))
+ task.id: entry,
+ };
+ final tasks = [for (final e in open.values) e.task!];
+ final members = [
+ for (final agent in agents)
+ if (agent.crewRole != null &&
+ agent.projectId == projectId &&
+ !agent.isBuddy)
+ SuperTabMemberColumn(
+ agent: agent,
+ inHand: [
+ for (final t in tasks)
+ if (t.assignment?['agentId'] == agent.id &&
+ _active(t) &&
+ !_handed(t))
+ open[t.id]!,
+ ],
+ handed: [
+ for (final t in tasks)
+ if (t.assignment?['agentId'] == agent.id && _handed(t))
+ open[t.id]!,
+ ],
+ ),
+ ];
+ final queue = superTabQueueOrder(tasks.where(_unheld));
+ return (
+ members: members,
+ unassigned: [
+ for (final t in [
+ ...queue.where((t) => t.priority == 'P0'),
+ ...queue.where((t) => t.priority != 'P0'),
+ ])
+ (entry: open[t.id]!, lane: t.handOutLane),
+ ],
+ );
+}
+
+/// The lanes in the dispatch table's order (backend dispatch.ts
+/// `DISPATCH_RULES.lanes`).
+const _laneOrder = ['backend', 'CLI', 'Desktop', 'mobile', 'docs'];
+
+/// One lane of a crew project, worked out from its tasks: those waiting for
+/// a member, those in hand, and when the oldest waiting one began waiting.
+class SuperTabLaneCapacity {
+ const SuperTabLaneCapacity({
+ required this.lane,
+ required this.waiting,
+ required this.busy,
+ required this.oldestAt,
+ });
+ final String lane;
+ final int waiting, busy;
+ final DateTime? oldestAt;
+}
+
+/// When [task] began waiting with nobody holding it: when it was orphaned,
+/// else when its last attempt was lost (backend dispatch.ts `waitingSince`).
+DateTime? _waitingSince(SuperTabConversation task) {
+ final liveness = task.liveness;
+ final lost = task.assignment?['lost'];
+ final since = liveness?['state'] == 'orphaned'
+ ? liveness!['since']
+ : lost is Map
+ ? lost['at']
+ : null;
+ return since is num
+ ? DateTime.fromMillisecondsSinceEpoch(since.toInt())
+ : null;
+}
+
+/// [tasks]' lanes at [now], as the dispatch counts them (backend dispatch.ts
+/// `laneCapacity`), from each task's hand-out lane: waiting, a task not
+/// archived, nobody holding it, not done or cancelled, whose not-before day
+/// has come in the project's [timeZone] (Vietnam's when null or unknown, as
+/// the server reads it); busy, one with active work. The oldest is the
+/// earliest a waiting task began waiting. Lanes in the table's order, only
+/// those with work; none from a server before hand-out lanes. Every task the
+/// app holds counts, so one changed task moves the line.
+List<SuperTabLaneCapacity> superTabLaneCapacity(
+ Iterable<SuperTabConversation> tasks,
+ DateTime now, {
+ String? timeZone,
+}) {
+ final today = superTabDateIn(timeZone ?? superTabDefaultTimeZone, now);
+ final waiting = <String, int>{}, busy = <String, int>{};
+ final oldest = <String, DateTime>{};
+ for (final task in tasks) {
+ final lane = task.handOutLane;
+ if (lane == null || task.archived) continue;
+ if (_active(task)) {
+ busy[lane] = (busy[lane] ?? 0) + 1;
+ continue;
+ }
+ if (!_unheld(task)) continue;
+ if (task.notBefore case final day?
+ when DateTime.utc(day.year, day.month, day.day).isAfter(today)) {
+ continue;
+ }
+ waiting[lane] = (waiting[lane] ?? 0) + 1;
+ final since = _waitingSince(task);
+ final held = oldest[lane];
+ if (since != null && (held == null || since.isBefore(held))) {
+ oldest[lane] = since;
+ }
+ }
+ int rank(String lane) => switch (_laneOrder.indexOf(lane)) {
+ -1 => _laneOrder.length,
+ final i => i,
+ };
+ final lanes = [
+ ...{...waiting.keys, ...busy.keys},
+ ]..sort((a, b) => rank(a) - rank(b));
+ return [
+ for (final lane in lanes)
+ SuperTabLaneCapacity(
+ lane: lane,
+ waiting: waiting[lane] ?? 0,
+ busy: busy[lane] ?? 0,
+ oldestAt: oldest[lane],
+ ),
+ ];
+}
+
+/// The lanes' capacity as one line: "Desktop: 6 waiting, 2 busy, oldest 2 h",
+/// lanes joined by middle dots. The oldest is in whole hours, rounded down,
+/// or in minutes under an hour, and left out when none was recorded. Null
+/// with no lanes.
+String? superTabCapacityLine(List<SuperTabLaneCapacity> lanes, DateTime now) {
+ if (lanes.isEmpty) return null;
+ String oldest(DateTime at) {
+ final age = now.difference(at);
+ if (age.isNegative) return 'oldest 0 min';
+ return age.inHours >= 1
+ ? 'oldest ${age.inHours} h'
+ : 'oldest ${age.inMinutes} min';
+ }
+
+ return [
+ for (final lane in lanes)
+ [
+ '${lane.lane}: ${lane.waiting} waiting',
+ '${lane.busy} busy',
+ if (lane.oldestAt case final at?) oldest(at),
+ ].join(', '),
+ ].join(' · ');
+}
diff --git a/desktop/lib/super_tabs/model.dart b/desktop/lib/super_tabs/model.dart
index 84180e708..dcdf71c41 100644
--- a/desktop/lib/super_tabs/model.dart
+++ b/desktop/lib/super_tabs/model.dart
@@ -428,6 +428,9 @@ class SuperTabConversation {
: null,
queueRank = (row['queueRank'] as num?)?.toDouble(),
priority = row['priority'] as String?,
+ handOutLane = row['handOutLane'] is String
+ ? row['handOutLane'] as String
+ : null,
notBefore = DateTime.tryParse(row['notBefore'] as String? ?? ''),
lastMessageSequence = (row['lastMessageSequence'] as num?)?.toInt() ?? 0,
lastMainSequence = (row['lastMainSequence'] as num?)?.toInt(),
@@ -536,6 +539,11 @@ class SuperTabConversation {
/// whose title may still mark one (`superTabTaskPriority`, backlog.dart).
final String? priority;
+ /// The lane the crew dispatch hands this task out in (backend read/views.ts
+ /// `handOutLane`, task #3400): its PM's, else its owned paths'. Null when
+ /// no lane owns it, on a chat or a step, and from an older server.
+ final String? handOutLane;
+
/// The day before which its work may not start, a promise the PM keeps
/// ("remove the preview route after Dec 4"); null when there is none.
final DateTime? notBefore;
@@ -550,6 +558,10 @@ class SuperTabConversation {
final Map<String, dynamic>? leadAction;
}
+/// The zone a project's day is read in when its digest names none (backend
+/// costs/reflection.ts `DEFAULT_TIME_ZONE`).
+const superTabDefaultTimeZone = 'Asia/Ho_Chi_Minh';
+
class SuperTabProject {
SuperTabProject.fromJson(Map<String, dynamic> row)
: id = _text(row, 'id'),
@@ -573,6 +585,10 @@ class SuperTabProject {
superTabMap(member)['generation'] as String?,
},
updateMinutes = (row['updateMinutes'] as num?)?.toInt() ?? 5,
+ timeZone = switch (row['digest']) {
+ {'timeZone': final String zone} when zone.isNotEmpty => zone,
+ _ => superTabDefaultTimeZone,
+ },
status = SuperTabProjectStatus.read(row['status']),
repository = row['repository'] is Map
? Map.unmodifiable(superTabMap(row['repository']))
@@ -582,6 +598,11 @@ class SuperTabProject {
);
final String id, name, ownerId, leadConversationId;
+ /// The zone its day is read in, as the server reads it for the crew
+ /// dispatch and the morning digest: its digest's, else
+ /// [superTabDefaultTimeZone] (backend dispatch.ts `openTasks`).
+ final String timeZone;
+
/// Sent to the daemon unchanged as `swarmSkillMode` when an agent starts (an older CLI refuses other values).
final String skillMode;
@@ -709,6 +730,43 @@ class SuperTabProjectStatus {
final String? by;
}
+/// One task agent at a prompt in its terminal, waiting for the reader, as the
+/// backend lists it: no screen text, which the reader's app reads through the
+/// terminal read that checks who may (task #3029).
+class SuperTabPromptWait {
+ const SuperTabPromptWait({
+ required this.agentId,
+ required this.agentName,
+ required this.conversationId,
+ required this.conversationTitle,
+ required this.projectId,
+ required this.projectName,
+ });
+ final String agentId, agentName, conversationId, conversationTitle;
+ final String projectId, projectName;
+
+ /// Null for a row missing what it needs.
+ static SuperTabPromptWait? read(Map<String, dynamic> row) => switch (row) {
+ {
+ 'agentId': final String agentId,
+ 'agentName': final String agentName,
+ 'conversationId': final String conversationId,
+ 'conversationTitle': final String conversationTitle,
+ 'projectId': final String projectId,
+ 'projectName': final String projectName,
+ } =>
+ SuperTabPromptWait(
+ agentId: agentId,
+ agentName: agentName,
+ conversationId: conversationId,
+ conversationTitle: conversationTitle,
+ projectId: projectId,
+ projectName: projectName,
+ ),
+ _ => null,
+ };
+}
+
class SuperTabSnapshot {
SuperTabSnapshot.fromJson(Map<String, dynamic> row)
: id = _text(row, 'id'),
@@ -766,6 +824,10 @@ class SuperTabSnapshot {
mentionsDigest = row['mentionsDigest'] as String?,
decisionsWaiting = (row['decisionsWaiting'] as num?)?.toInt() ?? 0,
decisionsDigest = row['decisionsDigest'] as String?,
+ promptsWaiting = List.unmodifiable([
+ for (final wait in row['promptsWaiting'] as List? ?? const [])
+ if (wait is Map) ?SuperTabPromptWait.read(superTabMap(wait)),
+ ]),
activityDigest = row['activityDigest'] as String?,
remindersDigest = row['remindersDigest'] as String?,
_pulses = SuperTabPulse.readAll(row['pulse']),
@@ -903,6 +965,11 @@ class SuperTabSnapshot {
/// count may not; null from a backend before it (superTabs/decisions.ts).
final String? decisionsDigest;
+ /// The task agents waiting at a prompt in their terminals for the reader
+ /// (backend superTabs/promptWaits.ts): under Decisions, counted with them.
+ /// Empty from a backend before it (task #3029).
+ final List<SuperTabPromptWait> promptsWaiting;
+
/// Which of the reader's Activity rows are unread (replies to them, reactions to their messages), as a digest
/// that moves when one comes or is read; null from a backend before Activity (superTabs/activity.ts).
final String? activityDigest;
diff --git a/desktop/lib/super_tabs/parts.dart b/desktop/lib/super_tabs/parts.dart
index 184ac753b..7ccaac1ca 100644
--- a/desktop/lib/super_tabs/parts.dart
+++ b/desktop/lib/super_tabs/parts.dart
@@ -488,6 +488,9 @@ class SuperTabParts {
if (_derived['decisionsDigest'] case final String digest) {
state['decisionsDigest'] = digest;
}
+ if (_derived['promptsWaiting'] case final List waiting) {
+ state['promptsWaiting'] = waiting;
+ }
if (_derived['remindersDigest'] case final String digest) {
state['remindersDigest'] = digest;
}
diff --git a/desktop/lib/super_tabs/prompt_lines.dart b/desktop/lib/super_tabs/prompt_lines.dart
new file mode 100644
index 000000000..bc346908e
--- /dev/null
+++ b/desktop/lib/super_tabs/prompt_lines.dart
@@ -0,0 +1,163 @@
+import 'package:flutter/foundation.dart' show kIsWeb;
+import 'package:flutter/material.dart';
+
+import '../shared/theme/app_theme.dart' as grid;
+import '../widgets/desktop_chrome.dart';
+import 'controller.dart';
+
+/// What a Decisions prompt row shows of its agent's terminal (task #3029):
+/// its last lines, read once through the terminal read the backend checks
+/// (terminal.ts mayDrive), so nobody sees a screen here they could not watch
+/// in its terminal. The read writes nothing to any chat. On the web, whose
+/// transport refuses terminal reads (backend_transport.dart), it reads
+/// nothing and points to the terminal instead.
+class SuperTabPromptLines extends StatefulWidget {
+ const SuperTabPromptLines({
+ super.key,
+ required this.controller,
+ required this.agentId,
+ this.web = kIsWeb,
+ });
+ final SuperTabController controller;
+ final String agentId;
+ final bool web;
+
+ /// How many of its last lines with text show.
+ static const lines = 6;
+
+ /// Said when the reader may not read this terminal (a Harness Team
+ /// account's agent, for anyone but its project's owner).
+ static const refused =
+ 'Its terminal isn\'t shown to you. Open the task to answer it.';
+
+ /// Said when its machine did not answer.
+ static const failed = 'Its last lines could not be read.';
+
+ /// Said on the web, which reads no terminal here.
+ static const onWeb = 'Open its terminal to see what it asks.';
+
+ /// The last [count] lines of [screen] with text, right-trimmed.
+ static String lastLines(String screen, {int count = lines}) {
+ final kept = [
+ for (final line in screen.split('\n'))
+ if (line.trimRight().isNotEmpty) line.trimRight(),
+ ];
+ return kept.skip(kept.length > count ? kept.length - count : 0).join('\n');
+ }
+
+ @override
+ State<SuperTabPromptLines> createState() => _PromptLinesState();
+}
+
+enum _Read { reading, shown, refused, failed, web }
+
+class _PromptLinesState extends State<SuperTabPromptLines> {
+ _Read _read = _Read.reading;
+ String _text = '';
+
+ String get _path =>
+ '/api/super-tabs/${Uri.encodeComponent(widget.controller.tabId)}';
+
+ /// Which read is current: an answer for an earlier controller or agent is
+ /// dropped.
+ int _turn = 0;
+
+ @override
+ void initState() {
+ super.initState();
+ _load();
+ }
+
+ @override
+ void didUpdateWidget(SuperTabPromptLines old) {
+ super.didUpdateWidget(old);
+ if (old.controller != widget.controller || old.agentId != widget.agentId) {
+ _read = _Read.reading;
+ _load();
+ }
+ }
+
+ Future<void> _load() async {
+ final turn = ++_turn;
+ void show(_Read read) {
+ if (turn == _turn) _show(read);
+ }
+
+ if (widget.web) return show(_Read.web);
+
+ try {
+ final sent = await widget.controller.request(
+ 'POST',
+ '$_path/commands',
+ body: {
+ 'operationId': superTabOperationId(),
+ 'command': {'type': 'agent.screen', 'agentId': widget.agentId},
+ },
+ );
+ final id = (sent['result'] as Map?)?['requestId'] as String?;
+ if (id == null) return show(_Read.failed);
+ // The backend waits about 20 seconds per read; a request still pending
+ // then is read once more before the row gives up.
+ for (var i = 0; i < 2; i++) {
+ final answer = await widget.controller.request(
+ 'GET',
+ '$_path/terminal/${Uri.encodeComponent(id)}',
+ );
+ if (answer['pending'] == true) continue;
+ final text = answer['ok'] == true ? answer['text'] as String? : null;
+ if (text == null) return show(_Read.failed);
+ if (turn != _turn) return;
+ _text = SuperTabPromptLines.lastLines(text);
+ return show(_text.isEmpty ? _Read.failed : _Read.shown);
+ }
+ show(_Read.failed);
+ } on SuperTabFailure catch (failure) {
+ show(failure.statusCode == 403 ? _Read.refused : _Read.failed);
+ } catch (_) {
+ show(_Read.failed);
+ }
+ }
+
+ void _show(_Read read) {
+ if (mounted) setState(() => _read = read);
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ grid.AppTheme.watch(context);
+ return Padding(
+ padding: const EdgeInsets.only(top: grid.AppDesktop.controlGap),
+ child: switch (_read) {
+ _Read.reading => const SizedBox.shrink(),
+ _Read.refused => Text(
+ SuperTabPromptLines.refused,
+ style: DesktopChrome.metadata(),
+ ),
+ _Read.failed => Text(
+ SuperTabPromptLines.failed,
+ style: DesktopChrome.metadata(),
+ ),
+ _Read.web => Text(
+ SuperTabPromptLines.onWeb,
+ style: DesktopChrome.metadata(),
+ ),
+ _Read.shown => Container(
+ key: ValueKey('super-prompt-lines:${widget.agentId}'),
+ width: double.infinity,
+ padding: const EdgeInsets.symmetric(
+ horizontal: grid.AppDesktop.controlGap,
+ vertical: grid.AppDesktop.listRowGap,
+ ),
+ decoration: BoxDecoration(
+ color: grid.AppSurface.recess,
+ borderRadius: BorderRadius.circular(grid.AppDesktop.fieldRadius),
+ ),
+ child: Text(
+ _text,
+ style: grid.AppType.mono(color: DesktopChrome.foreground),
+ ),
+ ),
+ },
+ );
+ }
+}
diff --git a/desktop/lib/super_tabs/tasks_view.dart b/desktop/lib/super_tabs/tasks_view.dart
index 8bf93e036..0169c2a76 100644
--- a/desktop/lib/super_tabs/tasks_view.dart
+++ b/desktop/lib/super_tabs/tasks_view.dart
@@ -14,13 +14,16 @@ import 'attention.dart';
import 'backlog.dart';
import 'controller.dart';
import 'machine_status.dart';
+import 'member_groups.dart';
import 'model.dart';
import 'pulse_strip.dart';
import 'task_card.dart';
import 'task_groups.dart';
+import 'zone_time.dart';
/// A project's Tasks view (Dee, task #2569): every ask from proposal to
-/// shipped, as a Board (the default) or a List, with Mine and Search. It reads
+/// shipped, as a Board (the default), a List or by crew member (Members,
+/// task #3400), with Mine and Search. It reads
/// only what the controller holds, and the shipped tasks it reads for the
/// window, so cards move as the work does.
class SuperTabTasksView extends StatefulWidget {
@@ -54,7 +57,7 @@ class SuperTabTasksView extends StatefulWidget {
/// shows selected (task #2948).
final String? selectedId;
- /// Where Board or List, and Mine, are kept for this reader on this Mac.
+ /// Where Board, List or Members, and Mine, are kept for this reader on this Mac.
final LocalKeyValueStore? storage;
final DateTime Function() now;
@@ -69,8 +72,12 @@ class SuperTabTasksView extends StatefulWidget {
State<SuperTabTasksView> createState() => _SuperTabTasksViewState();
}
+/// How the Tasks view lays its cards out, kept by its name.
+enum _Layout { board, list, members }
+
class _SuperTabTasksViewState extends State<SuperTabTasksView> {
- bool _list = false, _mine = false;
+ var _layout = _Layout.board;
+ bool _mine = false;
String _query = '';
/// List's sections folded: Shipped starts so; not kept.
@@ -90,6 +97,14 @@ class _SuperTabTasksViewState extends State<SuperTabTasksView> {
void initState() {
super.initState();
unawaited(_restore());
+ // The lanes read each task's not-before day in its project's zone.
+ if (!superTabZonesLoaded) {
+ unawaited(
+ superTabLoadZones().then((_) {
+ if (mounted) setState(() {});
+ }),
+ );
+ }
_readShipped();
}
@@ -114,7 +129,11 @@ class _SuperTabTasksViewState extends State<SuperTabTasksView> {
final saved = jsonDecode(raw);
if (saved is! Map) return;
setState(() {
- _list = saved['layout'] == 'list';
+ _layout =
+ _Layout.values
+ .where((l) => l.name == saved['layout'])
+ .firstOrNull ??
+ _Layout.board;
_mine = saved['mine'] == true;
});
} on FormatException {
@@ -123,15 +142,15 @@ class _SuperTabTasksViewState extends State<SuperTabTasksView> {
}
}
- void _choose({bool? list, bool? mine}) {
+ void _choose({_Layout? layout, bool? mine}) {
setState(() {
- _list = list ?? _list;
+ _layout = layout ?? _layout;
_mine = mine ?? _mine;
});
unawaited(
widget.storage?.write(
_key,
- jsonEncode({'layout': _list ? 'list' : 'board', 'mine': _mine}),
+ jsonEncode({'layout': _layout.name, 'mine': _mine}),
),
);
}
@@ -213,14 +232,17 @@ class _SuperTabTasksViewState extends State<SuperTabTasksView> {
),
),
Expanded(
- child: empty
+ // Members draws the crew, free or not, though no task is open.
+ child: _layout == _Layout.members
+ ? _membersView(project, board, now)
+ : empty
? Center(
child: Text(
'No tasks yet',
style: DesktopChrome.control(color: DesktopChrome.muted),
),
)
- : _list
+ : _layout == _Layout.list
? _listView(shown, now)
: _boardView(shown, now),
),
@@ -228,7 +250,8 @@ class _SuperTabTasksViewState extends State<SuperTabTasksView> {
);
}
- /// The view's own bar: Board or List, Mine and Search, nothing else.
+ /// The view's own bar: Board, List or Members, Mine and Search, nothing
+ /// else.
Widget _bar(BuildContext context) => Padding(
padding: const EdgeInsets.fromLTRB(
grid.AppDesktop.groupGap,
@@ -255,15 +278,23 @@ class _SuperTabTasksViewState extends State<SuperTabTasksView> {
DesktopPill(
key: const ValueKey('super-tasks-layout-board'),
label: 'Board',
- selected: !_list,
- onPressed: () => _choose(list: false),
+ selected: _layout == _Layout.board,
+ onPressed: () => _choose(layout: _Layout.board),
),
const SizedBox(width: grid.AppDesktop.listRowGap),
DesktopPill(
key: const ValueKey('super-tasks-layout-list'),
label: 'List',
- selected: _list,
- onPressed: () => _choose(list: true),
+ selected: _layout == _Layout.list,
+ onPressed: () => _choose(layout: _Layout.list),
+ ),
+ const SizedBox(width: grid.AppDesktop.listRowGap),
+ DesktopPill(
+ key: const ValueKey('super-tasks-layout-members'),
+ label: 'Members',
+ selected: _layout == _Layout.members,
+ tooltip: 'Tasks by crew member',
+ onPressed: () => _choose(layout: _Layout.members),
),
const SizedBox(width: grid.AppDesktop.groupGap),
DesktopPill(
@@ -402,16 +433,23 @@ class _SuperTabTasksViewState extends State<SuperTabTasksView> {
return HarnessActivity.working;
}
- Widget _card(SuperTabTaskEntry entry, DateTime now, {required bool list}) {
+ /// [entry]'s card; [lane] leads its caption (Members' Unassigned).
+ Widget _card(
+ SuperTabTaskEntry entry,
+ DateTime now, {
+ required bool list,
+ String? lane,
+ }) {
final task = entry.task;
final id = task?.id ?? entry.proposal!.messageId;
+ final caption = _caption(entry, now);
return SuperTabTaskCard(
key: ValueKey('super-task-card-$id'),
// A legacy marker is the badge now: the title drops it.
title: task == null
? entry.proposal!.title
: superTabTitlePriority(task.title).title,
- caption: _caption(entry, now),
+ caption: [?lane, if (caption.isNotEmpty) caption].join(' · '),
priority: superTabEntryPriority(entry),
needsYou: entry.needsYou,
unread: task != null && widget.controller.unreadShown(task),
@@ -453,14 +491,11 @@ class _SuperTabTasksViewState extends State<SuperTabTasksView> {
),
);
- /// One column of the Board: card material with its hairline rim at the
- /// card radius, and no shadow, which is for floating content only.
- Widget _panel(
- SuperTabTaskColumn column,
- List<SuperTabTaskEntry> entries,
- DateTime now,
- ) => DecoratedBox(
- key: ValueKey('super-tasks-column-${column.name}'),
+ /// One column of the Board or of Members: card material with its hairline
+ /// rim at the card radius, and no shadow, which is for floating content
+ /// only; [heading] over [body], which fills the rest.
+ Widget _framed(Key key, Widget heading, Widget body) => DecoratedBox(
+ key: key,
decoration: BoxDecoration(
color: grid.AppCard.base,
borderRadius: BorderRadius.circular(grid.AppCard.radius),
@@ -471,39 +506,196 @@ class _SuperTabTasksViewState extends State<SuperTabTasksView> {
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
- _heading(column, entries.length),
+ heading,
const SizedBox(height: grid.AppDesktop.listRowGap),
- Expanded(
- child: entries.isEmpty
- // Said, not left blank: a column with nothing in it reads
- // as one still loading (task #2948).
- ? Padding(
- padding: const EdgeInsets.symmetric(
- vertical: grid.AppDesktop.groupGap,
- ),
- child: Text(
- 'No tasks',
- textAlign: TextAlign.center,
- style: DesktopChrome.metadata(),
- ),
- )
- : column == SuperTabTaskColumn.nextUp
- ? _nextUp(entries, now)
- : LaidOutListView.builder(
- itemCount: entries.length,
- itemBuilder: (context, i) => Padding(
- padding: const EdgeInsets.only(
- bottom: grid.AppDesktop.controlGap,
- ),
- child: _card(entries[i], now, list: false),
- ),
- ),
- ),
+ Expanded(child: body),
],
),
),
);
+ /// Said, not left blank: a column with nothing in it reads as one still
+ /// loading (task #2948).
+ static Widget _noTasks() => Padding(
+ padding: const EdgeInsets.symmetric(vertical: grid.AppDesktop.groupGap),
+ child: Text(
+ 'No tasks',
+ textAlign: TextAlign.center,
+ style: DesktopChrome.metadata(),
+ ),
+ );
+
+ /// One column of the Board.
+ Widget _panel(
+ SuperTabTaskColumn column,
+ List<SuperTabTaskEntry> entries,
+ DateTime now,
+ ) => _framed(
+ ValueKey('super-tasks-column-${column.name}'),
+ _heading(column, entries.length),
+ entries.isEmpty
+ ? _noTasks()
+ : column == SuperTabTaskColumn.nextUp
+ ? _nextUp(entries, now)
+ : LaidOutListView.builder(
+ itemCount: entries.length,
+ itemBuilder: (context, i) => Padding(
+ padding: const EdgeInsets.only(
+ bottom: grid.AppDesktop.controlGap,
+ ),
+ child: _card(entries[i], now, list: false),
+ ),
+ ),
+ );
+
+ /// Members (task #3400): one muted line of the lanes' capacity, then a
+ /// column per crew member, its name and lane over Working, Full or Free,
+ /// with the tasks in its hands and then those it handed over; and last,
+ /// Unassigned, in the order the Swarm hands work out, each card led by its
+ /// lane. Columns as the Board's: side by side, scrolling sideways.
+ ///
+ /// Mine and Search hide cards of the whole [board]; a member's state and
+ /// the lanes count every task the app holds.
+ Widget _membersView(
+ SuperTabProject project,
+ Map<SuperTabTaskColumn, List<SuperTabTaskEntry>> board,
+ DateTime now,
+ ) {
+ final c = widget.controller;
+ final groups = superTabMemberGroups(
+ agents: c.snapshot?.agents ?? const [],
+ projectId: project.id,
+ entries: board.values.expand((entries) => entries),
+ );
+ final capacity = superTabCapacityLine(
+ superTabLaneCapacity(
+ superTabProjectTasks(c, project),
+ now,
+ timeZone: project.timeZone,
+ ),
+ now,
+ );
+ Widget column(Key key, Widget heading, List<Widget> rows) => SizedBox(
+ width: SuperTabTasksView.columnWidth,
+ child: _framed(
+ key,
+ heading,
+ LaidOutListView.builder(
+ itemCount: rows.length,
+ itemBuilder: (context, i) => rows[i],
+ ),
+ ),
+ );
+ Widget card(SuperTabTaskEntry entry, {String? lane}) => Padding(
+ padding: const EdgeInsets.only(bottom: grid.AppDesktop.controlGap),
+ child: _card(entry, now, list: false, lane: lane),
+ );
+ const inset = EdgeInsets.symmetric(
+ horizontal: grid.AppDesktop.controlGap,
+ vertical: grid.AppDesktop.menuInset,
+ );
+ final unassigned = groups.unassigned.where((u) => _keeps(u.entry)).toList();
+ return Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ if (capacity != null)
+ Padding(
+ padding: const EdgeInsets.fromLTRB(
+ grid.AppDesktop.groupGap,
+ 0,
+ grid.AppDesktop.groupGap,
+ grid.AppDesktop.controlGap,
+ ),
+ child: Text(
+ capacity,
+ key: const ValueKey('super-tasks-capacity'),
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: DesktopChrome.metadata(),
+ ),
+ ),
+ Expanded(
+ child: SingleChildScrollView(
+ key: const ValueKey('super-tasks-members'),
+ scrollDirection: Axis.horizontal,
+ padding: const EdgeInsets.only(
+ left: grid.AppDesktop.groupGap,
+ right: grid.AppDesktop.groupGap,
+ bottom: grid.AppDesktop.groupGap,
+ ),
+ child: Row(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ for (final member in groups.members) ...[
+ column(
+ ValueKey('super-tasks-member-${member.agent.id}'),
+ Padding(
+ padding: inset,
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Text(
+ superTabMemberHeading(member.agent),
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: DesktopChrome.control(medium: true),
+ ),
+ Text(
+ member.state.label,
+ style: DesktopChrome.metadata(),
+ ),
+ ],
+ ),
+ ),
+ [
+ for (final entry in member.inHand.where(_keeps))
+ card(entry),
+ if (member.handed.where(_keeps).isNotEmpty)
+ Padding(
+ padding: inset,
+ child: Text(
+ 'handed:',
+ style: DesktopChrome.metadata(),
+ ),
+ ),
+ for (final entry in member.handed.where(_keeps))
+ card(entry),
+ ],
+ ),
+ const SizedBox(width: _columnGap),
+ ],
+ column(
+ const ValueKey('super-tasks-unassigned'),
+ Padding(
+ padding: inset,
+ child: Row(
+ children: [
+ Text(
+ 'Unassigned',
+ style: DesktopChrome.control(medium: true),
+ ),
+ const SizedBox(width: grid.AppDesktop.controlGap),
+ Text(
+ '${unassigned.length}',
+ style: DesktopChrome.metadata(),
+ ),
+ ],
+ ),
+ ),
+ [
+ if (unassigned.isEmpty) _noTasks(),
+ for (final (:entry, :lane) in unassigned)
+ card(entry, lane: lane),
+ ],
+ ),
+ ],
+ ),
+ ),
+ ),
+ ],
+ );
+ }
+
Widget _listView(
Map<SuperTabTaskColumn, List<SuperTabTaskEntry>> shown,
DateTime now,
diff --git a/desktop/lib/super_tabs/view.dart b/desktop/lib/super_tabs/view.dart
index 1360fafd8..475427956 100644
--- a/desktop/lib/super_tabs/view.dart
+++ b/desktop/lib/super_tabs/view.dart
@@ -211,6 +211,11 @@ class _SuperTabViewState extends State<SuperTabView>
/// Mentions or Threads (anh Dee, 11-05, task #2996).
SwarmPage? _page;
+ /// The need a notice opened Decisions for, lit there for a moment, and how
+ /// many times one was (task #3029): the same need opened again lights again.
+ String? _highlight;
+ int _highlightTurn = 0;
+
/// Manage holds the main pane; [_manageTab] is which of its pages, but for
/// Devices, which is the pane the view holds for it ([_devicesVisible]).
bool _showManage = false;
@@ -2045,6 +2050,9 @@ class _SuperTabViewState extends State<SuperTabView>
_page = notice?.kind == SuperTabNoticeKind.mention
? SwarmPage.mentions
: SwarmPage.decisions;
+ // Decisions lights the row it was opened for (task #3029).
+ _highlight = notice?.need?.id;
+ _highlightTurn++;
_showManage = false;
_showPullRequests = _showTasks = false;
});
@@ -5764,6 +5772,8 @@ class _SuperTabViewState extends State<SuperTabView>
switch (_pageShown) {
SwarmPage.decisions => SuperTabDecisionsPage(
activity: SuperTabActivity.of(c),
+ highlight: _highlight,
+ highlightTurn: _highlightTurn,
onOpenConversation: _openConversation,
onOpenReminder: (reminder) =>
unawaited(_openReminder(reminder)),
diff --git a/desktop/lib/super_tabs/zone_time.dart b/desktop/lib/super_tabs/zone_time.dart
index eff09f813..678dde779 100644
--- a/desktop/lib/super_tabs/zone_time.dart
+++ b/desktop/lib/super_tabs/zone_time.dart
@@ -2,6 +2,8 @@ import 'package:flutter/material.dart';
import 'package:timezone/data/latest_10y.dart' deferred as zones;
import 'package:timezone/timezone.dart' as tz;
+import 'model.dart' show superTabDefaultTimeZone;
+
Future<void>? _zonesLoading;
var _zonesLoaded = false;
@@ -35,3 +37,18 @@ Future<TimeOfDay?> superTabTimeIn(String? zone, DateTime now) async {
await superTabLoadZones();
return superTabTimeNow(zone, now);
}
+
+/// The date in [zone] at [now], as a UTC midnight to compare dates by; in
+/// [superTabDefaultTimeZone] for a zone the table lacks. Until the table is
+/// loaded, this computer's date.
+DateTime superTabDateIn(String zone, DateTime now) {
+ DateTime day(DateTime t) => DateTime.utc(t.year, t.month, t.day);
+ if (!_zonesLoaded) return day(now.toLocal());
+ tz.Location location;
+ try {
+ location = tz.getLocation(zone);
+ } on tz.LocationNotFoundException {
+ location = tz.getLocation(superTabDefaultTimeZone);
+ }
+ return day(tz.TZDateTime.from(now, location));
+}
diff --git a/desktop/test/super_tab_backend_transport_test.dart b/desktop/test/super_tab_backend_transport_test.dart
index 0e96ce0fc..0a0d0eb5e 100644
--- a/desktop/test/super_tab_backend_transport_test.dart
+++ b/desktop/test/super_tab_backend_transport_test.dart
@@ -536,6 +536,9 @@ void main() {
skip: const {
'lib/super_tabs/attachment_upload.dart',
'lib/super_tabs/avatar_upload.dart',
+ // A Decisions prompt row reads its agent's screen only off the web
+ // (prompt_lines.dart `web`): the web refuses terminal reads.
+ 'lib/super_tabs/prompt_lines.dart',
},
);
// The walk finds what it should, so a broken walk cannot pass.
diff --git a/desktop/test/super_tab_member_groups_test.dart b/desktop/test/super_tab_member_groups_test.dart
new file mode 100644
index 000000000..f6f8c588c
--- /dev/null
+++ b/desktop/test/super_tab_member_groups_test.dart
@@ -0,0 +1,710 @@
+import 'package:flutter/material.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/shared/theme/app_theme.dart' as grid;
+import 'package:harness/super_tabs/controller.dart';
+import 'package:harness/super_tabs/member_groups.dart';
+import 'package:harness/super_tabs/model.dart';
+import 'package:harness/super_tabs/tasks_view.dart';
+import 'package:harness/super_tabs/zone_time.dart';
+
+import 'support/memory_key_value_store.dart';
+import 'support/super_tab_fixture.dart';
+
+/// 09:00 on 11-05 in Vietnam, a project's day when its digest names no zone,
+/// whatever zone the machine running the test is in.
+final _now = DateTime.utc(2026, 11, 5, 2);
+
+/// 11-06 01:00 in Vietnam, still 11-05 (10:00) in Los Angeles.
+final _vietnamTomorrow = DateTime.utc(2026, 11, 5, 18);
+int _ago(Duration d) => _now.subtract(d).millisecondsSinceEpoch;
+
+Map<String, dynamic> _task(
+ String id,
+ String title,
+ int number, {
+ String? lane,
+ String? status,
+ String? agent,
+ String? priority,
+ String? notBefore,
+ int? lostAt,
+ int? orphanedSince,
+ bool archived = false,
+}) => {
+ ...conversationFixture(id, title),
+ 'projectId': 'lead',
+ 'number': number,
+ 'brief': 'Do it',
+ 'task': {'goal': title, 'changes': '', 'constraints': '', 'owns': <String>[]},
+ 'archived': archived,
+ 'priority': ?priority,
+ 'notBefore': ?notBefore,
+ // Absent on a task from an older server; null when no lane owns it.
+ 'handOutLane': ?lane,
+ if (status != null)
+ 'assignment': {
+ 'id': 'as-$id',
+ 'agentId': agent,
+ 'status': status,
+ 'progressAt': 1,
+ if (lostAt != null) 'lost': {'at': lostAt, 'reason': 'agent lost'},
+ },
+ if (orphanedSince != null)
+ 'liveness': {'state': 'orphaned', 'since': orphanedSince},
+};
+
+Map<String, dynamic> _agent(
+ String id,
+ String name, {
+ String? displayName,
+ Map<String, dynamic>? crew,
+}) => {
+ 'id': id,
+ 'projectId': 'lead',
+ 'name': name,
+ 'displayName': ?displayName,
+ 'machineId': 'studio',
+ 'harnessId': 'h-$id',
+ 'contributorId': 'owner',
+ 'configuration': {'engine': 'claude'},
+ 'crew': ?crew,
+};
+
+/// A project with four crew members (Desktop, backend, docs with three tasks
+/// handed over, and one with no lane), an agent that is not crew, and the
+/// open tasks nobody holds: two lost, one P0, one not before tomorrow, one no
+/// lane owns. With [lanes] off, the server is one from before hand-out lanes.
+ConversationServer _server({bool lanes = true, String? digestZone}) {
+ final server = ConversationServer();
+ server.state['projects'] = [
+ {
+ ...projectFixture('lead', 'openharness', 'lead'),
+ if (digestZone != null)
+ 'digest': {'time': '08:00', 'timeZone': digestZone},
+ },
+ ];
+ server.state['people'] = [
+ {'id': 'owner', 'email': '[email protected]', 'role': 'owner'},
+ ];
+ server.state['agents'] = [
+ _agent(
+ 'finch',
+ 'Engineer',
+ displayName: 'Finch2',
+ crew: {'role': 'Engineer', 'lane': 'Desktop', 'at': 1, 'by': 'owner'},
+ ),
+ _agent(
+ 'heron',
+ 'Heron',
+ crew: {'role': 'Engineer', 'lane': 'backend', 'at': 1, 'by': 'owner'},
+ ),
+ _agent(
+ 'robin',
+ 'Robin',
+ crew: {'role': 'Engineer', 'at': 1, 'by': 'owner'},
+ ),
+ _agent(
+ 'wren',
+ 'Wren',
+ crew: {'role': 'Engineer', 'lane': 'docs', 'at': 1, 'by': 'owner'},
+ ),
+ _agent('plover', 'Plover'),
+ ];
+ String? lane(String name) => lanes ? name : null;
+ Map<String, dynamic> task(
+ String id,
+ String title,
+ int number, {
+ String? lane,
+ String? status,
+ String? agent,
+ String? priority,
+ String? notBefore,
+ int? lostAt,
+ int? orphanedSince,
+ bool archived = false,
+ }) {
+ final t = _task(
+ id,
+ title,
+ number,
+ lane: lane,
+ status: status,
+ agent: agent,
+ priority: priority,
+ notBefore: notBefore,
+ lostAt: lostAt,
+ orphanedSince: orphanedSince,
+ archived: archived,
+ );
+ // A lane no table owns is null on a newer server, absent on an older.
+ if (lanes && lane == null) t['handOutLane'] = null;
+ return t;
+ }
+
+ (server.state['conversations'] as List)
+ ..removeWhere((g) => (g as Map)['id'] == 'offline')
+ ..addAll(<Map<String, dynamic>>[
+ task(
+ 'd-work',
+ 'Members on the board',
+ 30,
+ lane: lane('Desktop'),
+ status: 'working',
+ agent: 'finch',
+ ),
+ task(
+ 'd-hand',
+ 'Lane line',
+ 31,
+ lane: lane('Desktop'),
+ status: 'review',
+ agent: 'finch',
+ ),
+ task(
+ 'b-block',
+ 'Dispatch pass',
+ 32,
+ lane: lane('backend'),
+ status: 'blocked',
+ agent: 'heron',
+ ),
+ task(
+ 'p-work',
+ 'Not crew work',
+ 33,
+ lane: lane('backend'),
+ status: 'working',
+ agent: 'plover',
+ ),
+ for (final n in [1, 2, 3])
+ task(
+ 'w-h$n',
+ 'Guide part $n',
+ 40 + n,
+ lane: lane('docs'),
+ status: 'review',
+ agent: 'wren',
+ ),
+ task('b-early', 'Pass log', 20, lane: lane('backend')),
+ task('u1', 'Tray icon', 21, lane: lane('Desktop')),
+ task(
+ 'u-orph',
+ 'Sidebar order',
+ 23,
+ lane: lane('Desktop'),
+ status: 'lost',
+ agent: 'finch',
+ lostAt: _ago(const Duration(minutes: 30)),
+ orphanedSince: _ago(const Duration(hours: 2, minutes: 10)),
+ ),
+ task(
+ 'u4',
+ 'Pick check',
+ 24,
+ lane: lane('backend'),
+ status: 'lost',
+ agent: 'heron',
+ lostAt: _ago(const Duration(hours: 2, minutes: 40)),
+ ),
+ task('u5', 'Nobody owns it', 25),
+ task(
+ 'd-urgent',
+ 'Crash on open',
+ 26,
+ lane: lane('Desktop'),
+ priority: 'P0',
+ ),
+ task(
+ 'tomorrow',
+ 'Later work',
+ 27,
+ lane: lane('Desktop'),
+ notBefore: '2026-11-06',
+ ),
+ task(
+ 'd-done',
+ 'Ready to merge',
+ 28,
+ lane: lane('Desktop'),
+ status: 'done',
+ agent: 'finch',
+ ),
+ task('d-archived', 'Put away', 29, lane: lane('Desktop'), archived: true),
+ ]);
+ return server;
+}
+
+const _line =
+ 'backend: 2 waiting, 2 busy, oldest 2 h · '
+ 'Desktop: 3 waiting, 2 busy, oldest 2 h · '
+ 'docs: 0 waiting, 3 busy';
+const _handOut = [
+ 'd-urgent',
+ 'b-early',
+ 'u1',
+ 'u-orph',
+ 'u4',
+ 'u5',
+ 'tomorrow',
+];
+
+Finder _member(String id) => find.byKey(ValueKey('super-tasks-member-$id'));
+Finder _unassigned() => find.byKey(const ValueKey('super-tasks-unassigned'));
+Finder _card(String id) => find.byKey(ValueKey('super-task-card-$id'));
+final _capacity = find.byKey(const ValueKey('super-tasks-capacity'));
+final _members = find.byKey(const ValueKey('super-tasks-layout-members'));
+
+Future<SuperTabController> _show(
+ WidgetTester tester,
+ ConversationServer server, {
+ MemoryKeyValueStore? storage,
+ List<String>? opened,
+ bool members = true,
+ DateTime? now,
+}) async {
+ await tester.binding.setSurfaceSize(const Size(1900, 900));
+ addTearDown(() => tester.binding.setSurfaceSize(null));
+ final c = server.controller();
+ await c.refresh();
+ await tester.pumpWidget(
+ MaterialApp(
+ theme: grid.buildAppTheme(brightness: Brightness.light),
+ builder: (context, child) => MediaQuery(
+ data: MediaQuery.of(context).copyWith(disableAnimations: true),
+ child: child!,
+ ),
+ home: Scaffold(
+ body: SuperTabTasksView(
+ controller: c,
+ project: c.snapshot!.projects.single,
+ storage: storage ?? MemoryKeyValueStore(),
+ needsHuman: (_) => 0,
+ onOpenTask: (id) => opened?.add(id),
+ onOpenProposal: (_) {},
+ onOpenMessage: (_, _) {},
+ now: () => now ?? _now,
+ ),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ if (members) {
+ await tester.tap(_members);
+ await tester.pumpAndSettle();
+ }
+ return c;
+}
+
+Future<void> _close(WidgetTester tester, SuperTabController c) async {
+ await tester.pumpWidget(const SizedBox());
+ await c.flush();
+ c.dispose();
+}
+
+/// The cards and the texts [names] in [column], top to bottom.
+List<String> _top(
+ WidgetTester tester,
+ Finder column, {
+ Set<String> names = const {},
+}) {
+ final found = [
+ for (final e
+ in find
+ .descendant(
+ of: column,
+ matching: find.byWidgetPredicate(
+ (w) =>
+ w.key is ValueKey<String> &&
+ (w.key as ValueKey<String>).value.startsWith(
+ 'super-task-card-',
+ ) ||
+ w is Text && names.contains(w.data),
+ ),
+ )
+ .evaluate())
+ (
+ switch (e.widget) {
+ Text(:final data) => data!,
+ final w => (w.key as ValueKey<String>).value.substring(
+ 'super-task-card-'.length,
+ ),
+ },
+ tester.getTopLeft(find.byWidget(e.widget)).dy,
+ ),
+ ]..sort((a, b) => a.$2.compareTo(b.$2));
+ return [for (final (id, _) in found) id];
+}
+
+Finder _text(Finder of, String text) =>
+ find.descendant(of: of, matching: find.text(text));
+
+Finder _containing(Finder of, String text) =>
+ find.descendant(of: of, matching: find.textContaining(text));
+
+/// The board's Group by Member (task #3400): a column per crew member with
+/// its lane, what it holds and what it handed over, then Unassigned in the
+/// order the Swarm hands work out, under one line of lane capacity worked out
+/// from the tasks the app holds.
+void main() {
+ setUpAll(superTabLoadZones);
+
+ testWidgets('the Tasks view still opens on the Board', (tester) async {
+ final c = await _show(tester, _server(), members: false);
+ expect(find.byKey(const ValueKey('super-tasks-board')), findsOneWidget);
+ expect(_members, findsOneWidget);
+ expect(_member('finch'), findsNothing);
+ expect(_unassigned(), findsNothing);
+ final pills = [
+ for (final key in ['board', 'list', 'members'])
+ tester.getTopLeft(find.byKey(ValueKey('super-tasks-layout-$key'))).dx,
+ ];
+ expect(pills, orderedEquals([...pills]..sort()));
+ expect(
+ tester.getTopLeft(_members).dx,
+ lessThan(
+ tester.getTopLeft(find.byKey(const ValueKey('super-tasks-mine'))).dx,
+ ),
+ );
+ await _close(tester, c);
+ });
+
+ testWidgets('Members lists each crew member with its lane, what it holds, '
+ 'then what it handed over', (tester) async {
+ final c = await _show(tester, _server());
+ expect(find.byKey(const ValueKey('super-tasks-board')), findsNothing);
+
+ expect(_text(_member('finch'), 'Finch2 · Desktop'), findsOneWidget);
+ expect(_text(_member('finch'), 'Working'), findsOneWidget);
+ expect(_top(tester, _member('finch'), names: {'handed:'}), [
+ 'd-work',
+ 'handed:',
+ 'd-hand',
+ ]);
+
+ expect(_text(_member('heron'), 'Heron · backend'), findsOneWidget);
+ expect(_text(_member('heron'), 'Working'), findsOneWidget);
+ expect(_top(tester, _member('heron'), names: {'handed:'}), ['b-block']);
+
+ // No lane: its name alone; nothing in its hands: Free.
+ expect(_text(_member('robin'), 'Robin'), findsOneWidget);
+ expect(_text(_member('robin'), 'Free'), findsOneWidget);
+ expect(_top(tester, _member('robin')), isEmpty);
+
+ // Three handed over and nothing in its hands: Full, not Free.
+ expect(_text(_member('wren'), 'Wren · docs'), findsOneWidget);
+ expect(_text(_member('wren'), 'Full'), findsOneWidget);
+ expect(_text(_member('wren'), 'Free'), findsNothing);
+ // In the board's order: Waiting lists the newest first.
+ expect(_top(tester, _member('wren'), names: {'handed:'}), [
+ 'handed:',
+ 'w-h3',
+ 'w-h2',
+ 'w-h1',
+ ]);
+
+ // An agent that is not crew gets no column, and its task is not
+ // anybody's to take.
+ expect(_member('plover'), findsNothing);
+ expect(_card('p-work'), findsNothing);
+
+ // Members in roster order, Unassigned last.
+ final lefts = [
+ for (final f in [
+ _member('finch'),
+ _member('heron'),
+ _member('robin'),
+ _member('wren'),
+ _unassigned(),
+ ])
+ tester.getTopLeft(f).dx,
+ ];
+ expect(lefts, orderedEquals([...lefts]..sort()));
+ await _close(tester, c);
+ });
+
+ testWidgets('Unassigned goes in the Swarm\'s hand-out order, P0 first, each '
+ 'card with its lane and priority', (tester) async {
+ final c = await _show(tester, _server());
+ expect(_text(_unassigned(), 'Unassigned'), findsOneWidget);
+ expect(_text(_unassigned(), '${_handOut.length}'), findsOneWidget);
+ // The P0 Desktop task goes before the earlier backend P2 one; then the
+ // shared queue, lanes not interleaved. Done, archived and held work is
+ // nobody's to take.
+ expect(_top(tester, _unassigned()), _handOut);
+ expect(_text(_card('d-urgent'), 'Desktop'), findsOneWidget);
+ expect(_text(_card('d-urgent'), 'P0'), findsOneWidget);
+ expect(_text(_card('b-early'), 'backend'), findsOneWidget);
+ expect(_text(_card('b-early'), 'P2'), findsOneWidget);
+ expect(_text(_card('u1'), 'Desktop'), findsOneWidget);
+ for (final lane in ['Desktop', 'backend', 'docs']) {
+ expect(_containing(_card('u5'), lane), findsNothing, reason: lane);
+ }
+ await _close(tester, c);
+ });
+
+ testWidgets('the lanes\' capacity, worked out from the tasks, reads as one '
+ 'line above the columns', (tester) async {
+ final c = await _show(tester, _server());
+ // Not before tomorrow, done and archived tasks wait in no lane.
+ expect(tester.widget<Text>(_capacity).data, _line);
+ expect(
+ tester.widget<Text>(_capacity).style?.color,
+ grid.AppPalette.textSecondary,
+ );
+ expect(
+ tester.getBottomLeft(_capacity).dy,
+ lessThanOrEqualTo(tester.getTopLeft(_member('finch')).dy),
+ );
+ await _close(tester, c);
+ });
+
+ testWidgets('a task waits from its not-before day in the project\'s zone, '
+ 'not the computer\'s', (tester) async {
+ // 11-06 in Vietnam: the task not before 11-06 waits too.
+ var c = await _show(tester, _server(), now: _vietnamTomorrow);
+ expect(
+ tester.widget<Text>(_capacity).data,
+ contains('Desktop: 4 waiting, 2 busy'),
+ );
+ await _close(tester, c);
+ // Still 11-05 where this project's digest is sent: it does not yet.
+ c = await _show(
+ tester,
+ _server(digestZone: 'America/Los_Angeles'),
+ now: _vietnamTomorrow,
+ );
+ expect(
+ tester.widget<Text>(_capacity).data,
+ contains('Desktop: 3 waiting, 2 busy'),
+ );
+ await _close(tester, c);
+ });
+
+ testWidgets('a change to one task moves the line and the member', (
+ tester,
+ ) async {
+ final server = _server();
+ final c = await _show(tester, server);
+ expect(_text(_member('robin'), 'Free'), findsOneWidget);
+ final u1 = (server.state['conversations'] as List)
+ .cast<Map<String, dynamic>>()
+ .firstWhere((g) => g['id'] == 'u1');
+ u1['assignment'] = {
+ 'id': 'as-u1',
+ 'agentId': 'robin',
+ 'status': 'working',
+ 'progressAt': 1,
+ };
+ await c.refresh();
+ await tester.pumpAndSettle();
+ expect(
+ tester.widget<Text>(_capacity).data,
+ 'backend: 2 waiting, 2 busy, oldest 2 h · '
+ 'Desktop: 2 waiting, 3 busy, oldest 2 h · '
+ 'docs: 0 waiting, 3 busy',
+ );
+ expect(_text(_member('robin'), 'Working'), findsOneWidget);
+ expect(_top(tester, _member('robin')), ['u1']);
+ expect(_top(tester, _unassigned()), isNot(contains('u1')));
+ await _close(tester, c);
+ });
+
+ testWidgets('Search hides cards, never a member\'s state', (tester) async {
+ final c = await _show(tester, _server());
+ await tester.enterText(
+ find.byKey(const ValueKey('super-tasks-search')),
+ 'Lane line',
+ );
+ await tester.pumpAndSettle();
+ // Its in-hand task is hidden; it still holds it.
+ expect(_card('d-work'), findsNothing);
+ expect(_top(tester, _member('finch'), names: {'handed:'}), [
+ 'handed:',
+ 'd-hand',
+ ]);
+ expect(_text(_member('finch'), 'Working'), findsOneWidget);
+ expect(_top(tester, _member('heron')), isEmpty);
+ expect(_text(_member('heron'), 'Working'), findsOneWidget);
+ expect(_top(tester, _member('wren')), isEmpty);
+ expect(_text(_member('wren'), 'Full'), findsOneWidget);
+ // The lanes count every task too.
+ expect(tester.widget<Text>(_capacity).data, _line);
+ await _close(tester, c);
+ });
+
+ testWidgets('a card opens its task as the Board\'s do', (tester) async {
+ final opened = <String>[];
+ final c = await _show(tester, _server(), opened: opened);
+ await tester.tap(_card('u1'));
+ await tester.tap(_card('d-hand'));
+ expect(opened, ['u1', 'd-hand']);
+ await _close(tester, c);
+ });
+
+ testWidgets('an older server without hand-out lanes: Unassigned in the same '
+ 'order without lanes, and no lane line', (tester) async {
+ final c = await _show(tester, _server(lanes: false));
+ expect(_capacity, findsNothing);
+ expect(_text(_member('finch'), 'Finch2 · Desktop'), findsOneWidget);
+ expect(_top(tester, _unassigned()), _handOut);
+ for (final id in _handOut) {
+ for (final lane in ['Desktop', 'backend', 'docs']) {
+ expect(_containing(_card(id), lane), findsNothing, reason: '$id $lane');
+ }
+ }
+ expect(tester.takeException(), isNull);
+ await _close(tester, c);
+ });
+
+ testWidgets('Members is remembered for the reader on this Mac', (
+ tester,
+ ) async {
+ final storage = MemoryKeyValueStore();
+ var c = await _show(tester, _server(), storage: storage);
+ await _close(tester, c);
+ c = await _show(tester, _server(), storage: storage, members: false);
+ expect(_member('finch'), findsOneWidget);
+ expect(find.byKey(const ValueKey('super-tasks-board')), findsNothing);
+ await tester.tap(find.byKey(const ValueKey('super-tasks-layout-board')));
+ await tester.pumpAndSettle();
+ expect(find.byKey(const ValueKey('super-tasks-board')), findsOneWidget);
+ await _close(tester, c);
+ });
+
+ group('superTabLaneCapacity', () {
+ SuperTabConversation task(
+ String id,
+ String? lane, {
+ String? status,
+ String? notBefore,
+ }) => SuperTabConversation.fromJson(
+ _task(
+ id,
+ id,
+ 1,
+ lane: lane,
+ status: status,
+ agent: 'finch',
+ notBefore: notBefore,
+ ),
+ );
+
+ test('lanes in the table\'s order, only those with work', () {
+ final lanes = superTabLaneCapacity([
+ task('a', 'docs'),
+ task('b', 'Desktop', status: 'planned'),
+ task('c', 'backend', status: 'reconciling'),
+ task('d', 'mobile', status: 'done'),
+ task('e', 'CLI', status: 'cancelled'),
+ task('f', 'Desktop', notBefore: '2026-11-05'),
+ task('g', null),
+ ], _now);
+ expect(
+ [for (final l in lanes) (l.lane, l.waiting, l.busy, l.oldestAt)],
+ [
+ ('backend', 0, 1, null),
+ ('Desktop', 1, 1, null),
+ ('docs', 1, 0, null),
+ ],
+ );
+ });
+
+ test('today is the project\'s day, Vietnam\'s by default', () {
+ final later = [task('t', 'Desktop', notBefore: '2026-11-06')];
+ int? waiting(String? zone) => superTabLaneCapacity(
+ later,
+ _vietnamTomorrow,
+ timeZone: zone,
+ ).firstOrNull?.waiting;
+ expect(waiting('Asia/Ho_Chi_Minh'), 1);
+ expect(waiting(null), 1);
+ expect(waiting('America/Los_Angeles'), isNull);
+ // A zone the table lacks: Vietnam's.
+ expect(waiting('Mars/Base'), 1);
+ });
+ });
+
+ test('a project reads its digest\'s zone, Vietnam\'s without one', () {
+ SuperTabProject project(Object? digest) => SuperTabProject.fromJson({
+ ...projectFixture('lead', 'openharness', 'lead'),
+ 'digest': ?digest,
+ });
+ expect(
+ project({'time': '08:00', 'timeZone': 'America/Los_Angeles'}).timeZone,
+ 'America/Los_Angeles',
+ );
+ expect(project(null).timeZone, 'Asia/Ho_Chi_Minh');
+ expect(
+ project({'time': '08:00', 'timeZone': 5}).timeZone,
+ 'Asia/Ho_Chi_Minh',
+ );
+ expect(project('08:00').timeZone, 'Asia/Ho_Chi_Minh');
+ });
+
+ group('superTabCapacityLine', () {
+ SuperTabLaneCapacity lane(String name, Duration? age) =>
+ SuperTabLaneCapacity(
+ lane: name,
+ waiting: 3,
+ busy: 1,
+ oldestAt: age == null ? null : _now.subtract(age),
+ );
+
+ test('whole hours, rounded down', () {
+ expect(
+ superTabCapacityLine([
+ lane('Desktop', const Duration(hours: 5, minutes: 59)),
+ ], _now),
+ 'Desktop: 3 waiting, 1 busy, oldest 5 h',
+ );
+ });
+
+ test('minutes under an hour, and no oldest when none was recorded', () {
+ expect(
+ superTabCapacityLine([
+ lane('CLI', const Duration(minutes: 45)),
+ lane('docs', null),
+ ], _now),
+ 'CLI: 3 waiting, 1 busy, oldest 45 min · docs: 3 waiting, 1 busy',
+ );
+ });
+
+ test('no lanes, no line', () {
+ expect(superTabCapacityLine(const [], _now), isNull);
+ });
+ });
+
+ test('a task reads its hand-out lane, and none from an older server', () {
+ expect(
+ SuperTabConversation.fromJson(_task('t', 'T', 1, lane: 'Desktop'))
+ .handOutLane,
+ 'Desktop',
+ );
+ expect(SuperTabConversation.fromJson(_task('t', 'T', 1)).handOutLane, null);
+ });
+
+ test(
+ 'a member heads its column with its lane as the lane table names it',
+ () {
+ String heading(Map<String, Object?> crew) => superTabMemberHeading(
+ SuperTabAgent.fromJson(_agent('finch', 'Finch', crew: crew)),
+ );
+ // The crew mark keeps its lane in lower case (backend crew.ts, #3397).
+ expect(
+ heading({
+ 'role': 'Engineer',
+ 'lane': 'desktop',
+ 'at': 5,
+ 'by': 'owner',
+ }),
+ 'Finch · Desktop',
+ );
+ expect(
+ heading({'role': 'Engineer', 'lane': 'cli', 'at': 5, 'by': 'owner'}),
+ 'Finch · CLI',
+ );
+ expect(heading({'role': 'Engineer', 'at': 5, 'by': 'owner'}), 'Finch');
+ },
+ );
+}
diff --git a/desktop/test/super_tab_menu_bar_notices_test.dart b/desktop/test/super_tab_menu_bar_notices_test.dart
index f1f7a1041..3672f04b8 100644
--- a/desktop/test/super_tab_menu_bar_notices_test.dart
+++ b/desktop/test/super_tab_menu_bar_notices_test.dart
@@ -589,6 +589,31 @@ void main() {
await close(tester, view);
});
+ testWidgets('a decision\'s notice lights its row on Decisions for a moment '
+ '(task #3029)', (tester) async {
+ final server = ConversationServer()
+ ..ask(['Ship it behind a flag?', 'Keep the old route?']);
+ final view = await showView(tester, server);
+ view.controller.openNotice('decision', 'decision-1');
+ await tester.pump();
+ await tester.pump();
+ expect(
+ find.byKey(const ValueKey('super-activity-lit:decision:decision-1')),
+ findsOneWidget,
+ );
+ expect(
+ find.byKey(const ValueKey('super-activity-lit:decision:decision-2')),
+ findsNothing,
+ );
+ await tester.pump(const Duration(seconds: 3));
+ await tester.pumpAndSettle();
+ expect(
+ find.byKey(const ValueKey('super-activity-lit:decision:decision-1')),
+ findsNothing,
+ );
+ await close(tester, view);
+ });
+
testWidgets('from the menu bar: its Swarm tab comes forward and opens it', (
tester,
) async {
diff --git a/desktop/test/super_tab_prompt_waits_shots_test.dart b/desktop/test/super_tab_prompt_waits_shots_test.dart
new file mode 100644
index 000000000..2233e9d92
--- /dev/null
+++ b/desktop/test/super_tab_prompt_waits_shots_test.dart
@@ -0,0 +1,65 @@
+// Task #3029 (Gray, 11-05): the Decisions row of an agent at a prompt in the reader's task, for the PR's pictures,
+// light and dark. Writes nothing unless PROMPT_SHOTS names a folder.
+import 'dart:io';
+
+import 'package:clock/clock.dart';
+import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/shared/theme/app_theme.dart' as grid;
+import 'package:harness/super_tabs/decisions_page.dart';
+
+import 'super_tab_activity_lists_test.dart' show load, swarm;
+import 'super_tab_prompt_waits_test.dart' show wrenAtPrompt;
+import 'support/capture.dart';
+
+final shots = Platform.environment['PROMPT_SHOTS'];
+final _now = DateTime(2026, 11, 5, 10, 30);
+
+void main() {
+ setUpAll(() async {
+ await loadCaptureFonts(shots);
+ // The last lines are in the terminal's face: SF Mono, under its name here.
+ if (shots == null || !Platform.isMacOS) return;
+ final mono = File('/System/Library/Fonts/SFNSMono.ttf').readAsBytesSync();
+ await (FontLoader(
+ grid.AppType.monoFamily,
+ )..addFont(Future.value(ByteData.sublistView(mono)))).load();
+ });
+
+ for (final brightness in Brightness.values) {
+ testWidgets('the prompt row in ${brightness.name}', (tester) async {
+ if (shots == null) return;
+ final previous = grid.AppTheme.brightness.value;
+ grid.AppTheme.brightness.value = brightness;
+ addTearDown(() => grid.AppTheme.brightness.value = previous);
+ tester.view.devicePixelRatio = 2;
+ tester.view.physicalSize = const Size(1440, 900);
+ addTearDown(tester.view.reset);
+ await withClock(Clock.fixed(_now), () async {
+ final server = swarm()..followedThreads = null;
+ server.ask(['Ship the board firmware behind a flag?']);
+ wrenAtPrompt(server);
+ final activity = (await tester.runAsync(() => load(server)))!;
+ await tester.pumpWidget(
+ MaterialApp(
+ debugShowCheckedModeBanner: false,
+ theme: grid.buildAppTheme(brightness: brightness),
+ home: Scaffold(
+ body: SuperTabDecisionsPage(
+ activity: activity,
+ onOpenConversation: (_) {},
+ now: () => _now,
+ ),
+ ),
+ ),
+ );
+ await tester.runAsync(
+ () => Future<void>.delayed(const Duration(milliseconds: 80)),
+ );
+ await tester.pumpAndSettle();
+ await captureWindow(tester, shots, 'prompt-row-${brightness.name}');
+ });
+ });
+ }
+}
diff --git a/desktop/test/super_tab_prompt_waits_test.dart b/desktop/test/super_tab_prompt_waits_test.dart
new file mode 100644
index 000000000..324cd2218
--- /dev/null
+++ b/desktop/test/super_tab_prompt_waits_test.dart
@@ -0,0 +1,239 @@
+import 'package:clock/clock.dart';
+import 'package:flutter/material.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/shared/theme/app_theme.dart' as grid;
+import 'package:harness/super_tabs/activity.dart';
+import 'package:harness/super_tabs/decisions_page.dart';
+import 'package:harness/super_tabs/prompt_lines.dart';
+
+import 'super_tab_activity_lists_test.dart' show load, swarm;
+import 'support/super_tab_fixture.dart';
+
+// Task #3029 (Gray, 11-05): an agent in a task waiting at a prompt in its
+// terminal reaches the task's person under Decisions, with its last lines and
+// a button to its terminal, and leaves once it moves on.
+
+final _now = DateTime(2026, 11, 5, 10, 30);
+
+const _screen =
+ 'Pairing the iPhone with the board.\n'
+ 'Open Settings > Glinks on the iPhone, check the password,\n'
+ 'press Connect, then tell me "connect rồi".\n'
+ '\n'
+ '> \n';
+
+/// Wren, at a prompt in its task "Flash the board", as the backend lists it
+/// for the reader (backend superTabs/promptWaits.ts).
+void wrenAtPrompt(ConversationServer server, {bool screen = true}) {
+ server.state['agents'] = [
+ ...(server.state['agents'] as List),
+ {
+ 'id': 'wren',
+ 'projectId': 'lead',
+ 'name': 'Builder',
+ 'displayName': 'Wren',
+ 'machineId': 'host',
+ 'harnessId': 'wren',
+ 'contributorId': 'owner',
+ 'configuration': {'engine': 'claude'},
+ 'alerting': ['prompt'],
+ },
+ ];
+ (server.state['conversations'] as List).add(<String, dynamic>{
+ ...conversationFixture('flash', 'Flash the board'),
+ 'projectId': 'lead',
+ 'agentIds': ['wren'],
+ 'requesterId': 'owner',
+ 'assignment': {'id': 'a1', 'agentId': 'wren', 'status': 'working'},
+ });
+ server.state['promptsWaiting'] = [
+ {
+ 'agentId': 'wren',
+ 'agentName': 'Wren',
+ 'conversationId': 'flash',
+ 'conversationTitle': 'Flash the board',
+ 'projectId': 'lead',
+ 'projectName': 'web-project',
+ },
+ ];
+ if (screen) server.screens['wren'] = _screen;
+}
+
+Future<SuperTabActivity> _loaded(
+ WidgetTester tester,
+ ConversationServer server,
+) async => (await tester.runAsync(() => load(server)))!;
+
+Future<List<String>> _show(
+ WidgetTester tester,
+ SuperTabActivity activity, {
+ Brightness brightness = Brightness.dark,
+ String? highlight,
+}) async {
+ await tester.binding.setSurfaceSize(const Size(900, 700));
+ addTearDown(() => tester.binding.setSurfaceSize(null));
+ final opened = <String>[];
+ await tester.pumpWidget(
+ MaterialApp(
+ theme: grid.buildAppTheme(brightness: brightness),
+ home: Scaffold(
+ body: SuperTabDecisionsPage(
+ activity: activity,
+ onOpenConversation: opened.add,
+ highlight: highlight,
+ now: () => _now,
+ ),
+ ),
+ ),
+ );
+ // The last lines come from a screen read: let it answer.
+ await tester.runAsync(
+ () => Future<void>.delayed(const Duration(milliseconds: 80)),
+ );
+ await tester.pumpAndSettle();
+ return opened;
+}
+
+Finder _key(String key) => find.byKey(ValueKey(key));
+
+void main() {
+ testWidgets('an agent at a prompt in the reader\'s task is a Decisions row '
+ 'with its task and last lines, counted, that opens its terminal', (
+ tester,
+ ) async {
+ await withClock(Clock.fixed(_now), () async {
+ final server = swarm()..followedThreads = null;
+ wrenAtPrompt(server);
+ final activity = await _loaded(tester, server);
+ expect(activity.needsCount, 1);
+ final opened = await _show(tester, activity);
+ final row = _key('super-activity-row-prompt:wren');
+ expect(row, findsOneWidget);
+ expect(
+ find.descendant(
+ of: row,
+ matching: find.text('Wren is waiting at a prompt in its terminal'),
+ ),
+ findsOneWidget,
+ );
+ expect(
+ find.descendant(of: row, matching: find.text('Flash the board')),
+ findsOneWidget,
+ );
+ // Its last lines, as its terminal shows them, blank ones trimmed.
+ final lines = _key('super-prompt-lines:wren');
+ expect(
+ tester
+ .widget<Text>(
+ find.descendant(of: lines, matching: find.byType(Text)),
+ )
+ .data,
+ 'Pairing the iPhone with the board.\n'
+ 'Open Settings > Glinks on the iPhone, check the password,\n'
+ 'press Connect, then tell me "connect rồi".\n'
+ '>',
+ );
+ await tester.tap(_key('super-prompt-open:wren'));
+ await tester.pumpAndSettle();
+ expect(opened, ['flash']);
+ expect(activity.controller.agentTerminalRequest, (
+ agentId: 'wren',
+ conversationId: 'flash',
+ ));
+ });
+ });
+
+ testWidgets('the row leaves Decisions, and its count, once the agent moves '
+ 'on', (tester) async {
+ await withClock(Clock.fixed(_now), () async {
+ final server = swarm()..followedThreads = null;
+ wrenAtPrompt(server);
+ final activity = await _loaded(tester, server);
+ await _show(tester, activity);
+ expect(_key('super-activity-row-prompt:wren'), findsOneWidget);
+ server.state['promptsWaiting'] = <dynamic>[];
+ await tester.runAsync(activity.controller.refresh);
+ await tester.pumpAndSettle();
+ expect(_key('super-activity-row-prompt:wren'), findsNothing);
+ expect(activity.needsCount, 0);
+ expect(find.text('Nothing needs you'), findsOneWidget);
+ });
+ });
+
+ testWidgets('a terminal the reader may not read keeps the row and says so', (
+ tester,
+ ) async {
+ await withClock(Clock.fixed(_now), () async {
+ final server = swarm()
+ ..followedThreads = null
+ ..refuseScreens = true;
+ wrenAtPrompt(server);
+ await _show(tester, await _loaded(tester, server));
+ expect(_key('super-activity-row-prompt:wren'), findsOneWidget);
+ expect(
+ find.text(
+ 'Its terminal isn\'t shown to you. Open the task to answer it.',
+ ),
+ findsOneWidget,
+ );
+ expect(_key('super-prompt-lines:wren'), findsNothing);
+ });
+ // Its machine did not answer: the row says that instead.
+ await withClock(Clock.fixed(_now), () async {
+ final server = swarm()..followedThreads = null;
+ wrenAtPrompt(server, screen: false);
+ await _show(tester, await _loaded(tester, server));
+ expect(find.text('Its last lines could not be read.'), findsOneWidget);
+ });
+ });
+
+ // The web calls the backend straight, and its transport refuses terminal
+ // reads (backend_transport.dart): there the row reads no screen at all.
+ testWidgets('on the web the row reads no terminal and points to it', (
+ tester,
+ ) async {
+ await withClock(Clock.fixed(_now), () async {
+ final server = swarm()..followedThreads = null;
+ wrenAtPrompt(server);
+ final activity = await _loaded(tester, server);
+ await tester.pumpWidget(
+ MaterialApp(
+ theme: grid.buildAppTheme(brightness: Brightness.dark),
+ home: Scaffold(
+ body: SuperTabPromptLines(
+ controller: activity.controller,
+ agentId: 'wren',
+ web: true,
+ ),
+ ),
+ ),
+ );
+ await tester.runAsync(
+ () => Future<void>.delayed(const Duration(milliseconds: 80)),
+ );
+ await tester.pumpAndSettle();
+ expect(server.screenRequests, isEmpty);
+ expect(_key('super-prompt-lines:wren'), findsNothing);
+ expect(
+ find.text('Open its terminal to see what it asks.'),
+ findsOneWidget,
+ );
+ });
+ });
+
+ testWidgets('opening Decisions for one need lights its row for a moment', (
+ tester,
+ ) async {
+ await withClock(Clock.fixed(_now), () async {
+ final server = swarm()..followedThreads = null;
+ server.ask(['Ship it behind a flag?', 'Keep the old route?']);
+ final activity = await _loaded(tester, server);
+ await _show(tester, activity, highlight: 'decision:decision-2');
+ expect(_key('super-activity-lit:decision:decision-2'), findsOneWidget);
+ expect(_key('super-activity-lit:decision:decision-1'), findsNothing);
+ await tester.pump(const Duration(seconds: 3));
+ await tester.pumpAndSettle();
+ expect(_key('super-activity-lit:decision:decision-2'), findsNothing);
+ });
+ });
+}
diff --git a/desktop/test/support/super_tab_fixture.dart b/desktop/test/support/super_tab_fixture.dart
index fe7b65c87..5eedbc34e 100644
--- a/desktop/test/support/super_tab_fixture.dart
+++ b/desktop/test/support/super_tab_fixture.dart
@@ -103,6 +103,7 @@ class SwarmPartsBackend {
'mentionsWaiting',
'decisionsWaiting',
'decisionsDigest',
+ 'promptsWaiting',
'otherProjectsWork',
'githubApp',
'readMarks',
@@ -188,6 +189,8 @@ class SwarmPartsBackend {
'decisionsWaiting': state['decisionsWaiting'],
if (state['decisionsDigest'] != null)
'decisionsDigest': state['decisionsDigest'],
+ if (state['promptsWaiting'] != null)
+ 'promptsWaiting': state['promptsWaiting'],
if (state['otherProjectsWork'] != null)
'otherProjectsWork': state['otherProjectsWork'],
// Each project's board pulse (backend superTabs/pulse.ts, task #3384).
@@ -545,6 +548,14 @@ class ConversationServer {
// Added to every successful command's result, as a newer backend adds
// fields such as `credentialNotice`.
final commandResult = <String, dynamic>{};
+ // Each agent's screen as an `agent.screen` request reads it (backend
+ // terminal.ts): absent, its host answers that it failed.
+ final screens = <String, String>{};
+ // `agent.screen` is refused, as mayDrive refuses a reader who may not read
+ // the terminal (a Harness Team account's agent, for anyone but its owner).
+ bool refuseScreens = false;
+ // The screen requests sent, by request id, with their agent.
+ final screenRequests = <String, String>{};
final posts = <Map<String, dynamic>>[];
/// Notification settings sent (backend chatSettings.ts), in order; while
@@ -1390,6 +1401,16 @@ class ConversationServer {
} else if (command['type'] == 'message.delete') {
output['changed'] = true;
output['kept'] = deleteMessage(command['messageId'] as String);
+ } else if (command['type'] == 'agent.screen') {
+ if (refuseScreens) {
+ throw const SuperTabFailure(
+ 'TERMINAL_PRIVATE',
+ 'Only its project\'s owner reads its screen.',
+ statusCode: 403,
+ );
+ }
+ screenRequests[operationId] = command['agentId'] as String;
+ output['requestId'] = operationId;
} else if (command['type'] == 'decision.answer') {
final id = command['decisionId'] as String;
if (command['delegate'] == true) {
@@ -1833,6 +1854,19 @@ class ConversationServer {
throw StateError('Offline');
}
final uri = Uri.parse(path);
+ // A screen request's answer (backend store.ts terminalResult).
+ if (uri.pathSegments.length > 2 &&
+ uri.pathSegments[uri.pathSegments.length - 2] == 'terminal') {
+ final id = uri.pathSegments.last;
+ final agentId = screenRequests.remove(id);
+ if (agentId == null) {
+ throw const SuperTabFailure('NOT_FOUND', 'Not found.', statusCode: 404);
+ }
+ final text = screens[agentId];
+ return text == null
+ ? {'requestId': id, 'ok': false, 'error': 'Its machine is offline.'}
+ : {'requestId': id, 'ok': true, 'text': text};
+ }
if (uri.pathSegments.length > 5 &&
uri.pathSegments[3] == 'projects' &&
uri.pathSegments[5] == 'instructions') {
diff --git a/docs/plans/2026-11-05-crew-dispatch-plan.md b/docs/plans/2026-11-05-crew-dispatch-plan.md
new file mode 100644
index 000000000..deb6f26b0
--- /dev/null
+++ b/docs/plans/2026-11-05-crew-dispatch-plan.md
@@ -0,0 +1,195 @@
+# The Swarm hands the next task to a free crew member: implementation plan
+
+> Implemented by the task's Engineer the project's way (project instructions, Engineer): task by task, test first, each
+> failing test committed before the code that passes it. No per-task review; the pull request's review step is the one
+> independent review. No Execution Handoff.
+
+**Goal:** The server, not the PM, gives work to the crew: every 30 seconds and right after the events that free a member
+or open a task, each free crew member gets its pinned work, then its lane's top task (P0 first, then queue order). Two
+hours without progress sends the member a line; three hours puts the task back in its lane with the reason. The board
+can group tasks by member.
+
+**Architecture:** A pure module `backend/src/superTabs/dispatch.ts` decides (lanes, who is free, pins, the next task,
+the clocks, the capacity line) from the state alone. `SuperTabStore.dispatchCrew(tabId)` reads a Swarm once, asks
+`dispatchPlan` for its picks and sends each through the existing `work.assign` command, as the project's PM, in that
+command's own transaction: `WORK_ACTIVE` and `AGENT_BUSY` already refuse a second assignment inside the write, and the
+pick's operation id is stable (`dispatch:<task>:<attempt>`), so two racing passes replay or collide instead of assigning
+twice. The 30-second liveness sweep (which machine reports already run, with the Swarm loaded) starts a pass when the
+plan is not empty, and API processes start one after a commit that can free a member or open a task. It runs in the API
+store, whose hooks give `work.assign` the GitHub facts it reads; the backend worker's store has none of them. The two clocks run in the liveness sweep that already loses tasks (liveness.ts), through
+its `loseTask`. Desktop adds Group by Member to the board.
+
+**Tech Stack:** TypeScript backend (vitest unit tests; the Mongo integration suite runs in PR CI), Flutter Desktop
+(flutter_test, memory store and fake sign-in).
+
+**Spec:** Task #3400 brief and its two acceptance checks (anh Dee's Swarm redesign, approved 2026-11-05).
+
+## Global Constraints
+
+- PR body first line: "Requested by Dee through Harness."
+- Owns `backend/src/superTabs/`, `backend/src/worker.ts`, `desktop/lib/super_tabs/` (and their tests).
+- Numbers live in one place, `DISPATCH_RULES` in `dispatch.ts`, until the project rules record (#3393) lands; then
+ `lanes` is read from its `lanes` section (`{ name, owns[] }`, the same shape) and the rest from the fields it adds.
+- None of removedRefusals.test.ts's codes comes back (that test stays green); `work.lane` adds two named ones,
+ `LANE_UNKNOWN` and `LANE_TASK_ONLY`, each naming the next step. A pick `work.assign` refuses is skipped and logged by
+ code, never retried in a loop.
+- Swarm code stays out of cli/src/core. Tests never sign the Mac out of the real CLI. Temp files only in mktemp -d.
+
+## Sibling interfaces (agreed in their tasks)
+
+- Crew (#3397, Keeper): `Agent.crew?: { role: string; at: number; by: string; lane?: string }` and `isCrew(agent)`.
+ `lane` is the one field this task asks Keeper to add (`crew.add` takes an optional `lane`). Until #3397 merges this
+ branch declares the same field in model.ts; whichever lands second keeps one copy.
+- Sleep and move (#3398, Heron): `Agent.asleep?: { since: number }` and `Agent.movedTo` on the agent record. An asleep
+ crew member counts as free, and its assignment wakes it in the same write (asked of Heron: `work.assign` wakes an
+ asleep crew member instead of refusing its closed session); a member with `movedTo` is skipped.
+- Handed (#3399, Handoff): `occupiesAgent(group)` (active work that is not handed) and `handed(group)` from handed.ts.
+ Until #3399 merges, dispatch.ts has the same two rules locally (handed = a task's own `review` status); then it imports
+ them. Before #3399, `work.assign` still refuses an agent with a handed task (`AGENT_BUSY`): the pass skips it.
+- Rules record (#3393, Ledger): `lanes` as above; `DISPATCH_RULES` moves there.
+
+## Design
+
+- **Growth:** two small fields per task (`lane` set by the PM, `pin` cleared at its assignment) and one per assignment
+ (`nudgedAt`); nothing else stored. The pass stores nothing of its own.
+- **Concurrency:** every assignment is one `work.assign` transaction (group and agent parts written, so a concurrent
+ write retries). Stable operation ids make racing passes (worker and API, two API processes) replay one receipt or
+ collide (`OPERATION_REUSED`, `WORK_ACTIVE`, `AGENT_BUSY`), never assign twice.
+- **Read cost:** no new query: the 30 s check computes the plan on the state the sweep already loaded, and a pass loads
+ only that one Swarm's active state, then writes one `work.assign` per pick.
+- **Scale:** 10x crew is 10x picks per pass, each a small transaction; the pass's log line (`[swarm-dispatch]` assigned,
+ skipped by code, ms) warns first.
+- **Compatibility:** older clients ignore `lane`, `pin`, `nudgedAt` and `derived.lanes`; an older CLI reads the
+ assignment as any other. A project with no crew is untouched: the PM assigns as today.
+- **Migration + rollback:** none. Rolling back stops the dispatch; assignments it made are ordinary assignments.
+- **Audience:** the server picks and assigns as the project's PM; only the PM or a person of the project sets a lane
+ (`work.lane`), as `work.queue` is guarded.
+- **Identity:** assignments are made as the project's PM agent (the actor the PM itself would be), never as a person or
+ the machine owner. A project with no PM is not dispatched (logged).
+- **Failure:** a refused pick is logged by code and left for the next pass; the 2 h line and the 3 h return each post in
+ the task (the return also to the PM, as any loss does); nothing changes silently.
+- **Platforms:** backend only, and the shared Desktop board (macOS, Windows, Linux, web alike).
+
+## Review Focus
+
+- Two passes at once (worker and an API process) over one free member and two tasks: one assignment each, never two
+ tasks to one member, never one task to two members (Task 3 integration test).
+- A member that lost a task to the 3 h clock is not handed the same task again at once (Task 2 test).
+- A P0 task deep in the queue beats the queue's first P2 (Task 2 test); a `notBefore` in the future, a step, an archived
+ task or a chat is never picked (Task 2 test).
+- A pinned task whose member left the crew or the Swarm goes to its lane, not nowhere (Task 2 test).
+- Waiting on a person or on review stops the clocks (Task 4 test).
+
+---
+
+### Task 1: Lanes and the task's lane
+
+**Files:**
+- Create: `backend/src/superTabs/dispatch.ts`, `backend/src/superTabs/dispatch.test.ts`
+- Modify: `backend/src/superTabs/model.ts` (Conversation `lane?`, `pin?`; Assignment `nudgedAt?`; Agent `crew?`),
+ `backend/src/superTabs/commands.ts` (`work.lane`)
+
+**Interfaces:**
+- Produces: `interface Lane { name: string; owns: string[] }`; `DISPATCH_RULES = { everyMs: 30_000, maxHanded: 3,
+ nudgeAfterMs: 2 * HOUR, returnAfterMs: 3 * HOUR, lanes: [backend: backend/, CLI: cli/, Desktop: desktop/,
+ mobile: mobile/, docs: docs/] }`; `laneOf(group, lanes): string | null`: the PM's `group.lane` if set, else the lane
+ owning most of the task's `owns` paths (prefix match; a tie goes to the table's first), else null.
+- Command `{ type: 'work.lane', conversationId, lane: string | null }`: the PM or a person of the project (the
+ `work.queue` guard); the lane name is matched to the table case-insensitively and stored as the table writes it.
+
+- [ ] Failing tests: owns `backend/src/x.ts` -> backend; `desktop/lib/a.dart` + `backend/src/b.ts` + `desktop/test/c`
+ -> Desktop; no match -> null; the PM's lane wins over paths; `work.lane` by the PM and by a person sets it, by another
+ agent is refused as `work.queue` is, null clears it.
+- [ ] Implement; run `npm test -- src/superTabs/dispatch.test.ts src/superTabs/commands.test.ts`; commit test, then code.
+
+### Task 2: Who is free, and what each free member gets
+
+**Files:** `dispatch.ts`, `dispatch.test.ts`
+
+**Interfaces:**
+- Produces: `freeCrew(state, projectId, rules): Agent[]`: crew agents of the project (not the PM, not a Buddy, not
+ stopping, not moving (`movedTo`), session not closed unless asleep, no pending start) with no occupying task and fewer than `maxHanded` handed tasks, fewest
+ handed first, then roster order. `dispatchPlan(state, projectId, rules, now): Pick[]` with
+ `Pick = { conversationId: string; agentId: string; why: 'pin' | 'lane'; lane: string | null }`: each member takes
+ first a task pinned to it (oldest pin first), then its lane's top open task (a member with no lane, whose role is
+ Engineer, takes the project's top task). Open = a task with a brief, no active work, not a step, not archived, not
+ cancelled or done, `notBefore` not after today. Order: P0 first, then `queueOrder`. Each task goes to one member.
+ A task lost by this member to the 3 h clock is skipped for it.
+
+- [ ] Failing tests: pins before the lane's top; P0 beats queue order; one task, two free members -> one pick; a member
+ with an occupying task or 3 handed tasks is not free; a member with 2 handed tasks is; the PM, a Buddy, a stopping agent, a moving one
+ and a non-crew agent get nothing; an asleep member is free; a pin whose member left the crew goes to the lane; the 3 h loser is skipped; future
+ `notBefore`, steps, archived and chats are never picked.
+- [ ] Implement; run the file; commit test, then code.
+
+### Task 3: The pass, as the PM, through work.assign
+
+**Files:**
+- Modify: `backend/src/superTabs/store.ts` (`dispatchCrew`, `dispatchSoon`, the sweep's check, hook `dispatch`),
+ `backend/src/routes/superTabs.ts` (one line: `dispatch: true` on the API store), `backend/vitest.super-tabs.config.ts`
+- Create: `backend/integration/crewDispatch.test.ts`
+
+**Interfaces:**
+- Produces: `SuperTabStore.dispatchCrew(tabId): Promise<{ assigned: number; skipped: Record<string, number> }>`. Each pick is
+ `executeOnce(PM's host user, tabId, { operationId: stableId('dispatch', task, String(attempts)), command: work.assign },
+ leadId)`. Triggers after commit: `work.status` (done, review, stopped), `work.cancel`, `conversation.create`,
+ `work.define`, `work.priority`, `work.queue`, `work.lane`, and losses.
+
+- [ ] Failing integration tests (fresh replica set, never DATABASE_URL): a free crew member is assigned its pin, then its
+ lane's top task; two `dispatchCrew` passes run together over one member and two tasks leave exactly one assignment
+ (one task, that member); a project with no crew is untouched; a refused pick (Team-written task, main-account member)
+ is skipped and the next task is tried.
+- [ ] Implement; run `npm test -- integration/crewDispatch.test.ts` once locally; commit test, then code.
+
+### Task 4: The 2 h line and the 3 h return
+
+**Files:** `backend/src/superTabs/liveness.ts` (in `lostReason` / `sweepLiveness`), `dispatch.ts`, `dispatch.test.ts`
+
+**Interfaces:**
+- Produces: `crewClock(state, group, worker, assignment, now, rules): 'nudge' | 'return' | null` from the assignment's
+ own progress (`progressAt`, else when it was assigned), only for crew members' tasks in `working`. `nudge` posts one
+ line to the member in the task (`assignment.nudgedAt`, once per assignment): "No progress on this task for 2 hours.
+ Post where it stands, or set it blocked with why; at 3 hours it goes back to the <lane> lane." `return` loses the task
+ with the reason "no progress for 3 hours: back in the <lane> lane".
+
+- [ ] Failing tests: at 2 h one line, not twice; at 3 h the task is lost with that reason and appears in `dispatchPlan`
+ for another member, not the same one; `needs_human`, `blocked` and handed tasks never tick; a non-crew worker is
+ unchanged; progress at 1 h 59 restarts both clocks.
+- [ ] Implement; run the file and liveness.test.ts; commit test, then code.
+
+### Task 5: Pins for findings, red CI and conflicts
+
+**Files:** `commands.ts` (`work.check`, `work.assign` clears), `store.ts` (`pullRequestSeen`), `dispatch.ts`, tests
+
+**Interfaces:**
+- Produces: `Conversation.pin?: { agentId: string; why: 'findings' | 'ci' | 'conflict'; at: number }`, set on a task with
+ no active work for its last builder (its assignment's or `lostAttempt`'s agent) when another agent's check fails
+ (findings), or the PR watch reads a failed check run at the head (ci) or `mergeable === false` (conflict); cleared by
+ any `work.assign`.
+
+- [ ] Failing tests: a Reviewer's failed check on a lost task pins it to its builder; the builder's own failed check does
+ not; red CI and a conflict pin; a green run does not; an assignment clears the pin.
+- [ ] Implement; commit test, then code.
+
+### Task 6: The capacity line per lane
+
+**Files:** `dispatch.ts`, `read/views.ts` (`derived.lanes`), `read/contract.ts`, tests
+
+**Interfaces:**
+- Produces: `laneCapacity(state, projectId, rules, now): Array<{ lane: string; waiting: number; busy: number;
+ oldestAt: number | null }>` and `capacityLine(c, now)`: `Desktop: 6 waiting, 2 busy, oldest 2 h`. Read:
+ `derived.lanes: Record<projectId, LaneCapacity[]>` for projects with crew.
+
+- [ ] Failing tests: counts and oldest for one lane; `capacityLine` reads exactly `Desktop: 6 waiting, 2 busy, oldest 2 h`;
+ no crew -> no entry.
+- [ ] Implement; commit test, then code.
+
+### Task 7: Desktop: Group by Member
+
+**Files:** `desktop/lib/super_tabs/tasks_view.dart`, `desktop/lib/super_tabs/model.dart`, a new
+`desktop/lib/super_tabs/member_groups.dart`; `desktop/test/super_tab_member_groups_test.dart`
+
+- [ ] ASCII mockup posted in the task first (the PM brings it to anh Dee; work goes on, his look comes after merge).
+- [ ] Failing widget test (memory store, fake sign-in): Group by Member lists each member with its lane and its tasks,
+ then Unassigned; the lane capacity lines show at the top; the default board is unchanged.
+- [ ] Implement by the Harness design language; run the test file and the board's existing tests; commit test, then code.
diff --git a/docs/plans/2026-11-05-prompt-waits-for-people-plan.md b/docs/plans/2026-11-05-prompt-waits-for-people-plan.md
new file mode 100644
index 000000000..41ebf972b
--- /dev/null
+++ b/docs/plans/2026-11-05-prompt-waits-for-people-plan.md
@@ -0,0 +1,89 @@
+# When an agent needs a person, the person is told in the Swarm: plan
+
+> Written by the Engineer per the project instructions (writing-plans, then test-driven-development task by task). No
+> Execution Handoff: the Engineer implements it.
+
+**Goal:** An agent in a task that waits at a prompt in its terminal reaches the person that task needs, under Decisions
+(Desktop's red count and row, the phone's notice), and the row clears once the agent moves on. Agents are told never to
+ask a person only in their terminal. Task #3029, requested by Gray.
+
+**Architecture:** The backend already keeps `agent.alerting` with `prompt` while a host sees its agent at a prompt
+(cli `superTabs/terminal.ts`, after 3 minutes) and drops it when the prompt goes. A new pure function
+(`backend/src/superTabs/promptWaits.ts`) derives, on each person's read, the prompts that wait for them: an agent at a
+prompt whose active task names them as its requester (a step's, the task it reviews), or whose task needs a device on
+the agent's machine and they own that machine; only in tasks they still read. It goes out as `derived.promptsWaiting`.
+Nothing is stored. Desktop lists these as rows on the Decisions page and counts them in the sidebar's red count. The
+agent's last lines are read on demand through the existing `agent.screen` request, which checks who may read the
+terminal (`terminal.ts mayDrive`). The row's button opens the terminal through `openAgentTerminal`. The phone adds each
+as a need, so it raises the same local notice as other needs. The skill text gets one line in every role.
+
+**Tech Stack:** TypeScript (backend, vitest), Dart/Flutter (Desktop and phone widget tests with the in-memory
+`ConversationServer`), CLI skill text (vitest).
+
+**Spec:** the task's brief (#3029) and River's added piece: opening Decisions for one need lights its row for a moment.
+
+## Design
+
+- growth: nothing is stored. A row exists while `alerting` holds `prompt` and the task is active.
+- concurrency: N/A, because it is read-only and derived inside each read from the state that read already loaded.
+- read cost: one pass over agents that are alerting (few), then one conversation lookup each, per person read. No database read.
+- scale: at 10x agents, the pass is still O(agents). The first warning would be read latency on `/changes`, which is already measured.
+- compatibility: `promptsWaiting` is a new optional field. Older Desktops and phones ignore it, and newer apps read an
+ older backend's missing field as none. An old app's count does not change.
+- migration + rollback: none. Rolling back the backend removes the field, and apps show nothing.
+- audience: the server picks each reader's rows. A row needs the reader to be the task's requester or the device
+ machine's owner, and to still read the task (`canReadGroup`). Agents get no field. No screen text goes in the read;
+ last lines come only through `agent.screen`, under `mayDrive`.
+- identity: the person comes from the task's `requesterId` and the agent's `machineOwnerId`, never from a login.
+- failure: when the terminal read is refused or fails (Team account, machine offline), the row still shows and says it
+ cannot show the lines. The button then opens the task.
+- platforms: backend; Desktop on macOS, Windows and Linux (Flutter); phone (iOS/Android, local notices).
+
+## Global Constraints
+
+- Only the task's own people are told; nothing about other projects.
+- No screen text stored or sent in reads; the PM's alert row is unchanged.
+- Swarm code stays out of `cli/src/core`. Desktop tests use a memory store and a fake sign-in.
+
+## Review Focus
+
+- Who is told (`promptWaits.ts taskPerson`), and that a reader who lost the task is told nothing.
+- That last lines go only through `agent.screen` (mayDrive), never in the read.
+
+## Tasks
+
+### Task 1: Backend: prompts that wait for a person, in their read
+
+**Files:** `backend/src/superTabs/promptWaits.ts` (new), `promptWaits.test.ts` (new), `read/views.ts`, `read/contract.ts`.
+**Interfaces:** `promptWaits(state, person): PromptWait[]`; `Derived.promptsWaiting?: PromptWait[]`.
+
+- [ ] Failing tests: requester told and PM still told, cleared on `active: false`; others, the machine owner without a
+ device, and a reader who lost the task are not told; the device machine owner is told; a step's task requester is told;
+ the field is on a person's read only.
+- [ ] Implement; run `promptWaits.test.ts`, `terminal.test.ts`, `read/views.test.ts`.
+
+### Task 2: Skill text: never ask a person only in your terminal
+
+**Files:** `cli/src/lib/swarmSkills.ts`, `cli/src/lib/swarmSkills.spec.ts`.
+
+- [ ] Failing test: every role in both modes has the line once (post the ask in the task, tag the person, set needs_human).
+- [ ] Add the line under each role's "Who a post reaches". (The brief names a Desktop copy of this text. None exists in
+ `desktop/`: Desktop launches agents through the CLI, which writes these files.)
+
+### Task 3: Desktop: the Decisions row, the count, last lines, the highlight
+
+**Files:** `desktop/lib/super_tabs/model.dart`, `parts.dart`, `activity.dart`, `decisions_page.dart`, a new
+`prompt_lines.dart` (the screen read), tests in `desktop/test/super_tab_prompt_waits_test.dart` and the fixture.
+
+- [ ] Failing widget tests: a prompt wait shows as a Decisions row with its agent, task and last lines, and counts in the
+ sidebar; its button opens the terminal; it leaves once the read drops it; a refused screen read says so; opening the
+ page for one need lights its row.
+- [ ] Implement; light and dark screenshots of the row.
+
+### Task 4: Phone: the notice
+
+**Files:** `mobile/lib/swarm/model.dart`, `parts.dart`, `swarm_inbox.dart`, `swarm_notices.dart`, a test.
+
+- [ ] Failing test: a prompt wait in a read becomes a need that announces once ("X is waiting at a prompt"), and goes when
+ the read drops it.
+- [ ] Implement.
diff --git a/docs/plans/2026-11-06-merge-train-rules-record-plan.md b/docs/plans/2026-11-06-merge-train-rules-record-plan.md
new file mode 100644
index 000000000..3a9cc0881
--- /dev/null
+++ b/docs/plans/2026-11-06-merge-train-rules-record-plan.md
@@ -0,0 +1,52 @@
+# Merge train reads the project rules record Implementation Plan
+
+> **For agentic workers:** implemented the project's way (project instructions, Engineer): task by task, each failing test
+> committed before the code that passes it; one review and one security review on the pull request.
+
+**Goal:** The merge train (#3402) decides which reviews a change needs, and whether it runs at all, from the project's rules
+record (#3393, on main), not from its own copy, so one rules edit changes both the review steps and what the train waits for.
+
+**Architecture:** The train's review gate calls `requiredReads(rules, files)` and `testsFor(rules, files)` from
+`backend/src/superTabs/policy.ts`, and reads the record per project with `currentRules(db, tabId, projectId)`
+(`policyStore.ts`; the seed at revision 0 when nothing is saved). Its switch and interval come from `rules.mergeTrain`.
+The train's local table, matcher and constants (as Train described them: `mergeTrain/config.ts` and a constant list of
+security paths needing two reads) are deleted. A changed-file list the train cannot read stays `null`, which the helpers
+treat as the most reads any row asks: fail closed.
+
+**Tech Stack:** TypeScript, Vitest, Prisma on MongoDB (backend).
+
+**Spec:** Task #3475's brief (River, anh Dee's Swarm redesign, 11-06). Interfaces: `policy.ts` and `policyStore.ts` on main;
+the train as merged from #3226 (read on main once it lands; its branch is Team-written and is not checked out before).
+
+## Global Constraints
+
+- PR body first line: "Requested by Dee through Harness."
+- Owns the merge train (`backend/src/superTabs/mergeTrain/`, where it landed, and `backend/src/github/train.ts`) and its wiring in `backend/src/worker.ts`; `policy.ts` is used, not changed.
+- Built from main only after #3226 merges; started blocked until then.
+- No path may let the train merge with fewer reads than the rules require: an unreadable rules record or file list fails
+ closed (holds the batch), never falls back to fewer reads.
+
+## Review Focus
+
+- Rules record unreadable (database error): the train holds; it does not use the seed's numbers in place of a saved record.
+- Changed files unknown (GitHub read fails, or a file list cut off): most reads of any row, as `requiredReads(rules, null)`.
+- The train and the review steps disagree on a file (the old local matcher's rules differed, e.g. the folder boundary,
+ #3237): both now call one matcher, and a test pins them to the same answer on the same files.
+- A rules save between planning a batch and merging it: the train re-reads the record at merge time, or pins the revision
+ it planned with and refuses if it moved (decided after reading the train's code).
+- Merge train switched off in the rules record: no batch starts; one in flight finishes or stops as the train defines.
+
+---
+
+### Task 1: The train reads the record
+**Files:** `backend/src/superTabs/mergeTrain/` (plan.ts, config.ts, train.ts, run.ts and their tests), `backend/src/worker.ts` (the reader).
+- [ ] Failing tests: a saved record with a new two-read area makes the train wait for two reads on a file there; with no
+ record the seed applies; an unreadable record holds the batch; `mergeTrain.enabled` false starts nothing.
+- [ ] Code: call `currentRules`/`requiredReads`/`testsFor`; delete the local table, matcher and constants.
+
+### Task 2: The train and the review steps agree
+**Files:** `backend/src/superTabs/mergeTrain/rulesRecord.test.ts`.
+- [ ] Failing test: for the seed and for a saved record, over a fixed set of changed-file lists (security paths, tests-only,
+ Desktop, unknown), the train's required reads equal what the review steps plan (`requiredReads`, or `reviewPlan` if
+ #3227 is on main by then).
+- [ ] Code: any remaining divergence removed.
diff --git a/mobile/lib/swarm/model.dart b/mobile/lib/swarm/model.dart
index 9f48c4ec5..c3773f0fe 100644
--- a/mobile/lib/swarm/model.dart
+++ b/mobile/lib/swarm/model.dart
@@ -430,6 +430,9 @@ class SuperTabConversation {
: null,
queueRank = (row['queueRank'] as num?)?.toDouble(),
priority = row['priority'] as String?,
+ handOutLane = row['handOutLane'] is String
+ ? row['handOutLane'] as String
+ : null,
notBefore = DateTime.tryParse(row['notBefore'] as String? ?? ''),
lastMainSequence = (row['lastMainSequence'] as num?)?.toInt(),
lastPersonSequence = (row['lastPersonSequence'] as num?)?.toInt() ?? 0,
@@ -495,6 +498,11 @@ class SuperTabConversation {
/// taskPriority.ts, task #3117); null on a step, a chat and a task from
/// before it. Read here for the phone's Tasks view to come.
final String? priority;
+
+ /// The lane the crew dispatch hands this task out in (backend read/views.ts
+ /// `handOutLane`, task #3400; desktop model.dart). Null when no lane owns it,
+ /// on a chat or a step, and from an older server.
+ final String? handOutLane;
String get label => number == null ? title : '#$number $title';
final String? leadId;
final List<String> agentIds;
@@ -566,6 +574,10 @@ class SuperTabConversation {
final Map<String, dynamic>? leadAction;
}
+/// The zone a project's day is read in when its digest names none (backend
+/// costs/reflection.ts `DEFAULT_TIME_ZONE`).
+const superTabDefaultTimeZone = 'Asia/Ho_Chi_Minh';
+
class SuperTabProject {
SuperTabProject.fromJson(Map<String, dynamic> row)
: id = _text(row, 'id'),
@@ -589,6 +601,10 @@ class SuperTabProject {
superTabMap(member)['generation'] as String?,
},
updateMinutes = (row['updateMinutes'] as num?)?.toInt() ?? 5,
+ timeZone = switch (row['digest']) {
+ {'timeZone': final String zone} when zone.isNotEmpty => zone,
+ _ => superTabDefaultTimeZone,
+ },
status = SuperTabProjectStatus.read(row['status']),
repository = row['repository'] is Map
? Map.unmodifiable(superTabMap(row['repository']))
@@ -602,6 +618,10 @@ class SuperTabProject {
};
final String id, name, ownerId, leadConversationId;
+ /// The zone its day is read in, read as the desktop's model reads it (its
+ /// digest's, else [superTabDefaultTimeZone]); the phone shows no lanes yet.
+ final String timeZone;
+
/// The person's messages the server keeps for this project's Lead: a
/// Personal Swarm's chat with none, whose Lead their computer starts
/// (backend leadStart.ts). Empty from a server before it.
@@ -735,6 +755,14 @@ class SuperTabSnapshot {
pulses = SuperTabPulse.readAll(row['pulse']),
decisionsWaiting = (row['decisionsWaiting'] as num?)?.toInt() ?? 0,
decisionsDigest = row['decisionsDigest'] as String?,
+ promptsWaiting = List.unmodifiable([
+ for (final wait in row['promptsWaiting'] as List? ?? const [])
+ if (wait case {
+ 'agentId': final String agentId,
+ 'conversationId': final String conversationId,
+ })
+ (agentId: agentId, conversationId: conversationId),
+ ]),
activityDigest = row['activityDigest'] as String?,
remindersDigest = row['remindersDigest'] as String?,
chatSettings = Map.unmodifiable({
@@ -864,6 +892,11 @@ class SuperTabSnapshot {
/// count may not; null from a backend before it (superTabs/decisions.ts).
final String? decisionsDigest;
+ /// The task agents at a prompt in their terminals that wait for the reader,
+ /// as the backend chose them (superTabs/promptWaits.ts, task #3029); empty
+ /// from a backend before it.
+ final List<({String agentId, String conversationId})> promptsWaiting;
+
/// Which of the reader's Activity rows are unread, as a digest (backend superTabs/activity.ts); null from a backend
/// before it. Read as the desktop's model reads it; the phone shows no Activity yet.
final String? activityDigest;
diff --git a/mobile/lib/swarm/parts.dart b/mobile/lib/swarm/parts.dart
index 184ac753b..7ccaac1ca 100644
--- a/mobile/lib/swarm/parts.dart
+++ b/mobile/lib/swarm/parts.dart
@@ -488,6 +488,9 @@ class SuperTabParts {
if (_derived['decisionsDigest'] case final String digest) {
state['decisionsDigest'] = digest;
}
+ if (_derived['promptsWaiting'] case final List waiting) {
+ state['promptsWaiting'] = waiting;
+ }
if (_derived['remindersDigest'] case final String digest) {
state['remindersDigest'] = digest;
}
diff --git a/mobile/lib/swarm/swarm_notices.dart b/mobile/lib/swarm/swarm_notices.dart
index a23911a07..a7dc24312 100644
--- a/mobile/lib/swarm/swarm_notices.dart
+++ b/mobile/lib/swarm/swarm_notices.dart
@@ -27,6 +27,11 @@ SwarmNoticeMessage swarmNotice(SwarmNeed need) {
mention.projectName,
'Open Harness to read it.',
),
+ SwarmWorkNeed(:final work) when work.atPrompt => (
+ '${work.agentName} is waiting at a prompt',
+ work.project.name,
+ 'Open Harness to answer it.',
+ ),
SwarmWorkNeed(:final work) when work.status == 'blocked' => (
'${work.agentName} is stuck',
work.project.name,
diff --git a/mobile/lib/swarm/waiting_work.dart b/mobile/lib/swarm/waiting_work.dart
index b6699f61f..b7683937a 100644
--- a/mobile/lib/swarm/waiting_work.dart
+++ b/mobile/lib/swarm/waiting_work.dart
@@ -1,25 +1,41 @@
import 'model.dart';
/// One piece of work waiting on the reader: its worker needs a person or is
-/// stuck.
+/// stuck, or waits at a prompt in its terminal ([atPrompt], task #3029).
class SwarmWaitingWork {
- SwarmWaitingWork(this.conversation, this.project, this.snapshot);
+ SwarmWaitingWork(
+ this.conversation,
+ this.project,
+ this.snapshot, {
+ this.promptAgentId,
+ });
final SuperTabConversation conversation;
final SuperTabProject project;
final SuperTabSnapshot snapshot;
- /// `needs_human` or `blocked`.
- String get status => conversation.assignment!['status'] as String;
+ /// The agent at a prompt in its terminal, when that is what waits.
+ final String? promptAgentId;
+
+ /// Whether its agent waits at a prompt in its terminal, whatever its status.
+ bool get atPrompt => promptAgentId != null;
+
+ /// `needs_human` or `blocked`; `prompt` for an agent at a prompt.
+ String get status =>
+ atPrompt ? 'prompt' : conversation.assignment!['status'] as String;
/// The worker's name.
- String get agentName =>
- snapshot.agentName(conversation.assignment!['agentId'] as String? ?? '');
+ String get agentName => snapshot.agentName(
+ promptAgentId ?? conversation.assignment!['agentId'] as String? ?? '',
+ );
/// What the worker wrote with the status: its question, or why it is stuck.
- String? get question => switch (conversation.assignment!['result']) {
- final String text when text.trim().isNotEmpty => text.trim(),
- _ => null,
- };
+ /// At a prompt, it says so: the prompt itself is in its terminal.
+ String? get question => atPrompt
+ ? 'Waiting at a prompt in its terminal'
+ : switch (conversation.assignment!['result']) {
+ final String text when text.trim().isNotEmpty => text.trim(),
+ _ => null,
+ };
}
/// Each conversation's partner, the person its work needs (`partnerId`, named
@@ -59,6 +75,17 @@ List<SwarmWaitingWork> swarmWaitingWork(
if (snapshot.projectById(conversation.projectId) case final project?)
if ((partners[conversation.id] ?? project.ownerId) == accountId)
SwarmWaitingWork(conversation, project, snapshot),
+ // An agent at a prompt in a task of the reader's: the backend chose them
+ // (the task's requester, or the device machine's owner), so no rule here.
+ for (final wait in snapshot.promptsWaiting)
+ if (snapshot.conversation(wait.conversationId) case final conversation?)
+ if (snapshot.projectById(conversation.projectId) case final project?)
+ SwarmWaitingWork(
+ conversation,
+ project,
+ snapshot,
+ promptAgentId: wait.agentId,
+ ),
]);
_kept[snapshot] = (accountId: accountId, partners: partners, work: work);
return work;
diff --git a/mobile/test/swarm/swarm_notices_test.dart b/mobile/test/swarm/swarm_notices_test.dart
index 12f00a9b2..b4dbd1d19 100644
--- a/mobile/test/swarm/swarm_notices_test.dart
+++ b/mobile/test/swarm/swarm_notices_test.dart
@@ -135,6 +135,63 @@ void main() {
keepsItsContent(stuck, ['No access', 'Sync']);
});
+ // Task #3029: an agent of the reader's task at a prompt in its terminal, as
+ // the backend lists it for them (superTabs/promptWaits.ts).
+ SuperTabSnapshot atPrompt({bool listed = true}) => SuperTabSnapshot.fromJson(
+ SuperTabParts.firstLoad(
+ firstLoad(
+ groups: [
+ {
+ ...groupData(
+ 'g1',
+ title: 'Flash the board',
+ number: 4,
+ status: 'working',
+ ),
+ 'assignment': {
+ 'id': 'attempt-g1',
+ 'agentId': 'agent-builder',
+ 'status': 'working',
+ },
+ },
+ ],
+ derived: {
+ if (listed)
+ 'promptsWaiting': [
+ {
+ 'agentId': 'agent-builder',
+ 'agentName': 'Nova',
+ 'conversationId': 'g1',
+ 'conversationTitle': 'Flash the board',
+ 'projectId': 'p1',
+ 'projectName': 'Mobile',
+ },
+ ],
+ },
+ ),
+ ).state,
+ );
+
+ test('an agent at a prompt in the reader\'s task is a notice of its own, '
+ 'whoever owns the project, and goes when the read drops it', () {
+ // The backend chose the reader: no partner or owner rule here.
+ final waiting = swarmWaitingWork(atPrompt(), 'person-requester').single;
+ expect(waiting.atPrompt, isTrue);
+ expect(waiting.status, 'prompt');
+ final notice = swarmNotice(SwarmWorkNeed(tab, waiting));
+ expect(notice.title, 'Nova is waiting at a prompt');
+ expect(notice.subtitle, 'Mobile');
+ expect(notice.body, 'Open Harness to answer it.');
+ expect(notice.target.conversationId, 'g1');
+ keepsItsContent(notice, ['Flash the board']);
+ // A key of its own: a needs_human of the same task is another notice.
+ expect(SwarmWorkNeed(tab, waiting).key, contains(':prompt'));
+ expect(
+ swarmWaitingWork(atPrompt(listed: false), 'person-requester'),
+ isEmpty,
+ );
+ });
+
test('each need is its own notice, and the same need replaces itself', () {
expect(swarmNotice(decision()).key, swarmNotice(decision()).key);
expect(swarmNotice(decision()).key, isNot(swarmNotice(mention()).key));