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-02 b2010: #2569 #2593 #2596 (#2606)

0xken1508e24276a464
diff --git a/backend/integration/superTabLiveness.test.ts b/backend/integration/superTabLiveness.test.ts
index 6d96f77f1..1c34ad9fb 100644
--- a/backend/integration/superTabLiveness.test.ts
+++ b/backend/integration/superTabLiveness.test.ts
@@ -629,7 +629,8 @@ describe('messages from an agent whose task moved', () => {
await f.observe('test-host', [], { stoppedHarnessIds: [f.harness.worker] })
const other = await f.add(f.group, 'test-host', f.harness.other, 'Other')
const next = String((await f.execute({ type: 'work.assign', conversationId: f.group, agentId: other })).result.assignmentId)
- await f.observe('test-host', [], { stoppedHarnessIds: [f.harness.worker, f.harness.other] })
+ // The first worker is back and running; only the second's session stopped.
+ await f.observe('test-host', [f.harness.worker], { stoppedHarnessIds: [f.harness.other] })
expect(await f.assignment()).toMatchObject({ id: next, status: 'lost' })
expect(await deliveredTo(await post(f, f.worker, 'Severe: the worker is down.'))).toEqual([f.lead])
expect(await deliveredTo(await post(f, other, 'Lost my session.'))).toEqual([f.lead])
@@ -2061,3 +2062,158 @@ describe('the morning digest', () => {
expect(await db.swarmGroup.count({ where: { tabId: f.tab, key: first!.conversationId } })).toBe(1)
})
})
+
+// Huy, 2026-11-02: four agents closed on MacBookPro2021 sat under Idle for hours, each in the machine's stopped list. A
+// session closed on its machine is recorded as stopped and leaves the list; only a kept one stays, shown as closed.
+describe('an agent closed on its machine', () => {
+ const agents = async (f: Awaited<ReturnType<typeof swarm>>) => (await f.timed.read(owner, f.tab)).state.agents
+ const ids = async (f: Awaited<ReturnType<typeof swarm>>) => (await agents(f)).map(a => a.id)
+ type Fixture = Awaited<ReturnType<typeof swarm>>
+ /** Both machines report every 5 seconds for `seconds`; the worker host lists `running` and `stopped`. */
+ const reports = async (f: Fixture, seconds: number, running: string[], stopped: string[] = [], store?: SuperTabStore) => {
+ for (let t = 0; t < seconds; t += 5) {
+ f.clock.now += 5_000
+ await f.observe('lead-host', [f.harness.lead])
+ await f.observe('test-host', running, { stoppedHarnessIds: stopped }, store)
+ }
+ }
+ const closing = async (f: Fixture) => (await rosterRows(f.timed, host, 'test-host')).filter(r => r.tabId === f.tab && 'closeSession' in r)
+
+ it('leaves the list when its machine keeps reporting its session stopped, never on the first report', async () => {
+ const f = await swarm()
+ await f.beat(f.clock.now)
+ const idle = await f.add(f.group, 'test-host', f.harness.other, 'Idle one')
+ expect(await ids(f)).toContain(idle)
+ await reports(f, 5, [f.harness.worker], [f.harness.other])
+ expect(await ids(f)).toContain(idle)
+ await reports(f, 20, [f.harness.worker], [f.harness.other])
+ expect(await ids(f)).toContain(idle)
+ await reports(f, 10, [f.harness.worker], [f.harness.other])
+ expect(await ids(f)).toEqual([f.lead, f.worker])
+ const group = (await f.timed.read(owner, f.tab)).state.conversations.find(c => c.id === f.group)!
+ expect(group.agentIds).not.toContain(idle)
+ })
+
+ it('has its host close the session it leaves (security reviews of #2569)', async () => {
+ const f = await swarm()
+ await f.beat(f.clock.now)
+ const idle = await f.add(f.group, 'test-host', f.harness.other, 'Idle one')
+ await reports(f, 40, [f.harness.worker], [f.harness.other])
+ expect(await ids(f)).not.toContain(idle)
+ expect(await closing(f)).toEqual([expect.objectContaining({ agent: expect.objectContaining({ id: idle, harnessId: f.harness.other }) })])
+ await f.execute({ type: 'agent.sessionClosed', agentId: idle, harnessId: f.harness.other } as Command, host)
+ expect(await closing(f)).toEqual([])
+ })
+
+ it('keeps an agent whose task was just lost, tells its Lead, and removes it once the Lead cancels the task', async () => {
+ const f = await swarm()
+ await f.beat(f.clock.now)
+ f.clock.now += MINUTE
+ await f.observe('lead-host', [f.harness.lead])
+ await f.observe('test-host', [], { stoppedHarnessIds: [f.harness.worker] })
+ expect(await f.assignment()).toMatchObject({ status: 'lost', lost: { reason: 'its session on Worker Mac stopped' } })
+ expect((await f.leadInbox()).some(m => (m.source as { kind?: string }).kind === 'work-lost')).toBe(true)
+ await reports(f, 60, [], [f.harness.worker])
+ expect(await ids(f)).toContain(f.worker)
+ await f.execute({ type: 'work.cancel', conversationId: f.group, assignmentId: f.assignmentId, reason: 'Not needed' })
+ await reports(f, 10, [], [f.harness.worker])
+ expect(await ids(f)).toEqual([f.lead])
+ })
+
+ it('stays when it was kept, and shows as down; a coordinator or a running session stays too', async () => {
+ const f = await swarm()
+ await f.beat(f.clock.now)
+ const kept = await f.add(f.group, 'test-host', f.harness.other, 'Kept one')
+ await f.execute({ type: 'agent.release', agentId: kept, decision: 'keep' })
+ await reports(f, 60, [f.harness.worker], [f.harness.other])
+ // The Lead's session is in its machine's stopped list; the worker's is running.
+ for (let i = 0; i < 12; i++) {
+ f.clock.now += 5_000
+ await f.observe('lead-host', [], { stoppedHarnessIds: [f.harness.lead] })
+ await f.observe('test-host', [f.harness.worker], { stoppedHarnessIds: [f.harness.other] })
+ }
+ expect((await ids(f)).sort()).toEqual([f.lead, f.worker, kept].sort())
+ expect((await agents(f)).find(a => a.id === kept)).toMatchObject({ workDecision: 'keep', downSince: expect.any(String) })
+ })
+
+ it('stays when its session is in both lists, as a host resuming it reports', async () => {
+ const f = await swarm()
+ await f.beat(f.clock.now)
+ await reports(f, 60, [f.harness.worker], [f.harness.worker])
+ expect(await ids(f)).toContain(f.worker)
+ })
+
+ it('stays when a stop was asked for: its host closes it and takes it out', async () => {
+ const f = await swarm()
+ await f.beat(f.clock.now)
+ const idle = await f.add(f.group, 'test-host', f.harness.other, 'Idle one')
+ await f.execute({ type: 'agent.release', agentId: idle, decision: 'stop' })
+ await reports(f, 60, [f.harness.worker], [f.harness.other])
+ expect(await ids(f)).toContain(idle)
+ expect(await closing(f)).toEqual([])
+ })
+
+ it('stays when its host lists it stopped for a moment and then running again, as after a restart', async () => {
+ const f = await swarm()
+ await f.beat(f.clock.now)
+ const idle = await f.add(f.group, 'test-host', f.harness.other, 'Idle one')
+ await reports(f, 25, [f.harness.worker], [f.harness.other])
+ await reports(f, 5, [f.harness.worker, f.harness.other])
+ await reports(f, 25, [f.harness.worker], [f.harness.other])
+ expect(await ids(f)).toContain(idle)
+ })
+
+ it('leaves after 15 minutes down while its machine keeps reporting without it, never on the first report after silence', async () => {
+ const f = await swarm()
+ await f.beat(f.clock.now)
+ const idle = await f.add(f.group, 'test-host', f.harness.other, 'Idle one')
+ await f.observe('test-host', [f.harness.worker, f.harness.other])
+ // Down from here, in no stopped list: the host just does not list it. Reports come every 15 seconds.
+ const report = async (seconds = 15) => {
+ f.clock.now += seconds * 1000
+ await f.observe('lead-host', [f.harness.lead])
+ await f.observe('test-host', [f.harness.worker])
+ }
+ for (let i = 0; i < 24; i++) await report()
+ expect(await ids(f)).toContain(idle)
+ // Silent past 15 minutes, then back: not removed on the report that ends the silence, nor soon after.
+ await report(15 * 60)
+ await report()
+ expect(await ids(f)).toContain(idle)
+ // The full report that follows (at least every two minutes) removes it.
+ for (let i = 0; i < 10; i++) await report()
+ expect(await ids(f)).not.toContain(idle)
+ expect(await ids(f)).toContain(f.worker)
+ expect(await closing(f)).toHaveLength(1)
+ })
+
+ it('removes nobody by time while its machine lists no session running (a fault in its listing)', async () => {
+ const f = await swarm()
+ await f.beat(f.clock.now)
+ const idle = await f.add(f.group, 'test-host', f.harness.other, 'Idle one')
+ await reports(f, 20 * 60, [])
+ expect(await ids(f)).toContain(idle)
+ })
+
+ it('does not lose an assignment that lands while it is being removed (the report retries against it)', async () => {
+ const f = await swarm()
+ await f.beat(f.clock.now)
+ const idle = await f.add(f.group, 'test-host', f.harness.other, 'Idle one')
+ const second = String((await f.execute({ type: 'conversation.create', title: 'Second', brief: 'More', checks: [{ description: 'Verified', independent: false }] })).result.conversationId)
+ await reports(f, 30, [f.harness.worker], [f.harness.other])
+ let raced = false
+ const racing = new SuperTabStore(beforeFirstWrite(db, async () => {
+ if (raced) return
+ raced = true
+ await f.execute({ type: 'work.assign', conversationId: second, agentId: idle })
+ }), () => f.clock.now)
+ await reports(f, 10, [f.harness.worker], [f.harness.other], racing)
+ expect(raced).toBe(true)
+ const state = (await f.timed.read(owner, f.tab)).state
+ const group = state.conversations.find(c => c.id === second)!
+ expect(group.assignment).toMatchObject({ agentId: idle })
+ expect(state.agents.map(a => a.id)).toContain(idle)
+ expect(group.agentIds).toContain(idle)
+ expect(await closing(f)).toEqual([])
+ })
+})
diff --git a/backend/integration/superTabTidy.test.ts b/backend/integration/superTabTidy.test.ts
index 2bbfe16c0..2ddf6aceb 100644
--- a/backend/integration/superTabTidy.test.ts
+++ b/backend/integration/superTabTidy.test.ts
@@ -451,6 +451,47 @@ describe('a review nobody reviews', () => {
expect((await f.reviews()).filter(row => !row.archived)).toHaveLength(1)
})
+ /** The task's check recorded by its Reviewer, and the task set done by its Builder, its step as it stands. */
+ const finishTask = async (f: Awaited<ReturnType<typeof waiting>>) => {
+ const row = await db.swarmGroup.findFirstOrThrow({ where: { tabId: f.tab, key: f.reviewed } })
+ for (const check of (row.data as unknown as { checks: Array<{ id: string }> }).checks) {
+ await f.execute({ type: 'work.check', conversationId: f.reviewed, assignmentId: f.work, checkId: check.id, passed: true, evidence: 'Read it' }, host, f.reviewer)
+ }
+ await f.execute({ type: 'work.status', conversationId: f.reviewed, assignmentId: f.work, status: 'done', result: `Done ${PR}` }, host, f.builder)
+ }
+
+ // Diego, 2026-11-02: an Engineer set its task done before its Tester's verdict, the pull request merged, and 30 minutes later
+ // the pass cancelled the Tester's step without a word; its verdict was then refused, and lost.
+ it('the archive pass tells a working step agent its task was archived', async () => {
+ const f = await waiting(true)
+ await finishTask(f)
+ await db.superTabDelivery.updateMany({ where: { tabId: f.tab, conversationId: f.review.key, status: 'queued' }, data: { status: 'delivered' } })
+ f.clock.now += 40 * MINUTE
+ expect(await archiveFinishedGroups(db, f.timed, github({ [PR]: 'merged' }), f.clock.now)).toBeGreaterThan(0)
+ expect((await db.swarmGroup.findFirstOrThrow({ where: { tabId: f.tab, key: f.reviewed } })).archived).toBe(true)
+ const rows = (await db.superTabMessage.findMany({ where: { tabId: f.tab, conversationId: f.review.key } }))
+ .filter(row => row.recipientIds.includes(f.reviewer) && row.text === 'Parser v2 was archived.')
+ expect(rows).toHaveLength(1)
+ // It can still reach its agent: the step stays open to deliver it, cancelled.
+ expect((await db.superTabDelivery.findMany({ where: { tabId: f.tab, messageId: rows[0]!.id, agentId: f.reviewer } })).map(d => d.status)).toEqual(['queued'])
+ expect(await f.isArchived()).toBe(false)
+ expect((await db.swarmGroup.findUniqueOrThrow({ where: { id: f.review.id } })).data).toMatchObject({ assignment: { status: 'cancelled', result: 'Parser v2 was archived.' } })
+ })
+
+ it('the archive pass ends the deliveries of a step it archives, and tells a finished step\'s agent nothing', async () => {
+ const f = await waiting(true)
+ await verdict(f)
+ await f.execute({ type: 'message.send', conversationId: f.review.key, text: 'One more thing', replyTo: null, recipientIds: [f.reviewer] }, host, f.lead)
+ const left = await db.superTabMessage.findFirstOrThrow({ where: { tabId: f.tab, conversationId: f.review.key, text: 'One more thing' } })
+ expect((await db.superTabDelivery.findMany({ where: { tabId: f.tab, messageId: left.id } })).map(d => d.status)).toEqual(['queued'])
+ await finishTask(f)
+ f.clock.now += 40 * MINUTE
+ await archiveFinishedGroups(db, f.timed, github({ [PR]: 'merged' }), f.clock.now)
+ expect(await f.isArchived()).toBe(true)
+ expect((await db.superTabDelivery.findMany({ where: { tabId: f.tab, messageId: left.id } })).map(d => d.status)).toEqual(['cancelled'])
+ expect((await db.superTabMessage.findMany({ where: { tabId: f.tab, conversationId: f.review.key } })).filter(row => row.text.includes('was archived'))).toEqual([])
+ })
+
it('archives with its task once the task ends and its pull requests are merged, the task\'s pass closing it in the same write', async () => {
const f = await waiting()
await f.execute({ type: 'work.cancel', conversationId: f.reviewed, assignmentId: f.work, reason: 'Landed outside the Swarm' }, host, f.lead)
diff --git a/backend/integration/superTabs.test.ts b/backend/integration/superTabs.test.ts
index c2b296b44..aa86b401e 100644
--- a/backend/integration/superTabs.test.ts
+++ b/backend/integration/superTabs.test.ts
@@ -914,7 +914,8 @@ describe('since when a worker is down', () => {
await f.timed.stopped(host, f.tab, f.assignmentId, 'fixture-native-stop')
expect(await f.downSince(f.worker)).toBe(iso(stopped))
f.clock.now += 1_000
- await f.observe([f.leadHarness], [f.workerHarness])
+ // Its session is still not listed (a stopped list would remove the agent, superTabLiveness.test.ts).
+ await f.observe([f.leadHarness])
expect(await f.downSince(f.worker)).toBe(iso(stopped))
await f.observe([f.leadHarness, f.workerHarness])
expect(await f.downSince(f.worker)).toBeUndefined()
diff --git a/backend/src/superTabs/closedAgents.test.ts b/backend/src/superTabs/closedAgents.test.ts
new file mode 100644
index 000000000..6cee91179
--- /dev/null
+++ b/backend/src/superTabs/closedAgents.test.ts
@@ -0,0 +1,110 @@
+import { describe, expect, it } from 'vitest'
+import { applyCommand } from './commands.js'
+import { closedAgents, DOWN_REMOVE_MS, removeClosedAgents, STOPPED_REMOVE_MS } from './closedAgents.js'
+import { MACHINE_FRESH_MS } from './machines.js'
+import { createSuperTab, type Actor, type Agent, type SuperTabState } from './model.js'
+import { projectsOf } from './projects.js'
+
+const config = { engine: 'codex', model: 'm', effort: 'high', contextWindow: null, engineVersion: null }
+const person: Actor = { kind: 'person', userId: 'owner', email: '[email protected]' }
+const NOW = 10_000_000
+
+/** A Swarm with its coordinator and one worker on machine 'mac', whose last reading (fresh) listed `before` running. */
+function fixture(before: string[] = ['lead', 'other']) {
+ let state: SuperTabState = createSuperTab('tab', 'Work', { id: 'owner', email: '[email protected]' }, 'prod')
+ const add = (harnessId: string, lead: boolean) => {
+ state = applyCommand(state, person, { type: 'agent.add', conversationId: 'lead', machineId: 'mac', harnessId, name: harnessId, lead, configuration: config },
+ { now: 1, operationId: `add-${harnessId}`, contribution: { machineOwnerId: 'owner', contributorId: 'owner' } }).state
+ return state.agents.find(a => a.harnessId === harnessId)!
+ }
+ const lead = add('lead', true)
+ const worker = add('worker', false)
+ state.machines = [{ machineId: 'mac', name: 'Mac', cwd: '/r', engines: ['codex'], maxAgents: 4, contributorId: 'owner', membershipGeneration: 'g', generation: 'g1', paused: false,
+ observation: { runningHarnessIds: before, stoppedHarnessIds: [], receivedAt: NOW - 5_000 } } as unknown as NonNullable<SuperTabState['machines']>[number]]
+ worker.downSince = new Date(NOW - 2 * STOPPED_REMOVE_MS).toISOString()
+ const report = (running: string[], stopped: string[] = []) => ({ runningHarnessIds: running, stoppedHarnessIds: stopped, stoppedReservations: [] })
+ return { state, lead, worker, report }
+}
+const ids = (agents: Agent[]) => agents.map(a => a.harnessId)
+
+describe('closedAgents: which agents a report shows closed', () => {
+ it('takes an agent listed stopped, down long enough, after a fresh reading that did not list it running', () => {
+ const f = fixture()
+ expect(ids(closedAgents(f.state, 'mac', f.report(['lead'], ['worker']), NOW))).toEqual(['worker'])
+ })
+ it('takes nobody on the first report after a silence', () => {
+ const f = fixture()
+ f.state.machines![0]!.observation!.receivedAt = NOW - MACHINE_FRESH_MS - 1
+ expect(closedAgents(f.state, 'mac', f.report(['lead'], ['worker']), NOW)).toEqual([])
+ })
+ it('waits STOPPED_REMOVE_MS since it went down, so a host mid-restart or a Change agent in progress is not cut off', () => {
+ const f = fixture()
+ f.worker.downSince = new Date(NOW - STOPPED_REMOVE_MS + 1).toISOString()
+ expect(closedAgents(f.state, 'mac', f.report(['lead'], ['worker']), NOW)).toEqual([])
+ delete f.worker.downSince
+ expect(closedAgents(f.state, 'mac', f.report(['lead'], ['worker']), NOW)).toEqual([])
+ })
+ it('takes none that the last reading listed running: a session back from a restart starts its wait again', () => {
+ const f = fixture(['lead', 'worker'])
+ expect(closedAgents(f.state, 'mac', f.report(['lead'], ['worker']), NOW)).toEqual([])
+ })
+ it('leaves an agent whose stop was asked for to its host, which closes it', () => {
+ const f = fixture()
+ f.worker.workDecision = 'stop'
+ expect(closedAgents(f.state, 'mac', f.report(['lead'], ['worker']), NOW)).toEqual([])
+ f.worker.workDecision = 'keep'
+ expect(closedAgents(f.state, 'mac', f.report(['lead'], ['worker']), NOW)).toEqual([])
+ })
+ it('takes an agent not listed at all only after DOWN_REMOVE_MS, and never when the report lists nothing running', () => {
+ const f = fixture()
+ f.worker.downSince = new Date(NOW - DOWN_REMOVE_MS + 1).toISOString()
+ expect(closedAgents(f.state, 'mac', f.report(['lead']), NOW)).toEqual([])
+ f.worker.downSince = new Date(NOW - DOWN_REMOVE_MS).toISOString()
+ expect(ids(closedAgents(f.state, 'mac', f.report(['lead']), NOW))).toEqual(['worker'])
+ // A fault in the host's listing would empty a whole machine: not this way.
+ expect(closedAgents(f.state, 'mac', f.report([]), NOW)).toEqual([])
+ f.state.machines![0]!.observation!.runningHarnessIds = []
+ expect(closedAgents(f.state, 'mac', f.report(['lead']), NOW)).toEqual([])
+ })
+ it('never takes a coordinator', () => {
+ const f = fixture()
+ f.lead.downSince = f.worker.downSince
+ expect(projectsOf(f.state).some(p => p.leadConversationId === 'lead')).toBe(true)
+ expect(ids(closedAgents(f.state, 'mac', f.report([], ['lead', 'worker']), NOW))).toEqual(['worker'])
+ })
+})
+
+describe('removeClosedAgents: what a removal leaves for the host', () => {
+ it('writes the close record a removal by command writes, so the host closes the session and frees its slot', () => {
+ const f = fixture()
+ expect(ids(removeClosedAgents(f.state, [f.worker], NOW))).toEqual(['worker'])
+ expect(f.state.closingSessions).toEqual([{ agentId: f.worker.id, machineId: 'mac', harnessId: 'worker', machineOwnerId: 'owner' }])
+ expect(f.state.agents.map(a => a.id)).toEqual([f.lead.id])
+ expect(f.state.conversations.every(c => !c.agentIds.includes(f.worker.id))).toBe(true)
+ })
+ it('frees the slot of its reservation once the host confirms the close', () => {
+ const f = fixture()
+ f.state.harnessReservations = [{ machineId: 'mac', harnessId: 'worker', generation: 'r1', operationId: 'reserve' } as never]
+ removeClosedAgents(f.state, [f.worker], NOW)
+ expect(f.state.harnessReservations).toHaveLength(1)
+ const closed = applyCommand(f.state, { kind: 'person', userId: 'owner', email: '[email protected]' }, { type: 'agent.sessionClosed', agentId: f.worker.id, harnessId: 'worker' } as never, { now: NOW, operationId: 'closed' })
+ expect(closed.state.closingSessions).toBeUndefined()
+ expect(closed.state.harnessReservations).toEqual([])
+ expect(closed.state.releasedHarnesses).toEqual([{ machineId: 'mac', harnessId: 'worker' }])
+ })
+ it('holds a Team account for the project of a confidential session until its host confirms the data deleted', () => {
+ const f = fixture()
+ f.worker.confidential = true
+ f.worker.teamAccount = true
+ removeClosedAgents(f.state, [f.worker], NOW)
+ expect(f.state.closingSessions).toEqual([expect.objectContaining({ agentId: f.worker.id, heldFor: expect.any(String), since: NOW })])
+ })
+ it('keeps an agent that holds a task, active or just lost', () => {
+ const f = fixture()
+ const group = f.state.conversations.find(c => c.id === 'lead')!
+ group.assignment = { id: 'work', agentId: f.worker.id, status: 'lost', configuration: config,
+ execution: { machineId: 'mac', machineOwnerId: 'owner', harnessId: 'worker' }, result: null } as never
+ expect(removeClosedAgents(f.state, [f.worker], NOW)).toEqual([])
+ expect(f.state.closingSessions).toBeUndefined()
+ })
+})
diff --git a/backend/src/superTabs/closedAgents.ts b/backend/src/superTabs/closedAgents.ts
new file mode 100644
index 000000000..737f0f697
--- /dev/null
+++ b/backend/src/superTabs/closedAgents.ts
@@ -0,0 +1,87 @@
+import { isBuddy } from './buddies.js'
+import { MACHINE_FRESH_MS, type MachineObservation } from './machines.js'
+import { activeWork, type Agent, type SuperTabState } from './model.js'
+import { agentProjectId, isConfidential, ledProject, onTeamAccount } from './projects.js'
+
+// Huy, 2026-11-02: four agents closed on their machine sat under Idle for hours, each in the machine's stopped list, because
+// only an agent's own host removed it, and only after a stop was asked for. A session closed by hand never asked. Now the
+// report that shows a session gone removes its agent (docs/plans/2026-11-02-closed-agents-leave-list-plan.md).
+
+/** How long an agent not listed running stays before its machine, still reporting, removes it without a stopped list. */
+export const DOWN_REMOVE_MS = 15 * 60_000
+/** How long an agent whose session is listed stopped stays first: a host mid-restart, or an agent changing its session, lists
+ * one stopped for a moment before it is back (security reviews of #2569). */
+export const STOPPED_REMOVE_MS = 30_000
+
+/** Whether [target] could ever leave this way: not a coordinator, a Buddy, one kept or being stopped. */
+const removable = (state: SuperTabState, target: Agent): boolean =>
+ !isBuddy(target) && target.workDecision !== 'keep' && target.workDecision !== 'stop' && !ledProject(state, target.id)
+
+/**
+ * The agents of [machineId] that [report], arriving now over the reading in [state], shows closed: not listed running, down
+ * for a while, and either proved stopped (the proof the slot count accepts, machines.ts machineSlots; STOPPED_REMOVE_MS) or
+ * not listed for DOWN_REMOVE_MS while the machine's other sessions still run. The last reading must be fresh and not list
+ * them running either, so one report after a silence never removes anyone, and a report whose running list is empty never
+ * removes by time (a fault in the host's listing would empty a whole machine). Never a coordinator (a project's end is the
+ * only removal that takes one), a Buddy (its owner stops it), an agent someone chose to keep: it stays, shown as closed, or
+ * one being stopped: its host closes it and takes it out (commands.ts agent.remove). Whether a task is still held is judged by
+ * removeClosedAgents, after the loss of tasks.
+ */
+export function closedAgents(state: SuperTabState, machineId: string, report: Pick<MachineObservation, 'runningHarnessIds' | 'stoppedHarnessIds' | 'stoppedReservations'>, now: number): Agent[] {
+ const previous = state.machines?.find(m => m.machineId === machineId)?.observation
+ const fresh = previous && now - previous.receivedAt <= MACHINE_FRESH_MS ? previous : undefined
+ if (!fresh) return []
+ return state.agents.filter(target => {
+ if (target.machineId !== machineId || report.runningHarnessIds.includes(target.harnessId) || fresh.runningHarnessIds.includes(target.harnessId)) return false
+ if (!removable(state, target)) return false
+ if (!target.downSince) return false
+ const down = now - Date.parse(target.downSince)
+ if (report.stoppedHarnessIds.includes(target.harnessId)) {
+ const reservation = state.harnessReservations?.find(r => r.machineId === machineId && r.harnessId === target.harnessId)
+ // Older hosts can prove a first launch stopped, but cannot tell a resumed runtime from its predecessor.
+ return down >= STOPPED_REMOVE_MS
+ && (!reservation || !reservation.renewed || !!report.stoppedReservations?.some(r => r.harnessId === target.harnessId && r.generation === reservation.generation))
+ }
+ return down >= DOWN_REMOVE_MS && report.runningHarnessIds.length > 0 && fresh.runningHarnessIds.length > 0
+ })
+}
+
+/** The record that its host closes the session of a removed agent: a confidential session in a Team account keeps the account
+ * for its project until the host confirms the close, which it does once the session's data there is deleted (security re-check
+ * 2 of #2089). The close also frees the session's slot (commands.ts agent.sessionClosed). Written before the agent leaves its
+ * groups, which decide whether the session is confidential. */
+export function recordClosing(state: SuperTabState, target: Agent, now: number): void {
+ if (state.closingSessions?.some(c => c.agentId === target.id && c.harnessId === target.harnessId)) return
+ const held = onTeamAccount(state, target) && isConfidential(state, target) ? { heldFor: agentProjectId(state, target), since: now } : {}
+ // Its machine part outlives the Buddy-only record while this closes: it stays as private as the record (read/changes.ts).
+ const hidden = state.machines?.some(m => m.machineId === target.machineId && m.buddyOnly) ? { buddyOnly: true as const } : {}
+ ;(state.closingSessions ??= []).push({ agentId: target.id, machineId: target.machineId, harnessId: target.harnessId, machineOwnerId: target.machineOwnerId, ...held, ...hidden })
+}
+
+/** Removes those of [closed] that hold no task now: from the agents and from every group's members and leads, as commands.ts
+ * removeAgent does, with the close order its host needs. A task just lost keeps its agent until its Lead hands it on or
+ * cancels it (it is still fenced and told by name, liveness.ts); the next report removes the agent then. The removed agents,
+ * for the caller to cancel what waits for them. */
+export function removeClosedAgents(state: SuperTabState, closed: Agent[], now: number): Agent[] {
+ const holding = new Set(state.conversations.filter(group => activeWork(group) || group.assignment?.status === 'lost').map(group => group.assignment!.agentId))
+ const removed = closed.filter(target => !holding.has(target.id))
+ if (!removed.length) return []
+ for (const target of removed) recordClosing(state, target, now)
+ const gone = new Set(removed.map(target => target.id))
+ state.agents = state.agents.filter(target => !gone.has(target.id))
+ for (const group of state.conversations) {
+ group.agentIds = group.agentIds.filter(id => !gone.has(id))
+ if (group.leadId && gone.has(group.leadId)) group.leadId = null
+ }
+ return removed
+}
+
+/** The next time a report of [machineId] could remove an agent, after those it just judged: its reports skip the full load
+ * until then (machineReports.ts), so a stopped list that stays the same still removes its agent when its wait ends. */
+export function nextRemovalAt(state: SuperTabState, machineId: string, now: number): number | undefined {
+ const stopped = state.machines?.find(m => m.machineId === machineId)?.observation?.stoppedHarnessIds ?? []
+ const ends = state.agents.filter(a => a.machineId === machineId && a.downSince && removable(state, a))
+ .map(a => Date.parse(a.downSince!) + (stopped.includes(a.harnessId) ? STOPPED_REMOVE_MS : DOWN_REMOVE_MS))
+ .filter(end => end > now)
+ return ends.length ? Math.min(...ends) : undefined
+}
diff --git a/backend/src/superTabs/commands.ts b/backend/src/superTabs/commands.ts
index 38a41fb38..1fe76348c 100644
--- a/backend/src/superTabs/commands.ts
+++ b/backend/src/superTabs/commands.ts
@@ -11,7 +11,7 @@ import {
type Actor, type AgentConfiguration, type AgentStart, type AgentStartRequest, type BuddySessionEntry, type WorkTask, type Agent, type Author, type Check, type CommandEffects, type Conversation, type SuperTabState,
} from './model.js'
import { jobKindOf } from './evidence/jobKind.js'
-import { endSteps, holdsStepOf, isStep, ownerOf, taskOwner } from './steps.js'
+import { endSteps, stepEndedRows, holdsStepOf, isStep, ownerOf, taskOwner } from './steps.js'
import { routeRecordSchema, routeTitle, startedAs, type RouteCandidate, type RouteDecision, type RouteFinal, type RouteOverride } from './routeRecord.js'
import { routingOverrideSaveSchema } from './routingPolicy.js'
import { askedInSchema, RULE_MESSAGE_MS, ruleSchema, ruleTextSchema } from './rules.js'
@@ -38,7 +38,8 @@ import { assignedNotice, tellBuddies } from './buddyNews.js'
import { bindPullRequestCards, bindTaskCard, pullRequestCard, recordCardMerged } from './cards.js'
import { avatarChoice, setAgentAvatar, setMemberAvatar, setStatus, statusSchema, type AvatarUpload } from './profile.js'
import { switchExpired } from './tidy.js'
-import { BUILT_IN_ROLE_DEFAULTS, agentProjectId, audienceOf, canReadProject, deleteProject, isConfidential, markConfidential, onTeamAccount, requireSingleRegistration, groupProject, inviteLanding, ledProject, manageProject, MAX_ROLES, mutableProjects, placeRules, projectAgent, projectMembers, projectOf, projectsOf, readAgent, readConversation, readProject, requestedByLine, sameProject, sharedWithLeads, withRoleDefaults, type SwarmProject, PROJECT_STATUS_MAX } from './projects.js'
+import { BUILT_IN_ROLE_DEFAULTS, agentProjectId, audienceOf, canReadProject, deleteProject, markConfidential, onTeamAccount, requireSingleRegistration, groupProject, inviteLanding, ledProject, manageProject, MAX_ROLES, mutableProjects, placeRules, projectAgent, projectMembers, projectOf, projectsOf, readAgent, readConversation, readProject, requestedByLine, sameProject, sharedWithLeads, withRoleDefaults, type SwarmProject, PROJECT_STATUS_MAX } from './projects.js'
+import { recordClosing } from './closedAgents.js'
import { BUDDY_SESSION_CAPABILITY, chatOwner, endSessionEntry, entryProject, liveSessions, mainBuddyOf, MAX_SESSION_WAITING, requireChatOwner, SESSION_ENDED_KIND, sessionAgentsOf, sessionOf, setSessions, type SessionEndReason } from './buddySessions.js'
import { BUDDY_REQUIREMENTS, buddyChatId, buddyReady, chosenBuddyName, isBuddy, isBuddyChat, isSwarmBuddy, isSwarmBuddyChat, MAX_PROPOSAL_ASKS, MAX_PROPOSAL_ATTACHMENTS, openBuddyChat, openSwarmBuddyChat, PM_LINE_KIND, PROPOSAL_ASK_MS, PROPOSAL_SENT_KIND, proposalSentText, proposalText, renameBuddy, requireBuddyCommand, swarmBuddyChatId } from './buddies.js'
import { BUDDY_OWN_MACHINE_REFUSAL, CODEX_BUDDY_REFUSAL } from './buddyContract.js'
@@ -903,10 +904,7 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
* [archive], its finished steps archive with it. */
const endStepsOf = (task: Conversation, reason: string, archive: boolean) => {
// A row of its own in each step, as the command's own row may be in the task: one id per row.
- for (const step of endSteps(state, task, reason, archive)) {
- effects.messages.push({ id: stableId(operationId, 'step-ended', step.id), conversationId: step.id, author: sender, text: reason,
- replyTo: null, recipients: [step.assignment!.agentId], source: SYSTEM_ROW })
- }
+ effects.messages.push(...stepEndedRows(state, endSteps(state, task, reason, archive), reason, sender, step => stableId(operationId, 'step-ended', step.id)))
}
/** Agent bookkeeping, a routing line or an agent joined or ready: no one's in the project chat, which carries only what
* people read or decide on (the Lead's ruling, 2026-10-29); a task's chat keeps it as its record. */
@@ -1235,15 +1233,7 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
}
}
if (!lead) protectLead(state, target.id)
- if (close && !state.closingSessions?.some(c => c.agentId === target.id && c.harnessId === target.harnessId)) {
- // A confidential session in a Team account keeps the account for its project until its host confirms the close, which
- // it does once the session's data there is deleted (security re-check 2 of #2089).
- const held = onTeamAccount(state, target) && isConfidential(state, target) ? { heldFor: agentProjectId(state, target), since: context.now } : {}
- // Its machine part outlives the Buddy-only record while this closes: it stays as private as the record (read/changes.ts).
- const hidden = state.machines?.some(m => m.machineId === target.machineId && m.buddyOnly) ? { buddyOnly: true as const } : {}
- ;(state.closingSessions ??= []).push({ agentId: target.id, machineId: target.machineId, harnessId: target.harnessId, machineOwnerId: target.machineOwnerId,
- ...held, ...hidden })
- }
+ if (close) recordClosing(state, target, context.now)
state.agents = state.agents.filter(a => a.id !== target.id)
effects.cancelledAgents.push(target.id)
for (const group of state.conversations) {
diff --git a/backend/src/superTabs/steps.test.ts b/backend/src/superTabs/steps.test.ts
index 28c244123..9a7154d1e 100644
--- a/backend/src/superTabs/steps.test.ts
+++ b/backend/src/superTabs/steps.test.ts
@@ -5,9 +5,9 @@
*/
import { describe, expect, it } from 'vitest'
import { applyCommand, type Command, type CommandContext } from './commands.js'
-import { createSuperTab, type Actor, type AgentConfiguration } from './model.js'
+import { agent, createSuperTab, type Actor, type AgentConfiguration } from './model.js'
import { extracted } from './parts/write.js'
-import { stepSleeps } from './steps.js'
+import { stepEndedRows, stepSleeps } from './steps.js'
import { reportedAs } from './projectUpdates.js'
import { idleNotices } from './tidy.js'
@@ -354,3 +354,39 @@ describe('the PM is not told what a step\'s agent says to its task', () => {
expect(notices).not.toContain(rev)
})
})
+
+// The archive pass writes these with no command behind it, so they must never stop it: a delivery to an agent that has left throws.
+describe("the row a step's ended work leaves", () => {
+ const state = { people: [{ id: 'owner', generation: 'g' }, { id: 'rejoined', generation: 'new' }], agents: [
+ { id: 'kept', name: 'Reviewer', contributorId: 'owner', membershipGeneration: 'g' },
+ // agent() throws for both of these, as writeMessages calls it for each recipient (review 2 of #2596).
+ { id: 'orphaned', name: 'Reviewer', contributorId: 'left', membershipGeneration: 'g' },
+ { id: 'stale', name: 'Reviewer', contributorId: 'rejoined', membershipGeneration: 'old' },
+ ] } as never
+ const step = (agentId: string) => ({ id: `step-${agentId}`, assignment: { agentId } }) as never
+ const lead = { kind: 'agent', id: 'lead', name: 'Lead', membershipGeneration: 'g' } as const
+
+ it("goes to the step's agent, in that step, as the author given", () => {
+ expect(stepEndedRows(state, [step('kept')], 'Fix was archived.', lead, s => `row-${s.id}`)).toEqual([expect.objectContaining({
+ id: 'row-step-kept', conversationId: 'step-kept', author: lead, text: 'Fix was archived.', recipients: ['kept'], source: { kind: 'system' } })])
+ })
+
+ it('goes to nobody when its agent has left the Swarm', () => {
+ expect(stepEndedRows(state, [step('gone')], 'Fix was archived.', lead, s => s.id)[0]!.recipients).toEqual([])
+ })
+
+ it('goes to nobody, and never throws at its delivery, when its agent\'s contributor is gone or has another generation', () => {
+ for (const id of ['orphaned', 'stale']) {
+ const [row] = stepEndedRows(state, [step(id)], 'Fix was archived.', lead, s => s.id)
+ expect(row!.recipients).toEqual([])
+ expect(() => { for (const recipient of row!.recipients) agent(state, recipient) }).not.toThrow()
+ expect(stepEndedRows(state, [step(id)], 'Fix was archived.', null, s => s.id)).toEqual([])
+ }
+ expect(() => agent(state, 'orphaned')).toThrow()
+ })
+
+ it('is written as the agent told when there is no Lead, and not at all when there is nobody to write it', () => {
+ expect(stepEndedRows(state, [step('kept')], 'Fix was archived.', null, s => s.id)[0]!.author).toMatchObject({ kind: 'agent', id: 'kept' })
+ expect(stepEndedRows(state, [step('gone')], 'Fix was archived.', null, s => s.id)).toEqual([])
+ })
+})
diff --git a/backend/src/superTabs/steps.ts b/backend/src/superTabs/steps.ts
index 37f34f8cf..90dbdfa34 100644
--- a/backend/src/superTabs/steps.ts
+++ b/backend/src/superTabs/steps.ts
@@ -3,7 +3,8 @@
* task) with a name the project's instructions give: it keeps its own assignment, lease, attempts and costs, and readers
* show it inside its task. Nothing here reads a step's name: which steps a task has is the instructions' to say.
*/
-import { activeWork, finishWorker, type Conversation, type SuperTabState } from './model.js'
+import { agentDisplayName } from './agentNames.js'
+import { activeWork, finishWorker, type Author, type Conversation, type MessageDraft, type SuperTabState } from './model.js'
/** Whether [group] is a step of a task: any linked group, named or not. Ken, 2026-11-02: a PM that opened "Test: PR #2514"
* the old way, a minute after saving the steps workflow, still heard every Tester post; what reaches the PM must not rest on
@@ -40,6 +41,19 @@ export function endSteps(state: SuperTabState, task: Conversation, reason: strin
return cancelled
}
+/** The row each step endSteps cancelled keeps, in that step, for the agent whose work ended: [reason], as [author], or as that
+ * agent where none is given (a project with no Lead). One whose agent or its contributor has left the Swarm reaches nobody: a delivery to it would
+ * throw, and the archive pass that wrote it could then never archive its task. With no author either, there is no row. */
+export function stepEndedRows(state: SuperTabState, cancelled: Conversation[], reason: string, author: Author | null, id: (step: Conversation) => string): MessageDraft[] {
+ return cancelled.flatMap(step => {
+ // agent()'s own rule, without its throw: its contributor still here, at the generation it was shared under.
+ const found = state.agents.find(a => a.id === step.assignment!.agentId)
+ const agent = found && state.people.find(p => p.id === found.contributorId)?.generation === found.membershipGeneration ? found : undefined
+ const by: Author | null = author ?? (agent ? { kind: 'agent', id: agent.id, name: agent.name, displayName: agentDisplayName(state.agents, agent.id), membershipGeneration: agent.membershipGeneration } : null)
+ return by ? [{ id: id(step), conversationId: step.id, author: by, text: reason, replyTo: null, recipients: agent ? [agent.id] : [], source: { kind: 'system' } }] : []
+ })
+}
+
/** Whether a step may sleep, given its task's row as the sweep read it (null: gone). A step sleeps once its task is
* archived, never on its own clock nor with a task that is only dormant: a dormant step drops out of the Swarm read with
* its verdict, and one asleep under a done task was not loaded when that task was archived later, so it stayed open in an
diff --git a/backend/src/superTabs/store.ts b/backend/src/superTabs/store.ts
index 04be6d33b..037626197 100644
--- a/backend/src/superTabs/store.ts
+++ b/backend/src/superTabs/store.ts
@@ -43,14 +43,15 @@ import { confidentialSessions, otherRegistrations, recordConfidential } from './
import { answersRequest, dirtyGroups, noteWorkChanges, projectUpdateRequest, UNANSWERED_REQUEST_MS } from './projectUpdates.js'
import { cloneData } from './cloneData.js'
import { digestDue, digestMessageId, digestOf, digestRequest, digestSince } from './digest.js'
+import { closedAgents, nextRemovalAt, removeClosedAgents } from './closedAgents.js'
import { judgedMachines, loseTasks, nextLossAt, sweepForLead, sweepLiveness, SWEEP_EVERY_MS, unpurgedNotice } from './liveness.js'
import { archivable, archiveLine, idleNotices, reviewClosable, reviewCloseLine, reviewPullRequests } from './tidy.js'
-import { clock, insertParts, loadActive, loadLightGroups, loadMachineParts, loadObserved, reassemble, split, type GroupData, type HeadData, type MachineData, type Part, type SwarmParts } from './parts/index.js'
+import { clock, insertParts, loadActive, loadGroups, loadLightGroups, loadMachineParts, loadObserved, reassemble, split, type GroupData, type HeadData, type MachineData, type Part, type SwarmParts } from './parts/index.js'
import { groupsBy, listingDrops, quietSince, readBy, withoutHints } from './parts/indexed.js'
import { memberSwarms } from './swarmRows.js'
import { commitParts, indexesOf, numberMessages, type Touch, type Written } from './parts/commit.js'
import { loadDeliveryParts, ms } from './parts/light.js'
-import { endSteps } from './steps.js'
+import { endSteps, stepEndedRows, stepsOf } from './steps.js'
import { guardedWrite, partId } from './parts/write.js'
import { retryable } from './retry.js'
import { touchesFor } from './parts/touches.js'
@@ -2922,7 +2923,16 @@ export class SuperTabStore {
const before = (await readStamps([tabId]))?.get(tabId)?.main
const { version, record } = await transaction(this.db, async (tx): Promise<{ version: number; record?: Omit<ReportRecord, 'stamp'> }> => {
// Only the conversations its checks read (parts/load.ts loadObserved): the whole Swarm was ~1.1 MB a report (#876).
- const loaded = loadedFrom(await this.row(tx, user, tabId), await loadObserved(tx, tabId, machineId)), state = cloneData(loaded.state)
+ const row = await this.row(tx, user, tabId)
+ const observed = await loadObserved(tx, tabId, machineId)
+ let loaded = loadedFrom(row, observed)
+ // Agents this reading shows closed leave with their groups' membership, so every group they are in is read, quiet ones too.
+ const closed = closedAgents(loaded.state, machineId, observation, this.now()).map(a => a.id)
+ if (closed.length) {
+ const more = await loadGroups(tx, tabId, 'agents', { agentIds: { $in: closed } })
+ loaded = loadedFrom(row, { ...observed, groups: [...new Map([...observed.groups, ...more].map(g => [g.key, g])).values()] })
+ }
+ const state = cloneData(loaded.state)
await this.hostFor(tx, user, machineId, owned, state)
const pool = await strangerRefusal(state, user.sub, () => {
const found = machineContribution(state, machineId)
@@ -2936,7 +2946,7 @@ export class SuperTabStore {
// A machine that went silent while cleaning takes the fallback before this fresh reading can bring it back: its records
// go, its cleanup waits for this host, as the next sweep would have done (machines.ts expireRemovals).
const ended = expireRemovals(state, now)
- const stamp = clock.next()
+ const stamp = clock.next(), removedIds: string[] = []
// A reading writes only its machine's part, and an agent's part only when its presence changes (spec); a group's only
// when a task there is lost or a removal ends.
const saved = async (lost: MessageDraft[] = []) => {
@@ -2948,6 +2958,18 @@ export class SuperTabStore {
await recordEvidence(tx, tabId, loaded.state, state, now)
const version = (await this.save(tx, loaded, state, stamp, touches)).versions.get(`machine:${machineId}`) ?? 0
await this.writeMessages(tx, tabId, state, rows, sequences, true)
+ // Nothing more is delivered to an agent that left, whatever was written for it just now, and no terminal opened on its old
+ // session stays valid (as a removal by command does). One plain match each: an `in` here is sent as $expr (hotFilters).
+ for (const agentId of removedIds) {
+ for (const status of ['queued', 'claimed', 'uncertain']) {
+ await tx.superTabDelivery.updateMany({ where: { tabId, agentId, status }, data: { status: 'cancelled', holdReason: null, holdSince: null } })
+ }
+ }
+ if (removedIds.length) {
+ const watchersLost = await revokeNativeContexts(tx, loaded.state, state)
+ const told = this.hooks.accessChanged
+ if (told && watchersLost.length) afterCommit(tx, () => told(tabId))
+ }
return { version }
}
if (!state.machines?.includes(pool)) return saved()
@@ -2973,12 +2995,14 @@ export class SuperTabStore {
// Its own agents lose their tasks at once (a stopped session); every 30 seconds it runs the Swarm's time checks too, so
// they keep running when the Lead's own machine is the one that died.
const checked = [...loseTasks(state, now, worker => worker.machineId === machineId), ...sweep ? sweepLiveness(state, now) : []]
+ // Then the agents it shows closed leave, those with no active work left: the Lead is told of their tasks above (closedAgents.ts).
+ removedIds.push(...removeClosedAgents(state, state.agents.filter(a => closed.includes(a.id)), now).map(a => a.id))
const written = await saved(checked)
// What the next reports of this machine need to skip the load, as this commit leaves the Swarm.
const mine = state.machines?.find(m => m.machineId === machineId)
return { ...written, ...mine ? { record: { lentCount: lentAgents(state, mine, mine.observation?.runningHarnessIds ?? []),
lentProjects: lentProjects(state, mine, mine.observation?.runningHarnessIds ?? []),
- removals: !!state.machines?.some(m => m.removal), deadline: Math.min(nextLossAt(state, machineId) ?? Infinity, now + DEADLINE_CAP_MS),
+ removals: !!state.machines?.some(m => m.removal), deadline: Math.min(nextLossAt(state, machineId) ?? Infinity, nextRemovalAt(state, machineId, now) ?? Infinity, now + DEADLINE_CAP_MS),
team: teamByRecord(state, machineId), members: state.people.map(p => p.id),
preparable: (state.starts ?? []).filter(s => preparableStart(s, machineId)).map(s => s.id), at: now } } : {} }
})
@@ -3570,13 +3594,20 @@ export class SuperTabStore {
group.archived = true
// Its steps archive with it (task steps design): its work is done or cancelled and its pull requests settled, so a
// step still open there has nothing left to check.
- endSteps(state, group, `${group.title} was archived.`, true)
- const line = finished ? archiveLine(state, group, now) : reviewCloseLine(state, group, checked, now), rows = line ? [line] : []
+ const reason = `${group.title} was archived.`, heldBefore = new Set(stepsOf(state, group.id).filter(step => step.archived).map(step => step.id))
+ const cancelled = endSteps(state, group, reason, true)
+ const line = finished ? archiveLine(state, group, now) : reviewCloseLine(state, group, checked, now)
+ // A step this pass cancelled hears why, as when a command ends it (commands.ts endStepsOf): its later verdict is refused.
+ const rows = [...line ? [line] : [], ...stepEndedRows(state, cancelled, reason, line?.author ?? null, step => stableId('auto-archive-step', step.id, String(now)))]
const sequences = numberMessages(state, rows, now)
if (!dirtyGroups(state, groupProject(state, group)).includes(group)) group.dormant = true
// As a person's archive does (execute): a claim of a delivery here conflicts with this write.
- await tx.superTabDelivery.updateMany({ where: { tabId, conversationId: groupId, status: { in: [...CANCELLABLE_DELIVERY] } },
- data: { status: 'cancelled', holdReason: null, holdSince: null } })
+ // Its finished steps archive here too (execute does the same): a cancelled one stays open, to hear why. One plain match per
+ // conversation: an `in` on this hot collection is sent as $expr, which no index bounds (hotFilters).
+ for (const conversationId of [groupId, ...stepsOf(state, group.id).filter(step => step.archived && !heldBefore.has(step.id)).map(step => step.id)]) {
+ await tx.superTabDelivery.updateMany({ where: { tabId, conversationId, status: { in: [...CANCELLABLE_DELIVERY] } },
+ data: { status: 'cancelled', holdReason: null, holdSince: null } })
+ }
// A review's close also writes the work it reviews (review of #2322): a Ready for review committed since the load linked
// a new pull request and saw this review still open, so it opened none. The touch makes one of the two writes retry,
// and the retry sees the other: this one declines (a pull request not read), or that one opens a new review.
diff --git a/cli/src/core/agents/create.spec.ts b/cli/src/core/agents/create.spec.ts
index 9ae3a1cd9..07a227b67 100644
--- a/cli/src/core/agents/create.spec.ts
+++ b/cli/src/core/agents/create.spec.ts
@@ -589,6 +589,14 @@ describe('creating an agent', () => {
expect(await setup().create(request({ engine: 'claude', claudeHome: '/profiles/claude-work' }))).toMatchObject({ ok: true })
})
+ it('says what went wrong when that failure is not an Error, and still launches', async () => {
+ syncProfileHome.mockImplementationOnce(() => { throw 'plain reason' })
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
+ expect(await setup().create(request({ engine: 'claude', claudeHome: '/profiles/claude-work' }))).toMatchObject({ ok: true })
+ expect(warn).toHaveBeenCalledWith(expect.stringContaining('connections for /profiles/claude-work · plain reason'))
+ warn.mockRestore()
+ })
+
it('reaches the existing first-install pane route when OpenCode is absent', async () => {
vi.mocked(opencodeMajorVersion).mockResolvedValueOnce(null)
const { create } = setup({ installOpencodePlugin })
diff --git a/cli/src/services/connectors.spec.ts b/cli/src/services/connectors.spec.ts
index 2beeae8ff..40d030752 100644
--- a/cli/src/services/connectors.spec.ts
+++ b/cli/src/services/connectors.spec.ts
@@ -1,7 +1,8 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
-import { bridgePort, saveBridgePort } from '../lib/connectors/agents.js'
-import { mkdtempSync, rmSync } from 'node:fs'
-import { createServer } from 'node:net'
+import { bridgeKey, bridgePort, bridgeSocketPath, saveBridgePort } from '../lib/connectors/agents.js'
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from 'node:fs'
+import { request as httpRequest } from 'node:http'
+import { connect, createServer } from 'node:net'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { fakeCore } from '../testing/fakeCore.js'
@@ -10,6 +11,13 @@ import { CONNECTORS_REQUESTS, startConnectors } from './connectors.js'
import { Store } from '../lib/connectors/store.js'
import * as gateway from '../lib/connectors/gateway.js'
import { FakeGateway } from '../testing/connectorServers.js'
+import { serveBridgeSocket } from '../lib/connectors/bridge.js'
+
+// The real socket, but for a failure with no Error to say why, which nothing here can provoke.
+vi.mock('../lib/connectors/bridge.js', async (original) => {
+ const real = await original<typeof import('../lib/connectors/bridge.js')>()
+ return { ...real, serveBridgeSocket: vi.fn(real.serveBridgeSocket) }
+})
const OWNER = { local: true, owner: true }
@@ -23,7 +31,15 @@ describe('the connectors service', () => {
// Signed out of Harness whatever this computer is: nothing here reaches the backend.
gateway.backend.signedIn = () => false
})
- afterEach(() => { gateway.backend.signedIn = signedIn; rmSync(home, { recursive: true, force: true }) })
+ afterEach(() => {
+ gateway.backend.signedIn = signedIn
+ vi.mocked(serveBridgeSocket).mockClear()
+ rmSync(home, { recursive: true, force: true })
+ for (const made of shortHomes.splice(0)) rmSync(made, { recursive: true, force: true })
+ })
+ // A socket's path has a limit, and an agent's temporary folder can be past it on its own. These tests need the socket.
+ const shortHomes: string[] = []
+ const shortHome = () => { const made = mkdtempSync('/tmp/hc-'); shortHomes.push(made); return made }
it('answers exactly the request it declares, and only for the owner', async () => {
const requests = startConnectors(fakeCore(), { env })
@@ -237,6 +253,129 @@ describe('the connectors service', () => {
}
})
+ // A vault folder and a home both too long for a socket, the one case left on TCP on a Mac or Linux, as every case is on Windows: the
+ // port is the only way in, so its keys stay as they are and neither is replaced or retired.
+ describe('where neither the vault\'s folder nor the home can hold a socket', () => {
+ beforeEach(() => { vi.stubEnv('HOME', `/${'h'.repeat(120)}`) })
+ afterEach(() => { vi.unstubAllEnvs() })
+
+ const freePort = async () => {
+ const server = createServer()
+ await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve))
+ const { port } = server.address() as { port: number }
+ await new Promise<void>(resolve => server.close(() => resolve()))
+ return port
+ }
+ const status = async (port: number, path: string) => {
+ for (let n = 0; n < 40; n++) {
+ const answer = await fetch(`http://127.0.0.1:${port}${path}`, { method: 'POST', body: '{}' }).then(reply => reply.status, () => 0)
+ if (answer) return answer
+ await new Promise(resolve => setTimeout(resolve, 25))
+ }
+ return 0
+ }
+ const body = (port: number, path: string) => fetch(`http://127.0.0.1:${port}${path}`, { method: 'POST', body: '{}' }).then(reply => reply.text())
+ const rawStatus = (port: number, path: string) => new Promise<number>((resolve, reject) => {
+ const sent = httpRequest({ host: '127.0.0.1', port, path, method: 'POST' }, (reply) => { reply.resume(); resolve(reply.statusCode ?? 0) })
+ sent.once('error', reject)
+ sent.end('{}')
+ })
+ const longVault = () => {
+ const vault = new Store(join(home, 'v'.repeat(120)), env)
+ expect(bridgeSocketPath(vault)).toBeNull()
+ return vault
+ }
+
+ it('answers both keys on the port, leaves them unchanged, and makes no socket', async () => {
+ const vault = longVault(), port = await freePort()
+ mkdirSync(vault.root, { recursive: true, mode: 0o700 })
+ writeFileSync(join(vault.root, 'harness-key.json'), JSON.stringify({ key: 'harness-key-placeholder' }), { mode: 0o600 })
+ const agentKey = bridgeKey(vault)
+ startConnectors(fakeCore(), { vault, env, port, offered: async () => ({}), retryMs: 20, vaultPort: null })
+ expect(vault.file('bridge.json').key).toBe(agentKey)
+ expect(vault.file('bridge.json').keyRetiresAt).toBeUndefined()
+ expect(vault.file('harness-key.json').key).toBe('harness-key-placeholder')
+ expect(existsSync(join(vault.root, 'bridge.sock'))).toBe(false)
+ expect(vi.mocked(serveBridgeSocket)).not.toHaveBeenCalled()
+ expect(await status(port, '/not-a-key/connections')).toBe(404)
+ expect(await status(port, '/harness-key-placeholder/connections')).toBe(200)
+ // The agents' key reaches a connection's MCP address, and the list stays Harness's alone.
+ expect(await status(port, `/${agentKey}/connections`)).toBe(404)
+ expect(await body(port, `/${agentKey}/linear/mcp`)).toContain('is not connected')
+ expect(await body(port, '/not-a-key/linear/mcp')).toContain('Unknown connection address')
+ })
+
+ it('with neither key on file, refuses everyone, an empty key included', async () => {
+ const vault = longVault(), port = await freePort()
+ const agentKey = bridgeKey(vault)
+ startConnectors(fakeCore(), { vault, env, port, offered: async () => ({}), retryMs: 20, vaultPort: null })
+ rmSync(join(vault.root, 'bridge.json'), { force: true })
+ rmSync(join(vault.root, 'harness-key.json'), { force: true })
+ expect(await status(port, '/x/connections')).toBe(404)
+ // A raw request, as fetch would normalize this path: the first segment is empty, and an empty key never matches a missing one.
+ expect(await rawStatus(port, '/.//connections')).toBe(404)
+ expect(await body(port, `/${agentKey}/linear/mcp`)).toContain('Unknown connection address')
+ })
+ })
+
+ // The store refuses a vault folder that has become a link: its keys cannot be read or replaced, and nobody gets in by that.
+ it('starts anyway when its folder cannot be trusted, says so, and refuses everyone on the port', async () => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
+ const short = shortHome()
+ const elsewhere = join(short, 'elsewhere'), root = join(short, 'link')
+ mkdirSync(elsewhere, { mode: 0o700 })
+ const behindLink = JSON.stringify({ key: 'k'.repeat(40) })
+ writeFileSync(join(elsewhere, 'bridge.json'), behindLink, { mode: 0o600 })
+ symlinkSync(elsewhere, root)
+ const server = createServer()
+ await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve))
+ const { port } = server.address() as { port: number }
+ await new Promise<void>(resolve => server.close(() => resolve()))
+ startConnectors(fakeCore(), { vault: new Store(root, env), env, port, offered: async () => ({}), retryMs: 20, vaultPort: null })
+ expect(warn).toHaveBeenCalledWith(expect.stringContaining('could not replace Harness\'s key'))
+ let answer = ''
+ for (let n = 0; n < 40 && !answer; n++) {
+ answer = await fetch(`http://127.0.0.1:${port}/${'k'.repeat(40)}/linear/mcp`, { method: 'POST', body: '{}' }).then(reply => reply.text(), () => '')
+ if (!answer) await new Promise(resolve => setTimeout(resolve, 25))
+ }
+ expect(answer).toContain('Unknown connection address')
+ expect(readFileSync(join(elsewhere, 'bridge.json'), 'utf8')).toBe(behindLink)
+ warn.mockRestore()
+ })
+
+ describe('while another listener holds the bridge\'s socket', () => {
+ it('says so once, keeps trying, and takes the socket when it is free', async () => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
+ const vault = new Store(join(shortHome(), 's'), env), path = join(vault.root, 'bridge.sock')
+ mkdirSync(vault.root, { recursive: true, mode: 0o700 })
+ const holder = createServer()
+ await new Promise<void>(resolve => holder.listen(path, resolve))
+ startConnectors(fakeCore(), { vault, env, port: 0, offered: async () => ({}), retryMs: 10, vaultPort: null })
+ const said = () => warn.mock.calls.filter(([line]) => String(line).includes('socket is not listening'))
+ await vi.waitFor(() => expect(vi.mocked(serveBridgeSocket).mock.calls.length).toBeGreaterThanOrEqual(3))
+ expect(said()).toHaveLength(1)
+ expect(String(said()[0][0])).toContain(path)
+ const calls = vi.mocked(serveBridgeSocket).mock.calls.length
+ await new Promise<void>(resolve => holder.close(() => resolve()))
+ await vi.waitFor(async () => {
+ expect(vi.mocked(serveBridgeSocket).mock.calls.length).toBeGreaterThan(calls)
+ await new Promise<void>((resolve, reject) => { const client = connect(path, () => { client.destroy(); resolve() }); client.once('error', reject) })
+ })
+ warn.mockRestore()
+ })
+
+ it('says what went wrong when the failure is not an Error', async () => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
+ vi.mocked(serveBridgeSocket).mockRejectedValueOnce('a plain reason')
+ const vault = new Store(join(shortHome(), 'p'), env), path = join(vault.root, 'bridge.sock')
+ startConnectors(fakeCore(), { vault, env, port: 0, offered: async () => ({}), retryMs: 10, vaultPort: null })
+ await vi.waitFor(() => expect(warn).toHaveBeenCalledWith(expect.stringContaining('a plain reason')))
+ // Its retry goes on and listens: waited for, or it would make the folder again after this test's cleanup.
+ await vi.waitFor(() => new Promise<void>((resolve, reject) => { const client = connect(path, () => { client.destroy(); resolve() }); client.once('error', reject) }))
+ warn.mockRestore()
+ })
+ })
+
it('waits for its port while another process holds it', async () => {
const holder = createServer()
await new Promise<void>(resolve => holder.listen(0, '127.0.0.1', resolve))
diff --git a/desktop/lib/super_tabs/agent_details.dart b/desktop/lib/super_tabs/agent_details.dart
index 7b3af133b..51c544f40 100644
--- a/desktop/lib/super_tabs/agent_details.dart
+++ b/desktop/lib/super_tabs/agent_details.dart
@@ -12,6 +12,7 @@ import '../state/app_state.dart';
import '../state/harness_activity.dart';
import '../widgets/desktop_chrome.dart';
import '../widgets/engine_identity.dart';
+import 'agent_line.dart';
import 'agent_mark.dart';
import 'controller.dart';
import 'identity.dart';
@@ -145,6 +146,9 @@ class SuperTabAgentInfo {
return 'Waiting for a person to answer';
}
if (activity == HarnessActivity.needsInput) return 'Needs input';
+ // Closed on its machine and kept by someone: the same word as its line and its group (agent_line.dart), also in the
+ // roster's hover, which adds the status when it differs from the line's.
+ if (agent.keptClosed && workStatus != 'lost') return 'Kept (closed)';
if (taskGroup case final group?) {
return switch (workStatus) {
'planned' => 'Assigned to "${group.title}"',
@@ -176,7 +180,15 @@ class SuperTabAgentInfo {
};
}
- String get tooltip => [
+ String get tooltip =>
+ // Closed on its machine and kept by someone: it reads as its line does (agent_line.dart), the mockup Huy approved.
+ agent.keptClosed &&
+ activity != HarnessActivity.offline &&
+ taskGroup?.assignment?['status'] != 'lost'
+ ? superTabAgentGlance(this).line
+ : _tooltip;
+
+ String get _tooltip => [
if (engine case final value?) [value, ?model].join(' '),
?machine,
if (status case final value?)
diff --git a/desktop/lib/super_tabs/agent_line.dart b/desktop/lib/super_tabs/agent_line.dart
index 38ab5e3d4..a2b2c1731 100644
--- a/desktop/lib/super_tabs/agent_line.dart
+++ b/desktop/lib/super_tabs/agent_line.dart
@@ -57,6 +57,8 @@ SuperTabAgentGlance superTabAgentGlance(
final label = switch (null) {
_ when agent.switchRequest != null => 'Switching…',
_ when work == 'lost' => 'Lost',
+ _ when agent.keptClosed && activity != HarnessActivity.offline =>
+ 'Kept (closed)',
_
when agent.downSince != null ||
activity == HarnessActivity.offline ||
diff --git a/desktop/lib/super_tabs/machines.dart b/desktop/lib/super_tabs/machines.dart
index 62aa94ba4..13ee58130 100644
--- a/desktop/lib/super_tabs/machines.dart
+++ b/desktop/lib/super_tabs/machines.dart
@@ -2069,18 +2069,23 @@ class _SuperTabMachinesState extends State<SuperTabMachines> {
);
}
- /// [view]'s agents under Working, Waiting and Idle, each by name; a group with none is left out.
+ /// [view]'s agents under Working, Waiting, Idle and Kept (closed), each by name; a group with none is left out.
List<Widget> _agentGroups(_MachineView view) {
final groups = <String, List<(SuperTabAgent, HarnessActivity)>>{
'Working': [],
'Waiting': [],
'Idle': [],
+ 'Kept (closed)': [],
};
for (final agent in view.agents) {
final activity = _activity(view, agent);
groups[switch (activity) {
HarnessActivity.working || HarnessActivity.starting => 'Working',
HarnessActivity.needsInput || HarnessActivity.failed => 'Waiting',
+ // A kept agent whose session is closed on a machine that is
+ // there: the Swarm removes the others, so this one says so.
+ _ when agent.keptClosed && activity != HarnessActivity.offline =>
+ 'Kept (closed)',
_ => 'Idle',
}]!
.add((agent, activity));
diff --git a/desktop/lib/super_tabs/model.dart b/desktop/lib/super_tabs/model.dart
index 2efae341e..f406738cb 100644
--- a/desktop/lib/super_tabs/model.dart
+++ b/desktop/lib/super_tabs/model.dart
@@ -160,6 +160,7 @@ class SuperTabAgent {
profileId = row['profileId'] as String?,
avatar = SuperTabAvatarPicture.fromJson(row['avatar']),
downSince = DateTime.tryParse(row['downSince'] as String? ?? ''),
+ workDecision = row['workDecision'] as String?,
confidential = row['confidential'] == true,
configuration = Map.unmodifiable(superTabMap(row['configuration']));
final String id, projectId, name, machineId, harnessId, contributorId;
@@ -187,6 +188,13 @@ class SuperTabAgent {
/// while it runs.
final DateTime? downSince;
+ /// What its coordinator or a person chose for it once its work ended: `keep` or `stop`; `awaiting` while nobody has.
+ final String? workDecision;
+
+ /// Its session is closed on its machine and someone chose to keep the agent: the backend removes every other closed
+ /// agent from the list (backend closedAgents.ts), so this one is shown as closed, never as Idle.
+ bool get keptClosed => workDecision == 'keep' && downSince != null;
+
/// The account whose computer runs it; a contributor may run agents on a computer another account shared with them.
final String machineOwnerId;
diff --git a/desktop/test/super_tab_agent_line_test.dart b/desktop/test/super_tab_agent_line_test.dart
index 9bdb9477e..e31e085fa 100644
--- a/desktop/test/super_tab_agent_line_test.dart
+++ b/desktop/test/super_tab_agent_line_test.dart
@@ -174,7 +174,7 @@ void main() {
});
testWidgets(
- 'names each state in a word: waiting, lost, down, limited, stuck, in review',
+ 'names each state in a word: waiting, lost, down, kept (closed), limited, stuck, in review',
(tester) async {
final until = DateTime.now().add(const Duration(hours: 2)).toLocal();
String two(int n) => n.toString().padLeft(2, '0');
@@ -195,6 +195,15 @@ void main() {
),
_agent('Moss', 'm1'),
_agent('Teal', 'm1'),
+ // Closed on its machine, and someone chose to keep it: not Idle, not Down.
+ _agent(
+ 'Moth',
+ 'm2',
+ extra: {
+ 'downSince': DateTime.now().toUtc().toIso8601String(),
+ 'workDecision': 'keep',
+ },
+ ),
],
tasks: [
_task('Wren', 'needs_human'),
@@ -230,6 +239,10 @@ void main() {
_line('Kite', 'Down · MacBook Pro · Opus · high'),
findsOneWidget,
);
+ expect(
+ _line('Moth', 'Kept (closed) · MacBook Pro · Opus · high'),
+ findsOneWidget,
+ );
expect(
_line(
'Rook',
diff --git a/desktop/test/super_tab_machines_test.dart b/desktop/test/super_tab_machines_test.dart
index 804e370dc..76347c841 100644
--- a/desktop/test/super_tab_machines_test.dart
+++ b/desktop/test/super_tab_machines_test.dart
@@ -689,7 +689,7 @@ void main() {
});
testWidgets(
- 'tapping the line lists every agent, Working, Waiting, then Idle, with name, role and status',
+ 'tapping the line lists every agent, Working, Waiting, Idle, then Kept (closed), with name, role and status',
(tester) async {
final f = SuperTabLaunchFixture();
f.app.bindSuperTab(f.app.activeSwarmId, tabId, 'Pilot');
@@ -708,15 +708,24 @@ void main() {
agent('dev', 'Nova'),
agent('rev', 'Sage'),
agent('idle', 'Iris'),
+ // Closed on its machine and kept by someone: not Idle (Huy, 2026-11-02).
+ agent('kept', 'Kai')
+ ..['workDecision'] = 'keep'
+ ..['downSince'] = DateTime.now().toUtc().toIso8601String()
+ ..['configuration'] = {
+ 'engine': 'claude',
+ 'model': 'opus',
+ 'effort': 'high',
+ },
];
(server.state['agents'] as List)[2]['role'] = 'reviewer';
(server.state['conversations'] as List)[0]
..['leadId'] = 'pm'
- ..['agentIds'] = ['pm', 'dev', 'rev', 'idle']
+ ..['agentIds'] = ['pm', 'dev', 'rev', 'idle', 'kept']
..['assignment'] = {'agentId': 'rev', 'status': 'needs_human'};
f.app.machineStates['m']!
..agents = [
- for (final id in ['pm', 'dev', 'rev', 'idle'])
+ for (final id in ['pm', 'dev', 'rev', 'idle', 'kept'])
Agent.fromJson({
'id': 'native-$id',
'name': id,
@@ -744,7 +753,7 @@ void main() {
expect(
find.descendant(
of: line,
- matching: find.text('4 agents · 2 working'),
+ matching: find.text('5 agents · 2 working'),
),
findsOneWidget,
);
@@ -757,7 +766,7 @@ void main() {
expect(list, findsOneWidget);
double top(Finder finder) => tester.getTopLeft(finder).dy;
final headings = [
- for (final group in ['Working', 'Waiting', 'Idle'])
+ for (final group in ['Working', 'Waiting', 'Idle', 'Kept (closed)'])
find.descendant(of: list, matching: find.text(group)),
];
for (final heading in headings) {
@@ -774,6 +783,8 @@ void main() {
row('rev'),
headings[2],
row('idle'),
+ headings[3],
+ row('kept'),
];
for (var i = 1; i < order.length; i++) {
expect(top(order[i]), greaterThan(top(order[i - 1])));
@@ -805,6 +816,18 @@ void main() {
);
}
expect(find.descendant(of: list, matching: agentAvatar), findsNothing);
+ // Hovering the kept, closed agent reads as its line does, the mockup Huy approved: status, machine, model, effort.
+ Finder tip(String id) => find.ancestor(
+ of: row(id),
+ matching: find.byWidgetPredicate(
+ (w) =>
+ w is Tooltip &&
+ (w.message ?? '').startsWith('Kept (closed) · ') &&
+ (w.message ?? '').endsWith(' · Opus · high'),
+ ),
+ );
+ expect(tip('kept'), findsOneWidget);
+ expect(tip('idle'), findsNothing);
await tester.tap(row('rev'));
await tester.pump();
diff --git a/desktop/test/super_tab_roster_test.dart b/desktop/test/super_tab_roster_test.dart
index 5ccf54699..b317136ab 100644
--- a/desktop/test/super_tab_roster_test.dart
+++ b/desktop/test/super_tab_roster_test.dart
@@ -245,6 +245,23 @@ void main() {
},
);
+ testWidgets(
+ 'a kept agent closed on its machine reads "Kept (closed)" in the hover, never Idle (Huy, 2026-11-02)',
+ (tester) async {
+ final f = await fixture(tester);
+ final agents = f.server.state['agents'] as List;
+ agents[3]['workDecision'] = 'keep';
+ agents[3]['downSince'] = DateTime.now().toUtc().toIso8601String();
+ await f.controller.refresh();
+ await f.show(tester);
+ final tip = rowTooltip(tester, f, 3);
+ expect(tip, contains('Kept (closed)'));
+ expect(tip, isNot(contains('Idle')));
+ expect(tip, isNot(contains('Status unavailable')));
+ await f.close(tester);
+ },
+ );
+
testWidgets('agent tooltip combines known model, machine, task and activity', (
tester,
) async {
diff --git a/docs/plans/2026-11-02-archive-pass-tells-steps-plan.md b/docs/plans/2026-11-02-archive-pass-tells-steps-plan.md
new file mode 100644
index 000000000..9adfc88f8
--- /dev/null
+++ b/docs/plans/2026-11-02-archive-pass-tells-steps-plan.md
@@ -0,0 +1,56 @@
+# Archive pass tells the steps it ends Implementation Plan
+
+> **For agentic workers:** implement task by task, test first. No review per step: the Review step on the pull request is the one independent review.
+
+**Goal:** When the archive pass ends a task's open step, the step's agent hears why, and the steps it archives keep no open deliveries.
+
+**Architecture:** `archiveFinished` already calls `endSteps`, drops the steps it returns and cancels only the task's own deliveries. A new `steps.ts` helper builds the "was archived" rows; the command path and the archive pass both use it, and the pass writes them with its own line.
+
+**Tech Stack:** TypeScript, Prisma on MongoDB, vitest integration suite (`npm run test:super-tabs`).
+
+**Spec:** task #2134 (Diego's repro on main 2826547cb); `docs/plans/2026-11-02-task-steps-design.md`, "Archive and sleep".
+
+## Global Constraints
+
+- A cancelled step stays unarchived, so its row can still be delivered (`endSteps`).
+- Only deliveries of steps archived in this write are cancelled.
+- One plain delivery match per conversation: an `in` on this collection is sent as `$expr`, which no index bounds.
+- Two security reviews before merge; full Super Tab integration suite before Ready.
+
+## Review Focus
+
+- A step whose agent has left the Swarm: the pass must still archive the task, and writes the row to nobody. A delivery to a missing agent would throw, and the task would never archive.
+- A project with no Lead: `archiveLine` is null, and the step's agent must still hear.
+- A step that finished before the pass: it is archived, its deliveries end, and no row goes to its agent.
+- A step already archived before this write: its deliveries are not touched.
+- A retried write: one row per step per pass, no second delivery.
+
+## Design
+
+- Growth: one row and one delivery per cancelled step; they go with the group.
+- Concurrency: inside the pass's one transaction; a claim of a delivery conflicts with the write, as for the task's.
+- Read cost: one more delivery update per archived step; no new reads.
+- Scale: a task has a handful of steps. Warns first: the pass's skipped-group warning.
+- Compatibility: old and new clients read an ordinary system row.
+- Migration + rollback: none; nothing stored changes shape.
+- Audience: the row goes only to the step's own assigned agent, in that step's conversation.
+- Identity: written as the project's Lead, as the pass's own line, else as the agent told.
+- Failure: a row to a missing agent is written to nobody, so it cannot stop the archive.
+- Platforms: backend only.
+
+---
+
+### Task 1: The archive pass tells a working step's agent
+
+**Files:**
+- Modify: `backend/src/superTabs/steps.ts`, `backend/src/superTabs/commands.ts` (`endStepsOf`), `backend/src/superTabs/store.ts` (`archiveFinished`)
+- Test: `backend/integration/superTabTidy.test.ts`
+
+**Interfaces:**
+- Produces: `stepEndedRows(state, cancelled: Conversation[], reason: string, author: Author | null, id: (step: Conversation) => string): MessageDraft[]` in `steps.ts`
+
+- [ ] **Step 1: Write the failing tests:** the working step's agent gets a row and a queued delivery; a finished step is archived and its deliveries end; a step whose agent left does not stop the archive; no Lead still tells the agent.
+- [ ] **Step 2: Run them to see them fail:** `npx vitest run --config vitest.super-tabs.config.ts integration/superTabTidy.test.ts`
+- [ ] **Step 3: Add `stepEndedRows`, use it in `endStepsOf` and `archiveFinished`, and cancel the archived steps' deliveries.**
+- [ ] **Step 4: Run them to see them pass,** then the unit tests for steps and commands.
+- [ ] **Step 5: Run the full suite:** `npm run test:super-tabs`, and post the count.
diff --git a/docs/plans/2026-11-02-closed-agents-leave-list-plan.md b/docs/plans/2026-11-02-closed-agents-leave-list-plan.md
new file mode 100644
index 000000000..ddd1e7a97
--- /dev/null
+++ b/docs/plans/2026-11-02-closed-agents-leave-list-plan.md
@@ -0,0 +1,71 @@
+# Swarm: an agent closed on its machine leaves the list, and is never shown as Idle
+
+**Goal:** an agent whose session is closed on its machine is recorded as stopped and leaves the Machines list on its
+own. Huy (2026-11-02) closed 4 agents on MacBookPro2021. Their sessions were in the machine's stopped list and each had
+been down since 07:04-08:15 UTC, yet the Swarm kept them waiting for a keep-or-stop answer and the Machines list showed
+them under **Idle** for hours.
+
+**Why it happens:** a machine's report that lists a session as stopped already loses the agent's open task
+(`liveness.ts` `loseTasks`) but leaves the agent itself in `state.agents`. Only the agent's own host, after a stop was
+asked for (`agent.release` then `agent.remove`), ever removed it. A session closed by hand never asked. Desktop then draws
+any agent without work as Idle (`machines.dart` `_agentGroups`).
+
+## Behavior
+
+- A report that lists an agent's session as stopped (proved the way slot counting already proves it, `machines.ts`
+ `machineSlots`) and not running removes the agent once it has been down 30 seconds (`STOPPED_REMOVE_MS`) and the
+ previous fresh reading did not list it running either. The wait covers a host mid-restart and Change agent, which list a
+ session stopped for a moment before it is back. The task it held went to the PM as lost first.
+- An agent that is down (not listed running) for 15 minutes, with its machine reporting fresh on two reports in a row,
+ is removed the same way, but never while the report or the previous one lists no session running at all (a fault in
+ the host's listing must not empty a machine). One report after a machine was silent never removes anyone.
+- Stays: a coordinator (it leads a project), a Buddy (its owner's to stop), an agent whose coordinator or a person
+ chose **keep**, an agent whose stop was asked for (its host closes it and takes it out), and an agent that holds a
+ task: active, or lost just now and not yet handed on or cancelled by the PM (the PM is told by name and the agent
+ stays fenced). The next report after the PM decides removes it. A kept agent that is down shows **Kept (closed)**, not
+ Idle, in the Machines list, on its line and in its hover.
+- Removal is `removeAgent`'s bookkeeping, **with its close record** (`closedAgents.ts` `recordClosing`, shared with
+ `commands.ts`): the agent's host closes the session, a confidential session on a Team account keeps the account held
+ for its project until the host confirms the data deleted, and the host's confirmation frees the session's slot
+ (`agent.sessionClosed`). The agent leaves every group's members and leads, its undelivered messages are cancelled, and
+ the terminals opened on its old session are revoked.
+- Resume: the CLI host never sends `agent.add` (only Desktop's "add session" does), so a session reopened after its
+ agent was removed runs without a Swarm agent until someone adds it. Re-adding it from the host is its own task (the
+ removed agent's group, role and configuration are gone, so the host needs a new command and a journal of what to
+ restore); Lead 2026-11-02.
+
+## Steps (test first)
+
+1. Integration tests in `backend/integration/superTabLiveness.test.ts`, run on main to watch them fail: a stopped
+ session's agent leaves (with its lost task still reaching the PM), a kept one stays, a coordinator stays, a running
+ one stays, a down-15-minutes one leaves only after two fresh reports; a stop requested, a restart and an empty running list keep it;
+ an assignment racing the removal; the close record (unit tests in `closedAgents.test.ts`, confidential Team session held).
+2. `closedAgents` (selection) and `removeClosedAgents` (state change) in `backend/src/superTabs/closedAgents.ts`;
+ `store.ts` `fullReading` loads the groups of those agents, removes them, cancels their deliveries (one plain match each: an `in` here is
+ sent as `$expr`, hotFilters) and revokes their native contexts. `nextRemovalAt` keeps the machine's deadline: an unchanged stopped
+ list skips the full report, so the agent's wait end forces one.
+3. Dart tests for the row label: a kept agent with `downSince` reads **Kept (closed)** in the Machines list and the agent
+ line. Then the label in `agent_line.dart` and the grouping in `machines.dart`.
+4. Full Super Tab suite (`cd backend && npm run test:super-tabs`); Desktop tests for the changed files.
+
+## Design
+
+- **Growth:** this deletes. An agent row, its group memberships and undelivered messages go when its session is
+ closed, instead of waiting for a person.
+- **Concurrency:** inside the machine's report transaction, which already writes the agent and group parts it
+ changes and retries on a conflict with a newer write.
+- **Read cost:** the report additionally loads the groups of the agents it removes (by the `agents` index), only when
+ there is one; the common report loads exactly what it did.
+- **Scale:** at most the machine's agents per report; the metric to watch is reports that remove agents.
+- **Compatibility:** no new fields. Old clients see the agent leave the list as they do after a host-confirmed stop; a
+ kept closed agent keeps showing as before on old clients (Idle or Down).
+- **Migration + rollback:** none; reverting stops removals, and nothing removed comes back by itself (an agent whose
+ session is resumed is not added again, see Behavior).
+- **Audience:** the server decides from the machine owner's own report, which can only name its own sessions
+ (the report already refuses another's machine); no client input chooses who is removed.
+- **Identity:** nothing is written as a person; no message is posted.
+- **Failure:** an agent holding a task is not removed (its task is lost first, the PM decides, the next report removes it);
+ a coordinator is never removed. A heartbeat that changes nothing is stored without the full load; the machine's deadline
+ is the end of the next agent's wait (`nextRemovalAt`), so a stopped list that stays the same still removes its agent
+ then, not after the five-minute cap.
+- **Platforms:** backend, Desktop and the web build share `machines.dart`.